gencow 0.1.280 → 0.1.281

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.
@@ -1,5 +1,6 @@
1
1
  import { appNotFoundDiagnostic } from "./app-response-contract.mjs";
2
2
  import { describeProdTargetFailure, resolveProdAppTarget } from "./cloud-targets.mjs";
3
+ import { responseHeaderCorrelationId, SAFE_CORRELATION_ID } from "./http-correlation-id.mjs";
3
4
  import { readJsonObjectResponse } from "./http-response-json.mjs";
4
5
  import { authCauseNextAction, safeAuthCauseCode } from "./release-auth-cause.mjs";
5
6
 
@@ -12,14 +13,19 @@ const PUBLIC_LOOKUP_ERROR_CODES = new Set([
12
13
  "APP_RELEASE_ENVIRONMENT_INVALID",
13
14
  "APP_RELEASE_POLICY_READ_UNAVAILABLE",
14
15
  ]);
15
- const SAFE_CORRELATION_ID = /^[A-Za-z0-9_-]{8,128}$/u;
16
+ const UNTYPED_STAGE = "deploy target lookup";
16
17
 
17
18
  function publicLookupFailure(response, body, creds) {
18
- const code = PUBLIC_LOOKUP_ERROR_CODES.has(body?.code)
19
+ const typed = PUBLIC_LOOKUP_ERROR_CODES.has(body?.code);
20
+ const code = typed
19
21
  ? body.code
20
22
  : response.status === 401
21
23
  ? "APP_RELEASE_AUTH_REQUIRED"
22
24
  : "APP_DEPLOY_TARGET_LOOKUP_FAILED";
25
+ // A 5xx without a public code (empty, HTML or unknown-code body) may come from the edge or a proxy, so it is
26
+ // untyped. Its Stage and state lines are rendered; the header ID is used only here, so typed output is unchanged.
27
+ const untyped = !typed && response.status >= 500;
28
+ const bodyRetryable = typeof body?.retryable === "boolean" ? body.retryable : undefined;
23
29
  const causeCode =
24
30
  code === "APP_RELEASE_AUTH_REQUIRED" && body?.stage === "auth" ? safeAuthCauseCode(body.causeCode) : null;
25
31
  // Only a fixed env name is kept, so the next action can tell the user to replace or unset it.
@@ -28,20 +34,63 @@ function publicLookupFailure(response, body, creds) {
28
34
  (creds.credentialEnvName === "GENCOW_TOKEN" || creds.credentialEnvName === "GENCOW_DEPLOY_TOKEN")
29
35
  ? creds.credentialEnvName
30
36
  : null;
37
+ const correlationId =
38
+ typeof body?.correlationId === "string" && SAFE_CORRELATION_ID.test(body.correlationId)
39
+ ? body.correlationId
40
+ : untyped
41
+ ? responseHeaderCorrelationId(response)
42
+ : undefined;
31
43
  return {
32
44
  kind: "error",
33
45
  code,
34
46
  status: response.status,
35
- retryable: typeof body?.retryable === "boolean" ? body.retryable : response.status >= 500,
36
- ...(typeof body?.correlationId === "string" && SAFE_CORRELATION_ID.test(body.correlationId)
37
- ? { correlationId: body.correlationId }
38
- : {}),
47
+ retryable: bodyRetryable ?? response.status >= 500,
48
+ // The CLI estimates retryability when the Platform states none.
49
+ ...(bodyRetryable === undefined && untyped ? { retryableEstimated: true } : {}),
50
+ ...(correlationId ? { correlationId } : {}),
39
51
  ...(causeCode ? { causeCode } : {}),
40
52
  ...(causeCode && credentialEnvName ? { credentialEnvName } : {}),
53
+ ...(untyped ? { untyped: true } : {}),
41
54
  };
42
55
  }
43
56
 
44
- function formatLookupFailure(failure, target) {
57
+ // Lookup failure without a typed Platform error: an untyped 5xx, or no HTTP response at all (network error).
58
+ // Serving is stated only for this lookup: a GET changes nothing, so the incumbent serving state is unchanged by it.
59
+ function formatUntypedLookupFailure(failure, target, retryCommand) {
60
+ const lines = [
61
+ `${failure.code}: Could not verify the configured ${target} app. No replacement app was created and gencow.json was unchanged.`,
62
+ `Stage: ${UNTYPED_STAGE}`,
63
+ ];
64
+ if (failure.transportError) lines.push("Response: none received (network error)");
65
+ else lines.push(`HTTP status: ${failure.status}`);
66
+ lines.push(
67
+ failure.retryableEstimated
68
+ ? "Retry: rerun the same command (the Platform did not say whether a retry is safe)"
69
+ : `Retryable: ${failure.retryable ? "yes" : "no"}`,
70
+ );
71
+ lines.push(`Changed: ${DEPLOY_CHANGED_TEXT}`);
72
+ lines.push("Incumbent serving: PRESERVED (this lookup did not change it)");
73
+ lines.push(`Correlation ID: ${failure.correlationId ?? "none returned"}`);
74
+ const reportTail =
75
+ `add the failure time (UTC)${failure.correlationId ? " and the Correlation ID above" : ""} to the GitHub issue.`;
76
+ if (failure.transportError) {
77
+ lines.push(
78
+ "Action: check the network connection, then wait for Platform release capability to recover and retry.",
79
+ );
80
+ } else if (failure.retryable === false) {
81
+ // The Platform stated the failure is not retryable: no rerun instruction, only a report.
82
+ lines.push(`Action: do not retry this command. Report it: ${reportTail}`);
83
+ } else {
84
+ lines.push(`Rerun: ${retryCommand ?? "the same deploy command"}`);
85
+ lines.push(
86
+ `Action: wait 5-10 seconds, then rerun the same command once. If it fails again, ${reportTail}`,
87
+ );
88
+ }
89
+ return lines.join("\n");
90
+ }
91
+
92
+ function formatLookupFailure(failure, target, retryCommand = null) {
93
+ if (failure?.untyped) return formatUntypedLookupFailure(failure, target, retryCommand);
45
94
  const code = failure?.kind === "error" ? failure.code : "APP_DEPLOY_TARGET_LOOKUP_FAILED";
46
95
  const lines = [
47
96
  `${code}: Could not verify the configured ${target} app. No replacement app was created and gencow.json was unchanged.`,
@@ -198,6 +247,8 @@ export async function lookupOwnedApp({ creds, appId, environment, platformFetchI
198
247
  kind: "error",
199
248
  code: "APP_RELEASE_CAPABILITY_UNAVAILABLE",
200
249
  retryable: true,
250
+ untyped: true,
251
+ transportError: true,
201
252
  };
202
253
  }
203
254
  }
@@ -210,6 +261,7 @@ export async function resolveDeployAppId({
210
261
  platformFetchImpl,
211
262
  allowMissingAppReplacement,
212
263
  explicitApp = false,
264
+ retryCommand = null,
213
265
  infoImpl,
214
266
  errorImpl,
215
267
  exitImpl,
@@ -218,7 +270,7 @@ export async function resolveDeployAppId({
218
270
  const lookup = await lookupOwnedApp({ creds, appId, environment, platformFetchImpl });
219
271
  if (lookup === "found" || lookup === "unsupported") return appId;
220
272
  if (lookup?.kind === "error" || lookup === "error") {
221
- errorImpl(formatLookupFailure(lookup, `"${appId}"`));
273
+ errorImpl(formatLookupFailure(lookup, `"${appId}"`, retryCommand));
222
274
  exitImpl(1);
223
275
  return false;
224
276
  }
@@ -245,6 +297,7 @@ export async function reconcileProductionAppTarget({
245
297
  platformFetchImpl,
246
298
  createCloudAppIfNeeded,
247
299
  explicitApp = false,
300
+ retryCommand = null,
248
301
  infoImpl,
249
302
  errorImpl,
250
303
  exitImpl,
@@ -256,7 +309,7 @@ export async function reconcileProductionAppTarget({
256
309
  }
257
310
 
258
311
  const failLookup = (failure, target) => {
259
- errorImpl(formatLookupFailure(failure, target));
312
+ errorImpl(formatLookupFailure(failure, target, retryCommand));
260
313
  exitImpl(1);
261
314
  return null;
262
315
  };
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, writeFileSync } from "fs";
2
2
 
3
3
  import { CONFIRMATION_MODE, resolveConfirmationMode } from "./confirm-gate.mjs";
4
4
  import { confirmFirstProductionDeploy } from "./deploy-first-prod-confirm.mjs";
5
- import { reconcileProductionAppTarget } from "./deploy-app-target.mjs";
5
+ import { prodRetryCommandLine, reconcileProductionAppTarget } from "./deploy-app-target.mjs";
6
6
  import { readJsonObjectResponse } from "./http-response-json.mjs";
7
7
  import { BOLD, DIM, GREEN, RED, RESET, error, info, log, success } from "./output.mjs";
8
8
  import { prodCreateFailureMessage } from "./prod-create-failure.mjs";
@@ -52,6 +52,7 @@ export async function ensureProductionDeployTarget({
52
52
  platformFetchImpl,
53
53
  createCloudAppIfNeeded,
54
54
  explicitApp,
55
+ retryCommand: prodRetryCommandLine({ command: "deploy", args: deployArgs ?? [] }),
55
56
  infoImpl,
56
57
  errorImpl,
57
58
  exitImpl,
@@ -0,0 +1,13 @@
1
+ // Correlation ID shape accepted from Platform bodies and headers. Anything else is dropped, never echoed.
2
+ export const SAFE_CORRELATION_ID = /^[A-Za-z0-9_-]{8,128}$/u;
3
+
4
+ // Header names checked, in order, when the JSON body carries no correlation ID.
5
+ const SAFE_CORRELATION_HEADERS = ["x-gencow-correlation-id", "x-correlation-id", "x-request-id"];
6
+
7
+ export function responseHeaderCorrelationId(response) {
8
+ for (const name of SAFE_CORRELATION_HEADERS) {
9
+ const value = response?.headers?.get?.(name);
10
+ if (typeof value === "string" && SAFE_CORRELATION_ID.test(value)) return value;
11
+ }
12
+ return undefined;
13
+ }
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { unlink } from "node:fs/promises";
3
3
 
4
+ import { responseHeaderCorrelationId } from "./http-correlation-id.mjs";
4
5
  import { safeAuthCauseCode } from "./release-auth-cause.mjs";
5
6
  import { platformFetch } from "./platform-client.mjs";
6
7
  import { createReleaseSourcePackage } from "./release-source-package.mjs";
@@ -66,17 +67,6 @@ function safePlatformOrigin(value) {
66
67
  }
67
68
  }
68
69
 
69
- // Header names checked, in order, when the JSON body carries no correlation ID.
70
- const SAFE_CORRELATION_HEADERS = ["x-gencow-correlation-id", "x-correlation-id", "x-request-id"];
71
-
72
- function responseHeaderCorrelationId(response) {
73
- for (const name of SAFE_CORRELATION_HEADERS) {
74
- const value = response?.headers?.get?.(name);
75
- if (typeof value === "string" && SAFE_CORRELATION_ID.test(value)) return value;
76
- }
77
- return undefined;
78
- }
79
-
80
70
  // `context.stage` is set only where the request is known to happen before any serving
81
71
  // change, so an untyped 5xx there can be reported as "incumbent serving preserved".
82
72
  function throwResponseError(response, fallback, body, creds = {}, context = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.280",
3
+ "version": "0.1.281",
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/core": "0.1.47",
44
- "@gencow/shared": "0.0.0",
45
- "@gencow/server": "0.1.3",
46
43
  "@gencow/client": "0.2.8",
47
- "@gencow/react": "0.2.8"
44
+ "@gencow/react": "0.2.8",
45
+ "@gencow/server": "0.1.3",
46
+ "@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",
@@ -9280,7 +9280,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
9280
9280
  LEFT JOIN app_serving_route_authorities authority ON authority.app_id = app.id
9281
9281
  WHERE app.id = ${input2.appId}
9282
9282
  AND app.instance_id::text = ${input2.appInstanceId}
9283
- `);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 randomUUID48}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-${randomUUID48()}`,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(text34){const markerMatch=text34.match(new RegExp(`${BOOT_FAILURE_MARKER}\\b[^\\n]*\\breason=(boot_db_[a-z_]+)`));const reason=markerMatch?.[1];return isRetryableBootDbStatusReason(reason)?reason:null}function classifyLegacySettingsDbTrace(text34){const lower=text34.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 text34=(event?.stderrTail??[]).join("\n");if(!text34)return null;if(/AUTH_SCHEMA_CONTRACT_INVALID:[^\n]*Expected exactly one (?:legacy|project) Auth schema entry, received [2-9]\d*/u.test(text34)){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(text34);if(markerReason)return buildClassification(markerReason);const legacyReason=classifyLegacySettingsDbTrace(text34);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{randomUUID as randomUUID49}from"node:crypto";import postgres from"postgres";var init_pg_listen_health=__esm({"../platform/src/pg-listen-health.ts"(){"use strict"}});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";init_pg_listen_health();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`
9283
+ `);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,outcome2){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"};const withStatic=operation.environment==="static"?{...base2,files:null,size:operation.staticSize}:base2;const receipt=outcome2.verifiedReceipt;const receiptFields=receipt&&hasVerifiedDeploymentExecutorCompletion(operation)?{databaseState:receipt.databaseState,servingState:outcome2.superseded?"PRESERVED":"CHANGED"}:{};return{...withStatic,...receiptFields,...outcome2.superseded?{superseded:true}:{}}}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,{verifiedReceipt,superseded:true})}}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),{verifiedReceipt})}}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),{verifiedReceipt})}}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 randomUUID48}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-${randomUUID48()}`,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(text34){const markerMatch=text34.match(new RegExp(`${BOOT_FAILURE_MARKER}\\b[^\\n]*\\breason=(boot_db_[a-z_]+)`));const reason=markerMatch?.[1];return isRetryableBootDbStatusReason(reason)?reason:null}function classifyLegacySettingsDbTrace(text34){const lower=text34.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 text34=(event?.stderrTail??[]).join("\n");if(!text34)return null;if(/AUTH_SCHEMA_CONTRACT_INVALID:[^\n]*Expected exactly one (?:legacy|project) Auth schema entry, received [2-9]\d*/u.test(text34)){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(text34);if(markerReason)return buildClassification(markerReason);const legacyReason=classifyLegacySettingsDbTrace(text34);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{randomUUID as randomUUID49}from"node:crypto";import postgres from"postgres";var init_pg_listen_health=__esm({"../platform/src/pg-listen-health.ts"(){"use strict"}});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";init_pg_listen_health();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`
9284
9284
  SELECT last_failure_reason FROM runtime_lifecycle_requests
9285
9285
  WHERE id = ${receipt.operationId} AND app_id = ${receipt.appId}
9286
9286
  AND action = 'converge' AND last_failure_code = ${RUNTIME_CONVERGENCE_PENDING_FAILURE_CODE}