// ../core/src/contextRouting/graphExecutionMode.ts
var GRAPH_EXECUTION_MODE_ROUTER_VERSION = 1;
var GRAPH_EXECUTION_MODES = [
  "convex_local",
  "connected_work_shallow",
  "memgraph_depth3",
  "memgraph_depth5",
  "memgraph_depth5_plus_lite_llm"
];
var MODE_REQUIREMENTS = {
  convex_local: { requiresNetwork: false, requiresProvider: false },
  connected_work_shallow: { requiresNetwork: false, requiresProvider: false },
  memgraph_depth3: { requiresNetwork: true, requiresProvider: false },
  memgraph_depth5: { requiresNetwork: true, requiresProvider: false },
  memgraph_depth5_plus_lite_llm: { requiresNetwork: true, requiresProvider: true }
};
var MODE_LIFT = {
  convex_local: "baseline",
  connected_work_shallow: "local_enrichment",
  memgraph_depth3: "graph_expansion",
  memgraph_depth5: "deep_graph_expansion",
  memgraph_depth5_plus_lite_llm: "synthesis"
};
var MODE_COST = {
  convex_local: "local",
  connected_work_shallow: "connected_work_local",
  memgraph_depth3: "network_graph",
  memgraph_depth5: "network_graph",
  memgraph_depth5_plus_lite_llm: "network_graph_provider"
};
function graphExecutionModePolicyMetadataFor(mode) {
  const requirements = MODE_REQUIREMENTS[mode];
  return {
    version: GRAPH_EXECUTION_MODE_ROUTER_VERSION,
    mode,
    requiresNetwork: requirements.requiresNetwork,
    requiresProvider: requirements.requiresProvider,
    lift: MODE_LIFT[mode],
    cost: MODE_COST[mode],
    reportOnly: true
  };
}
function graphExecutionModePolicyMetadataList() {
  return GRAPH_EXECUTION_MODES.map((mode) => graphExecutionModePolicyMetadataFor(mode));
}
function normalizeInput(input = {}) {
  return {
    intentConfidence: input.intentConfidence,
    graphComplexity: input.graphComplexity,
    localGraphConfidence: input.localGraphConfidence ?? null,
    graphScaleTier: input.graphScaleTier,
    highComplexityEvidenceScore: input.highComplexityEvidenceScore ?? null,
    highComplexityScaleEvidencePresent: input.graphScaleTier !== undefined || input.highComplexityEvidenceScore !== undefined,
    connectedWorkAvailable: input.connectedWorkAvailable ?? false,
    memgraphAvailable: input.memgraphAvailable ?? false,
    llmAvailable: input.llmAvailable ?? false,
    noLiveMode: input.noLiveMode ?? true,
    networkAllowed: input.networkAllowed ?? false,
    providerCallsAllowed: input.providerCallsAllowed ?? false,
    synthesisRequested: input.synthesisRequested ?? false
  };
}
function hasNoMeaningfulSignal(input) {
  return input.intentConfidence === undefined && input.graphComplexity === undefined && input.localGraphConfidence === null && input.synthesisRequested === false;
}
function recommendGraphExecutionMode(input) {
  if (hasNoMeaningfulSignal(input)) {
    return { mode: "convex_local", reason: "default_convex_local" };
  }
  if (input.intentConfidence === "strong" && (input.graphComplexity === undefined || input.graphComplexity === "simple") && (input.localGraphConfidence === null || input.localGraphConfidence >= 0.8)) {
    return { mode: "convex_local", reason: "strong_simple_local" };
  }
  if (input.graphComplexity === "shallow") {
    return { mode: "connected_work_shallow", reason: "connected_work_enrichment" };
  }
  if (input.graphComplexity === "medium") {
    return { mode: "memgraph_depth3", reason: "medium_graph_complexity" };
  }
  if (input.graphComplexity === "high") {
    if (!input.highComplexityScaleEvidencePresent) {
      return { mode: "memgraph_depth5", reason: "high_graph_complexity" };
    }
    if (input.graphScaleTier === "large_1500_3000" && input.highComplexityEvidenceScore !== null && input.highComplexityEvidenceScore >= 0.7) {
      return { mode: "memgraph_depth5", reason: "high_graph_complexity" };
    }
    return { mode: "memgraph_depth3", reason: "high_graph_complexity_depth5_scale_gated" };
  }
  if (input.intentConfidence === "ambiguous" || input.synthesisRequested) {
    return { mode: "memgraph_depth5_plus_lite_llm", reason: "ambiguous_synthesis" };
  }
  return { mode: "convex_local", reason: "default_convex_local" };
}
function blockersForMode(mode, input) {
  switch (mode) {
    case "convex_local":
      return [];
    case "connected_work_shallow":
      return input.connectedWorkAvailable ? [] : ["connected_work_unavailable"];
    case "memgraph_depth3":
    case "memgraph_depth5": {
      const blockers = [];
      if (input.noLiveMode)
        blockers.push("no_live_mode");
      if (!input.networkAllowed)
        blockers.push("network_disabled");
      if (!input.memgraphAvailable)
        blockers.push("memgraph_unavailable");
      return blockers;
    }
    case "memgraph_depth5_plus_lite_llm": {
      const blockers = [];
      if (input.noLiveMode)
        blockers.push("no_live_mode");
      if (!input.networkAllowed)
        blockers.push("network_disabled");
      if (!input.memgraphAvailable)
        blockers.push("memgraph_unavailable");
      if (!input.providerCallsAllowed)
        blockers.push("provider_calls_disabled");
      if (!input.llmAvailable)
        blockers.push("llm_unavailable");
      return blockers;
    }
  }
}
function fallbackMode(input) {
  return input.connectedWorkAvailable ? "connected_work_shallow" : "convex_local";
}
function fallbackReason(selectedMode) {
  return selectedMode === "connected_work_shallow" ? "fallback_connected_work" : "fallback_convex_local";
}
function chooseGraphExecutionMode(input = {}) {
  const normalized = normalizeInput(input);
  const recommendation = recommendGraphExecutionMode(normalized);
  const recommendedMode = recommendation.mode;
  const blockers = blockersForMode(recommendedMode, normalized);
  const fallbackUsed = blockers.length > 0;
  const selectedMode = fallbackUsed ? fallbackMode(normalized) : recommendedMode;
  const selectedRequirements = MODE_REQUIREMENTS[selectedMode];
  const recommendedRequirements = MODE_REQUIREMENTS[recommendedMode];
  return {
    version: GRAPH_EXECUTION_MODE_ROUTER_VERSION,
    reportOnly: true,
    recommendedMode,
    selectedMode,
    reasons: fallbackUsed ? [recommendation.reason, fallbackReason(selectedMode)] : [recommendation.reason],
    blockers,
    fallbackUsed,
    requiresNetwork: selectedRequirements.requiresNetwork,
    requiresProvider: selectedRequirements.requiresProvider,
    recommendedRequiresNetwork: recommendedRequirements.requiresNetwork,
    recommendedRequiresProvider: recommendedRequirements.requiresProvider,
    lift: {
      recommended: MODE_LIFT[recommendedMode],
      selected: MODE_LIFT[selectedMode]
    },
    cost: {
      recommended: MODE_COST[recommendedMode],
      selected: MODE_COST[selectedMode]
    }
  };
}
var DEFAULT_SCENARIOS = [
  {
    scenarioId: "baseline",
    label: "Baseline conservative local graph",
    policy: "Report-only no-live baseline; production default remains convex_local.",
    input: {}
  },
  {
    scenarioId: "connected_work_enrichment",
    label: "Connected work shallow enrichment",
    policy: "Allow local connected-work enrichment when the graph is shallow and connected work is available.",
    input: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true
    }
  },
  {
    scenarioId: "memgraph_auto_escalation_depth3",
    label: "Memgraph depth 3 auto-escalation",
    policy: "Recommend Memgraph depth 3 for medium graph complexity, but keep conservative no-live fallback by default.",
    input: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true
    }
  },
  {
    scenarioId: "memgraph_deep_depth5",
    label: "Memgraph depth 5 deep graph expansion",
    policy: "Recommend Memgraph depth 5 for high graph complexity, but keep conservative no-live fallback by default.",
    input: {
      intentConfidence: "strong",
      graphComplexity: "high",
      connectedWorkAvailable: true
    }
  },
  {
    scenarioId: "lite_llm_synthesis",
    label: "Lite LLM synthesis",
    policy: "Recommend depth 5 plus lite LLM for ambiguous synthesis, but keep conservative no-live fallback by default.",
    input: {
      intentConfidence: "ambiguous",
      connectedWorkAvailable: true,
      synthesisRequested: true
    }
  }
];
function buildGraphExecutionModeDefaultDecisions() {
  return {
    version: GRAPH_EXECUTION_MODE_ROUTER_VERSION,
    reportOnly: true,
    deterministic: true,
    productionDefaultsChanged: false,
    productionDefaultMode: "convex_local",
    decisions: DEFAULT_SCENARIOS.map((scenario) => ({
      scenarioId: scenario.scenarioId,
      label: scenario.label,
      policy: scenario.policy,
      decision: chooseGraphExecutionMode(scenario.input)
    }))
  };
}
// ../core/src/contextRouting/graphRoutingPolicy.ts
var GRAPH_ROUTING_POLICY_VERSION = 1;
var GRAPH_ROUTING_MAX_NOISE_RATE_V1 = 0.2;
var GRAPH_ROUTING_MIN_SOURCE_GROUNDING_RATE_V1 = 0.95;
var GRAPH_ROUTING_DEPTH5_MIN_HIGH_COMPLEXITY_SCORE_V1 = 0.7;
var GRAPH_ROUTING_MIN_DEPTH5_LIFT_V1 = 0;
function isFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value);
}
function isValidRate(value) {
  return isFiniteNumber(value) && value >= 0 && value <= 1;
}
function normalizeRate(value) {
  if (!isFiniteNumber(value))
    return null;
  return value >= 0 && value <= 1 ? value : null;
}
function normalizeLift(value) {
  return isFiniteNumber(value) ? value : null;
}
function hasInvalidRateEvidence(value) {
  return value !== null && value !== undefined && !isValidRate(value);
}
function hasInvalidLiftEvidence(value) {
  return value !== null && value !== undefined && !isFiniteNumber(value);
}
function normalizePolicyInput(input) {
  const rawHighComplexityEvidenceScore = input.highComplexityEvidenceScore;
  const rawGraphExpansionNoiseRate = input.graphEvidence?.graphExpansionNoiseRate;
  const rawSourceGroundingRate = input.graphEvidence?.sourceGroundingRate;
  const rawDepth5LiftOverBestDepth3 = input.graphEvidence?.depth5LiftOverBestDepth3;
  const rawDepth5NoiseRate = input.graphEvidence?.depth5NoiseRate;
  return {
    taskKind: input.taskKind,
    changeShape: input.changeShape,
    repoScaleTier: input.repoScaleTier,
    highComplexityEvidenceScore: normalizeRate(rawHighComplexityEvidenceScore),
    graphExpansionNoiseRate: normalizeRate(rawGraphExpansionNoiseRate),
    sourceGroundingRate: normalizeRate(rawSourceGroundingRate),
    depth5LiftOverBestDepth3: normalizeLift(rawDepth5LiftOverBestDepth3),
    depth5NoiseRate: normalizeRate(rawDepth5NoiseRate),
    depth5ThresholdEvidenceAvailable: input.graphEvidence?.depth5ThresholdEvidenceAvailable ?? false,
    invalidGraphEvidence: hasInvalidRateEvidence(rawGraphExpansionNoiseRate) || hasInvalidRateEvidence(rawSourceGroundingRate),
    invalidDepth5Evidence: hasInvalidRateEvidence(rawHighComplexityEvidenceScore) || hasInvalidLiftEvidence(rawDepth5LiftOverBestDepth3) || hasInvalidRateEvidence(rawDepth5NoiseRate),
    connectedWorkAvailable: input.connectedWorkAvailable ?? false,
    memgraphAvailable: input.memgraphAvailable ?? false,
    llmAvailable: input.llmAvailable ?? false,
    noLiveMode: input.noLiveMode ?? true,
    networkAllowed: input.networkAllowed ?? false,
    providerCallsAllowed: input.providerCallsAllowed ?? false
  };
}
function orderedUniqueBlockers(blockers) {
  return Array.from(new Set(blockers));
}
function graphNoiseOverThreshold(input) {
  if (input.invalidGraphEvidence)
    return true;
  if (input.graphExpansionNoiseRate !== null && input.graphExpansionNoiseRate > GRAPH_ROUTING_MAX_NOISE_RATE_V1)
    return true;
  if (input.sourceGroundingRate !== null && input.sourceGroundingRate < GRAPH_ROUTING_MIN_SOURCE_GROUNDING_RATE_V1)
    return true;
  return false;
}
function depth5PolicyBlockers(input) {
  const blockers = [];
  if (input.repoScaleTier !== "large_1500_3000")
    blockers.push("depth5_requires_large_repo");
  if (input.highComplexityEvidenceScore === null || input.highComplexityEvidenceScore < GRAPH_ROUTING_DEPTH5_MIN_HIGH_COMPLEXITY_SCORE_V1) {
    blockers.push("depth5_requires_high_complexity_evidence");
  }
  if (input.depth5ThresholdEvidenceAvailable !== true || input.depth5LiftOverBestDepth3 === null || input.depth5NoiseRate === null || input.invalidDepth5Evidence) {
    blockers.push("depth5_threshold_evidence_insufficient");
  } else {
    if (input.depth5LiftOverBestDepth3 <= GRAPH_ROUTING_MIN_DEPTH5_LIFT_V1)
      blockers.push("depth5_requires_positive_lift");
    if (input.depth5NoiseRate > GRAPH_ROUTING_MAX_NOISE_RATE_V1)
      blockers.push("depth5_noise_over_threshold");
  }
  return blockers;
}
function depth5EligibilityReason(blockers) {
  if (blockers.length === 0)
    return "eligible_large_high_complexity_positive_lift_noise_ok";
  if (blockers.includes("depth5_requires_large_repo"))
    return "blocked_missing_large_repo";
  if (blockers.includes("depth5_requires_high_complexity_evidence"))
    return "blocked_missing_high_complexity";
  if (blockers.includes("depth5_threshold_evidence_insufficient"))
    return "blocked_threshold_evidence_insufficient";
  if (blockers.includes("depth5_requires_positive_lift"))
    return "blocked_missing_positive_lift";
  if (blockers.includes("depth5_noise_over_threshold"))
    return "blocked_noise_over_threshold";
  return "not_requested";
}
function baseGraphInputForTask(input, depth5Eligible, noisyGraphEvidence) {
  const commonSafetyInput = {
    connectedWorkAvailable: input.connectedWorkAvailable,
    memgraphAvailable: input.memgraphAvailable,
    llmAvailable: input.llmAvailable,
    noLiveMode: input.noLiveMode,
    networkAllowed: input.networkAllowed,
    providerCallsAllowed: input.providerCallsAllowed
  };
  if (noisyGraphEvidence) {
    return {
      ...commonSafetyInput,
      intentConfidence: "strong",
      graphComplexity: "shallow"
    };
  }
  switch (input.taskKind) {
    case "local_symbol_lookup":
      return {
        ...commonSafetyInput,
        intentConfidence: "strong",
        graphComplexity: "simple",
        localGraphConfidence: 0.9
      };
    case "docs_code_alignment":
      return {
        ...commonSafetyInput,
        intentConfidence: "strong",
        graphComplexity: "shallow"
      };
    case "deep_synthesis":
      return {
        ...commonSafetyInput,
        intentConfidence: "ambiguous",
        graphScaleTier: input.repoScaleTier,
        highComplexityEvidenceScore: input.highComplexityEvidenceScore,
        synthesisRequested: true
      };
    case "execution_safety_impact":
      return {
        ...commonSafetyInput,
        intentConfidence: "strong",
        graphComplexity: depth5Eligible ? "high" : "medium",
        graphScaleTier: depth5Eligible ? "large_1500_3000" : input.repoScaleTier,
        highComplexityEvidenceScore: input.highComplexityEvidenceScore
      };
    case "weak_search_recovery":
    case "changed_file_impact":
    case "shared_abstraction_review":
    case "provider_integration_impact":
    case "agent_handoff_planning":
      return {
        ...commonSafetyInput,
        intentConfidence: "strong",
        graphComplexity: "medium",
        graphScaleTier: input.repoScaleTier,
        highComplexityEvidenceScore: input.highComplexityEvidenceScore
      };
  }
}
function chooseGraphRoutingPolicyV1(input) {
  const normalized = normalizePolicyInput(input);
  const noisyGraphEvidence = graphNoiseOverThreshold(normalized);
  const depth5Requested = normalized.taskKind === "execution_safety_impact" || normalized.taskKind === "deep_synthesis";
  const depth5Blockers = orderedUniqueBlockers([
    ...depth5Requested ? depth5PolicyBlockers(normalized) : [],
    ...depth5Requested && noisyGraphEvidence ? ["depth5_noise_over_threshold"] : []
  ]);
  const depth5Eligible = depth5Requested && !noisyGraphEvidence && depth5Blockers.length === 0;
  const graphInput = baseGraphInputForTask(normalized, depth5Eligible, noisyGraphEvidence);
  const decision = chooseGraphExecutionMode(graphInput);
  const policyBlockers = orderedUniqueBlockers([
    ...noisyGraphEvidence ? ["graph_noise_over_threshold"] : [],
    ...depth5Blockers,
    ...decision.blockers
  ]);
  return {
    version: GRAPH_ROUTING_POLICY_VERSION,
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true,
    taskKind: normalized.taskKind,
    changeShape: normalized.changeShape,
    repoScaleTier: normalized.repoScaleTier,
    recommendedMode: decision.recommendedMode,
    selectedMode: decision.selectedMode,
    decision,
    policyBlockers,
    evidenceSummary: {
      graphExpansionNoiseRate: normalized.graphExpansionNoiseRate,
      sourceGroundingRate: normalized.sourceGroundingRate,
      highComplexityEvidenceScore: normalized.highComplexityEvidenceScore,
      depth5LiftOverBestDepth3: normalized.depth5LiftOverBestDepth3,
      depth5NoiseRate: normalized.depth5NoiseRate,
      depth5ThresholdEvidenceAvailable: normalized.depth5ThresholdEvidenceAvailable
    },
    depthPolicy: {
      depth3Allowed: true,
      depth5Eligible,
      depth5Default: false,
      depth5EligibilityReason: depth5Requested ? depth5EligibilityReason(depth5Blockers) : "not_requested"
    },
    productionSafe: {
      noLiveMode: normalized.noLiveMode,
      networkAllowed: normalized.networkAllowed,
      providerCallsAllowed: normalized.providerCallsAllowed,
      requiresNetwork: decision.recommendedRequiresNetwork,
      requiresProvider: decision.recommendedRequiresProvider,
      selectedRequiresNetwork: decision.requiresNetwork,
      selectedRequiresProvider: decision.requiresProvider
    }
  };
}
// ../core/src/contextRouting/plannerHandoffGraphAdvisory.ts
var PLANNER_HANDOFF_GRAPH_ADVISORY_SCHEMA_VERSION = 1;
var PLANNER_HANDOFF_GRAPH_ADVISORY_KIND = "planner_handoff_graph_advisory";
var PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY = "Graph routing advisory explains context selection. It does not authorize graph mutation, provider synthesis, Memgraph execution, code writes, or Truth Gate promotion.";
var DEFAULT_SUMMARY = "Graph routing advisory is metadata-only and grants no execution authority.";
var DEFAULT_REASON_CODES = ["planner_graph_advisory:metadata_only", "planner_graph_advisory:no_authority"];
var VALID_SOURCES = new Set([
  "local_code_context",
  "code_market",
  "mcp_input",
  "task_brief",
  "workroom_context_receipt",
  "connected_work_packet",
  "plan_contract",
  "external"
]);
var VALID_BASES = new Set([
  "graph_routing_policy_v1",
  "explicit_metadata",
  "default_no_live"
]);
var VALID_EVIDENCE_QUALITY = new Set(["none", "weak", "usable", "strong"]);
var VALID_GRAPH_NOISE_RISK = new Set(["unknown", "low", "medium", "high"]);
var VALID_MODES = new Set(GRAPH_EXECUTION_MODES);
var MAX_STRING_ITEMS = 24;
var MAX_METADATA_KEYS = 24;
var MAX_METADATA_STRING_LENGTH = 500;
function buildPlannerHandoffGraphAdvisoryV1(args = {}) {
  const recommendedMode = cleanMode(args.recommendedGraphMode ?? args.recommendedMode) ?? "convex_local";
  const selectedMode = cleanMode(args.selectedGraphMode ?? args.selectedMode) ?? "convex_local";
  const policyBlockers = cleanStringArray(args.policyBlockers).slice(0, MAX_STRING_ITEMS);
  const recommendedRequirements = requirementsForMode(recommendedMode);
  const selectedRequirements = requirementsForMode(selectedMode);
  const sourceRefs = cleanOptionalStringArray(args.sourceRefs);
  const evidenceRefs = cleanOptionalStringArray(args.evidenceRefs);
  const receiptRefs = cleanOptionalStringArray(args.receiptRefs);
  const reasonCodes = cleanStringArray(args.reasonCodes).slice(0, MAX_STRING_ITEMS);
  return {
    schemaVersion: PLANNER_HANDOFF_GRAPH_ADVISORY_SCHEMA_VERSION,
    kind: PLANNER_HANDOFF_GRAPH_ADVISORY_KIND,
    generatedAt: finiteNumber(args.generatedAt) ?? Date.now(),
    source: args.source ?? "external",
    basis: args.basis ?? "explicit_metadata",
    summary: cleanString(args.summary) ?? DEFAULT_SUMMARY,
    taskKind: cleanString(args.taskKind),
    repoScaleTier: cleanString(args.repoScaleTier),
    selectedGraphMode: selectedMode,
    recommendedGraphMode: recommendedMode,
    selectedMode,
    recommendedMode,
    evidenceQuality: args.evidenceQuality ?? "none",
    graphNoiseRisk: args.graphNoiseRisk ?? "unknown",
    policyBlockers,
    depthPolicy: {
      depth3Allowed: args.depthPolicy?.depth3Allowed ?? true,
      depth5Eligible: args.depthPolicy?.depth5Eligible ?? false,
      depth5Default: false,
      depth5Allowed: false,
      depth5EligibilityReason: cleanString(args.depthPolicy?.depth5EligibilityReason)
    },
    executionPolicy: safeExecutionPolicy(),
    productionSafe: {
      productionDefaultMode: "convex_local",
      recommendedRequiresNetwork: booleanOrDefault(args.productionSafe?.recommendedRequiresNetwork, recommendedRequirements.requiresNetwork),
      recommendedRequiresProvider: booleanOrDefault(args.productionSafe?.recommendedRequiresProvider, recommendedRequirements.requiresProvider),
      selectedRequiresNetwork: booleanOrDefault(args.productionSafe?.selectedRequiresNetwork, selectedRequirements.requiresNetwork),
      selectedRequiresProvider: booleanOrDefault(args.productionSafe?.selectedRequiresProvider, selectedRequirements.requiresProvider)
    },
    reasonCodes: reasonCodes.length > 0 ? reasonCodes : DEFAULT_REASON_CODES,
    sourceRefs,
    evidenceRefs,
    receiptRefs,
    verificationCommand: cleanString(args.verificationCommand),
    metadata: sanitizeMetadata(args.metadata),
    memgraphAllowed: false,
    depth5Allowed: false,
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function plannerHandoffGraphAdvisoryFromPolicyDecision(args) {
  const decision = args.decision;
  return buildPlannerHandoffGraphAdvisoryV1({
    source: args.source ?? "local_code_context",
    basis: "graph_routing_policy_v1",
    generatedAt: args.generatedAt,
    summary: args.summary ?? `Graph routing policy recommends ${decision.recommendedMode} and selected ${decision.selectedMode}; advisory only.`,
    taskKind: decision.taskKind,
    repoScaleTier: decision.repoScaleTier,
    recommendedGraphMode: decision.recommendedMode,
    selectedGraphMode: decision.selectedMode,
    evidenceQuality: evidenceQualityFromPolicyDecision(decision),
    graphNoiseRisk: graphNoiseRiskFromPolicyDecision(decision),
    policyBlockers: decision.policyBlockers,
    depthPolicy: {
      depth3Allowed: decision.depthPolicy.depth3Allowed,
      depth5Eligible: decision.depthPolicy.depth5Eligible,
      depth5EligibilityReason: decision.depthPolicy.depth5EligibilityReason
    },
    productionSafe: {
      recommendedRequiresNetwork: decision.productionSafe.requiresNetwork,
      recommendedRequiresProvider: decision.productionSafe.requiresProvider,
      selectedRequiresNetwork: decision.productionSafe.selectedRequiresNetwork,
      selectedRequiresProvider: decision.productionSafe.selectedRequiresProvider
    },
    reasonCodes: ["graph_routing_policy_v1", ...decision.decision.reasons.map((reason) => `graph_routing:${reason}`)],
    sourceRefs: args.sourceRefs,
    evidenceRefs: args.evidenceRefs,
    receiptRefs: args.receiptRefs,
    verificationCommand: args.verificationCommand,
    metadata: args.metadata
  });
}
function normalizePlannerHandoffGraphAdvisoryV1(value, fallback = {}) {
  if (!isRecord(value))
    return;
  const source = readSource(value["source"], fallback.source ?? "external");
  const basis = readBasis(value["basis"], fallback.basis ?? "explicit_metadata");
  const executionPolicy = isRecord(value["executionPolicy"]) ? value["executionPolicy"] : undefined;
  const depthPolicy = isRecord(value["depthPolicy"]) ? value["depthPolicy"] : undefined;
  const productionSafe = isRecord(value["productionSafe"]) ? value["productionSafe"] : undefined;
  return buildPlannerHandoffGraphAdvisoryV1({
    source,
    basis,
    generatedAt: finiteNumber(value["generatedAt"]) ?? fallback.generatedAt,
    summary: cleanString(value["summary"]) ?? fallback.summary,
    taskKind: cleanString(value["taskKind"]),
    repoScaleTier: cleanString(value["repoScaleTier"]),
    recommendedGraphMode: cleanMode(value["recommendedGraphMode"] ?? value["recommendedMode"]),
    selectedGraphMode: cleanMode(value["selectedGraphMode"] ?? value["selectedMode"]),
    evidenceQuality: readEvidenceQuality(value["evidenceQuality"]),
    graphNoiseRisk: readGraphNoiseRisk(value["graphNoiseRisk"]),
    policyBlockers: cleanStringArray(value["policyBlockers"]),
    depthPolicy: {
      depth3Allowed: booleanOrDefault(depthPolicy?.["depth3Allowed"], true),
      depth5Eligible: booleanOrDefault(depthPolicy?.["depth5Eligible"], false),
      depth5EligibilityReason: cleanString(depthPolicy?.["depth5EligibilityReason"])
    },
    productionSafe: {
      recommendedRequiresNetwork: Boolean(productionSafe?.["recommendedRequiresNetwork"]),
      recommendedRequiresProvider: Boolean(productionSafe?.["recommendedRequiresProvider"]),
      selectedRequiresNetwork: Boolean(productionSafe?.["selectedRequiresNetwork"]),
      selectedRequiresProvider: Boolean(productionSafe?.["selectedRequiresProvider"])
    },
    reasonCodes: uniqueStrings([
      ...cleanStringArray(value["reasonCodes"]),
      executionPolicy?.["memgraphAllowed"] === true || value["memgraphAllowed"] === true ? "planner_graph_advisory:unsafe_input_sanitized" : undefined,
      executionPolicy?.["providerCallsAllowed"] === true ? "planner_graph_advisory:provider_input_sanitized" : undefined,
      executionPolicy?.["synapsePredictionInputAllowed"] === true ? "planner_graph_advisory:synapse_input_sanitized" : undefined,
      depthPolicy?.["depth5Default"] === true || depthPolicy?.["depth5Allowed"] === true || value["depth5Allowed"] === true ? "planner_graph_advisory:depth5_input_sanitized" : undefined
    ]),
    sourceRefs: cleanOptionalStringArray(value["sourceRefs"]),
    evidenceRefs: cleanOptionalStringArray(value["evidenceRefs"]),
    receiptRefs: cleanOptionalStringArray(value["receiptRefs"]),
    verificationCommand: cleanString(value["verificationCommand"]),
    metadata: sanitizeMetadata(isRecord(value["metadata"]) ? value["metadata"] : undefined)
  });
}
function safeExecutionPolicy() {
  return {
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true,
    noAutomaticExecution: true,
    memgraphAllowed: false,
    providerCallsAllowed: false,
    synapsePredictionInputAllowed: false,
    graphMutationAllowed: false,
    codeWritesAllowed: false,
    truthGatePromotionAllowed: false,
    productionWritesAllowed: false,
    routePersistenceAllowed: false,
    uiSurfacingAllowed: false,
    productionDefaultsChanged: false
  };
}
function requirementsForMode(mode) {
  if (VALID_MODES.has(mode)) {
    const metadata = graphExecutionModePolicyMetadataFor(mode);
    return { requiresNetwork: metadata.requiresNetwork, requiresProvider: metadata.requiresProvider };
  }
  return {
    requiresNetwork: mode.includes("memgraph") || mode.includes("network"),
    requiresProvider: mode.includes("provider") || mode.includes("llm")
  };
}
function evidenceQualityFromPolicyDecision(decision) {
  const sourceGrounding = decision.evidenceSummary.sourceGroundingRate;
  const noise = decision.evidenceSummary.graphExpansionNoiseRate;
  if (sourceGrounding === null && noise === null && decision.policyBlockers.length === 0)
    return "none";
  if (sourceGrounding !== null && sourceGrounding >= 0.98 && noise !== null && noise <= 0.1)
    return "strong";
  if (sourceGrounding !== null && sourceGrounding >= 0.95 && (noise === null || noise <= 0.2))
    return "usable";
  return "weak";
}
function graphNoiseRiskFromPolicyDecision(decision) {
  const noise = decision.evidenceSummary.graphExpansionNoiseRate;
  if (noise === null)
    return decision.policyBlockers.includes("graph_noise_over_threshold") ? "high" : "unknown";
  if (noise <= 0.1)
    return "low";
  if (noise <= 0.2)
    return "medium";
  return "high";
}
function readSource(value, fallback) {
  return typeof value === "string" && VALID_SOURCES.has(value) ? value : fallback;
}
function readBasis(value, fallback) {
  return typeof value === "string" && VALID_BASES.has(value) ? value : fallback;
}
function readEvidenceQuality(value) {
  return typeof value === "string" && VALID_EVIDENCE_QUALITY.has(value) ? value : undefined;
}
function readGraphNoiseRisk(value) {
  return typeof value === "string" && VALID_GRAPH_NOISE_RISK.has(value) ? value : undefined;
}
function cleanMode(value) {
  const text = cleanString(value);
  if (!text)
    return;
  return VALID_MODES.has(text) ? text : text;
}
function cleanOptionalStringArray(value) {
  const output = cleanStringArray(value).slice(0, MAX_STRING_ITEMS);
  return output.length > 0 ? output : undefined;
}
function cleanStringArray(value) {
  if (!Array.isArray(value))
    return [];
  return uniqueStrings(value.map(cleanString)).slice(0, MAX_STRING_ITEMS);
}
function uniqueStrings(values) {
  const seen = new Set;
  const output = [];
  for (const value of values) {
    if (!value || seen.has(value))
      continue;
    seen.add(value);
    output.push(value);
  }
  return output;
}
function sanitizeMetadata(value) {
  if (!value)
    return;
  const output = {};
  for (const [key, raw] of Object.entries(value).slice(0, MAX_METADATA_KEYS)) {
    const cleanKey = cleanString(key);
    if (!cleanKey)
      continue;
    const cleanValue = sanitizeMetadataValue(raw);
    if (cleanValue !== undefined)
      output[cleanKey] = cleanValue;
  }
  return Object.keys(output).length > 0 ? output : undefined;
}
function sanitizeMetadataValue(value) {
  if (typeof value === "string")
    return value.slice(0, MAX_METADATA_STRING_LENGTH);
  if (typeof value === "number")
    return Number.isFinite(value) ? value : undefined;
  if (typeof value === "boolean" || value === null)
    return value;
  if (Array.isArray(value))
    return value.map(sanitizeMetadataValue).filter((item) => item !== undefined).slice(0, MAX_STRING_ITEMS);
  if (isRecord(value))
    return sanitizeMetadata(value);
  return;
}
function booleanOrDefault(value, fallback) {
  return typeof value === "boolean" ? value : fallback;
}
function finiteNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function cleanString(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../core/src/contextRouting/surfacePolicies.ts
var CHANGE_SHAPES_V1 = [
  "shared_abstraction",
  "ui_behavior",
  "ui_reuse_or_design_system",
  "execution_safety",
  "provider_integration",
  "agent_handoff",
  "docs_or_migration"
];
var CONNECTED_SURFACE_KINDS_V1 = [
  "primary_code",
  "targeted_tests",
  "user_docs",
  "config_policy",
  "package_exports",
  "runtime_enforcement",
  "schema_persistence",
  "ui_surface",
  "design_system_or_shared_component",
  "usage_sites",
  "visual_snapshot_or_story",
  "native_counterpart",
  "receipt_audit",
  "eval_report",
  "migration_notes",
  "provider_gateway",
  "agent_handoff"
];
var COMMON_CODE_EVIDENCE = [
  "primary_edit_file",
  "context_slice",
  "source_ref",
  "evidence_ref"
];
var COMMON_SUPPORT_EVIDENCE = [
  "context_slice",
  "affected_test",
  "affected_doc",
  "config_file",
  "source_ref",
  "evidence_ref",
  "receipt_ref"
];
function required(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
  return { surfaceKind, level: "required", minEvidenceCount, evidenceTypes, rationale };
}
function optional(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
  return { surfaceKind, level: "optional", minEvidenceCount, evidenceTypes, rationale };
}
var CONNECTED_SURFACE_POLICIES_V1 = {
  shared_abstraction: {
    version: 1,
    changeShape: "shared_abstraction",
    label: "Shared abstraction",
    description: "Reusable code contracts need implementation, public contract/docs, and regression tests in the same bounded packet.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Shared behavior changes need targeted regression tests."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Public behavior should stay aligned with user-facing docs."),
      optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Export/type surfaces often carry shared abstraction contracts."),
      optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Runtime guards and helpers can constrain shared behavior."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing receipts or reports help confirm prior behavior.")
    ]
  },
  ui_behavior: {
    version: 1,
    changeShape: "ui_behavior",
    label: "UI behavior",
    description: "UI behavior packets need render code and visible surface context, with tests/docs when available.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary render/state code must be represented."),
      required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
      optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "UI regression tests are useful when present."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Trail/receipt display surfaces should remain auditable."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-visible behavior may need docs or copy updates.")
    ]
  },
  ui_reuse_or_design_system: {
    version: 1,
    changeShape: "ui_reuse_or_design_system",
    label: "UI reuse or design system",
    description: "Reusable UI/design-system opportunities need shared component context, usage sites, package exports, and visible UI surfaces in the same bounded packet.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
      required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
      required("design_system_or_shared_component", 1, COMMON_SUPPORT_EVIDENCE, "The shared UI primitive or design-system component must be represented."),
      required("usage_sites", 1, COMMON_SUPPORT_EVIDENCE, "Representative call sites must show how the reusable behavior is consumed."),
      required("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Package export surfaces must expose or bound the reusable UI contract."),
      optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Reusable UI behavior should have targeted regression tests when available."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Shared UI behavior may need docs or usage guidance."),
      optional("visual_snapshot_or_story", 1, COMMON_SUPPORT_EVIDENCE, "Visual snapshots or stories help validate reusable UI behavior."),
      optional("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes can bound adoption across usage sites."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing reports or receipts help confirm prior UI behavior.")
    ]
  },
  execution_safety: {
    version: 1,
    changeShape: "execution_safety",
    label: "Execution safety",
    description: "Safety-sensitive changes need implementation, enforcement, tests, and audit/receipt surfaces.",
    recommendedEscalation: "memgraph_depth5",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "high",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Safety behavior must include the primary implementation."),
      required("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Policy/enforcement code must be represented."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Safety changes require targeted regression tests."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Environment/config policy can change safety behavior."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipt and audit surfaces support post-run proof."),
      optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Operator docs should reflect safety policy."),
      optional("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "User-facing callbacks or flows can be affected by safety policy.")
    ]
  },
  provider_integration: {
    version: 1,
    changeShape: "provider_integration",
    label: "Provider integration",
    description: "Provider-routing changes need gateway/provider code, call-path code, docs, and targeted tests.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Provider integration must include primary call-path code."),
      required("provider_gateway", 1, COMMON_SUPPORT_EVIDENCE, "Gateway/provider routing surfaces must be present."),
      required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Provider fallback behavior needs targeted tests."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Provider integration contracts are user-facing."),
      optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Exported provider contracts should be checked."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Provider options/config can control routing."),
      optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Retry/error wrappers enforce provider behavior.")
    ]
  },
  agent_handoff: {
    version: 1,
    changeShape: "agent_handoff",
    label: "Agent handoff",
    description: "Agent handoff work needs handoff contracts, docs/work packets, and preferably tests/eval reports.",
    recommendedEscalation: "memgraph_depth3",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "medium",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("agent_handoff", 1, COMMON_SUPPORT_EVIDENCE, "The handoff contract or work packet must be represented."),
      required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary handoff implementation/contract code must be present."),
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Agent-facing docs or markdown guidance must be present."),
      optional("eval_report", 1, COMMON_SUPPORT_EVIDENCE, "Eval reports help validate handoff usefulness."),
      optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipts can prove agent handoff lineage."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Handoff contracts should have targeted tests when available.")
    ]
  },
  docs_or_migration: {
    version: 1,
    changeShape: "docs_or_migration",
    label: "Docs or migration",
    description: "Documentation/migration work needs user docs and migration notes, with code/tests when applicable.",
    recommendedEscalation: "connected_work_shallow",
    graphInput: {
      intentConfidence: "strong",
      graphComplexity: "shallow",
      connectedWorkAvailable: true,
      noLiveMode: true,
      networkAllowed: false,
      providerCallsAllowed: false
    },
    rules: [
      required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-facing docs must be represented."),
      required("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes or planning docs must be represented."),
      optional("primary_code", 1, COMMON_CODE_EVIDENCE, "Related implementation code can anchor docs changes."),
      optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Tests can validate migration guidance."),
      optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Migration/config policy may be relevant.")
    ]
  }
};
function connectedSurfacePolicyForChangeShape(changeShape) {
  return CONNECTED_SURFACE_POLICIES_V1[changeShape];
}
// ../core/src/contextRouting/semanticSelectionSignals.ts
var SEMANTIC_SELECTION_SIGNAL_PREFIX_V1 = "semantic_label:v1";
var DEFAULT_MAX_SEMANTIC_SELECTION_SIGNALS = 48;
var CONNECTED_SURFACE_KIND_SET = new Set(CONNECTED_SURFACE_KINDS_V1);
var TEXT_SURFACE_PATTERNS = [
  { surfaceKind: "targeted_tests", patterns: [/\b(test|tests|qa|regression|assertion|fixture)\b/i] },
  { surfaceKind: "user_docs", patterns: [/\b(doc|docs|documentation|readme|guide|operator)\b/i] },
  { surfaceKind: "config_policy", patterns: [/\b(config|configuration|policy|env|environment|allowlist|setting|option)\b/i] },
  { surfaceKind: "package_exports", patterns: [/\b(export|exports|public api|barrel|contract|type contract|package)\b/i] },
  { surfaceKind: "runtime_enforcement", patterns: [/\b(runtime|guard|validation|enforce|safety|auth|redirect|retry|timeout|error|risk)\b/i] },
  { surfaceKind: "schema_persistence", patterns: [/\b(schema|persistence|database|db|migration|data integrity|storage)\b/i] },
  { surfaceKind: "ui_surface", patterns: [/\b(ui|render|component|screen|panel|message|style|design system|visible)\b/i] },
  { surfaceKind: "native_counterpart", patterns: [/\b(native|ios|android|expo|react native|mobile)\b/i] },
  { surfaceKind: "receipt_audit", patterns: [/\b(receipt|audit|trail|observability|provenance|report)\b/i] },
  { surfaceKind: "eval_report", patterns: [/\b(eval|evaluation|benchmark|report|fixture|coverage)\b/i] },
  { surfaceKind: "migration_notes", patterns: [/\b(migration|migrate|upgrade|release note|planning)\b/i] },
  { surfaceKind: "provider_gateway", patterns: [/\b(provider|gateway|model|routing|registry|fallback|llm)\b/i] },
  { surfaceKind: "agent_handoff", patterns: [/\b(agent|handoff|brief|work packet|workroom|context plan)\b/i] }
];
var CRITICAL_SURFACE_MAP = {
  auth: ["runtime_enforcement", "config_policy"],
  billing: ["runtime_enforcement", "config_policy"],
  onboarding: ["ui_surface", "user_docs"],
  search: ["primary_code"],
  recommendations: ["primary_code"],
  ai_context: ["agent_handoff", "primary_code"],
  evals: ["eval_report", "targeted_tests"],
  deployment: ["config_policy", "user_docs"],
  data_integrity: ["schema_persistence", "runtime_enforcement"],
  privacy: ["runtime_enforcement", "config_policy"],
  observability: ["receipt_audit"],
  design_system: ["ui_surface", "native_counterpart"],
  agent_runtime: ["agent_handoff", "runtime_enforcement"],
  docs_drift: ["user_docs", "migration_notes"],
  code_graph: ["primary_code"]
};
function semanticSelectionSignalMappingsFromReadyLabels(labels, options = {}) {
  const includeLabelSignals = options.includeLabelSignals ?? true;
  return labels.filter((label) => label.status === "ready").slice().sort(compareSemanticLabelsForSignals).map((label) => {
    const connectedSurfaceKinds = connectedSurfaceKindsForLabel(label);
    const signals = uniqueStrings2([
      ...includeLabelSignals ? [labelSignal(label)] : [],
      ...connectedSurfaceKinds.map((surfaceKind) => connectedSurfaceSignal(label, surfaceKind))
    ]);
    return {
      labelIdentity: label.labelIdentity,
      nodeId: label.nodeId,
      nodeKey: label.nodeKey,
      filePath: label.filePath,
      source: label.source,
      architectureAuthority: label.architectureAuthority,
      namespace: label.namespace,
      key: label.key,
      normalizedValue: label.normalizedValue,
      connectedSurfaceKinds,
      signals,
      reportOnly: true
    };
  });
}
function semanticSelectionSignalsFromReadyLabels(labels, options = {}) {
  const maxSignals = options.maxSignals ?? DEFAULT_MAX_SEMANTIC_SELECTION_SIGNALS;
  return uniqueStrings2(semanticSelectionSignalMappingsFromReadyLabels(labels, options).flatMap((mapping) => mapping.signals)).slice(0, maxSignals);
}
function semanticSelectionSignalsByFilePath(labels, options = {}) {
  const byPath = new Map;
  for (const label of labels) {
    const path = label.filePath.trim();
    if (!path)
      continue;
    byPath.set(path, [...byPath.get(path) ?? [], label]);
  }
  return Object.fromEntries(Array.from(byPath.entries()).sort(([left], [right]) => left.localeCompare(right)).map(([path, pathLabels]) => [path, semanticSelectionSignalsFromReadyLabels(pathLabels, options)]));
}
function connectedSurfaceKindsForSemanticLabel(label) {
  return connectedSurfaceKindsForLabel(label);
}
function connectedSurfaceKindsForLabel(label) {
  if (label.status !== "ready")
    return [];
  const normalizedValue = normalizeSignalPart(label.normalizedValue || label.value);
  const directSurface = surfaceKindFromValue(normalizedValue);
  const kinds = [];
  if (directSurface)
    kinds.push(directSurface);
  if (label.namespace === "connected_surface") {
    const fromValue = surfaceKindFromValue(label.normalizedValue) ?? surfaceKindFromValue(label.value);
    if (fromValue)
      kinds.push(fromValue);
  }
  if (label.namespace === "parser") {
    if (label.key === "node_type" || label.key === "language" || label.key === "import" || label.key === "call") {
      kinds.push("primary_code");
    }
    if (label.key === "is_exported" && normalizedValue === "true")
      kinds.push("package_exports");
    if (["has_parse_warnings", "has_parse_error", "has_fallback"].includes(label.key) && normalizedValue === "true") {
      kinds.push("runtime_enforcement");
    }
  }
  if (label.namespace === "critical_surface") {
    kinds.push(...CRITICAL_SURFACE_MAP[normalizedValue] ?? []);
  }
  if (label.namespace === "code_role" || label.namespace === "architecture_layer") {
    kinds.push(...surfaceKindsFromText(`${label.key} ${label.value}`));
  }
  if (["focus_lens", "audience", "intent", "tag", "feature_label", "risk"].includes(label.namespace)) {
    kinds.push(...surfaceKindsFromText(`${label.namespace} ${label.key} ${label.value}`));
  }
  return uniqueSurfaceKinds(kinds);
}
function surfaceKindFromValue(value) {
  const normalized = normalizeSignalPart(value);
  if (CONNECTED_SURFACE_KIND_SET.has(normalized))
    return normalized;
  return;
}
function surfaceKindsFromText(text) {
  const kinds = [];
  for (const item of TEXT_SURFACE_PATTERNS) {
    if (item.patterns.some((pattern) => pattern.test(text)))
      kinds.push(item.surfaceKind);
  }
  return uniqueSurfaceKinds(kinds);
}
function labelSignal(label) {
  return [
    SEMANTIC_SELECTION_SIGNAL_PREFIX_V1,
    label.source,
    label.architectureAuthority,
    "label",
    signalToken(label.namespace),
    signalToken(label.key),
    signalToken(label.normalizedValue || label.value)
  ].join(":");
}
function connectedSurfaceSignal(label, surfaceKind) {
  return [
    SEMANTIC_SELECTION_SIGNAL_PREFIX_V1,
    label.source,
    label.architectureAuthority,
    "connected_surface",
    surfaceKind
  ].join(":");
}
function compareSemanticLabelsForSignals(left, right) {
  return left.filePath.localeCompare(right.filePath) || (left.startLine ?? 0) - (right.startLine ?? 0) || left.namespace.localeCompare(right.namespace) || left.key.localeCompare(right.key) || left.normalizedValue.localeCompare(right.normalizedValue) || left.source.localeCompare(right.source) || left.architectureAuthority.localeCompare(right.architectureAuthority) || left.labelIdentity.localeCompare(right.labelIdentity);
}
function signalToken(value) {
  return normalizeSignalPart(value).replace(/[^a-z0-9_.-]+/g, "_").replace(/^_+|_+$/g, "") || "unknown";
}
function normalizeSignalPart(value) {
  return value.trim().normalize("NFKC").replace(/\s+/g, "_").toLowerCase();
}
function uniqueSurfaceKinds(values) {
  const seen = new Set;
  const output = [];
  for (const surfaceKind of values) {
    if (seen.has(surfaceKind))
      continue;
    seen.add(surfaceKind);
    output.push(surfaceKind);
  }
  return output;
}
function uniqueStrings2(values) {
  const seen = new Set;
  const output = [];
  for (const value of values) {
    const trimmed = value.trim();
    if (!trimmed || seen.has(trimmed))
      continue;
    seen.add(trimmed);
    output.push(trimmed);
  }
  return output;
}
// ../core/src/contextRouting/semanticGraphRouting.ts
var SEMANTIC_GRAPH_ROUTING_REPORT_VERSION = 1;
var DEFAULT_MAX_TOP_PATHS = 6;
var PUBLIC_SURFACES = new Set(["package_exports", "user_docs"]);
var CRITICAL_SURFACES = new Set([
  "runtime_enforcement",
  "config_policy",
  "schema_persistence",
  "receipt_audit"
]);
var TOKEN_VALUE_NAMESPACES = new Set(["focus_lens", "audience", "intent", "tag", "feature_label", "risk", "context_packet"]);
function buildGraphExecutionModeInputFromSemanticLabels(labels, options = {}) {
  return buildSemanticGraphRoutingReportFromLabels(labels, options).input;
}
function buildSemanticGraphRoutingReportFromLabels(labels, options = {}) {
  const sortedLabels = labels.slice().sort(compareLabels);
  const readyLabels = sortedLabels.filter((label) => label.status === "ready");
  const parserFactLabels = readyLabels.filter(isParserFactLabel);
  const advisoryLabels = readyLabels.filter((label) => !isParserFactLabel(label));
  const fanout = buildFanout(readyLabels);
  const surfaces = uniqueSurfaces(fanout.flatMap((item) => item.connectedSurfaceKinds));
  const surfaceCounts = countSurfaces(fanout);
  const signals = semanticGraphRoutingSignals({ labels: readyLabels, fanout, surfaces });
  const input = graphInputFromSignals({ readyLabels, parserFactLabels, advisoryLabels, surfaces, signals, fanout, options });
  const changeShape = changeShapeFromSemanticSignals({ signals, surfaces });
  const routingPolicy = chooseGraphRoutingPolicyV1({
    taskKind: graphRoutingTaskKindFromSemanticSignals({ parserFactLabels, signals, surfaces }),
    ...changeShape ? { changeShape } : {},
    connectedWorkAvailable: input.connectedWorkAvailable ?? false,
    memgraphAvailable: input.memgraphAvailable ?? false,
    llmAvailable: input.llmAvailable ?? false,
    noLiveMode: input.noLiveMode ?? true,
    networkAllowed: input.networkAllowed ?? false,
    providerCallsAllowed: input.providerCallsAllowed ?? false
  });
  return {
    version: SEMANTIC_GRAPH_ROUTING_REPORT_VERSION,
    reportOnly: true,
    deterministic: true,
    input,
    routingPolicy,
    evidence: {
      version: SEMANTIC_GRAPH_ROUTING_REPORT_VERSION,
      reportOnly: true,
      deterministic: true,
      parserFactsAuthoritative: true,
      advisoryOnly: true,
      promotedAdvisoryLabelsToTruth: false,
      labelCount: labels.length,
      readyLabelCount: readyLabels.length,
      parserFactLabelCount: parserFactLabels.length,
      advisoryLabelCount: advisoryLabels.length,
      sourceCounts: countSources(sortedLabels),
      namespaceCounts: countNamespaces(sortedLabels),
      surfaceCounts,
      surfaces,
      signals,
      semanticFanout: {
        pathCount: fanout.length,
        maxReadyLabelsPerPath: max(fanout.map((item) => item.labels.length)),
        maxConnectedSurfacesPerPath: max(fanout.map((item) => item.connectedSurfaceKinds.length)),
        topPaths: fanout.slice(0, options.maxTopPaths ?? DEFAULT_MAX_TOP_PATHS).map((item) => ({
          path: item.path,
          readyLabelCount: item.labels.length,
          connectedSurfaceKinds: item.connectedSurfaceKinds
        }))
      },
      recommendationEvidence: recommendationEvidence({ parserFactLabels, advisoryLabels, surfaces, signals })
    }
  };
}
function graphRoutingTaskKindFromSemanticSignals(input) {
  if (input.signals.includes("token_value_surface") && input.parserFactLabels.length === 0)
    return "deep_synthesis";
  if (input.signals.includes("provider_surface") || input.surfaces.includes("provider_gateway"))
    return "provider_integration_impact";
  if (input.signals.includes("critical_surface") || input.signals.includes("receipt_surface") || input.signals.includes("schema_surface") || input.surfaces.includes("runtime_enforcement") || input.surfaces.includes("receipt_audit") || input.surfaces.includes("schema_persistence")) {
    return "execution_safety_impact";
  }
  if (input.surfaces.includes("agent_handoff"))
    return "agent_handoff_planning";
  if (input.signals.includes("public_surface") || input.surfaces.includes("user_docs"))
    return "docs_code_alignment";
  if (input.signals.includes("semantic_fanout") || input.surfaces.length >= 2)
    return "shared_abstraction_review";
  if (input.surfaces.length > 0)
    return "changed_file_impact";
  return "local_symbol_lookup";
}
function changeShapeFromSemanticSignals(input) {
  if (input.signals.includes("provider_surface") || input.surfaces.includes("provider_gateway"))
    return "provider_integration";
  if (input.signals.includes("critical_surface") || input.signals.includes("receipt_surface") || input.signals.includes("schema_surface") || input.surfaces.includes("runtime_enforcement") || input.surfaces.includes("receipt_audit") || input.surfaces.includes("schema_persistence")) {
    return "execution_safety";
  }
  if (input.surfaces.includes("agent_handoff"))
    return "agent_handoff";
  if (input.surfaces.includes("ui_surface"))
    return "ui_behavior";
  if (input.signals.includes("public_surface") || input.surfaces.includes("user_docs"))
    return "docs_or_migration";
  if (input.signals.includes("semantic_fanout") || input.surfaces.length >= 2)
    return "shared_abstraction";
  return;
}
function graphInputFromSignals(input) {
  const hasReadyLabels = input.readyLabels.length > 0;
  const hasParserFacts = input.parserFactLabels.length > 0;
  const hasAdvisoryTokenValue = input.signals.includes("token_value_surface");
  const graphComplexity = graphComplexityFromSignals(input);
  const intentConfidence = hasAdvisoryTokenValue && !hasParserFacts ? "ambiguous" : hasParserFacts ? "strong" : hasReadyLabels ? "weak" : undefined;
  const output = {
    localGraphConfidence: localGraphConfidence(input.parserFactLabels, input.advisoryLabels),
    connectedWorkAvailable: input.options.connectedWorkAvailable ?? (hasReadyLabels && input.surfaces.length > 0),
    memgraphAvailable: input.options.memgraphAvailable ?? false,
    llmAvailable: input.options.llmAvailable ?? false,
    noLiveMode: input.options.noLiveMode ?? true,
    networkAllowed: input.options.networkAllowed ?? false,
    providerCallsAllowed: input.options.providerCallsAllowed ?? false,
    synthesisRequested: hasAdvisoryTokenValue && !hasParserFacts
  };
  if (intentConfidence)
    output.intentConfidence = intentConfidence;
  if (graphComplexity)
    output.graphComplexity = graphComplexity;
  return output;
}
function graphComplexityFromSignals(input) {
  if (input.readyLabels.length === 0)
    return;
  if (input.signals.includes("critical_surface") && (input.signals.includes("receipt_surface") || input.signals.includes("schema_surface"))) {
    return "high";
  }
  if (input.signals.includes("provider_surface") && (input.signals.includes("schema_surface") || input.signals.includes("testability_surface"))) {
    return "high";
  }
  if (input.surfaces.length >= 6 || max(input.fanout.map((item) => item.connectedSurfaceKinds.length)) >= 5)
    return "high";
  if (input.signals.includes("semantic_fanout") || input.surfaces.length >= 3)
    return "medium";
  if (input.signals.includes("connected_surface") || input.signals.includes("public_surface"))
    return "shallow";
  return input.parserFactLabels.length > 0 ? "simple" : undefined;
}
function localGraphConfidence(parserFactLabels, advisoryLabels) {
  if (parserFactLabels.length > 0)
    return 0.9;
  if (advisoryLabels.length > 0)
    return 0.65;
  return null;
}
function semanticGraphRoutingSignals(input) {
  const signals = [];
  const surfaceSet = new Set(input.surfaces);
  if (input.fanout.some((item) => item.labels.length >= 4 || item.connectedSurfaceKinds.length >= 3))
    signals.push("semantic_fanout");
  if (input.surfaces.some((surface) => PUBLIC_SURFACES.has(surface)))
    signals.push("public_surface");
  if (input.surfaces.some((surface) => CRITICAL_SURFACES.has(surface)) || hasRoutingFactNamespace(input.labels, "critical_surface"))
    signals.push("critical_surface");
  if (input.surfaces.length > 0 || hasRoutingFactNamespace(input.labels, "connected_surface"))
    signals.push("connected_surface");
  if (surfaceSet.has("provider_gateway"))
    signals.push("provider_surface");
  if (surfaceSet.has("schema_persistence"))
    signals.push("schema_surface");
  if (surfaceSet.has("receipt_audit"))
    signals.push("receipt_surface");
  if (surfaceSet.has("targeted_tests") || surfaceSet.has("eval_report"))
    signals.push("testability_surface");
  if (input.labels.some((label) => TOKEN_VALUE_NAMESPACES.has(label.namespace)))
    signals.push("token_value_surface");
  return signals;
}
function buildFanout(labels) {
  const byPath = new Map;
  for (const label of labels) {
    const path = label.filePath.trim();
    if (!path)
      continue;
    byPath.set(path, [...byPath.get(path) ?? [], label]);
  }
  return Array.from(byPath.entries()).map(([path, pathLabels]) => ({
    path,
    labels: pathLabels.sort(compareLabels),
    connectedSurfaceKinds: uniqueSurfaces(pathLabels.flatMap(connectedSurfaceKindsForRoutingLabel))
  })).sort((left, right) => right.connectedSurfaceKinds.length - left.connectedSurfaceKinds.length || right.labels.length - left.labels.length || compareStable(left.path, right.path));
}
function connectedSurfaceKindsForRoutingLabel(label) {
  if (label.source === "llm" && label.architectureAuthority === "advisory_only")
    return [];
  return connectedSurfaceKindsForSemanticLabel(label);
}
function recommendationEvidence(input) {
  return [
    `parser_fact_labels:${input.parserFactLabels.length}`,
    `advisory_labels:${input.advisoryLabels.length}`,
    ...input.signals.map((signal) => `signal:${signal}`),
    ...input.surfaces.map((surface) => `surface:${surface}`),
    `selection_signals:${semanticSelectionSignalsFromReadyLabels([...input.parserFactLabels, ...input.advisoryLabels]).length}`
  ];
}
function countSources(labels) {
  return {
    parser: labels.filter((label) => label.source === "parser").length,
    heuristic: labels.filter((label) => label.source === "heuristic").length,
    llm: labels.filter((label) => label.source === "llm").length
  };
}
function countNamespaces(labels) {
  const counts = new Map;
  for (const label of labels)
    counts.set(label.namespace, (counts.get(label.namespace) ?? 0) + 1);
  return Object.fromEntries(Array.from(counts.entries()).sort(([left], [right]) => compareStable(left, right)));
}
function countSurfaces(fanout) {
  const counts = new Map;
  for (const item of fanout) {
    for (const surface of item.connectedSurfaceKinds)
      counts.set(surface, (counts.get(surface) ?? 0) + 1);
  }
  return Object.fromEntries(Array.from(counts.entries()).sort(([left], [right]) => compareStable(left, right)));
}
function isParserFactLabel(label) {
  return label.source === "parser" && label.architectureAuthority === "parser_fact";
}
function hasRoutingFactNamespace(labels, namespace) {
  return labels.some((label) => label.namespace === namespace && (label.source !== "llm" || isParserFactLabel(label)));
}
function compareLabels(left, right) {
  return compareStable(left.filePath, right.filePath) || (left.startLine ?? 0) - (right.startLine ?? 0) || compareStable(left.namespace, right.namespace) || compareStable(left.key, right.key) || compareStable(left.normalizedValue, right.normalizedValue) || compareStable(left.source, right.source) || compareStable(left.architectureAuthority, right.architectureAuthority) || compareStable(left.labelIdentity, right.labelIdentity);
}
function compareStable(left, right) {
  if (left < right)
    return -1;
  if (left > right)
    return 1;
  return 0;
}
function max(values) {
  return values.reduce((highest, value) => Math.max(highest, value), 0);
}
function uniqueSurfaces(values) {
  return Array.from(new Set(values)).sort(compareStable);
}
// ../core/src/contextRouting/connectedSurfaceCoverage.ts
var CONNECTED_SURFACE_COVERAGE_REPORT_VERSION = 1;
var CHANGE_SHAPE_TIE_PRIORITY = [
  "provider_integration",
  "execution_safety",
  "agent_handoff",
  "ui_reuse_or_design_system",
  "ui_behavior",
  "shared_abstraction",
  "docs_or_migration"
];
var SURFACE_PAIR_DEFINITIONS = [
  {
    pairId: "runtime_enforcement__targeted_tests",
    left: "runtime_enforcement",
    right: "targeted_tests",
    repairHint: "Add targeted regression tests for the runtime enforcement surface.",
    suggestedPathPatterns: ["**/*test.ts", "convex-tests/**/*.test.ts", "test/**/*.ts"]
  },
  {
    pairId: "provider_gateway__primary_code",
    left: "provider_gateway",
    right: "primary_code",
    repairHint: "Pair provider gateway files with the primary call-path code they route.",
    suggestedPathPatterns: ["**/provider*.ts", "**/gateway*.ts", "**/generate-text*.ts", "**/stream-text*.ts"]
  },
  {
    pairId: "receipt_audit__runtime_enforcement",
    left: "receipt_audit",
    right: "runtime_enforcement",
    repairHint: "Pair receipt/audit evidence with the runtime enforcement path it proves.",
    suggestedPathPatterns: ["**/*receipt*.ts", "**/*trail*.ts", "prompt-exports/**/*.md"]
  },
  {
    pairId: "ui_surface__native_counterpart",
    left: "ui_surface",
    right: "native_counterpart",
    repairHint: "Check whether a native counterpart is needed for the UI surface.",
    suggestedPathPatterns: ["**/*.native.tsx", "apps/expo/**/*.tsx", "packages/ui/**/*.native.tsx"]
  },
  {
    pairId: "design_system_or_shared_component__usage_sites",
    left: "design_system_or_shared_component",
    right: "usage_sites",
    repairHint: "Pair the shared UI/design-system surface with representative usage sites.",
    suggestedPathPatterns: ["packages/ui/**/*.tsx", "apps/**/*.tsx", "**/*.stories.tsx"]
  },
  {
    pairId: "agent_handoff__package_exports",
    left: "agent_handoff",
    right: "package_exports",
    repairHint: "Pair agent handoff guidance with exported contracts/types consumed by agents.",
    suggestedPathPatterns: ["**/index.ts", "packages/core/src/briefs/**/*.ts", "packages/core/src/contextRouting/**/*.ts"]
  }
];
var CASE_ID_PATTERNS = {
  provider_integration: [/provider/i, /gateway/i, /vercel-ai/i, /routing/i],
  execution_safety: [/auth/i, /redirect/i, /safety/i, /receipt/i, /validation/i],
  agent_handoff: [/agent/i, /handoff/i, /work-?brief/i, /context-?plan/i],
  ui_reuse_or_design_system: [/reuse/i, /design[-_ ]?system/i, /shared[-_ ]?ui/i, /component[-_ ]?reuse/i, /shared[-_ ]?component/i, /faded[-_ ]?disclosure/i, /package[-_ ]?export/i],
  ui_behavior: [/ui/i, /chat/i, /message/i, /panel/i, /runtime/i],
  shared_abstraction: [/shared/i, /abstraction/i, /retry/i, /ky/i, /core/i],
  docs_or_migration: [/docs/i, /migration/i, /markdown/i, /readme/i]
};
var INTENT_PATTERNS = {
  provider_integration: [/provider/i, /gateway/i, /routing/i, /fallback/i, /model/i],
  execution_safety: [/harden/i, /safe/i, /safety/i, /auth/i, /redirect/i, /receipt/i, /validation/i],
  agent_handoff: [/agent/i, /handoff/i, /brief/i, /context plan/i, /work packet/i],
  ui_reuse_or_design_system: [/faded disclosure/i, /fade/i, /gradient mask/i, /mask image/i, /shared ui/i, /component reuse/i, /duplicated UI behavior/i, /message bubble/i, /side panel/i, /spotlight/i, /thread list/i, /thinking indicator/i, /design system/i, /package export/i, /shared component/i],
  ui_behavior: [/ui/i, /render/i, /message/i, /panel/i, /runtime/i, /visible/i],
  shared_abstraction: [/shared/i, /contract/i, /retry/i, /behavior/i, /options/i, /hooks/i],
  docs_or_migration: [/docs/i, /documentation/i, /migration/i, /readme/i, /operator/i]
};
var PATH_PATTERNS = {
  provider_integration: [/provider/i, /gateway/i, /generate-text/i, /stream-text/i, /resolve-model/i, /registry/i, /model/i],
  execution_safety: [/auth/i, /redirect/i, /validation/i, /executionSafety/i, /receipt/i, /guard/i, /policy/i],
  agent_handoff: [/agent/i, /handoff/i, /workBrief/i, /work-brief/i, /contextPlan/i, /prompt-exports/i, /briefs/i],
  ui_reuse_or_design_system: [/packages\/ui/i, /design[-_ ]?system/i, /shared[-_ ]?component/i, /faded[-_ ]?disclosure/i, /stories?\./i, /visual[-_ ]?snapshot/i, /message[-_ ]?bubble/i, /side[-_ ]?panel/i, /thread[-_ ]?list/i, /thinking[-_ ]?indicator/i],
  ui_behavior: [/\.tsx$/i, /components/i, /ui/i, /expo/i, /native/i, /Message/i, /Panel/i, /styles/i],
  shared_abstraction: [/core/i, /types/i, /utils/i, /retry/i, /options/i, /hooks/i, /constants/i, /packages\/core/i],
  docs_or_migration: [/docs/i, /migration/i, /readme/i, /\.mdx?$/i, /prompt-exports/i]
};
function classifyConnectedSurfaceChangeShape(input) {
  const scores = zeroScores();
  const signals = [];
  const caseId = input.caseId ?? "";
  const intent = input.intent ?? input.packet.objective ?? "";
  const paths = packetPaths(input.packet);
  const selectionSignals = input.packet.contextSlices.flatMap((slice) => slice.selectionSignals ?? []);
  const roleContentSignals = input.packet.contextSlices.map((slice) => `${slice.role}:${slice.contentMode ?? "none"}:${slice.path}`);
  const refs = [...input.packet.sourceRefs, ...input.packet.evidenceRefs, ...input.packet.receiptRefs];
  addSignals(scores, signals, "case_id", caseId, 10, CASE_ID_PATTERNS);
  for (const value of selectionSignals)
    addSelectionSignal(scores, signals, value);
  addSignals(scores, signals, "intent_phrase", intent, 3, INTENT_PATTERNS);
  for (const path of paths)
    addSignals(scores, signals, "path_pattern", path, 2, PATH_PATTERNS);
  for (const value of roleContentSignals)
    addRoleContentSignal(scores, signals, value);
  for (const ref of refs)
    addSignals(scores, signals, "ref_signal", ref, 1, PATH_PATTERNS);
  const total = Object.values(scores).reduce((sum, score) => sum + score, 0);
  if (total === 0) {
    scores.shared_abstraction = 1;
    signals.push({ changeShape: "shared_abstraction", source: "fallback", weight: 1, value: "no_signal_shared_abstraction" });
  }
  const changeShape = CHANGE_SHAPE_TIE_PRIORITY.reduce((best, candidate) => {
    if (scores[candidate] > scores[best])
      return candidate;
    return best;
  }, CHANGE_SHAPE_TIE_PRIORITY[0]);
  const winningScore = scores[changeShape];
  const confidence = winningScore >= 10 ? "high" : winningScore >= 5 ? "medium" : "low";
  return { changeShape, confidence, scores, signals };
}
function scoreConnectedSurfaceCoverage(input) {
  const caseId = input.caseId ?? input.packet.packetId;
  const classification = classifyConnectedSurfaceChangeShape({
    caseId,
    intent: input.intent,
    packet: input.packet
  });
  const policy = connectedSurfacePolicyForChangeShape(classification.changeShape);
  const evidence = buildEvidenceIndex(input.packet);
  const allowedPaths = new Set((input.allowedPaths ?? evidence.map((item) => item.path)).filter(Boolean));
  const surfaceResults = policy.rules.map((rule) => scoreRule(rule, evidence));
  const requiredResults = surfaceResults.filter((result) => result.level === "required");
  const optionalResults = surfaceResults.filter((result) => result.level === "optional");
  const requiredCoverage = coverageCount(requiredResults.filter((result) => result.passed).length, requiredResults.length) ?? 1;
  const optionalCoverage = coverageCount(optionalResults.filter((result) => result.passed).length, optionalResults.length);
  const missingCriticalCount = requiredResults.filter((result) => !result.passed).length;
  const inventedPathCount = evidence.filter((item) => !allowedPaths.has(item.path)).length;
  const evidenceKinds = evidence.map((item) => evidenceSurfaceKinds(item));
  const lowValueEvidenceCount = evidenceKinds.filter((kinds) => kinds.length === 0).length;
  const coveredSurfaceKinds = new Set(surfaceResults.filter((result) => result.passed).map((result) => result.surfaceKind));
  const expectedSurfaceKinds = new Set(policy.rules.map((rule) => rule.surfaceKind));
  const observedSurfaceKinds = new Set(evidenceKinds.flat());
  const overIncludedSurfaceCount = Array.from(observedSurfaceKinds).filter((surfaceKind) => !expectedSurfaceKinds.has(surfaceKind)).length;
  const policyRelevantEvidenceCount = evidenceKinds.filter((kinds) => kinds.some((surfaceKind) => expectedSurfaceKinds.has(surfaceKind))).length;
  const surfacePrecision = evidence.length === 0 ? null : round3(policyRelevantEvidenceCount / evidence.length);
  const packetConfidence = average(evidence.map((item) => item.confidence ?? null));
  const estimatedTokens = input.packet.contentBudget?.estimatedTokens;
  const tokenRatio = typeof estimatedTokens === "number" && typeof input.repoPromptTokenEstimate === "number" && input.repoPromptTokenEstimate > 0 ? round3(estimatedTokens / input.repoPromptTokenEstimate) : null;
  const plannerSufficiency = typeof input.plannerSufficiency === "number" ? input.plannerSufficiency : null;
  const plannerSufficiencyWithSurfaceCoverage = plannerSufficiency === null ? null : round1(Math.min(3, plannerSufficiency * 0.65 + requiredCoverage * 3 * 0.35));
  const surfacePairCoverage = buildSurfacePairCoverage(coveredSurfaceKinds, surfaceResults);
  const readiness = deriveReadiness({
    requiredCoverage,
    missingCriticalCount,
    inventedPathCount,
    surfacePrecision,
    lowValueEvidenceCount
  });
  const productSurfaces = predictProductSurfaces({
    caseId,
    intent: input.intent ?? input.packet.objective,
    packet: input.packet
  });
  const decision = chooseGraphExecutionMode(policy.graphInput);
  const routingPolicy = chooseGraphRoutingPolicyV1({
    taskKind: graphRoutingTaskKindForChangeShape(classification.changeShape),
    changeShape: classification.changeShape,
    connectedWorkAvailable: true,
    noLiveMode: true,
    networkAllowed: false,
    providerCallsAllowed: false
  });
  return {
    reportKind: "connected_surface_coverage",
    version: CONNECTED_SURFACE_COVERAGE_REPORT_VERSION,
    caseId,
    packetId: input.packet.packetId,
    changeShape: classification,
    policy: {
      changeShape: policy.changeShape,
      label: policy.label,
      recommendedEscalation: policy.recommendedEscalation,
      requiredSurfaceKinds: policy.rules.filter((rule) => rule.level === "required").map((rule) => rule.surfaceKind),
      optionalSurfaceKinds: policy.rules.filter((rule) => rule.level === "optional").map((rule) => rule.surfaceKind)
    },
    graph: {
      recommendedEscalation: policy.recommendedEscalation,
      selectedMode: decision.selectedMode,
      decision,
      routingPolicy
    },
    surfaceResults,
    surfacePairCoverage,
    readiness,
    productSurfaces,
    evidence,
    metrics: {
      requiredCoverage,
      optionalCoverage,
      missingCriticalCount,
      inventedPathCount,
      surfacePrecision,
      overIncludedSurfaceCount,
      lowValueEvidenceCount,
      packetConfidence,
      tokenRatio,
      plannerSufficiency,
      plannerSufficiencyWithSurfaceCoverage
    },
    noLiveInvariants: {
      noNetwork: true,
      noProviderCalls: true,
      noConvexWrites: true,
      noProductionWrites: true,
      noMemgraph: true,
      noLiveSourceScans: true,
      noRepoPromptLiveCalls: true,
      allSatisfied: true
    }
  };
}
function buildConnectedSurfaceReadinessGateV1(report) {
  const missingResults = report.surfaceResults.filter((result) => result.level === "required" && !result.passed);
  const status = report.readiness === "needs_targeted_surface_repair" ? "block" : report.readiness === "needs_broader_context" || report.readiness === "ready_with_caveats" ? "warn" : "pass";
  return {
    schemaVersion: 1,
    kind: "connected_surface_readiness_gate",
    status,
    readiness: report.readiness,
    missingSurfaceKinds: missingResults.map((result) => result.surfaceKind),
    repairSearches: missingResults.map((result) => ({
      surfaceKind: result.surfaceKind,
      repairHint: result.repairHint ?? `Add evidence for ${result.surfaceKind}.`,
      suggestedPathPatterns: result.suggestedPathPatterns ?? []
    })),
    reportRef: `connected-surface:${report.packetId}:${report.caseId}`,
    reasonCodes: [
      `connected_surface:readiness_${report.readiness}`,
      `connected_surface:gate_${status}`,
      ...missingResults.map((result) => `connected_surface:missing_${result.surfaceKind}`),
      "authority:report_only"
    ],
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function graphRoutingTaskKindForChangeShape(changeShape) {
  switch (changeShape) {
    case "shared_abstraction":
    case "ui_reuse_or_design_system":
      return "shared_abstraction_review";
    case "ui_behavior":
      return "changed_file_impact";
    case "execution_safety":
      return "execution_safety_impact";
    case "provider_integration":
      return "provider_integration_impact";
    case "agent_handoff":
      return "agent_handoff_planning";
    case "docs_or_migration":
      return "docs_code_alignment";
  }
}
function zeroScores() {
  return {
    shared_abstraction: 0,
    ui_behavior: 0,
    ui_reuse_or_design_system: 0,
    execution_safety: 0,
    provider_integration: 0,
    agent_handoff: 0,
    docs_or_migration: 0
  };
}
function addSelectionSignal(scores, signals, value) {
  const surfaceKind = surfaceKindFromSelectionSignal(value);
  if (surfaceKind) {
    for (const changeShape of changeShapesForSurfaceKindSignal(surfaceKind)) {
      scores[changeShape] += 4;
      signals.push({ changeShape, source: "selection_signal", weight: 4, value });
    }
    return;
  }
  addSignals(scores, signals, "selection_signal", value, 4, INTENT_PATTERNS);
}
function surfaceKindFromSelectionSignal(value) {
  const lower = value.toLowerCase();
  const surfaceKinds = [
    "primary_code",
    "targeted_tests",
    "user_docs",
    "config_policy",
    "package_exports",
    "runtime_enforcement",
    "schema_persistence",
    "ui_surface",
    "design_system_or_shared_component",
    "usage_sites",
    "visual_snapshot_or_story",
    "native_counterpart",
    "receipt_audit",
    "eval_report",
    "migration_notes",
    "provider_gateway",
    "agent_handoff"
  ];
  return surfaceKinds.find((surfaceKind) => lower === surfaceKind || lower.includes(`connected_surface:${surfaceKind}`) || lower.includes(`surface:${surfaceKind}`)) ?? null;
}
function changeShapesForSurfaceKindSignal(surfaceKind) {
  switch (surfaceKind) {
    case "ui_surface":
    case "native_counterpart":
      return ["ui_behavior"];
    case "design_system_or_shared_component":
    case "usage_sites":
    case "visual_snapshot_or_story":
      return ["ui_reuse_or_design_system"];
    case "runtime_enforcement":
    case "receipt_audit":
    case "config_policy":
      return ["execution_safety"];
    case "provider_gateway":
      return ["provider_integration"];
    case "agent_handoff":
      return ["agent_handoff"];
    case "user_docs":
    case "migration_notes":
      return ["docs_or_migration"];
    case "targeted_tests":
      return ["execution_safety", "shared_abstraction"];
    case "package_exports":
    case "schema_persistence":
    case "eval_report":
      return ["shared_abstraction"];
    case "primary_code":
      return [];
  }
}
function addSignals(scores, signals, source, value, weight, patterns) {
  if (!value.trim())
    return;
  for (const changeShape of CHANGE_SHAPE_TIE_PRIORITY) {
    if (!patterns[changeShape].some((pattern) => pattern.test(value)))
      continue;
    scores[changeShape] += weight;
    signals.push({ changeShape, source, weight, value });
  }
}
function addRoleContentSignal(scores, signals, value) {
  const lower = value.toLowerCase();
  const matches = [];
  if (lower.includes("edit:full_file") || lower.includes("edit:multi_slice") || lower.includes("edit:symbol_slice"))
    matches.push("shared_abstraction");
  if (lower.includes("test:"))
    matches.push("execution_safety", "shared_abstraction");
  if (lower.includes("doc:"))
    matches.push("docs_or_migration");
  if (lower.includes("config:"))
    matches.push("execution_safety", "provider_integration");
  if (lower.includes(".tsx") || lower.includes("native") || lower.includes("styles"))
    matches.push("ui_behavior");
  if (lower.includes("gateway") || lower.includes("provider"))
    matches.push("provider_integration");
  if (lower.includes("handoff") || lower.includes("brief"))
    matches.push("agent_handoff");
  for (const changeShape of matches) {
    scores[changeShape] += 1;
    signals.push({ changeShape, source: "role_content", weight: 1, value });
  }
}
function buildEvidenceIndex(packet) {
  const byPath = new Map;
  for (const file of packet.primaryEditFiles)
    addEvidence(byPath, file.path, "primary_edit_file", { confidence: file.confidence });
  for (const slice of packet.contextSlices) {
    addEvidence(byPath, slice.path, "context_slice", {
      role: slice.role,
      contentMode: slice.contentMode,
      selectionSignals: slice.selectionSignals,
      confidence: slice.confidence
    });
  }
  for (const file of packet.affectedTests)
    addEvidence(byPath, file.path, "affected_test", { confidence: file.confidence });
  for (const file of packet.affectedDocs)
    addEvidence(byPath, file.path, "affected_doc", { confidence: file.confidence });
  for (const file of packet.configFiles)
    addEvidence(byPath, file.path, "config_file", { confidence: file.confidence });
  for (const path of packet.sourceRefs)
    addEvidence(byPath, path, "source_ref");
  for (const path of packet.evidenceRefs)
    addEvidence(byPath, path, "evidence_ref");
  for (const path of packet.receiptRefs)
    addEvidence(byPath, path, "receipt_ref");
  return Array.from(byPath.values()).map((item) => ({
    path: item.path,
    evidenceTypes: Array.from(item.evidenceTypes),
    role: item.role,
    contentMode: item.contentMode,
    selectionSignals: Array.from(item.selectionSignals),
    confidence: average(item.confidenceValues) ?? undefined
  }));
}
function addEvidence(byPath, path, evidenceType, options = {}) {
  const trimmed = path.trim();
  if (!trimmed)
    return;
  const existing = byPath.get(trimmed) ?? {
    path: trimmed,
    evidenceTypes: new Set,
    selectionSignals: new Set,
    confidenceValues: []
  };
  existing.evidenceTypes.add(evidenceType);
  existing.role = existing.role ?? options.role;
  existing.contentMode = existing.contentMode ?? options.contentMode;
  for (const signal of options.selectionSignals ?? [])
    existing.selectionSignals.add(signal);
  if (typeof options.confidence === "number" && Number.isFinite(options.confidence))
    existing.confidenceValues.push(options.confidence);
  byPath.set(trimmed, existing);
}
function scoreRule(rule, evidence) {
  const matchedPaths = evidence.filter((item) => item.evidenceTypes.some((type) => rule.evidenceTypes.includes(type))).filter((item) => pathMatchesSurfaceKind(item, rule.surfaceKind)).map((item) => item.path);
  const uniquePaths = Array.from(new Set(matchedPaths));
  const passed = uniquePaths.length >= rule.minEvidenceCount;
  const repair = repairForSurfaceKind(rule.surfaceKind);
  return {
    surfaceKind: rule.surfaceKind,
    level: rule.level,
    minEvidenceCount: rule.minEvidenceCount,
    matchedEvidenceCount: uniquePaths.length,
    matchedPaths: uniquePaths,
    passed,
    rationale: rule.rationale,
    repairHint: passed ? undefined : repair.repairHint,
    suggestedPathPatterns: passed ? undefined : repair.suggestedPathPatterns
  };
}
function connectedSurfaceKindsForEvidenceItemV1(item) {
  return evidenceSurfaceKinds(item);
}
function evidenceSurfaceKinds(item) {
  return CONNECTED_SURFACE_KIND_MATCH_ORDER.filter((surfaceKind) => pathMatchesSurfaceKind(item, surfaceKind));
}
var CONNECTED_SURFACE_KIND_MATCH_ORDER = [
  "primary_code",
  "targeted_tests",
  "user_docs",
  "config_policy",
  "package_exports",
  "runtime_enforcement",
  "schema_persistence",
  "ui_surface",
  "design_system_or_shared_component",
  "usage_sites",
  "visual_snapshot_or_story",
  "native_counterpart",
  "receipt_audit",
  "eval_report",
  "migration_notes",
  "provider_gateway",
  "agent_handoff"
];
function pathMatchesSurfaceKind(item, surfaceKind) {
  if (selectionSignalsMatchSurfaceKind(item.selectionSignals, surfaceKind))
    return true;
  const path = item.path;
  const lower = path.toLowerCase();
  switch (surfaceKind) {
    case "primary_code":
      if (item.evidenceTypes.includes("primary_edit_file") || item.role === "edit")
        return true;
      if (item.role === "test" || item.role === "doc" || item.role === "config")
        return false;
      if (/(^|\/)(test|tests|convex-tests)\/|\.test\.|\.spec\.|config|env|policy/.test(lower))
        return false;
      return /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(lower);
    case "targeted_tests":
      return item.evidenceTypes.includes("affected_test") || item.role === "test" || /(^|\/)(test|tests|convex-tests)\//.test(lower) || /\.test\./.test(lower);
    case "user_docs":
      return item.evidenceTypes.includes("affected_doc") || item.role === "doc" || /(^|\/)docs\//.test(lower) || /readme|\.mdx?$/.test(lower);
    case "config_policy":
      return item.evidenceTypes.includes("config_file") || item.role === "config" || /config|env|policy|allowlist|options/.test(lower);
    case "package_exports":
      return /(^|\/)package\.json$|(^|\/)packages\/[^/]+\/src\/index\.ts$|(^|\/)(src|source)\/index\.ts$|exports?|types?|options|constants/.test(lower);
    case "runtime_enforcement":
      return /auth|redirect|validation|guard|enforce|runtime|safety|retry|timeout|error|receipt/.test(lower);
    case "schema_persistence":
      return /schema|migration|db|persistence|convex\/schema|types/.test(lower);
    case "ui_surface":
      return /\.tsx$|components|ui|expo|web|native|message|panel|styles/.test(lower);
    case "design_system_or_shared_component":
      return /design[-_ ]?system|shared[-_ ]?component|packages\/ui|@rhei\/ui|primitive|faded[-_ ]?disclosure/.test(lower);
    case "usage_sites":
      return /usage|call[-_ ]?site|consumer|message[-_ ]?bubble|side[-_ ]?panel|spotlight|thread[-_ ]?list|thinking[-_ ]?indicator/.test(lower);
    case "visual_snapshot_or_story":
      return /story|stories|storybook|snapshot|visual|screenshot|chromatic/.test(lower);
    case "native_counterpart":
      return /\.native\.|native|expo|ios|android/.test(lower);
    case "receipt_audit":
      return item.evidenceTypes.includes("receipt_ref") || /receipt|trail|audit|report|prompt-exports/.test(lower);
    case "eval_report":
      return /eval|test|report|prompt-exports|fixture/.test(lower);
    case "migration_notes":
      return /migration|migrate|docs|readme|prompt-exports|planning/.test(lower);
    case "provider_gateway":
      return /provider|gateway|model|generate-text|stream-text|registry|routing/.test(lower);
    case "agent_handoff":
      return /agent|handoff|brief|contextplan|context-plan|workroom|work-packet|prompt-exports/.test(lower);
  }
}
function selectionSignalsMatchSurfaceKind(signals, surfaceKind) {
  return signals.some((signal) => {
    const lower = signal.toLowerCase();
    return lower === surfaceKind || lower.includes(`connected_surface:${surfaceKind}`) || lower.includes(`surface:${surfaceKind}`) || lower.includes(`role:${surfaceKind}`);
  });
}
function buildSurfacePairCoverage(coveredSurfaceKinds, surfaceResults) {
  const pathsFor = (surfaceKind) => surfaceResults.find((result) => result.surfaceKind === surfaceKind)?.matchedPaths ?? [];
  return SURFACE_PAIR_DEFINITIONS.map((definition) => {
    const leftCovered = coveredSurfaceKinds.has(definition.left);
    const rightCovered = coveredSurfaceKinds.has(definition.right);
    const covered = leftCovered && rightCovered;
    return {
      pairId: definition.pairId,
      left: definition.left,
      right: definition.right,
      covered,
      leftCovered,
      rightCovered,
      matchedPaths: Array.from(new Set([...pathsFor(definition.left), ...pathsFor(definition.right)])),
      repairHint: covered ? undefined : definition.repairHint,
      suggestedPathPatterns: covered ? undefined : definition.suggestedPathPatterns
    };
  });
}
function deriveReadiness(input) {
  const precision = input.surfacePrecision ?? 1;
  if (input.inventedPathCount > 0 || input.requiredCoverage < 0.5)
    return "needs_broader_context";
  if (input.missingCriticalCount > 0 || input.requiredCoverage < 0.9)
    return "needs_targeted_surface_repair";
  if (precision < 0.75 || input.lowValueEvidenceCount > 2)
    return "ready_with_caveats";
  return "ready_without_search";
}
function predictProductSurfaces(input) {
  const scores = new Map;
  const add = (surface, score, signal) => {
    const current = scores.get(surface) ?? { score: 0, signals: new Set };
    current.score += score;
    current.signals.add(signal);
    scores.set(surface, current);
  };
  const values = [
    input.caseId,
    input.intent ?? "",
    ...packetPaths(input.packet),
    ...input.packet.contextSlices.flatMap((slice) => slice.selectionSignals ?? [])
  ];
  for (const value of values) {
    const lower = value.toLowerCase();
    if (/canvas/.test(lower))
      add("canvas", 2, value);
    if (/chat|message|ai\/|agent_chat/.test(lower))
      add("agent_chat", 2, value);
    if (/code[_-]?map|code_layer|code-layer/.test(lower))
      add("code_map", 2, value);
    if (/workroom|work-?packet|brief|handoff/.test(lower))
      add("workroom", 2, value);
    if (/auth|redirect|session|callback/.test(lower))
      add("auth", 3, value);
    if (/receipt|trail|audit|execution[-_]?safety/.test(lower))
      add("execution_receipts", 3, value);
    if (/provider|gateway|routing|model/.test(lower))
      add("provider_routing", 3, value);
    if (/docs|readme|\.mdx?$|documentation/.test(lower))
      add("docs", 2, value);
  }
  return Array.from(scores.entries()).map(([surface, value]) => ({
    surface,
    confidence: Math.min(1, round3(value.score / 10)),
    signals: Array.from(value.signals).slice(0, 6)
  })).filter((item) => item.confidence > 0).sort((left, right) => right.confidence - left.confidence || left.surface.localeCompare(right.surface));
}
function repairForSurfaceKind(surfaceKind) {
  switch (surfaceKind) {
    case "primary_code":
      return { repairHint: "Add the primary implementation file or focused source slice.", suggestedPathPatterns: ["packages/**/*.ts", "convex/**/*.ts", "source/**/*.ts"] };
    case "targeted_tests":
      return { repairHint: "Add targeted regression tests for this surface.", suggestedPathPatterns: ["**/*.test.ts", "convex-tests/**/*.test.ts", "test/**/*.ts"] };
    case "user_docs":
      return { repairHint: "Add user-facing docs or README coverage.", suggestedPathPatterns: ["docs/**/*.md", "**/readme.md", "content/docs/**/*.mdx"] };
    case "config_policy":
      return { repairHint: "Add config, environment, or policy files that control this behavior.", suggestedPathPatterns: ["**/*config*.ts", "**/*Env*.ts", "**/*policy*.ts"] };
    case "package_exports":
      return { repairHint: "Add export barrel or public type files.", suggestedPathPatterns: ["**/index.ts", "**/types.ts", "package.json"] };
    case "runtime_enforcement":
      return { repairHint: "Add runtime guard/enforcement/error handling code.", suggestedPathPatterns: ["**/*validation*.ts", "**/*guard*.ts", "**/*error*.ts"] };
    case "schema_persistence":
      return { repairHint: "Add schema or persistence contract files.", suggestedPathPatterns: ["**/schema*.ts", "**/*migration*.ts", "convex/schema/**/*.ts"] };
    case "ui_surface":
      return { repairHint: "Add the visible UI component/style surface.", suggestedPathPatterns: ["**/*.tsx", "**/*.styles.ts", "packages/ui/**/*.tsx"] };
    case "design_system_or_shared_component":
      return { repairHint: "Add the shared UI primitive or design-system component surface.", suggestedPathPatterns: ["packages/ui/**/*.tsx", "packages/theme/**/*.ts", "**/*design-system*.tsx"] };
    case "usage_sites":
      return { repairHint: "Add representative UI usage sites for the shared behavior.", suggestedPathPatterns: ["apps/**/*.tsx", "**/*Message*.tsx", "**/*Panel*.tsx"] };
    case "visual_snapshot_or_story":
      return { repairHint: "Add a visual snapshot, story, or fixture for the UI behavior.", suggestedPathPatterns: ["**/*.stories.tsx", "**/*snapshot*", "tests/browser/snapshots/**/*"] };
    case "native_counterpart":
      return { repairHint: "Add native counterpart context or document why none is needed.", suggestedPathPatterns: ["**/*.native.tsx", "apps/expo/**/*.tsx"] };
    case "receipt_audit":
      return { repairHint: "Add receipt, trail, audit, or report evidence.", suggestedPathPatterns: ["**/*receipt*.ts", "**/*trail*.ts", "prompt-exports/**/*.md"] };
    case "eval_report":
      return { repairHint: "Add eval/report fixture coverage.", suggestedPathPatterns: ["convex-tests/evals/**/*.test.ts", "convex-tests/evals/lib/**/*.ts"] };
    case "migration_notes":
      return { repairHint: "Add migration notes or planning docs.", suggestedPathPatterns: ["docs/**/*.md", "prompt-exports/**/*.md"] };
    case "provider_gateway":
      return { repairHint: "Add provider/gateway routing files.", suggestedPathPatterns: ["**/*provider*.ts", "**/*gateway*.ts", "**/*routing*.ts"] };
    case "agent_handoff":
      return { repairHint: "Add agent handoff brief/work-packet context.", suggestedPathPatterns: ["**/*brief*.ts", "**/*handoff*.ts", "prompt-exports/**/*.md"] };
  }
}
function packetPaths(packet) {
  return Array.from(new Set([
    ...packet.primaryEditFiles.map((file) => file.path),
    ...packet.contextSlices.map((slice) => slice.path),
    ...packet.affectedTests.map((file) => file.path),
    ...packet.affectedDocs.map((file) => file.path),
    ...packet.configFiles.map((file) => file.path),
    ...packet.sourceRefs,
    ...packet.evidenceRefs,
    ...packet.receiptRefs
  ].filter(Boolean)));
}
function coverageCount(passed, total) {
  if (total === 0)
    return null;
  return passed / total;
}
function average(values) {
  const numbers = values.filter((value) => typeof value === "number" && Number.isFinite(value));
  if (numbers.length === 0)
    return null;
  return round3(numbers.reduce((sum, value) => sum + value, 0) / numbers.length);
}
function round1(value) {
  return Math.round(value * 10) / 10;
}
function round3(value) {
  return Math.round(value * 1000) / 1000;
}
export {
  semanticSelectionSignalsFromReadyLabels,
  semanticSelectionSignalsByFilePath,
  semanticSelectionSignalMappingsFromReadyLabels,
  scoreConnectedSurfaceCoverage,
  plannerHandoffGraphAdvisoryFromPolicyDecision,
  normalizePlannerHandoffGraphAdvisoryV1,
  graphExecutionModePolicyMetadataList,
  graphExecutionModePolicyMetadataFor,
  connectedSurfacePolicyForChangeShape,
  connectedSurfaceKindsForSemanticLabel,
  connectedSurfaceKindsForEvidenceItemV1,
  classifyConnectedSurfaceChangeShape,
  chooseGraphRoutingPolicyV1,
  chooseGraphExecutionMode,
  buildSemanticGraphRoutingReportFromLabels,
  buildPlannerHandoffGraphAdvisoryV1,
  buildGraphExecutionModeInputFromSemanticLabels,
  buildGraphExecutionModeDefaultDecisions,
  buildConnectedSurfaceReadinessGateV1,
  SEMANTIC_SELECTION_SIGNAL_PREFIX_V1,
  SEMANTIC_GRAPH_ROUTING_REPORT_VERSION,
  PLANNER_HANDOFF_GRAPH_ADVISORY_SCHEMA_VERSION,
  PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY,
  PLANNER_HANDOFF_GRAPH_ADVISORY_KIND,
  GRAPH_ROUTING_POLICY_VERSION,
  GRAPH_ROUTING_MIN_SOURCE_GROUNDING_RATE_V1,
  GRAPH_ROUTING_MIN_DEPTH5_LIFT_V1,
  GRAPH_ROUTING_MAX_NOISE_RATE_V1,
  GRAPH_ROUTING_DEPTH5_MIN_HIGH_COMPLEXITY_SCORE_V1,
  GRAPH_EXECUTION_MODE_ROUTER_VERSION,
  GRAPH_EXECUTION_MODES,
  CONNECTED_SURFACE_POLICIES_V1,
  CONNECTED_SURFACE_KINDS_V1,
  CONNECTED_SURFACE_COVERAGE_REPORT_VERSION,
  CHANGE_SHAPES_V1
};
