// Force strict mode and setup for ESM
"use strict";
import {
  evaluateDaemonWorkspaceTrust
} from "./chunk-HEBW74ZW.js";
import {
  createWorkspaceGenerationGuard
} from "./chunk-2M5N3DHY.js";
import "./chunk-GRC5HGPI.js";
import "./chunk-HIXVWF7I.js";
import "./chunk-GLWP3FDB.js";
import "./chunk-XCGIMOLN.js";
import "./chunk-OCPBI7J5.js";
import "./chunk-UWSXFI6E.js";
import "./chunk-PDDYAXL2.js";
import "./chunk-UKZEXS6K.js";
import "./chunk-J26HHFI5.js";
import "./chunk-6PLDPT2C.js";
import "./chunk-BK2UNYWD.js";
import "./chunk-M5GB774H.js";
import "./chunk-UDXSXLER.js";
import "./chunk-22YFMJBW.js";
import "./chunk-RKUWKYED.js";
import "./chunk-GOXKNSDZ.js";
import "./chunk-IDS7MSUP.js";
import "./chunk-KXWERR6P.js";
import "./chunk-6NE5NTHJ.js";
import "./chunk-6PEXNQTX.js";
import "./chunk-M5LIY7Y6.js";
import "./chunk-ALGGS7UH.js";
import "./chunk-MR3PXB6E.js";
import "./chunk-UQDFEU47.js";
import "./chunk-GOFAQQZA.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-TWPJO254.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-VA5NLVPT.js";
import "./chunk-I7JDGNG6.js";
import "./chunk-A6SX5TAH.js";
import "./chunk-33FNCQSY.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-XUMAD5IT.js";
import "./chunk-IRH27ZC2.js";
import "./chunk-QHWCP53L.js";
import "./chunk-MOHAWIAW.js";
import "./chunk-X6QNZOTC.js";
import "./chunk-O6GEWCJA.js";
import "./chunk-T26EAKDL.js";
import "./chunk-ZPJWUGCS.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-MISUEWB4.js";
import "./chunk-KRXPRVGL.js";
import "./chunk-A5YZ3FA2.js";
import "./chunk-YAVY33G4.js";
import "./chunk-2UISUFHQ.js";
import "./chunk-HFVW54NL.js";
import "./chunk-TZTBZ25J.js";
import "./chunk-S6LOFUVP.js";
import "./chunk-SRY26X4H.js";
import "./chunk-K623ENWT.js";
import "./chunk-AQ37AY7B.js";
import "./chunk-432XCUHF.js";
import "./chunk-XC656O42.js";
import "./chunk-NAVJD2PQ.js";
import "./chunk-QYPT3QUD.js";
import "./chunk-QMBEW7EW.js";
import "./chunk-DGEIYUC3.js";
import "./chunk-MPHPFVKK.js";
import "./chunk-GLNBDYUX.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-EIMKVOSF.js";
import "./chunk-RPYYTL7E.js";
import "./chunk-2J3OJGTL.js";
import "./chunk-P3QQPMQA.js";
import "./chunk-6O5DVH27.js";
import "./chunk-GLCZKT5V.js";
import "./chunk-2DNKEBXY.js";
import "./chunk-4K3RV3OA.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-E4WHKETF.js";
import "./chunk-UEJESCS7.js";
import "./chunk-CFDR3GNL.js";
import "./chunk-H35Q5CEG.js";
import "./chunk-46UV252V.js";
import "./chunk-ZBVS26BY.js";
import "./chunk-BFHXDAR7.js";
import "./chunk-TYERNYH4.js";
import "./chunk-UH7Z7Y45.js";
import "./chunk-O2ZYHG33.js";
import "./chunk-W4RQUHY3.js";
import "./chunk-G7XXKQYS.js";
import "./chunk-3RXUYQJI.js";
import "./chunk-VOQXFAY5.js";
import "./chunk-OWAK7LMW.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
 */
