SLOPSHOPPER

deadhd

Draw this session's deadhd progress as a band above the prompt or a status line under it, from the state file the deadhd skill writes.

bandspinnerguardcommandtoaststatus
★ 32v1.14.1MITupdated 2026-10-23lcalmsky/deadhd/skills/deadhd
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · deadhd
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /deadhd-band ⎿ deadhd: 지금은 밴드 모드가 아니에요. /deadhd setup 에서 밴드를 고르면 보여요. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<h1 align="center"><img src="docs/logo.png" alt="deadhd" width="420"></h1>

<a href="https://github.com/lcalmsky/deadhd/releases/latest"><img alt="release" src="https://img.shields.io/github/v/release/lcalmsky/deadhd?label=release"></a> <a href="LICENSE"><img alt="license" src="https://img.shields.io/github/license/lcalmsky/deadhd"></a> <img alt="Claude Code plugin" src="https://img.shields.io/badge/Claude%20Code-plugin-d97757"> <img alt="python3 stdlib" src="https://img.shields.io/badge/python3-stdlib%20only-3776ab">

<a href="#빠른-시작">빠른 시작</a> · <a href="#기능">기능</a> · <a href="#설치">설치</a> · <a href="#사용법">사용법</a> · <a href="#설정">설정</a> · <a href="#동작-방식">동작 방식</a>

Claude Code 세션을 여러 개 띄워 놓고 일하다 보면, 다른 세션을 보고 돌아왔을 때 이 세션이 어디까지 진행했는지 놓치기 쉽습니다. deadhd 는 세션이 완료한 단계, 진행 중인 단계, 남은 단계를 체크리스트 페이지로 띄워 두고 작업이 진행되는 동안 계속 갱신합니다. 터미널 로그를 거슬러 올라가지 않아도 페이지 한 장으로 진행 상황을 확인할 수 있습니다.

진행 상황을 그리는 HUD 는 여럿이지만, deadhd 는 두 가지 점에서 다릅니다.

  • 세션 상태는 모델이 아니라 이벤트가 그립니다. 체크리스트의 단계와 근거는 Claude 가 적지만, 작업 중·입력 대기·권한 승인 대기·마지막 도구·압축 횟수는 플러그인 훅과 mod 가 턴 시작·끝, 도구 호출, 알림, 압축 이벤트에서 직접 읽습니다. 그래서 모델이 갱신을 잊었거나 /deadhd 를 실행하기 전이어도 이 세션이 지금 무엇을 기다리는지 보입니다.
  • 같은 진행 상황을 터미널 안과 밖에 함께 씁니다. 터미널 안에서는 프롬프트 위 밴드나 아래 상태줄로 보고, 같은 상태 파일로 터미널 옆 브라우저 페이지와 이 컴퓨터의 세션을 모은 허브를 그립니다.

Orca 처럼 인앱 브라우저를 갖춘 터미널 앱에서 진행 페이지를 터미널 옆 패널에 띄워 두는 용도로 만들었습니다. Orca 를 쓰지 않으면 시스템 브라우저나 Claude 데스크톱 앱의 인앱 브라우저로 열고, Claude Code 에서는 페이지 대신 프롬프트 위아래의 한 줄로도 볼 수 있습니다.

빠른 시작

Claude Code 에서 플러그인을 설치합니다.

/plugin marketplace add lcalmsky/deadhd
/plugin install deadhd@deadhd

긴 작업을 시작한 세션에서 /deadhd:deadhd 를 입력합니다. 처음 실행할 때 열기 위치, 표시 방식, 테마, 글꼴을 한 번 묻고, 그 뒤로는 단계의 상태가 바뀔 때마다 Claude 가 페이지를 갱신합니다. 명령 대신 "진행 상황 띄워줘", "체크리스트로 보여줘" 처럼 요청해도 됩니다.

다른 설치 방법은 설치에 있습니다.

기능

기능내용
진행 페이지완료·진행·남은 단계를 흐름도와 카드로 보여 주고, 단계마다 근거가 되는 파일·PR·커밋·테스트 통과 건수를 붙입니다
상태 띠권한 승인 대기, 입력 대기, 마지막 도구, 압축 같은 세션 상태를 페이지 위쪽에 알려 줍니다
보정 완료 예상처음 적은 예상과 실제 소요의 이력을 쌓아, 3건부터 보정한 완료 예상 시각을 함께 보여 줍니다
표시 방식 3종브라우저 페이지, 프롬프트 위 밴드, 프롬프트 아래 상태줄 중에서 고릅니다
보기 모드 4종같은 진행 상황을 원본·스트립·타임라인·타일로 바꿔 봅니다
허브이 컴퓨터에서 도는 세션을 한 장에 모아 상태 순으로 정렬합니다
레인 보드병렬로 도는 작업 단위를 작업 × 단계 표로 보여 줍니다
테마 10종과 글꼴 12종페이지 테마와 제목 글꼴을 고릅니다
메뉴 막대선택 사항. 별도 앱 Pulse 를 설치하면 같은 상태 파일을 읽어 macOS 메뉴 막대에서도 체크리스트와 입력 대기를 봅니다

진행 페이지와 상태 띠

작업 중인 세션에서 /deadhd 를 입력하면 완료한 단계, 진행 중인 단계, 남은 단계를 흐름도와 카드로 정리한 페이지가 열립니다. 작업이 길어지면 페이지 위쪽에 이 세션이 지금 무엇을 기다리는지 알려 주는 상태 띠가 붙고, 이 띠는 모델이 아니라 플러그인 훅이 유지합니다.

표시 방식

같은 진행 상황을 세 가지 방식으로 볼 수 있습니다. 밴드와 상태줄은 페이지를 열지 않고 Claude Code 터미널 안에서 바로 보는 방식입니다.

표시 방식위치구성
band프롬프트 위 한 줄세션 상태와 마지막 도구를 먼저 보여 주고, 체크리스트가 있으면 완료 수와 진행 막대, 지금 하는 단계와 경과 시간, 막힘·남음이 붙습니다. 브라우저 탭을 열지 않아 가장 가볍습니다
statusline프롬프트 아래 한 줄세션 상태와 마지막 도구에 티켓 키와 제목, 진행 중인 단계의 PR, 다음 단계, 완료 예상, 마지막 갱신, 백그라운드 작업·압축 횟수까지 담습니다
html브라우저 페이지위의 진행 페이지입니다

체크리스트의 상태 파일은 /deadhd 를 실행해야 생깁니다. 그 전에도 mod 는 세션의 이벤트를 직접 보며 세션 상태(● 작업 중 N분째, ⌨️ 입력 대기 N분째)와 마지막 도구(🔧 도구이름 N초 전)를 그립니다. 상태줄은 여기에 지켜본 압축 횟수(🗜 압축 N)까지 더합니다. 세션이 시작하자마자 대화에 아무것도 남기지 않고 상태가 보이는 것은 이 때문입니다. 아직 열 페이지가 없으니 이때는 열기 대신 켜기 버튼이 보이고, 누르면 Claude 에게 체크리스트를 띄워 달라는 요청이 보내집니다. /deadhd 를 실행해도 같습니다.

이 HUD 는 python3 <스킬 폴더>/config.py set hud off(설정에 경로가 있습니다) 또는 /deadhd setup 으로 끌 수 있습니다. 끄면 세션 상태·입력 대기·마지막 도구를 그리지 않고, /deadhd 를 실행해 체크리스트가 생긴 뒤부터 그 줄을 그립니다. 켜면 세션을 다시 시작하지 않고 바로 반영됩니다.

밴드는 막힌 단계가 있으면 둘째 줄이 붙습니다. /deadhd-band 로 접으면 세션 상태와 열기·펼치기 버튼만 남습니다.

상태줄은 같은 상태 파일을 더 많은 항목으로 담습니다. 티켓 키와 진행 중인 단계의 PR 은 누르면 열리는 링크입니다. 터미널 폭을 넘으면 제목부터 잘려 … 이 붙고, 그래도 넘치면 덜 중요한 항목부터 빠지며 세션 상태와 완료 수는 끝까지 남습니다. 줄 끝의 열기 버튼으로 페이지를 엽니다. /deadhd-statusline 으로 접으면 세션 상태 한 조각만 남습니다. 다른 상태줄 플러그인의 줄 바로 밑에 붙어 보이면 python3 <스킬 폴더>/config.py set divider on(설정에 경로가 있습니다)으로 그 줄 위에 구분선을 켤 수 있습니다.

/deadhd setup 에서 고르거나 /deadhd --view <값> 으로 바꿉니다. 우선순위는 --view 값, 이 세션의 상태 파일에 기록된 값, 설정값, 기본값 html 순입니다. 그래서 --view band 로 한 번 실행하면 그 세션은 이후 렌더에서도 밴드로 그립니다.

밴드와 상태줄은 deadhd 플러그인의 mod(skills/deadhd/hooks/register.tsx)가 그리며 Claude Code 전용입니다. mod 는 세션의 이벤트(턴 시작·끝, 도구 호출, 압축)로 세션 상태를 직접 관측하고 스킬이 쓴 상태 파일을 읽습니다. Claude Code 가 아닌 환경(Codex $deadhd 등)에서는 묻지 않고 html 로 동작합니다.

band·statusline 에서는 페이지 파일을 곧바로 쓰지 않습니다. 상태 요약과 허브는 매 갱신마다 다시 쓰고, 페이지는 처음 열 때(/deadhd-open, 열기 버튼) 만들고 그 뒤로는 계속 씁니다. 허브에서 아직 페이지가 없는 세션은 링크 대신 표시 방식 이름(밴드/상태줄)이나 페이지 없음 을 보여 줍니다. 현재 표시 방식과 맞지 않는 명령을 부르면 어떻게 바꾸는지 한 줄로 알려 줍니다.

보기 모드

페이지 왼쪽 위 버튼으로 같은 진행 상황을 네 가지 보기로 바꿔 볼 수 있습니다. Claude 아티팩트 패널이나 좁게 나눈 Orca 탭처럼 폭이 좁은 곳에서는 컴팩트 보기가 한눈에 읽기 쉽습니다.

