import {
  readChainIndex,
  resolveChainsDir
} from "./chunk-XMHBH5H6.js";
import "./chunk-URB2WSKZ.js";
import {
  searchCausalTrajectories
} from "./chunk-G2WADRQ3.js";
import "./chunk-DT5TVLJE.js";
import {
  log
} from "./chunk-2ODBA7MQ.js";
import "./chunk-DGXUHMOV.js";
import "./chunk-LPSF4OQH.js";
import "./chunk-PZ5AY32C.js";

// src/causal-retrieval.ts
function walkUpstream(seedId, index, maxDepth, counterfactualBoost) {
  const visited = /* @__PURE__ */ new Set([seedId]);
  const results = [];
  let frontier = [seedId];
  for (let depth = 1; depth <= maxDepth; depth++) {
    const nextFrontier = [];
    for (const currentId of frontier) {
      const incomingEdgeIds = index.incoming[currentId] ?? [];
      for (const edgeId of incomingEdgeIds) {
        const edge = index.edges[edgeId];
        if (!edge) continue;
        const fromId = edge.fromTrajectoryId;
        if (visited.has(fromId)) continue;
        visited.add(fromId);
        const outgoingFromSource = index.outgoing[fromId] ?? [];
        const isCounterfactual = outgoingFromSource.length > 1;
        const depthDecay = 1 / depth;
        let score = depthDecay * edge.confidence;
        if (isCounterfactual) score += counterfactualBoost;
        results.push({
          trajectoryId: fromId,
          depth,
          score,
          edgeType: edge.edgeType,
          edgeConfidence: edge.confidence,
          isCounterfactual
        });
        nextFrontier.push(fromId);
      }
    }
    frontier = nextFrontier;
    if (frontier.length === 0) break;
  }
  return results;
}
function walkDownstream(seedId, index, maxDepth, counterfactualBoost) {
  const downstreamMaxDepth = Math.min(maxDepth, 2);
  const visited = /* @__PURE__ */ new Set([seedId]);
  const results = [];
  let frontier = [seedId];
  for (let depth = 1; depth <= downstreamMaxDepth; depth++) {
    const nextFrontier = [];
    for (const currentId of frontier) {
      const outgoingEdgeIds = index.outgoing[currentId] ?? [];
      const isCounterfactual = outgoingEdgeIds.length > 1;
      for (const edgeId of outgoingEdgeIds) {
        const edge = index.edges[edgeId];
        if (!edge) continue;
        const toId = edge.toTrajectoryId;
        if (visited.has(toId)) continue;
        visited.add(toId);
        const depthDecay = 1 / (depth + 1);
        let score = depthDecay * edge.confidence;
        if (isCounterfactual) score += counterfactualBoost;
        results.push({
          trajectoryId: toId,
          depth,
          score,
          edgeType: edge.edgeType,
          edgeConfidence: edge.confidence,
          isCounterfactual
        });
        nextFrontier.push(toId);
      }
    }
    frontier = nextFrontier;
    if (frontier.length === 0) break;
  }
  return results;
}
function formatRetrievalResult(result) {
  const direction = result.direction === "upstream" ? "\u2191" : result.direction === "downstream" ? "\u2193" : "\u2022";
  const counterfactual = result.isCounterfactual ? " [branching point]" : "";
  const edgeInfo = result.edgeType ? ` (${result.edgeType})` : "";
  return `- ${direction} ${result.summary}${edgeInfo}${counterfactual}`;
}
function formatCausalRetrievalSection(results, maxChars) {
  if (results.length === 0) return null;
  const lines = [
    "## Causal Chain Context",
    "",
    "Related causal trajectories from connected sessions:",
    ""
  ];
  let totalChars = lines.join("\n").length;
  for (const result of results) {
    const line = formatRetrievalResult(result);
    if (totalChars + line.length + 1 > maxChars) break;
    lines.push(line);
    totalChars += line.length + 1;
  }
  if (lines.length <= 4) return null;
  lines.push("");
  return lines.join("\n");
}
async function retrieveCausalChains(options) {
  try {
    const { memoryDir, causalTrajectoryStoreDir, query, sessionKey, config: retrievalConfig } = options;
    const seeds = await searchCausalTrajectories({
      memoryDir,
      causalTrajectoryStoreDir,
      query,
      maxResults: 3,
      sessionKey
    });
    if (seeds.length === 0) return null;
    const chainsDir = resolveChainsDir(memoryDir, causalTrajectoryStoreDir);
    const chainIndex = await readChainIndex(chainsDir);
    if (Object.keys(chainIndex.edges).length === 0) return null;
    const allResults = [];
    for (const seed of seeds) {
      allResults.push({
        trajectoryId: seed.record.trajectoryId,
        direction: "seed",
        depth: 0,
        score: seed.score,
        isCounterfactual: false,
        summary: `[${seed.record.outcomeKind}] ${seed.record.goal} \u2192 ${seed.record.outcomeSummary}`
      });
      const upstream = walkUpstream(
        seed.record.trajectoryId,
        chainIndex,
        retrievalConfig.maxDepth,
        retrievalConfig.counterfactualBoost
      );
      for (const u of upstream) {
        allResults.push({
          trajectoryId: u.trajectoryId,
          direction: "upstream",
          depth: u.depth,
          score: u.score,
          edgeType: u.edgeType,
          edgeConfidence: u.edgeConfidence,
          isCounterfactual: u.isCounterfactual,
          summary: `Depth ${u.depth}: trajectory ${u.trajectoryId.slice(0, 12)}`
        });
      }
      const downstream = walkDownstream(
        seed.record.trajectoryId,
        chainIndex,
        retrievalConfig.maxDepth,
        retrievalConfig.counterfactualBoost
      );
      for (const d of downstream) {
        allResults.push({
          trajectoryId: d.trajectoryId,
          direction: "downstream",
          depth: d.depth,
          score: d.score,
          edgeType: d.edgeType,
          edgeConfidence: d.edgeConfidence,
          isCounterfactual: d.isCounterfactual,
          summary: `Depth ${d.depth}: trajectory ${d.trajectoryId.slice(0, 12)}`
        });
      }
    }
    allResults.sort((a, b) => b.score - a.score);
    return formatCausalRetrievalSection(allResults, retrievalConfig.maxChars);
  } catch (error) {
    log.warn(`[cmc] causal retrieval failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);
    return null;
  }
}
export {
  formatCausalRetrievalSection,
  retrieveCausalChains
};
//# sourceMappingURL=causal-retrieval.js.map