gencow 0.1.273 → 0.1.275

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.
@@ -290,6 +290,40 @@ function safePlatformOrigin(value) {
290
290
  }
291
291
  }
292
292
 
293
+ // Stages whose failing request is sent before the Platform changes the serving release.
294
+ const SAFE_UNTYPED_RELEASE_STAGES = new Set(["release-attempt registration"]);
295
+
296
+ // A 5xx that is not a typed Platform error: say where it failed, that serving was not
297
+ // changed, and what to do next. Retryability is not stated because the Platform did not say it.
298
+ function untypedReleaseFailureMessage(caught) {
299
+ const platformOrigin = safePlatformOrigin(caught.platformUrl);
300
+ const lines = [
301
+ `${caught.message}: the Platform returned an HTTP error without a typed release error.`,
302
+ `Stage: ${caught.untypedFailure.stage}`,
303
+ ];
304
+ if (platformOrigin) lines.push(`Platform: ${platformOrigin}`);
305
+ lines.push(`HTTP status: ${caught.status}`);
306
+ lines.push("Incumbent serving: PRESERVED (the deploy has not reached the serving step)");
307
+ const correlationId =
308
+ typeof caught.correlationId === "string" && SAFE_CORRELATION_ID.test(caught.correlationId)
309
+ ? caught.correlationId
310
+ : null;
311
+ lines.push(`Correlation ID: ${correlationId ?? "none returned"}`);
312
+ lines.push(
313
+ "Next action: rerun the same deploy command. If it fails again, add the failure time (UTC)" +
314
+ `${correlationId ? " and the Correlation ID above" : ""} to the GitHub issue.`,
315
+ );
316
+ return lines.join("\n");
317
+ }
318
+
319
+ // A retryable flag the CLI estimated (no Platform statement) is not shown as a server guarantee.
320
+ function retryabilityLine(caught) {
321
+ if (!caught.retryableEstimated) return `Retryable: ${caught.retryable ? "yes" : "no"}`;
322
+ return caught.retryable
323
+ ? "Retry: rerun the same command (the Platform did not say whether a retry is safe)"
324
+ : "Retryable: not stated by the Platform";
325
+ }
326
+
293
327
  export function formatCommandError(caught) {
294
328
  return commandErrorMessage(caught);
295
329
  }
@@ -364,6 +398,9 @@ function commandErrorMessage(caught) {
364
398
  }
365
399
  return lines.join("\n");
366
400
  }