보기구성
원본흐름도와 단계별 카드를 모두 보여 주는 기본 페이지입니다
스트립단계 흐름을 한 줄의 점으로 줄이고, 진행 중인 단계 카드만 펼칩니다. 나머지 단계는 완료·병행·남음으로 접어 둡니다
타임라인단계를 한 줄씩 세로로 쌓고, 단계마다 완료 시각이나 예상 시간을 붙입니다. 진행 중인 단계는 카드로 보여 줍니다
타일완료 수, 현재 단계의 남은 시간, 완료 예상 시각을 숫자로 먼저 보여 주고, 단계별 상태를 구간 막대로 보여 줍니다

컴팩트 보기를 고르면 자동·가로·세로 버튼이 나타납니다. 자동은 탭이 5:4보다 넓고 폭이 760px 이상이면 가로 배치로, 그렇지 않으면 세로 배치로 그리며, 탭 크기를 바꾸면 바로 다시 배치합니다. 고른 보기와 배치는 15초마다 데이터를 다시 받아 그린 뒤에도 유지됩니다. 보기는 페이지에 이미 들어 있는 데이터로 브라우저가 그리므로, 보기를 바꿔도 토큰 사용량은 늘지 않습니다.

허브

이 컴퓨터에서 도는 세션을 한 장에 모은 페이지입니다. /deadhd hub 로 열거나 세션 페이지 오른쪽 위의 허브 ↗ 버튼으로 이동합니다. 타일에는 상태 배지, 제목과 키, 단계별 미니 스트립, 6/12 완료, 지금 하는 일, 완료 예상이 나옵니다.

  • 승인 대기 > 신호 없음 > 입력 대기 > 작업 중 > 훅 없음 > 완료 > 종료 > 지난 세션 순으로 정렬하고, 같은 상태에서는 오래 기다린 세션이 위로 옵니다.
  • 타일을 누르면 같은 탭에서 그 세션의 페이지로 이동하고, 세션 페이지의 허브 ↗ 버튼도 같은 탭에서 허브로 돌아옵니다.
  • 상태 파일을 쓰는 1.8.0 이후 세션만 모입니다. 24시간 넘게 갱신이 없는 세션은 「종료·지난 세션」으로 접힙니다.

레인 보드

에픽의 하위 작업처럼 작업 단위가 넷 이상 병렬로 돌면, 데이터의 board 에 레인을 채워 페이지 아래에 작업 × 단계 표를 붙입니다. 레인마다 진행 단계, 작업자, 마지막 신호, 남은 시간, 티켓 전이 기록이 한 줄로 나오고, 완료·진행·정체·막힘·선행 대기·남음이 몇 건인지 위에 요약합니다.

정체 판정은 마지막 신호 뒤 얼마나 조용했는지(stallAfter, 기본 10분)를 브라우저가 직접 재므로, 모델이 갱신을 멈춘 레인도 정체로 드러나 주의 띠에 올라옵니다. 작업자를 나눠 돌리는 하네스 세션과 기본 서브에이전트에 일을 넘기는 보통 세션이 같은 형식을 씁니다. board 가 없는 세션은 흐름도만 그립니다.

테마와 글꼴

테마 9종을 3×3 갤러리로 묶은 화면입니다. 레인이 여러 개인 흐름, 막힌 작업, 자정을 넘기는 완료 예상, 모든 단계를 마친 상태를 함께 볼 수 있습니다. system 은 운영체제 설정을 따르므로 갤러리에서 빠집니다.

/deadhd setup 에서 기본값을 고르거나, /deadhd --theme <테마>·/deadhd --font <프리셋> 으로 이번 실행만 바꿉니다.

값설명
system운영체제의 라이트/다크 설정을 따릅니다 (권장)
light항상 라이트 테마로 표시합니다
dark항상 다크 테마(오로라)로 표시합니다
neon사이버펑크 네온: 검보라 배경에 시안·마젠타·형광 노랑
synthwave신스웨이브 선셋: 진보라 위 핑크·오렌지 레트로 노을
matrix매트릭스 터미널: 검정 위 초록 단색, 모든 글자 고정폭
nord노르드 아크틱: 오래 띄워 둬도 눈이 덜 피곤한 차분한 톤
paper페이퍼 노트북: 따뜻한 종이 질감의 라이트 테마, 명조 제목
sakura사쿠라: 벚꽃 분홍 라이트 테마, 손글씨 제목
ink잉크: 순흑 위 순백의 흑백 테마. 상태를 색 대신 채움·테두리·빗금으로 구분합니다

프리셋에는 글꼴·굵기·자간이 묶여 있고, 기본값 default 는 테마가 정한 제목 글꼴을 그대로 씁니다. 본문 글꼴은 바뀌지 않습니다.

값글꼴굵기 · 자간
default테마가 정한 글꼴테마에 따름
pretendardPretendard Variable800 · -0.03em
noto-sansNoto Sans KR900 · -0.03em
plex-sansIBM Plex Sans KR700 · -0.02em
gothic-a1Gothic A1900 · -0.03em
nanum-gothicNanum Gothic800 · -0.02em
noto-serifNoto Serif KR900 · -0.02em
nanum-myeongjoNanum Myeongjo800 · -0.02em
hahmletHahmlet900 · -0.02em
gowun-batangGowun Batang700 · -0.01em
do-hyeonDo Hyeon400 · -0.04em
black-han-sansBlack Han Sans400 · 0

Pulse 와 함께 쓰기

<table width="100%"> <tr> <td width="42%" valign="top"><img src="docs/pulse.png" alt="Pulse 팝오버의 진행 중 세션 행에 펼쳐진 deadhd 단계" width="360"></td> <td valign="top">

Pulse 는 Claude Code 세션을 macOS 메뉴 막대에서 보는 별도 앱입니다. deadhd 가 쓰는 상태 파일을 그대로 읽으므로, 터미널을 보고 있지 않을 때도 진행 중인 세션 행에 체크리스트가 붙습니다.

  • 진행률 4/6 과 단계 막대를 그리고, 막힌 단계는 주황으로 칠합니다
  • 지금 단계 단계 이름과 약 N분 남음 을 보여 줍니다
  • 단계 펼침 단계 줄을 누르면 직전·지금·다음 단계가 행 안에 펼쳐집니다
  • 진행 페이지 문서 버튼으로 deadhd 진행 페이지를 브라우저에서 엽니다

세션이 답을 기다리거나 끝나면 메뉴 막대 아래에 카드를 띄우고, 행을 누르면 Orca 터미널의 그 세션으로 이동합니다. deadhd 는 Pulse 없이도 모든 기능이 동작하며, Pulse 는 메뉴 막대를 한 곳 더하는 선택 사항입니다. Homebrew 로 설치합니다.

brew tap lcalmsky/pulse https://github.com/lcalmsky/pulse
brew trust lcalmsky/pulse
brew install lcalmsky/pulse/pulse

Homebrew 7 부터는 비공식 tap 을 brew trust 로 한 번 신뢰해야 formula 를 읽고, 같은 이름의 공식 cask 가 있어 lcalmsky/pulse/pulse 처럼 전체 이름으로 설치합니다.

</td> </tr> </table>

설치

필요한 것은 Claude Code 와 python3(표준 라이브러리만 사용)입니다. 세 가지 방법 중 하나만 씁니다.

방법호출 이름상태 띠 훅
플러그인 (권장)/deadhd:deadhd포함
스킬 폴더/deadhd포함
Orca 공유 링크/deadhd포함

플러그인으로 설치

/plugin marketplace add lcalmsky/deadhd
/plugin install deadhd@deadhd

스킬 폴더로 설치

git clone https://github.com/lcalmsky/deadhd.git
cp -r deadhd/skills/deadhd ~/.claude/skills/

skills/deadhd/.claude-plugin/ 이 함께 복사되므로, 이 폴더는 다음 세션부터 deadhd@skills-dir 플러그인으로 자동으로 읽혀 밴드·상태줄이 붙습니다. 상태 띠를 만드는 명령 훅도 이 플러그인의 hooks/hooks.json 에 들어 있어 함께 읽힙니다.

[!WARNING] 플러그인 설치와 스킬 폴더 설치를 함께 쓰지 마세요. 함께 두면 deadhd 플러그인이 두 번 로드되어 같은 명령과 같은 상태 키, 같은 상태 파일을 보는 타이머가 둘이 됩니다.

<a id="orca-install"></a>

Orca 에서 설치

Orca 를 사용한다면 공유 링크 를 열고 Open in Orca 를 누릅니다. Orca 에서 포함된 파일을 확인한 뒤 설치 위치를 고를 수 있습니다.

[!NOTE] Orca 공유 링크는 게시할 때 올린 파일을 바꿀 수 없는 묶음으로 보관합니다. 지금 링크에는 v1.14.1 이 들어 있고, 그 뒤의 릴리즈는 반영되지 않습니다. 최신 버전은 플러그인이나 스킬 폴더 방식으로 설치합니다.

업데이트

설치 방식업데이트 방법
플러그인서드파티 마켓플레이스는 자동 업데이트가 기본으로 꺼져 있습니다. /plugin 에서 deadhd 를 골라 Update now 를 누르거나 claude plugin update deadhd@deadhd 를 실행합니다. /plugin 의 Marketplaces 탭에서 Enable auto-update 를 켜 두면 새 버전이 자동으로 설치됩니다. 업데이트 뒤에는 /reload-plugins 를 실행하거나 새 세션을 시작합니다
스킬 폴더클론한 저장소에서 git pull 한 뒤 skills/deadhd 를 다시 복사합니다
Orca공유 링크는 게시 시점의 고정 사본이라 다시 열어도 새 버전이 설치되지 않습니다

사용법

