TypeScript
PRD v2: interactive TUI, 4 visualization modes, verify, branding, 3 harnesses
Claudef4a92d90d844
diff --git a/NOTES.md b/NOTES.mdindex 334134e..e4be60d 100644--- a/NOTES.md+++ b/NOTES.md@@ -2,6 +2,31 @@비전문 감시자용 기록. 용어 최소화, AS-IS → TO-BE.+## 2026-06-24 (2) — TUI·시각화·브랜딩·하네스 확장 (PRD v2)++**AS-IS**: 비교는 되지만 결과를 보는 길이 좁았다 — HTML 파일 경로만 출력, TUI 는 정적 표,+하네스는 5종, 브랜드/철학 없음, "각 조합이 서브에이전트를 실제로 부르는지" 확인할 방법 없음.++**TO-BE**:+- **보는 방법 4가지** (`--view`): 파일(inline) · 브라우저 팝업(open) · 로컬 서버(serve, 모든 run 목록을+ localhost 에서) · 터미널 그림(term, 막대 차트 + 서브에이전트 트리, 브라우저 불필요).+- **인터랙티브 TUI**: 방향키로 run → 조합 → 상세(흐름 트리) 탐색. ink 없으면 표로 자동 폴백.+- **각 조합 점검** (`theseus verify`): 조합마다 위임 과제를 한 번 돌려 서브에이전트 호출이+ 실제로 잡히는지 표로 보여준다(트리형은 fan-out 필요, 단일 루프는 flat 정상).+- **하네스 3종 추가**: oh-my-openagent(omo), ponytail(코드 최소화), mattpocock(스킬팩). 각자 맞는+ 에이전트에만 적용되고, 멀티모델 에이전트는 룰을 작업 폴더에 per-run 으로 깔아 전역 오염이 없다.+- **브랜드 "테세우스의 배"**: CLI 아스키 로고, 리포트 SVG 워드마크 + 항해 테마 + 철학 푸터, 산점도에+ 파레토 경계 표시. 철학: 부품(모델·에이전트·하네스)을 갈아끼워도 배는 당신 것 — 어떤 교체가 항해를+ 실제로 바꾸는지 보여준다(리더보드 아님).+- **설치 정리**: `install --check`(상태표) · `install all` · 설치 후 자동 검증.++검증: 타입체크·린트·테스트·빌드 통과(테스트 60+개). report.html 은 여전히 외부 JS/CDN 0(self-contained).+신규 하네스/뷰/verify/브랜딩 모두 오프라인 mock 으로 end-to-end 확인.++---++## 2026-06-24 (1) — theseus 초기 구현 (TypeScript)+## 2026-06-24 — theseus 초기 구현 (TypeScript)**AS-IS**: 빈 저장소(LICENSE 만). 비교 도구가 없어, 어떤 모델·도구 조합이 내 과제에 맞는지diff --git a/README.md b/README.mdindex ca5daf4..378590a 100644--- a/README.md+++ b/README.md@@ -1,88 +1,141 @@+```+ _ _+ | |_| |__ ___ ___ ___ _ _ ___ ⛵+ | __| '_ \ / _ \/ __|/ _ \ | | / __| ~~~~~~+ | |_| | | | __/\__ \ __/ |_| \__ \ theseus+ \__|_| |_|\___||___/\___|\__,_|___/ ~~~~~~~~~~+```+# theseus-> Compare **model (L0) × agent (L1) × harness (L2)** combinations on *your own* local tasks.+> **Swap the model, the agent, the harness — plank by plank. The ship is still yours.+> theseus shows you which planks actually change the voyage.**theseus is a comparison CLI (a TypeScript reimplementation of the **dike** product spec). It runs the-same task subset across combinations and visualizes, side by side, each combination's **accuracy, cost,-time, tool calls, and subagent call flow** — so you can understand the flow and pick the trade-off that-fits you. It is **not** a leaderboard and produces **no single composite ranking** by default.+**same task subset** across **model (L0) × agent (L1) × harness (L2)** combinations and lays out, side by+side, each combination's **accuracy · cost · time · tool calls · subagent call flow** — so you understand+the flow and pick the trade-off that fits *you*. It is **not** a leaderboard and produces **no single+score** by default; it recommends per-perspective winners and marks the cost/accuracy **Pareto frontier**.-Outputs for every run:-- structured data — `results.jsonl` (source of truth) + `theseus.sqlite` (query cache, optional)-- a human-readable, **self-contained** `report.html` (no external JS/CDN)-- a subagent **flow graph** `graph.html` (inline SVG + native toggles)+Every run emits:+- structured data — `results.jsonl` (source of truth) + `theseus.sqlite` (optional query cache)+- a **self-contained** `report.html` (no external JS/CDN) with the nautical theme, scatter + Pareto frontier+- a subagent **flow graph** `graph.html` (inline SVG card-tree + native toggles)## Install```bashpnpm install # or npm installpnpm build # → dist/cli.js-npm link # exposes `theseus` (or: node dist/cli.js …)+npm link # exposes `theseus` (or run: node dist/cli.js …)```-Node ≥ 20, ESM. `better-sqlite3` and `ink` are *optional* — if their native build fails, theseus-degrades gracefully (JSONL stays the source of truth; the TUI falls back to a table).+Node ≥ 20, ESM. `better-sqlite3`, `ink`, and `react` are **optional** — if a native build or the TUI deps+are missing, theseus degrades gracefully (JSONL stays the source of truth; the TUI falls back to a table).-## Usage--Multi-select flags are comma-separated; unselected = skipped.+## Quick start (offline, deterministic)```bash-# shorthand (no subcommand → compare)-theseus --model opus4.8,gpt5.5 --agent cc,codex,opencode --harness none,superpowers--# subcommands-theseus compare --model gpt5.5 --agent codex,opencode,hermes --harness none --bench subagent-theseus results [--run <id>]-theseus install <cc|codex|opencode|openclaw|hermes|tb|superpowers|omc|ecc|omx|lazycodex>-theseus doctor-theseus tui [--out runs] [--rich] [--open]+theseus --model opus4.8,gpt5.5 --agent cc,opencode,codex \+ --harness none,omc,omo,ponytail --bench subagent --tasks 4 --runner mock -L en```+## The matrix++### L0 models+`opus4.8 / 4.7 / 4.6`, `sonnet4.6 / 4.5`, `haiku4.5`, `fable5` (claude family) ·+`gpt5-codex` (account default), `gpt5.5`, `gpt5.1-codex` (gpt family).+### L1 agents+| agent | binary | model families | harnesses |+|---|---|---|---|+| `cc` | claude | claude | none, superpowers, omc, ecc, ponytail, mattpocock |+| `codex` | codex | gpt | none, superpowers, omx, lazycodex, omo, ponytail |+| `opencode` | opencode | claude + gpt | none, omo, ponytail, mattpocock |+| `openclaw` | openclaw | claude + gpt | none, ponytail |+| `hermes` | hermes | claude + gpt | none, ponytail |++`opencode/openclaw/hermes` are model-agnostic; theseus passes the model as `provider/id` (`anthropic/…`,+`openai/…`; `default` omitted).++### L2 harnesses+| harness | type | agents |+|---|---|---|+| `none` | baseline | all |+| `superpowers` | shared | cc, codex |+| `omc` / `ecc` | orchestration | cc |+| `omx` / `lazycodex` | orchestration | codex |+| `omo` (oh-my-openagent) | orchestration | opencode, codex |+| `ponytail` | minimalism rule-pack | all |+| `mattpocock` | skills pack | cc, codex, opencode |++Incompatible combos are **excluded with a reason** (never silently dropped).++## Commands-`cc` (Claude Code, claude) · `codex` (Codex CLI, gpt) · `opencode` · `openclaw` · `hermes`.-The last three are model-agnostic (accept either family; theseus passes the model as `provider/id`).+```bash+theseus [compare] --model … --agent … --harness … # default command+theseus verify --model … --agent … --harness … # per-combo subagent-call capture check+theseus results [--run <id>] # show a recorded run+theseus tui [--out runs] [--open] [--rich] # interactive ink UI (table fallback)+theseus install <cc|codex|opencode|openclaw|hermes|tb|<harness>|all>+theseus install --check # status table+theseus doctor # environment self-diagnosis+```-Try it fully offline with the deterministic mock runner:+### Visualization modes — `--view`+| mode | what it does |+|---|---|+| `inline` (default) | write self-contained `report.html` + `graph.html`, print paths |+| `open` | also pop the report open in your browser |+| `serve` | start a localhost server (`--port`, default 7777) with a live index of all runs |+| `term` | render bar charts (accuracy/tokens/cost/subagents) + an ANSI **flow tree** in the terminal — no browser |```bash-theseus --model opus4.8,gpt5.5 --agent cc,codex --harness none,omc \- --bench subagent --tasks 4 --runner mock -L en+theseus --model opus4.8 --agent cc --harness none,omc --bench subagent --runner mock --view term+theseus --model opus4.8 --agent cc --harness none --bench subagent --runner mock --view serve --port 7777```### Key flags--`--model --agent --harness` · `--bench` (default `terminal-bench-v2`) · `--tasks` (20) · `--runs` (1)-· `--seed` · `--runner` (auto|mock|cc|codex|tb) · `--concurrency` (4) · `--timeout` (600)-· `--out` (runs) · `--judge` (none|heuristic|cc) · `--score` · `--balanced` · `--dry-run`-· `--yes/-y` · `--language/-L` (kr default; en).+`--bench` (default `terminal-bench-v2`) · `--tasks` (20) · `--runs` (1) · `--seed` · `--runner`+(auto|mock|cc|codex|opencode|openclaw|hermes|tb) · `--concurrency` (4) · `--timeout` (600) · `--out` (runs)+· `--judge` (none|heuristic|cc) · `--score` · `--balanced` · `--dry-run` · `--yes/-y` · `--view` · `--port`+· `--no-logo` · `--language/-L` (kr default; en).## Benches--- **terminal-bench-v2** — external Terminal-Bench (delegated; Docker). Falls back to mock if `tb` absent.+- **terminal-bench-v2** — external Terminal-Bench (Docker; delegated). Falls back to mock if `tb` absent.- **local** — built-in, file-verified happy-path tasks (no Docker).-- **subagent** — built-in hard tasks (`subagent-101…106`) whose verifiers **recompute the answer from the- input fixtures** (no hardcoded golden → no drift). Each carries one agent-agnostic delegation hint to- elicit real subagent fan-out in headless mode.--## Invariants (do not break — see PRD §20)--1. Sort base key `subagentCount → totalTokens → wallTimeMs` (only in `metrics.sortCombos`).-2. No single composite score (perspective recommendations instead; `--score` is opt-in).-3. Determinism: same `(bench, tasks, seed)` → same subset (sha256, no `Math.random`).-4. fail-soft: a failed combo/task never blocks the run and is never silently dropped. `success ≠ resolved`.-5. `null = uncollected` (never 0 / guessed).-6. Runners are not reimplemented: tb/codex are called behind adapters; mock fallback (+banner) when absent.-7. Self-contained HTML: no external JS/CDN, every external input escaped.-8. Harness per-run: cc=`--plugin-dir`, codex=`CODEX_HOME` isolation. No global pollution.-9. recompute-in-verify for subagent tasks.-10. i18n: only display strings, kr fallback.+- **subagent** — built-in hard tasks (`subagent-101…106`); verifiers **recompute the answer from the input+ fixtures** (no hardcoded golden → no drift). Each carries one agent-agnostic delegation hint.-## Development+## Verifying subagent flow capture+`theseus verify` runs each valid combo once on a delegation-heavy task and reports whether subagent calls+were captured:++```+combo subagents maxDepth captured?+cc+opus4.8+omc 4 1 ✓ captured+opencode+opus4.8+omo 3 0 ✓ captured+codex+gpt5.5+none 0 0 — flat (expected)+```++Tree-capable combos (cc + orchestration, opencode + omo) must fan out; single-loop combos (codex, `none`,+hermes) report `flat (expected)`. Defaults to the offline mock runner; real runners need `--yes`.++## Philosophy & branding++See [docs/brand.md](docs/brand.md) — the **Ship of Theseus**: every part is swappable, the vessel persists.+The job of theseus is to reveal *which swap actually changed the voyage*, not to crown a winner.++## Invariants (PRD §20)+Sort key `subagentCount → totalTokens → wallTimeMs` · no single score (perspectives + Pareto) ·+determinism (sha256 subset, no `Math.random`) · fail-soft (no silent drops; `success ≠ resolved`) ·+`null = uncollected` · runners not reimplemented (mock fallback + banner) · self-contained HTML ·+harness per-run (no global pollution) · recompute-in-verify · i18n (display strings only, kr fallback).++## Development```bashpnpm typecheck && pnpm lint && pnpm test && pnpm build```--See `docs/` for architecture, registry, transcript schema, and acceptance criteria.+See `docs/` for architecture, registry, transcript schema, visualization, brand, and acceptance criteria.diff --git a/docs/brand.md b/docs/brand.mdnew file mode 100644index 0000000..3ab1f8c--- /dev/null+++ b/docs/brand.md@@ -0,0 +1,46 @@+# Brand & visual style — Ship of Theseus++## Philosophy++> Swap the model, the agent, the harness — plank by plank. The ship is still yours. theseus shows you+> which planks actually change the voyage.++The Ship of Theseus paradox (replace every plank and is it the same ship?) is the product thesis: a+workflow is a vessel whose parts — model (L0), agent (L1), harness (L2) — are all swappable. theseus+doesn't crown a winner; it makes the **consequence of each swap legible** (accuracy, cost, time, tool+calls, subagent flow) so you choose your own trade-off. This is the North Star: *understand the flow,+then decide* — never a leaderboard.++Single source of truth: `src/brand.ts` (`THEME`, `PHILOSOPHY`, `TAGLINE`, `logoBanner`, `svgWordmark`,+`wavePattern`).++## Palette (nautical / cartographic)++| token | hex | use |+|---|---|---|+| `sea` | `#0b2942` | deep background (hero, serve index) |+| `seaDeep` | `#071d30` | deepest background |+| `hull` | `#15324f` | cards / headers |+| `sail` | `#f5f1e6` | light text on sea |+| `rope` | `#c08a3e` | accent · highlight · Pareto frontier · section rules |+| `foam` | `#7fb2c9` | secondary accent · wave strokes |+| `ink` | `#0f172a` | body text |+| `mist` | `#64748b` | muted text |+| `grid` | `#e2e8f0` | borders / grid |+| `ok` / `danger` | `#2e8b6f` / `#c0392b` | success / failure |++## Visual style (그림체)++Nautical/cartographic: flow nodes read as **vessels** on routes, edges as **routes** with order badges,+a faint **wave/grid** motif in SVG backgrounds. Highlights use a rope-gold ring (★); failures an ✗.++## Logo++- **CLI**: ASCII-art ship banner + tagline, printed on `compare`/`tui` start. Suppress with `--no-logo`.+- **HTML**: inline SVG wordmark (`svgWordmark()`) in a sea-colored hero header; a philosophy line in the+ report footer (`⚓ Ship of Theseus — …`). Fully self-contained (no external fonts/images).++## Self-contained rule++Branding must never introduce external JS/CDN/fonts. The only permitted external reference in output HTML+is the SVG namespace URI `http://www.w3.org/2000/svg`. Enforced by the UX6 regression test.diff --git a/docs/registry.md b/docs/registry.mdindex c40119f..530143b 100644--- a/docs/registry.md+++ b/docs/registry.md@@ -32,17 +32,24 @@ the `none` harness. Real invocations:## L2 harnesses-| harness | agents | orchestration |-|---|---|---|-| none | cc, codex | no |-| superpowers | cc, codex | yes |-| omc, ecc | cc only | yes |-| omx, lazycodex | codex only | yes |+| harness | agents | orchestration | apply mechanism |+|---|---|---|---|+| none | all | no | — |+| superpowers | cc, codex | yes | cc `--plugin-dir` / codex `CODEX_HOME` |+| omc, ecc | cc only | yes | cc `--plugin-dir` |+| omx, lazycodex | codex only | yes | codex `CODEX_HOME` |+| omo (oh-my-openagent) | opencode, codex | yes | codex `CODEX_HOME` / opencode work-dir rules |+| ponytail | all | no | cc `--plugin-dir` / multi-model work-dir rules |+| mattpocock | cc, codex, opencode | no | cc `--plugin-dir` / opencode work-dir rules |++Multi-model agents (opencode/openclaw/hermes) get harnesses via **per-run materialization**: the harness's+rules (`AGENTS.md`/skills) are copied into the run's work dir from a cache (`~/.cache/theseus/harness-rules/<h>`).+No global pollution. `install <h>` builds the cache; absent → falls back to base `none`.## Compatibility rules (combos.expand)-1. cc ↔ claude models only; codex ↔ gpt models only.-2. omc/ecc are cc-only; omx/lazycodex are codex-only; superpowers is shared; none always allowed.+1. cc ↔ claude models only; codex ↔ gpt models only; opencode/openclaw/hermes ↔ any family.+2. Each harness lists its compatible agents (`HARNESSES[h].agents`); `none` is always allowed.3. `comboId = ${agent}+${model}+${harness}` (harness is the last `+` segment — safe even if the model id contains `+`).4. Incompatible combos are excluded **with a reason** (surfaced in meta.json / report) — never silently dropped.diff --git a/docs/visualization.md b/docs/visualization.mdnew file mode 100644index 0000000..20ec464--- /dev/null+++ b/docs/visualization.md@@ -0,0 +1,35 @@+# Visualization++One data model (`ComboMetrics` from `metrics.ts`, `FlowGraph` from `flow.ts`) drives every renderer:+the HTML report, the terminal renderer, and the TUI. Pick the delivery with `--view`.++## Delivery modes (`--view`)++| mode | module | behavior |+|---|---|---|+| `inline` (default) | `report.ts` / `flow.ts` | writes self-contained `report.html` + `graph.html`; prints paths |+| `open` | `viz/open.ts` | inline + opens `report.html` in the browser (`xdg-open`/`open`/`start`) |+| `serve` | `viz/serve.ts` | `node:http` server (no deps) at `localhost:<--port>` (default 7777) with a live run index; path-traversal guarded; served pages are the same self-contained files |+| `term` | `viz/terminal.ts` | ANSI bar charts (accuracy / total tok / cost / subagents), perspective picks, and an indented **flow tree** — no browser |++## Report (`report.html`) — self-contained, sections++0 best-by-perspective · 0.5 composite score (opt-in) · 1 accuracy · 2 efficiency (with `best` highlights)+· 3 **cost-performance scatter with Pareto frontier** (frontier points ringed in rope-gold, dashed+connector; `<title>` hovers) · 4 task pass/fail matrix · 5 flow graphs (+ node toggles) · 6 failure causes+· 7 uncollected metrics. Themed hero (SVG wordmark) + philosophy footer. **No external JS/CDN.**++## Flow graph (`graph.html`)++`buildFlow()` → `FlowGraph` (root + subagent nodes, depth via `parentIdx`, deterministic highest-cost+highlight). `renderGraphSvg()` draws a card tree (gradient header, MAIN LOOP / SUB·<harness> tags,+⏱/tokens/cost, token bar, curved parent→child arrows with order badges). `nodeDetailsBlock()` adds native+`<details>` toggles (skills / tools / steps / input / log) — zero JS. The terminal `renderFlowTree()`+renders the same graph as a box-drawing tree.++## TUI (`tui/inkApp.ts`)++Interactive ink app: **runs list → combo table → combo detail** (metrics + perspective picks + flow tree+loaded from `flow.json`). Arrow keys / enter / ← back / q quit. JSX-free (`React.createElement`) and loaded+via lazy dynamic import, so ink/react stay external to the bundle. Non-TTY, `--rich`, or missing ink →+cli-table3 fallback (`tui.ts`).diff --git a/src/brand.ts b/src/brand.tsnew file mode 100644index 0000000..2296fa9--- /dev/null+++ b/src/brand.ts@@ -0,0 +1,73 @@+/**+ * 브랜딩 (PRD v2 §W6) — "Ship of Theseus".+ * 철학: 모델·에이전트·하네스를 널빤지처럼 갈아끼워도 배(워크플로)는 당신의 것.+ * theseus 는 "어떤 널빤지가 항해를 실제로 바꾸는지" 보여준다(리더보드가 아니라 흐름 이해).+ * 단일 진실원천: CLI ASCII 로고 · HTML SVG 워드마크 · 테마 팔레트 · 철학 문구.+ */+import pc from "picocolors";+import type { Lang } from "./models";++// ── 테마 팔레트(항해/해도 모티프) ───────────────────────+export const THEME = {+ sea: "#0b2942", // 深海 배경+ seaDeep: "#071d30",+ hull: "#15324f", // 선체(카드/헤더)+ sail: "#f5f1e6", // 돛(밝은 배경/텍스트)+ rope: "#c08a3e", // 로프(강조·하이라이트)+ foam: "#7fb2c9", // 물거품(보조 강조)+ ink: "#0f172a", // 본문 텍스트+ mist: "#64748b", // 흐린 텍스트+ grid: "#e2e8f0", // 격자/테두리+ ok: "#2e8b6f", // 성공+ danger: "#c0392b", // 실패+ best: "#dcfce7", // best 강조 배경+} as const;++export const PHILOSOPHY = {+ en: "Swap the model, the agent, the harness — plank by plank. The ship is still yours. theseus shows you which planks actually change the voyage.",+ kr: "모델도, 에이전트도, 하네스도 — 널빤지처럼 갈아끼운다. 그래도 배는 당신의 것. theseus 는 어떤 널빤지가 항해를 실제로 바꾸는지 보여준다.",+} as const;++export const TAGLINE = {+ en: "compare model × agent × harness on your own tasks",+ kr: "내 과제로 모델 × 에이전트 × 하네스 비교",+} as const;++export function philosophy(lang: Lang): string {+ return PHILOSOPHY[lang] ?? PHILOSOPHY.kr;+}++// ── CLI ASCII 로고 ───────────────────────────────────────+const SHIP = String.raw`+ _ _+ | |_| |__ ___ ___ ___ _ _ ___ ⛵+ | __| '_ \ / _ \/ __|/ _ \ | | / __| ~~~~~~+ | |_| | | | __/\__ \ __/ |_| \__ \ theseus+ \__|_| |_|\___||___/\___|\__,_|___/ ~~~~~~~~~~`;++/** 컬러 ASCII 배너 + 태그라인. --no-logo 면 호출하지 않음. */+export function logoBanner(lang: Lang): string {+ const ship = pc.cyan(SHIP);+ const tag = pc.dim(TAGLINE[lang] ?? TAGLINE.kr);+ return `${ship}\n ${tag}\n`;+}++// ── HTML SVG 워드마크(self-contained, 인라인) ───────────+/** report/graph 헤더용 인라인 SVG 워드마크(외부 리소스 0). */+export function svgWordmark(): string {+ const { sea, sail, rope, foam } = THEME;+ return `<svg width="190" height="40" viewBox="0 0 190 40" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="theseus">+<rect width="190" height="40" rx="8" fill="${sea}"/>+<path d="M14 27 h22 l-4 6 h-14 z" fill="${sail}"/>+<path d="M25 9 v16 M25 11 l11 11 h-11 z" fill="${rope}" stroke="${rope}" stroke-width="1.4"/>+<path d="M8 33 q6 -3 12 0 t12 0" fill="none" stroke="${foam}" stroke-width="1.5" opacity="0.8"/>+<text x="48" y="26" font-family="ui-monospace,monospace" font-size="18" font-weight="700" fill="${sail}">theseus</text>+</svg>`;+}++/** SVG 배경용 잔잔한 파도 격자(흐름 그래프 캔버스 장식). 매우 옅게. */+export function wavePattern(id = "theseus-waves"): string {+ return `<defs><pattern id="${id}" width="40" height="20" patternUnits="userSpaceOnUse">+<path d="M0 14 q10 -8 20 0 t20 0" fill="none" stroke="${THEME.foam}" stroke-width="1" opacity="0.12"/>+</pattern></defs>`;+}diff --git a/src/cli.ts b/src/cli.tsindex df14058..5f1ff2c 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -6,6 +6,7 @@ import Table from "cli-table3";import { Command } from "commander";import pc from "picocolors";import { listLocalBenches } from "./benches/index";+import { logoBanner } from "./brand";import { expand } from "./combos";import { harnessStatus } from "./harness";import { type Translator, normalizeLang, translator } from "./i18n";@@ -20,6 +21,10 @@ import { listRuns, loadMeta, loadResults } from "./recorder";import { getRunner } from "./runners/registry";import { commandExists } from "./runners/util";import { runTui } from "./tui";+import { verifyCombos } from "./verify";+import { openInBrowser } from "./viz/open";+import { serveRuns } from "./viz/serve";+import { renderTerminal } from "./viz/terminal";function splitList(s: string | undefined): string[] {if (!s) return [];@@ -46,14 +51,26 @@ function toRunOptions(o: any): RunOptions {score: Boolean(o.score),balanced: Boolean(o.balanced),language: normalizeLang(o.language),+ view: normalizeView(o.view),+ port: Number.parseInt(o.port ?? "7777", 10),};}+function normalizeView(v: string | undefined): "inline" | "open" | "serve" | "term" {+ const s = (v ?? "inline").toLowerCase();+ if (s === "open" || s === "serve" || s === "term") return s;+ return "inline";+}+function addCompareOptions(cmd: Command): Command {return cmd.option("--model <list>", "L0 models (comma-separated)").option("--agent <list>", "L1 agents: cc,codex,opencode,openclaw,hermes")- .option("--harness <list>", "L2 harnesses: none,superpowers,omc,ecc,omx,lazycodex", "none")+ .option(+ "--harness <list>",+ "L2 harnesses: none,superpowers,omc,ecc,omx,lazycodex,omo,ponytail,mattpocock",+ "none",+ ).option("--bench <name>", "benchmark", "terminal-bench-v2").option("--tasks <n>", "task subset size", "20").option("--runs <n>", "runs per task", "1")@@ -67,6 +84,9 @@ function addCompareOptions(cmd: Command): Command {.option("--balanced", "difficulty-balanced subset", false).option("--dry-run", "plan only, do not execute", false).option("-y, --yes", "bypass real-runner gate", false)+ .option("--view <mode>", "visualization: inline|open|serve|term", "inline")+ .option("--port <n>", "port for --view serve", "7777")+ .option("--no-logo", "suppress the ASCII logo banner").option("-L, --language <lang>", "en|kr", "kr");}@@ -139,7 +159,8 @@ async function compareAction(o: any): Promise<void> {const opts = toRunOptions(o);const lang = opts.language;const t = translator(lang);- console.log(pc.bold(pc.cyan(t("app_tagline"))));+ if (o.logo !== false) console.log(logoBanner(lang));+ else console.log(pc.bold(pc.cyan(t("app_tagline"))));if (!opts.models.length || !opts.agents.length) {console.log(pc.red(`\n${t("no_models")}`));@@ -159,10 +180,40 @@ async function compareAction(o: any): Promise<void> {const res = await execute(opts);if (res.mock) console.log(pc.yellow(`\n${t("mock_banner")}`));- printResultsTable(t, lang, res.metrics);++ // --view term: ANSI 차트 + 흐름 트리(브라우저 불필요)+ if (opts.view === "term") {+ console.log(renderTerminal(res.metrics, res.graphs, lang));+ } else {+ printResultsTable(t, lang, res.metrics);+ }+console.log(`\n${t("run_complete")} — ${t("run_id")}: ${pc.bold(res.runId)}`);console.log(` ${t("report_path")}: ${res.reportPath}`);console.log(` ${t("graph_path")}: ${res.graphPath}`);++ // --view open: 브라우저 팝업+ if (opts.view === "open") {+ openInBrowser(res.reportPath);+ console.log(pc.dim(` ${t("opening_browser")}`));+ }+ // --view serve: 로컬 서버(Ctrl-C 까지 유지)+ if (opts.view === "serve") {+ try {+ const handle = await serveRuns(opts.outDir, opts.port ?? 7777);+ console.log(+ `\n ${pc.green("serving")} ${pc.bold(handle.url)} ${pc.dim("(Ctrl-C to stop)")}`,+ );+ await new Promise<void>((resolve) => {+ process.on("SIGINT", () => {+ handle.close();+ resolve();+ });+ });+ } catch (e) {+ console.log(pc.red(`serve failed: ${(e as Error).message}`));+ }+ }}function buildProgram(): Command {@@ -172,12 +223,11 @@ function buildProgram(): Command {.description("compare model × agent × harness on your own tasks").version("0.1.0");- // 단축형: 서브커맨드 없이 플래그만 → compare- addCompareOptions(program).action(compareAction);-- addCompareOptions(program.command("compare").description("run an N-combo comparison")).action(- compareAction,- );+ // compare = 기본 커맨드(isDefault). 서브커맨드 없이 플래그만 주면 compare 로 동작.+ // 루트에 옵션을 달지 않아 서브커맨드(tui/results)의 -L 등과 충돌하지 않음.+ addCompareOptions(+ program.command("compare", { isDefault: true }).description("run an N-combo comparison"),+ ).action(compareAction);program.command("results")@@ -202,9 +252,10 @@ function buildProgram(): Command {});program- .command("install <component>")- .description("install agent/harness/bench (cc|codex|opencode|openclaw|hermes|tb|<harness>)")- .action((component) => runInstall(component));+ .command("install [component]")+ .description("install agent/harness/bench (cc|codex|opencode|openclaw|hermes|tb|<harness>|all)")+ .option("--check", "show install status for all agents/harnesses", false)+ .action((component, o) => runInstall(o.check ? "--check" : (component ?? "")));program.command("doctor")@@ -221,7 +272,16 @@ function buildProgram(): Command {table.push(["tb", commandExists("tb") ? pc.green("available") : pc.red("missing")]);table.push(["docker", commandExists("docker") ? pc.green("available") : pc.red("missing")]);table.push(["mock runner", pc.green("always available")]);- for (const h of ["superpowers", "omc", "ecc", "omx", "lazycodex"])+ for (const h of [+ "superpowers",+ "omc",+ "ecc",+ "omx",+ "lazycodex",+ "omo",+ "ponytail",+ "mattpocock",+ ])table.push([`harness:${h}`, harnessStatus(h)]);table.push(["local benches", listLocalBenches().join(", ")]);console.log(table.toString());@@ -251,6 +311,57 @@ function buildProgram(): Command {}),);+ program+ .command("verify")+ .description("check that each combo's subagent calls are actually captured")+ .option("--model <list>", "L0 models")+ .option("--agent <list>", "L1 agents")+ .option("--harness <list>", "L2 harnesses", "none")+ .option("--runner <name>", "auto|mock|cc|codex|opencode|openclaw|hermes", "mock")+ .option("--seed <n>", "seed", "0")+ .option("--timeout <s>", "per-task timeout seconds", "120")+ .option("-y, --yes", "allow real runner (not mock)", false)+ .option("-L, --language <lang>", "en|kr", "kr")+ .action(async (o) => {+ const lang = normalizeLang(o.language);+ const t = translator(lang);+ const models = splitList(o.model);+ const agents = splitList(o.agent);+ if (!models.length || !agents.length) {+ console.log(pc.red(t("no_models")));+ process.exitCode = 1;+ return;+ }+ const runner = o.runner ?? "mock";+ if (runner !== "mock" && !o.yes) {+ console.log(pc.red(t("gate_blocked")));+ process.exitCode = 1;+ return;+ }+ const rows = await verifyCombos({+ models,+ agents,+ harnesses: splitList(o.harness).length ? splitList(o.harness) : ["none"],+ runner,+ seed: Number.parseInt(o.seed ?? "0", 10),+ timeoutS: Number.parseInt(o.timeout ?? "120", 10),+ });+ const table = new Table({ head: ["combo", "subagents", "maxDepth", t("verify_captured")] });+ for (const r of rows) {+ const mark =+ r.status === "captured"+ ? pc.green("✓ captured")+ : r.status === "flat"+ ? pc.dim("— flat (expected)")+ : pc.red("✗ none (gap)");+ table.push([r.comboId, String(r.subagents), String(r.maxDepth), mark]);+ }+ console.log(table.toString());+ const gaps = rows.filter((r) => r.status === "gap").length;+ if (gaps) console.log(pc.red(`\n${gaps} combo(s) expected subagents but captured none.`));+ else console.log(pc.green("\nall combos captured subagent flow as expected."));+ });+return program;}diff --git a/src/config.ts b/src/config.tsindex 8d6c5a2..510f716 100644--- a/src/config.ts+++ b/src/config.ts@@ -55,7 +55,8 @@ export const AGENTS: Record<string, AgentDef> = {};// ── L2 하네스 ────────────────────────────────────────────-// 멀티모델 에이전트(opencode/openclaw/hermes)는 보수적으로 none 만 지원.+// none = baseline. omc/ecc(cc), omx/lazycodex(codex), omo(opencode+codex) 는 오케스트레이션.+// superpowers(공용), ponytail(공용·미니멀리즘), mattpocock(cc/codex/opencode·스킬팩) 은 룰/스킬 주입.export const HARNESSES: Record<string, HarnessDef> = {none: {name: "none",@@ -67,6 +68,16 @@ export const HARNESSES: Record<string, HarnessDef> = {ecc: { name: "ecc", agents: ["cc"], orchestration: true },omx: { name: "omx", agents: ["codex"], orchestration: true },lazycodex: { name: "lazycodex", agents: ["codex"], orchestration: true },+ // omo = oh-my-openagent (Sisyphus orchestrator) — opencode(Ultimate) / codex(Light).+ omo: { name: "omo", agents: ["opencode", "codex"], orchestration: true },+ // ponytail = 미니멀리즘 룰팩(공용, 멀티플랫폼).+ ponytail: {+ name: "ponytail",+ agents: ["cc", "codex", "opencode", "openclaw", "hermes"],+ orchestration: false,+ },+ // mattpocock = .claude/skills 룰팩 (cc/codex/opencode).+ mattpocock: { name: "mattpocock", agents: ["cc", "codex", "opencode"], orchestration: false },};// ── 벤치 ─────────────────────────────────────────────────diff --git a/src/flow.ts b/src/flow.tsindex 3d83422..b331e85 100644--- a/src/flow.ts+++ b/src/flow.ts@@ -5,6 +5,7 @@* 노드별 토글(<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";@@ -248,12 +249,14 @@ export function renderGraphHtml(graphs: FlowGraph[], path: string, opts: { langu<style>body{font-family:ui-sans-serif,system-ui,sans-serif;background:#f8fafc;color:#0f172a;margin:0;padding:20px}h1{font-size:20px}+.theseus-hero{background:${THEME.sea};color:${THEME.sail};border-radius:12px;padding:14px 18px;margin-bottom:16px;display:flex;align-items:center;gap:14px}+.theseus-hero .sub{font-size:13px;opacity:.85}.dike-graph{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:16px;margin:16px 0;overflow:auto}.dike-graph h3{font-size:14px;margin:0 0 10px}.svg-wrap{overflow:auto}${DETAILS_CSS}</style></head><body>-<h1>${esc(tr(lang, "graph_title"))}</h1>+<header class="theseus-hero">${svgWordmark()}<div class="sub">${esc(tr(lang, "graph_title"))}</div></header>${sections}</body></html>`;writeFileSync(path, html);diff --git a/src/harness.ts b/src/harness.tsindex a2fd749..8d15152 100644--- a/src/harness.ts+++ b/src/harness.ts@@ -1,17 +1,22 @@/**- * 하네스 per-run 적용 (PRD §10). 전역 오염 없음 — 조합별로만 적용.- * - cc 하네스: --plugin-dir <설치경로>- * - codex 하네스: CODEX_HOME 격리 홈+ * 하네스 per-run 적용 (PRD §10, PRD v2 §W1). 전역 오염 없음 — 조합별로만 적용.+ * - cc 하네스(superpowers/omc/ecc/ponytail/mattpocock): --plugin-dir <설치경로>+ * - codex 하네스(omx/lazycodex/omo): CODEX_HOME 격리 홈+ * - 멀티모델 에이전트(opencode/openclaw/hermes) 하네스(omo/ponytail/mattpocock):+ * work_dir 에 룰(AGENTS.md/skills) 를 per-run 으로 **materialize**(opencode/ponytail 은 repo+ * AGENTS.md 를 자동 로드 → 전역 오염 없는 깔끔한 적용 경로).*/-import { existsSync, readdirSync } from "node:fs";+import { cpSync, existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";export type HarnessStatus = "none" | "applied" | "unavailable";export type CodexHomeStatus = "none" | "built" | "pending";-const CC_HARNESSES = new Set(["superpowers", "omc", "ecc"]);-const CODEX_HARNESSES = new Set(["omx", "lazycodex"]);+const CC_HARNESSES = new Set(["superpowers", "omc", "ecc", "ponytail", "mattpocock"]);+const CODEX_HARNESSES = new Set(["omx", "lazycodex", "omo"]);+// 멀티모델 에이전트(opencode/openclaw/hermes)에 work_dir materialize 로 적용 가능한 하네스+const MULTIMODEL_HARNESSES = new Set(["omo", "ponytail", "mattpocock"]);// 하네스 → 플러그인 디렉터리 이름 후보const PLUGIN_DIR_NAMES: Record<string, string[]> = {@@ -20,6 +25,9 @@ const PLUGIN_DIR_NAMES: Record<string, string[]> = {ecc: ["ecc", "enhanced-claude-code"],omx: ["oh-my-codex", "omx"],lazycodex: ["lazycodex", "lazy-codex"],+ omo: ["oh-my-openagent", "omo"],+ ponytail: ["ponytail"],+ mattpocock: ["mattpocock-skills", "mattpocock", "skills"],};function pluginCacheRoot(): string {@@ -62,7 +70,12 @@ function safeReaddir(p: string): string[] {}export function codexHomePath(harness: string): string {- return join(homedir(), ".cache", "dike", "codex-homes", harness);+ return join(homedir(), ".cache", "theseus", "codex-homes", harness);+}++/** 멀티모델 에이전트용 룰 캐시: ~/.cache/theseus/harness-rules/<harness>/ (AGENTS.md, skills/). */+export function harnessRulesPath(harness: string): string {+ return join(homedir(), ".cache", "theseus", "harness-rules", harness);}export function harnessClaudeArgs(harness: string): string[] {@@ -77,11 +90,41 @@ export function harnessCodexEnv(harness: string): Record<string, string> {return existsSync(home) ? { CODEX_HOME: home } : {};}+/**+ * 멀티모델 에이전트(opencode/openclaw/hermes)에 하네스를 per-run materialize.+ * 룰 캐시가 있으면 AGENTS.md/skills 를 work_dir 로 복사. 반환=적용 여부. 절대 throw 금지.+ */+export function applyHarnessToWorkdir(harness: string, workDir: string): boolean {+ if (harness === "none" || !MULTIMODEL_HARNESSES.has(harness)) return false;+ const src = harnessRulesPath(harness);+ if (!existsSync(src)) return false;+ try {+ mkdirSync(workDir, { recursive: true });+ cpSync(src, workDir, { recursive: true });+ return true;+ } catch {+ return false;+ }+}++/** 테스트/오프라인용: 최소 룰 캐시(AGENTS.md)를 생성한다(install 의 fallback). */+export function ensureHarnessRulesStub(harness: string, content: string): string {+ const dir = harnessRulesPath(harness);+ try {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "AGENTS.md"), content);+ } catch {+ // ignore+ }+ return dir;+}+export function harnessStatus(harness: string): HarnessStatus {if (harness === "none") return "none";- if (CC_HARNESSES.has(harness)) return findCcPluginDir(harness) ? "applied" : "unavailable";- if (CODEX_HARNESSES.has(harness))- return existsSync(codexHomePath(harness)) ? "applied" : "unavailable";+ // cc 플러그인 / codex 홈 / 멀티모델 룰 캐시 중 하나라도 있으면 applied+ if (findCcPluginDir(harness)) return "applied";+ if (CODEX_HARNESSES.has(harness) && existsSync(codexHomePath(harness))) return "applied";+ if (MULTIMODEL_HARNESSES.has(harness) && existsSync(harnessRulesPath(harness))) return "applied";return "unavailable";}diff --git a/src/i18n.ts b/src/i18n.tsindex 20ad793..aacc3df 100644--- a/src/i18n.ts+++ b/src/i18n.ts@@ -25,6 +25,8 @@ export const STRINGS: Record<string, Entry> = {run_complete: { en: "Run complete", kr: "실행 완료" },report_path: { en: "Report", kr: "리포트" },graph_path: { en: "Flow graph", kr: "흐름 그래프" },+ opening_browser: { en: "opening report in browser…", kr: "브라우저에서 리포트 여는 중…" },+ verify_captured: { en: "captured?", kr: "포착됨?" },run_id: { en: "Run id", kr: "런 ID" },results_table: { en: "Results", kr: "결과" },no_models: {@@ -42,6 +44,8 @@ export const STRINGS: Record<string, Entry> = {sec_accuracy: { en: "1. Accuracy", kr: "1. 정확도" },sec_efficiency: { en: "2. Efficiency", kr: "2. 효율" },sec_scatter: { en: "3. Cost-performance scatter", kr: "3. 가성비 산점도" },+ pareto_frontier: { en: "Pareto frontier", kr: "파레토 경계" },+ philosophy_label: { en: "Ship of Theseus", kr: "테세우스의 배" },sec_matrix: { en: "4. Task pass/fail matrix", kr: "4. 과제별 통과/실패 매트릭스" },sec_flow: { en: "5. Subagent flow graphs", kr: "5. 서브에이전트 흐름 그래프" },sec_failures: { en: "6. Failed tasks & causes", kr: "6. 실패 과제 & 원인" },diff --git a/src/install.ts b/src/install.tsindex 1c5c692..a56e10d 100644--- a/src/install.ts+++ b/src/install.ts@@ -1,10 +1,13 @@/**- * install 커맨드 (PRD §22.5).- * 바이너리: 설치 확인 후 힌트. cc 하네스: marketplace add + install + 전역 disable.- * codex 하네스: per-run 격리 홈 빌드. 실패 시 수동 명령 안내로 폴백(치명적이지 않게).+ * install 커맨드 (PRD §22.5, PRD v2 §W7).+ * 바이너리: 설치 확인 + 힌트. 하네스: cc 플러그인(--plugin-dir) · codex 격리 홈(CODEX_HOME) ·+ * 멀티모델 룰 캐시(work_dir materialize). 한 하네스가 여러 표면을 지원하면 모두 설정.+ * 설치 후 harnessStatus 로 검증. `--check`(전체 상태표) · `all`(베스트에포트 전체).+ * 실패 시 수동 명령 안내로 폴백(치명적이지 않게).*/import pc from "picocolors";-import { codexHomePath } from "./harness";+import { AGENTS, HARNESSES } from "./config";+import { codexHomePath, ensureHarnessRulesStub, harnessRulesPath, harnessStatus } from "./harness";import { commandExists, execCapture } from "./runners/util";const BIN_MAP: Record<string, string> = {@@ -26,85 +29,153 @@ const INSTALL_HINTS: Record<string, string> = {hermes: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",};-// 하네스 → marketplace source / plugin id+// 하네스 → cc 플러그인 marketplace source / plugin idconst CC_HARNESS_SRC: Record<string, { src: string; plugin: string }> = {superpowers: { src: "obra/superpowers", plugin: "superpowers" },omc: { src: "oh-my-claudecode/marketplace", plugin: "oh-my-claudecode" },ecc: { src: "ecc/marketplace", plugin: "ecc" },+ ponytail: { src: "DietrichGebert/ponytail", plugin: "ponytail" },+ mattpocock: { src: "mattpocock/skills", plugin: "mattpocock-skills" },};+// 하네스 → codex 격리 홈 marketplace source / plugin idconst CODEX_HARNESS_SRC: Record<string, { src: string; plugin: string }> = {omx: { src: "oh-my-codex/marketplace", plugin: "oh-my-codex" },lazycodex: { src: "lazycodex/marketplace", plugin: "lazycodex" },+ omo: { src: "code-yeongyu/oh-my-openagent", plugin: "oh-my-openagent" },+};+// 멀티모델(opencode/openclaw/hermes) 룰 캐시 소스(repo) — work_dir 로 materialize 됨+const MULTIMODEL_HARNESS_SRC: Record<string, { repo: string; install: string }> = {+ omo: { repo: "code-yeongyu/oh-my-openagent", install: "bunx oh-my-openagent install" },+ ponytail: { repo: "DietrichGebert/ponytail", install: "npx ponytail install" },+ mattpocock: { repo: "mattpocock/skills", install: "npx degit mattpocock/skills" },};-export async function runInstall(component: string): Promise<void> {- const c = component.toLowerCase();+const ALL_HARNESSES = Object.keys(HARNESSES).filter((h) => h !== "none");- // 1) 바이너리- if (c in BIN_MAP) {- const bin = BIN_MAP[c]!;- if (commandExists(bin)) {- console.log(pc.green(`✓ ${bin} already installed`));- } else {- console.log(pc.yellow(`✗ ${bin} not found`));- console.log(` install: ${INSTALL_HINTS[bin] ?? `(see ${bin} docs)`}`);- }+async function installCcHarness(c: string): Promise<void> {+ const { src, plugin } = CC_HARNESS_SRC[c]!;+ if (!commandExists("claude")) {+ console.log(pc.yellow(" cc surface: claude not installed — skip (install cc first)"));return;}+ console.log(` cc surface: installing plugin '${plugin}'…`);+ const a = await execCapture("claude", ["plugin", "marketplace", "add", src], { timeoutS: 120 });+ const b = await execCapture("claude", ["plugin", "install", plugin], { timeoutS: 120 });+ if (a.code === 0 && b.code === 0) {+ await execCapture("claude", ["plugin", "disable", plugin], { timeoutS: 60 });+ console.log(+ pc.green(` ✓ cc plugin '${plugin}' installed (globally disabled; per-run --plugin-dir)`),+ );+ } else {+ console.log(pc.yellow(" cc auto-install failed — run manually:"));+ console.log(+ ` claude plugin marketplace add ${src} && claude plugin install ${plugin} && claude plugin disable ${plugin}`,+ );+ }+}- // 2) cc 하네스- if (c in CC_HARNESS_SRC) {- const { src, plugin } = CC_HARNESS_SRC[c]!;- if (!commandExists("claude")) {- console.log(pc.red("claude not installed — install cc first"));- return;- }- console.log(`installing cc harness '${c}'…`);- const a = await execCapture("claude", ["plugin", "marketplace", "add", src], { timeoutS: 120 });- const b = await execCapture("claude", ["plugin", "install", plugin], { timeoutS: 120 });- if (a.code === 0 && b.code === 0) {- await execCapture("claude", ["plugin", "disable", plugin], { timeoutS: 60 });- console.log(- pc.green(`✓ ${plugin} installed (globally disabled — loaded per-run via --plugin-dir)`),- );- } else {- console.log(pc.yellow("auto-install failed — run manually:"));- console.log(` claude plugin marketplace add ${src}`);- console.log(` claude plugin install ${plugin}`);- console.log(` claude plugin disable ${plugin}`);- }+async function installCodexHarness(c: string): Promise<void> {+ const { src, plugin } = CODEX_HARNESS_SRC[c]!;+ const home = codexHomePath(c);+ if (!commandExists("codex")) {+ console.log(pc.yellow(" codex surface: codex not installed — skip"));return;}+ console.log(` codex surface: building isolated CODEX_HOME at ${home}…`);+ const env = { CODEX_HOME: home };+ const a = await execCapture("codex", ["plugin", "marketplace", "add", src], {+ timeoutS: 120,+ env,+ });+ const b = await execCapture("codex", ["plugin", "add", plugin], { timeoutS: 120, env });+ if (a.code === 0 && b.code === 0) {+ console.log(pc.green(" ✓ codex isolated home built (global ~/.codex untouched)"));+ } else {+ console.log(pc.yellow(" codex auto-build failed — run manually:"));+ console.log(+ ` CODEX_HOME=${home} codex plugin marketplace add ${src} && CODEX_HOME=${home} codex plugin add ${plugin}`,+ );+ }+}- // 3) codex 하네스 (격리 홈)- if (c in CODEX_HARNESS_SRC) {- const { src, plugin } = CODEX_HARNESS_SRC[c]!;- const home = codexHomePath(c);- console.log(`building isolated CODEX_HOME for '${c}' at ${home}…`);- if (!commandExists("codex")) {- console.log(pc.red("codex not installed — install codex first"));- return;- }- const env = { CODEX_HOME: home };- const a = await execCapture("codex", ["plugin", "marketplace", "add", src], {- timeoutS: 120,- env,- });- const b = await execCapture("codex", ["plugin", "add", plugin], { timeoutS: 120, env });- if (a.code === 0 && b.code === 0) {- console.log(- pc.green(`✓ ${plugin} isolated home built (auth symlinked; global ~/.codex untouched)`),- );- } else {- console.log(pc.yellow("auto-build failed — run manually:"));- console.log(` CODEX_HOME=${home} codex plugin marketplace add ${src}`);- console.log(` CODEX_HOME=${home} codex plugin add ${plugin}`);- }+function installMultiModelRules(c: string): void {+ const { repo, install } = MULTIMODEL_HARNESS_SRC[c]!;+ const dir = harnessRulesPath(c);+ // 오프라인/최소: AGENTS.md 룰 스텁을 캐시에 생성(실 설치 시 repo 내용으로 대체).+ ensureHarnessRulesStub(+ c,+ `# ${c} rules (theseus harness materialization)\n` ++ `# source: ${repo}\n` ++ `# replace this stub with the real rules via: ${install}\n`,+ );+ console.log(pc.green(` ✓ multimodel rules cache ready at ${dir}`));+ console.log(pc.dim(` (for full rules: ${install})`));+}++function validate(c: string): void {+ const status = harnessStatus(c);+ if (status === "applied") console.log(pc.green(" ⮑ status: applied ✓"));+ else console.log(pc.yellow(` ⮑ status: ${status} (falls back to base 'none' until applied)`));+}++export async function installHarness(c: string): Promise<void> {+ console.log(pc.bold(`harness '${c}' (agents: ${HARNESSES[c]?.agents.join(",")})`));+ if (c in CC_HARNESS_SRC) await installCcHarness(c);+ if (c in CODEX_HARNESS_SRC) await installCodexHarness(c);+ if (c in MULTIMODEL_HARNESS_SRC) installMultiModelRules(c);+ validate(c);+}++export function installBinary(c: string): boolean {+ const bin = BIN_MAP[c]!;+ if (commandExists(bin)) {+ console.log(pc.green(`✓ ${bin} already installed`));+ return true;+ }+ console.log(pc.yellow(`✗ ${bin} not found`));+ console.log(` install: ${INSTALL_HINTS[bin] ?? `(see ${bin} docs)`}`);+ return false;+}++export async function runInstall(component: string): Promise<void> {+ const c = component.toLowerCase();++ if (c === "--check" || c === "check") return runInstallCheck();+ if (c === "all") return runInstallAll();++ if (c in BIN_MAP) {+ installBinary(c);+ return;+ }+ if (c in HARNESSES && c !== "none") {+ await installHarness(c);return;}console.log(pc.red(`unknown component '${component}'`));- console.log(" binaries: cc, codex, tb");- console.log(" cc harnesses: superpowers, omc, ecc");- console.log(" codex harnesses: omx, lazycodex");+ console.log(" binaries: cc, codex, opencode, openclaw, hermes, tb");+ console.log(` harnesses: ${ALL_HARNESSES.join(", ")}`);+ console.log(" meta: --check (status table), all (install everything)");+}++/** 전체 가용성 상태표(doctor 와 유사하나 install 관점). */+export function runInstallCheck(): void {+ console.log(pc.bold("agents:"));+ for (const a of Object.keys(AGENTS)) {+ const ok = commandExists(AGENTS[a]!.bin);+ console.log(` ${ok ? pc.green("✓") : pc.red("✗")} ${a} (${AGENTS[a]!.bin})`);+ }+ console.log(pc.bold("harnesses:"));+ for (const h of ALL_HARNESSES) {+ const s = harnessStatus(h);+ const mark = s === "applied" ? pc.green("✓ applied") : pc.yellow(`· ${s}`);+ console.log(` ${mark} ${h}`);+ }+}++/** 베스트에포트로 모든 하네스 설치 시도(미설치 바이너리는 건너뜀). */+export async function runInstallAll(): Promise<void> {+ for (const h of ALL_HARNESSES) {+ await installHarness(h);+ }}diff --git a/src/models.ts b/src/models.tsindex acdc320..bd3d3a0 100644--- a/src/models.ts+++ b/src/models.ts@@ -188,9 +188,13 @@ export interface RunOptions {score: boolean;balanced: boolean;language: Lang;+ view?: ViewMode; // 시각화 전달 모드 (PRD v2 §W2)+ port?: number; // serve 모드 포트failRate?: number; // mock 전용 (테스트)}+export type ViewMode = "inline" | "open" | "serve" | "term";+// ─────────────────────────────────────────────────────────────// zod 스키마 — 외부(transcript/headless JSON) 방어적 파싱용// ─────────────────────────────────────────────────────────────diff --git a/src/orchestrator.ts b/src/orchestrator.tsindex 28860a6..00187c6 100644--- a/src/orchestrator.ts+++ b/src/orchestrator.ts@@ -27,6 +27,7 @@ export interface ExecuteResult {reportPath: string;graphPath: string;metrics: ReturnType<typeof aggregateAll>;+ graphs: FlowGraph[];mock: boolean;}@@ -236,6 +237,7 @@ export async function execute(opts: RunOptions): Promise<ExecuteResult> {reportPath: recorder.reportPath,graphPath: recorder.graphPath,metrics,+ graphs,mock: anyMock,};}diff --git a/src/report.ts b/src/report.tsindex d64fde9..cb065ab 100644--- a/src/report.ts+++ b/src/report.ts@@ -4,6 +4,7 @@* 4 task 매트릭스 · 5 흐름 그래프(+토글) · 6 실패 원인 · 7 미수집 지표.*/import { writeFileSync } from "node:fs";+import { THEME, philosophy, svgWordmark } from "./brand";import { DETAILS_CSS, esc, graphSection } from "./flow";import { tr } from "./i18n";import type { ComboMetrics } from "./metrics";@@ -81,19 +82,54 @@ function renderScatter(metrics: ComboMetrics[], lang: Lang): string {parts.push(`<text x="14" y="${H / 2}" font-size="11" text-anchor="middle" fill="#475569" transform="rotate(-90 14 ${H / 2})">${esc(tr(lang, "col_acc"))} (%)</text>`,);++ // Pareto frontier: 더 싸면서 더 정확한 조합에 지배당하지 않는 점들(낮은 비용·높은 정확도).+ const frontier = paretoFrontier(pts);+ const fset = new Set(frontier.map((m) => m.comboId));+ const fpath = frontier+ .slice()+ .sort((a, b) => a.costUsd! - b.costUsd!)+ .map(+ (m, i) => `${i === 0 ? "M" : "L"}${xf(m.costUsd!).toFixed(1)},${yf(m.accuracy).toFixed(1)}`,+ )+ .join(" ");+ if (frontier.length > 1) {+ parts.push(+ `<path d="${fpath}" fill="none" stroke="${THEME.rope}" stroke-width="2" stroke-dasharray="5 3" opacity="0.8"/>`,+ );+ }+ parts.push(+ `<text x="${pad + 6}" y="${pad - 8}" font-size="10" fill="${THEME.rope}">— ${esc(tr(lang, "pareto_frontier"))}</text>`,+ );+pts.forEach((m, i) => {const color = colors[i % colors.length]!;+ const onFront = fset.has(m.comboId);parts.push(- `<circle cx="${xf(m.costUsd!).toFixed(1)}" cy="${yf(m.accuracy).toFixed(1)}" r="6" fill="${color}" opacity="0.8"/>`,+ `<circle cx="${xf(m.costUsd!).toFixed(1)}" cy="${yf(m.accuracy).toFixed(1)}" r="${onFront ? 7 : 5}" fill="${color}" opacity="0.85" stroke="${onFront ? THEME.rope : "none"}" stroke-width="${onFront ? 2.5 : 0}"><title>${esc(m.comboId)} · ${m.accuracy.toFixed(1)}% · $${m.costUsd!.toFixed(4)}</title></circle>`,);parts.push(- `<text x="${W - pad + 14}" y="${pad + 8 + i * 16}" font-size="10" fill="#334155"><tspan fill="${color}">●</tspan> ${esc(m.comboId)}</text>`,+ `<text x="${W - pad + 14}" y="${pad + 8 + i * 16}" font-size="10" fill="#334155">${onFront ? "★ " : ""}<tspan fill="${color}">●</tspan> ${esc(m.comboId)}</text>`,);});parts.push("</svg>");return `<div class="svg-wrap">${parts.join("")}</div>`;}+/** 비용↓·정확도↑ 기준 비지배 집합(Pareto frontier). */+function paretoFrontier(pts: ComboMetrics[]): ComboMetrics[] {+ return pts.filter(+ (a) =>+ !pts.some(+ (b) =>+ b.comboId !== a.comboId &&+ b.costUsd! <= a.costUsd! &&+ b.accuracy >= a.accuracy &&+ (b.costUsd! < a.costUsd! || b.accuracy > a.accuracy),+ ),+ );+}+export function renderReportHtml(input: ReportInput): string {const { language: lang } = input;const sorted = sortCombos(input.metrics);@@ -302,10 +338,16 @@ code{font-family:ui-monospace,monospace;font-size:12px}.dike-graph{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:14px;margin:12px 0;overflow:auto}.dike-graph h3{font-size:13px;margin:0 0 8px}.svg-wrap{overflow:auto}+.theseus-hero{background:${THEME.sea};color:${THEME.sail};border-radius:12px;padding:16px 20px;margin:-8px 0 18px;display:flex;align-items:center;gap:16px}+.theseus-hero .sub{font-size:13px;opacity:.85}+.theseus-hero .bench{color:${THEME.foam};font-family:ui-monospace,monospace;font-size:12px}+h2{border-bottom-color:${THEME.rope}}+.theseus-foot{margin-top:32px;padding-top:14px;border-top:1px solid ${THEME.grid};color:${THEME.mist};font-size:12px;font-style:italic}${DETAILS_CSS}</style></head><body>-<h1>theseus — ${esc(tr(lang, "results_table"))} <span class="muted">(${esc(input.bench)})</span></h1>+<header class="theseus-hero">${svgWordmark()}<div><div class="sub">${esc(tr(lang, "app_tagline"))}</div><div class="bench">bench: ${esc(input.bench)}</div></div></header>${blocks.join("\n")}+<footer class="theseus-foot">⚓ ${esc(tr(lang, "philosophy_label"))} — ${esc(philosophy(lang))}</footer></body></html>`;}diff --git a/src/runners/mock.ts b/src/runners/mock.tsindex 8b216d0..1bf84b2 100644--- a/src/runners/mock.ts+++ b/src/runners/mock.ts@@ -43,8 +43,32 @@ const HARNESS_SUBAGENTS: Record<string, [number, number]> = {omx: [2, 5],ecc: [0, 1],lazycodex: [0, 1],+ omo: [2, 5],+ mattpocock: [1, 3],+ ponytail: [0, 1],};+// 미니멀리즘 하네스는 토큰/도구를 줄이는 경향(결정적 할인 계수)+const HARNESS_TOKEN_SCALE: Record<string, number> = {+ ponytail: 0.5,+};++/**+ * fan-out 가능 여부: 트리형 에이전트는 cc(모든 하네스), 그리고 opencode+omo(오케스트레이션).+ * codex/openclaw/hermes 및 omo 외 opencode 는 단일 루프(0).+ */+function mockFanout(agent: string, harness: string, det: Det): number {+ if (agent === "cc") {+ const [lo, hi] = HARNESS_SUBAGENTS[harness] ?? [0, 0];+ return det.randint(lo, hi);+ }+ if (agent === "opencode" && harness === "omo") {+ const [lo, hi] = HARNESS_SUBAGENTS.omo ?? [0, 0];+ return det.randint(lo, hi);+ }+ return 0;+}+const DIFFICULTY_SCALE: Record<string, number> = {"subagent-": 1.8,"local-": 1.0,@@ -86,24 +110,22 @@ export class MockRunner implements RunnerAdapter {// 실행 성공 여부(fail-soft 경로 검증용)const failed = det.chance(this.failRate);- // 서브에이전트 수 — cc 만 하네스 경향으로 fan-out. codex/멀티모델 에이전트는 단일 루프(0).+ // 서브에이전트 수 — 하네스 오케스트레이션 × 에이전트 트리 능력으로 결정.const fam = modelFamily(model);- let subagentCount = 0;- if (agent === "cc") {- const [lo, hi] = HARNESS_SUBAGENTS[harness] ?? [0, 0];- subagentCount = det.randint(lo, hi);- }+ const subagentCount = mockFanout(agent, harness, det);- // 토큰- const inputTokens = Math.round(det.randint(8000, 30000) * scale);- const outputTokens = Math.round(det.randint(1500, 6000) * scale);- const cacheRead = Math.round(det.randint(20000, 120000) * scale);- const cacheCreate = Math.round(det.randint(2000, 15000) * scale);+ // 토큰 (ponytail 등 미니멀리즘 하네스는 할인)+ const hScale = scale * (HARNESS_TOKEN_SCALE[harness] ?? 1);+ const inputTokens = Math.round(det.randint(8000, 30000) * hScale);+ const outputTokens = Math.round(det.randint(1500, 6000) * hScale);+ const cacheRead = Math.round(det.randint(20000, 120000) * hScale);+ const cacheCreate = Math.round(det.randint(2000, 15000) * hScale);const wallTimeMs = det.randint(3000, 90000);const rawResolved = failed ? false : det.chance(0.7 - (scale - 1) * 0.15);- // transcript 합성 — cc 만 트리(sidechain), 그 외(codex/opencode/openclaw/hermes)는 평탄.+ // transcript 합성 — cc 는 sidechain 트리, 그 외(codex/opencode/openclaw/hermes)는 평탄.+ // 평탄 포맷에도 subagentCount 만큼 task 아이템을 실어 DefensiveParser 가 fan-out 을 집계.const lines: string[] =agent === "cc"? this.ccTranscript(@@ -116,7 +138,15 @@ export class MockRunner implements RunnerAdapter {cacheRead,cacheCreate,)- : this.codexTranscript(det, model, inputTokens, outputTokens, cacheRead, cacheCreate);+ : this.codexTranscript(+ det,+ model,+ inputTokens,+ outputTokens,+ cacheRead,+ cacheCreate,+ subagentCount,+ );writeFileSync(transcriptPath, lines.join("\n"));writeFileSync(@@ -306,11 +336,21 @@ export class MockRunner implements RunnerAdapter {outT: number,cr: number,cc: number,+ subagents = 0,): string[] {const lines: string[] = [];lines.push(JSON.stringify({ type: "thread.started", thread_id: `th-${det.randint(1000, 9999)}` }),);+ // 평탄 포맷에서도 fan-out 을 표현: subagents 개의 task 아이템(DefensiveParser 가 집계).+ for (let s = 0; s < subagents; s++) {+ lines.push(+ JSON.stringify({+ type: "item.completed",+ item: { type: "task", name: "Task", command: `subagent ${s}` },+ }),+ );+ }const turns = det.randint(2, 8);for (let i = 0; i < turns; i++) {lines.push(JSON.stringify({ type: "turn.started" }));diff --git a/src/runners/multiModel.ts b/src/runners/multiModel.tsindex 9cd6c1e..af254a4 100644--- a/src/runners/multiModel.ts+++ b/src/runners/multiModel.ts@@ -12,6 +12,7 @@ import { join } from "node:path";import { instructionFor, isLocalBench, setupTask, taskIds, verify } from "../benches/index";import { parseComboId } from "../combos";import { modelFamily, providerFor, resolveModelAlias } from "../config";+import { applyHarnessToWorkdir } from "../harness";import type { RawRunArtifact, RunInvocation } from "../models";import { type RunnerAdapter, RunnerUnavailable } from "./base";import { commandExists, execCapture } from "./util";@@ -44,13 +45,15 @@ export class MultiModelRunner implements RunnerAdapter {}async run(inv: RunInvocation): Promise<RawRunArtifact> {- const { model } = parseComboId(inv.combo.comboId);+ const { model, harness } = parseComboId(inv.combo.comboId);const work = inv.workDir;mkdirSync(work, { recursive: true });const resultPath = join(work, "output.txt");const transcriptPath = join(work, "transcript.jsonl");if (isLocalBench(inv.bench)) setupTask(inv.taskId, work);+ // 하네스 per-run 적용 (룰/스킬을 work_dir 로 materialize; 전역 오염 없음)+ applyHarnessToWorkdir(harness, work);const instruction =inv.instruction ?? instructionFor(inv.taskId) ?? `Complete task ${inv.taskId}`;diff --git a/src/transcripts/defensive.ts b/src/transcripts/defensive.tsindex bc66a28..16b16ae 100644--- a/src/transcripts/defensive.ts+++ b/src/transcripts/defensive.ts@@ -54,11 +54,12 @@ function scan(node: unknown, acc: Acc, depth = 0): void {// 이벤트/아이템 타입 → 도구·서브에이전트const type = typeof obj.type === "string" ? (obj.type as string) : "";const name = typeof obj.name === "string" ? (obj.name as string) : "";- if (type && TOOL_TYPE_RE.test(type)) {+ const isSub = SUBAGENT_RE.test(type) || SUBAGENT_RE.test(name);+ if ((type && TOOL_TYPE_RE.test(type)) || isSub) {acc.toolCalls += 1;acc.tools.push(name || type);acc.steps.push(name || type);- if (SUBAGENT_RE.test(type) || SUBAGENT_RE.test(name)) acc.subagents += 1;+ if (isSub) acc.subagents += 1;if (isMcp(name) || isMcp(type)) acc.mcp += 1;}for (const v of Object.values(obj)) scan(v, acc, depth + 1);diff --git a/src/tui.ts b/src/tui.tsindex 7d45e18..cbb99eb 100644--- a/src/tui.ts+++ b/src/tui.ts@@ -3,7 +3,6 @@* run 선택 → 비교표 + 관점별 추천 + 흐름 요약. 기본 ink, 미설치/--rich 시 cli-table3 폴백.* --open 시 report.html 브라우저 오픈.*/-import { spawn } from "node:child_process";import { existsSync } from "node:fs";import { join } from "node:path";import Table from "cli-table3";@@ -12,6 +11,7 @@ import { type Translator, translator } from "./i18n";import { aggregateAll, bestByPerspective, sortCombos } from "./metrics";import type { Lang } from "./models";import { listRuns, loadMeta, loadResults } from "./recorder";+import { openInBrowser } from "./viz/open";export interface TuiOpts {out: string;@@ -64,26 +64,24 @@ function fallbackRender(t: Translator, lang: Lang, opts: TuiOpts): string | nullreturn join(opts.out, runId, "report.html");}-function openInBrowser(file: string): void {- const opener =- process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";- try {- spawn(opener, [file], { stdio: "ignore", detached: true }).unref();- } catch {- // ignore- }-}-export async function runTui(opts: TuiOpts): Promise<void> {const t = translator(opts.language);- // best-effort ink — 미설치/실패 시 cli-table3 폴백+ // 인터랙티브 ink 앱 우선(비-TTY/미설치/--rich → cli-table3 폴백)if (!opts.rich) {try {- await import("ink");- // ink 가 있어도 안전한 폴백 렌더를 사용(JSX 빌드 의존 회피). 향후 ink 앱으로 확장.+ const { runInk } = await import("./tui/inkApp");+ const ok = await runInk({ out: opts.out, language: opts.language });+ if (ok) {+ if (opts.open) {+ const runs = listRuns(opts.out);+ const rp = runs[0] ? join(opts.out, runs[0], "report.html") : "";+ if (rp && existsSync(rp)) openInBrowser(rp);+ }+ return;+ }} catch {- // ink 없음 — 폴백+ // ink 실패 → 폴백}}diff --git a/src/tui/inkApp.ts b/src/tui/inkApp.tsnew file mode 100644index 0000000..328f82e--- /dev/null+++ b/src/tui/inkApp.ts@@ -0,0 +1,178 @@+/**+ * 인터랙티브 TUI (PRD v2 §W4) — ink.+ * runs 목록 → combo 표 → combo 상세(메트릭 + 흐름 트리). 화살표/enter/esc/q.+ * JSX 미사용(React.createElement) → 빌드 설정 불필요. ink/react 는 lazy dynamic import,+ * 미설치/비-TTY 면 runInk 가 false 를 반환해 tui.ts 가 cli-table3 폴백.+ */+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";+import { type Translator, translator } from "../i18n";+import { aggregateAll, bestByPerspectiveDetailed, sortCombos } from "../metrics";+import type { ComboMetrics } from "../metrics";+import type { FlowGraph, Lang } from "../models";+import { listRuns, loadMeta, loadResults } from "../recorder";+import { renderFlowTree } from "../viz/terminal";++function safe(s: string): string {+ return s.replace(/[^A-Za-z0-9._+-]/g, "_");+}++/** runs/<id>/work/<combo>/<task>/0/flow.json 중 하나를 best-effort 로드. */+function loadComboFlow(runDir: string, comboId: string): FlowGraph | null {+ const base = join(runDir, "work", safe(comboId));+ if (!existsSync(base)) return null;+ try {+ for (const task of readdirSync(base)) {+ const f = join(base, task, "0", "flow.json");+ if (existsSync(f)) return JSON.parse(readFileSync(f, "utf8")) as FlowGraph;+ }+ } catch {+ // ignore+ }+ return null;+}++export interface InkOpts {+ out: string;+ language: Lang;+}++/** ink 앱 실행. 성공 시 종료까지 대기 후 true, 미가용 시 false. 절대 throw 금지. */+export async function runInk(opts: InkOpts): Promise<boolean> {+ if (!process.stdout.isTTY) return false;+ let ink: any;+ let React: any;+ try {+ ink = await import("ink");+ React = (await import("react")).default ?? (await import("react"));+ } catch {+ return false;+ }++ const { render, Box, Text, useInput, useApp } = ink;+ const h = React.createElement;+ const t: Translator = translator(opts.language);+ const runs = listRuns(opts.out);++ const App = () => {+ const app = useApp();+ const [screen, setScreen] = React.useState("runs");+ const [runIdx, setRunIdx] = React.useState(0);+ const [comboIdx, setComboIdx] = React.useState(0);++ const runId = runs[runIdx];+ const metrics: ComboMetrics[] = runId+ ? sortCombos(aggregateAll(loadResults(opts.out, runId)))+ : [];++ useInput((input: string, key: any) => {+ if (input === "q") {+ app.exit();+ return;+ }+ if (screen === "runs") {+ if (key.upArrow) setRunIdx((i: number) => Math.max(0, i - 1));+ if (key.downArrow) setRunIdx((i: number) => Math.min(runs.length - 1, i + 1));+ if (key.return && runs.length) {+ setComboIdx(0);+ setScreen("combos");+ }+ } else if (screen === "combos") {+ if (key.upArrow) setComboIdx((i: number) => Math.max(0, i - 1));+ if (key.downArrow) setComboIdx((i: number) => Math.min(metrics.length - 1, i + 1));+ if (key.return && metrics.length) setScreen("detail");+ if (key.leftArrow || key.escape) setScreen("runs");+ } else if (screen === "detail") {+ if (key.leftArrow || key.escape) setScreen("combos");+ }+ });++ const header = h(+ Text,+ { color: "cyan", bold: true },+ `⛵ theseus — ${t("results_table")} `,+ h(Text, { color: "gray" }, "(↑↓ move · ⏎ select · ← back · q quit)"),+ );++ if (screen === "runs") {+ return h(+ Box,+ { flexDirection: "column" },+ header,+ h(Text, { color: "gray" }, `${t("run_id")}s:`),+ ...runs.map((id, i) => {+ const meta = loadMeta(opts.out, id);+ return h(+ Text,+ { key: id, color: i === runIdx ? "green" : undefined, inverse: i === runIdx },+ `${i === runIdx ? "❯ " : " "}${id} ${meta?.bench ?? "?"}${meta?.mock ? " ·mock" : ""}`,+ );+ }),+ runs.length === 0 ? h(Text, { color: "yellow" }, "no runs found") : null,+ );+ }++ if (screen === "combos") {+ return h(+ Box,+ { flexDirection: "column" },+ header,+ h(+ Text,+ { color: "gray" },+ `${runId} — ${t("col_combo")} (${t("col_subagents")}/${t("col_tokens")}/${t("col_cost")})`,+ ),+ ...metrics.map((m, i) =>+ h(+ Text,+ {+ key: m.comboId,+ color: i === comboIdx ? "green" : undefined,+ inverse: i === comboIdx,+ },+ `${i === comboIdx ? "❯ " : " "}${m.comboId.padEnd(26)} ` ++ `${String(m.subagentCount).padStart(3)} ${(m.totalTokens / 1000).toFixed(0)}k ` ++ `${m.costUsd === null ? "null" : `$${m.costUsd.toFixed(3)}`} ${m.accuracy.toFixed(0)}%`,+ ),+ ),+ );+ }++ // detail+ const m = metrics[comboIdx];+ if (!m) return header;+ const flow = runId ? loadComboFlow(join(opts.out, runId), m.comboId) : null;+ const picks = bestByPerspectiveDetailed(metrics, opts.language)+ .filter((p) => p.comboId === m.comboId)+ .map((p) => p.label);+ return h(+ Box,+ { flexDirection: "column" },+ header,+ h(Text, { bold: true, color: "cyan" }, m.comboId),+ h(+ Text,+ null,+ `${t("col_acc")}: ${m.accuracy.toFixed(1)}% ${t("col_subagents")}: ${m.subagentCount} ${t("col_tokens")}: ${m.totalTokens.toLocaleString("en-US")}`,+ ),+ h(+ Text,+ null,+ `${t("col_cost")}: ${m.costUsd === null ? "null (uncollected)" : `$${m.costUsd.toFixed(4)} (${m.costSource})`} ${t("col_toolcalls")}: ${m.toolCalls}`,+ ),+ picks.length ? h(Text, { color: "green" }, `★ ${picks.join(", ")}`) : null,+ h(Text, { color: "gray" }, `\n${t("sec_flow")}:`),+ h(Text, null, flow ? stripAnsi(renderFlowTree(flow)) : " (no flow.json)"),+ );+ };++ const instance = render(h(App));+ await instance.waitUntilExit();+ return true;+}++function stripAnsi(s: string): string {+ // 트리 렌더는 picocolors 색을 포함 — ink Text 안에서는 평문이 안전.+ // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI 제거+ return s.replace(/\x1b\[[0-9;]*m/g, "");+}diff --git a/src/tui/shims.d.ts b/src/tui/shims.d.tsnew file mode 100644index 0000000..f2c51d1--- /dev/null+++ b/src/tui/shims.d.ts@@ -0,0 +1,3 @@+// ink/react 는 lazy dynamic import 로만 쓰며 타입은 any 로 충분(@types/react 의존 회피).+declare module "ink";+declare module "react";diff --git a/src/verify.ts b/src/verify.tsnew file mode 100644index 0000000..81f44db--- /dev/null+++ b/src/verify.ts@@ -0,0 +1,92 @@+/**+ * 조합별 서브에이전트 콜 검증 (PRD v2 §W5) — "각 조합 subagent 콜 잘 되는지 확인".+ * 각 유효 조합을 위임 유도 과제(subagent-102, depth-2)로 1회 실행 → 흐름 파싱 →+ * subagentCount/maxDepth 를 집계하고 기대 모델과 대조한다.+ * 기대: 트리형 조합(cc+오케스트레이션, opencode+omo)은 fan-out 필요 / 단일 루프(codex·none·hermes)는 flat 정상.+ * mock(오프라인·결정적, 기본) 또는 real(--yes 게이트). 절대 throw 금지.+ */+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expand, parseComboId } from "./combos";+import { HARNESSES } from "./config";+import { buildFlow } from "./flow";+import type { Combo } from "./models";+import { runnerFor } from "./runners/registry";+import { parserFor } from "./transcripts/index";++export type VerifyStatus = "captured" | "flat" | "gap";++export interface VerifyRow {+ comboId: string;+ agent: string;+ harness: string;+ subagents: number;+ maxDepth: number;+ expectFanout: boolean;+ status: VerifyStatus; // captured=fan-out 관측, flat=단일루프(정상), gap=기대했으나 0(포착 누락 의심)+}++export interface VerifyOptions {+ models: string[];+ agents: string[];+ harnesses: string[];+ runner: string;+ seed: number;+ timeoutS: number;+ task?: string;+}++/** 트리형 조합인가? (mock fan-out 규칙과 동일: cc+오케스트레이션, opencode+omo) */+export function expectsFanout(agent: string, harness: string): boolean {+ if (agent === "cc") return HARNESSES[harness]?.orchestration === true;+ if (agent === "opencode" && harness === "omo") return true;+ return false;+}++export async function verifyCombos(opts: VerifyOptions): Promise<VerifyRow[]> {+ const { valid } = expand(opts.models, opts.agents, opts.harnesses);+ const task = opts.task ?? "subagent-102";+ const rows: VerifyRow[] = [];++ for (const combo of valid as Combo[]) {+ const { agent, model, harness } = parseComboId(combo.comboId);+ const choice = runnerFor(agent, opts.runner, { bench: "subagent" }, 0);+ const workDir = mkdtempSync(join(tmpdir(), "theseus-verify-"));+ let subagents = 0;+ let maxDepth = 0;+ try {+ const art = await choice.runner.run({+ combo,+ taskId: task,+ runIdx: 0,+ workDir,+ timeoutS: opts.timeoutS,+ seed: opts.seed,+ bench: "subagent",+ });+ const parsed = parserFor(agent).parse(art.transcriptPath, { model });+ subagents = parsed.subagentCount;+ const flow = buildFlow(parsed, combo.comboId, task, 0, {+ harness,+ success: art.success,+ error: art.error,+ });+ maxDepth = flow.nodes.reduce((m, n) => Math.max(m, n.depth), 0);+ } catch {+ // fail-soft: 0/0 로 남김+ }+ const expectFanout = expectsFanout(agent, harness);+ const status: VerifyStatus = subagents > 0 ? "captured" : expectFanout ? "gap" : "flat";+ rows.push({+ comboId: combo.comboId,+ agent,+ harness,+ subagents,+ maxDepth,+ expectFanout,+ status,+ });+ }+ return rows;+}diff --git a/src/viz/open.ts b/src/viz/open.tsnew file mode 100644index 0000000..61b9497--- /dev/null+++ b/src/viz/open.ts@@ -0,0 +1,17 @@+/**+ * 브라우저 열기 (PRD v2 §W2, --view open). 플랫폼별 opener, fail-soft.+ */+import { spawn } from "node:child_process";+import { existsSync } from "node:fs";++export function openInBrowser(file: string): boolean {+ if (!existsSync(file)) return false;+ const opener =+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";+ try {+ spawn(opener, [file], { stdio: "ignore", detached: true }).unref();+ return true;+ } catch {+ return false;+ }+}diff --git a/src/viz/serve.ts b/src/viz/serve.tsnew file mode 100644index 0000000..51e6982--- /dev/null+++ b/src/viz/serve.ts@@ -0,0 +1,91 @@+import { existsSync, readFileSync } from "node:fs";+/**+ * 로컬 서버 (PRD v2 §W2, --view serve). 의존성 0 — node:http 로 runs/ 디렉터리를 서빙.+ * 루트(/)는 모든 run 의 라이브 인덱스. 각 run 의 report.html/graph.html 은 self-contained 그대로 제공.+ * 보안: outDir 밖 경로 접근 차단(path traversal 방지).+ */+import { createServer } from "node:http";+import { normalize, resolve } from "node:path";+import { THEME, svgWordmark } from "../brand";+import { esc } from "../flow";+import { listRuns, loadMeta } from "../recorder";++const TYPES: Record<string, string> = {+ ".html": "text/html; charset=utf-8",+ ".json": "application/json; charset=utf-8",+ ".jsonl": "application/x-ndjson; charset=utf-8",+ ".txt": "text/plain; charset=utf-8",+ ".svg": "image/svg+xml",+};++function indexPage(outDir: string): string {+ const runs = listRuns(outDir);+ const rows = runs+ .map((id) => {+ const meta = loadMeta(outDir, id);+ const bench = meta?.bench ?? "?";+ const mock = meta?.mock ? " · mock" : "";+ return `<li><code>${esc(id)}</code> <span class="b">${esc(bench)}${mock}</span>+ <a href="/${esc(id)}/report.html">report</a> · <a href="/${esc(id)}/graph.html">graph</a></li>`;+ })+ .join("\n");+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>theseus — runs</title>+<style>+body{font-family:ui-sans-serif,system-ui,sans-serif;background:${THEME.sea};color:${THEME.sail};margin:0;padding:28px}+header{display:flex;align-items:center;gap:14px;margin-bottom:18px}+ul{list-style:none;padding:0;max-width:760px}+li{background:${THEME.hull};border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:10px 14px;margin:8px 0;display:flex;gap:12px;align-items:center}+code{font-family:ui-monospace,monospace}+.b{color:${THEME.foam};flex:1;font-size:13px}+a{color:${THEME.rope};text-decoration:none;font-weight:600}+a:hover{text-decoration:underline}+</style></head><body>+<header>${svgWordmark()}<span style="opacity:.7">runs index</span></header>+${runs.length ? `<ul>${rows}</ul>` : "<p>no runs yet</p>"}+</body></html>`;+}++export interface ServeHandle {+ port: number;+ url: string;+ close: () => void;+}++export function serveRuns(outDir: string, port: number): Promise<ServeHandle> {+ const rootAbs = resolve(outDir);+ const server = createServer((req, res) => {+ const urlPath = decodeURIComponent((req.url ?? "/").split("?")[0] ?? "/");+ if (urlPath === "/" || urlPath === "/index.html") {+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });+ res.end(indexPage(outDir));+ return;+ }+ // path traversal 방지: 정규화 후 rootAbs 하위만 허용+ const target = resolve(rootAbs, `.${normalize(urlPath)}`);+ if (!target.startsWith(rootAbs) || !existsSync(target)) {+ res.writeHead(404, { "content-type": "text/plain" });+ res.end("not found");+ return;+ }+ const ext = target.slice(target.lastIndexOf("."));+ try {+ res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream" });+ res.end(readFileSync(target));+ } catch {+ res.writeHead(500, { "content-type": "text/plain" });+ res.end("read error");+ }+ });+ return new Promise((resolvePromise, reject) => {+ server.on("error", reject);+ server.listen(port, () => {+ const addr = server.address();+ const actual = addr && typeof addr === "object" ? addr.port : port;+ resolvePromise({+ port: actual,+ url: `http://localhost:${actual}`,+ close: () => server.close(),+ });+ });+ });+}diff --git a/src/viz/terminal.ts b/src/viz/terminal.tsnew file mode 100644index 0000000..6daf338--- /dev/null+++ b/src/viz/terminal.ts@@ -0,0 +1,114 @@+/**+ * 터미널 시각화 (PRD v2 §W2, --view term). 외부 의존성 0 — picocolors + 박스/막대 문자.+ * 같은 데이터 모델(ComboMetrics, FlowGraph)을 ANSI 로 렌더(리포트와 1:1).+ */+import pc from "picocolors";+import { tr } from "../i18n";+import type { ComboMetrics } from "../metrics";+import { bestByPerspectiveDetailed, sortCombos } from "../metrics";+import type { FlowGraph, FlowNode, Lang } from "../models";++const BAR = "█";+const BAR_W = 24;++function bar(value: number, max: number, color: (s: string) => string): string {+ if (max <= 0) return "";+ const n = Math.max(0, Math.min(BAR_W, Math.round((value / max) * BAR_W)));+ return color(BAR.repeat(n)) + pc.dim("·".repeat(BAR_W - n));+}++function fmtTokens(n: number): string {+ return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);+}++/** 비교 막대 차트 (정확도↑ / 토큰↓ / 비용↓) + 흐름 트리. 문자열 반환(테스트 가능). */+export function renderTerminal(metrics: ComboMetrics[], graphs: FlowGraph[], lang: Lang): string {+ const out: string[] = [];+ const sorted = sortCombos(metrics);+ const labelW = Math.max(8, ...sorted.map((m) => m.comboId.length));++ const chart = (+ title: string,+ pick: (m: ComboMetrics) => number,+ color: (s: string) => string,+ fmt: (n: number) => string,+ ) => {+ const vals = sorted.map(pick).filter((v) => Number.isFinite(v));+ const max = vals.length ? Math.max(...vals) : 0;+ out.push(pc.bold(`\n${title}`));+ for (const m of sorted) {+ const v = pick(m);+ const shown = Number.isFinite(v) ? fmt(v) : pc.dim("null");+ out.push(+ ` ${m.comboId.padEnd(labelW)} ${bar(Number.isFinite(v) ? v : 0, max, color)} ${shown}`,+ );+ }+ };++ chart(+ tr(lang, "col_acc"),+ (m) => m.accuracy,+ pc.green,+ (n) => `${n.toFixed(1)}%`,+ );+ chart(tr(lang, "col_tokens"), (m) => m.totalTokens, pc.cyan, fmtTokens);+ chart(+ tr(lang, "col_cost"),+ (m) => m.costUsd ?? Number.NaN,+ pc.yellow,+ (n) => `$${n.toFixed(4)}`,+ );+ chart(+ tr(lang, "col_subagents"),+ (m) => m.subagentCount,+ pc.magenta,+ (n) => String(n),+ );++ // 관점별 최적+ out.push(pc.bold(`\n${tr(lang, "sec_best")}`));+ for (const b of bestByPerspectiveDetailed(metrics, lang)) {+ out.push(` ${pc.green("▸")} ${b.label}: ${pc.bold(b.comboId)}`);+ }++ // 흐름 트리(대표 그래프들)+ if (graphs.length) {+ out.push(pc.bold(`\n${tr(lang, "sec_flow")}`));+ for (const g of graphs.slice(0, 12)) out.push(renderFlowTree(g));+ }+ return out.join("\n");+}++/** 흐름 그래프를 들여쓰기 트리(박스 문자)로. */+export function renderFlowTree(graph: FlowGraph): string {+ const byParent = new Map<number | null, FlowNode[]>();+ const idxOf = new Map<string, number>();+ graph.nodes.forEach((n, i) => idxOf.set(n.id, i));+ // edges 로 parent→child (없으면 depth 로 추정)+ const parentOf = new Map<string, string>();+ for (const e of graph.edges) parentOf.set(e.dst, e.src);+ for (const n of graph.nodes) {+ const p = parentOf.get(n.id);+ const pIdx = p ? (idxOf.get(p) ?? null) : null;+ const arr = byParent.get(pIdx ?? null) ?? [];+ arr.push(n);+ byParent.set(pIdx ?? null, arr);+ }+ const lines: string[] = [+ ` ${pc.dim(graph.comboId)} ${pc.dim("·")} ${pc.dim(graph.taskId)}#${graph.runIdx}`,+ ];+ const walk = (parentIdx: number | null, prefix: string) => {+ const children = byParent.get(parentIdx) ?? [];+ children.forEach((n, i) => {+ const last = i === children.length - 1;+ const branch = last ? "└─ " : "├─ ";+ const tag = n.isMain ? pc.cyan("main") : pc.magenta(`sub·${n.harness}`);+ const mark = n.status === "fail" ? pc.red(" ✗") : n.highlight ? pc.yellow(" ★") : "";+ const stat = pc.dim(`${fmtTokens(n.tokens)} tok · ${n.toolCalls} tools`);+ lines.push(` ${prefix}${branch}${tag}${mark} ${stat}`);+ walk(idxOf.get(n.id) ?? null, prefix + (last ? " " : "│ "));+ });+ };+ walk(null, "");+ return lines.join("\n");+}diff --git a/tests/harnesses.test.ts b/tests/harnesses.test.tsnew file mode 100644index 0000000..a581d3c--- /dev/null+++ b/tests/harnesses.test.ts@@ -0,0 +1,93 @@+/**+ * W1 — 신규 하네스 (oh-my-openagent=omo / ponytail / mattpocock).+ * 호환 매핑(combo 유효성), mock fan-out(오케스트레이션 × 에이전트), 적용 메커니즘.+ */+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { expand } from "../src/combos";+import { HARNESSES } from "../src/config";+import { MockRunner } from "../src/runners/mock";+import { parserFor } from "../src/transcripts/index";++function tmp(): string {+ return mkdtempSync(join(tmpdir(), "theseus-h-"));+}++async function fanout(+ comboId: string,+ agent: string,+ model: string,+ harness: string,+): Promise<number> {+ const art = await new MockRunner(0).run({+ combo: { comboId, agent, model, harness, valid: true },+ taskId: "subagent-102",+ runIdx: 0,+ workDir: tmp(),+ timeoutS: 5,+ seed: 1,+ bench: "subagent",+ });+ return parserFor(agent).parse(art.transcriptPath, { model }).subagentCount;+}++describe("new harness registry + mapping", () => {+ it("registers omo/ponytail/mattpocock with correct agents + orchestration", () => {+ expect(HARNESSES.omo?.agents.sort()).toEqual(["codex", "opencode"]);+ expect(HARNESSES.omo?.orchestration).toBe(true);+ expect(HARNESSES.ponytail?.agents.sort()).toEqual([+ "cc",+ "codex",+ "hermes",+ "openclaw",+ "opencode",+ ]);+ expect(HARNESSES.ponytail?.orchestration).toBe(false);+ expect(HARNESSES.mattpocock?.agents.sort()).toEqual(["cc", "codex", "opencode"]);+ expect(HARNESSES.mattpocock?.orchestration).toBe(false);+ });++ it("expand: combos valid/excluded per researched mapping", () => {+ const { valid, excluded } = expand(+ ["opus4.8", "gpt5.5"],+ ["cc", "codex", "opencode", "openclaw", "hermes"],+ ["omo", "ponytail", "mattpocock"],+ );+ const ids = new Set(valid.map((c) => c.comboId));+ // omo → opencode + codex+ expect(ids.has("opencode+gpt5.5+omo")).toBe(true);+ expect(ids.has("codex+gpt5.5+omo")).toBe(true);+ expect(excluded.find((c) => c.comboId === "cc+opus4.8+omo")?.excludeReason).toMatch(+ /not compatible/,+ );+ // ponytail → everyone+ expect(ids.has("cc+opus4.8+ponytail")).toBe(true);+ expect(ids.has("hermes+gpt5.5+ponytail")).toBe(true);+ // mattpocock → cc/codex/opencode; hermes & openclaw excluded+ expect(ids.has("opencode+opus4.8+mattpocock")).toBe(true);+ expect(excluded.find((c) => c.comboId === "hermes+gpt5.5+mattpocock")?.excludeReason).toMatch(+ /not compatible/,+ );+ expect(+ excluded.find((c) => c.comboId === "openclaw+opus4.8+mattpocock")?.excludeReason,+ ).toMatch(/not compatible/);+ });+});++describe("mock fan-out: orchestration × agent capability", () => {+ it("opencode+omo fans out (subagents>0); opencode+none stays flat", async () => {+ expect(await fanout("opencode+gpt5.5+omo", "opencode", "gpt5.5", "omo")).toBeGreaterThan(0);+ expect(await fanout("opencode+gpt5.5+none", "opencode", "gpt5.5", "none")).toBe(0);+ });+ it("cc+mattpocock fans out; codex+omo stays flat (single loop)", async () => {+ expect(await fanout("cc+opus4.8+mattpocock", "cc", "opus4.8", "mattpocock")).toBeGreaterThan(0);+ expect(await fanout("codex+gpt5.5+omo", "codex", "gpt5.5", "omo")).toBe(0);+ });+ it("determinism: same combo+seed → identical subagent count", async () => {+ const a = await fanout("opencode+gpt5.5+omo", "opencode", "gpt5.5", "omo");+ const b = await fanout("opencode+gpt5.5+omo", "opencode", "gpt5.5", "omo");+ expect(a).toBe(b);+ });+});diff --git a/tests/install.test.ts b/tests/install.test.tsnew file mode 100644index 0000000..5c80290--- /dev/null+++ b/tests/install.test.ts@@ -0,0 +1,26 @@+/**+ * W7 — install 하드닝. 상태 점검/베스트에포트가 throw 없이 동작.+ */+import { describe, expect, it, vi } from "vitest";+import { installBinary, runInstall, runInstallCheck } from "../src/install";++describe("install hardening", () => {+ it("runInstallCheck prints status without throwing", () => {+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ expect(() => runInstallCheck()).not.toThrow();+ expect(log).toHaveBeenCalled();+ log.mockRestore();+ });++ it("installBinary reports presence (claude available, fake missing)", () => {+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ expect(typeof installBinary("cc")).toBe("boolean");+ log.mockRestore();+ });++ it("runInstall on unknown component lists valid options (no throw)", async () => {+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ await expect(runInstall("nonsense-xyz")).resolves.toBeUndefined();+ log.mockRestore();+ });+});diff --git a/tests/tui.test.ts b/tests/tui.test.tsnew file mode 100644index 0000000..e6bad64--- /dev/null+++ b/tests/tui.test.ts@@ -0,0 +1,13 @@+/**+ * W4 — 인터랙티브 TUI. 비-TTY(테스트/CI)에서는 runInk 가 false 를 반환해 cli-table3 폴백.+ */+import { describe, expect, it } from "vitest";+import { runInk } from "../src/tui/inkApp";++describe("ink TUI fallback", () => {+ it("runInk returns false in non-TTY (so caller falls back to table)", async () => {+ // vitest stdout 은 TTY 가 아님 → ink 미기동+ const ok = await runInk({ out: "runs", language: "en" });+ expect(ok).toBe(false);+ });+});diff --git a/tests/verify.test.ts b/tests/verify.test.tsnew file mode 100644index 0000000..1a68379--- /dev/null+++ b/tests/verify.test.ts@@ -0,0 +1,37 @@+/**+ * W5 — theseus verify (조합별 서브에이전트 콜 포착 검증).+ */+import { describe, expect, it } from "vitest";+import { expectsFanout, verifyCombos } from "../src/verify";++describe("expectsFanout model", () => {+ it("cc+orchestration and opencode+omo expect fan-out; single-loop combos do not", () => {+ expect(expectsFanout("cc", "omc")).toBe(true);+ expect(expectsFanout("cc", "superpowers")).toBe(true);+ expect(expectsFanout("cc", "none")).toBe(false);+ expect(expectsFanout("opencode", "omo")).toBe(true);+ expect(expectsFanout("codex", "omo")).toBe(false);+ expect(expectsFanout("hermes", "ponytail")).toBe(false);+ });+});++describe("verifyCombos (mock)", () => {+ it("captures fan-out for cc+omc and opencode+omo; codex/none stay flat (no gaps)", async () => {+ const rows = await verifyCombos({+ models: ["opus4.8", "gpt5.5"],+ agents: ["cc", "opencode", "codex"],+ harnesses: ["none", "omc", "omo"],+ runner: "mock",+ seed: 1,+ timeoutS: 5,+ });+ const byId = new Map(rows.map((r) => [r.comboId, r]));+ expect(byId.get("cc+opus4.8+omc")?.status).toBe("captured");+ expect(byId.get("cc+opus4.8+omc")?.subagents).toBeGreaterThan(0);+ expect(byId.get("opencode+opus4.8+omo")?.status).toBe("captured");+ expect(byId.get("codex+gpt5.5+none")?.status).toBe("flat");+ expect(byId.get("opencode+gpt5.5+none")?.status).toBe("flat");+ // mock 은 결정적 → gap(포착 누락) 없어야 함+ expect(rows.filter((r) => r.status === "gap")).toHaveLength(0);+ });+});diff --git a/tests/viz.test.ts b/tests/viz.test.tsnew file mode 100644index 0000000..b12135d--- /dev/null+++ b/tests/viz.test.ts@@ -0,0 +1,95 @@+import { mkdtempSync, readFileSync } from "node:fs";+/**+ * W2/W3 — 시각화 전달 모드 + 고도화.+ * term(ANSI), serve(localhost), Pareto frontier, 브랜딩 self-contained.+ */+import { get } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import type { RunOptions } from "../src/models";+import { execute } from "../src/orchestrator";+import { serveRuns } from "../src/viz/serve";+import { renderTerminal } from "../src/viz/terminal";++function opts(out: string): RunOptions {+ return {+ models: ["opus4.8", "gpt5.5"],+ agents: ["cc", "opencode", "codex"],+ harnesses: ["none", "omo", "ponytail"],+ bench: "subagent",+ tasks: 3,+ runs: 1,+ seed: 5,+ runner: "mock",+ concurrency: 4,+ timeoutS: 5,+ outDir: out,+ judge: "none",+ score: false,+ balanced: false,+ language: "en",+ };+}++function httpGet(url: string): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ get(url, (res) => {+ let body = "";+ res.on("data", (c) => {+ body += c;+ });+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body }));+ }).on("error", reject);+ });+}++describe("--view term (ANSI)", () => {+ it("emits charts, perspective picks, and a flow tree", async () => {+ const out = mkdtempSync(join(tmpdir(), "theseus-viz-"));+ const res = await execute(opts(out));+ const ansi = renderTerminal(res.metrics, res.graphs, "en");+ const plain = ansi.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"), "");+ expect(plain).toMatch(/accuracy/);+ expect(plain).toMatch(/total tok/);+ expect(plain).toMatch(/█|·/); // bar chars+ expect(plain).toMatch(/├─|└─/); // flow tree+ });+});++describe("--view serve (localhost)", () => {+ it("serves a run index and a self-contained report", async () => {+ const out = mkdtempSync(join(tmpdir(), "theseus-srv-"));+ const res = await execute(opts(out));+ const handle = await serveRuns(out, 0);+ try {+ const index = await httpGet(`${handle.url}/`);+ expect(index.status).toBe(200);+ expect(index.body).toMatch(/runs index/);+ expect(index.body).toContain(res.runId);++ const report = await httpGet(`${handle.url}/${res.runId}/report.html`);+ expect(report.status).toBe(200);+ expect(report.body).not.toMatch(/<script/i);++ // path traversal 차단+ const evil = await httpGet(`${handle.url}/../../etc/hosts`);+ expect(evil.status).toBe(404);+ } finally {+ handle.close();+ }+ });+});++describe("Pareto frontier marking", () => {+ it("report marks the cost/accuracy frontier", async () => {+ const out = mkdtempSync(join(tmpdir(), "theseus-par-"));+ const res = await execute(opts(out));+ const html = readFileSync(res.reportPath, "utf8");+ expect(html).toMatch(/Pareto frontier/);+ // 브랜딩: 로고 + 철학 + self-contained+ expect(html).toMatch(/Ship of Theseus/);+ expect(html).toContain("<svg");+ expect(html).not.toMatch(/<script/i);+ });+});