Skip to content
TypeScript
10.4 KB
Raw Blame
/**
 * 흐름 그래프 (PRD §9).
 * buildFlow → FlowGraph(root + 서브에이전트 노드, depth, 최고비용 highlight).
 * renderGraphSvg(카드 트리) / renderGraphHtml(self-contained, 외부 JS/CDN 0, 모든 입력 esc).
 * 노드별 토글(<details>)로 skills·tools·steps·in·log.
 */
import { writeFileSync } from "node:fs";
import { THEME, svgWordmark } from "./brand";
import { tr } from "./i18n";
import type { FlowEdge, FlowGraph, FlowNode, Lang, ParsedTranscript } from "./models";

export function esc(s: unknown): string {
  return String(s ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

// Olympus 알파인 모노크롬 — 다크 위에서 읽히는 절제된 톤. main(메인 루프)=실버.
const HARNESS_COLORS: Record<string, string> = {
  none: "#8b929b", // steel
  superpowers: "#9aa0c8", // periwinkle
  omc: "#7fa8c0", // glacier
  ecc: "#8fb8a6", // sage
  omx: "#c8a87a", // sand
  lazycodex: "#b98a8a", // clay
  main: "#cdd2d8", // silver(snow)
};

export interface BuildFlowOpts {
  harness: string;
  costPerToken?: number;
  success: boolean;
  error?: string | null;
}

export function buildFlow(
  parsed: ParsedTranscript,
  comboId: string,
  taskId: string,
  runIdx: number,
  opts: BuildFlowOpts,
): FlowGraph {
  const cpt = opts.costPerToken ?? 0;
  const events = parsed.events;

  // depth 계산 (parentIdx 체인, 순환 방어)
  const depthOf = (idx: number): number => {
    let d = 0;
    let cur = events[idx]?.parentIdx ?? null;
    const guard = new Set<number>([idx]);
    while (cur !== null && cur !== undefined && !guard.has(cur)) {
      guard.add(cur);
      d += 1;
      cur = events[cur]?.parentIdx ?? null;
    }
    return d;
  };

  const nodes: FlowNode[] = events.map((e) => {
    const tokens = e.inputTokens + e.outputTokens + e.cacheReadTokens + e.cacheCreationTokens;
    const isMain = e.idx === 0;
    return {
      id: `n${e.idx}`,
      label: isMain ? comboId : (e.name ?? `sub ${e.idx}`),
      startMs: e.tsMs,
      endMs: e.endMs,
      durationMs: e.durationMs,
      summaryIn: e.summaryIn,
      summaryOut: e.summaryOut,
      status: opts.success ? e.status : "fail",
      tokens,
      toolCalls: e.toolCalls,
      costUsd: Math.round(tokens * cpt * 1e6) / 1e6,
      depth: depthOf(e.idx),
      highlight: false,
      harness: isMain ? "main" : opts.harness,
      isMain,
      skillsUsed: e.skillsUsed,
      toolsUsed: e.toolsUsed,
      steps: e.steps,
      logText: e.logText,
    };
  });

  // 최고 비용 노드 1개 highlight (cost 우선, 동률/0 이면 tokens) — 결정적
  if (nodes.length) {
    let best = nodes[0]!;
    for (const n of nodes) {
      if (n.costUsd > best.costUsd || (n.costUsd === best.costUsd && n.tokens > best.tokens))
        best = n;
    }
    best.highlight = true;
  }

  const edges: FlowEdge[] = [];
  let order = 1;
  for (const e of events) {
    if (e.parentIdx !== null && e.parentIdx !== undefined) {
      edges.push({ src: `n${e.parentIdx}`, dst: `n${e.idx}`, order: order++ });
    }
  }

  return { comboId, taskId, runIdx, nodes, edges };
}

// ── 렌더링 ───────────────────────────────────────────────
const CARD_W = 230;
const CARD_H = 96;
const H_GAP = 30;
const V_GAP = 70;

export function renderGraphSvg(graph: FlowGraph): string {
  // depth 별 행 배치
  const byDepth = new Map<number, FlowNode[]>();
  for (const n of graph.nodes) {
    const arr = byDepth.get(n.depth) ?? [];
    arr.push(n);
    byDepth.set(n.depth, arr);
  }
  const depths = [...byDepth.keys()].sort((a, b) => a - b);
  const pos = new Map<string, { x: number; y: number }>();
  let maxCols = 1;
  for (const d of depths) maxCols = Math.max(maxCols, byDepth.get(d)!.length);
  const width = Math.max(CARD_W + 40, maxCols * (CARD_W + H_GAP) + H_GAP);

  for (const d of depths) {
    const row = byDepth.get(d)!;
    const rowWidth = row.length * (CARD_W + H_GAP) - H_GAP;
    const startX = (width - rowWidth) / 2;
    row.forEach((n, i) => {
      pos.set(n.id, { x: startX + i * (CARD_W + H_GAP), y: H_GAP + d * (CARD_H + V_GAP) });
    });
  }
  const height = (depths.length || 1) * (CARD_H + V_GAP) + H_GAP;

  const parts: string[] = [];
  parts.push(
    `<svg viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" font-family="ui-sans-serif,system-ui,sans-serif">`,
  );
  parts.push(
    `<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 Z" fill="${THEME.foam}"/></marker></defs>`,
  );

  // edges (곡선 + 호출순서 배지)
  for (const e of graph.edges) {
    const p = pos.get(e.src);
    const c = pos.get(e.dst);
    if (!p || !c) continue;
    const x1 = p.x + CARD_W / 2;
    const y1 = p.y + CARD_H;
    const x2 = c.x + CARD_W / 2;
    const y2 = c.y;
    const my = (y1 + y2) / 2;
    parts.push(
      `<path d="M${x1},${y1} C${x1},${my} ${x2},${my} ${x2},${y2}" fill="none" stroke="${THEME.foam}" stroke-width="1.5" marker-end="url(#arrow)"/>`,
    );
    const bx = (x1 + x2) / 2;
    parts.push(
      `<circle cx="${bx}" cy="${my}" r="9" fill="${THEME.hull}" stroke="${THEME.foam}"/><text x="${bx}" y="${my + 3}" font-size="10" text-anchor="middle" fill="${THEME.foam}">${e.order}</text>`,
    );
  }

  // nodes (카드)
  for (const n of graph.nodes) {
    const p = pos.get(n.id)!;
    const color = HARNESS_COLORS[n.harness] ?? "#8b929b";
    const stroke = n.highlight ? THEME.rope : THEME.grid;
    const sw = n.highlight ? 3 : 1;
    const tag = n.isMain
      ? tr("en", "tag_main")
      : `${tr("en", "tag_sub")}·${esc(n.harness).toUpperCase()}`;
    const statusMark = n.status === "fail" ? "✗" : n.highlight ? "★" : "";
    const tokK = (n.tokens / 1000).toFixed(1);
    const barW = Math.min(CARD_W - 24, Math.max(2, (n.tokens / 200000) * (CARD_W - 24)));
    parts.push("<g>");
    parts.push(
      `<rect x="${p.x}" y="${p.y}" rx="10" width="${CARD_W}" height="${CARD_H}" fill="${THEME.hull}" stroke="${stroke}" stroke-width="${sw}"/>`,
    );
    parts.push(
      `<rect x="${p.x}" y="${p.y}" rx="10" width="${CARD_W}" height="22" fill="${color}"/>`,
    );
    parts.push(
      `<text x="${p.x + 10}" y="${p.y + 15}" font-size="11" font-weight="600" fill="${THEME.seaDeep}">${esc(tag)} ${statusMark}</text>`,
    );
    parts.push(
      `<text x="${p.x + 10}" y="${p.y + 40}" font-size="11" fill="${THEME.sail}">${esc(truncateLabel(n.label))}</text>`,
    );
    parts.push(
      `<text x="${p.x + 10}" y="${p.y + 58}" font-size="10" fill="${THEME.mist}">⏱${(n.durationMs / 1000).toFixed(1)}s · ${tokK}k tok · $${n.costUsd.toFixed(4)}</text>`,
    );
    parts.push(
      `<rect x="${p.x + 10}" y="${p.y + 70}" width="${CARD_W - 24}" height="6" rx="3" fill="#23272d"/>`,
    );
    parts.push(
      `<rect x="${p.x + 10}" y="${p.y + 70}" width="${barW}" height="6" rx="3" fill="${color}"/>`,
    );
    parts.push("</g>");
  }
  parts.push("</svg>");
  return parts.join("");
}

function truncateLabel(s: string): string {
  return s.length > 32 ? `${s.slice(0, 31)}…` : s;
}

export const DETAILS_CSS = `
.theseus-details{margin:4px 0;border:1px solid ${THEME.grid};border-radius:8px;background:${THEME.hull}}
.theseus-details>summary{cursor:pointer;padding:6px 10px;font-size:13px;font-weight:600;color:${THEME.sail};list-style:none}
.theseus-details>summary::-webkit-details-marker{display:none}
.theseus-details>summary::before{content:'▸ ';color:${THEME.foam}}
.theseus-details[open]>summary::before{content:'▾ '}
.theseus-details .body{padding:6px 12px;font-size:12px;color:${THEME.ink};border-top:1px solid ${THEME.grid}}
.theseus-details .body div{margin:3px 0;word-break:break-word}
.theseus-details .k{color:${THEME.foam};font-weight:600;margin-right:4px}
`;

function row(label: string, value: string): string {
  if (!value) return "";
  return `<div><span class="k">${esc(label)}:</span>${esc(value)}</div>`;
}

/** 노드별 토글(네이티브 details, 외부 JS 0) */
export function nodeDetailsBlock(node: FlowNode, lang: Lang): string {
  const body = [
    row(tr(lang, "node_skills"), node.skillsUsed.join(", ")),
    row(tr(lang, "node_tools"), node.toolsUsed.join(", ")),
    row(tr(lang, "node_steps"), node.steps.slice(0, 30).join(" → ")),
    row(tr(lang, "node_input"), node.summaryIn),
    row(tr(lang, "node_log"), node.logText),
  ].join("");
  return `<details class="theseus-details"><summary>${esc(node.label)} (${esc(node.harness)})</summary><div class="body">${body}</div></details>`;
}

/** graph.html / report.html 공용 — 한 그래프 섹션(인라인 SVG + 노드 토글) */
export function graphSection(graph: FlowGraph, lang: Lang): string {
  const svg = renderGraphSvg(graph);
  const toggles = graph.nodes.map((n) => nodeDetailsBlock(n, lang)).join("");
  return `<div class="theseus-graph"><h3>${esc(graph.comboId)} — ${esc(graph.taskId)} #${graph.runIdx}</h3><div class="svg-wrap">${svg}</div>${toggles}</div>`;
}

export function renderGraphHtml(graphs: FlowGraph[], path: string, opts: { language: Lang }): void {
  const lang = opts.language;
  const sections = graphs.map((g) => graphSection(g, lang)).join("\n");
  const html = `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(tr(lang, "graph_title"))}</title>
<style>
body{font-family:ui-sans-serif,system-ui,sans-serif;background:${THEME.sea};color:${THEME.ink};margin:0;padding:20px}
h1{font-size:20px;color:${THEME.sail}}
.theseus-hero{background:linear-gradient(135deg,${THEME.hull},${THEME.seaDeep});color:${THEME.sail};border:1px solid ${THEME.grid};border-radius:12px;padding:14px 18px;margin-bottom:16px;display:flex;align-items:center;gap:14px}
.theseus-hero .sub{font-size:13px;color:${THEME.mist}}
.theseus-graph{background:${THEME.hull};border:1px solid ${THEME.grid};border-radius:12px;padding:16px;margin:16px 0;overflow:auto}
.theseus-graph h3{font-size:14px;margin:0 0 10px;color:${THEME.sail}}
.svg-wrap{overflow:auto}
${DETAILS_CSS}
</style></head><body>
<header class="theseus-hero">${svgWordmark()}<div class="sub">${esc(tr(lang, "graph_title"))}</div></header>
${sections}
</body></html>`;
  writeFileSync(path, html);
}

export function writeFlowJson(graph: FlowGraph, path: string): void {
  writeFileSync(path, JSON.stringify(graph, null, 2));
}