입력동작
/deadhd진행 상황 페이지를 브라우저 탭으로 엽니다 (-h 와 같음)
/deadhd -oOrca 아티팩트(공유 링크가 있는 웹 페이지)로 게시합니다. orca CLI 로그인이 필요하고, 실패하면 브라우저 탭으로 엽니다
/deadhd -cClaude 아티팩트로 게시합니다
/deadhd setup기본 열기 위치·표시 방식·테마·글꼴을 다시 고릅니다. 밴드나 상태줄을 고르면 세션 시작부터 HUD 를 그릴지도 이어서 묻습니다
/deadhd hub이 컴퓨터의 세션을 모은 허브 페이지를 엽니다
/deadhd --open <모드>이번 실행만 다른 위치로 엽니다
/deadhd --view <표시 방식>이번 실행만 다른 표시 방식으로 그립니다
/deadhd --theme <테마>이번 실행만 다른 테마로 렌더합니다
/deadhd --font <프리셋>이번 실행만 다른 제목 글꼴로 렌더합니다
/deadhd off체크리스트 갱신을 끄고 밴드·상태줄에서 떼어 냅니다. 다시 /deadhd 를 실행하면 켜집니다

Claude Code 에서 밴드나 상태줄로 보고 있으면 다음 명령도 씁니다.

입력동작
/deadhd-band프롬프트 위 밴드를 접거나 펼칩니다
/deadhd-statusline프롬프트 아래 상태줄을 접거나 펼칩니다
/deadhd-open진행 페이지를 만들어 브라우저로 엽니다

설정

처음 실행할 때 열기 위치, 표시 방식, 테마, 글꼴을 한 번 묻고, 고른 값은 다음 실행부터 그대로 쓰입니다. 표시 방식으로 밴드나 상태줄을 고르면 세션 HUD 를 그릴지도 이어서 묻습니다. /deadhd setup 으로 언제든 다시 고를 수 있습니다. 설정 파일은 ~/.config/deadhd/config.json 이고 XDG_CONFIG_HOME 을 지정하면 그 아래에 만들어집니다. 아래 명령의 <스킬 폴더> 는 스킬 폴더로 설치했다면 ~/.claude/skills/deadhd 이고, 플러그인으로 설치했다면 ~/.claude/plugins/installed_plugins.json 의 deadhd@deadhd → installPath 뒤에 /skills/deadhd 를 붙인 경로(예: ~/.claude/plugins/cache/deadhd/deadhd/1.13.2/skills/deadhd)입니다. 플러그인 경로는 버전마다 바뀌므로, 경로를 찾기 번거로우면 /deadhd setup 으로 같은 값을 바꿉니다.

열기 위치는 다음 값을 씁니다.

값동작
autoOrca 안에서 실행 중이면 이 세션이 있는 Orca 작업 칸에 탭을 열어 앞으로 가져오고, 아니면 시스템 브라우저로 엽니다
orcaorca 명령이 있으면 Orca 탭으로 엽니다
browserOrca 를 건너뛰고 시스템 브라우저로 엽니다
desktop페이지를 열지 않고 경로만 출력합니다. Claude 데스크톱 앱에서 그 경로나 출력된 http 주소를 누르면 인앱 브라우저 패널로 열립니다

표시 방식은 band(권장), statusline, html 중에서 고릅니다(표시 방식). 테마와 글꼴 값은 테마와 글꼴에 있습니다.

밴드와 상태줄에서 세션 시작부터 HUD 를 그릴지는 hud 로 정합니다.

값동작
on세션이 시작하자마자 그립니다. /deadhd 를 실행하기 전에도 작업 중·입력 대기·마지막 도구가 보입니다
off/deadhd 를 실행해 체크리스트가 생긴 뒤부터 그립니다. 관측은 그대로 하므로 켜면 바로 맞게 보입니다

python3 <스킬 폴더>/config.py set hud off 로 끕니다. 값이 없으면 on 입니다.

다른 플러그인의 상태줄과 붙어 보이면 상태줄 위에 구분선을 그립니다.

값동작
on상태줄 위에 ── 진행 ───… 구분선을 그립니다. 다른 플러그인의 상태줄과 구분됩니다
off구분선을 그리지 않습니다. 상태줄 바로 위에 다른 줄이 붙어 보일 수 있습니다

python3 <스킬 폴더>/config.py set divider on 으로 켭니다. 값이 없으면 off 이고, 상태줄 보기에서만 그립니다.

~/.config/deadhd/writing-rules.md 를 두면 페이지 문장을 쓸 때 그 파일의 작성 규칙을 따릅니다. 없으면 기본 규칙(제목은 명사구, 분야 용어 사용, 의인화 금지)을 씁니다. 자기 작성 가이드 파일에 심볼릭 링크로 연결해도 됩니다.

동작 방식

  • 완료 표시는 실행 결과로 확인된 단계에만 붙습니다. 테스트 통과, 파일 작성, PR 머지처럼 결과가 남은 단계만 done 으로 분류하고, 시도했지만 검증하지 못한 단계는 now 또는 blocked 로 표시합니다. 단계마다 근거가 되는 파일 경로, PR, 커밋, 테스트 통과 건수가 함께 표시됩니다.
  • 모델은 JSON 데이터만 작성합니다. 페이지 디자인은 template.html 에 고정되어 있고, render.py 가 데이터를 검증한 뒤 HTML 을 생성합니다. 테마와 글꼴 CSS 는 themes.css 로 분리되어 세션 페이지와 허브가 같은 파일을 씁니다. 데이터 형식의 전체 예시는 skills/deadhd/example.json 에 있습니다.
  • 영어로 대화하면 페이지의 고정 문구도 영어로 표시됩니다. 데이터의 lang 필드로 정해지며, 없으면 한국어입니다.
  • 완료 예상 시각은 데이터 파일이 마지막으로 수정된 시각을 기준으로 계산합니다. 그래서 훅이 데이터를 바꾸지 않고 페이지를 다시 렌더해도 예상 시각이 밀리지 않습니다. 이미 지난 예상에는 (지남) 이 붙고, 내일 이나 날짜 표기는 페이지를 보는 시점을 기준으로 정해지므로 자정이 지나면 자동으로 바뀝니다.
  • 열어 둔 탭은 15초마다 데이터만 다시 받아 그립니다. 문서를 다시 로드하지 않으므로 펼쳐 둔 항목·스크롤·포커스가 그대로 남습니다. 새로 완료된 단계에는 완료 효과가 재생되고, 상태 띠도 같은 주기로 갱신됩니다. 데이터를 받지 못하면 화면 아래에 「최신 상태를 불러오지 못하고 있어요 · N분째」 가 뜹니다.
  • 페이지는 127.0.0.1 전용 정적 서버(serve.py)로 열립니다. Orca 같은 인앱 브라우저가 페이지 안의 file:// 이동을 막기 때문입니다. 서버는 처음 페이지를 열 때 자동으로 뜨고 세션이 끝나도 남습니다. /tmp 의 deadhd-*.html 만 제공하고, 심볼릭 링크는 따르지 않으며, 외부 사이트가 읽지 못하도록 Host 헤더를 검사합니다. 끄려면 python3 <스킬 폴더>/serve.py --stop(설정에 적은 경로)을 실행합니다.
  • 허브는 이 컴퓨터의 세션 상태 파일만 읽어 만듭니다. render.py 가 세션 페이지를 렌더할 때와 훅 이벤트마다 허브 파일을 다시 씁니다.

입력 대기 알림과 예상 시간 보정

플러그인이든 스킬 폴더든 함께 읽히는 hooks/hooks.json 의 훅이 세션 이벤트(권한 요청, 답변 종료, 도구 실행, 압축, 세션 종료)를 받아 /tmp/deadhd-state/<세션 ID>.json 에 상태를 쓰고 페이지를 다시 렌더합니다. 페이지 상단에 권한 승인 대기 · 12분째, 입력 대기 · 23분째, 작업 중 · 마지막 도구 Bash 8초 전, 신호 없음, 세션 종료 띠가 붙습니다. 모델이 갱신을 잊어도 띠는 훅이 유지하고, 압축 뒤에는 세션 시작 훅이 데이터 파일 경로를 모델에 다시 알려 줍니다.

단계가 완료될 때 처음 적힌 예상과 실제 소요가 ~/.config/deadhd/history.jsonl 에 쌓이고, 3건부터 보정 완료 예상이 원래 값 옆에 표시됩니다. 기록되는 것은 단계 id·예상·실제 분 수뿐입니다.

<a id="훅-직접-등록"></a>

스킬 폴더나 Orca 로 설치해도 상태 띠 훅이 함께 읽히므로 ~/.claude/settings.json 에 직접 넣을 필요가 없습니다. 예전 안내대로 아래 여섯 훅을 넣어 두었다면 지워도 되고, 남겨 두어도 화면에 남는 값은 같습니다. state.py 는 같은 이벤트가 연달아 두 번 들어오면 두 번째를 이미 반영한 것으로 보고 넘깁니다.

훅이 아예 돌지 않는 세션(Codex 처럼 이 플러그인을 읽지 않는 곳)은 페이지에 상태 띠가 붙지 않고, 허브에서는 훅 없음 또는 완료 로 나옵니다.