401
+ if (caught instanceof Error && caught.untypedFailure && SAFE_UNTYPED_RELEASE_STAGES.has(caught.untypedFailure.stage)) {
402
+ return untypedReleaseFailureMessage(caught);
403
+ }
367
404
  if (caught instanceof Error && caught.message) {
368
405
  const platformOrigin = safePlatformOrigin(caught.platformUrl);
369
406
  const correlationId =
@@ -377,7 +414,7 @@ function commandErrorMessage(caught) {
377
414
  if (Number.isInteger(caught.status) && caught.status >= 400 && caught.status <= 599) {
378
415
  lines.push(`HTTP status: ${caught.status}`);
379
416
  }
380
- if (typeof caught.retryable === "boolean") lines.push(`Retryable: ${caught.retryable ? "yes" : "no"}`);
417
+ if (typeof caught.retryable === "boolean") lines.push(retryabilityLine(caught));
381
418
  if (correlationId) lines.push(`Correlation ID: ${correlationId}`);
382
419
  return lines.join("\n");
383
420
  }
@@ -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",
@@ -16,12 +16,48 @@ const USER_FIXABLE_CAUSES = new Map([
16
16
  ["undefined_column", "the statement references a column that does not exist"],
17
17
  ["undefined_table", "the statement references a table that does not exist"],
18
18
  ["duplicate_table", "the table already exists"],
19
+ [
20
+ "feature_not_supported_in_statement",
21
+ "PostgreSQL does not allow this construct in the statement (for example a bare word instead of a quoted string, a subquery, or a column reference in a DEFAULT)",
22
+ ],
23
+ ["datatype_mismatch", "a DEFAULT value does not match the column's data type"],
24
+ ["undefined_function", "the statement calls a function that does not exist"],
25
+ ["undefined_object", "the statement uses a type that does not exist"],
19
26
  ]);
20
27
 
21
28
  // Extra guidance for causes whose generic repair advice needs a specific hint.
22
29
  const NOT_NULL_REPAIR_HINT =
23
30
  "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
31
 
32
+ // Type/data repair hints for the unlocated fallback. Mirrors the server's suggested-fix text in
33
+ // migration-rollback-diagnostic.ts; both must name only the column DEFAULT or literal in schema.ts.
34
+ const TYPE_REPAIR_HINTS = new Map([
35
+ [
36
+ "invalid_text_representation",
37
+ "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.",
38
+ ],
39
+ [
40
+ "string_data_right_truncation",
41
+ "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.",
42
+ ],
43
+ [
44
+ "feature_not_supported_in_statement",
45
+ "For a DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference), change the DEFAULT in gencow/schema.ts to a literal valid for the column type: a quoted string for text columns, a number for integer columns, true or false for boolean columns. Then run db:generate to replace only this unapplied migration.",
46
+ ],
47
+ [
48
+ "datatype_mismatch",
49
+ "For a DEFAULT whose value type does not match its column, change the DEFAULT in gencow/schema.ts to a value of the column's declared type, then run db:generate to replace only this unapplied migration.",
50
+ ],
51
+ [
52
+ "undefined_function",
53
+ "The statement calls a function that does not exist in this database. Correct the function name or remove it from the DEFAULT in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
54
+ ],
55
+ [
56
+ "undefined_object",
57
+ "The statement uses a type name that does not exist in this database. Correct the column type in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
58
+ ],
59
+ ]);
60
+
25
61
  const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
26
62
 
27
63
  export function isUserFixableRolledBackDiagnostic(diagnostic) {
@@ -51,7 +87,8 @@ export function renderRollbackCauseLine(diagnostic) {
51
87
  export function renderUnlocatedRollbackFix(diagnostic) {
52
88
  const name = diagnostic?.migration?.name;
53
89
  const code = safeRollbackReasonCode(diagnostic);
54
- const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : "";
90
+ const typeHint = code ? TYPE_REPAIR_HINTS.get(code) : undefined;
91
+ const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : typeHint ? ` ${typeHint}` : "";
55
92
  return {
56
93
  title: name
57
94
  ? `Inspect the unapplied migration file ${name}`
@@ -65,7 +65,20 @@ function safePlatformOrigin(value) {
65
65
  }
66
66
  }
67
67
 
68
- function throwResponseError(response, fallback, body, creds = {}) {
68
+ // Header names checked, in order, when the JSON body carries no correlation ID.
69
+ const SAFE_CORRELATION_HEADERS = ["x-gencow-correlation-id", "x-correlation-id", "x-request-id"];
70
+
71
+ function responseHeaderCorrelationId(response) {
72
+ for (const name of SAFE_CORRELATION_HEADERS) {
73
+ const value = response?.headers?.get?.(name);
74
+ if (typeof value === "string" && SAFE_CORRELATION_ID.test(value)) return value;
75
+ }
76
+ return undefined;
77
+ }
78
+
79
+ // `context.stage` is set only where the request is known to happen before any serving
80
+ // change, so an untyped 5xx there can be reported as "incumbent serving preserved".
81
+ function throwResponseError(response, fallback, body, creds = {}, context = {}) {
69
82
  const authRequired = response.status === 401;
70
83
  const responseCode = PUBLIC_RELEASE_ERROR_CODES.has(body?.code) ? body.code : fallback;
71
84
  const error = new Error(authRequired ? "APP_RELEASE_AUTH_REQUIRED" : responseCode);
@@ -78,20 +91,40 @@ function throwResponseError(response, fallback, body, creds = {}) {
78
91
  if (creds.credentialEnvName === "GENCOW_TOKEN" || creds.credentialEnvName === "GENCOW_DEPLOY_TOKEN") {
79
92
  error.credentialEnvName = creds.credentialEnvName;
80
93
  }
81
- if (typeof body.correlationId === "string" && SAFE_CORRELATION_ID.test(body.correlationId)) {
82
- error.correlationId = body.correlationId;
94
+ const bodyCorrelationId =
95
+ typeof body?.correlationId === "string" && SAFE_CORRELATION_ID.test(body.correlationId)
96
+ ? body.correlationId
97
+ : undefined;
98
+ const correlationId = bodyCorrelationId ?? responseHeaderCorrelationId(response);
99
+ if (correlationId) error.correlationId = correlationId;
100
+ if (authRequired) {
101
+ error.retryable = false;
102
+ } else if (typeof body?.retryable === "boolean") {
103
+ error.retryable = body.retryable;
104
+ } else {
105
+ // Not stated by the Platform: this is the CLI's guess, not a server guarantee.
106
+ error.retryable = response.status >= 500;
107
+ error.retryableEstimated = true;
108
+ }
109
+ // A 5xx whose body carries no public Platform code may come from the edge or an
110
+ // intermediary, so it is untyped. A public code keeps the server-stated code and
111
+ // retryable value even when the correlation ID is missing.
112
+ const typedPlatformCode = context.bodyIsJson !== false && PUBLIC_RELEASE_ERROR_CODES.has(body?.code);
113
+ if (response.status >= 500 && !typedPlatformCode && context.stage) {
114
+ error.untypedFailure = { stage: context.stage };
83
115
  }
84
- error.retryable = authRequired
85
- ? false
86
- : typeof body.retryable === "boolean"
87
- ? body.retryable
88
- : response.status >= 500;
89
116
  throw error;
90
117
  }
91
118
 
92
- async function responseError(response, fallback, creds, parsedBody) {
93
- const body = parsedBody ?? ((await response.json().catch(() => ({}))) || {});
94
- throwResponseError(response, fallback, body, creds);
119
+ async function responseError(response, fallback, creds, parsedBody, context = {}) {
120
+ let body = parsedBody;
121
+ let bodyIsJson = true;
122
+ if (body === undefined) {
123
+ const parsed = await response.json().catch(() => undefined);
124
+ bodyIsJson = parsed !== null && typeof parsed === "object";
125
+ body = bodyIsJson ? parsed : {};
126
+ }
127
+ throwResponseError(response, fallback, body || {}, creds, { ...context, bodyIsJson });
95
128
  }
96
129
 
97
130
  const DEFAULT_CAPABILITY_RETRY_DELAYS_MS = [1_000, 2_000];
@@ -263,7 +296,9 @@ export async function prepareReleaseAttempt({
263
296
  ...(sourcePackage ? { body: sourcePackage.bundleBuffer } : {}),
264
297
  });
265
298
  if (!response.ok) {
266
- await responseError(response, "APP_RELEASE_SOURCE_UPLOAD_FAILED", creds);
299
+ await responseError(response, "APP_RELEASE_SOURCE_UPLOAD_FAILED", creds, undefined, {
300
+ stage: "release-attempt registration",
301
+ });
267
302
  }
268
303
  const data = await response.json();
269
304
  if (!data.attemptId || (data.state !== "source_stored" && data.state !== "received")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.273",
3
+ "version": "0.1.275",
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];let extensionUnavailable=false;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);const ownSqlStates=[];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);ownSqlStates.push(value2)}}}if(ownSqlStates.includes("0A000")){const message=safeObjectField(current,"message");if(typeof message==="string"&&EXTENSION_UNAVAILABLE_MESSAGE.test(message.slice(0,EXTENSION_MESSAGE_MAX_LENGTH))){extensionUnavailable=true}}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],extensionUnavailable}}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(facts){for(const state2 of facts.sqlStates){if(state2==="0A000"){if(facts.extensionUnavailable)return EXTENSION_UNAVAILABLE_REASON;continue}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);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,EXTENSION_UNAVAILABLE_REASON,EXTENSION_UNAVAILABLE_MESSAGE,EXTENSION_MESSAGE_MAX_LENGTH,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"],["42704","undefined_object"],["42804","datatype_mismatch"],["42883","undefined_function"],["42P01","undefined_table"],["42P07","duplicate_table"],["0A000","feature_not_supported_in_statement"]]);EXTENSION_UNAVAILABLE_REASON="feature_not_supported";EXTENSION_UNAVAILABLE_MESSAGE=/extension\s+\S.*?\s+is not (?:available|allowed)/iu;EXTENSION_MESSAGE_MAX_LENGTH=512;PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["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."],["feature_not_supported_in_statement","For a DEFAULT PostgreSQL does not accept (a bare word, a subquery, or a column reference), change the DEFAULT in gencow/schema.ts to a literal valid for the column type: a quoted string for text columns, a number for integer columns, true or false for boolean columns. Then run db:generate to replace only this unapplied migration."],["datatype_mismatch","For a DEFAULT whose value type does not match its column, change the DEFAULT in gencow/schema.ts to a value of the column's declared type, then run db:generate to replace only this unapplied migration."],["undefined_function","The statement calls a function that does not exist in this database. Correct the function name or remove it from the DEFAULT in gencow/schema.ts, then run db:generate to replace only this unapplied migration."],["undefined_object","The statement uses a type name that does not exist in this database. Correct the column type 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
@@ -9263,7 +9263,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
9263
9263
  LEFT JOIN app_serving_route_authorities authority ON authority.app_id = app.id
9264
9264
  WHERE app.id = ${input2.appId}
9265
9265
  AND app.instance_id::text = ${input2.appInstanceId}
9266
- `);const rows8=postgresExecuteRows(result3);if(rows8.length!==1)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;const row=rows8[0];const authorityEpoch=row.authority_epoch===null?0:Number(row.authority_epoch);const observedEpoch=row.observed_epoch===null?0:Number(row.observed_epoch);if(!Number.isSafeInteger(authorityEpoch)||authorityEpoch<0||!Number.isSafeInteger(observedEpoch)||observedEpoch<0||observedEpoch===0||observedEpoch<authorityEpoch||typeof row.active_reservation!=="boolean"||typeof row.active_release!=="boolean"||row.active_release&&!isWellFormedActiveRelease(row.active_release_attempt_id,row.active_release_environment)||!row.active_release&&(row.active_release_attempt_id!==null||row.active_release_environment!==null)||typeof row.active_runtime_recovery!=="boolean"||typeof row.active_delete!=="boolean"||typeof row.incumbent_committed!=="boolean"||typeof row.pointer_proven_incumbent!=="boolean"||row.authority_environment!==null&&row.authority_environment!==input2.servingRouteEnvironment||row.authority_instance_id!==null&&row.authority_instance_id!==input2.appInstanceId||row.authority_environment===null!==(row.authority_instance_id===null)||row.authority_environment===null&&(row.authority_epoch!==null||row.authority_entry_payload!==null||row.authority_entry_hash!==null))return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;let authorityEntry=null;if(row.authority_environment===null){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}if(row.authority_environment!==null){try{authorityEntry=buildServingRouteManifestEntry(JSON.parse(row.authority_entry_payload??""));if(row.authority_disposition!=="upsert"||authorityEntry.disposition!==row.authority_disposition||authorityEntry.appId!==input2.appId||authorityEntry.appInstanceId!==input2.appInstanceId||authorityEntry.routeEpoch!==authorityEpoch||hashServingRouteManifestEntry(authorityEntry)!==row.authority_entry_hash)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}catch{return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}}const failedOperationGeneration=row.failed_op_generation_ref??null;const failedOperationOwnsLive=failedOperationOwnsLiveGeneration({authorityGeneration:authorityEntry.static?.generationRef??null,failedOperationGeneration});const failedOperationLiveProven=failedOperationOwnsLive&&row.failed_op_release_attempt_id!==null&&await proveCommittedLiveStaticRelease(input2.db,{appId:input2.appId,releaseAttemptId:row.failed_op_release_attempt_id,servingRouteEnvironment:input2.servingRouteEnvironment},input2.deploymentId)!==null;const authorityGeneration=authorityEntry.static?.generationRef??null;const failedOperationOtherOwnerProven=row.failed_op_never_staged===true&&row.failed_op_release_attempt_id!==null&&authorityGeneration!==null&&authorityGeneration===(row.current_static_generation_ref??null)&&await proveOtherLiveReleaseOwnsGeneration(input2.db,{appId:input2.appId,servingRouteEnvironment:input2.servingRouteEnvironment,generation:authorityGeneration,failedDeploymentId:input2.deploymentId,failedReleaseAttemptId:row.failed_op_release_attempt_id});let incumbentServing=resolveIncumbentServing({pointer:row.current_static_deployment_id,deploymentId:input2.deploymentId,pointerCommitted:row.incumbent_committed,pointerProvenIncumbent:row.pointer_proven_incumbent===true,pointerUnexecuted:row.pointer_unexecuted===true,failedOperationLiveProven,failedOperationOtherOwnerProven,authorityGeneration,projectedGeneration:row.current_static_generation_ref??null,failedOperationGeneration,failedOperationExecutorState:row.failed_op_executor_state??null,probe:input2.probeFailedOperation===true});const blockingDeploymentId=Number(row.blocking_deployment_id);if(row.blocking_deployment_id!==null&&(!Number.isSafeInteger(blockingDeploymentId)||blockingDeploymentId<1)){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}const safeBlockingDeploymentId=Number.isSafeInteger(blockingDeploymentId)&&blockingDeploymentId>0?blockingDeploymentId:null;const activeOwnerKinds=[...safeBlockingDeploymentId?["deployment"]:[],...row.active_release?["release"]:[],...row.active_runtime_recovery?["runtime_recovery"]:[],...row.active_delete?["app_lifecycle"]:[]];if(row.current_static_deployment_id!==null&&row.current_static_deployment_id>input2.deploymentId&&incumbentServing!=="PRESERVED"){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}const recoveredDeploymentId=incumbentServing==="PRESERVED"&&row.current_static_deployment_id!==null&&row.current_static_deployment_id>input2.deploymentId?row.current_static_deployment_id:null;if(recoveredDeploymentId!==null)incumbentServing="UNKNOWN";if(recoveredDeploymentId===null&&incumbentServing==="UNKNOWN"){if(activeOwnerKinds.length===0)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;return{retryReady:false,reason:"ACTIVE_OWNER",activeOwnerKinds,blockingDeploymentId:safeBlockingDeploymentId,blockingReleaseAttemptId:row.active_release?row.active_release_attempt_id:null,blockingReleaseEnvironment:row.active_release?row.active_release_environment:null,recoveredDeploymentId:null,incumbentServing:"UNKNOWN"}}const retryAfterSeconds=Number(row.reservation_retry_after_seconds);const reservationRetryAfter=row.active_reservation&&row.reservation_unbounded===false&&typeof row.reservation_retry_after==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u.test(row.reservation_retry_after)&&Number.isFinite(retryAfterSeconds)?{at:row.reservation_retry_after,afterSeconds:Math.min(Math.ceil(PREPARE_COMMIT_ABANDONMENT_MS/1e3),Math.max(1,retryAfterSeconds))}:null;return{...reservationRetryAfter?{reservationRetryAfter}:{},retryReady:recoveredDeploymentId===null&&incumbentServing!=="CHANGED"&&!row.active_reservation&&!safeBlockingDeploymentId&&!row.active_release&&!row.active_runtime_recovery&&!row.active_delete,reason:recoveredDeploymentId!==null?"ALREADY_RECOVERED":row.active_reservation?"ACTIVE_ROUTE_RESERVATION":safeBlockingDeploymentId||row.active_release||row.active_runtime_recovery||row.active_delete?"ACTIVE_OWNER":incumbentServing==="CHANGED"?"SERVING_CHANGED":"READY",activeOwnerKinds,blockingDeploymentId:safeBlockingDeploymentId,blockingReleaseAttemptId:row.active_release?row.active_release_attempt_id:null,blockingReleaseEnvironment:row.active_release?row.active_release_environment:null,recoveredDeploymentId,incumbentServing}}function publicStaticIncumbentServing(readiness){return readiness.incumbentServing==="NONE_TO_PRESERVE"?"NOT_APPLICABLE":readiness.incumbentServing}function staticStaleServingProven(readiness){return readiness.incumbentServing==="PRESERVED"||readiness.incumbentServing==="NONE_TO_PRESERVE"}function settledStaticServingState(readiness){return readiness.incumbentServing==="NONE_TO_PRESERVE"?"NOT_APPLICABLE":"PRESERVED"}var UNKNOWN_STATIC_ROUTE_RETRY_READINESS,BLOCKED_ELIGIBLE_STATIC_FAILURES;var init_deployment_route_retry_readiness=__esm({"../platform/src/deployment-route-retry-readiness.ts"(){"use strict";init_serving_route_manifest_contract();init_app_delete_operation_store();init_app_serving_route_prepare_abandonment();init_app_release_unbound_attempt_lease();init_deployment_executor_store();init_postgres_execute_rows();init_deployment_live_static_release_proof();UNKNOWN_STATIC_ROUTE_RETRY_READINESS={retryReady:false,reason:"OBSERVATION_UNAVAILABLE",activeOwnerKinds:null,blockingDeploymentId:null,blockingReleaseAttemptId:null,blockingReleaseEnvironment:null,recoveredDeploymentId:null,incumbentServing:"UNKNOWN"};BLOCKED_ELIGIBLE_STATIC_FAILURES=[{stage:"route",code:"APP_SERVING_ROUTE_EPOCH_CONFLICT"},{stage:"controller",code:"PLATFORM_STALE_DEPLOYMENT_RECOVERED"}]}});function buildSettledStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;return{status:503,body:{error:fallbackDiagnostic.selfService.reason.summary,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:operation.environment==="static"?settledStaticServingState(input2.routeRetryReadiness):"PRESERVED",retryClass:"platform-action",userAction:"RETRY",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"RETRY",command:fallbackDiagnostic.newDeploymentCommand},diagnostic:fallbackDiagnostic}}}function buildChangedStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;const staleShape=input2.failureCode===STALE_DEPLOYMENT_RECOVERED_CODE2&&input2.failureStage==="controller";const epochShape=input2.failureCode===ROUTE_EPOCH_CONFLICT_CODE3&&input2.failureStage==="route";if(!fallbackDiagnostic||!(staleShape||epochShape)||input2.recoveryRequired||operation.environment!=="static"||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt?.phase!=="failed"||currentReceipt.code!==input2.failureCode||input2.routeRetryReadiness.incumbentServing!=="CHANGED"){return null}const statusCommand=`gencow deploy status --deployment ${operation.deploymentId}`;const error62="The deployment's content is live and serving changed to it, but its record is closed as failed. Check this operation's status before starting another deployment.";const retryCondition="Serving already changed to this deployment's live content and its record is terminal. Do not start or repeat a deployment for this operation; check its status, and start a new deployment only to change the app.";const reasonSummary="This deployment's content is live and serving changed to it, but Platform closed its record as failed. No retry is needed.";return{status:503,body:{error:error62,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:"CHANGED",retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:retryCondition,...epochShape?{retryReady:false,retryReadinessReason:input2.routeRetryReadiness.reason,statusCommand}:{},correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"VIEW_STATUS",command:statusCommand},diagnostic:{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:"VIEW_STATUS",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:retryCondition},action:{kind:"VIEW_STATUS",command:statusCommand},stateImpact:{...fallbackDiagnostic.selfService.stateImpact,incumbentServing:"CHANGED",operationState:"FAILED"},reason:{code:"deployment_content_live",summary:reasonSummary}}}}}}var STALE_DEPLOYMENT_RECOVERED_CODE2,ROUTE_EPOCH_CONFLICT_CODE3;var init_deployment_stale_changed_presentation=__esm({"../platform/src/deployment-stale-changed-presentation.ts"(){"use strict";init_deployment_route_retry_readiness();STALE_DEPLOYMENT_RECOVERED_CODE2="PLATFORM_STALE_DEPLOYMENT_RECOVERED";ROUTE_EPOCH_CONFLICT_CODE3="APP_SERVING_ROUTE_EPOCH_CONFLICT"}});function buildSupersededStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;const superseded=currentReceipt?.warnings?.some(warning=>warning.code===SUPERSEDED_BY_NEWER_COMMIT_CODE2||warning.code===SUPERSEDED_SCHEMA_OUTCOME_CODE);if(!fallbackDiagnostic||!superseded||input2.failureCode!==STALE_DEPLOYMENT_RECOVERED_CODE3||input2.failureStage!=="controller"||input2.recoveryRequired||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt?.phase!=="failed"||currentReceipt.code!==input2.failureCode){return null}const ambiguous=currentReceipt.databaseState==="RECOVERY_REQUIRED";const inspectCommand=operation.environment==="prod"?"gencow db:check --prod --inspect-state":"gencow db:check --inspect-state";const statusCommand=`gencow deploy status --deployment ${operation.deploymentId}`;const nextAction=ambiguous?{kind:"INSPECT_STATE",command:inspectCommand}:{kind:"VIEW_STATUS",command:statusCommand};const error62=ambiguous?"A newer deployment is serving this app, so this deployment was closed as failed. Its database outcome is uncertain: check the migration state before relying on the schema. New deployments are accepted.":"A newer deployment is serving this app, so this deployment was closed as failed. No retry is needed. New deployments are accepted.";const retryCondition=ambiguous?`Do not repeat this operation. Run "${inspectCommand}" to confirm the migration state, then start a new deployment only to change the app.`:"Do not repeat this operation. Check its status if needed; a new deployment is accepted to change the app.";return{status:409,body:{error:error62,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:"PRESERVED",retryClass:"platform-action",userAction:ambiguous?"INSPECT_STATE":"VIEW_STATUS",retryPrecondition:retryCondition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction,diagnostic:{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:ambiguous?"INSPECT_STATE":"VIEW_STATUS",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:retryCondition},action:nextAction,stateImpact:{...fallbackDiagnostic.selfService.stateImpact,mutation:ambiguous?"UNKNOWN":currentReceipt.databaseState==="APPLIED"?"APPLIED":"NONE",incumbentServing:"PRESERVED",operationState:"FAILED"},reason:{code:ambiguous?"stale_superseded_schema_outcome":"stale_superseded_by_newer_commit",summary:error62}}}}}}var STALE_DEPLOYMENT_RECOVERED_CODE3,SUPERSEDED_BY_NEWER_COMMIT_CODE2;var init_deployment_stale_superseded_presentation=__esm({"../platform/src/deployment-stale-superseded-presentation.ts"(){"use strict";init_deployment_superseded_by_newer_commit();STALE_DEPLOYMENT_RECOVERED_CODE3="PLATFORM_STALE_DEPLOYMENT_RECOVERED";SUPERSEDED_BY_NEWER_COMMIT_CODE2="PLATFORM_STALE_SUPERSEDED_BY_NEWER_COMMIT"}});function deploymentStatusPath(deploymentId){return`/platform/deployments/${deploymentId}`}function pendingDeploymentBody(attempt,appName,executorState,executorAvailable=true,options={}){const state2=executorState==="queued"?"queued":"running";const executorUnavailable=executorAvailable===false;const executorObservationUnknown=executorAvailable===null;const databaseState=executorObservationUnknown?"UNKNOWN":options.databaseState??(executorState==="queued"?"UNCHANGED":"UNKNOWN");const servingState=executorObservationUnknown||databaseState==="APPLIED"?"UNKNOWN":options.servingState??"UNKNOWN";return{accepted:true,status:executorUnavailable?"queued_executor_unavailable":executorState,executorAvailable,...executorAvailable===true?{}:{code:options.diagnosticCode??"PLATFORM_DEPLOYMENT_EXECUTOR_UNAVAILABLE"},...executorAvailable===true?{}:{stage:"executor",capability:options.capability??"deployment_executor_process",retryClass:options.retryClass??"retryable-infra",userAction:"VIEW_STATUS",...executorObservationUnknown?{executorObservation:"unknown"}:{},retryPrecondition:options.retryPrecondition??"Wait for the target deployment executor process to recover before retrying.",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${attempt.deploymentId}`}},databaseState,servingState,operationId:attempt.deploymentId,deployId:attempt.deploymentId,correlationId:attempt.correlationId,appName,state:state2,...options.phase??{},pollUrl:deploymentStatusPath(attempt.deploymentId)}}var init_deployment_executor_http_pending=__esm({"../platform/src/deployment-executor-http-pending.ts"(){"use strict"}});async function resolveDeploymentStatusResponse(input2){const operation=await(input2.getStatusImpl??getOwnedDeploymentExecutorStatus)({db:input2.db,deploymentId:input2.deploymentId,userId:input2.user.id});if(!operation||input2.user.tokenType==="deploy"&&input2.user.appId!==operation.appId){return{status:404,body:{error:"Deployment operation not found"}}}const verifiedReceipt=readVerifiedDeploymentExecutorReceipt(operation);const currentReceipt=verifiedReceipt?.phase===operation.executorState?verifiedReceipt:null;const response=await resolveAuthorizedDeploymentStatusResponse(input2,operation,currentReceipt,verifiedReceipt);if(!currentReceipt?.warnings?.length)return response;return{...response,body:{...response.body,warnings:publicDeploymentExecutorWarnings(currentReceipt.warnings)}}}async function resolveAuthorizedDeploymentStatusResponse(input2,operation,currentReceipt,verifiedReceipt){const staleRecoveryNewDeploymentCommand=resolveStaleDeploymentNewDeploymentCommand({executionEnvironment:operation.environment,releaseEnvironment:operation.releaseEnvironment,releaseBindingPresent:operation.releaseAttemptId!=null});const backendServing=operation.environment==="static"?null:await observeBackendServing({db:input2.db,appId:operation.appId,correlationId:operation.correlationId,loadRouteBindingImpl:input2.loadRouteBindingImpl});const servingRouteBinding=backendServing?.kind==="SERVING"?backendServing.binding:null;const candidateCleanupServingState=operation.environment==="static"?"NOT_APPLICABLE":backendServingState(backendServing);let candidateCleanupDebt=null;let candidateCleanupDebtObservationUnavailable=false;if(currentReceipt?.code==="CANDIDATE_CLEANUP_PENDING"){try{if(input2.findCandidateCleanupDebtImpl){candidateCleanupDebt=await input2.findCandidateCleanupDebtImpl({db:input2.db,appId:operation.appId,env:operation.environment})}else if(input2.hasCandidateCleanupDebtImpl){candidateCleanupDebt=await input2.hasCandidateCleanupDebtImpl({db:input2.db,appId:operation.appId,env:operation.environment})?{deploymentId:operation.deploymentId}:null}else{candidateCleanupDebt=await findCandidateCleanupDebt({db:input2.db,appId:operation.appId,env:operation.environment})}}catch{candidateCleanupDebtObservationUnavailable=true}}const candidateCleanupPending=candidateCleanupDebt!==null;const candidateCleanupBlockingOperationId=candidateCleanupDebt?.deploymentId??operation.deploymentId;let candidateCleanupRecoveryObservation="not_required";if(candidateCleanupDebtObservationUnavailable){candidateCleanupRecoveryObservation="unavailable"}else if(candidateCleanupPending){try{candidateCleanupRecoveryObservation=await(input2.hasDurableCandidateCleanupRecoveryRequiredImpl??hasDurableCandidateCleanupRecoveryRequired)({db:input2.db,appId:operation.appId,deploymentId:candidateCleanupBlockingOperationId})?"required":"not_required"}catch{candidateCleanupRecoveryObservation="unavailable"}}if(candidateCleanupRecoveryObservation!=="not_required"){const recoveryUnavailable=candidateCleanupRecoveryObservation==="unavailable";return{status:503,body:{error:recoveryUnavailable?"Platform cleanup recovery state is temporarily unavailable":"Platform runtime cleanup requires isolated recovery",code:recoveryUnavailable?"PLATFORM_CANDIDATE_CLEANUP_RECOVERY_OBSERVATION_UNAVAILABLE":"PLATFORM_CANDIDATE_CLEANUP_RECOVERY_REQUIRED",deployId:operation.deploymentId,operationId:operation.deploymentId,...candidateCleanupBlockingOperationId===operation.deploymentId?{}:{blockingOperationId:candidateCleanupBlockingOperationId},stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:recoveryUnavailable?"Platform must restore cleanup recovery observation before another deployment can start.":"Platform must prove the previous candidate is absent before another deployment can start.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${candidateCleanupBlockingOperationId}`}}}}if(candidateCleanupPending){return{status:503,body:{error:"Candidate cleanup is still pending",code:currentReceipt.code,deployId:operation.deploymentId,operationId:operation.deploymentId,...candidateCleanupBlockingOperationId===operation.deploymentId?{}:{blockingOperationId:candidateCleanupBlockingOperationId},stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"retryable-infra",userAction:"WAIT",retryPrecondition:"Wait for exact candidate cleanup to finish before starting a new deployment.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${candidateCleanupBlockingOperationId}`}}}}if(currentReceipt?.code==="CANDIDATE_CLEANUP_PENDING"){return{status:503,body:{error:"Candidate cleanup completed; a new deployment may be started",code:"CANDIDATE_CLEANUP_SETTLED",deployId:operation.deploymentId,operationId:operation.deploymentId,stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"retryable-infra",userAction:"RETRY",retryPrecondition:"Exact candidate cleanup is complete.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"RETRY",command:operation.environment==="prod"?"gencow deploy --prod":"gencow deploy"}}}}if(operation.status==="running"&&operation.controlPlaneState==="active"&&(operation.executorState==="not_queued"||hasVerifiedDeploymentExecutorCompletion(operation))){if(operation.environment==="static"){if(operation.currentStaticDeployId!==operation.deploymentId){return{status:409,body:{error:"Static deployment projection is incomplete",code:"STATIC_ROUTE_CONVERGENCE_PENDING",stage:"route",retryClass:"retryable-infra",userAction:"RETRY",correlationId:operation.correlationId,appName:operation.appName,state:"running",operationId:operation.deploymentId,deployId:operation.deploymentId,pollUrl:deploymentStatusPath(operation.deploymentId)}}}return{status:200,body:{success:true,bundleHash:operation.bundleHash.slice(0,8),url:input2.getAppUrl(operation.appName,operation.appPort),files:null,size:operation.staticSize,deployId:operation.deploymentId,operationId:operation.deploymentId,correlationId:operation.correlationId,controlPlane:"v1",appName:operation.appName,state:"succeeded"}}}const binding=servingRouteBinding;if(!binding){return{status:202,headers:{Location:deploymentStatusPath(operation.deploymentId),"Retry-After":"1"},body:pendingDeploymentBody({deploymentId:operation.deploymentId,appId:operation.appId,env:operation.environment,attemptId:"",correlationId:operation.correlationId,sourceBundleSha256:"",replayed:true,status:operation.status,controlPlaneState:operation.controlPlaneState,bundleHash:operation.bundleHash,artifactRef:null},operation.appName,operation.executorState,true)}}if(binding.deploymentId!==operation.deploymentId){return{status:409,body:{error:"Deployment route commit is incomplete",code:"ROUTE_CONVERGENCE_PENDING",stage:"route",retryClass:"retryable-infra",userAction:"RETRY",correlationId:operation.correlationId,appName:operation.appName,state:"running",operationId:operation.deploymentId,deployId:operation.deploymentId,pollUrl:deploymentStatusPath(operation.deploymentId)}}}return{status:200,body:{success:true,bundleHash:operation.bundleHash.slice(0,8),url:input2.getAppUrl(operation.appName,binding.port),deployId:operation.deploymentId,operationId:operation.deploymentId,correlationId:operation.correlationId,controlPlane:"v1",appName:operation.appName,state:"succeeded"}}}if(operation.status==="failed"||operation.executorState==="failed"||operation.executorState==="recovery_required"){const recoveryRequired=operation.executorState==="recovery_required";const failureCode2=operation.failureCode||resolvePlatformExecutorTerminalCode(recoveryRequired);const failureStage=operation.failureStage||"controller";const failurePolicy=resolveStoredDeploymentFailurePolicy(failureStage,failureCode2);const routeRetryReadiness=operation.environment==="static"&&isBlockedEligibleStaticFailure({stage:failureStage,code:failureCode2})&&currentReceipt?.phase==="failed"&&operation.appInstanceId===operation.executorAppInstanceId&&(operation.releaseEnvironment==="dev"||operation.releaseEnvironment==="prod")?await(input2.readStaticRouteRetryReadinessImpl??readStaticRouteRetryReadiness)({db:input2.db,appId:operation.appId,appInstanceId:operation.appInstanceId,releaseEnvironment:operation.releaseEnvironment,servingRouteEnvironment:input2.servingRouteEnvironment===void 0?appReleaseRuntimeConfig().servingRoute.environment:input2.servingRouteEnvironment,deploymentId:operation.deploymentId}).catch(()=>UNKNOWN_STATIC_ROUTE_RETRY_READINESS):UNKNOWN_STATIC_ROUTE_RETRY_READINESS;const fallbackDiagnostic=currentReceipt?buildPublicDeploymentExecutorDiagnostic({code:failureCode2||currentReceipt.code,stage:failureStage,recoveryRequired,receipt:currentReceipt,correlationId:operation.correlationId,operationId:String(operation.deploymentId),incumbentServing:operation.environment==="static"?publicStaticIncumbentServing(routeRetryReadiness):backendServingState(backendServing),environment:operation.environment,releaseEnvironment:operation.releaseEnvironment,releaseBindingPresent:operation.releaseAttemptId!=null,routeRetryReadiness}):null;if(recoveryRequired&&failureStage==="route"&&operation.environment!=="static"&&isCommittedRouteBlockedReceipt(currentReceipt)&&fallbackDiagnostic?.newDeploymentCommand!==void 0&&fallbackDiagnostic.newDeploymentCommand===staleRecoveryNewDeploymentCommand){return{status:503,body:{error:fallbackDiagnostic.selfService.reason.summary,code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,databaseState:currentReceipt.databaseState,servingState:backendServingState(backendServing),retryClass:"platform-action",userAction:"RETRY",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"RETRY",command:fallbackDiagnostic.newDeploymentCommand},diagnostic:fallbackDiagnostic}}}if(operation.status==="superseded"&&operation.environment!=="static"&&isSupersededByNewerCommitReceipt(currentReceipt)&&fallbackDiagnostic){return{status:409,body:{error:fallbackDiagnostic.selfService.reason.summary,code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,databaseState:currentReceipt.databaseState,servingState:"PRESERVED",retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`},diagnostic:fallbackDiagnostic}}}const superseded=buildSupersededStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,failureCode:failureCode2,failureStage,recoveryRequired});if(superseded)return superseded;const crashedRetired=buildCrashedStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,failureCode:failureCode2,failureStage,recoveryRequired});if(crashedRetired)return crashedRetired;const settledStaleDeployment=failureCode2==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&failureStage==="controller"&&operation.status==="failed"&&operation.controlPlaneState==="failed"&&operation.executorState==="failed"&&currentReceipt?.phase==="failed"&&currentReceipt.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&!recoveryRequired&&(operation.environment==="static"?staticStaleServingProven(routeRetryReadiness):Boolean(servingRouteBinding))&&fallbackDiagnostic?.retryability==="NEW_DEPLOYMENT_AFTER_STATUS"&&staleRecoveryNewDeploymentCommand!==null&&fallbackDiagnostic.newDeploymentCommand===staleRecoveryNewDeploymentCommand;if(settledStaleDeployment){return buildSettledStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,routeRetryReadiness,failureStage,failureCode:failureCode2})}const changedStale=buildChangedStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,routeRetryReadiness,failureCode:failureCode2,failureStage,recoveryRequired});if(changedStale)return changedStale;const unverifiedStaleDeployment=failureCode2==="PLATFORM_STALE_DEPLOYMENT_RECOVERED";const diagnostic=unverifiedStaleDeployment&&fallbackDiagnostic?{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:"VIEW_STATUS",observedState:"BLOCKED",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:"Platform has not verified the terminal recovery receipt and preserved serving state. Do not start another deployment until status confirms recovery and app admission is open."},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`},stateImpact:{...fallbackDiagnostic.selfService.stateImpact,incumbentServing:backendServingState(backendServing),operationState:"BLOCKED"},reason:{code:"stale_deployment_recovery_unverified",summary:"Platform has not verified the terminal recovery receipt and preserved serving deployment. Check this operation before starting another deployment."}}}:fallbackDiagnostic;const rootCauseClass=publicRoutePrepareRootCauseClass({stage:failureStage,code:failureCode2,stored:currentReceipt?.rootCauseClass});const routeTargetRejections=publicRouteTargetRejections({stage:failureStage,code:failureCode2,stored:currentReceipt?.routeTargetRejections});const userAction=unverifiedStaleDeployment?"VIEW_STATUS":((routeRetryReadiness.retryReady||routeRetryReadiness.reason==="ALREADY_RECOVERED")&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?fallbackDiagnostic?.action:currentReceipt?.diagnostic?.nextAction.kind)??fallbackDiagnostic?.action??resolvePublicSelfServiceAction({code:failureCode2,stage:failureStage,requestedAction:recoveryRequired?"OPERATOR_ACTION":failurePolicy.userAction,operationId:String(operation.deploymentId)});const retryClass=unverifiedStaleDeployment?"platform-action":currentReceipt?.diagnostic?.failureClass==="USER_FIXABLE"?"terminal-client":currentReceipt?.diagnostic?.failureClass==="RETRYABLE_INFRA"?"retryable-infra":routeRetryReadiness.retryReady&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?"retryable-infra":recoveryRequired?"platform-action":failurePolicy.retryClass;return{status:recoveryRequired||unverifiedStaleDeployment?503:failurePolicy.status,body:{error:unverifiedStaleDeployment?"Platform has not verified stale deployment recovery. Check this operation before starting another deployment.":(failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&(routeRetryReadiness.reason==="READY"||routeRetryReadiness.reason==="ALREADY_RECOVERED")?fallbackDiagnostic?.selfService.reason.summary:currentReceipt?.diagnostic?.reason.summary)??(recoveryRequired?"Deployment state inspection is required":failurePolicy.error),code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,retryClass,userAction,correlationId:operation.correlationId,appName:operation.appName,state:recoveryRequired||unverifiedStaleDeployment?"blocked":"failed",...unverifiedStaleDeployment?{nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`}}:{},...operation.environment==="static"&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?{retryReady:routeRetryReadiness.retryReady,retryReadinessReason:routeRetryReadiness.reason,activeOwnerKinds:routeRetryReadiness.activeOwnerKinds??null,statusCommand:`gencow deploy status --deployment ${operation.deploymentId}`,...routeRetryReadiness.blockingDeploymentId?{blockingOperationId:routeRetryReadiness.blockingDeploymentId}:{},...routeRetryReadiness.blockingReleaseAttemptId&&routeRetryReadiness.blockingReleaseEnvironment?{blockingReleaseAttemptId:routeRetryReadiness.blockingReleaseAttemptId,blockingReleaseEnvironment:routeRetryReadiness.blockingReleaseEnvironment}:{},...routeRetryReadiness.recoveredDeploymentId?{recoveredOperationId:routeRetryReadiness.recoveredDeploymentId}:{}}:{},...rootCauseClass?{rootCauseClass}:{},...routeTargetRejections?{routeTargetRejections}:{},...buildPublicFailureChain({primaryCode:failureCode2,primaryStage:failureStage,correlationId:operation.correlationId}),...diagnostic?{diagnostic}:{}}}}const routeOnlyResume=operation.environment!=="static"&&operation.status==="pending"&&operation.executorState==="reconciling"&&isRouteOnlyResumeReceipt(verifiedReceipt);const observation=routeOnlyResume?{targetGenerationBound:true,executorAvailable:true,probeFailed:false}:await observeDeploymentExecutorProcess({db:input2.db,nodeId:operation.targetNodeId,slotId:operation.targetSlotId,revision:operation.targetRevision,ownerId:operation.targetOwnerId,generationDigest:operation.targetGenerationDigest,probeImpl:input2.hasReadyExecutorProcessImpl});const{targetGenerationBound,executorAvailable,probeFailed:executorProbeFailed}=observation;const diagnosticCode=targetGenerationBound?executorProbeFailed?"PLATFORM_DEPLOYMENT_EXECUTOR_STATUS_UNAVAILABLE":void 0:"DEPLOYMENT_EXECUTOR_GENERATION_UNAVAILABLE";return{status:202,headers:{Location:deploymentStatusPath(operation.deploymentId),"Retry-After":"1"},body:pendingDeploymentBody({deploymentId:operation.deploymentId,appId:operation.appId,env:operation.environment,attemptId:"",correlationId:operation.correlationId,sourceBundleSha256:"",replayed:true,status:operation.status,controlPlaneState:operation.controlPlaneState,bundleHash:operation.bundleHash,artifactRef:null},operation.appName,operation.executorState,executorAvailable,{phase:resolvePendingDeploymentPhase({executorState:operation.executorState,environment:operation.environment,receipt:verifiedReceipt,queuedAt:operation.queuedAt}),databaseState:verifiedReceipt?.databaseState,servingState:operation.environment==="static"?operation.currentStaticDeployId!==null&&operation.currentStaticDeployId!==operation.deploymentId?"PRESERVED":"UNKNOWN":backendServingState(backendServing),capability:targetGenerationBound?"deployment_executor_process":"deployment_executor_generation_fence",diagnosticCode,retryClass:targetGenerationBound&&!executorProbeFailed?"retryable-infra":"platform-action",retryPrecondition:!targetGenerationBound?"Wait for Platform to restore the exact executor generation before retrying.":executorProbeFailed?"Wait for Platform status observation to recover, then check this operation again.":void 0})}}async function presentDeploymentStatus(input2){const response=await resolveDeploymentStatusResponse(input2);for(const[name,value2]of Object.entries(response.headers??{}))input2.c.header(name,value2);return input2.c.json(response.body,response.status)}var init_deployment_executor_http_presentation=__esm({"../platform/src/deployment-executor-http-presentation.ts"(){"use strict";init_deployment_executor_warning_receipt();init_deployment_executor_store();init_deployment_executor_pending_phase();init_deployment_executor_process_observation();init_deployment_backend_incumbent_serving();init_deployment_executor_public_diagnostic();init_deployment_failure_public_diagnostic();init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_route_prepare_root_cause();init_deployment_request_admission();init_deployment_executor_completion_contract();init_deployment_committed_route_contract();init_runtime_exact_cleanup_operation_store();init_public_self_service_diagnostic();init_app_release_runtime_env();init_deployment_stale_changed_presentation();init_deployment_stale_superseded_presentation();init_deployment_stale_crashed_presentation();init_deployment_route_retry_readiness();init_deployment_executor_http_pending();init_deployment_executor_http_pending();init_deployment_executor_completion_contract()}});import{createHash as createHash69}from"node:crypto";import{and as and31,desc as desc7,eq as eq34,gt as gt7,sql as sql112}from"drizzle-orm";async function getOwnedDeploymentFailureReceipt(db,ownerId,correlationId,now=new Date){if(!CORRELATION_PATTERN.test(correlationId))return null;const rows8=await db.select().from(deploymentFailureReceipts).where(and31(eq34(deploymentFailureReceipts.ownerId,ownerId),eq34(deploymentFailureReceipts.correlationId,correlationId),gt7(deploymentFailureReceipts.retainUntil,now))).limit(1);return rows8[0]??null}async function getLatestAppDeploymentFailureReceiptForOperator(db,appId,appInstanceId,now=new Date){const rows8=await db.select().from(deploymentFailureReceipts).where(and31(eq34(deploymentFailureReceipts.appId,appId),eq34(deploymentFailureReceipts.appInstanceId,appInstanceId),gt7(deploymentFailureReceipts.retainUntil,now))).orderBy(desc7(deploymentFailureReceipts.createdAt)).limit(1);return rows8[0]??null}var CORRELATION_PATTERN,DEFAULT_RETENTION_MS,DEFAULT_GC_GRACE_MS;var init_deployment_failure_receipt_store=__esm({"../platform/src/deployment-failure-receipt-store.ts"(){"use strict";init_schema();init_candidate_failure_provenance();CORRELATION_PATTERN=/^[A-Za-z0-9_-]{8,128}$/u;DEFAULT_RETENTION_MS=30*24*60*6e4;DEFAULT_GC_GRACE_MS=24*60*6e4}});function hasDeployOperationPollingCapability(value2){if(!value2||value2.length>1024)return false;return value2.split(",").map(capability2=>capability2.trim()).filter(capability2=>CAPABILITY_PATTERN2.test(capability2)).includes(DEPLOY_OPERATION_POLL_CAPABILITY)}function hasDeployOperationPollingProtocol(input2){return input2.deployProtocol?.trim()==="1"||hasDeployOperationPollingCapability(input2.capabilities)}function deployOperationCapabilityUpgradeBody(){return{error:"This CLI cannot wait for an asynchronous deployment result",code:"DEPLOY_CLI_UPGRADE_REQUIRED",stage:"admission",retryClass:"terminal-client",userAction:"UPDATE_CLI",requiredCapability:DEPLOY_OPERATION_POLL_CAPABILITY}}var DEPLOY_OPERATION_POLL_CAPABILITY,CAPABILITY_PATTERN2;var init_deploy_operation_capability=__esm({"../platform/src/deploy-operation-capability.ts"(){"use strict";DEPLOY_OPERATION_POLL_CAPABILITY="deploy-operation-poll-v1";CAPABILITY_PATTERN2=/^[a-z0-9][a-z0-9-]{0,63}$/u}});import{eq as eq35}from"drizzle-orm";import{randomUUID as randomUUID46}from"node:crypto";function registerPlatformApiDeployRoutes({app:app2,getDb:getDb3,withOwnerTransaction,getUser,getAppUrl,currentNodeId,currentSlotId=(process.env.GENCOW_PLATFORM_SLOT||"active").trim().toLowerCase(),currentRevision=resolveDeploymentExecutorRevision(),executorSpoolRoot:executorSpoolRoot2,acquireAdmissionLock:acquireAdmissionLock2,maxQueuedOperations,maxQueuedBytes,busyRetryTimeoutMs,logger:logger3=console}){const deployApp=async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);const{name}=c.req.param();const db=getDb3();const appRows=await db.select().from(apps).where(eq35(apps.name,name));if(appRows.length===0||appRows[0].userId!==user2.id){return c.json({error:"App not found"},404)}const appRow=appRows[0];const holdResponse=buildAppAccountHoldResponse(appRow);if(holdResponse)return c.json(holdResponse.body,holdResponse.status);const environment=c.req.query("env")||"dev";if(environment!=="dev"&&environment!=="prod"){return c.json({error:"Invalid deployment environment"},400)}let bundleBuffer;const contentType=c.req.header("Content-Type")||"";if(contentType.includes("multipart")){const form=await c.req.formData();const file2=form.get("bundle");if(!file2)return c.json({error:"bundle field missing"},400);bundleBuffer=Buffer.from(await file2.arrayBuffer())}else{bundleBuffer=Buffer.from(await c.req.arrayBuffer())}const supportsOperationPolling=hasDeployOperationPollingProtocol({capabilities:c.req.header("X-Gencow-CLI-Capabilities"),deployProtocol:c.req.header("X-Gencow-Deploy-Protocol")});if(!supportsOperationPolling){return c.json(deployOperationCapabilityUpgradeBody(),426)}const proxied=await maybeProxyAppHomeNodeResponse({app:appRow,db,req:{raw:c.req.raw,method:"POST"},pathSuffix:"/deploy",query:{env:environment},body:Uint8Array.from(bundleBuffer),logger:logger3});if(proxied){if(proxied instanceof Response)return proxied;return c.json(proxied.body??{},proxied.status??502)}let attempt=null;let protocolHeaders=deploymentProtocolResponseHeaders(c.req.header("X-Gencow-Deploy-Claim")?"v1-enforce":"legacy-observe");const applyProtocolHeaders=()=>{for(const[header,value2]of Object.entries(protocolHeaders))c.header(header,value2)};try{const admission=await admitDeploymentExecutorRequestAfterActiveOperation({db,withOwnerTransaction,app:appRow,userId:user2.id,environment,bundle:bundleBuffer,getHeader:header=>c.req.header(header)||"",currentNodeId,currentSlotId,currentRevision,spoolRoot:executorSpoolRoot2,acquireAdmissionLock:acquireAdmissionLock2,maxQueuedOperations,maxQueuedBytes},{timeoutMs:busyRetryTimeoutMs});protocolHeaders=admission.protocolHeaders;applyProtocolHeaders();const committedAttempt=admission.attempt;attempt=committedAttempt;if(admission.replayed){return presentDeploymentStatus({c,db,user:user2,deploymentId:committedAttempt.deploymentId,getAppUrl})}c.header("Location",deploymentStatusPath(committedAttempt.deploymentId));c.header("Retry-After","1");return c.json(pendingDeploymentBody(committedAttempt,name,"queued",admission.executorAvailable),202)}catch(error62){applyProtocolHeaders();logger3.warn("[deployment-api] admission or enqueue failed",{code:error62 instanceof Error?error62.message:"UNKNOWN",deploymentId:attempt?.deploymentId,...error62 instanceof DeploymentExecutorAdmissionError&&error62.requestId?{requestId:error62.requestId,correlationId:error62.requestId}:{}});const failure2=buildDeployFailureResponse(error62,[],{stage:"admission",correlationId:attempt?.correlationId,cliVersion:c.req.header("X-Gencow-CLI-Version")||void 0,blockingOperation:await resolveAppBusyBlockingOperation({db,appId:appRow.id,error:error62,warn:()=>logger3.warn("[deployment-api] active operation diagnostic read unavailable")})});if(error62 instanceof DeploymentExecutorAdmissionError&&!isAppBusyAdmissionError(error62)){if(error62.httpStatus===429||error62.httpStatus===503){c.header("Retry-After","5")}const confirmedAbsentOutcome=error62.code==="DEPLOYMENT_EXECUTOR_ADMISSION_OUTCOME_UNKNOWN"&&error62.requestId!==void 0&&/^[A-Za-z0-9_-]{16,128}$/u.test(error62.requestId);const reconciliationUnavailable=error62.code==="DEPLOYMENT_EXECUTOR_ADMISSION_RECONCILIATION_UNAVAILABLE"&&error62.requestId!==void 0&&/^[A-Za-z0-9_-]{16,128}$/u.test(error62.requestId);const hasAdmissionRequestIdentity=confirmedAbsentOutcome||reconciliationUnavailable;const correlationId=hasAdmissionRequestIdentity?error62.requestId:void 0;const queuedOperationId=error62.code==="DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL"&&Number.isSafeInteger(error62.blockingOperationId)&&error62.blockingOperationId>0?error62.blockingOperationId:void 0;const queueDiagnostic=error62.code==="DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL"?buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId:`deploy-queue-${randomUUID46()}`,appName:name,...queuedOperationId===void 0?{}:{operationId:String(queuedOperationId)},databaseState:"UNCHANGED",requestedAction:queuedOperationId===void 0?"WAIT":"VIEW_STATUS",retryAfterSeconds:5,reasonCode:"account_queue_capacity_exhausted",reasonSummary:"This deployment was not started because the account's queued deployment capacity is full. Check the existing operation before retrying.",incumbentServing:"PRESERVED",operationState:"BLOCKED"}):void 0;const queueAction=queueDiagnostic?{...queueDiagnostic,action:{...queueDiagnostic.action,command:queuedOperationId===void 0?`gencow deploy status --app ${name}${environment==="prod"?" --prod":""}`:`gencow deploy status --deployment ${queuedOperationId}`}}:void 0;const selfService=hasAdmissionRequestIdentity&&correlationId?buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId,requestId:error62.requestId,appName:name,...confirmedAbsentOutcome?{resumeEnvironment:environment,admissionOutcomeConfirmedAbsent:true,databaseState:"UNCHANGED",requestedAction:"RETRY",reasonCode:"admission_transaction_rolled_back",reasonSummary:"The original deployment claim was not committed; replay the same saved claim.",incumbentServing:"PRESERVED"}:{resumeEnvironment:environment,databaseState:"RECOVERY_REQUIRED",requestedAction:"VIEW_STATUS",reasonCode:"admission_reconciliation_unavailable",reasonSummary:"The server could not verify whether this deployment request committed.",incumbentServing:"UNKNOWN"},operationState:"BLOCKED"}):void 0;return c.json({error:deploymentExecutorAdmissionPublicMessage(error62.code),code:error62.code,stage:"admission",retryClass:reconciliationUnavailable?"platform-action":"retryable-infra",userAction:queueAction?queueAction.action.kind:reconciliationUnavailable?"VIEW_STATUS":"RETRY",...queueAction?{correlationId:queueAction.correlationId,...queuedOperationId===void 0?{}:{blockingOperationId:queuedOperationId},databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",diagnostic:{selfService:queueAction},retryPrecondition:queueAction.retry.condition,nextAction:{kind:queueAction.action.kind,command:queueAction.action.command}}:{},...hasAdmissionRequestIdentity?{requestId:error62.requestId,appName:name,environment,correlationId,databaseState:confirmedAbsentOutcome?"UNCHANGED":"UNKNOWN",activeDeploymentState:confirmedAbsentOutcome?"PRESERVED":"UNKNOWN",diagnostic:{selfService}}:{}},error62.httpStatus)}return c.json(failure2.body,failure2.status)}};app2.post("/api/apps/:name/deploy",deployApp);app2.post("/platform/apps/:name/deploy",deployApp);app2.get("/platform/deployments/:deploymentId",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);const deploymentId=Number(c.req.param("deploymentId"));if(!Number.isSafeInteger(deploymentId)||deploymentId<=0){return c.json({error:"Invalid deployment operation"},400)}return presentDeploymentStatus({c,db:getDb3(),user:user2,deploymentId,getAppUrl})});app2.get("/platform/deployment-executor/status",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);return c.json({available:await hasReadyDeploymentExecutor({db:getDb3(),nodeId:currentNodeId,slotId:currentSlotId,revision:currentRevision}).catch(()=>false)})});app2.get("/platform/deployment-failures/:correlationId",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);let receipt;try{receipt=await getOwnedDeploymentFailureReceipt(getDb3(),user2.id,c.req.param("correlationId"))}catch{return c.json({error:"Deployment failure diagnostic is temporarily unavailable",code:"DEPLOYMENT_FAILURE_DIAGNOSTIC_UNAVAILABLE"},503)}if(!receipt||user2.tokenType==="deploy"&&user2.appId!==receipt.appId){return c.json({error:"Deployment failure diagnostic not found"},404)}const refreshedPolicy=resolvePersistedDeploymentFailurePolicyRefresh(receipt.publicStage,receipt.publicCode);return c.json({success:true,correlationId:receipt.correlationId,attemptId:receipt.deploymentAttemptId,stage:receipt.publicStage,code:receipt.publicCode,retryClass:refreshedPolicy?.retryClass??receipt.retryClass,userAction:refreshedPolicy?.userAction??receipt.requiredAction,failurePhase:receipt.failurePhase,candidateProcessStarted:receipt.processSpawned,candidateLogAvailable:receipt.candidateLogAvailable,databaseState:receipt.databaseState,evidenceSource:receipt.evidenceSource,createdAt:receipt.createdAt})})}var init_platform_api_deploy_route=__esm({"../platform/src/platform-api-deploy-route.ts"(){"use strict";init_schema();init_apps_account_hold();init_apps_home_node_proxy();init_apps_deploy_failures();init_deployment_request_admission();init_deployment_executor_store();init_public_self_service_diagnostic();init_deployment_executor_generation();init_deployment_executor_worker_store();init_deployment_executor_http_presentation();init_deployment_executor_admission();init_deployment_failure_receipt_store();init_deployment_failure_contract();init_deploy_operation_capability()}});function controlPlaneSchemaUnavailableResponse(c,error62,options={}){const unavailable3=options.acceptUndefinedTable?asControlPlaneSchemaUnavailableError(error62):isControlPlaneSchemaUnavailableError(error62);if(!unavailable3)return null;return c.json({error:"Platform control-plane schema is unavailable",code:CONTROL_PLANE_SCHEMA_UNAVAILABLE,retryClass:"platform-action",userAction:"OPERATOR_ACTION"},503)}var init_platform_api_schema_unavailable_response=__esm({"../platform/src/platform-api-schema-unavailable-response.ts"(){"use strict";init_deployment_control_plane_rollout()}});import{and as and32,eq as eq36,like as like3,or as or12}from"drizzle-orm";async function nextPlatformWakeCorrelation(input2){const rows8=await input2.db.select({correlationId:runtimeLifecycleRequests.correlationId,state:runtimeLifecycleRequests.state}).from(runtimeLifecycleRequests).where(and32(eq36(runtimeLifecycleRequests.appId,input2.appId),eq36(runtimeLifecycleRequests.action,"converge"),or12(eq36(runtimeLifecycleRequests.correlationId,input2.baseCorrelationId),like3(runtimeLifecycleRequests.correlationId,`${input2.baseCorrelationId}${CYCLE_SEPARATOR}%`))));let latest={cycle:-1,state:""};for(const row of rows8){const suffix=row.correlationId.slice(input2.baseCorrelationId.length+CYCLE_SEPARATOR.length);const cycle2=row.correlationId===input2.baseCorrelationId?0:Number(suffix);if(Number.isSafeInteger(cycle2)&&cycle2>latest.cycle)latest={cycle:cycle2,state:row.state}}if(latest.cycle<0)return input2.baseCorrelationId;const cycle=latest.state==="completed"?latest.cycle+1:latest.cycle;return cycle===0?input2.baseCorrelationId:`${input2.baseCorrelationId}${CYCLE_SEPARATOR}${cycle}`}var CYCLE_SEPARATOR;var init_runtime_wake_cycle_correlation=__esm({"../platform/src/runtime-wake-cycle-correlation.ts"(){"use strict";init_schema();CYCLE_SEPARATOR=":cycle-"}});import{and as and33,eq as eq37}from"drizzle-orm";function isRetryableBootDbStatusReason(value2){return typeof value2==="string"&&BOOT_DB_FAILURE_REASONS.has(value2)}function buildClassification(statusReason){return{kind:"boot_db_failure",phase:"settings_db_env",retryable:true,status:"failed",statusReason,statusMessage:APP_BOOT_DB_STATUS_MESSAGE}}function parseMarkerReason(text33){const markerMatch=text33.match(new RegExp(`${BOOT_FAILURE_MARKER}\\b[^\\n]*\\breason=(boot_db_[a-z_]+)`));const reason=markerMatch?.[1];return isRetryableBootDbStatusReason(reason)?reason:null}function classifyLegacySettingsDbTrace(text33){const lower=text33.toLowerCase();const hasRuntimePostgresFailure=lower.includes("runtimepostgresclienterror")||lower.includes("postgres client");if(!hasRuntimePostgresFailure)return null;const isSettingsBootPath=lower.includes("_system_settings")||lower.includes("loaddbenvvars")||lower.includes("settings-db-env")||lower.includes("settings.ts");if(!isSettingsBootPath)return null;if(lower.includes("operation_timeout")||lower.includes("operation timeout")){return"boot_db_operation_timeout"}if(lower.includes("generation_changed")||lower.includes("generation changed")){return"boot_db_generation_changed"}if(lower.includes("socket_closed")||lower.includes("socket closed")){return"boot_db_socket_closed"}if(lower.includes("connection_closed")||lower.includes("connection closed")||lower.includes("client is closed")||lower.includes("closed unexpectedly")){return"boot_db_connection_closed"}if(lower.includes("connection_timeout")||lower.includes("connection timeout")||lower.includes("connect timeout")||lower.includes("connection timed out")){return APP_BOOT_DB_CONNECTION_TIMEOUT_REASON}return null}function classifyRuntimeBootFailureFromExitEvent(event){const text33=(event?.stderrTail??[]).join("\n");if(!text33)return null;if(/AUTH_SCHEMA_CONTRACT_INVALID:[^\n]*Expected exactly one (?:legacy|project) Auth schema entry, received [2-9]\d*/u.test(text33)){return{kind:"auth_schema_failure",phase:"auth_schema_contract",retryable:false,status:"failed",statusReason:"auth_schema_provenance_ambiguous",statusMessage:"Auth schema \uC18C\uC2A4\uAC00 \uC911\uBCF5\uB418\uC5B4 \uC2E4\uD589\uC744 \uC911\uB2E8\uD588\uC2B5\uB2C8\uB2E4. \uC911\uBCF5 \uD30C\uC77C\uC744 \uC815\uB9AC\uD55C \uB4A4 \uC7AC\uBC30\uD3EC\uD558\uC138\uC694."}}const markerReason=parseMarkerReason(text33);if(markerReason)return buildClassification(markerReason);const legacyReason=classifyLegacySettingsDbTrace(text33);return legacyReason?buildClassification(legacyReason):null}var APP_BOOT_DB_CONNECTION_TIMEOUT_REASON,APP_BOOT_DB_STATUS_MESSAGE,BOOT_FAILURE_MARKER,RETRYABLE_APP_BOOT_DB_FAILURE_REASONS,BOOT_DB_FAILURE_REASONS;var init_app_boot_failure_policy=__esm({"../platform/src/app-boot-failure-policy.ts"(){"use strict";init_schema();init_app_runtime_event_scope();init_app_status_projector();init_stable_error_code();APP_BOOT_DB_CONNECTION_TIMEOUT_REASON="boot_db_connection_timeout";APP_BOOT_DB_STATUS_MESSAGE="\uC571 \uBD80\uD305 \uC911 \uC124\uC815 DB \uC5F0\uACB0\uC774 \uC77C\uC2DC\uC801\uC73C\uB85C \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4. \uC790\uB3D9 \uBCF5\uAD6C \uB300\uC0C1\uC785\uB2C8\uB2E4.";BOOT_FAILURE_MARKER="GENCOW_RUNTIME_BOOT_FAILURE";RETRYABLE_APP_BOOT_DB_FAILURE_REASONS=["boot_db_connection_closed",APP_BOOT_DB_CONNECTION_TIMEOUT_REASON,"boot_db_generation_changed","boot_db_operation_timeout","boot_db_socket_closed"];BOOT_DB_FAILURE_REASONS=new Set(RETRYABLE_APP_BOOT_DB_FAILURE_REASONS)}});function classifyWakeConvergenceFailure(input2){const typedCode=PUBLIC_WAKE_TYPED_FAILURE_CODE.test(input2.failureCode)?input2.failureCode:void 0;const retryable=typedCode!==void 0&&WAKE_RETRYABLE_CONVERGENCE_CODES.has(typedCode)||isTransientConnectionError(input2.error);return{...typedCode?{lastFailureCode:typedCode}:{},retryable,...retryable?{retryAfterSec:WAKE_TRANSIENT_RETRY_AFTER_SEC,retryCondition:`Retry the wake after ${WAKE_TRANSIENT_RETRY_AFTER_SEC} seconds; no app state changed. Check gencow app status ${input2.appName} before repeating the request.`}:{}}}function typedWakeConvergenceFailureFields(input2){if(input2.reasonCode===MIGRATION_FORWARD_REQUIRED_REASON)return{retryable:false};const classification2=classifyWakeConvergenceFailure({appName:input2.appName,failureCode:input2.failureCode,error:input2.error});return{...classification2.retryable?{hint:`\uC7A0\uC2DC \uD6C4 \uC571 \uC0C1\uD0DC\uB97C \uD655\uC778\uD55C \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694: gencow app status ${input2.appName}.`}:{},stage:"runtime_wake_convergence",stateChanged:false,nextAction:`gencow app status ${input2.appName}`,...classification2}}var PUBLIC_WAKE_TYPED_FAILURE_CODE,WAKE_RETRYABLE_CONVERGENCE_CODES,WAKE_TRANSIENT_RETRY_AFTER_SEC,MIGRATION_FORWARD_REQUIRED_REASON;var init_wake_convergence_failure=__esm({"../platform/src/simple-lifecycle/wake-convergence-failure.ts"(){"use strict";init_transient_connection_error();PUBLIC_WAKE_TYPED_FAILURE_CODE=/^[A-Z][A-Z0-9_]{2,99}$/u;WAKE_RETRYABLE_CONVERGENCE_CODES=new Set(["RUNTIME_CONVERGENCE_OPERATION_MISSING"]);WAKE_TRANSIENT_RETRY_AFTER_SEC=5;MIGRATION_FORWARD_REQUIRED_REASON="runtime_migration_forward_required"}});import postgres from"postgres";import{sql as sql113}from"drizzle-orm";async function notifyRuntimeConvergenceWake(db){await db.execute(sql113`SELECT pg_notify(${RUNTIME_CONVERGENCE_WAKE_CHANNEL}, ${RUNTIME_CONVERGENCE_WAKE_PAYLOAD})`)}var RUNTIME_CONVERGENCE_WAKE_CHANNEL,RUNTIME_CONVERGENCE_WAKE_PAYLOAD;var init_runtime_convergence_wake_signal=__esm({"../platform/src/runtime-convergence-wake-signal.ts"(){"use strict";RUNTIME_CONVERGENCE_WAKE_CHANNEL="gencow_runtime_convergence_v1";RUNTIME_CONVERGENCE_WAKE_PAYLOAD="runtime-convergence-v1"}});function resolveRuntimeOwner(input2){return resolveRuntimeLane(input2)}function isCanonicalDeploymentAbsent(canonicalDeploymentPresent){return isCanonicalClaimAbsent(canonicalDeploymentPresent)}var init_runtime_owner_resolution=__esm({"../platform/src/runtime-owner-resolution.ts"(){"use strict";init_runtime_lane()}});function isPublicRuntimeConvergencePendingReason(value2){return typeof value2==="string"&&PUBLIC_REASON.test(value2)}function runtimeConvergencePendingClass(reason){if(ARTIFACT_UNAVAILABLE.has(reason))return"artifact_unavailable";if(OWNERSHIP.has(reason))return"ownership_conflict";if(OBSERVING.has(reason))return"observing";return"applying"}function runtimeConvergencePendingGuidance(reason,appName){const status=appName?`gencow app status ${appName}`:"gencow app status";const pendingClass=runtimeConvergencePendingClass(reason);if(pendingClass==="artifact_unavailable"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:false,retryPrecondition:"repeating the request cannot succeed: the runtime artifact of this app is no longer in the artifact store; a new deployment creates a new artifact",command:status,nextAction:`\uC571\uC744 \uB2E4\uC2DC \uBC30\uD3EC\uD558\uC138\uC694: \uC571 \uC791\uC5C5\uACF5\uAC04\uC5D0\uC11C gencow deploy \uC2E4\uD589 (PROD \uC571\uC740 gencow deploy --prod), \uADF8 \uB2E4\uC74C \`${status}\`\uB85C \uD655\uC778`,responsibility:"platform_then_owner"}}if(pendingClass==="ownership_conflict"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:false,retryPrecondition:"the platform kept the current runtime because it could not prove who owns it; repeating the request does not change that",command:status,nextAction:`run \`${status}\` and keep the correlation id; if the reason stays, redeploy from the app workspace: gencow deploy (add --prod for PROD)`,responsibility:"platform_then_owner"}}if(pendingClass==="observing"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:true,retryPrecondition:"wait for Retry-After; the platform is waiting for a complete runtime observation",command:status,nextAction:`retry after Retry-After; if the same reason repeats, run \`${status}\` and keep the correlation id`,responsibility:"platform"}}return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:true,retryPrecondition:"wait for Retry-After; the platform is applying the correction for this reason",command:status,nextAction:`retry after Retry-After; if the same reason repeats, run \`${status}\` and keep the correlation id`,responsibility:"platform"}}function runtimeConvergencePendingReasonFor(failureCode2,storedReason){if(typeof failureCode2==="string"&&ARTIFACT_UNAVAILABLE_FAILURE_CODES.has(failureCode2)){return"runtime_artifact_unavailable"}return failureCode2===RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE&&isPublicRuntimeConvergencePendingReason(storedReason)?storedReason:void 0}var RUNTIME_CONVERGENCE_PENDING_REASONS,OBSERVING,OWNERSHIP,ARTIFACT_UNAVAILABLE,ARTIFACT_UNAVAILABLE_FAILURE_CODES,KNOWN,PUBLIC_REASON,RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE;var init_runtime_convergence_pending_reason=__esm({"../internal/dist/src/runtime-convergence-pending-reason.js"(){"use strict";RUNTIME_CONVERGENCE_PENDING_REASONS=["committed_activation_route_ack_missing","route_epoch_stale","serving_runtime_status_projection_stale","compatibility_projection_stale","retained_activation_exited","retained_activation_stopped","desired_instance_absent","non_attested_starting_runtime","unhealthy_serving_exact_identity","desired_instance_unhealthy","runtime_env_protocol_unsupported","platform_bootstrap_not_desired","durable_stop_intent_pending","durable_stop_exit_observed","desired_runtime_stopped","restore_enqueued","authority_not_enforced","observation_incomplete","observation_fence_stale","exact_binding_incomplete","runtime_observation_unknown","route_observation_unknown","projection_observation_unknown","draining_without_consumable_intent","runtime_ownership_foreign","runtime_ownership_ambiguous","tenant_runtime_without_desired_activation","stopped_runtime_ownership_ambiguous","runtime_artifact_unavailable","unclassified"];OBSERVING=new Set(["authority_not_enforced","observation_incomplete","observation_fence_stale","exact_binding_incomplete","runtime_observation_unknown","route_observation_unknown","projection_observation_unknown","draining_without_consumable_intent"]);OWNERSHIP=new Set(["runtime_ownership_foreign","runtime_ownership_ambiguous","tenant_runtime_without_desired_activation","stopped_runtime_ownership_ambiguous"]);ARTIFACT_UNAVAILABLE=new Set(["runtime_artifact_unavailable"]);ARTIFACT_UNAVAILABLE_FAILURE_CODES=new Set(["RUNTIME_CONVERGENCE_AUTHORITY_RUNTIME_ARTIFACT_UNAVAILABLE","ARTIFACT_NOT_FOUND"]);KNOWN=new Set(RUNTIME_CONVERGENCE_PENDING_REASONS);PUBLIC_REASON=/^[a-z][a-z0-9_]{2,79}$/u;RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE="RUNTIME_CONVERGENCE_PENDING"}});import{sql as sql114}from"drizzle-orm";async function readRuntimeConvergencePendingReasons(db,receipts){const pending=receipts.filter(receipt=>receipt.lastFailureCode===RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE);const reasons=new Map;for(const receipt of pending){const rows8=postgresExecuteRows(await db.execute(sql114`
9266
+ `);const rows8=postgresExecuteRows(result3);if(rows8.length!==1)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;const row=rows8[0];const authorityEpoch=row.authority_epoch===null?0:Number(row.authority_epoch);const observedEpoch=row.observed_epoch===null?0:Number(row.observed_epoch);if(!Number.isSafeInteger(authorityEpoch)||authorityEpoch<0||!Number.isSafeInteger(observedEpoch)||observedEpoch<0||observedEpoch===0||observedEpoch<authorityEpoch||typeof row.active_reservation!=="boolean"||typeof row.active_release!=="boolean"||row.active_release&&!isWellFormedActiveRelease(row.active_release_attempt_id,row.active_release_environment)||!row.active_release&&(row.active_release_attempt_id!==null||row.active_release_environment!==null)||typeof row.active_runtime_recovery!=="boolean"||typeof row.active_delete!=="boolean"||typeof row.incumbent_committed!=="boolean"||typeof row.pointer_proven_incumbent!=="boolean"||row.authority_environment!==null&&row.authority_environment!==input2.servingRouteEnvironment||row.authority_instance_id!==null&&row.authority_instance_id!==input2.appInstanceId||row.authority_environment===null!==(row.authority_instance_id===null)||row.authority_environment===null&&(row.authority_epoch!==null||row.authority_entry_payload!==null||row.authority_entry_hash!==null))return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;let authorityEntry=null;if(row.authority_environment===null){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}if(row.authority_environment!==null){try{authorityEntry=buildServingRouteManifestEntry(JSON.parse(row.authority_entry_payload??""));if(row.authority_disposition!=="upsert"||authorityEntry.disposition!==row.authority_disposition||authorityEntry.appId!==input2.appId||authorityEntry.appInstanceId!==input2.appInstanceId||authorityEntry.routeEpoch!==authorityEpoch||hashServingRouteManifestEntry(authorityEntry)!==row.authority_entry_hash)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}catch{return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}}const failedOperationGeneration=row.failed_op_generation_ref??null;const failedOperationOwnsLive=failedOperationOwnsLiveGeneration({authorityGeneration:authorityEntry.static?.generationRef??null,failedOperationGeneration});const failedOperationLiveProven=failedOperationOwnsLive&&row.failed_op_release_attempt_id!==null&&await proveCommittedLiveStaticRelease(input2.db,{appId:input2.appId,releaseAttemptId:row.failed_op_release_attempt_id,servingRouteEnvironment:input2.servingRouteEnvironment},input2.deploymentId)!==null;const authorityGeneration=authorityEntry.static?.generationRef??null;const failedOperationOtherOwnerProven=row.failed_op_never_staged===true&&row.failed_op_release_attempt_id!==null&&authorityGeneration!==null&&authorityGeneration===(row.current_static_generation_ref??null)&&await proveOtherLiveReleaseOwnsGeneration(input2.db,{appId:input2.appId,servingRouteEnvironment:input2.servingRouteEnvironment,generation:authorityGeneration,failedDeploymentId:input2.deploymentId,failedReleaseAttemptId:row.failed_op_release_attempt_id});let incumbentServing=resolveIncumbentServing({pointer:row.current_static_deployment_id,deploymentId:input2.deploymentId,pointerCommitted:row.incumbent_committed,pointerProvenIncumbent:row.pointer_proven_incumbent===true,pointerUnexecuted:row.pointer_unexecuted===true,failedOperationLiveProven,failedOperationOtherOwnerProven,authorityGeneration,projectedGeneration:row.current_static_generation_ref??null,failedOperationGeneration,failedOperationExecutorState:row.failed_op_executor_state??null,probe:input2.probeFailedOperation===true});const blockingDeploymentId=Number(row.blocking_deployment_id);if(row.blocking_deployment_id!==null&&(!Number.isSafeInteger(blockingDeploymentId)||blockingDeploymentId<1)){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}const safeBlockingDeploymentId=Number.isSafeInteger(blockingDeploymentId)&&blockingDeploymentId>0?blockingDeploymentId:null;const activeOwnerKinds=[...safeBlockingDeploymentId?["deployment"]:[],...row.active_release?["release"]:[],...row.active_runtime_recovery?["runtime_recovery"]:[],...row.active_delete?["app_lifecycle"]:[]];if(row.current_static_deployment_id!==null&&row.current_static_deployment_id>input2.deploymentId&&incumbentServing!=="PRESERVED"){return UNKNOWN_STATIC_ROUTE_RETRY_READINESS}const recoveredDeploymentId=incumbentServing==="PRESERVED"&&row.current_static_deployment_id!==null&&row.current_static_deployment_id>input2.deploymentId?row.current_static_deployment_id:null;if(recoveredDeploymentId!==null)incumbentServing="UNKNOWN";if(recoveredDeploymentId===null&&incumbentServing==="UNKNOWN"){if(activeOwnerKinds.length===0)return UNKNOWN_STATIC_ROUTE_RETRY_READINESS;return{retryReady:false,reason:"ACTIVE_OWNER",activeOwnerKinds,blockingDeploymentId:safeBlockingDeploymentId,blockingReleaseAttemptId:row.active_release?row.active_release_attempt_id:null,blockingReleaseEnvironment:row.active_release?row.active_release_environment:null,recoveredDeploymentId:null,incumbentServing:"UNKNOWN"}}const retryAfterSeconds=Number(row.reservation_retry_after_seconds);const reservationRetryAfter=row.active_reservation&&row.reservation_unbounded===false&&typeof row.reservation_retry_after==="string"&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u.test(row.reservation_retry_after)&&Number.isFinite(retryAfterSeconds)?{at:row.reservation_retry_after,afterSeconds:Math.min(Math.ceil(PREPARE_COMMIT_ABANDONMENT_MS/1e3),Math.max(1,retryAfterSeconds))}:null;return{...reservationRetryAfter?{reservationRetryAfter}:{},retryReady:recoveredDeploymentId===null&&incumbentServing!=="CHANGED"&&!row.active_reservation&&!safeBlockingDeploymentId&&!row.active_release&&!row.active_runtime_recovery&&!row.active_delete,reason:recoveredDeploymentId!==null?"ALREADY_RECOVERED":row.active_reservation?"ACTIVE_ROUTE_RESERVATION":safeBlockingDeploymentId||row.active_release||row.active_runtime_recovery||row.active_delete?"ACTIVE_OWNER":incumbentServing==="CHANGED"?"SERVING_CHANGED":"READY",activeOwnerKinds,blockingDeploymentId:safeBlockingDeploymentId,blockingReleaseAttemptId:row.active_release?row.active_release_attempt_id:null,blockingReleaseEnvironment:row.active_release?row.active_release_environment:null,recoveredDeploymentId,incumbentServing}}function publicStaticIncumbentServing(readiness){return readiness.incumbentServing==="NONE_TO_PRESERVE"?"NOT_APPLICABLE":readiness.incumbentServing}function staticStaleServingProven(readiness){return readiness.incumbentServing==="PRESERVED"||readiness.incumbentServing==="NONE_TO_PRESERVE"}function settledStaticServingState(readiness){return readiness.incumbentServing==="NONE_TO_PRESERVE"?"NOT_APPLICABLE":"PRESERVED"}var UNKNOWN_STATIC_ROUTE_RETRY_READINESS,BLOCKED_ELIGIBLE_STATIC_FAILURES;var init_deployment_route_retry_readiness=__esm({"../platform/src/deployment-route-retry-readiness.ts"(){"use strict";init_serving_route_manifest_contract();init_app_delete_operation_store();init_app_serving_route_prepare_abandonment();init_app_release_unbound_attempt_lease();init_deployment_executor_store();init_postgres_execute_rows();init_deployment_live_static_release_proof();UNKNOWN_STATIC_ROUTE_RETRY_READINESS={retryReady:false,reason:"OBSERVATION_UNAVAILABLE",activeOwnerKinds:null,blockingDeploymentId:null,blockingReleaseAttemptId:null,blockingReleaseEnvironment:null,recoveredDeploymentId:null,incumbentServing:"UNKNOWN"};BLOCKED_ELIGIBLE_STATIC_FAILURES=[{stage:"route",code:"APP_SERVING_ROUTE_EPOCH_CONFLICT"},{stage:"controller",code:"PLATFORM_STALE_DEPLOYMENT_RECOVERED"}]}});function buildSettledStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;return{status:503,body:{error:fallbackDiagnostic.selfService.reason.summary,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:operation.environment==="static"?settledStaticServingState(input2.routeRetryReadiness):"PRESERVED",retryClass:"platform-action",userAction:"RETRY",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"RETRY",command:fallbackDiagnostic.newDeploymentCommand},diagnostic:fallbackDiagnostic}}}function buildChangedStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;const staleShape=input2.failureCode===STALE_DEPLOYMENT_RECOVERED_CODE2&&input2.failureStage==="controller";const epochShape=input2.failureCode===ROUTE_EPOCH_CONFLICT_CODE3&&input2.failureStage==="route";if(!fallbackDiagnostic||!(staleShape||epochShape)||input2.recoveryRequired||operation.environment!=="static"||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt?.phase!=="failed"||currentReceipt.code!==input2.failureCode||input2.routeRetryReadiness.incumbentServing!=="CHANGED"){return null}const statusCommand=`gencow deploy status --deployment ${operation.deploymentId}`;const error62="The deployment's content is live and serving changed to it, but its record is closed as failed. Check this operation's status before starting another deployment.";const retryCondition="Serving already changed to this deployment's live content and its record is terminal. Do not start or repeat a deployment for this operation; check its status, and start a new deployment only to change the app.";const reasonSummary="This deployment's content is live and serving changed to it, but Platform closed its record as failed. No retry is needed.";return{status:503,body:{error:error62,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:"CHANGED",retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:retryCondition,...epochShape?{retryReady:false,retryReadinessReason:input2.routeRetryReadiness.reason,statusCommand}:{},correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"VIEW_STATUS",command:statusCommand},diagnostic:{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:"VIEW_STATUS",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:retryCondition},action:{kind:"VIEW_STATUS",command:statusCommand},stateImpact:{...fallbackDiagnostic.selfService.stateImpact,incumbentServing:"CHANGED",operationState:"FAILED"},reason:{code:"deployment_content_live",summary:reasonSummary}}}}}}var STALE_DEPLOYMENT_RECOVERED_CODE2,ROUTE_EPOCH_CONFLICT_CODE3;var init_deployment_stale_changed_presentation=__esm({"../platform/src/deployment-stale-changed-presentation.ts"(){"use strict";init_deployment_route_retry_readiness();STALE_DEPLOYMENT_RECOVERED_CODE2="PLATFORM_STALE_DEPLOYMENT_RECOVERED";ROUTE_EPOCH_CONFLICT_CODE3="APP_SERVING_ROUTE_EPOCH_CONFLICT"}});function buildSupersededStaleDeploymentResponse(input2){const{operation,currentReceipt,fallbackDiagnostic}=input2;const superseded=currentReceipt?.warnings?.some(warning=>warning.code===SUPERSEDED_BY_NEWER_COMMIT_CODE2||warning.code===SUPERSEDED_SCHEMA_OUTCOME_CODE);if(!fallbackDiagnostic||!superseded||input2.failureCode!==STALE_DEPLOYMENT_RECOVERED_CODE3||input2.failureStage!=="controller"||input2.recoveryRequired||operation.status!=="failed"||operation.controlPlaneState!=="failed"||operation.executorState!=="failed"||currentReceipt?.phase!=="failed"||currentReceipt.code!==input2.failureCode){return null}const ambiguous=currentReceipt.databaseState==="RECOVERY_REQUIRED";const inspectCommand=operation.environment==="prod"?"gencow db:check --prod --inspect-state":"gencow db:check --inspect-state";const statusCommand=`gencow deploy status --deployment ${operation.deploymentId}`;const nextAction=ambiguous?{kind:"INSPECT_STATE",command:inspectCommand}:{kind:"VIEW_STATUS",command:statusCommand};const error62=ambiguous?"A newer deployment is serving this app, so this deployment was closed as failed. Its database outcome is uncertain: check the migration state before relying on the schema. New deployments are accepted.":"A newer deployment is serving this app, so this deployment was closed as failed. No retry is needed. New deployments are accepted.";const retryCondition=ambiguous?`Do not repeat this operation. Run "${inspectCommand}" to confirm the migration state, then start a new deployment only to change the app.`:"Do not repeat this operation. Check its status if needed; a new deployment is accepted to change the app.";return{status:409,body:{error:error62,code:input2.failureCode,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:input2.failureStage,databaseState:currentReceipt.databaseState,servingState:"PRESERVED",retryClass:"platform-action",userAction:ambiguous?"INSPECT_STATE":"VIEW_STATUS",retryPrecondition:retryCondition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction,diagnostic:{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:ambiguous?"INSPECT_STATE":"VIEW_STATUS",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:retryCondition},action:nextAction,stateImpact:{...fallbackDiagnostic.selfService.stateImpact,mutation:ambiguous?"UNKNOWN":currentReceipt.databaseState==="APPLIED"?"APPLIED":"NONE",incumbentServing:"PRESERVED",operationState:"FAILED"},reason:{code:ambiguous?"stale_superseded_schema_outcome":"stale_superseded_by_newer_commit",summary:error62}}}}}}var STALE_DEPLOYMENT_RECOVERED_CODE3,SUPERSEDED_BY_NEWER_COMMIT_CODE2;var init_deployment_stale_superseded_presentation=__esm({"../platform/src/deployment-stale-superseded-presentation.ts"(){"use strict";init_deployment_superseded_by_newer_commit();STALE_DEPLOYMENT_RECOVERED_CODE3="PLATFORM_STALE_DEPLOYMENT_RECOVERED";SUPERSEDED_BY_NEWER_COMMIT_CODE2="PLATFORM_STALE_SUPERSEDED_BY_NEWER_COMMIT"}});function succeededDeploymentBody(operation,url2){const base2={success:true,bundleHash:operation.bundleHash.slice(0,8),...url2===null?{}:{url:url2},deployId:operation.deploymentId,operationId:operation.deploymentId,correlationId:operation.correlationId,controlPlane:"v1",appName:operation.appName,state:"succeeded"};return operation.environment==="static"?{...base2,files:null,size:operation.staticSize}:base2}function buildSupersededSucceededDeploymentResponse(input2){const{operation,verifiedReceipt}=input2;if(operation.status!=="superseded"||operation.controlPlaneState!=="superseded"||!verifiedReceipt||!hasVerifiedDeploymentExecutorCompletion(operation)){return null}const url2=operation.environment==="static"?input2.getAppUrl(operation.appName,operation.appPort):input2.servingRouteBinding?input2.getAppUrl(operation.appName,input2.servingRouteBinding.port):null;return{status:200,body:{...succeededDeploymentBody(operation,url2),superseded:true,servingState:"PRESERVED",databaseState:verifiedReceipt.databaseState}}}var init_deployment_executor_http_succeeded=__esm({"../platform/src/deployment-executor-http-succeeded.ts"(){"use strict";init_deployment_executor_completion_contract()}});function deploymentStatusPath(deploymentId){return`/platform/deployments/${deploymentId}`}function pendingDeploymentBody(attempt,appName,executorState,executorAvailable=true,options={}){const state2=executorState==="queued"?"queued":"running";const executorUnavailable=executorAvailable===false;const executorObservationUnknown=executorAvailable===null;const databaseState=executorObservationUnknown?"UNKNOWN":options.databaseState??(executorState==="queued"?"UNCHANGED":"UNKNOWN");const servingState=executorObservationUnknown||databaseState==="APPLIED"?"UNKNOWN":options.servingState??"UNKNOWN";return{accepted:true,status:executorUnavailable?"queued_executor_unavailable":executorState,executorAvailable,...executorAvailable===true?{}:{code:options.diagnosticCode??"PLATFORM_DEPLOYMENT_EXECUTOR_UNAVAILABLE"},...executorAvailable===true?{}:{stage:"executor",capability:options.capability??"deployment_executor_process",retryClass:options.retryClass??"retryable-infra",userAction:"VIEW_STATUS",...executorObservationUnknown?{executorObservation:"unknown"}:{},retryPrecondition:options.retryPrecondition??"Wait for the target deployment executor process to recover before retrying.",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${attempt.deploymentId}`}},databaseState,servingState,operationId:attempt.deploymentId,deployId:attempt.deploymentId,correlationId:attempt.correlationId,appName,state:state2,...options.phase??{},pollUrl:deploymentStatusPath(attempt.deploymentId)}}var init_deployment_executor_http_pending=__esm({"../platform/src/deployment-executor-http-pending.ts"(){"use strict"}});async function resolveDeploymentStatusResponse(input2){const operation=await(input2.getStatusImpl??getOwnedDeploymentExecutorStatus)({db:input2.db,deploymentId:input2.deploymentId,userId:input2.user.id});if(!operation||input2.user.tokenType==="deploy"&&input2.user.appId!==operation.appId){return{status:404,body:{error:"Deployment operation not found"}}}const verifiedReceipt=readVerifiedDeploymentExecutorReceipt(operation);const currentReceipt=verifiedReceipt?.phase===operation.executorState?verifiedReceipt:null;const response=await resolveAuthorizedDeploymentStatusResponse(input2,operation,currentReceipt,verifiedReceipt);if(!currentReceipt?.warnings?.length)return response;return{...response,body:{...response.body,warnings:publicDeploymentExecutorWarnings(currentReceipt.warnings)}}}async function resolveAuthorizedDeploymentStatusResponse(input2,operation,currentReceipt,verifiedReceipt){const staleRecoveryNewDeploymentCommand=resolveStaleDeploymentNewDeploymentCommand({executionEnvironment:operation.environment,releaseEnvironment:operation.releaseEnvironment,releaseBindingPresent:operation.releaseAttemptId!=null});const backendServing=operation.environment==="static"?null:await observeBackendServing({db:input2.db,appId:operation.appId,correlationId:operation.correlationId,loadRouteBindingImpl:input2.loadRouteBindingImpl});const servingRouteBinding=backendServing?.kind==="SERVING"?backendServing.binding:null;const candidateCleanupServingState=operation.environment==="static"?"NOT_APPLICABLE":backendServingState(backendServing);let candidateCleanupDebt=null;let candidateCleanupDebtObservationUnavailable=false;if(currentReceipt?.code==="CANDIDATE_CLEANUP_PENDING"){try{if(input2.findCandidateCleanupDebtImpl){candidateCleanupDebt=await input2.findCandidateCleanupDebtImpl({db:input2.db,appId:operation.appId,env:operation.environment})}else if(input2.hasCandidateCleanupDebtImpl){candidateCleanupDebt=await input2.hasCandidateCleanupDebtImpl({db:input2.db,appId:operation.appId,env:operation.environment})?{deploymentId:operation.deploymentId}:null}else{candidateCleanupDebt=await findCandidateCleanupDebt({db:input2.db,appId:operation.appId,env:operation.environment})}}catch{candidateCleanupDebtObservationUnavailable=true}}const candidateCleanupPending=candidateCleanupDebt!==null;const candidateCleanupBlockingOperationId=candidateCleanupDebt?.deploymentId??operation.deploymentId;let candidateCleanupRecoveryObservation="not_required";if(candidateCleanupDebtObservationUnavailable){candidateCleanupRecoveryObservation="unavailable"}else if(candidateCleanupPending){try{candidateCleanupRecoveryObservation=await(input2.hasDurableCandidateCleanupRecoveryRequiredImpl??hasDurableCandidateCleanupRecoveryRequired)({db:input2.db,appId:operation.appId,deploymentId:candidateCleanupBlockingOperationId})?"required":"not_required"}catch{candidateCleanupRecoveryObservation="unavailable"}}if(candidateCleanupRecoveryObservation!=="not_required"){const recoveryUnavailable=candidateCleanupRecoveryObservation==="unavailable";return{status:503,body:{error:recoveryUnavailable?"Platform cleanup recovery state is temporarily unavailable":"Platform runtime cleanup requires isolated recovery",code:recoveryUnavailable?"PLATFORM_CANDIDATE_CLEANUP_RECOVERY_OBSERVATION_UNAVAILABLE":"PLATFORM_CANDIDATE_CLEANUP_RECOVERY_REQUIRED",deployId:operation.deploymentId,operationId:operation.deploymentId,...candidateCleanupBlockingOperationId===operation.deploymentId?{}:{blockingOperationId:candidateCleanupBlockingOperationId},stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:recoveryUnavailable?"Platform must restore cleanup recovery observation before another deployment can start.":"Platform must prove the previous candidate is absent before another deployment can start.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${candidateCleanupBlockingOperationId}`}}}}if(candidateCleanupPending){return{status:503,body:{error:"Candidate cleanup is still pending",code:currentReceipt.code,deployId:operation.deploymentId,operationId:operation.deploymentId,...candidateCleanupBlockingOperationId===operation.deploymentId?{}:{blockingOperationId:candidateCleanupBlockingOperationId},stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"retryable-infra",userAction:"WAIT",retryPrecondition:"Wait for exact candidate cleanup to finish before starting a new deployment.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${candidateCleanupBlockingOperationId}`}}}}if(currentReceipt?.code==="CANDIDATE_CLEANUP_PENDING"){return{status:503,body:{error:"Candidate cleanup completed; a new deployment may be started",code:"CANDIDATE_CLEANUP_SETTLED",deployId:operation.deploymentId,operationId:operation.deploymentId,stage:"candidate",databaseState:currentReceipt.databaseState,servingState:candidateCleanupServingState,retryClass:"retryable-infra",userAction:"RETRY",retryPrecondition:"Exact candidate cleanup is complete.",correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"RETRY",command:operation.environment==="prod"?"gencow deploy --prod":"gencow deploy"}}}}if(operation.status==="running"&&operation.controlPlaneState==="active"&&(operation.executorState==="not_queued"||hasVerifiedDeploymentExecutorCompletion(operation))){if(operation.environment==="static"){if(operation.currentStaticDeployId!==operation.deploymentId){return{status:409,body:{error:"Static deployment projection is incomplete",code:"STATIC_ROUTE_CONVERGENCE_PENDING",stage:"route",retryClass:"retryable-infra",userAction:"RETRY",correlationId:operation.correlationId,appName:operation.appName,state:"running",operationId:operation.deploymentId,deployId:operation.deploymentId,pollUrl:deploymentStatusPath(operation.deploymentId)}}}return{status:200,body:succeededDeploymentBody(operation,input2.getAppUrl(operation.appName,operation.appPort))}}const binding=servingRouteBinding;if(!binding){return{status:202,headers:{Location:deploymentStatusPath(operation.deploymentId),"Retry-After":"1"},body:pendingDeploymentBody({deploymentId:operation.deploymentId,appId:operation.appId,env:operation.environment,attemptId:"",correlationId:operation.correlationId,sourceBundleSha256:"",replayed:true,status:operation.status,controlPlaneState:operation.controlPlaneState,bundleHash:operation.bundleHash,artifactRef:null},operation.appName,operation.executorState,true)}}if(binding.deploymentId!==operation.deploymentId){return{status:409,body:{error:"Deployment route commit is incomplete",code:"ROUTE_CONVERGENCE_PENDING",stage:"route",retryClass:"retryable-infra",userAction:"RETRY",correlationId:operation.correlationId,appName:operation.appName,state:"running",operationId:operation.deploymentId,deployId:operation.deploymentId,pollUrl:deploymentStatusPath(operation.deploymentId)}}}return{status:200,body:succeededDeploymentBody(operation,input2.getAppUrl(operation.appName,binding.port))}}const supersededSucceeded=buildSupersededSucceededDeploymentResponse({operation,verifiedReceipt,servingRouteBinding,getAppUrl:input2.getAppUrl});if(supersededSucceeded)return supersededSucceeded;if(operation.status==="failed"||operation.executorState==="failed"||operation.executorState==="recovery_required"){const recoveryRequired=operation.executorState==="recovery_required";const failureCode2=operation.failureCode||resolvePlatformExecutorTerminalCode(recoveryRequired);const failureStage=operation.failureStage||"controller";const failurePolicy=resolveStoredDeploymentFailurePolicy(failureStage,failureCode2);const routeRetryReadiness=operation.environment==="static"&&isBlockedEligibleStaticFailure({stage:failureStage,code:failureCode2})&&currentReceipt?.phase==="failed"&&operation.appInstanceId===operation.executorAppInstanceId&&(operation.releaseEnvironment==="dev"||operation.releaseEnvironment==="prod")?await(input2.readStaticRouteRetryReadinessImpl??readStaticRouteRetryReadiness)({db:input2.db,appId:operation.appId,appInstanceId:operation.appInstanceId,releaseEnvironment:operation.releaseEnvironment,servingRouteEnvironment:input2.servingRouteEnvironment===void 0?appReleaseRuntimeConfig().servingRoute.environment:input2.servingRouteEnvironment,deploymentId:operation.deploymentId}).catch(()=>UNKNOWN_STATIC_ROUTE_RETRY_READINESS):UNKNOWN_STATIC_ROUTE_RETRY_READINESS;const fallbackDiagnostic=currentReceipt?buildPublicDeploymentExecutorDiagnostic({code:failureCode2||currentReceipt.code,stage:failureStage,recoveryRequired,receipt:currentReceipt,correlationId:operation.correlationId,operationId:String(operation.deploymentId),incumbentServing:operation.environment==="static"?publicStaticIncumbentServing(routeRetryReadiness):backendServingState(backendServing),environment:operation.environment,releaseEnvironment:operation.releaseEnvironment,releaseBindingPresent:operation.releaseAttemptId!=null,routeRetryReadiness}):null;if(recoveryRequired&&failureStage==="route"&&operation.environment!=="static"&&isCommittedRouteBlockedReceipt(currentReceipt)&&fallbackDiagnostic?.newDeploymentCommand!==void 0&&fallbackDiagnostic.newDeploymentCommand===staleRecoveryNewDeploymentCommand){return{status:503,body:{error:fallbackDiagnostic.selfService.reason.summary,code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,databaseState:currentReceipt.databaseState,servingState:backendServingState(backendServing),retryClass:"platform-action",userAction:"RETRY",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"blocked",nextAction:{kind:"RETRY",command:fallbackDiagnostic.newDeploymentCommand},diagnostic:fallbackDiagnostic}}}if(operation.status==="superseded"&&operation.environment!=="static"&&isSupersededByNewerCommitReceipt(currentReceipt)&&fallbackDiagnostic){return{status:409,body:{error:fallbackDiagnostic.selfService.reason.summary,code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,databaseState:currentReceipt.databaseState,servingState:"PRESERVED",retryClass:"platform-action",userAction:"VIEW_STATUS",retryPrecondition:fallbackDiagnostic.selfService.retry.condition,correlationId:operation.correlationId,appName:operation.appName,state:"failed",nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`},diagnostic:fallbackDiagnostic}}}const superseded=buildSupersededStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,failureCode:failureCode2,failureStage,recoveryRequired});if(superseded)return superseded;const crashedRetired=buildCrashedStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,failureCode:failureCode2,failureStage,recoveryRequired});if(crashedRetired)return crashedRetired;const settledStaleDeployment=failureCode2==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&failureStage==="controller"&&operation.status==="failed"&&operation.controlPlaneState==="failed"&&operation.executorState==="failed"&&currentReceipt?.phase==="failed"&&currentReceipt.code==="PLATFORM_STALE_DEPLOYMENT_RECOVERED"&&!recoveryRequired&&(operation.environment==="static"?staticStaleServingProven(routeRetryReadiness):Boolean(servingRouteBinding))&&fallbackDiagnostic?.retryability==="NEW_DEPLOYMENT_AFTER_STATUS"&&staleRecoveryNewDeploymentCommand!==null&&fallbackDiagnostic.newDeploymentCommand===staleRecoveryNewDeploymentCommand;if(settledStaleDeployment){return buildSettledStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,routeRetryReadiness,failureStage,failureCode:failureCode2})}const changedStale=buildChangedStaleDeploymentResponse({operation,currentReceipt,fallbackDiagnostic,routeRetryReadiness,failureCode:failureCode2,failureStage,recoveryRequired});if(changedStale)return changedStale;const unverifiedStaleDeployment=failureCode2==="PLATFORM_STALE_DEPLOYMENT_RECOVERED";const diagnostic=unverifiedStaleDeployment&&fallbackDiagnostic?{...fallbackDiagnostic,newDeploymentCommand:void 0,failureClass:"PLATFORM_ACTION_REQUIRED",retryability:"AFTER_STATUS",action:"VIEW_STATUS",observedState:"BLOCKED",selfService:{...fallbackDiagnostic.selfService,responsibility:"PLATFORM_ACTION_REQUIRED",retry:{allowedNow:false,policy:"AFTER_STATUS",condition:"Platform has not verified the terminal recovery receipt and preserved serving state. Do not start another deployment until status confirms recovery and app admission is open."},action:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`},stateImpact:{...fallbackDiagnostic.selfService.stateImpact,incumbentServing:backendServingState(backendServing),operationState:"BLOCKED"},reason:{code:"stale_deployment_recovery_unverified",summary:"Platform has not verified the terminal recovery receipt and preserved serving deployment. Check this operation before starting another deployment."}}}:fallbackDiagnostic;const rootCauseClass=publicRoutePrepareRootCauseClass({stage:failureStage,code:failureCode2,stored:currentReceipt?.rootCauseClass});const routeTargetRejections=publicRouteTargetRejections({stage:failureStage,code:failureCode2,stored:currentReceipt?.routeTargetRejections});const userAction=unverifiedStaleDeployment?"VIEW_STATUS":((routeRetryReadiness.retryReady||routeRetryReadiness.reason==="ALREADY_RECOVERED")&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?fallbackDiagnostic?.action:currentReceipt?.diagnostic?.nextAction.kind)??fallbackDiagnostic?.action??resolvePublicSelfServiceAction({code:failureCode2,stage:failureStage,requestedAction:recoveryRequired?"OPERATOR_ACTION":failurePolicy.userAction,operationId:String(operation.deploymentId)});const retryClass=unverifiedStaleDeployment?"platform-action":currentReceipt?.diagnostic?.failureClass==="USER_FIXABLE"?"terminal-client":currentReceipt?.diagnostic?.failureClass==="RETRYABLE_INFRA"?"retryable-infra":routeRetryReadiness.retryReady&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?"retryable-infra":recoveryRequired?"platform-action":failurePolicy.retryClass;return{status:recoveryRequired||unverifiedStaleDeployment?503:failurePolicy.status,body:{error:unverifiedStaleDeployment?"Platform has not verified stale deployment recovery. Check this operation before starting another deployment.":(failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"&&(routeRetryReadiness.reason==="READY"||routeRetryReadiness.reason==="ALREADY_RECOVERED")?fallbackDiagnostic?.selfService.reason.summary:currentReceipt?.diagnostic?.reason.summary)??(recoveryRequired?"Deployment state inspection is required":failurePolicy.error),code:failureCode2,deployId:operation.deploymentId,operationId:operation.deploymentId,stage:failureStage,retryClass,userAction,correlationId:operation.correlationId,appName:operation.appName,state:recoveryRequired||unverifiedStaleDeployment?"blocked":"failed",...unverifiedStaleDeployment?{nextAction:{kind:"VIEW_STATUS",command:`gencow deploy status --deployment ${operation.deploymentId}`}}:{},...operation.environment==="static"&&failureCode2==="APP_SERVING_ROUTE_EPOCH_CONFLICT"?{retryReady:routeRetryReadiness.retryReady,retryReadinessReason:routeRetryReadiness.reason,activeOwnerKinds:routeRetryReadiness.activeOwnerKinds??null,statusCommand:`gencow deploy status --deployment ${operation.deploymentId}`,...routeRetryReadiness.blockingDeploymentId?{blockingOperationId:routeRetryReadiness.blockingDeploymentId}:{},...routeRetryReadiness.blockingReleaseAttemptId&&routeRetryReadiness.blockingReleaseEnvironment?{blockingReleaseAttemptId:routeRetryReadiness.blockingReleaseAttemptId,blockingReleaseEnvironment:routeRetryReadiness.blockingReleaseEnvironment}:{},...routeRetryReadiness.recoveredDeploymentId?{recoveredOperationId:routeRetryReadiness.recoveredDeploymentId}:{}}:{},...rootCauseClass?{rootCauseClass}:{},...routeTargetRejections?{routeTargetRejections}:{},...buildPublicFailureChain({primaryCode:failureCode2,primaryStage:failureStage,correlationId:operation.correlationId}),...diagnostic?{diagnostic}:{}}}}const routeOnlyResume=operation.environment!=="static"&&operation.status==="pending"&&operation.executorState==="reconciling"&&isRouteOnlyResumeReceipt(verifiedReceipt);const observation=routeOnlyResume?{targetGenerationBound:true,executorAvailable:true,probeFailed:false}:await observeDeploymentExecutorProcess({db:input2.db,nodeId:operation.targetNodeId,slotId:operation.targetSlotId,revision:operation.targetRevision,ownerId:operation.targetOwnerId,generationDigest:operation.targetGenerationDigest,probeImpl:input2.hasReadyExecutorProcessImpl});const{targetGenerationBound,executorAvailable,probeFailed:executorProbeFailed}=observation;const diagnosticCode=targetGenerationBound?executorProbeFailed?"PLATFORM_DEPLOYMENT_EXECUTOR_STATUS_UNAVAILABLE":void 0:"DEPLOYMENT_EXECUTOR_GENERATION_UNAVAILABLE";return{status:202,headers:{Location:deploymentStatusPath(operation.deploymentId),"Retry-After":"1"},body:pendingDeploymentBody({deploymentId:operation.deploymentId,appId:operation.appId,env:operation.environment,attemptId:"",correlationId:operation.correlationId,sourceBundleSha256:"",replayed:true,status:operation.status,controlPlaneState:operation.controlPlaneState,bundleHash:operation.bundleHash,artifactRef:null},operation.appName,operation.executorState,executorAvailable,{phase:resolvePendingDeploymentPhase({executorState:operation.executorState,environment:operation.environment,receipt:verifiedReceipt,queuedAt:operation.queuedAt}),databaseState:verifiedReceipt?.databaseState,servingState:operation.environment==="static"?operation.currentStaticDeployId!==null&&operation.currentStaticDeployId!==operation.deploymentId?"PRESERVED":"UNKNOWN":backendServingState(backendServing),capability:targetGenerationBound?"deployment_executor_process":"deployment_executor_generation_fence",diagnosticCode,retryClass:targetGenerationBound&&!executorProbeFailed?"retryable-infra":"platform-action",retryPrecondition:!targetGenerationBound?"Wait for Platform to restore the exact executor generation before retrying.":executorProbeFailed?"Wait for Platform status observation to recover, then check this operation again.":void 0})}}async function presentDeploymentStatus(input2){const response=await resolveDeploymentStatusResponse(input2);for(const[name,value2]of Object.entries(response.headers??{}))input2.c.header(name,value2);return input2.c.json(response.body,response.status)}var init_deployment_executor_http_presentation=__esm({"../platform/src/deployment-executor-http-presentation.ts"(){"use strict";init_deployment_executor_warning_receipt();init_deployment_executor_store();init_deployment_executor_pending_phase();init_deployment_executor_process_observation();init_deployment_backend_incumbent_serving();init_deployment_executor_public_diagnostic();init_deployment_failure_public_diagnostic();init_deployment_failure_contract();init_app_serving_route_target_rejection();init_deployment_route_prepare_root_cause();init_deployment_request_admission();init_deployment_executor_completion_contract();init_deployment_committed_route_contract();init_runtime_exact_cleanup_operation_store();init_public_self_service_diagnostic();init_app_release_runtime_env();init_deployment_stale_changed_presentation();init_deployment_stale_superseded_presentation();init_deployment_executor_http_succeeded();init_deployment_stale_crashed_presentation();init_deployment_route_retry_readiness();init_deployment_executor_http_pending();init_deployment_executor_http_pending();init_deployment_executor_completion_contract()}});import{createHash as createHash69}from"node:crypto";import{and as and31,desc as desc7,eq as eq34,gt as gt7,sql as sql112}from"drizzle-orm";async function getOwnedDeploymentFailureReceipt(db,ownerId,correlationId,now=new Date){if(!CORRELATION_PATTERN.test(correlationId))return null;const rows8=await db.select().from(deploymentFailureReceipts).where(and31(eq34(deploymentFailureReceipts.ownerId,ownerId),eq34(deploymentFailureReceipts.correlationId,correlationId),gt7(deploymentFailureReceipts.retainUntil,now))).limit(1);return rows8[0]??null}async function getLatestAppDeploymentFailureReceiptForOperator(db,appId,appInstanceId,now=new Date){const rows8=await db.select().from(deploymentFailureReceipts).where(and31(eq34(deploymentFailureReceipts.appId,appId),eq34(deploymentFailureReceipts.appInstanceId,appInstanceId),gt7(deploymentFailureReceipts.retainUntil,now))).orderBy(desc7(deploymentFailureReceipts.createdAt)).limit(1);return rows8[0]??null}var CORRELATION_PATTERN,DEFAULT_RETENTION_MS,DEFAULT_GC_GRACE_MS;var init_deployment_failure_receipt_store=__esm({"../platform/src/deployment-failure-receipt-store.ts"(){"use strict";init_schema();init_candidate_failure_provenance();CORRELATION_PATTERN=/^[A-Za-z0-9_-]{8,128}$/u;DEFAULT_RETENTION_MS=30*24*60*6e4;DEFAULT_GC_GRACE_MS=24*60*6e4}});function hasDeployOperationPollingCapability(value2){if(!value2||value2.length>1024)return false;return value2.split(",").map(capability2=>capability2.trim()).filter(capability2=>CAPABILITY_PATTERN2.test(capability2)).includes(DEPLOY_OPERATION_POLL_CAPABILITY)}function hasDeployOperationPollingProtocol(input2){return input2.deployProtocol?.trim()==="1"||hasDeployOperationPollingCapability(input2.capabilities)}function deployOperationCapabilityUpgradeBody(){return{error:"This CLI cannot wait for an asynchronous deployment result",code:"DEPLOY_CLI_UPGRADE_REQUIRED",stage:"admission",retryClass:"terminal-client",userAction:"UPDATE_CLI",requiredCapability:DEPLOY_OPERATION_POLL_CAPABILITY}}var DEPLOY_OPERATION_POLL_CAPABILITY,CAPABILITY_PATTERN2;var init_deploy_operation_capability=__esm({"../platform/src/deploy-operation-capability.ts"(){"use strict";DEPLOY_OPERATION_POLL_CAPABILITY="deploy-operation-poll-v1";CAPABILITY_PATTERN2=/^[a-z0-9][a-z0-9-]{0,63}$/u}});import{eq as eq35}from"drizzle-orm";import{randomUUID as randomUUID46}from"node:crypto";function registerPlatformApiDeployRoutes({app:app2,getDb:getDb3,withOwnerTransaction,getUser,getAppUrl,currentNodeId,currentSlotId=(process.env.GENCOW_PLATFORM_SLOT||"active").trim().toLowerCase(),currentRevision=resolveDeploymentExecutorRevision(),executorSpoolRoot:executorSpoolRoot2,acquireAdmissionLock:acquireAdmissionLock2,maxQueuedOperations,maxQueuedBytes,busyRetryTimeoutMs,logger:logger3=console}){const deployApp=async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);const{name}=c.req.param();const db=getDb3();const appRows=await db.select().from(apps).where(eq35(apps.name,name));if(appRows.length===0||appRows[0].userId!==user2.id){return c.json({error:"App not found"},404)}const appRow=appRows[0];const holdResponse=buildAppAccountHoldResponse(appRow);if(holdResponse)return c.json(holdResponse.body,holdResponse.status);const environment=c.req.query("env")||"dev";if(environment!=="dev"&&environment!=="prod"){return c.json({error:"Invalid deployment environment"},400)}let bundleBuffer;const contentType=c.req.header("Content-Type")||"";if(contentType.includes("multipart")){const form=await c.req.formData();const file2=form.get("bundle");if(!file2)return c.json({error:"bundle field missing"},400);bundleBuffer=Buffer.from(await file2.arrayBuffer())}else{bundleBuffer=Buffer.from(await c.req.arrayBuffer())}const supportsOperationPolling=hasDeployOperationPollingProtocol({capabilities:c.req.header("X-Gencow-CLI-Capabilities"),deployProtocol:c.req.header("X-Gencow-Deploy-Protocol")});if(!supportsOperationPolling){return c.json(deployOperationCapabilityUpgradeBody(),426)}const proxied=await maybeProxyAppHomeNodeResponse({app:appRow,db,req:{raw:c.req.raw,method:"POST"},pathSuffix:"/deploy",query:{env:environment},body:Uint8Array.from(bundleBuffer),logger:logger3});if(proxied){if(proxied instanceof Response)return proxied;return c.json(proxied.body??{},proxied.status??502)}let attempt=null;let protocolHeaders=deploymentProtocolResponseHeaders(c.req.header("X-Gencow-Deploy-Claim")?"v1-enforce":"legacy-observe");const applyProtocolHeaders=()=>{for(const[header,value2]of Object.entries(protocolHeaders))c.header(header,value2)};try{const admission=await admitDeploymentExecutorRequestAfterActiveOperation({db,withOwnerTransaction,app:appRow,userId:user2.id,environment,bundle:bundleBuffer,getHeader:header=>c.req.header(header)||"",currentNodeId,currentSlotId,currentRevision,spoolRoot:executorSpoolRoot2,acquireAdmissionLock:acquireAdmissionLock2,maxQueuedOperations,maxQueuedBytes},{timeoutMs:busyRetryTimeoutMs});protocolHeaders=admission.protocolHeaders;applyProtocolHeaders();const committedAttempt=admission.attempt;attempt=committedAttempt;if(admission.replayed){return presentDeploymentStatus({c,db,user:user2,deploymentId:committedAttempt.deploymentId,getAppUrl})}c.header("Location",deploymentStatusPath(committedAttempt.deploymentId));c.header("Retry-After","1");return c.json(pendingDeploymentBody(committedAttempt,name,"queued",admission.executorAvailable),202)}catch(error62){applyProtocolHeaders();logger3.warn("[deployment-api] admission or enqueue failed",{code:error62 instanceof Error?error62.message:"UNKNOWN",deploymentId:attempt?.deploymentId,...error62 instanceof DeploymentExecutorAdmissionError&&error62.requestId?{requestId:error62.requestId,correlationId:error62.requestId}:{}});const failure2=buildDeployFailureResponse(error62,[],{stage:"admission",correlationId:attempt?.correlationId,cliVersion:c.req.header("X-Gencow-CLI-Version")||void 0,blockingOperation:await resolveAppBusyBlockingOperation({db,appId:appRow.id,error:error62,warn:()=>logger3.warn("[deployment-api] active operation diagnostic read unavailable")})});if(error62 instanceof DeploymentExecutorAdmissionError&&!isAppBusyAdmissionError(error62)){if(error62.httpStatus===429||error62.httpStatus===503){c.header("Retry-After","5")}const confirmedAbsentOutcome=error62.code==="DEPLOYMENT_EXECUTOR_ADMISSION_OUTCOME_UNKNOWN"&&error62.requestId!==void 0&&/^[A-Za-z0-9_-]{16,128}$/u.test(error62.requestId);const reconciliationUnavailable=error62.code==="DEPLOYMENT_EXECUTOR_ADMISSION_RECONCILIATION_UNAVAILABLE"&&error62.requestId!==void 0&&/^[A-Za-z0-9_-]{16,128}$/u.test(error62.requestId);const hasAdmissionRequestIdentity=confirmedAbsentOutcome||reconciliationUnavailable;const correlationId=hasAdmissionRequestIdentity?error62.requestId:void 0;const queuedOperationId=error62.code==="DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL"&&Number.isSafeInteger(error62.blockingOperationId)&&error62.blockingOperationId>0?error62.blockingOperationId:void 0;const queueDiagnostic=error62.code==="DEPLOYMENT_EXECUTOR_USER_QUEUE_FULL"?buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId:`deploy-queue-${randomUUID46()}`,appName:name,...queuedOperationId===void 0?{}:{operationId:String(queuedOperationId)},databaseState:"UNCHANGED",requestedAction:queuedOperationId===void 0?"WAIT":"VIEW_STATUS",retryAfterSeconds:5,reasonCode:"account_queue_capacity_exhausted",reasonSummary:"This deployment was not started because the account's queued deployment capacity is full. Check the existing operation before retrying.",incumbentServing:"PRESERVED",operationState:"BLOCKED"}):void 0;const queueAction=queueDiagnostic?{...queueDiagnostic,action:{...queueDiagnostic.action,command:queuedOperationId===void 0?`gencow deploy status --app ${name}${environment==="prod"?" --prod":""}`:`gencow deploy status --deployment ${queuedOperationId}`}}:void 0;const selfService=hasAdmissionRequestIdentity&&correlationId?buildPublicSelfServiceDiagnostic({code:error62.code,stage:"admission",correlationId,requestId:error62.requestId,appName:name,...confirmedAbsentOutcome?{resumeEnvironment:environment,admissionOutcomeConfirmedAbsent:true,databaseState:"UNCHANGED",requestedAction:"RETRY",reasonCode:"admission_transaction_rolled_back",reasonSummary:"The original deployment claim was not committed; replay the same saved claim.",incumbentServing:"PRESERVED"}:{resumeEnvironment:environment,databaseState:"RECOVERY_REQUIRED",requestedAction:"VIEW_STATUS",reasonCode:"admission_reconciliation_unavailable",reasonSummary:"The server could not verify whether this deployment request committed.",incumbentServing:"UNKNOWN"},operationState:"BLOCKED"}):void 0;return c.json({error:deploymentExecutorAdmissionPublicMessage(error62.code),code:error62.code,stage:"admission",retryClass:reconciliationUnavailable?"platform-action":"retryable-infra",userAction:queueAction?queueAction.action.kind:reconciliationUnavailable?"VIEW_STATUS":"RETRY",...queueAction?{correlationId:queueAction.correlationId,...queuedOperationId===void 0?{}:{blockingOperationId:queuedOperationId},databaseState:"UNCHANGED",activeDeploymentState:"PRESERVED",diagnostic:{selfService:queueAction},retryPrecondition:queueAction.retry.condition,nextAction:{kind:queueAction.action.kind,command:queueAction.action.command}}:{},...hasAdmissionRequestIdentity?{requestId:error62.requestId,appName:name,environment,correlationId,databaseState:confirmedAbsentOutcome?"UNCHANGED":"UNKNOWN",activeDeploymentState:confirmedAbsentOutcome?"PRESERVED":"UNKNOWN",diagnostic:{selfService}}:{}},error62.httpStatus)}return c.json(failure2.body,failure2.status)}};app2.post("/api/apps/:name/deploy",deployApp);app2.post("/platform/apps/:name/deploy",deployApp);app2.get("/platform/deployments/:deploymentId",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);const deploymentId=Number(c.req.param("deploymentId"));if(!Number.isSafeInteger(deploymentId)||deploymentId<=0){return c.json({error:"Invalid deployment operation"},400)}return presentDeploymentStatus({c,db:getDb3(),user:user2,deploymentId,getAppUrl})});app2.get("/platform/deployment-executor/status",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);return c.json({available:await hasReadyDeploymentExecutor({db:getDb3(),nodeId:currentNodeId,slotId:currentSlotId,revision:currentRevision}).catch(()=>false)})});app2.get("/platform/deployment-failures/:correlationId",async c=>{const user2=await getUser(c);if(!user2)return c.json({error:"Unauthorized"},401);let receipt;try{receipt=await getOwnedDeploymentFailureReceipt(getDb3(),user2.id,c.req.param("correlationId"))}catch{return c.json({error:"Deployment failure diagnostic is temporarily unavailable",code:"DEPLOYMENT_FAILURE_DIAGNOSTIC_UNAVAILABLE"},503)}if(!receipt||user2.tokenType==="deploy"&&user2.appId!==receipt.appId){return c.json({error:"Deployment failure diagnostic not found"},404)}const refreshedPolicy=resolvePersistedDeploymentFailurePolicyRefresh(receipt.publicStage,receipt.publicCode);return c.json({success:true,correlationId:receipt.correlationId,attemptId:receipt.deploymentAttemptId,stage:receipt.publicStage,code:receipt.publicCode,retryClass:refreshedPolicy?.retryClass??receipt.retryClass,userAction:refreshedPolicy?.userAction??receipt.requiredAction,failurePhase:receipt.failurePhase,candidateProcessStarted:receipt.processSpawned,candidateLogAvailable:receipt.candidateLogAvailable,databaseState:receipt.databaseState,evidenceSource:receipt.evidenceSource,createdAt:receipt.createdAt})})}var init_platform_api_deploy_route=__esm({"../platform/src/platform-api-deploy-route.ts"(){"use strict";init_schema();init_apps_account_hold();init_apps_home_node_proxy();init_apps_deploy_failures();init_deployment_request_admission();init_deployment_executor_store();init_public_self_service_diagnostic();init_deployment_executor_generation();init_deployment_executor_worker_store();init_deployment_executor_http_presentation();init_deployment_executor_admission();init_deployment_failure_receipt_store();init_deployment_failure_contract();init_deploy_operation_capability()}});function controlPlaneSchemaUnavailableResponse(c,error62,options={}){const unavailable3=options.acceptUndefinedTable?asControlPlaneSchemaUnavailableError(error62):isControlPlaneSchemaUnavailableError(error62);if(!unavailable3)return null;return c.json({error:"Platform control-plane schema is unavailable",code:CONTROL_PLANE_SCHEMA_UNAVAILABLE,retryClass:"platform-action",userAction:"OPERATOR_ACTION"},503)}var init_platform_api_schema_unavailable_response=__esm({"../platform/src/platform-api-schema-unavailable-response.ts"(){"use strict";init_deployment_control_plane_rollout()}});import{and as and32,eq as eq36,like as like3,or as or12}from"drizzle-orm";async function nextPlatformWakeCorrelation(input2){const rows8=await input2.db.select({correlationId:runtimeLifecycleRequests.correlationId,state:runtimeLifecycleRequests.state}).from(runtimeLifecycleRequests).where(and32(eq36(runtimeLifecycleRequests.appId,input2.appId),eq36(runtimeLifecycleRequests.action,"converge"),or12(eq36(runtimeLifecycleRequests.correlationId,input2.baseCorrelationId),like3(runtimeLifecycleRequests.correlationId,`${input2.baseCorrelationId}${CYCLE_SEPARATOR}%`))));let latest={cycle:-1,state:""};for(const row of rows8){const suffix=row.correlationId.slice(input2.baseCorrelationId.length+CYCLE_SEPARATOR.length);const cycle2=row.correlationId===input2.baseCorrelationId?0:Number(suffix);if(Number.isSafeInteger(cycle2)&&cycle2>latest.cycle)latest={cycle:cycle2,state:row.state}}if(latest.cycle<0)return input2.baseCorrelationId;const cycle=latest.state==="completed"?latest.cycle+1:latest.cycle;return cycle===0?input2.baseCorrelationId:`${input2.baseCorrelationId}${CYCLE_SEPARATOR}${cycle}`}var CYCLE_SEPARATOR;var init_runtime_wake_cycle_correlation=__esm({"../platform/src/runtime-wake-cycle-correlation.ts"(){"use strict";init_schema();CYCLE_SEPARATOR=":cycle-"}});import{and as and33,eq as eq37}from"drizzle-orm";function isRetryableBootDbStatusReason(value2){return typeof value2==="string"&&BOOT_DB_FAILURE_REASONS.has(value2)}function buildClassification(statusReason){return{kind:"boot_db_failure",phase:"settings_db_env",retryable:true,status:"failed",statusReason,statusMessage:APP_BOOT_DB_STATUS_MESSAGE}}function parseMarkerReason(text33){const markerMatch=text33.match(new RegExp(`${BOOT_FAILURE_MARKER}\\b[^\\n]*\\breason=(boot_db_[a-z_]+)`));const reason=markerMatch?.[1];return isRetryableBootDbStatusReason(reason)?reason:null}function classifyLegacySettingsDbTrace(text33){const lower=text33.toLowerCase();const hasRuntimePostgresFailure=lower.includes("runtimepostgresclienterror")||lower.includes("postgres client");if(!hasRuntimePostgresFailure)return null;const isSettingsBootPath=lower.includes("_system_settings")||lower.includes("loaddbenvvars")||lower.includes("settings-db-env")||lower.includes("settings.ts");if(!isSettingsBootPath)return null;if(lower.includes("operation_timeout")||lower.includes("operation timeout")){return"boot_db_operation_timeout"}if(lower.includes("generation_changed")||lower.includes("generation changed")){return"boot_db_generation_changed"}if(lower.includes("socket_closed")||lower.includes("socket closed")){return"boot_db_socket_closed"}if(lower.includes("connection_closed")||lower.includes("connection closed")||lower.includes("client is closed")||lower.includes("closed unexpectedly")){return"boot_db_connection_closed"}if(lower.includes("connection_timeout")||lower.includes("connection timeout")||lower.includes("connect timeout")||lower.includes("connection timed out")){return APP_BOOT_DB_CONNECTION_TIMEOUT_REASON}return null}function classifyRuntimeBootFailureFromExitEvent(event){const text33=(event?.stderrTail??[]).join("\n");if(!text33)return null;if(/AUTH_SCHEMA_CONTRACT_INVALID:[^\n]*Expected exactly one (?:legacy|project) Auth schema entry, received [2-9]\d*/u.test(text33)){return{kind:"auth_schema_failure",phase:"auth_schema_contract",retryable:false,status:"failed",statusReason:"auth_schema_provenance_ambiguous",statusMessage:"Auth schema \uC18C\uC2A4\uAC00 \uC911\uBCF5\uB418\uC5B4 \uC2E4\uD589\uC744 \uC911\uB2E8\uD588\uC2B5\uB2C8\uB2E4. \uC911\uBCF5 \uD30C\uC77C\uC744 \uC815\uB9AC\uD55C \uB4A4 \uC7AC\uBC30\uD3EC\uD558\uC138\uC694."}}const markerReason=parseMarkerReason(text33);if(markerReason)return buildClassification(markerReason);const legacyReason=classifyLegacySettingsDbTrace(text33);return legacyReason?buildClassification(legacyReason):null}var APP_BOOT_DB_CONNECTION_TIMEOUT_REASON,APP_BOOT_DB_STATUS_MESSAGE,BOOT_FAILURE_MARKER,RETRYABLE_APP_BOOT_DB_FAILURE_REASONS,BOOT_DB_FAILURE_REASONS;var init_app_boot_failure_policy=__esm({"../platform/src/app-boot-failure-policy.ts"(){"use strict";init_schema();init_app_runtime_event_scope();init_app_status_projector();init_stable_error_code();APP_BOOT_DB_CONNECTION_TIMEOUT_REASON="boot_db_connection_timeout";APP_BOOT_DB_STATUS_MESSAGE="\uC571 \uBD80\uD305 \uC911 \uC124\uC815 DB \uC5F0\uACB0\uC774 \uC77C\uC2DC\uC801\uC73C\uB85C \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4. \uC790\uB3D9 \uBCF5\uAD6C \uB300\uC0C1\uC785\uB2C8\uB2E4.";BOOT_FAILURE_MARKER="GENCOW_RUNTIME_BOOT_FAILURE";RETRYABLE_APP_BOOT_DB_FAILURE_REASONS=["boot_db_connection_closed",APP_BOOT_DB_CONNECTION_TIMEOUT_REASON,"boot_db_generation_changed","boot_db_operation_timeout","boot_db_socket_closed"];BOOT_DB_FAILURE_REASONS=new Set(RETRYABLE_APP_BOOT_DB_FAILURE_REASONS)}});function classifyWakeConvergenceFailure(input2){const typedCode=PUBLIC_WAKE_TYPED_FAILURE_CODE.test(input2.failureCode)?input2.failureCode:void 0;const retryable=typedCode!==void 0&&WAKE_RETRYABLE_CONVERGENCE_CODES.has(typedCode)||isTransientConnectionError(input2.error);return{...typedCode?{lastFailureCode:typedCode}:{},retryable,...retryable?{retryAfterSec:WAKE_TRANSIENT_RETRY_AFTER_SEC,retryCondition:`Retry the wake after ${WAKE_TRANSIENT_RETRY_AFTER_SEC} seconds; no app state changed. Check gencow app status ${input2.appName} before repeating the request.`}:{}}}function typedWakeConvergenceFailureFields(input2){if(input2.reasonCode===MIGRATION_FORWARD_REQUIRED_REASON)return{retryable:false};const classification2=classifyWakeConvergenceFailure({appName:input2.appName,failureCode:input2.failureCode,error:input2.error});return{...classification2.retryable?{hint:`\uC7A0\uC2DC \uD6C4 \uC571 \uC0C1\uD0DC\uB97C \uD655\uC778\uD55C \uB4A4 \uB2E4\uC2DC \uC2DC\uB3C4\uD558\uC138\uC694: gencow app status ${input2.appName}.`}:{},stage:"runtime_wake_convergence",stateChanged:false,nextAction:`gencow app status ${input2.appName}`,...classification2}}var PUBLIC_WAKE_TYPED_FAILURE_CODE,WAKE_RETRYABLE_CONVERGENCE_CODES,WAKE_TRANSIENT_RETRY_AFTER_SEC,MIGRATION_FORWARD_REQUIRED_REASON;var init_wake_convergence_failure=__esm({"../platform/src/simple-lifecycle/wake-convergence-failure.ts"(){"use strict";init_transient_connection_error();PUBLIC_WAKE_TYPED_FAILURE_CODE=/^[A-Z][A-Z0-9_]{2,99}$/u;WAKE_RETRYABLE_CONVERGENCE_CODES=new Set(["RUNTIME_CONVERGENCE_OPERATION_MISSING"]);WAKE_TRANSIENT_RETRY_AFTER_SEC=5;MIGRATION_FORWARD_REQUIRED_REASON="runtime_migration_forward_required"}});import postgres from"postgres";import{sql as sql113}from"drizzle-orm";async function notifyRuntimeConvergenceWake(db){await db.execute(sql113`SELECT pg_notify(${RUNTIME_CONVERGENCE_WAKE_CHANNEL}, ${RUNTIME_CONVERGENCE_WAKE_PAYLOAD})`)}var RUNTIME_CONVERGENCE_WAKE_CHANNEL,RUNTIME_CONVERGENCE_WAKE_PAYLOAD;var init_runtime_convergence_wake_signal=__esm({"../platform/src/runtime-convergence-wake-signal.ts"(){"use strict";RUNTIME_CONVERGENCE_WAKE_CHANNEL="gencow_runtime_convergence_v1";RUNTIME_CONVERGENCE_WAKE_PAYLOAD="runtime-convergence-v1"}});function resolveRuntimeOwner(input2){return resolveRuntimeLane(input2)}function isCanonicalDeploymentAbsent(canonicalDeploymentPresent){return isCanonicalClaimAbsent(canonicalDeploymentPresent)}var init_runtime_owner_resolution=__esm({"../platform/src/runtime-owner-resolution.ts"(){"use strict";init_runtime_lane()}});function isPublicRuntimeConvergencePendingReason(value2){return typeof value2==="string"&&PUBLIC_REASON.test(value2)}function runtimeConvergencePendingClass(reason){if(ARTIFACT_UNAVAILABLE.has(reason))return"artifact_unavailable";if(OWNERSHIP.has(reason))return"ownership_conflict";if(OBSERVING.has(reason))return"observing";return"applying"}function runtimeConvergencePendingGuidance(reason,appName){const status=appName?`gencow app status ${appName}`:"gencow app status";const pendingClass=runtimeConvergencePendingClass(reason);if(pendingClass==="artifact_unavailable"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:false,retryPrecondition:"repeating the request cannot succeed: the runtime artifact of this app is no longer in the artifact store; a new deployment creates a new artifact",command:status,nextAction:`\uC571\uC744 \uB2E4\uC2DC \uBC30\uD3EC\uD558\uC138\uC694: \uC571 \uC791\uC5C5\uACF5\uAC04\uC5D0\uC11C gencow deploy \uC2E4\uD589 (PROD \uC571\uC740 gencow deploy --prod), \uADF8 \uB2E4\uC74C \`${status}\`\uB85C \uD655\uC778`,responsibility:"platform_then_owner"}}if(pendingClass==="ownership_conflict"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:false,retryPrecondition:"the platform kept the current runtime because it could not prove who owns it; repeating the request does not change that",command:status,nextAction:`run \`${status}\` and keep the correlation id; if the reason stays, redeploy from the app workspace: gencow deploy (add --prod for PROD)`,responsibility:"platform_then_owner"}}if(pendingClass==="observing"){return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:true,retryPrecondition:"wait for Retry-After; the platform is waiting for a complete runtime observation",command:status,nextAction:`retry after Retry-After; if the same reason repeats, run \`${status}\` and keep the correlation id`,responsibility:"platform"}}return{pendingClass,stateImpact:"incumbent_route_preserved",retryable:true,retryPrecondition:"wait for Retry-After; the platform is applying the correction for this reason",command:status,nextAction:`retry after Retry-After; if the same reason repeats, run \`${status}\` and keep the correlation id`,responsibility:"platform"}}function runtimeConvergencePendingReasonFor(failureCode2,storedReason){if(typeof failureCode2==="string"&&ARTIFACT_UNAVAILABLE_FAILURE_CODES.has(failureCode2)){return"runtime_artifact_unavailable"}return failureCode2===RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE&&isPublicRuntimeConvergencePendingReason(storedReason)?storedReason:void 0}var RUNTIME_CONVERGENCE_PENDING_REASONS,OBSERVING,OWNERSHIP,ARTIFACT_UNAVAILABLE,ARTIFACT_UNAVAILABLE_FAILURE_CODES,KNOWN,PUBLIC_REASON,RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE;var init_runtime_convergence_pending_reason=__esm({"../internal/dist/src/runtime-convergence-pending-reason.js"(){"use strict";RUNTIME_CONVERGENCE_PENDING_REASONS=["committed_activation_route_ack_missing","route_epoch_stale","serving_runtime_status_projection_stale","compatibility_projection_stale","retained_activation_exited","retained_activation_stopped","desired_instance_absent","non_attested_starting_runtime","unhealthy_serving_exact_identity","desired_instance_unhealthy","runtime_env_protocol_unsupported","platform_bootstrap_not_desired","durable_stop_intent_pending","durable_stop_exit_observed","desired_runtime_stopped","restore_enqueued","authority_not_enforced","observation_incomplete","observation_fence_stale","exact_binding_incomplete","runtime_observation_unknown","route_observation_unknown","projection_observation_unknown","draining_without_consumable_intent","runtime_ownership_foreign","runtime_ownership_ambiguous","tenant_runtime_without_desired_activation","stopped_runtime_ownership_ambiguous","runtime_artifact_unavailable","unclassified"];OBSERVING=new Set(["authority_not_enforced","observation_incomplete","observation_fence_stale","exact_binding_incomplete","runtime_observation_unknown","route_observation_unknown","projection_observation_unknown","draining_without_consumable_intent"]);OWNERSHIP=new Set(["runtime_ownership_foreign","runtime_ownership_ambiguous","tenant_runtime_without_desired_activation","stopped_runtime_ownership_ambiguous"]);ARTIFACT_UNAVAILABLE=new Set(["runtime_artifact_unavailable"]);ARTIFACT_UNAVAILABLE_FAILURE_CODES=new Set(["RUNTIME_CONVERGENCE_AUTHORITY_RUNTIME_ARTIFACT_UNAVAILABLE","ARTIFACT_NOT_FOUND"]);KNOWN=new Set(RUNTIME_CONVERGENCE_PENDING_REASONS);PUBLIC_REASON=/^[a-z][a-z0-9_]{2,79}$/u;RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE="RUNTIME_CONVERGENCE_PENDING"}});import{sql as sql114}from"drizzle-orm";async function readRuntimeConvergencePendingReasons(db,receipts){const pending=receipts.filter(receipt=>receipt.lastFailureCode===RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE);const reasons=new Map;for(const receipt of pending){const rows8=postgresExecuteRows(await db.execute(sql114`
9267
9267
  SELECT last_failure_reason FROM runtime_lifecycle_requests
9268
9268
  WHERE id = ${receipt.operationId} AND app_id = ${receipt.appId}
9269
9269
  AND action = 'converge' AND last_failure_code = ${RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE}