SLOPSHOPPER

game-harness-monitor

코드를 무엇으로 찾았는지(인덱스 대 grep)를 프롬프트 위 띠로, 하네스 기능을 상태줄·토스트·/harness 패널로, 세션들 이력을 /harness-history HTML 로 보여준다

panebandguardcommandtoaststatus
v0.1.0no licenseupdated 2026-10-23jokate/jokate-harness/mods/game-harness-monitor
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · game-harness-monitor
│ ┃ Harness ✕ › fix the failing auth test and add an audit log call │ ┃ 코드 탐색 · 인덱스 0 · 직접 1 (0% 인덱스) · │ ┃ clangd 인덱스 없음 ⏺ Read(src/auth.ts) │ ┃ gq 좌표 인덱스 · 0 ⎿ Read 6 lines │ ┃ clangd 의미 인덱스 · 0 ⏺ Update(src/auth.ts) │ ┃ 위키 · 0 ⎿ Added 2 lines, removed 1 line │ ┃ ue_q 엔진 인덱스 · 0 ⏺ Bash(bun test) │ ┃ grep 직접 검색 · 0 ⎿ 3 pass, 1 fail │ ┃ 파일 찾기 · 0 │ ┃ 파일 읽기 ██████████████████████ 1 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ──────────────────────────────────────── │ ┃ 하네스 기능 0개 · 기록 0건 ✻ Worked for 42s · done 4:20 PM │ ┃ ──────────────────────────────────────── │ ┃ 08:53 읽기 auth.ts › /harness │ ┃ 세션들 이력: /harness-history ⎿ game-harness-monitor: 하네스 패널을 열었다 (이 세션 기록 0건). 세션들 이력은 /harness │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Harness
코드 탐색 · 인덱스 0 · 직접 1 (0% 인덱스) · clangd 인덱스 없음 gq 좌표 인덱스 · 0 clangd 의미 인덱스 · 0 위키 · 0 ue_q 엔진 인덱스 · 0 grep 직접 검색 · 0 파일 찾기 · 0 파일 읽기 ██████████████████████ 1 ──────────────────────────────────────── 하네스 기능 0개 · 기록 0건 ──────────────────────────────────────── 08:53 읽기 auth.ts 세션들 이력: /harness-history
README

jokate-harness

게임 프로젝트(Unreal Engine / Unity)용 Claude Code 하네스. 어느 프로젝트에 들어가도 엔진·프로젝트·기획을 좌표로 빠르게 파악하고, 기능 요청에서 한 기능에 매몰되지 않고 유지보수가 가장 좋은 구조를 근거(변경 이력 계측 + 그림)와 함께 사람이 고르게 한다.

구성

skills/
  game-bootstrap/     0층 · 프로젝트 세팅 (/game-bootstrap) · harness/ 훅 원본 · evals/ 평가
  game-onboard/       1층 · 엔진·프로젝트 파악 · scripts/gq.py, ue_q.py, cindex.py(clangd 의미 인덱스 · 증분·유니티는 cindex_speed.py, RIFF 는 clangd_riff.py, 런처 엔진의 엔진 cdb 는 engine_cdb.py), index_view.py(웹뷰)
  game-design-doc/    1층 · 기획서 → 사양 표 → 구현 대응·어긋남
  game-architecture/  2층 · 구현 전 구조 조사 · scripts/evidence.py, render.py · references/patterns/ 패턴 카탈로그 + 게임 도메인 증상 + UE/Unity 관용구 (옛 game-patterns)
  game-testing/       3층 · 검증 기준·테스트
  game-mcp/           4층 · 에디터 MCP 운용
mods/
  game-harness-monitor/  Claude Code mod · 하네스 기능이 동작하면 상태줄·토스트·/harness 패널로 보인다
tools/
  harness_probe.py    하네스 대조 시험: 같은 과제를 지금 · 수정안 두 팔로 돌려 정답 재현율 · 스킬 호출 · 비용 · 도구 사용을 비교
  context_budget.py   세션마다 항상 들어가는 글의 크기 (하네스 몫 한도 7,000 B)
docs/experience/      대조로 뒷받침된 하네스 교훈 (목차 INDEX.md — 하네스를 고치기 전에 본다)
setup.bat             한 번에: 설치 + 훅 등록 + mod 등록 + (옆에 있으면) 위키 하네스 + 프로젝트 세팅 + 사용법 출력
uninstall.bat         제거: 스킬·훅·설정 항목 (+ 프로젝트 폴더를 주면 그 세팅도)
rules/common.md       모든 프로젝트 공용 규칙 (답변 길이). 설치 때 ~/.claude/CLAUDE.md 의 표시 구간에 들어간다
install.py / .bat    머신 설치: 스킬·훅, settings 조각 출력 (bat 는 더블클릭용)
bootstrap.bat         프로젝트 세팅: 폴더를 끌어다 놓으면 CLAUDE.local.md + 인덱스 선언
index_build.bat       인덱스 지금 만들기: 프로젝트 좌표 → 엔진 좌표 → clangd (프로젝트 증분, 엔진은 없을 때만) → 조회용 정리
index_view.bat        인덱스 웹뷰

빠른 시작

setup.bat 더블클릭 (Windows) — 또는 게임 프로젝트 폴더를 setup.bat 위에 끌어다 놓는다. 한 번에:

  1. 스킬·훅·mod 를 ~/.claude 에 설치하고 settings.json 에 훅과 mod(env.CLAUDE_CODE_PLUGIN_DIRS)를 등록한다 (원본은 settings.json.bak)
  2. 위키 하네스(jokate-wiki, 비공개)가 이 폴더 옆에 있거나 JOKATE_WIKI_DIR 로 알려 주면 그것도 설치한다 (없으면 건너뛴다, --no-wiki 로 끈다). 새 PC 에서는 같은 폴더 안에 나란히 받는다: git clone https://github.com/jokate/jokate-harness.git game-harness · git clone https://github.com/jokate/jokate-wiki.git jokate-wiki 그림 스킬 diagram-design(MIT)도 옆에 받아 두면(git clone --depth 1 https://github.com/cathrynlavery/diagram-design.git diagram-design) 스킬로 연결한다 — game-architecture 의 구조 그림 · 위키의 보기용 그림을 그것으로 그린다. 처음 그릴 때 스타일을 한 번 묻는다
  3. 프로젝트 폴더를 물어보고 세팅한다 (CLAUDE.local.md + 인덱스 선언. CLAUDE.md 가 이미 있으면 라우팅 절만. 덮어쓰지 않는다). 위키 하네스가 있으면 그 프로젝트의 위키까지 만든다 — 면담 답 초안 · 위키(~/.jokate-wiki/<프로젝트>) · 뼈대 · 세션 시작 훅, AI 없음. 면담 다듬기 · 파트 묶기 · 설명 미리 채우기는 그 뒤 Claude Code 에서 /wiki-bootstrap (선택)
  4. clangd 프로젝트 인덱스(호출 · 참조 · 영향 범위)가 없으면 지금 만들지 묻는다 — 백그라운드로 처음 20–30분, 엔진 단계 없음(index_all.py --project-only), 로그는 ~/.claude/cache/game-harness/index_build_<프로젝트>.log. --clangd 면 묻지 않고 시작, --no-clangd 면 안 한다. 그 뒤로는 세션 시작 때 바뀐 것만 갱신된다
  5. 사용법을 출력한다