{
  "hooks": {
    "Notification": [{ "matcher": "permission_prompt|idle_prompt", "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }],
    "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }],
    "PostToolUse": [{ "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }],
    "Stop": [{ "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }],
    "SessionStart": [{ "matcher": "compact", "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }],
    "SessionEnd": [{ "hooks": [{ "type": "command", "command": "python3 \"$HOME/.claude/skills/deadhd/state.py\"" }] }]
  }
}

파일과 환경 변수

경로내용
/tmp/deadhd-<slug>.json진행 데이터. 모델이 작성합니다
/tmp/deadhd-<slug>.html진행 페이지
/tmp/deadhd-hub.html허브 페이지
/tmp/deadhd-state/<세션 ID>.json세션 상태. 훅과 render.py 가 씁니다. 7일이 지난 파일은 정리합니다
~/.config/deadhd/config.json설정(열기 위치·표시 방식·세션 HUD·테마·글꼴)
~/.config/deadhd/history.jsonl예상·실제 이력
~/.config/deadhd/writing-rules.md작성 규칙(선택)
변수기본값
DEADHD_PORT47320 (서버는 127.0.0.1 에서만 받습니다)
DEADHD_HUB/tmp/deadhd-hub.html
DEADHD_STATE_DIR/tmp/deadhd-state
DEADHD_HISTORY~/.config/deadhd/history.jsonl
DEADHD_CONFIG~/.config/deadhd/config.json
XDG_CONFIG_HOME지정하면 설정과 이력이 $XDG_CONFIG_HOME/deadhd/ 아래에 만들어집니다
DEADHD_NOW페이지가 쓰는 시각을 고정합니다. 테스트와 예시 그림 재생성에 씁니다

개발

python3 -m unittest skills/deadhd/test_render.py

예시 그림 열네 장은 Chrome 을 설치한 환경에서 다음 명령으로 다시 만듭니다. 모든 그림은 2배율, 폭 1600px 로 찍고 README 에서 width="800" 으로 보여 줍니다. docs/pulse.png 와 docs/pulse.en.png 는 캡처하지 않고 Pulse 저장소 의 docs/images/deadhd-steps.png·deadhd-steps.en.png 를 복사한 것입니다.

python3 docs/capture_themes.py && python3 docs/capture_themes.py --lang en   # themes.png, themes.en.png
python3 docs/capture_views.py && python3 docs/capture_views.py --lang en     # views.png, views.en.png
python3 docs/capture_hub.py && python3 docs/capture_hub.py --lang en         # hub.png, hub.en.png, live.png, live.en.png
python3 docs/capture_board.py && python3 docs/capture_board.py --lang en     # board.png, board.en.png
python3 docs/capture_mods.py && python3 docs/capture_mods.py --lang en       # band.png, band.en.png, statusline.png, statusline.en.png

라이선스

MIT

Source 2 files
hooks/register.tsx 1992 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, ThemeKey } from 'claude-code'
3
4import type {
5  DeadhdHud,
6  DeadhdLang,
7  DeadhdPr,
8  DeadhdState,
9  DeadhdStep,
10  DeadhdView,
11} from '../types'
12
13const DEFAULT_STATE_DIR = '/tmp/deadhd-state'
14const REFRESH_MS = 5000
15
16/** PromptHint hands the tree no width, so this is the budget its pieces are cut to. */
17const STATUS_COLS = 240
18/**
19 * Cells the hint line is indented by, the indent on both sides together, inside
20 * the surface's own width: `e.viewport.columns` is the whole screen, so the line
21 * drawn in the indented slot must have them taken off its budget.
22 */
23const HINT_INSET = 4
24/** Cells the progress bar draws; `done/total` is rounded onto them. */
25const BAR_CELLS = 6
26const SEP = ' · '
27const OPEN_TIMEOUT_MS = 15000
28
29/** The mark both lines open with, so a folded row names no command. */
30const STATUS_MARK = '◆'
31
32/** With no state file and no config the session draws in this view, as render.py decides too. */
33export const DEFAULT_VIEW: DeadhdView = 'html'
34
35/** The HUD of a mod that has watched nothing yet: what a line with no observation draws from. */
36export const EMPTY_HUD: DeadhdHud = {
37  startedAt: null,
38  turnAt: null,
39  endedAt: null,
40  tool: null,
41  toolAt: null,
42  running: 0,
43  compactions: 0,
44}
45
46const VIEWS: readonly DeadhdView[] = ['html', 'band', 'statusline']
47
48/** The theme keys a piece may name; `plain` leaves the text the person's own color. */
49export type Tone =
50  | 'plain'
51  | Extract<
52      ThemeKey,
53      | 'claude'
54      | 'permission'
55      | 'text'
56      | 'success'
57      | 'subtle'
58      | 'planMode'
59      | 'warning'
60      | 'error'
61      | 'suggestion'
62      | 'inactive'
63      | 'autoAccept'
64      | 'merged'
65      | 'ide'
66      | 'remember'
67    >
68
69/**
70 * One drawn piece of a line: `text` is what shows, `tone` what colors it, and
71 * `href` the address the piece links to when it has one.
72 */
73export type Segment = { text: string; tone: Tone; bold?: boolean; href?: string }
74
75/** One field of a line: its pieces drawn side by side, a separator before the next field. */
76type Field = { tag: string; parts: Segment[] }
77
78const WORDS: Record<
79  DeadhdLang,
80  {
81    blocked: string
82    left: string
83    allDone: string
84    ask: string
85    next: string
86    eta: string
87    background: string
88    compacted: string
89    collapse: string
90    expand: string
91    open: string
92    enable: string
93    enablePrompt: string
94    enableSent: string
95    enableFailed: string
96    folded: string
97    unfolded: string
98    statusFolded: string
99    statusUnfolded: string
100    bandOnly: string
101    statusOnly: string
102    permission: string
103    input: string
104    running: string
105    stale: string
106    toolRunning: string
107    progress: string
108    opened: string
109    noPage: string
110    openFailed: string
111    desktopPath: string
112    noBrowser: string
113  }
114> = {
115  ko: {
116    blocked: '막힘',
117    left: '남음',
118    allDone: '완료',
119    ask: '할 일',
120    next: '다음',
121    eta: '예상',
122    background: '백그라운드',
123    compacted: '압축',
124    collapse: '접기',
125    expand: '펼치기',
126    open: '열기',
127    enable: '켜기',
128    enablePrompt: 'deadhd 스킬로 이 세션의 체크리스트를 띄워 줘.',
129    enableSent: '체크리스트를 켜 달라고 보냈어요',
130    enableFailed: '체크리스트를 켜 달라고 보내지 못했어요',
131    folded: '밴드를 접었어요',
132    unfolded: '밴드를 펼쳤어요',
133    statusFolded: '상태줄을 접었어요',
134    statusUnfolded: '상태줄을 펼쳤어요',
135    bandOnly: '지금은 밴드 모드가 아니에요. /deadhd setup 에서 밴드를 고르면 보여요.',
136    statusOnly: '지금은 상태줄 모드가 아니에요. /deadhd setup 에서 상태줄을 고르면 보여요.',
137    permission: '권한 승인 대기',
138    input: '입력 대기',
139    running: '작업 중',
140    stale: '낡음',
141    toolRunning: '실행 중',
142    progress: '진행',
143    opened: 'HTML 페이지를 열었어요',
144    noPage: '아직 HTML 페이지가 없어요',
145    openFailed: 'HTML 페이지를 열지 못했어요',
146    desktopPath: 'Claude 데스크톱 앱에서 이 경로를 눌러 주세요:',
147    noBrowser: '열 수 있는 브라우저를 찾지 못했어요:',
148  },
149  en: {
150    blocked: 'blocked',
151    left: 'left',
152    allDone: 'all done',
153    ask: 'your move',
154    next: 'next',
155    eta: 'ETA',
156    background: 'background',
157    compacted: 'compacted',
158    collapse: 'Collapse',
159    expand: 'Expand',
160    open: 'Open',
161    enable: 'Enable',
162    enablePrompt: "Show this session's checklist with the deadhd skill.",
163    enableSent: 'Asked Claude to show the checklist.',
164    enableFailed: 'Could not ask Claude to show the checklist.',
165    folded: 'Band collapsed.',
166    unfolded: 'Band expanded.',
167    statusFolded: 'Collapsed the status line',
168    statusUnfolded: 'Expanded the status line',
169    bandOnly: 'The band is not drawn in this view. Choose band with /deadhd setup.',
170    statusOnly: 'The status line is not drawn in this view. Choose statusline with /deadhd setup.',
171    permission: 'waiting for permission',
172    input: 'waiting for input',
173    running: 'working',
174    stale: 'stale',
175    toolRunning: 'running',
176    progress: 'progress',
177    opened: 'Opened the HTML.',
178    noPage: 'No HTML page yet.',
179    openFailed: 'Could not open the HTML',
180    desktopPath: 'Press this path in the Claude desktop app to open the page:',
181    noBrowser: 'Could not find a browser to open the page:',
182  },
183}
184
185const live = atom({ plugin: 'deadhd', key: 'state' } as const, null)
186const collapsed = atom({ plugin: 'deadhd', key: 'collapsed' } as const, false)
187const shown = atom({ plugin: 'deadhd', key: 'view' } as const, DEFAULT_VIEW)
188/** Whether the config asks the mod to draw the HUD it watches; an unset config reads as on. */
189const hudOn = atom({ plugin: 'deadhd', key: 'hud-on' } as const, true)
190/** Whether the config asks for a rule above the status line; an unset config reads as off. */
191const dividerOn = atom({ plugin: 'deadhd', key: 'divider-on' } as const, false)
192
193/** What the mod watched of this session by itself, before any state file is there to read. */
194const seen = atom({ plugin: 'deadhd', key: 'hud' } as const, EMPTY_HUD)
195
196/**
197 * The text each mode last asked a repaint for, so a refresh whose line did not
198 * move stays quiet. A hot reload losing it costs one extra repaint.
199 */
200const painted: Partial<Record<'band' | 'status', string>> = {}
201
202/**
203 * The cells each mode's line may take, as the surface last measured them: the
204 * band's region without its buttons, the status line's viewport without the
205 * button beside it. A refresh cuts the line it compares to the same width; the
206 * fixed budget stands in until a drawing has measured one.
207 */
208const widths: Record<'band' | 'status', number> = { band: STATUS_COLS, status: STATUS_COLS }
209
210/**
211 * Code point ranges that take two cells in a terminal's monospace metric:
212 * East Asian Wide, plus the emoji blocks a terminal draws with emoji
213 * presentation (a symbol below U+1F300 like `✅` or `⏳` is one of these).
214 */
215const WIDE: readonly (readonly [number, number])[] = [
216  [0x1100, 0x115f],
217  [0x231a, 0x231b],
218  [0x23e9, 0x23f3],
219  [0x25fd, 0x25fe],
220  [0x2614, 0x2615],
221  [0x2648, 0x2653],
222  [0x267f, 0x267f],
223  [0x2693, 0x2693],
224  [0x26a1, 0x26a1],
225  [0x26aa, 0x26ab],
226  [0x26bd, 0x26be],
227  [0x26c4, 0x26c5],
228  [0x26ce, 0x26ce],
229  [0x26d4, 0x26d4],
230  [0x26ea, 0x26ea],
231  [0x26f2, 0x26f3],
232  [0x26f5, 0x26f5],
233  [0x26fa, 0x26fa],
234  [0x26fd, 0x26fd],
235  [0x2705, 0x2705],
236  [0x270a, 0x270b],
237  [0x2728, 0x2728],
238  [0x274c, 0x274c],
239  [0x274e, 0x274e],
240  [0x2753, 0x2755],
241  [0x2757, 0x2757],
242  [0x2795, 0x2797],
243  [0x27b0, 0x27b0],
244  [0x27bf, 0x27bf],
245  [0x2b1b, 0x2b1c],
246  [0x2b50, 0x2b50],
247  [0x2b55, 0x2b55],
248  [0x2e80, 0xa4cf],
249  [0xac00, 0xd7a3],
250  [0xf900, 0xfaff],
251  [0xfe30, 0xfe4f],
252  [0xff00, 0xff60],
253  [0xffe0, 0xffe6],
254  [0x1f300, 0x1faff],
255  [0x20000, 0x3fffd],
256]
257
258/** Code point ranges that take no cell of their own (combining and zero width). */
259const ZERO: readonly (readonly [number, number])[] = [
260  [0x0300, 0x036f],
261  [0x200b, 0x200f],
262  [0xfe00, 0xfe0f],
263]
264
265/** The variation selector that asks for a glyph's emoji drawing. */
266const VS16 = 0xfe0f
267
268const within = (code: number, ranges: readonly (readonly [number, number])[]): boolean =>
269  ranges.some(([low, high]) => code >= low && code <= high)
270
271/**
272 * How many terminal cells `text` takes, one code point at a time. A symbol
273 * drawn as text (`✓`, `▶`, `↗`, `▓`) is one cell, an emoji-presentation one is
274 * two, and a base character followed by U+FE0F is drawn as the emoji it selects.
275 */
276export function cellWidth(text: string): number {
277  const points = Array.from(text, code => code.codePointAt(0) ?? 0)
278  let cells = 0
279
280  for (let at = 0; at < points.length; at += 1) {
281    const point = points[at] ?? 0
282
283    if (within(point, ZERO)) {
284      // The selector itself is no cell; the character it follows gains the one
285      // that makes it an emoji.
286      const before = points[at - 1]
287
288      if (point === VS16 && before !== undefined && !within(before, WIDE) && !within(before, ZERO)) {
289        cells += 1
290      }
291
292      continue
293    }
294
295    cells += within(point, WIDE) ? 2 : 1
296  }
297
298  return cells
299}
300
301/** Cells a band control takes when drawn: `[ label ]`, brackets and padding included. */
302const buttonCols = (label: string): number => cellWidth(label) + 4
303
304/** The Text props a tone names: the theme key itself, or the text's own color. */
305const paint = (tone: Tone): { color?: ThemeKey } => (tone === 'plain' ? {} : { color: tone })
306
307const record = (value: unknown): Record<string, unknown> =>
308  typeof value === 'object' && value !== null && !Array.isArray(value)
309    ? (value as Record<string, unknown>)
310    : {}
311
312const count = (value: unknown): number =>
313  typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0
314
315const text = (value: unknown, fallback: string): string =>
316  typeof value === 'string' ? value : fallback
317
318/** A value the config or a state file may spell as a view; anything else has no reading. */
319const asView = (value: unknown): DeadhdView | null =>
320  typeof value === 'string' && (VIEWS as readonly string[]).includes(value)
321    ? (value as DeadhdView)
322    : null
323
324/** The view in force: the state file's own, else the config file's, else the default. */
325export function resolveView(stateView: unknown, configView: unknown): DeadhdView {
326  return asView(stateView) ?? asView(configView) ?? DEFAULT_VIEW
327}
328
329/** A lane or column as the data file may spell it; a non-integer has no reading. */
330const asIndex = (value: unknown): number | null => {
331  if (typeof value === 'number' && Number.isFinite(value)) {
332    return value >= 0 ? Math.floor(value) : null
333  }
334
335  if (typeof value === 'string' && /^\d+$/.test(value)) {
336    return Number(value)
337  }
338
339  return null
340}
341
342/** An instant as the HUD keeps it: ISO 8601, the shape `minutesBetween` reads. */
343const instant = (now: number): string => new Date(now).toISOString()
344
345/** Whole seconds between an ISO instant and `now`, or null when either does not read as one. */
346const secondsBetween = (from: string | null, now: number): number | null => {
347  if (from === null) {
348    return null
349  }
350
351  const at = Date.parse(from)
352
353  if (!Number.isFinite(at) || now < at) {
354    return null
355  }
356
357  return Math.floor((now - at) / 1000)
358}
359
360/** Whole minutes between an ISO instant and `now`, or null when either does not read as one. */
361const minutesBetween = (from: string | null, now: number): number | null => {
362  const seconds = secondsBetween(from, now)
363
364  return seconds === null ? null : Math.floor(seconds / 60)
365}
366
367/** `8분째` / `8m in`: how long a step has been running. */
368const since = (minutes: number, lang: DeadhdLang): string =>
369  lang === 'en' ? `${minutes}m in` : `${minutes}분째`
370
371/** `8분 전` / `8m ago`: how long since the state file was written. */
372const ago = (minutes: number, lang: DeadhdLang): string =>
373  lang === 'en' ? `${minutes}m ago` : `${minutes}분 전`
374
375/** `12초 전` / `12s ago`: how long since the tool a line names last ran. */
376const toolAgo = (seconds: number, lang: DeadhdLang): string =>
377  lang === 'en' ? `${seconds}s ago` : `${seconds}초 전`
378
379/** The `HH:MM` an eta carries, in the offset its writer used; null for anything else. */
380const clockOf = (eta: string | null): string | null => {
381  if (eta === null) {
382    return null
383  }
384
385  const match = /T(\d{2}:\d{2})/.exec(eta)
386
387  return match === null ? null : (match[1] ?? null)
388}
389
390/** The first line of a command's stderr, trimmed; `''` when it wrote none. */
391const firstLine = (output: string): string => (output.split('\n')[0] ?? '').trim()
392
393/**
394 * `label` cut to `room` cells, its ellipsis counted, or `…` when not even one
395 * cell is left. A cut that would land inside a number drops that whole run of
396 * digits first, so `PR 1059 리뷰` in 7 cells reads `PR …` rather than a number
397 * a reader would take for another one.
398 */
399const cut = (label: string, room: number): string => {
400  if (cellWidth(label) <= room) {
401    return label
402  }
403
404  if (room <= 1) {
405    return '…'
406  }
407
408  const codes = [...label]
409  let kept = ''
410  let used = 0
411  let at = 0
412
413  for (; at < codes.length; at++) {
414    const code = codes[at] ?? ''
415    const wide = cellWidth(code)
416
417    if (used + wide > room - 1) {
418      break
419    }
420
421    kept += code
422    used += wide
423  }
424
425  if (/[0-9][0-9.,:]*$/.test(kept) && /^[0-9]$/.test(codes[at] ?? '')) {
426    const body = kept.replace(/[0-9.,:]+$/, '')
427    const spaced = /\s$/.test(body) ? body.trimEnd() + ' ' : body
428
429    return spaced === '' ? '…' : spaced + '…'
430  }
431
432  return `${kept.trimEnd()}…`
433}
434
435const barParts = (done: number, total: number): Segment[] => {
436  const cells = Math.max(0, Math.min(BAR_CELLS, Math.round((done / total) * BAR_CELLS)))
437  const parts: Segment[] = []
438
439  if (cells > 0) {
440    parts.push({ text: '▓'.repeat(cells), tone: 'success' })
441  }
442
443  if (cells < BAR_CELLS) {
444    parts.push({ text: '░'.repeat(BAR_CELLS - cells), tone: 'subtle' })
445  }
446
447  return parts
448}
449
450/** The glyph and color a marked step carries: work running in parallel draws its own. */
451const stepMark = (state: string, running: string): Segment =>
452  state === 'side'
453    ? { text: '◐', tone: 'autoAccept' }
454    : { text: running, tone: 'suggestion', bold: true }
455
456/**
457 * The piece for the step a line marks, colored and marked by that step's own
458 * state. The mark and the label are their own piece so a line too narrow for
459 * the whole step gives up the label's words, never the run of time drawn
460 * beside them: a duration cut in the middle of its digits reads as another one.
461 */
462const stepField = (step: DeadhdStep, lang: DeadhdLang, now: number, running: string): Field => {
463  const mark = stepMark(step.state, running)
464  const minutes = minutesBetween(step.startedAt, now)
465  const tail = minutes === null ? '' : ` ${since(minutes, lang)}`
466  const label: Segment = { text: `${mark.text} ${step.label}`, tone: mark.tone, bold: mark.bold === true }
467
468  return {
469    tag: 'current',
470    parts: tail === '' ? [label] : [label, { text: tail, tone: mark.tone, bold: mark.bold === true }],
471  }
472}
473
474/** One session-state piece: the mark, the word for the state, and how long it has lasted. */
475const sessionPiece = (
476  mark: string,
477  word: string,
478  tone: Tone,
479  from: string | null,
480  now: number,
481  lang: DeadhdLang,
482): Field => {
483  const minutes = minutesBetween(from, now)
484  const tail = minutes === null ? '' : ` ${since(minutes, lang)}`
485
486  return { tag: 'session', parts: [{ text: `${mark} ${word}${tail}`, tone, bold: true }] }
487}
488
489/**
490 * The session's own state: the wait it is in, and since when. The mod watches
491 * the turn itself, so its own word for working and for waiting beats the state
492 * file's; the permission dialog is the engine's own and raises no event the mod
493 * can watch, so that one word is the state file's.
494 */
495const sessionField = (
496  state: DeadhdState | null,
497  hud: DeadhdHud,
498  now: number,
499  lang: DeadhdLang,
500): Field | null => {
501  const words = WORDS[lang]
502
503  if (state !== null && state.status === 'waiting_permission') {
504    return sessionPiece('🔐', words.permission, 'warning', state.since, now, lang)
505  }
506
507  // `●`, not the `▶` the run's own current step carries: one row draws both, so
508  // the mark has to say which of the two a reader is looking at.
509  if (hud.turnAt !== null) {
510    return sessionPiece('●', words.running, 'suggestion', hud.turnAt, now, lang)
511  }
512
513  // A mod that loaded into a running session watched no turn either way, so the
514  // state file's own word for the wait stands where it names one.
515  const from = hud.endedAt ?? hud.startedAt ?? (state !== null && state.status === 'idle' ? state.since : null)
516
517  return from === null ? null : sessionPiece('⌨️', words.input, 'merged', from, now, lang)
518}
519
520/** The tool the main loop called last, or the one it runs now; a subagent's own calls are not its own. */
521const toolField = (hud: DeadhdHud, now: number, lang: DeadhdLang): Field | null => {
522  if (hud.tool === null) {
523    return null
524  }
525
526  if (hud.running > 0) {
527    return { tag: 'tool', parts: [{ text: `🔧 ${hud.tool} ${WORDS[lang].toolRunning}`, tone: 'ide', bold: true }] }
528  }
529
530  const seconds = secondsBetween(hud.toolAt, now)
531
532  return seconds === null
533    ? null
534    : { tag: 'tool', parts: [{ text: `🔧 ${hud.tool} ${toolAgo(seconds, lang)}`, tone: 'subtle' }] }
535}
536
537/** The compaction piece: the count the mod watched, the state file's own standing in for its miss. */
538const compactedField = (state: DeadhdState | null, hud: DeadhdHud, lang: DeadhdLang): Field | null => {
539  // Both counts are of this session, so the larger one missed fewer of its events.
540  const compactions = Math.max(hud.compactions, state?.compactions ?? 0)
541
542  return compactions === 0
543    ? null
544    : {
545        tag: 'compacted',
546        parts: [{ text: `🗜 ${WORDS[lang].compacted} ${compactions}`, tone: 'remember' }],
547      }
548}
549
550/**
551 * The session's own state and the tool it last called: the fields no state file
552 * is needed for. The status line draws the compactions watched here too, since
553 * that count is the mod's own watch; the band draws the session state and the
554 * tool alone.
555 */
556const hudFields = (
557  state: DeadhdState | null,
558  hud: DeadhdHud,
559  now: number,
560  lang: DeadhdLang,
561  compacted: boolean,
562): Field[] => {
563  const fields: Field[] = []
564  const session = sessionField(state, hud, now, lang)
565  const tool = toolField(hud, now, lang)
566  const compaction = compacted ? compactedField(state, hud, lang) : null
567
568  // Ahead of the session's own state: the status line drew the compaction there
569  // while the field was the run's own.
570  if (compaction !== null) {
571    fields.push(compaction)
572  }
573
574  if (session !== null) {
575    fields.push(session)
576  }
577
578  if (tool !== null) {
579    fields.push(tool)
580  }
581
582  return fields
583}
584
585/** The mark a line opens with, on its own while the session has nothing else to draw. */
586const markField = (): Field => ({ tag: 'name', parts: [{ text: STATUS_MARK, tone: 'claude', bold: true }] })
587
588/** The band's first row: how far the run has come, and what is on it, then the session's own state. */
589const bandFields = (state: DeadhdState | null, hud: DeadhdHud, now: number): Field[] => {
590  const lang = state?.lang ?? 'ko'
591
592  return [
593    ...(state === null ? [markField()] : bandRun(state, hud, now)),
594    ...hudFields(state, hud, now, lang, false),
595  ]
596}
597
598/**
599 * Whether the session is working on a checklist it has not finished: the case
600 * a behind-age piece is drawn as `낡음` for. It follows the two things the mod
601 * already reads as working — the `●` `sessionField` draws for a turn in flight,
602 * and the state file's own word for a session the mod loaded into mid-run.
603 */
604const busyNow = (state: DeadhdState, hud: DeadhdHud): boolean =>
605  !state.allDone &&
606  state.status !== 'waiting_permission' &&
607  (hud.turnAt !== null || (hud.endedAt === null && hud.startedAt === null && state.status === 'working'))
608
609/** The run's own pieces on the band's first row: the progress, the step it marks and the counts. */
610const bandRun = (state: DeadhdState, hud: DeadhdHud, now: number): Field[] => {
611  const words = WORDS[state.lang]
612  const fields: Field[] = [markField()]
613
614  if (state.total > 0) {
615    fields.push({
616      tag: 'bar',
617      parts: [
618        ...barParts(state.done, state.total),
619        { text: ' ', tone: 'plain' },
620        { text: `${state.done}/${state.total}`, tone: 'success', bold: true },
621      ],
622    })
623  }
624
625  if (state.current !== null) {
626    fields.push(stepField(state.current, state.lang, now, '▶'))
627  }
628
629  if (state.next !== null) {
630    fields.push({
631      tag: 'next',
632      parts: [{ text: `⏭ ${words.next} ${state.next.label}`, tone: 'inactive' }],
633    })
634  }
635
636  const eta = clockOf(state.eta)
637
638  if (eta !== null) {
639    fields.push({ tag: 'etaBand', parts: [{ text: `⏱ ${words.eta} ${eta}`, tone: 'planMode' }] })
640  }
641
642  const behind = minutesBetween(state.updatedAt, now)
643
644  if (behind !== null) {
645    const piece = updatePiece(behind, state.lang, busyNow(state, hud))
646
647    fields.push({ tag: piece.tone === 'subtle' ? 'agoQuiet' : 'ago', parts: [piece] })
648  }
649
650  if (state.blocked > 0) {
651    fields.push({
652      tag: 'stuck',
653      parts: [{ text: `${words.blocked} ${state.blocked}`, tone: 'error', bold: true }],
654    })
655  }
656
657  if (state.left > 0) {
658    fields.push({ tag: 'leftCount', parts: [{ text: `${words.left} ${state.left}`, tone: 'text' }] })
659  }
660
661  if (state.allDone) {
662    fields.push({ tag: 'allDone', parts: [{ text: words.allDone, tone: 'success', bold: true }] })
663  }
664
665  return fields
666}
667
668/** The band's second row: the step that got stuck, when one is. */
669const bandAlertFields = (state: DeadhdState): Field[] => {
670  const words = WORDS[state.lang]
671  const fields: Field[] = []
672
673  if (state.stuck !== null) {
674    const note = state.stuck.sub === '' ? state.stuck.label : `${state.stuck.label} (${state.stuck.sub})`
675
676    fields.push({
677      tag: 'blocked',
678      parts: [
679        { text: `⛔ ${words.blocked}: `, tone: 'error', bold: true },
680        { text: note, tone: 'error', bold: true },
681      ],
682    })
683  }
684
685  if (state.stuck !== null && state.stuck.state === 'blocked' && state.stuck.ask !== '') {
686    fields.push({
687      tag: 'ask',
688      parts: [
689        { text: `${words.ask}: `, tone: 'warning', bold: true },
690        { text: state.stuck.ask, tone: 'text' },
691      ],
692    })
693  }
694
695  return fields
696}
697
698/** The status line's pieces, in the order the long row draws them. */
699const statusFields = (state: DeadhdState | null, hud: DeadhdHud, now: number): Field[] => {
700  const lang = state?.lang ?? 'ko'
701
702  return [
703    ...(state === null ? [markField()] : statusRun(state, hud, now)),
704    ...hudFields(state, hud, now, lang, true),
705  ]
706}
707
708/** The run's own pieces on the long row, in the order it draws them. */
709const statusRun = (state: DeadhdState, hud: DeadhdHud, now: number): Field[] => {
710  const words = WORDS[state.lang]
711  const fields: Field[] = []
712
713  if (state.total > 0) {
714    // The mark rides in the count's own field, so no separator falls between it
715    // and the count; the bar's cells can go without taking the mark with them.
716    fields.push({
717      tag: 'count',
718      parts: [
719        { text: `${STATUS_MARK} `, tone: 'claude', bold: true },
720        { text: `✓ ${state.done}/${state.total}`, tone: 'success', bold: true },
721        { text: ' ', tone: 'plain' },
722        ...barParts(state.done, state.total),
723      ],
724    })
725  } else {
726    fields.push(markField())
727  }
728
729  const heading = headingParts(state)
730
731  if (heading.length > 0) {
732    fields.push({ tag: 'title', parts: heading })
733  }
734
735  if (state.current !== null) {
736    fields.push(stepField(state.current, state.lang, now, '▶'))
737  }
738
739  if (state.pr !== null) {
740    fields.push({
741      tag: 'pr',
742      parts: [
743        { text: '🔀 ', tone: 'permission' },
744        { text: state.pr.text, tone: 'permission', href: state.pr.href },
745      ],
746    })
747  }
748
749  if (state.next !== null) {
750    fields.push({
751      tag: 'next',
752      parts: [{ text: `⏭ ${words.next} ${state.next.label}`, tone: 'inactive' }],
753    })
754  }
755
756  const eta = clockOf(state.eta)
757
758  if (eta !== null) {
759    fields.push({ tag: 'eta', parts: [{ text: `⏱ ${words.eta} ${eta}`, tone: 'planMode' }] })
760  }
761
762  const behind = minutesBetween(state.updatedAt, now)
763
764  if (behind !== null) {
765    fields.push({ tag: 'ago', parts: [updatePiece(behind, state.lang, busyNow(state, hud))] })
766  }
767
768  if (state.blocked > 0) {
769    const parts: Segment[] = [
770      { text: `⛔ ${words.blocked} ${state.blocked}`, tone: 'error', bold: true },
771    ]
772
773    if (state.stuck !== null) {
774      parts.push({ text: `: ${state.stuck.label}`, tone: 'error', bold: true })
775    }
776
777    fields.push({ tag: 'blocked', parts })
778  }
779
780  if (state.left > 0) {
781    fields.push({ tag: 'left', parts: [{ text: `⏳ ${words.left} ${state.left}`, tone: 'text' }] })
782  }
783
784  if (state.background > 0) {
785    fields.push({
786      tag: 'background',
787      parts: [{ text: `🧵 ${words.background} ${state.background}`, tone: 'ide' }],
788    })
789  }
790
791  return fields
792}
793
794/**
795 * The title's pieces: the key it opens with, colored and, when the state names
796 * one, linked, then the rest of the title. A title that opens with the key
797 * itself draws the key once, out of the title's own cells, rather than beside
798 * it as a copy.
799 */
800const headingParts = (state: DeadhdState): Segment[] => {
801  const key = state.key
802
803  if (key === null) {
804    return state.title === '' ? [] : [{ text: state.title, tone: 'text' }]
805  }
806
807  const link = state.keyHref === null ? {} : { href: state.keyHref }
808  const piece: Segment = { text: key, tone: 'permission', bold: true, ...link }
809  const body = titleAfterKey(state.title, key)
810
811  if (body === null) {
812    return state.title === '' ? [piece] : [piece, { text: ` ${state.title}`, tone: 'text' }]
813  }
814
815  return body === '' ? [piece] : [piece, { text: body, tone: 'text' }]
816}
817
818/**
819 * What is left of `title` past the `key` it opens with, or null when it opens
820 * with something else. The key must end where a word does: the string, a space
821 * or a punctuation mark, so `CAS-11` is not read as the key of `CAS-1159`.
822 */
823const titleAfterKey = (title: string, key: string): string | null => {
824  const trimmed = title.trimStart()
825
826  if (!trimmed.startsWith(key)) {
827    return null
828  }
829
830  const after = trimmed.slice(key.length)
831
832  return after === '' || /^[\s\p{P}]/u.test(after) ? after : null
833}
834
835/**
836 * The last-update piece: quiet while the skill keeps up, louder as it falls
837 * behind. A session that is not working raises no alarm however old the write
838 * is — a wait or a finished run is not a stale one.
839 */
840const updatePiece = (minutes: number, lang: DeadhdLang, busy: boolean): Segment => {
841  const body = ago(minutes, lang)
842
843  if (busy && minutes > 30) {
844    return { text: `🛑 ${WORDS[lang].stale} ${body}`, tone: 'error' }
845  }
846
847  if (busy && minutes > 10) {
848    return { text: `⚠️ ${body}`, tone: 'warning' }
849  }
850
851  return { text: `🔄 ${body}`, tone: 'subtle' }
852}
853
854const fieldWidth = (field: Field): number =>
855  field.parts.reduce((cells, part) => cells + cellWidth(part.text), 0)
856
857/** Cells the whole line takes, its separators counted. */
858const lineWidth = (fields: readonly Field[]): number =>
859  fields.length === 0
860    ? 0
861    : fields.reduce((cells, field) => cells + fieldWidth(field), 0) +
862      (fields.length - 1) * cellWidth(SEP)
863
864/** Cuts a field's last piece to the cells left for it, or drops that piece when none are. */
865const cutLast = (field: Field, room: number): void => {
866  const last = field.parts[field.parts.length - 1]
867
868  if (last === undefined) {
869    return
870  }
871
872  const fixed = field.parts
873    .slice(0, -1)
874    .reduce((cells, part) => cells + cellWidth(part.text), 0)
875  const left = room - fixed
876
877  if (left <= 1) {
878    field.parts.pop()
879
880    return
881  }
882
883  field.parts[field.parts.length - 1] = { ...last, text: cut(last.text, left) }
884}
885
886/**
887 * Cuts the marked step's label to the cells left once its run of time is kept
888 * whole. Too few cells for the label at all leaves the field untouched, so the
889 * drop that follows takes the whole step rather than the mark with a bare `…`.
890 */
891const cutStepLabel = (field: Field, room: number): void => {
892  const label = field.parts[0]
893
894  if (label === undefined) {
895    return
896  }
897
898  const tail = field.parts.slice(1).reduce((cells, part) => cells + cellWidth(part.text), 0)
899  const left = room - tail
900
901  if (left <= 1) {
902    return
903  }
904
905  field.parts[0] = { ...label, text: cut(label.text, left) }
906}
907
908/** Cells the stuck step's label keeps while the ask beside it gives way first. */
909const STUCK_KEEP = 8
910
911/**
912 * Brings a line inside `maxCols` cells, giving way in the order the fields can
913 * spare it: the title's body first, then what the mod watched of the session by
914 * itself (the compaction and background counts, then the last tool), the next step,
915 * the band's quiet age piece (`🔄`, which goes before the step's label; an age loud
916 * enough to warn or read stale keeps the last-write age's own place below), the
917 * band's estimate (`etaBand`, which goes just after that quiet age), the
918 * second row's blocked label down to the few cells it keeps while an ask sits
919 * beside it, then that ask (`ask`, which gives its own sentence away and then
920 * goes), the blocked step's label, and the blocked field itself, the label the
921 * step a line marks carries and then the field itself, the last-write age, the
922 * estimate, the left count, the pull request, and the progress bar's own cells.
923 * The band's row carries the same pieces under its own names (`leftCount` for the
924 * left count, `bar` for the count's bar, `stuck` for the blocked label) and gives
925 * them up in the same places. Still too wide, the title falls back to its key alone and then goes.
926 * A title that stayed draws the beginning of what it gave away into the cells
927 * the dropped fields left, so a line too long to hold it whole shows the title's
928 * own words rather than the key alone. What a line must not lose stays: the
929 * state the session is in, the mark or command it opens with, and the
930 * `done/total` the bar's cells are rounded onto — so a row narrower than those
931 * keeps drawing them.
932 */
933const fit = (fields: Field[], maxCols: number): Field[] => {
934  const shrink = (tag: string): void => {
935    const field = fields.find(one => one.tag === tag)
936
937    if (field === undefined) {
938      return
939    }
940
941    cutLast(field, maxCols - (lineWidth(fields) - fieldWidth(field)))
942  }
943
944  /** The marked step gives its label away alone: the mark and the run's time stay. */
945  const shrinkStep = (tag: string): void => {
946    const field = fields.find(one => one.tag === tag)
947
948    if (field !== undefined) {
949      cutStepLabel(field, maxCols - (lineWidth(fields) - fieldWidth(field)))
950    }
951  }
952
953  /** The stuck step keeps a few cells of its own label while the ask beside it gives its sentence away. */
954  const shrinkStuck = (): void => {
955    if (!fields.some(one => one.tag === 'ask')) {
956      return
957    }
958
959    const field = fields.find(one => one.tag === 'blocked')
960
961    if (field === undefined) {
962      return
963    }
964
965    const last = field.parts[field.parts.length - 1]
966
967    if (last === undefined) {
968      return
969    }
970
971    const fixed = field.parts
972      .slice(0, -1)
973      .reduce((cells, part) => cells + cellWidth(part.text), 0)
974    const room =
975      Math.max(maxCols - (lineWidth(fields) - fieldWidth(field)) - fixed, STUCK_KEEP)
976
977    field.parts[field.parts.length - 1] = { ...last, text: cut(last.text, room) }
978  }
979
980  const drop = (tag: string): void => {
981    const at = fields.findIndex(one => one.tag === tag)
982
983    if (at >= 0) {
984      fields.splice(at, 1)
985    }
986  }
987
988  /** The bar's cells go while the `done/total` drawn beside them stays. */
989  const shrinkBar = (tag: string): void => {
990    const field = fields.find(one => one.tag === tag)
991
992    if (field === undefined) {
993      return
994    }
995
996    const kept = field.parts.filter(part => !/^[▓░]+$/.test(part.text))
997
998    // The space the bar was drawn behind goes with it.
999    field.parts = kept.filter((part, at) => at < kept.length - 1 || part.text.trim() !== '')
1000  }
1001
1002  /** The title keeps only the key it opens with; a title without one is left to go. */
1003  const keyOnly = (tag: string): void => {
1004    const field = fields.find(one => one.tag === tag)
1005
1006    if (field === undefined || field.parts.length < 2) {
1007      return
1008    }
1009
1010    const first = field.parts[0]
1011
1012    if (first !== undefined) {
1013      field.parts = [{ ...first, text: first.text.trimEnd() }]
1014    }
1015  }
1016
1017  // The title's own pieces as they came in: it gives its body away first, and
1018  // takes the room the fields after it left back at the end.
1019  const title = fields.find(one => one.tag === 'title')
1020  const whole = title?.parts.map(part => ({ ...part }))
1021
1022  if (lineWidth(fields) > maxCols) shrink('title')
1023  if (lineWidth(fields) > maxCols) drop('compacted')
1024  if (lineWidth(fields) > maxCols) drop('background')
1025  if (lineWidth(fields) > maxCols) drop('tool')
1026  if (lineWidth(fields) > maxCols) drop('next')
1027  if (lineWidth(fields) > maxCols) drop('agoQuiet')
1028  if (lineWidth(fields) > maxCols) drop('etaBand')
1029  if (lineWidth(fields) > maxCols) shrinkStuck()
1030  if (lineWidth(fields) > maxCols) shrink('ask')
1031  if (lineWidth(fields) > maxCols) drop('ask')
1032  if (lineWidth(fields) > maxCols) shrink('blocked')
1033  if (lineWidth(fields) > maxCols) drop('blocked')
1034  if (lineWidth(fields) > maxCols) shrinkStep('current')
1035  if (lineWidth(fields) > maxCols) drop('current')
1036  if (lineWidth(fields) > maxCols) drop('ago')
1037  if (lineWidth(fields) > maxCols) drop('eta')
1038  if (lineWidth(fields) > maxCols) drop('left')
1039  if (lineWidth(fields) > maxCols) drop('leftCount')
1040  if (lineWidth(fields) > maxCols) drop('pr')
1041  if (lineWidth(fields) > maxCols) shrinkBar('count')
1042  if (lineWidth(fields) > maxCols) shrinkBar('bar')
1043  if (lineWidth(fields) > maxCols) drop('stuck')
1044  if (lineWidth(fields) > maxCols) keyOnly('title')
1045  if (lineWidth(fields) > maxCols) drop('title')
1046
1047  // The line fits again, so the title draws the beginning of the body it gave
1048  // away into the cells the dropped fields left. A title that went stays gone.
1049  if (title !== undefined && whole !== undefined && whole.length > 1 && fields.includes(title)) {
1050    title.parts = whole.map(part => ({ ...part }))
1051    cutLast(title, maxCols - (lineWidth(fields) - fieldWidth(title)))
1052  }
1053
1054  return fields.filter(field => field.parts.length > 0)
1055}
1056
1057/** One line's fields as the pieces a drawing lays out, a separator between the fields. */
1058const flatten = (fields: readonly Field[]): Segment[] => {
1059  const parts: Segment[] = []
1060
1061  fields.forEach((field, index) => {
1062    if (index > 0) {
1063      parts.push({ text: SEP, tone: 'subtle' })
1064    }
1065
1066    for (const part of field.parts) {
1067      parts.push(part)
1068    }
1069  })
1070
1071  return parts
1072}
1073
1074/** The band's first row, cut to `maxCols` cells. */
1075export function bandLine(
1076  state: DeadhdState | null,
1077  now: number,
1078  maxCols: number,
1079  hud: DeadhdHud = EMPTY_HUD,
1080): Segment[] {
1081  return flatten(fit(bandFields(state, hud, now), maxCols))
1082}
1083
1084/** The band's second row, empty while no step is stuck. */
1085export function bandAlertLine(state: DeadhdState | null, now: number, maxCols: number): Segment[] {
1086  if (state === null) {
1087    return []
1088  }
1089
1090  return flatten(fit(bandAlertFields(state), maxCols))
1091}
1092
1093const segmentsText = (parts: readonly Segment[]): string => parts.map(part => part.text).join('')
1094
1095/** The status line's pieces, cut to `maxCols` cells. */
1096export function statusLine(
1097  state: DeadhdState | null,
1098  now: number,
1099  maxCols: number,
1100  hud: DeadhdHud = EMPTY_HUD,
1101): Segment[] {
1102  return flatten(fit(statusFields(state, hud, now), maxCols))
1103}
1104
1105/** The status line as plain text: the same pieces a drawing lays out, joined. */
1106export function formatLine(
1107  state: DeadhdState | null,
1108  now: number,
1109  maxCols: number,
1110  hud: DeadhdHud = EMPTY_HUD,
1111): string {
1112  return segmentsText(statusLine(state, now, maxCols, hud))
1113}
1114
1115/**
1116 * A folded line's one row: the mark and the state the session is in, nothing
1117 * else. The buttons drawn at the row's end carry the way back to the long line,
1118 * so the row itself names no command.
1119 */
1120function foldedSegments(
1121  state: DeadhdState | null,
1122  hud: DeadhdHud,
1123  now: number,
1124): Segment[] {
1125  const session = sessionField(state, hud, now, state?.lang ?? 'ko')
1126
1127  return session === null
1128    ? [{ text: STATUS_MARK, tone: 'claude', bold: true }]
1129    : [{ text: STATUS_MARK, tone: 'claude', bold: true }, { text: ' ', tone: 'plain' }, ...session.parts]
1130}
1131
1132/** The rule drawn above the status line, filled with `─` to `cells` cells. */
1133function dividerText(label: string, cells: number): string {
1134  const head = `── ${label} `
1135
1136  return head + '─'.repeat(Math.max(0, cells - cellWidth(head)))
1137}
1138
1139/** The data file's items in lane·column order; a column the data leaves out follows its lane's last. */
1140const readSteps = (data: unknown): DeadhdStep[] => {
1141  const board = record(data)
1142  const raw = board.items
1143
1144  if (!Array.isArray(raw)) {
1145    return []
1146  }
1147
1148  const items: readonly unknown[] = raw
1149  const lanes: readonly unknown[] = Array.isArray(board.lanes) ? board.lanes : []
1150
1151  const laneOf = (value: unknown): number => {
1152    const direct = asIndex(value)
1153
1154    if (direct !== null) {
1155      return direct
1156    }
1157
1158    if (typeof value === 'string') {
1159      const at = lanes.findIndex(
1160        lane => lane === value || record(lane).id === value || record(lane).label === value,
1161      )
1162
1163      if (at >= 0) {
1164        return at
1165      }
1166    }
1167
1168    return 0
1169  }
1170
1171  const filled = new Map<number, number>()
1172
1173  return items
1174    .map((item, index) => {
1175      const source = record(item)
1176      const lane = laneOf(source.lane)
1177      const given = asIndex(source.col)
1178      const col = given ?? filled.get(lane) ?? 0
1179
1180      filled.set(lane, col + 1)
1181
1182      const step: DeadhdStep = {
1183        state: text(source.state, ''),
1184        label: text(source.label, ''),
1185        sub: text(source.sub, ''),
1186        ask: text(source.ask, ''),
1187        startedAt: typeof source.startedAt === 'string' ? source.startedAt : null,
1188        lane,
1189        col,
1190      }
1191
1192      return { step, index }
1193    })
1194    .sort(
1195      (left, right) =>
1196        left.step.lane - right.step.lane ||
1197        left.step.col - right.step.col ||
1198        left.index - right.index,
1199    )
1200    .map(one => one.step)
types/index.d.ts 149 lines
1/**
2 * deadhd's `$.state` contract: the normalized progress the band and the status
3 * line draw from, what the mod watched of the session itself, which view this
4 * session draws in, and whether the person folded the line down for this
5 * session.
6 */
7
8export type DeadhdLang = 'ko' | 'en'
9
10/** Where the session's progress is drawn. */
11export type DeadhdView = 'html' | 'band' | 'statusline'
12
13/**
14 * One step of the session's data file, as the band reads it.
15 *
16 * A step the data spells wrongly costs the pieces that read it, never the line.
17 */
18export type DeadhdStep = {
19  /** The skill's own word for the step: `now`, `side`, `left`, `blocked` or `done`. */
20  state: string
21  label: string
22  /** The one-to-three-word note drawn under the step; `''` when the data has none. */
23  sub: string
24  /** What the user has to do to unblock a blocked step; `''` when the data has none. */
25  ask: string
26  /** When the step started, ISO 8601 with an offset, or null when the data omits it. */
27  startedAt: string | null
28  /** The step's lane and column, the order the page draws it in. */
29  lane: number
30  col: number
31}
32
33/**
34 * The pull request the status line links to: the words an evidence entry shows
35 * and the http(s) address it opens.
36 */
37export type DeadhdPr = {
38  /** The evidence entry's own text, as the page draws it too. */
39  text: string
40  href: string
41}
42
43/**
44 * The session's state file and data file together, normalized: what the band
45 * and the status line read.
46 *
47 * Absent or unreadable values are folded to the neutral ones (`0`, `''`,
48 * `null`), so a file the skill wrote differently costs a part of the line,
49 * never the plugin. A data file that is missing or broken costs the steps
50 * alone: the summary still draws.
51 */
52export type DeadhdState = {
53  /** The skill's own word: `working`, `waiting_permission`, `idle`, `ended`, ... */
54  status: string
55  lang: DeadhdLang
56  /** The ticket or program key of the run, or null when the summary has none. */
57  key: string | null
58  /** The http(s) address the key links to, or null when the summary names none. */
59  keyHref: string | null
60  title: string
61  done: number
62  now: number
63  side: number
64  left: number
65  blocked: number
66  total: number
67  allDone: boolean
68  /** The step the lines mark as running: the first `now`, else the first `side`. */
69  current: DeadhdStep | null
70  /**
71   * The pull request of that running step, as the summary carries it, or null
72   * when the step names none.
73   */
74  pr: DeadhdPr | null
75  /** The first `left` step after `current`, in lane·column order. */
76  next: DeadhdStep | null
77  /** The first `blocked` step the data names. */
78  stuck: DeadhdStep | null
79  /**
80   * The completion estimate, an ISO 8601 instant with an offset, or null:
81   * render.py's calibrated one (`etaCalibrated`) when it calibrated one, else
82   * the estimate it computed from the steps alone.
83   */
84  eta: string | null
85  /**
86   * When the skill last wrote the data file, ISO 8601 with an offset; the lines
87   * count `N분 전` from here. The state file's own write time stands in when the
88   * summary carries none, since the hooks rewrite it on every event.
89   */
90  updatedAt: string | null
91  /** When the current status began, ISO 8601 with an offset. */
92  since: string | null
93  /** How many background tasks the session's last turn left running. */
94  background: number
95  /** How many times the session has compacted. */
96  compactions: number
97  /** The view the state file names, or null when it names none render.py knows. */
98  view: DeadhdView | null
99  /** The absolute path of the data file the page is rendered from, or null. */
100  data: string | null
101  /** The absolute path of the rendered page, or null before one is rendered. */
102  out: string | null
103  /** Whether `state.py --off` has turned this session off. */
104  off: boolean
105}
106
107/**
108 * What the mod has watched of this session itself, for the line it draws before
109 * the skill writes a state file: a session-scoped reading of the engine's own
110 * events, never of the state file.
111 *
112 * The permission dialog is the engine's own and raises no event the mod can
113 * watch, so the state file's word for that wait stands in its place; a watched
114 * turn beats the state file's, which goes stale between renders.
115 */
116export type DeadhdHud = {
117  /** When the session started, ISO 8601 with an offset; `입력 대기` counts from here. */
118  startedAt: string | null
119  /** When the turn in flight began, ISO 8601, or null while no turn runs. */
120  turnAt: string | null
121  /** When the last turn ended, ISO 8601, or null before one has. */
122  endedAt: string | null
123  /** The tool the session's own loop called last, or the one it runs now. */
124  tool: string | null
125  /** When that tool began, or finished, ISO 8601. */
126  toolAt: string | null
127  /** Tool calls in flight; parallel calls settle one at a time. */
128  running: number
129  /** How many compactions the mod watched. */
130  compactions: number
131}
132
133declare module 'claude-code' {
134  interface PluginState {
135    deadhd: {
136      /** The last state read, or null while the session has none. */
137      state: DeadhdState | null
138      /** True while the line is folded to its one-word summary; kept for the session. */
139      collapsed: boolean
140      /** The view in force: the state file's, else the config file's, else `html`. */
141      view: DeadhdView
142      /** What the mod watched of the session itself, drawn with no state file. */
143      hud: DeadhdHud
144      /** Whether the config asks for the HUD; an unset or unknown `hud` value reads as on. */
145      'hud-on': boolean
146    }
147  }
148}
149