UNPKG

mlld

Version:

mlld: llm scripting language

21,931 lines 791 kB
import { parseVersionSpecifier } from './chunk-KQOGKTK5.mjs';
import { parseFrontmatter } from './chunk-URVQO5JY.mjs';
import { labelsForPath, wrapLoadContentValue, isFileLoadedValue } from './chunk-GLVJZ2CA.mjs';
import { evaluateForeachSection, evaluateForeachCommand } from './chunk-2NIKWPWP.mjs';
import { toIterable } from './chunk-JVJPPTN3.mjs';
import { AutoUnwrapManager } from './chunk-QTYWAF2L.mjs';
import { accessFields, accessField } from './chunk-3VW6WZGZ.mjs';
import { isVariable, extractVariableValue } from './chunk-DUS6QZAC.mjs';
import { VariableImporter } from './chunk-WVAX2Q4I.mjs';
import { createNDJSONAdapter } from './chunk-YRFPMAAJ.mjs';
import { llmxmlInstance } from './chunk-GPFWQ7PB.mjs';
import { InterpolationContext, EscapingStrategyFactory } from './chunk-PHUTH3LV.mjs';
import { JSONFormatter } from './chunk-VWPKQQNW.mjs';
import { debugPipelineDetection, detectPipeline } from './chunk-JM4XNSW2.mjs';
import { version, checkMlldVersion, formatVersionError } from './chunk-BJCESMSP.mjs';
import { inferMlldMode } from './chunk-O2UUQ4YJ.mjs';
import { logger, interpreterLogger } from './chunk-M3R2H5KU.mjs';
import { GuardError, GuardRetrySignal, MlldError, ErrorSeverity, MlldCommandExecutionError, MlldImportError, MlldDirectiveError, MlldWhenExpressionError, MlldConditionError, FieldAccessError, MlldInterpreterError, isGuardRetrySignal, MlldOutputError } from './chunk-V5XE5YB5.mjs';
import { parse } from './chunk-J3EQD6RR.mjs';
import { isTextNode, astLocationToSourceLocation, isWhenSimpleNode, isWhenMatchNode, isWhenBlockNode, isLetAssignment, isAugmentedAssignment, isConditionPair, isPrimitiveValue, isDirectiveValue, isVariableReferenceValue, isTemplateValue, isDoneLiteral, isContinueLiteral, isExecInvocation, isLiteralNode } from './chunk-6PZVQRSR.mjs';
import { asText, isStructuredValue, getExpressionProvenance, extractSecurityDescriptor, inheritExpressionProvenance, materializeExpressionValue, createSimpleTextVariable, makeSecurityDescriptor, updateVarMxFromDescriptor, varMxToSecurityDescriptor, VariableMetadataUtils, createPathVariable, ensureStructuredValue, asData, isExecutableVariable, normalizeWhenShowEffect, mergeDescriptors, assertStructuredValue, createArrayVariable, createObjectVariable, buildTokenMetrics, wrapStructured, createPipelineInputVariable, createStructuredValueVariable, applySecurityDescriptorToStructuredValue, setExpressionProvenance, parseAndWrapJson, createPrimitiveVariable, createCommandResultVariable, createComputedVariable, createFileContentVariable, createSectionContentVariable, createTemplateVariable, createInterpolatedTextVariable, createCapabilityContext, createExecutableVariable, looksLikeJsonString, hasSecurityVarMx } from './chunk-RKGZ44GZ.mjs';
import { isTextLike, isArray, isObject, isCommandResult, isPipelineInput, isExecutable, isPath, isImported, isStructuredValueVariable, isTemplate, isComputed, isPrimitive } from './chunk-EIWSEMQ4.mjs';
import { isLoadContentResult } from './chunk-TZUIAYSF.mjs';
import { __name, __publicField } from './chunk-NJQT543K.mjs';
import * as path7 from 'path';
import path7__default from 'path';
import * as crypto from 'crypto';
import * as fs from 'fs';
import { appendFileSync } from 'fs';
import { spawnSync } from 'child_process';
import { createRequire } from 'module';
import minimatch from 'minimatch';
import { JSDOM } from 'jsdom';
import yaml from 'js-yaml';
import { glob } from 'tinyglobby';
import ts from 'typescript';
import { Readability } from '@mozilla/readability';
import TurndownService from 'turndown';
import * as shellQuote from 'shell-quote';

// interpreter/utils/type-guard-helpers.ts
function getTextContent(node) {
  return node && isTextNode(node) ? node.content : void 0;
}
__name(getTextContent, "getTextContent");

// interpreter/utils/display-formatter.ts
function formatForDisplay(value, options = {}) {
  const { pretty = true, indent = 2, separator = "\n", isForeachSection = false } = options;
  if (typeof value === "string") {
    return value;
  }
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  if (isLoadContentResult(value)) {
    return asText(value);
  }
  if (isStructuredValue(value)) {
    const data = value.data;
    if (Array.isArray(data)) {
      const printableArray = data.map((item) => normalizeArrayEntry(item));
      return JSONFormatter.stringify(printableArray, {
        pretty,
        indent
      });
    }
    if (data && typeof data === "object") {
      if (value.mx?.source === "load-content" || Boolean(value.mx?.filename) || Boolean(value.mx?.url)) {
        return value.text;
      }
      return JSONFormatter.stringify(data, {
        pretty,
        indent
      });
    }
    if (typeof data === "number" || typeof data === "boolean") {
      return String(data);
    }
    if (data === null) {
      return "null";
    }
    return value.text;
  }
  if (Array.isArray(value)) {
    if (isForeachSection && value.every((item) => typeof item === "string")) {
      return value.join("\n\n");
    }
    const printableArray = value.map((item) => normalizeArrayEntry(item));
    return JSONFormatter.stringify(printableArray, {
      pretty,
      indent
    });
  }
  if (value && typeof value === "object") {
    return JSONFormatter.stringify(value, {
      pretty,
      indent
    });
  }
  if (value === null || value === void 0) {
    return "";
  }
  return String(value);
}
__name(formatForDisplay, "formatForDisplay");
function normalizeArrayEntry(item) {
  if (isStructuredValue(item)) {
    const data = item.data;
    if (Array.isArray(data) || data && typeof data === "object") {
      return data;
    }
    if (typeof data === "number" || typeof data === "boolean" || data === null) {
      return data;
    }
    return asText(item);
  }
  if (item && typeof item === "object" && typeof item.text === "string") {
    return item.text;
  }
  return item;
}
__name(normalizeArrayEntry, "normalizeArrayEntry");

// interpreter/utils/display-materialization.ts
function materializeDisplayValue(value, options, descriptorSource, textOverride) {
  const provenanceSource = descriptorSource ?? value;
  const descriptor = getExpressionProvenance(provenanceSource) ?? extractSecurityDescriptor(provenanceSource, {
    recursive: true,
    mergeArrayElements: true
  });
  const text = textOverride !== void 0 ? textOverride : formatForDisplay(value, options);
  return {
    text,
    descriptor
  };
}
__name(materializeDisplayValue, "materializeDisplayValue");
function resolveNestedValue(value, options) {
  const preserve = options?.preserveProvenance ?? false;
  return resolveNestedValueInternal(value, preserve);
}
__name(resolveNestedValue, "resolveNestedValue");
function resolveNestedValueInternal(value, preserve) {
  if (isVariable(value)) {
    const resolved = resolveNestedValueInternal(value.value, preserve);
    inheritIfNeeded(resolved, value, preserve);
    return resolved;
  }
  if (isStructuredValue(value)) {
    const resolved = resolveNestedValueInternal(value.data, preserve);
    inheritIfNeeded(resolved, value, preserve);
    return resolved;
  }
  if (Array.isArray(value)) {
    const resolvedArray = value.map((entry) => resolveNestedValueInternal(entry, preserve));
    inheritIfNeeded(resolvedArray, value, preserve);
    return resolvedArray;
  }
  if (value && typeof value === "object") {
    const resolvedObject = {};
    for (const [key, entry] of Object.entries(value)) {
      resolvedObject[key] = resolveNestedValueInternal(entry, preserve);
    }
    inheritIfNeeded(resolvedObject, value, preserve);
    return resolvedObject;
  }
  return value;
}
__name(resolveNestedValueInternal, "resolveNestedValueInternal");
function inheritIfNeeded(target, source, preserve) {
  if (!preserve || !target || typeof target !== "object") {
    return;
  }
  inheritExpressionProvenance(target, source);
}
__name(inheritIfNeeded, "inheritIfNeeded");

// interpreter/utils/guard-inputs.ts
var FALLBACK_SOURCE = {
  directive: "var",
  syntax: "expression",
  hasInterpolation: false,
  isMultiLine: false
};
function materializeGuardInputs(values, options) {
  const nameHint = options?.nameHint ?? "__guard_input__";
  return values.map((value) => {
    if (isVariable(value)) {
      return value;
    }
    const normalized = resolveNestedValue(value, {
      preserveProvenance: true
    });
    const materialized = materializeExpressionValue(normalized, {
      name: nameHint
    });
    if (materialized) {
      return materialized;
    }
    const fallback = createSimpleTextVariable(nameHint, formatGuardInputValue(normalized), FALLBACK_SOURCE, {
      mx: {}
    });
    applyDescriptorFromValue(normalized, fallback);
    return fallback;
  }).filter((value) => Boolean(value));
}
__name(materializeGuardInputs, "materializeGuardInputs");
function materializeGuardInputsWithMapping(values, options) {
  const nameHint = options?.nameHint ?? "__guard_input__";
  const results = [];
  for (let index = 0; index < values.length; index++) {
    const value = values[index];
    const variable = (() => {
      if (isVariable(value)) {
        return value;
      }
      const normalized = resolveNestedValue(value, {
        preserveProvenance: true
      });
      const materialized = materializeExpressionValue(normalized, {
        name: nameHint
      });
      if (materialized) {
        return materialized;
      }
      const fallback = createSimpleTextVariable(nameHint, formatGuardInputValue(normalized), FALLBACK_SOURCE, {
        mx: {}
      });
      applyDescriptorFromValue(normalized, fallback);
      return fallback;
    })();
    if (variable) {
      results.push({
        index,
        variable
      });
    }
  }
  return results;
}
__name(materializeGuardInputsWithMapping, "materializeGuardInputsWithMapping");
function formatGuardInputValue(value) {
  if (value === null || value === void 0) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return String(value);
  }
  if (typeof value === "object") {
    try {
      return JSON.stringify(value);
    } catch {
      return "[object]";
    }
  }
  return String(value);
}
__name(formatGuardInputValue, "formatGuardInputValue");
function applyDescriptorFromValue(value, target) {
  const descriptor = extractSecurityDescriptor(value, {
    recursive: true,
    mergeArrayElements: true
  }) ?? makeSecurityDescriptor();
  if (!target.mx) {
    target.mx = {};
  }
  updateVarMxFromDescriptor(target.mx, descriptor);
  if (target.mx.mxCache) {
    delete target.mx.mxCache;
  }
}
__name(applyDescriptorFromValue, "applyDescriptorFromValue");

// interpreter/eval/directive-replay.ts
var INLINE_SOURCE = {
  directive: "var",
  syntax: "expression",
  hasInterpolation: false,
  isMultiLine: false
};
var replayStore = /* @__PURE__ */ new WeakMap();
function getReplayState(directive) {
  let state = replayStore.get(directive);
  if (!state) {
    state = /* @__PURE__ */ new Map();
    replayStore.set(directive, state);
  }
  return state;
}
__name(getReplayState, "getReplayState");
async function ensureReplayEntry(directive, env, invocation) {
  const state = getReplayState(directive);
  const existing = state.get(invocation);
  if (existing) {
    return existing;
  }
  const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
  const result = await evaluateExecInvocation(invocation, env);
  const entry = {
    result
  };
  state.set(invocation, entry);
  return entry;
}
__name(ensureReplayEntry, "ensureReplayEntry");
function materializeGuardVariable(value) {
  if (isVariable(value)) {
    return value;
  }
  const fromProvenance = materializeExpressionValue(value, {
    name: "__inline_exec__"
  });
  if (fromProvenance) {
    return fromProvenance;
  }
  if (value && typeof value === "object") {
    const metadataSecurity = value.metadata?.security;
    if (metadataSecurity) {
      const textValue = typeof value.text === "string" ? value.text : typeof value.data === "string" ? value.data : String(value.data ?? value);
      return createSimpleTextVariable("__inline_exec__", textValue, INLINE_SOURCE, {
        security: metadataSecurity
      });
    }
  }
  return void 0;
}
__name(materializeGuardVariable, "materializeGuardVariable");
async function replayInlineExecInvocations(directive, env, invocations) {
  if (!invocations || invocations.length === 0) {
    return [];
  }
  const guardVariables = [];
  const unique = Array.from(new Set(invocations));
  for (const invocation of unique) {
    if (!invocation) {
      continue;
    }
    const entry = await ensureReplayEntry(directive, env, invocation);
    if (!entry.guardVariable) {
      entry.guardVariable = materializeGuardVariable(entry.result.value);
    }
    if (entry.guardVariable) {
      guardVariables.push(entry.guardVariable);
    }
  }
  return guardVariables;
}
__name(replayInlineExecInvocations, "replayInlineExecInvocations");
async function resolveDirectiveExecInvocation(directive, env, invocation) {
  const entry = await ensureReplayEntry(directive, env, invocation);
  return entry.result;
}
__name(resolveDirectiveExecInvocation, "resolveDirectiveExecInvocation");
function clearDirectiveReplay(directive) {
  replayStore.delete(directive);
}
__name(clearDirectiveReplay, "clearDirectiveReplay");

// interpreter/eval/directive-inputs.ts
async function extractDirectiveInputs(directive, env) {
  switch (directive.kind) {
    case "show":
      return extractShowInputs(directive, env);
    case "output":
      return extractOutputInputs(directive, env);
    case "append":
      return extractOutputInputs(directive, env);
    case "run":
      return extractRunInputs(directive, env);
    default:
      return [];
  }
}
__name(extractDirectiveInputs, "extractDirectiveInputs");
async function extractShowInputs(directive, env) {
  const inlineInvocations = [];
  const invocation = directive.values?.invocation;
  if (invocation?.type === "ExecInvocation") {
    inlineInvocations.push(invocation);
  }
  const execInvocation = directive.values?.execInvocation;
  if (execInvocation?.type === "ExecInvocation") {
    inlineInvocations.push(execInvocation);
  }
  if (inlineInvocations.length > 0) {
    const guardValues = [];
    guardValues.push(...await replayInlineExecInvocations(directive, env, inlineInvocations));
    for (const inv of inlineInvocations) {
      guardValues.push(...extractExecInvocationArgs(inv, env));
    }
    if (guardValues.length > 0) {
      return materializeGuardInputs(guardValues);
    }
  }
  const inputs = [];
  const varName = resolveShowVariableName(directive);
  if (!varName) {
    return inputs;
  }
  const variable = env.getVariable(varName);
  if (variable) {
    inputs.push(variable);
  }
  return materializeGuardInputs(inputs);
}
__name(extractShowInputs, "extractShowInputs");
function resolveShowVariableName(directive) {
  const invocation = directive.values?.invocation;
  if (invocation) {
    if (invocation.type === "VariableReference") {
      return invocation.identifier;
    }
    if (invocation.type === "VariableReferenceWithTail") {
      const innerVar = invocation.variable;
      if (!innerVar) {
        return void 0;
      }
      if (innerVar.type === "TemplateVariable") {
        return innerVar.identifier;
      }
      return innerVar.identifier;
    }
    if (invocation.type === "TemplateVariable") {
      return invocation.identifier;
    }
  }
  const legacyVariable = directive.values?.variable;
  if (!legacyVariable) {
    return void 0;
  }
  const variableNode = Array.isArray(legacyVariable) ? legacyVariable[0] : legacyVariable;
  if (!variableNode) {
    return void 0;
  }
  if (variableNode.type === "VariableReferenceWithTail") {
    const innerVar = variableNode.variable;
    if (innerVar?.type === "TemplateVariable") {
      return innerVar.identifier;
    }
    return innerVar?.identifier;
  }
  if (variableNode.type === "VariableReference") {
    return variableNode.identifier;
  }
  if (variableNode.type === "TemplateVariable") {
    return variableNode.identifier;
  }
  return void 0;
}
__name(resolveShowVariableName, "resolveShowVariableName");
async function extractOutputInputs(directive, env) {
  const sourceNode = directive.values?.source;
  if (!sourceNode) {
    return [];
  }
  const execInvocation = findExecInvocation(sourceNode);
  if (execInvocation) {
    const guardValues = [
      ...await replayInlineExecInvocations(directive, env, [
        execInvocation
      ]),
      ...extractExecInvocationArgs(execInvocation, env)
    ];
    if (guardValues.length > 0) {
      return materializeGuardInputs(guardValues);
    }
  }
  const hasArgs = Boolean(sourceNode.args && Array.isArray(sourceNode.args) && sourceNode.args.length > 0) || directive.subtype === "outputInvocation" || directive.subtype === "outputExecInvocation";
  if (hasArgs) {
    return [];
  }
  const varName = resolveOutputVariableName(sourceNode);
  if (!varName) {
    return [];
  }
  const variable = env.getVariable(varName);
  if (!variable) {
    return [];
  }
  return materializeGuardInputs([
    variable
  ]);
}
__name(extractOutputInputs, "extractOutputInputs");
function resolveOutputVariableName(sourceNode) {
  if (!sourceNode) {
    return void 0;
  }
  if (Array.isArray(sourceNode)) {
    const first = sourceNode[0];
    if (first?.type === "VariableReference") {
      return first.identifier;
    }
    if (first?.type === "TemplateVariable") {
      return first.identifier;
    }
  }
  if (sourceNode.identifier && Array.isArray(sourceNode.identifier)) {
    const first = sourceNode.identifier[0];
    if (first?.identifier) {
      return first.identifier;
    }
  }
  if (sourceNode.variable?.identifier) {
    return sourceNode.variable.identifier;
  }
  if (typeof sourceNode.identifier === "string") {
    return sourceNode.identifier;
  }
  return void 0;
}
__name(resolveOutputVariableName, "resolveOutputVariableName");
async function extractRunInputs(directive, env) {
  if (directive.subtype === "runCommand") {
    const commandNodes = directive.values?.identifier || directive.values?.command;
    if (!commandNodes) {
      return [];
    }
    const commandArray = Array.isArray(commandNodes) ? commandNodes : [
      commandNodes
    ];
    const interpolatedDescriptors = [];
    const commandText = await interpolate(commandArray, env, InterpolationContext.ShellCommand, {
      collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
        if (descriptor) {
          interpolatedDescriptors.push(descriptor);
        }
      }, "collectSecurityDescriptor")
    });
    const referencedVariables = collectVariablesFromNodes(commandArray, env);
    const referencedDescriptors = referencedVariables.map((variable2) => variable2.mx ? varMxToSecurityDescriptor(variable2.mx) : void 0).filter((descriptor) => Boolean(descriptor));
    const interpolationDescriptor = interpolatedDescriptors.length === 1 ? interpolatedDescriptors[0] : interpolatedDescriptors.length > 1 ? env.mergeSecurityDescriptors(...interpolatedDescriptors) : void 0;
    let mergedDescriptor = referencedDescriptors.length > 0 ? env.mergeSecurityDescriptors(...referencedDescriptors) : void 0;
    if (interpolationDescriptor) {
      mergedDescriptor = mergedDescriptor ? env.mergeSecurityDescriptors(mergedDescriptor, interpolationDescriptor) : interpolationDescriptor;
    }
    const source = {
      directive: "run",
      syntax: "command",
      hasInterpolation: true,
      isMultiLine: Array.isArray(commandNodes) && commandNodes.some((node) => node?.type === "Newline")
    };
    const variable = createSimpleTextVariable("__run_command__", commandText, source, {
      mx: mergedDescriptor || {},
      internal: {
        isSystem: true
      }
    });
    if (mergedDescriptor) {
      env.recordSecurityDescriptor(mergedDescriptor);
    }
    return [
      variable
    ];
  }
  if (directive.subtype === "runExec" || directive.subtype === "runExecInvocation" || directive.subtype === "runExecReference") {
    const execInvocation = directive.values?.execInvocation ?? directive.values?.execRef;
    if (execInvocation?.type === "ExecInvocation") {
      const guardValues = [
        ...await replayInlineExecInvocations(directive, env, [
          execInvocation
        ]),
        ...extractExecInvocationArgs(execInvocation, env)
      ];
      if (guardValues.length > 0) {
        return materializeGuardInputs(guardValues);
      }
    }
    const execName = resolveRunExecName(directive);
    if (!execName) {
      return [];
    }
    const execVar = env.getVariable(execName);
    return execVar ? materializeGuardInputs([
      execVar
    ]) : [];
  }
  return [];
}
__name(extractRunInputs, "extractRunInputs");
function resolveRunExecName(directive) {
  const identifierNodes = directive.values?.identifier;
  if (identifierNodes && Array.isArray(identifierNodes) && identifierNodes[0]) {
    const identifier = identifierNodes[0];
    if (identifier && typeof identifier === "object" && "identifier" in identifier) {
      return identifier.identifier;
    }
  }
  const execInvocation = directive.values?.execInvocation;
  if (execInvocation?.commandRef?.identifier) {
    return execInvocation.commandRef.identifier;
  }
  const execRef = directive.values?.execRef;
  if (execRef?.commandRef?.identifier) {
    return execRef.commandRef.identifier;
  }
  return void 0;
}
__name(resolveRunExecName, "resolveRunExecName");
function extractExecInvocationArgs(invocation, env) {
  const args = invocation.commandRef?.args ?? [];
  return collectVariablesFromNodes(args, env);
}
__name(extractExecInvocationArgs, "extractExecInvocationArgs");
function collectVariablesFromNodes(nodes, env) {
  const bucket = /* @__PURE__ */ new Map();
  const seen = /* @__PURE__ */ new WeakSet();
  for (const node of nodes) {
    visitNodeForVariables(node, env, bucket, seen);
  }
  return Array.from(bucket.values());
}
__name(collectVariablesFromNodes, "collectVariablesFromNodes");
function findExecInvocation(candidate) {
  if (!candidate || typeof candidate !== "object") {
    return void 0;
  }
  const typed = candidate;
  if (typed.type === "ExecInvocation") {
    return typed;
  }
  for (const value of Object.values(typed)) {
    if (Array.isArray(value)) {
      for (const entry of value) {
        const found = findExecInvocation(entry);
        if (found) {
          return found;
        }
      }
      continue;
    }
    if (value && typeof value === "object") {
      const found = findExecInvocation(value);
      if (found) {
        return found;
      }
    }
  }
  return void 0;
}
__name(findExecInvocation, "findExecInvocation");
function visitNodeForVariables(node, env, bucket, seen) {
  if (!node || typeof node !== "object") {
    return;
  }
  if (seen.has(node)) {
    return;
  }
  seen.add(node);
  switch (node.type) {
    case "VariableReference":
      addVariableByIdentifier(node.identifier, env, bucket);
      break;
    case "VariableReferenceWithTail":
      visitNodeForVariables(node.variable, env, bucket, seen);
      break;
    case "TemplateVariable":
      addVariableByIdentifier(node.identifier, env, bucket);
      break;
    case "ExecInvocation": {
      const commandRef = node.commandRef;
      if (commandRef?.objectReference) {
        visitNodeForVariables(commandRef.objectReference, env, bucket, seen);
      }
      const execArgs = commandRef?.args ?? [];
      for (const arg of execArgs) {
        visitNodeForVariables(arg, env, bucket, seen);
      }
      break;
    }
  }
  for (const value of Object.values(node)) {
    if (Array.isArray(value)) {
      for (const entry of value) {
        visitNodeForVariables(entry, env, bucket, seen);
      }
      continue;
    }
    if (value && typeof value === "object") {
      visitNodeForVariables(value, env, bucket, seen);
    }
  }
}
__name(visitNodeForVariables, "visitNodeForVariables");
function addVariableByIdentifier(identifier, env, bucket) {
  if (typeof identifier !== "string" || bucket.has(identifier)) {
    return;
  }
  const variable = env.getVariable(identifier);
  if (!variable) {
    return;
  }
  VariableMetadataUtils.attachContext(variable);
  bucket.set(identifier, variable);
}
__name(addVariableByIdentifier, "addVariableByIdentifier");

// core/types/hooks.ts
function isDirectiveHookTarget(node) {
  return node.kind !== void 0;
}
__name(isDirectiveHookTarget, "isDirectiveHookTarget");
function isExecHookTarget(node) {
  return node.type === "ExecInvocation";
}
__name(isExecHookTarget, "isExecHookTarget");
function isEffectHookTarget(node) {
  return node.type === "Effect";
}
__name(isEffectHookTarget, "isEffectHookTarget");

// interpreter/hooks/hook-decision-handler.ts
var DEFAULT_GUARD_MAX = 3;
var afterRetryDebugEnabled = process.env.DEBUG_AFTER_RETRY === "1";
async function handleGuardDecision(decision, node, env, operationContext) {
  if (!decision || decision.action === "continue") {
    return;
  }
  const metadata = decision.metadata ?? {};
  const guardName = typeof metadata.guardName === "string" || metadata.guardName === null ? metadata.guardName : null;
  const reasonsArray = Array.isArray(metadata.reasons) ? metadata.reasons : void 0;
  const guardResults = Array.isArray(metadata.guardResults) ? metadata.guardResults : void 0;
  const hints = Array.isArray(metadata.hints) ? metadata.hints : void 0;
  const guardContextSnapshot = buildGuardContextFromMetadata(metadata, reasonsArray, guardResults, hints);
  const primaryReason = (typeof metadata.reason === "string" ? metadata.reason : void 0) ?? (reasonsArray && reasonsArray.length > 0 ? reasonsArray[0] : void 0);
  const info = {
    guardName,
    guardFilter: typeof metadata.guardFilter === "string" ? metadata.guardFilter : void 0,
    scope: metadata.scope,
    inputPreview: typeof metadata.inputPreview === "string" ? metadata.inputPreview : void 0,
    retryHint: typeof metadata.hint === "string" ? metadata.hint : void 0,
    baseMessage: primaryReason && primaryReason.length > 0 ? primaryReason : decision.action === "abort" || decision.action === "deny" ? "Operation aborted by guard" : "Guard requested retry",
    guardContext: guardContextSnapshot,
    guardInput: metadata.guardInput
  };
  if (decision.action === "abort" || decision.action === "deny") {
    throw new GuardError({
      decision: "deny",
      guardName: info.guardName,
      guardFilter: info.guardFilter,
      scope: info.scope,
      inputPreview: info.inputPreview ?? null,
      retryHint: info.retryHint,
      operation: operationContext,
      reason: info.baseMessage,
      guardContext: info.guardContext,
      guardInput: info.guardInput ?? null,
      reasons: reasonsArray,
      guardResults,
      hints,
      sourceLocation: extractNodeLocation(node),
      env
    });
  }
  if (decision.action === "retry") {
    enforcePipelineGuardRetry(info, env, operationContext, node, {
      reasons: reasonsArray,
      guardResults,
      hints
    });
  }
}
__name(handleGuardDecision, "handleGuardDecision");
function getGuardTransformedInputs(decision, originalInputs) {
  if (!decision?.metadata) {
    return void 0;
  }
  const candidates = decision.metadata.transformedInputs;
  if (!Array.isArray(candidates)) {
    return void 0;
  }
  const variables = candidates.filter(isVariable);
  if (variables.length !== candidates.length) {
    return void 0;
  }
  if (!originalInputs || originalInputs.length === 0) {
    return variables;
  }
  return alignTransformedInputs(variables, originalInputs);
}
__name(getGuardTransformedInputs, "getGuardTransformedInputs");
function enforcePipelineGuardRetry(info, env, operationContext, node, extras) {
  const pipelineContext = env.getPipelineContext();
  if (!pipelineContext) {
    throw new GuardError({
      decision: "deny",
      guardName: info.guardName,
      guardFilter: info.guardFilter,
      scope: info.scope,
      inputPreview: info.inputPreview ?? null,
      retryHint: info.retryHint,
      operation: operationContext,
      guardContext: info.guardContext,
      guardInput: info.guardInput ?? null,
      reasons: extras?.reasons,
      guardResults: extras?.guardResults,
      hints: extras?.hints,
      reason: "guard retry requires pipeline context (non-pipeline retry deferred to Phase 7.3)",
      sourceLocation: extractNodeLocation(node),
      env
    });
  }
  if (!canRetryWithinPipeline(pipelineContext)) {
    if (afterRetryDebugEnabled) {
      try {
        console.error("[after-guard-retry] pipeline retry denied (non-retryable source)", {
          guardName: info.guardName,
          guardFilter: info.guardFilter,
          operation: {
            type: operationContext.type,
            subtype: operationContext.subtype,
            name: operationContext.name
          },
          retryHint: info.retryHint
        });
      } catch {
      }
    }
    throw new GuardError({
      decision: "deny",
      guardName: info.guardName,
      guardFilter: info.guardFilter,
      scope: info.scope,
      inputPreview: info.inputPreview ?? null,
      retryHint: info.retryHint,
      operation: operationContext,
      guardContext: info.guardContext,
      guardInput: info.guardInput ?? null,
      reasons: extras?.reasons,
      guardResults: extras?.guardResults,
      hints: extras?.hints,
      reason: `Cannot retry: ${info.retryHint ?? "guard requested retry"} (source not retryable)`,
      sourceLocation: extractNodeLocation(node),
      env
    });
  }
  throw new GuardRetrySignal({
    decision: "retry",
    guardName: info.guardName,
    guardFilter: info.guardFilter,
    scope: info.scope,
    inputPreview: info.inputPreview ?? null,
    retryHint: info.retryHint,
    operation: operationContext,
    guardContext: info.guardContext,
    guardInput: info.guardInput ?? null,
    reasons: extras?.reasons,
    guardResults: extras?.guardResults,
    hints: extras?.hints,
    reason: info.baseMessage,
    sourceLocation: extractNodeLocation(node),
    env
  });
}
__name(enforcePipelineGuardRetry, "enforcePipelineGuardRetry");
function canRetryWithinPipeline(context2) {
  if (!context2.sourceRetryable) {
    return false;
  }
  return true;
}
__name(canRetryWithinPipeline, "canRetryWithinPipeline");
function buildGuardContextFromMetadata(metadata, reasons, guardResults, hints) {
  const baseContext = metadata.guardContext ?? {};
  const trace = guardResults ?? (Array.isArray(baseContext.trace) ? baseContext.trace : []);
  const hintList = hints ?? (Array.isArray(baseContext.hints) ? baseContext.hints : []);
  const reasonList = reasons ?? (Array.isArray(baseContext.reasons) ? baseContext.reasons : []);
  const attempt = typeof baseContext.attempt === "number" ? baseContext.attempt : typeof baseContext.try === "number" ? baseContext.try ?? 0 : 0;
  const max = typeof baseContext.max === "number" ? baseContext.max : DEFAULT_GUARD_MAX;
  const resolvedReason = baseContext.reason ?? (typeof metadata.reason === "string" ? metadata.reason : void 0) ?? reasonList[0] ?? null;
  return {
    ...baseContext,
    trace,
    hints: hintList,
    reasons: reasonList,
    reason: resolvedReason,
    attempt,
    try: typeof baseContext.try === "number" ? baseContext.try : attempt,
    max
  };
}
__name(buildGuardContextFromMetadata, "buildGuardContextFromMetadata");
function extractNodeLocation(node) {
  if (isDirectiveHookTarget(node)) {
    return node.location ?? null;
  }
  return node.location ?? null;
}
__name(extractNodeLocation, "extractNodeLocation");
function alignTransformedInputs(transformed, originals) {
  const aligned = [];
  const limit = Math.min(transformed.length, originals.length);
  for (let i = 0; i < limit; i++) {
    const replacement = transformed[i];
    const original = originals[i];
    if (isVariable(original) && original.name !== replacement.name) {
      const cloned = {
        ...replacement,
        name: original.name,
        mx: replacement.mx ? {
          ...replacement.mx
        } : void 0,
        internal: replacement.internal ? {
          ...replacement.internal
        } : void 0
      };
      if (cloned.mx?.mxCache) {
        delete cloned.mx.mxCache;
      }
      aligned.push(cloned);
    } else {
      aligned.push(replacement);
    }
  }
  for (let i = limit; i < transformed.length; i++) {
    aligned.push(transformed[i]);
  }
  return aligned;
}
__name(alignTransformedInputs, "alignTransformedInputs");

// interpreter/eval/path.ts
async function evaluatePath(directive, env) {
  const identifierNodes = directive.values?.identifier;
  if (!identifierNodes || !Array.isArray(identifierNodes) || identifierNodes.length === 0) {
    throw new Error("Path directive missing identifier");
  }
  const identifierNode = identifierNodes[0];
  let identifier;
  if (identifierNode.type === "Text" && "content" in identifierNode) {
    identifier = identifierNode.content;
  } else if (identifierNode.type === "VariableReference" && "identifier" in identifierNode) {
    identifier = identifierNode.identifier;
  } else {
    throw new Error("Path directive identifier must be a simple variable name");
  }
  const pathNodes = directive.values?.path;
  if (!pathNodes) {
    throw new Error("Path directive missing path");
  }
  const pathNode = pathNodes[0];
  const isURL = pathNode?.subtype === "urlPath" || pathNode?.subtype === "urlSectionPath";
  const descriptors = [];
  const interpolatedPath = await interpolate(pathNodes, env, void 0, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  const merged = descriptors.length === 1 ? descriptors[0] : descriptors.length > 1 ? env.mergeSecurityDescriptors(...descriptors) : void 0;
  if (merged) {
    env.recordSecurityDescriptor(merged);
  }
  let resolvedPath = interpolatedPath;
  const resolverManager = env.getResolverManager();
  if (resolverManager && interpolatedPath.startsWith("@")) {
    const pathParts = interpolatedPath.substring(1).split("/");
    const potentialResolver = pathParts[0];
    if (resolverManager.isResolverName(potentialResolver)) {
      try {
        const resolverContent = await env.resolveModule(interpolatedPath, "path");
        if (resolverContent.contentType === "module") {
          throw new Error(`Cannot use module as path: ${interpolatedPath} (modules must be imported, not used as paths)`);
        }
        resolvedPath = resolverContent.content;
      } catch (error) {
        if (error.message?.includes("Cannot use module as path")) {
          throw error;
        }
        resolvedPath = await env.resolvePath(interpolatedPath);
      }
    } else {
      resolvedPath = await env.resolvePath(interpolatedPath);
    }
  } else if (isURL || env.isURL(interpolatedPath)) {
    resolvedPath = interpolatedPath;
  } else {
    if (interpolatedPath.startsWith("@PROJECTPATH") || interpolatedPath.startsWith("/")) {
      resolvedPath = await env.resolvePath(interpolatedPath);
    }
    resolvedPath = resolvedPath.replace(/^\.\//, "");
  }
  const source = {
    directive: "var",
    syntax: "path",
    hasInterpolation: false,
    isMultiLine: false
  };
  const location = astLocationToSourceLocation(directive.location, env.getCurrentFilePath());
  const variable = createPathVariable(identifier, resolvedPath, interpolatedPath, isURL || env.isURL(resolvedPath), resolvedPath.startsWith("/"), source, {
    definedAt: location
  });
  env.setVariable(identifier, variable);
  return {
    value: resolvedPath,
    env
  };
}
__name(evaluatePath, "evaluatePath");

// core/security/taint.ts
function dedupe(values) {
  const seen = /* @__PURE__ */ new Set();
  for (const value of values) {
    if (!seen.has(value)) {
      seen.add(value);
    }
  }
  return Array.from(seen);
}
__name(dedupe, "dedupe");
function freezeArray(values) {
  const array = values ? dedupe(values) : [];
  return Object.freeze(array.slice());
}
__name(freezeArray, "freezeArray");
var _TaintTracker = class _TaintTracker {
  constructor() {
    __publicField(this, "entries", /* @__PURE__ */ new Map());
  }
  track(id, options) {
    const existing = this.entries.get(id);
    const mergedSources = freezeArray([
      ...existing?.sources ?? [],
      ...options?.sources ?? []
    ]);
    const mergedLabels = freezeArray([
      ...existing?.labels ?? [],
      ...options?.labels ?? []
    ]);
    const mergedTaint = freezeArray([
      ...existing?.taint ?? [],
      ...mergedLabels,
      ...options?.taint ?? []
    ]);
    const snapshot = Object.freeze({
      sources: mergedSources,
      labels: mergedLabels,
      taint: mergedTaint
    });
    this.entries.set(id, snapshot);
    return snapshot;
  }
  get(id) {
    return this.entries.get(id);
  }
  merge(id, ...snapshots) {
    const incoming = snapshots.filter((snapshot2) => Boolean(snapshot2));
    const existing = this.entries.get(id);
    if (!existing && incoming.length === 0) {
      const defaultSnapshot = Object.freeze({
        sources: Object.freeze([]),
        labels: Object.freeze([]),
        taint: Object.freeze([])
      });
      this.entries.set(id, defaultSnapshot);
      return defaultSnapshot;
    }
    const sources = freezeArray([
      ...existing?.sources ?? [],
      ...incoming.flatMap((snapshot2) => snapshot2.sources)
    ]);
    const labels = freezeArray([
      ...existing?.labels ?? [],
      ...incoming.flatMap((snapshot2) => snapshot2.labels)
    ]);
    const taint = freezeArray([
      ...existing?.taint ?? [],
      ...incoming.flatMap((snapshot2) => snapshot2.taint),
      ...labels
    ]);
    const snapshot = Object.freeze({
      sources,
      labels,
      taint
    });
    this.entries.set(id, snapshot);
    return snapshot;
  }
  clear() {
    this.entries.clear();
  }
};
__name(_TaintTracker, "TaintTracker");
var TaintTracker = _TaintTracker;
function isUrlLike(value) {
  return /^https?:\/\//i.test(value);
}
__name(isUrlLike, "isUrlLike");
function shouldTreatAsFile(options, resolvedPath) {
  if (!resolvedPath) {
    return false;
  }
  if (options.sourceType === "url" || options.importType === "cached") {
    return false;
  }
  if (options.sourceType === "module" || options.sourceType === "input") {
    return false;
  }
  if (isUrlLike(resolvedPath)) {
    return false;
  }
  if (resolvedPath.startsWith("@")) {
    return false;
  }
  return true;
}
__name(shouldTreatAsFile, "shouldTreatAsFile");
function deriveImportTaint(options) {
  const resolverName = options.resolverName?.toLowerCase();
  const resolvedPath = options.resolvedPath ?? options.source;
  const dirLabels = resolvedPath && shouldTreatAsFile(options, resolvedPath) ? labelsForPath(resolvedPath) : [];
  const sources = freezeArray([
    ...resolverName === "dynamic" ? [
      "dynamic-module"
    ] : [],
    ...options.source ? [
      options.source
    ] : resolverName ? [
      `resolver:${resolverName}`
    ] : []
  ]);
  const explicitLabels = freezeArray(options.labels);
  const taint = freezeArray([
    ...explicitLabels,
    ...resolverName === "dynamic" ? [
      "src:dynamic"
    ] : [],
    ...dirLabels.length > 0 ? [
      "src:file",
      ...dirLabels
    ] : []
  ]);
  return Object.freeze({
    sources,
    labels: explicitLabels,
    taint
  });
}
__name(deriveImportTaint, "deriveImportTaint");
function deriveCommandTaint(options) {
  const baseCommand = options.command.trim().split(/\s+/)[0] ?? "";
  const sources = freezeArray([
    options.source ? options.source : `command:${baseCommand}`
  ]);
  const taint = freezeArray([
    "src:exec"
  ]);
  return Object.freeze({
    sources,
    labels: Object.freeze([]),
    taint
  });
}
__name(deriveCommandTaint, "deriveCommandTaint");

// interpreter/streaming/adapter-registry.ts
var BUILTIN_ADAPTERS = {
  "claude-code": /* @__PURE__ */ __name(async () => {
    const { createClaudeCodeAdapter } = await import('./claude-code-QRQD7JJP.mjs');
    return createClaudeCodeAdapter();
  }, "claude-code"),
  "claude-agent-sdk": /* @__PURE__ */ __name(async () => {
    const { createClaudeCodeAdapter } = await import('./claude-code-QRQD7JJP.mjs');
    return createClaudeCodeAdapter();
  }, "claude-agent-sdk"),
  "@mlld/claude-agent-sdk": /* @__PURE__ */ __name(async () => {
    const { createClaudeCodeAdapter } = await import('./claude-code-QRQD7JJP.mjs');
    return createClaudeCodeAdapter();
  }, "@mlld/claude-agent-sdk"),
  "anthropic": /* @__PURE__ */ __name(async () => {
    const { createClaudeCodeAdapter } = await import('./claude-code-QRQD7JJP.mjs');
    return createClaudeCodeAdapter();
  }, "anthropic"),
  "ndjson": /* @__PURE__ */ __name(async () => {
    return createNDJSONAdapter({
      name: "generic-ndjson",
      schemas: [
        {
          kind: "message",
          matchPath: "type",
          matchValue: "text",
          extract: {
            chunk: [
              "text",
              "content",
              "message",
              "data"
            ]
          }
        }
      ]
    });
  }, "ndjson")
};
var _AdapterRegistry = class _AdapterRegistry {
  constructor() {
    __publicField(this, "customAdapters", /* @__PURE__ */ new Map());
    __publicField(this, "adapterCache", /* @__PURE__ */ new Map());
  }
  /**
  * Register a custom adapter.
  */
  register(name, entry) {
    this.customAdapters.set(name, {
      name,
      ...entry
    });
    this.adapterCache.delete(name);
  }
  /**
  * Register an adapter from a configuration object.
  */
  registerConfig(config) {
    this.register(config.name, {
      version: "1.0.0",
      description: `Custom adapter: ${config.name}`,
      factory: /* @__PURE__ */ __name(() => createNDJSONAdapter(config), "factory")
    });
  }
  /**
  * Get an adapter by name.
  * Returns a cached instance if available.
  */
  async get(name) {
    if (this.adapterCache.has(name)) {
      return this.adapterCache.get(name);
    }
    if (this.customAdapters.has(name)) {
      const entry = this.customAdapters.get(name);
      const adapter = entry.factory();
      this.adapterCache.set(name, adapter);
      return adapter;
    }
    if (name in BUILTIN_ADAPTERS) {
      const factory = BUILTIN_ADAPTERS[name];
      const adapter = await factory();
      this.adapterCache.set(name, adapter);
      return adapter;
    }
    return void 0;
  }
  /**
  * Get a builtin adapter by name (synchronous).
  * Only works if the adapter has been loaded previously.
  */
  getCached(name) {
    return this.adapterCache.get(name);
  }
  /**
  * Check if an adapter exists (builtin or custom).
  */
  has(name) {
    return this.customAdapters.has(name) || name in BUILTIN_ADAPTERS;
  }
  /**
  * Get list of all available adapter names.
  */
  list() {
    const builtins = Object.keys(BUILTIN_ADAPTERS);
    const custom = Array.from(this.customAdapters.keys());
    return [
      .../* @__PURE__ */ new Set([
        ...builtins,
        ...custom
      ])
    ];
  }
  /**
  * Get information about an adapter.
  */
  getInfo(name) {
    if (this.customAdapters.has(name)) {
      return this.customAdapters.get(name);
    }
    if (name in BUILTIN_ADAPTERS) {
      return {
        name,
        version: "1.0.0",
        description: `Builtin adapter for ${name} streaming format`,
        factory: /* @__PURE__ */ __name(() => {
          throw new Error("Use get() for builtin adapters");
        }, "factory")
      };
    }
    return void 0;
  }
  /**
  * Clear the adapter cache.
  */
  clearCache() {
    this.adapterCache.clear();
  }
  /**
  * Unregister a custom adapter.
  */
  unregister(name) {
    this.adapterCache.delete(name);
    return this.customAdapters.delete(name);
  }
};
__name(_AdapterRegistry, "AdapterRegistry");
var AdapterRegistry = _AdapterRegistry;
var adapterRegistry = new AdapterRegistry();
async function getAdapter(name) {
  return adapterRegistry.get(name);
}
__name(getAdapter, "getAdapter");

// interpreter/streaming/stream-format.ts
function isStreamAdapter(value) {
  return Boolean(value && typeof value === "object" && typeof value.processChunk === "function" && typeof value.flush === "function");
}
__name(isStreamAdapter, "isStreamAdapter");
function isAdapterConfig(value) {
  return Boolean(value && typeof value === "object" && Array.isArray(value.schemas));
}
__name(isAdapterConfig, "isAdapterConfig");
async function resolveStreamFormatValue(source, env) {
  if (source === void 0 || source === null) {
    return source;
  }
  let value = source;
  if (typeof value === "object" && value !== null && (value.type || Array.isArray(value))) {
    const { evaluate: evaluate3 } = await import('./interpreter-MW7QI3FC.mjs');
    const result = await evaluate3(value, env, {
      isExpression: true
    });
    value = result.value;
  }
  const { isVariable: isVariable2, resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
  if (isVariable2(value)) {
    value = await resolveValue(value, env, ResolutionContext.Display);
  }
  return value;
}
__name(resolveStreamFormatValue, "resolveStreamFormatValue");
async function loadStreamAdapter(value) {
  if (!value) {
    return void 0;
  }
  if (typeof value === "string") {
    return getAdapter(value);
  }
  if (isStreamAdapter(value)) {
    return value;
  }
  if (isAdapterConfig(value)) {
    const config = {
      name: typeof value.name === "string" ? value.name : "custom-stream-adapter",
      format: "ndjson",
      schemas: value.schemas,
      defaultSchema: value.defaultSchema
    };
    return createNDJSONAdapter(config);
  }
  return void 0;
}
__name(loadStreamAdapter, "loadStreamAdapter");

// interpreter/utils/structured-exec.ts
function wrapExecResult(value, options) {
  if (isStructuredValue(value)) {
    if (options?.type || options?.text) {
      return ensureStructuredValue(value, options?.type, options?.text);
    }
    return value;
  }
  return ensureStructuredValue(value, options?.type, options?.text);
}
__name(wrapExecResult, "wrapExecResult");
function wrapPipelineResult(value, options) {
  return wrapExecResult(value, options);
}
__name(wrapPipelineResult, "wrapPipelineResult");

// interpreter/utils/shell-value.ts
function classifyShellValue(value) {
  if (value === void 0) {
    return {
      kind: "simple",
      text: ""
    };
  }
  if (value === null) {
    return {
      kind: "simple",
      text: "null"
    };
  }
  if (typeof value === "string") {
    if (looksLikeStructuredString(value)) {
      return {
        kind: "complex",
        text: value
      };
    }
    return {
      kind: "simple",
      text: value
    };
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return {
      kind: "simple",
      text: String(value)
    };
  }
  if (Buffer.isBuffer(value)) {
    return {
      kind: "simple",
      text: value.toString("utf8")
    };
  }
  if (isStructuredValue(value)) {
    return classifyStructuredValue(value);
  }
  if (isLoadContentResult(value)) {
    return {
      kind: "complex",
      text: asText(value)
    };
  }
  if (isStructuredValue(value) && value.type === "array") {
    const arrayType = value.mx?.arrayType;
    if (arrayType === "renamed-content") {
      const data = value.data;
      const elements = data.map((item) => String(item ?? ""));
      return {
        kind: "array-simple",
        elements
      };
    }
    return {
      kind: "complex",
      text: value.text
    };
  }
  if (Array.isArray(value)) {
    return classifyArray(value);
  }
  if (typeof value === "object") {
    return {
      kind: "complex",
      text: JSONFormatter.stringify(normalizeForJson(value))
    };
  }
  return {
    kind: "simple",
    text: String(value)
  };
}
__name(classifyShellValue, "classifyShellValue");
function coerceValueForStdin(value) {
  const classification = classifyShellValue(value);
  if (classification.kind === "simple") {
    return classification.text;
  }
  if (classification.kind === "array-simple") {
    return classification.elements.join("\n");
  }
  return classification.text;
}
__name(coerceValueForStdin, "coerceValueForStdin");
function classifyStructuredValue(value) {
  const data = value.data;
  if (Array.isArray(data)) {
    return classifyArray(data);
  }
  if (data && typeof data === "object") {
    return {
      kind: "complex",
      text: JSONFormatter.stringify(normalizeForJson(data))
    };
  }
  return {
    kind: "simple",
    text: asText(value)
  };
}
__name(classifyStructuredValue, "classifyStructuredValue");
function classifyArray(array) {
  if (array.length === 0) {
    return {
      kind: "array-simple",
      elements: []
    };
  }
  const elements = [];
  for (const item of array) {
    const classification = classifyShellValue(item);
    if (classification.kind === "simple") {
      elements.push(classification.text);
      continue;
    }
    return {
      kind: "complex",
      text: JSONFormatter.stringify(normalizeForJson(array))
    };
  }
  return {
    kind: "array-simple",
    elements
  };
}
__name(classifyArray, "classifyArray");
function normalizeForJson(value) {
  if (isStructuredValue(value)) {
    return normalizeForJson(asData(value));
  }
  if (isLoadContentResult(value)) {
    try {
      if (value.json !== void 0) {
        return value.json;
      }
    } catch {
    }
    try {
      return JSON.parse(asText(value));
    } catch {
      return asText(value);
    }
  }
  if (isStructuredValue(value) && value.type === "array") {
    const data = value.data;
    return data.map((item) => normalizeForJson(item));
  }
  if (Array.isArray(value)) {
    return value.map((item) => normalizeForJson(item));
  }
  if (typeof value === "bigint") {
    return value.toString();
  }
  if (value && typeof value === "object") {
    const entries = Object.entries(value).map(([key, val]) => [
      key,
      normalizeForJson(val)
    ]);
    return Object.fromEntries(entries);
  }
  return value;
}
__name(normalizeForJson, "normalizeForJson");
function looksLikeStructuredString(value) {
  const trimmed = value.trim();
  if (trimmed.length < 2) {
    return false;
  }
  const first = trimmed[0];
  const last = trimmed[trimmed.length - 1];
  if (!(first === "[" && last === "]" || first === "{" && last === "}")) {
    return false;
  }
  const inner = trimmed.slice(1, -1);
  return /[{}\[\]:,]/.test(inner);
}
__name(looksLikeStructuredString, "looksLikeStructuredString");
function createWorkingDirError(message, workingDirectory, env, options) {
  return new MlldError(message, {
    code: "INVALID_WORKING_DIRECTORY",
    severity: ErrorSeverity.Recoverable,
    sourceLocation: options.sourceLocation,
    env,
    details: {
      workingDirectory,
      directiveType: options.directiveType
    }
  });
}
__name(createWorkingDirError, "createWorkingDirError");
async function resolveWorkingDirectory(workingDir, env, options = {}) {
  if (!workingDir || Array.isArray(workingDir) && workingDir.length === 0) {
    return void 0;
  }
  const rawPath = typeof workingDir === "string" ? workingDir : await interpolate(workingDir, env, InterpolationContext.FilePath);
  const candidate = rawPath.trim();
  if (!candidate || candidate === ".") {
    return void 0;
  }
  if (candidate.startsWith("~")) {
    throw createWorkingDirError('Working directory cannot use "~" expansion.', candidate, env, options);
  }
  if (/^[a-zA-Z]:[\\/]/.test(candidate) || candidate.startsWith("\\\\")) {
    throw createWorkingDirError("Working directory must use absolute Unix-style paths.", candidate, env, options);
  }
  if (!path7__default.posix.isAbsolute(candidate)) {
    throw createWorkingDirError('Working directory must start with "/".', candidate, env, options);
  }
  const normalized = path7__default.posix.normalize(candidate);
  const fs5 = env.getFileSystemService();
  if (!await fs5.exists(normalized)) {
    throw createWorkingDirError("Working directory does not exist.", normalized, env, options);
  }
  const isDirectory = await fs5.isDirectory(normalized);
  if (!isDirectory) {
    throw createWorkingDirError("Working directory must be a directory.", normalized, env, options);
  }
  return normalized;
}
__name(resolveWorkingDirectory, "resolveWorkingDirectory");

// interpreter/eval/run.ts
function extractRawTextContent(nodes) {
  const parts = [];
  for (const node of nodes) {
    if (node.type === "Text") {
      parts.push(node.content || "");
    } else if (node.type === "Newline") {
      parts.push("\n");
    } else {
      parts.push(String(node.value || node.content || ""));
    }
  }
  const rawContent = parts.join("");
  return rawContent.replace(/^\n/, "");
}
__name(extractRawTextContent, "extractRawTextContent");
function dedentCommonIndent(src) {
  const lines = src.replace(/\r\n/g, "\n").split("\n");
  let minIndent = null;
  for (const line of lines) {
    if (line.trim().length === 0) continue;
    const match = line.match(/^[ \t]*/);
    const indent = match ? match[0].length : 0;
    if (minIndent === null || indent < minIndent) minIndent = indent;
    if (minIndent === 0) break;
  }
  if (!minIndent) return src;
  return lines.map((l) => l.trim().length === 0 ? "" : l.slice(minIndent)).join("\n");
}
__name(dedentCommonIndent, "dedentCommonIndent");
async function resolveStdinInput(stdinSource, env) {
  if (stdinSource === null || stdinSource === void 0) {
    return "";
  }
  const result = await evaluate2(stdinSource, env, {
    isExpression: true
  });
  let value = result.value;
  if (process.env.MLLD_DEBUG_STDIN === "true") {
    try {
      console.error("[mlld] stdin evaluate result", JSON.stringify(value));
    } catch {
      console.error("[mlld] stdin evaluate result", value);
    }
  }
  const { isVariable: isVariable2, resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
  if (isVariable2(value)) {
    value = await resolveValue(value, env, ResolutionContext.CommandExecution);
    if (process.env.MLLD_DEBUG_STDIN === "true") {
      try {
        console.error("[mlld] stdin resolved variable", JSON.stringify(value));
      } catch {
        console.error("[mlld] stdin resolved variable", value);
      }
    }
  }
  return coerceValueForStdin(value);
}
__name(resolveStdinInput, "resolveStdinInput");
async function evaluateRun(directive, env, callStack = [], context2) {
  if (env.getIsImporting()) {
    return {
      value: null,
      env
    };
  }
  let outputValue;
  let outputText;
  let pendingOutputDescriptor;
  let lastOutputDescriptor;
  const mergePendingDescriptor = /* @__PURE__ */ __name((descriptor) => {
    if (!descriptor) {
      return;
    }
    pendingOutputDescriptor = pendingOutputDescriptor ? env.mergeSecurityDescriptors(pendingOutputDescriptor, descriptor) : descriptor;
  }, "mergePendingDescriptor");
  const interpolateWithPendingDescriptor = /* @__PURE__ */ __name(async (nodes, interpolationContext = InterpolationContext.Default, targetEnv = env) => {
    return interpolate(nodes, targetEnv, interpolationContext, {
      collectSecurityDescriptor: mergePendingDescriptor
    });
  }, "interpolateWithPendingDescriptor");
  const setOutput = /* @__PURE__ */ __name((value) => {
    const wrapped = wrapExecResult(value);
    if (pendingOutputDescriptor) {
      const existingDescriptor = wrapped.mx && hasSecurityVarMx(wrapped.mx) ? varMxToSecurityDescriptor(wrapped.mx) : void 0;
      const descriptor = existingDescriptor ? env.mergeSecurityDescriptors(existingDescriptor, pendingOutputDescriptor) : pendingOutputDescriptor;
      applySecurityDescriptorToStructuredValue(wrapped, descriptor);
      lastOutputDescriptor = descriptor;
      pendingOutputDescriptor = void 0;
    } else {
      lastOutputDescriptor = void 0;
    }
    outputValue = wrapped;
    outputText = asText(wrapped);
  }, "setOutput");
  setOutput("");
  let sourceNodeForPipeline;
  let withClause = directive.meta?.withClause || directive.values?.withClause;
  if (process.env.MLLD_DEBUG_STDIN === "true") {
    try {
      console.error("[mlld] directive meta withClause", JSON.stringify(directive.meta?.withClause));
      console.error("[mlld] directive values withClause", JSON.stringify(directive.values?.withClause));
    } catch {
      console.error("[mlld] directive meta withClause", directive.meta?.withClause);
      console.error("[mlld] directive values withClause", directive.values?.withClause);
    }
  }
  const streamingOptions = env.getStreamingOptions();
  const streamingRequested = Boolean(withClause && withClause.stream);
  const streamingEnabled = streamingOptions.enabled !== false && streamingRequested;
  const pipelineId = `run-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e4)}`;
  const hasStreamFormat = withClause && withClause.streamFormat !== void 0;
  const rawStreamFormat = hasStreamFormat ? withClause.streamFormat : void 0;
  const streamFormatValue = hasStreamFormat ? await resolveStreamFormatValue(rawStreamFormat, env) : void 0;
  if (hasStreamFormat) {
    env.setStreamingOptions({
      ...streamingOptions,
      streamFormat: streamFormatValue,
      skipDefaultSinks: true,
      suppressTerminal: true
    });
  }
  const activeStreamingOptions = env.getStreamingOptions();
  if (process.env.MLLD_DEBUG) {
    console.error("[FormatAdapter /run] streamingEnabled:", streamingEnabled);
    console.error("[FormatAdapter /run] hasStreamFormat:", hasStreamFormat);
    console.error("[FormatAdapter /run] streamFormatValue:", streamFormatValue);
    console.error("[FormatAdapter /run] withClause:", JSON.stringify(withClause));
  }
  const streamingManager = env.getStreamingManager();
  if (streamingEnabled) {
    let adapter;
    if (hasStreamFormat && streamFormatValue) {
      adapter = await loadStreamAdapter(streamFormatValue);
      if (!adapter) {
        adapter = await getAdapter("ndjson");
      }
    }
    streamingManager.configure({
      env,
      streamingEnabled: true,
      streamingOptions: activeStreamingOptions,
      adapter
    });
  }
  if (streamingEnabled) {
    const registry = env.getGuardRegistry?.();
    const subtypeKey = directive.subtype === "runCommand" ? "runCommand" : directive.subtype === "runCode" ? "runCode" : void 0;
    const afterGuards = registry ? [
      ...registry.getOperationGuardsForTiming("run", "after"),
      ...subtypeKey ? registry.getOperationGuardsForTiming(subtypeKey, "after") : []
    ] : [];
    if (afterGuards.length > 0) {
      const streamingMessage = [
        "Cannot run after-guards when streaming is enabled.",
        "Options:",
        "- Remove after-timed guards or change them to before",
        "- Disable streaming with `with { stream: false }`"
      ].join("\n");
      throw new GuardError({
        decision: "deny",
        message: streamingMessage,
        reason: streamingMessage,
        operation: {
          type: "run",
          subtype: directive.subtype === "runCode" ? "runCode" : "runCommand"
        },
        timing: "after",
        guardResults: [],
        reasons: [
          streamingMessage
        ]
      });
    }
  }
  const executionContext = {
    sourceLocation: directive.location,
    directiveNode: directive,
    filePath: env.getCurrentFilePath(),
    directiveType: directive.meta?.directiveType || "run"
  };
  try {
    if (directive.subtype === "runCommand") {
      const commandNodes = directive.values?.identifier || directive.values?.command;
      if (!commandNodes) {
        throw new Error("Run command directive missing command");
      }
      const preExtractedCommand = getPreExtractedRunCommand(context2);
      const command = preExtractedCommand ?? await interpolateWithPendingDescriptor(commandNodes, InterpolationContext.ShellCommand);
      const workingDirectory = await resolveWorkingDirectory(directive.values?.workingDir, env, {
        sourceLocation: directive.location,
        directiveType: "run"
      });
      const effectiveWorkingDirectory = workingDirectory || env.getExecutionDirectory();
      const commandTaint = deriveCommandTaint({
        command
      });
      mergePendingDescriptor(makeSecurityDescriptor({
        taint: commandTaint.taint,
        labels: commandTaint.labels,
        sources: commandTaint.sources
      }));
      try {
        const CMD_MAX = (() => {
          const v = process.env.MLLD_MAX_SHELL_COMMAND_SIZE;
          if (!v) return 128 * 1024;
          const n = Number(v);
          return Number.isFinite(n) && n > 0 ? Math.floor(n) : 128 * 1024;
        })();
        const cmdBytes = Buffer.byteLength(command || "", "utf8");
        if (process.env.MLLD_DEBUG === "true") {
          try {
            console.error(`[run.ts] /run command size: ${cmdBytes} bytes (max ~${CMD_MAX})`);
          } catch {
          }
        }
        if (cmdBytes > CMD_MAX) {
          const message = [
            "Command payload too large for /run execution (may exceed OS args+env limits).",
            `Command size: ${cmdBytes} bytes (max ~${CMD_MAX})`,
            "Suggestions:",
            '- Use `/run sh (@var) { echo "$var" | tool }` or `/exe ... = sh { ... }` to leverage heredocs',
            "- Pass file paths or stream via stdin (printf, here-strings)",
            "- Reduce or split the data",
            "",
            "Learn more: https://mlld.ai/docs/large-variables"
          ].join("\n");
          throw new MlldCommandExecutionError(message, directive.location, {
            command,
            exitCode: 1,
            duration: 0,
            stderr: message,
            workingDirectory: effectiveWorkingDirectory,
            directiveType: "run"
          }, env);
        }
      } catch (e) {
        if (e instanceof MlldCommandExecutionError) {
          throw e;
        }
      }
      const security = env.getSecurityManager();
      if (security) {
        const securityManager = security;
        const analyzer = securityManager.commandAnalyzer;
        if (analyzer) {
          const analysis = await analyzer.analyze(command, commandTaint.taint);
          if (analysis.blocked) {
            const reason = analysis.risks[0]?.description || "Security policy violation";
            throw new MlldCommandExecutionError(`Security: Command blocked - ${reason}`, directive.location, {
              command,
              exitCode: 1,
              duration: 0,
              stderr: `This command is blocked by security policy: ${reason}`,
              workingDirectory: effectiveWorkingDirectory,
              directiveType: "run"
            }, env);
          }
        }
      }
      let stdinInput;
      if (withClause && "stdin" in withClause) {
        stdinInput = await resolveStdinInput(withClause.stdin, env);
      }
      const commandOptions = stdinInput !== void 0 || workingDirectory ? {
        ...stdinInput !== void 0 ? {
          input: stdinInput
        } : {},
        ...workingDirectory ? {
          workingDirectory
        } : {}
      } : void 0;
      setOutput(await env.executeCommand(command, commandOptions, {
        ...executionContext,
        streamingEnabled,
        pipelineId,
        suppressTerminal: hasStreamFormat || activeStreamingOptions.suppressTerminal === true,
        workingDirectory
      }));
    } else if (directive.subtype === "runCode") {
      const codeNodes = directive.values?.code;
      if (!codeNodes) {
        throw new Error("Run code directive missing code");
      }
      const code = dedentCommonIndent(extractRawTextContent(codeNodes));
      const workingDirectory = await resolveWorkingDirectory(directive.values?.workingDir, env, {
        sourceLocation: directive.location,
        directiveType: "run"
      });
      const args = directive.values?.args || [];
      const argValues = args.length === 0 ? {} : await AutoUnwrapManager.executeWithPreservation(async () => {
        const extracted = {};
        for (let i = 0; i < args.length; i++) {
          const arg = args[i];
          if (arg && typeof arg === "object" && arg.type === "VariableReference") {
            const varName = arg.identifier;
            const variable = env.getVariable(varName);
            if (!variable) {
              throw new Error(`Variable not found: ${varName}`);
            }
            const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
            const value = await extractVariableValue2(variable, env);
            const unwrappedValue = AutoUnwrapManager.unwrap(value);
            extracted[varName] = unwrappedValue;
          } else if (typeof arg === "string") {
            extracted[`arg${i}`] = arg;
          }
        }
        return extracted;
      });
      const language = directive.meta?.language || "javascript";
      setOutput(await AutoUnwrapManager.executeWithPreservation(async () => {
        return await env.executeCode(code, language, argValues, void 0, workingDirectory ? {
          workingDirectory
        } : void 0, {
          ...executionContext,
          streamingEnabled,
          pipelineId,
          workingDirectory
        });
      }));
    } else if (directive.subtype === "runExec") {
      const identifierNodes = directive.values?.identifier;
      if (!identifierNodes || !Array.isArray(identifierNodes) || identifierNodes.length === 0) {
        throw new Error("Run exec directive missing exec reference");
      }
      let commandName = "";
      const identifierNode = identifierNodes[0];
      if (identifierNode.type === "VariableReference" && "identifier" in identifierNode) {
        commandName = identifierNode.identifier;
      }
      if (commandName && !callStack.includes(commandName)) {
        callStack = [
          ...callStack,
          commandName
        ];
      }
      let execVar;
      if (identifierNode.type === "VariableReference" && identifierNode.fields && identifierNode.fields.length > 0) {
        const varRef = identifierNode;
        const baseVar = env.getVariable(varRef.identifier);
        if (!baseVar) {
          throw new Error(`Base variable not found: ${varRef.identifier}`);
        }
        const variantMap = baseVar.internal?.transformerVariants;
        let value;
        let remainingFields = Array.isArray(varRef.fields) ? [
          ...varRef.fields
        ] : [];
        if (variantMap && remainingFields.length > 0) {
          const firstField = remainingFields[0];
          if (firstField.type === "field" || firstField.type === "stringIndex" || firstField.type === "numericField") {
            const variantName = String(firstField.value);
            const variant = variantMap[variantName];
            if (!variant) {
              throw new Error(`Pipeline function '@${varRef.identifier}.${variantName}' is not defined`);
            }
            value = variant;
            remainingFields = remainingFields.slice(1);
          }
        }
        if (typeof value === "undefined") {
          const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
          value = await extractVariableValue2(baseVar, env);
        }
        for (const field of remainingFields) {
          if ((field.type === "field" || field.type === "stringIndex" || field.type === "numericField") && typeof value === "object" && value !== null) {
            value = value[String(field.value)];
          } else if (field.type === "arrayIndex" && Array.isArray(value)) {
            value = value[Number(field.value)];
          } else {
            const fieldName = String(field.value);
            throw new Error(`Cannot access field '${fieldName}' on ${typeof value}`);
          }
        }
        if (typeof value === "object" && value !== null && "type" in value && value.type === "executable") {
          execVar = value;
        } else if (typeof value === "object" && value !== null && "__executable" in value && value.__executable) {
          const fullName = `${varRef.identifier}.${varRef.fields.map((f) => f.value).join(".")}`;
          let capturedShadowEnvs = value.internal?.capturedShadowEnvs;
          if (capturedShadowEnvs && typeof capturedShadowEnvs === "object") {
            const deserialized = {};
            for (const [lang, shadowObj] of Object.entries(capturedShadowEnvs)) {
              if (shadowObj && typeof shadowObj === "object") {
                const map = /* @__PURE__ */ new Map();
                for (const [name, func] of Object.entries(shadowObj)) {
                  map.set(name, func);
                }
                deserialized[lang] = map;
              }
            }
            capturedShadowEnvs = deserialized;
          }
          execVar = {
            type: "executable",
            name: fullName,
            value: value.value || {
              type: "code",
              template: "",
              language: "js"
            },
            paramNames: value.paramNames || [],
            source: {
              directive: "import",
              syntax: "code",
              hasInterpolation: false,
              isMultiLine: false
            },
            createdAt: Date.now(),
            modifiedAt: Date.now(),
            mx: {
              ...value.mx || {}
            },
            internal: {
              ...value.internal || {},
              executableDef: value.executableDef,
              // CRITICAL: Preserve captured shadow environments from imports (deserialized)
              capturedShadowEnvs
            }
          };
        } else if (typeof value === "string") {
          const variable = env.getVariable(value);
          if (!variable || !isExecutableVariable(variable)) {
            throw new Error(`Executable variable not found: ${value}`);
          }
          execVar = variable;
        } else {
          throw new Error(`Field access did not resolve to an executable: ${typeof value}, got: ${JSON.stringify(value)}`);
        }
      } else {
        if (!commandName) {
          throw new Error("Run exec directive identifier must be a command reference");
        }
        const variable = getPreExtractedExec(context2, commandName) ?? env.getVariable(commandName);
        if (!variable || !isExecutableVariable(variable)) {
          throw new Error(`Executable variable not found: ${commandName}`);
        }
        execVar = variable;
      }
      const definition = execVar.internal?.executableDef;
      if (!definition) {
        const fullPath = identifierNode.type === "VariableReference" && identifierNode.fields && identifierNode.fields.length > 0 ? `${identifierNode.identifier}.${identifierNode.fields.map((f) => f.value).join(".")}` : commandName;
        throw new Error(`Executable ${fullPath} has no definition (missing executableDef)`);
      }
      const args = directive.values?.args || [];
      const argValues = {};
      const paramNames = definition.paramNames;
      if (paramNames && paramNames.length > 0) {
        for (let i = 0; i < paramNames.length; i++) {
          const paramName = paramNames[i];
          if (!args[i]) {
            argValues[paramName] = "";
            continue;
          }
          const arg = args[i];
          let argValue;
          if (typeof arg === "string" || typeof arg === "number" || typeof arg === "boolean") {
            argValue = String(arg);
          } else if (arg && typeof arg === "object" && "type" in arg) {
            argValue = await interpolateWithPendingDescriptor([
              arg
            ], InterpolationContext.Default);
          } else {
            argValue = String(arg);
          }
          argValues[paramName] = argValue;
        }
      }
      if (definition.type === "command" && "commandTemplate" in definition) {
        const tempEnv = env.createChild();
        for (const [key, value] of Object.entries(argValues)) {
          tempEnv.setParameterVariable(key, createSimpleTextVariable(key, value));
        }
        const workingDirectory = await resolveWorkingDirectory(definition?.workingDir, tempEnv, {
          sourceLocation: directive.location,
          directiveType: "run"
        });
        const effectiveWorkingDirectory = workingDirectory || env.getExecutionDirectory();
        const cleanTemplate = definition.commandTemplate.map((seg, idx) => {
          if (idx === 0 && seg.type === "Text" && "content" in seg && seg.content.startsWith("[")) {
            return {
              ...seg,
              content: seg.content.substring(1)
            };
          }
          return seg;
        });
        const command = await interpolateWithPendingDescriptor(cleanTemplate, InterpolationContext.ShellCommand, tempEnv);
        const security = env.getSecurityManager();
        if (security) {
          const securityManager = security;
          const analyzer = securityManager.commandAnalyzer;
          if (analyzer) {
            const analysis = await analyzer.analyze(command);
            if (analysis.blocked) {
              const reason = analysis.risks?.[0]?.description || "Security policy violation";
              throw new MlldCommandExecutionError(`Security: Exec command blocked - ${reason}`, directive.location, {
                command,
                exitCode: 1,
                duration: 0,
                stderr: `This exec command is blocked by security policy: ${reason}`,
                workingDirectory: effectiveWorkingDirectory,
                directiveType: "run"
              }, env);
            }
          }
        }
        setOutput(await env.executeCommand(command, workingDirectory ? {
          workingDirectory
        } : void 0, {
          ...executionContext,
          streamingEnabled,
          pipelineId,
          workingDirectory
        }));
      } else if (definition.type === "commandRef") {
        const refExecVar = env.getVariable(definition.commandRef);
        if (!refExecVar || !isExecutableVariable(refExecVar)) {
          throw new Error(`Referenced executable not found: ${definition.commandRef}`);
        }
        if (callStack.includes(definition.commandRef)) {
          const cycle = [
            ...callStack,
            definition.commandRef
          ].join(" -> ");
          throw new Error(`Circular command reference detected: ${cycle}`);
        }
        const refDirective = {
          ...directive,
          values: {
            ...directive.values,
            identifier: [
              {
                type: "Text",
                content: definition.commandRef
              }
            ],
            args: definition.commandArgs
          }
        };
        const result = await evaluateRun(refDirective, env, callStack);
        setOutput(result.value);
      } else if (definition.type === "code") {
        const tempEnv = env.createChild();
        for (const [key, value] of Object.entries(argValues)) {
          tempEnv.setParameterVariable(key, createSimpleTextVariable(key, value));
        }
        const workingDirectory = await resolveWorkingDirectory(definition?.workingDir, tempEnv, {
          sourceLocation: directive.location,
          directiveType: "run"
        });
        const codeParams = {
          ...argValues
        };
        const capturedEnvs = execVar.internal?.capturedShadowEnvs;
        if (capturedEnvs && (definition.language === "js" || definition.language === "javascript" || definition.language === "node" || definition.language === "nodejs")) {
          codeParams.__capturedShadowEnvs = capturedEnvs;
        }
        if (definition.language === "mlld-when") {
          logger.debug("\u{1F3AF} mlld-when handler in run.ts CALLED");
          const whenExprNode = definition.codeTemplate[0];
          if (!whenExprNode || whenExprNode.type !== "WhenExpression") {
            throw new Error("mlld-when executable missing WhenExpression node");
          }
          const execEnv = env.createChild();
          for (const [key, value] of Object.entries(codeParams)) {
            execEnv.setParameterVariable(key, createSimpleTextVariable(key, value));
          }
          const { evaluateWhenExpression: evaluateWhenExpression2 } = await import('./when-expression-ZW53U2K2.mjs');
          const whenResult = await evaluateWhenExpression2(whenExprNode, execEnv);
          const normalized = normalizeWhenShowEffect(whenResult.value);
          setOutput(normalized.normalized);
          logger.debug("\u{1F3AF} mlld-when result:", {
            outputType: typeof outputValue,
            outputValue: outputText.substring(0, 100)
          });
        } else if (definition.language === "mlld-exe-block") {
          const blockNode = Array.isArray(definition.codeTemplate) ? definition.codeTemplate[0] : void 0;
          if (!blockNode || !blockNode.values) {
            throw new Error("mlld-exe-block executable missing block content");
          }
          const execEnv = env.createChild();
          for (const [key, value] of Object.entries(codeParams)) {
            execEnv.setParameterVariable(key, createSimpleTextVariable(key, value));
          }
          const { evaluateExeBlock: evaluateExeBlock2 } = await import('./exe-T3P26GTO.mjs');
          const blockResult = await evaluateExeBlock2(blockNode, execEnv);
          setOutput(blockResult.value);
        } else {
          const code = await interpolateWithPendingDescriptor(definition.codeTemplate, InterpolationContext.ShellCommand, tempEnv);
          if (process.env.DEBUG_EXEC) {
            logger.debug("run.ts code execution debug:", {
              codeTemplate: definition.codeTemplate,
              interpolatedCode: code,
              argValues
            });
          }
          setOutput(await AutoUnwrapManager.executeWithPreservation(async () => {
            return await env.executeCode(code, definition.language || "javascript", codeParams, void 0, workingDirectory ? {
              workingDirectory
            } : void 0, {
              ...executionContext,
              streamingEnabled,
              pipelineId,
              workingDirectory
            });
          }));
        }
      } else if (definition.type === "template") {
        const tempEnv = env.createChild();
        for (const [key, value] of Object.entries(argValues)) {
          tempEnv.setParameterVariable(key, createSimpleTextVariable(key, value));
        }
        const templateOutput = await interpolateWithPendingDescriptor(definition.template, InterpolationContext.Default, tempEnv);
        setOutput(templateOutput);
      } else if (definition.type === "prose") {
        const { executeProseExecutable } = await import('./prose-execution-BCUOZNHM.mjs');
        const proseResult = await executeProseExecutable(definition, argValues, env);
        setOutput(proseResult);
      } else {
        throw new Error(`Unsupported executable type: ${definition.type}`);
      }
    } else if (directive.subtype === "runExecInvocation") {
      const execInvocation = directive.values?.execInvocation;
      if (!execInvocation) {
        throw new Error("Run exec invocation directive missing exec invocation");
      }
      const result = await resolveDirectiveExecInvocation(directive, env, execInvocation);
      setOutput(result.value);
      sourceNodeForPipeline = execInvocation;
    } else if (directive.subtype === "runExecReference") {
      const execRef = directive.values?.execRef;
      if (!execRef) {
        throw new Error("Run exec reference directive missing exec reference");
      }
      const result = await resolveDirectiveExecInvocation(directive, env, execRef);
      setOutput(result.value);
      sourceNodeForPipeline = execRef;
    } else if (directive.subtype === "runPipeline") {
      setOutput("");
      withClause = directive.values.withClause;
    } else {
      throw new Error(`Unsupported run subtype: ${directive.subtype}`);
    }
    if (withClause) {
      if (process.env.MLLD_DEBUG_STDIN === "true") {
        try {
          console.error("[mlld] withClause", JSON.stringify(withClause, null, 2));
        } catch {
          console.error("[mlld] withClause", withClause);
        }
      }
      if (withClause.pipeline && withClause.pipeline.length > 0) {
        const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
        const enableStage0 = !!sourceNodeForPipeline;
        const pipelineInput = outputValue;
        const valueForPipeline = enableStage0 ? {
          value: pipelineInput,
          mx: {},
          internal: {
            isRetryable: true,
            sourceFunction: sourceNodeForPipeline
          }
        } : pipelineInput;
        const outputDescriptor = lastOutputDescriptor ?? extractSecurityDescriptor(pipelineInput, {
          recursive: true,
          mergeArrayElements: true
        });
        const pipelineDescriptorHint = pendingOutputDescriptor ? outputDescriptor ? env.mergeSecurityDescriptors(pendingOutputDescriptor, outputDescriptor) : pendingOutputDescriptor : outputDescriptor;
        const pipelineResult = await processPipeline2({
          value: valueForPipeline,
          env,
          directive,
          pipeline: withClause.pipeline,
          format: withClause.format,
          isRetryable: enableStage0,
          location: directive.location,
          descriptorHint: pipelineDescriptorHint
        });
        setOutput(pipelineResult);
      }
    }
    const finalizedStreaming = streamingManager.finalizeResults();
    env.setStreamingResult(finalizedStreaming.streaming);
    if (hasStreamFormat && finalizedStreaming.streaming?.text) {
      outputText = finalizedStreaming.streaming.text;
      setOutput(outputText);
    }
    let displayText = outputText;
    if (!displayText.endsWith("\n")) {
      displayText += "\n";
    }
    outputText = displayText;
    if (!directive.meta?.isDataValue && !directive.meta?.isEmbedded) {
      const replacementNode = {
        type: "Text",
        nodeId: `${directive.nodeId}-output`,
        content: displayText
      };
      env.addNode(replacementNode);
    }
    const shouldEmitFinalOutput = !hasStreamFormat || !streamingEnabled;
    if (displayText && !directive.meta?.isDataValue && !directive.meta?.isEmbedded && !directive.meta?.isRHSRef && shouldEmitFinalOutput) {
      const materializedEffect = materializeDisplayValue(outputValue, void 0, outputValue, displayText);
      const effectText = materializedEffect.text;
      if (materializedEffect.descriptor) {
        env.recordSecurityDescriptor(materializedEffect.descriptor);
      }
      env.emitEffect("both", effectText);
    }
    return {
      value: outputValue,
      env
    };
  } catch (error) {
    throw error;
  } finally {
  }
}
__name(evaluateRun, "evaluateRun");
function getPreExtractedRunCommand(context2) {
  if (!context2?.extractedInputs || context2.extractedInputs.length === 0) {
    return void 0;
  }
  for (const input of context2.extractedInputs) {
    if (input && typeof input === "object" && "name" in input && input.name === "__run_command__" && typeof input.value === "string") {
      return input.value;
    }
  }
  return void 0;
}
__name(getPreExtractedRunCommand, "getPreExtractedRunCommand");
function getPreExtractedExec(context2, name) {
  if (!context2?.extractedInputs || context2.extractedInputs.length === 0) {
    return void 0;
  }
  for (const input of context2.extractedInputs) {
    if (input && typeof input === "object" && "name" in input && input.name === name && input.type === "executable") {
      return input;
    }
  }
  return void 0;
}
__name(getPreExtractedExec, "getPreExtractedExec");

// interpreter/eval/import/ImportPathResolver.ts
var _ImportPathResolver = class _ImportPathResolver {
  constructor(env) {
    __publicField(this, "env");
    this.env = env;
  }
  /**
  * Resolve import path and determine the type of import
  */
  async resolveImportPath(directive) {
    const pathValue = directive.values?.path;
    if (!pathValue) {
      throw new Error("Import directive missing path");
    }
    const pathNodes = this.normalizePathNodes(pathValue, directive);
    const specialImport = await this.detectSpecialImports(pathNodes, directive);
    if (specialImport) {
      return specialImport;
    }
    const importPath = await this.interpolatePathNodes(pathNodes);
    return this.routeImportRequest(importPath, pathNodes, directive);
  }
  /**
  * Convert path value to consistent node array format
  */
  normalizePathNodes(pathValue, directive) {
    if (typeof pathValue === "string") {
      return [
        {
          type: "Text",
          content: pathValue,
          nodeId: "",
          location: directive.location
        }
      ];
    } else if (Array.isArray(pathValue)) {
      return pathValue;
    } else if (pathValue && typeof pathValue === "object" && pathValue.type === "path") {
      if (pathValue.subtype === "urlPath" && pathValue.values?.url) {
        return pathValue.values.url;
      } else if (pathValue.values?.path) {
        return pathValue.values.path;
      } else {
        throw new Error("Invalid path object structure in import directive");
      }
    } else {
      throw new Error("Import directive path must be a string, array of nodes, or path object");
    }
  }
  /**
  * Detect special imports (@input, @stdin, resolver imports)
  * Also handles "liberal" quoted syntax like "@local/module" where @local is a resolver
  */
  async detectSpecialImports(pathNodes, directive) {
    if (pathNodes.length === 0) {
      return null;
    }
    const firstNode = pathNodes[0];
    if (firstNode.type === "Text") {
      const content = firstNode.content;
      if (content === "@INPUT" || content === "@input") {
        return {
          type: "input",
          resolvedPath: "@input",
          resolverName: "input"
        };
      } else if (content === "@stdin") {
        return {
          type: "input",
          resolvedPath: "@input",
          resolverName: "input"
        };
      } else if (content === "@state" || content === "@payload") {
        return {
          type: "module",
          resolvedPath: content
        };
      }
    }
    if (firstNode.type === "VariableReference") {
      const varRef = firstNode;
      if (varRef.identifier === "state" || varRef.identifier === "payload") {
        return {
          type: "module",
          resolvedPath: `@${varRef.identifier}`
        };
      }
      if (varRef.identifier === "INPUT" || varRef.identifier === "input") {
        return {
          type: "input",
          resolvedPath: "@input",
          resolverName: "input"
        };
      } else if (varRef.identifier === "stdin") {
        return {
          type: "input",
          resolvedPath: "@input",
          resolverName: "input"
        };
      }
      if (varRef.isSpecial && varRef.identifier && pathNodes.length === 1) {
        const resolverManager2 = this.env.getResolverManager();
        if (resolverManager2) {
          if (resolverManager2.isResolverName(varRef.identifier)) {
            return {
              type: "resolver",
              resolvedPath: `@${varRef.identifier}`,
              resolverName: varRef.identifier
            };
          }
          const dynamicResolver = resolverManager2.findResolverForRef?.(`@${varRef.identifier}`);
          if (dynamicResolver) {
            return {
              type: "resolver",
              resolvedPath: `@${varRef.identifier}`,
              resolverName: dynamicResolver.name
            };
          }
        }
      }
      const resolverManager = this.env.getResolverManager();
      if (varRef.isSpecial && varRef.identifier) {
        const potentialName = varRef.identifier;
        if (resolverManager && resolverManager.isResolverName(potentialName)) {
          return null;
        }
        const remainingPath = pathNodes.slice(1).map((node) => {
          if (node.type === "Text") {
            return node.content;
          } else if (node.type === "PathSeparator") {
            return node.value || "/";
          }
          return "";
        }).join("");
        if (remainingPath.startsWith("/") || remainingPath.length > 0) {
          const fullRef = `@${potentialName}${remainingPath.startsWith("/") ? "" : "/"}${remainingPath}`;
          return {
            type: "module",
            resolvedPath: fullRef
          };
        }
      }
    }
    return null;
  }
  /**
  * Interpolate path nodes to get the final import path
  */
  async interpolatePathNodes(pathNodes) {
    const descriptors = [];
    const interpolated = await interpolate(pathNodes, this.env, void 0, {
      collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
        if (descriptor) {
          descriptors.push(descriptor);
        }
      }, "collectSecurityDescriptor")
    });
    const merged = descriptors.length === 1 ? descriptors[0] : descriptors.length > 1 ? this.env.mergeSecurityDescriptors(...descriptors) : void 0;
    if (merged) {
      this.env.recordSecurityDescriptor(merged);
    }
    return interpolated.trim();
  }
  /**
  * Route import request based on the interpolated path
  */
  async routeImportRequest(importPath, pathNodes, directive) {
    const sectionNodes = directive.values?.section;
    let sectionName;
    if (sectionNodes && Array.isArray(sectionNodes)) {
      const sectionDescriptors = [];
      sectionName = await interpolate(sectionNodes, this.env, void 0, {
        collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
          if (descriptor) {
            sectionDescriptors.push(descriptor);
          }
        }, "collectSecurityDescriptor")
      });
      const mergedSection = sectionDescriptors.length === 1 ? sectionDescriptors[0] : sectionDescriptors.length > 1 ? this.env.mergeSecurityDescriptors(...sectionDescriptors) : void 0;
      if (mergedSection) {
        this.env.recordSecurityDescriptor(mergedSection);
      }
    }
    if (importPath.startsWith("@")) {
      return this.handleModuleReference(importPath, directive, sectionName);
    }
    const pathNode = pathNodes[0];
    const isURL = pathNode?.subtype === "urlPath" || pathNode?.subtype === "urlSectionPath" || this.env.isURL(importPath);
    if (isURL) {
      return this.handleURLImport(importPath, directive, sectionName);
    }
    return this.handleFileImport(importPath, directive, sectionName);
  }
  /**
  * Handle module reference imports (@user/module, @now, etc.)
  */
  async handleModuleReference(importPath, directive, sectionName) {
    const resolverManager = this.env.getResolverManager();
    const potentialResolverName = importPath.substring(1);
    if (resolverManager && resolverManager.isResolverName(potentialResolverName)) {
      return {
        type: "resolver",
        resolvedPath: importPath,
        resolverName: potentialResolverName,
        sectionName
      };
    }
    const { moduleRef, expectedHash, extension } = this.extractHashFromPath(importPath, directive);
    return {
      type: "module",
      resolvedPath: moduleRef,
      expectedHash,
      sectionName,
      moduleExtension: extension
    };
  }
  /**
  * Handle URL imports
  */
  async handleURLImport(importPath, directive, sectionName) {
    const pathMeta = directive.meta?.path;
    const expectedHash = pathMeta?.hash;
    return {
      type: "url",
      resolvedPath: importPath,
      expectedHash,
      sectionName
    };
  }
  /**
  * Handle file path imports
  */
  async handleFileImport(importPath, directive, sectionName) {
    const resolvedPath = await this.env.resolvePath(importPath);
    const pathMeta = directive.meta?.path;
    const expectedHash = pathMeta?.hash;
    return {
      type: "file",
      resolvedPath,
      expectedHash,
      sectionName
    };
  }
  /**
  * Extract hash information from module reference
  */
  extractHashFromPath(importPath, directive) {
    let moduleRef = importPath;
    let expectedHash;
    let extension;
    const pathMeta = directive.meta?.path;
    if (pathMeta && pathMeta.hash) {
      expectedHash = pathMeta.hash;
      const hashIndex = moduleRef.lastIndexOf("@");
      if (hashIndex > 0) {
        moduleRef = moduleRef.substring(0, hashIndex);
      }
    }
    if (pathMeta && pathMeta.extension) {
      extension = pathMeta.extension;
      if (moduleRef.endsWith(extension)) {
        moduleRef = moduleRef.substring(0, moduleRef.length - extension.length);
      }
    }
    return {
      moduleRef,
      expectedHash,
      extension
    };
  }
  /**
  * Check if a path is a URL
  */
  isURLPath(path10) {
    return this.env.isURL(path10);
  }
  /**
  * Liberal import syntax support - handles both quoted and unquoted module references
  * This follows Postel's Law: "be liberal in what you accept"
  */
  handleLiberalImportSyntax(pathNodes) {
    return pathNodes;
  }
};
__name(_ImportPathResolver, "ImportPathResolver");
var ImportPathResolver = _ImportPathResolver;
var _HashUtils = class _HashUtils {
  /**
  * Generate SHA-256 hash of content
  * @param content - The content to hash
  * @returns 64-character hex string hash
  */
  static hash(content) {
    return crypto.createHash("sha256").update(content).digest("hex");
  }
  /**
  * Generate SRI-style integrity hash (sha256-base64)
  * @param content - The content to hash
  * @returns SRI-formatted integrity string
  */
  static integrity(content) {
    const hash = crypto.createHash("sha256").update(content).digest("base64");
    return `sha256-${hash}`;
  }
  /**
  * Verify content against a hash
  * @param content - The content to verify
  * @param expectedHash - The expected SHA-256 hash (hex)
  * @returns true if content matches hash
  */
  static verify(content, expectedHash) {
    const actualHash = this.hash(content);
    return actualHash === expectedHash;
  }
  /**
  * Verify content against SRI integrity string
  * @param content - The content to verify
  * @param integrity - The SRI integrity string (e.g., "sha256-...")
  * @returns true if content matches integrity
  */
  static verifyIntegrity(content, integrity) {
    const actualIntegrity = this.integrity(content);
    return actualIntegrity === integrity;
  }
  /**
  * Get short hash (first n characters)
  * @param fullHash - The full 64-character hash
  * @param length - Number of characters (default 8)
  * @returns Short hash string
  */
  static shortHash(fullHash, length = 8) {
    return fullHash.substring(0, length);
  }
  /**
  * Expand short hash to full hash by searching cache
  * @param shortHash - The short hash to expand
  * @param availableHashes - List of full hashes to search
  * @returns Full hash if unique match found, null otherwise
  */
  static expandHash(shortHash, availableHashes) {
    const matches = availableHashes.filter((hash) => hash.startsWith(shortHash));
    if (matches.length === 1) {
      return matches[0];
    } else if (matches.length === 0) {
      return null;
    } else {
      throw new Error(`Ambiguous short hash '${shortHash}' matches ${matches.length} hashes`);
    }
  }
  /**
  * Get cache directory path for a hash
  * Uses first 2 characters as subdirectory for better filesystem performance
  * @param hash - The full hash
  * @returns Path components [prefix, rest] for directory structure
  */
  static getCachePathComponents(hash) {
    return {
      prefix: hash.substring(0, 2),
      rest: hash.substring(2)
    };
  }
  /**
  * Create module content object with hash
  * @param content - The module content
  * @param source - The source URL/path
  * @returns ModuleContent object
  */
  static createModuleContent(content, source) {
    return {
      content,
      hash: this.hash(content),
      metadata: {
        source,
        timestamp: /* @__PURE__ */ new Date(),
        size: Buffer.byteLength(content, "utf8")
      }
    };
  }
  /**
  * Compare two hashes in constant time to prevent timing attacks
  * @param hash1 - First hash
  * @param hash2 - Second hash
  * @returns true if hashes match
  */
  static secureCompare(hash1, hash2) {
    if (hash1.length !== hash2.length) {
      return false;
    }
    const buffer1 = Buffer.from(hash1);
    const buffer2 = Buffer.from(hash2);
    return crypto.timingSafeEqual(buffer1, buffer2);
  }
};
__name(_HashUtils, "HashUtils");
var HashUtils = _HashUtils;
var _ImportSecurityValidator = class _ImportSecurityValidator {
  constructor(env) {
    __publicField(this, "env");
    this.env = env;
  }
  /**
  * Validates import security including circular imports, content hashes, 
  * version compatibility, and import approval
  */
  async validateImportSecurity(resolution, content) {
    const validation = {
      approved: true,
      hashValid: true,
      versionCompatible: true,
      circularImportDetected: false,
      errors: []
    };
    validation.circularImportDetected = this.checkCircularImports(resolution.resolvedPath);
    if (validation.circularImportDetected) {
      validation.errors.push(`Circular import detected: ${resolution.resolvedPath}`);
      return validation;
    }
    if (resolution.expectedHash && content) {
      validation.hashValid = this.validateContentHash(content, resolution.expectedHash, resolution.resolvedPath);
      if (!validation.hashValid) {
        validation.errors.push(`Hash validation failed for: ${resolution.resolvedPath}`);
      }
    }
    return validation;
  }
  /**
  * Checks for circular import dependencies
  */
  checkCircularImports(resolvedPath) {
    return this.env.isImporting(resolvedPath);
  }
  /**
  * Validates content hash against expected hash (supports both full and short hashes)
  */
  validateContentHash(content, expectedHash, resolvedPath) {
    const isTestMode = process.env.MLLD_SKIP_HASH_VALIDATION === "true";
    if (isTestMode) {
      return true;
    }
    const actualHash = HashUtils.hash(content);
    const shortActualHash = HashUtils.shortHash(actualHash, expectedHash.length);
    if (expectedHash.length < 64) {
      if (shortActualHash !== expectedHash) {
        throw new Error(`Module hash mismatch for '${resolvedPath}': expected ${expectedHash}, got ${shortActualHash} (full: ${actualHash})`);
      }
    } else {
      if (!HashUtils.secureCompare(actualHash, expectedHash)) {
        throw new Error(`Module hash mismatch for '${resolvedPath}': expected ${expectedHash}, got ${actualHash}`);
      }
    }
    return true;
  }
  /**
  * Checks mlld version compatibility from frontmatter
  */
  checkVersionCompatibility(frontmatterData, resolvedPath) {
    const requiredVersion = frontmatterData["mlld-version"] || frontmatterData["mlldVersion"] || frontmatterData["mlld_version"];
    if (!requiredVersion) {
      return true;
    }
    if (process.env.MLLD_DEBUG_VERSION) {
      logger.debug(`[Version Check] Module requires: ${requiredVersion}, Current: ${version}`);
    }
    const versionCheck = checkMlldVersion(requiredVersion);
    if (!versionCheck.compatible) {
      const moduleName = frontmatterData.module || frontmatterData.name || path7.basename(resolvedPath);
      throw new MlldError(formatVersionError(moduleName, requiredVersion, version), {
        code: "VERSION_MISMATCH",
        severity: "error",
        module: moduleName,
        requiredVersion,
        path: resolvedPath
      });
    }
    return true;
  }
  /**
  * Requests import approval for URL imports if needed
  */
  async requestImportApproval(resolvedPath) {
    const isURL = this.env.isURL(resolvedPath);
    if (isURL) {
      return true;
    }
    return true;
  }
  /**
  * Marks the beginning of an import for circular detection
  */
  beginImport(resolvedPath) {
    const isURL = this.env.isURL(resolvedPath);
    if (isURL) {
      this.env.beginImport(resolvedPath);
    }
  }
  /**
  * Marks the end of an import for circular detection
  */
  endImport(resolvedPath) {
    const isURL = this.env.isURL(resolvedPath);
    if (isURL) {
      this.env.endImport(resolvedPath);
    }
  }
  /**
  * Validates overall module integrity combining all security checks
  */
  async validateModuleIntegrity(resolution, content, frontmatterData) {
    if (this.checkCircularImports(resolution.resolvedPath)) {
      throw new Error(`Circular import detected: ${resolution.resolvedPath}`);
    }
    if (resolution.expectedHash) {
      this.validateContentHash(content, resolution.expectedHash, resolution.resolvedPath);
    }
    if (frontmatterData) {
      this.checkVersionCompatibility(frontmatterData, resolution.resolvedPath);
    }
  }
  /**
  * Validates content security excluding circular import checks
  * (Used when import tracking is already in progress)
  */
  async validateContentSecurity(resolution, content, frontmatterData) {
    if (resolution.expectedHash) {
      this.validateContentHash(content, resolution.expectedHash, resolution.resolvedPath);
    }
    if (frontmatterData) {
      this.checkVersionCompatibility(frontmatterData, resolution.resolvedPath);
    }
  }
};
__name(_ImportSecurityValidator, "ImportSecurityValidator");
var ImportSecurityValidator = _ImportSecurityValidator;

// interpreter/eval/import/ExportManifest.ts
var _ExportManifest = class _ExportManifest {
  constructor() {
    __publicField(this, "entries", /* @__PURE__ */ new Map());
  }
  add(entries) {
    for (const entry of entries) {
      const name = entry?.name;
      if (!name) continue;
      const trimmed = name.trim();
      if (!trimmed) continue;
      if (!this.entries.has(trimmed)) {
        this.entries.set(trimmed, {
          name: trimmed,
          kind: entry.kind,
          location: entry.location
        });
      } else if (entry.location && !this.entries.get(trimmed)?.location) {
        const existing = this.entries.get(trimmed);
        this.entries.set(trimmed, {
          ...existing,
          location: entry.location
        });
      }
    }
  }
  hasEntries() {
    return this.entries.size > 0;
  }
  getNames() {
    return Array.from(this.entries.keys());
  }
  getEntries() {
    return Array.from(this.entries.values());
  }
  getLocation(name) {
    return this.entries.get(name)?.location;
  }
  [Symbol.iterator]() {
    return this.entries.values();
  }
  toArray() {
    return this.getEntries();
  }
};
__name(_ExportManifest, "ExportManifest");
var ExportManifest = _ExportManifest;
var _ModuleContentProcessor = class _ModuleContentProcessor {
  constructor(env, securityValidator, variableImporter) {
    __publicField(this, "env");
    __publicField(this, "securityValidator");
    __publicField(this, "variableImporter");
    this.env = env;
    this.securityValidator = securityValidator;
    this.variableImporter = variableImporter;
  }
  /**
  * Process module content from reading through evaluation
  */
  async processModuleContent(resolution, directive) {
    const { resolvedPath } = resolution;
    const isURL = resolution.type === "url";
    this.securityValidator.beginImport(resolvedPath);
    const snapshot = this.env.getSecuritySnapshot();
    const importDescriptor = mergeDescriptors(snapshot ? makeSecurityDescriptor({
      labels: snapshot.labels,
      taint: snapshot.taint,
      sources: snapshot.sources,
      policyContext: snapshot.policy ? {
        ...snapshot.policy
      } : void 0
    }) : makeSecurityDescriptor(), makeSecurityDescriptor({
      labels: directive.meta?.securityLabels || directive.values?.securityLabels
    }));
    const fileDescriptor = !isURL ? makeSecurityDescriptor({
      taint: [
        "src:file",
        ...labelsForPath(resolvedPath)
      ],
      sources: [
        resolvedPath
      ]
    }) : void 0;
    const combinedDescriptor = fileDescriptor ? mergeDescriptors(importDescriptor, fileDescriptor) : importDescriptor;
    if (combinedDescriptor) {
      this.env.recordSecurityDescriptor(combinedDescriptor);
    }
    try {
      if (resolution.importType === "templates") {
        return await this.processTemplateCollection(resolution, directive);
      }
      const lowerPath = resolvedPath.toLowerCase();
      if (lowerPath.endsWith(".att") || lowerPath.endsWith(".mtt")) {
        const { MlldImportError: MlldImportError2 } = await import('./errors-WJULH47E.mjs');
        let suggestedName = "template";
        try {
          const ns = directive?.values?.namespace;
          if (Array.isArray(ns) && ns[0]?.content) suggestedName = ns[0].content;
          const firstImport = directive?.values?.imports?.[0];
          if (firstImport?.alias) suggestedName = firstImport.alias;
        } catch {
        }
        const example = `/exe @${suggestedName}(param1, param2) = template "${resolvedPath}"
/show @${suggestedName}("value1", "value2")`;
        throw new MlldImportError2(`Template files cannot be imported: ${resolvedPath}. Use an executable template instead.`, {
          code: "TEMPLATE_IMPORT_NOT_ALLOWED",
          context: {
            hint: "Define an /exe that loads the template file and declares parameters.",
            example
          },
          details: {
            filePath: resolvedPath
          }
        });
      }
      const content = await this.readContentFromSource(resolution);
      this.env.cacheSource(resolvedPath, content);
      await this.securityValidator.validateContentSecurity(resolution, content);
      const { parsed, processedContent, isPlainText, templateSyntax } = await this.parseContentByType(content, resolvedPath, directive);
      if (resolvedPath.endsWith(".json")) {
        return this.processJSONContent(parsed, directive, resolvedPath);
      }
      if (isPlainText) {
        return this.processPlainTextContent(resolvedPath);
      }
      if (!parsed && templateSyntax) {
        return this.processRawTemplate(processedContent, templateSyntax, resolvedPath);
      }
      return this.processMLLDContent(parsed, processedContent, resolvedPath, isURL);
    } finally {
      this.securityValidator.endImport(resolvedPath);
    }
  }
  /**
  * Process module content from resolver (content already fetched)
  */
  async processResolverContent(content, ref, directive, contentType, labels) {
    this.securityValidator.beginImport(ref);
    const snapshot = this.env.getSecuritySnapshot();
    const importDescriptor = mergeDescriptors(snapshot ? makeSecurityDescriptor({
      labels: snapshot.labels,
      taint: snapshot.taint,
      sources: snapshot.sources,
      policyContext: snapshot.policy ? {
        ...snapshot.policy
      } : void 0
    }) : makeSecurityDescriptor(), makeSecurityDescriptor({
      labels: directive.meta?.securityLabels || directive.values?.securityLabels
    }));
    const fileDescriptor = ref && !this.isUrlLike(ref) && !ref.startsWith("@") ? makeSecurityDescriptor({
      taint: [
        "src:file",
        ...labelsForPath(ref)
      ],
      sources: [
        ref
      ]
    }) : void 0;
    const combinedDescriptor = fileDescriptor ? mergeDescriptors(importDescriptor, fileDescriptor) : importDescriptor;
    if (combinedDescriptor) {
      this.env.recordSecurityDescriptor(combinedDescriptor);
    }
    try {
      const lowerRef = ref.toLowerCase();
      if (lowerRef.endsWith(".att") || lowerRef.endsWith(".mtt")) {
        const { MlldImportError: MlldImportError2 } = await import('./errors-WJULH47E.mjs');
        let suggestedName = "template";
        try {
          const ns = directive?.values?.namespace;
          if (Array.isArray(ns) && ns[0]?.content) suggestedName = ns[0].content;
          const firstImport = directive?.values?.imports?.[0];
          if (firstImport?.alias) suggestedName = firstImport.alias;
        } catch {
        }
        const example = `/exe @${suggestedName}(param1, param2) = template "${ref}"
/show @${suggestedName}("value1", "value2")`;
        throw new MlldImportError2(`Template files cannot be imported: ${ref}. Use an executable template instead.`, {
          code: "TEMPLATE_IMPORT_NOT_ALLOWED",
          context: {
            hint: "Define an /exe that loads the template file and declares parameters.",
            example
          },
          details: {
            filePath: ref
          }
        });
      }
      if (process.env.MLLD_DEBUG === "true") {
        console.log(`[ModuleContentProcessor] Processing resolver content for: ${ref}`);
        console.log(`[ModuleContentProcessor] Content length: ${content.length}`);
        console.log(`[ModuleContentProcessor] Content preview: ${content.substring(0, 200)}`);
      }
      this.env.cacheSource(ref, content);
      const isDynamicModule = labels?.includes("src:dynamic") ?? false;
      const { parsed, processedContent, isPlainText, templateSyntax } = await this.parseContentByType(content, ref, directive, contentType, isDynamicModule);
      if (ref.endsWith(".json")) {
        return this.processJSONContent(parsed, directive, ref);
      }
      if (isPlainText) {
        return this.processPlainTextContent(ref);
      }
      if (!parsed && templateSyntax) {
        return this.processRawTemplate(processedContent, templateSyntax, ref);
      }
      const result = await this.processMLLDContent(parsed, processedContent, ref, false);
      if (process.env.MLLD_DEBUG === "true") {
        console.log(`[ModuleContentProcessor] Module object keys: ${Object.keys(result.moduleObject).join(", ")}`);
        console.log(`[ModuleContentProcessor] Has frontmatter: ${result.frontmatter !== null}`);
        console.log(`[ModuleContentProcessor] Child env vars: ${result.childEnvironment.getCurrentVariables().size}`);
        console.log(`[ModuleContentProcessor] Child env var names: ${Array.from(result.childEnvironment.getCurrentVariables().keys()).join(", ")}`);
      }
      return result;
    } finally {
      this.securityValidator.endImport(ref);
    }
  }
  async processTemplateCollection(resolution, directive) {
    const fsService = this.env.getFileSystemService?.();
    if (!fsService || typeof fsService.readdir !== "function") {
      throw new MlldImportError("Templates import requires filesystem access", {
        code: "TEMPLATE_IMPORT_FS_UNAVAILABLE",
        details: {
          path: resolution.resolvedPath
        }
      });
    }
    const paramNames = this.extractParamNames(directive?.values?.templateParams);
    if (paramNames.length === 0) {
      throw new MlldImportError('Templates import requires parameters. Use: /import templates from "dir" as @name(param1, param2)', {
        code: "TEMPLATE_IMPORT_MISSING_PARAMS",
        details: {
          path: resolution.resolvedPath
        }
      });
    }
    const baseDir = resolution.resolvedPath;
    const isDir = await fsService.isDirectory(baseDir);
    if (!isDir) {
      throw new MlldImportError(`Templates import must target a directory: ${baseDir}`, {
        code: "TEMPLATE_IMPORT_NOT_DIRECTORY",
        details: {
          path: baseDir
        }
      });
    }
    const moduleObject = {};
    await this.walkTemplateDirectory(fsService, baseDir, moduleObject, paramNames, baseDir);
    if (Object.keys(moduleObject).length === 0) {
      throw new MlldImportError(`No templates found under ${baseDir}`, {
        code: "TEMPLATE_IMPORT_EMPTY",
        details: {
          path: baseDir
        }
      });
    }
    const childEnv = this.env.createChild(baseDir);
    childEnv.setCurrentFilePath(baseDir);
    return {
      moduleObject,
      frontmatter: null,
      childEnvironment: childEnv,
      guardDefinitions: []
    };
  }
  async walkTemplateDirectory(fsService, dir, target, paramNames, root) {
    const entries = await fsService.readdir(dir);
    for (const entry of entries) {
      const fullPath = path7.join(dir, entry);
      const stat = await fsService.stat(fullPath).catch(() => ({
        isDirectory: /* @__PURE__ */ __name(() => false, "isDirectory"),
        isFile: /* @__PURE__ */ __name(() => false, "isFile")
      }));
      if (stat.isDirectory()) {
        const key = this.sanitizeKey(entry);
        if (key in target) {
          throw new MlldImportError(`Duplicate template group '${key}' in ${dir}`, {
            code: "TEMPLATE_IMPORT_DUPLICATE_GROUP",
            details: {
              path: fullPath
            }
          });
        }
        const childGroup = {};
        await this.walkTemplateDirectory(fsService, fullPath, childGroup, paramNames, root);
        if (Object.keys(childGroup).length > 0) {
          target[key] = childGroup;
        }
      } else if (stat.isFile()) {
        const lower = entry.toLowerCase();
        if (!lower.endsWith(".att") && !lower.endsWith(".mtt")) {
          continue;
        }
        const key = this.sanitizeKey(entry);
        if (key in target) {
          throw new MlldImportError(`Duplicate template name '${key}' in ${dir}`, {
            code: "TEMPLATE_IMPORT_DUPLICATE_TEMPLATE",
            details: {
              path: fullPath
            }
          });
        }
        const relativePath = path7.relative(root, fullPath) || entry;
        target[key] = await this.buildTemplateExecutable(fullPath, paramNames, relativePath);
      }
    }
  }
  async buildTemplateExecutable(filePath, paramNames, displayPath) {
    const ext = path7.extname(filePath).toLowerCase();
    const fileContent = await this.env.readFile(filePath);
    const { parseSync } = await import('./parser-6HNWFG6W.mjs');
    const startRule = ext === ".mtt" ? "TemplateBodyMtt" : "TemplateBodyAtt";
    let templateNodes;
    try {
      templateNodes = parseSync(fileContent, {
        startRule
      });
    } catch (err) {
      let normalized = fileContent;
      if (ext === ".mtt") {
        normalized = normalized.replace(/{{\s*([A-Za-z_][\w\.]*)\s*}}/g, "@$1");
      }
      templateNodes = this.buildTemplateAst(normalized);
    }
    this.validateTemplateParameters(templateNodes, paramNames, displayPath);
    const execDef = {
      type: "template",
      template: templateNodes,
      paramNames,
      sourceDirective: "exec"
    };
    return {
      __executable: true,
      value: execDef,
      executableDef: execDef,
      internal: {
        executableDef: execDef
      }
    };
  }
  validateTemplateParameters(templateNodes, paramNames, templatePath) {
    const references = /* @__PURE__ */ new Set();
    this.collectTemplateReferences(templateNodes, references);
    const allowed = /* @__PURE__ */ new Set([
      ...paramNames,
      "mx",
      "pipeline",
      "p",
      "state",
      "payload",
      "input"
    ]);
    const invalid = Array.from(references).filter((ref) => !allowed.has(ref));
    if (invalid.length > 0) {
      throw new MlldImportError(`Template '${templatePath}' references undeclared variables: ${invalid.join(", ")}`, {
        code: "TEMPLATE_IMPORT_PARAM_MISMATCH",
        details: {
          template: templatePath,
          allowed: paramNames,
          invalid
        }
      });
    }
  }
  collectTemplateReferences(node, refs) {
    if (!node) return;
    if (Array.isArray(node)) {
      node.forEach((child) => this.collectTemplateReferences(child, refs));
      return;
    }
    if (typeof node !== "object") {
      return;
    }
    if (node.type === "VariableReference" && typeof node.identifier === "string") {
      refs.add(node.identifier);
    }
    if (node.type === "VariableReferenceWithTail" && node.variable && typeof node.variable.identifier === "string") {
      refs.add(node.variable.identifier);
    }
    for (const value of Object.values(node)) {
      if (value && typeof value === "object") {
        this.collectTemplateReferences(value, refs);
      }
    }
  }
  sanitizeKey(name) {
    const withoutExt = name.replace(/\.[^.]+$/, "");
    const sanitized = withoutExt.replace(/[^a-zA-Z0-9_-]/g, "_");
    return sanitized.length > 0 ? sanitized : "template";
  }
  extractParamNames(params) {
    if (!params || params.length === 0) {
      return [];
    }
    return params.map((param) => {
      if (typeof param === "string") {
        return param;
      }
      if (param?.type === "Parameter" && param.name) {
        return param.name;
      }
      if (param?.identifier) {
        return param.identifier;
      }
      return "";
    }).filter(Boolean);
  }
  /**
  * Read content from file or URL
  */
  async readContentFromSource(resolution) {
    const { resolvedPath, type, importType, cacheDurationMs } = resolution;
    try {
      if (type === "url") {
        return await this.env.fetchURL(resolvedPath, {
          forImport: true,
          importType,
          cacheDurationMs
        });
      }
      return await this.env.readFile(resolvedPath);
    } catch (error) {
      throw new Error(`Failed to read imported file '${resolvedPath}': ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  /**
  * Parse content by type (JSON vs mlld vs text)
  */
  async parseContentByType(content, resolvedPath, directive, contentType, isDynamicModule) {
    if (resolvedPath.endsWith(".json")) {
      try {
        return {
          parsed: JSON.parse(content),
          processedContent: content,
          isPlainText: false
        };
      } catch (error) {
        throw new Error(`Failed to parse JSON file '${resolvedPath}': ${error instanceof Error ? error.message : String(error)}`);
      }
    }
    if (resolvedPath.endsWith(".att")) {
      return {
        parsed: null,
        processedContent: content,
        isPlainText: false,
        templateSyntax: "doubleColon"
      };
    }
    if (resolvedPath.endsWith(".mtt")) {
      return {
        parsed: null,
        processedContent: content,
        isPlainText: false,
        templateSyntax: "tripleColon"
      };
    }
    const hasModuleExtension = resolvedPath.endsWith(".mld") || resolvedPath.endsWith(".mlld") || resolvedPath.endsWith(".mld.md") || resolvedPath.endsWith(".mlld.md") || resolvedPath.endsWith(".md");
    const forceModuleParse = contentType === "module" || resolvedPath.startsWith("@");
    if (!forceModuleParse && !hasModuleExtension) {
      return {
        parsed: {
          isPlainText: true
        },
        processedContent: content,
        isPlainText: true
      };
    }
    let processedContent = content;
    const sectionNodes = directive.values?.section;
    if (sectionNodes && Array.isArray(sectionNodes)) {
      const descriptors = [];
      const section = await interpolate(sectionNodes, this.env, void 0, {
        collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
          if (descriptor) {
            descriptors.push(descriptor);
          }
        }, "collectSecurityDescriptor")
      });
      const merged = descriptors.length === 1 ? descriptors[0] : descriptors.length > 1 ? this.env.mergeSecurityDescriptors(...descriptors) : void 0;
      if (merged) {
        this.env.recordSecurityDescriptor(merged);
      }
      if (section) {
        processedContent = this.extractSectionContent(content, section);
      }
    }
    const fsService = this.env.getFileSystemService();
    const hasIsVirtual = typeof fsService?.isVirtual === "function";
    const isVirtualFS = hasIsVirtual ? fsService.isVirtual() : false;
    const mode = isDynamicModule ? this.env.getDynamicModuleMode() : isVirtualFS ? "markdown" : inferMlldMode(resolvedPath);
    const parseResult = await parse(processedContent, {
      mode
    });
    if (!parseResult.success) {
      this.handleParseError(parseResult.error, resolvedPath);
    }
    return {
      parsed: parseResult,
      processedContent,
      isPlainText: false
    };
  }
  /**
  * Process plain text content (non-mlld files like .txt)
  */
  async processPlainTextContent(resolvedPath) {
    const moduleObject = {};
    const childEnv = this.env.createChild(path7.dirname(resolvedPath));
    childEnv.setCurrentFilePath(resolvedPath);
    return {
      moduleObject,
      frontmatter: null,
      childEnvironment: childEnv,
      guardDefinitions: []
    };
  }
  /**
  * Process raw template content without parsing
  */
  async processRawTemplate(content, templateSyntax, resolvedPath) {
    let finalContent = content;
    let finalSyntax = templateSyntax;
    if (templateSyntax === "tripleColon") {
      finalContent = content.replace(/{{\s*([\w\.]+)\s*}}/g, "@$1");
      finalSyntax = "doubleColon";
    }
    const moduleObject = {
      default: {
        __template: true,
        content: finalContent,
        templateSyntax: finalSyntax,
        templateAst: this.buildTemplateAst(finalContent)
      }
    };
    const childEnv = this.env.createChild(path7.dirname(resolvedPath));
    childEnv.setCurrentFilePath(resolvedPath);
    return {
      moduleObject,
      frontmatter: null,
      childEnvironment: childEnv,
      guardDefinitions: []
    };
  }
  /**
  * Process JSON content into module format
  */
  async processJSONContent(jsonData, directive, resolvedPath) {
    let moduleObject = {};
    if (typeof jsonData === "object" && jsonData !== null && !Array.isArray(jsonData)) {
      moduleObject = jsonData;
    } else {
      moduleObject = {
        content: jsonData
      };
    }
    const childEnv = this.env.createChild(path7.dirname(resolvedPath));
    childEnv.setCurrentFilePath(resolvedPath);
    return {
      moduleObject,
      frontmatter: null,
      childEnvironment: childEnv,
      guardDefinitions: []
    };
  }
  /**
  * Process mlld content through full AST evaluation
  */
  async processMLLDContent(parseResult, sourceContent, resolvedPath, isURL) {
    const ast = parseResult.ast;
    if (process.env.MLLD_DEBUG === "true") {
      console.log(`[processMLLDContent] Processing ${resolvedPath}:`, {
        astLength: ast.length,
        astTypes: ast.slice(0, 10).map((n) => `${n.type}${n.kind ? ":" + n.kind : ""}`)
      });
    }
    const frontmatterData = await this.extractAndValidateFrontmatter(ast, resolvedPath);
    const childEnv = this.createChildEnvironment(resolvedPath, isURL);
    if (frontmatterData) {
      childEnv.setFrontmatter(frontmatterData);
    }
    if (this.containsExportDirective(ast)) {
      childEnv.setExportManifest(new ExportManifest());
    } else {
      childEnv.setExportManifest(null);
    }
    const evalResult = await this.evaluateInChildEnvironment(ast, childEnv, resolvedPath);
    const childVars = childEnv.getCurrentVariables();
    if (process.env.MLLD_DEBUG === "true") {
      console.log(`[processMLLDContent] After evaluation:`, {
        childVarsSize: childVars.size,
        childVarNames: Array.from(childVars.keys()),
        evalResult: evalResult?.value ? "has value" : "no value"
      });
    }
    const exportManifest = childEnv.getExportManifest();
    const { moduleObject, frontmatter, guards } = this.variableImporter.processModuleExports(childVars, {
      frontmatter: frontmatterData
    }, void 0, exportManifest, childEnv);
    if (frontmatter) {
      moduleObject.__meta__ = frontmatter;
    }
    if (Object.keys(moduleObject).length === 0 && (resolvedPath.endsWith(".mld") || resolvedPath.endsWith(".mld.md"))) {
      const hasSubstantive = this.hasSubstantiveContent(sourceContent);
      if (!hasSubstantive) {
        const moduleNeeds2 = childEnv.getModuleNeeds();
        const moduleWants2 = childEnv.getModuleWants();
        const policyContext2 = childEnv.getPolicyContext() ?? null;
        return {
          moduleObject,
          frontmatter,
          childEnvironment: childEnv,
          guardDefinitions: guards,
          moduleNeeds: moduleNeeds2,
          moduleWants: moduleWants2,
          policyContext: policyContext2
        };
      }
      let templateSyntax = "doubleColon";
      let templateContent = sourceContent;
      const trimmedSource = sourceContent.trim();
      if (trimmedSource.startsWith(":::")) {
        templateSyntax = "tripleColon";
        templateContent = trimmedSource.slice(3).trimStart();
        if (templateContent.endsWith(":::")) {
          templateContent = templateContent.slice(0, -3).trimEnd();
        }
      }
      moduleObject.default = {
        __template: true,
        content: templateContent,
        templateSyntax,
        templateAst: this.buildTemplateAst(templateContent)
      };
    }
    const moduleNeeds = childEnv.getModuleNeeds();
    const moduleWants = childEnv.getModuleWants();
    const policyContext = childEnv.getPolicyContext() ?? null;
    return {
      moduleObject,
      frontmatter,
      childEnvironment: childEnv,
      guardDefinitions: guards,
      moduleNeeds,
      moduleWants,
      policyContext
    };
  }
  /**
  * Determine if content has substantive (non-comment, non-whitespace) text
  */
  hasSubstantiveContent(content) {
    const lines = content.split("\n");
    const filtered = lines.filter((l) => !/^\s*(>>|<<)/.test(l) && l.trim() !== "");
    return filtered.join("").trim().length > 0;
  }
  /**
  * Extract section content from markdown
  */
  extractSectionContent(content, sectionName) {
    const lines = content.split("\n");
    const sectionRegex = new RegExp(`^#+\\s+${sectionName}\\s*$`, "i");
    let inSection = false;
    let sectionLevel = 0;
    const sectionLines = [];
    for (const line of lines) {
      if (!inSection && sectionRegex.test(line)) {
        inSection = true;
        sectionLevel = line.match(/^#+/)?.[0].length || 0;
        continue;
      }
      if (inSection) {
        const headerMatch = line.match(/^(#+)\\s+/);
        if (headerMatch && headerMatch[1].length <= sectionLevel) {
          break;
        }
        sectionLines.push(line);
      }
    }
    return sectionLines.join("\n").trim();
  }
  /**
  * Build a simple template AST from content with @var placeholders
  */
  buildTemplateAst(content) {
    const ast = [];
    const regex = /@([A-Za-z_][\w\.]*)/g;
    let lastIndex = 0;
    let match;
    while ((match = regex.exec(content)) !== null) {
      if (match.index > lastIndex) {
        ast.push({
          type: "Text",
          content: content.slice(lastIndex, match.index)
        });
      }
      ast.push({
        type: "VariableReference",
        identifier: match[1]
      });
      lastIndex = match.index + match[0].length;
    }
    if (lastIndex < content.length) {
      ast.push({
        type: "Text",
        content: content.slice(lastIndex)
      });
    }
    return ast;
  }
  /**
  * Handle parse errors with detailed context
  */
  handleParseError(parseError, resolvedPath) {
    const errorMessage = parseError && "location" in parseError ? `Syntax error in imported file '${resolvedPath}' at line ${parseError.location?.start?.line || "?"}: ${parseError.message || "Unknown parse error"}` : `Failed to parse imported file '${resolvedPath}': ${parseError?.message || "Unknown parse error"}`;
    const importError = new Error(errorMessage);
    importError.importParseError = {
      file: path7.basename(resolvedPath, ".mld"),
      line: parseError?.location?.start?.line || "?",
      message: parseError?.message || "Unknown parse error"
    };
    throw importError;
  }
  /**
  * Extract and validate frontmatter from AST
  */
  async extractAndValidateFrontmatter(ast, resolvedPath) {
    let frontmatterData = null;
    if (ast.length > 0 && ast[0].type === "Frontmatter") {
      const { parseFrontmatter: parseFrontmatter2 } = await import('./frontmatter-parser-DG2LNZDQ.mjs');
      const frontmatterNode = ast[0];
      frontmatterData = parseFrontmatter2(frontmatterNode.content);
      this.securityValidator.checkVersionCompatibility(frontmatterData, resolvedPath);
    }
    return frontmatterData;
  }
  /**
  * Create child environment with proper path configuration
  */
  createChildEnvironment(resolvedPath, isURL) {
    const importDir = isURL ? this.env.getBasePath() : path7.dirname(resolvedPath);
    const childEnv = this.env.createChild(importDir);
    childEnv.setCurrentFilePath(resolvedPath);
    childEnv.setModuleIsolated(true);
    return childEnv;
  }
  containsExportDirective(ast) {
    return ast.some((node) => node?.type === "Directive" && node.kind === "export");
  }
  /**
  * Evaluate AST in child environment with error handling
  */
  async evaluateInChildEnvironment(ast, childEnv, resolvedPath) {
    childEnv.setImporting(true);
    try {
      return await evaluate2(ast, childEnv, {
        isExpression: true
      });
    } catch (error) {
      throw new Error(`Error evaluating imported file '${resolvedPath}': ${error instanceof Error ? error.message : String(error)}`);
    } finally {
      childEnv.setImporting(false);
    }
  }
  isUrlLike(candidate) {
    return /^https?:\/\//i.test(candidate);
  }
};
__name(_ModuleContentProcessor, "ModuleContentProcessor");
var ModuleContentProcessor = _ModuleContentProcessor;
var _ObjectReferenceResolver = class _ObjectReferenceResolver {
  /**
  * Recursively resolve variable references in nested objects
  * This handles cases like { ask: @claude_ask } where @claude_ask needs to be resolved
  */
  resolveObjectReferences(value, variableMap, options) {
    const resolveStrings = options?.resolveStrings !== false;
    const stringRefPattern = /^@[A-Za-z0-9_.-]+$/;
    if (value === null || value === void 0) {
      return value;
    }
    if (Array.isArray(value)) {
      return value.map((item) => this.resolveObjectReferences(item, variableMap, options));
    }
    if (typeof value === "object" && value.type === "VariableReference" && value.identifier) {
      if (process.env.MLLD_DEBUG_FIX === "true") {
        console.error("[ObjectReferenceResolver] Found VariableReference AST node:", {
          identifier: value.identifier,
          hasFields: !!value.fields,
          fields: value.fields
        });
      }
      return this.resolveVariableReference(value.identifier, variableMap, value.fields);
    }
    if (typeof value === "object") {
      if (value.type === "object" && value.properties) {
        return this.resolveASTObjectNode(value, variableMap, options);
      }
      if (value.type === "object" && Array.isArray(value.entries)) {
        return this.resolveASTObjectNode(value, variableMap, options);
      }
      return this.resolveNestedStructures(value, variableMap, options);
    }
    if (typeof value === "string" && resolveStrings && stringRefPattern.test(value)) {
      const varName = value.substring(1);
      const referencedVar = variableMap.get(varName);
      if (process.env.DEBUG_EXEC) {
        logger.debug("resolveObjectReferences looking for variable:", {
          originalValue: value,
          varName,
          found: !!referencedVar,
          referencedVarType: referencedVar?.type,
          availableVars: Array.from(variableMap.keys())
        });
      }
      if (referencedVar) {
        return this.resolveExecutableReference(referencedVar);
      }
      return value;
    }
    return value;
  }
  /**
  * Resolve a single variable reference by name, optionally applying field access
  */
  resolveVariableReference(varName, variableMap, fields) {
    const referencedVar = variableMap.get(varName);
    if (referencedVar) {
      let result = this.resolveExecutableReference(referencedVar);
      if (fields && fields.length > 0 && result && typeof result === "object") {
        for (const field of fields) {
          if (field.type === "field" && typeof field.value === "string") {
            if (result && typeof result === "object" && field.value in result) {
              result = result[field.value];
            } else {
              return void 0;
            }
          } else if (field.type === "bracketAccess") {
            const key = field.value;
            if (result && typeof result === "object" && key in result) {
              result = result[key];
            } else if (Array.isArray(result) && typeof key === "number") {
              result = result[key];
            } else {
              return void 0;
            }
          }
        }
      }
      if (result && typeof result === "object" && !result.__executable && !Array.isArray(result) && !result.__arraySnapshot) {
        return this.resolveObjectReferences(result, variableMap);
      }
      return result;
    } else {
      if (process.env.DEBUG_EXEC) {
        logger.debug("VariableReference AST node not found during import resolution:", varName);
      }
      throw new Error(`Variable reference @${varName} not found during import`);
    }
  }
  /**
  * Handle executable variable references with special serialization format
  */
  resolveExecutableReference(referencedVar) {
    if (referencedVar.type === "executable") {
      const execVar = referencedVar;
      let serializedCtx = {
        ...execVar.mx
      };
      let serializedInternal = {
        ...execVar.internal
      };
      if (execVar.internal?.capturedShadowEnvs) {
        serializedInternal = {
          ...serializedInternal,
          capturedShadowEnvs: this.serializeShadowEnvs(execVar.internal.capturedShadowEnvs)
        };
      }
      if (execVar.internal?.capturedModuleEnv) {
        serializedInternal = {
          ...serializedInternal,
          capturedModuleEnv: this.serializeModuleEnv(execVar.internal.capturedModuleEnv)
        };
      }
      const result = {
        __executable: true,
        value: execVar.value,
        paramNames: execVar.paramNames,
        executableDef: execVar.internal?.executableDef,
        mx: serializedCtx,
        internal: serializedInternal
      };
      return result;
    } else {
      if (referencedVar.type === "array") {
        return {
          __arraySnapshot: true,
          value: referencedVar.value,
          mx: referencedVar.mx,
          internal: referencedVar.internal,
          isComplex: referencedVar.isComplex === true,
          name: referencedVar.name
        };
      }
      return referencedVar.value;
    }
  }
  /**
  * Serialize shadow environments for export (Maps to objects)
  * WHY: Maps don't serialize to JSON, so we convert them to plain objects
  */
  serializeShadowEnvs(envs) {
    const result = {};
    for (const [lang, shadowMap] of Object.entries(envs)) {
      if (shadowMap instanceof Map && shadowMap.size > 0) {
        const obj = {};
        for (const [name, func] of shadowMap) {
          obj[name] = func;
        }
        result[lang] = obj;
      }
    }
    return result;
  }
  /**
  * Serialize module environment for export (Map to object)
  * WHY: Maps don't serialize to JSON, so we need to convert to exportable format
  * IMPORTANT: Delegate to VariableImporter to ensure consistent serialization
  */
  serializeModuleEnv(moduleEnv) {
    const result = {};
    for (const [name, variable] of moduleEnv) {
      if (variable.type === "executable") {
        const execVar = variable;
        let serializedCtx = {
          ...execVar.mx
        };
        let serializedInternal = {
          ...execVar.internal
        };
        if (serializedInternal.capturedShadowEnvs) {
          serializedInternal = {
            ...serializedInternal,
            capturedShadowEnvs: this.serializeShadowEnvs(serializedInternal.capturedShadowEnvs)
          };
        }
        delete serializedInternal.capturedModuleEnv;
        result[name] = {
          __executable: true,
          value: execVar.value,
          paramNames: execVar.paramNames,
          executableDef: execVar.internal?.executableDef,
          mx: serializedCtx,
          internal: serializedInternal
        };
      } else {
        result[name] = variable.value;
      }
    }
    return result;
  }
  /**
  * Handle AST object nodes with type and properties
  */
  resolveASTObjectNode(value, variableMap, options) {
    const resolved = {};
    if (Array.isArray(value.entries) && value.entries.length > 0) {
      for (const entry of value.entries) {
        if (entry.type === "pair") {
          resolved[entry.key] = this.resolveObjectReferences(entry.value, variableMap, options);
        } else if (entry.type === "spread") {
          for (const spreadNode of entry.value || []) {
            const spreadValue = this.resolveObjectReferences(spreadNode, variableMap, options);
            if (spreadValue && typeof spreadValue === "object" && !Array.isArray(spreadValue)) {
              Object.assign(resolved, spreadValue);
            } else {
              throw new Error("Cannot spread non-object value during import resolution");
            }
          }
        }
      }
      if (process.env.MLLD_DEBUG_FIX === "true") {
        console.error("[ObjectReferenceResolver] resolved entries object", {
          keys: Object.keys(resolved),
          hasEntries: true
        });
        try {
          fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
            source: "ObjectReferenceResolver",
            keys: Object.keys(resolved),
            hasEntries: true
          }) + "\n");
        } catch {
        }
      }
      return resolved;
    }
    if (value.properties) {
      for (const [key, val] of Object.entries(value.properties)) {
        resolved[key] = this.resolveObjectReferences(val, variableMap, options);
      }
      if (process.env.MLLD_DEBUG_FIX === "true") {
        console.error("[ObjectReferenceResolver] resolved properties object", {
          keys: Object.keys(resolved),
          hasProperties: true
        });
        try {
          fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
            source: "ObjectReferenceResolver",
            keys: Object.keys(resolved),
            hasProperties: true
          }) + "\n");
        } catch {
        }
      }
      return resolved;
    }
    return this.resolveNestedStructures(value, variableMap);
  }
  /**
  * Recursively resolve references in nested objects and arrays
  */
  resolveNestedStructures(value, variableMap, options) {
    const resolved = {};
    for (const [key, val] of Object.entries(value)) {
      resolved[key] = this.resolveObjectReferences(val, variableMap, options);
    }
    return resolved;
  }
};
__name(_ObjectReferenceResolver, "ObjectReferenceResolver");
var ObjectReferenceResolver = _ObjectReferenceResolver;

// core/policy/union.ts
function mergePolicyConfigs(base, incoming) {
  if (!base) {
    return normalizePolicyConfig(incoming);
  }
  if (!incoming) {
    return normalizePolicyConfig(base);
  }
  const baseAllow = toAllowShape(base.allow);
  const incomingAllow = toAllowShape(incoming.allow);
  const mergedAllow = mergeAllowShapes(baseAllow, incomingAllow);
  const baseDeny = toDenyShape(base.deny);
  const incomingDeny = toDenyShape(incoming.deny);
  const mergedDeny = mergeDenyShapes(baseDeny, incomingDeny);
  const limits = mergeLimits(base.limits, incoming.limits);
  return {
    allow: fromAllowShape(mergedAllow),
    deny: fromDenyShape(mergedDeny),
    ...limits ? {
      limits
    } : {}
  };
}
__name(mergePolicyConfigs, "mergePolicyConfigs");
function normalizePolicyConfig(config) {
  if (!config) {
    return {};
  }
  const allow = config.allow !== void 0 ? fromAllowShape(toAllowShape(config.allow)) : void 0;
  const deny = config.deny !== void 0 ? fromDenyShape(toDenyShape(config.deny)) : void 0;
  const limits = config.limits ? normalizeLimits(config.limits) : void 0;
  return {
    allow,
    deny,
    ...limits ? {
      limits
    } : {}
  };
}
__name(normalizePolicyConfig, "normalizePolicyConfig");
function toAllowShape(value) {
  if (value === true || value === "*" || value === "all") {
    return {
      type: "wildcard"
    };
  }
  const entries = /* @__PURE__ */ new Map();
  if (Array.isArray(value)) {
    entries.set("default", new Set(value.map(String)));
    return {
      type: "map",
      entries
    };
  }
  if (value && typeof value === "object") {
    for (const [key, raw] of Object.entries(value)) {
      if (raw === true || raw === "*" || raw === "all") {
        entries.set(key, /* @__PURE__ */ new Set([
          "*"
        ]));
        continue;
      }
      const vals = Array.isArray(raw) ? raw.map(String) : [
        String(raw)
      ];
      entries.set(key, new Set(vals));
    }
    return {
      type: "map",
      entries
    };
  }
  return {
    type: "map",
    entries
  };
}
__name(toAllowShape, "toAllowShape");
function fromAllowShape(shape) {
  if (shape.type === "wildcard") {
    return true;
  }
  const result = {};
  for (const [key, values] of shape.entries.entries()) {
    if (values.has("*")) {
      result[key] = [
        "*"
      ];
    } else {
      result[key] = Array.from(values);
    }
  }
  return result;
}
__name(fromAllowShape, "fromAllowShape");
function mergeAllowShapes(a, b) {
  if (a.type === "wildcard") return b;
  if (b.type === "wildcard") return a;
  const entries = /* @__PURE__ */ new Map();
  for (const [key, aSet] of a.entries.entries()) {
    const bSet = b.entries.get(key);
    if (!bSet) {
      continue;
    }
    if (aSet.has("*")) {
      entries.set(key, new Set(bSet));
    } else if (bSet.has("*")) {
      entries.set(key, new Set(aSet));
    } else {
      const intersection = /* @__PURE__ */ new Set();
      for (const val of aSet) {
        if (bSet.has(val)) {
          intersection.add(val);
        }
      }
      entries.set(key, intersection);
    }
  }
  return {
    type: "map",
    entries
  };
}
__name(mergeAllowShapes, "mergeAllowShapes");
function toDenyShape(value) {
  if (value === true || value === "*" || value === "all") {
    return {
      type: "wildcard"
    };
  }
  const entries = /* @__PURE__ */ new Map();
  if (Array.isArray(value)) {
    entries.set("default", new Set(value.map(String)));
    return {
      type: "map",
      entries
    };
  }
  if (value && typeof value === "object") {
    for (const [key, raw] of Object.entries(value)) {
      if (raw === true || raw === "*" || raw === "all") {
        entries.set(key, /* @__PURE__ */ new Set([
          "*"
        ]));
        continue;
      }
      const vals = Array.isArray(raw) ? raw.map(String) : [
        String(raw)
      ];
      entries.set(key, new Set(vals));
    }
    return {
      type: "map",
      entries
    };
  }
  return {
    type: "map",
    entries
  };
}
__name(toDenyShape, "toDenyShape");
function fromDenyShape(shape) {
  if (shape.type === "wildcard") {
    return true;
  }
  const result = {};
  for (const [key, values] of shape.entries.entries()) {
    if (values.has("*")) {
      result[key] = [
        "*"
      ];
    } else {
      result[key] = Array.from(values);
    }
  }
  return result;
}
__name(fromDenyShape, "fromDenyShape");
function mergeDenyShapes(a, b) {
  if (a.type === "wildcard" || b.type === "wildcard") {
    return {
      type: "wildcard"
    };
  }
  const entries = /* @__PURE__ */ new Map();
  for (const [key, set] of a.entries.entries()) {
    entries.set(key, new Set(set));
  }
  for (const [key, set] of b.entries.entries()) {
    const existing = entries.get(key);
    if (!existing) {
      entries.set(key, new Set(set));
      continue;
    }
    if (existing.has("*") || set.has("*")) {
      entries.set(key, /* @__PURE__ */ new Set([
        "*"
      ]));
      continue;
    }
    for (const val of set) {
      existing.add(val);
    }
  }
  return {
    type: "map",
    entries
  };
}
__name(mergeDenyShapes, "mergeDenyShapes");
function mergeLimits(a, b) {
  if (!a && !b) {
    return void 0;
  }
  const limits = {};
  if (a?.maxTokens !== void 0 || b?.maxTokens !== void 0) {
    limits.maxTokens = Math.min(a?.maxTokens ?? Number.POSITIVE_INFINITY, b?.maxTokens ?? Number.POSITIVE_INFINITY);
  }
  if (a?.timeout !== void 0 || b?.timeout !== void 0) {
    limits.timeout = Math.min(a?.timeout ?? Number.POSITIVE_INFINITY, b?.timeout ?? Number.POSITIVE_INFINITY);
  }
  return limits;
}
__name(mergeLimits, "mergeLimits");
function normalizeLimits(limits) {
  const normalized = {};
  if (typeof limits.maxTokens === "number") {
    normalized.maxTokens = limits.maxTokens;
  }
  if (typeof limits.timeout === "number") {
    normalized.timeout = limits.timeout;
  }
  return normalized;
}
__name(normalizeLimits, "normalizeLimits");
var MODULE_SOURCE_EXTENSIONS = [
  ".mld.md",
  ".mld",
  ".md",
  ".mlld.md",
  ".mlld"
];
var DIRECTORY_INDEX_FILENAME = "index.mld";
var DEFAULT_DIRECTORY_IMPORT_SKIP_DIRS = [
  "_*",
  ".*"
];
function matchesModuleExtension(candidate) {
  return MODULE_SOURCE_EXTENSIONS.some((ext) => candidate.endsWith(ext));
}
__name(matchesModuleExtension, "matchesModuleExtension");
var _ImportDirectiveEvaluator = class _ImportDirectiveEvaluator {
  // TODO: Integrate capability context construction when import types and security descriptors land.
  constructor(env) {
    __publicField(this, "env");
    __publicField(this, "pathResolver");
    __publicField(this, "securityValidator");
    __publicField(this, "contentProcessor");
    __publicField(this, "variableImporter");
    __publicField(this, "objectResolver");
    this.env = env;
    this.objectResolver = new ObjectReferenceResolver();
    this.pathResolver = new ImportPathResolver(env);
    this.securityValidator = new ImportSecurityValidator(env);
    this.variableImporter = new VariableImporter(this.objectResolver);
    this.contentProcessor = new ModuleContentProcessor(env, this.securityValidator, this.variableImporter);
  }
  /**
  * Main entry point for import directive evaluation
  */
  async evaluateImport(directive, env) {
    try {
      const resolution = await this.pathResolver.resolveImportPath(directive);
      const importContext = this.resolveImportType(directive, resolution);
      resolution.importType = importContext.importType;
      if (importContext.cacheDurationMs !== void 0) {
        resolution.cacheDurationMs = importContext.cacheDurationMs;
      }
      if (resolution.importType === "templates" && resolution.type !== "file") {
        const resolvedPath = await env.resolvePath(resolution.resolvedPath);
        resolution.resolvedPath = resolvedPath;
        resolution.type = "file";
      }
      if (directive?.values?.templateParams && directive.values.templateParams.length > 0 && resolution.importType !== "templates") {
        throw new MlldImportError("Import parameters are only supported with templates imports", {
          code: "IMPORT_TYPE_MISMATCH",
          details: {
            importType: resolution.importType,
            path: resolution.resolvedPath
          }
        });
      }
      const securityLabels = directive.meta?.securityLabels || directive.values?.securityLabels;
      const baseDescriptor = makeSecurityDescriptor({
        labels: securityLabels
      });
      const taintSnapshot = deriveImportTaint({
        importType: resolution.importType ?? "live",
        resolverName: resolution.resolverName,
        source: resolution.resolvedPath,
        resolvedPath: resolution.resolvedPath,
        sourceType: resolution.type,
        labels: resolution.mx?.labels
      });
      const taintDescriptor = makeSecurityDescriptor({
        taint: taintSnapshot.taint,
        labels: taintSnapshot.labels,
        sources: taintSnapshot.sources
      });
      const descriptor = mergeDescriptors(baseDescriptor, taintDescriptor);
      return await this.withPolicyOverride(directive, env, async () => await this.routeImportRequest(resolution, directive, env));
    } catch (error) {
      return this.handleImportError(error, directive, env);
    }
  }
  /**
  * Route import request to appropriate handler
  */
  async routeImportRequest(resolution, directive, env) {
    switch (resolution.type) {
      case "input":
        return this.evaluateInputImport(directive, env);
      case "resolver":
        return this.evaluateResolverImport(directive, resolution.resolverName, env);
      case "module":
        return this.evaluateModuleImport(resolution, directive, env);
      case "file":
      case "url":
        return this.evaluateFileImport(resolution, directive, env);
      default:
        throw new Error(`Unknown import type: ${resolution.type}`);
    }
  }
  /**
  * Handle input imports (@input, @stdin)
  */
  resolveImportType(directive, resolution) {
    const importDirective = directive;
    const declaredType = importDirective.values?.importType;
    const cachedDuration = importDirective.values?.cachedDuration;
    if (declaredType) {
      this.validateDeclaredImportType(declaredType, resolution);
    }
    if (declaredType === "local" && resolution.type === "module") {
      resolution.preferLocal = true;
    }
    const resolvedType = declaredType ?? this.inferImportType(resolution);
    const cacheDurationMs = resolvedType === "cached" ? this.durationToMilliseconds(cachedDuration) : void 0;
    return {
      importType: resolvedType,
      cacheDurationMs
    };
  }
  inferImportType(resolution) {
    switch (resolution.type) {
      case "module":
        return "module";
      case "file":
        return "static";
      case "url":
        return "cached";
      case "input":
        return "live";
      case "resolver":
        return this.inferResolverImportType(resolution);
      default:
        return "live";
    }
  }
  inferResolverImportType(resolution) {
    const name = resolution.resolverName?.toLowerCase();
    if (!name) {
      return "live";
    }
    if (name === "local") {
      return "local";
    }
    if (name === "base" || name === "root" || name === "project") {
      return "static";
    }
    return "live";
  }
  validateDeclaredImportType(type, resolution) {
    const resolverName = resolution.resolverName?.toLowerCase();
    switch (type) {
      case "module":
        if (resolution.type !== "module") {
          throw new MlldImportError("Import type 'module' requires a registry module reference.", {
            code: "IMPORT_TYPE_MISMATCH",
            details: {
              importType: type,
              resolvedType: resolution.type
            }
          });
        }
        return;
      case "cached":
        if (resolution.type !== "url") {
          throw new MlldImportError("Import type 'cached' requires an absolute URL source.", {
            code: "IMPORT_TYPE_MISMATCH",
            details: {
              importType: type,
              resolvedType: resolution.type
            }
          });
        }
        return;
      case "local":
        if (resolution.type === "module") {
          resolution.preferLocal = true;
          return;
        }
        if (resolution.type !== "resolver" || resolverName !== "local") {
          throw new MlldImportError("Import type 'local' expects an @local/... module.", {
            code: "IMPORT_TYPE_MISMATCH",
            details: {
              importType: type,
              resolvedType: resolution.type
            }
          });
        }
        return;
      case "static":
        if (resolution.type === "file") {
          return;
        }
        if (resolution.type === "resolver" && (resolverName === "base" || resolverName === "root" || resolverName === "project")) {
          return;
        }
        throw new MlldImportError("Import type 'static' supports local files or @base/@root/@project resolver paths.", {
          code: "IMPORT_TYPE_MISMATCH",
          details: {
            importType: type,
            resolvedType: resolution.type
          }
        });
      case "live":
        if (resolution.type === "url" || resolution.type === "resolver" || resolution.type === "input") {
          return;
        }
        throw new MlldImportError("Import type 'live' is only valid for resolvers, URLs, or @input.", {
          code: "IMPORT_TYPE_MISMATCH",
          details: {
            importType: type,
            resolvedType: resolution.type
          }
        });
      case "templates": {
        const isAllowedResolver = resolution.type === "resolver" && (resolverName === "base" || resolverName === "root" || resolverName === "project" || resolverName === "local");
        if (resolution.type === "file" || isAllowedResolver) {
          return;
        }
        throw new MlldImportError("Import type 'templates' expects a directory from the local filesystem or @base/@root/@project/@local resolvers.", {
          code: "IMPORT_TYPE_MISMATCH",
          details: {
            importType: type,
            resolvedType: resolution.type
          }
        });
      }
      default:
        return;
    }
  }
  durationToMilliseconds(duration) {
    if (!duration) {
      return void 0;
    }
    const multipliers = {
      seconds: 1e3,
      minutes: 60 * 1e3,
      hours: 60 * 60 * 1e3,
      days: 24 * 60 * 60 * 1e3,
      weeks: 7 * 24 * 60 * 60 * 1e3,
      years: 365 * 24 * 60 * 60 * 1e3
    };
    const value = multipliers[duration.unit];
    if (!value) {
      return void 0;
    }
    return duration.value * value;
  }
  /**
  * Handle input imports (@input, @stdin)
  */
  async evaluateInputImport(directive, env) {
    const resolverManager = env.getResolverManager();
    if (!resolverManager) {
      throw new Error("Resolver manager not available");
    }
    const resolver = resolverManager.getResolver("input");
    if (!resolver) {
      throw new Error("input resolver not found");
    }
    const requestedImports = directive.subtype === "importSelected" ? (directive.values?.imports || []).map((imp) => imp.identifier) : void 0;
    const result = await resolver.resolve("@input", {
      context: "import",
      requestedImports
    });
    let exportData = {};
    if (result.contentType === "data" && typeof result.content === "string") {
      try {
        exportData = JSON.parse(result.content);
      } catch (e) {
        exportData = {
          value: result.content
        };
      }
    } else {
      exportData = {
        value: result.content
      };
    }
    await this.importResolverVariables(directive, exportData, env, "@input");
    return {
      value: void 0,
      env
    };
  }
  /**
  * Handle resolver imports (@now, @debug, etc.)
  */
  async evaluateResolverImport(directive, resolverName, env) {
    const resolverManager = env.getResolverManager();
    if (!resolverManager) {
      throw new Error("Resolver manager not available");
    }
    const resolver = resolverManager.getResolver(resolverName) || resolverManager.getResolver(resolverName.toUpperCase());
    if (!resolver) {
      throw new Error(`Resolver '${resolverName}' not found`);
    }
    if (!resolver.capabilities.contexts.import) {
      const { ResolverError } = await import('./errors-WJULH47E.mjs');
      throw ResolverError.unsupportedCapability(resolver.name, "imports", "import");
    }
    const requestedImports = directive.subtype === "importSelected" ? (directive.values?.imports || []).map((imp) => imp.identifier) : void 0;
    const resolverResult = await resolver.resolve(`@${resolverName}`, {
      context: "import",
      requestedImports
    });
    if (resolverResult.contentType === "module") {
      const ref = resolverResult.mx?.source ?? `@${resolverName}`;
      const taintDescriptor = deriveImportTaint({
        importType: "module",
        resolverName,
        source: ref,
        resolvedPath: ref,
        sourceType: "resolver",
        labels: resolverResult.mx?.labels
      });
      env.recordSecurityDescriptor(makeSecurityDescriptor({
        taint: taintDescriptor.taint,
        labels: taintDescriptor.labels,
        sources: taintDescriptor.sources
      }));
      return this.importFromResolverContent(directive, ref, resolverResult, env);
    }
    let exportData = {};
    if ("getExportData" in resolver) {
      exportData = await this.getResolverExportData(resolver, directive, resolverName);
    } else {
      exportData = await this.fallbackResolverData(resolver, directive, resolverName, resolverResult);
    }
    await this.importResolverVariables(directive, exportData, env, `@${resolverName}`);
    return {
      value: void 0,
      env
    };
  }
  /**
  * Handle module imports (@user/module)
  */
  async evaluateModuleImport(resolution, directive, env) {
    if (resolution.preferLocal) {
      const resolverManager = env.getResolverManager();
      if (!resolverManager || !resolverManager.hasLocalModule(resolution.resolvedPath)) {
        throw new MlldImportError(`Local module not found for ${resolution.resolvedPath}`, {
          code: "LOCAL_MODULE_NOT_FOUND",
          severity: ErrorSeverity.Fatal,
          details: {
            reference: resolution.resolvedPath
          }
        });
      }
    }
    const candidates = this.buildModuleCandidates(resolution);
    let lastError = void 0;
    for (const candidate of candidates) {
      try {
        const resolverContent = await env.resolveModule(candidate, "import");
        if (resolverContent.resolverName) {
          resolution.resolverName = resolverContent.resolverName;
        }
        const treatAsModule = resolverContent.contentType === "module" || matchesModuleExtension(candidate);
        if (!treatAsModule) {
          lastError = new Error(`Import target is not a module: ${candidate} (content type: ${resolverContent.contentType})`);
          continue;
        }
        const importDescriptor = deriveImportTaint({
          importType: resolution.importType ?? "module",
          resolverName: resolverContent.resolverName,
          source: resolverContent.mx?.source ?? resolution.resolvedPath,
          resolvedPath: resolverContent.mx?.source ?? resolution.resolvedPath,
          sourceType: "module",
          labels: resolverContent.mx?.labels
        });
        env.recordSecurityDescriptor(makeSecurityDescriptor({
          taint: importDescriptor.taint,
          labels: importDescriptor.labels,
          sources: importDescriptor.sources
        }));
        await this.validateLockFileVersion(candidate, resolverContent, env);
        return this.importFromResolverContent(directive, candidate, resolverContent, env);
      } catch (error) {
        if (error?.code === "IMPORT_NO_EXPORTS") {
          lastError = error;
          break;
        }
        lastError = error;
      }
    }
    if (lastError) {
      throw lastError;
    }
    throw new Error(`Unable to resolve module import: ${resolution.resolvedPath}`);
  }
  /**
  * Handle file and URL imports
  */
  async evaluateFileImport(resolution, directive, env) {
    const directoryResult = await this.maybeProcessDirectoryImport(resolution, directive, env);
    const processingResult = directoryResult ?? await this.contentProcessor.processModuleContent(resolution, directive);
    this.validateModuleResult(processingResult, directive, resolution.resolvedPath);
    await this.variableImporter.importVariables(processingResult, directive, env);
    this.applyPolicyImportContext(directive, env, resolution.resolvedPath);
    return {
      value: void 0,
      env
    };
  }
  async maybeProcessDirectoryImport(resolution, directive, env) {
    if (resolution.type !== "file") {
      return null;
    }
    if (resolution.importType === "templates") {
      return null;
    }
    const fsService = env.getFileSystemService();
    if (typeof fsService.isDirectory !== "function") {
      return null;
    }
    const baseDir = resolution.resolvedPath;
    const isDir = await fsService.isDirectory(baseDir);
    if (!isDir) {
      return null;
    }
    return await this.processDirectoryImport(fsService, baseDir, resolution, directive, env);
  }
  async processDirectoryImport(fsService, baseDir, resolution, directive, env) {
    if (typeof fsService.readdir !== "function" || typeof fsService.stat !== "function") {
      throw new MlldImportError("Directory import requires filesystem access", {
        code: "DIRECTORY_IMPORT_FS_UNAVAILABLE",
        details: {
          path: baseDir
        }
      });
    }
    const skipDirs = this.getDirectoryImportSkipDirs(directive, baseDir);
    const moduleObject = {};
    const guardDefinitions = [];
    const entries = await fsService.readdir(baseDir);
    for (const entry of entries) {
      const fullPath = path7.join(baseDir, entry);
      const stat = await fsService.stat(fullPath).catch(() => ({
        isDirectory: /* @__PURE__ */ __name(() => false, "isDirectory"),
        isFile: /* @__PURE__ */ __name(() => false, "isFile")
      }));
      if (!stat.isDirectory()) {
        continue;
      }
      if (this.shouldSkipDirectory(entry, skipDirs)) {
        continue;
      }
      const indexPath = path7.join(fullPath, DIRECTORY_INDEX_FILENAME);
      const hasIndex = await fsService.exists(indexPath).catch(() => false);
      if (!hasIndex) {
        continue;
      }
      const indexStat = await fsService.stat(indexPath).catch(() => ({
        isDirectory: /* @__PURE__ */ __name(() => false, "isDirectory"),
        isFile: /* @__PURE__ */ __name(() => false, "isFile")
      }));
      if (!indexStat.isFile()) {
        continue;
      }
      const childResolution = {
        type: "file",
        resolvedPath: indexPath,
        importType: resolution.importType
      };
      const childResult = await this.contentProcessor.processModuleContent(childResolution, directive);
      this.enforceModuleNeeds(childResult.moduleNeeds, indexPath);
      const key = this.sanitizeDirectoryKey(entry);
      if (key in moduleObject) {
        throw new MlldImportError(`Duplicate directory import key '${key}' under ${baseDir}`, {
          code: "DIRECTORY_IMPORT_DUPLICATE_KEY",
          details: {
            path: baseDir,
            key,
            entries: [
              entry
            ]
          }
        });
      }
      moduleObject[key] = childResult.moduleObject;
      if (childResult.guardDefinitions && childResult.guardDefinitions.length > 0) {
        guardDefinitions.push(...childResult.guardDefinitions);
      }
    }
    if (Object.keys(moduleObject).length === 0) {
      throw new MlldImportError(`No ${DIRECTORY_INDEX_FILENAME} modules found under ${baseDir}`, {
        code: "DIRECTORY_IMPORT_EMPTY",
        details: {
          path: baseDir,
          index: DIRECTORY_INDEX_FILENAME
        }
      });
    }
    const childEnv = env.createChild(baseDir);
    childEnv.setCurrentFilePath(baseDir);
    return {
      moduleObject,
      frontmatter: null,
      childEnvironment: childEnv,
      guardDefinitions
    };
  }
  getDirectoryImportSkipDirs(directive, baseDir) {
    const withClause = directive.meta?.withClause || directive.values?.withClause;
    if (!withClause || !("skipDirs" in withClause)) {
      return [
        ...DEFAULT_DIRECTORY_IMPORT_SKIP_DIRS
      ];
    }
    const value = withClause.skipDirs;
    const parsed = this.parseStringArrayOption(value, {
      option: "skipDirs",
      source: baseDir
    });
    return parsed;
  }
  parseStringArrayOption(value, context2) {
    if (Array.isArray(value)) {
      const coerced = value.map((item) => this.coerceStringLiteral(item)).filter((v) => v !== null);
      if (coerced.length !== value.length) {
        throw new MlldImportError(`Import with { ${context2.option}: [...] } only supports string values`, {
          code: "DIRECTORY_IMPORT_INVALID_OPTION",
          details: {
            option: context2.option,
            source: context2.source
          }
        });
      }
      return coerced;
    }
    if (this.isArrayLiteralAst(value)) {
      const coerced = value.items.map((item) => this.coerceStringLiteral(item)).filter((v) => v !== null);
      if (coerced.length !== value.items.length) {
        throw new MlldImportError(`Import with { ${context2.option}: [...] } only supports string values`, {
          code: "DIRECTORY_IMPORT_INVALID_OPTION",
          details: {
            option: context2.option,
            source: context2.source
          }
        });
      }
      return coerced;
    }
    throw new MlldImportError(`Import with { ${context2.option}: [...] } expects an array`, {
      code: "DIRECTORY_IMPORT_INVALID_OPTION",
      details: {
        option: context2.option,
        source: context2.source
      }
    });
  }
  isArrayLiteralAst(value) {
    return Boolean(value && typeof value === "object" && "type" in value && value.type === "array" && "items" in value && Array.isArray(value.items));
  }
  coerceStringLiteral(value) {
    if (typeof value === "string") {
      return value;
    }
    if (value && typeof value === "object") {
      if (value.type === "Literal" && value.valueType === "string") {
        return String(value.value ?? "");
      }
      if ("content" in value && Array.isArray(value.content)) {
        const parts = value.content;
        const hasOnlyLiteralOrText = parts.every((node) => node && typeof node === "object" && (node.type === "Literal" && "value" in node || node.type === "Text" && "content" in node));
        if (!hasOnlyLiteralOrText) {
          return null;
        }
        return parts.map((node) => node.type === "Literal" ? String(node.value ?? "") : String(node.content ?? "")).join("");
      }
    }
    return null;
  }
  shouldSkipDirectory(dirName, patterns) {
    return patterns.some((pattern) => minimatch(dirName, pattern, {
      dot: true
    }));
  }
  sanitizeDirectoryKey(name) {
    const sanitized = name.replace(/[^a-zA-Z0-9_-]/g, "_");
    return sanitized.length > 0 ? sanitized : "module";
  }
  /**
  * Import from resolver content (already resolved)
  */
  async importFromResolverContent(directive, ref, resolverContent, env) {
    if (this.securityValidator.checkCircularImports(ref)) {
      throw new Error(`Circular import detected: ${ref}`);
    }
    try {
      if (process.env.MLLD_DEBUG === "true") {
        console.log(`[ImportDirectiveEvaluator] Resolver content for ${ref}:`, {
          contentLength: resolverContent.content.length,
          contentType: resolverContent.contentType,
          firstChars: resolverContent.content.substring(0, 100)
        });
      }
      const processingRef = typeof resolverContent.metadata?.source === "string" ? resolverContent.metadata.source : ref;
      const processingResult = await this.contentProcessor.processResolverContent(resolverContent.content, processingRef, directive, resolverContent.contentType, resolverContent.mx?.labels);
      this.validateModuleResult(processingResult, directive, processingRef);
      if (process.env.MLLD_DEBUG === "true") {
        console.log(`[ImportDirectiveEvaluator] Processing result for ${ref}:`, {
          moduleObjectKeys: Object.keys(processingResult.moduleObject),
          moduleObjectSize: Object.keys(processingResult.moduleObject).length,
          hasFrontmatter: processingResult.frontmatter !== null
        });
      }
      await this.variableImporter.importVariables(processingResult, directive, env);
      this.applyPolicyImportContext(directive, env, processingRef);
      const dynamicSource = resolverContent.mx?.source;
      if (dynamicSource && typeof dynamicSource === "string" && dynamicSource.startsWith("dynamic://")) {
        const childVariables = processingResult.childEnvironment.getAllVariables?.();
        const parentVariables = env.getAllVariables?.();
        const exportedNames = env.getExportManifest()?.getNames?.() ?? (Array.isArray(resolverContent.metadata?.exports) ? resolverContent.metadata.exports : void 0) ?? processingResult.childEnvironment.getExportManifest?.()?.getNames?.() ?? (childVariables ? Array.from(childVariables.keys()) : void 0) ?? (parentVariables ? Array.from(parentVariables.keys()) : void 0) ?? Object.keys(processingResult.moduleObject ?? {});
        const provenance = env.isProvenanceEnabled?.() === true ? resolverContent.metadata?.provenance ?? this.buildDynamicImportProvenance(dynamicSource ?? ref, env) : void 0;
        env.emitSDKEvent({
          type: "debug:import:dynamic",
          path: ref,
          source: dynamicSource,
          tainted: true,
          variables: exportedNames,
          timestamp: Date.now(),
          ...provenance && {
            provenance
          }
        });
      }
      return {
        value: void 0,
        env
      };
    } finally {
    }
  }
  /**
  * Get export data from resolver with format support
  */
  async getResolverExportData(resolver, directive, resolverName) {
    if (directive.subtype === "importSelected") {
      const imports = directive.values?.imports || [];
      if (imports.length === 1) {
        const importNode = imports[0];
        const format = importNode.identifier.replace(/^["']|["']$/g, "");
        if (importNode.identifier.startsWith('"') || importNode.identifier.startsWith("'")) {
          const exportData = await resolver.getExportData(format);
          return {
            [importNode.alias || format]: exportData[format]
          };
        }
      }
      return await resolver.getExportData();
    } else {
      return await resolver.getExportData();
    }
  }
  /**
  * Fallback resolver data handling
  */
  async fallbackResolverData(resolver, directive, resolverName, resolvedResult) {
    const requestedImports = directive.subtype === "importSelected" ? (directive.values?.imports || []).map((imp) => imp.identifier) : void 0;
    const result = resolvedResult ?? await resolver.resolve(`@${resolverName}`, {
      context: "import",
      requestedImports
    });
    if (result.contentType === "data" && typeof result.content === "string") {
      try {
        return JSON.parse(result.content);
      } catch (e) {
        return {
          value: result.content
        };
      }
    } else {
      return {
        value: result.content
      };
    }
  }
  /**
  * Import variables from resolver data
  */
  async importResolverVariables(directive, exportData, env, sourcePath) {
    const securityLabels = directive.meta?.securityLabels || directive.values?.securityLabels;
    if (directive.subtype === "importSelected") {
      const imports = directive.values?.imports || [];
      for (const importItem of imports) {
        let varName = importItem.identifier.replace(/^["']|["']$/g, "");
        const alias = importItem.alias || varName;
        if (varName in exportData) {
          const value = exportData[varName];
          const variable = this.variableImporter.createVariableFromValue(alias, value, sourcePath, varName, {
            securityLabels,
            env
          });
          env.setVariable(alias, variable);
        } else {
          throw new Error(`Export '${varName}' not found in resolver '${sourcePath}'`);
        }
      }
    } else {
      for (const [name, value] of Object.entries(exportData)) {
        const variable = this.variableImporter.createVariableFromValue(name, value, sourcePath, void 0, {
          securityLabels,
          env
        });
        env.setVariable(name, variable);
      }
    }
  }
  buildModuleCandidates(resolution) {
    const baseRef = resolution.resolvedPath;
    const extension = resolution.moduleExtension;
    const candidates = [];
    if (extension) {
      candidates.push(`${baseRef}${extension}`);
      candidates.push(baseRef);
      return candidates;
    }
    const seen = /* @__PURE__ */ new Set();
    for (const ext of MODULE_SOURCE_EXTENSIONS) {
      const candidate = `${baseRef}${ext}`;
      if (!seen.has(candidate)) {
        seen.add(candidate);
        candidates.push(candidate);
      }
    }
    if (!seen.has(baseRef)) {
      candidates.push(baseRef);
    }
    return candidates;
  }
  /**
  * Extract section content from markdown (copied from original)
  */
  extractSection(content, sectionName) {
    const lines = content.split("\n");
    const sectionRegex = new RegExp(`^#+\\s+${sectionName}\\s*$`, "i");
    let inSection = false;
    let sectionLevel = 0;
    const sectionLines = [];
    for (const line of lines) {
      if (!inSection && sectionRegex.test(line)) {
        inSection = true;
        sectionLevel = line.match(/^#+/)?.[0].length || 0;
        continue;
      }
      if (inSection) {
        const headerMatch = line.match(/^(#+)\\s+/);
        if (headerMatch && headerMatch[1].length <= sectionLevel) {
          break;
        }
        sectionLines.push(line);
      }
    }
    return sectionLines.join("\n").trim();
  }
  /**
  * Validate resolved version against lock file version
  */
  async validateLockFileVersion(candidate, resolverContent, env) {
    if (!resolverContent.metadata?.version || !resolverContent.metadata?.source?.startsWith("registry://")) {
      return;
    }
    const registrySource = resolverContent.metadata.source;
    const moduleMatch = registrySource.match(/^registry:\/\/(@[^@]+)@(.+)$/);
    if (!moduleMatch) {
      return;
    }
    const [, moduleRef, resolvedVersion] = moduleMatch;
    const registryManager = env.getRegistryManager();
    if (!registryManager) {
      return;
    }
    const lockFile = registryManager.getLockFile();
    const lockEntry = lockFile.getImport(moduleRef);
    if (!lockEntry) {
      return;
    }
    if (lockEntry.registryVersion) {
      if (lockEntry.registryVersion !== resolvedVersion) {
        throw new Error(`Locked version mismatch for ${moduleRef}: lock file has version ${lockEntry.registryVersion}, but resolved to version ${resolvedVersion}. Run 'mlld install' to update the lock file or specify the locked version explicitly.`);
      }
    } else {
      if (process.env.MLLD_DEBUG === "true") {
        console.warn(`[LockFileValidation] No version field in lock entry for ${moduleRef}. Resolved to ${resolvedVersion}.`);
      }
    }
  }
  buildDynamicImportProvenance(source, env) {
    const snapshot = env.getSecuritySnapshot?.();
    const normalizedSource = source ? source.startsWith("dynamic://") ? source : `dynamic://${source}` : "dynamic://";
    return makeSecurityDescriptor({
      labels: [
        "untrusted"
      ],
      taint: snapshot?.taint ?? [
        "src:dynamic"
      ],
      sources: snapshot?.sources && snapshot.sources.length > 0 ? snapshot.sources : [
        normalizedSource
      ],
      policyContext: snapshot?.policy
    });
  }
  /**
  * Handle import errors with detailed context
  */
  handleImportError(error, directive, env) {
    throw error;
  }
  async withPolicyOverride(directive, env, operation) {
    const overrideConfig = directive.values?.withClause?.policy;
    if (!overrideConfig) {
      return await operation();
    }
    const previousContext = env.getPolicyContext();
    const mergedConfig = mergePolicyConfigs(previousContext?.configs, normalizePolicyConfig(overrideConfig));
    const nextContext = {
      tier: previousContext?.tier ?? null,
      configs: mergedConfig ?? {},
      activePolicies: previousContext?.activePolicies ?? []
    };
    env.setPolicyContext(nextContext);
    try {
      return await operation();
    } finally {
      env.setPolicyContext(previousContext ?? null);
    }
  }
  applyPolicyImportContext(directive, env, source) {
    const isPolicyImport = directive.subtype === "importPolicy" || directive.meta?.importType === "policy" || directive.values?.importType === "policy";
    if (!isPolicyImport) {
      return;
    }
    const existing = env.getPolicyContext() || {};
    const activePolicies = Array.isArray(existing.activePolicies) ? [
      ...existing.activePolicies
    ] : [];
    const alias = directive.values?.namespace?.[0]?.content || directive.values?.imports?.[0]?.alias || directive.values?.imports?.[0]?.identifier || source || "policy";
    if (!activePolicies.includes(alias)) {
      activePolicies.push(alias);
    }
    const nextContext = {
      tier: existing.tier ?? null,
      configs: existing.configs ?? {},
      activePolicies
    };
    env.setPolicyContext(nextContext);
  }
  validateModuleResult(result, directive, source) {
    this.enforceModuleNeeds(result.moduleNeeds, source);
    this.validateExportBindings(result.moduleObject, directive, source);
  }
  enforceModuleNeeds(needs, source) {
    if (!needs) {
      return;
    }
    const unmet = this.findUnmetNeeds(needs);
    if (unmet.length === 0) {
      return;
    }
    const detailLines = unmet.map((entry) => {
      const valueSegment = entry.value ? ` '${entry.value}'` : "";
      return `- ${entry.capability}${valueSegment}: ${entry.reason}`;
    });
    const label = source ?? "import";
    const message = `Import needs not satisfied for ${label}:
${detailLines.join("\n")}`;
    throw new MlldImportError(message, {
      code: "NEEDS_UNMET",
      details: {
        source: label,
        unmet,
        needs
      }
    });
  }
  findUnmetNeeds(needs) {
    const unmet = [];
    if (needs.sh && !this.isCommandAvailable("sh")) {
      unmet.push({
        capability: "sh",
        reason: "shell executable not available (sh)"
      });
    }
    if (needs.cmd) {
      for (const cmd of this.collectCommandNames(needs.cmd)) {
        if (!this.isCommandAvailable(cmd)) {
          unmet.push({
            capability: "cmd",
            value: cmd,
            reason: "command not found in PATH"
          });
        }
      }
    }
    if (needs.packages) {
      const basePath = this.env.getBasePath ? this.env.getBasePath() : process.cwd();
      const moduleDir = this.env.getCurrentFilePath ? path7.dirname(this.env.getCurrentFilePath() ?? basePath) : basePath;
      for (const [ecosystem, packages] of Object.entries(needs.packages)) {
        if (!Array.isArray(packages)) {
          continue;
        }
        switch (ecosystem) {
          case "node":
            for (const pkg of packages) {
              if (!this.isNodePackageAvailable(pkg.name, moduleDir)) {
                unmet.push({
                  capability: "node",
                  value: pkg.name,
                  reason: "package not installed"
                });
              }
            }
            break;
          case "python":
          case "py":
            if (!this.isRuntimeAvailable([
              "python",
              "python3"
            ])) {
              unmet.push({
                capability: "python",
                reason: "python runtime not available"
              });
            }
            break;
          case "ruby":
          case "rb":
            if (!this.isRuntimeAvailable([
              "ruby"
            ])) {
              unmet.push({
                capability: "ruby",
                reason: "ruby runtime not available"
              });
            }
            break;
          case "go":
            if (!this.isRuntimeAvailable([
              "go"
            ])) {
              unmet.push({
                capability: "go",
                reason: "go runtime not available"
              });
            }
            break;
          case "rust":
            if (!this.isRuntimeAvailable([
              "cargo",
              "rustc"
            ])) {
              unmet.push({
                capability: "rust",
                reason: "rust toolchain not available"
              });
            }
            break;
        }
      }
    }
    return unmet;
  }
  collectCommandNames(cmdNeeds) {
    if (cmdNeeds.type === "all") {
      return [];
    }
    if (cmdNeeds.type === "list") {
      return cmdNeeds.commands;
    }
    return Object.keys(cmdNeeds.entries ?? {});
  }
  isCommandAvailable(command) {
    if (!command || typeof command !== "string") {
      return false;
    }
    const binary = process.platform === "win32" ? "where" : "which";
    const result = spawnSync(binary, [
      command
    ], {
      stdio: "ignore"
    });
    return result.status === 0;
  }
  isRuntimeAvailable(candidates) {
    return candidates.some((cmd) => this.isCommandAvailable(cmd));
  }
  isNodePackageAvailable(name, basePath) {
    try {
      const esmRequire = createRequire(import.meta.url);
      esmRequire.resolve(name, {
        paths: [
          basePath
        ]
      });
      return true;
    } catch {
      return false;
    }
  }
  validateExportBindings(moduleObject, directive, source) {
    if (!directive.values) {
      return;
    }
    const exportKeys = Object.keys(moduleObject || {}).filter((key) => !key.startsWith("__"));
    if (directive.subtype !== "importSelected") {
      return;
    }
    const imports = directive.values?.imports ?? [];
    for (const importItem of imports) {
      const name = importItem?.identifier;
      if (typeof name !== "string") {
        continue;
      }
      if (!exportKeys.includes(name)) {
        throw new MlldImportError(`Import '${name}' not found in module '${source ?? "import"}'`, {
          code: "IMPORT_EXPORT_MISSING",
          details: {
            source,
            missing: name
          }
        });
      }
    }
  }
};
__name(_ImportDirectiveEvaluator, "ImportDirectiveEvaluator");
var ImportDirectiveEvaluator = _ImportDirectiveEvaluator;

// interpreter/eval/import/index.ts
async function evaluateImport(directive, env) {
  const evaluator = new ImportDirectiveEvaluator(env);
  return evaluator.evaluateImport(directive, env);
}
__name(evaluateImport, "evaluateImport");

// interpreter/utils/value-combine.ts
function isPlainObject(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
}
__name(isPlainObject, "isPlainObject");
function combineValues(target, source, targetName) {
  const targetValue = isStructuredValue(target) ? asData(target) : target;
  const sourceValue = isStructuredValue(source) ? asData(source) : source;
  if (Array.isArray(targetValue)) {
    const sourceArray = Array.isArray(sourceValue) ? sourceValue : [
      sourceValue
    ];
    return [
      ...targetValue,
      ...sourceArray
    ];
  }
  if (typeof targetValue === "number") {
    const rhsNumber = toNumber(sourceValue);
    if (Number.isNaN(rhsNumber)) {
      throw new MlldDirectiveError("let", `Cannot += non-numeric value to number @${targetName}.`);
    }
    return targetValue + rhsNumber;
  }
  if (typeof targetValue === "string") {
    return targetValue + asText(sourceValue);
  }
  if (isPlainObject(targetValue)) {
    if (!isPlainObject(sourceValue)) {
      const typeName2 = Array.isArray(sourceValue) ? "array" : typeof sourceValue;
      throw new MlldDirectiveError("let", `Cannot += non-object to object @${targetName}. Target is object, source is ${typeName2}.`);
    }
    return {
      ...targetValue,
      ...sourceValue
    };
  }
  const typeName = targetValue === null ? "null" : typeof targetValue;
  throw new MlldDirectiveError("let", `+= requires array, string, or object target. @${targetName} is ${typeName}.`);
}
__name(combineValues, "combineValues");

// interpreter/eval/when.ts
var DENIED_KEYWORD = "denied";
async function evaluateAssignmentValue(entry, env) {
  let value;
  const tail = entry.withClause;
  let handledByRunEvaluator = false;
  const wrapperType = entry.meta?.wrapperType;
  const firstValue = Array.isArray(entry.value) && entry.value.length > 0 ? entry.value[0] : entry.value;
  if (firstValue && typeof firstValue === "object" && firstValue.type === "code") {
    const { evaluateCodeExecution } = await import('./code-execution-RAAJT3Y7.mjs');
    const result = await evaluateCodeExecution(firstValue, env);
    value = result.value;
  }
  if (firstValue && typeof firstValue === "object" && firstValue.type === "command") {
    const commandNode = firstValue;
    if (tail) {
      const { evaluateRun: evaluateRun2 } = await import('./run-KYGSK2JR.mjs');
      const runDirective = {
        type: "Directive",
        nodeId: entry.nodeId ? `${entry.nodeId}-run` : void 0,
        location: entry.location,
        kind: "run",
        subtype: "runCommand",
        source: "command",
        values: {
          command: commandNode.command,
          withClause: tail
        },
        raw: {
          command: Array.isArray(commandNode.command) ? commandNode.meta?.raw || "" : String(commandNode.command),
          withClause: tail
        },
        meta: {
          isDataValue: true
        }
      };
      const result = await evaluateRun2(runDirective, env);
      value = result.value;
      handledByRunEvaluator = true;
    } else {
      if (Array.isArray(commandNode.command)) {
        const interpolatedCommand = await interpolate(commandNode.command, env, InterpolationContext.ShellCommand);
        value = await env.executeCommand(interpolatedCommand);
      } else {
        value = await env.executeCommand(commandNode.command);
      }
      const { processCommandOutput } = await import('./json-auto-parser-DOBRNARE.mjs');
      value = processCommandOutput(value);
    }
  }
  if (wrapperType && Array.isArray(entry.value)) {
    if (wrapperType === "tripleColon") {
      value = entry.value;
    } else if (wrapperType === "backtick" && entry.value.length === 1 && entry.value[0].type === "Text") {
      value = entry.value[0].content;
    } else {
      value = await interpolate(entry.value, env);
    }
  }
  const isRawPrimitive = firstValue === null || typeof firstValue === "number" || typeof firstValue === "boolean" || typeof firstValue === "string" && !("type" in firstValue);
  if (value === void 0) {
    if (isRawPrimitive) {
      value = entry.value.length === 1 ? firstValue : entry.value;
    } else {
      const valueResult = await evaluate2(entry.value, env, {
        isExpression: true
      });
      value = valueResult.value;
    }
  }
  if (tail && !handledByRunEvaluator) {
    const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
    value = await processPipeline2({
      value,
      env,
      node: entry,
      identifier: entry.identifier,
      location: entry.location
    });
  }
  return value;
}
__name(evaluateAssignmentValue, "evaluateAssignmentValue");
async function evaluateLetAssignment(entry, env) {
  const value = await evaluateAssignmentValue(entry, env);
  const importer = new VariableImporter();
  const variable = importer.createVariableFromValue(entry.identifier, value, "let", void 0, {
    env
  });
  const newEnv = env.createChild();
  newEnv.setVariable(entry.identifier, variable);
  return newEnv;
}
__name(evaluateLetAssignment, "evaluateLetAssignment");
async function evaluateAugmentedAssignment(entry, env) {
  const isolationRoot = findIsolationRoot(env);
  const existing = env.getVariable(entry.identifier);
  if (!existing) {
    throw new MlldWhenExpressionError(`Cannot use += on undefined variable @${entry.identifier}. Use "let @${entry.identifier} = ..." first.`, entry.location);
  }
  if (isolationRoot) {
    const owner = findVariableOwner(env, entry.identifier);
    if (!owner || !isDescendantEnvironment(owner, isolationRoot)) {
      throw new MlldWhenExpressionError(`Parallel for block cannot mutate outer variable @${entry.identifier}.`, entry.location);
    }
  }
  const rhsValue = await evaluateAssignmentValue(entry, env);
  const existingValue = await extractVariableValue(existing, env);
  const combined = combineValues(existingValue, rhsValue, entry.identifier);
  const importer = new VariableImporter();
  const updatedVar = importer.createVariableFromValue(entry.identifier, combined, "let", void 0, {
    env
  });
  let targetEnv = env;
  while (targetEnv && !targetEnv.getCurrentVariables().has(entry.identifier)) {
    targetEnv = targetEnv.getParent();
  }
  (targetEnv ?? env).updateVariable(entry.identifier, updatedVar);
  return env;
}
__name(evaluateAugmentedAssignment, "evaluateAugmentedAssignment");
function findIsolationRoot(env) {
  let current = env;
  while (current) {
    if (current.__parallelIsolationRoot === current) {
      return current;
    }
    current = current.getParent();
  }
  return void 0;
}
__name(findIsolationRoot, "findIsolationRoot");
function findVariableOwner(env, name) {
  let current = env;
  while (current) {
    if (current.getCurrentVariables().has(name)) return current;
    current = current.getParent();
  }
  return void 0;
}
__name(findVariableOwner, "findVariableOwner");
function isDescendantEnvironment(env, ancestor) {
  let current = env;
  while (current) {
    if (current === ancestor) return true;
    current = current.getParent();
  }
  return false;
}
__name(isDescendantEnvironment, "isDescendantEnvironment");
async function compareValues(expressionValue, conditionValue, env) {
  const { resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
  expressionValue = await resolveValue(expressionValue, env, ResolutionContext.Equality);
  conditionValue = await resolveValue(conditionValue, env, ResolutionContext.Equality);
  if ((expressionValue === null || expressionValue === void 0) && (conditionValue === null || conditionValue === void 0)) {
    return true;
  } else if (typeof expressionValue === "string" && typeof conditionValue === "string") {
    return expressionValue === conditionValue;
  } else if (typeof expressionValue === "boolean" && typeof conditionValue === "boolean") {
    return expressionValue === conditionValue;
  } else if (typeof expressionValue === "number" && typeof conditionValue === "number") {
    return expressionValue === conditionValue;
  } else if (typeof expressionValue === "string" && typeof conditionValue === "boolean") {
    return expressionValue === "true" && conditionValue === true || expressionValue === "false" && conditionValue === false;
  } else if (typeof expressionValue === "boolean" && typeof conditionValue === "string") {
    return expressionValue === true && conditionValue === "true" || expressionValue === false && conditionValue === "false";
  } else if (typeof conditionValue === "boolean") {
    return isTruthy(expressionValue) === conditionValue;
  } else {
    return expressionValue === conditionValue;
  }
}
__name(compareValues, "compareValues");
function preview(value, max = 60) {
  try {
    if (typeof value === "string") return value.length > max ? value.slice(0, max) + "\u2026" : value;
    if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) return String(value);
    return JSON.stringify(value)?.slice(0, max) + (JSON.stringify(value)?.length > max ? "\u2026" : "");
  } catch {
    return String(value);
  }
}
__name(preview, "preview");
async function evaluateWhen(node, env) {
  if (isWhenSimpleNode(node)) {
    return evaluateWhenSimple(node, env);
  } else if (isWhenMatchNode(node)) {
    return evaluateWhenMatch(node, env);
  } else if (isWhenBlockNode(node)) {
    return evaluateWhenBlock(node, env);
  }
  throw new MlldConditionError(`Unknown when node subtype: ${node.subtype}`, void 0, node.location);
}
__name(evaluateWhen, "evaluateWhen");
async function evaluateWhenSimple(node, env) {
  const conditionResult = await evaluateCondition(node.values.condition, env);
  if (process.env.DEBUG_WHEN) {
    logger.debug("When condition result:", {
      conditionResult
    });
  }
  if (conditionResult) {
    const result = await evaluate2(node.values.action, env);
    return result;
  }
  return {
    value: "",
    env
  };
}
__name(evaluateWhenSimple, "evaluateWhenSimple");
async function evaluateWhenMatch(node, env) {
  validateNonePlacement(node.values.conditions);
  let expressionValue;
  if (node.values.expression.length === 1 && node.values.expression[0].type === "Text") {
    expressionValue = node.values.expression[0].content;
  } else {
    const expressionResult = await evaluate2(node.values.expression, env);
    expressionValue = expressionResult.value;
  }
  let childEnv = env.createChild();
  for (const entry of node.values.conditions) {
    if (isLetAssignment(entry)) {
      childEnv = await evaluateLetAssignment(entry, childEnv);
    } else if (isAugmentedAssignment(entry)) {
      childEnv = await evaluateAugmentedAssignment(entry, childEnv);
    }
  }
  const conditionPairs = node.values.conditions.filter(isConditionPair);
  let anyNonNoneMatched = false;
  try {
    for (const pair of conditionPairs) {
      if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
        continue;
      }
      let isNegated = false;
      let actualCondition = pair.condition;
      if (actualCondition.length === 1 && actualCondition[0].type === "UnaryExpression") {
        const unaryNode = actualCondition[0];
        if (unaryNode.operator === "!") {
          isNegated = true;
          actualCondition = [
            unaryNode.operand
          ];
        }
      }
      let conditionValue;
      if (actualCondition.length === 1 && actualCondition[0].type === "Text") {
        conditionValue = actualCondition[0].content;
      } else if (actualCondition.length === 1 && actualCondition[0].type === "ExecInvocation") {
        const execResult = await evaluateCondition(actualCondition, childEnv);
        conditionValue = execResult;
      } else {
        const conditionResult = await evaluate2(actualCondition, childEnv);
        conditionValue = conditionResult.value;
      }
      let matches = await compareValues(expressionValue, conditionValue, childEnv);
      if (isNegated) {
        matches = !matches;
      }
      if (matches) {
        anyNonNoneMatched = true;
        if (pair.action) {
          const actionNodes = Array.isArray(pair.action) ? pair.action : [
            pair.action
          ];
          for (const actionNode of actionNodes) {
            await evaluate2(actionNode, childEnv);
          }
          env.mergeChild(childEnv);
          return {
            value: "",
            env
          };
        }
      }
    }
    if (!anyNonNoneMatched) {
      for (const pair of conditionPairs) {
        if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
          if (pair.action) {
            const actionNodes = Array.isArray(pair.action) ? pair.action : [
              pair.action
            ];
            for (const actionNode of actionNodes) {
              await evaluate2(actionNode, childEnv);
            }
            env.mergeChild(childEnv);
            return {
              value: "",
              env
            };
          }
        }
      }
    }
    return {
      value: "",
      env
    };
  } finally {
  }
}
__name(evaluateWhenMatch, "evaluateWhenMatch");
async function evaluateWhenBlock(node, env) {
  const modifier = node.meta.modifier;
  let expressionNodes;
  let variableName;
  if (node.values.variable && node.meta.hasVariable) {
    expressionNodes = node.values.variable;
    if (expressionNodes.length === 1 && expressionNodes[0].type === "VariableReference") {
      const varRef = expressionNodes[0];
      variableName = varRef.identifier;
      if (variableName) {
        env.hasVariable(variableName) ? env.getVariable(variableName) : void 0;
      }
    }
  }
  let childEnv = env.createChild();
  for (const entry of node.values.conditions) {
    if (isLetAssignment(entry)) {
      childEnv = await evaluateLetAssignment(entry, childEnv);
    } else if (isAugmentedAssignment(entry)) {
      childEnv = await evaluateAugmentedAssignment(entry, childEnv);
    }
  }
  const conditions = node.values.conditions.filter(isConditionPair);
  try {
    let result;
    switch (modifier) {
      case "first":
        result = await evaluateFirstMatch(conditions, childEnv, variableName, expressionNodes);
        break;
      case "all":
        throw new MlldConditionError("The 'all' modifier has been removed. Use the && operator instead.\nExample: /when (@cond1 && @cond2) => action", "all", node.location);
      case "any":
        throw new MlldConditionError("The 'any' modifier has been removed. Use the || operator instead.\nExample: /when (@cond1 || @cond2) => action", "any", node.location);
      case "default":
        if (node.values.action) {
          result = await evaluateAllMatches(conditions, childEnv, variableName, node.values.action);
        } else {
          result = await evaluateAllMatches(conditions, childEnv, variableName);
        }
        break;
      default:
        throw new MlldConditionError(`Invalid when modifier: ${modifier}`, modifier, node.location);
    }
    if (process.env.DEBUG_WHEN) {
      logger.debug("Before merge:", {
        parentNodes: env.nodes.length,
        childNodes: childEnv.nodes.length,
        childInitialCount: childEnv.initialNodeCount,
        resultEnvNodes: result.env.nodes.length
      });
    }
    env.mergeChild(result.env);
    if (process.env.DEBUG_WHEN) {
      logger.debug("After merge:", {
        parentEnvNodes: env.nodes.length,
        resultValue: result.value
      });
    }
    return {
      value: result.value,
      env
    };
  } finally {
  }
}
__name(evaluateWhenBlock, "evaluateWhenBlock");
async function evaluateFirstMatch(conditions, env, variableName, expressionNodes) {
  validateNonePlacement(conditions);
  let expressionValue;
  if (expressionNodes && expressionNodes.length > 0) {
    if (expressionNodes.length === 1 && expressionNodes[0].type === "Text") {
      expressionValue = expressionNodes[0].content;
    } else if (expressionNodes.length === 1 && expressionNodes[0].type === "VariableReference") {
      const varRef = expressionNodes[0];
      const variable = env.getVariable(varRef.identifier);
      if (variable) {
        expressionValue = variable.value;
      }
    } else {
      const expressionResult = await evaluate2(expressionNodes, env);
      expressionValue = expressionResult.value;
    }
  }
  let anyNonNoneMatched = false;
  for (const pair of conditions) {
    if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
      if (!anyNonNoneMatched) {
        if (pair.action) {
          const actionNodes = Array.isArray(pair.action) ? pair.action : [
            pair.action
          ];
          for (const actionNode of actionNodes) {
            await evaluate2(actionNode, env);
          }
        }
        return {
          value: "",
          env
        };
      }
      continue;
    }
    let matches = false;
    if (expressionValue !== void 0) {
      let conditionValue;
      let isNegated = false;
      let actualCondition = pair.condition;
      if (actualCondition.length === 1 && actualCondition[0].type === "UnaryExpression") {
        const unaryNode = actualCondition[0];
        if (unaryNode.operator === "!") {
          isNegated = true;
          actualCondition = [
            unaryNode.operand
          ];
        }
      }
      if (actualCondition.length === 1 && actualCondition[0].type === "Text") {
        conditionValue = actualCondition[0].content;
      } else if (actualCondition.length === 1 && actualCondition[0].type === "ExecInvocation") {
        const execResult = await evaluateCondition(actualCondition, env);
        conditionValue = execResult;
      } else {
        const conditionResult = await evaluate2(actualCondition, env);
        conditionValue = conditionResult.value;
      }
      matches = await compareValues(expressionValue, conditionValue, env);
      if (isNegated) {
        matches = !matches;
      }
    } else {
      matches = await evaluateCondition(pair.condition, env, variableName);
    }
    if (matches) {
      anyNonNoneMatched = true;
      if (pair.action) {
        const result = await evaluate2(pair.action, env);
        return result;
      }
      return {
        value: "",
        env
      };
    }
  }
  return {
    value: "",
    env
  };
}
__name(evaluateFirstMatch, "evaluateFirstMatch");
async function evaluateAllMatches(conditions, env, variableName, blockAction) {
  validateNonePlacement(conditions);
  if (blockAction) {
    if (conditions.some((pair) => pair.action)) {
      throw new MlldConditionError(`Invalid @when syntax: 'all:' modifier cannot have individual actions for conditions when using a block action. Use either individual actions OR a block action after the conditions: @when all: [...] => @add "action"`, "all", void 0);
    }
    let allMatch = true;
    for (const pair of conditions) {
      if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
        continue;
      }
      const conditionResult = await evaluateCondition(pair.condition, env, variableName);
      if (!conditionResult) {
        allMatch = false;
        break;
      }
    }
    if (allMatch) {
      if (process.env.DEBUG_WHEN) {
        logger.debug("Executing block action", {
          envNodesBefore: env.nodes.length
        });
      }
      const result = await evaluate2(blockAction, env);
      if (process.env.DEBUG_WHEN) {
        logger.debug("Block action completed", {
          result,
          envNodesAfter: env.nodes.length
        });
      }
      return result;
    }
    return {
      value: "",
      env
    };
  }
  const results = [];
  let anyNonNoneMatched = false;
  for (const pair of conditions) {
    if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
      continue;
    }
    const conditionResult = await evaluateCondition(pair.condition, env, variableName);
    if (conditionResult) {
      anyNonNoneMatched = true;
      if (pair.action) {
        const actionResult = await evaluate2(pair.action, env);
        if (actionResult.value) {
          results.push(String(actionResult.value));
        }
      }
    }
  }
  if (!anyNonNoneMatched) {
    for (const pair of conditions) {
      if (pair.condition.length === 1 && isNoneCondition(pair.condition[0])) {
        if (pair.action) {
          const actionResult = await evaluate2(pair.action, env);
          if (actionResult.value) {
            results.push(String(actionResult.value));
          }
        }
      }
    }
  }
  return {
    value: results.length > 1 ? results.join("\n") : results.join(""),
    env
  };
}
__name(evaluateAllMatches, "evaluateAllMatches");
async function evaluateCondition(condition, env, variableName) {
  const deniedContext = env.getContextManager().peekDeniedContext();
  const deniedState = Boolean(deniedContext?.denied);
  if (condition.length === 1 && condition[0].type === "WhenCondition") {
    const whenCondition = condition[0];
    const expression = whenCondition.expression;
    const result2 = await evaluateCondition([
      expression
    ], env, variableName);
    return whenCondition.negated ? !result2 : result2;
  }
  if (condition.length === 1 && condition[0].type === "UnaryExpression") {
    const unaryNode = condition[0];
    if (unaryNode.operator === "!") {
      if (isDeniedLiteralNode(unaryNode.operand)) {
        return !deniedState;
      }
      const innerCondition = [
        unaryNode.operand
      ];
      const innerResult = await evaluateCondition(innerCondition, env, variableName);
      return !innerResult;
    }
  }
  if (condition.length === 1 && isDeniedLiteralNode(condition[0])) {
    return deniedState;
  }
  if (condition.length === 1) {
    const node = condition[0];
    if (node.type === "BinaryExpression" || node.type === "TernaryExpression" || node.type === "UnaryExpression") {
      const { evaluateUnifiedExpression: evaluateUnifiedExpression2 } = await import('./expressions-CYFHZWDH.mjs');
      let resultValue;
      try {
        const expressionResult = await evaluateUnifiedExpression2(node, env);
        resultValue = expressionResult.value;
      } catch (err) {
        const op = node.operator || node.test?.type || node.type;
        const lhs = node.left ?? node.argument ?? node.test;
        const rhs = node.right ?? node.consequent;
        const message = `Failed to evaluate condition expression (${op}).`;
        throw new MlldConditionError(message, void 0, node.location, {
          originalError: err,
          errors: [
            {
              type: "expression",
              count: 1,
              firstExample: {
                conditionIndex: 0,
                message: `op=${op}, left=${preview(lhs)}, right=${preview(rhs)}`
              }
            }
          ]
        });
      }
      const truthy = isTruthy(resultValue);
      if (process.env.MLLD_DEBUG === "true") {
        try {
          console.error("[evaluateCondition] expression node result:", {
            nodeType: node.type,
            result: resultValue,
            truthy
          });
        } catch {
        }
      }
      return truthy;
    }
  }
  if (condition.length === 1 && condition[0].type === "ExecInvocation") {
    const execNode = condition[0];
    const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
    const childEnv2 = env.createChild();
    if (variableName) {
      const variable = env.getVariable(variableName);
      if (variable) {
        const modifiedExecNode = {
          ...execNode,
          commandRef: {
            ...execNode.commandRef,
            args: [
              // Insert the variable's value as the first argument
              {
                type: "VariableReference",
                identifier: variableName,
                nodeId: "implicit-when-arg",
                valueType: "variable"
              },
              ...execNode.commandRef.args || []
            ]
          }
        };
        let result3;
        try {
          result3 = await evaluateExecInvocation(modifiedExecNode, childEnv2);
        } catch (err) {
          const name = modifiedExecNode?.commandRef?.name || "exec";
          throw new MlldConditionError(`Failed to evaluate function in condition: ${name}`, void 0, modifiedExecNode.location, {
            originalError: err
          });
        }
        if (result3.stdout !== void 0) {
          if (result3.exitCode !== void 0 && result3.exitCode !== 0) {
            return false;
          }
          if (result3.value !== void 0 && result3.value !== result3.stdout) {
            const { resolveValue: resolveValue4, ResolutionContext: ResolutionContext4 } = await import('./variable-resolution-HFG3FTZK.mjs');
            const finalValue4 = await resolveValue4(result3.value, childEnv2, ResolutionContext4.Truthiness);
            return isTruthy(finalValue4);
          }
          return isTruthy(result3.stdout.trim());
        }
        const { resolveValue: resolveValue3, ResolutionContext: ResolutionContext3 } = await import('./variable-resolution-HFG3FTZK.mjs');
        const finalValue3 = await resolveValue3(result3.value, childEnv2, ResolutionContext3.Truthiness);
        return isTruthy(finalValue3);
      }
    }
    let result2;
    try {
      result2 = await evaluateExecInvocation(execNode, childEnv2);
    } catch (err) {
      const name = execNode?.commandRef?.name || "exec";
      throw new MlldConditionError(`Failed to evaluate function in condition: ${name}`, void 0, execNode.location, {
        originalError: err
      });
    }
    if (result2.stdout !== void 0) {
      if (result2.exitCode !== void 0 && result2.exitCode !== 0) {
        return false;
      }
      if (result2.value !== void 0 && result2.value !== result2.stdout) {
        const { resolveValue: resolveValue3, ResolutionContext: ResolutionContext3 } = await import('./variable-resolution-HFG3FTZK.mjs');
        const finalValue3 = await resolveValue3(result2.value, childEnv2, ResolutionContext3.Truthiness);
        return isTruthy(finalValue3);
      }
      return isTruthy(result2.stdout.trim());
    }
    const { resolveValue: resolveValue2, ResolutionContext: ResolutionContext2 } = await import('./variable-resolution-HFG3FTZK.mjs');
    const finalValue2 = await resolveValue2(result2.value, childEnv2, ResolutionContext2.Truthiness);
    return isTruthy(finalValue2);
  }
  const childEnv = env.createChild();
  if (variableName) {
    const variable = env.getVariable(variableName);
    if (variable) {
      childEnv.setVariable("_whenValue", variable);
    }
  }
  if (process.env.DEBUG_WHEN) {
    logger.debug("Evaluating condition:", {
      condition
    });
  }
  let result;
  try {
    result = await evaluate2(condition, childEnv, {
      isCondition: true,
      isExpression: true
    });
  } catch (err) {
    throw new MlldConditionError("Failed to evaluate condition value", void 0, condition[0]?.location, {
      originalError: err
    });
  }
  if (process.env.DEBUG_WHEN) {
    logger.debug("Condition evaluation result:", {
      result
    });
  }
  if (variableName && childEnv.hasVariable("_whenValue")) {
    const whenValue = childEnv.getVariable("_whenValue");
    if (result.value && typeof result.value === "object" && result.value.type === "executable") {
      const { resolveValue: resolveValue2, ResolutionContext: ResolutionContext2 } = await import('./variable-resolution-HFG3FTZK.mjs');
      const finalValue2 = await resolveValue2(result.value, childEnv, ResolutionContext2.Truthiness);
      return isTruthy(finalValue2);
    }
    let actualValue;
    if (whenValue && typeof whenValue === "object" && "value" in whenValue) {
      actualValue = whenValue.value;
    } else {
      actualValue = whenValue;
    }
    return compareValues(actualValue, result.value, childEnv);
  }
  if (result.stdout !== void 0) {
    if (result.exitCode !== void 0 && result.exitCode !== 0) {
      return false;
    }
    if (result.value !== void 0 && result.value !== result.stdout) {
      const { resolveValue: resolveValue2, ResolutionContext: ResolutionContext2 } = await import('./variable-resolution-HFG3FTZK.mjs');
      const finalValue2 = await resolveValue2(result.value, childEnv, ResolutionContext2.Truthiness);
      return isTruthy(finalValue2);
    }
    const trimmedStdout = result.stdout.trim();
    if (process.env.DEBUG_WHEN) {
      logger.debug("Trimmed stdout for truthiness:", {
        trimmedStdout
      });
    }
    return isTruthy(trimmedStdout);
  }
  const { resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
  const finalValue = await resolveValue(result.value, childEnv, ResolutionContext.Truthiness);
  return isTruthy(finalValue);
}
__name(evaluateCondition, "evaluateCondition");
function isDeniedLiteralNode(node) {
  if (!node) {
    return false;
  }
  if (node.type === "Literal" && typeof node.value === "string") {
    return node.value.toLowerCase() === DENIED_KEYWORD;
  }
  if (node.type === "Text" && typeof node.content === "string") {
    return node.content.trim().toLowerCase() === DENIED_KEYWORD;
  }
  if (node.type === "VariableReference" && typeof node.identifier === "string" && node.identifier.toLowerCase() === DENIED_KEYWORD) {
    return true;
  }
  return false;
}
__name(isDeniedLiteralNode, "isDeniedLiteralNode");
function isDeniedField(field) {
  if (!field) {
    return false;
  }
  if (typeof field.name === "string" && field.name.toLowerCase() === DENIED_KEYWORD) {
    return true;
  }
  if (typeof field.identifier === "string" && field.identifier.toLowerCase() === DENIED_KEYWORD) {
    return true;
  }
  return false;
}
__name(isDeniedField, "isDeniedField");
function conditionTargetsDenied(condition) {
  const visited = /* @__PURE__ */ new Set();
  const stack = [
    ...condition
  ];
  while (stack.length > 0) {
    const node = stack.pop();
    if (!node || typeof node !== "object") {
      continue;
    }
    if (visited.has(node)) {
      continue;
    }
    visited.add(node);
    if (isDeniedLiteralNode(node)) {
      return true;
    }
    if (node.type === "VariableReference") {
      const identifier = typeof node.identifier === "string" ? node.identifier.toLowerCase() : "";
      if (identifier === DENIED_KEYWORD) {
        return true;
      }
      if (identifier === "mx" && Array.isArray(node.fields) && node.fields.some(isDeniedField)) {
        return true;
      }
    }
    for (const value of Object.values(node)) {
      if (Array.isArray(value)) {
        for (const item of value) {
          if (item && typeof item === "object" && "type" in item) {
            stack.push(item);
          }
        }
      } else if (value && typeof value === "object" && "type" in value) {
        stack.push(value);
      }
    }
  }
  return false;
}
__name(conditionTargetsDenied, "conditionTargetsDenied");
function isTruthy(value) {
  if (value && typeof value === "object" && "type" in value && "name" in value) {
    const variable = value;
    if (isTextLike(variable)) {
      const str = variable.value;
      if (str === "" || str.toLowerCase() === "false" || str === "0") {
        return false;
      }
      return true;
    } else if (isArray(variable)) {
      return variable.value.length > 0;
    } else if (isObject(variable)) {
      return Object.keys(variable.value).length > 0;
    } else if (isCommandResult(variable)) {
      return variable.value.trim().length > 0;
    } else if (isPipelineInput(variable)) {
      assertStructuredValue(variable.value, "when:isTruthy:pipeline-input");
      return asText(variable.value).length > 0;
    }
    return isTruthy(variable.value);
  }
  if (isStructuredValue(value)) {
    try {
      const structuredData = asData(value);
      return isTruthy(structuredData);
    } catch {
      return isTruthy(asText(value));
    }
  }
  if (value === null || value === void 0) {
    return false;
  }
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value === "string") {
    if (value === "") {
      return false;
    }
    if (value.toLowerCase() === "false") {
      return false;
    }
    if (value === "0") {
      return false;
    }
    return true;
  }
  if (typeof value === "number") {
    return value !== 0 && !isNaN(value);
  }
  if (Array.isArray(value)) {
    return value.length > 0;
  }
  if (typeof value === "object") {
    return Object.keys(value).length > 0;
  }
  return true;
}
__name(isTruthy, "isTruthy");
function isNoneCondition(condition) {
  return condition?.type === "Literal" && condition?.valueType === "none";
}
__name(isNoneCondition, "isNoneCondition");
function validateNonePlacement(conditions) {
  let foundNone = false;
  let foundWildcard = false;
  for (let i = 0; i < conditions.length; i++) {
    const condition = conditions[i].condition || conditions[i];
    if (isNoneCondition(condition)) {
      foundNone = true;
    } else if (condition?.type === "Literal" && condition?.valueType === "wildcard") {
      foundWildcard = true;
      if (foundNone) {
        continue;
      }
    } else if (foundNone) {
      throw new Error('The "none" keyword can only appear as the last condition(s) in a when block');
    }
    if (foundWildcard && isNoneCondition(condition)) {
      throw new Error('The "none" keyword cannot appear after "*" (wildcard) as it would never be reached');
    }
  }
}
__name(validateNonePlacement, "validateNonePlacement");

// interpreter/eval/data-values/EvaluationStateManager.ts
var _EvaluationStateManager = class _EvaluationStateManager {
  constructor() {
    __publicField(this, "evaluationCache", /* @__PURE__ */ new Map());
  }
  /**
  * Attempts to retrieve a cached evaluation result
  * @param value The data value to check cache for
  * @returns Cache result with hit status and cached data/error
  */
  getCachedResult(value) {
    const cached = this.evaluationCache.get(value);
    if (!cached) {
      return null;
    }
    if (cached.evaluated && !cached.error) {
      return {
        hit: true,
        result: cached.result
      };
    }
    if (cached.evaluated && cached.error) {
      return {
        hit: true,
        error: cached.error
      };
    }
    return null;
  }
  /**
  * Stores an evaluation result in the cache
  * @param value The data value to cache results for
  * @param result The evaluation result (if successful)
  * @param error The error that occurred (if failed)
  */
  setCachedResult(value, result, error) {
    const state = {
      evaluated: true,
      result,
      error
    };
    this.evaluationCache.set(value, state);
  }
  /**
  * Clears all cached evaluation results
  */
  clearCache() {
    this.evaluationCache.clear();
  }
  /**
  * Gets cache performance statistics
  * @returns Object with cache size and other metrics
  */
  getCacheStats() {
    return {
      size: this.evaluationCache.size,
      entries: this.evaluationCache.size
    };
  }
  /**
  * Removes a specific cache entry
  * @param value The data value to remove from cache
  */
  removeCacheEntry(value) {
    return this.evaluationCache.delete(value);
  }
  /**
  * Checks if a value has been cached
  * @param value The data value to check
  * @returns True if value is in cache
  */
  isCached(value) {
    return this.evaluationCache.has(value);
  }
};
__name(_EvaluationStateManager, "EvaluationStateManager");
var EvaluationStateManager = _EvaluationStateManager;

// interpreter/eval/data-values/PrimitiveEvaluator.ts
async function interpolateAndRecord(nodes, env, context2 = InterpolationContext.Default) {
  const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
  const descriptors = [];
  const text = await interpolate2(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord, "interpolateAndRecord");
var _PrimitiveEvaluator = class _PrimitiveEvaluator {
  constructor(stateManager) {
    __publicField(this, "stateManager");
    this.stateManager = stateManager;
  }
  /**
  * Checks if this evaluator can handle the given data value
  */
  canHandle(value) {
    if (isPrimitiveValue(value)) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "Text" && "content" in value) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "Literal" && "value" in value) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "RegexLiteral") {
      return true;
    }
    if (value && typeof value === "object" && "wrapperType" in value && "content" in value && Array.isArray(value.content)) {
      return true;
    }
    if (value && typeof value === "object" && "needsInterpolation" in value && "parts" in value && Array.isArray(value.parts)) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "command" && "command" in value) {
      return true;
    }
    if (isDirectiveValue(value)) {
      return true;
    }
    return false;
  }
  /**
  * Evaluates primitive data values and simple AST nodes
  */
  async evaluate(value, env) {
    if (isPrimitiveValue(value)) {
      return value;
    }
    if (value && typeof value === "object" && value.type === "Text" && "content" in value) {
      return value.content;
    }
    if (value && typeof value === "object" && value.type === "Literal" && "value" in value) {
      return value.value;
    }
    if (value && typeof value === "object" && value.type === "RegexLiteral") {
      const pattern = value.pattern || "";
      const flags = value.flags || "";
      return new RegExp(pattern, flags);
    }
    if (value && typeof value === "object" && "wrapperType" in value && "content" in value && Array.isArray(value.content)) {
      const contentArray = value.content;
      const hasOnlyLiteralsOrText = contentArray.every((node) => node && typeof node === "object" && (node.type === "Literal" && "value" in node || node.type === "Text" && "content" in node));
      if (hasOnlyLiteralsOrText) {
        if (process.env.MLLD_DEBUG_FIX === "true") {
          console.error("[PrimitiveEvaluator] literal/text wrapper", {
            wrapperType: value.wrapperType,
            items: contentArray.map((n) => n?.type)
          });
        }
        return contentArray.map((node) => node.type === "Literal" ? node.value : node.content).join("");
      }
      if (process.env.MLLD_DEBUG_FIX === "true") {
        console.error("[PrimitiveEvaluator] interpolating wrapper", {
          wrapperType: value.wrapperType,
          itemTypes: contentArray.map((n) => n?.type)
        });
      }
      return await interpolateAndRecord(value.content, env);
    }
    if (value && typeof value === "object" && "needsInterpolation" in value && "parts" in value && Array.isArray(value.parts)) {
      return await interpolateAndRecord(value.parts, env);
    }
    if (value && typeof value === "object" && value.type === "command" && "command" in value) {
      return await this.evaluateCommandObject(value, env);
    }
    if (isDirectiveValue(value)) {
      return await this.evaluateDirective(value, env);
    }
    throw new Error(`PrimitiveEvaluator cannot handle value type: ${typeof value}`);
  }
  /**
  * Evaluates a command object (from run directives in objects)
  */
  async evaluateCommandObject(value, env) {
    let commandStr;
    if (typeof value.command === "string") {
      commandStr = value.command;
    } else if (Array.isArray(value.command)) {
      commandStr = await interpolateAndRecord(value.command, env, InterpolationContext.ShellCommand);
    } else {
      throw new Error("Invalid command format in command object evaluation");
    }
    const result = await env.executeCommand(commandStr);
    return result;
  }
  /**
  * Evaluates an embedded directive with caching
  */
  async evaluateDirective(value, env) {
    const cached = this.stateManager.getCachedResult(value);
    if (cached?.hit && !cached.error) {
      return cached.result;
    }
    if (cached?.hit && cached.error) {
      throw cached.error;
    }
    try {
      const childEnv = env.createChild();
      const result = await evaluate2([
        value
      ], childEnv);
      let finalValue = result.value;
      if ((value.kind === "run" || value.kind === "add") && typeof finalValue === "string") {
        finalValue = finalValue.replace(/\n+$/, "");
      }
      this.stateManager.setCachedResult(value, finalValue);
      return finalValue;
    } catch (error) {
      this.stateManager.setCachedResult(value, void 0, error);
      throw error;
    }
  }
};
__name(_PrimitiveEvaluator, "PrimitiveEvaluator");
var PrimitiveEvaluator = _PrimitiveEvaluator;
async function interpolateAndRecord2(nodes, env, context2 = InterpolationContext.Default) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord2, "interpolateAndRecord");
var _CollectionEvaluator = class _CollectionEvaluator {
  constructor(evaluateDataValue2) {
    __publicField(this, "evaluateDataValue");
    this.evaluateDataValue = evaluateDataValue2;
  }
  /**
  * Checks if this evaluator can handle the given data value
  */
  canHandle(value) {
    if (isStructuredValue(value)) {
      return true;
    }
    if (value?.type === "object") {
      return true;
    }
    if (value?.type === "array") {
      return true;
    }
    if (Array.isArray(value)) {
      if (value.length === 1 && value[0] && typeof value[0] === "object" && value[0].type === "foreach-command") {
        return true;
      }
      const isTemplateContent = value.every((item) => item?.type === "Text" || item?.type === "VariableReference");
      return isTemplateContent || value.every((item) => typeof item === "string");
    }
    if (typeof value === "object" && value !== null && !value.type && !Array.isArray(value)) {
      return true;
    }
    return false;
  }
  /**
  * Evaluates collection data values with recursive evaluation
  */
  async evaluate(value, env) {
    if (isStructuredValue(value)) {
      return value.data;
    }
    if (value?.type === "object") {
      if (!Array.isArray(value.entries) && !value.properties) {
        return value;
      }
      return await this.evaluateObject(value, env);
    }
    if (value?.type === "array") {
      const items = value.items ?? value.elements;
      if (!Array.isArray(items)) {
        return value;
      }
      return await this.evaluateArray(value, env);
    }
    if (Array.isArray(value)) {
      if (value.length === 1 && value[0] && typeof value[0] === "object" && value[0].type === "foreach-command") {
        return await this.evaluateDataValue(value[0], env);
      }
      const isTemplateContent = value.every((item) => item?.type === "Text" || item?.type === "VariableReference");
      if (isTemplateContent) {
        return await interpolateAndRecord2(value, env);
      }
      return value;
    }
    if (typeof value === "object" && value !== null && !value.type && !Array.isArray(value)) {
      return await this.evaluatePlainObject(value, env);
    }
    throw new Error(`CollectionEvaluator cannot handle value type: ${typeof value}`);
  }
  /**
  * Evaluates an object with recursive property evaluation and error isolation
  * Supports both pair entries and spread entries for object composition
  */
  async evaluateObject(value, env) {
    const evaluatedObj = {};
    if (Array.isArray(value.entries)) {
      for (const entry of value.entries) {
        if (entry.type === "pair") {
          try {
            let evaluated = await this.evaluateDataValue(entry.value, env, {
              suppressErrors: true
            });
            if (isStructuredValue(evaluated)) {
              evaluated = unwrapStructuredPrimitive(evaluated);
            }
            evaluatedObj[entry.key] = evaluated;
          } catch (error) {
            evaluatedObj[entry.key] = this.createPropertyError(entry.key, error);
          }
        } else if (entry.type === "conditionalPair") {
          try {
            let evaluated = await this.evaluateDataValue(entry.value, env, {
              suppressErrors: true
            });
            if (isStructuredValue(evaluated)) {
              evaluated = unwrapStructuredPrimitive(evaluated);
            }
            const { isTruthy: isTruthy3 } = await import('./expression-BNV7GVOG.mjs');
            if (isTruthy3(evaluated)) {
              evaluatedObj[entry.key] = evaluated;
            }
          } catch (error) {
            if (this.isConditionalOmissionError(error)) {
              continue;
            }
            evaluatedObj[entry.key] = this.createPropertyError(entry.key, error);
          }
        } else if (entry.type === "spread") {
          try {
            const [varRef] = entry.value;
            const varName = varRef?.identifier;
            const spreadVariable = varName ? env.getVariable(varName) : void 0;
            if (!spreadVariable) {
              throw new Error(`Cannot spread undefined variable: ${varName}`);
            }
            let spreadValue = await extractVariableValue(spreadVariable, env);
            if (varRef?.fields && varRef.fields.length > 0) {
              const fieldResult = await accessFields(spreadValue, varRef.fields, {
                env,
                preserveContext: false
              });
              spreadValue = fieldResult.value ?? fieldResult;
            }
            if (isStructuredValue(spreadValue)) {
              spreadValue = asData(spreadValue);
            }
            if (typeof spreadValue !== "object" || spreadValue === null || Array.isArray(spreadValue)) {
              throw new Error(`Cannot spread non-object value from ${varName} (got ${Array.isArray(spreadValue) ? "array" : typeof spreadValue})`);
            }
            Object.assign(evaluatedObj, spreadValue);
          } catch (error) {
            throw error;
          }
        }
      }
      return evaluatedObj;
    }
    if (value.properties && typeof value.properties === "object") {
      for (const [key, propValue] of Object.entries(value.properties)) {
        try {
          let evaluated = await this.evaluateDataValue(propValue, env, {
            suppressErrors: true
          });
          if (isStructuredValue(evaluated)) {
            evaluated = unwrapStructuredPrimitive(evaluated);
          }
          evaluatedObj[key] = evaluated;
        } catch (error) {
          evaluatedObj[key] = this.createPropertyError(key, error);
        }
      }
      return evaluatedObj;
    }
    return evaluatedObj;
  }
  /**
  * Evaluates an array with recursive element evaluation and error isolation
  */
  async evaluateArray(value, env) {
    const evaluatedElements = [];
    const items = value.items ?? value.elements ?? [];
    for (let i = 0; i < items.length; i++) {
      try {
        const item = items[i];
        if (item?.type === "ConditionalArrayElement") {
          const { evaluateConditionalInclusion: evaluateConditionalInclusion2 } = await import('./conditional-inclusion-5POVID4B.mjs');
          const { shouldInclude, value: value2 } = await evaluateConditionalInclusion2(item.condition, env, {
            valueNode: item.value
          });
          if (shouldInclude) {
            let evaluatedValue = value2;
            if (isStructuredValue(evaluatedValue)) {
              evaluatedValue = unwrapStructuredPrimitive(evaluatedValue);
            }
            evaluatedElements.push(evaluatedValue);
          }
          continue;
        }
        if (item && typeof item === "object" && "content" in item && Array.isArray(item.content)) {
          const hasOnlyLiteralsOrText = item.content.every((node) => node && typeof node === "object" && (node.type === "Literal" && "value" in node || node.type === "Text" && "content" in node));
          if (hasOnlyLiteralsOrText) {
            if (process.env.MLLD_DEBUG_FIX === "true") {
              console.error("[CollectionEvaluator] literal/text wrapper", {
                index: i,
                wrapperType: item.wrapperType,
                itemTypes: item.content.map((n) => n?.type)
              });
              try {
                fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
                  source: "CollectionEvaluator",
                  index: i,
                  wrapperType: item.wrapperType,
                  itemTypes: item.content.map((n) => n?.type)
                }) + "\n");
              } catch {
              }
            }
            evaluatedElements.push(item.content.map((node) => node.type === "Literal" ? node.value : node.content).join(""));
            continue;
          }
        }
        let evaluatedItem = await this.evaluateDataValue(items[i], env, {
          suppressErrors: true
        });
        if (isStructuredValue(evaluatedItem)) {
          evaluatedItem = unwrapStructuredPrimitive(evaluatedItem);
        }
        evaluatedElements.push(evaluatedItem);
      } catch (error) {
        evaluatedElements.push(this.createElementError(i, error));
      }
    }
    return evaluatedElements;
  }
  /**
  * Creates error object for a failed property evaluation
  */
  createPropertyError(key, error) {
    return {
      __error: true,
      __message: error instanceof Error ? error.message : String(error),
      __property: key
    };
  }
  /**
  * Creates error object for a failed element evaluation
  */
  createElementError(index, error) {
    return {
      __error: true,
      __message: error instanceof Error ? error.message : String(error),
      __index: index
    };
  }
  /**
  * Evaluates a plain object (without type field) recursively
  */
  async evaluatePlainObject(value, env) {
    const evaluatedObject = {};
    for (const [key, propValue] of Object.entries(value)) {
      if (key === "wrapperType" || key === "nodeId" || key === "location") {
        continue;
      }
      try {
        let evaluated = await this.evaluateDataValue(propValue, env, {
          suppressErrors: true
        });
        if (isStructuredValue(evaluated)) {
          evaluated = unwrapStructuredPrimitive(evaluated);
        }
        evaluatedObject[key] = evaluated;
      } catch (error) {
        evaluatedObject[key] = this.createPropertyError(key, error);
      }
    }
    return evaluatedObject;
  }
  isConditionalOmissionError(error) {
    if (error instanceof FieldAccessError) {
      return true;
    }
    if (error instanceof Error) {
      return error.message.includes("Variable not found");
    }
    return false;
  }
};
__name(_CollectionEvaluator, "CollectionEvaluator");
var CollectionEvaluator = _CollectionEvaluator;
function unwrapStructuredPrimitive(value) {
  if (!isStructuredValue(value)) {
    return value;
  }
  const data = value.data;
  if (data === null || data === void 0) {
    return data;
  }
  if (typeof data === "object") {
    return value;
  }
  return data;
}
__name(unwrapStructuredPrimitive, "unwrapStructuredPrimitive");

// interpreter/eval/data-values/VariableReferenceEvaluator.ts
async function interpolateAndRecord3(nodes, env, context2 = InterpolationContext.Default) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord3, "interpolateAndRecord");
var _VariableReferenceEvaluator = class _VariableReferenceEvaluator {
  constructor(evaluateDataValue2) {
    __publicField(this, "evaluateDataValue");
    this.evaluateDataValue = evaluateDataValue2;
  }
  /**
  * Checks if this evaluator can handle the given data value
  */
  canHandle(value) {
    if (value && typeof value === "object" && value.type === "VariableReference") {
      return true;
    }
    if (value && typeof value === "object" && value.type === "VariableReferenceWithTail") {
      return true;
    }
    if (isVariableReferenceValue(value)) {
      return true;
    }
    if (isTemplateValue(value)) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "ExecInvocation") {
      return true;
    }
    if (value && typeof value === "object" && value.type === "runExec" && "invocation" in value) {
      return true;
    }
    if (value && typeof value === "object" && value.type === "path") {
      return true;
    }
    if (value && typeof value === "object" && value.content && Array.isArray(value.content)) {
      return true;
    }
    if (value && typeof value === "object" && (value.type === "code" || value.type === "command") && ("template" in value || "codeTemplate" in value || "commandTemplate" in value)) {
      return true;
    }
    return false;
  }
  /**
  * Evaluates variable references and related operations
  */
  async evaluate(value, env) {
    if (value && typeof value === "object" && value.type === "VariableReference") {
      return await this.evaluateRawVariableReference(value, env);
    }
    if (value && typeof value === "object" && value.type === "VariableReferenceWithTail") {
      return await this.evaluateVariableReferenceWithTail(value, env);
    }
    if (isVariableReferenceValue(value)) {
      return await this.evaluateVariableReference(value, env);
    }
    if (isTemplateValue(value)) {
      return await interpolateAndRecord3(value, env);
    }
    if (value && typeof value === "object" && value.type === "ExecInvocation") {
      return await this.evaluateExecInvocation(value, env);
    }
    if (value && typeof value === "object" && value.type === "runExec" && "invocation" in value) {
      return await this.evaluateRunExec(value, env);
    }
    if (value && typeof value === "object" && value.type === "path") {
      return await this.evaluatePathNode(value, env);
    }
    if (value && typeof value === "object" && value.content && Array.isArray(value.content)) {
      return await interpolateAndRecord3(value.content, env);
    }
    if (value && typeof value === "object" && (value.type === "code" || value.type === "command") && ("template" in value || "codeTemplate" in value || "commandTemplate" in value)) {
      return value;
    }
    throw new Error(`VariableReferenceEvaluator cannot handle value type: ${typeof value}`);
  }
  /**
  * Evaluates a raw VariableReference node
  */
  async evaluateRawVariableReference(value, env) {
    const variable = env.getVariable(value.identifier);
    if (!variable) {
      throw new Error(`Variable not found: ${value.identifier}`);
    }
    if (isExecutable(variable)) {
      return variable;
    }
    const hasFieldAccess = Array.isArray(value.fields) && value.fields.length > 0;
    let result;
    if (hasFieldAccess) {
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await resolveVariable(variable, env, ResolutionContext.FieldAccess);
    } else {
      result = await this.extractVariableValue(variable, env);
    }
    this.attachProvenance(result, variable);
    if (hasFieldAccess) {
      for (const field of value.fields) {
        if (field.type === "variableIndex") {
          const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
          const indexNode = typeof field.value === "object" ? field.value : {
            type: "VariableReference",
            valueType: "varIdentifier",
            identifier: String(field.value)
          };
          const indexValue = await evaluateDataValue2(indexNode, env);
          const resolvedField = {
            type: "bracketAccess",
            value: indexValue
          };
          const fieldResult = await accessField(result, resolvedField, {
            preserveContext: true,
            env,
            sourceLocation: value?.location
          });
          result = fieldResult.value;
        } else {
          const fieldResult = await accessField(result, field, {
            preserveContext: true,
            env,
            sourceLocation: value?.location
          });
          result = fieldResult.value;
          if (result && typeof result === "object" && result.type === "VariableReference" && "identifier" in result) {
            const nestedVar = env.getVariable(result.identifier);
            if (!nestedVar) {
              throw new Error(`Variable not found: ${result.identifier}`);
            }
            const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
            result = await resolveVariable(nestedVar, env, ResolutionContext.FieldAccess);
          }
        }
      }
    }
    return result;
  }
  /**
  * Evaluates a VariableReferenceWithTail (with pipelines and modifiers)
  */
  async evaluateVariableReferenceWithTail(value, env) {
    const varRef = value.variable;
    const variable = env.getVariable(varRef.identifier);
    if (!variable) {
      throw new Error(`Variable not found: ${varRef.identifier}`);
    }
    let result;
    if (isTextLike(variable)) {
      result = variable.value;
    } else if (isPath(variable)) {
      result = variable.value.resolvedPath;
    } else if (isExecutable(variable)) {
      if (value.withClause && value.withClause.pipeline) {
        const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
        result = await evaluateExecInvocation({
          type: "ExecInvocation",
          identifier: varRef.identifier,
          args: [],
          withClause: null
        }, env);
      } else {
        result = variable;
      }
    } else if (isImported(variable)) {
      result = variable;
    } else if (isObject(variable) || isArray(variable)) {
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await resolveVariable(variable, env, ResolutionContext.DataStructure);
    } else {
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await resolveVariable(variable, env, ResolutionContext.DataStructure);
    }
    this.attachProvenance(result, variable);
    if (varRef.fields && varRef.fields.length > 0) {
      if (process.env.MLLD_DEBUG === "true") {
        console.log("\u{1F50D} BEFORE FIELD ACCESS (VariableReferenceWithTail):", {
          variableIdentifier: varRef.identifier,
          fields: varRef.fields,
          resultType: typeof result,
          resultKeys: typeof result === "object" && result !== null ? Object.keys(result) : "N/A",
          resultValue: result
        });
      }
      const { accessFields: accessFields2 } = await import('./field-access-MJ6PMBJX.mjs');
      const fieldResult = await accessFields2(result, varRef.fields, {
        preserveContext: true,
        env
      });
      result = fieldResult.value;
    }
    if (value.withClause && value.withClause.pipeline) {
      const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
      result = await processPipeline2({
        value: result,
        env,
        node: value,
        identifier: varRef.identifier,
        descriptorHint: variable.mx ? varMxToSecurityDescriptor(variable.mx) : void 0
      });
    }
    if (process.env.MLLD_DEBUG === "true") {
      logger.debug("VariableReferenceWithTail final result:", {
        variableIdentifier: varRef.identifier,
        resultValue: result,
        resultType: typeof result,
        resultIsNull: result === null,
        resultIsUndefined: result === void 0
      });
    }
    return result;
  }
  /**
  * Evaluates a standard variable reference with potential field access
  */
  async evaluateVariableReference(value, env) {
    const variable = env.getVariable(value.identifier);
    if (!variable) {
      throw new Error(`Variable not found: ${value.identifier}`);
    }
    if (isExecutable(variable)) {
      return variable;
    }
    const hasFieldAccess = Array.isArray(value.fields) && value.fields.length > 0;
    let result;
    if (hasFieldAccess) {
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await resolveVariable(variable, env, ResolutionContext.FieldAccess);
    } else {
      result = await this.extractVariableValue(variable, env);
    }
    this.attachProvenance(result, variable);
    if (process.env.MLLD_DEBUG === "true") {
      console.log("\u{1F50D} EXTRACTED VARIABLE VALUE:", {
        variableIdentifier: value.identifier,
        variableType: variable.type,
        resultType: typeof result,
        resultKeys: typeof result === "object" && result !== null ? Object.keys(result) : "N/A",
        resultValue: result
      });
    }
    if (hasFieldAccess) {
      for (const field of value.fields) {
        if (field.type === "variableIndex") {
          const indexVar = env.getVariable(field.value);
          if (!indexVar) {
            throw new Error(`Variable not found for index: ${field.value}`);
          }
          const { extractVariableValue: extract } = await import('./variable-resolution-HFG3FTZK.mjs');
          const indexValue = await extract(indexVar, env);
          const resolvedField = {
            type: "bracketAccess",
            value: indexValue
          };
          const fieldResult = await accessField(result, resolvedField, {
            preserveContext: true,
            env,
            sourceLocation: value?.location
          });
          result = fieldResult.value;
        } else {
          const fieldResult = await accessField(result, field, {
            preserveContext: true,
            env,
            sourceLocation: value?.location
          });
          result = fieldResult.value;
        }
      }
    }
    return result;
  }
  /**
  * Evaluates an ExecInvocation node with pipeline support
  */
  async evaluateExecInvocation(value, env) {
    const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
    if (value.withClause && value.withClause.pipeline) {
      const nodeWithoutPipeline = {
        ...value,
        withClause: null
      };
      const result2 = await evaluateExecInvocation(nodeWithoutPipeline, env);
      const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
      const pipelineResult = await processPipeline2({
        value: result2.value,
        env,
        node: value,
        identifier: value.identifier
      });
      if (process.env.MLLD_DEBUG === "true") {
        logger.debug("ExecInvocation pipeline result:", {
          pipelineResult,
          pipelineResultType: typeof pipelineResult,
          isPipelineInput: !!(pipelineResult && typeof pipelineResult === "object" && "text" in pipelineResult)
        });
      }
      try {
        const parsed = JSON.parse(pipelineResult);
        return parsed;
      } catch {
        return pipelineResult;
      }
    }
    const result = await evaluateExecInvocation(value, env);
    if (typeof result.value === "string") {
      try {
        const parsed = JSON.parse(result.value);
        return parsed;
      } catch {
        return result.value;
      }
    }
    return result.value;
  }
  /**
  * Extracts the actual value from a variable using type guards
  * Note: This is used in contexts where we MUST extract the raw value
  */
  async extractVariableValue(variable, env) {
    let result;
    if (isTextLike(variable)) {
      result = variable.value;
    } else if (isPath(variable)) {
      result = variable.value.resolvedPath;
    } else if (isImported(variable)) {
      result = variable.value;
    } else if (isObject(variable) || isArray(variable) || isStructuredValueVariable(variable)) {
      const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await extractVariableValue2(variable, env);
    } else {
      const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
      result = await extractVariableValue2(variable, env);
    }
    inheritExpressionProvenance(result, variable);
    return result;
  }
  /**
  * Evaluates a runExec node (run @command() in object context)
  */
  async evaluateRunExec(value, env) {
    const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
    const result = await evaluateExecInvocation(value.invocation, env);
    return result.value;
  }
  /**
  * Evaluates a path node (from [/path/to/file])
  */
  async evaluatePathNode(value, env) {
    const resolvedPath = await interpolateAndRecord3(value.segments || [], env);
    const content = await env.fileSystem.readFile(resolvedPath);
    return content;
  }
  attachProvenance(value, source) {
    if (!source) {
      return;
    }
    inheritExpressionProvenance(value, source);
  }
};
__name(_VariableReferenceEvaluator, "VariableReferenceEvaluator");
var VariableReferenceEvaluator = _VariableReferenceEvaluator;

// interpreter/eval/data-values/ForeachCommandEvaluator.ts
var _ForeachCommandEvaluator = class _ForeachCommandEvaluator {
  /**
  * Checks if this evaluator can handle the given data value.
  */
  canHandle(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value) && "type" in value && (value.type === "foreach" || value.type === "foreach-command");
  }
  /**
  * Evaluates a foreach command expression.
  */
  async evaluate(value, env) {
    if (!this.canHandle(value)) {
      throw new Error(`ForeachCommandEvaluator cannot handle value type: ${typeof value}`);
    }
    return this.evaluateForeachCommand(value, env);
  }
  /**
  * Delegates to the core foreach evaluator.
  */
  async evaluateForeachCommand(foreachExpr, env) {
    const { evaluateForeachCommand: evaluateForeachCommand2 } = await import('./foreach-USOCOKPZ.mjs');
    return evaluateForeachCommand2(foreachExpr, env);
  }
  /**
  * Delegates validation to the core foreach validator.
  */
  async validateForeachExpression(foreachExpr, env) {
    const { validateForeachExpression } = await import('./foreach-USOCOKPZ.mjs');
    return validateForeachExpression(foreachExpr, env);
  }
};
__name(_ForeachCommandEvaluator, "ForeachCommandEvaluator");
var ForeachCommandEvaluator = _ForeachCommandEvaluator;

// interpreter/eval/data-values/ForeachSectionEvaluator.ts
async function interpolateAndRecord4(nodes, env, context2 = InterpolationContext.Default) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord4, "interpolateAndRecord");
var _ForeachSectionEvaluator = class _ForeachSectionEvaluator {
  constructor(evaluateDataValue2) {
    __publicField(this, "evaluateDataValue");
    this.evaluateDataValue = evaluateDataValue2;
  }
  /**
  * Checks if this evaluator can handle the given data value
  */
  canHandle(value) {
    if (typeof value === "object" && value !== null && value.type === "foreachSection") {
      return true;
    }
    if (value && typeof value === "object" && value.type === "foreach-section") {
      return true;
    }
    return false;
  }
  /**
  * Evaluates a foreach section expression
  */
  async evaluate(value, env) {
    if (this.canHandle(value)) {
      return await this.evaluateForeachSection(value, env);
    }
    throw new Error(`ForeachSectionEvaluator cannot handle value type: ${typeof value}`);
  }
  /**
  * Evaluates a ForeachSectionExpression - iterating over arrays with section extraction
  * Usage: foreach <@array.field # section> as ::template::
  */
  async evaluateForeachSection(foreachExpr, env) {
    const { alligator, arrayVariable, pathField, path: path10, section, template } = foreachExpr.value || foreachExpr;
    let actualArrayVariable = arrayVariable;
    let actualPathField = pathField;
    let actualPath = path10;
    if (alligator && alligator.type === "load-content") {
      actualPath = alligator.source?.segments;
      if (actualPath) {
        for (const part of actualPath) {
          if (part.type === "VariableReference" && part.fields && part.fields.length > 0) {
            actualArrayVariable = part.identifier;
            actualPathField = part.fields[0].value || part.fields[0].field;
            break;
          }
        }
      }
    } else if (!actualArrayVariable && path10) {
      for (const part of path10) {
        if (part.type === "VariableReference" && part.fields && part.fields.length > 0) {
          actualArrayVariable = part.identifier;
          actualPathField = part.fields[0].value || part.fields[0].field;
          break;
        }
      }
    }
    if (!actualArrayVariable) {
      throw new Error("Cannot determine array variable from foreach section expression");
    }
    const arrayVar = env.getVariable(actualArrayVariable);
    if (!arrayVar) {
      throw new Error(`Array variable not found: ${actualArrayVariable}`);
    }
    const arrayValue = await this.evaluateDataValue(arrayVar.value, env);
    if (!Array.isArray(arrayValue)) {
      throw new Error(`Variable '${actualArrayVariable}' must be an array for foreach section extraction, got ${typeof arrayValue}`);
    }
    if (arrayValue.length === 0) {
      return [];
    }
    const results = [];
    for (let i = 0; i < arrayValue.length; i++) {
      const item = arrayValue[i];
      try {
        const childEnv = env.createChild();
        const itemVar = Array.isArray(item) ? createArrayVariable(actualArrayVariable, item, {
          directive: "var",
          syntax: "array",
          hasInterpolation: false,
          isMultiLine: false
        }, {
          internal: {
            isParameter: true,
            isFullyEvaluated: true
          }
        }) : createObjectVariable(actualArrayVariable, item, {
          directive: "var",
          syntax: "object",
          hasInterpolation: false,
          isMultiLine: false
        }, {
          internal: {
            isParameter: true,
            isFullyEvaluated: true
          }
        });
        childEnv.setParameterVariable(actualArrayVariable, itemVar);
        let pathValue;
        if (actualPath) {
          pathValue = await interpolateAndRecord4(actualPath, childEnv);
          pathValue = pathValue.trim();
        } else if (actualPathField) {
          if (!item || typeof item !== "object") {
            throw new Error(`Array item ${i + 1} must be an object with '${actualPathField}' field, got ${typeof item}`);
          }
          pathValue = item[actualPathField];
          if (typeof pathValue !== "string") {
            throw new Error(`Path field '${actualPathField}' in array item ${i + 1} must be a string, got ${typeof pathValue}`);
          }
        } else {
          throw new Error("No path specified for foreach section extraction");
        }
        let sectionName;
        let sectionToProcess = section;
        if (alligator && alligator.type === "load-content" && alligator.options?.section) {
          sectionToProcess = alligator.options.section.identifier;
        }
        const sectionNodes = Array.isArray(sectionToProcess) ? sectionToProcess : [
          sectionToProcess
        ];
        if (sectionNodes.length === 1 && sectionNodes[0].type === "Text") {
          sectionName = sectionNodes[0].content;
        } else if (sectionNodes.length === 1 && sectionNodes[0].type === "VariableReference") {
          const sectionValue = await interpolateAndRecord4(sectionNodes, childEnv);
          if (typeof sectionValue !== "string") {
            throw new Error(`Section variable must resolve to a string, got ${typeof sectionValue}`);
          }
          sectionName = sectionValue;
        } else if (sectionNodes.length > 0) {
          const sectionValue = await interpolateAndRecord4(sectionNodes, childEnv);
          if (typeof sectionValue !== "string") {
            throw new Error(`Section must resolve to a string, got ${typeof sectionValue}`);
          }
          sectionName = sectionValue;
        } else if (typeof sectionToProcess === "string") {
          sectionName = sectionToProcess;
        } else if (sectionToProcess && typeof sectionToProcess === "object" && sectionToProcess.content) {
          sectionName = sectionToProcess.content;
        } else {
          throw new Error("Section name is required for foreach section extraction");
        }
        const resolvedPath = await env.resolvePath(pathValue);
        const fileContent = await env.readFile(resolvedPath);
        const { llmxmlInstance: llmxmlInstance2 } = await import('./llmxml-instance-KTZFYTGC.mjs');
        let sectionContent;
        try {
          const titleWithoutHash = sectionName.replace(/^#+\s*/, "");
          sectionContent = await llmxmlInstance2.getSection(fileContent, titleWithoutHash, {
            includeNested: true
          });
          sectionContent = sectionContent.trimEnd();
        } catch (error) {
          sectionContent = this.extractSectionBasic(fileContent, sectionName);
        }
        const templateResult = await interpolateAndRecord4(template.values.content, childEnv);
        const lines = sectionContent.split("\n");
        if (lines.length > 0 && lines[0].match(/^#+\s/)) {
          lines[0] = templateResult;
          const result = lines.join("\n");
          results.push(result);
        } else {
          const result = templateResult + "\n" + sectionContent;
          results.push(result);
        }
      } catch (error) {
        const itemInfo = typeof item === "object" && item !== null ? Object.keys(item).slice(0, 3).map((k) => `${k}: ${JSON.stringify(item[k])}`).join(", ") : String(item);
        throw new Error(`Error in foreach section iteration ${i + 1} (${itemInfo}): ${error instanceof Error ? error.message : String(error)}`);
      }
    }
    return results;
  }
  /**
  * Extract a section from markdown content.
  * Basic fallback implementation when llmxml fails.
  */
  extractSectionBasic(content, sectionName) {
    const lines = content.split("\n");
    const sectionRegex = new RegExp(`^#+\\s+${sectionName}\\s*$`, "i");
    let inSection = false;
    let sectionLevel = 0;
    const sectionLines = [];
    for (const line of lines) {
      if (!inSection && sectionRegex.test(line)) {
        inSection = true;
        sectionLevel = line.match(/^#+/)?.[0].length || 0;
        continue;
      }
      if (inSection) {
        const headerMatch = line.match(/^(#+)\s+/);
        if (headerMatch && headerMatch[1].length <= sectionLevel) {
          break;
        }
        sectionLines.push(line);
      }
    }
    return sectionLines.join("\n").trim();
  }
};
__name(_ForeachSectionEvaluator, "ForeachSectionEvaluator");
var ForeachSectionEvaluator = _ForeachSectionEvaluator;
var _LoadContentResultImpl = class _LoadContentResultImpl {
  constructor(data) {
    __publicField(this, "content");
    __publicField(this, "filename");
    __publicField(this, "relative");
    __publicField(this, "absolute");
    __publicField(this, "_extension");
    __publicField(this, "_metrics");
    __publicField(this, "_fm");
    __publicField(this, "_fmParsed", false);
    __publicField(this, "_json");
    __publicField(this, "_jsonParsed", false);
    __publicField(this, "_rawContent");
    this.content = data.content;
    this.filename = data.filename;
    this.relative = data.relative;
    this.absolute = data.absolute;
    this._rawContent = data._rawContent;
    const match = this.filename.match(/\.([a-zA-Z0-9]+)$/);
    this._extension = match ? match[1].toLowerCase() : null;
  }
  get path() {
    return this.absolute;
  }
  get ext() {
    return this._extension || "";
  }
  get fm() {
    if (!this._fmParsed) {
      this._fmParsed = true;
      try {
        const contentToParse = this._rawContent || this.content;
        const fmMatch = contentToParse.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
        if (fmMatch) {
          this._fm = yaml.load(fmMatch[1]);
        }
      } catch (error) {
      }
    }
    return this._fm;
  }
  ensureMetrics() {
    if (!this._metrics) {
      const options = {
        extension: this._extension,
        format: void 0
      };
      this._metrics = buildTokenMetrics(this.content, options);
    }
    return this._metrics;
  }
  get tokest() {
    return this.ensureMetrics().tokest;
  }
  get tokens() {
    const metrics = this.ensureMetrics();
    return metrics.tokens ?? metrics.tokest;
  }
  get json() {
    if (!this._jsonParsed) {
      this._jsonParsed = true;
      try {
        this._json = JSON.parse(this.content);
      } catch {
        this._json = void 0;
      }
    }
    return this._json;
  }
  // String conversion returns content
  toString() {
    return this.content;
  }
  // StructuredValue-like surface
  get type() {
    return "text";
  }
  get text() {
    return this.content;
  }
  get data() {
    return this.content;
  }
  get mx() {
    const self = this;
    return {
      filename: this.filename,
      relative: this.relative,
      absolute: this.absolute,
      get tokest() {
        return self.tokest;
      },
      get tokens() {
        return self.tokens;
      },
      get fm() {
        return self.fm;
      },
      get json() {
        return self.json;
      },
      type: this.type
    };
  }
  valueOf() {
    return this.content;
  }
  [Symbol.toPrimitive]() {
    return this.content;
  }
  // JSON representation includes metadata
  toJSON() {
    return {
      content: this.content,
      filename: this.filename,
      relative: this.relative,
      absolute: this.absolute,
      ext: this.ext,
      fm: this.fm,
      tokest: this.tokest
    };
  }
};
__name(_LoadContentResultImpl, "LoadContentResultImpl");
var LoadContentResultImpl = _LoadContentResultImpl;
var _LoadContentResultURLImpl = class _LoadContentResultURLImpl extends LoadContentResultImpl {
  constructor(data) {
    const urlPath = new URL(data.url).pathname;
    const filename = urlPath.split("/").pop() || "index.html";
    super({
      content: data.content,
      filename,
      relative: data.url,
      absolute: data.url
    });
    __publicField(this, "url");
    __publicField(this, "domain");
    __publicField(this, "title");
    __publicField(this, "description");
    __publicField(this, "status");
    __publicField(this, "headers");
    __publicField(this, "rawContent");
    this.url = data.url;
    this.domain = new URL(data.url).hostname;
    this.headers = data.headers;
    this.status = data.status;
    this.rawContent = data.rawContent;
    const contentType = data.headers["content-type"] || data.headers["Content-Type"] || "";
    if (contentType.includes("text/html")) {
      this._extractHtmlMetadata();
    }
  }
  // Getters for common content type properties
  get contentType() {
    return this.headers?.["content-type"] || this.headers?.["Content-Type"];
  }
  get html() {
    const contentType = this.contentType;
    return contentType?.includes("text/html") ? this.rawContent : void 0;
  }
  get text() {
    const contentType = this.contentType;
    if (contentType?.includes("text/html")) {
      try {
        const dom = new JSDOM(this.rawContent);
        return dom.window.document.body?.textContent?.trim() || "";
      } catch {
        return this.rawContent;
      }
    }
    return this.rawContent;
  }
  get md() {
    const contentType = this.contentType;
    return contentType?.includes("text/html") ? this.content : void 0;
  }
  get type() {
    const contentType = this.contentType;
    if (contentType?.includes("application/json")) {
      const parsed = this.json;
      if (Array.isArray(parsed)) return "array";
      if (parsed && typeof parsed === "object") return "object";
    }
    if (contentType?.includes("text/html")) {
      return "html";
    }
    return "text";
  }
  get mx() {
    const base = super.mx;
    return {
      ...base,
      url: this.url,
      domain: this.domain,
      title: this.title,
      description: this.description,
      status: this.status,
      headers: this.headers,
      html: this.html
    };
  }
  // JSON representation includes URL metadata
  toJSON() {
    return {
      ...super.toJSON(),
      url: this.url,
      domain: this.domain,
      title: this.title,
      description: this.description,
      status: this.status,
      headers: this.headers
    };
  }
  _extractHtmlMetadata() {
    try {
      const dom = new JSDOM(this.rawContent);
      const doc = dom.window.document;
      const titleElement = doc.querySelector("title");
      if (titleElement) {
        this.title = titleElement.textContent?.trim() || void 0;
      }
      if (!this.title) {
        const ogTitle = doc.querySelector('meta[property="og:title"]');
        const twitterTitle = doc.querySelector('meta[name="twitter:title"]');
        this.title = ogTitle?.getAttribute("content")?.trim() || twitterTitle?.getAttribute("content")?.trim() || void 0;
      }
      const descElement = doc.querySelector('meta[name="description"]') || doc.querySelector('meta[property="og:description"]') || doc.querySelector('meta[property="twitter:description"]') || doc.querySelector('meta[name="twitter:description"]');
      if (descElement) {
        this.description = descElement.getAttribute("content")?.trim() || void 0;
      }
    } catch (error) {
      console.warn("DOM parsing failed, falling back to regex:", error);
      this._extractHtmlMetadataFallback();
    }
  }
  _extractHtmlMetadataFallback() {
    const titleMatch = this.rawContent.match(/<title[^>]*>([^<]+)<\/title>/i);
    if (titleMatch) {
      this.title = titleMatch[1].trim();
    }
    const descMatch = this.rawContent.match(/<meta\s+(?:name|property)=["'](?:description|og:description|twitter:description)["']\s+content=["']([^"']+)["']/i) || this.rawContent.match(/<meta\s+content=["']([^"']+)["']\s+(?:name|property)=["'](?:description|og:description|twitter:description)["']/i);
    if (descMatch) {
      this.description = descMatch[1].trim();
    }
  }
};
__name(_LoadContentResultURLImpl, "LoadContentResultURLImpl");
var LoadContentResultURLImpl = _LoadContentResultURLImpl;
var _LoadContentResultHTMLImpl = class _LoadContentResultHTMLImpl extends LoadContentResultImpl {
  constructor(data) {
    super({
      content: data.content,
      filename: data.filename,
      relative: data.relative,
      absolute: data.absolute
    });
    __publicField(this, "title");
    __publicField(this, "description");
    __publicField(this, "_rawHtml");
    this._rawHtml = data.rawHtml;
    this.title = data.title;
    this.description = data.description;
  }
  get html() {
    return this._rawHtml;
  }
  get text() {
    try {
      const dom = new JSDOM(this._rawHtml);
      return dom.window.document.body?.textContent?.trim() || "";
    } catch {
      return this._rawHtml;
    }
  }
  get type() {
    return "html";
  }
  get mx() {
    const base = super.mx;
    return {
      ...base,
      html: this.html
    };
  }
  // JSON representation includes HTML metadata
  toJSON() {
    return {
      ...super.toJSON(),
      title: this.title,
      description: this.description,
      html: this._rawHtml
    };
  }
};
__name(_LoadContentResultHTMLImpl, "LoadContentResultHTMLImpl");
var LoadContentResultHTMLImpl = _LoadContentResultHTMLImpl;
var TYPE_FILTER_MAP = {
  fn: [
    "function",
    "method"
  ],
  var: [
    "variable",
    "constant"
  ],
  class: [
    "class"
  ],
  interface: [
    "interface"
  ],
  type: [
    "type-alias"
  ],
  enum: [
    "enum"
  ],
  struct: [
    "struct"
  ],
  trait: [
    "trait"
  ],
  module: [
    "module"
  ]
};
function isWildcardPattern(name) {
  return name.includes("*") || name.includes("?");
}
__name(isWildcardPattern, "isWildcardPattern");
function createSymbolMatcher(pattern) {
  if (!isWildcardPattern(pattern)) {
    return (name) => name === pattern;
  }
  const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
  const regex = new RegExp(`^${regexPattern}$`);
  return (name) => regex.test(name);
}
__name(createSymbolMatcher, "createSymbolMatcher");
function matchesTypeFilter(defType, filter) {
  const allowedTypes = TYPE_FILTER_MAP[filter];
  return allowedTypes ? allowedTypes.includes(defType) : false;
}
__name(matchesTypeFilter, "matchesTypeFilter");
function hasNameListPattern(patterns) {
  return patterns.some((p) => p.type === "name-list" || p.type === "name-list-all" || p.type === "name-list-var");
}
__name(hasNameListPattern, "hasNameListPattern");
function hasContentPattern(patterns) {
  return patterns.some((p) => p.type === "definition" || p.type === "usage" || p.type === "type-filter" || p.type === "type-filter-all" || p.type === "type-filter-var");
}
__name(hasContentPattern, "hasContentPattern");
function getLinesAndOffsets(content) {
  const lines = content.split(/\r?\n/);
  const offsets = [];
  let pos = 0;
  for (const line of lines) {
    offsets.push(pos);
    pos += line.length + 1;
  }
  return {
    lines,
    offsets
  };
}
__name(getLinesAndOffsets, "getLinesAndOffsets");
function extractAst(content, filePath, patterns) {
  const ext = path7.extname(filePath).toLowerCase();
  let definitions = [];
  if ([
    ".py",
    ".pyi"
  ].includes(ext)) {
    definitions = extractPythonDefinitions(content);
  } else if (ext === ".rb") {
    definitions = extractRubyDefinitions(content);
  } else if (ext === ".go") {
    definitions = extractGoDefinitions(content);
  } else if (ext === ".rs") {
    definitions = extractRustDefinitions(content);
  } else if (ext === ".java") {
    definitions = extractJavaDefinitions(content);
  } else if (ext === ".sol") {
    definitions = extractSolidityDefinitions(content);
  } else if ([
    ".c",
    ".h",
    ".cpp",
    ".hpp",
    ".cc",
    ".cxx",
    ".hh",
    ".hxx"
  ].includes(ext)) {
    definitions = extractCppDefinitions(content);
  } else if (ext === ".cs") {
    definitions = extractCSharpDefinitions(content);
  } else {
    definitions = extractTsDefinitions(content, filePath);
  }
  const definitionMap = /* @__PURE__ */ new Map();
  const sequence = [];
  function toResult(def) {
    return {
      name: def.name,
      code: def.code,
      type: def.type,
      line: def.line
    };
  }
  __name(toResult, "toResult");
  function keyOf(def) {
    return `${def.start}:${def.end}:${def.name}`;
  }
  __name(keyOf, "keyOf");
  function contains(container, child) {
    return container.start <= child.start && container.end >= child.end && (container.start < child.start || container.end > child.end);
  }
  __name(contains, "contains");
  function pushDefinition(def) {
    const key = keyOf(def);
    if (definitionMap.has(key)) {
      return;
    }
    for (const existing of definitionMap.values()) {
      if (contains(existing, def)) {
        return;
      }
    }
    for (const [existingKey, existing] of definitionMap) {
      if (contains(def, existing)) {
        definitionMap.delete(existingKey);
        const index = sequence.findIndex((entry) => entry.kind === "definition" && entry.key === existingKey);
        if (index !== -1) {
          sequence.splice(index, 1);
        }
      }
    }
    definitionMap.set(key, def);
    sequence.push({
      kind: "definition",
      key
    });
  }
  __name(pushDefinition, "pushDefinition");
  for (const pattern of patterns) {
    if (pattern.type === "type-filter-all") {
      if (pattern.usage) {
        const matches = definitions.filter((def) => def.type !== "variable");
        if (matches.length === 0) {
          sequence.push({
            kind: "null"
          });
        } else {
          for (const def of matches) {
            pushDefinition(def);
          }
        }
      } else {
        if (definitions.length === 0) {
          sequence.push({
            kind: "null"
          });
        } else {
          for (const def of definitions) {
            pushDefinition(def);
          }
        }
      }
      continue;
    }
    if (pattern.type === "type-filter") {
      const matches = definitions.filter((def) => matchesTypeFilter(def.type, pattern.filter));
      if (pattern.usage) {
        new Set(matches.map((m) => m.name));
        const usageMatches = definitions.filter((def) => {
          if (def.type === "variable") return false;
          return matches.some((m) => {
            const regex = new RegExp(`\\b${escapeRegExp(m.name)}\\b`);
            return regex.test(def.search);
          });
        });
        const filteredUsages = usageMatches.filter((def) => !usageMatches.some((other) => other !== def && contains(def, other)));
        if (filteredUsages.length === 0) {
          sequence.push({
            kind: "null"
          });
        } else {
          for (const def of filteredUsages) {
            pushDefinition(def);
          }
        }
      } else {
        if (matches.length === 0) {
          sequence.push({
            kind: "null"
          });
        } else {
          for (const def of matches) {
            pushDefinition(def);
          }
        }
      }
      continue;
    }
    if (pattern.type === "definition") {
      const patternName = pattern.name;
      if (isWildcardPattern(patternName)) {
        const matcher = createSymbolMatcher(patternName);
        const matches = definitions.filter((d) => matcher(d.name));
        if (pattern.usage) {
          const usageMatches = definitions.filter((def) => {
            if (def.type === "variable") return false;
            return matches.some((m) => {
              const regex = new RegExp(`\\b${escapeRegExp(m.name)}\\b`);
              return regex.test(def.search);
            });
          });
          const filteredUsages = usageMatches.filter((def) => !usageMatches.some((other) => other !== def && contains(def, other)));
          if (filteredUsages.length === 0) {
            sequence.push({
              kind: "null"
            });
          } else {
            for (const def of filteredUsages) {
              pushDefinition(def);
            }
          }
        } else {
          if (matches.length === 0) {
            sequence.push({
              kind: "null"
            });
          } else {
            for (const def of matches) {
              pushDefinition(def);
            }
          }
        }
      } else if (pattern.usage) {
        const regex = new RegExp(`\\b${escapeRegExp(patternName)}\\b`);
        const matches = definitions.filter((def) => def.type !== "variable" && regex.test(def.search));
        const filteredMatches = matches.filter((def) => !matches.some((other) => other !== def && contains(def, other)));
        if (filteredMatches.length === 0) {
          sequence.push({
            kind: "null"
          });
        } else {
          for (const def of filteredMatches) {
            pushDefinition(def);
          }
        }
      } else {
        const def = definitions.find((d) => d.name === patternName);
        if (def) {
          pushDefinition(def);
        } else {
          sequence.push({
            kind: "null"
          });
        }
      }
      continue;
    }
    if (pattern.type === "usage") {
      const legacyPattern = pattern;
      const regex = new RegExp(`\\b${escapeRegExp(legacyPattern.name)}\\b`);
      const matches = definitions.filter((def) => def.type !== "variable" && regex.test(def.search));
      const filteredMatches = matches.filter((def) => !matches.some((other) => other !== def && contains(def, other)));
      if (filteredMatches.length === 0) {
        sequence.push({
          kind: "null"
        });
        continue;
      }
      for (const def of filteredMatches) {
        pushDefinition(def);
      }
      continue;
    }
  }
  return sequence.map((entry) => {
    if (entry.kind === "null") {
      return null;
    }
    const def = definitionMap.get(entry.key);
    return def ? toResult(def) : null;
  });
}
__name(extractAst, "extractAst");
function extractNames(content, filePath, filter) {
  const ext = path7.extname(filePath).toLowerCase();
  let definitions = [];
  if ([
    ".py",
    ".pyi"
  ].includes(ext)) {
    definitions = extractPythonDefinitions(content);
  } else if (ext === ".rb") {
    definitions = extractRubyDefinitions(content);
  } else if (ext === ".go") {
    definitions = extractGoDefinitions(content);
  } else if (ext === ".rs") {
    definitions = extractRustDefinitions(content);
  } else if (ext === ".java") {
    definitions = extractJavaDefinitions(content);
  } else if (ext === ".sol") {
    definitions = extractSolidityDefinitions(content);
  } else if ([
    ".c",
    ".h",
    ".cpp",
    ".hpp",
    ".cc",
    ".cxx",
    ".hh",
    ".hxx"
  ].includes(ext)) {
    definitions = extractCppDefinitions(content);
  } else if (ext === ".cs") {
    definitions = extractCSharpDefinitions(content);
  } else {
    definitions = extractTsDefinitions(content, filePath);
  }
  let filtered;
  if (filter) {
    filtered = definitions.filter((d) => matchesTypeFilter(d.type, filter));
  } else {
    const nestedTypes = [
      "method",
      "constructor"
    ];
    filtered = definitions.filter((d) => !nestedTypes.includes(d.type));
  }
  const names = [
    ...new Set(filtered.map((d) => d.name))
  ];
  names.sort();
  return names;
}
__name(extractNames, "extractNames");
function extractTsDefinitions(content, filePath) {
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
  const defs = [];
  for (const stmt of sourceFile.statements) {
    if (ts.isFunctionDeclaration(stmt) && stmt.name) {
      defs.push(makeTsDefinition(stmt.name.text, "function", stmt, sourceFile, content));
    } else if (ts.isClassDeclaration(stmt) && stmt.name) {
      defs.push(makeTsDefinition(stmt.name.text, "class", stmt, sourceFile, content));
      for (const member of stmt.members) {
        if (ts.isMethodDeclaration(member) && member.name && ts.isIdentifier(member.name)) {
          defs.push(makeTsDefinition(member.name.text, "method", member, sourceFile, content));
        }
      }
    } else if (ts.isInterfaceDeclaration(stmt) && stmt.name) {
      defs.push(makeTsDefinition(stmt.name.text, "interface", stmt, sourceFile, content));
    } else if (ts.isEnumDeclaration(stmt) && stmt.name) {
      defs.push(makeTsDefinition(stmt.name.text, "enum", stmt, sourceFile, content));
    } else if (ts.isTypeAliasDeclaration(stmt) && ts.isIdentifier(stmt.name)) {
      defs.push(makeTsDefinition(stmt.name.text, "type-alias", stmt, sourceFile, content));
    } else if (ts.isVariableStatement(stmt)) {
      for (const decl of stmt.declarationList.declarations) {
        if (ts.isIdentifier(decl.name)) {
          defs.push(makeTsDefinition(decl.name.text, "variable", stmt, sourceFile, content));
        }
      }
    }
  }
  return defs;
}
__name(extractTsDefinitions, "extractTsDefinitions");
function makeTsDefinition(name, type, node, sf, text) {
  const start = node.getStart();
  const end = node.getEnd();
  const line = sf.getLineAndCharacterOfPosition(start).line + 1;
  const code = text.slice(start, end);
  const body = node.body;
  const search = body ? body.getText(sf) : code;
  return {
    name,
    type,
    start,
    end,
    line,
    code,
    search
  };
}
__name(makeTsDefinition, "makeTsDefinition");
function extractPythonDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine, indent) {
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      if (current.trim() === "") continue;
      const currentIndent = current.match(/^\s*/)?.[0].length ?? 0;
      if (currentIndent <= indent) break;
    }
    return line;
  }
  __name(blockEnd, "blockEnd");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const indent = line.match(/^\s*/)?.[0].length ?? 0;
    const trimmed = line.trim();
    if (indent === 0 && /^def\s+(\w+)/.test(trimmed)) {
      const name = RegExp.$1;
      const endLine = blockEnd(i + 1, indent);
      const start = offsets[i];
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const search = code.split(/\r?\n/).slice(1).join("\n");
      defs.push({
        name,
        type: "function",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (indent === 0 && /^class\s+(\w+)/.test(trimmed)) {
      const name = RegExp.$1;
      const endLine = blockEnd(i + 1, indent);
      const start = offsets[i];
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const search = code.split(/\r?\n/).slice(1).join("\n");
      defs.push({
        name,
        type: "class",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      for (let j = i + 1; j < endLine; j++) {
        const inner = lines[j];
        const innerIndent = inner.match(/^\s*/)?.[0].length ?? 0;
        const innerTrim = inner.trim();
        if (innerIndent > indent && /^def\s+(\w+)/.test(innerTrim)) {
          const mName = RegExp.$1;
          const mEnd = blockEnd(j + 1, innerIndent);
          const mStart = offsets[j];
          const mEndPos = offsets[mEnd] ?? content.length;
          const mCode = content.slice(mStart, mEndPos);
          const mSearch = mCode.split(/\r?\n/).slice(1).join("\n");
          defs.push({
            name: mName,
            type: "method",
            start: mStart,
            end: mEndPos,
            line: j + 1,
            code: mCode,
            search: mSearch
          });
          j = mEnd - 1;
        }
      }
      i = endLine - 1;
    } else if (indent === 0 && /^(\w+)/.test(trimmed) && trimmed.includes("=")) {
      const name = RegExp.$1;
      const start = offsets[i];
      const end = start + line.length;
      const code = content.slice(start, end);
      const search = code;
      defs.push({
        name,
        type: "variable",
        start,
        end,
        line: i + 1,
        code,
        search
      });
    }
  }
  return defs;
}
__name(extractPythonDefinitions, "extractPythonDefinitions");
function extractRubyDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  const contextStack = [];
  function sanitized(line) {
    return line.replace(/#.*$/, "");
  }
  __name(sanitized, "sanitized");
  function blockEnd(startLine) {
    let depth = 0;
    for (let line = startLine; line < lines.length; line++) {
      const clean = sanitized(lines[line]);
      if (!clean.trim()) {
        continue;
      }
      if (line === startLine) {
        depth += 1;
      } else {
        const openers = clean.match(/\b(class|module|def|if|unless|case|begin|for|while|until|loop)\b/g);
        if (openers) {
          depth += openers.length;
        }
        const doMatches = clean.match(/\bdo\b/g);
        if (doMatches) {
          depth += doMatches.length;
        }
      }
      const endMatches = clean.match(/\bend\b/g);
      if (endMatches) {
        depth -= endMatches.length;
        if (depth <= 0) {
          return line + 1;
        }
      }
    }
    return lines.length;
  }
  __name(blockEnd, "blockEnd");
  function makeDefinition(name, type, startLine, endLine, overrideName) {
    const finalName = overrideName ?? name;
    const start = offsets[startLine];
    const end = offsets[endLine] ?? content.length;
    const code = content.slice(start, end);
    const search = code.split(/\r?\n/).slice(1).join("\n");
    defs.push({
      name: finalName,
      type,
      start,
      end,
      line: startLine + 1,
      code,
      search
    });
  }
  __name(makeDefinition, "makeDefinition");
  for (let i = 0; i < lines.length; i++) {
    const rawLine = lines[i];
    const clean = sanitized(rawLine);
    const trimmed = clean.trim();
    while (contextStack.length > 0 && i >= contextStack[contextStack.length - 1].endLine) {
      contextStack.pop();
    }
    if (!trimmed) {
      continue;
    }
    const classMatch = /^class\s+([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)/.exec(trimmed);
    if (classMatch) {
      const endLine = blockEnd(i);
      const parentSegments = contextStack.length > 0 ? contextStack[contextStack.length - 1].segments : [];
      const classSegments = classMatch[1].split("::");
      const segments = [
        ...parentSegments,
        ...classSegments
      ];
      const qualified = segments.join("::");
      makeDefinition(classMatch[1], "class", i, endLine, qualified);
      contextStack.push({
        endLine,
        segments,
        kind: "class"
      });
      continue;
    }
    const moduleMatch = /^module\s+([A-Za-z_]\w*(?:::[A-Za-z_]\w*)*)/.exec(trimmed);
    if (moduleMatch) {
      const endLine = blockEnd(i);
      const parentSegments = contextStack.length > 0 ? contextStack[contextStack.length - 1].segments : [];
      const moduleSegments = moduleMatch[1].split("::");
      const segments = [
        ...parentSegments,
        ...moduleSegments
      ];
      const qualified = segments.join("::");
      makeDefinition(moduleMatch[1], "module", i, endLine, qualified);
      contextStack.push({
        endLine,
        segments,
        kind: "module"
      });
      continue;
    }
    const defMatch = /^def\s+([A-Za-z_]\w*[!?=]?|(?:self|[A-Za-z_]\w*)\.[A-Za-z_]\w*[!?=]?)/.exec(trimmed);
    if (defMatch) {
      const endLine = blockEnd(i);
      const name = defMatch[1];
      const insideClass = contextStack.some((mx) => mx.kind === "class");
      const type = insideClass ? "method" : "function";
      makeDefinition(name, type, i, endLine);
      i = endLine - 1;
      continue;
    }
    const constMatch = /^([A-Z][A-Za-z0-9_]*)\s*=/.exec(trimmed);
    if (constMatch) {
      const start = offsets[i];
      const end = start + rawLine.length;
      const code = content.slice(start, end);
      defs.push({
        name: constMatch[1],
        type: "constant",
        start,
        end,
        line: i + 1,
        code,
        search: code
      });
    }
  }
  return defs;
}
__name(extractRubyDefinitions, "extractRubyDefinitions");
function extractRustDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      const opens = (current.match(/\{/g) ?? []).length;
      const closes = (current.match(/\}/g) ?? []).length;
      braces += opens;
      braces -= closes;
      if (opens > 0) started = true;
      if (started && braces === 0) break;
    }
    return line + 1;
  }
  __name(blockEnd, "blockEnd");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();
    const indent = line.match(/^\s*/)?.[0].length ?? 0;
    const fnMatch = /^(?:pub\s+)?fn\s+(\w+)/.exec(trimmed);
    const structMatch = /^(?:pub\s+)?struct\s+(\w+)/.exec(trimmed);
    const enumMatch = /^(?:pub\s+)?enum\s+(\w+)/.exec(trimmed);
    const traitMatch = /^(?:pub\s+)?trait\s+(\w+)/.exec(trimmed);
    const constMatch = /^(?:pub\s+)?(?:const|static)\s+(\w+)/.exec(trimmed);
    if (indent === 0 && fnMatch) {
      const name = fnMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "function",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (indent === 0 && structMatch) {
      const name = structMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "struct",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (indent === 0 && enumMatch) {
      const name = enumMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "enum",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (indent === 0 && traitMatch) {
      const name = traitMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "trait",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (indent === 0 && constMatch) {
      const name = constMatch[1];
      const start = offsets[i];
      const end = start + line.length;
      const code = content.slice(start, end);
      defs.push({
        name,
        type: "variable",
        start,
        end,
        line: i + 1,
        code,
        search: code
      });
    } else if (indent === 0 && /^(?:pub\s+)?impl\b/.test(trimmed)) {
      const endLine = blockEnd(i);
      for (let j = i + 1; j < endLine; j++) {
        const inner = lines[j];
        const innerTrim = inner.trim();
        const methodMatch = /^(?:pub\s+)?fn\s+(\w+)/.exec(innerTrim);
        if (methodMatch) {
          const name = methodMatch[1];
          const mStart = offsets[j];
          const mEndLine = blockEnd(j);
          const mEnd = offsets[mEndLine] ?? content.length;
          const code = content.slice(mStart, mEnd);
          const bodyStart = code.indexOf("{");
          const bodyEnd = code.lastIndexOf("}");
          const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
          defs.push({
            name,
            type: "method",
            start: mStart,
            end: mEnd,
            line: j + 1,
            code,
            search
          });
          j = mEndLine - 1;
        }
      }
      i = endLine - 1;
    }
  }
  return defs;
}
__name(extractRustDefinitions, "extractRustDefinitions");
function extractGoDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      const opens = (current.match(/\{/g) ?? []).length;
      const closes = (current.match(/\}/g) ?? []).length;
      braces += opens;
      braces -= closes;
      if (opens > 0) started = true;
      if (started && braces === 0) break;
    }
    return line + 1;
  }
  __name(blockEnd, "blockEnd");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();
    const funcMatch = /^func\s+(?:\([^)]+\)\s*)?(\w+)/.exec(trimmed);
    const typeMatch = /^type\s+(\w+)/.exec(trimmed);
    const varMatch = /^(?:var|const)\s+(\w+)/.exec(trimmed);
    if (funcMatch) {
      const name = funcMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      const type = trimmed.startsWith("func (") ? "method" : "function";
      defs.push({
        name,
        type,
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (typeMatch) {
      const name = typeMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      const kind = /struct/.test(trimmed) ? "struct" : /interface/.test(trimmed) ? "interface" : "type";
      defs.push({
        name,
        type: kind,
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (varMatch) {
      const name = varMatch[1];
      const start = offsets[i];
      const end = start + line.length;
      const code = content.slice(start, end);
      defs.push({
        name,
        type: "variable",
        start,
        end,
        line: i + 1,
        code,
        search: code
      });
    }
  }
  return defs;
}
__name(extractGoDefinitions, "extractGoDefinitions");
function extractCppDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  const strippedLines = [];
  let inBlockComment = false;
  for (const line of lines) {
    let result = "";
    for (let i = 0; i < line.length; i++) {
      const char = line[i];
      const next = line[i + 1];
      if (!inBlockComment && char === "/" && next === "/") {
        break;
      }
      if (!inBlockComment && char === "/" && next === "*") {
        inBlockComment = true;
        i++;
        continue;
      }
      if (inBlockComment && char === "*" && next === "/") {
        inBlockComment = false;
        i++;
        continue;
      }
      if (!inBlockComment) {
        result += char;
      }
    }
    strippedLines.push(result);
  }
  function sanitize(line) {
    return line.replace(/'(?:\\.|[^'\\])*'/g, "''").replace(/"(?:\\.|[^"\\])*"/g, '""');
  }
  __name(sanitize, "sanitize");
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    for (let line = startLine; line < lines.length; line++) {
      const sanitized = sanitize(strippedLines[line]);
      const opens = (sanitized.match(/\{/g) ?? []).length;
      const closes = (sanitized.match(/\}/g) ?? []).length;
      if (opens > 0) started = true;
      braces += opens;
      braces -= closes;
      if (!started && sanitized.includes(";")) {
        return line + 1;
      }
      if (started && braces <= 0) {
        return line + 1;
      }
    }
    return lines.length;
  }
  __name(blockEnd, "blockEnd");
  function pushBlockDefinition(name, type, startLine) {
    const start = offsets[startLine];
    const endLine = blockEnd(startLine);
    const end = offsets[endLine] ?? content.length;
    const code = content.slice(start, end);
    let search = code;
    const bodyStart = code.indexOf("{");
    const bodyEnd = code.lastIndexOf("}");
    if (bodyStart >= 0 && bodyEnd >= bodyStart) {
      search = code.slice(bodyStart + 1, bodyEnd);
    }
    defs.push({
      name,
      type,
      start,
      end,
      line: startLine + 1,
      code,
      search
    });
  }
  __name(pushBlockDefinition, "pushBlockDefinition");
  function pushVariable(name, startLine) {
    const start = offsets[startLine];
    const end = start + lines[startLine].length;
    const code = content.slice(start, end);
    defs.push({
      name,
      type: "variable",
      start,
      end,
      line: startLine + 1,
      code,
      search: code
    });
  }
  __name(pushVariable, "pushVariable");
  const classStack = [];
  let pendingFunction = null;
  let braceDepth = 0;
  function currentClass() {
    return classStack.length ? classStack[classStack.length - 1]?.name : void 0;
  }
  __name(currentClass, "currentClass");
  function resetPending() {
    pendingFunction = null;
  }
  __name(resetPending, "resetPending");
  function appendPending(text) {
    if (!pendingFunction || !text) return;
    if (pendingFunction.signature) pendingFunction.signature += " ";
    pendingFunction.signature += text;
  }
  __name(appendPending, "appendPending");
  function parsePending() {
    if (!pendingFunction) return null;
    const normalized = pendingFunction.signature.replace(/\s+/g, " ").trim();
    const parenIndex = normalized.indexOf("(");
    if (parenIndex === -1) return null;
    const before = normalized.slice(0, parenIndex).trim();
    if (!before) return null;
    const tokens = before.split(/\s+/);
    if (tokens.length === 0) return null;
    let candidate = tokens[tokens.length - 1];
    candidate = candidate.replace(/[*&]+$/, "");
    const namePart = (candidate.split("::").pop() ?? candidate).replace(/[*&]+$/, "");
    if (!/^~?[A-Za-z_]\w*$/.test(namePart)) return null;
    if (/^(?:if|for|while|switch|catch|return|sizeof|throw|case|else|do)$/.test(namePart)) return null;
    const type = pendingFunction.className || candidate.includes("::") ? "method" : "function";
    return {
      name: namePart,
      type
    };
  }
  __name(parsePending, "parsePending");
  function maybeFunctionStart(line) {
    if (!line.includes("(")) return false;
    if (/^(?:if|for|while|switch|catch|return|sizeof|throw|case|else|do)\b/.test(line)) return false;
    if (/^(?:using|typedef)\b/.test(line)) return false;
    return true;
  }
  __name(maybeFunctionStart, "maybeFunctionStart");
  for (let i = 0; i < lines.length; i++) {
    while (classStack.length && classStack[classStack.length - 1]?.endLine <= i) {
      classStack.pop();
    }
    const stripped = strippedLines[i];
    const trimmed = stripped.trim();
    const sanitizedLine = sanitize(stripped);
    if (pendingFunction) {
      appendPending(trimmed);
      if (sanitizedLine.includes("{")) {
        const parsed = parsePending();
        if (parsed) {
          pushBlockDefinition(parsed.name, parsed.type, pendingFunction.startLine);
        }
        resetPending();
      } else if (/;\s*$/.test(trimmed)) {
        resetPending();
      }
    } else if (trimmed && !trimmed.startsWith("#")) {
      const classMatch = /^(?:typedef\s+)?(?:template\s*<[^>]+>\s*)*(class|struct|union)\s+([A-Za-z_]\w*)/.exec(trimmed);
      if (classMatch && sanitizedLine.includes("{")) {
        const name = classMatch[2];
        const type = classMatch[1];
        const endLine = blockEnd(i);
        pushBlockDefinition(name, type, i);
        classStack.push({
          name,
          endLine
        });
      } else {
        const enumMatch = /^(?:typedef\s+)?(?:template\s*<[^>]+>\s*)*enum(?:\s+(?:class|struct))?\s+([A-Za-z_]\w*)/.exec(trimmed);
        if (enumMatch && sanitizedLine.includes("{")) {
          pushBlockDefinition(enumMatch[1], "enum", i);
        } else if (braceDepth === 0 && !trimmed.includes("(") && !/^(?:class|struct|union|enum|template|typedef)\b/.test(trimmed)) {
          const varMatch = /^(?:constexpr\s+|const\s+|static\s+|inline\s+|extern\s+|volatile\s+|register\s+|thread_local\s+)*[A-Za-z_]\w*[\w\s:<>,*&]*\s+([A-Za-z_]\w*)\s*(?:=\s*[^;]+)?;$/.exec(trimmed);
          if (varMatch) {
            pushVariable(varMatch[1], i);
          }
        }
        if (maybeFunctionStart(trimmed)) {
          pendingFunction = {
            startLine: i,
            signature: trimmed,
            className: currentClass()
          };
          if (sanitizedLine.includes("{")) {
            const parsed = parsePending();
            if (parsed) {
              pushBlockDefinition(parsed.name, parsed.type, pendingFunction.startLine);
            }
            resetPending();
          }
        }
      }
    }
    const opens = (sanitizedLine.match(/\{/g) ?? []).length;
    const closes = (sanitizedLine.match(/\}/g) ?? []).length;
    braceDepth += opens;
    braceDepth -= closes;
  }
  return defs;
}
__name(extractCppDefinitions, "extractCppDefinitions");
function extractSolidityDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      const cleaned = current.replace(/\/\/.*$/, "");
      const opens = (cleaned.match(/\{/g) ?? []).length;
      const closes = (cleaned.match(/\}/g) ?? []).length;
      if (!started && opens > 0) started = true;
      braces += opens;
      braces -= closes;
      if (!started && cleaned.includes(";")) {
        return line + 1;
      }
      if (started && braces <= 0) {
        return line + 1;
      }
    }
    return lines.length;
  }
  __name(blockEnd, "blockEnd");
  function pushDefinition(name, type, startLine) {
    const start = offsets[startLine];
    const endLine = blockEnd(startLine);
    const end = offsets[endLine] ?? content.length;
    const code = content.slice(start, end);
    const bodyStart = code.indexOf("{");
    const bodyEnd = code.lastIndexOf("}");
    const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
    defs.push({
      name,
      type,
      start,
      end,
      line: startLine + 1,
      code,
      search
    });
  }
  __name(pushDefinition, "pushDefinition");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const cleaned = line.replace(/\/\/.*$/, "");
    const trimmed = cleaned.trim();
    if (!trimmed) continue;
    const contractMatch = /^(?:abstract\s+)?(contract|interface|library)\s+([A-Za-z_][\w]*)/.exec(trimmed);
    if (contractMatch) {
      const type = contractMatch[1];
      const name = contractMatch[2];
      pushDefinition(name, type, i);
      let braceDepth = (trimmed.match(/\{/g) ?? []).length - (trimmed.match(/\}/g) ?? []).length;
      const endLine = blockEnd(i);
      for (let j = i + 1; j < endLine; j++) {
        const innerLine = lines[j];
        const innerClean = innerLine.replace(/\/\/.*$/, "");
        const innerTrim = innerClean.trim();
        const beforeDepth = braceDepth;
        const opens = (innerClean.match(/\{/g) ?? []).length;
        const closes = (innerClean.match(/\}/g) ?? []).length;
        if (beforeDepth >= 1 && innerTrim) {
          let memberName;
          let memberType;
          const fnMatch = /function\s+([A-Za-z_][\w]*)/.exec(innerTrim);
          if (fnMatch) {
            memberName = fnMatch[1];
            memberType = "function";
          } else if (/^constructor\s*\(/.test(innerTrim)) {
            memberName = "constructor";
            memberType = "constructor";
          } else {
            const modifierMatch = /modifier\s+([A-Za-z_][\w]*)/.exec(innerTrim);
            if (modifierMatch) {
              memberName = modifierMatch[1];
              memberType = "modifier";
            } else {
              const eventMatch = /event\s+([A-Za-z_][\w]*)/.exec(innerTrim);
              if (eventMatch) {
                memberName = eventMatch[1];
                memberType = "event";
              } else {
                const structMatch = /struct\s+([A-Za-z_][\w]*)/.exec(innerTrim);
                if (structMatch) {
                  memberName = structMatch[1];
                  memberType = "struct";
                } else {
                  const enumMatch = /enum\s+([A-Za-z_][\w]*)/.exec(innerTrim);
                  if (enumMatch) {
                    memberName = enumMatch[1];
                    memberType = "enum";
                  } else {
                    const errorMatch = /error\s+([A-Za-z_][\w]*)/.exec(innerTrim);
                    if (errorMatch) {
                      memberName = errorMatch[1];
                      memberType = "error";
                    }
                  }
                }
              }
            }
          }
          if (memberName && memberType) {
            pushDefinition(memberName, memberType, j);
          }
        }
        braceDepth += opens;
        braceDepth -= closes;
      }
      i = endLine - 1;
      continue;
    }
    const freeFnMatch = /^function\s+([A-Za-z_][\w]*)/.exec(trimmed);
    if (freeFnMatch) {
      pushDefinition(freeFnMatch[1], "function", i);
      continue;
    }
    const globalStructMatch = /^(struct|enum|error)\s+([A-Za-z_][\w]*)/.exec(trimmed);
    if (globalStructMatch) {
      pushDefinition(globalStructMatch[2], globalStructMatch[1], i);
    }
  }
  return defs;
}
__name(extractSolidityDefinitions, "extractSolidityDefinitions");
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
__name(escapeRegExp, "escapeRegExp");
function extractJavaDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      const cleaned = current.replace(/".*?"/g, "");
      const opens = (cleaned.match(/\{/g) ?? []).length;
      const closes = (cleaned.match(/\}/g) ?? []).length;
      braces += opens;
      braces -= closes;
      if (opens > 0) started = true;
      if (started && braces === 0) break;
    }
    return line + 1;
  }
  __name(blockEnd, "blockEnd");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();
    const cleaned = trimmed.replace(/\/\/.*$/, "");
    const classMatch = /^(?:public\s+|protected\s+|private\s+)?(?:abstract\s+|final\s+)?class\s+([\w$]+)/.exec(cleaned);
    const interfaceMatch = /^(?:public\s+|protected\s+|private\s+)?interface\s+([\w$]+)/.exec(cleaned);
    const enumMatch = /^(?:public\s+|protected\s+|private\s+)?enum\s+([\w$]+)/.exec(cleaned);
    if (classMatch) {
      const name = classMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "class",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      let braceDepth = 0;
      for (let j = i + 1; j < endLine; j++) {
        const inner = lines[j];
        const innerClean = inner.trim().replace(/\/\/.*$/, "");
        const opens = (innerClean.match(/\{/g) ?? []).length;
        const closes = (innerClean.match(/\}/g) ?? []).length;
        if (braceDepth === 0) {
          const methodMatch = /^(?:public|protected|private|static|final|abstract|synchronized|native|strictfp|default|\s)*(?:<[^>]+>\s*)?(?:[\w$]+\s+)*([\w$]+)\s*\(/.exec(innerClean);
          const name2 = methodMatch?.[1];
          if (name2 && ![
            "if",
            "for",
            "while",
            "switch",
            "catch"
          ].includes(name2)) {
            const mStart = offsets[j];
            const mEndLine = blockEnd(j);
            const mEnd = offsets[mEndLine] ?? content.length;
            const mCode = content.slice(mStart, mEnd);
            const bodyStart2 = mCode.indexOf("{");
            const bodyEnd2 = mCode.lastIndexOf("}");
            const search2 = bodyStart2 >= 0 && bodyEnd2 >= bodyStart2 ? mCode.slice(bodyStart2 + 1, bodyEnd2) : mCode;
            const type = name2 === classMatch[1] ? "constructor" : "method";
            defs.push({
              name: name2,
              type,
              start: mStart,
              end: mEnd,
              line: j + 1,
              code: mCode,
              search: search2
            });
            j = mEndLine - 1;
            braceDepth = 0;
            continue;
          }
        }
        braceDepth += opens;
        braceDepth -= closes;
      }
      i = endLine - 1;
    } else if (interfaceMatch) {
      const name = interfaceMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "interface",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    } else if (enumMatch) {
      const name = enumMatch[1];
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      defs.push({
        name,
        type: "enum",
        start,
        end,
        line: i + 1,
        code,
        search
      });
      i = endLine - 1;
    }
  }
  return defs;
}
__name(extractJavaDefinitions, "extractJavaDefinitions");
function extractCSharpDefinitions(content) {
  const { lines, offsets } = getLinesAndOffsets(content);
  const defs = [];
  function blockEnd(startLine) {
    let braces = 0;
    let started = false;
    let line = startLine;
    for (; line < lines.length; line++) {
      const current = lines[line];
      const cleaned = current.replace(/".*?"/g, "").replace(/\/\/.*$/, "");
      const opens = (cleaned.match(/\{/g) ?? []).length;
      const closes = (cleaned.match(/\}/g) ?? []).length;
      braces += opens;
      braces -= closes;
      if (opens > 0) started = true;
      if (started && braces === 0) break;
    }
    return started ? line + 1 : startLine + 1;
  }
  __name(blockEnd, "blockEnd");
  const modifierSet = /* @__PURE__ */ new Set([
    "public",
    "internal",
    "protected",
    "private",
    "partial",
    "static",
    "sealed",
    "abstract",
    "unsafe",
    "new",
    "readonly",
    "ref",
    "virtual",
    "override",
    "async",
    "extern"
  ]);
  const keywordBlockers = /* @__PURE__ */ new Set([
    "if",
    "for",
    "foreach",
    "while",
    "switch",
    "catch",
    "using",
    "lock"
  ]);
  function stripAttributes(text) {
    let current = text.trim();
    while (current.startsWith("[")) {
      const close = current.indexOf("]");
      if (close === -1) break;
      current = current.slice(close + 1).trimStart();
    }
    return current;
  }
  __name(stripAttributes, "stripAttributes");
  function skipModifiers(tokens) {
    let index = 0;
    while (index < tokens.length && modifierSet.has(tokens[index])) {
      index++;
    }
    return index;
  }
  __name(skipModifiers, "skipModifiers");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();
    if (!trimmed) continue;
    const noComment = trimmed.replace(/\/\/.*$/, "");
    if (!noComment) continue;
    const signature = stripAttributes(noComment);
    if (!signature) continue;
    const tokens = signature.split(/\s+/);
    if (tokens.length === 0) continue;
    const startIndex = skipModifiers(tokens);
    const keyword = tokens[startIndex];
    if (!keyword) continue;
    if (keyword === "record") {
      const recordKind = tokens[startIndex + 1] === "class" || tokens[startIndex + 1] === "struct" ? tokens[startIndex + 1] : void 0;
      const nameToken = tokens[startIndex + (recordKind ? 2 : 1)];
      if (nameToken) {
        const name = nameToken.replace(/[<({].*$/, "");
        const start = offsets[i];
        const endLine = blockEnd(i);
        const end = offsets[endLine] ?? content.length;
        const code = content.slice(start, end);
        const bodyStart = code.indexOf("{");
        const bodyEnd = code.lastIndexOf("}");
        const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
        defs.push({
          name,
          type: "record",
          start,
          end,
          line: i + 1,
          code,
          search
        });
        i = endLine - 1;
        continue;
      }
    } else if (keyword === "class" || keyword === "struct" || keyword === "interface" || keyword === "enum") {
      const nameToken = tokens[startIndex + 1];
      if (!nameToken) continue;
      const name = nameToken.replace(/[<({].*$/, "");
      const start = offsets[i];
      const endLine = blockEnd(i);
      const end = offsets[endLine] ?? content.length;
      const code = content.slice(start, end);
      const bodyStart = code.indexOf("{");
      const bodyEnd = code.lastIndexOf("}");
      const search = bodyStart >= 0 && bodyEnd >= bodyStart ? code.slice(bodyStart + 1, bodyEnd) : code;
      const type = keyword === "class" ? "class" : keyword === "struct" ? "struct" : keyword === "interface" ? "interface" : "enum";
      defs.push({
        name,
        type,
        start,
        end,
        line: i + 1,
        code,
        search
      });
      if (keyword === "class" || keyword === "struct") {
        let braceDepth = 0;
        for (let j = i + 1; j < endLine; j++) {
          const inner = lines[j];
          const innerTrim = inner.trim();
          if (!innerTrim) continue;
          const innerNoComment = innerTrim.replace(/\/\/.*$/, "");
          if (!innerNoComment) continue;
          const innerSignature = stripAttributes(innerNoComment);
          if (!innerSignature) continue;
          const opens = (innerSignature.match(/\{/g) ?? []).length;
          const closes = (innerSignature.match(/\}/g) ?? []).length;
          if (braceDepth <= 1 && innerSignature.includes("(")) {
            const parenIndex = innerSignature.indexOf("(");
            const before = innerSignature.slice(0, parenIndex).trim();
            if (before && !before.includes("=")) {
              const beforeTokens = before.split(/\s+/);
              const candidateRaw = beforeTokens[beforeTokens.length - 1];
              const candidate = candidateRaw?.replace(/<.*$/, "");
              if (candidate && !keywordBlockers.has(candidate)) {
                const mStart = offsets[j];
                const mEndLine = blockEnd(j);
                const mEnd = offsets[mEndLine] ?? content.length;
                const mCode = content.slice(mStart, mEnd);
                const bodyStart2 = mCode.indexOf("{");
                const bodyEnd2 = mCode.lastIndexOf("}");
                const search2 = bodyStart2 >= 0 && bodyEnd2 >= bodyStart2 ? mCode.slice(bodyStart2 + 1, bodyEnd2) : mCode;
                const typeName = candidate === name ? "constructor" : "method";
                defs.push({
                  name: candidate,
                  type: typeName,
                  start: mStart,
                  end: mEnd,
                  line: j + 1,
                  code: mCode,
                  search: search2
                });
                if (innerSignature.includes("{")) {
                  j = mEndLine - 1;
                  braceDepth = 0;
                  continue;
                }
              }
            }
          }
          braceDepth += opens;
          braceDepth -= closes;
        }
      }
      i = endLine - 1;
      continue;
    }
    if (/^(?:public|internal|protected|private|const|static|readonly)/.test(signature) && signature.includes("=")) {
      const equalIndex = signature.indexOf("=");
      if (equalIndex > 0) {
        const before = signature.slice(0, equalIndex).trim();
        const candidate = before.split(/\s+/).pop();
        if (candidate && /^[A-Za-z_][\w]*$/.test(candidate)) {
          const name = candidate;
          const start = offsets[i];
          const end = start + line.length;
          const code = content.slice(start, end);
          defs.push({
            name,
            type: "variable",
            start,
            end,
            line: i + 1,
            code,
            search: code
          });
        }
      }
    }
  }
  return defs;
}
__name(extractCSharpDefinitions, "extractCSharpDefinitions");

// interpreter/eval/pipeline/state-machine.ts
var _PipelineStateMachine = class _PipelineStateMachine {
  constructor(totalStages, isStage0Retryable = false, hasStage0Replay = false) {
    __publicField(this, "state");
    __publicField(this, "maxRetriesPerContext", 10);
    __publicField(this, "maxGlobalRetriesPerStage", 20);
    __publicField(this, "totalStages");
    __publicField(this, "isStage0Retryable");
    __publicField(this, "stage0Exhausted", false);
    __publicField(this, "stage0BaseOutput", null);
    __publicField(this, "stage0BaseStructuredOutput", null);
    __publicField(this, "hasStage0Replay");
    __publicField(this, "stage0RetryConsumed", false);
    this.totalStages = totalStages;
    this.isStage0Retryable = isStage0Retryable;
    this.hasStage0Replay = hasStage0Replay;
    this.state = this.initialState();
  }
  initialState() {
    return {
      status: "IDLE",
      currentStage: 0,
      currentInput: "",
      baseInput: "",
      currentStructuredInput: void 0,
      baseStructuredInput: void 0,
      events: [],
      stageStructuredOutputs: /* @__PURE__ */ new Map(),
      activeRetryContext: void 0,
      globalStageRetryCount: /* @__PURE__ */ new Map(),
      allRetryHistory: /* @__PURE__ */ new Map()
    };
  }
  /**
  * Public API - matches original interface
  */
  getTotalStages() {
    return this.totalStages;
  }
  getEvents() {
    return [
      ...this.state.events
    ];
  }
  getStatus() {
    return this.state.status;
  }
  /**
  * Get all retry history for simplified implementation
  */
  getAllRetryHistory() {
    return new Map(Array.from(this.state.allRetryHistory.entries()).map(([contextId, attempts]) => [
      contextId,
      attempts.map(cloneStructuredValue)
    ]));
  }
  /**
  * Main state transition function
  */
  /**
  * Transition the state machine based on the latest action.
  * WHY: Decouple stage execution from state mutations to keep behavior predictable.
  */
  transition(action) {
    switch (action.type) {
      case "START":
        return this.handleStart(action.input, action.structuredInput);
      case "STAGE_RESULT":
        return this.handleStageResult(action.result);
      case "ABORT":
        return this.handleAbort(action.reason);
      default:
        return {
          type: "INVALID_ACTION"
        };
    }
  }
  /**
  * Initialize pipeline execution for the first stage.
  * CONTEXT: Records PIPELINE_START and first STAGE_START events and seeds baseInput.
  */
  handleStart(input, structuredInput) {
    if (this.state.status !== "IDLE") {
      return {
        type: "INVALID_ACTION"
      };
    }
    const initialStructured = structuredInput ? cloneStructuredValue(structuredInput) : void 0;
    this.state.baseStructuredInput = initialStructured;
    this.state.currentStructuredInput = initialStructured;
    this.recordEvent({
      type: "PIPELINE_START",
      input,
      structuredInput: initialStructured
    });
    this.state.status = "RUNNING";
    this.state.currentStage = 0;
    this.state.currentInput = input;
    this.state.baseInput = input;
    this.stage0BaseOutput = input;
    this.stage0BaseStructuredOutput = initialStructured ?? null;
    if (this.totalStages === 0) {
      this.state.status = "COMPLETED";
      this.recordEvent({
        type: "PIPELINE_COMPLETE",
        output: input
      });
      return {
        type: "COMPLETE",
        output: input
      };
    }
    this.recordEvent({
      type: "STAGE_START",
      stage: 0,
      input,
      structuredInput: initialStructured
    });
    return {
      type: "EXECUTE_STAGE",
      stage: 0,
      input,
      structuredInput: initialStructured,
      context: this.buildStageContext(0)
    };
  }
  /**
  * Handle the result of a stage: success, retry, or error.
  * GOTCHA: Success on the retrying stage immediately re-executes the requesting stage.
  */
  handleStageResult(result) {
    const stage = this.state.currentStage;
    switch (result.type) {
      case "success":
        return this.handleStageSuccess(stage, result.output, result.structuredOutput);
      case "retry":
        return this.handleStageRetry(stage, result.reason, result.from, result.hint);
      case "error":
        return this.handleStageError(stage, result.error);
    }
  }
  /**
  * Process a successful stage output and advance the pipeline.
  * CONTEXT: When inside a retry context, completing the retried stage schedules the requester.
  */
  handleStageSuccess(stage, output, structuredOutput) {
    const context2 = this.state.activeRetryContext;
    const wrappedStructured = structuredOutput ? cloneStructuredValue(structuredOutput) : wrapStructured(output, "text", output);
    this.state.stageStructuredOutputs.set(stage, wrappedStructured);
    if (stage === 0) {
      this.stage0BaseStructuredOutput = wrappedStructured;
    }
    this.recordEvent({
      type: "STAGE_SUCCESS",
      stage,
      output,
      structuredOutput: wrappedStructured,
      contextId: context2?.id
    });
    if (context2 && stage === context2.retryingStage) {
      context2.allAttempts.push(cloneStructuredValue(wrappedStructured));
    }
    if (output === "") {
      this.state.status = "COMPLETED";
      this.state.currentStructuredInput = wrappedStructured;
      this.recordEvent({
        type: "PIPELINE_COMPLETE",
        output: ""
      });
      return {
        type: "COMPLETE",
        output: ""
      };
    }
    if (context2 && stage === context2.retryingStage) {
      context2.currentHint = void 0;
      const nextStage2 = context2.requestingStage;
      this.state.currentStage = nextStage2;
      this.state.currentInput = output;
      this.state.currentStructuredInput = wrappedStructured;
      this.recordEvent({
        type: "STAGE_START",
        stage: nextStage2,
        input: output,
        structuredInput: wrappedStructured,
        contextId: context2.id
      });
      return {
        type: "EXECUTE_STAGE",
        stage: nextStage2,
        input: output,
        structuredInput: wrappedStructured,
        context: this.buildStageContext(nextStage2)
      };
    }
    if (context2 && stage === context2.requestingStage) {
      this.state.allRetryHistory.set(context2.id, context2.allAttempts.map((attempt) => cloneStructuredValue(attempt)));
      this.state.activeRetryContext = void 0;
    }
    const nextStage = stage + 1;
    if (nextStage >= this.totalStages) {
      this.state.status = "COMPLETED";
      this.state.currentStructuredInput = wrappedStructured;
      this.recordEvent({
        type: "PIPELINE_COMPLETE",
        output
      });
      return {
        type: "COMPLETE",
        output
      };
    }
    this.state.currentStage = nextStage;
    this.state.currentInput = output;
    this.state.currentStructuredInput = wrappedStructured;
    this.recordEvent({
      type: "STAGE_START",
      stage: nextStage,
      input: output,
      structuredInput: wrappedStructured,
      contextId: context2?.id
    });
    return {
      type: "EXECUTE_STAGE",
      stage: nextStage,
      input: output,
      structuredInput: wrappedStructured,
      context: this.buildStageContext(nextStage)
    };
  }
  /**
  * Handle a retry request from the requesting stage.
  * WHY: Only upstream retries are allowed to keep the model simple and predictable.
  * GOTCHA: Targeting stage 0 requires a function source; otherwise we abort with guidance.
  */
  handleStageRetry(stage, reason, fromOverride, hint) {
    const targetStage = fromOverride ?? Math.max(0, stage - 1);
    if (process.env.MLLD_DEBUG === "true") {
      console.error("[SimplifiedStateMachine] handleStageRetry:", {
        requestingStage: stage,
        targetStage,
        hasActiveContext: !!this.state.activeRetryContext,
        contextRequestingStage: this.state.activeRetryContext?.requestingStage,
        contextRetryingStage: this.state.activeRetryContext?.retryingStage,
        willReuseContext: this.state.activeRetryContext?.requestingStage === stage && this.state.activeRetryContext?.retryingStage === targetStage
      });
    }
    if (stage === 0 && targetStage === 0) {
      if (!this.hasStage0Replay) {
        if (this.stage0RetryConsumed) {
          return this.advanceToNextStage(this.state.baseInput, this.stage0BaseStructuredOutput ?? void 0);
        }
        this.stage0RetryConsumed = true;
        this.stage0Exhausted = true;
        this.recordEvent({
          type: "STAGE_RETRY_REQUEST",
          requestingStage: 0,
          targetStage: 0,
          contextId: "stage0-self-retry"
        });
        this.recordEvent({
          type: "STAGE_SUCCESS",
          stage: 0,
          output: this.state.baseInput,
          structuredOutput: this.stage0BaseStructuredOutput ?? void 0,
          contextId: "stage0-self-retry"
        });
        this.state.currentStage = 0;
        this.state.currentInput = this.state.baseInput;
        this.state.currentStructuredInput = this.stage0BaseStructuredOutput ?? this.state.baseStructuredInput;
        return this.advanceToNextStage(this.state.baseInput, this.state.currentStructuredInput ?? void 0);
      }
      const globalRetries2 = this.state.globalStageRetryCount.get(0) || 0;
      if (globalRetries2 >= this.maxGlobalRetriesPerStage || this.stage0Exhausted) {
        return this.handleAbort(`Stage 0 exceeded global retry limit (${this.maxGlobalRetriesPerStage} attempts).`);
      }
      this.state.globalStageRetryCount.set(0, globalRetries2 + 1);
      this.recordEvent({
        type: "STAGE_RETRY_REQUEST",
        requestingStage: 0,
        targetStage: 0,
        contextId: "stage0-self-retry"
      });
      this.recordEvent({
        type: "STAGE_START",
        stage: 0,
        input: this.state.baseInput,
        structuredInput: this.stage0BaseStructuredOutput ?? this.state.baseStructuredInput,
        contextId: "stage0-self-retry"
      });
      return {
        type: "EXECUTE_STAGE",
        stage: 0,
        input: this.state.baseInput,
        structuredInput: this.stage0BaseStructuredOutput ?? this.state.baseStructuredInput,
        context: this.buildStageContext(0)
      };
    }
    if (targetStage === 0 && !this.isStage0Retryable) {
      return this.handleAbort("Cannot retry stage 0: input is not a function. Make the source a function to enable retries.");
    }
    let context2 = this.state.activeRetryContext;
    if (context2 && context2.requestingStage === stage && context2.retryingStage === targetStage) {
      context2.attemptNumber++;
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[SimplifiedStateMachine] Reusing context:", {
          contextId: context2.id,
          attemptNumber: context2.attemptNumber
        });
      }
    } else {
      const contextId = this.generateContextId();
      context2 = {
        id: contextId,
        requestingStage: stage,
        retryingStage: targetStage,
        attemptNumber: 1,
        allAttempts: [],
        hints: [],
        currentHint: void 0
      };
      if (this.state.activeRetryContext) {
        this.state.allRetryHistory.set(this.state.activeRetryContext.id, [
          ...this.state.activeRetryContext.allAttempts
        ]);
      }
      this.state.activeRetryContext = context2;
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[SimplifiedStateMachine] Created new context:", {
          contextId: context2.id,
          requestingStage: stage,
          retryingStage: targetStage
        });
      }
    }
    if (context2.attemptNumber > this.maxRetriesPerContext) {
      const attempts = context2.attemptNumber - 1;
      const hintSuffix = context2.currentHint ? ` Hint: ${typeof context2.currentHint === "string" ? context2.currentHint : JSON.stringify(context2.currentHint).slice(0, 120)}` : "";
      return this.handleAbort(`Stage ${stage} exceeded retry limit for stage ${targetStage} (${attempts} attempts; max ${this.maxRetriesPerContext}).${hintSuffix}`);
    }
    const globalRetries = this.state.globalStageRetryCount.get(targetStage) || 0;
    if (globalRetries >= this.maxGlobalRetriesPerStage) {
      const hintSuffix = context2.currentHint ? ` Hint: ${typeof context2.currentHint === "string" ? context2.currentHint : JSON.stringify(context2.currentHint).slice(0, 120)}` : "";
      return this.handleAbort(`Stage ${targetStage} exceeded global retry limit (${this.maxGlobalRetriesPerStage} attempts).${hintSuffix}`);
    }
    this.state.globalStageRetryCount.set(targetStage, globalRetries + 1);
    this.recordEvent({
      type: "STAGE_RETRY_REQUEST",
      requestingStage: stage,
      targetStage,
      contextId: context2.id
    });
    if (hint !== void 0 || reason) {
      const toStore = hint !== void 0 ? hint : reason;
      context2.currentHint = toStore;
      if (!context2.hints) context2.hints = [];
      context2.hints.push(toStore);
    }
    const retryInput = this.getInputForStage(targetStage);
    const retryStructuredInput = this.getStructuredInputForStage(targetStage);
    this.state.status = "RETRYING";
    this.state.currentStage = targetStage;
    this.state.currentInput = retryInput;
    this.state.currentStructuredInput = retryStructuredInput;
    this.recordEvent({
      type: "STAGE_START",
      stage: targetStage,
      input: retryInput,
      structuredInput: retryStructuredInput,
      contextId: context2.id
    });
    return {
      type: "EXECUTE_STAGE",
      stage: targetStage,
      input: retryInput,
      structuredInput: retryStructuredInput,
      context: this.buildStageContext(targetStage)
    };
  }
  /**
  * Record a stage error and halt execution.
  */
  handleStageError(stage, error) {
    this.recordEvent({
      type: "STAGE_FAILURE",
      stage,
      error
    });
    this.state.status = "FAILED";
    return {
      type: "ERROR",
      stage,
      error
    };
  }
  /**
  * Abort the pipeline with a reason (e.g., retry limit, non-retryable source).
  */
  handleAbort(reason) {
    this.recordEvent({
      type: "PIPELINE_ABORT",
      reason
    });
    this.state.status = "FAILED";
    return {
      type: "ABORT",
      reason
    };
  }
  /**
  * Build context for stage execution
  */
  /**
  * Build a user-facing context snapshot for a given stage.
  * WHY: The executor uses this to construct @mx and @p variables in stage environments.
  * GOTCHA: Attempt counts are context-local; downstream stages outside a retry context see try=1.
  */
  buildStageContext(stage) {
    const context2 = this.state.activeRetryContext;
    const events = this.state.events;
    const previousOutputs = [];
    const previousStructuredOutputs = [];
    const structuredOutputsRecord = {};
    structuredOutputsRecord[0] = this.stage0BaseStructuredOutput ?? this.state.baseStructuredInput;
    for (let s = 0; s < stage; s++) {
      let found = false;
      for (let i = events.length - 1; i >= 0; i--) {
        const event = events[i];
        if (event.type === "STAGE_SUCCESS" && event.stage === s) {
          previousOutputs.push(event.output);
          const structured = event.structuredOutput ?? this.state.stageStructuredOutputs.get(s);
          previousStructuredOutputs.push(structured ? cloneStructuredValue(structured) : void 0);
          structuredOutputsRecord[s + 1] = structured ? cloneStructuredValue(structured) : void 0;
          found = true;
          break;
        }
      }
      if (!found) {
        previousOutputs.push("");
        const structured = this.state.stageStructuredOutputs.get(s);
        previousStructuredOutputs.push(structured ? cloneStructuredValue(structured) : void 0);
        structuredOutputsRecord[s + 1] = structured ? cloneStructuredValue(structured) : void 0;
      }
    }
    const stageHistory = [];
    const stageHistoryStructured = [];
    if (context2 && (stage === context2.requestingStage || stage === context2.retryingStage)) {
      for (const attempt2 of context2.allAttempts) {
        const cloned = cloneStructuredValue(attempt2);
        stageHistoryStructured.push(cloned);
        stageHistory.push(cloned.text);
      }
    }
    let contextAttempt = 1;
    if (context2) {
      if (stage === context2.retryingStage) {
        contextAttempt = context2.attemptNumber + 1;
      } else if (stage === context2.requestingStage) {
        contextAttempt = context2.allAttempts.length + 1;
      }
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[SimplifiedStateMachine] buildStageContext attempt:", {
          stage,
          requestingStage: context2.requestingStage,
          retryingStage: context2.retryingStage,
          attemptNumber: context2.attemptNumber,
          allAttemptsLength: context2.allAttempts.length,
          willUseAttempt: stage === context2.requestingStage || stage === context2.retryingStage,
          contextAttempt
        });
      }
    }
    const globalStageRetries = this.state.globalStageRetryCount.get(stage) || 0;
    const attempt = globalStageRetries + 1;
    if (!context2) {
      contextAttempt = attempt;
    }
    let totalRetries = 0;
    for (const count of this.state.globalStageRetryCount.values()) {
      totalRetries += count;
    }
    const globalAttempt = totalRetries + 1;
    return {
      stage: stage + 1,
      attempt,
      contextAttempt,
      history: stageHistory,
      previousOutputs,
      globalAttempt,
      totalStages: this.totalStages,
      outputs: {
        0: this.state.baseInput,
        ...Object.fromEntries(previousOutputs.map((out, i) => [
          i + 1,
          out
        ]))
      },
      structuredOutputs: structuredOutputsRecord,
      contextId: context2?.id,
      hintHistory: context2?.hints ? [
        ...context2.hints
      ] : [],
      currentHint: context2?.currentHint,
      previousStructuredOutputs,
      historyStructured: stageHistoryStructured,
      baseStructuredInput: this.state.baseStructuredInput,
      currentStructuredInput: this.state.currentStructuredInput
    };
  }
  /**
  * Helper methods
  */
  generateContextId() {
    return `mx-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
  getInputForStage(stage) {
    if (stage === 0) {
      return this.state.baseInput;
    }
    for (let i = this.state.events.length - 1; i >= 0; i--) {
      const event = this.state.events[i];
      if (event.type === "STAGE_SUCCESS" && event.stage === stage - 1) {
        return event.output;
      }
    }
    return this.state.baseInput;
  }
  getStructuredInputForStage(stage) {
    if (stage === 0) {
      return this.state.baseStructuredInput ? cloneStructuredValue(this.state.baseStructuredInput) : void 0;
    }
    const structured = this.state.stageStructuredOutputs.get(stage - 1);
    if (structured) {
      return cloneStructuredValue(structured);
    }
    return this.state.baseStructuredInput ? cloneStructuredValue(this.state.baseStructuredInput) : void 0;
  }
  recordEvent(event) {
    this.state.events.push(event);
  }
  /**
  * Advance to the next stage without creating a retry context.
  * Used for non-replayable stage-0 retries to avoid spinning.
  */
  advanceToNextStage(output, structuredOutput) {
    const nextStage = this.state.currentStage + 1;
    if (output === "") {
      this.state.status = "COMPLETED";
      this.state.currentStructuredInput = structuredOutput ?? this.state.baseStructuredInput;
      this.recordEvent({
        type: "PIPELINE_COMPLETE",
        output: ""
      });
      return {
        type: "COMPLETE",
        output: ""
      };
    }
    if (nextStage >= this.totalStages) {
      this.state.status = "COMPLETED";
      this.state.currentStructuredInput = structuredOutput ?? this.state.baseStructuredInput;
      this.recordEvent({
        type: "PIPELINE_COMPLETE",
        output
      });
      return {
        type: "COMPLETE",
        output
      };
    }
    this.state.currentStage = nextStage;
    this.state.currentInput = output;
    this.state.currentStructuredInput = structuredOutput ?? this.state.baseStructuredInput;
    this.recordEvent({
      type: "STAGE_START",
      stage: nextStage,
      input: output,
      structuredInput: structuredOutput ?? this.state.baseStructuredInput,
      contextId: this.state.activeRetryContext?.id
    });
    return {
      type: "EXECUTE_STAGE",
      stage: nextStage,
      input: output,
      structuredInput: structuredOutput ?? this.state.baseStructuredInput,
      context: this.buildStageContext(nextStage)
    };
  }
};
__name(_PipelineStateMachine, "PipelineStateMachine");
var PipelineStateMachine = _PipelineStateMachine;
function cloneStructuredValue(value) {
  const clone = wrapStructured(value);
  inheritExpressionProvenance(clone, value);
  return clone;
}
__name(cloneStructuredValue, "cloneStructuredValue");

// interpreter/utils/json-to-xml.ts
function toScreamingSnakeCase(str) {
  return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s\-\.]+/g, "_").replace(/[^A-Z0-9_]/gi, "").toUpperCase().replace(/^_+|_+$/g, "");
}
__name(toScreamingSnakeCase, "toScreamingSnakeCase");
function escapeXml(str) {
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
__name(escapeXml, "escapeXml");
function jsonToXml(data, rootTag) {
  const lines = [];
  function convertValue(value, tagName, indent = "") {
    if (value === null || value === void 0) {
      return;
    }
    const tag = toScreamingSnakeCase(tagName);
    if (Array.isArray(value)) {
      lines.push(`${indent}<${tag}>`);
      value.forEach((item, index) => {
        convertValue(item, `item`, indent + "  ");
      });
      lines.push(`${indent}</${tag}>`);
    } else if (typeof value === "object" && value !== null) {
      const entries = Object.entries(value);
      if (entries.length === 0) {
        lines.push(`${indent}<${tag} />`);
      } else if (rootTag && indent === "") {
        entries.forEach(([key, val]) => {
          convertValue(val, key, indent);
        });
      } else {
        lines.push(`${indent}<${tag}>`);
        entries.forEach(([key, val]) => {
          convertValue(val, key, indent + "  ");
        });
        lines.push(`${indent}</${tag}>`);
      }
    } else {
      const content = escapeXml(String(value));
      lines.push(`${indent}<${tag}>${content}</${tag}>`);
    }
  }
  __name(convertValue, "convertValue");
  if (Array.isArray(data)) {
    convertValue(data, rootTag || "ROOT");
  } else if (typeof data === "object" && data !== null) {
    Object.entries(data).forEach(([key, value]) => {
      convertValue(value, key, "");
    });
  } else {
    return `<DOCUMENT>${escapeXml(String(data))}</DOCUMENT>`;
  }
  return lines.join("\n");
}
__name(jsonToXml, "jsonToXml");

// interpreter/utils/pipeline-input.ts
function parseCsv(text) {
  const lines = text.trim().split("\n");
  return lines.map((line) => {
    const result = [];
    let current = "";
    let inQuotes = false;
    for (let i = 0; i < line.length; i++) {
      const char = line[i];
      if (char === '"') {
        if (inQuotes && line[i + 1] === '"') {
          current += '"';
          i++;
        } else {
          inQuotes = !inQuotes;
        }
        continue;
      }
      if (char === "," && !inQuotes) {
        result.push(current);
        current = "";
        continue;
      }
      current += char;
    }
    if (current || line.endsWith(",")) {
      result.push(current);
    }
    return result;
  });
}
__name(parseCsv, "parseCsv");
function parseXml(text) {
  try {
    const parsed = JSON.parse(text);
    return jsonToXml(parsed);
  } catch {
    return `<DOCUMENT>
${text}
</DOCUMENT>`;
  }
}
__name(parseXml, "parseXml");
function wrapWithMetadata(value, extra) {
  for (const [key, data] of Object.entries(extra)) {
    Object.defineProperty(value, key, {
      value: data,
      enumerable: false,
      configurable: true
    });
  }
  return value;
}
__name(wrapWithMetadata, "wrapWithMetadata");
function buildPipelineStructuredValue(text, format = "json") {
  const normalizedFormat = (format ?? "json").toLowerCase();
  if (normalizedFormat === "csv") {
    try {
      const data = parseCsv(text);
      return wrapWithMetadata(wrapStructured(data, "array", text), {
        csv: data
      });
    } catch (error) {
      throw new MlldInterpreterError(`Failed to parse CSV: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  if (normalizedFormat === "xml") {
    try {
      const data = parseXml(text);
      return wrapWithMetadata(wrapStructured(data, "xml", text), {
        xml: data
      });
    } catch (error) {
      throw new MlldInterpreterError(`Failed to parse XML: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  if (normalizedFormat === "text") {
    return wrapStructured(text, "text", text);
  }
  try {
    const trimmed = typeof text === "string" ? text.trim() : text;
    if (trimmed === "") {
      return wrapStructured("", "text", text);
    }
    const parsed = JSON.parse(text);
    const structuredType = Array.isArray(parsed) ? "array" : parsed !== null && typeof parsed === "object" ? "object" : typeof parsed;
    return wrapStructured(parsed, "json", text, {
      format: "json",
      structuredType
    });
  } catch (error) {
    throw new MlldInterpreterError(`Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`);
  }
}
__name(buildPipelineStructuredValue, "buildPipelineStructuredValue");

// interpreter/eval/pipeline/context-builder.ts
async function createStageEnvironment(command, input, structuredInput, context2, env, format, events, hasSyntheticSource = false, allRetryHistory, structuredAccess, options) {
  const rawId = command?.rawIdentifier || "inline-stage";
  const userVisibleStage = hasSyntheticSource && rawId !== "__source__" ? context2.stage - 1 : context2.stage;
  const userVisibleTotalStages = hasSyntheticSource ? context2.totalStages - 1 : context2.totalStages;
  let normalizedHint = context2.currentHint;
  try {
    if (normalizedHint && typeof normalizedHint === "object") {
      if ("wrapperType" in normalizedHint && Array.isArray(normalizedHint.content)) {
        const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
        normalizedHint = await interpolate2(normalizedHint.content, env);
      } else if ("type" in normalizedHint) {
        const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
        normalizedHint = await extractVariableValue2(normalizedHint, env);
      }
      if (normalizedHint && typeof normalizedHint === "object") {
        const isPlain = Object.prototype.toString.call(normalizedHint) === "[object Object]" && !("wrapperType" in normalizedHint) && !("type" in normalizedHint) && !("nodeId" in normalizedHint);
        if (!isPlain) {
          try {
            const { JSONFormatter: JSONFormatter2 } = await import('./json-formatter-4JGND4MP.mjs');
            normalizedHint = JSONFormatter2.stringify(normalizedHint);
          } catch {
            normalizedHint = String(normalizedHint);
          }
        }
      }
    }
    if (normalizedHint !== void 0 && normalizedHint !== null && typeof normalizedHint !== "string" && typeof normalizedHint !== "object") {
      normalizedHint = String(normalizedHint);
    }
  } catch {
  }
  const pipelineContextSnapshot = {
    stage: userVisibleStage,
    totalStages: userVisibleTotalStages,
    currentCommand: rawId,
    input: context2.currentStructuredInput ?? structuredInput ?? input,
    previousOutputs: context2.previousStructuredOutputs && context2.previousStructuredOutputs.length > 0 ? context2.previousStructuredOutputs : context2.previousOutputs,
    format,
    // Use context-local attempt for ambient @mx.try
    attemptCount: context2.contextAttempt,
    // Preserve attempts history for @mx.tries
    attemptHistory: context2.historyStructured && context2.historyStructured.length > 0 ? context2.historyStructured : context2.history,
    // Provide hint info for ambient @mx.hint
    hint: normalizedHint,
    hintHistory: context2.hintHistory || [],
    sourceRetryable: options?.sourceRetryable ?? false,
    guards: env.getPipelineGuardHistory()
  };
  options?.capturePipelineContext?.(pipelineContextSnapshot);
  if (!options?.skipSetPipelineContext) {
    env.setPipelineContext(pipelineContextSnapshot);
  }
  const stageEnv = env.createChild();
  const pipelineInputWrapper = wrapStructured(structuredInput);
  inheritExpressionProvenance(pipelineInputWrapper, structuredInput);
  await setSimplifiedInputVariable(stageEnv, input, pipelineInputWrapper, format);
  setSimplifiedPipelineVariable(stageEnv, context2, events, hasSyntheticSource, allRetryHistory, structuredAccess);
  return stageEnv;
}
__name(createStageEnvironment, "createStageEnvironment");
async function setSimplifiedInputVariable(env, input, structuredInput, format) {
  const inputSource = {
    directive: "var",
    syntax: "template",
    hasInterpolation: false,
    isMultiLine: false
  };
  let inputVar;
  if (format) {
    const pipelineInputObj = buildPipelineStructuredValue(input, format);
    inputVar = createPipelineInputVariable("input", pipelineInputObj, format, input, inputSource, 1);
    inputVar.internal = {
      ...inputVar.internal ?? {},
      isSystem: true,
      isPipelineParameter: true
    };
  } else if (structuredInput && isStructuredValue(structuredInput)) {
    const structuredVar = createStructuredValueVariable("input", structuredInput, inputSource, {
      mx: {},
      internal: {
        isSystem: true,
        isPipelineParameter: true
      }
    });
    env.setParameterVariable("input", structuredVar);
    return;
  } else {
    inputVar = createSimpleTextVariable("input", input, inputSource, {
      mx: {},
      internal: {
        isSystem: true,
        isPipelineParameter: true
      }
    });
  }
  env.setParameterVariable("input", inputVar);
}
__name(setSimplifiedInputVariable, "setSimplifiedInputVariable");
function setSimplifiedPipelineVariable(env, context2, events, hasSyntheticSource = false, allRetryHistory, structuredAccess) {
  const pipelineContext = createSimplifiedPipelineContext(context2, events, hasSyntheticSource, allRetryHistory, structuredAccess, () => env.getPipelineGuardHistory());
  const inputSource = {
    directive: "var",
    syntax: "template",
    hasInterpolation: false,
    isMultiLine: false
  };
  const pipelineVar = createObjectVariable("pipeline", pipelineContext, false, inputSource, {
    mx: {},
    internal: {
      isSystem: true,
      isPipelineContext: true
    }
  });
  env.setParameterVariable("pipeline", pipelineVar);
  env.setParameterVariable("p", pipelineVar);
}
__name(setSimplifiedPipelineVariable, "setSimplifiedPipelineVariable");
function createSimplifiedPipelineContext(context2, events, hasSyntheticSource = false, allRetryHistory, structuredAccess, guardHistoryProvider) {
  const userVisibleStage = hasSyntheticSource && context2.stage > 0 ? context2.stage - 1 : context2.stage;
  if (process.env.MLLD_DEBUG === "true") {
    console.error("[SimplifiedContextBuilder] Creating context:", {
      internalStage: context2.stage,
      userVisibleStage,
      contextAttempt: context2.contextAttempt,
      historyLength: context2.history.length,
      hasSyntheticSource
    });
  }
  const toStructured = /* @__PURE__ */ __name((stageIndex, fallback) => {
    if (stageIndex !== null && structuredAccess) {
      return structuredAccess.getStageOutput(stageIndex, fallback ?? "");
    }
    return buildPipelineStructuredValue(fallback ?? "", "text");
  }, "toStructured");
  const baseInput = context2.outputs?.[0] ?? "";
  const baseWrapper = toStructured(-1, baseInput);
  const stageWrappers = context2.previousOutputs.map((output, index) => toStructured(index, output));
  const userVisibleWrappers = hasSyntheticSource && stageWrappers.length > 0 ? stageWrappers.slice(1) : stageWrappers;
  const pipelineContext = {
    try: context2.contextAttempt,
    stage: userVisibleStage,
    length: userVisibleWrappers.length
  };
  let triesText = [];
  let structuredTries = [];
  if (context2.historyStructured && context2.historyStructured.length > 0) {
    structuredTries = context2.historyStructured.map(cloneStructuredValue2);
    triesText = structuredTries.map((entry) => entry.text);
  } else if (context2.history.length > 0) {
    triesText = [
      ...context2.history
    ];
    structuredTries = context2.history.map((entry) => toStructured(null, entry));
  } else if (allRetryHistory && allRetryHistory.size > 0) {
    const attempts = Array.from(allRetryHistory.values()).map((history) => history.map((attempt) => cloneStructuredValue2(attempt)));
    structuredTries = attempts;
    triesText = attempts.map((history) => history.map((item) => item.text));
  }
  pipelineContext.tries = triesText;
  Object.defineProperty(pipelineContext, "structuredTries", {
    value: structuredTries,
    enumerable: false
  });
  pipelineContext[0] = baseWrapper;
  if (hasSyntheticSource) {
    userVisibleWrappers.forEach((wrapper, index) => {
      pipelineContext[index + 1] = wrapper;
    });
  } else {
    stageWrappers.forEach((wrapper, index) => {
      pipelineContext[index + 1] = wrapper;
    });
  }
  Object.defineProperty(pipelineContext, -1, {
    get: /* @__PURE__ */ __name(() => userVisibleWrappers[userVisibleWrappers.length - 1], "get"),
    enumerable: false
  });
  Object.defineProperty(pipelineContext, -2, {
    get: /* @__PURE__ */ __name(() => userVisibleWrappers[userVisibleWrappers.length - 2], "get"),
    enumerable: false
  });
  for (let i = 3; i <= Math.max(10, userVisibleWrappers.length); i++) {
    Object.defineProperty(pipelineContext, -i, {
      get: /* @__PURE__ */ __name(() => userVisibleWrappers[userVisibleWrappers.length - i], "get"),
      enumerable: false
    });
  }
  Object.defineProperty(pipelineContext, "retries", {
    get: /* @__PURE__ */ __name(() => {
      if (!allRetryHistory || allRetryHistory.size === 0) {
        return {
          all: []
        };
      }
      const allAttempts = [];
      for (const attempts of allRetryHistory.values()) {
        if (attempts.length > 0) {
          const mapped = attempts.map((attempt) => cloneStructuredValue2(attempt));
          allAttempts.push(mapped);
        }
      }
      return {
        all: allAttempts
      };
    }, "get"),
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(pipelineContext, "guards", {
    get: /* @__PURE__ */ __name(() => guardHistoryProvider ? guardHistoryProvider() : [], "get"),
    enumerable: true,
    configurable: true
  });
  return pipelineContext;
}
__name(createSimplifiedPipelineContext, "createSimplifiedPipelineContext");
function cloneStructuredValue2(value) {
  const clone = wrapStructured(value);
  inheritExpressionProvenance(clone, value);
  return clone;
}
__name(cloneStructuredValue2, "cloneStructuredValue");

// interpreter/eval/output-shared.ts
function formatJSONL(value) {
  return JSON.stringify(value);
}
__name(formatJSONL, "formatJSONL");
async function evaluateAppend(directive, env, context2) {
  if (env.getIsImporting()) {
    return {
      value: null,
      env
    };
  }
  if (!directive.meta?.hasSource) {
    throw new MlldDirectiveError("/append requires source content before the target", "append", {
      location: directive.location
    });
  }
  const sourceType = directive.meta?.sourceType;
  if (!sourceType) {
    throw new MlldDirectiveError("Unable to determine append source type", "append", {
      location: directive.location
    });
  }
  const target = directive.values?.target;
  if (!target || target.type !== "file") {
    throw new MlldDirectiveError("/append supports file targets only", "append", {
      location: directive.location
    });
  }
  const sourceResult = await evaluateOutputSource(directive, env, sourceType, context2);
  let content = sourceResult.text;
  const descriptorSource = sourceResult.rawValue;
  const materialized = materializeDisplayValue(descriptorSource ?? content, void 0, descriptorSource ?? content, content);
  content = materialized.text;
  if (materialized.descriptor) {
    env.recordSecurityDescriptor(materialized.descriptor);
  }
  const format = typeof directive.meta?.format === "string" ? directive.meta?.format : void 0;
  await appendContentToFile(target, content, env, {
    location: directive.location,
    directiveKind: "append",
    format
  });
  env.hasExplicitOutput = true;
  return {
    value: "",
    env
  };
}
__name(evaluateAppend, "evaluateAppend");
async function appendContentToFile(target, content, env, options) {
  const resolvedPath = await resolveAppendPath(target, env);
  const directiveKind = options.directiveKind ?? "append";
  const { payload, format } = formatAppendPayload(resolvedPath, content, {
    location: options.location,
    directiveKind,
    format: options.format
  });
  const fileSystem = env.fileSystem;
  if (!fileSystem || typeof fileSystem.appendFile !== "function") {
    throw new MlldDirectiveError("File system not available for append directive", directiveKind, {
      location: options.location
    });
  }
  await fileSystem.appendFile(resolvedPath, payload);
  env.emitEffect("file", payload, {
    path: resolvedPath,
    source: options.location,
    mode: "append",
    metadata: {
      format
    }
  });
}
__name(appendContentToFile, "appendContentToFile");
async function resolveAppendPath(target, env) {
  const descriptors = [];
  const interpolated = await interpolate(target.path, env, void 0, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  const merged = descriptors.length === 1 ? descriptors[0] : descriptors.length > 1 ? env.mergeSecurityDescriptors(...descriptors) : void 0;
  if (merged) {
    env.recordSecurityDescriptor(merged);
  }
  let resolvedPath = String(interpolated);
  if (!resolvedPath) {
    throw new MlldDirectiveError("Append target path cannot be empty", "append");
  }
  if (resolvedPath.startsWith("@base/")) {
    const projectRoot = env.getProjectRoot();
    resolvedPath = path7.join(projectRoot, resolvedPath.substring(6));
  } else if (resolvedPath.startsWith("@root/")) {
    const projectRoot = env.getProjectRoot();
    resolvedPath = path7.join(projectRoot, resolvedPath.substring(6));
  }
  if (!path7.isAbsolute(resolvedPath)) {
    resolvedPath = path7.resolve(env.getBasePath(), resolvedPath);
  }
  return resolvedPath;
}
__name(resolveAppendPath, "resolveAppendPath");
function formatAppendPayload(resolvedPath, rawContent, options) {
  const directiveKind = options.directiveKind ?? "append";
  const extension = path7.extname(resolvedPath).toLowerCase();
  const explicitFormat = options.format ? String(options.format).toLowerCase() : void 0;
  if (extension === ".json") {
    throw new MlldDirectiveError("Cannot append to .json files. Use a .jsonl extension for JSON lines output.", directiveKind, {
      location: options.location
    });
  }
  if (explicitFormat && explicitFormat !== "jsonl" && explicitFormat !== "text") {
    throw new MlldDirectiveError(`Unsupported /append format "${explicitFormat}". Allowed formats: jsonl, text.`, directiveKind, {
      location: options.location
    });
  }
  const treatAsJsonl = explicitFormat === "jsonl" || extension === ".jsonl";
  if (treatAsJsonl) {
    if (extension !== ".jsonl") {
      throw new MlldDirectiveError("JSONL format requires a .jsonl file extension.", directiveKind, {
        location: options.location
      });
    }
    let parsed;
    try {
      parsed = JSON.parse(rawContent);
    } catch (error) {
      throw new MlldDirectiveError("Content appended to .jsonl must be valid JSON. Provide a variable or template that resolves to JSON data.", directiveKind, {
        location: options.location,
        cause: error instanceof Error ? error : void 0
      });
    }
    const formatted = formatJSONL(parsed);
    return {
      payload: ensureTrailingNewline(formatted),
      format: "jsonl"
    };
  }
  return {
    payload: ensureTrailingNewline(rawContent),
    format: "text"
  };
}
__name(formatAppendPayload, "formatAppendPayload");
function ensureTrailingNewline(value) {
  return value.endsWith("\n") ? value : `${value}
`;
}
__name(ensureTrailingNewline, "ensureTrailingNewline");

// interpreter/eval/pipeline/builtin-effects.ts
var BUILTIN_EFFECTS = /* @__PURE__ */ new Set([
  "log",
  "LOG",
  "output",
  "OUTPUT",
  "show",
  "SHOW",
  "append",
  "APPEND"
]);
function isBuiltinEffect(name) {
  return BUILTIN_EFFECTS.has(name);
}
__name(isBuiltinEffect, "isBuiltinEffect");
function recordInterpolatedDescriptors(env, descriptors) {
  if (descriptors.length === 0) {
    return;
  }
  const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
  env.recordSecurityDescriptor(merged);
}
__name(recordInterpolatedDescriptors, "recordInterpolatedDescriptors");
async function evaluateEffectArg(arg, env) {
  const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
  if (Array.isArray(arg)) {
    const descriptors2 = [];
    const value2 = await interpolate2(arg, env, void 0, {
      collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
        if (descriptor) {
          descriptors2.push(descriptor);
        }
      }, "collectSecurityDescriptor")
    });
    recordInterpolatedDescriptors(env, descriptors2);
    return String(value2);
  }
  const descriptors = [];
  const value = await interpolate2([
    arg
  ], env, void 0, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  recordInterpolatedDescriptors(env, descriptors);
  return String(value);
}
__name(evaluateEffectArg, "evaluateEffectArg");
function buildEffectOperationContext(effect) {
  const type = typeof effect.rawIdentifier === "string" ? effect.rawIdentifier.toLowerCase() : "effect";
  const hasExplicitSource = Boolean(effect.meta?.hasExplicitSource);
  const labels = Array.isArray(effect.meta?.securityLabels) ? effect.meta.securityLabels : void 0;
  return {
    type,
    subtype: "effect",
    name: effect.rawIdentifier,
    labels,
    location: effect?.location ?? effect.meta?.location ?? null,
    metadata: {
      trace: `effect:${effect.rawIdentifier ?? type}`,
      isEffect: true,
      hasExplicitSource
    }
  };
}
__name(buildEffectOperationContext, "buildEffectOperationContext");
function createEffectHookNode(effect) {
  return {
    ...effect,
    type: "Effect",
    location: effect?.location ?? effect.meta?.location ?? null
  };
}
__name(createEffectHookNode, "createEffectHookNode");
async function resolveEffectPayload(effect, stageOutput, env) {
  const name = typeof effect.rawIdentifier === "string" ? effect.rawIdentifier.toLowerCase() : "";
  const args = effect.args ?? [];
  const hasExplicitSource = Boolean(effect.meta?.hasExplicitSource);
  const usesExplicitSource = args.length >= 2;
  const stageValue = stageOutput ?? "";
  const stageText = typeof stageValue === "string" ? stageValue : asText(stageValue);
  switch (name) {
    case "log":
    case "show": {
      if (args.length > 0) {
        const parts = [];
        for (const a of args) {
          parts.push(await evaluateEffectArg(a, env));
        }
        return parts.join(" ");
      }
      return stageValue ?? stageText;
    }
    case "output": {
      if (usesExplicitSource && args.length >= 1) {
        try {
          return await evaluateEffectArg(args[0], env);
        } catch {
          return stageValue ?? stageText;
        }
      }
      return stageValue ?? stageText;
    }
    case "append": {
      if (hasExplicitSource && args.length > 0) {
        return await evaluateEffectArg(args[0], env);
      }
      return stageValue ?? stageText;
    }
    default:
      return stageValue ?? stageText;
  }
}
__name(resolveEffectPayload, "resolveEffectPayload");
async function extractEffectGuardInputs(effect, stageOutput, env) {
  const payload = await resolveEffectPayload(effect, stageOutput, env);
  const guardInputs = materializeGuardInputs([
    payload
  ], {
    nameHint: "__effect_input__"
  });
  return {
    guardInputs,
    payload
  };
}
__name(extractEffectGuardInputs, "extractEffectGuardInputs");
function convertEffectRetryToDeny(error, operationContext, env) {
  const details = error.details;
  const retryHint = details?.retryHint ?? null ?? (error.retryHint === void 0 ? null : error.retryHint);
  const reason = retryHint && typeof retryHint === "string" ? `Guard retry not supported for effects: ${retryHint}` : "Guard retry not supported for effects";
  return new GuardError({
    decision: "deny",
    guardName: details?.guardName ?? null,
    guardFilter: details?.guardFilter,
    scope: details?.scope,
    operation: details?.operation ?? operationContext,
    inputPreview: details?.inputPreview,
    retryHint,
    reason,
    guardContext: details?.guardContext,
    guardInput: details?.guardInput ?? null,
    reasons: details?.reasons,
    guardResults: details?.guardResults,
    hints: details?.hints,
    timing: details?.timing,
    sourceLocation: error.sourceLocation ?? operationContext.location ?? void 0,
    env
  });
}
__name(convertEffectRetryToDeny, "convertEffectRetryToDeny");
async function runBuiltinEffect(effect, stageOutput, env) {
  const hookManager = env.getHookManager();
  const operationContext = buildEffectOperationContext(effect);
  const hookNode = createEffectHookNode(effect);
  const { guardInputs, payload } = await extractEffectGuardInputs(effect, stageOutput, env);
  const inputs = guardInputs.length > 0 ? guardInputs : materializeGuardInputs([
    stageOutput ?? ""
  ], {
    nameHint: "__effect_input__"
  });
  await env.withOpContext(operationContext, async () => {
    const preDecision = await hookManager.runPre(hookNode, inputs, env, operationContext);
    const transformedInputs = getGuardTransformedInputs(preDecision, inputs);
    const resolvedInputs = transformedInputs ?? inputs;
    try {
      await handleGuardDecision(preDecision, hookNode, env, operationContext);
    } catch (error) {
      if (isGuardRetrySignal(error)) {
        throw convertEffectRetryToDeny(error, operationContext, env);
      }
      throw error;
    }
    const primaryInput = resolvedInputs[0] ?? inputs[0];
    const payloadVariable = isVariable(primaryInput) ? primaryInput : void 0;
    const payloadValue = payloadVariable !== void 0 ? await extractVariableValue(payloadVariable, env) : payload;
    const effectResult = await executeEffect(effect, payloadValue, payloadVariable, env);
    try {
      await hookManager.runPost(hookNode, effectResult, resolvedInputs, env, operationContext);
    } catch (error) {
      if (isGuardRetrySignal(error)) {
        throw convertEffectRetryToDeny(error, operationContext, env);
      }
      throw error;
    }
  });
}
__name(runBuiltinEffect, "runBuiltinEffect");
async function executeEffect(effect, payloadValue, payloadVariable, env) {
  const name = effect.rawIdentifier;
  const normalizedPayload = payloadValue ?? "";
  const payloadText = typeof normalizedPayload === "string" ? normalizedPayload : asText(normalizedPayload);
  const descriptorSource = payloadVariable ?? normalizedPayload;
  switch (name) {
    case "log":
    case "LOG": {
      const materialized = materializeDisplayValue(descriptorSource ?? payloadText, void 0, descriptorSource ?? payloadText, payloadText);
      let output = materialized.text;
      if (!output.endsWith("\n")) output += "\n";
      if (materialized.descriptor) {
        env.recordSecurityDescriptor(materialized.descriptor);
      }
      env.emitEffect("stderr", output);
      return {
        value: payloadVariable ?? normalizedPayload,
        env
      };
    }
    case "show":
    case "SHOW": {
      const materialized = materializeDisplayValue(descriptorSource ?? payloadText, void 0, descriptorSource ?? payloadText, payloadText);
      let output = materialized.text;
      if (!output.endsWith("\n")) output += "\n";
      if (materialized.descriptor) {
        env.recordSecurityDescriptor(materialized.descriptor);
      }
      env.emitEffect("both", output);
      return {
        value: payloadVariable ?? normalizedPayload,
        env
      };
    }
    case "output":
    case "OUTPUT": {
      const args = effect.args ?? [];
      let content = payloadText;
      let target = null;
      if (args.length > 1) {
        target = args[1];
      } else if (args.length === 1) {
        target = args[0];
      }
      if (!target || typeof target !== "object" || !target.type) {
        throw new Error("output requires a valid target (file|stream|env|resolver)");
      }
      const materializedContent = materializeDisplayValue(descriptorSource ?? content, void 0, descriptorSource ?? content, content);
      content = materializedContent.text;
      if (materializedContent.descriptor) {
        env.recordSecurityDescriptor(materializedContent.descriptor);
      }
      switch (String(target.type)) {
        case "file": {
          const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
          const path10 = await import('path');
          let resolvedPath = "";
          if (Array.isArray(target.path)) {
            const descriptors = [];
            resolvedPath = await interpolate2(target.path, env, void 0, {
              collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
                if (descriptor) {
                  descriptors.push(descriptor);
                }
              }, "collectSecurityDescriptor")
            });
            recordInterpolatedDescriptors(env, descriptors);
          } else if (typeof target.path === "string") {
            resolvedPath = target.path;
          } else if (target.values) {
            const descriptors = [];
            resolvedPath = await interpolate2(target.values, env, void 0, {
              collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
                if (descriptor) {
                  descriptors.push(descriptor);
                }
              }, "collectSecurityDescriptor")
            });
            recordInterpolatedDescriptors(env, descriptors);
          }
          if (!resolvedPath) {
            throw new Error("output file target requires a non-empty path");
          }
          if (resolvedPath.startsWith("@base/")) {
            const projectRoot = env.getProjectRoot ? env.getProjectRoot() : "/";
            resolvedPath = path10.join(projectRoot, resolvedPath.substring(6));
          } else if (resolvedPath.startsWith("@root/")) {
            const projectRoot = env.getProjectRoot ? env.getProjectRoot() : "/";
            resolvedPath = path10.join(projectRoot, resolvedPath.substring(6));
          }
          if (!path10.isAbsolute(resolvedPath)) {
            const base = env.getBasePath ? env.getBasePath() : "/";
            resolvedPath = path10.resolve(base, resolvedPath);
          }
          if (process.env.MLLD_DEBUG === "true") {
            console.error("[builtin-effects] output:file \u2192", resolvedPath);
          }
          const fileSystem = env.fileSystem;
          if (!fileSystem || typeof fileSystem.writeFile !== "function") {
            throw new Error("File system not available for pipeline output");
          }
          const dir = path10.dirname(resolvedPath);
          try {
            await fileSystem.mkdir(dir, {
              recursive: true
            });
          } catch {
          }
          await fileSystem.writeFile(resolvedPath, content);
          env.emitEffect("file", content, {
            path: resolvedPath
          });
          return {
            value: payloadVariable ?? materializedContent.text,
            env
          };
        }
        case "stream": {
          const stream = target.stream === "stderr" ? "stderr" : "stdout";
          const payload = content.endsWith("\n") ? content : content + "\n";
          env.emitEffect(stream, payload);
          return {
            value: payloadVariable ?? materializedContent.text,
            env
          };
        }
        case "env": {
          let varName = "MLLD_OUTPUT";
          if (target.varname) {
            varName = target.varname;
          } else {
            const src = effect.args && effect.args.length > 0 ? effect.args[0] : null;
            const id = src && typeof src === "object" && Array.isArray(src.identifier) && src.identifier[0]?.identifier ? src.identifier[0].identifier : void 0;
            if (id) varName = `MLLD_${String(id).toUpperCase()}`;
          }
          process.env[varName] = content;
          return {
            value: payloadVariable ?? materializedContent.text,
            env
          };
        }
        case "resolver": {
          throw new Error("resolver targets not supported yet in pipeline output");
        }
        default:
          throw new Error(`Unknown output target type: ${String(target.type)}`);
      }
    }
    case "append":
    case "APPEND": {
      const args = effect.args ?? [];
      const hasExplicitSource = Boolean(effect.meta?.hasExplicitSource);
      const targetArgIndex = hasExplicitSource ? 1 : 0;
      const target = args[targetArgIndex];
      if (!target || typeof target !== "object" || target.type !== "file") {
        throw new Error("append requires a file target");
      }
      const materializedPayload = materializeDisplayValue(descriptorSource ?? payloadText, void 0, descriptorSource ?? payloadText, payloadText);
      const finalPayload = materializedPayload.text;
      if (materializedPayload.descriptor) {
        env.recordSecurityDescriptor(materializedPayload.descriptor);
      }
      await appendContentToFile(target, finalPayload, env, {
        directiveKind: "append"
      });
      return {
        value: payloadVariable ?? finalPayload,
        env
      };
    }
    default:
      throw new Error(`Unsupported builtin effect in pipeline: @${name}`);
  }
}
__name(executeEffect, "executeEffect");

// interpreter/eval/pipeline/rate-limit-retry.ts
var _RateLimitRetry = class _RateLimitRetry {
  constructor(maxAttempts = 5, baseDelay = 500) {
    __publicField(this, "maxAttempts");
    __publicField(this, "baseDelay");
    __publicField(this, "attempt", 0);
    this.maxAttempts = maxAttempts;
    this.baseDelay = baseDelay;
  }
  async wait() {
    if (this.attempt >= this.maxAttempts) return false;
    const delay = this.baseDelay * 2 ** this.attempt;
    this.attempt++;
    await new Promise((res) => setTimeout(res, delay));
    return true;
  }
  reset() {
    this.attempt = 0;
  }
};
__name(_RateLimitRetry, "RateLimitRetry");
var RateLimitRetry = _RateLimitRetry;
function isRateLimitError(err) {
  if (!err) return false;
  const msg = typeof err === "string" ? err : err.message || "";
  return /rate limit/i.test(msg) || err.status === 429;
}
__name(isRateLimitError, "isRateLimitError");

// interpreter/utils/parallel.ts
function getParallelLimit() {
  const raw = process.env.MLLD_PARALLEL_LIMIT;
  const n = raw !== void 0 ? parseInt(String(raw), 10) : NaN;
  if (!Number.isFinite(n) || n < 1) return 4;
  return n;
}
__name(getParallelLimit, "getParallelLimit");
async function runWithConcurrency(items, limit, run, opts = {}) {
  const count = items.length;
  if (count === 0) return [];
  const cap = Math.max(1, Math.min(limit || 1, count));
  const ordered = opts.ordered !== false;
  const paceMs = opts.paceMs && opts.paceMs > 0 ? opts.paceMs : 0;
  const results = ordered ? new Array(count) : [];
  let index = 0;
  let pacingChain = Promise.resolve();
  const nextIndex = /* @__PURE__ */ __name(async () => {
    if (paceMs > 0) {
      const prev = pacingChain;
      let release;
      pacingChain = new Promise((res) => {
        release = res;
      });
      await prev;
      setTimeout(release, paceMs);
    }
    if (index >= count) return -1;
    return index++;
  }, "nextIndex");
  const worker = /* @__PURE__ */ __name(async () => {
    while (true) {
      const i = await nextIndex();
      if (i < 0) break;
      const item = items[i];
      const r = await run(item, i);
      if (ordered) {
        results[i] = r;
      } else {
        results.push(r);
      }
    }
  }, "worker");
  const workers = Array.from({
    length: cap
  }, () => worker());
  await Promise.all(workers);
  return results;
}
__name(runWithConcurrency, "runWithConcurrency");

// interpreter/utils/evaluator-result.ts
function createEvaluatorResult(value, descriptor) {
  return descriptor ? {
    value,
    descriptor
  } : {
    value
  };
}
__name(createEvaluatorResult, "createEvaluatorResult");
function mergeEvaluatorDescriptors(...results) {
  const descriptors = results.map((result) => result?.descriptor).filter((descriptor) => Boolean(descriptor));
  if (descriptors.length === 0) {
    return void 0;
  }
  return mergeDescriptors(...descriptors);
}
__name(mergeEvaluatorDescriptors, "mergeEvaluatorDescriptors");

// interpreter/eval/helpers/parallel-exec.ts
function toPipelineCommand(node) {
  const commandRef = node.commandRef || {};
  const identifier = Array.isArray(commandRef.identifier) ? commandRef.identifier : commandRef.identifier ? [
    commandRef.identifier
  ] : [];
  const rawIdentifier = commandRef.name || (Array.isArray(commandRef.identifier) ? commandRef.identifier.map((id) => id.identifier || id.content || "").find(Boolean) : commandRef.identifier) || "unknown";
  const rawArgs = (commandRef.args || []).map((arg) => {
    if (arg && typeof arg === "object" && "content" in arg) return arg.content;
    return typeof arg === "string" ? arg : "";
  });
  const command = {
    identifier,
    args: commandRef.args || [],
    fields: commandRef.fields || [],
    rawIdentifier,
    rawArgs,
    meta: {}
  };
  if (node.withClause) {
    command.withClause = node.withClause;
    command.meta = {
      ...command.meta || {},
      withClause: node.withClause
    };
    if (node.withClause.stream !== void 0) {
      command.stream = node.withClause.stream;
    }
  }
  return command;
}
__name(toPipelineCommand, "toPipelineCommand");
async function executeParallelExecInvocations(left, right, env) {
  const stage = [
    toPipelineCommand(left),
    toPipelineCommand(right)
  ];
  const pipeline = [
    stage
  ];
  const executor = new PipelineExecutor(pipeline, env);
  const executionResult = await executor.execute("", {
    returnStructured: true
  });
  const descriptor = extractSecurityDescriptor(executionResult, {
    recursive: true,
    mergeArrayElements: true
  });
  return {
    value: executionResult,
    descriptor
  };
}
__name(executeParallelExecInvocations, "executeParallelExecInvocations");

// interpreter/eval/expressions.ts
async function evaluateUnifiedExpression(node, env) {
  try {
    switch (node.type) {
      case "BinaryExpression":
        return await evaluateBinaryExpression(node, env);
      case "UnaryExpression":
        return await evaluateUnaryExpression(node, env);
      case "TernaryExpression":
        return await evaluateTernaryExpression(node, env);
      case "ArrayFilterExpression":
        return await evaluateArrayFilterExpression(node, env);
      case "ArraySliceExpression":
        return await evaluateArraySliceExpression(node, env);
      case "Literal":
        if (node.valueType === "none") {
          throw new Error('The "none" keyword can only be used as a condition in /when directives');
        }
        return createEvaluatorResult(node.value);
      case "VariableReference":
        try {
          const varResult = await evaluate2(node, env);
          return createEvaluatorResult(varResult.value);
        } catch (error) {
          if (error instanceof Error && error.message.includes("Variable not found")) {
            return createEvaluatorResult(void 0);
          }
          throw error;
        }
      case "ExecReference":
        const execResult = await evaluate2(node, env);
        return createEvaluatorResult(execResult.value);
      case "Text":
        return createEvaluatorResult(node.content);
      default:
        const result = await evaluate2(node, env);
        return createEvaluatorResult(result.value);
    }
  } catch (error) {
    throw new MlldDirectiveError(`Expression evaluation failed: ${error instanceof Error ? error.message : String(error)}`, "expression", {
      location: node?.location,
      cause: error,
      context: {
        nodeType: node?.type,
        operator: node?.operator
      },
      env
    });
  }
}
__name(evaluateUnifiedExpression, "evaluateUnifiedExpression");
async function evaluateBinaryExpression(node, env) {
  let { operator } = node;
  if (Array.isArray(operator)) {
    operator = operator[0];
  }
  const isExecParallel = operator === "||" && node.left?.type === "ExecInvocation" && node.right?.type === "ExecInvocation";
  if (isExecParallel) {
    const { value, descriptor } = await executeParallelExecInvocations(node.left, node.right, env);
    return createEvaluatorResult(value, descriptor);
  }
  const leftResult = await evaluateUnifiedExpression(node.left, env);
  const leftValue = leftResult.value;
  if (operator === "&&") {
    const leftTruthy = isTruthy2(leftValue);
    if (!leftTruthy) {
      return leftResult;
    }
    const rightResult2 = await evaluateUnifiedExpression(node.right, env);
    return rightResult2;
  }
  if (operator === "||") {
    const leftTruthy = isTruthy2(leftValue);
    if (leftTruthy) {
      return leftResult;
    }
    const rightResult2 = await evaluateUnifiedExpression(node.right, env);
    return rightResult2;
  }
  if (operator === "??") {
    const isNullish = leftValue === null || leftValue === void 0;
    if (!isNullish) {
      return leftResult;
    }
    return await evaluateUnifiedExpression(node.right, env);
  }
  const rightResult = await evaluateUnifiedExpression(node.right, env);
  const rightValue = rightResult.value;
  const mergedDescriptor = mergeEvaluatorDescriptors(leftResult, rightResult);
  switch (operator) {
    case "==":
      const equal = isEqual(leftValue, rightValue);
      return createEvaluatorResult(equal, mergedDescriptor);
    case "!=":
      return createEvaluatorResult(!isEqual(leftValue, rightValue), mergedDescriptor);
    case "~=":
      const regex = new RegExp(String(rightValue));
      return createEvaluatorResult(regex.test(String(leftValue)), mergedDescriptor);
    case "<":
      const leftNum = toNumber(leftValue);
      const rightNum = toNumber(rightValue);
      const ltResult = leftNum < rightNum;
      return createEvaluatorResult(ltResult, mergedDescriptor);
    case ">":
      return createEvaluatorResult(toNumber(leftValue) > toNumber(rightValue), mergedDescriptor);
    case "<=":
      return createEvaluatorResult(toNumber(leftValue) <= toNumber(rightValue), mergedDescriptor);
    case ">=":
      return createEvaluatorResult(toNumber(leftValue) >= toNumber(rightValue), mergedDescriptor);
    case "+":
      return createEvaluatorResult(toNumber(leftValue) + toNumber(rightValue), mergedDescriptor);
    case "-":
      return createEvaluatorResult(toNumber(leftValue) - toNumber(rightValue), mergedDescriptor);
    case "*":
      return createEvaluatorResult(toNumber(leftValue) * toNumber(rightValue), mergedDescriptor);
    case "/":
      return createEvaluatorResult(toNumber(leftValue) / toNumber(rightValue), mergedDescriptor);
    case "%":
      return createEvaluatorResult(toNumber(leftValue) % toNumber(rightValue), mergedDescriptor);
    default:
      throw new Error(`Unknown binary operator: ${operator}`);
  }
}
__name(evaluateBinaryExpression, "evaluateBinaryExpression");
async function evaluateUnaryExpression(node, env) {
  const operandResult = await evaluateUnifiedExpression(node.operand, env);
  const operandValue = operandResult.value;
  switch (node.operator) {
    case "!":
      return createEvaluatorResult(!isTruthy2(operandValue), operandResult.descriptor);
    case "-":
      return createEvaluatorResult(-toNumber(operandValue), operandResult.descriptor);
    case "+":
      return createEvaluatorResult(+toNumber(operandValue), operandResult.descriptor);
    default:
      throw new Error(`Unknown unary operator: ${node.operator}`);
  }
}
__name(evaluateUnaryExpression, "evaluateUnaryExpression");
async function evaluateTernaryExpression(node, env) {
  const conditionResult = await evaluateUnifiedExpression(node.condition, env);
  const conditionValue = conditionResult.value;
  return isTruthy2(conditionValue) ? await evaluateUnifiedExpression(node.trueBranch, env) : await evaluateUnifiedExpression(node.falseBranch, env);
}
__name(evaluateTernaryExpression, "evaluateTernaryExpression");
async function evaluateArrayFilterExpression(node, env) {
  const arrayResult = await evaluateUnifiedExpression(node.array, env);
  const array = arrayResult.value;
  if (!Array.isArray(array)) {
    throw new Error(`Cannot filter non-array value: ${typeof array}`);
  }
  const results = [];
  for (const item of array) {
    const itemEnv = env.withVariable("$", item);
    const passes = await evaluateUnifiedExpression(node.filter, itemEnv);
    if (passes.value) {
      results.push(item);
    }
  }
  return createEvaluatorResult(results, arrayResult.descriptor);
}
__name(evaluateArrayFilterExpression, "evaluateArrayFilterExpression");
async function evaluateArraySliceExpression(node, env) {
  const arrayResult = await evaluateUnifiedExpression(node.array, env);
  const array = arrayResult.value;
  if (!Array.isArray(array)) {
    throw new Error(`Cannot slice non-array value: ${typeof array}`);
  }
  const start = node.start || 0;
  const end = node.end !== void 0 ? node.end : array.length;
  return createEvaluatorResult(array.slice(start, end), arrayResult.descriptor);
}
__name(evaluateArraySliceExpression, "evaluateArraySliceExpression");
function isUnifiedExpressionNode(node) {
  return node && [
    "BinaryExpression",
    "UnaryExpression",
    "TernaryExpression",
    "ArrayFilterExpression",
    "ArraySliceExpression",
    "Literal"
  ].includes(node.type);
}
__name(isUnifiedExpressionNode, "isUnifiedExpressionNode");
async function evaluateArrayFilter(array, filter, env) {
  const results = [];
  for (const item of array) {
    const itemEnv = env.withVariable("$", item);
    const passes = await evaluateUnifiedExpression(filter, itemEnv);
    if (passes.value) results.push(item);
  }
  return results;
}
__name(evaluateArrayFilter, "evaluateArrayFilter");

// interpreter/eval/while.ts
function sleep(ms) {
  return new Promise((resolve4) => setTimeout(resolve4, ms));
}
__name(sleep, "sleep");
function normalizeState(value) {
  if (isStructuredValue(value)) {
    return value;
  }
  const textValue = typeof value === "string" ? value : JSON.stringify(value ?? "");
  const kind = Array.isArray(value) ? "array" : typeof value === "object" && value !== null ? "object" : "text";
  return wrapStructured(value, kind, textValue);
}
__name(normalizeState, "normalizeState");
async function setWhileInputVariable(env, value) {
  const source = {
    directive: "var",
    syntax: "template",
    hasInterpolation: false,
    isMultiLine: false
  };
  const wrapped = isStructuredValue(value) ? value : wrapStructured(value, Array.isArray(value) ? "array" : typeof value === "object" && value !== null ? "object" : "text", typeof value === "string" ? value : void 0);
  const inputVar = createStructuredValueVariable("input", wrapped, source, {
    internal: {
      isSystem: true,
      isPipelineParameter: true
    }
  });
  env.setVariable("input", inputVar);
}
__name(setWhileInputVariable, "setWhileInputVariable");
async function resolveControlValue(result, iterEnv, currentState) {
  const unwrapped = isStructuredValue(result) ? asData(result) : result;
  const controlPayload = unwrapped && typeof unwrapped === "object" && "__whileControl" in unwrapped ? unwrapped : result && typeof result === "object" && "__whileControl" in result ? result : null;
  if (controlPayload) {
    const controlKind = controlPayload.__whileControl === "done" ? "done" : "continue";
    const controlValue = "value" in controlPayload ? controlPayload.value : void 0;
    return {
      kind: controlKind,
      value: controlValue ?? currentState
    };
  }
  if (unwrapped && typeof unwrapped === "object" && "valueType" in unwrapped) {
    if (isDoneLiteral(unwrapped)) {
      const val = unwrapped.value;
      if (Array.isArray(val)) {
        const target = val.length === 1 ? val[0] : val;
        if (target && typeof target === "object" && "type" in target) {
          const evaluated2 = await evaluateUnifiedExpression(target, iterEnv);
          return {
            kind: "done",
            value: evaluated2.value
          };
        }
        const evaluated = await evaluate2(val, iterEnv, {
          isExpression: true
        });
        return {
          kind: "done",
          value: evaluated.value
        };
      }
      return {
        kind: "done",
        value: val === "done" ? currentState : val
      };
    }
    if (isContinueLiteral(unwrapped)) {
      const val = unwrapped.value;
      if (Array.isArray(val)) {
        const target = val.length === 1 ? val[0] : val;
        if (target && typeof target === "object" && "type" in target) {
          const evaluated2 = await evaluateUnifiedExpression(target, iterEnv);
          return {
            kind: "continue",
            value: evaluated2.value
          };
        }
        const evaluated = await evaluate2(val, iterEnv, {
          isExpression: true
        });
        return {
          kind: "continue",
          value: evaluated.value
        };
      }
      return {
        kind: "continue",
        value: val === "continue" ? currentState : val
      };
    }
    if (unwrapped.valueType === "retry") {
      throw new Error("Use 'continue' instead of 'retry' in while processors");
    }
  }
  if (unwrapped === "retry") {
    throw new Error("Use 'continue' instead of 'retry' in while processors");
  }
  if (unwrapped === "done") {
    return {
      kind: "done",
      value: currentState
    };
  }
  if (unwrapped === "continue") {
    return {
      kind: "continue",
      value: currentState
    };
  }
  return {
    kind: "continue",
    value: isStructuredValue(result) ? result : unwrapped
  };
}
__name(resolveControlValue, "resolveControlValue");
async function evaluateWhileStage(stage, input, env, invokeProcessor) {
  const cap = stage.cap;
  const rateMs = stage.rateMs ?? null;
  let state = normalizeState(input);
  for (let iteration = 1; iteration <= cap; iteration++) {
    const whileCtx = {
      iteration,
      limit: cap,
      active: true
    };
    const iterEnv = env.createChild();
    await setWhileInputVariable(iterEnv, state);
    const evalResult = await iterEnv.withExecutionContext("while", whileCtx, async () => {
      if (invokeProcessor) {
        return invokeProcessor(stage.processor, state, iterEnv);
      }
      return evaluate2(stage.processor, iterEnv, {
        isExpression: true
      });
    });
    const value = evalResult && typeof evalResult === "object" && "env" in evalResult ? evalResult.value : evalResult;
    const resultEnv = evalResult && typeof evalResult === "object" && "env" in evalResult ? evalResult.env || iterEnv : iterEnv;
    const control = await resolveControlValue(value, resultEnv || iterEnv, state);
    if (control.kind === "done") {
      return control.value;
    }
    state = normalizeState(control.value);
    if (rateMs && iteration < cap) {
      await sleep(rateMs);
    }
  }
  throw new Error(`While loop reached cap (${cap}) without 'done'. Consider increasing cap or check termination logic.`);
}
__name(evaluateWhileStage, "evaluateWhileStage");

// interpreter/eval/pipeline/executor.ts
var pipelineCounter = 0;
function createPipelineId() {
  pipelineCounter += 1;
  return `pipeline-${pipelineCounter}`;
}
__name(createPipelineId, "createPipelineId");
function formatParallelStageError(error) {
  if (error instanceof Error) {
    let message = error.message;
    if (message.startsWith("Directive error (")) {
      const prefixEnd = message.indexOf(": ");
      if (prefixEnd >= 0) {
        message = message.slice(prefixEnd + 2);
      }
      const lineIndex = message.indexOf(" at line ");
      if (lineIndex >= 0) {
        message = message.slice(0, lineIndex);
      }
    }
    return message;
  }
  if (typeof error === "string") return error;
  try {
    return JSON.stringify(error);
  } catch {
    return String(error);
  }
}
__name(formatParallelStageError, "formatParallelStageError");
function resetParallelErrorsContext(env, errors) {
  const mxManager = env.getContextManager?.();
  if (!mxManager) return;
  while (mxManager.popGenericContext("parallel")) {
  }
  mxManager.pushGenericContext("parallel", {
    errors,
    timestamp: Date.now()
  });
  mxManager.setLatestErrors(errors);
}
__name(resetParallelErrorsContext, "resetParallelErrorsContext");
var _PipelineExecutor = class _PipelineExecutor {
  constructor(pipeline, env, format, isRetryable = false, sourceFunction, hasSyntheticSource = false, parallelCap, delayMs, streamingManager) {
    __publicField(this, "stateMachine");
    __publicField(this, "env");
    __publicField(this, "format");
    __publicField(this, "pipeline");
    __publicField(this, "isRetryable");
    __publicField(this, "sourceFunction");
    __publicField(this, "hasSyntheticSource");
    __publicField(this, "parallelCap");
    __publicField(this, "delayMs");
    __publicField(this, "sourceExecutedOnce", false);
    __publicField(this, "initialInputText", "");
    __publicField(this, "allRetryHistory", /* @__PURE__ */ new Map());
    __publicField(this, "rateLimiter", new RateLimitRetry());
    __publicField(this, "structuredOutputs", /* @__PURE__ */ new Map());
    __publicField(this, "initialOutput");
    __publicField(this, "finalOutput");
    __publicField(this, "lastStageIndex", -1);
    __publicField(this, "debugStructured", process.env.MLLD_DEBUG_STRUCTURED === "true");
    __publicField(this, "stageHookNodeCounter", 0);
    __publicField(this, "streamingOptions");
    __publicField(this, "pipelineId", createPipelineId());
    __publicField(this, "bus");
    __publicField(this, "streamingManager");
    __publicField(this, "streamingEnabled");
    if (process.env.MLLD_DEBUG === "true") {
      console.error("[PipelineExecutor] Constructor:", {
        pipelineLength: pipeline.length,
        pipelineStages: pipeline.map((p) => Array.isArray(p) ? "[parallel]" : p.rawIdentifier || "unknown"),
        isRetryable,
        hasSourceFunction: !!sourceFunction,
        hasSyntheticSource
      });
    }
    this.stateMachine = new PipelineStateMachine(pipeline.length, isRetryable, Boolean(sourceFunction));
    this.pipeline = pipeline;
    this.env = env;
    this.format = format;
    this.isRetryable = isRetryable;
    this.sourceFunction = sourceFunction;
    this.hasSyntheticSource = hasSyntheticSource;
    this.parallelCap = parallelCap;
    this.delayMs = delayMs;
    this.streamingOptions = env.getStreamingOptions();
    this.streamingEnabled = this.streamingOptions.enabled !== false && this.pipelineHasStreamingStage(pipeline);
    this.streamingManager = streamingManager ?? env.getStreamingManager();
    this.bus = this.streamingManager.getBus();
    if (this.streamingEnabled && !this.streamingOptions.skipDefaultSinks) {
      this.streamingManager.configure({
        env: this.env,
        streamingEnabled: true,
        streamingOptions: this.streamingOptions
      });
    }
  }
  buildCommandExecutionContext(stageIndex, stageContext, parallelIndex, directiveType, workingDirectory) {
    const stageStreaming = this.isStageStreaming(this.pipeline[stageIndex]);
    return {
      directiveType: directiveType || "run",
      streamingEnabled: this.streamingEnabled && stageStreaming,
      pipelineId: this.pipelineId,
      stageIndex,
      parallelIndex,
      streamId: stageContext.contextId ?? createPipelineId(),
      workingDirectory
    };
  }
  emitStream(event) {
    if (!this.streamingEnabled) {
      return;
    }
    this.bus.emit({
      ...event,
      pipelineId: event.pipelineId || this.pipelineId,
      timestamp: event.timestamp ?? Date.now()
    });
  }
  isStageStreaming(stage) {
    if (Array.isArray(stage)) {
      return stage.some((st) => this.isStageStreaming(st));
    }
    const candidate = stage;
    return Boolean(candidate?.stream || candidate?.withClause?.stream || candidate?.meta?.withClause?.stream);
  }
  pipelineHasStreamingStage(pipeline) {
    return pipeline.some((stage) => this.isStageStreaming(stage));
  }
  async execute(initialInput, options) {
    this.env.resetPipelineGuardHistory();
    try {
      const initialWrapper = isStructuredValue(initialInput) ? cloneStructuredValue3(initialInput) : wrapStructured(initialInput, "text", typeof initialInput === "string" ? initialInput : safeJSONStringify(initialInput));
      this.applySourceDescriptor(initialWrapper, initialInput);
      this.initialInputText = initialWrapper.text;
      this.structuredOutputs.clear();
      this.initialOutput = initialWrapper;
      this.finalOutput = this.initialOutput;
      this.lastStageIndex = -1;
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[PipelineExecutor] Pipeline start:", {
          stages: this.pipeline.map((p) => Array.isArray(p) ? "[parallel]" : p.rawIdentifier),
          hasSyntheticSource: this.hasSyntheticSource,
          isRetryable: this.isRetryable
        });
      }
      this.emitStream({
        type: "PIPELINE_START",
        source: "pipeline"
      });
      let nextStep = this.stateMachine.transition({
        type: "START",
        input: this.initialInputText,
        structuredInput: this.initialOutput ? cloneStructuredValue3(this.initialOutput) : void 0
      });
      let iteration = 0;
      while (nextStep.type === "EXECUTE_STAGE") {
        iteration++;
        if (process.env.MLLD_DEBUG === "true") {
          console.error(`[PipelineExecutor] Iteration ${iteration}:`, {
            stage: nextStep.stage,
            stageId: this.pipeline[nextStep.stage]?.rawIdentifier,
            contextAttempt: nextStep.context.contextAttempt
          });
        }
        this.clearStageOutputsFrom(nextStep.stage);
        if (process.env.MLLD_DEBUG === "true") {
          console.error("[PipelineExecutor] Execute stage:", {
            stage: nextStep.stage,
            contextId: nextStep.context.contextId,
            contextAttempt: nextStep.context.contextAttempt,
            inputLength: nextStep.input?.length,
            commandId: this.pipeline[nextStep.stage]?.rawIdentifier
          });
        }
        this.emitStream({
          type: "STAGE_START",
          stageIndex: nextStep.stage,
          command: this.pipeline[nextStep.stage],
          contextId: nextStep.context.contextId,
          attempt: nextStep.context.contextAttempt
        });
        const stageStartTime = Date.now();
        const stageEntry = this.pipeline[nextStep.stage];
        const result = Array.isArray(stageEntry) ? await this.executeParallelStage(nextStep.stage, stageEntry, nextStep.input, nextStep.context) : await this.executeSingleStage(nextStep.stage, stageEntry, nextStep.input, nextStep.context);
        if (process.env.MLLD_DEBUG === "true") {
          console.error("[PipelineExecutor] Stage result:", {
            resultType: result.type,
            isRetry: result.type === "retry"
          });
        }
        if (result.type === "success") {
          const stageEntry2 = this.pipeline[nextStep.stage];
          this.emitStream({
            type: "STAGE_SUCCESS",
            stageIndex: nextStep.stage,
            durationMs: Date.now() - stageStartTime
          });
        } else if (result.type === "error") {
          this.emitStream({
            type: "STAGE_FAILURE",
            stageIndex: nextStep.stage,
            error: result.error
          });
        }
        nextStep = this.stateMachine.transition({
          type: "STAGE_RESULT",
          result
        });
        this.allRetryHistory = this.stateMachine.getAllRetryHistory();
        if (process.env.MLLD_DEBUG === "true") {
          console.error("[PipelineExecutor] Next step:", {
            type: nextStep.type,
            nextStage: nextStep.type === "EXECUTE_STAGE" ? nextStep.stage : void 0
          });
        }
        if (iteration > 100) {
          throw new Error("Pipeline exceeded 100 iterations");
        }
      }
      switch (nextStep.type) {
        case "COMPLETE":
          this.emitStream({
            type: "PIPELINE_COMPLETE"
          });
          if (options?.returnStructured) {
            return this.getFinalOutput();
          }
          return nextStep.output;
        case "ERROR":
          this.emitStream({
            type: "PIPELINE_ABORT",
            reason: nextStep.error.message
          });
          throw new MlldCommandExecutionError(`Pipeline failed at stage ${nextStep.stage + 1}: ${nextStep.error.message}`, void 0, {
            command: this.pipeline[nextStep.stage]?.rawIdentifier || "unknown",
            exitCode: 1,
            duration: 0,
            workingDirectory: this.env.getExecutionDirectory()
          });
        case "ABORT":
          this.emitStream({
            type: "PIPELINE_ABORT",
            reason: nextStep.reason || "aborted"
          });
          throw new MlldCommandExecutionError(`Pipeline aborted: ${nextStep.reason}`, void 0, {
            command: "pipeline",
            exitCode: 1,
            duration: 0,
            workingDirectory: this.env.getExecutionDirectory()
          });
        default:
          throw new Error("Pipeline ended in unexpected state");
      }
    } finally {
      if (this.streamingEnabled && !this.streamingOptions.skipDefaultSinks) {
        try {
          this.streamingManager.teardown();
        } catch {
        }
      }
    }
  }
  /**
  * Execute a single stage
  */
  /**
  * Execute a single pipeline stage with the constructed stage environment.
  * GOTCHA: Inline effects are run after successful stage execution and re-run on retries.
  */
  async executeSingleStage(stageIndex, command, input, context2) {
    let stageEnv;
    let mxManager;
    let pipelineSnapshot;
    let stageDescriptor;
    let parentPipelineContextPushed = false;
    try {
      const structuredInput = this.getStageOutput(stageIndex - 1, input);
      this.logStructuredStage("input", command.rawIdentifier, stageIndex, structuredInput);
      if (process.env.MLLD_DEBUG === "true") {
        try {
          const prevOut = this.structuredOutputs.get(stageIndex - 1);
          const currOut = this.structuredOutputs.get(stageIndex);
          console.error("[PipelineExecutor] Stage input snapshot", {
            stageIndex,
            command: command.rawIdentifier,
            input,
            structuredInput: this.debugNormalize(structuredInput),
            previousStageOutput: this.debugNormalize(prevOut),
            cachedCurrentOutput: this.debugNormalize(currOut)
          });
        } catch {
        }
      }
      parentPipelineContextPushed = true;
      stageEnv = await createStageEnvironment(command, input, structuredInput, context2, this.env, this.format, this.stateMachine.getEvents(), this.hasSyntheticSource, this.allRetryHistory, {
        getStageOutput: /* @__PURE__ */ __name((stage, fallback) => this.getStageOutput(stage, fallback), "getStageOutput")
      }, {
        capturePipelineContext: /* @__PURE__ */ __name((snapshot) => {
          pipelineSnapshot = snapshot;
        }, "capturePipelineContext"),
        skipSetPipelineContext: false,
        sourceRetryable: this.isRetryable
      });
      if (!pipelineSnapshot) {
        throw new Error("Pipeline context snapshot unavailable for pipeline stage");
      }
      stageDescriptor = this.buildStageDescriptor(command, stageIndex, context2, structuredInput);
      mxManager = stageEnv.getContextManager();
      const stageOpContext = this.createPipelineOperationContext(command, stageIndex, context2);
      const stageHookNode = this.createStageHookNode(command);
      const executeStage = /* @__PURE__ */ __name(async () => {
        let stageExecution;
        while (true) {
          try {
            if (command.type === "whileStage") {
              const whileStage = command;
              const whileResult = await evaluateWhileStage(whileStage, structuredInput, stageEnv, async (processor, stateValue, iterEnv) => {
                const processorCommand = this.buildWhileProcessorCommand(processor);
                const normalizedState = this.normalizeWhileInput(stateValue);
                const execution = await this.executeCommand(processorCommand, normalizedState.text, normalizedState.structured, iterEnv, stageOpContext, stageHookNode, stageIndex, context2);
                return {
                  value: execution.result,
                  env: iterEnv
                };
              });
              stageExecution = {
                result: whileResult
              };
              this.rateLimiter.reset();
              break;
            }
            if (command.type === "inlineValue") {
              stageExecution = await this.executeInlineValueStage(command, structuredInput, stageEnv);
            } else if (command.type === "inlineCommand") {
              stageExecution = await this.executeInlineCommandStage(command, structuredInput, stageEnv, stageOpContext, stageHookNode, stageIndex, context2);
            } else {
              stageExecution = await this.executeCommand(command, input, structuredInput, stageEnv, stageOpContext, stageHookNode, stageIndex, context2);
            }
            const output2 = stageExecution.result;
            this.rateLimiter.reset();
            break;
          } catch (err) {
            if (err instanceof GuardError) {
              if (err.decision === "retry") {
                return {
                  type: "retry",
                  reason: err.message,
                  hint: err.retryHint
                };
              }
              throw err;
            }
            if (isRateLimitError(err)) {
              if (process.env.MLLD_DEBUG === "true") {
                logger.warn("Rate limit detected, retrying with backoff");
              }
              const retry = await this.rateLimiter.wait();
              if (retry) continue;
            }
            throw err;
          }
        }
        if (!stageExecution) {
          throw new Error("Pipeline command did not produce a result");
        }
        const output = stageExecution.result;
        if (this.isRetrySignal(output)) {
          if (process.env.MLLD_DEBUG === "true") {
            console.error("[PipelineExecutor] Retry detected at stage", context2.stage);
          }
          const from = this.parseRetryScope(output);
          const hint = this.parseRetryHint(output);
          return {
            type: "retry",
            reason: hint || "Stage requested retry",
            from,
            hint
          };
        }
        let normalized = this.normalizeOutput(output);
        if (this.debugStructured) {
          console.error("[PipelineExecutor][pre-output]", {
            stage: command.rawIdentifier,
            stageIndex
          });
        }
        this.logStructuredStage("output", command.rawIdentifier, stageIndex, normalized);
        if (this.debugStructured) {
          console.error("[PipelineExecutor][post-output]", {
            stage: command.rawIdentifier,
            stageIndex
          });
        }
        normalized = this.finalizeStageOutput(normalized, structuredInput, output, stageDescriptor, stageExecution?.labelDescriptor);
        if (process.env.MLLD_DEBUG === "true") {
          try {
            console.error("[PipelineExecutor] Stage output snapshot", {
              stageIndex,
              command: command.rawIdentifier,
              normalized: this.debugNormalize(normalized)
            });
          } catch {
          }
        }
        if (this.debugStructured) {
          try {
            console.error("[PipelineExecutor][finalized-output]", {
              stage: command.rawIdentifier,
              stageIndex,
              labels: normalized?.mx?.labels ?? null,
              metadataLabels: normalized?.metadata?.security?.labels ?? null
            });
          } catch {
          }
        }
        this.structuredOutputs.set(stageIndex, normalized);
        this.finalOutput = normalized;
        this.lastStageIndex = stageIndex;
        const normalizedText = normalized.text ?? "";
        if (!normalizedText || normalizedText.trim() === "") {
          await this.runInlineEffects(command, normalized, stageEnv);
          return {
            type: "success",
            output: normalizedText,
            structuredOutput: normalized
          };
        }
        try {
          const pmx = this.env.getPipelineContext?.();
          if (pmx) {
            this.env.updatePipelineContext({
              ...pmx,
              hint: null
            });
          }
        } catch {
        }
        await this.runInlineEffects(command, normalized, stageEnv);
        return {
          type: "success",
          output: normalizedText,
          structuredOutput: normalized
        };
      }, "executeStage");
      const runWithinPipeline = /* @__PURE__ */ __name(async () => {
        if (mxManager) {
          return await mxManager.withOperation(stageOpContext, executeStage);
        }
        return await executeStage();
      }, "runWithinPipeline");
      return await this.env.withPipeContext(pipelineSnapshot, runWithinPipeline);
    } catch (error) {
      return {
        type: "error",
        error
      };
    } finally {
      if (parentPipelineContextPushed && this.env.getPipelineContext()) {
        this.env.clearPipelineContext();
      }
    }
  }
  /**
  * Execute a pipeline command
  */
  /**
  * Execute a pipeline command (function or synthetic __source__).
  * CONTEXT: __source__ uses the initial input the first time, and a source function on retries.
  */
  async executeCommand(command, input, structuredInput, stageEnv, operationContext, hookNode, stageIndex, stageContext, parallelIndex) {
    if (command.rawIdentifier === "__source__") {
      const firstTime = !this.sourceExecutedOnce;
      this.sourceExecutedOnce = true;
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[PipelineExecutor] Executing __source__ stage:", {
          firstTime,
          hasSourceFunction: !!this.sourceFunction,
          isRetryable: this.isRetryable
        });
      }
      if (firstTime) {
        const sourceOutput = this.initialOutput ? cloneStructuredValue3(this.initialOutput) : wrapStructured(this.initialInputText, "text", this.initialInputText);
        return {
          result: sourceOutput
        };
      }
      if (!this.sourceFunction) {
        throw new Error("Cannot retry stage 0: input is not a function. Make the source a function to enable retries.");
      }
      const fresh = await this.sourceFunction();
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[PipelineExecutor] Source function returned fresh input:", fresh);
      }
      const freshWrapper = isStructuredValue(fresh) ? cloneStructuredValue3(fresh) : wrapStructured(fresh, "text", typeof fresh === "string" ? fresh : safeJSONStringify(fresh));
      this.applySourceDescriptor(freshWrapper, fresh);
      this.initialOutput = freshWrapper;
      this.finalOutput = freshWrapper;
      this.initialInputText = freshWrapper.text;
      return {
        result: freshWrapper
      };
    }
    if (command.rawIdentifier === "__identity__") {
      return {
        result: input
      };
    }
    const commandVar = await this.resolveCommandReference(command, stageEnv);
    if (!commandVar) {
      throw new Error(`Pipeline command ${command.rawIdentifier} not found`);
    }
    let args = await this.processArguments(command.args || [], stageEnv);
    const { AutoUnwrapManager: AutoUnwrapManager2 } = await import('./auto-unwrap-manager-K5BHSH47.mjs');
    if (args.length === 0) {
      args = await AutoUnwrapManager2.executeWithPreservation(async () => {
        return await this.bindParametersAutomatically(commandVar, input, structuredInput);
      });
    }
    const result = await AutoUnwrapManager2.executeWithPreservation(async () => {
      return await this.executeCommandVariable(commandVar, args, stageEnv, input, structuredInput, {
        hookNode,
        operationContext,
        stageInputs: [
          structuredInput
        ],
        executionContext: stageContext && typeof stageIndex === "number" ? this.buildCommandExecutionContext(stageIndex, stageContext, parallelIndex, command.rawIdentifier) : void 0
      });
    });
    const labelDescriptor = this.buildCommandLabelDescriptor(command, commandVar);
    return {
      result,
      labelDescriptor
    };
  }
  async executeInlineCommandStage(stage, structuredInput, stageEnv, operationContext, hookNode, stageIndex, stageContext, parallelIndex) {
    const mxManager = stageEnv.getContextManager();
    const runInline = /* @__PURE__ */ __name(async () => {
      const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
      const descriptors = [];
      const workingDirectory = await resolveWorkingDirectory(stage.workingDir, stageEnv, {
        sourceLocation: stage.location,
        directiveType: "run"
      });
      const commandText = await interpolate2(stage.command, stageEnv, InterpolationContext.ShellCommand, {
        collectSecurityDescriptor: /* @__PURE__ */ __name((d) => {
          if (d) descriptors.push(d);
        }, "collectSecurityDescriptor")
      });
      const stdinInput = structuredInput?.text ?? "";
      const result = await stageEnv.executeCommand(commandText, {
        input: stdinInput,
        ...workingDirectory ? {
          workingDirectory
        } : {}
      }, this.buildCommandExecutionContext(stageIndex, stageContext, parallelIndex, void 0, workingDirectory));
      const { processCommandOutput } = await import('./json-auto-parser-DOBRNARE.mjs');
      const normalizedResult = processCommandOutput(result);
      const labelDescriptor = descriptors.length > 1 ? stageEnv.mergeSecurityDescriptors(...descriptors) : descriptors[0];
      return {
        result: normalizedResult,
        labelDescriptor
      };
    }, "runInline");
    if (mxManager && operationContext) {
      return await mxManager.withOperation(operationContext, runInline);
    }
    return await runInline();
  }
  async executeInlineValueStage(stage, stageInput, stageEnv) {
    const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
    const value = await evaluateDataValue2(stage.value, stageEnv);
    const text = safeJSONStringify(value);
    const wrapped = wrapStructured(value, "object", text);
    const descriptor = extractSecurityDescriptor(value, {
      recursive: true,
      mergeArrayElements: true
    });
    if (descriptor) {
      applySecurityDescriptorToStructuredValue(wrapped, descriptor);
      setExpressionProvenance(wrapped, descriptor);
    }
    const mergedDescriptor = descriptor && stageEnv ? stageEnv.mergeSecurityDescriptors(descriptor) : descriptor;
    return {
      result: this.finalizeStageOutput(wrapped, stageInput, value, mergedDescriptor),
      labelDescriptor: mergedDescriptor
    };
  }
  normalizeWhileInput(value) {
    if (isStructuredValue(value)) {
      const textValue2 = value.text ?? safeJSONStringify(asData(value));
      return {
        structured: value,
        text: textValue2
      };
    }
    const textValue = typeof value === "string" ? value : safeJSONStringify(value);
    const kind = Array.isArray(value) ? "array" : typeof value === "object" && value !== null ? "object" : "text";
    const structured = wrapStructured(value, kind, textValue);
    return {
      structured,
      text: textValue
    };
  }
  buildWhileProcessorCommand(processor) {
    if (processor?.type === "ExecInvocation") {
      const ref = processor.commandRef || {};
      const identifier = Array.isArray(ref.identifier) ? ref.identifier : ref.identifier ? [
        ref.identifier
      ] : [];
      const rawIdentifier = ref.name || (Array.isArray(ref.identifier) ? ref.identifier.map((id) => id.identifier || id.content || "").find(Boolean) : ref.identifier) || "while-processor";
      const rawArgs = (ref.args || []).map((arg) => {
        if (arg && typeof arg === "object") {
          if ("content" in arg && typeof arg.content === "string") {
            return arg.content;
          }
          if (arg.identifier) {
            return `@${arg.identifier}`;
          }
        }
        return "";
      });
      const command = {
        identifier,
        args: ref.args || [],
        fields: ref.fields || [],
        rawIdentifier,
        rawArgs,
        meta: {}
      };
      if (processor.withClause && processor.withClause.stream !== void 0) {
        command.stream = processor.withClause.stream;
      }
      return command;
    }
    if (processor?.type === "VariableReferenceWithTail") {
      const variable = processor.variable || processor;
      const rawIdentifier = variable?.identifier || "while-processor";
      return {
        identifier: variable ? [
          variable
        ] : [],
        args: [],
        fields: variable?.fields || [],
        rawIdentifier,
        rawArgs: []
      };
    }
    if (processor?.type === "VariableReference") {
      return {
        identifier: [
          processor
        ],
        args: [],
        fields: processor.fields || [],
        rawIdentifier: processor.identifier || "while-processor",
        rawArgs: []
      };
    }
    const fallbackId = processor && typeof processor === "object" && "identifier" in processor && processor.identifier || processor && typeof processor === "object" && "rawIdentifier" in processor && processor.rawIdentifier || "while-processor";
    return {
      identifier: [],
      args: [],
      fields: [],
      rawIdentifier: fallbackId,
      rawArgs: []
    };
  }
  /**
  * Process and validate command arguments
  */
  async processArguments(args, env) {
    const evaluatedArgs = [];
    for (const arg of args) {
      if (typeof arg === "string" || typeof arg === "number" || typeof arg === "boolean" || arg === null) {
        evaluatedArgs.push(arg);
      } else if (arg && typeof arg === "object") {
        const evaluatedArg = await this.evaluateArgumentNode(arg, env);
        evaluatedArgs.push(evaluatedArg);
      }
    }
    return evaluatedArgs;
  }
  buildCommandLabelDescriptor(command, commandVar) {
    const descriptors = [];
    const inlineLabels = command?.securityLabels;
    if (inlineLabels && inlineLabels.length > 0) {
      descriptors.push(makeSecurityDescriptor({
        labels: inlineLabels
      }));
    }
    const variableLabels = Array.isArray(commandVar?.mx?.labels) ? commandVar.mx.labels : void 0;
    if (variableLabels && variableLabels.length > 0) {
      descriptors.push(makeSecurityDescriptor({
        labels: variableLabels
      }));
    }
    if (descriptors.length === 0) {
      return void 0;
    }
    if (descriptors.length === 1) {
      return descriptors[0];
    }
    return this.env.mergeSecurityDescriptors(...descriptors);
  }
  /**
  * Evaluate a single argument node
  */
  async evaluateArgumentNode(arg, env) {
    if (arg.type === "VariableReference") {
      const variable = env.getVariable(arg.identifier);
      if (!variable) {
        throw new Error(`Variable not found: ${arg.identifier}`);
      }
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      let value2 = await resolveVariable(variable, env, ResolutionContext.PipelineInput);
      if (arg.fields && arg.fields.length > 0) {
        const { accessFields: accessFields2 } = await import('./field-access-MJ6PMBJX.mjs');
        const fieldResult = await accessFields2(value2, arg.fields, {
          preserveContext: false,
          sourceLocation: arg?.location,
          env
        });
        value2 = fieldResult;
      }
      return value2;
    }
    const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
    const value = await interpolate2([
      arg
    ], env);
    try {
      return JSON.parse(value);
    } catch {
      return value;
    }
  }
  /**
  * Smart parameter binding for functions without explicit arguments
  */
  async bindParametersAutomatically(commandVar, input, structuredInput) {
    let paramNames;
    if (commandVar && commandVar.type === "executable" && commandVar.value) {
      paramNames = commandVar.value.paramNames;
    } else if (commandVar && commandVar.paramNames) {
      paramNames = commandVar.paramNames;
    }
    if (!paramNames || paramNames.length === 0) {
      return [];
    }
    const { AutoUnwrapManager: AutoUnwrapManager2 } = await import('./auto-unwrap-manager-K5BHSH47.mjs');
    const unwrappedOutput = AutoUnwrapManager2.unwrap(input);
    if (paramNames.length === 1) {
      if (structuredInput && isStructuredValue(structuredInput)) {
        return [
          structuredInput
        ];
      }
      return [
        {
          type: "Text",
          content: unwrappedOutput
        }
      ];
    }
    try {
      const parsed = JSON.parse(unwrappedOutput);
      if (typeof parsed === "object" && !Array.isArray(parsed)) {
        return paramNames.map((name) => ({
          type: "Text",
          content: parsed[name] !== void 0 ? typeof parsed[name] === "string" ? parsed[name] : JSON.stringify(parsed[name]) : ""
        }));
      }
    } catch {
    }
    return [
      {
        type: "Text",
        content: unwrappedOutput
      }
    ];
  }
  /**
  * Execute a command variable with arguments
  */
  async executeCommandVariable(commandVar, args, env, stdinInput, structuredInput, hookOptions) {
    const { executeCommandVariable } = await import('./command-execution-3VXJHNI2.mjs');
    return await executeCommandVariable(commandVar, args, env, stdinInput, structuredInput, hookOptions);
  }
  /**
  * Resolve a command reference to an executable variable
  */
  async resolveCommandReference(command, env) {
    const { resolveCommandReference } = await import('./command-execution-3VXJHNI2.mjs');
    return await resolveCommandReference(command, env);
  }
  isRetrySignal(output) {
    let isRetry = false;
    if (isStructuredValue(output)) {
      const data = output.data;
      isRetry = output.text === "retry" || typeof data === "string" && data === "retry" || data && typeof data === "object" && data.value === "retry";
    } else {
      isRetry = output === "retry" || output && typeof output === "object" && output.value === "retry";
    }
    if (process.env.MLLD_DEBUG === "true") {
      console.error("[PipelineExecutor] Retry check:", {
        output,
        result: isRetry
      });
    }
    return isRetry;
  }
  parseRetryScope(output) {
    if (output && typeof output === "object" && typeof output.from === "number") {
      return output.from;
    }
    return void 0;
  }
  parseRetryHint(output) {
    if (output && typeof output === "object" && "hint" in output) {
      return output.hint;
    }
    return void 0;
  }
  createPipelineOperationContext(command, stageIndex, stageContext) {
    const labels = command?.securityLabels;
    return {
      type: "pipeline-stage",
      subtype: command.rawIdentifier,
      name: command.rawIdentifier,
      labels,
      metadata: {
        stageIndex: stageIndex + 1,
        totalStages: stageContext.totalStages,
        streaming: this.streamingEnabled
      }
    };
  }
  async executeParallelStage(stageIndex, commands, input, context2) {
    try {
      const errors = [];
      resetParallelErrorsContext(this.env, errors);
      const sharedStructuredInput = this.getStageOutput(stageIndex - 1, input);
      const results = await runWithConcurrency(commands, Math.min(this.parallelCap ?? getParallelLimit(), commands.length), async (cmd, parallelIndex) => {
        const branchInput = cloneStructuredValue3(sharedStructuredInput);
        this.logStructuredStage("input", cmd.rawIdentifier, stageIndex, branchInput, true);
        let pipelineSnapshot;
        const subEnv = await createStageEnvironment(cmd, input, branchInput, context2, this.env, this.format, this.stateMachine.getEvents(), this.hasSyntheticSource, this.allRetryHistory, {
          getStageOutput: /* @__PURE__ */ __name((stage, fallback) => this.getStageOutput(stage, fallback), "getStageOutput")
        }, {
          capturePipelineContext: /* @__PURE__ */ __name((snapshot) => {
            pipelineSnapshot = snapshot;
          }, "capturePipelineContext"),
          skipSetPipelineContext: false,
          sourceRetryable: this.isRetryable
        });
        if (!pipelineSnapshot) {
          throw new Error("Pipeline context snapshot unavailable for parallel branch");
        }
        const branchCtxManager = subEnv.getContextManager();
        const stageDescriptor = this.buildStageDescriptor(cmd, stageIndex, context2, branchInput);
        const branchOpContext = this.createPipelineOperationContext(cmd, stageIndex, context2);
        const branchHookNode = this.createStageHookNode(cmd);
        const executeBranch = /* @__PURE__ */ __name(async () => {
          try {
            const stageExecution = cmd.type === "inlineValue" ? await this.executeInlineValueStage(cmd, branchInput, subEnv) : cmd.type === "inlineCommand" ? await this.executeInlineCommandStage(cmd, branchInput, subEnv, branchOpContext, branchHookNode, stageIndex, context2, parallelIndex) : await this.executeCommand(cmd, input, branchInput, subEnv, branchOpContext, branchHookNode, stageIndex, context2, parallelIndex);
            if (this.isRetrySignal(stageExecution.result)) {
              return stageExecution.result;
            }
            let normalized = this.normalizeOutput(stageExecution.result);
            this.logStructuredStage("output", cmd.rawIdentifier, stageIndex, normalized, true);
            normalized = this.finalizeStageOutput(normalized, branchInput, stageExecution.result, stageDescriptor, stageExecution.labelDescriptor);
            await this.runInlineEffects(cmd, normalized, subEnv);
            return {
              normalized,
              labels: stageExecution.labelDescriptor
            };
          } catch (err) {
            const message = formatParallelStageError(err);
            const marker = {
              index: parallelIndex,
              key: parallelIndex,
              message,
              error: message,
              value: extractStageValue(branchInput)
            };
            errors.push(marker);
            const markerText = safeJSONStringify(marker);
            const normalized = wrapStructured(marker, "object", markerText);
            this.logStructuredStage("output", cmd.rawIdentifier, stageIndex, normalized, true);
            return {
              normalized
            };
          }
        }, "executeBranch");
        return await this.env.withPipeContext(pipelineSnapshot, async () => {
          if (branchCtxManager) {
            return await branchCtxManager.withOperation(branchOpContext, executeBranch);
          }
          return await executeBranch();
        });
      }, {
        ordered: true,
        paceMs: this.delayMs
      });
      const retrySignal = results.find((res) => this.isRetrySignal(res));
      if (retrySignal) {
        return {
          type: "error",
          error: new Error("retry not supported in parallel stage")
        };
      }
      const branchPayloads = results;
      if (errors.length === 0) {
        for (let i = 0; i < branchPayloads.length; i++) {
          const candidate = extractStageValue(branchPayloads[i].normalized);
          if (candidate && typeof candidate === "object" && "message" in candidate && "error" in candidate) {
            const marker = {
              index: typeof candidate.index === "number" ? candidate.index : i,
              key: candidate.key ?? i,
              message: String(candidate.message ?? candidate.error),
              error: String(candidate.error ?? candidate.message),
              value: candidate.value
            };
            errors.push(marker);
          }
        }
      }
      resetParallelErrorsContext(this.env, errors);
      const aggregatedData = branchPayloads.map((result) => extractStageValue(result.normalized));
      const aggregatedText = safeJSONStringify(aggregatedData);
      const aggregatedBase = wrapStructured(aggregatedData, "array", aggregatedText, {
        stages: branchPayloads.map((result) => result.normalized),
        errors
      });
      const stageDescriptors = branchPayloads.map((result) => result.labels ?? getStructuredSecurityDescriptor(result.normalized)).filter((descriptor) => Boolean(descriptor));
      const aggregatedDescriptor = stageDescriptors.length > 0 ? mergeDescriptors(...stageDescriptors) : void 0;
      const aggregated = this.finalizeStageOutput(aggregatedBase, sharedStructuredInput, aggregatedData, aggregatedDescriptor);
      this.structuredOutputs.set(stageIndex, aggregated);
      this.finalOutput = aggregated;
      this.lastStageIndex = stageIndex;
      return {
        type: "success",
        output: aggregated.text,
        structuredOutput: aggregated
      };
    } catch (err) {
      return {
        type: "error",
        error: err
      };
    }
  }
  buildStageDescriptor(command, stageIndex, context2, _structuredInput) {
    const labels = command?.securityLabels;
    if (labels && labels.length > 0) {
      return makeSecurityDescriptor({
        labels
      });
    }
    return void 0;
  }
  normalizeOutput(output) {
    this.logStructuredValue("normalize:raw", output);
    if (isStructuredValue(output)) {
      this.logStructuredValue("normalize:structured", output);
      return output;
    }
    if (isPipelineInput(output)) {
      return output;
    }
    if (output === null || output === void 0) {
      const wrapped2 = wrapStructured("", "text", "");
      this.logStructuredValue("normalize:wrapped", wrapped2);
      return wrapped2;
    }
    if (typeof output === "string") {
      const wrapped2 = wrapStructured(output, "text", output);
      this.logStructuredValue("normalize:wrapped", wrapped2);
      return wrapped2;
    }
    if (typeof output === "number" || typeof output === "boolean" || typeof output === "bigint") {
      const text = String(output);
      const wrapped2 = wrapStructured(output, "text", text);
      this.logStructuredValue("normalize:wrapped", wrapped2);
      return wrapped2;
    }
    if (Array.isArray(output)) {
      const normalizedArray = output.map((item) => extractStageValue(item));
      const text = safeJSONStringify(normalizedArray);
      const wrapped2 = wrapStructured(normalizedArray, "array", text);
      this.logStructuredValue("normalize:wrapped", wrapped2);
      return wrapped2;
    }
    if (typeof output === "object") {
      const maybeText = typeof output.content === "string" ? output.content : void 0;
      const text = maybeText ?? safeJSONStringify(output);
      const wrapped2 = wrapStructured(output, "object", text);
      this.logStructuredValue("normalize:wrapped", wrapped2);
      return wrapped2;
    }
    const wrapped = wrapStructured(output, "text", safeJSONStringify(output));
    this.logStructuredValue("normalize:wrapped", wrapped);
    return wrapped;
  }
  finalizeStageOutput(value, stageInput, rawOutput, ...descriptorHints) {
    const descriptor = this.mergeStageDescriptors(value, stageInput, rawOutput, descriptorHints);
    if (descriptor) {
      applySecurityDescriptorToStructuredValue(value, descriptor);
      setExpressionProvenance(value, descriptor);
    }
    return value;
  }
  mergeStageDescriptors(normalizedValue, stageInput, rawOutput, descriptorHints = []) {
    const descriptors = [];
    const inputDescriptor = extractSecurityDescriptor(stageInput, {
      recursive: true,
      mergeArrayElements: true
    });
    if (inputDescriptor) {
      descriptors.push(inputDescriptor);
    }
    const rawDescriptor = extractSecurityDescriptor(rawOutput ?? normalizedValue, {
      recursive: true,
      mergeArrayElements: true
    });
    if (rawDescriptor) {
      descriptors.push(rawDescriptor);
    }
    const existingDescriptor = getStructuredSecurityDescriptor(normalizedValue);
    if (existingDescriptor) {
      descriptors.push(existingDescriptor);
    }
    for (const hint of descriptorHints) {
      if (hint) {
        descriptors.push(hint);
      }
    }
    if (process.env.MLLD_DEBUG === "true") {
      try {
        console.error("[PipelineExecutor][mergeStageDescriptors]", {
          inputLabels: inputDescriptor?.labels ?? null,
          rawLabels: rawDescriptor?.labels ?? null,
          existingLabels: existingDescriptor?.labels ?? null,
          hintLabels: descriptorHints.map((hint) => hint?.labels ?? null),
          normalizedLabels: normalizedValue?.mx?.labels ?? null,
          normalizedText: normalizedValue?.text
        });
      } catch {
      }
    }
    if (descriptors.length === 0) {
      return void 0;
    }
    if (descriptors.length === 1) {
      return descriptors[0];
    }
    return this.env.mergeSecurityDescriptors(...descriptors);
  }
  applySourceDescriptor(wrapper, source) {
    const descriptor = extractSecurityDescriptor(source, {
      recursive: true,
      mergeArrayElements: true
    });
    if (!descriptor) {
      return;
    }
    applySecurityDescriptorToStructuredValue(wrapper, descriptor);
    setExpressionProvenance(wrapper, descriptor);
  }
  /**
  * Execute any inline builtin effects attached to the command/stage.
  * Effects do not count as stages and run after successful execution.
  */
  async runInlineEffects(command, stageOutput, stageEnv) {
    if (!command?.effects || !Array.isArray(command.effects) || command.effects.length === 0) return;
    for (const effectCmd of command.effects) {
      try {
        if (!effectCmd?.rawIdentifier || !isBuiltinEffect(effectCmd.rawIdentifier)) continue;
        await runBuiltinEffect(effectCmd, stageOutput, stageEnv);
      } catch (err) {
        if (err instanceof Error) {
          throw new MlldCommandExecutionError(`Inline effect @${effectCmd.rawIdentifier} failed: ${err.message}`, void 0, {
            command: effectCmd.rawIdentifier,
            exitCode: 1,
            duration: 0,
            workingDirectory: this.env.getExecutionDirectory()
          });
        }
        throw err;
      }
    }
  }
  getStageOutput(stageIndex, fallbackText = "") {
    if (stageIndex < 0) {
      if (!this.initialOutput) {
        this.initialOutput = wrapStructured(fallbackText, "text", fallbackText);
      }
      return this.initialOutput;
    }
    const cached = this.structuredOutputs.get(stageIndex);
    if (cached) {
      return cached;
    }
    const wrapper = buildPipelineStructuredValue(fallbackText, "text");
    this.structuredOutputs.set(stageIndex, wrapper);
    return wrapper;
  }
  getFinalOutput() {
    if (this.finalOutput) {
      return this.finalOutput;
    }
    if (this.lastStageIndex >= 0) {
      return this.getStageOutput(this.lastStageIndex, this.initialOutput?.text ?? "");
    }
    if (this.initialOutput) {
      return this.initialOutput;
    }
    return wrapStructured("", "text", "");
  }
  clearStageOutputsFrom(startStage) {
    const keys = Array.from(this.structuredOutputs.keys());
    for (const key of keys) {
      if (key >= startStage) {
        this.structuredOutputs.delete(key);
      }
    }
  }
  createStageHookNode(command) {
    const nodeId = `pipeline-stage-${this.stageHookNodeCounter++}`;
    const commandRef = {
      type: "CommandReference",
      nodeId: `${nodeId}-command`,
      identifier: command.rawIdentifier,
      args: [],
      fields: command?.fields
    };
    return {
      type: "ExecInvocation",
      nodeId,
      commandRef,
      withClause: void 0,
      location: command?.location ?? command?.meta?.location
    };
  }
  logStructuredStage(phase, stageName, stageIndex, value, isParallelBranch = false) {
    if (!this.debugStructured) {
      return;
    }
    try {
      console.error(`[PipelineExecutor][${phase}]`, {
        stage: stageName,
        stageIndex,
        parallel: isParallelBranch,
        labels: value?.mx?.labels ?? null,
        taint: value?.mx?.taint ?? null,
        metadataLabels: value?.metadata?.security?.labels ?? null
      });
      console.error("[PipelineExecutor][detail-start]", {
        phase,
        stage: stageName
      });
      console.error("[PipelineExecutor]", {
        phase,
        stage: stageName,
        stageIndex,
        parallel: isParallelBranch,
        type: value?.type,
        textSnippet: snippet(value?.text),
        dataPreview: previewValue(value?.data)
      });
      console.error("[PipelineExecutor][detail-end]", {
        phase,
        stage: stageName
      });
    } catch (error) {
      console.error("[PipelineExecutor][logStructuredStage:error]", {
        phase,
        stage: stageName,
        stageIndex,
        error: error instanceof Error ? error.message : error
      });
    }
  }
  debugNormalize(value) {
    try {
      if (value === void 0 || value === null) return value;
      if (typeof value === "string") return value;
      if (typeof value === "object") {
        const base = {
          type: value.type
        };
        if (value.text !== void 0) base.text = value.text;
        if (value.data !== void 0 && typeof value.data !== "object") {
          base.data = value.data;
        }
        if (Array.isArray(value.mx?.labels)) {
          base.labels = value.mx.labels;
        }
        return base;
      }
      return value;
    } catch {
      return "[unserializable]";
    }
  }
  logStructuredValue(label, value) {
    if (!this.debugStructured) {
      return;
    }
    try {
      if (isStructuredValue(value)) {
        console.error("[PipelineExecutor]", {
          label,
          type: value.type,
          textSnippet: snippet(value.text),
          dataPreview: previewValue(value.data)
        });
      } else {
        console.error("[PipelineExecutor]", {
          label,
          typeofValue: typeof value,
          preview: previewValue(value)
        });
      }
    } catch (error) {
      console.error("[PipelineExecutor][logStructuredValue:error]", {
        label,
        error: error instanceof Error ? error.message : error
      });
    }
  }
};
__name(_PipelineExecutor, "PipelineExecutor");
var PipelineExecutor = _PipelineExecutor;
function safeJSONStringify(value) {
  try {
    return JSON.stringify(value);
  } catch {
    return String(value ?? "");
  }
}
__name(safeJSONStringify, "safeJSONStringify");
function extractStageValue(value) {
  if (isStructuredValue(value)) {
    return asData(value);
  }
  if (isPipelineInput(value)) {
    return value.data;
  }
  return value;
}
__name(extractStageValue, "extractStageValue");
function snippet(text, max = 120) {
  if (!text) {
    return text;
  }
  return text.length <= max ? text : `${text.slice(0, max)}\u2026`;
}
__name(snippet, "snippet");
function previewValue(value) {
  if (value === null || value === void 0) {
    return value;
  }
  if (isStructuredValue(value)) {
    return {
      type: value.type,
      textSnippet: snippet(value.text, 60)
    };
  }
  if (Array.isArray(value)) {
    return {
      length: value.length,
      sample: value.slice(0, 3).map((item) => isStructuredValue(item) ? {
        type: item.type,
        text: snippet(item.text, 40)
      } : item)
    };
  }
  if (typeof value === "object") {
    const keys = Object.keys(value);
    return {
      keys: keys.slice(0, 5),
      size: keys.length
    };
  }
  return value;
}
__name(previewValue, "previewValue");
function getStructuredSecurityDescriptor(value) {
  if (!value) {
    return void 0;
  }
  if (value.mx) {
    return varMxToSecurityDescriptor(value.mx);
  }
  return void 0;
}
__name(getStructuredSecurityDescriptor, "getStructuredSecurityDescriptor");
function cloneStructuredValue3(value) {
  const cloned = wrapStructured(value);
  inheritExpressionProvenance(cloned, value);
  return cloned;
}
__name(cloneStructuredValue3, "cloneStructuredValue");

// interpreter/eval/pipeline/builtin-transformers.ts
var BUILTIN_TRANSFORMERS = /* @__PURE__ */ new Set([
  // Format converters
  "json",
  "json.loose",
  "json.strict",
  "json.llm",
  "json.fromlist",
  "JSON",
  "JSON_LOOSE",
  "JSON_STRICT",
  "JSON_LLM",
  "JSON_FROMLIST",
  "xml",
  "XML",
  "csv",
  "CSV",
  "md",
  "MD",
  // String transformations
  "upper",
  "UPPER",
  "lower",
  "LOWER",
  "trim",
  "TRIM",
  // These might be built-in (need to verify)
  "pretty",
  "PRETTY",
  "sort",
  "SORT"
]);
function isBuiltinTransformer(name) {
  return BUILTIN_TRANSFORMERS.has(name);
}
__name(isBuiltinTransformer, "isBuiltinTransformer");
function getBuiltinTransformers() {
  return Array.from(new Set(Array.from(BUILTIN_TRANSFORMERS).map((t) => t.toLowerCase()))).sort();
}
__name(getBuiltinTransformers, "getBuiltinTransformers");

// interpreter/eval/pipeline/effects-attachment.ts
function attachBuiltinEffects(pipeline) {
  const functional = [];
  const pendingLeadingEffects = [];
  let hadLeadingEffects = false;
  for (const stage of pipeline) {
    if (Array.isArray(stage)) {
      const { functionalPipeline: group, hadLeadingEffects: inner } = attachBuiltinEffects(stage);
      if (pendingLeadingEffects.length > 0 && group.length > 0) {
        for (const cmd2 of group) {
          if (cmd2.rawIdentifier) {
            const command = cmd2;
            command.effects = [
              ...command.effects || [],
              ...pendingLeadingEffects
            ];
          }
        }
        pendingLeadingEffects.length = 0;
      }
      if (group.length > 0) {
        functional.push(group);
      }
      hadLeadingEffects = hadLeadingEffects || inner;
      continue;
    }
    const name = stage.rawIdentifier;
    const lowerName = typeof name === "string" ? name.toLowerCase() : "";
    const requiresMeta = lowerName === "append";
    const isInlineEffect = isBuiltinEffect(name) && (stage.meta?.isBuiltinEffect || !requiresMeta);
    if (isInlineEffect) {
      if (functional.length > 0) {
        const prev = functional[functional.length - 1];
        if (Array.isArray(prev)) {
          for (const pcmd of prev) {
            if (pcmd.rawIdentifier) {
              const command = pcmd;
              command.effects = [
                ...command.effects || [],
                stage
              ];
            }
          }
        } else {
          const prevCmd = prev;
          if (prevCmd.rawIdentifier) {
            prevCmd.effects = [
              ...prevCmd.effects || [],
              stage
            ];
          }
        }
      } else {
        pendingLeadingEffects.push(stage);
        hadLeadingEffects = true;
      }
      continue;
    }
    const cmd = {
      ...stage
    };
    if (pendingLeadingEffects.length > 0) {
      cmd.effects = [
        ...cmd.effects || [],
        ...pendingLeadingEffects
      ];
      pendingLeadingEffects.length = 0;
    }
    functional.push(cmd);
  }
  if (functional.length === 0 && pendingLeadingEffects.length > 0) {
    functional.push({
      rawIdentifier: "__identity__",
      identifier: [],
      args: [],
      fields: [],
      rawArgs: [],
      effects: [
        ...pendingLeadingEffects
      ]
    });
    pendingLeadingEffects.length = 0;
  }
  return {
    functionalPipeline: functional,
    hadLeadingEffects
  };
}
__name(attachBuiltinEffects, "attachBuiltinEffects");

// interpreter/eval/pipeline/unified-processor.ts
async function processPipeline(context2) {
  const { value, env, node, directive, identifier, descriptorHint } = context2;
  const streamRequested = context2.stream ?? Boolean(node?.withClause?.stream ?? directive?.values?.withClause?.stream ?? directive?.meta?.withClause?.stream);
  const sourceNode = getSourceFunctionFromValue(value);
  const descriptorFromValue = extractSecurityDescriptor(value, {
    recursive: true,
    mergeArrayElements: true
  });
  const descriptorFromAst = extractDescriptorFromAst(node, env);
  if (process.env.MLLD_DEBUG === "true") {
    const payload = {
      nodeType: node?.type,
      descriptorFromValue,
      descriptorFromAst,
      descriptorHint
    };
    console.error("[processPipeline] descriptor sources", payload);
    try {
      const fs5 = await import('node:fs');
      fs5.appendFileSync("/tmp/pipeline-debug.log", `${JSON.stringify(payload)}
`);
    } catch {
    }
  }
  let pipelineDescriptor = descriptorHint ?? descriptorFromValue ?? descriptorFromAst;
  const directiveLabels = directive ? directive.meta?.securityLabels || directive.values?.securityLabels : void 0;
  if (directiveLabels && directiveLabels.length > 0) {
    pipelineDescriptor = mergeDescriptors(pipelineDescriptor, makeSecurityDescriptor({
      labels: directiveLabels
    }));
  }
  if (pipelineDescriptor) {
    env.recordSecurityDescriptor(pipelineDescriptor);
  }
  if (identifier && process.env.MLLD_DEBUG === "true") {
    debugPipelineDetection(identifier, node, directive);
  }
  let detected = null;
  if (context2.pipeline) {
    detected = {
      pipeline: context2.pipeline,
      source: "directive-values",
      format: context2.format,
      isRetryable: context2.isRetryable ?? true
    };
  } else {
    detected = detectPipeline(node, directive);
    if (detected && context2.isRetryable !== void 0) {
      detected.isRetryable = context2.isRetryable;
    }
    if (detected && detected.pipeline && detected.pipeline.length > 0 && detected.isRetryable === false) {
      detected.isRetryable = true;
    }
    if (process.env.MLLD_DEBUG === "true" && identifier) {
      logger.debug("[processPipeline] Detection result:", {
        identifier,
        nodeType: node?.type,
        hasDetected: !!detected,
        source: detected?.source,
        pipelineLength: detected?.pipeline?.length,
        isRetryable: detected?.isRetryable
      });
    }
  }
  if (!detected || !detected.pipeline || detected.pipeline.length === 0) {
    return value;
  }
  if (process.env.MLLD_DEBUG === "true") {
    logger.debug("[processPipeline] Checking for synthetic source:", {
      isRetryable: detected.isRetryable,
      hasValue: !!value,
      hasMetadata: !!(value && typeof value === "object" && ("mx" in value || "internal" in value) && (value.mx || value.internal)),
      hasSourceFunction: !!sourceNode,
      valueType: value && typeof value === "object" && "type" in value ? value.type : typeof value
    });
  }
  const normalizedPipeline = detected.pipeline;
  const { functionalPipeline, hadLeadingEffects } = attachBuiltinEffects(normalizedPipeline);
  const pipelineToValidate = functionalPipeline.filter((cmd) => cmd.rawIdentifier !== "__source__" && cmd.rawIdentifier !== "__identity__");
  await validatePipeline(pipelineToValidate, env, identifier);
  const input = await prepareInput(value, env, pipelineDescriptor);
  const attachDescriptorToRetryInput = /* @__PURE__ */ __name((value2) => {
    if (!pipelineDescriptor) {
      return value2;
    }
    const wrapped = isStructuredValue(value2) ? value2 : wrapExecResult(value2);
    applySecurityDescriptorToStructuredValue(wrapped, pipelineDescriptor);
    setExpressionProvenance(wrapped, pipelineDescriptor);
    return wrapped;
  }, "attachDescriptorToRetryInput");
  let sourceFunction;
  if (detected.isRetryable) {
    if (sourceNode) {
      sourceFunction = /* @__PURE__ */ __name(async () => {
        if (sourceNode.type === "ExecInvocation") {
          const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
          const result = await evaluateExecInvocation(sourceNode, env);
          return attachDescriptorToRetryInput(result.value);
        }
        if (sourceNode.type === "command") {
          const { evaluateCommand } = await import('./run-KYGSK2JR.mjs');
          const result = await evaluateCommand(sourceNode, env);
          return attachDescriptorToRetryInput(structuredEnabled ? result.value : String(result.value));
        }
        if (sourceNode.type === "code") {
          const { evaluateCodeExecution } = await import('./code-execution-RAAJT3Y7.mjs');
          const result = await evaluateCodeExecution(sourceNode, env);
          return attachDescriptorToRetryInput(result.value);
        }
        return attachDescriptorToRetryInput(input);
      }, "sourceFunction");
    } else {
      const cachedInput = attachDescriptorToRetryInput(input);
      sourceFunction = /* @__PURE__ */ __name(async () => cachedInput, "sourceFunction");
    }
  }
  const hasSyntheticSource = functionalPipeline[0]?.rawIdentifier === "__source__";
  let executionResult;
  try {
    const executor = new PipelineExecutor(functionalPipeline, env, detected.format, detected.isRetryable, sourceFunction, hasSyntheticSource, detected.parallelCap, detected.delayMs);
    executionResult = await executor.execute(input, {
      returnStructured: true,
      stream: streamRequested
    });
  } catch (error) {
    if (error instanceof Error) {
      const funcName = detected.pipeline[0]?.rawIdentifier || "unknown";
      throw new MlldDirectiveError(`Pipeline execution failed at '@${funcName}': ${error.message}`, "pipeline", {
        location: context2.location
      });
    }
    throw error;
  }
  const errorsMeta = isStructuredValue(executionResult) && executionResult.metadata && Array.isArray(executionResult.metadata.errors) ? executionResult.metadata.errors : void 0;
  if (errorsMeta && errorsMeta.length > 0) {
    const mxManager = env.getContextManager?.();
    mxManager?.setLatestErrors(errorsMeta);
    mxManager?.pushGenericContext("parallel", {
      errors: errorsMeta,
      timestamp: Date.now()
    });
  }
  if (pipelineDescriptor && isStructuredValue(executionResult)) {
    const metadata = {
      ...executionResult.metadata || {},
      security: pipelineDescriptor
    };
    return wrapStructured(executionResult, void 0, void 0, metadata);
  }
  if (pipelineDescriptor) {
    env.recordSecurityDescriptor(pipelineDescriptor);
  }
  return executionResult;
}
__name(processPipeline, "processPipeline");
async function validatePipeline(pipeline, env, identifier) {
  for (const stage of pipeline) {
    if (Array.isArray(stage)) {
      await validatePipeline(stage, env, identifier);
      continue;
    }
    if (stage.type === "whileStage") {
      const processorName = getWhileProcessorName(stage);
      if (!processorName) {
        continue;
      }
      const variable2 = env.getVariable(processorName);
      if (!variable2) {
        throw new MlldDirectiveError(`While processor '@${processorName}' is not defined${identifier ? ` (in @${identifier})` : ""}. Available functions: ${getAvailableFunctions().join(", ")}`, "pipeline");
      }
      if (variable2.type !== "executable" && variable2.type !== "computed") {
        throw new MlldDirectiveError(`'@${processorName}' is not a function, it's a ${variable2.type}${identifier ? ` (in @${identifier})` : ""}`, "pipeline");
      }
      continue;
    }
    if (stage.type === "inlineCommand" || stage.type === "inlineValue") {
      continue;
    }
    const funcName = stage.rawIdentifier;
    if (isBuiltinTransformer(funcName)) {
      continue;
    }
    const variable = env.getVariable(funcName);
    if (!variable) {
      throw new MlldDirectiveError(`Pipeline function '@${funcName}' is not defined${identifier ? ` (in @${identifier})` : ""}. Available functions: ${getAvailableFunctions().join(", ")}`, "pipeline");
    }
    if (variable.type !== "executable" && variable.type !== "computed") {
      throw new MlldDirectiveError(`'@${funcName}' is not a function, it's a ${variable.type} variable${identifier ? ` (in @${identifier})` : ""}`, "pipeline");
    }
  }
}
__name(validatePipeline, "validatePipeline");
function getWhileProcessorName(stage) {
  const processor = stage?.processor;
  if (!processor) {
    return void 0;
  }
  if (processor.commandRef) {
    const ref = processor.commandRef;
    if (ref.name) {
      return ref.name;
    }
    if (Array.isArray(ref.identifier)) {
      const candidate = ref.identifier.map((id) => id.identifier || id.content || "").find(Boolean);
      if (candidate) {
        return candidate;
      }
    } else if (ref.identifier) {
      return ref.identifier;
    }
  }
  if (processor.identifier) {
    return processor.identifier;
  }
  if (Array.isArray(processor.identifier) && processor.identifier[0]?.identifier) {
    return processor.identifier[0].identifier;
  }
  if (processor.rawIdentifier) {
    return processor.rawIdentifier;
  }
  return void 0;
}
__name(getWhileProcessorName, "getWhileProcessorName");
async function prepareInput(value, env, descriptor) {
  return prepareStructuredInput(value, env, void 0, descriptor);
}
__name(prepareInput, "prepareInput");
async function prepareStructuredInput(value, env, incomingMetadata, providedDescriptor) {
  const sourceDescriptor = providedDescriptor ?? extractSecurityDescriptor(value, {
    recursive: true,
    mergeArrayElements: true
  });
  const finalizeWrapper = /* @__PURE__ */ __name((wrapper) => {
    if (sourceDescriptor) {
      applySecurityDescriptorToStructuredValue(wrapper, sourceDescriptor);
      setExpressionProvenance(wrapper, sourceDescriptor);
    } else {
      inheritExpressionProvenance(wrapper, value);
    }
    return wrapper;
  }, "finalizeWrapper");
  const mergedMetadata = /* @__PURE__ */ __name((current) => {
    if (!incomingMetadata && !current) {
      return void 0;
    }
    return {
      ...current || {},
      ...incomingMetadata || {}
    };
  }, "mergedMetadata");
  if (isStructuredValue(value)) {
    const normalizedData = sanitizeStructuredData(value.data);
    return finalizeWrapper(wrapStructured(normalizedData, value.type, value.text, mergedMetadata(value.metadata)));
  }
  if (value && typeof value === "object" && "type" in value && "text" in value && "data" in value && typeof value.text === "string" && typeof value.type === "string") {
    const normalizedData = sanitizeStructuredData(value.data);
    return finalizeWrapper(wrapStructured(normalizedData, value.type, value.text, mergedMetadata(value.metadata)));
  }
  if (value && typeof value === "object" && "value" in value && ("mx" in value || "internal" in value)) {
    const metadata = mergedMetadata(void 0);
    const nested = await prepareStructuredInput(value.value, env, metadata, providedDescriptor);
    return finalizeWrapper(nested);
  }
  if (value && typeof value === "object") {
    const { resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
    if ("type" in value && "value" in value && "name" in value) {
      const resolved = await resolveValue(value, env, ResolutionContext.PipelineInput);
      const nested = await prepareStructuredInput(resolved, env, incomingMetadata, providedDescriptor);
      return finalizeWrapper(nested);
    }
  }
  if (typeof value === "string") {
    return finalizeWrapper(ensureStructuredValue(value, "text", value, incomingMetadata));
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return finalizeWrapper(ensureStructuredValue(value, "text", String(value), incomingMetadata));
  }
  if (Array.isArray(value)) {
    const normalizedArray = value.map((item) => sanitizeStructuredData(item));
    return finalizeWrapper(wrapStructured(normalizedArray, "array", void 0, incomingMetadata));
  }
  if (value && typeof value === "object") {
    const normalizedObject = sanitizeStructuredData(value);
    return finalizeWrapper(wrapStructured(normalizedObject, "object", void 0, incomingMetadata));
  }
  return finalizeWrapper(ensureStructuredValue("", "text", "", incomingMetadata));
}
__name(prepareStructuredInput, "prepareStructuredInput");
function getAvailableFunctions(env) {
  const funcs = [];
  funcs.push(...getBuiltinTransformers());
  return funcs;
}
__name(getAvailableFunctions, "getAvailableFunctions");
function sanitizeStructuredData(value) {
  return resolveNestedValue(value, {
    preserveProvenance: true
  });
}
__name(sanitizeStructuredData, "sanitizeStructuredData");
function extractDescriptorFromAst(node, env) {
  if (!node || typeof node !== "object") {
    return void 0;
  }
  if (node.type === "ExecInvocation" && node.commandRef) {
    const execDescriptor = extractDescriptorFromAst(node.commandRef.objectReference, env) ?? extractDescriptorFromAst(node.commandRef.objectSource, env);
    if (execDescriptor) {
      return execDescriptor;
    }
    if (typeof node.commandRef.identifier === "string") {
      const variable = env.getVariable(node.commandRef.identifier);
      if (variable?.mx) {
        return varMxToSecurityDescriptor(variable.mx);
      }
    } else if (Array.isArray(node.commandRef.identifier)) {
      for (const identifierNode of node.commandRef.identifier) {
        const descriptor = extractDescriptorFromAst(identifierNode, env);
        if (descriptor) {
          return descriptor;
        }
      }
    }
  }
  if (node.type === "VariableReference" && typeof node.identifier === "string") {
    const variable = env.getVariable(node.identifier);
    if (variable?.mx) {
      return varMxToSecurityDescriptor(variable.mx);
    }
  }
  if (node.objectReference) {
    const descriptor = extractDescriptorFromAst(node.objectReference, env);
    if (descriptor) {
      return descriptor;
    }
  }
  if (node.commandRef?.objectReference) {
    const descriptor = extractDescriptorFromAst(node.commandRef.objectReference, env);
    if (descriptor) {
      return descriptor;
    }
  }
  if (node.commandRef?.objectSource) {
    const descriptor = extractDescriptorFromAst(node.commandRef.objectSource, env);
    if (descriptor) {
      return descriptor;
    }
  }
  if (Array.isArray(node.value)) {
    for (const child of node.value) {
      const descriptor = extractDescriptorFromAst(child, env);
      if (descriptor) {
        return descriptor;
      }
    }
  }
  return void 0;
}
__name(extractDescriptorFromAst, "extractDescriptorFromAst");
function needsPipelineProcessing(node, directive) {
  return !!(node?.pipes?.length || node?.withClause?.pipeline || directive?.values?.withClause?.pipeline || directive?.meta?.withClause?.pipeline);
}
__name(needsPipelineProcessing, "needsPipelineProcessing");
function getSourceFunctionFromValue(value) {
  if (!value || typeof value !== "object") {
    return void 0;
  }
  const candidate = value;
  if (candidate.internal && candidate.internal.sourceFunction) {
    return candidate.internal.sourceFunction;
  }
  return void 0;
}
__name(getSourceFunctionFromValue, "getSourceFunctionFromValue");

// interpreter/eval/content-loader.ts
async function interpolateAndRecord5(nodes, env, context2 = InterpolationContext.Default) {
  const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
  const descriptors = [];
  const text = await interpolate2(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord5, "interpolateAndRecord");
function isGlobPattern(path10) {
  return /[\*\?\{\}\[\]]/.test(path10);
}
__name(isGlobPattern, "isGlobPattern");
function getRelativeBasePath(env) {
  const projectRoot = env.getProjectRoot?.() ?? env.getBasePath();
  return projectRoot || env.getFileDirectory();
}
__name(getRelativeBasePath, "getRelativeBasePath");
function formatRelativePath(env, targetPath) {
  const basePath = path7.resolve(getRelativeBasePath(env));
  const absoluteTarget = path7.resolve(targetPath);
  const relative3 = path7.relative(basePath, absoluteTarget);
  return relative3 ? `./${relative3}` : "./";
}
__name(formatRelativePath, "formatRelativePath");
async function processContentLoader(node, env) {
  if (!node || node.type !== "load-content") {
    throw new MlldError("Invalid content loader node", {
      node: node ? node.type : "null",
      expected: "load-content"
    });
  }
  const { source, options, pipes, ast } = node;
  if (!source) {
    throw new MlldError("Content loader expression missing source", {
      node
    });
  }
  const hasTransform = options?.transform?.type === "template";
  const hasPipes = pipes && pipes.length > 0;
  let pathOrUrl;
  const actualSource = source.type === "path" || source.type === "url" ? source : source.segments && source.raw !== void 0 ? {
    ...source,
    type: "path"
  } : source;
  if (actualSource.type === "path") {
    pathOrUrl = await reconstructPath(actualSource, env);
  } else if (actualSource.type === "url") {
    pathOrUrl = reconstructUrl(actualSource);
  } else {
    throw new MlldError(`Unknown content loader source type: ${actualSource.type}`, {
      sourceType: actualSource.type,
      expected: [
        "path",
        "url"
      ]
    });
  }
  const isGlob = isGlobPattern(pathOrUrl);
  if (ast && actualSource.type === "path") {
    let astPatterns = ast;
    astPatterns = await Promise.all(astPatterns.map(async (pattern) => {
      if (pattern.type === "type-filter-var") {
        const variable = env.getVariable(pattern.identifier);
        if (!variable) {
          throw new MlldDirectiveError(`Variable @${pattern.identifier} is not defined`, {
            identifier: pattern.identifier
          });
        }
        const varValue = await extractVariableValue(variable, env);
        const filter = varValue ? String(varValue) : void 0;
        if (!filter) {
          throw new MlldDirectiveError(`Variable @${pattern.identifier} is empty`, {
            identifier: pattern.identifier
          });
        }
        return {
          type: "type-filter",
          filter,
          usage: pattern.usage
        };
      } else if (pattern.type === "name-list-var") {
        const variable = env.getVariable(pattern.identifier);
        if (!variable) {
          throw new MlldDirectiveError(`Variable @${pattern.identifier} is not defined`, {
            identifier: pattern.identifier
          });
        }
        const varValue = await extractVariableValue(variable, env);
        const filter = varValue ? String(varValue) : void 0;
        if (!filter) {
          throw new MlldDirectiveError(`Variable @${pattern.identifier} is empty`, {
            identifier: pattern.identifier
          });
        }
        return {
          type: "name-list",
          filter,
          usage: pattern.usage
        };
      }
      return pattern;
    }));
    const hasNames = hasNameListPattern(astPatterns);
    const hasContent = hasContentPattern(astPatterns);
    if (hasNames && hasContent) {
      throw new MlldDirectiveError("Cannot mix content selectors with name-list selectors", {
        patterns: astPatterns.map((p) => p.type)
      });
    }
    if (hasNames) {
      const loadNameResults = /* @__PURE__ */ __name(async () => {
        const namePattern = astPatterns.find((p) => p.type === "name-list" || p.type === "name-list-all");
        const filter = namePattern?.type === "name-list" ? namePattern.filter : void 0;
        if (isGlob) {
          const baseDir = env.getFileDirectory();
          const matches = await glob(pathOrUrl, {
            cwd: baseDir,
            absolute: true,
            followSymlinks: true,
            ignore: [
              "**/node_modules/**",
              "**/.git/**",
              "**/dist/**",
              "**/build/**"
            ]
          });
          const results = [];
          const fileList = Array.isArray(matches) ? matches : [];
          for (const filePath of fileList) {
            try {
              const content2 = await env.readFile(filePath);
              const names = extractNames(content2, filePath, filter);
              if (names.length > 0) {
                results.push({
                  names,
                  file: path7.basename(filePath),
                  relative: formatRelativePath(env, filePath),
                  absolute: filePath
                });
              }
            } catch {
            }
          }
          return results;
        }
        const content = await env.readFile(pathOrUrl);
        return extractNames(content, pathOrUrl, filter);
      }, "loadNameResults");
      const nameResults = await loadNameResults();
      if (hasPipes) {
        const piped = await processPipeline({
          value: nameResults,
          env,
          node: {
            pipes
          }
        });
        return finalizeLoaderResult(piped, {
          type: "array"
        });
      }
      return finalizeLoaderResult(nameResults, {
        type: "array"
      });
    }
    const loadAstResults = /* @__PURE__ */ __name(async () => {
      if (isGlob) {
        const baseDir = env.getFileDirectory();
        const matches = await glob(pathOrUrl, {
          cwd: baseDir,
          absolute: true,
          followSymlinks: true,
          ignore: [
            "**/node_modules/**",
            "**/.git/**",
            "**/dist/**",
            "**/build/**"
          ]
        });
        const aggregated = [];
        const fileList = Array.isArray(matches) ? matches : [];
        for (const filePath of fileList) {
          try {
            const content2 = await env.readFile(filePath);
            const extracted = extractAst(content2, filePath, astPatterns);
            for (const entry of extracted) {
              if (entry) {
                aggregated.push({
                  ...entry,
                  file: filePath
                });
              } else {
                aggregated.push(null);
              }
            }
          } catch {
          }
        }
        return aggregated;
      }
      const content = await env.readFile(pathOrUrl);
      return extractAst(content, pathOrUrl, astPatterns);
    }, "loadAstResults");
    const astResults = await loadAstResults();
    if (hasTransform && options?.transform) {
      const transformed = await applyTemplateToAstResults(astResults, options.transform, env);
      return finalizeLoaderResult(isGlob ? transformed : transformed[0] ?? "", {
        type: "text"
      });
    }
    if (hasPipes) {
      const piped = await processPipeline({
        value: astResults,
        env,
        node: {
          pipes
        }
      });
      return finalizeLoaderResult(piped, Array.isArray(astResults) ? {
        type: "array"
      } : void 0);
    }
    return finalizeLoaderResult(astResults, {
      type: "array"
    });
  }
  try {
    if (env.isURL(pathOrUrl)) {
      const response = await env.fetchURLWithMetadata(pathOrUrl);
      let processedContent = response.content;
      const contentType = response.headers["content-type"] || response.headers["Content-Type"] || "";
      if (contentType.includes("text/html")) {
        processedContent = await convertHtmlToMarkdown(response.content, pathOrUrl);
      }
      if (options?.section) {
        if (isSectionListPattern(options.section)) {
          const level = getSectionListLevel(options.section);
          const sections = listSections(processedContent, level);
          if (hasPipes) {
            const piped = await processPipeline({
              value: sections,
              env,
              node: {
                pipes
              }
            });
            return finalizeLoaderResult(piped, {
              type: "array",
              metadata: {
                url: pathOrUrl
              }
            });
          }
          return finalizeLoaderResult(sections, {
            type: "array",
            metadata: {
              url: pathOrUrl
            }
          });
        }
        const sectionName = await extractSectionName(options.section, env);
        const sectionContent = await extractSection(processedContent, sectionName, options.section.renamed, void 0, env);
        if (hasPipes) {
          const pipedSection = await processPipeline({
            value: sectionContent,
            env,
            node: {
              pipes
            }
          });
          return finalizeLoaderResult(pipedSection, {
            type: "text",
            metadata: {
              url: pathOrUrl
            }
          });
        }
        return finalizeLoaderResult(sectionContent, {
          type: "text",
          metadata: {
            url: pathOrUrl
          }
        });
      }
      const urlResult = new LoadContentResultURLImpl({
        content: processedContent,
        rawContent: response.content,
        url: pathOrUrl,
        headers: response.headers,
        status: response.status
      });
      if (hasPipes) {
        const pipedContent = await processPipeline({
          value: urlResult.content,
          env,
          node: {
            pipes
          }
        });
        const pipedResult = new LoadContentResultURLImpl({
          content: pipedContent,
          rawContent: response.content,
          url: pathOrUrl,
          headers: response.headers,
          status: response.status
        });
        return finalizeLoaderResult(pipedResult, {
          type: "object",
          text: asText(pipedContent),
          metadata: {
            url: pathOrUrl
          }
        });
      }
      return finalizeLoaderResult(urlResult, {
        type: "object",
        text: urlResult.content,
        metadata: {
          url: pathOrUrl
        }
      });
    }
    if (isGlob) {
      const results = await loadGlobPattern(pathOrUrl, options, env);
      if (hasTransform && options.transform) {
        const transformedResults = await applyTransformToResults(results, options.transform, env);
        return finalizeLoaderResult(transformedResults, {
          type: "array"
        });
      }
      if (hasPipes) {
        const pipedResults = await Promise.all(results.map(async (result2) => {
          const pipedContent = await processPipeline({
            value: typeof result2 === "string" ? result2 : result2.content,
            env,
            node: {
              pipes
            }
          });
          if (typeof result2 === "string") {
            return pipedContent;
          }
          return new LoadContentResultImpl({
            content: pipedContent,
            filename: result2.filename,
            relative: result2.relative,
            absolute: result2.absolute,
            _rawContent: result2._rawContent
          });
        }));
        return finalizeLoaderResult(pipedResults, {
          type: "array"
        });
      }
      return finalizeLoaderResult(results, {
        type: "array"
      });
    }
    const resolvedFilePath = await env.resolvePath(pathOrUrl);
    const fileSecurityDescriptor = makeSecurityDescriptor({
      taint: [
        "src:file",
        ...labelsForPath(resolvedFilePath)
      ],
      sources: [
        resolvedFilePath
      ]
    });
    const securityMetadata = {
      security: fileSecurityDescriptor
    };
    const result = await loadSingleFile(pathOrUrl, options, env, pipes, resolvedFilePath);
    if (Array.isArray(result)) {
      if (hasPipes) {
        const piped = await processPipeline({
          value: result,
          env,
          node: {
            pipes
          }
        });
        return finalizeLoaderResult(piped, {
          type: "array",
          metadata: securityMetadata
        });
      }
      return finalizeLoaderResult(result, {
        type: "array",
        metadata: securityMetadata
      });
    }
    if (hasTransform && options.transform) {
      const transformed = await applyTransformToResults([
        result
      ], options.transform, env);
      return finalizeLoaderResult(transformed[0], {
        type: typeof transformed[0] === "string" ? "text" : "object",
        metadata: securityMetadata
      });
    }
    if (hasPipes) {
      if (typeof result === "string") {
        const pipedString = await processPipeline({
          value: result,
          env,
          node: {
            pipes
          }
        });
        return finalizeLoaderResult(pipedString, {
          type: "text",
          metadata: securityMetadata
        });
      } else {
        const pipedContent = await processPipeline({
          value: result.content,
          env,
          node: {
            pipes
          }
        });
        const pipedResult = new LoadContentResultImpl({
          content: pipedContent,
          filename: result.filename,
          relative: result.relative,
          absolute: result.absolute,
          _rawContent: result._rawContent
        });
        return finalizeLoaderResult(pipedResult, {
          type: "object",
          text: asText(pipedContent),
          metadata: securityMetadata
        });
      }
    }
    return finalizeLoaderResult(result, {
      type: typeof result === "string" ? "text" : "object",
      text: typeof result === "string" ? result : result.content,
      metadata: securityMetadata
    });
  } catch (error) {
    if (process.env.DEBUG_CONTENT_LOADER) {
      console.log(`ERROR in processContentLoader: ${error.message}`);
      console.log(`Error stack:`, error.stack);
    }
    if (error.message && error.message.includes("Unknown transform:")) {
      throw error;
    }
    if (error.message && error.message.includes("Access denied:")) {
      throw new MlldError(error.message, {
        path: pathOrUrl,
        error: error.message
      });
    }
    let errorMessage = `Failed to load content: ${pathOrUrl}`;
    const hasAngleBracket = pathOrUrl.includes("<") || pathOrUrl.includes(">");
    if (!hasAngleBracket && !pathOrUrl.startsWith("/") && !pathOrUrl.startsWith("@") && !env.isURL(pathOrUrl)) {
      errorMessage += `

Hint: Paths are relative to mlld files. You can make them relative to your project root with the \`@base/\` prefix`;
    }
    throw new MlldError(errorMessage, {
      path: pathOrUrl,
      error: error.message
    });
  }
}
__name(processContentLoader, "processContentLoader");
async function loadSingleFile(filePath, options, env, pipes, resolvedPathOverride) {
  pipes && pipes.length > 0;
  const resolvedPath = resolvedPathOverride ?? await env.resolvePath(filePath);
  const rawContent = await env.readFile(resolvedPath);
  if (resolvedPath.endsWith(".html") || resolvedPath.endsWith(".htm")) {
    const markdownContent = await convertHtmlToMarkdown(rawContent, `file://${resolvedPath}`);
    if (options?.section) {
      if (isSectionListPattern(options.section)) {
        const level = getSectionListLevel(options.section);
        const sections = listSections(markdownContent, level);
        return sections;
      }
      const sectionName = await extractSectionName(options.section, env);
      const fileContext = new LoadContentResultImpl({
        content: rawContent,
        filename: path7.basename(resolvedPath),
        relative: formatRelativePath(env, resolvedPath),
        absolute: resolvedPath
      });
      const sectionContent = await extractSection(markdownContent, sectionName, options.section.renamed, fileContext, env);
      const dom2 = new JSDOM(rawContent);
      const doc2 = dom2.window.document;
      const title2 = doc2.querySelector("title")?.textContent || "";
      const description2 = doc2.querySelector('meta[name="description"]')?.getAttribute("content") || doc2.querySelector('meta[property="og:description"]')?.getAttribute("content") || "";
      const result3 = new LoadContentResultHTMLImpl({
        content: sectionContent,
        rawHtml: rawContent,
        filename: path7.basename(resolvedPath),
        relative: formatRelativePath(env, resolvedPath),
        absolute: resolvedPath,
        title: title2 || void 0,
        description: description2 || void 0
      });
      return result3;
    }
    const dom = new JSDOM(rawContent);
    const doc = dom.window.document;
    const title = doc.querySelector("title")?.textContent || "";
    const description = doc.querySelector('meta[name="description"]')?.getAttribute("content") || doc.querySelector('meta[property="og:description"]')?.getAttribute("content") || "";
    const result2 = new LoadContentResultHTMLImpl({
      content: markdownContent,
      rawHtml: rawContent,
      filename: path7.basename(resolvedPath),
      relative: formatRelativePath(env, resolvedPath),
      absolute: resolvedPath,
      title: title || void 0,
      description: description || void 0
    });
    return result2;
  }
  if (options?.section) {
    if (isSectionListPattern(options.section)) {
      const level = getSectionListLevel(options.section);
      const sections = listSections(rawContent, level);
      return sections;
    }
    const sectionName = await extractSectionName(options.section, env);
    const fileContext = new LoadContentResultImpl({
      content: rawContent,
      filename: path7.basename(resolvedPath),
      relative: formatRelativePath(env, resolvedPath),
      absolute: resolvedPath
    });
    const sectionContent = await extractSection(rawContent, sectionName, options.section.renamed, fileContext, env);
    const result2 = new LoadContentResultImpl({
      content: sectionContent,
      filename: path7.basename(resolvedPath),
      relative: formatRelativePath(env, resolvedPath),
      absolute: resolvedPath,
      // Pass the full raw content so frontmatter can be parsed
      _rawContent: rawContent
    });
    return result2;
  }
  const result = new LoadContentResultImpl({
    content: rawContent,
    filename: path7.basename(resolvedPath),
    relative: formatRelativePath(env, resolvedPath),
    absolute: resolvedPath
  });
  return result;
}
__name(loadSingleFile, "loadSingleFile");
async function loadGlobPattern(pattern, options, env) {
  const relativeBase = getRelativeBasePath(env);
  let globCwd = env.getFileDirectory();
  let globPattern = pattern;
  if (pattern.startsWith("@base/")) {
    globCwd = relativeBase;
    globPattern = pattern.slice("@base/".length);
  } else if (pattern.startsWith("@root/")) {
    globCwd = relativeBase;
    globPattern = pattern.slice("@root/".length);
  } else if (path7.isAbsolute(pattern)) {
    globCwd = path7.parse(pattern).root || "/";
    globPattern = path7.relative(globCwd, pattern);
  }
  const computeRelative = /* @__PURE__ */ __name((filePath) => formatRelativePath(env, filePath), "computeRelative");
  let matches;
  try {
    matches = await glob(globPattern, {
      cwd: globCwd,
      absolute: true,
      followSymlinks: true,
      // Ignore common non-text files
      ignore: [
        "**/node_modules/**",
        "**/.git/**",
        "**/dist/**",
        "**/build/**"
      ]
    });
  } catch (globError) {
    throw globError;
  }
  matches.sort();
  const results = [];
  for (const filePath of matches) {
    try {
      const rawContent = await env.readFile(filePath);
      if (filePath.endsWith(".html") || filePath.endsWith(".htm")) {
        const markdownContent = await convertHtmlToMarkdown(rawContent, `file://${filePath}`);
        if (options?.section) {
          if (isSectionListPattern(options.section)) {
            const level = getSectionListLevel(options.section);
            const sections = listSections(markdownContent, level);
            if (sections.length > 0) {
              results.push({
                names: sections,
                file: path7.basename(filePath),
                relative: computeRelative(filePath),
                absolute: filePath
              });
            }
            continue;
          }
          const sectionName = await extractSectionName(options.section, env);
          try {
            const fileContext = new LoadContentResultImpl({
              content: rawContent,
              filename: path7.basename(filePath),
              relative: computeRelative(filePath),
              absolute: filePath
            });
            const sectionContent = await extractSection(markdownContent, sectionName, options.section.renamed, fileContext, env);
            if (options.section.renamed) {
              results.push(sectionContent);
            } else {
              const dom = new JSDOM(rawContent);
              const doc = dom.window.document;
              const title = doc.querySelector("title")?.textContent || "";
              const description = doc.querySelector('meta[name="description"]')?.getAttribute("content") || doc.querySelector('meta[property="og:description"]')?.getAttribute("content") || "";
              results.push(new LoadContentResultHTMLImpl({
                content: sectionContent,
                rawHtml: rawContent,
                filename: path7.basename(filePath),
                relative: computeRelative(filePath),
                absolute: filePath,
                title: title || void 0,
                description: description || void 0
              }));
            }
          } catch (error) {
            continue;
          }
        } else {
          const dom = new JSDOM(rawContent);
          const doc = dom.window.document;
          const title = doc.querySelector("title")?.textContent || "";
          const description = doc.querySelector('meta[name="description"]')?.getAttribute("content") || doc.querySelector('meta[property="og:description"]')?.getAttribute("content") || "";
          results.push(new LoadContentResultHTMLImpl({
            content: markdownContent,
            rawHtml: rawContent,
            filename: path7.basename(filePath),
            relative: computeRelative(filePath),
            absolute: filePath,
            title: title || void 0,
            description: description || void 0
          }));
        }
      } else {
        if (options?.section) {
          if (isSectionListPattern(options.section)) {
            const level = getSectionListLevel(options.section);
            const sections = listSections(rawContent, level);
            if (sections.length > 0) {
              results.push({
                names: sections,
                file: path7.basename(filePath),
                relative: computeRelative(filePath),
                absolute: filePath
              });
            }
            continue;
          }
          const sectionName = await extractSectionName(options.section, env);
          try {
            const fileContext = new LoadContentResultImpl({
              content: rawContent,
              filename: path7.basename(filePath),
              relative: computeRelative(filePath),
              absolute: filePath
            });
            const sectionContent = await extractSection(rawContent, sectionName, options.section.renamed, fileContext, env);
            if (options.section.renamed) {
              results.push(sectionContent);
            } else {
              results.push(new LoadContentResultImpl({
                content: sectionContent,
                filename: path7.basename(filePath),
                relative: computeRelative(filePath),
                absolute: filePath,
                _rawContent: rawContent
              }));
            }
          } catch (error) {
            continue;
          }
        } else {
          results.push(new LoadContentResultImpl({
            content: rawContent,
            filename: path7.basename(filePath),
            relative: computeRelative(filePath),
            absolute: filePath
          }));
        }
      }
    } catch (error) {
      continue;
    }
  }
  return results;
}
__name(loadGlobPattern, "loadGlobPattern");
async function reconstructPath(pathNode, env) {
  if (!pathNode.segments || !Array.isArray(pathNode.segments)) {
    return (pathNode.raw || "").trim();
  }
  const hasVariables = pathNode.segments.some((seg) => seg.type === "VariableReference");
  if (hasVariables) {
    const interpolated = await interpolateAndRecord5(pathNode.segments, env);
    return interpolated.trim();
  }
  const reconstructed = pathNode.segments.map((segment) => {
    if (segment.type === "Text") {
      return segment.content;
    } else if (segment.type === "PathSeparator") {
      return segment.value;
    }
    return "";
  }).join("");
  return reconstructed.trim();
}
__name(reconstructPath, "reconstructPath");
function reconstructUrl(urlNode) {
  if (urlNode.raw) {
    return urlNode.raw;
  }
  const { protocol, host, path: path10 } = urlNode;
  return `${protocol}://${host}${path10 || ""}`;
}
__name(reconstructUrl, "reconstructUrl");
function isSectionListPattern(sectionNode) {
  return sectionNode?.identifier?.type === "section-list";
}
__name(isSectionListPattern, "isSectionListPattern");
function getSectionListLevel(sectionNode) {
  return sectionNode?.identifier?.level ?? 0;
}
__name(getSectionListLevel, "getSectionListLevel");
async function extractSectionName(sectionNode, env) {
  if (!sectionNode || !sectionNode.identifier) {
    throw new MlldError("Invalid section node", {
      node: sectionNode
    });
  }
  const identifier = sectionNode.identifier;
  if (identifier.type === "section-list") {
    throw new MlldError("Section list patterns (??) should be handled separately", {
      identifierType: identifier.type
    });
  }
  if (identifier.type === "Text") {
    return identifier.content;
  } else if (identifier.type === "VariableReference") {
    return await interpolateAndRecord5([
      identifier
    ], env);
  } else if (Array.isArray(identifier)) {
    return await interpolateAndRecord5(identifier, env);
  }
  throw new MlldError("Unable to extract section name", {
    identifierType: identifier.type
  });
}
__name(extractSectionName, "extractSectionName");
async function extractSection(content, sectionName, renamedTitle, fileContext, env) {
  try {
    let extracted;
    try {
      extracted = await llmxmlInstance.getSection(content, sectionName, {
        includeNested: true
      });
    } catch (llmxmlError) {
      throw llmxmlError;
    }
    if (!extracted) {
      throw new MlldError(`Section "${sectionName}" not found in content`, {
        sectionName,
        availableSections: await getAvailableSections(content)
      });
    }
    if (renamedTitle) {
      let finalTitle;
      if (typeof renamedTitle === "object" && renamedTitle.type === "rename-template") {
        if (!fileContext) {
          throw new MlldError("File context required for template interpolation in rename", {
            sectionName
          });
        }
        const processedParts = [];
        for (const part of renamedTitle.parts || []) {
          if (part.type === "FileReference" && part.source?.type === "placeholder") {
            if (part.fields && part.fields.length > 0) {
              let value = fileContext;
              for (const field of part.fields) {
                if (value && typeof value === "object") {
                  value = value[field.value];
                } else {
                  value = void 0;
                  break;
                }
              }
              processedParts.push({
                type: "Text",
                content: value !== void 0 ? String(value) : ""
              });
            } else {
              const lines = extracted.split("\n");
              let contentWithoutHeader = extracted;
              if (lines.length > 0 && lines[0].match(/^#+\s/)) {
                contentWithoutHeader = lines.slice(1).join("\n").trim();
              }
              processedParts.push({
                type: "Text",
                content: contentWithoutHeader
              });
            }
          } else {
            processedParts.push(part);
          }
        }
        if (!env) {
          throw new MlldError("Environment required for template interpolation", {
            sectionName
          });
        }
        finalTitle = await interpolateAndRecord5(processedParts, env);
      } else {
        finalTitle = renamedTitle;
      }
      const { applyHeaderTransform: applyHeaderTransform2 } = await import('./show-5RN42ZAU.mjs');
      return applyHeaderTransform2(extracted, finalTitle);
    }
    return extracted;
  } catch (error) {
    throw new MlldError(`Failed to extract section: ${error.message}`, {
      sectionName,
      error: error.message
    });
  }
}
__name(extractSection, "extractSection");
async function getAvailableSections(content) {
  try {
    const headings = await llmxmlInstance.getHeadings(content);
    return headings.map((h) => h.title);
  } catch {
    const sections = [];
    const lines = content.split("\n");
    for (const line of lines) {
      const match = line.match(/^#+\s+(.+)$/);
      if (match) {
        sections.push(match[1]);
      }
    }
    return sections;
  }
}
__name(getAvailableSections, "getAvailableSections");
function listSections(content, level) {
  const lines = content.split("\n");
  const headings = [];
  for (const line of lines) {
    const match = line.match(/^(#{1,6})\s+(.+)$/);
    if (match) {
      const headingLevel = match[1].length;
      const title = match[2].trim();
      if (level === void 0 || level === 0 || headingLevel === level) {
        headings.push(title);
      }
    }
  }
  return headings;
}
__name(listSections, "listSections");
async function convertHtmlToMarkdown(html, url) {
  try {
    const dom = new JSDOM(html, {
      url
    });
    const reader = new Readability(dom.window.document);
    const article = reader.parse();
    if (!article) {
      const turndownService2 = new TurndownService({
        headingStyle: "atx",
        codeBlockStyle: "fenced",
        bulletListMarker: "-",
        emDelimiter: "*",
        strongDelimiter: "**"
      });
      return turndownService2.turndown(html);
    }
    const turndownService = new TurndownService({
      headingStyle: "atx",
      codeBlockStyle: "fenced",
      bulletListMarker: "-",
      emDelimiter: "*",
      strongDelimiter: "**"
    });
    let markdown = "";
    if (article.title) {
      markdown += `# ${article.title}

`;
    }
    if (article.byline) {
      markdown += `*By ${article.byline}*

`;
    }
    markdown += turndownService.turndown(article.content);
    return markdown;
  } catch (error) {
    console.warn("Failed to convert HTML to Markdown:", error);
    return html;
  }
}
__name(convertHtmlToMarkdown, "convertHtmlToMarkdown");
async function applyTransformToResults(results, transform, env) {
  const transformed = [];
  for (const result of results) {
    const childEnv = env.createChild();
    ({
      // Make the LoadContentResult properties available
      fm: result.fm,
      content: result.content,
      filename: result.filename,
      relative: result.relative,
      absolute: result.absolute
    });
    const templateParts = transform.parts || [];
    const processedParts = [];
    for (const part of templateParts) {
      const isPlaceholder = part.type === "placeholder" || part.type === "FileReference" && part.source?.type === "placeholder";
      if (isPlaceholder) {
        if (part.fields && part.fields.length > 0) {
          let value = result;
          for (const field of part.fields) {
            if (value && typeof value === "object") {
              const fieldName = field.value;
              if (fieldName === "mx" && typeof value.mx === "object") {
                value = value.mx;
              } else {
                value = value[fieldName];
              }
            } else {
              value = void 0;
              break;
            }
          }
          processedParts.push({
            type: "Text",
            content: value !== void 0 ? String(value) : ""
          });
        } else {
          processedParts.push({
            type: "Text",
            content: result.content
          });
        }
      } else {
        processedParts.push(part);
      }
    }
    const transformedContent = await interpolateAndRecord5(processedParts, childEnv);
    transformed.push(transformedContent);
  }
  return transformed;
}
__name(applyTransformToResults, "applyTransformToResults");
async function applyTemplateToAstResults(results, transform, env) {
  const transformed = [];
  for (const result of results) {
    const templateParts = transform.parts || [];
    const processedParts = [];
    for (const part of templateParts) {
      if (part.type === "placeholder") {
        if (!result) {
          processedParts.push({
            type: "Text",
            content: ""
          });
          continue;
        }
        if (part.fields && part.fields.length > 0) {
          let value = result;
          for (const field of part.fields) {
            if (value && typeof value === "object") {
              value = value[field.value];
            } else {
              value = void 0;
              break;
            }
          }
          processedParts.push({
            type: "Text",
            content: value !== void 0 && value !== null ? String(value) : ""
          });
        } else {
          processedParts.push({
            type: "Text",
            content: result.code ?? ""
          });
        }
      } else {
        processedParts.push(part);
      }
    }
    const childEnv = env.createChild();
    const transformedContent = await interpolateAndRecord5(processedParts, childEnv);
    transformed.push(transformedContent);
  }
  return transformed;
}
__name(applyTemplateToAstResults, "applyTemplateToAstResults");
function finalizeLoaderResult(value, options) {
  if (isLoadContentResult(value)) {
    return wrapLoadContentValue(value);
  }
  if (isStructuredValue(value)) {
    const metadata2 = mergeMetadata(value.metadata, options?.metadata);
    if (!options?.type && !options?.text && (!metadata2 || metadata2 === value.metadata)) {
      return value;
    }
    return wrapStructured(value, options?.type, options?.text, metadata2);
  }
  const inferredType = options?.type ?? inferLoaderType(value);
  const text = options?.text ?? deriveLoaderText(value, inferredType);
  const metadata = mergeMetadata(void 0, options?.metadata);
  return ensureStructuredValue(value, inferredType, text, metadata);
}
__name(finalizeLoaderResult, "finalizeLoaderResult");
function inferLoaderType(value) {
  if (typeof value === "string") {
    return "text";
  }
  if (Array.isArray(value)) {
    return "array";
  }
  return "object";
}
__name(inferLoaderType, "inferLoaderType");
function deriveLoaderText(value, type) {
  if (type === "text") {
    return typeof value === "string" ? value : String(value ?? "");
  }
  if (type === "array") {
    if (Array.isArray(value)) {
      if (value.length > 0 && isLoadContentResult(value[0])) {
        return value.map((item) => item.content ?? "").join("\n\n");
      }
      return value.map((item) => String(item)).join("\n\n");
    }
    return String(value ?? "");
  }
  if (type === "object" && value && typeof value === "object" && "content" in value && typeof value.content === "string") {
    return value.content;
  }
  try {
    return JSON.stringify(value);
  } catch {
    return String(value ?? "");
  }
}
__name(deriveLoaderText, "deriveLoaderText");
function mergeMetadata(base, extra) {
  const baseSecurity = base?.security;
  const extraSecurity = extra?.security;
  const mergedSecurity = baseSecurity && extraSecurity ? mergeDescriptors(baseSecurity, extraSecurity) : baseSecurity ?? extraSecurity;
  const merged = {
    source: "load-content",
    ...base || {},
    ...extra || {}
  };
  if (mergedSecurity) {
    merged.security = mergedSecurity;
  }
  return merged;
}
__name(mergeMetadata, "mergeMetadata");

// interpreter/eval/data-values/LoadContentEvaluator.ts
var _LoadContentEvaluator = class _LoadContentEvaluator {
  /**
  * Checks if this evaluator can handle the given data value
  */
  canHandle(value) {
    return value && typeof value === "object" && value.type === "load-content";
  }
  /**
  * Evaluates load-content expressions to load file or URL content
  */
  async evaluate(value, env) {
    if (!this.canHandle(value)) {
      throw new Error(`LoadContentEvaluator cannot handle value type: ${value?.type || typeof value}`);
    }
    const result = await processContentLoader(value, env);
    const structured = wrapLoadContentValue(result);
    return structured;
  }
};
__name(_LoadContentEvaluator, "LoadContentEvaluator");
var LoadContentEvaluator = _LoadContentEvaluator;

// interpreter/eval/data-values/DataValueEvaluator.ts
var _DataValueEvaluator = class _DataValueEvaluator {
  constructor() {
    __publicField(this, "stateManager");
    __publicField(this, "primitiveEvaluator");
    __publicField(this, "collectionEvaluator");
    __publicField(this, "variableReferenceEvaluator");
    __publicField(this, "foreachCommandEvaluator");
    __publicField(this, "foreachSectionEvaluator");
    __publicField(this, "loadContentEvaluator");
    this.stateManager = new EvaluationStateManager();
    this.primitiveEvaluator = new PrimitiveEvaluator(this.stateManager);
    this.collectionEvaluator = new CollectionEvaluator(this.evaluate.bind(this));
    this.variableReferenceEvaluator = new VariableReferenceEvaluator(this.evaluate.bind(this));
    this.foreachCommandEvaluator = new ForeachCommandEvaluator();
    this.foreachSectionEvaluator = new ForeachSectionEvaluator(this.evaluate.bind(this));
    this.loadContentEvaluator = new LoadContentEvaluator();
  }
  /**
  * Evaluates a DataValue, recursively evaluating any embedded directives,
  * variable references, or templates.
  * 
  * @param value The data value to evaluate
  * @param env The evaluation environment
  * @returns The evaluated result
  */
  async evaluate(value, env, options) {
    try {
      if (this.primitiveEvaluator.canHandle(value)) {
        return await this.primitiveEvaluator.evaluate(value, env);
      }
      if (this.collectionEvaluator.canHandle(value)) {
        const result = await this.collectionEvaluator.evaluate(value, env);
        return result;
      }
      if (this.variableReferenceEvaluator.canHandle(value)) {
        return await this.variableReferenceEvaluator.evaluate(value, env);
      }
      if (this.foreachCommandEvaluator.canHandle(value)) {
        return await this.foreachCommandEvaluator.evaluate(value, env);
      }
      if (this.foreachSectionEvaluator.canHandle(value)) {
        return await this.foreachSectionEvaluator.evaluate(value, env);
      }
      if (this.loadContentEvaluator.canHandle(value)) {
        return await this.loadContentEvaluator.evaluate(value, env);
      }
      logger.warn("Unexpected value type in DataValueEvaluator:", {
        value
      });
      return value;
    } catch (error) {
      const valueTypeField = typeof value === "object" ? value?.type : void 0;
      const identifier = typeof value === "object" ? value?.identifier : void 0;
      let contextHint = "";
      if (identifier) {
        contextHint = ` (evaluating @${identifier})`;
      } else if (valueTypeField) {
        contextHint = ` (evaluating ${valueTypeField})`;
      }
      const originalMessage = error instanceof Error ? error.message : String(error);
      if (originalMessage && originalMessage.length > 0 && !originalMessage.includes("undefined")) {
        throw error;
      }
      const wrappedError = new Error(`Data evaluation failed${contextHint}: ${originalMessage || "unknown error"}`);
      if (error instanceof Error) {
        wrappedError.stack = error.stack;
        wrappedError.cause = error;
      }
      throw wrappedError;
    }
  }
  /**
  * Gets the state manager for external access (if needed for testing)
  */
  getStateManager() {
    return this.stateManager;
  }
  /**
  * Gets evaluator statistics for monitoring and debugging
  */
  getEvaluatorStats() {
    const cacheStats = this.stateManager.getCacheStats();
    return {
      cacheSize: cacheStats.size,
      cacheEntries: cacheStats.entries,
      evaluatorTypes: [
        "PrimitiveEvaluator",
        "CollectionEvaluator",
        "VariableReferenceEvaluator",
        "ForeachCommandEvaluator",
        "ForeachSectionEvaluator"
      ]
    };
  }
};
__name(_DataValueEvaluator, "DataValueEvaluator");
var DataValueEvaluator = _DataValueEvaluator;

// interpreter/eval/data-value-evaluator.ts
var dataValueEvaluator = new DataValueEvaluator();
function getDataValueEvaluator() {
  return dataValueEvaluator;
}
__name(getDataValueEvaluator, "getDataValueEvaluator");
function getEvaluatorStats() {
  return dataValueEvaluator.getEvaluatorStats();
}
__name(getEvaluatorStats, "getEvaluatorStats");
async function evaluateDataValue(value, env, options) {
  return await dataValueEvaluator.evaluate(value, env, options);
}
__name(evaluateDataValue, "evaluateDataValue");
function isFullyEvaluated(value) {
  if (isPrimitiveValue(value)) {
    return true;
  }
  if (isDirectiveValue(value)) {
    const stateManager = dataValueEvaluator.getStateManager();
    const cached = stateManager.getCachedResult(value);
    return cached?.hit === true;
  }
  if (isVariableReferenceValue(value) || isTemplateValue(value)) {
    return false;
  }
  if (value?.type === "object") {
    return Object.values(value.properties).every(isFullyEvaluated);
  }
  if (value?.type === "array") {
    return value.items.every(isFullyEvaluated);
  }
  return true;
}
__name(isFullyEvaluated, "isFullyEvaluated");
function hasUnevaluatedDirectives(value) {
  if (isPrimitiveValue(value)) {
    return false;
  }
  if (value?.type === "Directive") {
    return true;
  }
  if (value && typeof value === "object" && value.type === "foreach") {
    return true;
  }
  if (value && typeof value === "object" && value.type === "ExecInvocation") {
    return true;
  }
  if (value && typeof value === "object" && value.type === "command" && "command" in value) {
    return true;
  }
  if (value && typeof value === "object" && "wrapperType" in value && "content" in value && Array.isArray(value.content)) {
    return true;
  }
  if (Array.isArray(value)) {
    return value.some(hasUnevaluatedDirectives);
  }
  if (value?.type === "array" && "items" in value) {
    return value.items.some(hasUnevaluatedDirectives);
  }
  if (value?.type === "object" && "properties" in value) {
    return Object.values(value.properties).some(hasUnevaluatedDirectives);
  }
  if (typeof value === "object" && value !== null && !value.type) {
    return Object.values(value).some(hasUnevaluatedDirectives);
  }
  return false;
}
__name(hasUnevaluatedDirectives, "hasUnevaluatedDirectives");
function collectEvaluationErrors(value, path10 = "") {
  const errors = {};
  if (value?.__error) {
    errors[path10] = new Error(value.__message);
    return errors;
  }
  if (typeof value === "object" && value !== null) {
    for (const [key, propValue] of Object.entries(value)) {
      const propPath = path10 ? `${path10}.${key}` : key;
      Object.assign(errors, collectEvaluationErrors(propValue, propPath));
    }
  }
  if (Array.isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      const elemPath = `${path10}[${i}]`;
      Object.assign(errors, collectEvaluationErrors(value[i], elemPath));
    }
  }
  return errors;
}
__name(collectEvaluationErrors, "collectEvaluationErrors");
function mergeInterpolatedDescriptors(env, descriptors) {
  if (descriptors.length === 0) {
    return void 0;
  }
  return descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
}
__name(mergeInterpolatedDescriptors, "mergeInterpolatedDescriptors");
async function interpolateAndRecord6(nodes, env, context2 = InterpolationContext.Default) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  const merged = mergeInterpolatedDescriptors(env, descriptors);
  if (merged) {
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord6, "interpolateAndRecord");
async function evaluateOutput(directive, env, context2) {
  if (env.getIsImporting()) {
    return {
      value: null,
      env
    };
  }
  const hasSource = directive.meta?.hasSource;
  const sourceType = directive.meta?.sourceType;
  const targetType = directive.meta?.targetType || "file";
  const format = directive.meta?.format;
  directive.meta?.securityLabels || directive.values?.securityLabels;
  try {
    let content;
    let descriptorSource;
    if (!hasSource) {
      const effectHandler = env.getEffectHandler();
      if (effectHandler && typeof effectHandler.getDocument === "function") {
        content = effectHandler.getDocument();
        descriptorSource = content;
      } else {
        try {
          const nodes = env.getNodes();
          const { formatOutput } = await import('./formatter-J7JYQSZR.mjs');
          content = await formatOutput(nodes, {
            format: format || "markdown",
            variables: env.getAllVariables()
          });
          descriptorSource = content;
        } catch (formatError) {
          if (env.hasVariable("DEBUG")) {
            const debug = env.getVariable("DEBUG");
            if (debug && debug.value) {
              logger.error("Output format error", {
                error: formatError.message
              });
            }
          }
          throw formatError;
        }
      }
    } else {
      const sourceResult = await evaluateOutputSource(directive, env, sourceType, context2);
      content = sourceResult.text;
      descriptorSource = sourceResult.rawValue;
    }
    if (format) {
      content = await applyOutputFormat(content, format, env);
    }
    const materializedContent = materializeDisplayValue(descriptorSource ?? content, void 0, descriptorSource ?? content, content);
    content = materializedContent.text;
    if (materializedContent.descriptor) {
      env.recordSecurityDescriptor(materializedContent.descriptor);
    }
    const resolvedValue = resolveNestedValue(descriptorSource ?? content, {
      preserveProvenance: true
    });
    const snapshot = env.getSecuritySnapshot();
    const securityDescriptor = materializedContent.descriptor ?? (snapshot ? makeSecurityDescriptor({
      labels: snapshot.labels,
      taint: snapshot.taint,
      sources: snapshot.sources,
      policyContext: snapshot.policy
    }) : void 0);
    let target;
    if (directive.values.target) {
      target = directive.values.target;
    } else if (directive.values.path) {
      target = {
        type: "file",
        path: directive.values.path,
        raw: directive.raw?.path || "",
        meta: {
          bracketed: true
        }
      };
    } else {
      throw new MlldOutputError("No target specified for output directive", "unknown", {
        sourceLocation: directive.location,
        env
      });
    }
    if (targetType === "file") {
      const rawTarget = typeof target?.raw === "string" ? target.raw.replace(/^["']|["']$/g, "") : "";
      if (rawTarget.startsWith("state://")) {
        const statePath = rawTarget.replace(/^state:\/\//, "");
        env.recordStateWrite({
          path: statePath,
          value: content,
          operation: "set",
          security: securityDescriptor ?? makeSecurityDescriptor()
        });
      } else {
        await outputToFile(target, content, env, directive, resolvedValue, securityDescriptor);
      }
    } else if (targetType === "stream") {
      await outputToStream(target, content, env);
    } else if (targetType === "env") {
      await outputToEnv(target, content, env, hasSource ? directive.values.source : null);
    } else if (targetType === "resolver") {
      await outputToResolver(target, content, env, directive);
    } else {
      throw new MlldOutputError(`Unknown target type: ${targetType}`, "unknown", {
        location: directive.location
      });
    }
    env.hasExplicitOutput = true;
    return {
      value: "",
      env
    };
  } catch (error) {
    if (env.hasVariable("DEBUG")) {
      const debug = env.getVariable("DEBUG");
      if (debug && debug.value) {
        logger.error("Output directive error", {
          error: error.message,
          stack: error.stack
        });
      }
    }
    if (error instanceof Error) {
      throw new MlldOutputError(`Failed to process output: ${error.message}`, format || "unknown", {
        sourceLocation: directive.location,
        env,
        cause: error
      });
    }
    throw error;
  }
}
__name(evaluateOutput, "evaluateOutput");
async function evaluateOutputSource(directive, env, sourceType, context2) {
  switch (sourceType) {
    case "literal":
      const source = directive.values.source;
      if (Array.isArray(source)) {
        const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
        const text = await interpolateAndRecord6(source, env);
        return {
          rawValue: text,
          text
        };
      }
      console.warn("Unexpected literal source format:", source);
      const fallback = String(source);
      return {
        rawValue: fallback,
        text: fallback
      };
    case "variable":
      return await evaluateVariableSource(directive, env, context2);
    case "command":
      return await evaluateCommandSource(directive, env);
    case "exec":
    case "execInvocation":
      return await evaluateExecSource(directive, env);
    default:
      throw new MlldOutputError(`Unknown source type: ${sourceType}`, "unknown", {
        sourceLocation: directive.location,
        env
      });
  }
}
__name(evaluateOutputSource, "evaluateOutputSource");
async function evaluateVariableSource(directive, env, context2) {
  const source = directive.values.source;
  const hasArgs = source.args && Array.isArray(source.args) && source.args.length > 0;
  if (hasArgs || directive.subtype === "outputInvocation" || directive.subtype === "outputExecInvocation") {
    return await evaluateInvocationSource(directive, env, context2);
  } else {
    return await evaluateSimpleVariableSource(directive, env, context2);
  }
}
__name(evaluateVariableSource, "evaluateVariableSource");
async function evaluateInvocationSource(directive, env, context2) {
  const identifierNodes = directive.values.source.identifier;
  const varName = identifierNodes && Array.isArray(identifierNodes) && identifierNodes[0]?.identifier ? identifierNodes[0].identifier : void 0;
  if (!varName) {
    throw new MlldOutputError(`Invalid variable reference in output directive`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  const args = directive.values.source.args || [];
  const variable = findExtractedVariable(context2, varName) ?? env.getVariable(varName);
  if (!variable) {
    throw new MlldOutputError(`Variable ${varName} not found`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  if (args.length > 0) {
    const execNode = {
      type: "ExecInvocation",
      commandRef: {
        name: varName,
        identifier: [
          {
            type: "Text",
            content: varName
          }
        ],
        args
      },
      withClause: null
    };
    const result = await resolveDirectiveExecInvocation(directive, env, execNode);
    const text = String(result.value ?? "");
    return {
      rawValue: result.value,
      text
    };
  } else if (isTextLike(variable)) {
    const templateContent = variable.value;
    const childEnv = env.createChild();
    const text = await interpolateAndRecord6(templateContent, childEnv);
    return {
      rawValue: text,
      text
    };
  } else if (isExecutable(variable)) {
    const definition = variable.value;
    const childEnv = env.createChild();
    const params = definition.paramNames || [];
    if (params.length > 0) {
      for (let i = 0; i < params.length && i < args.length; i++) {
        const paramName = params[i];
        const argValue = await evaluateDataValue(args[i], env);
        const paramVar = createSimpleTextVariable(paramName, String(argValue), {
          directive: "var",
          syntax: "quoted",
          hasInterpolation: false,
          isMultiLine: false
        }, {
          internal: {
            isSystem: true,
            isParameter: true
          }
        });
        childEnv.set(paramName, paramVar);
      }
    }
    let result;
    if (definition.type === "template") {
      const templateResult = await interpolateAndRecord6(definition.template, childEnv);
      result = templateResult;
    } else if (definition.type === "command") {
      const command = await interpolateAndRecord6(definition.commandTemplate, childEnv);
      result = await childEnv.executeCommand(command);
    } else if (definition.type === "code") {
      const code = await interpolateAndRecord6(definition.codeTemplate, childEnv);
      result = await childEnv.executeCode(code, definition.language || "javascript");
    } else {
      throw new MlldOutputError(`Unsupported executable type: ${definition.type}`, "unknown", {
        sourceLocation: directive.location,
        env
      });
    }
    const text = String(result ?? "");
    return {
      rawValue: result,
      text
    };
  } else {
    throw new MlldOutputError(`Variable ${varName} is not a template or executable`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
}
__name(evaluateInvocationSource, "evaluateInvocationSource");
async function evaluateSimpleVariableSource(directive, env, context2) {
  let varName;
  if (directive.values.source.identifier) {
    const identifierNodes = directive.values.source.identifier;
    varName = identifierNodes && Array.isArray(identifierNodes) && identifierNodes[0]?.identifier ? identifierNodes[0].identifier : void 0;
  } else if (Array.isArray(directive.values.source) && directive.values.source[0]?.type === "VariableReference") {
    varName = directive.values.source[0].identifier;
  } else if (Array.isArray(directive.values.source) && directive.values.source[0]?.type === "Text") {
    const parts = directive.values.source;
    const { interpolate: interpolate2 } = await import('./interpreter-MW7QI3FC.mjs');
    return await interpolateAndRecord6(parts, env);
  } else {
    throw new MlldOutputError("Invalid source structure for variable output", "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  const variable = findExtractedVariable(context2, varName) ?? env.getVariable(varName);
  if (!variable) {
    throw new MlldOutputError(`Variable ${varName} not found`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  let value;
  if (isTextLike(variable)) {
    value = variable.value;
  } else if ("value" in variable) {
    const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
    value = await extractVariableValue2(variable, env);
  } else {
    throw new MlldOutputError(`Cannot output variable ${varName} - unknown variable type`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  let structuredWrapper = null;
  if (isStructuredValue(value)) {
    structuredWrapper = value;
    value = value.data;
  }
  const sourceFields = directive.values.source.fields;
  if (sourceFields && sourceFields.length > 0) {
    for (const field of sourceFields) {
      if (value === null || value === void 0) {
        throw new MlldOutputError(`Cannot access field on null or undefined value`, directive.location);
      }
      if (field.type === "arrayIndex") {
        const index = Number(field.value);
        if (Array.isArray(value)) {
          value = value[index];
        } else {
          throw new MlldOutputError(`Cannot index non-array value with [${index}]`, directive.location);
        }
      } else if (field.type === "field" || field.type === "stringIndex" || field.type === "numericField" || field.type === "dot") {
        const fieldName = String(field.value);
        if (typeof value === "object" && value !== null) {
          value = value[fieldName];
        } else {
          throw new MlldOutputError(`Cannot access property '${fieldName}' on non-object value`, directive.location);
        }
      }
    }
  }
  if (structuredWrapper && (!sourceFields || sourceFields.length === 0)) {
    return {
      rawValue: structuredWrapper,
      text: structuredWrapper.text
    };
  }
  const rawValue = value;
  if (typeof value === "string") {
    return {
      rawValue,
      text: value
    };
  } else if (isStructuredValue(value)) {
    const text = asText(value);
    return {
      rawValue: value,
      text
    };
  } else if (typeof value === "object") {
    const text = JSON.stringify(value, null, 2);
    return {
      rawValue,
      text
    };
  } else {
    const text = String(value || "");
    return {
      rawValue,
      text
    };
  }
}
__name(evaluateSimpleVariableSource, "evaluateSimpleVariableSource");
function findExtractedVariable(context2, name) {
  if (!context2?.extractedInputs || !name) {
    return void 0;
  }
  for (const candidate of context2.extractedInputs) {
    if (candidate && typeof candidate === "object" && "name" in candidate && candidate.name === name) {
      return candidate;
    }
  }
  return void 0;
}
__name(findExtractedVariable, "findExtractedVariable");
async function evaluateCommandSource(directive, env) {
  const cmdName = directive.values.source.identifier[0].identifier;
  const cmdArgs = directive.values.source.args || [];
  const cmdVariable = env.getVariable(cmdName);
  if (!isCommandVariable(cmdVariable)) {
    throw new MlldOutputError(`Variable ${cmdName} is not a command`, directive.location);
  }
  const cmdChildEnv = env.createChild();
  if (cmdVariable.params && cmdVariable.params.length > 0) {
    for (let i = 0; i < cmdVariable.params.length && i < cmdArgs.length; i++) {
      const paramName = cmdVariable.params[i];
      const argValue = await evaluateDataValue(cmdArgs[i], env);
      const paramVar = createSimpleTextVariable(paramName, String(argValue), {
        directive: "var",
        syntax: "quoted",
        hasInterpolation: false,
        isMultiLine: false
      }, {
        internal: {
          isSystem: true,
          isParameter: true
        }
      });
      cmdChildEnv.setParameterVariable(paramName, paramVar);
    }
  }
  const cmdResult = await evaluate2(cmdVariable.value, cmdChildEnv);
  const text = String(cmdResult.value ?? "");
  return {
    rawValue: cmdResult.value,
    text
  };
}
__name(evaluateCommandSource, "evaluateCommandSource");
async function evaluateExecSource(directive, env) {
  const execInvocationNode = directive.values.source || directive.values.execInvocation;
  if (execInvocationNode && execInvocationNode.type === "ExecInvocation") {
    const result = await resolveDirectiveExecInvocation(directive, env, execInvocationNode);
    const text = String(result.value ?? "");
    return {
      rawValue: result.value,
      text
    };
  } else {
    throw new MlldOutputError(`Invalid exec invocation source`, "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
}
__name(evaluateExecSource, "evaluateExecSource");
async function outputToFile(target, content, env, directive) {
  const pathResult = await interpolateAndRecord6(target.path, env);
  let targetPath = String(pathResult);
  if (targetPath.startsWith("@base/")) {
    const projectRoot = env.getProjectRoot();
    targetPath = path7.join(projectRoot, targetPath.substring(6));
  } else if (targetPath.startsWith("@root/")) {
    const projectRoot = env.getProjectRoot();
    targetPath = path7.join(projectRoot, targetPath.substring(6));
  }
  if (!path7.isAbsolute(targetPath)) {
    targetPath = path7.resolve(env.getBasePath(), targetPath);
  }
  const fileSystem = env.fileSystem;
  if (!fileSystem) {
    throw new MlldOutputError("File system not available", "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  const dirPath = path7.dirname(targetPath);
  try {
    await fileSystem.mkdir(dirPath, {
      recursive: true
    });
  } catch (err) {
  }
  await fileSystem.writeFile(targetPath, content);
  env.emitEffect("file", content, {
    path: targetPath,
    source: directive.location
  });
}
__name(outputToFile, "outputToFile");
async function outputToStream(target, content, env) {
  if (target.stream === "stdout") {
    env.emitEffect("stdout", content + "\n");
  } else if (target.stream === "stderr") {
    env.emitEffect("stderr", content + "\n");
  }
}
__name(outputToStream, "outputToStream");
async function outputToEnv(target, content, env, source) {
  let varName;
  if (target.varname) {
    varName = target.varname;
  } else {
    if (source && source.identifier) {
      const identifierNodes = source.identifier;
      const sourceVarName = identifierNodes && Array.isArray(identifierNodes) && identifierNodes[0]?.identifier ? identifierNodes[0].identifier : void 0;
      varName = sourceVarName ? `MLLD_${sourceVarName.toUpperCase()}` : "MLLD_OUTPUT";
    } else {
      varName = "MLLD_OUTPUT";
    }
  }
  process.env[varName] = content;
}
__name(outputToEnv, "outputToEnv");
async function outputToResolver(target, content, env, directive) {
  const resolverManager = env.resolverManager;
  if (!resolverManager) {
    throw new MlldOutputError("Resolver manager not available", "unknown", {
      sourceLocation: directive.location,
      env
    });
  }
  const resolverPath = `@${target.resolver}/${target.path.map((p) => p.content).join("/")}`;
  const looksLikeVariable = !!env.getVariable(target.resolver);
  if (looksLikeVariable) {
    const hintQuoted = `/output @<source> to "@${target.resolver}/${target.path.map((p) => p.content).join("/")}"`;
    const hintExplain = `The target '@${target.resolver}/...' is interpreted as a resolver name, not a variable. Quote the path to interpolate variables.`;
    throw new MlldOutputError(`Unquoted variable in /output target: '@${target.resolver}' is interpreted as a resolver name
Hint: ${hintExplain}
Example: ${hintQuoted}`, "unknown", {
      sourceLocation: directive.location,
      env,
      context: {
        resolverPath
      }
    });
  }
  throw new MlldOutputError(`Resolver output not yet implemented for ${resolverPath}`, "unknown", {
    sourceLocation: directive.location,
    env
  });
}
__name(outputToResolver, "outputToResolver");
async function applyOutputFormat(content, format, env) {
  switch (format) {
    case "json":
      try {
        const parsed = JSON.parse(content);
        return JSON.stringify(parsed, null, 2);
      } catch {
        return content;
      }
    case "yaml":
      return content;
    case "text":
      return content;
    default:
      return content;
  }
}
__name(applyOutputFormat, "applyOutputFormat");

// interpreter/utils/foreach.ts
var DEFAULT_FOREACH_OPTIONS = {
  separator: "\n\n---\n\n"
};
async function evaluateForeachAsText(foreachExpression, env, options = {}) {
  let results;
  if (foreachExpression.type === "foreach-section" || foreachExpression.value && foreachExpression.value.type === "foreach-section") {
    results = await evaluateForeachSection(foreachExpression, env);
  } else {
    results = await evaluateForeachCommand(foreachExpression, env);
  }
  const normalizedResults = Array.isArray(results) ? results : isStructuredValue(results) && Array.isArray(results.data) ? results.data : [
    results
  ];
  if (normalizedResults.length === 0) {
    return "";
  }
  const finalOptions = {
    ...DEFAULT_FOREACH_OPTIONS,
    ...options
  };
  const stringResults = normalizedResults.map((result) => {
    const normalized = normalizeForeachResultValue(result);
    if (typeof normalized === "string") {
      return normalized;
    }
    if (typeof normalized === "object") {
      return JSON.stringify(normalized, null, 2);
    }
    return String(normalized);
  });
  if (finalOptions.template) {
    const templatedResults = await Promise.all(stringResults.map(async (result, index) => {
      const childEnv = env.createChild();
      const { createSimpleTextVariable: createSimpleTextVariable2, createObjectVariable: createObjectVariable2 } = await import('./variable-FNPDYIEH.mjs');
      const { VariableSource } = await import('./variable-FNPDYIEH.mjs');
      const templateSource = {
        directive: "var",
        syntax: "quoted",
        hasInterpolation: false,
        isMultiLine: false
      };
      childEnv.setVariable("result", createSimpleTextVariable2("result", result, templateSource, {
        mx: templateSource
      }));
      childEnv.setVariable("index", createObjectVariable2("index", index, false, templateSource, {
        mx: templateSource
      }));
      childEnv.setVariable("item", createSimpleTextVariable2("item", result, templateSource, {
        mx: templateSource
      }));
      const templateNodes = parseTemplateString(finalOptions.template);
      const descriptors = [];
      const interpolated = await interpolate(templateNodes, childEnv, void 0, {
        collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
          if (descriptor) {
            descriptors.push(descriptor);
          }
        }, "collectSecurityDescriptor")
      });
      if (descriptors.length > 0) {
        const merged = descriptors.length === 1 ? descriptors[0] : childEnv.mergeSecurityDescriptors(...descriptors);
        childEnv.recordSecurityDescriptor(merged);
      }
      return interpolated;
    }));
    return templatedResults.join(finalOptions.separator);
  }
  return stringResults.join(finalOptions.separator);
}
__name(evaluateForeachAsText, "evaluateForeachAsText");
function parseTemplateString(template) {
  const nodes = [];
  let current = "";
  let i = 0;
  while (i < template.length) {
    if (template[i] === "{" && template[i + 1] === "{") {
      if (current) {
        nodes.push({
          type: "Text",
          nodeId: "",
          content: current,
          location: {
            start: {
              offset: 0,
              line: 1,
              column: 1
            },
            end: {
              offset: 0,
              line: 1,
              column: 1
            }
          }
        });
        current = "";
      }
      i += 2;
      let varName = "";
      while (i < template.length && !(template[i] === "}" && template[i + 1] === "}")) {
        varName += template[i];
        i++;
      }
      if (i < template.length) {
        nodes.push({
          type: "VariableReference",
          nodeId: "",
          valueType: "varIdentifier",
          identifier: varName.trim(),
          location: {
            start: {
              offset: 0,
              line: 1,
              column: 1
            },
            end: {
              offset: 0,
              line: 1,
              column: 1
            }
          }
        });
        i += 2;
      }
    } else {
      current += template[i];
      i++;
    }
  }
  if (current) {
    nodes.push({
      type: "Text",
      nodeId: "",
      content: current,
      location: {
        start: {
          offset: 0,
          line: 1,
          column: 1
        },
        end: {
          offset: 0,
          line: 1,
          column: 1
        }
      }
    });
  }
  return nodes;
}
__name(parseTemplateString, "parseTemplateString");
function parseForeachOptions(withClause) {
  const options = {};
  if (!withClause) {
    return options;
  }
  if (withClause.separator !== void 0) {
    if (typeof withClause.separator === "string") {
      options.separator = processEscapeSequences(withClause.separator);
    } else if (withClause.separator && withClause.separator.type === "Text") {
      options.separator = processEscapeSequences(withClause.separator.content);
    }
  }
  if (withClause.template !== void 0) {
    if (typeof withClause.template === "string") {
      options.template = processEscapeSequences(withClause.template);
    } else if (withClause.template && withClause.template.type === "Text") {
      options.template = processEscapeSequences(withClause.template.content);
    }
  }
  return options;
}
__name(parseForeachOptions, "parseForeachOptions");
function normalizeForeachResultValue(value) {
  if (isStructuredValue(value)) {
    return normalizeForeachResultValue(value.data);
  }
  if (Array.isArray(value)) {
    return value.map((item) => normalizeForeachResultValue(item));
  }
  if (value && typeof value === "object") {
    if (isStructuredValueLike(value)) {
      return normalizeForeachResultValue(value.data);
    }
    const entries = Object.entries(value).map(([key, entryValue]) => [
      key,
      normalizeForeachResultValue(entryValue)
    ]);
    return Object.fromEntries(entries);
  }
  if (typeof value === "string") {
    try {
      const parsed = JSON.parse(value);
      return parsed;
    } catch {
      return value;
    }
  }
  return value;
}
__name(normalizeForeachResultValue, "normalizeForeachResultValue");
function isStructuredValueLike(value) {
  if (!value || typeof value !== "object") {
    return false;
  }
  return "data" in value && "text" in value;
}
__name(isStructuredValueLike, "isStructuredValueLike");
function processEscapeSequences(str) {
  return str.replace(/\\n/g, "\n").replace(/\\t/g, "	").replace(/\\r/g, "\r").replace(/\\\\/g, "\\").replace(/\\"/g, '"').replace(/\\'/g, "'");
}
__name(processEscapeSequences, "processEscapeSequences");

// interpreter/eval/show.ts
async function evaluateShow(directive, env, context2) {
  if (env.getIsImporting()) {
    return {
      value: null,
      env
    };
  }
  if (process.env.MLLD_DEBUG === "true") ;
  let resultValue;
  let content = "";
  let skipJsonFormatting = false;
  const hasErrorMetadata = /* @__PURE__ */ __name((val) => isStructuredValue(val) && Array.isArray(val.metadata?.errors) && val.metadata?.errors?.length > 0, "hasErrorMetadata");
  const securityLabels = directive.meta?.securityLabels || directive.values?.securityLabels;
  let isStreamingShow = false;
  let interpolatedDescriptor;
  const collectInterpolatedDescriptor = /* @__PURE__ */ __name((descriptor) => {
    if (!descriptor) {
      return;
    }
    interpolatedDescriptor = interpolatedDescriptor ? env.mergeSecurityDescriptors(interpolatedDescriptor, descriptor) : descriptor;
  }, "collectInterpolatedDescriptor");
  const mergePipelineDescriptor = /* @__PURE__ */ __name((...values) => {
    const descriptors = values.filter(Boolean);
    if (descriptors.length === 0) {
      return void 0;
    }
    if (descriptors.length === 1) {
      return descriptors[0];
    }
    return env.mergeSecurityDescriptors(...descriptors);
  }, "mergePipelineDescriptor");
  const descriptorFromVariable = /* @__PURE__ */ __name((variable) => {
    if (!variable?.mx) {
      return void 0;
    }
    return varMxToSecurityDescriptor(variable.mx);
  }, "descriptorFromVariable");
  const directiveLocation = astLocationToSourceLocation(directive.location, env.getCurrentFilePath());
  if (directive.subtype === "showVariable") {
    let variableNode;
    let varName;
    if (directive.values?.invocation) {
      const invocationNode = directive.values.invocation;
      const allowedTypes = [
        "VariableReference",
        "VariableReferenceWithTail",
        "TemplateVariable"
      ];
      if (!invocationNode || !allowedTypes.includes(invocationNode.type)) {
        throw new Error("Show variable directive missing variable reference");
      }
      variableNode = invocationNode;
      if (invocationNode.type === "VariableReference") {
        varName = invocationNode.identifier;
      } else if (invocationNode.type === "VariableReferenceWithTail") {
        const innerVar = invocationNode.variable;
        if (innerVar.type === "TemplateVariable") {
          varName = innerVar.identifier;
        } else {
          varName = innerVar.identifier;
        }
      } else if (invocationNode.type === "TemplateVariable") {
        varName = invocationNode.identifier;
      }
    } else if (directive.values?.variable) {
      const legacyVariable = directive.values.variable;
      if (!legacyVariable) {
        throw new Error("Show variable directive missing variable reference");
      }
      if (Array.isArray(legacyVariable)) {
        if (legacyVariable.length === 0) {
          throw new Error("Show variable directive missing variable reference");
        }
        variableNode = legacyVariable[0];
      } else {
        variableNode = legacyVariable;
      }
      if (variableNode.type === "VariableReferenceWithTail") {
        const innerVar = variableNode.variable;
        if (innerVar.type === "TemplateVariable") {
          varName = innerVar.identifier;
        } else {
          varName = innerVar.identifier;
        }
      } else if (variableNode.type === "VariableReference") {
        varName = variableNode.identifier;
      } else if (variableNode.type === "TemplateVariable") {
        varName = variableNode.identifier;
      } else {
        throw new Error("Show variable directive missing variable reference");
      }
    } else {
      throw new Error("Show variable directive missing variable reference");
    }
    let variable;
    let value;
    let originalValue;
    let isForeachSection = false;
    if (varName === "__template__") {
      let templateContent;
      if (variableNode.type === "VariableReferenceWithTail" && variableNode.variable.type === "TemplateVariable") {
        templateContent = variableNode.variable.content;
      } else if (variableNode.type === "TemplateVariable") {
        templateContent = variableNode.content;
      }
      if (templateContent) {
        if (Array.isArray(templateContent) && templateContent.length === 1 && templateContent[0].type === "Literal") {
          value = templateContent[0].value;
        } else {
          const result = await evaluate(templateContent, env);
          value = result.value;
        }
      } else {
        value = "";
      }
    } else {
      const extractedVar = getExtractedVariable(context2, varName);
      variable = extractedVar ?? env.getVariable(varName);
      if (!variable) {
        throw new Error(`Variable not found: ${varName}`);
      }
    }
    if (value === void 0 && variable) {
      if (isTextLike(variable)) {
        value = variable.value;
        if (isTemplate(variable)) {
          if (Array.isArray(value)) {
            if (process.env.MLLD_DEBUG === "true") {
              logger.debug("Template interpolation in show", {
                variableName: variable.name,
                astArray: value
              });
            }
            value = await interpolate(value, env, void 0, {
              collectSecurityDescriptor: collectInterpolatedDescriptor
            });
            if (process.env.MLLD_DEBUG === "true") {
              logger.debug("Interpolation result:", {
                value
              });
            }
          } else if (variable.internal?.templateAst && Array.isArray(variable.internal.templateAst)) {
            value = await interpolate(variable.internal.templateAst, env, void 0, {
              collectSecurityDescriptor: collectInterpolatedDescriptor
            });
          }
        }
      } else if (isObject(variable)) {
        value = variable.value;
        originalValue = value;
        if (value && typeof value === "object" && value.type === "object" && ("properties" in value || "entries" in value)) {
          value = await evaluateDataValue(value, env);
        }
      } else if (isArray(variable)) {
        value = variable.value;
        originalValue = value;
        if (process.env.MLLD_DEBUG === "true") {
          logger.debug("show.ts: Processing array variable:", {
            varName: variable.name,
            valueType: typeof value,
            hasType: value && typeof value === "object" && "type" in value,
            typeValue: value && typeof value === "object" && value.type,
            hasItems: value && typeof value === "object" && "items" in value,
            isArray: Array.isArray(value),
            value
          });
        }
        if (value && typeof value === "object" && value.type === "array" && "items" in value) {
          value = await evaluateDataValue(value, env);
          if (process.env.MLLD_DEBUG === "true") {
            logger.debug("show.ts: After evaluation:", {
              varName: variable.name,
              value
            });
          }
        }
      } else if (isComputed(variable)) {
        value = variable.value;
      } else if (isPipelineInput(variable)) {
        assertStructuredValue(variable.value, "show:pipeline-input");
        value = asText(variable.value);
      } else if (isImported(variable)) {
        value = variable.value;
      } else if (isPath(variable)) {
        const pathValue = variable.value.resolvedPath;
        const isURL = variable.value.isURL || /^https?:\/\//.test(pathValue);
        try {
          value = await env.readFile(pathValue);
        } catch (error) {
          try {
            if (isURL) {
              const override = globalThis.__mlldFetchOverride;
              if (override) {
                const resp = await override(pathValue);
                if (resp && typeof resp.text === "function") {
                  value = await resp.text();
                } else {
                  value = String(resp);
                }
              } else {
                value = pathValue;
              }
            } else {
              value = pathValue;
            }
          } catch {
            value = pathValue;
          }
        }
      } else if (isExecutable(variable)) {
        value = `[executable: ${variable.name}]`;
      } else if (isPrimitive(variable)) {
        value = variable.value;
      } else if (isStructuredValueVariable(variable)) {
        value = variable.value;
      } else {
        throw new Error(`Unknown variable type in show evaluator: ${variable.type}`);
      }
      const fieldsToProcess = variableNode?.type === "VariableReferenceWithTail" ? variableNode.variable?.fields : variableNode?.fields;
      if (fieldsToProcess && fieldsToProcess.length > 0) {
        const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
        const { resolveVariable, ResolutionContext: ResolutionContext2 } = await import('./variable-resolution-HFG3FTZK.mjs');
        let fieldTarget = variable ? await resolveVariable(variable, env, ResolutionContext2.FieldAccess) : value;
        for (const field of fieldsToProcess) {
          if (field.type === "variableIndex") {
            const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
            const indexNode = typeof field.value === "object" ? field.value : {
              type: "VariableReference",
              valueType: "varIdentifier",
              identifier: String(field.value)
            };
            const indexValue = await evaluateDataValue2(indexNode, env);
            const resolvedField = {
              type: "bracketAccess",
              value: indexValue
            };
            const fieldResult = await accessField2(fieldTarget, resolvedField, {
              preserveContext: true,
              env,
              sourceLocation: directiveLocation
            });
            value = fieldResult.value;
          } else {
            const fieldResult = await accessField2(fieldTarget, field, {
              preserveContext: true,
              env,
              sourceLocation: directiveLocation
            });
            value = fieldResult.value;
          }
          fieldTarget = value;
          if (value === void 0) break;
        }
      }
      if (!directive?.values?.invocation) {
        if (variableNode?.type === "VariableReferenceWithTail" && variableNode.withClause?.pipeline) {
          const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
          const processed = await processPipeline2({
            value,
            env,
            node: variableNode,
            directive,
            pipeline: variableNode.withClause.pipeline,
            identifier: varName,
            location: directive.location,
            descriptorHint: mergePipelineDescriptor(descriptorFromVariable(variable), interpolatedDescriptor)
          });
          value = processed;
          if (isStructuredValue(processed)) {
            content = asText(processed);
          } else if (typeof processed === "string") {
            content = processed;
          } else {
            content = JSONFormatter.stringify(processed, {
              pretty: true
            });
          }
        }
      }
    }
    if (process.env.MLLD_DEBUG === "true" && variable) {
      logger.debug("Show variable value:", {
        varName: variable.name,
        varType: variable.type,
        valueType: typeof value,
        isObject: isObject(variable),
        valueKeys: value && typeof value === "object" ? Object.keys(value) : void 0
      });
    }
    if (!isStructuredValue(value) && hasUnevaluatedDirectives(value)) {
      value = await evaluateDataValue(value, env);
      if (originalValue && typeof originalValue === "object" && originalValue.type === "foreach-section") {
        isForeachSection = true;
      }
    }
    const { isVariable: isVariable2, resolveValue, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
    value = await resolveValue(value, env, ResolutionContext.Display);
    const hadFieldAccess = variableNode.fields && variableNode.fields.length > 0;
    const isNamespaceVariable = variable?.internal?.isNamespace && !hadFieldAccess;
    if (process.env.MLLD_DEBUG_FIX === "true" && varName === "complex") {
      try {
        fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
          source: "show-variable",
          name: varName,
          valueType: typeof value,
          isStructured: isStructuredValue(value),
          valuePreview: value && typeof value === "object" ? {
            keys: Object.keys(value).slice(0, 5),
            settings: value.config?.settings,
            dataKeys: value.data ? Object.keys(value.data) : void 0
          } : value
        }) + "\n");
      } catch {
      }
    }
    if (isNamespaceVariable && value && typeof value === "object") {
      if (process.env.DEBUG_NAMESPACE) {
        logger.debug("Cleaning namespace for display:", {
          varName: variable.name,
          hasMetadata: !!variable.internal,
          isNamespace: variable.internal?.isNamespace,
          valueKeys: Object.keys(value)
        });
      }
      content = JSONFormatter.stringifyNamespace(value);
    } else if (value && typeof value === "object" && value.__executable) {
      const params = value.paramNames || [];
      content = `<function(${params.join(", ")})>`;
    } else {
      if (isStructuredValue(value)) {
        if (hasErrorMetadata(value)) {
          content = asText(value);
          skipJsonFormatting = true;
        } else {
          content = formatForDisplay(value, {
            isForeachSection,
            pretty: true
          });
        }
      } else {
        if (Array.isArray(value) && process.env.MLLD_DEBUG === "true") {
          logger.debug("show.ts: Formatting array:", {
            varName: variable.name,
            valueLength: value.length,
            value,
            isForeachSection
          });
        }
        content = formatForDisplay(value, {
          isForeachSection,
          pretty: false
        });
      }
    }
    if (!directive?.values?.invocation) {
      if (variableNode?.type === "VariableReferenceWithTail" && variableNode.withClause?.pipeline) {
        const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
        const processed = await processPipeline2({
          value: content,
          env,
          node: variableNode,
          directive,
          pipeline: variableNode.withClause.pipeline,
          identifier: varName,
          location: directive.location,
          descriptorHint: mergePipelineDescriptor(descriptorFromVariable(variable), interpolatedDescriptor)
        });
        value = processed;
        if (isStructuredValue(processed)) {
          content = asText(processed);
        } else if (typeof processed === "string") {
          content = processed;
        } else {
          content = JSONFormatter.stringify(processed, {
            pretty: true
          });
        }
      }
    }
    try {
      const { hasPipeline } = await import('./detector-S7SBFKTT.mjs');
      const invocationNode = directive?.values?.invocation;
      if (hasPipeline(invocationNode, directive)) {
        const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
        const processed = await processPipeline2({
          value: content,
          env,
          node: invocationNode,
          directive,
          identifier: varName || "show",
          location: directive.location,
          descriptorHint: mergePipelineDescriptor(descriptorFromVariable(variable), interpolatedDescriptor)
        });
        value = processed;
        if (isStructuredValue(processed)) {
          content = asText(processed);
        } else if (typeof processed === "string") {
          content = processed;
        } else {
          content = JSONFormatter.stringify(processed, {
            pretty: true
          });
        }
      }
    } catch {
    }
    resultValue = value;
  } else if (directive.subtype === "showPath") {
    const pathValue = directive.values?.path;
    if (!pathValue) {
      throw new Error("Add path directive missing path");
    }
    let resolvedPath;
    if (typeof pathValue === "string") {
      resolvedPath = pathValue;
    } else if (Array.isArray(pathValue)) {
      resolvedPath = await interpolate(pathValue, env, void 0, {
        collectSecurityDescriptor: collectInterpolatedDescriptor
      });
    } else {
      throw new Error("Invalid path type in add directive");
    }
    if (!resolvedPath) {
      throw new Error("Add path directive resolved to empty path");
    }
    if (env.isURL(resolvedPath)) {
      content = await env.fetchURL(resolvedPath);
    } else {
      content = await env.readFile(resolvedPath);
    }
  } else if (directive.subtype === "showPathSection") {
    const sectionTitleNodes = directive.values?.sectionTitle;
    const pathValue = directive.values?.path;
    if (!sectionTitleNodes || !pathValue) {
      throw new Error("Add section directive missing section title or path");
    }
    const sectionTitle = await interpolate(sectionTitleNodes, env, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
    let resolvedPath;
    if (typeof pathValue === "string") {
      resolvedPath = pathValue;
    } else if (Array.isArray(pathValue)) {
      resolvedPath = await interpolate(pathValue, env, void 0, {
        collectSecurityDescriptor: collectInterpolatedDescriptor
      });
    } else {
      throw new Error("Invalid path type in add section directive");
    }
    let fileContent;
    if (env.isURL(resolvedPath)) {
      fileContent = await env.fetchURL(resolvedPath);
    } else {
      fileContent = await env.readFile(resolvedPath);
    }
    try {
      const titleWithoutHash = sectionTitle.replace(/^#+\s*/, "");
      content = await llmxmlInstance.getSection(fileContent, titleWithoutHash, {
        includeNested: true
      });
      content = content.trimEnd();
    } catch (error) {
      content = extractSection2(fileContent, sectionTitle);
    }
    const newTitleNodes = directive.values?.newTitle;
    if (newTitleNodes) {
      const newTitle = await interpolate(newTitleNodes, env, void 0, {
        collectSecurityDescriptor: collectInterpolatedDescriptor
      });
      const lines = content.split("\n");
      if (lines.length > 0 && lines[0].match(/^#+\s/)) {
        const newTitleTrimmed = newTitle.trim();
        const newHeadingMatch = newTitleTrimmed.match(/^(#+)(\s+(.*))?$/);
        if (newHeadingMatch) {
          if (!newHeadingMatch[3]) {
            const originalText = lines[0].replace(/^#+\s*/, "");
            lines[0] = `${newHeadingMatch[1]} ${originalText}`;
          } else {
            lines[0] = newTitleTrimmed;
          }
        } else {
          const originalLevel = lines[0].match(/^(#+)\s/)?.[1] || "#";
          lines[0] = `${originalLevel} ${newTitleTrimmed}`;
        }
        content = lines.join("\n");
      } else {
        content = newTitle + "\n" + content;
      }
    }
  } else if (directive.subtype === "showTemplate") {
    const templateNodes = directive.values?.content;
    if (!templateNodes) {
      throw new Error("Add template directive missing content");
    }
    content = await interpolate(templateNodes, env, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
    if (directive.values?.pipeline) {
      const { executePipeline } = await import('./pipeline-6P6GNLL2.mjs');
      content = await executePipeline(content, directive.values.pipeline, env);
    }
    const sectionNodes = directive.values?.section;
    if (sectionNodes && Array.isArray(sectionNodes)) {
      const section = await interpolate(sectionNodes, env, void 0, {
        collectSecurityDescriptor: collectInterpolatedDescriptor
      });
      if (section) {
        content = extractSection2(content, section);
      }
    }
  } else if (directive.subtype === "addInvocation" || directive.subtype === "showInvocation") {
    const baseInvocation = directive.values?.invocation;
    if (!baseInvocation) {
      throw new Error("Show invocation directive missing invocation");
    }
    isStreamingShow = Boolean(securityLabels?.includes("stream"));
    const invocation = isStreamingShow ? {
      ...baseInvocation,
      withClause: {
        ...baseInvocation.withClause || {},
        stream: true
      }
    } : baseInvocation;
    const commandRef = invocation.commandRef;
    if (commandRef && (commandRef.objectReference || commandRef.objectSource)) {
      const result = await resolveDirectiveExecInvocation(directive, env, invocation);
      resultValue = result.value;
      if (isStructuredValue(result.value)) {
        if (result.value.type === "array" && Array.isArray(result.value.data)) {
          const cleaned = result.value.data.map((item) => isStructuredValue(item) ? asText(item) : item);
          content = JSONFormatter.stringify(cleaned, {
            pretty: true
          });
        } else {
          content = asText(result.value);
        }
      } else if (typeof result.value === "string") {
        content = result.value;
      } else if (result.value === null || result.value === void 0) {
        content = "";
      } else if (typeof result.value === "object") {
        content = JSON.stringify(result.value);
      } else {
        content = String(result.value);
      }
    } else {
      const name = commandRef.name || commandRef.identifier?.[0]?.content;
      if (!name) {
        throw new Error("Add invocation missing name");
      }
      const extracted = getExtractedVariable(context2, name);
      const variable = extracted ?? env.getVariable(name);
      if (!variable) {
        throw new Error(`Variable not found: ${name}`);
      }
      if (isExecutable(variable)) {
        const result = await resolveDirectiveExecInvocation(directive, env, invocation);
        resultValue = result.value;
        if (isStructuredValue(result.value)) {
          if (result.value.type === "array" && Array.isArray(result.value.data)) {
            const cleaned = result.value.data.map((item) => isStructuredValue(item) ? asText(item) : item);
            content = JSONFormatter.stringify(cleaned, {
              pretty: true
            });
          } else {
            content = asText(result.value);
          }
        } else if (typeof result.value === "string") {
          content = result.value;
        } else if (result.value === null || result.value === void 0) {
          content = "";
        } else if (typeof result.value === "object") {
          content = JSON.stringify(result.value);
        } else {
          content = String(result.value);
        }
      } else {
        throw new Error(`Variable ${name} is not executable (type: ${variable.type})`);
      }
    }
  } else if (directive.subtype === "addTemplateInvocation") {
    const templateNameNodes = directive.values?.templateName;
    if (!templateNameNodes || templateNameNodes.length === 0) {
      throw new Error("Add template invocation missing template name");
    }
    const templateName = await interpolate(templateNameNodes, env, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
    const template = env.getVariable(templateName);
    if (!template || template.type !== "executable") {
      throw new Error(`Template not found: ${templateName}`);
    }
    const definition = template.value;
    if (definition.type !== "template") {
      throw new Error(`Variable ${templateName} is not a template`);
    }
    const args = directive.values?.arguments || [];
    if (args.length !== definition.paramNames.length) {
      throw new Error(`Template ${templateName} expects ${definition.paramNames.length} parameters, got ${args.length}`);
    }
    const childEnv = env.createChild();
    for (let i = 0; i < definition.paramNames.length; i++) {
      const paramName = definition.paramNames[i];
      const argValue = args[i];
      let value;
      if (typeof argValue === "object" && argValue.type === "Text") {
        value = argValue.content || "";
      } else if (typeof argValue === "object" && argValue.type === "VariableReference") {
        const varName = argValue.identifier;
        const variable2 = env.getVariable(varName);
        if (!variable2) {
          throw new Error(`Variable not found: ${varName}`);
        }
        if (isTextLike(variable2)) {
          value = variable2.value;
        } else if (isObject(variable2) || isArray(variable2)) {
          value = JSON.stringify(variable2.value);
        } else {
          value = String(variable2.value);
        }
      } else if (typeof argValue === "object" && argValue.type === "string") {
        value = argValue.value;
      } else if (typeof argValue === "object" && argValue.type === "variable") {
        const varRef = argValue.value;
        const varName = varRef.identifier;
        const variable2 = env.getVariable(varName);
        if (!variable2) {
          throw new Error(`Variable not found: ${varName}`);
        }
        if (isTextLike(variable2)) {
          value = variable2.value;
        } else if (isObject(variable2) || isArray(variable2)) {
          value = JSON.stringify(variable2.value);
        } else {
          value = String(variable2.value);
        }
      } else {
        value = String(argValue);
      }
      const source = {
        directive: "var",
        syntax: "quoted",
        hasInterpolation: false,
        isMultiLine: false
      };
      const variable = createSimpleTextVariable(paramName, value, source);
      childEnv.setParameterVariable(paramName, variable);
    }
    const templateNodes = definition.template || definition.templateContent;
    if (!templateNodes) {
      throw new Error(`Template ${templateName} has no template content`);
    }
    content = await interpolate(templateNodes, childEnv, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
  } else if (directive.subtype === "addForeach") {
    const foreachExpression = directive.values?.foreach;
    if (!foreachExpression) {
      throw new Error("Add foreach directive missing foreach expression");
    }
    const options = parseForeachOptions(foreachExpression.with);
    if (!options.separator) {
      options.separator = "\n";
    }
    content = await evaluateForeachAsText(foreachExpression, env, options);
  } else if (directive.subtype === "addExecInvocation" || directive.subtype === "showExecInvocation") {
    const execInvocation = directive.values?.execInvocation;
    if (!execInvocation) {
      throw new Error("Show exec invocation directive missing exec invocation");
    }
    const result = await resolveDirectiveExecInvocation(directive, env, execInvocation);
    resultValue = result.value;
    if (isStructuredValue(result.value)) {
      if (hasErrorMetadata(result.value)) {
        content = asText(result.value);
        skipJsonFormatting = true;
      } else {
        content = formatForDisplay(result.value, {
          pretty: false
        });
      }
    } else if (typeof result.value === "string") {
      content = result.value;
    } else if (result.value === null || result.value === void 0) {
      content = "";
    } else if (typeof result.value === "object") {
      content = JSON.stringify(result.value);
    } else {
      content = String(result.value);
    }
  } else if (directive.subtype === "showForeach") {
    const foreachExpression = directive.values?.foreach;
    if (!foreachExpression) {
      throw new Error("Show foreach directive missing foreach expression");
    }
    const options = parseForeachOptions(foreachExpression.with);
    if (!options.separator) {
      options.separator = "\n";
    }
    content = await evaluateForeachAsText(foreachExpression, env, options);
  } else if (directive.subtype === "showForeachSection") {
    const foreachExpression = directive.values?.foreach;
    if (!foreachExpression) {
      throw new Error("Add foreach section directive missing foreach expression");
    }
    const { ForeachSectionEvaluator: ForeachSectionEvaluator2 } = await import('./ForeachSectionEvaluator-6VGO6HEW.mjs');
    const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
    const foreachSectionEvaluator = new ForeachSectionEvaluator2(evaluateDataValue2);
    const result = await foreachSectionEvaluator.evaluate(foreachExpression, env);
    if (Array.isArray(result)) {
      content = result.join("\n\n");
    } else {
      content = String(result);
    }
  } else if (directive.subtype === "showLoadContent") {
    const loadContentNode = directive.values?.loadContent;
    if (!loadContentNode) {
      throw new Error("Show load content directive missing content loader");
    }
    const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
    const loadResult = await processContentLoader2(loadContentNode, env);
    if (isStructuredValue(loadResult)) {
      resultValue = loadResult;
      content = asText(loadResult);
    } else if (typeof loadResult === "string") {
      content = loadResult;
      resultValue = loadResult;
    } else {
      try {
        content = String(loadResult ?? "");
      } catch {
        content = "";
      }
    }
    const newTitleNodes = directive.values?.newTitle;
    if (newTitleNodes && loadContentNode.options?.section) {
      const newTitle = await interpolate(newTitleNodes, env, void 0, {
        collectSecurityDescriptor: collectInterpolatedDescriptor
      });
      content = applyHeaderTransform(content, newTitle);
    }
  } else if (directive.subtype === "showCommand") {
    const commandNodes = directive.values?.command;
    if (!commandNodes) {
      throw new Error("Show command directive missing command");
    }
    const { InterpolationContext: InterpolationContext2 } = await import('./interpolation-context-7G7AJPQ4.mjs');
    const command = await interpolate(commandNodes, env, InterpolationContext2.ShellCommand, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
    const executionContext = {
      sourceLocation: directiveLocation,
      directiveNode: directive,
      filePath: env.getCurrentFilePath(),
      directiveType: "show"
      // Mark as show for context
    };
    content = await env.executeCommand(command, void 0, executionContext);
    resultValue = content;
  } else if (directive.subtype === "showCode") {
    let extractRawTextContent3 = function(nodes) {
      const parts = [];
      for (const node of nodes) {
        if (node.type === "Text") {
          parts.push(node.content || "");
        } else if (node.type === "Newline") {
          parts.push("\n");
        } else {
          parts.push(String(node.value || node.content || ""));
        }
      }
      const rawContent = parts.join("");
      return rawContent.replace(/^\n/, "");
    }, dedentCommonIndent3 = function(src) {
      const lines = src.replace(/\r\n/g, "\n").split("\n");
      let minIndent = null;
      for (const line of lines) {
        if (line.trim().length === 0) continue;
        const match = line.match(/^[ \t]*/);
        const indent = match ? match[0].length : 0;
        if (minIndent === null || indent < minIndent) minIndent = indent;
        if (minIndent === 0) break;
      }
      if (!minIndent) return src;
      return lines.map((l) => l.trim().length === 0 ? "" : l.slice(minIndent)).join("\n");
    };
    __name(extractRawTextContent3, "extractRawTextContent");
    __name(dedentCommonIndent3, "dedentCommonIndent");
    const codeNodes = directive.values?.code;
    const langNodes = directive.values?.lang;
    if (!codeNodes || !langNodes) {
      throw new Error("Show code directive missing code or language");
    }
    const lang = extractRawTextContent3(langNodes);
    const code = dedentCommonIndent3(extractRawTextContent3(codeNodes));
    const executionContext = {
      sourceLocation: directiveLocation,
      directiveNode: directive,
      filePath: env.getCurrentFilePath(),
      directiveType: "show"
      // Mark as show for context
    };
    content = await env.executeCode(code, lang, {}, executionContext);
    resultValue = content;
  } else if (directive.subtype === "show" && directive.values?.content) {
    let templateNodes = directive.values.content;
    if (Array.isArray(templateNodes) && templateNodes.length === 1 && templateNodes[0].content && templateNodes[0].wrapperType) {
      templateNodes = templateNodes[0].content;
    }
    content = await interpolate(templateNodes, env, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
  } else if (directive.subtype === "showLiteral" && directive.values?.content) {
    const templateNodes = directive.values.content;
    content = await interpolate(templateNodes, env, void 0, {
      collectSecurityDescriptor: collectInterpolatedDescriptor
    });
  } else {
    throw new Error(`Unsupported show subtype: ${directive.subtype}`);
  }
  if (resultValue === void 0) {
    resultValue = content;
  }
  const tailPipeline = directive.values?.withClause?.pipeline;
  if (Array.isArray(tailPipeline) && tailPipeline.length > 0 && directive.meta?.applyTailPipeline) {
    const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
    const pipeline = tailPipeline;
    const processed = await processPipeline2({
      value: content,
      env,
      directive,
      pipeline,
      identifier: "show-tail",
      location: directive.location,
      descriptorHint: interpolatedDescriptor
    });
    resultValue = processed;
    if (isStructuredValue(processed)) {
      content = asText(processed);
    } else if (typeof processed === "string") {
      content = processed;
    } else {
      content = JSONFormatter.stringify(processed, {
        pretty: true
      });
    }
  }
  if (typeof content !== "string") {
    try {
      if (isStructuredValue(content)) {
        content = asText(content);
      } else if (Array.isArray(content)) {
        content = JSONFormatter.stringify(content, {
          pretty: true
        });
      } else if (content !== null && content !== void 0) {
        content = JSONFormatter.stringify(content, {
          pretty: true
        });
      } else {
        content = "";
      }
    } catch {
      content = String(content);
    }
  } else if (typeof content === "string" && !skipJsonFormatting) {
    const parsed = parseAndWrapJson(content, {
      preserveText: true
    });
    if (parsed && typeof parsed !== "string" && isStructuredValue(parsed)) {
      content = JSONFormatter.stringify(parsed.data, {
        pretty: true
      });
    }
  }
  if (resultValue === void 0) {
    resultValue = content;
  }
  const displayMaterialized = materializeDisplayValue(content, void 0, resultValue);
  content = displayMaterialized.text;
  const textForWrapper = content;
  if (process.env.MLLD_DEBUG_FIX === "true") {
    try {
      fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
        source: "show-final",
        invocationName: directive.values?.invocation?.commandRef?.name,
        contentType: typeof content,
        contentPreview: typeof content === "string" ? content.slice(0, 160) : content,
        resultValueType: typeof resultValue,
        resultValueIsStructured: resultValue ? resultValue[Symbol.for("mlld.StructuredValue")] === true : false,
        resultValueKeys: resultValue && typeof resultValue === "object" ? Object.keys(resultValue).slice(0, 5) : void 0
      }) + "\n");
    } catch {
    }
  }
  if (!content.endsWith("\n")) {
    content = `${content}
`;
  }
  const snapshot = env.getSecuritySnapshot();
  const resultDescriptor = mergeDescriptors(interpolatedDescriptor, displayMaterialized.descriptor, snapshot ? makeSecurityDescriptor({
    labels: snapshot.labels,
    taint: snapshot.taint,
    sources: snapshot.sources,
    policyContext: snapshot.policy ? {
      ...snapshot.policy
    } : void 0
  }) : void 0);
  if (!context2?.isExpression) {
    if (!isStreamingShow) {
      env.emitEffect("both", content, {
        source: directive.location
      });
    }
  }
  const baseValue = resultValue ?? textForWrapper;
  const wrapOptions = !isStructuredValue(baseValue) && typeof baseValue !== "string" ? {
    text: textForWrapper
  } : void 0;
  const wrapped = wrapExecResult(baseValue, wrapOptions);
  if (resultDescriptor) {
    applySecurityDescriptorToStructuredValue(wrapped, resultDescriptor);
  }
  return {
    value: wrapped,
    env
  };
}
__name(evaluateShow, "evaluateShow");
function applyHeaderTransform(content, newHeader) {
  const lines = content.split("\n");
  if (lines.length === 0) return newHeader;
  if (lines[0].match(/^#+\s/)) {
    const newHeaderTrimmed = newHeader.trim();
    const headerMatch = newHeaderTrimmed.match(/^(#+)(\s+(.*))?$/);
    if (headerMatch) {
      if (!headerMatch[3]) {
        const originalText = lines[0].replace(/^#+\s*/, "");
        lines[0] = `${headerMatch[1]} ${originalText}`;
      } else {
        lines[0] = newHeaderTrimmed;
      }
    } else {
      const originalLevel = lines[0].match(/^(#+)\s/)?.[1] || "#";
      lines[0] = `${originalLevel} ${newHeaderTrimmed}`;
    }
  } else {
    lines.unshift(newHeader);
  }
  return lines.join("\n");
}
__name(applyHeaderTransform, "applyHeaderTransform");
function extractSection2(content, sectionName) {
  const lines = content.split("\\n");
  const sectionRegex = new RegExp(`^#+\\s+${sectionName}\\s*$`, "i");
  let inSection = false;
  let sectionLevel = 0;
  const sectionLines = [];
  for (const line of lines) {
    if (!inSection && sectionRegex.test(line)) {
      inSection = true;
      sectionLevel = line.match(/^#+/)?.[0].length || 0;
      continue;
    }
    if (inSection) {
      const headerMatch = line.match(/^(#+)\\s+/);
      if (headerMatch && headerMatch[1].length <= sectionLevel) {
        break;
      }
      sectionLines.push(line);
    }
  }
  return sectionLines.join("\\n").trim();
}
__name(extractSection2, "extractSection");
function getExtractedVariable(context2, name) {
  if (!context2?.extractedInputs || context2.extractedInputs.length === 0) {
    return void 0;
  }
  for (const candidate of context2.extractedInputs) {
    if (candidate && typeof candidate === "object" && "name" in candidate && candidate.name === name) {
      return candidate;
    }
  }
  return void 0;
}
__name(getExtractedVariable, "getExtractedVariable");

// interpreter/eval/var.ts
function valueToString(value) {
  if (value === null) return "";
  if (value === void 0) return "undefined";
  if (typeof value === "string") return value;
  if (isStructuredValue(value)) return asText(value);
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}
__name(valueToString, "valueToString");
function createVariableSource(valueNode, directive) {
  const baseSource = {
    directive: "var",
    syntax: "quoted",
    hasInterpolation: false,
    isMultiLine: false
  };
  if (typeof valueNode === "number" || typeof valueNode === "boolean" || valueNode === null) {
    if (directive.meta?.primitiveType) {
      baseSource.syntax = "quoted";
    }
    return baseSource;
  }
  if (valueNode.type === "array") {
    baseSource.syntax = "array";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "object") {
    baseSource.syntax = "object";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "command") {
    baseSource.syntax = "command";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "code") {
    baseSource.syntax = "code";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "path") {
    baseSource.syntax = "path";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "section") {
    baseSource.syntax = "path";
    baseSource.wrapperType = "brackets";
  } else if (valueNode.type === "VariableReference") {
    baseSource.syntax = "reference";
  } else if (directive.meta?.wrapperType) {
    baseSource.wrapperType = directive.meta.wrapperType;
    if (directive.meta.wrapperType === "singleQuote") {
      baseSource.syntax = "quoted";
      baseSource.hasInterpolation = false;
    } else if (directive.meta.wrapperType === "doubleQuote" || directive.meta.wrapperType === "backtick" || directive.meta.wrapperType === "doubleColon") {
      baseSource.syntax = "template";
      baseSource.hasInterpolation = true;
    } else if (directive.meta.wrapperType === "tripleColon") {
      baseSource.syntax = "template";
      baseSource.hasInterpolation = true;
    }
  }
  return baseSource;
}
__name(createVariableSource, "createVariableSource");
async function interpolateAndCollect(nodes, env, mergeDescriptor, interpolationContext = InterpolationContext.Default) {
  if (!mergeDescriptor) {
    return interpolate(nodes, env, interpolationContext);
  }
  const descriptors = [];
  const text = await interpolate(nodes, env, interpolationContext, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((collected) => {
      if (collected) {
        descriptors.push(collected);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    mergeDescriptor(merged);
  }
  return text;
}
__name(interpolateAndCollect, "interpolateAndCollect");
async function prepareVarAssignment(directive, env) {
  const identifierNodes = directive.values?.identifier;
  if (!identifierNodes || !Array.isArray(identifierNodes) || identifierNodes.length === 0) {
    throw new Error("Var directive missing identifier");
  }
  const identifierNode = identifierNodes[0];
  if (!identifierNode || typeof identifierNode !== "object" || !("identifier" in identifierNode)) {
    throw new Error("Invalid identifier node structure");
  }
  const identifier = identifierNode.identifier;
  if (!identifier || typeof identifier !== "string") {
    throw new Error("Var directive identifier must be a simple variable name");
  }
  const securityLabels = directive.meta?.securityLabels ?? directive.values?.securityLabels;
  const baseDescriptor = makeSecurityDescriptor({
    labels: securityLabels
  });
  const capabilityKind = directive.kind;
  const operationMetadata = {
    kind: "var",
    identifier,
    location: directive.location
  };
  let resolvedSecurityDescriptor;
  const mergeResolvedDescriptor = /* @__PURE__ */ __name((descriptor) => {
    if (!descriptor) {
      return;
    }
    resolvedSecurityDescriptor = resolvedSecurityDescriptor ? env.mergeSecurityDescriptors(resolvedSecurityDescriptor, descriptor) : descriptor;
  }, "mergeResolvedDescriptor");
  const mergePipelineDescriptor = /* @__PURE__ */ __name((...descriptors) => {
    const resolved = descriptors.filter(Boolean);
    if (resolved.length === 0) {
      return void 0;
    }
    if (resolved.length === 1) {
      return resolved[0];
    }
    return env.mergeSecurityDescriptors(...resolved);
  }, "mergePipelineDescriptor");
  const descriptorFromVariable = /* @__PURE__ */ __name((variable) => {
    if (!variable?.mx) {
      return void 0;
    }
    return varMxToSecurityDescriptor(variable.mx);
  }, "descriptorFromVariable");
  const interpolateWithSecurity = /* @__PURE__ */ __name((nodes, interpolationContext = InterpolationContext.Default) => {
    return interpolateAndCollect(nodes, env, mergeResolvedDescriptor, interpolationContext);
  }, "interpolateWithSecurity");
  const extractSecurityFromValue = /* @__PURE__ */ __name((value) => {
    if (!value) return void 0;
    if (typeof value === "object" && "mx" in value && value.mx) {
      const mx = value.mx;
      const hasLabels = Array.isArray(mx.labels) && mx.labels.length > 0;
      const hasTaint = Array.isArray(mx.taint) && mx.taint.length > 0;
      if (hasLabels || hasTaint) {
        return {
          labels: mx.labels,
          taint: mx.taint,
          sources: mx.sources,
          policyContext: mx.policy ?? void 0
        };
      }
    }
    return void 0;
  }, "extractSecurityFromValue");
  const finalizeVariable = /* @__PURE__ */ __name((variable) => {
    const descriptor = resolvedSecurityDescriptor ? env.mergeSecurityDescriptors(baseDescriptor, resolvedSecurityDescriptor) : baseDescriptor;
    const capabilityContext = createCapabilityContext({
      kind: capabilityKind,
      descriptor,
      metadata: {
        identifier
      },
      operation: operationMetadata
    });
    const existingSecurity = extractSecurityFromValue(variable);
    const finalMetadata = VariableMetadataUtils.applySecurityMetadata(existingSecurity ? {
      security: existingSecurity
    } : void 0, {
      existingDescriptor: descriptor,
      capability: capabilityContext
    });
    if (!variable.mx) {
      variable.mx = {};
    }
    if (finalMetadata.security) {
      updateVarMxFromDescriptor(variable.mx, finalMetadata.security);
    }
    return VariableMetadataUtils.attachContext(variable);
  }, "finalizeVariable");
  const valueNodes = directive.values?.value;
  if (process.env.MLLD_DEBUG === "true") {
    console.log(`
=== Processing @${identifier} ===`);
    if (Array.isArray(valueNodes) && valueNodes.length > 0) {
      console.log("  Value node type:", valueNodes[0].type);
      console.log("  Has directive.values.withClause?", !!directive.values?.withClause);
      console.log("  Has directive.meta.withClause?", !!directive.meta?.withClause);
      if (directive.values?.withClause || directive.meta?.withClause) {
        const wc = directive.values?.withClause || directive.meta?.withClause;
        console.log("  Pipeline:", wc.pipeline?.map((p) => p.rawIdentifier).join(" | "));
      }
    }
  }
  if (!valueNodes || !Array.isArray(valueNodes) || valueNodes.length === 0) {
    throw new Error("Var directive missing value");
  }
  const valueNode = valueNodes.length === 1 ? valueNodes[0] : valueNodes;
  if (process.env.MLLD_DEBUG === "true") {
    console.error("[var.ts] Extracted valueNode:", {
      identifier,
      type: valueNode?.type,
      isArray: Array.isArray(valueNode),
      hasWithClause: !!valueNode?.withClause,
      hasPipeline: !!valueNode?.withClause?.pipeline
    });
  }
  try {
    let resolvedValue;
    const templateAst = null;
    if (valueNode && typeof valueNode === "object" && valueNode.type === "FileReference") {
      const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
      const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
      const loadContentNode = {
        type: "load-content",
        source: valueNode.source,
        options: valueNode.options,
        pipes: valueNode.pipes
      };
      const rawResult = await processContentLoader2(loadContentNode, env);
      let structuredResult = isStructuredValue(rawResult) ? rawResult : wrapLoadContentValue(rawResult);
      if (valueNode.fields && valueNode.fields.length > 0) {
        for (const field of valueNode.fields) {
          structuredResult = await accessField2(structuredResult, field, {
            env
          });
        }
      }
      resolvedValue = structuredResult;
    } else if (typeof valueNode === "number" || typeof valueNode === "boolean" || valueNode === null) {
      resolvedValue = valueNode;
    } else if (valueNode.type === "Literal") {
      resolvedValue = valueNode.value;
    } else if (valueNode.type === "array") {
      const isComplex = hasComplexArrayItems(valueNode.items || valueNode.elements || []);
      if (isComplex) {
        if (process.env.MLLD_DEBUG === "true") {
          logger.debug("var.ts: Storing complex array AST for lazy evaluation:", {
            identifier,
            valueNode
          });
        }
        resolvedValue = valueNode;
      } else {
        const processedItems = [];
        for (const item of valueNode.items || []) {
          if (item && typeof item === "object") {
            if ("content" in item && Array.isArray(item.content)) {
              const interpolated = await interpolateWithSecurity(item.content);
              processedItems.push(interpolated);
            } else if (item.type === "Text" && "content" in item) {
              processedItems.push(item.content);
            } else if (typeof item === "object" && item.type) {
              const evaluated = await evaluateArrayItem(item, env, mergeResolvedDescriptor);
              processedItems.push(evaluated);
            } else {
              processedItems.push(item);
            }
          } else {
            processedItems.push(item);
          }
        }
        resolvedValue = processedItems;
      }
    } else if (valueNode.type === "object") {
      const isComplex = hasComplexValues(valueNode.entries || valueNode.properties);
      if (isComplex) {
        resolvedValue = valueNode;
      } else {
        const processedObject = {};
        if (valueNode.entries) {
          for (const entry of valueNode.entries) {
            if (entry.type === "pair") {
              const key = entry.key;
              const propValue = entry.value;
              if (propValue && typeof propValue === "object" && "content" in propValue && Array.isArray(propValue.content)) {
                processedObject[key] = await interpolateWithSecurity(propValue.content);
              } else if (propValue && typeof propValue === "object" && propValue.type === "array") {
                const processedArray = [];
                if (identifier === "complex" && key === "users") {
                  logger.debug("Processing users array items:", {
                    itemCount: (propValue.items || []).length,
                    firstItem: propValue.items?.[0]
                  });
                }
                for (const item of propValue.items || []) {
                  const evaluated = await evaluateArrayItem(item, env, mergeResolvedDescriptor);
                  processedArray.push(evaluated);
                }
                processedObject[key] = processedArray;
              } else if (propValue && typeof propValue === "object" && propValue.type === "object") {
                const nestedObj = {};
                if (propValue.entries) {
                  for (const nestedEntry of propValue.entries) {
                    if (nestedEntry.type === "pair") {
                      nestedObj[nestedEntry.key] = await evaluateArrayItem(nestedEntry.value, env, mergeResolvedDescriptor);
                    }
                  }
                } else if (propValue.properties) {
                  for (const [nestedKey, nestedValue] of Object.entries(propValue.properties)) {
                    nestedObj[nestedKey] = await evaluateArrayItem(nestedValue, env, mergeResolvedDescriptor);
                  }
                }
                processedObject[key] = nestedObj;
              } else if (propValue && typeof propValue === "object" && propValue.type) {
                processedObject[key] = await evaluateArrayItem(propValue, env, mergeResolvedDescriptor);
              } else if (propValue && typeof propValue === "object" && "needsInterpolation" in propValue && Array.isArray(propValue.parts)) {
                processedObject[key] = await interpolateWithSecurity(propValue.parts);
              } else {
                processedObject[key] = propValue;
              }
            }
          }
        } else if (valueNode.properties) {
          for (const [key, propValue] of Object.entries(valueNode.properties)) {
            if (propValue && typeof propValue === "object" && "content" in propValue && Array.isArray(propValue.content)) {
              processedObject[key] = await interpolateWithSecurity(propValue.content);
            } else if (propValue && typeof propValue === "object" && propValue.type === "array") {
              const processedArray = [];
              for (const item of propValue.items || []) {
                const evaluated = await evaluateArrayItem(item, env, mergeResolvedDescriptor);
                processedArray.push(evaluated);
              }
              processedObject[key] = processedArray;
            } else if (propValue && typeof propValue === "object" && propValue.type === "object") {
              const nestedObj = {};
              const nestedData = propValue.entries || propValue.properties;
              if (nestedData) {
                if (propValue.entries) {
                  for (const nestedEntry of propValue.entries) {
                    if (nestedEntry.type === "pair") {
                      nestedObj[nestedEntry.key] = await evaluateArrayItem(nestedEntry.value, env, mergeResolvedDescriptor);
                    }
                  }
                } else if (propValue.properties) {
                  for (const [nestedKey, nestedValue] of Object.entries(propValue.properties)) {
                    nestedObj[nestedKey] = await evaluateArrayItem(nestedValue, env, mergeResolvedDescriptor);
                  }
                }
              }
              processedObject[key] = nestedObj;
            } else if (propValue && typeof propValue === "object" && propValue.type) {
              processedObject[key] = await evaluateArrayItem(propValue, env, mergeResolvedDescriptor);
            } else if (propValue && typeof propValue === "object" && "needsInterpolation" in propValue && Array.isArray(propValue.parts)) {
              processedObject[key] = await interpolateWithSecurity(propValue.parts);
            } else {
              processedObject[key] = propValue;
            }
          }
        }
        resolvedValue = processedObject;
      }
    } else if (valueNode.type === "section") {
      const filePath = await interpolateWithSecurity(valueNode.path);
      const sectionName = await interpolateWithSecurity(valueNode.section);
      const fileContent = await env.readFile(filePath);
      const { llmxmlInstance: llmxmlInstance2 } = await import('./llmxml-instance-KTZFYTGC.mjs');
      try {
        resolvedValue = await llmxmlInstance2.getSection(fileContent, sectionName, {
          includeNested: true,
          includeTitle: true
        });
      } catch (error) {
        resolvedValue = extractSection3(fileContent, sectionName);
      }
      if (directive.values?.withClause?.asSection) {
        const newHeader = await interpolateWithSecurity(directive.values.withClause.asSection);
        resolvedValue = applyHeaderTransform(resolvedValue, newHeader);
      }
    } else if (valueNode.type === "load-content") {
      const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
      if (directive.values?.withClause?.asSection) {
        if (!valueNode.options) {
          valueNode.options = {};
        }
        const isGlob = valueNode.source?.raw?.includes("*") || valueNode.source?.raw?.includes("?");
        if (isGlob) {
          valueNode.options.transform = {
            type: "template",
            parts: directive.values.withClause.asSection
          };
        } else {
          if (!valueNode.options.section) {
            valueNode.options.section = {};
          }
          valueNode.options.section.renamed = {
            type: "rename-template",
            parts: directive.values.withClause.asSection
          };
        }
      }
      resolvedValue = await processContentLoader2(valueNode, env);
    } else if (valueNode.type === "path") {
      const filePath = await interpolateWithSecurity(valueNode.segments);
      resolvedValue = await env.readFile(filePath);
    } else if (valueNode.type === "code") {
      const { evaluateCodeExecution } = await import('./code-execution-RAAJT3Y7.mjs');
      const result2 = await evaluateCodeExecution(valueNode, env);
      resolvedValue = result2.value;
    } else if (valueNode.type === "command") {
      const withClause = directive.values?.withClause || directive.meta?.withClause;
      const hasWithClause = !!withClause;
      let handledByRunEvaluator = false;
      if (hasWithClause) {
        const { evaluateRun: evaluateRun2 } = await import('./run-KYGSK2JR.mjs');
        const runDirective = {
          type: "Directive",
          nodeId: directive.nodeId ? `${directive.nodeId}-run` : void 0,
          location: directive.location,
          kind: "run",
          subtype: "runCommand",
          source: "command",
          values: {
            command: valueNode.command,
            withClause
          },
          raw: {
            command: Array.isArray(valueNode.command) ? valueNode.meta?.raw || "" : String(valueNode.command),
            withClause
          },
          meta: {
            // Mark as data value so evaluateRun does not emit document output
            isDataValue: true
          }
        };
        const result2 = await evaluateRun2(runDirective, env);
        resolvedValue = result2.value;
        handledByRunEvaluator = true;
      } else {
        if (Array.isArray(valueNode.command)) {
          const interpolatedCommand = await interpolateWithSecurity(valueNode.command, InterpolationContext.ShellCommand);
          resolvedValue = await env.executeCommand(interpolatedCommand);
        } else {
          resolvedValue = await env.executeCommand(valueNode.command);
        }
        const { processCommandOutput } = await import('./json-auto-parser-DOBRNARE.mjs');
        resolvedValue = processCommandOutput(resolvedValue);
      }
    } else if (valueNode.type === "VariableReference") {
      if (process.env.MLLD_DEBUG === "true") {
        console.log("Processing VariableReference in var.ts:", {
          identifier,
          varIdentifier: valueNode.identifier,
          hasFields: !!(valueNode.fields && valueNode.fields.length > 0),
          fields: valueNode.fields?.map((f) => f.value)
        });
      }
      const sourceVar = env.getVariable(valueNode.identifier);
      if (!sourceVar) {
        const { MlldDirectiveError: MlldDirectiveError2 } = await import('./errors-WJULH47E.mjs');
        throw new MlldDirectiveError2(`Variable not found: ${valueNode.identifier}`, "var", {
          location: directive.location,
          env
        });
      }
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
      const resolvedVar = await resolveVariable(sourceVar, env, ResolutionContext.VariableCopy);
      if (valueNode.fields && valueNode.fields.length > 0) {
        const fieldResult = await accessField2(resolvedVar, valueNode.fields[0], {
          preserveContext: true,
          env,
          sourceLocation: directive.location
        });
        let currentResult = fieldResult;
        for (let i = 1; i < valueNode.fields.length; i++) {
          currentResult = await accessField2(currentResult.value, valueNode.fields[i], {
            preserveContext: true,
            parentPath: currentResult.accessPath,
            env,
            sourceLocation: directive.location
          });
        }
        resolvedValue = currentResult.value;
        if (resolvedValue && typeof resolvedValue === "object" && resolvedValue.type === "executable") {
          const finalVar2 = finalizeVariable(resolvedValue);
          return {
            identifier,
            variable: finalVar2,
            evalResultOverride: {
              value: finalVar2,
              env,
              stdout: "",
              stderr: "",
              exitCode: 0
            }
          };
        }
      } else {
        resolvedValue = resolvedVar;
      }
      if (valueNode.pipes && valueNode.pipes.length > 0) {
        const { processPipeline: processPipeline3 } = await import('./unified-processor-GTJC5G2K.mjs');
        const result2 = await processPipeline3({
          value: resolvedValue,
          env,
          node: valueNode,
          identifier,
          location: directive.location,
          descriptorHint: mergePipelineDescriptor(descriptorFromVariable(sourceVar), resolvedSecurityDescriptor)
        });
        resolvedValue = result2;
      }
    } else if (Array.isArray(valueNode)) {
      if (valueNode.length === 1 && valueNode[0].type === "Text" && directive.meta?.wrapperType === "backtick") {
        resolvedValue = valueNode[0].content;
      } else if (directive.meta?.wrapperType === "doubleColon" || directive.meta?.wrapperType === "tripleColon") {
        if (directive.meta?.wrapperType === "tripleColon") {
          resolvedValue = valueNode;
          logger.debug("Storing template AST for triple-colon template", {
            identifier,
            ast: valueNode
          });
        } else {
          resolvedValue = await interpolateWithSecurity(valueNode);
        }
      } else {
        resolvedValue = await interpolateWithSecurity(valueNode);
      }
    } else if (valueNode.type === "Text" && "content" in valueNode) {
      resolvedValue = valueNode.content;
    } else if (valueNode && (valueNode.type === "foreach" || valueNode.type === "foreach-command")) {
      const { evaluateForeachCommand: evaluateForeachCommand2 } = await import('./foreach-USOCOKPZ.mjs');
      resolvedValue = await evaluateForeachCommand2(valueNode, env);
    } else if (valueNode && valueNode.type === "WhenExpression") {
      const { evaluateWhenExpression: evaluateWhenExpression2 } = await import('./when-expression-ZW53U2K2.mjs');
      const whenResult = await evaluateWhenExpression2(valueNode, env);
      resolvedValue = whenResult.value;
    } else if (valueNode && valueNode.type === "ExeBlock") {
      const { evaluateExeBlock: evaluateExeBlock2 } = await import('./exe-T3P26GTO.mjs');
      const blockEnv = env.createChild();
      const blockResult = await evaluateExeBlock2(valueNode, blockEnv);
      resolvedValue = blockResult.value;
    } else if (valueNode && valueNode.type === "ExecInvocation") {
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[var.ts] Processing ExecInvocation:", {
          hasWithClause: !!valueNode.withClause,
          hasPipeline: !!valueNode.withClause?.pipeline
        });
      }
      const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
      const result2 = await evaluateExecInvocation(valueNode, env);
      resolvedValue = result2.value;
    } else if (valueNode && valueNode.type === "VariableReferenceWithTail") {
      if (process.env.MLLD_DEBUG === "true") {
        console.log("Processing VariableReferenceWithTail in var.ts");
      }
      const varWithTail = valueNode;
      const sourceVar = env.getVariable(varWithTail.variable.identifier);
      if (!sourceVar) {
        const { MlldDirectiveError: MlldDirectiveError2 } = await import('./errors-WJULH47E.mjs');
        throw new MlldDirectiveError2(`Variable not found: ${varWithTail.variable.identifier}`, "var", {
          location: directive.location,
          env
        });
      }
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      const { accessFields: accessFields2 } = await import('./field-access-MJ6PMBJX.mjs');
      const needsPipelineExtraction = varWithTail.withClause && varWithTail.withClause.pipeline;
      const hasFieldAccess = varWithTail.variable.fields && varWithTail.variable.fields.length > 0;
      const context2 = needsPipelineExtraction && !hasFieldAccess ? ResolutionContext.PipelineInput : ResolutionContext.FieldAccess;
      const resolvedVar = await resolveVariable(sourceVar, env, context2);
      let result2 = resolvedVar;
      if (varWithTail.variable.fields && varWithTail.variable.fields.length > 0) {
        const fieldResult = await accessFields2(resolvedVar, varWithTail.variable.fields, {
          preserveContext: true,
          env,
          sourceLocation: directive.location
        });
        result2 = fieldResult.value;
      }
      if (varWithTail.withClause && varWithTail.withClause.pipeline) {
        const { processPipeline: processPipeline3 } = await import('./unified-processor-GTJC5G2K.mjs');
        result2 = await processPipeline3({
          value: result2,
          env,
          node: varWithTail,
          identifier: varWithTail.identifier,
          location: directive.location,
          descriptorHint: mergePipelineDescriptor(descriptorFromVariable(sourceVar), resolvedSecurityDescriptor)
        });
      }
      resolvedValue = result2;
    } else if (valueNode && (valueNode.type === "BinaryExpression" || valueNode.type === "TernaryExpression" || valueNode.type === "UnaryExpression")) {
      const { evaluateUnifiedExpression: evaluateUnifiedExpression2 } = await import('./expressions-CYFHZWDH.mjs');
      const result2 = await evaluateUnifiedExpression2(valueNode, env);
      resolvedValue = result2.value;
    } else if (valueNode && valueNode.type === "ForExpression") {
      const { evaluateForExpression: evaluateForExpression2 } = await import('./for-FC7J7F6X.mjs');
      const forResult = await evaluateForExpression2(valueNode, env);
      const finalVar2 = finalizeVariable(forResult);
      return {
        identifier,
        variable: finalVar2,
        evalResultOverride: {
          value: finalVar2,
          env
        }
      };
    } else {
      if (process.env.MLLD_DEBUG === "true") {
        logger.debug("var.ts: Default case for valueNode:", {
          valueNode
        });
      }
      resolvedValue = await interpolateWithSecurity([
        valueNode
      ]);
    }
    const resolvedValueDescriptor = extractSecurityDescriptor(resolvedValue, {
      recursive: true,
      mergeArrayElements: true
    });
    mergeResolvedDescriptor(resolvedValueDescriptor);
    const location = astLocationToSourceLocation(directive.location, env.getCurrentFilePath());
    const source = createVariableSource(valueNode, directive);
    const baseCtx = {
      definedAt: location
    };
    const baseInternal = {};
    const cloneFactoryOptions = /* @__PURE__ */ __name((overrides) => ({
      mx: {
        ...baseCtx,
        ...overrides?.mx ?? {}
      },
      internal: {
        ...baseInternal,
        ...overrides?.internal ?? {}
      }
    }), "cloneFactoryOptions");
    const applySecurityOptions = /* @__PURE__ */ __name((overrides, existing) => {
      const options = cloneFactoryOptions(overrides);
      const finalMetadata = VariableMetadataUtils.applySecurityMetadata(void 0, {
        labels: securityLabels,
        existingDescriptor: existing ?? resolvedValueDescriptor
      });
      if (finalMetadata?.security) {
        updateVarMxFromDescriptor(options.mx ?? (options.mx = {}), finalMetadata.security);
      }
      if (finalMetadata) {
        options.metadata = {
          ...options.metadata ?? {},
          ...finalMetadata
        };
      }
      return options;
    }, "applySecurityOptions");
    if (valueNode && (valueNode.type === "ExecInvocation" || valueNode.type === "command" || valueNode.type === "code")) {
      baseInternal.isRetryable = true;
      baseInternal.sourceFunction = valueNode;
    }
    let variable;
    if (process.env.MLLD_DEBUG === "true") {
      console.log("Creating variable:", {
        identifier,
        valueNodeType: valueNode?.type,
        resolvedValue,
        resolvedValueType: typeof resolvedValue
      });
    }
    if (process.env.MLLD_DEBUG_IDS === "true" && (identifier === "squared" || identifier === "ids")) {
      try {
        const structuredInfo = isStructuredValue(resolvedValue) ? {
          type: resolvedValue.type,
          text: resolvedValue.text,
          dataType: typeof resolvedValue.data,
          preview: resolvedValue.data && typeof resolvedValue.data === "object" ? Array.isArray(resolvedValue.data) ? {
            length: resolvedValue.data.length,
            first: resolvedValue.data[0]
          } : {
            keys: Object.keys(resolvedValue.data).slice(0, 5)
          } : resolvedValue.data
        } : void 0;
        console.error("[var-debug]", {
          identifier,
          resolvedType: typeof resolvedValue,
          isStructured: isStructuredValue(resolvedValue),
          structuredInfo,
          rawValue: resolvedValue
        });
      } catch {
      }
    }
    const { isVariable: isVariable2 } = await import('./variable-resolution-HFG3FTZK.mjs');
    if (isVariable2(resolvedValue)) {
      if (process.env.MLLD_DEBUG === "true") {
        console.log("Preserving existing Variable:", {
          identifier,
          resolvedValueType: resolvedValue.type,
          resolvedValueName: resolvedValue.name
        });
      }
      const overrides = {
        mx: {
          ...resolvedValue.mx ?? {},
          ...baseCtx
        },
        internal: {
          ...resolvedValue.internal ?? {},
          ...baseInternal
        }
      };
      const existingSecurity = extractSecurityFromValue(resolvedValue);
      const options = applySecurityOptions(overrides, existingSecurity);
      variable = {
        ...resolvedValue,
        name: identifier,
        definedAt: location,
        mx: options.mx,
        internal: options.internal
      };
      VariableMetadataUtils.attachContext(variable);
    } else if (isStructuredValue(resolvedValue)) {
      const options = applySecurityOptions({
        internal: {
          isStructuredValue: true,
          structuredValueType: resolvedValue.type
        }
      }, resolvedValueDescriptor);
      variable = createStructuredValueVariable(identifier, resolvedValue, source, options);
    } else if (typeof valueNode === "number" || typeof valueNode === "boolean" || valueNode === null) {
      const options = applySecurityOptions();
      variable = createPrimitiveVariable(identifier, valueNode, source, options);
    } else if (valueNode.type === "array") {
      const isComplex = hasComplexArrayItems(valueNode.items || valueNode.elements || []);
      if (process.env.MLLD_DEBUG === "true") {
        logger.debug("var.ts: Creating array variable:", {
          identifier,
          isComplex,
          resolvedValueType: typeof resolvedValue,
          resolvedValueIsArray: Array.isArray(resolvedValue),
          resolvedValue
        });
      }
      const options = applySecurityOptions();
      variable = createArrayVariable(identifier, resolvedValue, isComplex, source, options);
    } else if (valueNode.type === "object") {
      const isComplex = hasComplexValues(valueNode.entries || valueNode.properties);
      const options = applySecurityOptions();
      variable = createObjectVariable(identifier, resolvedValue, isComplex, source, options);
    } else if (valueNode.type === "command") {
      const options = applySecurityOptions();
      variable = createCommandResultVariable(identifier, resolvedValue, valueNode.command, source, void 0, void 0, options);
    } else if (valueNode.type === "code") {
      const sourceCode = valueNode.code || "";
      const options = applySecurityOptions();
      variable = createComputedVariable(identifier, resolvedValue, valueNode.language || "js", sourceCode, source, options);
    } else if (valueNode.type === "path") {
      const filePath = await interpolateWithSecurity(valueNode.segments);
      const options = applySecurityOptions();
      variable = createFileContentVariable(identifier, resolvedValue, filePath, source, options);
    } else if (valueNode.type === "section") {
      const filePath = await interpolateWithSecurity(valueNode.path);
      const sectionName = await interpolateWithSecurity(valueNode.section);
      const options = applySecurityOptions();
      variable = createSectionContentVariable(identifier, resolvedValue, filePath, sectionName, "hash", source, options);
    } else if (valueNode.type === "VariableReference") {
      const actualValue = isStructuredValue(resolvedValue) ? asData(resolvedValue) : resolvedValue;
      const existingSecurity = extractSecurityFromValue(resolvedValue);
      if (typeof actualValue === "string") {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createSimpleTextVariable(identifier, actualValue, source, options);
      } else if (typeof actualValue === "number" || typeof actualValue === "boolean" || actualValue === null) {
        const options = applySecurityOptions(void 0, existingSecurity);
        variable = createPrimitiveVariable(identifier, actualValue, source, options);
      } else if (Array.isArray(actualValue)) {
        const options = applySecurityOptions(void 0, existingSecurity);
        variable = createArrayVariable(identifier, actualValue, false, source, options);
      } else if (typeof actualValue === "object" && actualValue !== null) {
        const options = applySecurityOptions(void 0, existingSecurity);
        variable = createObjectVariable(identifier, actualValue, false, source, options);
      } else {
        const options = applySecurityOptions(void 0, existingSecurity);
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    } else if (valueNode.type === "load-content") {
      const structuredValue = wrapLoadContentValue(resolvedValue);
      const options = applySecurityOptions({
        internal: {
          structuredValueMetadata: structuredValue.metadata
        }
      });
      variable = createStructuredValueVariable(identifier, structuredValue, source, options);
      resolvedValue = structuredValue;
    } else if (valueNode.type === "foreach" || valueNode.type === "foreach-command") {
      const isComplex = false;
      const options = applySecurityOptions();
      variable = createArrayVariable(identifier, resolvedValue, isComplex, source, options);
    } else if (valueNode.type === "WhenExpression") {
      if (isStructuredValue(resolvedValue)) {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createStructuredValueVariable(identifier, resolvedValue, source, options);
      } else if (typeof resolvedValue === "object" && resolvedValue !== null) {
        if (Array.isArray(resolvedValue)) {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createArrayVariable(identifier, resolvedValue, false, source, options);
        } else {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createObjectVariable(identifier, resolvedValue, false, source, options);
        }
      } else if (typeof resolvedValue === "boolean" || typeof resolvedValue === "number" || resolvedValue === null) {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createPrimitiveVariable(identifier, resolvedValue, source, options);
      } else {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    } else if (valueNode.type === "ExecInvocation" || valueNode.type === "ExeBlock") {
      if (isStructuredValue(resolvedValue)) {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createStructuredValueVariable(identifier, resolvedValue, source, options);
      } else if (typeof resolvedValue === "object" && resolvedValue !== null) {
        if (Array.isArray(resolvedValue)) {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createArrayVariable(identifier, resolvedValue, false, source, options);
        } else {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createObjectVariable(identifier, resolvedValue, false, source, options);
        }
      } else {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    } else if (valueNode.type === "VariableReferenceWithTail") {
      const actualValue = isStructuredValue(resolvedValue) ? asData(resolvedValue) : resolvedValue;
      if (typeof actualValue === "object" && actualValue !== null) {
        if (Array.isArray(actualValue)) {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createArrayVariable(identifier, actualValue, false, source, options);
        } else {
          const options = applySecurityOptions(void 0, resolvedValueDescriptor);
          variable = createObjectVariable(identifier, actualValue, false, source, options);
        }
      } else {
        const options = applySecurityOptions(void 0, resolvedValueDescriptor);
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    } else if (directive.meta?.expressionType) {
      if (typeof resolvedValue === "boolean" || typeof resolvedValue === "number" || resolvedValue === null) {
        const options = applySecurityOptions();
        variable = createPrimitiveVariable(identifier, resolvedValue, source, options);
      } else {
        const options = applySecurityOptions();
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    } else if (valueNode.type === "Literal") {
    } else {
      const strValue = valueToString(resolvedValue);
      if (directive.meta?.wrapperType === "singleQuote") {
        const options = applySecurityOptions();
        variable = createSimpleTextVariable(identifier, strValue, source, options);
      } else if (directive.meta?.isTemplateContent || directive.meta?.wrapperType === "backtick" || directive.meta?.wrapperType === "doubleQuote" || directive.meta?.wrapperType === "doubleColon" || directive.meta?.wrapperType === "tripleColon") {
        let templateType = "backtick";
        if (directive.meta?.wrapperType === "doubleColon") {
          templateType = "doubleColon";
        } else if (directive.meta?.wrapperType === "tripleColon") {
          templateType = "tripleColon";
        }
        const templateValue = directive.meta?.wrapperType === "tripleColon" && Array.isArray(resolvedValue) ? resolvedValue : strValue;
        const options = applySecurityOptions();
        variable = createTemplateVariable(identifier, templateValue, void 0, templateType, source, options);
      } else if (directive.meta?.wrapperType === "doubleQuote" || source.hasInterpolation) {
        const options = applySecurityOptions();
        variable = createInterpolatedTextVariable(identifier, strValue, [], source, options);
      } else {
        const options = applySecurityOptions();
        variable = createSimpleTextVariable(identifier, strValue, source, options);
      }
    }
    const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
    if (!variable) {
      if (valueNode && valueNode.type === "Literal") {
        if (typeof resolvedValue === "boolean" || typeof resolvedValue === "number" || resolvedValue === null) {
          const options = applySecurityOptions();
          variable = createPrimitiveVariable(identifier, resolvedValue, source, options);
        } else {
          const options = applySecurityOptions();
          variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
        }
      } else {
        const options = applySecurityOptions();
        variable = createSimpleTextVariable(identifier, valueToString(resolvedValue), source, options);
      }
    }
    let result = variable;
    const skipPipeline = valueNode && valueNode.type === "ExecInvocation" && valueNode.withClause || valueNode && valueNode.type === "VariableReference" && valueNode.pipes || valueNode && valueNode.type === "load-content" && valueNode.pipes;
    const handledByRun = valueNode && valueNode.type === "command" && !!(directive.values?.withClause || directive.meta?.withClause);
    if (!skipPipeline && !handledByRun) {
      if (process.env.MLLD_DEBUG === "true") {
        console.error("[var.ts] Calling processPipeline:", {
          identifier,
          variableType: variable.type,
          hasCtx: !!variable.mx,
          hasInternal: !!variable.internal,
          isRetryable: variable.internal?.isRetryable || false,
          hasSourceFunction: !!variable.internal?.sourceFunction,
          sourceNodeType: variable.internal?.sourceFunction?.type
        });
      }
      result = await processPipeline2({
        value: variable,
        env,
        node: valueNode,
        directive,
        identifier,
        location: directive.location,
        isRetryable: variable.internal?.isRetryable || false
      });
    }
    if (typeof result === "string" && result !== variable.value) {
      const existingSecurity = extractSecurityFromValue(variable);
      const options = applySecurityOptions({
        mx: {
          ...variable.mx ?? {},
          ...baseCtx
        },
        internal: {
          ...variable.internal ?? {},
          ...baseInternal
        }
      }, existingSecurity);
      variable = createSimpleTextVariable(identifier, result, source, options);
    } else if (isStructuredValue(result)) {
      const existingSecurity = extractSecurityFromValue(variable);
      const options = applySecurityOptions({
        mx: {
          ...variable.mx ?? {},
          ...baseCtx
        },
        internal: {
          ...variable.internal ?? {},
          ...baseInternal,
          isPipelineResult: true
        }
      }, existingSecurity);
      variable = createStructuredValueVariable(identifier, result, source, options);
    }
    const finalVar = finalizeVariable(variable);
    if (process.env.MLLD_DEBUG === "true" && identifier === "sum") {
      logger.debug("Setting variable @sum:", {
        identifier,
        resolvedValue,
        valueType: typeof resolvedValue,
        variableType: finalVar.type,
        variableValue: finalVar.value
      });
    }
    return {
      identifier,
      variable: finalVar
    };
  } catch (error) {
    throw error;
  }
}
__name(prepareVarAssignment, "prepareVarAssignment");
async function evaluateVar(directive, env, context2) {
  const assignment = context2?.precomputedVarAssignment ?? await prepareVarAssignment(directive, env);
  env.setVariable(assignment.identifier, assignment.variable);
  return assignment.evalResultOverride ?? {
    value: "",
    env
  };
}
__name(evaluateVar, "evaluateVar");
function hasComplexValues(objOrProperties) {
  if (!objOrProperties) return false;
  if (Array.isArray(objOrProperties)) {
    for (const entry of objOrProperties) {
      if (entry.type === "spread") {
        return true;
      }
      if (entry.type === "pair") {
        const value = entry.value;
        if (value && typeof value === "object") {
          if ("type" in value && (value.type === "code" || value.type === "command" || value.type === "VariableReference" || value.type === "path" || value.type === "section" || value.type === "runExec" || value.type === "ExecInvocation" || value.type === "load-content")) {
            return true;
          }
          if (value.type === "object") {
            const nestedData = value.entries || value.properties;
            if (nestedData && hasComplexValues(nestedData)) {
              return true;
            }
          }
          if (value.type === "array" && hasComplexArrayItems(value.items || value.elements || [])) {
            return true;
          }
          if (!value.type && typeof value === "object" && !Array.isArray(value)) {
            if (hasComplexValues(value)) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
  for (const value of Object.values(objOrProperties)) {
    if (value && typeof value === "object") {
      if ("type" in value && (value.type === "code" || value.type === "command" || value.type === "VariableReference" || value.type === "path" || value.type === "section" || value.type === "runExec" || value.type === "ExecInvocation" || value.type === "load-content")) {
        return true;
      }
      if (value.type === "object") {
        const nestedData = value.entries || value.properties;
        if (nestedData && hasComplexValues(nestedData)) {
          return true;
        }
      }
      if (value.type === "array" && hasComplexArrayItems(value.items || value.elements || [])) {
        return true;
      }
      if (!value.type && typeof value === "object" && !Array.isArray(value)) {
        if (hasComplexValues(value)) {
          return true;
        }
      }
    }
  }
  return false;
}
__name(hasComplexValues, "hasComplexValues");
function hasComplexArrayItems(items) {
  if (!items || !Array.isArray(items) || items.length === 0) return false;
  for (const item of items) {
    if (item && typeof item === "object") {
      if ("type" in item && (item.type === "code" || item.type === "command" || item.type === "VariableReference" || item.type === "array" || item.type === "object" || item.type === "path" || item.type === "section" || item.type === "load-content" || item.type === "ExecInvocation")) {
        return true;
      }
      if (Array.isArray(item) && hasComplexArrayItems(item)) {
        return true;
      }
      if (item.constructor === Object && hasComplexValues(item)) {
        return true;
      }
    }
  }
  return false;
}
__name(hasComplexArrayItems, "hasComplexArrayItems");
async function evaluateArrayItem(item, env, collectDescriptor) {
  if (!item || typeof item !== "object") {
    return item;
  }
  if (process.env.MLLD_DEBUG === "true" && item.type === "object") {
    logger.debug("evaluateArrayItem processing object:", {
      hasProperties: !!item.properties,
      propertyKeys: item.properties ? Object.keys(item.properties) : [],
      sampleProperty: item.properties?.name
    });
  }
  if ("content" in item && Array.isArray(item.content) && "wrapperType" in item) {
    const hasOnlyLiteralsOrText = item.content.every((node) => node && typeof node === "object" && (node.type === "Literal" && "value" in node || node.type === "Text" && "content" in node));
    if (hasOnlyLiteralsOrText) {
      if (process.env.MLLD_DEBUG_FIX === "true") {
        console.error("[evaluateArrayItem] literal/text wrapper", {
          wrapperType: item.wrapperType,
          items: item.content.map((node) => node.type)
        });
      }
      const joined = item.content.map((node) => node.type === "Literal" ? node.value : node.content).join("");
      if (process.env.MLLD_DEBUG_FIX === "true") {
        try {
          fs.appendFileSync("/tmp/mlld-debug.log", JSON.stringify({
            source: "evaluateArrayItem",
            wrapperType: item.wrapperType,
            joined
          }) + "\n");
        } catch {
        }
      }
      return joined;
    }
    if (process.env.MLLD_DEBUG_FIX === "true") {
      console.error("[evaluateArrayItem] interpolating wrapper", {
        wrapperType: item.wrapperType,
        itemTypes: item.content.map((node) => node?.type)
      });
    }
    return await interpolateAndCollect(item.content, env, collectDescriptor);
  }
  if ("content" in item && Array.isArray(item.content)) {
    return await interpolateAndCollect(item.content, env, collectDescriptor);
  }
  if (item.type === "Text" && "content" in item) {
    return item.content;
  }
  if (item.type === "Literal" && "value" in item) {
    return item.value;
  }
  if ("needsInterpolation" in item && Array.isArray(item.parts)) {
    return await interpolateAndCollect(item.parts, env, collectDescriptor);
  }
  if (!item.type && typeof item === "object" && item.constructor === Object) {
    const nestedObj = {};
    for (const [key, value] of Object.entries(item)) {
      if (key === "wrapperType" || key === "nodeId" || key === "location") {
        continue;
      }
      nestedObj[key] = await evaluateArrayItem(value, env, collectDescriptor);
    }
    return nestedObj;
  }
  switch (item.type) {
    case "WhenExpression": {
      const { evaluateWhenExpression: evaluateWhenExpression2 } = await import('./when-expression-ZW53U2K2.mjs');
      const res = await evaluateWhenExpression2(item, env);
      return res.value;
    }
    case "array":
      const nestedItems = [];
      for (const nestedItem of item.items || []) {
        nestedItems.push(await evaluateArrayItem(nestedItem, env, collectDescriptor));
      }
      return nestedItems;
    case "object":
      const processedObject = {};
      if (item.entries) {
        for (const entry of item.entries) {
          if (entry.type === "pair") {
            processedObject[entry.key] = await evaluateArrayItem(entry.value, env, collectDescriptor);
          }
        }
      } else if (item.properties) {
        for (const [key, propValue] of Object.entries(item.properties)) {
          processedObject[key] = await evaluateArrayItem(propValue, env, collectDescriptor);
        }
      }
      return processedObject;
    case "VariableReference":
      const variable = env.getVariable(item.identifier);
      if (!variable) {
        throw new Error(`Variable not found: ${item.identifier}`);
      }
      const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
      return await resolveVariable(variable, env, ResolutionContext.ArrayElement);
    case "path":
      const filePath = await interpolateAndCollect(item.segments || [
        item
      ], env, collectDescriptor);
      const fileContent = await env.readFile(filePath);
      return fileContent;
    case "SectionExtraction":
      const sectionName = await interpolateAndCollect(item.section, env, collectDescriptor);
      const sectionFilePath = await interpolateAndCollect(item.path.segments || [
        item.path
      ], env, collectDescriptor);
      const sectionFileContent = await env.readFile(sectionFilePath);
      const { extractSection: extractSection4 } = await import('./show-5RN42ZAU.mjs');
      return extractSection4(sectionFileContent, sectionName);
    case "load-content":
      const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
      const loadResult = await processContentLoader2(item, env);
      const { isFileLoadedValue: isFileLoadedValue2 } = await import('./load-content-structured-FVMWENVK.mjs');
      if (isFileLoadedValue2(loadResult)) {
        return isStructuredValue(loadResult) ? loadResult : loadResult.content;
      }
      return loadResult;
    default:
      if (!item.type && typeof item === "object" && item.constructor === Object) {
        const plainObj = {};
        for (const [key, value] of Object.entries(item)) {
          if (key === "wrapperType" || key === "nodeId" || key === "location") {
            continue;
          }
          plainObj[key] = await evaluateArrayItem(value, env, collectDescriptor);
        }
        return plainObj;
      }
      return await interpolateAndCollect([
        item
      ], env, collectDescriptor);
  }
}
__name(evaluateArrayItem, "evaluateArrayItem");
function extractSection3(content, sectionName) {
  const lines = content.split("\n");
  const sectionRegex = new RegExp(`^#+\\s+${sectionName}\\s*$`, "i");
  let inSection = false;
  let sectionLevel = 0;
  const sectionLines = [];
  for (const line of lines) {
    if (!inSection && sectionRegex.test(line)) {
      inSection = true;
      sectionLevel = line.match(/^#+/)?.[0].length || 0;
      sectionLines.push(line);
      continue;
    }
    if (inSection) {
      const headerMatch = line.match(/^(#+)\\s+/);
      if (headerMatch && headerMatch[1].length <= sectionLevel) {
        break;
      }
      sectionLines.push(line);
    }
  }
  return sectionLines.join("\n").trim();
}
__name(extractSection3, "extractSection");

// interpreter/eval/helpers/shadowEnvResolver.ts
function resolveShadowEnvironment(language, capturedEnvs, currentEnv) {
  const normalizedLang = normalizeLanguage(language);
  if (capturedEnvs) {
    const captured = capturedEnvs[normalizedLang];
    if (captured && captured.size > 0) {
      return captured;
    }
  }
  return currentEnv.getShadowEnv(language);
}
__name(resolveShadowEnvironment, "resolveShadowEnvironment");
function detectShadowConflicts(captured, current) {
  const conflicts = [];
  if (captured && current) {
    for (const [name, capturedFunc] of captured) {
      const currentFunc = current.get(name);
      if (currentFunc && currentFunc !== capturedFunc) {
        conflicts.push(name);
      }
    }
  }
  return conflicts;
}
__name(detectShadowConflicts, "detectShadowConflicts");
function mergeShadowFunctions(captured, current, paramNames) {
  const merged = /* @__PURE__ */ new Map();
  if (process.env.MLLD_DEBUG === "true") {
    const conflicts = detectShadowConflicts(captured, current);
    if (conflicts.length > 0) {
      console.warn(`[Shadow Environment] Conflict detected for functions: ${conflicts.join(", ")}. Current environment shadows are overriding captured ones.`);
    }
  }
  if (captured) {
    for (const [name, func] of captured) {
      if (!paramNames.has(name)) {
        merged.set(name, func);
      }
    }
  }
  if (current) {
    for (const [name, func] of current) {
      if (!paramNames.has(name)) {
        merged.set(name, func);
      }
    }
  }
  const names = [];
  const values = [];
  for (const [name, func] of merged) {
    names.push(name);
    values.push(func);
  }
  return {
    names,
    values
  };
}
__name(mergeShadowFunctions, "mergeShadowFunctions");
function normalizeLanguage(language) {
  switch (language) {
    case "js":
    case "javascript":
      return "js";
    case "node":
    case "nodejs":
      return "node";
    default:
      return language;
  }
}
__name(normalizeLanguage, "normalizeLanguage");
async function evaluateExeBlock(block, env, args = {}) {
  let blockEnv = env.createChild();
  if (args && Object.keys(args).length > 0) {
    const importer = new VariableImporter();
    for (const [param, value] of Object.entries(args)) {
      const variable = importer.createVariableFromValue(param, value, "exe-param", void 0, {
        env: blockEnv
      });
      blockEnv.setVariable(param, variable);
    }
  }
  for (const stmt of block.values?.statements ?? []) {
    if (isLetAssignment(stmt)) {
      blockEnv = await evaluateLetAssignment(stmt, blockEnv);
    } else if (isAugmentedAssignment(stmt)) {
      blockEnv = await evaluateAugmentedAssignment(stmt, blockEnv);
    } else {
      const result = await evaluate2(stmt, blockEnv);
      blockEnv = result.env || blockEnv;
    }
  }
  let returnValue = void 0;
  const returnNode = block.values?.return;
  const hasReturnValue = returnNode?.meta?.hasValue !== false;
  if (returnNode && hasReturnValue) {
    const returnNodes = Array.isArray(returnNode.values) ? returnNode.values : [];
    if (returnNodes.length > 0) {
      const returnResult = await evaluate2(returnNodes, blockEnv, {
        isExpression: true
      });
      returnValue = returnResult.value;
      blockEnv = returnResult.env || blockEnv;
    }
  }
  env.mergeChild(blockEnv);
  return {
    value: returnValue,
    env
  };
}
__name(evaluateExeBlock, "evaluateExeBlock");
async function interpolateAndRecord7(nodes, env, context2 = InterpolationContext.Default) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context2, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateAndRecord7, "interpolateAndRecord");
function buildTemplateAstFromContent(content) {
  const ast = [];
  const regex = /@([A-Za-z_][\w\.]*)/g;
  let lastIndex = 0;
  let match;
  while ((match = regex.exec(content)) !== null) {
    if (match.index > lastIndex) {
      ast.push({
        type: "Text",
        content: content.slice(lastIndex, match.index)
      });
    }
    ast.push({
      type: "VariableReference",
      identifier: match[1]
    });
    lastIndex = match.index + match[0].length;
  }
  if (lastIndex < content.length) {
    ast.push({
      type: "Text",
      content: content.slice(lastIndex)
    });
  }
  return ast;
}
__name(buildTemplateAstFromContent, "buildTemplateAstFromContent");
function extractParamNames(params) {
  return params.map((p) => {
    if (typeof p === "string") {
      return p;
    } else if (p.type === "VariableReference") {
      return p.identifier;
    } else if (p.type === "Parameter") {
      return p.name;
    }
    return "";
  }).filter(Boolean);
}
__name(extractParamNames, "extractParamNames");
async function evaluateExe(directive, env) {
  if (directive.subtype === "environment") {
    const identifierNodes2 = directive.values?.identifier;
    if (!identifierNodes2 || !Array.isArray(identifierNodes2) || identifierNodes2.length === 0) {
      throw new Error("Exec environment directive missing language identifier");
    }
    const identifierNode2 = identifierNodes2[0];
    let language2;
    if (identifierNode2.type === "VariableReference" && "identifier" in identifierNode2) {
      language2 = identifierNode2.identifier;
    } else {
      throw new Error("Exec environment language must be a simple string");
    }
    const envRefs = directive.values?.environment || [];
    const shadowFunctions = /* @__PURE__ */ new Map();
    for (const ref of envRefs) {
      const funcName = ref.identifier;
      const funcVar = env.getVariable(funcName);
      if (!funcVar || funcVar.type !== "executable") {
        throw new Error(`${funcName} is not a defined exec function`);
      }
      const wrapper = createExecWrapper(funcName, funcVar, env);
      let effectiveWrapper = wrapper;
      if (language2 === "js" || language2 === "javascript") {
        if (funcVar.value.type === "code" && (funcVar.value.language === "javascript" || funcVar.value.language === "js")) {
          const execDef = funcVar.internal?.executableDef;
          if (execDef && execDef.type === "code") {
            execDef.capturedShadowEnvs = funcVar.internal?.capturedShadowEnvs;
            effectiveWrapper = createSyncJsWrapper(funcName, execDef, env);
          }
        }
      }
      shadowFunctions.set(funcName, effectiveWrapper);
    }
    env.setShadowEnv(language2, shadowFunctions);
    if (env.hasShadowEnvs()) {
      const capturedEnvs = env.captureAllShadowEnvs();
      for (const ref of envRefs) {
        const funcName = ref.identifier;
        const funcVar = env.getVariable(funcName);
        if (funcVar && funcVar.type === "executable") {
          funcVar.internal = {
            ...funcVar.internal ?? {},
            capturedShadowEnvs: capturedEnvs
          };
          const execDef = funcVar.internal?.executableDef;
          if (execDef) {
            execDef.capturedShadowEnvs = capturedEnvs;
          }
        }
      }
    }
    return {
      value: null,
      env
    };
  }
  const identifierNodes = directive.values?.identifier;
  if (!identifierNodes || !Array.isArray(identifierNodes) || identifierNodes.length === 0) {
    throw new Error("Exec directive missing identifier");
  }
  const identifierNode = identifierNodes[0];
  let identifier;
  if (identifierNode.type === "VariableReference" && "identifier" in identifierNode) {
    identifier = identifierNode.identifier;
  } else {
    throw new Error("Exec directive identifier must be a simple command name");
  }
  const securityLabels = directive.meta?.securityLabels || directive.values?.securityLabels;
  const descriptor = makeSecurityDescriptor({
    labels: securityLabels
  });
  const capabilityContext = createCapabilityContext({
    kind: "exe",
    descriptor,
    metadata: {
      identifier,
      filePath: env.getCurrentFilePath()
    },
    operation: {
      kind: "exe",
      identifier,
      location: directive.location
    }
  });
  let executableDef;
  if (directive.subtype === "exeCommand") {
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const withClause = directive.values?.withClause;
    if (directive.meta?.isPipelineOnly && withClause?.pipeline) {
      executableDef = {
        type: "pipeline",
        pipeline: withClause.pipeline,
        format: withClause.format,
        parallelCap: withClause.parallel,
        delayMs: withClause.delayMs,
        paramNames,
        sourceDirective: "exec"
      };
    } else {
      const commandRef = directive.values?.commandRef;
      if (commandRef) {
        let refName;
        const commandRefNodes = Array.isArray(commandRef) ? commandRef : [
          commandRef
        ];
        try {
          const refCandidate2 = commandRefNodes[0];
          if (refCandidate2 && typeof refCandidate2 === "object") {
            if ("type" in refCandidate2 && refCandidate2.type === "VariableReference" && "identifier" in refCandidate2) {
              refName = refCandidate2.identifier;
            } else if ("name" in refCandidate2 && typeof refCandidate2.name === "string") {
              refName = refCandidate2.name;
            }
          }
        } catch {
        }
        if (!refName) {
          refName = await interpolateAndRecord7(commandRef, env);
        }
        const args = directive.values?.args || [];
        const refCandidate = commandRefNodes[0];
        const isVariableRef = refCandidate && typeof refCandidate === "object" && "type" in refCandidate && (refCandidate.type === "VariableReference" || refCandidate.type === "VariableReferenceWithTail");
        const refFields = isVariableRef ? refCandidate.fields : void 0;
        const refPipes = isVariableRef ? refCandidate.pipes : void 0;
        const shouldTemplateFromRef = isVariableRef && (refCandidate.type === "VariableReferenceWithTail" || Array.isArray(refFields) && refFields.length > 0 || Array.isArray(refPipes) && refPipes.length > 0);
        const isIdentity = !shouldTemplateFromRef && isVariableRef && commandRefNodes.length === 1 && paramNames.length >= 1 && args.length === 0 && typeof refName === "string" && refName.length > 0 && refName === paramNames[0];
        if (isIdentity || shouldTemplateFromRef) {
          executableDef = {
            type: "template",
            template: isIdentity ? [
              {
                type: "VariableReference",
                identifier: refName
              }
            ] : commandRefNodes,
            paramNames,
            sourceDirective: "exec"
          };
          if (withClause) {
            executableDef.withClause = withClause;
          }
        } else {
          executableDef = {
            type: "commandRef",
            commandRef: refName,
            commandArgs: args,
            withClause,
            paramNames,
            sourceDirective: "exec"
          };
        }
      } else {
        const commandNodes = directive.values?.command;
        if (!commandNodes) {
          throw new Error("Exec command directive missing command");
        }
        const workingDir = directive.values?.workingDir;
        const workingDirMeta = directive.meta?.workingDirMeta || directive.values?.workingDirMeta;
        executableDef = {
          type: "command",
          commandTemplate: commandNodes,
          withClause,
          paramNames,
          sourceDirective: "exec",
          ...workingDir ? {
            workingDir
          } : {},
          ...workingDirMeta ? {
            workingDirMeta
          } : {}
        };
      }
    }
  } else if (directive.subtype === "exeData") {
    const dataNodes = directive.values?.data;
    if (!dataNodes) {
      throw new Error("Exec data directive missing data content");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    executableDef = {
      type: "data",
      dataTemplate: dataNodes,
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeCode") {
    const codeNodes = directive.values?.code;
    if (!codeNodes) {
      throw new Error("Exec code directive missing code");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const withClause = directive.values?.withClause;
    const language2 = directive.meta?.language || "javascript";
    const workingDir = directive.values?.workingDir;
    const workingDirMeta = directive.meta?.workingDirMeta || directive.values?.workingDirMeta;
    executableDef = {
      type: "code",
      codeTemplate: codeNodes,
      language: language2,
      paramNames,
      sourceDirective: "exec",
      ...withClause ? {
        withClause
      } : {},
      ...workingDir ? {
        workingDir
      } : {},
      ...workingDirMeta ? {
        workingDirMeta
      } : {}
    };
  } else if (directive.subtype === "exeResolver") {
    const resolverNodes = directive.values?.resolver;
    if (!resolverNodes) {
      throw new Error("Exec resolver directive missing resolver path");
    }
    const resolverPath = await interpolateAndRecord7(resolverNodes, env);
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const payloadNodes = directive.values?.payload;
    if (resolverPath === "run") {
      throw new Error("Grammar parsing issue: @exec with @run should be parsed as execCommand, not execResolver");
    }
    executableDef = {
      type: "resolver",
      resolverPath,
      payloadTemplate: payloadNodes,
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeTemplate") {
    const templateNodes = directive.values?.template;
    if (!templateNodes) {
      throw new Error("Exec template directive missing template");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    executableDef = {
      type: "template",
      template: templateNodes,
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeTemplateFile") {
    const pathNodes = directive.values?.path;
    if (!pathNodes || !Array.isArray(pathNodes) || pathNodes.length === 0) {
      throw new Error("Exec template-file directive missing path");
    }
    const evaluatedPath = await interpolate(pathNodes, env);
    const filePath = String(evaluatedPath);
    const ext = path7.extname(filePath).toLowerCase();
    if (ext !== ".att" && ext !== ".mtt") {
      throw new Error(`Unsupported template file extension for ${filePath}. Use .att (@var) or .mtt ({{var}}).`);
    }
    const fileContent = await env.readFile(filePath);
    const { parseSync } = await import('./parser-6HNWFG6W.mjs');
    const startRule = ext === ".mtt" ? "TemplateBodyMtt" : "TemplateBodyAtt";
    let templateNodes;
    try {
      templateNodes = parseSync(fileContent, {
        startRule
      });
    } catch (err) {
      try {
        let normalized = fileContent;
        if (ext === ".mtt") {
          normalized = normalized.replace(/{{\s*([A-Za-z_][\w\.]*)\s*}}/g, "@$1");
        }
        templateNodes = buildTemplateAstFromContent(normalized);
      } catch (fallbackErr) {
        throw new Error(`Failed to parse template file ${filePath}: ${err.message}`);
      }
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    executableDef = {
      type: "template",
      template: templateNodes,
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeSection") {
    const pathNodes = directive.values?.path;
    const sectionNodes = directive.values?.section;
    if (!pathNodes || !sectionNodes) {
      throw new Error("Exec section directive missing path or section");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const renameNodes = directive.values?.rename;
    executableDef = {
      type: "section",
      pathTemplate: pathNodes,
      sectionTemplate: sectionNodes,
      renameTemplate: renameNodes,
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeWhen") {
    const contentNodes = directive.values?.content;
    if (!contentNodes || !Array.isArray(contentNodes) || contentNodes.length === 0) {
      throw new Error("Exec when directive missing when expression");
    }
    const whenExprNode = contentNodes[0];
    if (!whenExprNode || whenExprNode.type !== "WhenExpression") {
      throw new Error("Exec when directive content must be a WhenExpression");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    if (process.env.DEBUG_EXEC) {
      logger.debug("Creating exe when expression:", {
        identifier,
        paramNames,
        conditionCount: whenExprNode.conditions?.length
      });
    }
    executableDef = {
      type: "code",
      codeTemplate: contentNodes,
      language: "mlld-when",
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeForeach") {
    const contentNodes = directive.values?.content;
    if (!contentNodes || !Array.isArray(contentNodes) || contentNodes.length === 0) {
      throw new Error("Exec foreach directive missing foreach expression");
    }
    const foreachNode = contentNodes[0];
    if (!foreachNode || foreachNode.type !== "foreach-command" && foreachNode.value?.type !== "foreach") {
      throw new Error("Exec foreach directive content must be a ForeachCommandExpression");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    if (process.env.DEBUG_EXEC) {
      logger.debug("Creating exe foreach expression:", {
        identifier,
        paramNames
      });
    }
    executableDef = {
      type: "code",
      codeTemplate: contentNodes,
      language: "mlld-foreach",
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeFor") {
    const contentNodes = directive.values?.content;
    if (!contentNodes || !Array.isArray(contentNodes) || contentNodes.length === 0) {
      throw new Error("Exec for directive missing for expression");
    }
    const forExprNode = contentNodes[0];
    if (!forExprNode || forExprNode.type !== "ForExpression") {
      throw new Error("Exec for directive content must be a ForExpression");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    if (process.env.DEBUG_EXEC) {
      logger.debug("Creating exe for expression:", {
        identifier,
        paramNames,
        variable: forExprNode.variable?.identifier
      });
    }
    executableDef = {
      type: "code",
      codeTemplate: contentNodes,
      language: "mlld-for",
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeBlock") {
    const statements = directive.values?.statements || [];
    const returnStmt = directive.values?.return;
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const blockNode = {
      type: "ExeBlock",
      nodeId: directive.nodeId,
      values: {
        statements,
        ...returnStmt ? {
          return: returnStmt
        } : {}
      },
      meta: {
        statementCount: directive.meta?.statementCount ?? statements.length,
        hasReturn: directive.meta?.hasReturn ?? Boolean(returnStmt)
      },
      location: directive.location
    };
    executableDef = {
      type: "code",
      codeTemplate: [
        blockNode
      ],
      language: "mlld-exe-block",
      paramNames,
      sourceDirective: "exec"
    };
  } else if (directive.subtype === "exeProse" || directive.subtype === "exeProseFile" || directive.subtype === "exeProseTemplate") {
    const configRefNodes = directive.values?.configRef;
    if (!configRefNodes || !Array.isArray(configRefNodes) || configRefNodes.length === 0) {
      throw new Error("Prose executable missing config reference");
    }
    const params = directive.values?.params || [];
    const paramNames = extractParamNames(params);
    const contentType = directive.values?.contentType;
    if (contentType === "inline") {
      const contentNodes = directive.values?.content;
      if (!contentNodes) {
        throw new Error("Inline prose executable missing content");
      }
      executableDef = {
        type: "prose",
        configRef: configRefNodes,
        contentType: "inline",
        contentTemplate: contentNodes,
        paramNames,
        sourceDirective: "exec"
      };
    } else {
      const pathNodes = directive.values?.path;
      if (!pathNodes || !Array.isArray(pathNodes) || pathNodes.length === 0) {
        throw new Error("File-based prose executable missing path");
      }
      executableDef = {
        type: "prose",
        configRef: configRefNodes,
        contentType,
        pathTemplate: pathNodes,
        paramNames,
        sourceDirective: "exec"
      };
    }
    if (process.env.DEBUG_EXEC) {
      logger.debug("Creating exe prose:", {
        identifier,
        paramNames,
        contentType,
        hasConfig: true
      });
    }
  } else {
    throw new Error(`Unsupported exec subtype: ${directive.subtype}`);
  }
  const source = {
    directive: "var",
    syntax: "code",
    hasInterpolation: false,
    isMultiLine: false
  };
  if (executableDef.type === "command" || executableDef.type === "commandRef" || executableDef.type === "pipeline") {
    source.syntax = "command";
  } else if (executableDef.type === "template") {
    source.syntax = "template";
  } else if (executableDef.type === "data") {
    source.syntax = "object";
  } else if (executableDef.type === "prose") {
    source.syntax = "prose";
  }
  const language = executableDef.type === "code" ? executableDef.language : void 0;
  const location = astLocationToSourceLocation(directive.location, env.getCurrentFilePath());
  const metadata = {
    definedAt: location,
    executableDef
  };
  if (env.hasShadowEnvs()) {
    metadata.capturedShadowEnvs = env.captureAllShadowEnvs();
  }
  if (env.getIsImporting()) {
    metadata.capturedModuleEnv = env.captureModuleEnvironment();
  }
  const executableTypeForVariable = executableDef.type === "code" ? "code" : executableDef.type === "data" ? "data" : "command";
  let executableDescriptor = descriptor;
  if (executableDef.type === "command") {
    const commandTaintDescriptor = makeSecurityDescriptor({
      taint: [
        "src:exec"
      ]
    });
    executableDescriptor = executableDescriptor ? env.mergeSecurityDescriptors(executableDescriptor, commandTaintDescriptor) : commandTaintDescriptor;
  }
  const metadataWithSecurity = VariableMetadataUtils.applySecurityMetadata(metadata, {
    existingDescriptor: executableDescriptor,
    capability: capabilityContext
  });
  const variable = createExecutableVariable(identifier, executableTypeForVariable, "", executableDef.paramNames || [], language, source, {
    metadata: metadataWithSecurity,
    internal: {
      executableDef
    }
  });
  if (executableDef.type === "command") {
    variable.value.template = executableDef.commandTemplate;
  } else if (executableDef.type === "code") {
    variable.value.template = executableDef.codeTemplate;
  } else if (executableDef.type === "template") {
    variable.value.template = executableDef.template;
  } else if (executableDef.type === "data") {
    variable.value.template = executableDef.dataTemplate;
  }
  env.setVariable(identifier, variable);
  return {
    value: executableDef,
    env
  };
}
__name(evaluateExe, "evaluateExe");
function createSyncJsWrapper(funcName, definition, env) {
  return function(...args) {
    const params = definition.paramNames || [];
    env.createChild();
    const codeParams = {};
    for (let i = 0; i < params.length; i++) {
      const paramName = params[i];
      let argValue = args[i];
      if (argValue !== void 0) {
        if (isStructuredValue(argValue)) {
          argValue = asData(argValue);
        } else if (isFileLoadedValue(argValue)) {
          argValue = argValue.content;
        }
        if (typeof argValue === "string") {
          const numValue = Number(argValue);
          if (!isNaN(numValue) && argValue.trim() !== "") {
            argValue = numValue;
          }
        }
      }
      codeParams[paramName] = argValue;
    }
    const codeTemplate = definition.codeTemplate;
    if (!codeTemplate) {
      throw new Error(`Function ${funcName} has no code template`);
    }
    let code;
    try {
      code = codeTemplate.map((node) => {
        if (node.type === "Text") {
          return node.content;
        }
        throw new Error(`Synchronous shadow functions only support simple code templates`);
      }).join("");
    } catch (error) {
      throw new Error(`Cannot create synchronous wrapper for ${funcName}: ${error.message}`);
    }
    const capturedEnvs = definition.capturedShadowEnvs;
    const shadowEnv = resolveShadowEnvironment("js", capturedEnvs, env);
    const paramSet = new Set(Object.keys(codeParams));
    const { names: shadowNames, values: shadowValues } = mergeShadowFunctions(shadowEnv, void 0, paramSet);
    const allParamNames = [
      ...Object.keys(codeParams),
      ...shadowNames
    ];
    const allParamValues = [
      ...Object.values(codeParams),
      ...shadowValues
    ];
    let functionBody = code;
    const trimmedCode = code.trim();
    const isExpression = !code.includes("return") && !code.includes(";") || trimmedCode.startsWith("(") && trimmedCode.endsWith(")");
    if (isExpression) {
      functionBody = `return (${functionBody})`;
    }
    const fn = new Function(...allParamNames, functionBody);
    return fn(...allParamValues);
  };
}
__name(createSyncJsWrapper, "createSyncJsWrapper");
function createExecWrapper(execName, execVar, env) {
  return async function(...args) {
    const definition = execVar.internal?.executableDef;
    if (!definition) {
      throw new Error(`Executable ${execName} has no definition in metadata`);
    }
    const params = definition.paramNames || [];
    const execEnv = env.createChild();
    for (let i = 0; i < params.length; i++) {
      const paramName = params[i];
      const argValue = args[i];
      if (argValue !== void 0) {
        const stringValue = typeof argValue === "string" ? argValue : argValue === null || argValue === void 0 ? String(argValue) : typeof argValue === "object" ? isStructuredValue(argValue) ? asText(argValue) : JSON.stringify(argValue) : String(argValue);
        const paramVar = createSimpleTextVariable(paramName, stringValue, {
          directive: "var",
          syntax: "quoted",
          hasInterpolation: false,
          isMultiLine: false
        }, {
          internal: {
            isSystem: true,
            isParameter: true
          }
        });
        execEnv.setParameterVariable(paramName, paramVar);
      }
    }
    let result;
    if (definition.type === "command") {
      const commandTemplate = definition.commandTemplate;
      if (!commandTemplate) {
        throw new Error(`Command ${execName} has no command template`);
      }
      const command = await interpolateAndRecord7(commandTemplate, execEnv, InterpolationContext.ShellCommand);
      const envVars = {};
      for (let i = 0; i < params.length; i++) {
        const paramName = params[i];
        const argValue = args[i];
        if (argValue !== void 0) {
          envVars[paramName] = String(argValue);
        }
      }
      result = await execEnv.executeCommand(command, {
        env: envVars
      });
    } else if (definition.type === "code") {
      const codeTemplate = definition.codeTemplate;
      if (!codeTemplate) {
        throw new Error(`Code command ${execName} has no code template`);
      }
      const code = await interpolateAndRecord7(codeTemplate, execEnv);
      const codeParams = {};
      for (let i = 0; i < params.length; i++) {
        const paramName = params[i];
        let argValue = args[i];
        if (argValue !== void 0) {
          argValue = argValue instanceof Promise ? await argValue : argValue;
          argValue = AutoUnwrapManager.unwrap(argValue);
          if (typeof argValue === "string") {
            const numValue = Number(argValue);
            if (!isNaN(numValue) && argValue.trim() !== "") {
              argValue = numValue;
            }
          }
        }
        codeParams[paramName] = argValue;
      }
      const capturedEnvs = execVar.internal?.capturedShadowEnvs;
      if (capturedEnvs && (definition.language === "js" || definition.language === "javascript" || definition.language === "node" || definition.language === "nodejs")) {
        codeParams.__capturedShadowEnvs = capturedEnvs;
      }
      result = await execEnv.executeCode(code, definition.language || "javascript", codeParams);
    } else if (definition.type === "template") {
      const templateNodes = definition.template;
      if (!templateNodes) {
        throw new Error(`Template ${execName} has no template content`);
      }
      result = await interpolateAndRecord7(templateNodes, execEnv);
    } else if (definition.type === "data") {
      const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
      const dataValue = await evaluateDataValue2(definition.dataTemplate, execEnv);
      try {
        return JSON.parse(JSON.stringify(dataValue));
      } catch {
        return dataValue;
      }
    } else if (definition.type === "section") {
      throw new Error(`Section executables cannot be invoked from shadow environments yet`);
    } else if (definition.type === "resolver") {
      throw new Error(`Resolver executables cannot be invoked from shadow environments yet`);
    } else if (definition.type === "commandRef") {
      throw new Error(`Command reference executables cannot be invoked from shadow environments yet`);
    } else {
      throw new Error(`Unknown command type: ${definition.type}`);
    }
    try {
      return JSON.parse(result);
    } catch {
      return result;
    }
  };
}
__name(createExecWrapper, "createExecWrapper");

// interpreter/eval/when-expression.ts
var cachedInterpolateFn = null;
async function getInterpolateFn() {
  if (!cachedInterpolateFn) {
    const module = await import('./interpreter-MW7QI3FC.mjs');
    cachedInterpolateFn = module.interpolate;
  }
  return cachedInterpolateFn;
}
__name(getInterpolateFn, "getInterpolateFn");
function isNoneCondition2(condition) {
  return condition?.type === "Literal" && condition?.valueType === "none";
}
__name(isNoneCondition2, "isNoneCondition");
async function normalizeActionValue(value, actionEnv) {
  let normalized = value;
  if (normalized && typeof normalized === "object" && "wrapperType" in normalized && Array.isArray(normalized.content)) {
    try {
      const interpolateFn = await getInterpolateFn();
      normalized = await interpolateFn(normalized.content, actionEnv);
    } catch {
      normalized = String(normalized);
    }
  }
  if (isStructuredValue(normalized)) {
    return normalized;
  }
  if (normalized && typeof normalized === "object" && "type" in normalized) {
    const nodeType = normalized.type;
    if (nodeType === "Literal" && "value" in normalized) {
      const valueType = normalized.valueType;
      if (valueType === "done" || valueType === "continue") {
        return normalized;
      }
      normalized = normalized.value;
    } else {
      const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
      try {
        normalized = await extractVariableValue2(normalized, actionEnv);
      } catch (error) {
        logger.debug("Could not extract variable value in when expression:", error);
      }
    }
  }
  return normalized;
}
__name(normalizeActionValue, "normalizeActionValue");
async function evaluateControlLiteral(literal, env) {
  const val = literal.value;
  if (Array.isArray(val)) {
    const target = val.length === 1 ? val[0] : val;
    if (target && typeof target === "object" && "type" in target) {
      const evaluated2 = await evaluateUnifiedExpression(target, env);
      return evaluated2.value;
    }
    const evaluated = await evaluate2(val, env, {
      isExpression: true
    });
    return evaluated.value;
  }
  if (val === "done" || val === "continue") {
    return void 0;
  }
  return val;
}
__name(evaluateControlLiteral, "evaluateControlLiteral");
function validateNonePlacement2(entries) {
  const conditionPairs = entries.filter(isConditionPair);
  let foundNone = false;
  let foundWildcard = false;
  for (let i = 0; i < conditionPairs.length; i++) {
    const condition = conditionPairs[i].condition;
    if (condition.length === 1 && isNoneCondition2(condition[0])) {
      foundNone = true;
    } else if (condition.length === 1 && condition[0]?.type === "Literal" && condition[0]?.valueType === "wildcard") {
      foundWildcard = true;
      if (foundNone) {
        continue;
      }
    } else if (foundNone) {
      throw new MlldWhenExpressionError('The "none" keyword can only appear as the last condition(s) in a when block', condition[0]?.location);
    }
    if (foundWildcard && condition.length === 1 && isNoneCondition2(condition[0])) {
      throw new MlldWhenExpressionError('The "none" keyword cannot appear after "*" (wildcard) as it would never be reached', condition[0].location);
    }
  }
}
__name(validateNonePlacement2, "validateNonePlacement");
async function evaluateWhenExpression(node, env, context2, options) {
  validateNonePlacement2(node.conditions);
  const errors = [];
  const denyMode = Boolean(options?.denyMode);
  let deniedHandlerRan = false;
  const isFirstMode = node.meta?.modifier === "first";
  const boundIdentifier = node.boundIdentifier || node.meta?.boundIdentifier;
  const hasBoundValue = Boolean(node.boundValue && typeof boundIdentifier === "string" && boundIdentifier.length > 0);
  let boundValue;
  if (hasBoundValue) {
    const boundResult = await evaluate2(node.boundValue, env, context2);
    boundValue = boundResult.value;
  }
  const setBoundValue = /* @__PURE__ */ __name((targetEnv) => {
    if (!hasBoundValue) return;
    const importer = new VariableImporter();
    const variable = importer.createVariableFromValue(boundIdentifier, boundValue, "let", void 0, {
      env: targetEnv
    });
    targetEnv.setVariable(boundIdentifier, variable);
  }, "setBoundValue");
  let lastMatchValue = null;
  let hasMatch = false;
  let hasNonNoneMatch = false;
  let hasValueProducingMatch = false;
  let lastNoneValue = null;
  let accumulatedEnv = env;
  const buildResult = /* @__PURE__ */ __name((value, environment) => ({
    value,
    env: environment,
    internal: deniedHandlerRan ? {
      deniedHandlerRan: true
    } : void 0
  }), "buildResult");
  if (node.conditions.length === 0) {
    return buildResult(null, env);
  }
  const conditionPairs = node.conditions.filter(isConditionPair);
  const hasAnyAction = conditionPairs.some((c) => c.action && c.action.length > 0);
  if (!hasAnyAction) {
    logger.warn("WhenExpression has no actions defined");
    return buildResult(null, env);
  }
  for (let i = 0; i < conditionPairs.length; i++) {
    const pair = conditionPairs[i];
    if (pair.action && pair.action.length > 0) {
      const hasCodeExecution = pair.action.some((actionNode) => {
        if (typeof actionNode === "object" && actionNode !== null && "type" in actionNode) {
          return actionNode.type === "code" || actionNode.type === "command" || actionNode.type === "nestedDirective" && actionNode.directive === "run";
        }
        return false;
      });
      if (hasCodeExecution) {
        throw new MlldWhenExpressionError("Code blocks are not supported in when expressions. Define your logic in a separate /exe function and call it instead.", node.location, {
          conditionIndex: i,
          phase: "action",
          type: "code-block-not-supported"
        });
      }
    }
  }
  for (let i = 0; i < node.conditions.length; i++) {
    const entry = node.conditions[i];
    if (isLetAssignment(entry)) {
      let value;
      const firstValue = Array.isArray(entry.value) && entry.value.length > 0 ? entry.value[0] : entry.value;
      const isRawPrimitive = firstValue === null || typeof firstValue === "number" || typeof firstValue === "boolean" || typeof firstValue === "string" && !("type" in firstValue);
      if (isRawPrimitive) {
        value = entry.value.length === 1 ? firstValue : entry.value;
      } else {
        const valueResult = await evaluate2(entry.value, accumulatedEnv, {
          ...context2 || {},
          isExpression: true
        });
        value = valueResult.value;
      }
      const importer = new VariableImporter();
      const variable = importer.createVariableFromValue(entry.identifier, value, "let", void 0, {
        env: accumulatedEnv
      });
      accumulatedEnv = accumulatedEnv.createChild();
      accumulatedEnv.setVariable(entry.identifier, variable);
      continue;
    }
    if (isAugmentedAssignment(entry)) {
      const existing = accumulatedEnv.getVariable(entry.identifier);
      if (!existing) {
        throw new MlldWhenExpressionError(`Cannot use += on undefined variable @${entry.identifier}. Use "let @${entry.identifier} = ..." first.`, entry.location);
      }
      let rhsValue;
      const firstValue = Array.isArray(entry.value) && entry.value.length > 0 ? entry.value[0] : entry.value;
      const isRawPrimitive = firstValue === null || typeof firstValue === "number" || typeof firstValue === "boolean" || typeof firstValue === "string" && !("type" in firstValue);
      if (isRawPrimitive) {
        rhsValue = entry.value.length === 1 ? firstValue : entry.value;
      } else {
        const rhsResult = await evaluate2(entry.value, accumulatedEnv, {
          ...context2 || {},
          isExpression: true
        });
        rhsValue = rhsResult.value;
      }
      const existingValue = await extractVariableValue(existing, accumulatedEnv);
      const combined = combineValues(existingValue, rhsValue, entry.identifier);
      const importer = new VariableImporter();
      const updatedVar = importer.createVariableFromValue(entry.identifier, combined, "let", void 0, {
        env: accumulatedEnv
      });
      accumulatedEnv.updateVariable(entry.identifier, updatedVar);
      continue;
    }
    const pair = entry;
    if (pair.condition.length === 1 && isNoneCondition2(pair.condition[0])) {
      continue;
    }
    if (denyMode && !conditionTargetsDenied(pair.condition)) {
      continue;
    }
    try {
      const conditionEnv = hasBoundValue ? accumulatedEnv.createChild() : accumulatedEnv;
      if (hasBoundValue) setBoundValue(conditionEnv);
      const conditionResult = await evaluateCondition(pair.condition, conditionEnv);
      if (process.env.DEBUG_WHEN) {
        logger.debug("WhenExpression condition result:", {
          index: i,
          conditionResult,
          hasAction: !!(pair.action && pair.action.length > 0)
        });
      }
      if (conditionResult) {
        hasMatch = true;
        hasNonNoneMatch = true;
        const matchedDeniedCondition = conditionTargetsDenied(pair.condition);
        if (matchedDeniedCondition) {
          deniedHandlerRan = true;
        }
        if (!pair.action || pair.action.length === 0) {
          continue;
        }
        try {
          if (Array.isArray(pair.action) && pair.action.length >= 1) {
            const first = pair.action[0];
            if (first && typeof first === "object" && first.type === "Literal" && first.value === "retry") {
              let value2 = "retry";
              if (pair.action.length > 1) {
                const hintNodes = pair.action.slice(1);
                const hintEnv = accumulatedEnv.createChild();
                try {
                  let hintValue;
                  const firstNode = hintNodes[0];
                  if (firstNode && typeof firstNode === "object" && "type" in firstNode && firstNode.type === "object") {
                    const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
                    hintValue = await evaluateDataValue2(firstNode, hintEnv);
                  } else {
                    const interpolateFn = await getInterpolateFn();
                    if (firstNode && typeof firstNode === "object" && "content" in firstNode && Array.isArray(firstNode.content)) {
                      hintValue = await interpolateFn(firstNode.content, hintEnv);
                    } else {
                      hintValue = await interpolateFn(hintNodes, hintEnv);
                    }
                    if (typeof hintValue !== "string") {
                      try {
                        hintValue = String(hintValue);
                      } catch {
                        hintValue = "";
                      }
                    }
                  }
                  value2 = {
                    value: "retry",
                    hint: hintValue
                  };
                } catch {
                  value2 = "retry";
                }
              }
              if (isFirstMode) {
                return buildResult(value2, accumulatedEnv);
              }
              lastMatchValue = value2;
              hasMatch = true;
              hasValueProducingMatch = true;
              continue;
            }
          }
          if (Array.isArray(pair.action) && pair.action[0]) {
            const firstAction = pair.action[0];
            logger.debug("WhenExpression evaluating action:", {
              actionType: firstAction.type,
              actionKind: firstAction.kind,
              actionSubtype: firstAction.subtype
            });
          }
          const actionEnv = accumulatedEnv.createChild();
          let actionResult = null;
          let value;
          const wrapperCandidate = pair.action.length === 1 && pair.action[0] && typeof pair.action[0] === "object" && !("type" in pair.action[0]) && Array.isArray(pair.action[0].content) ? pair.action[0] : null;
          if (wrapperCandidate) {
            const interpolateFn = await getInterpolateFn();
            value = await interpolateFn(wrapperCandidate.content, actionEnv, InterpolationContext.Template);
          } else {
            actionResult = await evaluate2(pair.action, actionEnv, context2);
            value = actionResult.value;
          }
          value = await normalizeActionValue(value, actionEnv);
          const executionEnv = actionResult?.env ?? actionEnv;
          if (isDoneLiteral(value)) {
            const resolved = await evaluateControlLiteral(value, executionEnv);
            value = {
              __whileControl: "done",
              value: resolved
            };
          } else if (isContinueLiteral(value)) {
            const resolved = await evaluateControlLiteral(value, executionEnv);
            value = {
              __whileControl: "continue",
              value: resolved
            };
          }
          if (Array.isArray(pair.action) && pair.action.length === 1) {
            const singleAction = pair.action[0];
            if (singleAction && typeof singleAction === "object" && singleAction.type === "Directive") {
              const directiveKind = singleAction.kind;
              if (directiveKind === "show") {
                const textValue = typeof value === "string" ? value : isStructuredValue(value) ? asText(value) : value === null || value === void 0 ? "" : String(value);
                value = {
                  __whenEffect: "show",
                  text: textValue
                };
              } else if (directiveKind === "output") {
                value = "";
              } else if (directiveKind === "var") {
                const identifier = singleAction.values?.identifier;
                if (identifier && Array.isArray(identifier) && identifier[0]) {
                  const varName = identifier[0].identifier;
                  if (varName && actionResult.env) {
                    try {
                      const variable = actionResult.env.getVariable(varName);
                      if (variable) {
                        const { extractVariableValue: extractVariableValue2 } = await import('./variable-resolution-HFG3FTZK.mjs');
                        const variableValue = await extractVariableValue2(variable, actionResult.env);
                        value = variableValue;
                      }
                    } catch (e) {
                      logger.debug("Could not get variable value for when expression:", {
                        varName,
                        error: e
                      });
                    }
                  }
                }
              }
            }
          }
          if (node.withClause && node.withClause.pipes) {
            value = await applyTailModifiers(value, node.withClause.pipes, executionEnv);
          }
          accumulatedEnv.mergeChild(executionEnv);
          if (value && typeof value === "object" && "__whileControl" in value) {
            return buildResult(value, accumulatedEnv);
          }
          if (isFirstMode) {
            return buildResult(value, accumulatedEnv);
          }
          lastMatchValue = value;
          if (Array.isArray(pair.action) && pair.action.length === 1) {
            const singleAction = pair.action[0];
            if (singleAction && typeof singleAction === "object" && singleAction.type === "Directive" && singleAction.kind === "var") {
            } else {
              hasValueProducingMatch = true;
            }
          } else {
            hasValueProducingMatch = true;
          }
        } catch (actionError) {
          throw new MlldWhenExpressionError(`Error evaluating action for condition ${i + 1}: ${actionError.message}`, node.location, {
            conditionIndex: i,
            phase: "action",
            originalError: actionError
          });
        }
      }
    } catch (conditionError) {
      errors.push(new MlldWhenExpressionError(`Error evaluating condition ${i + 1}: ${conditionError.message}`, node.location, {
        conditionIndex: i,
        phase: "condition",
        originalError: conditionError
      }));
    }
  }
  if (!hasValueProducingMatch && !denyMode) {
    for (let i = 0; i < node.conditions.length; i++) {
      const entry = node.conditions[i];
      if (isLetAssignment(entry)) {
        continue;
      }
      const pair = entry;
      if (!(pair.condition.length === 1 && isNoneCondition2(pair.condition[0]))) {
        continue;
      }
      if (!pair.action || pair.action.length === 0) {
        continue;
      }
      try {
        const actionEnv = accumulatedEnv.createChild();
        const actionResult = await evaluate2(pair.action, actionEnv, context2);
        let value = actionResult.value;
        value = await normalizeActionValue(value, actionEnv);
        if (node.withClause && node.withClause.pipes) {
          value = await applyTailModifiers(value, node.withClause.pipes, actionResult.env);
        }
        accumulatedEnv.mergeChild(actionEnv);
        if (isFirstMode) {
          return buildResult(value, accumulatedEnv);
        }
        lastNoneValue = value;
        hasMatch = true;
      } catch (actionError) {
        throw new MlldWhenExpressionError(`Error evaluating none action for condition ${i + 1}: ${actionError.message}`, node.location, {
          conditionIndex: i,
          phase: "action",
          originalError: actionError
        });
      }
    }
    if (lastNoneValue !== null) {
      lastMatchValue = lastNoneValue;
    }
  }
  if (hasMatch) {
    return buildResult(lastMatchValue, accumulatedEnv);
  }
  if (errors.length > 0) {
    throw new MlldWhenExpressionError(`When expression evaluation failed with ${errors.length} condition errors`, node.location, {
      errors
    });
  }
  return buildResult(null, accumulatedEnv);
}
__name(evaluateWhenExpression, "evaluateWhenExpression");
async function applyTailModifiers(value, pipes, env) {
  let result = value;
  for (const pipe of pipes) {
    const pipeEnv = env.createChild();
    const { createStructuredValueVariable: createStructuredValueVariable2 } = await import('./variable-FNPDYIEH.mjs');
    const structuredInput = ensureStructuredValue(result, void 0, String(result));
    const pipelineVar = createStructuredValueVariable2("_pipelineInput", structuredInput, {
      directive: "var",
      syntax: "reference",
      hasInterpolation: false,
      isMultiLine: false
    }, {
      internal: {
        isPipelineInput: true,
        pipelineStage: 0
      }
    });
    pipeEnv.setVariable("_pipelineInput", pipelineVar);
    const pipeResult = await evaluate2(pipe, pipeEnv);
    result = pipeResult.value;
  }
  return result;
}
__name(applyTailModifiers, "applyTailModifiers");
async function peekWhenExpressionType(node, env) {
  const actionTypes = /* @__PURE__ */ new Set();
  for (const entry of node.conditions) {
    if (isLetAssignment(entry)) {
      continue;
    }
    const pair = entry;
    if (pair.action && pair.action.length > 0) {
      const firstNode = pair.action[0];
      if (firstNode.type === "Text") {
        actionTypes.add("simple-text");
      } else if (firstNode.type === "Literal") {
        const literal = firstNode;
        if (typeof literal.value === "number") {
          actionTypes.add("primitive");
        } else if (typeof literal.value === "boolean") {
          actionTypes.add("primitive");
        } else if (literal.value === null) {
          actionTypes.add("primitive");
        }
      } else if (firstNode.type === "object") {
        actionTypes.add("object");
      } else if (firstNode.type === "array") {
        actionTypes.add("array");
      } else if (firstNode.type === "Directive") {
        actionTypes.add("computed");
      } else {
        actionTypes.add("computed");
      }
    }
  }
  if (actionTypes.size === 1) {
    return Array.from(actionTypes)[0];
  }
  return "computed";
}
__name(peekWhenExpressionType, "peekWhenExpressionType");

// interpreter/eval/for.ts
function looksLikeFileData(value) {
  if (!value || typeof value !== "object") return false;
  const obj = value;
  if (typeof obj.content !== "string") return false;
  return typeof obj.filename === "string" || typeof obj.relative === "string" || typeof obj.absolute === "string";
}
__name(looksLikeFileData, "looksLikeFileData");
function ensureVariable(name, value, env) {
  if (isVariable(value)) {
    return value;
  }
  if (isLoadContentResult(value)) {
    const variable = createObjectVariable(name, value, false, {
      directive: "var",
      syntax: "object",
      hasInterpolation: false,
      isMultiLine: false
    }, {
      isLoadContentResult: true,
      source: "for-loop"
    });
    variable.mx = {
      ...variable.mx ?? {},
      filename: value.filename,
      relative: value.relative,
      absolute: value.absolute,
      ext: value.ext ?? value._extension,
      tokest: value.tokest ?? value._metrics?.tokest,
      tokens: value.tokens ?? value._metrics?.tokens
    };
    return variable;
  }
  if (isStructuredValue(value)) {
    const variable = createObjectVariable(name, value, false, {
      directive: "var",
      syntax: "object",
      hasInterpolation: false,
      isMultiLine: false
    }, {
      arrayType: value.type === "array" ? "structured-value-array" : void 0,
      source: "for-loop"
    });
    if (value.mx) {
      variable.mx = {
        ...value.mx
      };
    }
    return variable;
  }
  if (looksLikeFileData(value)) {
    const importer2 = new VariableImporter();
    const variable = importer2.createVariableFromValue(name, value, "for-loop", void 0, {
      env
    });
    variable.mx = {
      ...variable.mx ?? {},
      filename: value.filename,
      relative: value.relative,
      absolute: value.absolute,
      ext: value.ext,
      tokest: value.tokest,
      tokens: value.tokens
    };
    return variable;
  }
  const importer = new VariableImporter();
  return importer.createVariableFromValue(name, value, "for-loop", void 0, {
    env
  });
}
__name(ensureVariable, "ensureVariable");
function formatFieldPath(fields) {
  if (!fields || fields.length === 0) {
    return null;
  }
  const parts = [];
  for (const field of fields) {
    const value = field.value;
    switch (field.type) {
      case "field":
      case "stringIndex":
      case "bracketAccess":
      case "numericField":
        parts.push(typeof value === "number" ? String(value) : String(value ?? ""));
        break;
      case "arrayIndex":
      case "variableIndex":
        parts.push(`[${typeof value === "number" ? value : String(value ?? "")}]`);
        break;
      case "arraySlice":
        parts.push(`[${field.start ?? ""}:${field.end ?? ""}]`);
        break;
      case "arrayFilter":
        parts.push("[?]");
        break;
      default:
        parts.push(String(value ?? ""));
        break;
    }
  }
  return parts.map((part, index) => part.startsWith("[") || index === 0 ? part : `.${part}`).join("");
}
__name(formatFieldPath, "formatFieldPath");
function enhanceFieldAccessError(error, options) {
  if (!(error instanceof FieldAccessError)) {
    return error;
  }
  const pathSuffix = options.fieldPath ? `.${options.fieldPath}` : "";
  const contextParts = [];
  if (options.key !== null && options.key !== void 0) {
    contextParts.push(`key ${String(options.key)}`);
  } else if (options.index >= 0) {
    contextParts.push(`index ${options.index}`);
  }
  const context2 = contextParts.length > 0 ? ` (${contextParts.join(", ")})` : "";
  const message = `${error.message} in for binding @${options.varName}${pathSuffix}${context2}`;
  const enhancedDetails = {
    ...error.details || {},
    iterationIndex: options.index,
    iterationKey: options.key
  };
  return new FieldAccessError(message, enhancedDetails, {
    cause: error,
    sourceLocation: error.sourceLocation ?? options.sourceLocation
  });
}
__name(enhanceFieldAccessError, "enhanceFieldAccessError");
function withIterationMxKey(variable, key) {
  if (key === null || typeof key === "undefined") {
    return variable;
  }
  if (typeof key !== "string" && typeof key !== "number") {
    return variable;
  }
  return {
    ...variable,
    mx: {
      ...variable.mx ?? {},
      key
    }
  };
}
__name(withIterationMxKey, "withIterationMxKey");
function formatIterationError(error) {
  if (error instanceof Error) {
    let message = error.message;
    if (message.startsWith("Directive error (")) {
      const prefixEnd = message.indexOf(": ");
      if (prefixEnd >= 0) {
        message = message.slice(prefixEnd + 2);
      }
      const lineIndex = message.indexOf(" at line ");
      if (lineIndex >= 0) {
        message = message.slice(0, lineIndex);
      }
    }
    return message;
  }
  if (typeof error === "string") return error;
  try {
    return JSON.stringify(error);
  } catch {
    return String(error);
  }
}
__name(formatIterationError, "formatIterationError");
function resetForErrorsContext(env, errors) {
  const mxManager = env.getContextManager?.();
  if (!mxManager) return;
  while (mxManager.popGenericContext("for")) {
  }
  mxManager.pushGenericContext("for", {
    errors,
    timestamp: Date.now()
  });
  mxManager.setLatestErrors(errors);
}
__name(resetForErrorsContext, "resetForErrorsContext");
function findVariableOwner2(env, name) {
  let current = env;
  while (current) {
    if (current.getCurrentVariables().has(name)) return current;
    current = current.getParent();
  }
  return void 0;
}
__name(findVariableOwner2, "findVariableOwner");
function isDescendantEnvironment2(env, ancestor) {
  let current = env;
  while (current) {
    if (current === ancestor) return true;
    current = current.getParent();
  }
  return false;
}
__name(isDescendantEnvironment2, "isDescendantEnvironment");
async function evaluateForDirective(directive, env) {
  const varNode = directive.values.variable[0];
  const varName = varNode.identifier;
  const varFields = varNode.fields;
  const fieldPathString = formatFieldPath(varFields);
  process.env.DEBUG_FOR === "1" || process.env.DEBUG_FOR === "true" || process.env.MLLD_DEBUG === "true";
  env.pushDirective("/for", `@${varName} in ...`, directive.location);
  try {
    const sourceNode = Array.isArray(directive.values.source) ? directive.values.source[0] : directive.values.source;
    const sourceResult = await evaluate2(sourceNode, env);
    const sourceValue = sourceResult.value;
    const iterable = toIterable(sourceValue);
    if (!iterable) {
      const receivedType = typeof sourceValue;
      const preview2 = (() => {
        try {
          if (receivedType === "object") return JSON.stringify(sourceValue)?.slice(0, 120);
          return String(sourceValue)?.slice(0, 120);
        } catch {
          return String(sourceValue);
        }
      })();
      throw new MlldDirectiveError(`Type mismatch: /for expects an array. Received: ${receivedType}${preview2 ? ` (${preview2})` : ""}`, "for", {
        location: directive.location,
        context: {
          expected: "array",
          receivedType
        }
      });
    }
    const specified = directive.values.forOptions;
    const inherited = env.__forOptions;
    const effective = specified ?? inherited;
    const iterableArray = Array.from(iterable);
    const forErrors = effective?.parallel ? [] : null;
    if (forErrors) {
      resetForErrorsContext(env, forErrors);
    }
    const runOne = /* @__PURE__ */ __name(async (entry, idx) => {
      const [key, value] = entry;
      const iterationRoot = env.createChildEnvironment();
      if (effective?.parallel) {
        iterationRoot.__parallelIsolationRoot = iterationRoot;
      }
      let childEnv = iterationRoot;
      if (effective) childEnv.__forOptions = effective;
      let derivedValue;
      if (varFields && varFields.length > 0) {
        try {
          const accessed = await accessFields(value, varFields, {
            env: childEnv,
            preserveContext: true,
            sourceLocation: varNode.location
          });
          derivedValue = accessed?.value ?? accessed;
          inheritExpressionProvenance(derivedValue, value);
        } catch (error) {
          throw enhanceFieldAccessError(error, {
            fieldPath: fieldPathString,
            varName,
            index: idx,
            key: key ?? null,
            sourceLocation: varNode.location
          });
        }
      }
      const iterationVar = ensureVariable(varName, value, env);
      childEnv.setVariable(varName, withIterationMxKey(iterationVar, key));
      if (typeof derivedValue !== "undefined" && fieldPathString) {
        const derivedVar = ensureVariable(`${varName}.${fieldPathString}`, derivedValue, env);
        childEnv.setVariable(`${varName}.${fieldPathString}`, derivedVar);
      }
      if (key !== null && typeof key === "string") {
        const keyVar = ensureVariable(`${varName}_key`, key, env);
        childEnv.setVariable(`${varName}_key`, keyVar);
      }
      const actionNodes = directive.values.action;
      const retry = new RateLimitRetry();
      while (true) {
        try {
          if (directive.meta?.actionType === "block") {
            let blockEnv = childEnv;
            for (const actionNode of actionNodes) {
              if (isLetAssignment(actionNode)) {
                blockEnv = await evaluateLetAssignment(actionNode, blockEnv);
              } else if (isAugmentedAssignment(actionNode)) {
                if (effective?.parallel) {
                  const owner = findVariableOwner2(blockEnv, actionNode.identifier);
                  if (!owner || !isDescendantEnvironment2(owner, iterationRoot)) {
                    throw new MlldDirectiveError(`Parallel for block cannot mutate outer variable @${actionNode.identifier}.`, "for", {
                      location: actionNode.location
                    });
                  }
                }
                blockEnv = await evaluateAugmentedAssignment(actionNode, blockEnv);
              } else if (actionNode.type === "WhenExpression" && actionNode.meta?.modifier !== "first") {
                const nodeWithFirst = {
                  ...actionNode,
                  meta: {
                    ...actionNode.meta || {},
                    modifier: "first"
                  }
                };
                const actionResult = await evaluateWhenExpression(nodeWithFirst, blockEnv);
                blockEnv = actionResult.env || blockEnv;
              } else {
                const actionResult = await evaluate2(actionNode, blockEnv);
                blockEnv = actionResult.env || blockEnv;
              }
            }
            childEnv = blockEnv;
          } else {
            let actionResult = {
              value: void 0,
              env: childEnv
            };
            for (const actionNode of actionNodes) {
              if (actionNode.type === "WhenExpression" && actionNode.meta?.modifier !== "first") {
                const nodeWithFirst = {
                  ...actionNode,
                  meta: {
                    ...actionNode.meta || {},
                    modifier: "first"
                  }
                };
                actionResult = await evaluateWhenExpression(nodeWithFirst, childEnv);
              } else {
                actionResult = await evaluate2(actionNode, childEnv);
              }
              if (actionResult.env) childEnv = actionResult.env;
            }
            if (directive.values.action.length === 1 && directive.values.action[0].type === "ExecInvocation" && actionResult.value !== void 0 && actionResult.value !== null) {
              const materialized = materializeDisplayValue(actionResult.value, void 0, actionResult.value);
              let outputContent = materialized.text;
              if (!outputContent.endsWith("\n")) {
                outputContent += "\n";
              }
              if (materialized.descriptor) {
                env.recordSecurityDescriptor(materialized.descriptor);
              }
              env.emitEffect("both", outputContent, {
                source: directive.values.action[0].location
              });
            }
          }
          retry.reset();
          break;
        } catch (err) {
          if (isRateLimitError(err)) {
            const again = await retry.wait();
            if (again) continue;
          }
          if (forErrors) {
            forErrors.push({
              index: idx,
              key: key ?? null,
              message: formatIterationError(err),
              error: formatIterationError(err),
              value
            });
            return;
          }
          throw err;
        }
      }
      return;
    }, "runOne");
    if (effective?.parallel) {
      const cap = Math.min(effective.cap ?? getParallelLimit(), iterableArray.length);
      await runWithConcurrency(iterableArray, cap, runOne, {
        ordered: false,
        paceMs: effective.rateMs
      });
    } else {
      for (let i = 0; i < iterableArray.length; i++) {
        await runOne(iterableArray[i], i);
      }
    }
  } finally {
    env.popDirective();
  }
  return {
    value: void 0,
    env
  };
}
__name(evaluateForDirective, "evaluateForDirective");
async function evaluateForExpression(expr, env) {
  const varName = expr.variable.identifier;
  const varFields = expr.variable.fields;
  const fieldPathString = formatFieldPath(varFields);
  const sourceResult = await evaluate2(expr.source, env, {
    isExpression: true
  });
  const sourceValue = sourceResult.value;
  const iterable = toIterable(sourceValue);
  if (!iterable) {
    const receivedType = typeof sourceValue;
    const preview2 = (() => {
      try {
        if (receivedType === "object") return JSON.stringify(sourceValue)?.slice(0, 120);
        return String(sourceValue)?.slice(0, 120);
      } catch {
        return String(sourceValue);
      }
    })();
    throw new MlldDirectiveError(`Type mismatch: /for expects an array. Received: ${receivedType}${preview2 ? ` (${preview2})` : ""}`, "for", {
      location: expr.location,
      context: {
        expected: "array",
        receivedType
      }
    });
  }
  const results = [];
  const errors = [];
  const specified = expr.meta?.forOptions;
  const inherited = env.__forOptions;
  const effective = specified ?? inherited;
  if (effective?.parallel) {
    resetForErrorsContext(env, errors);
  }
  const iterableArray = Array.from(iterable);
  const SKIP = Symbol("skip");
  const runOne = /* @__PURE__ */ __name(async (entry, idx) => {
    const [key, value] = entry;
    const iterationRoot = env.createChildEnvironment();
    if (effective?.parallel) {
      iterationRoot.__parallelIsolationRoot = iterationRoot;
    }
    let childEnv = iterationRoot;
    if (effective) childEnv.__forOptions = effective;
    let derivedValue;
    if (varFields && varFields.length > 0) {
      try {
        const accessed = await accessFields(value, varFields, {
          env: childEnv,
          preserveContext: true,
          sourceLocation: expr.variable.location
        });
        derivedValue = accessed?.value ?? accessed;
        inheritExpressionProvenance(derivedValue, value);
      } catch (error) {
        throw enhanceFieldAccessError(error, {
          fieldPath: fieldPathString,
          varName,
          index: idx,
          key: key ?? null,
          sourceLocation: expr.variable.location
        });
      }
    }
    const iterationVar = ensureVariable(varName, value, env);
    childEnv.setVariable(varName, withIterationMxKey(iterationVar, key));
    if (typeof derivedValue !== "undefined" && fieldPathString) {
      const derivedVar = ensureVariable(`${varName}.${fieldPathString}`, derivedValue, env);
      childEnv.setVariable(`${varName}.${fieldPathString}`, derivedVar);
    }
    if (key !== null && typeof key === "string") {
      const keyVar = ensureVariable(`${varName}_key`, key, env);
      childEnv.setVariable(`${varName}_key`, keyVar);
    }
    try {
      let exprResult = null;
      if (Array.isArray(expr.expression) && expr.expression.length > 0) {
        let nodesToEvaluate = expr.expression;
        if (expr.expression.length === 1 && expr.expression[0].content && expr.expression[0].wrapperType && !expr.expression[0].hasInterpolation) {
          nodesToEvaluate = expr.expression[0].content;
        }
        const evaluateSequence = /* @__PURE__ */ __name(async (nodes, startEnv) => {
          let currentEnv = startEnv;
          let lastResult = {
            value: void 0,
            env: currentEnv
          };
          for (const node of nodes) {
            if (isLetAssignment(node)) {
              currentEnv = await evaluateLetAssignment(node, currentEnv);
              lastResult = {
                value: void 0,
                env: currentEnv
              };
              continue;
            }
            if (isAugmentedAssignment(node)) {
              currentEnv = await evaluateAugmentedAssignment(node, currentEnv);
              lastResult = {
                value: void 0,
                env: currentEnv
              };
              continue;
            }
            if (node?.type === "WhenExpression" && node.meta?.modifier !== "first") {
              const nodeWithFirst = {
                ...node,
                meta: {
                  ...node.meta || {},
                  modifier: "first"
                }
              };
              lastResult = await evaluateWhenExpression(nodeWithFirst, currentEnv);
              currentEnv = lastResult.env || currentEnv;
              continue;
            }
            lastResult = await evaluate2(node, currentEnv, {
              isExpression: true
            });
            currentEnv = lastResult.env || currentEnv;
          }
          return {
            value: lastResult.value,
            env: currentEnv
          };
        }, "evaluateSequence");
        const result = await evaluateSequence(nodesToEvaluate, childEnv);
        if (result.env) childEnv = result.env;
        let branchValue = result?.value;
        if (isStructuredValue(branchValue)) {
          try {
            branchValue = asData(branchValue);
          } catch {
            branchValue = asText(branchValue);
          }
        }
        if (branchValue === "skip") {
          return SKIP;
        }
        if (isVariable(branchValue)) {
          exprResult = await extractVariableValue(branchValue, childEnv);
        } else {
          exprResult = branchValue;
        }
        exprResult = normalizeWhenShowEffect(exprResult).normalized;
        if (typeof exprResult === "string" && looksLikeJsonString(exprResult)) {
          try {
            exprResult = JSON.parse(exprResult.trim());
          } catch {
          }
        }
      }
      return exprResult;
    } catch (error) {
      const message = formatIterationError(error);
      const marker = {
        index: idx,
        key: key ?? null,
        message,
        error: message,
        value
      };
      errors.push(marker);
      if (effective?.parallel) {
        return marker;
      }
      return null;
    }
  }, "runOne");
  if (effective?.parallel) {
    const cap = Math.min(effective.cap ?? getParallelLimit(), iterableArray.length);
    const orderedResults = await runWithConcurrency(iterableArray, cap, runOne, {
      ordered: true,
      paceMs: effective.rateMs
    });
    for (const r of orderedResults) if (r !== SKIP) results.push(r);
  } else {
    for (let i = 0; i < iterableArray.length; i++) {
      const r = await runOne(iterableArray[i], i);
      if (r !== SKIP) results.push(r);
    }
  }
  let finalResults = results;
  const batchPipelineConfig = expr.meta?.batchPipeline;
  const batchStages = Array.isArray(batchPipelineConfig) ? batchPipelineConfig : batchPipelineConfig?.pipeline;
  if (batchStages && batchStages.length > 0) {
    const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
    const batchInput = createArrayVariable("for-batch-input", results, false, {
      directive: "for",
      syntax: "expression",
      hasInterpolation: false,
      isMultiLine: false
    }, {
      isBatchInput: true
    });
    try {
      const pipelineResult = await processPipeline2({
        value: batchInput,
        env,
        pipeline: batchStages,
        identifier: `for-batch-${expr.variable.identifier}`,
        location: expr.location,
        isRetryable: false
      });
      if (isStructuredValue(pipelineResult)) {
        finalResults = asData(pipelineResult);
      } else if (isVariable(pipelineResult)) {
        finalResults = await extractVariableValue(pipelineResult, env);
      } else {
        finalResults = pipelineResult;
      }
    } catch (error) {
      logger.warn(`Batch pipeline failed for for-expression: ${error instanceof Error ? error.message : String(error)}`);
      errors.push({
        index: -1,
        error,
        value: results
      });
      finalResults = results;
    }
  }
  const variableSource = {
    directive: "for",
    syntax: "expression",
    hasInterpolation: false,
    isMultiLine: false
  };
  const metadata = {
    sourceExpression: expr.expression,
    iterationVariable: expr.variable.identifier
  };
  if (batchStages && batchStages.length > 0) {
    metadata.hadBatchPipeline = true;
  }
  if (errors.length > 0) {
    metadata.forErrors = errors;
  }
  if (Array.isArray(finalResults)) {
    return createArrayVariable("for-result", finalResults, false, variableSource, {
      metadata,
      internal: {
        arrayType: "for-expression-result"
      }
    });
  }
  if (finalResults === void 0) {
    return createPrimitiveVariable("for-result", null, variableSource, {
      mx: metadata
    });
  }
  if (finalResults === null || typeof finalResults === "number" || typeof finalResults === "boolean") {
    return createPrimitiveVariable("for-result", finalResults, variableSource, {
      mx: metadata
    });
  }
  if (typeof finalResults === "string") {
    return createSimpleTextVariable("for-result", finalResults, variableSource, {
      mx: metadata
    });
  }
  if (typeof finalResults === "object") {
    return createObjectVariable("for-result", finalResults, false, variableSource, {
      mx: metadata
    });
  }
  return createSimpleTextVariable("for-result", String(finalResults), variableSource, {
    mx: metadata
  });
}
__name(evaluateForExpression, "evaluateForExpression");

// interpreter/eval/export.ts
async function evaluateExport(directive, env) {
  const exportNodes = directive.values?.exports ?? [];
  const filePath = env.getCurrentFilePath();
  const entries = [];
  let hasWildcard = false;
  const guardRegistry = env.getGuardRegistry();
  for (const node of exportNodes) {
    const identifier = node?.identifier ?? "";
    if (!identifier) continue;
    if (identifier === "*") {
      hasWildcard = true;
      continue;
    }
    const location = astLocationToSourceLocation(node?.location, filePath);
    const isGuard = guardRegistry.getByName(identifier) !== void 0;
    const kind = isGuard ? "guard" : "variable";
    entries.push({
      name: identifier,
      location,
      kind
    });
  }
  if (hasWildcard) {
    env.setExportManifest(null);
    return {
      value: void 0,
      env
    };
  }
  if (entries.length === 0) {
    return {
      value: void 0,
      env
    };
  }
  let manifest = env.getExportManifest();
  if (!manifest) {
    manifest = new ExportManifest();
    env.setExportManifest(manifest);
  }
  manifest.add(entries);
  const emitter = env;
  if (typeof emitter.emitSDKEvent === "function") {
    for (const entry of entries) {
      emitter.emitSDKEvent({
        type: "debug:export:registered",
        name: entry.name,
        timestamp: Date.now()
      });
    }
  }
  return {
    value: void 0,
    env
  };
}
__name(evaluateExport, "evaluateExport");

// interpreter/eval/guard.ts
async function evaluateGuard(directive, env) {
  const guardNode = directive;
  const registry = env.getGuardRegistry();
  registry.register(guardNode, directive.location ?? null);
  return {
    value: void 0,
    env
  };
}
__name(evaluateGuard, "evaluateGuard");

// core/policy/needs.ts
var PACKAGE_ECOSYSTEM_ALIASES = {
  node: "node",
  js: "node",
  python: "python",
  py: "python",
  ruby: "ruby",
  rb: "ruby",
  go: "go",
  rust: "rust"
};
var BOOLEAN_CAPABILITY_ALIASES = {
  sh: "sh",
  bash: "sh",
  network: "network",
  net: "network",
  filesystem: "filesystem",
  fs: "filesystem"
};
var ALLOW_ALL_POLICY = Object.freeze({
  allowAll: true,
  cmd: {
    type: "all"
  },
  sh: true,
  network: true,
  filesystem: true
});
function normalizeNeedsDeclaration(raw, context2 = "needs") {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
    throw new MlldInterpreterError(`/${context2} expects an object`, {
      code: "INVALID_NEEDS_DECLARATION"
    });
  }
  const rawObj = raw;
  const result = {
    packages: {}
  };
  const commandNeeds = normalizeCommandNeeds(rawObj.cmd);
  const bareCommands = normalizeBareCommands(rawObj.__commands);
  for (const [key, value] of Object.entries(rawObj)) {
    if (key === "cmd" || key === "__commands") {
      continue;
    }
    const packageKey = PACKAGE_ECOSYSTEM_ALIASES[key];
    if (packageKey) {
      const normalized = normalizePackages(value, packageKey, context2);
      const existing = result.packages[packageKey] || [];
      const merged = [
        ...existing
      ];
      for (const pkg of normalized) {
        if (!merged.find((p) => p.name === pkg.name && p.specifier === pkg.specifier)) {
          merged.push(pkg);
        }
      }
      result.packages[packageKey] = merged;
      continue;
    }
    const booleanKey = BOOLEAN_CAPABILITY_ALIASES[key];
    if (booleanKey === "sh") {
      result.sh = Boolean(value === void 0 ? true : value) || result.sh === true;
      continue;
    }
    if (booleanKey === "network") {
      result.network = Boolean(value === void 0 ? true : value) || result.network === true;
      continue;
    }
    if (booleanKey === "filesystem") {
      result.filesystem = Boolean(value === void 0 ? true : value) || result.filesystem === true;
      continue;
    }
    throw new MlldInterpreterError(`/${context2} contains unsupported key '${key}'`, {
      code: "INVALID_NEEDS_KEY"
    });
  }
  if (commandNeeds) {
    result.cmd = commandNeeds;
  }
  if (bareCommands.length > 0) {
    result.cmd = mergeCommandNeeds(result.cmd, {
      type: "list",
      commands: bareCommands
    });
  }
  return result;
}
__name(normalizeNeedsDeclaration, "normalizeNeedsDeclaration");
function normalizeWantsDeclaration(raw) {
  if (raw === void 0 || raw === null) {
    return [];
  }
  if (!Array.isArray(raw)) {
    throw new MlldInterpreterError("/wants expects an array of tier objects", {
      code: "INVALID_WANTS_DECLARATION"
    });
  }
  return raw.map((entry, index) => {
    if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
      throw new MlldInterpreterError(`/wants tier at index ${index} is not an object`, {
        code: "INVALID_WANTS_TIER"
      });
    }
    const tierObj = entry;
    const tierValue = tierObj.tier;
    if (typeof tierValue !== "string" || tierValue.trim().length === 0) {
      throw new MlldInterpreterError(`/wants tier at index ${index} is missing required 'tier'`, {
        code: "INVALID_WANTS_TIER"
      });
    }
    const { tier, why, ...rest } = tierObj;
    const needs = normalizeNeedsDeclaration(rest, "wants");
    const allowedKeys = /* @__PURE__ */ new Set([
      "tier",
      "why",
      "cmd",
      "__commands",
      ...Object.keys(PACKAGE_ECOSYSTEM_ALIASES),
      ...Object.keys(BOOLEAN_CAPABILITY_ALIASES)
    ]);
    for (const key of Object.keys(tierObj)) {
      if (!allowedKeys.has(key)) {
        throw new MlldInterpreterError(`/wants tier '${tierValue}' contains unsupported key '${key}'`, {
          code: "INVALID_WANTS_KEY"
        });
      }
    }
    return {
      tier: tierValue,
      why: typeof why === "string" ? why : void 0,
      needs
    };
  });
}
__name(normalizeWantsDeclaration, "normalizeWantsDeclaration");
function policySatisfiesNeeds(needs, policy) {
  if (policy.allowAll) {
    return true;
  }
  if (needs.sh && policy.sh !== true) {
    return false;
  }
  if (needs.network && policy.network !== true) {
    return false;
  }
  if (needs.filesystem && policy.filesystem !== true) {
    return false;
  }
  if (needs.cmd) {
    if (!policy.cmd) {
      return true;
    }
    if (!commandsAllowed(needs.cmd, policy.cmd)) {
      return false;
    }
  }
  return true;
}
__name(policySatisfiesNeeds, "policySatisfiesNeeds");
function selectWantsTier(wants, policy) {
  for (const tier of wants) {
    if (policySatisfiesNeeds(tier.needs, policy)) {
      return {
        tier: tier.tier,
        granted: tier.needs
      };
    }
  }
  return null;
}
__name(selectWantsTier, "selectWantsTier");
function mergeNeedsDeclarations(base, incoming) {
  if (!base) {
    return incoming;
  }
  const mergedPackages = {
    ...base.packages || {}
  };
  for (const [ecosystem, pkgs] of Object.entries(incoming.packages || {})) {
    const existing = mergedPackages[ecosystem] || [];
    const combined = [
      ...existing
    ];
    for (const pkg of pkgs) {
      if (!combined.find((p) => p.name === pkg.name && p.specifier === pkg.specifier)) {
        combined.push(pkg);
      }
    }
    mergedPackages[ecosystem] = combined;
  }
  return {
    packages: mergedPackages,
    sh: base.sh || incoming.sh,
    network: base.network || incoming.network,
    filesystem: base.filesystem || incoming.filesystem,
    cmd: mergeCommandNeeds(base.cmd, incoming.cmd)
  };
}
__name(mergeNeedsDeclarations, "mergeNeedsDeclarations");
function normalizeCommandNeeds(raw) {
  if (raw === void 0 || raw === null) {
    return void 0;
  }
  if (raw === "*" || typeof raw === "object" && raw.type === "wildcard") {
    return {
      type: "all"
    };
  }
  if (typeof raw === "object") {
    const obj = raw;
    if (obj.type === "list") {
      const commands = normalizeStringArray(obj.items, "cmd list");
      return {
        type: "list",
        commands
      };
    }
    if (obj.type === "map") {
      const entries = normalizeCommandMap(obj.entries);
      return {
        type: "map",
        entries
      };
    }
    if (Array.isArray(obj.items)) {
      const commands = normalizeStringArray(obj.items, "cmd list");
      return {
        type: "list",
        commands
      };
    }
    if (obj.entries && typeof obj.entries === "object") {
      const entries = normalizeCommandMap(obj.entries);
      return {
        type: "map",
        entries
      };
    }
  }
  if (Array.isArray(raw)) {
    const commands = normalizeStringArray(raw, "cmd list");
    return {
      type: "list",
      commands
    };
  }
  if (typeof raw === "string") {
    return {
      type: "list",
      commands: [
        raw
      ]
    };
  }
  throw new MlldInterpreterError("Invalid /needs cmd declaration", {
    code: "INVALID_NEEDS_CMD"
  });
}
__name(normalizeCommandNeeds, "normalizeCommandNeeds");
function normalizeBareCommands(raw) {
  if (!raw) {
    return [];
  }
  if (Array.isArray(raw)) {
    return normalizeStringArray(raw, "command list");
  }
  return normalizeStringArray([
    raw
  ], "command list");
}
__name(normalizeBareCommands, "normalizeBareCommands");
function normalizeStringArray(raw, label) {
  if (!Array.isArray(raw)) {
    throw new MlldInterpreterError(`Expected array for ${label}`, {
      code: "INVALID_NEEDS_VALUE"
    });
  }
  const values = raw.map((item) => {
    if (typeof item === "string") {
      return item;
    }
    if (item && typeof item === "object" && "toString" in item) {
      return String(item);
    }
    throw new MlldInterpreterError(`Expected string entries for ${label}`, {
      code: "INVALID_NEEDS_VALUE"
    });
  }).map((str) => str.trim()).filter((str) => str.length > 0);
  return Array.from(new Set(values));
}
__name(normalizeStringArray, "normalizeStringArray");
function normalizeCommandMap(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
    throw new MlldInterpreterError("Invalid command map in /needs", {
      code: "INVALID_NEEDS_CMD"
    });
  }
  const result = {};
  for (const [name, value] of Object.entries(raw)) {
    result[name] = normalizeCommandDetail(value);
  }
  return result;
}
__name(normalizeCommandMap, "normalizeCommandMap");
function normalizeCommandDetail(raw) {
  if (raw === "*" || raw && typeof raw === "object" && raw.type === "wildcard") {
    return {
      wildcard: true
    };
  }
  if (Array.isArray(raw)) {
    return {
      list: normalizeStringArray(raw, "command detail")
    };
  }
  if (raw && typeof raw === "object") {
    const obj = raw;
    if (obj.type === "list") {
      return {
        list: normalizeStringArray(obj.items ?? [], "command detail")
      };
    }
    if (obj.type === "detail" && obj.props && typeof obj.props === "object") {
      return normalizeCommandDetail(obj.props);
    }
    const detail = {};
    if (obj.methods !== void 0) {
      detail.methods = normalizeStringArray(obj.methods, "command methods");
    }
    if (obj.subcommands !== void 0) {
      detail.subcommands = normalizeStringArray(obj.subcommands, "command subcommands");
    }
    if (obj.flags !== void 0) {
      detail.flags = normalizeStringArray(obj.flags, "command flags");
    }
    if (Object.keys(detail).length === 0) {
      return {
        list: []
      };
    }
    return detail;
  }
  if (typeof raw === "string") {
    return {
      list: [
        raw
      ]
    };
  }
  throw new MlldInterpreterError("Invalid command detail in /needs", {
    code: "INVALID_NEEDS_CMD"
  });
}
__name(normalizeCommandDetail, "normalizeCommandDetail");
function normalizePackages(raw, ecosystem, context2) {
  if (!Array.isArray(raw)) {
    throw new MlldInterpreterError(`/${context2} ${ecosystem} expects an array of packages`, {
      code: "INVALID_NEEDS_PACKAGES"
    });
  }
  const packages = [];
  for (const entry of raw) {
    if (typeof entry !== "string") {
      throw new MlldInterpreterError(`/${context2} ${ecosystem} entries must be strings`, {
        code: "INVALID_NEEDS_PACKAGES"
      });
    }
    const parsed = parseVersionSpecifier(entry);
    if (!parsed.name) {
      throw new MlldInterpreterError(`/${context2} ${ecosystem} entry '${entry}' is invalid`, {
        code: "INVALID_NEEDS_PACKAGES"
      });
    }
    if (!packages.find((pkg) => pkg.name === parsed.name && pkg.specifier === parsed.specifier)) {
      packages.push(parsed);
    }
  }
  return packages;
}
__name(normalizePackages, "normalizePackages");
function commandsAllowed(needs, policy) {
  if (policy.type === "all" || needs.type === "list" && policy.type === "all") {
    return true;
  }
  if (needs.type === "all" && policy.type !== "all") {
    return false;
  }
  if (needs.type === "list") {
    if (policy.type === "list") {
      return needs.commands.every((cmd) => policy.commands.includes(cmd));
    }
    if (policy.type === "map") {
      return needs.commands.every((cmd) => Boolean(policy.entries[cmd]));
    }
  }
  if (needs.type === "map") {
    if (policy.type === "all") {
      return true;
    }
    if (policy.type === "list") {
      return Object.keys(needs.entries).every((cmd) => policy.commands.includes(cmd));
    }
    if (policy.type === "map") {
      return Object.keys(needs.entries).every((cmd) => Boolean(policy.entries[cmd]));
    }
  }
  return true;
}
__name(commandsAllowed, "commandsAllowed");
function mergeCommandNeeds(base, incoming) {
  if (!base) return incoming;
  if (!incoming) return base;
  if (base.type === "all" || incoming.type === "all") {
    return {
      type: "all"
    };
  }
  if (base.type === "list" && incoming.type === "list") {
    const combined = Array.from(/* @__PURE__ */ new Set([
      ...base.commands,
      ...incoming.commands
    ]));
    return {
      type: "list",
      commands: combined
    };
  }
  if (base.type === "map" && incoming.type === "map") {
    return {
      type: "map",
      entries: {
        ...base.entries,
        ...incoming.entries
      }
    };
  }
  if (base.type === "map" && incoming.type === "list") {
    const entries = {
      ...base.entries
    };
    for (const cmd of incoming.commands) {
      entries[cmd] = entries[cmd] || {
        list: []
      };
    }
    return {
      type: "map",
      entries
    };
  }
  if (base.type === "list" && incoming.type === "map") {
    const entries = {
      ...incoming.entries
    };
    for (const cmd of base.commands) {
      entries[cmd] = entries[cmd] || {
        list: []
      };
    }
    return {
      type: "map",
      entries
    };
  }
  return incoming;
}
__name(mergeCommandNeeds, "mergeCommandNeeds");

// interpreter/eval/needs.ts
async function evaluateNeeds(directive, env) {
  const needsRaw = directive.values?.needs ?? {};
  const needs = normalizeNeedsDeclaration(needsRaw);
  env.recordModuleNeeds(needs);
  return {
    value: void 0,
    env,
    stdout: "",
    stderr: "",
    exitCode: 0
  };
}
__name(evaluateNeeds, "evaluateNeeds");
async function evaluateWants(directive, env) {
  const wantsRaw = directive.values?.wants ?? [];
  const wants = normalizeWantsDeclaration(wantsRaw);
  env.recordModuleWants(wants);
  const policy = env.getPolicyCapabilities();
  const match = selectWantsTier(wants, policy);
  const existingContext = env.getPolicyContext();
  const policyContext = {
    tier: match?.tier ?? null,
    configs: existingContext?.configs ?? {},
    activePolicies: existingContext?.activePolicies ?? [],
    ...existingContext?.environment ? {
      environment: existingContext.environment
    } : {}
  };
  env.setPolicyContext(policyContext);
  return {
    value: match?.tier ?? null,
    env,
    stdout: "",
    stderr: "",
    exitCode: 0
  };
}
__name(evaluateWants, "evaluateWants");
var DEFAULT_GUARD_MAX2 = 3;
var afterRetryDebugEnabled2 = process.env.DEBUG_AFTER_RETRY === "1";
function logAfterRetryDebug(label, payload) {
  if (!afterRetryDebugEnabled2) {
    return;
  }
  try {
    console.error(`[after-guard-retry] ${label}`, payload);
  } catch {
  }
}
__name(logAfterRetryDebug, "logAfterRetryDebug");
function extractGuardRetryDetails(error) {
  if (!error || typeof error !== "object") {
    return {};
  }
  const candidate = error;
  const details = candidate.details ?? {};
  return {
    guardName: candidate.guardName ?? details.guardName,
    guardFilter: candidate.guardFilter ?? details.guardFilter,
    scope: candidate.scope ?? details.scope,
    operation: candidate.operation ?? details.operation,
    inputPreview: candidate.inputPreview ?? details.inputPreview,
    outputPreview: candidate.outputPreview ?? details.outputPreview,
    guardContext: candidate.guardContext ?? details.guardContext,
    guardResults: candidate.guardResults ?? details.guardResults,
    hints: candidate.hints ?? details.hints
  };
}
__name(extractGuardRetryDetails, "extractGuardRetryDetails");
async function runWithGuardRetry(options) {
  const state = {
    attempt: 1,
    max: DEFAULT_GUARD_MAX2,
    history: [],
    hintHistory: []
  };
  for (; ; ) {
    const guardRetryContext = {
      attempt: state.attempt,
      try: state.attempt,
      tries: state.history.map((entry) => ({
        ...entry
      })),
      max: state.max,
      hintHistory: state.hintHistory.slice()
    };
    try {
      return await options.env.getContextManager().withGenericContext("guardRetry", guardRetryContext, options.execute);
    } catch (error) {
      const isRetrySignal = error instanceof GuardError && error.decision === "retry" || isGuardRetrySignal(error);
      const debugPayload = {
        attempt: state.attempt,
        isRetrySignal,
        sourceRetryable: options.sourceRetryable ?? null,
        pipeline: Boolean(options.env.getPipelineContext())
      };
      logAfterRetryDebug("guard retry caught", debugPayload);
      try {
        appendFileSync("/tmp/mlld_guard_retry.log", JSON.stringify({
          event: "caught",
          ...debugPayload,
          hint: error?.retryHint ?? extractGuardRetryDetails(error).hints?.[0]?.hint ?? error.reason ?? null
        }, null, 2) + "\n");
      } catch {
      }
      if (!isRetrySignal) {
        throw error;
      }
      if (options.env.getPipelineContext()) {
        const rethrowPayload = {
          attempt: state.attempt,
          hint: error.retryHint ?? error?.retryHint ?? extractGuardRetryDetails(error).hints?.[0]?.hint ?? null
        };
        logAfterRetryDebug("rethrow to pipeline executor", rethrowPayload);
        try {
          appendFileSync("/tmp/mlld_guard_retry.log", JSON.stringify({
            event: "rethrow",
            ...rethrowPayload
          }, null, 2) + "\n");
        } catch {
        }
        throw error;
      }
      const details = extractGuardRetryDetails(error);
      const guardContext = details.guardContext;
      if (typeof guardContext?.max === "number") {
        state.max = guardContext.max;
      }
      const hint = error.retryHint ?? (typeof details.hints?.[0]?.hint === "string" ? details.hints[0].hint : null) ?? error.reason ?? null;
      state.history.push({
        attempt: state.attempt,
        decision: "retry",
        hint
      });
      state.hintHistory.push(hint ?? null);
      state.attempt += 1;
      if (!options.sourceRetryable) {
        const denyPayload = {
          attempt: state.attempt - 1,
          hint,
          sourceRetryable: options.sourceRetryable ?? null,
          guardName: details.guardName ?? guardContext?.name ?? null
        };
        logAfterRetryDebug("guard retry denied (non-retryable source)", denyPayload);
        try {
          appendFileSync("/tmp/mlld_guard_retry.log", JSON.stringify({
            event: "deny-non-retryable",
            ...denyPayload
          }, null, 2) + "\n");
        } catch {
        }
        throw new GuardError({
          decision: "deny",
          guardName: details.guardName ?? guardContext?.name ?? null,
          guardFilter: details.guardFilter ?? guardContext?.guardFilter,
          scope: details.scope,
          operation: details.operation ?? options.operationContext,
          inputPreview: details.inputPreview ?? null,
          outputPreview: details.outputPreview ?? null,
          retryHint: hint,
          reason: `Cannot retry: ${hint ?? "source not retryable"}`,
          guardContext: guardContext ?? void 0,
          guardResults: details.guardResults,
          hints: details.hints
        });
      }
      if (state.attempt > state.max) {
        logAfterRetryDebug("guard retry budget exceeded", {
          attempt: state.attempt - 1,
          max: state.max,
          hint,
          guardName: details.guardName ?? guardContext?.name ?? null
        });
        throw new GuardError({
          decision: "deny",
          guardName: details.guardName ?? guardContext?.name ?? null,
          guardFilter: details.guardFilter ?? guardContext?.guardFilter,
          scope: details.scope,
          operation: details.operation ?? options.operationContext,
          inputPreview: details.inputPreview ?? null,
          outputPreview: details.outputPreview ?? null,
          reason: `Guard retry limit exceeded (${state.max})`,
          guardContext: {
            ...guardContext ?? {},
            attempt: state.attempt - 1,
            try: state.attempt - 1,
            tries: state.history.map((entry) => ({
              ...entry
            })),
            max: state.max
          },
          guardResults: details.guardResults,
          hints: details.hints
        });
      }
    }
  }
}
__name(runWithGuardRetry, "runWithGuardRetry");

// interpreter/eval/policy.ts
async function evaluatePolicy(directive, env) {
  const configs = await evaluateUnionExpression(directive.values.expr, env);
  const merged = mergePolicyConfigsFromArray(configs);
  const nameNode = directive.values.name?.[0];
  const policyName = getTextContent(nameNode) || directive.raw?.name;
  if (!policyName) {
    throw new MlldInterpreterError("Policy directive is missing a name", {
      code: "INVALID_POLICY_NAME"
    });
  }
  const source = {
    directive: "policy",
    syntax: "object",
    hasInterpolation: false,
    isMultiLine: false
  };
  const variable = createObjectVariable(policyName, merged, false, source, {
    definedAt: astLocationToSourceLocation(directive.location, env.getCurrentFilePath())
  });
  env.setVariable(policyName, variable);
  env.recordPolicyConfig(policyName, merged);
  return {
    value: merged,
    env,
    stdout: "",
    stderr: "",
    exitCode: 0
  };
}
__name(evaluatePolicy, "evaluatePolicy");
async function evaluateUnionExpression(expr, env) {
  if (!expr || expr.type !== "union") {
    throw new MlldInterpreterError("Only union expressions are supported in /policy", {
      code: "INVALID_POLICY_EXPRESSION"
    });
  }
  if (!expr.args || expr.args.length === 0) {
    throw new MlldInterpreterError("Policy union requires at least one reference", {
      code: "INVALID_POLICY_EXPRESSION"
    });
  }
  const configs = [];
  for (const arg of expr.args) {
    configs.push(await resolvePolicyReference(arg, env));
  }
  return configs;
}
__name(evaluateUnionExpression, "evaluateUnionExpression");
async function resolvePolicyReference(arg, env) {
  if (!arg || arg.type !== "ref") {
    throw new MlldInterpreterError("Unsupported policy expression argument", {
      code: "INVALID_POLICY_REFERENCE"
    });
  }
  const refName = arg.name;
  const variable = env.getVariable(refName);
  if (!variable) {
    throw new MlldInterpreterError(`Policy reference '@${refName}' is not defined`, {
      code: "POLICY_REFERENCE_NOT_FOUND"
    });
  }
  const rawValue = await extractVariableValue(variable, env);
  const candidate = resolvePolicyConfigSource(rawValue);
  if (!candidate) {
    throw new MlldInterpreterError(`Policy reference '@${refName}' is not a policy configuration`, {
      code: "INVALID_POLICY_REFERENCE"
    });
  }
  return normalizePolicyConfig(candidate);
}
__name(resolvePolicyReference, "resolvePolicyReference");
function resolvePolicyConfigSource(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return void 0;
  }
  if (value.config && typeof value.config === "object") {
    return value.config;
  }
  return value;
}
__name(resolvePolicyConfigSource, "resolvePolicyConfigSource");
function mergePolicyConfigsFromArray(configs) {
  return configs.reduce((acc, current) => mergePolicyConfigs(acc, current), void 0) ?? {};
}
__name(mergePolicyConfigsFromArray, "mergePolicyConfigsFromArray");

// interpreter/eval/directive.ts
function extractTraceInfo(directive) {
  const info = {
    directive: `/${directive.kind}`
  };
  switch (directive.kind) {
    case "path":
    case "var":
      const identifierNodes = directive.values?.identifier;
      if (identifierNodes && Array.isArray(identifierNodes) && identifierNodes.length > 0) {
        const identifier = identifierNodes[0];
        if (identifier?.type === "Text" && "content" in identifier) {
          info.varName = identifier.content;
        } else if (identifier?.type === "VariableReference" && "identifier" in identifier) {
          info.varName = identifier.identifier;
        }
      }
      break;
    case "run":
      if (directive.subtype === "runExec") {
        const execId = directive.values?.identifier?.[0];
        if (execId?.type === "Text" && "content" in execId) {
          info.varName = `@${execId.content}`;
        }
      }
      break;
    case "exec":
    case "exe":
      const execName = directive.values?.name?.[0];
      const execNameContent = getTextContent(execName);
      if (execNameContent) {
        info.varName = execNameContent;
      }
      break;
    case "foreach":
      const template = directive.values?.template?.[0];
      const templateContent = getTextContent(template);
      if (templateContent) {
        info.varName = templateContent;
      }
      break;
    case "import":
      const importPath = directive.values?.path?.[0];
      const pathContent = getTextContent(importPath);
      if (pathContent) {
        info.varName = pathContent.split("/").pop()?.replace(/\.mld$/, "");
      }
      break;
    case "export":
      const firstExport = directive.values?.exports?.[0];
      if (firstExport && typeof firstExport.identifier === "string") {
        info.varName = firstExport.identifier;
      }
      break;
    case "policy":
      const policyNameNode = directive.values?.name?.[0];
      const policyName = getTextContent(policyNameNode);
      if (policyName) {
        info.varName = policyName;
      }
      break;
  }
  return info;
}
__name(extractTraceInfo, "extractTraceInfo");
async function evaluateDirective(directive, env, context2) {
  const traceInfo = extractTraceInfo(directive);
  env.pushDirective(traceInfo.directive, traceInfo.varName, directive.location);
  const hookManager = env.getHookManager();
  const operationContext = buildOperationContext(directive, traceInfo);
  try {
    const executeOnce = /* @__PURE__ */ __name(async () => {
      return await env.withOpContext(operationContext, async () => {
        let extractedInputs = [];
        let precomputedVarAssignment;
        if (directive.kind === "var") {
          precomputedVarAssignment = await prepareVarAssignment(directive, env);
          extractedInputs = [
            precomputedVarAssignment.variable
          ];
        } else {
          extractedInputs = await extractDirectiveInputs(directive, env);
        }
        const preDecision = await hookManager.runPre(directive, extractedInputs, env, operationContext);
        const transformedInputs = getGuardTransformedInputs(preDecision, extractedInputs);
        if (precomputedVarAssignment && transformedInputs && transformedInputs[0]) {
          const firstTransformed = transformedInputs[0];
          if (isVariable(firstTransformed)) {
            precomputedVarAssignment = {
              ...precomputedVarAssignment,
              variable: firstTransformed
            };
          }
        }
        const resolvedInputs = transformedInputs ?? extractedInputs;
        await handleGuardDecision(preDecision, directive, env, operationContext);
        const mergedContext = mergeEvaluationContext(context2, resolvedInputs, operationContext, precomputedVarAssignment);
        let result = await dispatchDirective(directive, env, mergedContext);
        result = await hookManager.runPost(directive, result, resolvedInputs, env, operationContext);
        if (directive.kind === "var" && precomputedVarAssignment && result.__guardTransformed) {
          const targetVar = env.getVariable(precomputedVarAssignment.identifier) ?? {
            ...precomputedVarAssignment.variable
          };
          if (isVariable(result.value)) {
            const replacement = result.value;
            targetVar.value = replacement.value ?? replacement;
            targetVar.mx = {
              ...targetVar.mx ?? {},
              ...replacement.mx ?? {}
            };
          } else {
            targetVar.value = result.value;
            const descriptor = extractSecurityDescriptor(result.value, {
              recursive: true,
              mergeArrayElements: true
            });
            if (descriptor) {
              const mx = targetVar.mx ?? (targetVar.mx = {});
              updateVarMxFromDescriptor(mx, descriptor);
              if ("mxCache" in mx) {
                delete mx.mxCache;
              }
            }
          }
        }
        return result;
      });
    }, "executeOnce");
    const sourceRetryable = operationContext.metadata && typeof operationContext.metadata.sourceRetryable === "boolean" && operationContext.metadata.sourceRetryable === true || false;
    return await runWithGuardRetry({
      env,
      operationContext,
      sourceRetryable,
      execute: executeOnce
    });
  } catch (error) {
    const trace = env.getDirectiveTrace();
    if (error && typeof error === "object" && "importParseError" in error) {
      const parseError = error.importParseError;
      env.markLastDirectiveFailed(`${parseError.file}.mld failed to parse at line ${parseError.line}: ${parseError.message}`);
    }
    if (trace.length > 0) {
      if (error && typeof error === "object") {
        if ("details" in error && typeof error.details === "object") {
          if (!error.details.directiveTrace) {
            error.details = {
              ...error.details,
              directiveTrace: trace
            };
          }
        } else if (error instanceof Error) {
          error.mlldTrace = trace;
        }
      }
    }
    throw error;
  } finally {
    env.popDirective();
    clearDirectiveReplay(directive);
  }
}
__name(evaluateDirective, "evaluateDirective");
function mergeEvaluationContext(baseContext, extractedInputs, operationContext, precomputedVarAssignment) {
  const extra = {
    extractedInputs,
    operationContext,
    precomputedVarAssignment
  };
  return baseContext ? {
    ...baseContext,
    ...extra
  } : extra;
}
__name(mergeEvaluationContext, "mergeEvaluationContext");
function buildOperationContext(directive, traceInfo) {
  const labels = directive.meta?.securityLabels || directive.values?.securityLabels;
  const baseMetadata = {
    trace: traceInfo.directive
  };
  const streamingEnabled = readStreamFlag(directive);
  const context2 = {
    type: directive.kind,
    subtype: directive.subtype,
    labels,
    name: traceInfo.varName,
    location: directive.location ?? null,
    metadata: streamingEnabled ? {
      ...baseMetadata,
      streaming: true
    } : baseMetadata
  };
  switch (directive.kind) {
    case "run":
      applyRunMetadata(context2, directive);
      break;
    case "import":
      applyImportMetadata(context2, directive);
      break;
    case "output":
    case "append":
      applyOutputMetadata(context2, directive);
      break;
    case "var":
      applyVarMetadata(context2, directive);
      break;
    case "show":
    case "stream":
      applyShowMetadata(context2, directive);
      break;
  }
  return context2;
}
__name(buildOperationContext, "buildOperationContext");
async function dispatchDirective(directive, env, evaluationContext) {
  switch (directive.kind) {
    case "path":
      return await evaluatePath(directive, env);
    case "run":
      return await evaluateRun(directive, env, [], evaluationContext);
    case "import":
      return await evaluateImport(directive, env);
    case "when":
      return await evaluateWhen(directive, env);
    case "output":
      return await evaluateOutput(directive, env, evaluationContext);
    case "append":
      return await evaluateAppend(directive, env, evaluationContext);
    case "var":
      return await evaluateVar(directive, env, evaluationContext);
    case "show":
      return await evaluateShow(directive, env, evaluationContext);
    case "stream":
      return await evaluateShow(directive, env, evaluationContext);
    case "exe":
      return await evaluateExe(directive, env);
    case "for":
      return await evaluateForDirective(directive, env);
    case "export":
      return await evaluateExport(directive, env);
    case "guard":
      return await evaluateGuard(directive, env);
    case "needs":
      return await evaluateNeeds(directive, env);
    case "wants":
      return await evaluateWants(directive, env);
    case "policy":
      return await evaluatePolicy(directive, env);
    default:
      throw new Error(`Unknown directive kind: ${directive.kind}`);
  }
}
__name(dispatchDirective, "dispatchDirective");
function applyRunMetadata(context2, directive) {
  const metadata = {
    ...context2.metadata ?? {}
  };
  metadata.runSubtype = directive.subtype;
  const language = directive.meta?.language;
  if (typeof language === "string" && language.length > 0) {
    metadata.language = language;
  }
  if (directive.subtype === "runCommand") {
    const nodes = directive.values?.identifier || directive.values?.command;
    const preview2 = summarizeNodes(nodes);
    if (preview2) {
      context2.command = preview2;
      metadata.commandPreview = preview2;
    }
  } else if (directive.subtype === "runExec") {
    const execNode = directive.values?.identifier?.[0];
    const execName = execNode ? getTextContent(execNode) : void 0;
    if (execName) {
      context2.command = `@${execName}`;
      metadata.execName = execName;
    }
  }
  context2.metadata = metadata;
}
__name(applyRunMetadata, "applyRunMetadata");
function applyImportMetadata(context2, directive) {
  const metadata = {
    ...context2.metadata ?? {}
  };
  const pathNode = directive.values?.path?.[0];
  const path10 = pathNode ? getTextContent(pathNode) : void 0;
  if (path10) {
    context2.target = path10;
  }
  context2.metadata = metadata;
}
__name(applyImportMetadata, "applyImportMetadata");
function applyOutputMetadata(context2, directive) {
  const metadata = {
    ...context2.metadata ?? {}
  };
  const pathNode = directive.values?.path?.[0] || directive.values?.target?.path?.[0] || (Array.isArray(directive.values?.target) ? directive.values.target[0]?.path?.[0] : void 0);
  const path10 = pathNode ? getTextContent(pathNode) : void 0;
  if (path10) {
    context2.target = path10;
  }
  const targetType = directive.meta?.targetType;
  if (targetType) {
    metadata.outputTargetType = targetType;
  }
  context2.metadata = metadata;
}
__name(applyOutputMetadata, "applyOutputMetadata");
function applyVarMetadata(context2, directive) {
  const metadata = {
    ...context2.metadata ?? {}
  };
  const identifierNodes = directive.values?.identifier;
  const varName = identifierNodes && identifierNodes[0] ? getTextContent(identifierNodes[0]) : void 0;
  if (varName) {
    context2.target = varName;
  }
  metadata.sourceRetryable = true;
  context2.metadata = metadata;
}
__name(applyVarMetadata, "applyVarMetadata");
function applyShowMetadata(context2, directive) {
  const metadata = {
    ...context2.metadata ?? {}
  };
  metadata.showSubtype = directive.subtype;
  metadata.sourceRetryable = true;
  context2.metadata = metadata;
}
__name(applyShowMetadata, "applyShowMetadata");
function readStreamFlag(directive) {
  const candidates = [
    directive.values?.withClause?.stream,
    directive.values?.invocation?.withClause?.stream,
    directive.values?.execInvocation?.withClause?.stream,
    directive.meta?.withClause?.stream
  ];
  return candidates.some((value) => value === true || value === "true");
}
__name(readStreamFlag, "readStreamFlag");
function summarizeNodes(nodes) {
  if (!nodes) {
    return void 0;
  }
  const array = Array.isArray(nodes) ? nodes : [
    nodes
  ];
  const parts = array.map((node) => typeof node === "string" ? node : getTextContent(node) ?? "").join("");
  const preview2 = parts.trim();
  if (!preview2) {
    return void 0;
  }
  return preview2.length > 120 ? `${preview2.slice(0, 117)}...` : preview2;
}
__name(summarizeNodes, "summarizeNodes");

// interpreter/eval/conditional-inclusion.ts
async function evaluateConditionalInclusion(conditionNode, env, options) {
  const { evaluate: evaluate3 } = await import('./interpreter-MW7QI3FC.mjs');
  const result = await evaluate3(conditionNode, env, {
    isExpression: true,
    isCondition: true
  });
  const shouldInclude = isTruthy2(result.value);
  if (!shouldInclude) {
    return {
      shouldInclude,
      value: result.value
    };
  }
  if (options?.valueNode) {
    const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
    const value = await evaluateDataValue2(options.valueNode, env);
    return {
      shouldInclude,
      value
    };
  }
  return {
    shouldInclude,
    value: result.value
  };
}
__name(evaluateConditionalInclusion, "evaluateConditionalInclusion");
var ASSERT_MODE = process.env.MLLD_ASSERT_ARRAY_BEHAVIOR === "true";
function assertArrayBehavior(condition, message, context2) {
  if (ASSERT_MODE && !condition) {
    const contextStr = context2 ? `
Context: ${JSON.stringify(context2, null, 2)}` : "";
    throw new Error(`[ARRAY MIGRATION ASSERTION] ${message}${contextStr}`);
  }
}
__name(assertArrayBehavior, "assertArrayBehavior");
function createInterpolator(getDeps) {
  const interpolateImpl = /* @__PURE__ */ __name(async function interpolate2(nodes, env, context2 = InterpolationContext.Default, options) {
    interpreterLogger.info("[INTERPOLATE] interpolate() called");
    if (!Array.isArray(nodes)) {
      if (typeof nodes === "string") {
        return nodes;
      }
      if (nodes && typeof nodes === "object" && "content" in nodes) {
        return nodes.content || "";
      }
      return String(nodes || "");
    }
    const parts = [];
    let withinDoubleQuotes = false;
    let withinSingleQuotes = false;
    const updateQuoteState = /* @__PURE__ */ __name((fragment) => {
      if (!fragment) return;
      let backslashCount = 0;
      for (let i = 0; i < fragment.length; i++) {
        const char = fragment[i];
        if (char === "\\") {
          backslashCount++;
          continue;
        }
        if (char === '"' || char === "'") {
          const isEscaped = backslashCount % 2 === 1;
          if (char === '"' && !withinSingleQuotes && !isEscaped) {
            withinDoubleQuotes = !withinDoubleQuotes;
          } else if (char === "'" && !withinDoubleQuotes && !isEscaped) {
            withinSingleQuotes = !withinSingleQuotes;
          }
        }
        backslashCount = 0;
      }
    }, "updateQuoteState");
    const pushPart = /* @__PURE__ */ __name((fragment) => {
      const value = fragment ?? "";
      parts.push(value);
      if (context2 === InterpolationContext.ShellCommand) {
        updateQuoteState(value);
      }
    }, "pushPart");
    const collectDescriptor = /* @__PURE__ */ __name((descriptor) => {
      if (!descriptor) {
        return;
      }
      options?.collectSecurityDescriptor?.(descriptor);
    }, "collectDescriptor");
    const { evaluate: evaluate3 } = getDeps();
    for (const node of nodes) {
      if (node.type === "Text") {
        pushPart(node.content || "");
      } else if (node.type === "PathSeparator") {
        pushPart(node.value || "/");
      } else if (node.type === "ConditionalTemplateSnippet" || node.type === "ConditionalStringFragment") {
        const conditionNode = node.condition;
        const contentNodes = node.content;
        const { shouldInclude } = await evaluateConditionalInclusion(conditionNode, env);
        if (!shouldInclude) {
          continue;
        }
        const snippet2 = await interpolateImpl(Array.isArray(contentNodes) ? contentNodes : [], env, context2, options);
        pushPart(snippet2);
      } else if (node.type === "ExecInvocation") {
        const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
        const result2 = await evaluateExecInvocation(node, env);
        collectDescriptor(extractInterpolationDescriptor(result2.value));
        pushPart(asText(result2.value));
      } else if (node.type === "InterpolationVar") {
        const varName = node.identifier || node.name;
        if (!varName) continue;
        let variable = env.getVariable(varName);
        if (!variable && env.hasVariable(varName)) {
          const resolverVar = await env.getResolverVariable(varName);
          if (resolverVar) {
            variable = resolverVar;
          }
        }
        if (!variable) {
          if (process.env.MLLD_DEBUG === "true") {
            interpreterLogger.debug("Variable not found during {{var}} interpolation:", {
              varName
            });
          }
          pushPart(`{{${varName}}}`);
          continue;
        }
        collectDescriptor(variable.mx ? varMxToSecurityDescriptor(variable.mx) : void 0);
        const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
        const value = await resolveVariable(variable, env, ResolutionContext.StringInterpolation);
        collectDescriptor(extractInterpolationDescriptor(value));
        let stringValue;
        if (value === null) {
          stringValue = "null";
        } else if (value === void 0) {
          stringValue = "";
        } else if (isStructuredValue(value)) {
          stringValue = asText(value);
          collectDescriptor(extractInterpolationDescriptor(value));
          if (value.type === "Path") {
            const classification = classifyShellValue(value.value);
            if (classification.type === "path") {
              stringValue = classification.value;
            }
          } else if (value.type === "CommandResult") {
            const classification = classifyShellValue(value.text);
            if (classification.type === "path") {
              stringValue = classification.value;
            }
          } else if (value.type === "PipelineInput") {
            assertStructuredValue(value, "interpolate:pipeline-input");
            stringValue = asText(value);
          } else if (isStructuredValue(value) && value.type === "array") {
            stringValue = value.text;
          }
        } else if (typeof value === "object") {
          stringValue = JSON.stringify(value);
          if (process.env.MLLD_DEBUG === "true") ;
        } else {
          stringValue = String(value);
        }
        pushPart(stringValue);
        interpreterLogger.debug("[INTERPOLATE] Pushed to parts:", {
          stringValue,
          partsLength: parts.length
        });
      } else if (node.type === "TemplateVariable") {
        const varName = node.identifier || node.name;
        if (!varName) continue;
        const variable = env.getVariable(varName);
        if (!variable) {
          pushPart(`@${varName}`);
          continue;
        }
        collectDescriptor(variable.mx ? varMxToSecurityDescriptor(variable.mx) : void 0);
        if (variable.internal?.templateAst) {
          const templateContent = await interpolateImpl(variable.internal.templateAst, env, InterpolationContext.Template, options);
          pushPart(templateContent);
        } else {
          const strategy = EscapingStrategyFactory.getStrategy(context2);
          const value = asText(variable.value);
          pushPart(strategy.escape(value));
        }
      } else if (node.type === "VariableReference" || node.type === "VariableReferenceWithTail" || node.type === "TemplateVariable") {
        const varName = node.identifier || node.name;
        let variable = env.getVariable(varName);
        if (!variable && env.hasVariable(varName)) {
          const resolverVar = await env.getResolverVariable(varName);
          if (resolverVar) {
            variable = resolverVar;
          }
        }
        if (!variable) {
          if (process.env.MLLD_DEBUG === "true") {
            interpreterLogger.debug("Variable not found during interpolation:", {
              varName,
              valueType: node.valueType
            });
          }
          if (node.valueType === "varInterpolation") {
            pushPart(`{{${varName}}}`);
          } else {
            pushPart(`@${varName}`);
          }
          continue;
        }
        collectDescriptor(variable.mx ? varMxToSecurityDescriptor(variable.mx) : void 0);
        let value = "";
        const { isExecutableVariable: isExecutableVariable2 } = await import('./variable-FNPDYIEH.mjs');
        if (isExecutableVariable2(variable)) {
          const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
          const commandRef = node.commandRef || {
            identifier: variable.name,
            args: []
          };
          const execInvocation = {
            type: "ExecInvocation",
            commandRef: {
              identifier: commandRef.identifier || variable.name || node.name || node.identifier,
              args: commandRef.args || []
            },
            location: commandRef.location || node.location
          };
          const result2 = await evaluateExecInvocation(execInvocation, env);
          collectDescriptor(extractInterpolationDescriptor(result2.value));
          const execOutput = asText(result2.value);
          const strategy2 = EscapingStrategyFactory.getStrategy(context2);
          pushPart(strategy2.escape(execOutput));
          continue;
        }
        if (node.type === "TemplateVariable") {
          if (node.content) {
            value = await interpolateImpl(node.content, env, InterpolationContext.Template, options);
          } else if (variable.internal?.templateAst) {
            value = await interpolateImpl(variable.internal.templateAst, env, InterpolationContext.Template, options);
          }
          pushPart(String(value ?? ""));
          continue;
        }
        const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
        const fields = node.fields;
        const wantsVarMx = Array.isArray(fields) && fields.length > 0 && fields[0]?.type === "field" && String(fields[0]?.value ?? "") === "mx";
        const resolutionContext = wantsVarMx ? ResolutionContext.FieldAccess : ResolutionContext.StringInterpolation;
        value = await resolveVariable(variable, env, resolutionContext);
        collectDescriptor(extractInterpolationDescriptor(value));
        if (value === null && variable.internal?.isReserved && variable.internal?.isLazy) {
          const resolverVar = await env.getResolverVariable(varName);
          if (resolverVar && resolverVar.value !== null) {
            value = resolverVar.value;
          }
        }
        let fieldsToProcess = node.fields || [];
        if (fieldsToProcess.length > 0 && (typeof value === "object" || typeof value === "string") && value !== null) {
          const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
          for (const field of fieldsToProcess) {
            if (field.type === "variableIndex") {
              const { evaluateDataValue: evaluateDataValue2 } = await import('./data-value-evaluator-6G4NQGOF.mjs');
              const indexNode = typeof field.value === "object" ? field.value : {
                type: "VariableReference",
                valueType: "varIdentifier",
                identifier: String(field.value)
              };
              const indexValue = await evaluateDataValue2(indexNode, env);
              const resolvedField = {
                type: "bracketAccess",
                value: indexValue
              };
              const fieldResult = await accessField2(value, resolvedField, {
                preserveContext: true,
                env
              });
              value = fieldResult.value;
            } else {
              const fieldResult = await accessField2(value, field, {
                preserveContext: true,
                env
              });
              value = fieldResult.value;
            }
            if (value && typeof value === "object" && "type" in value) {
              const nodeValue = value;
              if (nodeValue.type === "Null") {
                value = null;
              } else if (nodeValue.type === "runExec" || nodeValue.type === "ExecInvocation" || nodeValue.type === "command" || nodeValue.type === "code" || nodeValue.type === "VariableReference" || nodeValue.type === "path") {
                value = await evaluateDataValue(value, env);
              }
            }
            if (value === void 0) break;
          }
        }
        if (node.pipes && node.pipes.length > 0) {
          const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
          value = await processPipeline2({
            value,
            env,
            node,
            identifier: node.identifier,
            descriptorHint: variable?.mx ? varMxToSecurityDescriptor(variable.mx) : void 0
          });
          if (typeof value === "string") {
            const strategy2 = EscapingStrategyFactory.getStrategy(context2);
            pushPart(strategy2.escape(value));
            continue;
          }
        }
        const { resolveValue, ResolutionContext: ResContext } = await import('./variable-resolution-HFG3FTZK.mjs');
        value = await resolveValue(value, env, ResContext.StringInterpolation);
        if (context2 === InterpolationContext.ShellCommand) {
          const classification = classifyShellValue(value);
          const strategy2 = EscapingStrategyFactory.getStrategy(context2);
          const escapeForSingleQuotes = /* @__PURE__ */ __name((text) => {
            if (text === "'") {
              return "'";
            }
            if (!text.includes("'")) {
              return text;
            }
            const segments = text.split("'");
            return segments.map((segment, index) => {
              if (index === segments.length - 1) {
                return segment;
              }
              return `${segment}'\\''`;
            }).join("");
          }, "escapeForSingleQuotes");
          const escapeForDoubleQuotes = /* @__PURE__ */ __name((text) => strategy2.escape(text), "escapeForDoubleQuotes");
          if (classification.kind === "simple") {
            if (withinSingleQuotes) {
              pushPart(escapeForSingleQuotes(classification.text));
            } else {
              pushPart(escapeForDoubleQuotes(classification.text));
            }
          } else if (classification.kind === "array-simple") {
            if (withinSingleQuotes) {
              const escapedElements = classification.elements.map((elem) => escapeForSingleQuotes(elem));
              pushPart(escapedElements.join(" "));
            } else {
              const escapedElements = classification.elements.map((elem) => escapeForDoubleQuotes(elem));
              pushPart(escapedElements.join(" "));
            }
          } else {
            if (withinDoubleQuotes) {
              pushPart(escapeForDoubleQuotes(classification.text));
            } else if (withinSingleQuotes) {
              pushPart(escapeForSingleQuotes(classification.text));
            } else {
              pushPart(shellQuote.quote([
                classification.text
              ]));
            }
          }
          continue;
        }
        let stringValue;
        if (value === null) {
          stringValue = "null";
        } else if (value === void 0) {
          stringValue = "";
        } else if (isStructuredValue(value)) {
          stringValue = asText(value);
        } else if (typeof value === "object" && "wrapperType" in value && "content" in value && Array.isArray(value.content)) {
          stringValue = await interpolateImpl(value.content, env, context2, options);
        } else if (typeof value === "object" && "type" in value) {
          const nodeValue = value;
          if (nodeValue.type === "array" && "items" in nodeValue) {
            const evaluatedArray = await evaluateDataValue(value, env);
            if (Array.isArray(evaluatedArray)) {
              const { JSONFormatter: JSONFormatter2 } = await import('./json-formatter-4JGND4MP.mjs');
              stringValue = JSONFormatter2.stringify(evaluatedArray);
            } else {
              stringValue = String(evaluatedArray);
            }
          } else if (nodeValue.type === "Null") {
            stringValue = "null";
          } else {
            const { isPipelineInput: isPipelineInput2 } = await import('./TypeGuards-JUFTTZPL.mjs');
            if (isPipelineInput2(value)) {
              stringValue = asText(value);
            } else {
              stringValue = JSON.stringify(value);
            }
          }
        } else if (Array.isArray(value)) {
          if (isStructuredValue(value) && value.type === "array") {
            stringValue = value.text;
            assertArrayBehavior(typeof stringValue === "string", "StructuredValue array should have .text property", {
              arrayLength: Array.isArray(value.data) ? value.data.length : 0,
              resultType: typeof stringValue
            });
          } else {
            const { JSONFormatter: JSONFormatter2 } = await import('./json-formatter-4JGND4MP.mjs');
            const printableArray = value.map((item) => {
              if (isStructuredValue(item)) {
                if (item.type === "object" || item.type === "array" || item.type === "json") {
                  return item.data;
                }
                return asText(item);
              }
              return item;
            });
            stringValue = JSONFormatter2.stringify(printableArray);
          }
        } else if (typeof value === "object") {
          const { isLoadContentResult: isLoadContentResult2 } = await import('./load-content-HGGFOE4J.mjs');
          if (isLoadContentResult2(value)) {
            stringValue = asText(value);
          } else if (isStructuredValue(value) && value.type === "array") {
            stringValue = value.text;
          } else if (variable && variable.internal?.isNamespace && node.fields?.length === 0) {
            const { JSONFormatter: JSONFormatter2 } = await import('./json-formatter-4JGND4MP.mjs');
            stringValue = JSONFormatter2.stringifyNamespace(value);
          } else if (value.__executable) {
            const params = value.paramNames || [];
            stringValue = `<function(${params.join(", ")})>`;
          } else if (value.type === "path" && value.values) {
            const { interpolate: pathInterpolate } = await import('./interpreter-MW7QI3FC.mjs');
            stringValue = await pathInterpolate(value.values.segments || [], env, InterpolationContext.FilePath, options);
          } else {
            const { JSONFormatter: JSONFormatter2 } = await import('./json-formatter-4JGND4MP.mjs');
            stringValue = JSONFormatter2.stringify(value);
          }
        } else {
          stringValue = String(value);
        }
        const strategy = EscapingStrategyFactory.getStrategy(context2);
        const escapedValue = strategy.escape(stringValue);
        pushPart(escapedValue);
        if (node.boundary) {
          if (node.boundary.type === "literal") {
            pushPart(node.boundary.value);
          }
        }
      } else if (node.type === "ExecInvocation") {
        const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
        const result2 = await evaluateExecInvocation(node, env);
        collectDescriptor(extractInterpolationDescriptor(result2.value));
        const stringValue = asText(result2.value);
        const strategy = EscapingStrategyFactory.getStrategy(context2);
        pushPart(strategy.escape(stringValue));
      } else if (node.type === "FileReference") {
        const result2 = await interpolateFileReference(node, env, context2, interpolateImpl);
        pushPart(result2);
      } else if (node.type === "TemplateForBlock") {
        const sourceEval = await evaluate3(node.source, env, {
          isExpression: true
        });
        const { toIterable: toIterable2 } = await import('./for-utils-AL3W5YD7.mjs');
        const iterable = toIterable2(sourceEval.value);
        if (!iterable) {
          continue;
        }
        const { VariableImporter: VariableImporter2 } = await import('./VariableImporter-7E4PKQ75.mjs');
        const importer = new VariableImporter2();
        for (const [key, value] of iterable) {
          const childEnv = env.createChildEnvironment();
          const varName = node.variable?.identifier || node.variable?.name || "item";
          const iterationVar = importer.createVariableFromValue(varName, value, "template-for", void 0, {
            env
          });
          childEnv.setVariable(varName, iterationVar);
          if (key !== null && key !== void 0) {
            const keyVar = importer.createVariableFromValue(`${varName}_key`, key, "template-for", void 0, {
              env
            });
            childEnv.setVariable(`${varName}_key`, keyVar);
          }
          const bodyStr = await interpolateImpl(node.body, childEnv, InterpolationContext.Template, options);
          pushPart(bodyStr);
        }
      } else if (node.type === "TemplateInlineShow") {
        const directive = {
          type: "Directive",
          kind: "show",
          subtype: void 0,
          values: {},
          raw: {},
          meta: {
            applyTailPipeline: !!node.tail
          },
          location: node.location
        };
        const n = node;
        switch (n.showKind) {
          case "command":
            directive.subtype = "showCommand";
            directive.values.command = n.content?.values?.command || n.content?.values || n.content;
            directive.meta = {
              ...directive.meta || {},
              ...n.content?.meta || {}
            };
            if (n.tail) directive.values.withClause = n.tail;
            break;
          case "code":
            directive.subtype = "showCode";
            directive.values.lang = n.lang || [];
            directive.values.code = n.code || [];
            directive.meta = {
              ...directive.meta || {},
              ...n.meta || {}
            };
            if (n.tail) directive.values.withClause = n.tail;
            break;
          case "template":
            directive.subtype = "showTemplate";
            directive.values.content = n.template?.values?.content ? [
              {
                content: n.template.values.content
              }
            ] : n.template?.values ? [
              n.template.values
            ] : [];
            directive.meta = {
              ...directive.meta || {},
              ...n.template?.meta || {},
              isTemplateContent: true
            };
            if (n.tail) directive.values.withClause = n.tail;
            break;
          case "load":
            directive.subtype = "showLoadContent";
            directive.values.loadContent = n.loadContent;
            if (n.tail) directive.values.withClause = n.tail;
            break;
          case "reference":
            if (n.reference?.type === "VariableReference" || n.reference?.type === "VariableReferenceWithTail" || n.reference?.type === "TemplateVariable") {
              directive.subtype = "showVariable";
              directive.values.variable = n.reference;
            } else {
              directive.subtype = "showExecInvocation";
              directive.values.execInvocation = n.reference;
            }
            break;
        }
        const { evaluateShow: evaluateShow2 } = await import('./show-5RN42ZAU.mjs');
        const res = await evaluateShow2(directive, env, {
          isExpression: true
        });
        pushPart(asText(res.value ?? ""));
      } else if (node.type === "Literal") {
        const { LiteralNode } = await import('./types-24ZTKTBW.mjs');
        const literalNode = node;
        const value = literalNode.value;
        let stringValue;
        if (value === null) {
          stringValue = "null";
        } else if (value === void 0) {
          stringValue = "";
        } else {
          stringValue = String(value);
        }
        const strategy = EscapingStrategyFactory.getStrategy(context2);
        pushPart(strategy.escape(stringValue));
      }
    }
    const result = parts.join("");
    return result;
  }, "interpolate");
  return interpolateImpl;
}
__name(createInterpolator, "createInterpolator");
function extractInterpolationDescriptor(value) {
  if (!value) {
    return void 0;
  }
  if (isStructuredValue(value)) {
    return varMxToSecurityDescriptor(value.mx);
  }
  if (typeof value === "object") {
    const mx = value.mx;
    return mx ? varMxToSecurityDescriptor(mx) : void 0;
  }
  return void 0;
}
__name(extractInterpolationDescriptor, "extractInterpolationDescriptor");
async function interpolateFileReference(node, env, context2, interpolateFn) {
  const { FileReferenceNode } = await import('./types-24ZTKTBW.mjs');
  if (node.meta?.isPlaceholder) {
    const currentFile = env.getCurrentIterationFile?.();
    if (!currentFile) {
      throw new Error('<> can only be used in "as" template contexts');
    }
    return processFileFields(currentFile, node.fields, node.pipes, env);
  }
  let resolvedPath;
  if (typeof node.source === "string") {
    resolvedPath = node.source;
  } else if (node.source.raw) {
    resolvedPath = node.source.raw;
  } else if (node.source.segments) {
    resolvedPath = await interpolateFn(node.source.segments, env);
  } else {
    resolvedPath = await interpolateFn([
      node.source
    ], env);
  }
  if (!env.isFileInterpolationEnabled()) {
    throw new Error("File interpolation disabled by security policy");
  }
  if (env.isInInterpolationStack(resolvedPath)) {
    console.error(`Warning: Circular reference detected - '${resolvedPath}' references itself, skipping`);
    return "";
  }
  env.pushInterpolationStack(resolvedPath);
  try {
    const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
    const { isLoadContentResult: isLoadContentResult2 } = await import('./load-content-HGGFOE4J.mjs');
    let loadResult;
    try {
      const sourceToUse = resolvedPath !== node.source?.raw ? {
        type: "path",
        raw: resolvedPath,
        segments: [
          {
            type: "Text",
            content: resolvedPath
          }
        ]
      } : node.source;
      loadResult = await processContentLoader2({
        type: "load-content",
        source: sourceToUse
      }, env);
    } catch (error) {
      if (error.code === "ENOENT") {
        console.error(`Warning: File not found - '${resolvedPath}'`);
        if (resolvedPath.includes("@")) {
          const varMatches = resolvedPath.match(/@(\w+)/g);
          if (varMatches && varMatches.length > 0) {
            console.error("");
            for (const match of varMatches) {
              const varName = match.substring(1);
              try {
                const actualValue = env.getVariable(varName);
                const valueType = actualValue?.type || typeof actualValue;
                const valuePreview = JSON.stringify(actualValue, null, 2).substring(0, 200);
                console.error(`Variable @${varName} is a ${valueType} containing:`);
                console.error(valuePreview);
              } catch {
                console.error(`Variable @${varName} is not in scope or failed to retrieve.`);
              }
            }
            console.error(`
Content loaders like <path> need a string path or array of paths.`);
            console.error(`Did you mean to use the variable directly (without angle brackets)?`);
            console.error("");
          }
        } else if (!resolvedPath.startsWith("/") && !resolvedPath.startsWith("@")) {
          console.error(`Hint: Paths are relative to mlld files. You can make them relative to your project root with the \`@base/\` prefix`);
        }
        return "";
      } else if (error.code === "EACCES") {
        console.error(`Warning: Permission denied - '${resolvedPath}'`);
        return "";
      } else {
        console.error(`Warning: Failed to load file '${resolvedPath}': ${error.message}`);
        const hasAngleBracket = resolvedPath.includes("<") || resolvedPath.includes(">");
        if (hasAngleBracket) {
          console.error("");
          console.error("This looks like you tried to use alligator field access inside XML/HTML tags.");
          console.error("Due to grammar ambiguity with nested angle brackets, this pattern is not supported.");
          console.error("");
          console.error("Workaround: Use a variable instead:");
          console.error("  /var @file = <file.md>.keep");
          console.error("  /show `<@file.mx.filename>@file</@file.mx.filename>`");
          console.error("");
          return "";
        }
        let hasVariableHint = false;
        if (resolvedPath.includes("@")) {
          const varMatches = resolvedPath.match(/@(\w+)/g);
          if (varMatches && varMatches.length > 0) {
            hasVariableHint = true;
            console.error("");
            for (const match of varMatches) {
              const varName = match.substring(1);
              try {
                const actualValue = env.getVariable(varName);
                const valueType = actualValue?.type || typeof actualValue;
                const valuePreview = JSON.stringify(actualValue, null, 2).substring(0, 200);
                console.error(`Variable @${varName} is a ${valueType} containing:`);
                console.error(valuePreview);
              } catch {
                console.error(`Variable @${varName} is not in scope or failed to retrieve.`);
              }
            }
            console.error(`
Content loaders like <path> need a string path or array of paths.`);
            console.error(`Did you mean to use the variable directly (without angle brackets)?`);
            console.error("");
          }
        }
        if (!hasVariableHint && !resolvedPath.startsWith("/") && !resolvedPath.startsWith("@")) {
          console.error(`Hint: Paths are relative to mlld files. You can make them relative to your project root with the \`@base/\` prefix`);
        }
        return "";
      }
    }
    if (isStructuredValue(loadResult) && loadResult.type === "array") {
      const items = loadResult.data;
      const contents = await Promise.all(items.map((file) => processFileFields(file, node.fields, node.pipes, env)));
      return contents.join("\n\n");
    }
    return processFileFields(loadResult, node.fields, node.pipes, env);
  } finally {
    env.popInterpolationStack(resolvedPath);
  }
}
__name(interpolateFileReference, "interpolateFileReference");
async function processFileFields(content, fields, pipes, env) {
  const { isLoadContentResult: isLoadContentResult2 } = await import('./load-content-HGGFOE4J.mjs');
  let result = content;
  if (isLoadContentResult2(result)) {
    if (!fields || fields.length === 0) {
      result = asText(result);
    }
  }
  if (fields && fields.length > 0) {
    const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
    for (const field of fields) {
      try {
        const fieldResult = await accessField2(result, field, {
          preserveContext: true,
          env
        });
        result = fieldResult.value;
        if (result === void 0) {
          console.error(`Warning: field '${field.value}' not found`);
          return "";
        }
      } catch (error) {
        console.error(`Warning: field '${field.value}' not found`);
        return "";
      }
    }
  }
  if (pipes && pipes.length > 0) {
    const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
    const nodeWithPipes = {
      pipes
    };
    result = await processPipeline2({
      value: result,
      env,
      node: nodeWithPipes
    });
    return asText(result);
  }
  if (isStructuredValue(result)) {
    return asText(result);
  }
  return typeof result === "string" ? result : JSON.stringify(result);
}
__name(processFileFields, "processFileFields");

// interpreter/core/interpreter.ts
function isDocument(node) {
  return node.type === "Document";
}
__name(isDocument, "isDocument");
function isDirective(node) {
  return node.type === "Directive";
}
__name(isDirective, "isDirective");
function isText(node) {
  return node.type === "Text";
}
__name(isText, "isText");
function isNewline(node) {
  return node.type === "Newline";
}
__name(isNewline, "isNewline");
function isComment(node) {
  return node.type === "Comment";
}
__name(isComment, "isComment");
function isFrontmatter(node) {
  return node.type === "Frontmatter";
}
__name(isFrontmatter, "isFrontmatter");
function isCodeFence(node) {
  return node.type === "CodeFence";
}
__name(isCodeFence, "isCodeFence");
function isMlldRunBlock(node) {
  return node.type === "MlldRunBlock";
}
__name(isMlldRunBlock, "isMlldRunBlock");
function isVariableReference(node) {
  return node.type === "VariableReference";
}
__name(isVariableReference, "isVariableReference");
async function evaluate2(node, env, context1) {
  if (Array.isArray(node)) {
    let lastValue = void 0;
    let lastResult = null;
    if (node.length > 0 && isFrontmatter(node[0])) {
      const frontmatterNode = node[0];
      const frontmatterData = parseFrontmatter(frontmatterNode.content);
      env.setFrontmatter(frontmatterData);
      for (let i = 1; i < node.length; i++) {
        const n = node[i];
        const result = await evaluate2(n, env, context1);
        lastValue = result.value;
        lastResult = result;
        if (!isDirective(n) && !context1?.isExpression) {
          if (isText(n) && n.content.trimStart().match(/^(>>|<<)/)) {
            continue;
          }
          if (isComment(n)) {
            interpreterLogger.debug("Skipping comment node:", {
              content: n.content
            });
            continue;
          }
          if (isText(n)) {
            if (/^\n+$/.test(n.content)) {
              for (let i2 = 0; i2 < n.content.length; i2++) {
                env.emitIntent({
                  type: "break",
                  value: "\n",
                  source: "newline",
                  visibility: "always",
                  collapsible: true
                });
              }
            } else {
              const materialized = materializeDisplayValue(n.content, void 0, n.content);
              env.emitIntent({
                type: "content",
                value: materialized.text,
                source: "text",
                visibility: "always",
                collapsible: false
              });
              if (materialized.descriptor) {
                env.recordSecurityDescriptor(materialized.descriptor);
              }
            }
          } else if (isNewline(n)) {
            env.emitIntent({
              type: "break",
              value: "\n",
              source: "newline",
              visibility: "always",
              collapsible: true
            });
          } else if (isCodeFence(n)) {
            const materialized = materializeDisplayValue(n.content, void 0, n.content);
            env.emitIntent({
              type: "content",
              value: materialized.text,
              source: "text",
              visibility: "always",
              collapsible: false
            });
            if (materialized.descriptor) {
              env.recordSecurityDescriptor(materialized.descriptor);
            }
          } else if (isMlldRunBlock(n) && !n.error) ; else if ("wrapperType" in n && "content" in n) ; else {
            interpreterLogger.debug("Skipping non-document node type:", {
              type: n.type
            });
          }
        }
        if (!context1?.isExpression) {
          env.addNode(n);
        }
      }
    } else {
      for (const n of node) {
        const result = await evaluate2(n, env, context1);
        lastValue = result.value;
        lastResult = result;
        if (!context1?.isExpression) {
          env.addNode(n);
        }
        if (!isDirective(n) && !context1?.isExpression) {
          if (isText(n) && n.content.trimStart().match(/^(>>|<<)/)) {
            continue;
          }
          if (isComment(n)) {
            interpreterLogger.debug("Skipping comment node:", {
              content: n.content
            });
            continue;
          }
          if (isText(n)) {
            if (/^\n+$/.test(n.content)) {
              for (let i = 0; i < n.content.length; i++) {
                env.emitIntent({
                  type: "break",
                  value: "\n",
                  source: "newline",
                  visibility: "always",
                  collapsible: true
                });
              }
            } else {
              const materialized = materializeDisplayValue(n.content, void 0, n.content);
              env.emitIntent({
                type: "content",
                value: materialized.text,
                source: "text",
                visibility: "always",
                collapsible: false
              });
              if (materialized.descriptor) {
                env.recordSecurityDescriptor(materialized.descriptor);
              }
            }
          } else if (isNewline(n)) {
            env.emitIntent({
              type: "break",
              value: "\n",
              source: "newline",
              visibility: "always",
              collapsible: true
            });
          } else if (isCodeFence(n)) {
            const materialized = materializeDisplayValue(n.content, void 0, n.content);
            env.emitIntent({
              type: "content",
              value: materialized.text,
              source: "text",
              visibility: "always",
              collapsible: false
            });
            if (materialized.descriptor) {
              env.recordSecurityDescriptor(materialized.descriptor);
            }
          } else if (isMlldRunBlock(n) && !n.error) ; else if ("wrapperType" in n && "content" in n) ; else {
            interpreterLogger.debug("Skipping non-document node type:", {
              type: n.type
            });
          }
        }
      }
    }
    if (lastResult && (lastResult.stdout !== void 0 || lastResult.stderr !== void 0 || lastResult.exitCode !== void 0)) {
      return lastResult;
    }
    return {
      value: lastValue,
      env
    };
  }
  if (!Array.isArray(node) && node && typeof node === "object") {
    let contentToInterpolate = null;
    if ("content" in node && Array.isArray(node.content) && "wrapperType" in node && !node.type) {
      contentToInterpolate = node.content;
    } else if (node.type === "template" && node.values?.content && Array.isArray(node.values.content)) {
      contentToInterpolate = node.values.content;
    } else if (node.type === "template" && node.content && Array.isArray(node.content)) {
      contentToInterpolate = node.content;
    }
    if (contentToInterpolate) {
      const interpolated = await interpolateWithSecurityRecording(contentToInterpolate, env);
      return {
        value: interpolated,
        env
      };
    }
  }
  if (isDocument(node)) {
    return evaluateDocument(node, env);
  }
  if (isDirective(node)) {
    return evaluateDirective(node, env, context1);
  }
  if (isText(node)) {
    return evaluateText(node, env);
  }
  if (isNewline(node)) {
    return {
      value: "\n",
      env
    };
  }
  if (isComment(node)) {
    return {
      value: node.content,
      env
    };
  }
  if (isFrontmatter(node)) {
    const frontmatterData = parseFrontmatter(node.content);
    env.setFrontmatter(frontmatterData);
    return {
      value: frontmatterData,
      env
    };
  }
  if (isCodeFence(node)) {
    env.emitIntent({
      type: "content",
      value: node.content,
      source: "text",
      visibility: "always",
      collapsible: false
    });
    return {
      value: node.content,
      env
    };
  }
  if (isMlldRunBlock(node)) {
    if (node.error) {
      env.emitIntent({
        type: "error",
        value: `Error in mlld-run block: ${node.error}`,
        source: "directive",
        visibility: "always",
        collapsible: false
      });
      return {
        value: node.error,
        env
      };
    }
    const result = await evaluate2(node.content, env, context1);
    return result;
  }
  if (isVariableReference(node)) {
    let hasValidLocation2 = function(loc) {
      return typeof loc === "object" && loc !== null && "start" in loc && "end" in loc;
    };
    __name(hasValidLocation2, "hasValidLocation");
    const location = node.location;
    const hasZeroOffset = hasValidLocation2(location) && location.start?.offset === 0 && location.end?.offset === 0;
    if (hasZeroOffset && node.valueType !== "commandRef" && node.valueType !== "varIdentifier" && // Allow ambient @mx to resolve even if parser produced zero offsets
    node.identifier !== "mx") {
      return {
        value: "",
        env
      };
    }
    let variable = env.getVariable(node.identifier);
    if (!variable && env.hasVariable(node.identifier)) {
      const resolverVar = await env.getResolverVariable(node.identifier);
      if (resolverVar) {
        variable = resolverVar;
      }
    }
    if (!variable) {
      if (context1?.isExpression) {
        return {
          value: void 0,
          env
        };
      }
      throw new Error(`Variable not found: ${node.identifier}`);
    }
    if (node.valueType === "commandRef" && isCommandVariable(variable)) {
      const args = node.args || [];
      const definition = variable.definition || variable.value;
      if (!definition) {
        throw new Error(`Command variable ${node.identifier} has no definition`);
      }
      if (typeof definition === "object" && definition !== null && "type" in definition) {
        const typedDef = definition;
        if (typedDef.type === "command") {
          const commandTemplate = typedDef.commandTemplate || typedDef.command;
          if (!commandTemplate) {
            throw new Error(`Command ${node.identifier} has no command template`);
          }
          const command = await interpolateWithSecurityRecording(commandTemplate, env);
          if (args.length > 0) ;
          const stdout = await env.executeCommand(command);
          return {
            value: stdout,
            env,
            stdout,
            stderr: "",
            exitCode: 0
            // executeCommand only returns on success
          };
        } else if (typedDef.type === "code") {
          const codeTemplate = typedDef.codeTemplate || typedDef.code;
          if (!codeTemplate) {
            throw new Error(`Code command ${node.identifier} has no code template`);
          }
          const code = await interpolateWithSecurityRecording(codeTemplate, env);
          const result = await env.executeCode(code, typedDef.language || "javascript");
          return {
            value: result,
            env,
            stdout: result,
            stderr: "",
            exitCode: 0
          };
        }
      }
    }
    const { resolveVariable, ResolutionContext } = await import('./variable-resolution-HFG3FTZK.mjs');
    const isInExpression = context1 && context1.isExpression;
    const hasFieldAccess = Array.isArray(node.fields) && node.fields.length > 0;
    const resolutionContext = hasFieldAccess ? ResolutionContext.FieldAccess : isInExpression ? ResolutionContext.Equality : ResolutionContext.FieldAccess;
    let resolvedValue = await resolveVariable(variable, env, resolutionContext);
    if (node.fields && node.fields.length > 0) {
      const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
      const fieldAccessLocation = astLocationToSourceLocation(node.location, env.getCurrentFilePath());
      for (const field of node.fields) {
        const fieldResult = await accessField2(resolvedValue, field, {
          preserveContext: true,
          returnUndefinedForMissing: context1?.isCondition,
          env,
          sourceLocation: fieldAccessLocation
        });
        resolvedValue = fieldResult.value;
        if (resolvedValue === void 0) break;
      }
    }
    if (node.pipes && node.pipes.length > 0) {
      const { processPipeline: processPipeline2 } = await import('./unified-processor-GTJC5G2K.mjs');
      resolvedValue = await processPipeline2({
        value: resolvedValue,
        env,
        node,
        identifier: node.identifier
      });
    }
    return {
      value: resolvedValue,
      env
    };
  }
  if (isExecInvocation(node)) {
    const { evaluateExecInvocation } = await import('./exec-invocation-M54PNM33.mjs');
    return evaluateExecInvocation(node, env);
  }
  if (node.type === "VariableReferenceWithTail") {
    const { VariableReferenceEvaluator: VariableReferenceEvaluator2 } = await import('./VariableReferenceEvaluator-Y3VNX4OC.mjs');
    const evaluator = new VariableReferenceEvaluator2();
    const result = await evaluator.evaluate(node, env);
    return {
      value: result,
      env
    };
  }
  if (node.type === "BinaryExpression" || node.type === "TernaryExpression" || node.type === "UnaryExpression") {
    const { evaluateUnifiedExpression: evaluateUnifiedExpression2 } = await import('./expressions-CYFHZWDH.mjs');
    const result = await evaluateUnifiedExpression2(node, env);
    return {
      value: result.value,
      env
    };
  }
  if (isLiteralNode(node)) {
    if (node.valueType === "retry") {
      const pipelineCtx = env.getPipelineContext();
      if (!pipelineCtx) {
        throw new Error("retry keyword used outside pipeline context");
      }
      return {
        value: "retry",
        env
      };
    }
    if (node.valueType === "done" || node.valueType === "continue") {
      return {
        value: node,
        env
      };
    }
    return {
      value: node.value,
      env
    };
  }
  if (node.type === "WhenExpression") {
    const { evaluateWhenExpression: evaluateWhenExpression2 } = await import('./when-expression-ZW53U2K2.mjs');
    return evaluateWhenExpression2(node, env, context1);
  }
  if (node.type === "ExeBlock") {
    const { evaluateExeBlock: evaluateExeBlock2 } = await import('./exe-T3P26GTO.mjs');
    return evaluateExeBlock2(node, env);
  }
  if (node.type === "foreach" || node.type === "foreach-command") {
    const { evaluateForeachCommand: evaluateForeachCommand2 } = await import('./foreach-USOCOKPZ.mjs');
    const result = await evaluateForeachCommand2(node, env);
    return {
      value: result,
      env
    };
  }
  if (node.type === "ForExpression") {
    const { evaluateForExpression: evaluateForExpression2 } = await import('./for-FC7J7F6X.mjs');
    const result = await evaluateForExpression2(node, env);
    return {
      value: result,
      env
    };
  }
  if (node.type === "array" || node.type === "object") {
    const result = await evaluateDataValue(node, env);
    return {
      value: result,
      env
    };
  }
  if (node.type === "load-content") {
    const result = await evaluateDataValue(node, env);
    return {
      value: result,
      env
    };
  }
  if (node.type === "FileReference") {
    const fileRefNode = node;
    const { processContentLoader: processContentLoader2 } = await import('./content-loader-QADYRQX5.mjs');
    const { accessField: accessField2 } = await import('./field-access-MJ6PMBJX.mjs');
    const { wrapLoadContentValue: wrapLoadContentValue2 } = await import('./load-content-structured-FVMWENVK.mjs');
    const { isStructuredValue: isStructuredValue2 } = await import('./structured-value-OILNJH5U.mjs');
    const loadContentNode = {
      type: "load-content",
      source: fileRefNode.source
    };
    const rawLoadResult = await processContentLoader2(loadContentNode, env);
    let loadResult = isStructuredValue2(rawLoadResult) ? rawLoadResult : wrapLoadContentValue2(rawLoadResult);
    if (fileRefNode.fields && fileRefNode.fields.length > 0) {
      let result = loadResult;
      for (const field of fileRefNode.fields) {
        result = await accessField2(result, field, {
          env
        });
      }
      return {
        value: result,
        env
      };
    }
    return {
      value: loadResult,
      env
    };
  }
  if (node.type === "command") {
    let commandStr;
    if (typeof node.command === "string") {
      commandStr = node.command || "";
    } else if (Array.isArray(node.command)) {
      const interpolatedCommand = await interpolateWithSecurityRecording(node.command, env);
      commandStr = interpolatedCommand || "";
    } else {
      commandStr = "";
    }
    if (node.hasRunKeyword) {
      const result = await env.executeCommand(commandStr);
      return {
        value: result,
        env
      };
    }
    return {
      value: commandStr,
      env
    };
  }
  throw new Error(`Unknown node type: ${node.type}`);
}
__name(evaluate2, "evaluate");
var interpolate = createInterpolator(() => ({
  evaluate: evaluate2
}));
async function interpolateWithSecurityRecording(nodes, env, context1) {
  const descriptors = [];
  const text = await interpolate(nodes, env, context1, {
    collectSecurityDescriptor: /* @__PURE__ */ __name((descriptor) => {
      if (descriptor) {
        descriptors.push(descriptor);
      }
    }, "collectSecurityDescriptor")
  });
  if (descriptors.length > 0) {
    const merged = descriptors.length === 1 ? descriptors[0] : env.mergeSecurityDescriptors(...descriptors);
    env.recordSecurityDescriptor(merged);
  }
  return text;
}
__name(interpolateWithSecurityRecording, "interpolateWithSecurityRecording");
async function evaluateDocument(doc, env) {
  let lastValue = void 0;
  for (const child of doc.nodes) {
    const result = await evaluate2(child, env, context);
    lastValue = result.value;
    if (isText(child)) {
      env.emitIntent({
        type: "content",
        value: child.content,
        source: "text",
        visibility: "always",
        collapsible: false
      });
    }
  }
  return {
    value: lastValue,
    env
  };
}
__name(evaluateDocument, "evaluateDocument");
async function evaluateText(node, env) {
  return {
    value: node.content,
    env
  };
}
__name(evaluateText, "evaluateText");
function cleanNamespaceForDisplay(namespaceObject) {
  const cleaned = {
    frontmatter: {},
    exports: {
      variables: {},
      executables: {}
    }
  };
  const fm = namespaceObject.fm || namespaceObject.frontmatter || namespaceObject.__meta__;
  if (fm && Object.keys(fm).length > 0) {
    cleaned.frontmatter = fm;
  }
  const internalFields = [
    "fm",
    "frontmatter",
    "__meta__"
  ];
  let hasExports = false;
  for (const [key, value] of Object.entries(namespaceObject)) {
    if (!internalFields.includes(key)) {
      hasExports = true;
      if (value && typeof value === "object" && value.__executable) {
        const params = value.paramNames || [];
        cleaned.exports.executables[key] = `<function(${params.join(", ")})>`;
      } else if (value && typeof value === "object" && value.type === "executable") {
        const def = value.value || value.definition;
        const params = def?.paramNames || [];
        cleaned.exports.executables[key] = `<function(${params.join(", ")})>`;
      } else {
        if (value && typeof value === "object" && value.value !== void 0) {
          cleaned.exports.variables[key] = value.value;
        } else {
          cleaned.exports.variables[key] = value;
        }
      }
    }
  }
  const hasFrontmatter = fm && Object.keys(fm).length > 0;
  if (!hasFrontmatter && !hasExports) {
    return "{}";
  }
  if (!hasFrontmatter) {
    delete cleaned.frontmatter;
  }
  return JSON.stringify(cleaned, null, 2);
}
__name(cleanNamespaceForDisplay, "cleanNamespaceForDisplay");

// interpreter/eval/expression.ts
function isTruthy2(value) {
  if (value && typeof value === "object" && "type" in value && "name" in value) {
    const variable = value;
    if (isTextLike(variable)) {
      const str = variable.value;
      if (str === "" || str.toLowerCase() === "false" || str === "0") {
        return false;
      }
      return true;
    } else if (isArray(variable)) {
      return variable.value.length > 0;
    } else if (isObject(variable)) {
      return Object.keys(variable.value).length > 0;
    } else if (isCommandResult(variable)) {
      return variable.value.trim().length > 0;
    } else if (isPipelineInput(variable)) {
      assertStructuredValue(variable.value, "expression:isTruthy:pipeline-input");
      return asText(variable.value).length > 0;
    }
    return isTruthy2(variable.value);
  }
  if (value === null || value === void 0) {
    return false;
  }
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value === "number") {
    return value !== 0 && !isNaN(value);
  }
  if (typeof value === "string") {
    if (value === "*") {
      return true;
    }
    if (value === "") {
      return false;
    }
    if (value.toLowerCase() === "false") {
      return false;
    }
    if (value === "0") {
      return false;
    }
    return true;
  }
  if (Array.isArray(value)) {
    return value.length > 0;
  }
  if (typeof value === "object") {
    return Object.keys(value).length > 0;
  }
  return !!value;
}
__name(isTruthy2, "isTruthy");
async function evaluateExpression(node, env, context2) {
  if (node.type === "BinaryExpression") {
    return evaluateBinaryExpression2(node, env, context2);
  } else if (node.type === "TernaryExpression") {
    return evaluateTernaryExpression2(node, env, context2);
  } else if (node.type === "UnaryExpression") {
    return evaluateUnaryExpression2(node, env, context2);
  }
  throw new Error(`Unknown expression type: ${node.type}`);
}
__name(evaluateExpression, "evaluateExpression");
async function evaluateBinaryExpression2(node, env, context2) {
  let { operator, left, right } = node;
  if (Array.isArray(operator)) {
    operator = operator[0];
  }
  const isExecParallel = operator === "||" && left?.type === "ExecInvocation" && right?.type === "ExecInvocation";
  if (isExecParallel) {
    const { value } = await executeParallelExecInvocations(left, right, env);
    return {
      value,
      env
    };
  }
  const expressionContext = {
    isExpression: true,
    ...context2
  };
  if (operator === "&&") {
    const leftResult2 = await evaluate2(left, env, expressionContext);
    const leftTruthy = isTruthy2(leftResult2.value);
    if (!leftTruthy) {
      return {
        value: leftResult2.value,
        env
      };
    }
    const rightResult2 = await evaluate2(right, env, expressionContext);
    return {
      value: rightResult2.value,
      env
    };
  }
  if (operator === "||") {
    const leftResult2 = await evaluate2(left, env, expressionContext);
    const leftTruthy = isTruthy2(leftResult2.value);
    if (leftTruthy) {
      return {
        value: leftResult2.value,
        env
      };
    }
    const rightResult2 = await evaluate2(right, env, expressionContext);
    return {
      value: rightResult2.value,
      env
    };
  }
  const leftResult = await evaluate2(left, env, expressionContext);
  const rightResult = await evaluate2(right, env, expressionContext);
  if (operator === "==") {
    const equal = isEqual(leftResult.value, rightResult.value);
    return {
      value: equal,
      env
    };
  }
  if (operator === "!=") {
    const equal = isEqual(leftResult.value, rightResult.value);
    return {
      value: !equal,
      env
    };
  }
  if (operator === "<") {
    const leftNum = toNumber(leftResult.value);
    const rightNum = toNumber(rightResult.value);
    return {
      value: leftNum < rightNum,
      env
    };
  }
  if (operator === ">") {
    const leftNum = toNumber(leftResult.value);
    const rightNum = toNumber(rightResult.value);
    return {
      value: leftNum > rightNum,
      env
    };
  }
  if (operator === "<=") {
    const leftNum = toNumber(leftResult.value);
    const rightNum = toNumber(rightResult.value);
    return {
      value: leftNum <= rightNum,
      env
    };
  }
  if (operator === ">=") {
    const leftNum = toNumber(leftResult.value);
    const rightNum = toNumber(rightResult.value);
    return {
      value: leftNum >= rightNum,
      env
    };
  }
  throw new Error(`Unknown binary operator: ${operator}`);
}
__name(evaluateBinaryExpression2, "evaluateBinaryExpression");
async function evaluateTernaryExpression2(node, env, context2) {
  const { condition, trueBranch, falseBranch } = node;
  const condResult = await evaluate2(condition, env, {
    isExpression: true,
    ...context2
  });
  const condTruthy = isTruthy2(condResult.value);
  if (condTruthy) {
    return evaluate2(trueBranch, env, {
      isExpression: true,
      ...context2
    });
  } else {
    return evaluate2(falseBranch, env, {
      isExpression: true,
      ...context2
    });
  }
}
__name(evaluateTernaryExpression2, "evaluateTernaryExpression");
async function evaluateUnaryExpression2(node, env, context2) {
  const { operator, operand } = node;
  if (operator === "!") {
    const operandResult = await evaluate2(operand, env, {
      isExpression: true,
      ...context2
    });
    const operandTruthy = isTruthy2(operandResult.value);
    return {
      value: !operandTruthy,
      env
    };
  }
  throw new Error(`Unknown unary operator: ${operator}`);
}
__name(evaluateUnaryExpression2, "evaluateUnaryExpression");
function isEqual(a, b) {
  const aValue = extractValue(a);
  const bValue = extractValue(b);
  if (aValue === null || aValue === void 0) {
    return bValue === null || bValue === void 0;
  }
  if (bValue === null || bValue === void 0) {
    return false;
  }
  if (typeof aValue === "string" && typeof bValue === "boolean") {
    return aValue === "true" && bValue === true || aValue === "false" && bValue === false;
  }
  if (typeof bValue === "string" && typeof aValue === "boolean") {
    return bValue === "true" && aValue === true || bValue === "false" && aValue === false;
  }
  if (typeof aValue === "string" && typeof bValue === "number") {
    const numA = Number(aValue);
    return !isNaN(numA) && numA === bValue;
  }
  if (typeof bValue === "string" && typeof aValue === "number") {
    const numB = Number(bValue);
    return !isNaN(numB) && numB === aValue;
  }
  return aValue === bValue;
}
__name(isEqual, "isEqual");
function extractValue(value) {
  if (value && typeof value === "object" && "type" in value && "value" in value) {
    const variable = value;
    return extractValue(variable.value);
  }
  if (isStructuredValue(value)) {
    return value.data ?? value.text;
  }
  return value;
}
__name(extractValue, "extractValue");
function toNumber(value) {
  const extracted = extractValue(value);
  if (extracted === null) {
    return 0;
  }
  if (extracted === void 0) {
    return NaN;
  }
  if (typeof extracted === "boolean") {
    return extracted ? 1 : 0;
  }
  if (typeof extracted === "number") {
    return extracted;
  }
  if (typeof extracted === "string") {
    if (extracted === "true") {
      return 1;
    }
    if (extracted === "false") {
      return 0;
    }
    const num = Number(extracted);
    return num;
  }
  return NaN;
}
__name(toNumber, "toNumber");

export { ALLOW_ALL_POLICY, ForeachSectionEvaluator, HashUtils, PipelineExecutor, TaintTracker, VariableReferenceEvaluator, applyHeaderTransform, attachBuiltinEffects, buildPipelineStructuredValue, cleanNamespaceForDisplay, coerceValueForStdin, collectEvaluationErrors, combineValues, deriveImportTaint, evaluate2 as evaluate, evaluateArrayFilter, evaluateCondition, evaluateConditionalInclusion, evaluateDataValue, evaluateDirective, evaluateExe, evaluateExeBlock, evaluateExpression, evaluateForDirective, evaluateForExpression, evaluateRun, evaluateShow, evaluateUnifiedExpression, evaluateWhenExpression, extractSection2 as extractSection, getAdapter, getDataValueEvaluator, getEvaluatorStats, getGuardTransformedInputs, handleGuardDecision, hasUnevaluatedDirectives, interpolate, interpolateFileReference, isDirectiveHookTarget, isEffectHookTarget, isEqual, isExecHookTarget, isFullyEvaluated, isTruthy2 as isTruthy, isUnifiedExpressionNode, jsonToXml, loadStreamAdapter, materializeDisplayValue, materializeGuardInputs, materializeGuardInputsWithMapping, mergeNeedsDeclarations, mergePolicyConfigs, needsPipelineProcessing, normalizeNeedsDeclaration, normalizePolicyConfig, normalizeWantsDeclaration, peekWhenExpressionType, processContentLoader, processFileFields, processPipeline, resolveShadowEnvironment, resolveStreamFormatValue, resolveWorkingDirectory, runWithGuardRetry, toNumber, wrapExecResult, wrapPipelineResult };
//# sourceMappingURL=chunk-IA26UJYI.mjs.map
//# sourceMappingURL=chunk-IA26UJYI.mjs.map