// Force strict mode and setup for ESM
"use strict";
import {
  evaluateDaemonWorkspaceTrust
} from "./chunk-DJ7ATWB4.js";
import {
  createWorkspaceGenerationGuard
} from "./chunk-JYBU6YUE.js";
import "./chunk-GRC5HGPI.js";
import "./chunk-G2JZKUYU.js";
import "./chunk-GLWP3FDB.js";
import "./chunk-XCGIMOLN.js";
import "./chunk-OCPBI7J5.js";
import "./chunk-BQFF7ITW.js";
import "./chunk-ZQ4ICJPB.js";
import "./chunk-XZC5VLBZ.js";
import "./chunk-B4AJNNOL.js";
import "./chunk-2RFKHEXL.js";
import "./chunk-BK2UNYWD.js";
import "./chunk-M5GB774H.js";
import "./chunk-UDXSXLER.js";
import "./chunk-O3JAFRIR.js";
import "./chunk-RKUWKYED.js";
import "./chunk-GAPR7Q3F.js";
import "./chunk-4NSIRXOI.js";
import "./chunk-GOXKNSDZ.js";
import "./chunk-IDS7MSUP.js";
import "./chunk-6PEXNQTX.js";
import "./chunk-NHQGRBZG.js";
import "./chunk-ALGGS7UH.js";
import "./chunk-MR3PXB6E.js";
import "./chunk-OWAK7LMW.js";
import "./chunk-QQOPXQYM.js";
import "./chunk-TWPJO254.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-UPUG4GXM.js";
import "./chunk-64LQLPL7.js";
import "./chunk-2LQTH543.js";
import "./chunk-KRXPRVGL.js";
import "./chunk-GNCIZTNJ.js";
import "./chunk-CVHIL5IG.js";
import "./chunk-IRH27ZC2.js";
import "./chunk-QHWCP53L.js";
import "./chunk-PONHVBRT.js";
import "./chunk-T26EAKDL.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-6QIGFD5W.js";
import "./chunk-XWWKIXVD.js";
import "./chunk-75GFAX4R.js";
import "./chunk-OKF7JF3R.js";
import "./chunk-JSD33JG6.js";
import "./chunk-S6LOFUVP.js";
import "./chunk-JCW2R7WC.js";
import "./chunk-2DN4J57Y.js";
import "./chunk-ZPJWUGCS.js";
import "./chunk-2LKVPASC.js";
import "./chunk-NAVJD2PQ.js";
import "./chunk-LW3RFMG7.js";
import "./chunk-W4MIWP6M.js";
import "./chunk-DGEIYUC3.js";
import "./chunk-MPHPFVKK.js";
import "./chunk-GLNBDYUX.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-6D2RWQMA.js";
import "./chunk-75MIQ3LV.js";
import "./chunk-2J3OJGTL.js";
import "./chunk-P3QQPMQA.js";
import "./chunk-RPLGZJV2.js";
import "./chunk-GLCZKT5V.js";
import "./chunk-DZLYR4U3.js";
import "./chunk-NKHOVMWF.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-SGFT55XI.js";
import "./chunk-Y4IHBGBP.js";
import "./chunk-Y6AXW2OG.js";
import "./chunk-2M3XQKPR.js";
import "./chunk-46UV252V.js";
import "./chunk-ZBVS26BY.js";
import "./chunk-WZRWHXFE.js";
import "./chunk-A3NDJ5SB.js";
import "./chunk-7XATOOE7.js";
import "./chunk-BGTQCTQW.js";
import "./chunk-W4RQUHY3.js";
import "./chunk-S7W2GKIO.js";
import "./chunk-UHUSJ6X7.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
 */
