// Force strict mode and setup for ESM
"use strict";
import {
  evaluateDaemonWorkspaceTrust
} from "./chunk-5SV5RW25.js";
import {
  createWorkspaceGenerationGuard
} from "./chunk-JYBU6YUE.js";
import "./chunk-GRC5HGPI.js";
import "./chunk-MWXYVCYT.js";
import "./chunk-GLWP3FDB.js";
import "./chunk-XCGIMOLN.js";
import "./chunk-OCPBI7J5.js";
import "./chunk-S54LBQKF.js";
import "./chunk-ZEPVXKRP.js";
import "./chunk-CPZAH673.js";
import "./chunk-B4AJNNOL.js";
import "./chunk-2RFKHEXL.js";
import "./chunk-BK2UNYWD.js";
import "./chunk-M5GB774H.js";
import "./chunk-UDXSXLER.js";
import "./chunk-65735MAF.js";
import "./chunk-RKUWKYED.js";
import "./chunk-GOXKNSDZ.js";
import "./chunk-IDS7MSUP.js";
import "./chunk-RNNQYOBE.js";
import "./chunk-Y26TPMQ7.js";
import "./chunk-6PEXNQTX.js";
import "./chunk-4QPH7TD4.js";
import "./chunk-ALGGS7UH.js";
import "./chunk-MR3PXB6E.js";
import "./chunk-OWAK7LMW.js";
import "./chunk-HVFUW4JT.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-TWPJO254.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-AOHY3QJ3.js";
import "./chunk-5NNHICSA.js";
import "./chunk-SHN4KHDK.js";
import "./chunk-JXVC2PL3.js";
import "./chunk-KRXPRVGL.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-OV2BALJJ.js";
import "./chunk-IRH27ZC2.js";
import "./chunk-QHWCP53L.js";
import "./chunk-TEGJSJDF.js";
import "./chunk-TIRRPCFS.js";
import "./chunk-O6GEWCJA.js";
import "./chunk-T26EAKDL.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-4KP2F2TE.js";
import "./chunk-3APUUXRF.js";
import "./chunk-THVU3RNH.js";
import "./chunk-LHKCY7DY.js";
import "./chunk-6FMJLI5M.js";
import "./chunk-CBBP4BMC.js";
import "./chunk-S6LOFUVP.js";
import "./chunk-K623ENWT.js";
import "./chunk-AQ37AY7B.js";
import "./chunk-N4ACHWNH.js";
import "./chunk-ZPJWUGCS.js";
import "./chunk-D4HTUMGX.js";
import "./chunk-NAVJD2PQ.js";
import "./chunk-LOY7RWQG.js";
import "./chunk-E6CJ2SMM.js";
import "./chunk-DGEIYUC3.js";
import "./chunk-MPHPFVKK.js";
import "./chunk-GLNBDYUX.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-JHNMFZLP.js";
import "./chunk-Z3S5EMOW.js";
import "./chunk-2J3OJGTL.js";
import "./chunk-P3QQPMQA.js";
import "./chunk-XQK4XXTN.js";
import "./chunk-GLCZKT5V.js";
import "./chunk-QDK4F2N5.js";
import "./chunk-SCUZ3ZCL.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-3I6DUGQD.js";
import "./chunk-7ULQIS27.js";
import "./chunk-MM7TH7ZM.js";
import "./chunk-6WSXKTJR.js";
import "./chunk-46UV252V.js";
import "./chunk-ZBVS26BY.js";
import "./chunk-Q3T5KA2V.js";
import "./chunk-R2XWGR75.js";
import "./chunk-HC45LTEN.js";
import "./chunk-QARJNL2V.js";
import "./chunk-W4RQUHY3.js";
import "./chunk-G7XXKQYS.js";
import "./chunk-E2BHWIDT.js";
import "./chunk-VOQXFAY5.js";
import "./chunk-75DOP5OR.js";
import "./chunk-DMTGGOSA.js";
import "./chunk-YQ3U5MUC.js";
import "./chunk-AMDSOFFV.js";
import "./chunk-QUGAUQGJ.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/serve/workspace-trust-reconciler.ts
init_esbuild_shims();
function errorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
__name(errorMessage, "errorMessage");
function createWorkspaceTrustReconciler(options) {
  let pendingSnapshot;
  let running;
  const materializationKey = /* @__PURE__ */ __name((entry, snapshot, decision) => options.materializationKey?.({ entry, snapshot, decision }) ?? String(decision.targetTrusted), "materializationKey");
  const drainRuntime = /* @__PURE__ */ __name(async (runtime) => {
    try {
      await options.drainRuntime(runtime, "trust_reconfigured");
      return void 0;
    } catch (error) {
      return error;
    }
  }, "drainRuntime");
  const replace = /* @__PURE__ */ __name(async (planned, snapshot) => {
    const { entry, previous } = planned;
    if (planned.decrease) {
      if (entry.state !== "transitioning" || entry.current?.runtime !== previous) {
        return;
      }
    } else {
      if (!options.registry.beginReplacement(entry, snapshot.revision)) return;
    }
    let contained = previous === void 0;
    try {
      if (previous) {
        const drainError = await (planned.drainResult ?? drainRuntime(previous));
        await options.disposeRuntime(previous, "trust_reconfigured");
        contained = true;
        if (drainError) options.onError?.(entry, drainError);
      }
      let desiredSnapshot = snapshot;
      let desiredDecision = planned.decision;
      for (; ; ) {
        const generationGuard = createWorkspaceGenerationGuard();
        let candidate;
        let candidateActivated = false;
        try {
          candidate = await options.buildRuntime({
            entry,
            trusted: desiredDecision.targetTrusted,
            snapshot: desiredSnapshot,
            decision: desiredDecision,
            generationGuard
          });
        } catch (error) {
          generationGuard.close();
          if (!desiredDecision.targetTrusted) throw error;
          const fallbackGuard = createWorkspaceGenerationGuard();
          let fallback;
          let fallbackActivated = false;
          try {
            fallback = await options.buildRuntime({
              entry,
              trusted: false,
              snapshot: desiredSnapshot,
              decision: { ...desiredDecision, targetTrusted: false },
              generationGuard: fallbackGuard
            });
            const latest = await options.readLatestSnapshot();
            if (latest.revision !== desiredSnapshot.revision) {
              pendingSnapshot = latest;
              desiredSnapshot = latest;
              desiredDecision = evaluateDaemonWorkspaceTrust(
                latest,
                entry.workspaceCwd
              );
              entry.configuredRevision = latest.revision;
              continue;
            }
            options.registry.activateReplacement(
              entry,
              fallback,
              desiredSnapshot.revision
            );
            fallbackActivated = true;
            entry.appliedRevision = null;
            entry.applyError = errorMessage(error);
            try {
              await options.runtimeActivated?.(fallback, previous);
            } catch (activationError) {
              options.onError?.(entry, activationError);
            }
            options.onError?.(entry, error);
            return;
          } catch (fallbackError) {
            throw new AggregateError(
              [error, fallbackError],
              "Trusted runtime and untrusted fallback both failed to build."
            );
          } finally {
            if (!fallbackActivated) {
              fallbackGuard.close();
              if (fallback) {
                await options.disposeRuntime(fallback, "trust_reconfigured");
              }
            }
          }
        }
        try {
          const latest = await options.readLatestSnapshot();
          if (latest.revision !== desiredSnapshot.revision) {
            pendingSnapshot = latest;
            desiredSnapshot = latest;
            desiredDecision = evaluateDaemonWorkspaceTrust(
              latest,
              entry.workspaceCwd
            );
            entry.configuredRevision = latest.revision;
            continue;
          }
          options.registry.activateReplacement(
            entry,
            candidate,
            desiredSnapshot.revision
          );
          candidateActivated = true;
          try {
            await options.runtimeActivated?.(candidate, previous);
          } catch (activationError) {
            options.onError?.(entry, activationError);
          }
          return;
        } finally {
          if (!candidateActivated) {
            generationGuard.close();
            await options.disposeRuntime(candidate, "trust_reconfigured");
          }
        }
      }
    } catch (error) {
      if (contained) {
        entry.current = void 0;
        options.registry.blockReplacement(entry, errorMessage(error));
      } else {
        options.registry.blockReplacement(
          entry,
          `Runtime containment failed: ${errorMessage(error)}`
        );
      }
      options.onError?.(entry, error);
    }
  }, "replace");
  const applySnapshot = /* @__PURE__ */ __name(async (snapshot) => {
    const planned = [];
    for (const entry of options.registry.listEntries()) {
      const current = entry.current;
      if (entry.state === "active" && current?.runtime.provenance === "managed-scratch") {
        options.registry.advancePolicyRevision(entry, snapshot.revision);
        continue;
      }
      if (entry.state === "blocked") {
        const decision2 = evaluateDaemonWorkspaceTrust(
          snapshot,
          entry.workspaceCwd
        );
        planned.push({
          entry,
          previous: current?.runtime,
          decision: decision2,
          materialization: materializationKey(entry, snapshot, decision2),
          decrease: false
        });
        continue;
      }
      if (!current || entry.state !== "active") {
        entry.configuredRevision = snapshot.revision;
        continue;
      }
      const decision = evaluateDaemonWorkspaceTrust(
        snapshot,
        entry.workspaceCwd
      );
      const materialization = materializationKey(entry, snapshot, decision);
      if (current.runtime.trusted === decision.targetTrusted && current.runtime.trustMaterialization === materialization) {
        options.registry.advancePolicyRevision(entry, snapshot.revision);
        continue;
      }
      const decrease = options.isTrustDecrease?.({
        entry,
        runtime: current.runtime,
        nextMaterialization: materialization,
        decision
      }) ?? (current.runtime.trusted && !decision.targetTrusted);
      planned.push({
        entry,
        previous: current.runtime,
        decision,
        materialization,
        decrease
      });
    }
    for (const item of planned) {
      if (item.decrease) {
        if (!options.registry.beginReplacement(item.entry, snapshot.revision)) {
          continue;
        }
      }
    }
    for (const item of planned) {
      if (item.decrease && item.previous) {
        item.drainResult = drainRuntime(item.previous);
      }
    }
    for (const item of planned) {
      await replace(item, snapshot);
    }
  }, "applySnapshot");
  const drain = /* @__PURE__ */ __name(async () => {
    while (pendingSnapshot) {
      const snapshot = pendingSnapshot;
      pendingSnapshot = void 0;
      await applySnapshot(snapshot);
    }
  }, "drain");
  const ensureRunning = /* @__PURE__ */ __name(() => {
    if (!running) {
      running = drain().finally(() => {
        running = void 0;
        if (pendingSnapshot) return ensureRunning();
        return void 0;
      });
    }
    return running;
  }, "ensureRunning");
  return {
    reconcile(snapshot) {
      pendingSnapshot = snapshot;
      return ensureRunning();
    }
  };
}
__name(createWorkspaceTrustReconciler, "createWorkspaceTrustReconciler");
export {
  createWorkspaceTrustReconciler
};
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