PowerShell 에서는 .\setup.bat "D:\Work\MyGame". 다시 돌려도 안전하다 — 다른 프로젝트를 추가할 때도 같은 파일. 그 뒤에는 그 프로젝트에서 Claude Code 를 새로 열고 평소처럼 요청하면 된다.

나눠서 하려면 install.bat(머신) + bootstrap.bat(프로젝트). 프로젝트 규칙 파일이 없으면 스킬이 거의 불리지 않는다 — 평가로 확인한 사실이다 (검증 기록).

인덱스를 지금 만들려면 프로젝트 폴더를 index_build.bat 위에 끌어다 놓는다 (더블클릭이면 하네스가 최근에 돈 프로젝트). 프로젝트 좌표 → 엔진 좌표 → clangd 의미 인덱스 순으로 돌고, 끝에 단계별 완료·건너뜀·실패와 이유를 보여 준다. 엔진 폴더를 못 찾으면 창에서 경로를 묻고 프로젝트별로 저장한다 (명령 창에서는 --engine-root <엔진 폴더>). clangd 도구는 setup 이 설치한다 — 받지 못했으면 clangd 단계만 건너뛰고, setup.bat 을 다시 돌리면 된다.

제거

uninstall.bat 더블클릭 — 또는 세팅했던 프로젝트 폴더를 그 위에 끌어다 놓는다. 미리보기는 --dry-run.

  • 머신: ~/.claude/skills/game-*·~/.claude/mods/game-harness-monitor(링크만 끊는다), 설치한 훅 파일, settings.json 의 해당 훅 항목과 mod 경로(원본은 .bak, 다른 훅·env 는 그대로), 하네스 이벤트 로그. --purge 면 엔진 인덱스와 setup 이 받은 clangd 도구도
  • 프로젝트: CLAUDE.local.md 는 CLAUDE.local.md.removed 로 이름만 바꾼다. 인덱스 선언·HandOff·프로젝트 인덱스는 지운다. CLAUDE.md 는 건드리지 않는다
  • 한 프로젝트에서만 빼려면 uninstall.bat "<폴더>" --project-only
  • 이 저장소 폴더는 남는다. 다시 쓰려면 setup.bat

요구

Python 3.10+, git (svn 은 선택 — 이력 신호용, 검증 안 됨), Claude Code 2.1.x. clangd·clangd-indexer(의미 인덱스용)는 setup 이 없을 때만 내려받는다 (clangd 23.1.0 고정, SHA-256 대조, Windows 약 63MB — 실패해도 나머지는 동작). 모니터 mod 는 Claude Code 의 함수 훅 플러그인(early access, 2.1.290 에서 확인)이 필요하다.

하네스가 동작하는지 보기

  • 상태줄 harness ● 기능 N개 · 마지막 … 과 토스트 — 모니터 mod. /harness 로 기록 패널.
  • index_view.bat 더블클릭 — 인덱스 검색·그래프·검증과 하네스 이벤트 기록을 브라우저로. 프로젝트 폴더를 끌어다 놓으면 그 프로젝트, 그냥 더블클릭하면 하네스가 최근에 돈 프로젝트. 이미 떠 있으면 새로 띄우지 않고 연다. 화면 오른쪽 위에서 프로젝트를 바꾼다. (터미널: python ~/.claude/skills/game-onboard/scripts/index_view.py --open [--root <프로젝트>])
  • 상세: docs/GUIDE.md 8절.
Source 2 files
hooks/register.tsx 593 lines
1// game-harness-monitor — 하네스가 이 세션에서 "어떤 기능을 동작시켰는지"와 "코드를 무엇으로 찾았는지" 보여준다.
2//
3// 근거 자료 두 가지:
4//  1) 하네스 훅·스크립트가 남기는 이벤트 로그 (~/.claude/cache/game-harness/events.jsonl,
5//     형식은 skills/game-bootstrap/harness/harness_events.py) — 읽기만 한다.
6//  2) 이 세션의 도구 호출 — 인덱스(gq · clangd · 위키 · ue_q)로 찾았나, 직접(grep · 파일 찾기 · 파일 읽기) 찾았나를 센다.
7//     세션 요약은 $.store 에 남겨 이력 페이지를 만든다. 도구 호출을 막거나 결과를 바꾸지 않는다 — 소스에서 C++ 심볼을
8//     grep 하고 그 심볼이 clangd 인덱스에 있으면 결과 뒤에 cindex 명령 한 줄을 붙일 뿐이다(세션당 3번).
9//     로그 · 문서 · 설정 · 명령 출력을 거르는 grep 은 코드 탐색이 아니라 세지 않는다.
10//
11//   프롬프트 위 띠  코드 탐색 │ gq 3 · clangd 0 · 위키 2 · ue_q 0 │ 직접 grep 12 · 찾기 4 · 읽기 30   (게임 프로젝트)
12//   상태줄          harness ● 기능 N개 · 마지막 <기능>
13//   토스트          기능이 처음 동작할 때, clangd · 위키를 이 세션에서 처음 쓸 때
14//   /harness         패널: 코드 탐색 횟수 · 하네스 기능 · 최근 기록
15//   /harness-history 이력 HTML(세션별 탐색 · 기능 · 최근 기록)을 만들어 브라우저로 연다
16// 사용자: "clangd 가 많이 안 불리는 것 같은데 하단에 쥐똥만하게 나온다 — 확실하게 알 수 있게, 이력은 상세 페이지로"(2026-10-20).
17import { atom, read, update } from 'claude-code'
18import type { EngineInterface, Register } from 'claude-code'
19
20import type { Counts, HarnessEvent, Kind, ProjectInfo, SearchEvent, SessionSummary } from '../types'
21
22const PANE = 'game-harness'
23const POLL_MS = 3000
24const KEEP = 300
25const KEEP_SEARCH = 200
26const KEEP_SESSIONS = 200
27
28export const INDEX_KINDS: readonly Kind[] = ['gq', 'clangd', 'wiki', 'ue_q']
29export const DIRECT_KINDS: readonly Kind[] = ['grep', 'glob', 'read']
30const SHORT: Record<Kind, string> = {
31  gq: 'gq', clangd: 'clangd', wiki: '위키', ue_q: 'ue_q', grep: 'grep', glob: '찾기', read: '읽기',
32}
33const LONG: Record<Kind, string> = {
34  gq: 'gq 좌표 인덱스', clangd: 'clangd 의미 인덱스', wiki: '위키', ue_q: 'ue_q 엔진 인덱스',
35  grep: 'grep 직접 검색', glob: '파일 찾기', read: '파일 읽기',
36}
37
38export function emptyCounts(): Counts {
39  return { gq: 0, clangd: 0, wiki: 0, ue_q: 0, grep: 0, glob: 0, read: 0 }
40}
41
42const events = atom({ plugin: 'game-harness-monitor', key: 'events' } as const, [] as HarnessEvent[])
43const counts = atom({ plugin: 'game-harness-monitor', key: 'counts' } as const, emptyCounts())
44const searches = atom({ plugin: 'game-harness-monitor', key: 'searches' } as const, [] as SearchEvent[])
45const project = atom({ plugin: 'game-harness-monitor', key: 'project' } as const,
46  { isGame: false, hasClangd: false, hasWiki: false } as ProjectInfo)
47
48const LABELS: Record<string, string> = {
49  'context.routing': '세션 라우팅 주입',
50  'stuck.warn': '매몰 경고',
51  'mcp.guard': 'MCP 가드 경고',
52  'mcp.call': 'MCP 호출 기록',
53}
54
55const PREFIXES: [string, string][] = [
56  ['skill.', '스킬 '],
57  ['script.', '조회 '],
58  ['session_start.', '세션 시작 명령 '],
59  ['index.', '인덱스 '],
60]
61
62export function label(feature: string): string {
63  const fixed = LABELS[feature]
64  if (fixed !== undefined) return fixed
65  for (const [prefix, name] of PREFIXES) {
66    if (feature.startsWith(prefix)) return name + feature.slice(prefix.length)
67  }
68  return feature
69}
70
71const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
72const base = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').split('/').pop() ?? p
73
74// 세션 id 가 있는 이벤트(훅이 남긴 것)는 id 로, 없는 것(스크립트가 직접 남긴 것)은 프로젝트 경로와 시각으로 가른다.
75export function belongs(ev: HarnessEvent, sessionId: string, root: string, startedAt: number): boolean {
76  if (ev.session !== '') return ev.session === sessionId
77  if (ev.ts < startedAt || ev.project === '') return false
78  const p = norm(ev.project)
79  const r = norm(root)
80  return r === p || r.startsWith(p + '/') || p.startsWith(r + '/')
81}
82
83export function parse(text: string): HarnessEvent[] {
84  const out: HarnessEvent[] = []
85  for (const line of text.split('\n')) {
86    if (line.trim() === '') continue
87    try {
88      const ev = JSON.parse(line) as HarnessEvent
89      if (typeof ev.feature === 'string' && typeof ev.ts === 'number') out.push(ev)
90    } catch {
91      // 반쯤 쓰인 줄은 다음 폴링에서 다시 읽힌다
92    }
93  }
94  return out
95}
96
97export function statusText(list: readonly HarnessEvent[]): string | undefined {
98  const last = list.at(-1)
99  if (last === undefined) return undefined
100  const features = new Set(list.map(ev => ev.feature)).size
101  const failed = list.filter(ev => !ev.ok).length
102  return `harness ● 기능 ${features}개 · 마지막 ${label(last.feature)}${last.ok ? '' : ' ✗'}` +
103    (failed > 0 ? ` · 실패 ${failed}` : '')
104}
105
106const INDEX_SCRIPT = /(cindex|gq|wq|ue_q)\.py["']?(?:\s+([a-z][\w-]*))?(?:\s+([^\s|;&>"']+))?/
107const KIND_OF_SCRIPT: Record<string, Kind> = { cindex: 'clangd', gq: 'gq', wq: 'wiki', ue_q: 'ue_q' }
108const GREP_CMD = /(^|[\s|;&(])(rg|grep|egrep|findstr|Select-String|sls)(\s|$)/
109const FIND_CMD = /(^|[\s|;&(])(find|fd|Get-ChildItem|gci|dir|ls)(\s|$)/
110
111// grep 이 코드를 찾는가. 로그 · 문서 · 설정 · 앞 명령의 출력을 거르는 grep 은 코드 탐색이 아니라 세지 않는다 —
112// MNYS 세션 52개(10-20~22)의 grep 대부분이 Saved/Logs 의 로그 줄 · Docs 의 기획 용어 · git 출력이었고, 그것까지 세서
113// "clangd 인덱스가 있는데 grep 만 씀" 이 늘 떴다.
114const CODE_TARGET = /(^|[\s"'=:/\\])(Source|Plugins)([/\\\s"']|$)|\.(h|hpp|cpp|cc|cxx|inl|cs)\b|--type[= ]?(cpp|c|cs)\b|(^|\s)-t\s*(cpp|c|cs)\b/i
115const TEXT_TARGET = /Saved[/\\]Logs|\.(log|md|txt|json|ini|csv|ya?ml)\b|(^|[\s"'=:/\\])(Docs|Config|Saved)([/\\\s"']|$)/i
116const PIPED_GREP = /\|\s*(rg|grep|egrep|findstr|Select-String|sls)\b[^|;&]*/g
117const PATHLIKE = /[A-Za-z]:[/\\]\S*|\S*\/\S*/g
118// C++ 심볼처럼 보이는 이름: A::B, UE 접두 타입(FYSInput · UThing · AActor · EKind · IFace · TArray), 두 마디 이상 CamelCase
119const SYMBOL = /\b[A-Za-z_]\w*::[A-Za-z_]\w*|\b[AUFEIT][A-Z]\w*[a-z]\w*|\b[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+\b/g
120const hasSymbol = (text: string) => new RegExp(SYMBOL.source).test(text)
121
122export function grepTarget(tool: string, args: Record<string, unknown>): 'code' | 'text' {
123  const s = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
124  if (tool === 'Grep') {
125    const where = `${s('path')} ${s('glob')}`
126    if (CODE_TARGET.test(where) || /^(cpp|c|cs|csharp)$/i.test(s('type'))) return 'code'
127    if (TEXT_TARGET.test(where) || /^(md|markdown|json|log|txt|ini|yaml)$/i.test(s('type'))) return 'text'
128    return hasSymbol(s('pattern')) ? 'code' : 'text'
129  }
130  const cmd = s('command')
131  if (CODE_TARGET.test(cmd)) return 'code'
132  if (TEXT_TARGET.test(cmd)) return 'text'
133  const own = cmd.replace(PIPED_GREP, ' ')
134  if (!GREP_CMD.test(own)) return 'text' // 앞 명령의 출력만 거른다 (git log | grep …)
135  return hasSymbol(own.replace(PATHLIKE, ' ')) ? 'code' : 'text'
136}
137
138// grep 이 찾던 C++ 심볼 후보 (한정 이름 → UE 접두 타입 → 그 밖, 3개까지). 경로 · 뒤에 붙은 grep 은 뺀다.
139export function symbolCandidates(tool: string, args: Record<string, unknown>): string[] {
140  const s = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
141  const text = tool === 'Grep' ? s('pattern') : s('command').replace(PIPED_GREP, ' ').replace(PATHLIKE, ' ')
142  const names = [...new Set([...text.matchAll(SYMBOL)].map(m => m[0]))]
143  const rank = (n: string) => (n.includes('::') ? 0 : /^[AUFEIT][A-Z]/.test(n) ? 1 : 2)
144  return names.sort((a, b) => rank(a) - rank(b)).slice(0, 3)
145}
146
147// `cindex.py sym <이름>` 출력의 첫 줄 — 정확히 맞는 심볼이 없으면 undefined
148export function symbolLine(out: string): string | undefined {
149  const first = out.split(/\r?\n/).find(l => l.trim() !== '')
150  if (first === undefined || /^(#|없음|clangd 인덱스 없음)/.test(first.trim())) return undefined
151  return first.trim().replace(/\s+/g, ' ')
152}
153
154export function nudgeText(name: string, found: string, script: string): string {
155  const cmd = `python ${script}`
156  return `[game-harness] grep 한 \`${name}\` 은 clangd 인덱스에 있다 — ${found}. ` +
157    `쓰는 곳 \`${cmd} refs ${name}\` · 부르는 곳 \`callers\` · 파생 \`derived\` · 바꾸면 영향 \`impact\` ` +
158    '(컴파일 기준이라 주석 · 문자열 · 같은 이름이 안 섞이고 생성 코드는 빠진다. 같은 이름이 여럿이면 A::B 로 좁힌다). ' +
159    '코드 심볼은 다음부터 이쪽을 먼저 쓴다 — 문자열 · 주석 · 로그를 찾을 때만 grep.'
160}
161
162// 도구 호출 하나 → 코드 탐색 종류. 탐색이 아니면 undefined.
163export function classify(tool: string, args: Record<string, unknown>): { kind: Kind; what: string } | undefined {
164  const s = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
165  if (tool === 'Bash' || tool === 'PowerShell') {
166    const cmd = s('command')
167    const m = INDEX_SCRIPT.exec(cmd)
168    if (m) return { kind: KIND_OF_SCRIPT[m[1]], what: [m[2], m[3]].filter(Boolean).join(' ') }
169    if (GREP_CMD.test(cmd)) return grepTarget(tool, args) === 'code' ? { kind: 'grep', what: cmd.slice(0, 80) } : undefined
170    if (FIND_CMD.test(cmd)) return { kind: 'glob', what: cmd.slice(0, 80) }
171    return undefined
172  }
173  if (tool === 'Grep') return grepTarget(tool, args) === 'code' ? { kind: 'grep', what: s('pattern') } : undefined
174  if (tool === 'Glob') return { kind: 'glob', what: s('pattern') }
175  if (tool === 'Read') {
176    const p = s('file_path')
177    return { kind: /[\\/]\.jokate-wiki[\\/]/.test(p) ? 'wiki' : 'read', what: base(p) }
178  }
179  return undefined
180}
181
182const total = (c: Counts, kinds: readonly Kind[]) => kinds.reduce((n, k) => n + c[k], 0)
183
184// clangd 인덱스가 있는데 안 쓰고 grep 으로만 찾고 있으면 알린다
185export function clangdIdle(c: Counts, proj: ProjectInfo): boolean {
186  return proj.hasClangd && c.clangd === 0 && c.grep >= 5
187}
188
189export function upsertSession(list: readonly SessionSummary[], s: SessionSummary): SessionSummary[] {
190  return [...list.filter(x => x.id !== s.id), s].sort((a, b) => a.started - b.started).slice(-KEEP_SESSIONS)
191}
192
193const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
194const pct = (a: number, b: number) => (b === 0 ? 0 : Math.round((a * 100) / b))
195const stamp = (ms: number) => {
196  const d = new Date(ms)
197  const two = (n: number) => String(n).padStart(2, '0')
198  return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
199}
200
201const PAGE_CSS = [
202  ':root{--bg:#f6f5f2;--card:#fff;--fg:#1d2125;--mute:#5f6b76;--line:#e4e2dc;--soft:#f1efea;--accent:#bf4520;--tint:rgba(191,69,32,.07);--ok:#2f7d4f;--warn:#9a6a12;--warnbg:#f6eedb;--idx:#3d6fb6;--dir:#9aa4ad;color-scheme:light}',
203  '@media (prefers-color-scheme:dark){:root:not([data-theme=light]){--bg:#0f1215;--card:#171b20;--fg:#e4e7ea;--mute:#98a2ad;--line:#2a3037;--soft:#1d2228;--accent:#f0875a;--tint:rgba(240,135,90,.10);--ok:#7fc79a;--warn:#e0b85f;--warnbg:#2f2817;--idx:#7aa7e6;--dir:#4a535c;color-scheme:dark}}',
204  ':root[data-theme=dark]{--bg:#0f1215;--card:#171b20;--fg:#e4e7ea;--mute:#98a2ad;--line:#2a3037;--soft:#1d2228;--accent:#f0875a;--tint:rgba(240,135,90,.10);--ok:#7fc79a;--warn:#e0b85f;--warnbg:#2f2817;--idx:#7aa7e6;--dir:#4a535c;color-scheme:dark}',
205  '*{box-sizing:border-box} html,body{background:var(--bg)}',
206  'body{margin:0;color:var(--fg);font:15px/1.65 "Pretendard Variable",Pretendard,"Malgun Gothic","Apple SD Gothic Neo",system-ui,sans-serif;word-break:keep-all}',
207  '.wrap{max-width:1040px;margin:0 auto;padding:32px 20px 64px}',
208  '.top{display:flex;justify-content:space-between;align-items:center;gap:12px} .eyebrow{font-size:12px;color:var(--mute);letter-spacing:.06em}',
209  '.theme{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:5px 14px;font:inherit;font-size:13px;cursor:pointer}',
210  'h1{font-size:28px;letter-spacing:-.02em;margin:4px 0 20px} h2{font-size:17px;margin:0 0 12px;display:flex;gap:10px;align-items:center}',
211  'h2::before{content:"";width:4px;height:17px;border-radius:2px;background:var(--accent)}',
212  'section{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px 22px;margin:0 0 16px}',
213  'section.lead{background:var(--tint);border-color:transparent} .note{color:var(--mute);font-size:13px;margin:8px 0 0}',
214  '.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}',
215  '.kpi{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 14px} .kpi b{display:block;font-size:22px;font-variant-numeric:tabular-nums} .kpi span{color:var(--mute);font-size:12.5px}',
216  '.tbl{overflow-x:auto;border:1px solid var(--line);border-radius:10px}',
217  'table{border-collapse:collapse;width:100%;font-size:13.5px;font-variant-numeric:tabular-nums}',
218  'th{background:var(--soft);color:var(--mute);font-weight:600;font-size:12px;text-align:left;white-space:nowrap}',
219  'th,td{padding:8px 12px;border-bottom:1px solid var(--line);vertical-align:middle} tr:last-child td{border-bottom:0}',
220  'td.n{text-align:right} td.zero{color:var(--mute)} td.warn{background:var(--warnbg);color:var(--warn);font-weight:600}',
221  '.bar{display:flex;height:8px;border-radius:4px;overflow:hidden;min-width:120px;background:var(--soft)} .bar i{display:block} .bar .x{background:var(--idx)} .bar .d{background:var(--dir)}',
222  '.ok{color:var(--ok)} .bad{color:var(--warn)} code{font-family:ui-monospace,Consolas,monospace;font-size:.9em}',
223].join('\n')
224
225const PAGE_JS = [
226  'try{var t=localStorage.getItem("gh-theme");if(t==="light"||t==="dark")document.documentElement.dataset.theme=t;}catch(e){}',
227  'var L={auto:"자동",light:"밝게",dark:"어둡게"},N={auto:"light",light:"dark",dark:"auto"},m=document.documentElement.dataset.theme||"auto";',
228  'function ap(){if(m==="auto")delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=m;document.getElementById("theme").textContent="테마: "+L[m];}',
229  'document.addEventListener("DOMContentLoaded",function(){ap();document.getElementById("theme").onclick=function(){m=N[m];try{localStorage.setItem("gh-theme",m)}catch(e){}ap();};});',
230].join('\n')
231
232// 이력 페이지 — 세션별 코드 탐색(인덱스 대 직접), 하네스 기능 합계, 최근 기능 기록
233export function historyHtml(sessions: readonly SessionSummary[], evs: readonly HarnessEvent[], now: number): string {
234  const recent = [...sessions].sort((a, b) => b.started - a.started)
235  const week = recent.filter(s => s.updated >= now - 7 * 24 * 3600 * 1000)
236  const sum = emptyCounts()
237  for (const s of week) for (const k of Object.keys(sum) as Kind[]) sum[k] += s.counts[k] ?? 0
238  const idx = total(sum, INDEX_KINDS)
239  const dir = total(sum, DIRECT_KINDS)
240  const idle = week.filter(s => clangdIdle(s.counts, { isGame: true, hasClangd: s.hasClangd, hasWiki: false })).length
241  const kpi = (v: string, k: string, cls = '') => `<div class="kpi"><b class="${cls}">${v}</b><span>${k}</span></div>`
242  const lead = [
243    kpi(`${pct(idx, idx + dir)}%`, '인덱스로 찾은 비율 (7일)', pct(idx, idx + dir) >= 30 ? 'ok' : 'bad'),
244    ...INDEX_KINDS.map(k => kpi(String(sum[k]), LONG[k], sum[k] === 0 ? 'bad' : '')),
245    kpi(String(sum.grep), LONG.grep), kpi(String(sum.read), LONG.read),
246  ].join('')
247  const rows = recent.slice(0, 60).map(s => {
248    const c = s.counts
249    const i = total(c, INDEX_KINDS)
250    const d = total(c, DIRECT_KINDS)
251    const cells = (Object.keys(SHORT) as Kind[]).map(k => {
252      const warn = k === 'clangd' && clangdIdle(c, { isGame: true, hasClangd: s.hasClangd, hasWiki: false })
253      return `<td class="n ${warn ? 'warn' : c[k] === 0 ? 'zero' : ''}">${c[k] ?? 0}</td>`
254    }).join('')
255    const bar = `<div class="bar" title="인덱스 ${i} · 직접 ${d}"><i class="x" style="width:${pct(i, i + d)}%"></i><i class="d" style="width:${100 - pct(i, i + d)}%"></i></div>`
256    return `<tr><td>${esc(stamp(s.started))}</td><td>${esc(base(s.project))}${s.hasClangd ? '' : ' <span class="note">clangd 없음</span>'}</td>${cells}<td>${bar}</td></tr>`
257  }).join('')
258  const head = (Object.keys(SHORT) as Kind[]).map(k => `<th>${esc(SHORT[k])}</th>`).join('')
259  const feats = new Map<string, { n: number; failed: number; last: string }>()
260  for (const ev of evs) {
261    const r = feats.get(ev.feature) ?? { n: 0, failed: 0, last: '' }
262    r.n += 1
263    r.failed += ev.ok ? 0 : 1
264    r.last = ev.t
265    feats.set(ev.feature, r)
266  }
267  const featRows = [...feats.entries()].sort((a, b) => b[1].n - a[1].n).slice(0, 40)
268    .map(([f, r]) => `<tr><td>${esc(label(f))}</td><td class="n">${r.n}</td><td class="n ${r.failed ? 'warn' : 'zero'}">${r.failed}</td><td>${esc(r.last)}</td></tr>`).join('')
269  const lines = evs.slice(-40).reverse()
270    .map(ev => `<tr><td>${esc(ev.t)}</td><td class="${ev.ok ? '' : 'warn'}">${ev.ok ? '✓' : '✗'} ${esc(label(ev.feature))}</td><td><code>${esc(ev.detail.slice(0, 120))}</code></td></tr>`).join('')
271  return [
272    '<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',
273    '<title>하네스 이력</title>',
274    '<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css">',
275    `<style>${PAGE_CSS}</style><script>${PAGE_JS}</script></head><body><div class="wrap">`,
276    `<div class="top"><span class="eyebrow">game-harness-monitor · ${esc(stamp(now))}</span><button class="theme" id="theme" type="button">테마: 자동</button></div>`,
277    '<h1>하네스 이력</h1>',
278    `<section class="lead"><h2>최근 7일 코드 탐색</h2><div class="kpis">${lead}</div>`,
279    `<p class="note">세션 ${week.length}개 · 인덱스 ${idx}회 · 직접 검색 ${dir}회${idle ? ` · clangd 인덱스가 있는데 grep 으로만 찾은 세션 ${idle}개` : ''}</p></section>`,
280    `<section><h2>세션별</h2><div class="tbl"><table><thead><tr><th>시작</th><th>프로젝트</th>${head}<th>인덱스 : 직접</th></tr></thead><tbody>`,
281    rows || '<tr><td colspan="10" class="zero">아직 기록이 없다</td></tr>',
282    '</tbody></table></div><p class="note">노란 칸: clangd 인덱스가 있는데 0회, grep 5회 이상. 막대: 파란색 인덱스, 회색 직접 검색.</p></section>',
283    `<section><h2>하네스 기능</h2><div class="tbl"><table><thead><tr><th>기능</th><th>횟수</th><th>실패</th><th>마지막</th></tr></thead><tbody>${featRows}</tbody></table></div></section>`,
284    `<section><h2>최근 기능 기록</h2><div class="tbl"><table><thead><tr><th>시각</th><th>기능</th><th>내용</th></tr></thead><tbody>${lines}</tbody></table></div></section>`,
285    '</div></body></html>',
286  ].join('\n')
287}
288
289async function home($: EngineInterface): Promise<string> {
290  return ((await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? '').replace(/[\\/]+$/, '')
291}
292
293async function logPath($: EngineInterface): Promise<string> {
294  const custom = await $.env.get('GAME_HARNESS_EVENTS')
295  if (custom) return custom
296  return `${await home($)}/.claude/cache/game-harness/events.jsonl`
297}
298
299// 모듈 변수는 핫 리로드 때 처음으로 돌아간다. 그래도 화면이 읽는 기록은 $.state 에 있어 남는다.
300let path = ''
301let seenMtime = -1
302let seenSize = -1
303let isPolling = false
304
305async function poll($: EngineInterface): Promise<void> {
306  if (path === '') path = await logPath($)
307  const stat = await $.fs.stat(path).catch(() => undefined)
308  if (stat === undefined || (stat.mtimeMs === seenMtime && stat.size === seenSize)) return
309  seenMtime = stat.mtimeMs
310  seenSize = stat.size
311  const text = await $.fs.read(path)
312  const sessionId = await $.session.id()
313  const root = await $.session.root()
314  const { startedAt } = await $.session.usage()
315  const mine = parse(typeof text === 'string' ? text : '')
316    .filter(ev => belongs(ev, sessionId, root, startedAt))
317    .slice(-KEEP)
318  const before = await read($, events)
319  if (mine.length === before.length && mine.at(-1)?.ts === before.at(-1)?.ts) return
320  const known = new Set(before.map(ev => ev.feature))
321  const fresh = [...new Set(mine.map(ev => ev.feature))].filter(f => !known.has(f))
322  await update($, events, () => mine)
323  $.ui.status(statusText(mine))
324  if (fresh.length > 0) {
325    $.ui.toast(`하네스 기능 시작: ${fresh.map(label).join(', ')}`)
326  }
327}
328
329function pollSafely($: EngineInterface): void {
330  if (isPolling) return
331  isPolling = true
332  poll($).catch(() => undefined).finally(() => { isPolling = false })
333}
334
335async function detectProject($: EngineInterface): Promise<ProjectInfo> {
336  const root = (await $.session.root()).replace(/[\\/]+$/, '')
337  const names = (await $.fs.list(root).catch(() => [])).map(x => x.name)
338  const isGame = names.some(n => n.endsWith('.uproject')) || (names.includes('Assets') && names.includes('ProjectSettings'))
339  const exists = async (p: string) => (await $.fs.stat(p).catch(() => undefined)) !== undefined
340  return {
341    isGame,
342    hasClangd: await exists(`${root}/Saved/ClaudeIndex/clangd.sqlite`),
343    hasWiki: await exists(`${await home($)}/.jokate-wiki/${base(root)}`),
344  }
345}
346
347async function record($: EngineInterface, kind: Kind, what: string): Promise<void> {
348  const now = await $.clock.now()
349  const before = await read($, counts)
350  const next = { ...before, [kind]: before[kind] + 1 }
351  await update($, counts, () => next)
352  await update($, searches, list => [...list, { ts: now, kind, what }].slice(-KEEP_SEARCH))
353  if (before[kind] === 0 && (kind === 'clangd' || kind === 'wiki')) {
354    $.ui.toast(`${LONG[kind]} 사용${what ? `: ${what}` : ''}`)
355  }
356  const proj = await read($, project)
357  const id = await $.session.id()
358  const { startedAt } = await $.session.usage()
359  const list = ((await $.store.get('sessions')) ?? []) as SessionSummary[]
360  await $.store.set('sessions', upsertSession(list, {
361    id, project: await $.session.root(), started: startedAt, updated: now, hasClangd: proj.hasClangd, counts: next,
362  }))
363}
364
365// 소스에서 C++ 심볼을 grep 하면: 그 이름이 clangd 인덱스에 정확히 있는지 `cindex.py sym` 으로 보고, 있으면 결과 뒤에
366// cindex 명령 한 줄을 붙인다. 세션 시작 안내만으로는 모델이 grep 으로 갔다(10-20 뒤 MNYS 세션에서 clangd 0회).
367// 세션당 알림 3번 · 조회 8번까지, 심볼마다 한 번. 모듈 변수라 mod 가 다시 읽히면 처음부터 센다.
368const MAX_NUDGES = 3
369const MAX_LOOKUPS = 8
370const nudged = new Map<string, { names: Set<string>; lookups: number }>()
371
372async function lookupSymbol($: EngineInterface, script: string, root: string, name: string): Promise<string | undefined> {
373  for (const py of ['python', 'python3']) {
374    const ran = await $.process.run([py, script, 'sym', name, '--root', root, '--limit', '1'], { timeoutMs: 8000 })
375      .catch(() => undefined)
376    if (ran === undefined || ran.exitCode !== 0) continue
377    return symbolLine(ran.stdout)
378  }
379  return undefined
380}
381
382async function nudge($: EngineInterface, tool: string, args: Record<string, unknown>): Promise<string | undefined> {
383  if (!(await read($, project)).hasClangd) return undefined
384  const names = symbolCandidates(tool, args)
385  if (names.length === 0) return undefined
386  const id = await $.session.id()
387  const st = nudged.get(id) ?? { names: new Set<string>(), lookups: 0 }
388  nudged.set(id, st)
389  const root = (await $.session.root()).replace(/[\\/]+$/, '')
390  const script = `${await home($)}/.claude/skills/game-onboard/scripts/cindex.py`.replace(/\\/g, '/')
391  for (const name of names) {
392    if (st.names.size >= MAX_NUDGES || st.lookups >= MAX_LOOKUPS) return undefined
393    if (st.names.has(name)) continue
394    st.lookups += 1
395    const found = await lookupSymbol($, script, root, name)
396    // 엔진 심볼([E])은 프로젝트 인덱스가 엔진 .cpp 를 안 봐서 refs 가 반쪽이다 — 엔진 안은 ue_q 몫이라 알리지 않는다
397    if (found === undefined || found.includes('[E] ')) continue
398    st.names.add(name)
399    return nudgeText(name, found, script)
400  }
401  return undefined
402}
403
404// 지난 세션: 대화 기록에서 센 요약(game-onboard/scripts/search_history.py). mod 가 켜지기 전 세션까지 들어온다.
405// 같은 세션은 mod 가 실시간으로 센 쪽($.store)을 쓴다. 파이썬이나 스크립트가 없으면 $.store 만.
406async function pastSessions($: EngineInterface): Promise<SessionSummary[]> {
407  const script = `${await home($)}/.claude/skills/game-onboard/scripts/search_history.py`
408  const root = await $.session.root()
409  for (const py of ['python', 'python3']) {
410    const ran = await $.process.run([py, script, root], { timeoutMs: 120000 }).catch(() => undefined)
411    if (ran === undefined || ran.exitCode !== 0) continue
412    try {
413      const list = JSON.parse(ran.stdout) as SessionSummary[]
414      return Array.isArray(list) ? list : []
415    } catch {
416      return []
417    }
418  }
419  return []
420}
421
422export function mergeSessions(past: readonly SessionSummary[], live: readonly SessionSummary[]): SessionSummary[] {
423  let out = [...past]
424  for (const s of live) out = upsertSession(out, s)
425  return out
426}
427
428async function openHistory($: EngineInterface): Promise<string> {
429  await poll($).catch(() => undefined)
430  const now = await $.clock.now()
431  const live = ((await $.store.get('sessions')) ?? []) as SessionSummary[]
432  const sessions = mergeSessions(await pastSessions($), live)
433  const logText = await $.fs.read(path || (await logPath($))).catch(() => '')
434  const evs = parse(typeof logText === 'string' ? logText : '').slice(-3000)
435  const out = `${await home($)}/.claude/cache/game-harness/history.html`
436  await $.fs.write(out, historyHtml(sessions, evs, now))
437  const isWindows = ((await $.env.get('OS')) ?? '').startsWith('Windows')
438  const isMac = out.startsWith('/Users/')
439  const argv = isWindows ? ['cmd', '/c', 'start', '', out.replace(/\//g, '\\')] : [isMac ? 'open' : 'xdg-open', out]
440  const ran = await $.process.run(argv, { timeoutMs: 15000 }).catch(() => undefined)
441  return ran !== undefined && ran.exitCode === 0
442    ? `하네스 이력 페이지를 열었다: ${out} (세션 ${sessions.length}개)`
443    : `하네스 이력 페이지를 만들었다 — 브라우저로 연다: ${out}`
444}
445
446// 내 한 줄 — 한 줄을 넘지 않게 잘라 다른 플러그인 몫의 줄을 남긴다
447function searchRow($: EngineInterface, e: Parameters<EngineInterface['ui']['resolve']>[0], c: Counts, idle: boolean) {
448  const { Box, Text } = $.ui.resolve(e)
449  return (
450    <Box key="game-harness-search" flexDirection="row" flexWrap="nowrap">
451      <Text bold color="claude">코드 탐색 </Text>
452      <Text dimColor>│ 인덱스 </Text>
453      {INDEX_KINDS.map((k, i) => (
454        <Text key={k} color={c[k] > 0 ? 'success' : k === 'clangd' && idle ? 'warning' : 'subtle'}>
455          {i > 0 ? ' · ' : ''}{SHORT[k]} {c[k]}
456        </Text>
457      ))}
458      <Text dimColor> │ 직접 </Text>
459      <Text dimColor>{DIRECT_KINDS.map(k => `${SHORT[k]} ${c[k]}`).join(' · ')}</Text>
460      {idle ? <Text color="warning"> │ clangd 인덱스가 있는데 grep 만 씀</Text> : <Text dimColor> │ /harness 상세</Text>}
461    </Box>
462  )
463}
464
465export const register: Register = on => {
466  on('session.start', async ($, e, next) => {
467    $.clock.every(POLL_MS, () => pollSafely($))
468    pollSafely($)
469    const info = await detectProject($).catch(() => undefined)
470    if (info !== undefined) await update($, project, () => info)
471    await $.command.register({
472      name: 'harness',
473      description: '이 세션의 코드 탐색(인덱스 대 직접 검색)과 하네스 기능(훅·스킬·조회 스크립트)을 패널로 보여준다',
474    }).catch(() => undefined) // 명령 등록이 막혀도 띠·상태줄·토스트는 돈다
475    await $.command.register({
476      name: 'harness-history',
477      description: '세션별 코드 탐색 · 하네스 기능 이력을 HTML 상세 페이지로 만들어 브라우저로 연다',
478    }).catch(() => undefined)
479    return next(e)
480  })
481
482  // 도구 호출마다: 코드 탐색이면 센다. 하네스 추적 훅(PostToolUse)이 로그를 쓴 직후를 놓치지 않으려고 한 번 더 읽는다.
483  // 소스 심볼 grep 이면 결과 뒤에 cindex 안내 한 줄(context)을 붙인다 — 결과 자체는 바꾸지 않는다.
484  on('tool.call', async ($, e, next) => {
485    const ran = await next(e)
486    const tool = String(e.tool)
487    if (tool === 'Skill' || tool === 'Bash' || tool === 'PowerShell' || tool.startsWith('mcp__')) {
488      $.clock.after(700, () => pollSafely($))
489    }
490    if (ran.deny !== undefined) return ran
491    const args = e as unknown as Record<string, unknown>
492    const hit = classify(tool, args)
493    if (hit !== undefined) await record($, hit.kind, hit.what).catch(() => undefined)
494    if (hit?.kind !== 'grep') return ran
495    const hint = await nudge($, tool, args).catch(() => undefined)
496    return hint === undefined ? ran : { ...ran, context: [...(ran.context ?? []), hint] }
497  }).catch(($, e, next) => next(e))
498
499  on('command.run', { command: 'harness' }, async $ => {
500    await poll($).catch(() => undefined)
501    const opened = await $.ui.open({ id: PANE, title: 'Harness' })
502    const list = await read($, events)
503    if (!opened.isPlaced) {
504      return { text: `하네스 패널을 열지 못했다. 이 세션 기록 ${list.length}건 · 로그 ${path} · 이력은 /harness-history` }
505    }
506    return { text: `하네스 패널을 열었다 (이 세션 기록 ${list.length}건). 세션들 이력은 /harness-history` }
507  })
508
509  on('command.run', { command: 'harness-history' }, async $ => ({ text: await openHistory($) }))
510
511  // 프롬프트 위 띠: 이번 세션에 코드를 무엇으로 찾았나. 게임 프로젝트이거나 인덱스를 한 번이라도 썼을 때만.
512  // 띠는 다른 플러그인과 나눠 쓴다 — 아래 플러그인(과 엔진)이 그린 것을 next(e) 로 받아 내 한 줄 밑에 그대로 둔다.
513  // 내 줄만 돌려주면 그 아래 플러그인의 띠가 사라진다(사용자: "다른 플러그인도 잡아먹는다", 2026-10-20).
514  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
515    const rest = await next(e)
516    const c = await read($, counts)
517    const proj = await read($, project)
518    const idx = total(c, INDEX_KINDS)
519    const dir = total(c, DIRECT_KINDS)
520    if (e.props.hasSurvey || idx + dir === 0 || (!proj.isGame && idx === 0)) return rest
521    const { Box } = $.ui.resolve(e)
522    const idle = clangdIdle(c, proj)
523    return (
524      <Box flexDirection="column">
525        {searchRow($, e, c, idle)}
526        {rest}
527      </Box>
528    )
529  })
530
531  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
532    const { Box, Text } = $.ui.resolve(e)
533    const list = await read($, events)
534    const c = await read($, counts)
535    const proj = await read($, project)
536    const found = await read($, searches)
537    const width = Math.max(20, e.props.bodyColumns)
538    const room = Math.max(6, (e.viewport?.rows ?? 30) - 4)
539    const idx = total(c, INDEX_KINDS)
540    const dir = total(c, DIRECT_KINDS)
541    const barW = Math.max(10, Math.min(30, width - 34))
542    const max = Math.max(1, ...Object.values(c))
543    const byFeature = new Map<string, { count: number; failed: number; last: string }>()
544    for (const ev of list) {
545      const row = byFeature.get(ev.feature) ?? { count: 0, failed: 0, last: '' }
546      row.count += 1
547      row.failed += ev.ok ? 0 : 1
548      row.last = ev.t.slice(11)
549      byFeature.set(ev.feature, row)
550    }
551    const summary = [...byFeature.entries()]
552    const lines = Math.max(2, room - 12 - summary.length)
553    const recent = found.slice(-Math.ceil(lines / 2))
554    const timeline = list.slice(-Math.floor(lines / 2))
555    return (
556      <Box flexDirection="column">
557        <Text bold>
558          코드 탐색 · 인덱스 {idx} · 직접 {dir} ({pct(idx, idx + dir)}% 인덱스)
559          {proj.hasClangd ? '' : ' · clangd 인덱스 없음'}
560        </Text>
561        {(Object.keys(SHORT) as Kind[]).map(k => (
562          <Text key={k} wrap="truncate-end"
563            color={INDEX_KINDS.includes(k) ? (c[k] > 0 ? 'success' : k === 'clangd' && clangdIdle(c, proj) ? 'warning' : 'subtle') : undefined}
564            dimColor={DIRECT_KINDS.includes(k)}>
565            {LONG[k].padEnd(12, ' ')} {'█'.repeat(Math.round((c[k] / max) * barW)) || '·'} {c[k]}
566          </Text>
567        ))}
568        <Text dimColor>{'─'.repeat(Math.min(width, 40))}</Text>
569        <Text bold>하네스 기능 {summary.length}개 · 기록 {list.length}건</Text>
570        {summary.map(([feature, row]) => (
571          <Text key={feature} wrap="truncate-end" color={row.failed > 0 ? 'warning' : undefined}>
572            {row.failed > 0 ? '✗' : '●'} {label(feature)} ×{row.count}
573            {row.failed > 0 ? ` (실패 ${row.failed})` : ''} · {row.last}
574          </Text>
575        ))}
576        <Text dimColor>{'─'.repeat(Math.min(width, 40))}</Text>
577        {recent.map(s => (
578          <Text key={`s${s.ts}${s.kind}`} wrap="truncate-end" color={INDEX_KINDS.includes(s.kind) ? 'success' : undefined}
579            dimColor={DIRECT_KINDS.includes(s.kind)}>
580            {stamp(s.ts).slice(11)} {SHORT[s.kind]} {s.what}
581          </Text>
582        ))}
583        {timeline.map(ev => (
584          <Text key={`e${ev.ts}${ev.feature}`} wrap="truncate-end" dimColor={ev.ok} color={ev.ok ? undefined : 'error'}>
585            {ev.t.slice(11)} {ev.ok ? '✓' : '✗'} {label(ev.feature)}{ev.detail ? ` — ${ev.detail}` : ''}
586          </Text>
587        ))}
588        <Text dimColor>세션들 이력: /harness-history</Text>
589      </Box>
590    )
591  })
592}
593
types/index.d.ts 37 lines
1export type HarnessEvent = {
2  ts: number
3  t: string
4  session: string
5  project: string
6  feature: string
7  ok: boolean
8  detail: string
9  source: string
10}
11
12// 코드를 무엇으로 찾았나 — 인덱스(gq · clangd · 위키 · ue_q)와 직접 검색(grep · 파일 찾기 · 파일 읽기)
13export type Kind = 'gq' | 'clangd' | 'wiki' | 'ue_q' | 'grep' | 'glob' | 'read'
14export type Counts = Record<Kind, number>
15export type SearchEvent = { ts: number; kind: Kind; what: string }
16export type ProjectInfo = { isGame: boolean; hasClangd: boolean; hasWiki: boolean }
17// 세션 하나의 탐색 요약 — $.store 'sessions' 에 세션을 넘어 남는다(이력 페이지 재료)
18export type SessionSummary = {
19  id: string
20  project: string
21  started: number
22  updated: number
23  hasClangd: boolean
24  counts: Counts
25}
26
27declare module 'claude-code' {
28  interface PluginState {
29    'game-harness-monitor': {
30      events: HarnessEvent[]
31      counts: Counts
32      searches: SearchEvent[]
33      project: ProjectInfo
34    }
35  }
36}
37