SLOPSHOPPER

sitrep

Under each long reply, a box built from the reply's own lines (haiku only picks line numbers): status, outcome, what you have to do, collapsible sections, and…

panebandspinnerrowsguardcommand
★ 1v0.11.0MITupdated 2026-10-25mangow314/mango-mods/sitrep
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sitrep
│ ┃ sitrep ✕ › fix the failing auth test and add an audit log call │ ┃ Changes · uncommitted │ ┃ src/auth.ts +1 ⏺ Read(src/auth.ts) │ ┃ src (not changed this turn) 1 ⎿ 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 │ │ › /sitrep-pane │ ⎿ sitrep: sitrep: opened the status pane (experimental; /sitrep-pa │ │ ⟨Claude Code's own drawing⟩ tool 9 · last Bash cat .env ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ tool 9 · last Bash cat .env
Pane · sitrep
Changes · uncommitted src/auth.ts +11 −3 src (not changed this turn) 1 file
README

sitrep

A Claude Code mod that makes long replies easy to scan. "Sitrep" is short for situation report.

繁體中文版:README.zh-TW.md

Long replies bury the part you need: did it work, and what does Claude want from you? sitrep puts a box under each long reply with the status, a one-line outcome, what you have to do, and the questions waiting on you, which you answer from the keyboard. Every word in the box is copied from the reply itself: a small model only picks line numbers, so the box cannot say anything the reply did not.

Labels and language

The mod's own labels (status, rows, pane titles) are English by default. Set language to zh-TW for Traditional Chinese, from the sitrep row in /config or from a shell:

echo '{"language": "zh-TW"}' | claude plugin configure sitrep@mango-mods --values-stdin

The text inside the box is always the reply's own text, so it follows the language of your conversation.

Core

  • Excerpt. When a main-conversation reply is long (800+ characters outside code blocks) or has 2+ headings, after the turn ends sitrep numbers the reply's lines and asks haiku (low effort, 20 s limit) for line numbers only: the outcome line, questions with their option lines, what you have to do, what Claude does next, up to 4 risk sentences counting risk-section summaries (risks, unverified items, limits, under any heading), and the sections that can be collapsed. The mod checks every number and builds the box from those lines. An outcome or a question that is out of range or points at the wrong kind of line rejects the whole answer; a bad option, recommendation, You do, Then I, risk or section number drops only that item. The system prompt is left alone.
  • Headings the mod recognizes override the model's numbers: the first line under a Result/Summary/## 結果 heading is the outcome, consecutive A./B. (or 選項 A:) lines in a Decisions/## 待你決定 section are a question's options (the line before them is the question; a later line saying "recommend"/建議 marks the pick), and a Changes/Checks/Risks section's summary is the model's pick when it lies in that section, otherwise the section's first line. Status, You do and Then I still come from the model.
  • The box keeps only the outcome line's first sentence (up to the first 。!?, or .!? followed by a space); the reply is unchanged. A lead-in ending in a colon (Steps:) or a table header is never the outcome or a section summary; the next line is used. A section whose summary repeats the outcome, a You do/Then I line, an option, a line of the decisions section shown under the questions, or another summary stays in the body; a risk line repeating any of them is dropped. You do/ Then I pointing at a heading are dropped; a question pointing at a heading shows the heading text without #.
  • While it waits, the reply shows … excerpting; a failure shows – excerpt failed: <reason> where the box would be. If a new turn starts before the answer arrives, the excerpt is dropped.
  • The box under the reply, with a dim excerpt tag in its title:
  • The title on the top border shows the status: ? Your call (questions waiting), > Your move (something for you to do by hand), ! Blocked, ~ In progress, ✓ Done, and the turn's duration on the right. A done or blocked reply keeps its color even with a You do line; only a reply that stopped halfway to wait for you is Your move. Only the two "waiting on you" states are yellow.
  • Then the outcome in bold, risk lines with a red Risk tag (wrapped in full, never cut), and You do lines in yellow.
  • Sections the model picks (for example Changes, Checks) leave the body and become one summary line each, under a bold blue label; ▸ puts a section back in its place in the body. When there are questions, a section whose heading mentions a decision (## Decisions, ## 待你決定) also leaves the body, so the questions are not written twice; its other lines (the pros and cons, why one is recommended) are shown in the box under the questions, with no ▸ to press.
  • Questions come next, one option per line, never cut short. Clicking an option only fills its letter into the prompt box (A; with several questions, the answers so far by question number, 1. A 2. B); nothing is sent. A question asked without listed choices shows alone (answer by typing). A table row the model picks is shown with its cells joined by · . Then I (what Claude does next) comes last, dim.
  • The outcome takes at most two lines and ends in … past that. Each ▸ section is one line, label and summary cut to the box width. A box estimated taller than 12 rows is split into sections after the outcome: Risks in red (risk sections and risk lines), Needs you in yellow (questions, You do), Details in blue (other sections, subagents, Then I), each under a divider joined to the border; an empty section is left out.
  • Once a newer reply has its own box, an older box folds to one line (▸ ✓ outcome 8s); ▸ draws it again.
  • Colors are Claude Code theme names (warning, error, success, inactive…), so they follow your /theme, light and daltonized included. The box is the terminal width minus 4, at most 88 columns.
  • The row above the prompt. While questions are unanswered it reads ? N open with the first open question's options. Focus the row (Ctrl+X, then Tab) and press an option's letter (a, b…); that fills the prompt box the same way. With no questions but something for you to do, it reads Your move: … (suggestions in a done reply do not count). It steps aside for a survey, stacks under other mods' rows (ctx-relay), and goes away once a newer reply has neither. While a turn runs and nothing waits on you, the same row is one dim line, tool N · last <tool> <argument> (for example tool 4 · last Bash npm test): main-conversation tool calls only, counted from 0 each turn. Elapsed time is left to Claude Code's own spinner line; tool rows are not hidden.

Glyphs: ? yellow = your call, > yellow = your move, ! red = blocked, ~ in progress, ✓ done, – excerpt failed.

Extras

  • A collapsed subagent report row (Message from @…) shows the report's first sentence; expanded, it drops the [Subagent hand-back] … framing written for the model.
  • A background task's notification row (subagent, background shell…) starts with its status: dim ✓ completed, red ! failed, dim – killed.
  • Background subagents dispatched in a turn are listed in that turn's box (⠋ Explore description running 42s, ticking every 250 ms) and switch to ✓ with their run time. For such a turn, the engine's "Waiting for N background agents" line is not drawn.
  • sitrep draws no subagent list of its own. Claude Code already lists running subagents below the status line, in both fullscreen and the default renderer; set subagentStatusLine to change what each row shows.
  • /sitrep-pane opens or closes a status pane (experimental): needs you (questions, answer with a letter), running (subagents and background jobs), tasks (the engine's task list), evidence (the latest checks as small tags), and changes (files this session edited, with +/−). While it is open, questions are answered there only: the row above the prompt is not drawn and each reply ends with a one-line outcome instead of the box.
  • An ASCII figure in a reply (a code block with no language or text, where at least 2 lines, and at least 30% of the non-blank lines, carry box-drawing characters, arrows, or plain +-- / |--) is drawn on a gray background under a dim figure label. A line with Chinese sentence punctuation or starting like a Markdown list item does not count, so prose that writes A → B stays a plain code block.
  • A ```dot block is drawn the same way, its label adding rough node and edge counts. It is not rendered as a picture, since Claude Code turns pictures off inside tmux.
  • Drawing only: the stored messages are unchanged.

Try it

git clone https://github.com/mangow314/mango-mods
claude --plugin-dir ./mango-mods/sitrep

Known limits

  • Each long reply costs one extra haiku request, sent through your own Claude Code account.
  • The excerpt only picks lines: an outcome the reply never states in one line cannot appear, and a decision not written as a question with option lines is not offered as buttons. An unanswered question from an earlier reply is not carried over unless the new reply repeats it. Which line the model calls the outcome, or "next", is its judgment and can be off.
  • The turn-closing line carries no turn id, so hiding the "Waiting for N background agents" line is matched to turn.complete by duration (±3 s); two turns with close durations may swap. The engine may skip that line on short turns, which is why the outcome bar is drawn inside the reply.
  • The box is matched to the reply by a hash of its text. When tool calls split a reply into several blocks, the box sits under the last one. A reply too short for an excerpt gets no box, so subagents it dispatched show only in Claude Code's own list below the status line.
  • ctrl+o does not show the original reply: an assistant row does not say whether it is drawn in the ctrl+o transcript, so the box is drawn there too. Use ▸ to put a collapsed section back.
  • The excerpt arrives a few seconds after the reply, and the collapsed sections leave the body at that moment, so the body shifts up once.
  • The box and the status pane record a subagent when agent.spawn returns an id; a workflow's remote agent has none and is not listed. A subagent whose turn.complete never arrives keeps spinning until the session ends.
  • In focus mode (/focus) the engine hides background-task notification rows, so their status glyph is not shown there.
  • Under a Team/Enterprise sign-in, Claude Code's built-in guard mod keeps classic.* events from user-installed mods, so the status pane has no source for background shells or the task list; its Running section says so in one line instead. Subagents are unaffected.

Development

claude plugin test ., npx -p typescript@5 tsc -p ..

Source 2 files
hooks/register.tsx 1484 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, Timer } from 'claude-code'
3
4import type { AgentNote, ChangeNote, Evidence, Excerpt, Facet, Item, Option, Summary, TaskNote, TurnNote } from '../types'
5
6// sitrep:
7// 1. 主對話回覆夠長時,回合結束後(turn.complete)把回覆切成編號行,請小模型($.model.complete)只回編號:
8//    哪行是結論、哪些是待決題目與選項、你要做的事、之後我做的事、哪幾段是可收合的細節。mod 檢查編號、用回覆原句組成結論框,
9//    模型寫不出回覆裡沒有的字;編號對不上、逾時、API 錯都在框的位置寫「摘錄失敗:原因」。不改系統提示。
10// 2. 畫回覆時(AssistantMessage)用正文雜湊找摘錄,正文下面畫一個圓角結論框:標題(狀態+耗時)疊在上框線,
11//    框裡是粗體結論、細節段落(從正文拿掉,一行摘要;展開時放回正文原位)、待你決定的題目(按選項把「題號. key」填進提示框,不送出)。
12//    AssistantMessage 沒有 isExpanded,分不出 ctrl+o 畫面,那裡一樣畫成結論框。
13// 3. 回合結束那列(TurnDuration,「Baked for 3s」)照引擎原樣畫;只有那一輪派了背景子代理時不畫(結論框裡已列子代理)。
14//    那列沒有輪次編號,用耗時對回 turn.complete。
15// 4. 子代理回報那列(UserMessage,收合時「Message from @…」)換成它回報的第一句,ctrl+o 照原樣展開。
16// 5. 還有沒答的題目時,prompt 上方(AbovePrompt)一行「? N 項等你決定」,聚焦後按選項字母選答(一樣只填提示框)。
17//    回合進行中、沒事等你時,同一列改成一行「第 N 個工具 · 最近 <工具> <參數>」(只算主對話,不隱藏工具列)。
18// 6. 背景工作結束的通知列開頭換成狀態符號(✓ 完成、! 失敗、– 中止);那一輪派出的背景子代理也列在結論框裡,跑完自動更新。
19// 7. 回覆裡的 ASCII 圖(含框線字元或箭頭的程式碼區塊)畫在灰底區塊、上方一行灰字「圖」,不被大量文字蓋過。
20// 8. 回覆裡的 ```dot 區塊照 7 畫原文,標籤附粗算的節點與邊數。
21
22const TAG = 'sitrep'
23
24// 畫面上的字:userConfig language 選 en(預設)或 zh-TW;回覆內容照對話語言,不在這裡
25const ZH = {
26  status: { '?': '等你決定', '>': '等你動手', '!': '卡住', '~': '進行中', '✓': '完成' } as Record<string, string>,
27  cmdPane: 'sitrep:開關狀態 pane(需要你、進行中、任務、證據、變更)',
28  registerFailed: (name: string, err: string) => `${TAG} 註冊 /${name} 失敗:${err}`,
29  logFailed: (what: string, err: string) => `${TAG} ${what}失敗:${err}`,
30  logSpawn: '記錄子代理啟動',
31  paneClosed: `${TAG}:已關閉狀態 pane(/sitrep-pane 可再打開)`,
32  paneOpened: `${TAG}:已打開狀態 pane(實驗中;再打一次 /sitrep-pane 關閉)`,
33  excerpting: '摘錄中',
34  openCount: (n: number) => `? ${n} 題待決`,
35  recommended: ' 建議',
36  recShort: ' 建議',
37  rowHint: '   · 聚焦後按字母,只填入輸入框',
38  yourMove: '等你動手:',
39  figure: '圖',
40  dotFigure: (nodes: number, edges: number) => `圖:${nodes} 個節點、${edges} 條邊(dot 原文)`,
41  excerptFailed: (reason: string) => `摘錄失敗:${reason}`,
42  excerptTag: '摘錄 ',
43  fullText: '  (ctrl+o 看全文)',
44  timedOut: (s: number) => `逾時或中止(${s}s)`,
45  mismatch: '回傳的編號對不上原文',
46  needsYou: (n: number) => `需要你 · ${n}`,
47  secRisk: '風險',
48  secNeed: '需要你',
49  secDetail: '細節',
50  running: '進行中',
51  subagent: (d: string) => `子代理 ${d}`,
52  background: (b: string) => `背景 ${b}`,
53  tasks: (done: number, all: number) => `任務 ${done}/${all}`,
54  evidence: '證據',
55  evidenceAge: (n: number) => `證據 · ${n} 輪前`,
56  moreProof: (n: number) => `…還有 ${n} 行,點結論框的 › 驗證看全部`,
57  changes: '變更 · 未 commit',
58  notThisTime: '(不是這次改的)',
59  files: (n: number) => `${n} 檔`,
60  guarded: '背景 shell、任務清單:Team/Enterprise 帳號看不到',
61  nothing: '目前沒有需要你或進行中的事',
62  more: (n: number) => `…還有 ${n} 項`,
63  stateRunning: '執行中',
64  stateDone: '完成',
65  stateFailed: '失敗',
66  stateKilled: '已中止',
67  backInReply: '(已放回正文)',
68  youDo: '你要做  ',
69  riskTag: '風險  ',
70  thenI: '之後我  ',
71  notFilled: (why: string | undefined) => `${TAG}:沒填進提示框(${why ?? '原因不明'})`,
72  progress: (n: number, last: string) => `第 ${n} 個工具 · 最近 ${last}`,
73}
74type Texts = typeof ZH
75const EN: Texts = {
76  status: { '?': 'Your call', '>': 'Your move', '!': 'Blocked', '~': 'In progress', '✓': 'Done' },
77  cmdPane: 'sitrep: toggle the status pane (needs you, running, tasks, evidence, changes)',
78  registerFailed: (name, err) => `${TAG} could not register /${name}: ${err}`,
79  logFailed: (what, err) => `${TAG} ${what} failed: ${err}`,
80  logSpawn: 'recording a subagent start',
81  paneClosed: `${TAG}: closed the status pane (/sitrep-pane opens it again)`,
82  paneOpened: `${TAG}: opened the status pane (experimental; /sitrep-pane again closes it)`,
83  excerpting: 'excerpting',
84  openCount: n => `? ${n} open`,
85  recommended: ' recommended',
86  recShort: ' rec',
87  rowHint: '   · focus, then press a letter; only fills the prompt',
88  yourMove: 'Your move: ',
89  figure: 'figure',
90  dotFigure: (nodes, edges) => `figure: ${nodes} nodes, ${edges} edges (dot source)`,
91  excerptFailed: reason => `excerpt failed: ${reason}`,
92  excerptTag: 'excerpt ',
93  fullText: '  (ctrl+o for the full text)',
94  timedOut: s => `timed out or aborted (${s}s)`,
95  mismatch: 'line numbers did not match the reply',
96  needsYou: n => `Needs you · ${n}`,
97  secRisk: 'Risks',
98  secNeed: 'Needs you',
99  secDetail: 'Details',
100  running: 'Running',
101  subagent: d => `subagent ${d}`,
102  background: b => `background ${b}`,
103  tasks: (done, all) => `Tasks ${done}/${all}`,
104  evidence: 'Evidence',
105  evidenceAge: n => `Evidence · ${n} turn${n === 1 ? '' : 's'} ago`,
106  moreProof: n => `…${n} more lines; open the checks row in the box to see all`,
107  changes: 'Changes · uncommitted',
108  notThisTime: ' (not changed this turn)',
109  files: n => `${n} file${n === 1 ? '' : 's'}`,
110  guarded: 'Background shells and the task list: not shown under a Team/Enterprise sign-in',
111  nothing: 'Nothing needs you and nothing is running',
112  more: n => `…${n} more`,
113  stateRunning: 'running',
114  stateDone: 'done',
115  stateFailed: 'failed',
116  stateKilled: 'killed',
117  backInReply: ' (back in the reply)',
118  youDo: 'You do  ',
119  riskTag: 'Risk  ',
120  thenI: 'Then I  ',
121  notFilled: why => `${TAG}: could not fill the prompt (${why ?? 'unknown reason'})`,
122  progress: (n, last) => `tool ${n} · last ${last}`,
123}
124let T: Texts = EN
125const KEEP_TURNS = 50
126const KEEP_AGENTS = 50
127const PANE = 'sitrep'
128// 子代理在跑時的重畫計時器(模組層,同一時間只開一個):每 250ms 一幀,轉圈字形與已跑時間跟著走
129let tick: Timer | null = null
130let frame = 0
131const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
132const spin = () => SPIN[frame % SPIN.length]
133// 顏色只給「需要你」:黃=等你決定;紅=卡住;其餘灰階(第三輪設計稿的安靜版)。
134// 一律用引擎的主題色名稱,跟著使用者的 Claude Code 主題(含淺色、daltonized)走;深色主題預設值:
135// warning 琥珀、error 粉紅、success 綠(daltonized 是藍)、inactive 153 灰、subtle 80 灰、text 白
136const YELLOW = 'warning'
137const RED = 'error'
138const GREEN = 'success'
139const DIM = 'inactive'
140const SOFT = 'inactive'
141// ASCII 圖的灰底:用你的訊息底色(深色 55 灰、淺色 240 灰),淺色主題下字才看得到
142const FIG_BG = 'userMessageBackground'
143const BRIGHT = 'text'
144// pane(設計稿駕駛艙版):進行中的藍、需要你那塊的底、證據小標籤的框線
145const BLUE = 'suggestion'
146const NEED_BG = 'userMessageBackground'
147const LINE = 'subtle'
148// 每輪結論框(學 your-turn 的圓角框,標題嵌在上框線):框線是暗一階的狀態色(borderDimColor),標題用亮的;只有「等你決定」是黃
149const FRAMES: Record<string, { title: string }> = {
150  '?': { title: YELLOW },
151  '>': { title: YELLOW },
152  '!': { title: RED },
153  '~': { title: BLUE },
154  '✓': { title: GREEN },
155}
156const DONE_FRAME = { title: GREEN }
157const BOX_MAX = 88
158// TurnDuration 的耗時和 turn.complete 的不一定分毫不差(實測 13s 對得上、42s 對不上):取差距最小、在這範圍內的那筆
159const MATCH_MS = 3000
160
161// 摘錄:回覆(不算程式碼區塊)至少這麼長,或有這麼多個標題才摘(分段的短完工報告也要框;實測 310 則回覆裡 16% 是這種);
162// 挑編號用的模型與時限
163const EXCERPT_MIN = 800
164const EXCERPT_HEADINGS = 2
165const EXCERPT_MODEL = 'haiku'
166const EXCERPT_TIMEOUT_MS = 20_000
167const KEEP_EXCERPTS = 50
168// 主對話每開始一輪 +1:摘錄回來時已經換輪就作廢,待決題目不能蓋掉新一輪的
169let turnGen = 0
170
171// 給挑編號模型的規則:只回編號,文字一律由 mod 從回覆原句取
172const PICK_RULES = [
173  'You index an assistant reply for a terminal UI. The reply is given as numbered lines "[n] text". Return ONLY one line of JSON, no prose:',
174  '{"status":"done|blocked|partial","outcome":n,"decisions":[{"question":n,"options":[n,n],"recommended":n}],"todo":[n],"next":[n],"risks":[n],"sections":[{"heading":n,"summary":n}]}',
175  '- Every value except status is a line number from the reply. Never write text of your own.',
176  '- outcome: the one line that best states the result or answer.',
177  '- status: blocked when the work cannot go on until the user answers a question, approves, or does a step only they can do, or when an obstacle stops it; partial when only part of the asked work is done; otherwise done. Optional suggestions or follow-ups do not make a reply blocked.',
178  '- decisions: only questions the reply explicitly asks the user. question is the line that asks (never a heading line); options are the lines of each listed choice (2 or more, never the question line itself), or [] when the reply lists no choices; recommended is the option line the reply recommends, or omit it.',
179  '- todo: lines telling the user to do something the work needs: run, test, push, approve, reply, paste output. Not suggestions, recommendations or optional extras, not explanations, not information about the state of things.',
180  '- next: lines where the assistant states an action it will take itself, including conditional ones ("after you pick, I will…"). A line asking the user to reply or paste something is todo, not next. A recommendation ("I recommend A") is neither.',
181  '- risks: lines pointing out a risk, something not verified, a limitation, or what could go wrong, under any heading or none. Most important first; never the outcome line. At most 4 lines in total, counting the summary you give for a section whose heading is about risks.',
182  '- todo, next, risks and section summaries never point at a heading line, a table header, or a line ending in ":" that only introduces what follows. Use [] when there are none.',
183  '- sections: for each heading line ("#" lines) whose section holds details the user can expand later (changes, verification, risks, evidence), the heading line and the one line inside that section that best summarizes it. Skip the section holding the main result.',
184].join('\n')
185
186const answersAtom = atom({ plugin: 'sitrep', key: 'answers' } as const, {} as Record<string, Record<number, string>>)
187const openAtom = atom({ plugin: 'sitrep', key: 'open' } as const, {} as Record<string, boolean>)
188const turnsAtom = atom({ plugin: 'sitrep', key: 'turns' } as const, [] as TurnNote[])
189const agentsAtom = atom({ plugin: 'sitrep', key: 'agents' } as const, [] as AgentNote[])
190const excerptsAtom = atom({ plugin: 'sitrep', key: 'excerpts' } as const, {} as Record<string, Excerpt>)
191const lastAtom = atom({ plugin: 'sitrep', key: 'last' } as const, null as { id: string; summary: Summary } | null)
192const evidenceAtom = atom({ plugin: 'sitrep', key: 'evidence' } as const, null as Evidence | null)
193const backgroundAtom = atom({ plugin: 'sitrep', key: 'background' } as const, [] as string[])
194const tasksAtom = atom({ plugin: 'sitrep', key: 'tasks' } as const, [] as TaskNote[])
195// classic.* 收不收得到:Team/Enterprise 登入時內建守門 mod(sec-default)讓 classic.* 跳過使用者裝的 mod,
196// 背景 shell 與任務清單就沒有來源。主對話正常結束一定先跑 classic.Stop 才有 turn.complete,沒看到就當成收不到
197const classicAtom = atom({ plugin: 'sitrep', key: 'classic' } as const, 'unknown' as 'unknown' | 'seen' | 'guarded')
198const changesAtom = atom({ plugin: 'sitrep', key: 'changes' } as const, [] as ChangeNote[])
199const touchedAtom = atom({ plugin: 'sitrep', key: 'touched' } as const, [] as string[])
200const paneOpenAtom = atom({ plugin: 'sitrep', key: 'paneOpen' } as const, false)
201const pendingAtom = atom({ plugin: 'sitrep', key: 'pending' } as const, null as { id: string; decisions: Item[]; todo: string[] } | null)
202// 這一輪主對話呼叫了幾個工具、最近一個是什麼(turn.start 歸零):回合進行中 prompt 上方那列用
203const progressAtom = atom({ plugin: 'sitrep', key: 'progress' } as const, { count: 0, last: '' })
204
205export const register: Register = (on, options) => {
206  T = options.language === 'zh-TW' ? ZH : EN
207  on('turn.start', async ($, e, next) => {
208    turnGen++
209    await update($, progressAtom, () => ({ count: 0, last: '' }))
210    return next(e)
211  })
212
213  on('session.start', async ($, e, next) => {
214    const result = await next(e)
215    // 名稱衝突會丟例外,包住免得中斷 hook
216    try {
217      await $.command.register({ name: 'sitrep-pane', description: T.cmdPane })
218    } catch (err) {
219      $.ui.log(T.registerFailed('sitrep-pane', String(err)))
220    }
221    return result
222  })
223
224  // 子代理一啟動就記下:開始時間是真的。主對話派的等這一輪結束由 trackAgents 補上結論框;
225  // 子代理再派的、workflow 的不屬於任何結論框(card ''),只在狀態 pane 列出。寫 state 失敗不能擋住子代理啟動
226  on('agent.spawn', async ($, e, next) => {
227    const started = await next(e)
228    if (started.deny !== undefined || !started.agentId) return started
229    const id = started.agentId
230    try {
231      const at = await $.clock.now()
232      const nested = e.parentAgentId !== undefined || e.workflow !== undefined
233      const note: AgentNote = { id, type: e.subagentType, description: e.description, status: 'running', startedAt: at, ...(nested ? { card: '' } : {}) }
234      await update($, agentsAtom, list => [...list.filter(a => a.id !== id), note].slice(-KEEP_AGENTS))
235      startTick($)
236    } catch (err) {
237      $.ui.log(T.logFailed(T.logSpawn, String(err)))
238    }
239    return started
240  }).catch(($, e, next) => next(e)) // 這個 hook 本身出錯也照常啟動子代理(next 已呼叫過就回放那次結果,不會啟動兩次)
241
242  // pane 只能手動開關(2026-10-08 使用者:pane 視覺另案設計,平常只用安靜版,不再自動開)
243  on('command.run', { command: 'sitrep-pane' }, async $ => {
244    if ((await $.ui.panes()).some(p => p.id === PANE)) {
245      await $.ui.close({ id: PANE })
246      return { text: T.paneClosed }
247    }
248    await openPane($)
249    return { text: T.paneOpened }
250  })
251
252  // pane 關了:結論框與 prompt 上方那列回來
253  on('ui.close', async ($, e, next) => {
254    if (e.id !== PANE) return next(e)
255    await update($, paneOpenAtom, () => false)
256    return next(e)
257  })
258
259  // 記下這個 session 用工具改過的檔:pane 的「變更」段只逐檔列這些,其餘當成「不是這次改的」
260  on('tool.call', async ($, e, next) => {
261    if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(e.tool)) {
262      const input = e as unknown as { file_path?: unknown; notebook_path?: unknown }
263      const path = input.file_path ?? input.notebook_path
264      if (typeof path === 'string') await update($, touchedAtom, list => (list.includes(path) ? list : [...list, path].slice(-200)))
265    }
266    // 回合進行中那列只算主對話:子代理引擎已在 status line 下方列出;workflow、引擎 fork 的 agentId 也不一定是子代理
267    if (e.agentId === undefined) {
268      await update($, progressAtom, p => ({ count: p.count + 1, last: toolLabel(e as unknown as Record<string, unknown>) }))
269      $.ui.invalidate('ui.render')
270    }
271    return next(e)
272  })
273
274  // 主對話停下時引擎回報的背景工作(背景 shell、monitor、workflow;子代理另外從 $.agent.list() 拿)
275  on('classic.Stop', async ($, e, next) => {
276    const result = await next(e)
277    await update($, classicAtom, () => 'seen')
278    if (result.block !== undefined) return result
279    const work = (e.background_tasks ?? []).filter(t => t.type !== 'subagent').map(t => `${t.type} ${t.command ?? t.description}`)
280    await update($, backgroundAtom, () => work)
281    return result
282  })
283
284  // 別的 hook 擋下(block)的建立/完成沒有生效,不記
285  on('classic.TaskCreated', async ($, e, next) => {
286    const result = await next(e)
287    if (result.block !== undefined) return result
288    await update($, tasksAtom, list => [...list.filter(t => t.id !== e.task_id), { id: e.task_id, subject: e.task_subject, done: false }].slice(-30))
289    return result
290  })
291
292  on('classic.TaskCompleted', async ($, e, next) => {
293    const result = await next(e)
294    if (result.block !== undefined) return result
295    await update($, tasksAtom, list => list.map(t => (t.id === e.task_id ? { ...t, done: true } : t)))
296    return result
297  })
298
299  on('turn.complete', async ($, e, next) => {
300    const result = await next(e)
301    if (e.agentId) {
302      // 背景子代理跑完:結論框裡它那一行改成完成(或中止)+耗時
303      const id = e.agentId
304      await update($, agentsAtom, list => list.map(a => (a.id === id ? { ...a, status: e.isAborted ? 'killed' : 'completed', durationMs: e.durationMs } : a)))
305      return result
306    }
307    if (!e.isAborted) await update($, classicAtom, c => (c === 'unknown' ? 'guarded' : c))
308    const lines = numberLines(e.answer)
309    const isLong = lines.join('').length >= EXCERPT_MIN || lines.filter(l => HEADING_RE.test(l)).length >= EXCERPT_HEADINGS
310    const id = isLong ? keyOf(e.answer) : undefined
311    await trackAgents($, id)
312    // 有子代理在跑時每 250ms 重畫一次:轉圈字形和已跑時間證明它還活著(使用者 2026-10-08 選轉圈);都跑完就停
313    if ((await read($, agentsAtom)).some(a => !(a.status in TASK_MARKS))) startTick($)
314    const note: TurnNote = id ? { id, durationMs: e.durationMs } : { durationMs: e.durationMs }
315    await update($, turnsAtom, list => [...list, note].slice(-KEEP_TURNS))
316    if (id) {
317      // 不在這裡等模型:回合結束不能被摘錄拖住,回來後再補畫
318      await update($, excerptsAtom, all => keepLast({ ...all, [id]: { state: 'pending' } }))
319      const gen = turnGen
320      $.clock.after(0, () => void excerpt($, id, e.answer, lines, gen))
321    }
322    // pane 的「變更」段:這一輪結束時還沒 commit 的改動(git diff --numstat,路徑換成絕對路徑好跟 touched 比);不在 git repo 就清空
323    const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 5000 }).catch(() => null)
324    const stat = top?.exitCode === 0 ? await $.process.run(['git', 'diff', 'HEAD', '--numstat'], { timeoutMs: 5000 }).catch(() => null) : null
325    const root = top?.stdout.trim() ?? ''
326    await update($, changesAtom, () => (stat?.exitCode === 0 ? parseNumstat(stat.stdout, root) : []))
327    return result
328  })
329
330  // 你自己送出訊息=已回應上一輪的題目或待辦:那列馬上消失,不等這一輪結束(使用者實機:核准後「等你動手」一直掛著)
331  on('prompt.submit', async ($, e, next) => {
332    const result = await next(e)
333    // 你打字(composer)、手機遙控(bridge),或其他 mod 代你送出(asUser,例如 ctx-relay 的接續鈕)才算;背景通知、別的 session 傳來的不算
334    const o = e.origin
335    if (o.kind === 'composer' || o.kind === 'bridge' || (o.kind === 'plugin' && o.asUser)) await update($, pendingAtom, () => null)
336    return result
337  })
338
339  // prompt 上方一行:有沒答的題目時「? N 題待決」+第一題的選項(題號代替題幹,題目本身在結論框裡),聚焦這列後按字母選答;
340  // 沒題目但有要你親手做的事時「等你動手:…」。熱鍵只在 band/pane 有焦點時有效,所以選項留在這裡(結論框的按鈕按不到鍵盤)
341  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
342    if (e.props.hasSurvey) return next(e)
343    const pending = await read($, pendingAtom)
344    const answers = pending ? (await read($, answersAtom))[pending.id] ?? {} : {}
345    const open = pending ? pending.decisions.map((d, n) => ({ d, n })).filter(({ n }) => answers[n] === undefined) : []
346    const first = open[0]
347    const todo = pending?.todo[0]
348    // pane 開著時題目在 pane 裡選:這列不畫,alt+n(ctrl+x tab)才會直接跳到 pane
349    const paneOpen = await read($, paneOpenAtom)
350    const hasAsk = !!pending && (!!first || todo !== undefined) && !paneOpen
351    if (!hasAsk) {
352      // 回合進行中:一行「第 N 個工具 · 最近 <工具> <參數>」,字都是工具呼叫的原文。經過時間引擎的轉圈列已有,不重複
353      const progress = e.props.isWorking && !paneOpen ? await read($, progressAtom) : null
354      if (!progress || progress.count === 0) return next(e)
355      const below = await next(e)
356      const { Box, Text } = $.ui.resolve(e)
357      return (
358        <Box flexDirection="column">
359          {below}
360          <Text key="above-progress" color={DIM} wrap="truncate-end">{T.progress(progress.count, progress.last)}</Text>
361        </Box>
362      )
363    }
364    // band 只有一個:先讓排在下面的 mod 畫(例如 ctx-relay 的交接列),自己這列疊在它下面
365    const below = await next(e)
366    const { Box, Button, Text } = $.ui.resolve(e)
367    let line: RenderElement | null = null
368    if (pending && first) {
369      const { d, n } = first
370      const total = pending.decisions.length
371      // hotkey 只收一個小寫字母;數字不給:空的提示框裡按數字會直接按到 band 的按鈕,也會撞 ctx-relay 的 "1"
372      line = (
373        <Box key="above-row" flexDirection="row">
374          {/* 計數和選項不縮:英文較長時會被擠成兩行(實機),只讓最後的說明截斷 */}
375          <Box flexShrink={0}>
376            <Text color={YELLOW} bold>{T.openCount(open.length)}</Text>
377            <Text color={BRIGHT}>{total > 1 ? `   ${n + 1}.` : '  '}</Text>
378          </Box>
379          {(d.options ?? []).map(o => {
380            const hotkey = /^[a-z]$/i.test(o.key) ? o.key.toLowerCase() : undefined
381            return (
382              <Box key={`above-opt-${o.key}`} flexDirection="row" marginLeft={2} flexShrink={0}>
383                <Button key={`above-pick-${n}-${o.key}`} plain label={clip(hotkey ? o.label : `${o.key} ${o.label}`, 24)} {...(hotkey ? { hotkey } : {})} onPress={() => pick($, pending.id, n, o.key, total)} />
384                {d.recommended === o.key ? <Text color={YELLOW}>{T.recShort}</Text> : null}
385              </Box>
386            )
387          })}
388          <Text color={DIM} wrap="truncate-end">{T.rowHint}</Text>
389        </Box>
390      )
391    } else {
392      line = (
393        <Text key="above-todo" wrap="truncate-end">
394          <Text color={YELLOW} bold>{T.yourMove}</Text>
395          <Text>{todo}</Text>
396        </Text>
397      )
398    }
399    return (
400      <Box flexDirection="column">
401        {below}
402        {line}
403      </Box>
404    )
405  })
406
407  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
408    if (e.requestId !== PANE) return next(e)
409    return drawPane($, e, e.props.bodyColumns)
410  })
411
412  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
413    // 正文交給引擎畫;ASCII 圖切出來畫在灰底區塊,前後段各自交回引擎(只有第一段帶回覆開頭的圓點)
414    const draw = async (text: string) => {
415      const parts = splitFigures(text)
416      const [only] = parts
417      if (parts.length === 1 && only?.kind === 'text') return next({ ...e, props: { ...e.props, text } })
418      const { Box, Text } = $.ui.resolve(e)
419      const out: RenderElement[] = []
420      for (const [i, p] of parts.entries()) {
421        if (p.kind === 'text') {
422          // 圓點和它後面的縮排是引擎畫在第一段裡的;後面幾段沒有,自己補兩欄對齊(實機 2026-10-08)
423          const indent = e.props.isFirstOfReply && i > 0 ? 2 : 0
424          out.push(<Box key={`seg-${i}`} marginLeft={indent}>{await next({ ...e, props: { ...e.props, text: p.text, isFirstOfReply: e.props.isFirstOfReply && i === 0 } })}</Box>)
425          continue
426        }
427        // dot 區塊跟 ASCII 圖一樣畫原文,標籤附粗算的節點與邊數(不畫成圖片:Claude Code 在 tmux 裡關掉圖片,使用者 2026-10-08 選不做)
428        let label = T.figure
429        if (p.kind === 'dot') {
430          const c = countDot(p.text)
431          label = T.dotFigure(c.nodes, c.edges)
432        }
433        out.push(
434          <Box key={`fig-${i}`} flexDirection="column" marginLeft={2} marginY={1} alignSelf="flex-start">
435            <Text color={DIM}>{label}</Text>
436            <Box flexDirection="column" backgroundColor={FIG_BG} paddingX={1}>
437              {p.text.split('\n').map((l, j) => <Text key={`l-${j}`} color={BRIGHT} wrap="truncate-end">{l === '' ? ' ' : l}</Text>)}
438            </Box>
439          </Box>,
440        )
441      }
442      return <Box flexDirection="column">{out}</Box>
443    }
444    const id = keyOf(e.props.text)
445    const ex = (await read($, excerptsAtom))[id]
446    if (ex === undefined) return draw(e.props.text)
447    if (ex.state !== 'ready') {
448      const { Box, Text } = $.ui.resolve(e)
449      return (
450        <Box flexDirection="column">
451          {await draw(e.props.text)}
452          <Text key="excerpt-note" color={DIM}>{ex.state === 'pending' ? `  … ${T.excerpting}` : `  – ${T.excerptFailed(ex.reason)}`}</Text>
453        </Box>
454      )
455    }
456    const found = { id, summary: ex.summary, rest: e.props.text }
457    // pane 開著=駕駛艙模式:不畫安靜版的結論框,正文完整照畫,底下只留一行「✓ 結論  耗時」;需要你、證據、變更都在 pane
458    if (await read($, paneOpenAtom)) {
459      const { Box, Text } = $.ui.resolve(e)
460      const glyph = glyphOf(found.summary)
461      const frame = FRAMES[glyph] ?? DONE_FRAME
462      const turn = (await read($, turnsAtom)).findLast(t => t.id === found.id)
463      return (
464        <Box flexDirection="column">
465          {await draw(found.rest)}
466          <Box key="lens-line" flexDirection="row" marginTop={1}>
467            <Text color={frame.title} bold>{`${glyph} `}</Text>
468            <Text color={BRIGHT}>{found.summary.outcome}</Text>
469            {turn ? <Text color={DIM}>{`  ${duration(turn.durationMs)}`}</Text> : null}
470          </Box>
471        </Box>
472      )
473    }
474    const facets = found.summary.facets
475    const open = await read($, openAtom)
476    const asked = decisionHeading(found.summary, found.rest)
477    // 決定段排在最後一起切:永遠從正文拿掉,內文攤在框裡
478    const cut = cutSections(found.rest, asked === undefined ? facets : [...facets, { label: '', summary: '', heading: asked }], i => i < facets.length && open[`${found.id}:${i}`] === true)
479    const { shown } = cut
480    const sections = cut.sections.slice(0, facets.length)
481    const notes = asked === undefined ? [] : decisionNotes(cut.sections[facets.length] ?? '', found.summary.items)
482    const body = await draw(shown)
483    const { Box, Text } = $.ui.resolve(e)
484    // 結論框畫在帶區塊的那一段下面,不靠 TurnDuration:短回合、子代理回報觸發的回合,引擎不一定畫那列(實測 3s 那輪沒有)
485    const glyph = glyphOf(found.summary)
486    const frame = FRAMES[glyph] ?? DONE_FRAME
487    const turns = await read($, turnsAtom)
488    const turn = turns.findLast(t => t.id === found.id)
489    // 舊回合(之後還有別張結論框)收成一行,點 ▸ 才畫完整框:同一畫面不堆好幾個框(實機 s5 三個框)。
490    // 還沒進 turns 的(串流中、剛收尾)一律當最新,免得先畫一行再展開
491    const at = turns.findIndex(t => t.id === found.id)
492    const isOld = at >= 0 && turns.slice(at + 1).some(t => t.id !== undefined && t.id !== found.id)
493    const boxKey = `${found.id}:box`
494    const toggleBox = () => update($, openAtom, o => ({ ...o, [boxKey]: !o[boxKey] }))
495    const { Button } = $.ui.resolve(e)
496    if (isOld && open[boxKey] !== true) {
497      return (
498        <Box flexDirection="column">
499          {body}
500          <Box key="lens-line" flexDirection="row" marginTop={1}>
501            <Button key="box-open" plain label="▸" onPress={toggleBox} />
502            <Text color={frame.title} bold>{` ${glyph} `}</Text>
503            <Text color={SOFT}>{found.summary.outcome}</Text>
504            {turn ? <Text color={DIM}>{`  ${duration(turn.durationMs)}`}</Text> : null}
505          </Box>
506        </Box>
507      )
508    }
509    // 框寬固定(不跟內容跳,實機 36~81 欄):終端寬減 4,最寬 88
510    const width = Math.min((e.viewport?.columns ?? 92) - 4, BOX_MAX)
511    // 選項標籤可用的欄數:框線 2、內距 2、縮排 2、選項鍵 2、空一格
512    // 長版(現況列數估算 > 12 且除了結論還有風險/需要你/細節任一區)才分段,順序:結論→風險→需要你→細節;短版維持一整串
513    const risky = (f: Facet) => RISK_RE.test(f.heading ?? f.label)
514    const agents = await agentRows($, e, found.id)
515    const layout = sectionLayout(found.summary, notes, agents.length, width)
516    const items = await itemRows($, e, found.id, found.summary.items, width - 9, notes, layout !== null)
517    // 風險句:短版每行前面紅色「風險」標籤;分段版已在「風險」隔線底下,只留一個點
518    // 風險句沒有段落可以按 ▸ 放回正文,所以整句折行畫完、不截斷(使用者實機:截成 … 就看不到全文)
519    const riskRows = (tagged: boolean) => (found.summary.risks ?? []).flatMap((r, i) => {
520      const lead = tagged ? cols(T.riskTag) : 2
521      return wrapCols(r, width - 4 - lead).map((l, j) => (
522        <Text key={`risk-${i}-${j}`}>
523          {j > 0 ? ' '.repeat(lead) : tagged ? <Text color={RED} bold>{T.riskTag}</Text> : <Text color={DIM}>{'· '}</Text>}
524          <Text color={BRIGHT}>{l}</Text>
525        </Text>
526      ))
527    })
528    const sep = (key: string, label: string) => {
529      const line = boxSep(label, width)
530      return (
531        <Box key={`sep-${key}`} flexDirection="row" marginX={-2}>
532          <Text color={frame.title} dimColor>{line.head}</Text>
533          <Text color={label === T.secRisk ? RED : label === T.secDetail ? BLUE : YELLOW} bold>{label}</Text>
534          <Text color={frame.title} dimColor>{line.tail}</Text>
535        </Box>
536      )
537    }
538    const rows = layout === null
539      ? [
540        <Text key="outcome" color={BRIGHT} bold>{clip(found.summary.outcome, 2 * (width - 4))}</Text>,
541        ...riskRows(true),
542        ...items.todo,
543        ...facetRows($, e, found.id, facets, sections, open, width - 4),
544        ...agents,
545        ...items.questions,
546        ...items.later,
547      ]
548      : [
549        <Text key="outcome" color={BRIGHT} bold>{clip(found.summary.outcome, 2 * (width - 4))}</Text>,
550        ...(layout.risk ? [sep('risk', T.secRisk), ...facetRows($, e, found.id, facets, sections, open, width - 4, risky), ...riskRows(false)] : []),
551        ...(layout.need ? [sep('need', T.secNeed), ...items.questions, ...items.todo] : []),
552        ...(layout.detail ? [sep('detail', T.secDetail), ...facetRows($, e, found.id, facets, sections, open, width - 4, f => !risky(f)), ...agents, ...items.later] : []),
553      ]
554    // 標題疊在上框線(2026-10-09 使用者要再試):框自己的子元素會被框線蓋掉(your-turn 2026-10-05 實測),
555    // 所以標題是框的「後一個兄弟」、absolute 疊上去。舊紀錄:框頂捲出畫面時標題曾疊到內容上(實機 opus/s2:1),這次重看
556    return (
557      <Box flexDirection="column">
558        {body}
559        <Box key="lens-wrap" flexDirection="column" marginTop={1} width={width}>
560          <Box key="lens" borderStyle="round" borderColor={frame.title} borderDimColor paddingX={1} flexDirection="column">
561            {rows}
562          </Box>
563          <Box key="title" position="absolute" top={0} left={2} flexDirection="row">
564            {isOld ? <Button key="box-close" plain label="▾" onPress={toggleBox} /> : null}
565            <Text color={frame.title} bold>{` ${glyph} ${T.status[glyph] ?? T.status['✓']} `}</Text>
566            <Text color={DIM}>{T.excerptTag}</Text>
567          </Box>
568          {turn ? <Box key="time" position="absolute" top={0} right={2}><Text color={DIM}>{` ${duration(turn.durationMs)} `}</Text></Box> : null}
569        </Box>
570      </Box>
571    )
572  })
573
574  // 這一輪派了背景子代理:引擎這列會寫「Waiting for N background agents…」,結論框裡已經有子代理那一行,不畫
575  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
576    const note = matchTurn(await read($, turnsAtom), e.props.durationMs)
577    if (note?.id && (await read($, agentsAtom)).some(a => a.card === note.id)) return $.ui.resolve(e).Box({})
578    return next(e)
579  })
580
581  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
582    // 背景工作(子代理、背景 shell…)結束的通知列:沒有 from,開頭換成狀態符號,只有失敗用紅色
583    const task = e.props.task
584    if (task && !e.props.isExpanded) {
585      const mark = TASK_MARKS[task.status ?? ''] ?? { glyph: '·', color: DIM }
586      const { Text } = $.ui.resolve(e)
587      return (
588        <Text>
589          <Text color={mark.color} bold>{`${mark.glyph} `}</Text>
590          <Text>{clip(e.props.text.split('\n')[0] ?? '', 90)}</Text>
591          {task.durationMs !== undefined ? <Text color={DIM}>{`  ${duration(task.durationMs)}`}</Text> : null}
592        </Text>
593      )
594    }
595    const from = e.props.from
596    if (!from || e.props.origin.kind === 'composer') return next(e)
597    // 子代理回報開頭那段給模型看的框架說明([Subagent hand-back] … The report follows:)不畫,只留回報本文;存下來的訊息不動
598    const report = stripHandback(e.props.text)
599    if (e.props.isExpanded) return report === e.props.text ? next(e) : next({ ...e, props: { ...e.props, text: report } })
600    const first = firstSentence(report)
601    if (first === '') return next(e)
602    const { Text } = $.ui.resolve(e)
603    return (
604      <Text>
605        <Text color={DIM}>{'› '}</Text>
606        <Text color={SOFT}>{`${from.name}  `}</Text>
607        <Text>{clip(first, 90)}</Text>
608        <Text color={DIM}>{T.fullText}</Text>
609      </Text>
610    )
611  })
612}
613
614// 請小模型挑編號、組成結論框。換輪了就作廢(待決題目不能蓋掉新一輪的);失敗照實記下原因,框的位置會寫出來
615async function excerpt($: EngineInterface, id: string, answer: string, lines: string[], gen: number) {
616  const prompt = lines.map((l, i) => `[${i + 1}] ${l}`).join('\n')
617  const r = await $.model.complete({ model: EXCERPT_MODEL, system: PICK_RULES, prompt, effort: 'low', maxTokens: 600, timeoutMs: EXCERPT_TIMEOUT_MS })
618    .catch((err: unknown) => ({ isAnswered: false as const, reason: String(err) }))
619  let result: Excerpt
620  if (!r.isAnswered) result = { state: 'failed', reason: r.reason === 'aborted' ? T.timedOut(EXCERPT_TIMEOUT_MS / 1000) : r.reason }
621  else {
622    const summary = buildSummary(lines, r.text)
623    result = summary ? { state: 'ready', summary } : { state: 'failed', reason: T.mismatch }
624  }
625  if (gen !== turnGen) {
626    await update($, excerptsAtom, all => {
627      const { [id]: _, ...rest } = all
628      return rest
629    })
630    await update($, turnsAtom, list => list.map(t => (t.id === id ? { durationMs: t.durationMs } : t)))
631    $.ui.invalidate('ui.render')
632    return
633  }
634  await update($, excerptsAtom, all => keepLast({ ...all, [id]: result }))
635  if (result.state === 'failed') {
636    $.ui.invalidate('ui.render')
637    return
638  }
639  const summary = result.summary
640  // 新的結論框沒有題目=之前的題目已經處理過(例如使用者自己打字回答),那列跟著消失
641  // 完工回覆的「你要做」多半是建議(例如手動再測一次),不在 prompt 上方催;卡住、做到一半才提示
642  const todo = summary.status === 'done' ? [] : summary.items.filter(i => i.kind === 'user-next').map(i => i.text.replace(TODO_PREFIX_RE, ''))
643  await update($, pendingAtom, () => ({ id, decisions: decisionsOf(summary.items), todo }))
644  await update($, lastAtom, () => ({ id, summary }))
645  // 證據:沿用最近一輪有「驗證」段的結果,直到下一次驗證蓋過去(問題輪通常沒有驗證段,pane 卻正好開著)
646  const verify = summary.facets.map((f, i) => ({ f, i })).filter(({ f }) => /驗證|verif|check|test/i.test(f.label))
647  if (verify.length > 0) {
648    // 細節:回覆裡「驗證」那段的前幾行(跑過的指令與結果),pane 的證據段畫在小標籤下面
649    const { sections } = cutSections(answer, summary.facets, () => false)
650    const chips = verify.flatMap(({ f }) => f.summary.split(/\s*[·、,,]\s*/)).filter(c => c !== '')
651    const proof = verify.flatMap(({ i }) => (sections[i] ?? '').split('\n'))
652      .map(l => l.replace(/^\s*[-*]\s+|`/g, '').trim()).filter(l => l !== '' && !l.startsWith('```'))
653    await update($, evidenceAtom, () => ({ chips, proof, age: 0 }))
654  } else {
655    await update($, evidenceAtom, ev => (ev ? { ...ev, age: ev.age + 1 } : null))
656  }
657  $.ui.invalidate('ui.render')
658}
659
660// 開 pane;真的畫出來(isPlaced)才把題目從 prompt 上方那列移過去,太窄等著時題目留在原處
661async function openPane($: EngineInterface) {
662  // 寬度照設計稿(520px ≈ 52 欄);使用者自己拖過的寬度引擎會優先
663  const opened = await $.ui.open({ id: PANE, title: 'sitrep', columns: 52 })
664  await update($, paneOpenAtom, () => opened.isPlaced)
665}
666
667// pane 照設計稿「駕駛艙」版(spec R11):需要你、進行中、任務、證據、變更;空的段不畫,超過上限最後一列換成「…還有 N 項」
668async function drawPane($: EngineInterface, e: RenderEvent, width: number) {
669  const { Box, Button, Text } = $.ui.resolve(e)
670  const last = await read($, lastAtom)
671  const pending = await read($, pendingAtom)
672  const answers = pending ? (await read($, answersAtom))[pending.id] ?? {} : {}
673  const sections: { title: string; color: string; rows: RenderElement[]; max: number }[] = []
674
675  // 需要你:每題一塊黃底,選項照引擎問卷樣式畫成「a: 標籤」(第一題沒答的有字母熱鍵),選過的整題變灰、選中的打 ●
676  const need: RenderElement[] = []
677  let left = 0
678  if (pending) {
679    const total = pending.decisions.length
680    const firstOpen = pending.decisions.findIndex((_, n) => answers[n] === undefined)
681    pending.decisions.forEach((d, n) => {
682      const picked = answers[n]
683      if (picked === undefined) left++
684      need.push(
685        <Box key={`need-${n}`} flexDirection="column" backgroundColor={picked === undefined ? NEED_BG : undefined} paddingX={1}>
686          <Text color={picked === undefined ? BRIGHT : DIM}>{total > 1 ? `${n + 1}. ${d.text}` : d.text}</Text>
687          <Box flexDirection="row">
688            {(d.options ?? []).map(o => {
689              const isLetter = /^[a-z]$/i.test(o.key)
690              const letter = isLetter ? o.key.toLowerCase() : o.key
691              const hotkey = n === firstOpen && isLetter ? letter : undefined
692              return (
693                // 有熱鍵時引擎自己畫「a: 標籤」(字母用強調色);沒熱鍵的照同一個樣子把「a: 」寫進標籤
694                <Box key={`pane-opt-${n}-${o.key}`} flexDirection="row" marginRight={3}>
695                  {picked === o.key ? <Text color={BRIGHT} bold>{'● '}</Text> : null}
696                  <Button key={`pane-pick-${n}-${o.key}`} plain label={clip(hotkey ? o.label : `${letter}: ${o.label}`, 24)} {...(hotkey ? { hotkey } : {})} {...(picked !== undefined && picked !== o.key ? { dimColor: true } : {})} onPress={() => pick($, pending.id, n, o.key, total)} />
697                  {d.recommended === o.key && picked === undefined ? <Text color={YELLOW}>{T.recommended}</Text> : null}
698                </Box>
699              )
700            })}
701          </Box>
702        </Box>,
703      )
704    })
705  }
706  const userNext = (last?.summary.items ?? []).filter(x => x.kind === 'user-next')
707  for (const [i, item] of userNext.entries()) {
708    need.push(<Text key={`you-${i}`}><Text color={YELLOW} bold>{'> '}</Text>{clip(item.text, width - 2)}</Text>)
709  }
710  sections.push({ title: T.needsYou(left + userNext.length), color: YELLOW, rows: need, max: 8 })
711
712  // 進行中:轉圈字形+子代理/背景 描述,已跑時間靠右
713  const now = await $.clock.now().catch(() => null)
714  const runningRow = (key: string, label: string, since: number | undefined) => (
715    <Box key={key} flexDirection="row">
716      <Text color={BLUE}>{`${spin()} `}</Text>
717      <Text>{clip(label, width - 10)}</Text>
718      <Box flexGrow={1} />
719      <Text color={DIM}>{now !== null && since !== undefined ? duration(now - since) : ''}</Text>
720    </Box>
721  )
722  const agents = (await read($, agentsAtom)).filter(a => !(a.status in TASK_MARKS))
723  sections.push({
724    title: T.running,
725    color: DIM,
726    rows: [
727      ...agents.map(a => runningRow(`run-${a.id}`, T.subagent(a.description), a.startedAt)),
728      ...(await read($, backgroundAtom)).map((b, i) => runningRow(`bg-${i}`, T.background(b), undefined)),
729      ...((await read($, classicAtom)) === 'guarded' ? [<Text key="guarded" color={DIM}>{clip(T.guarded, width)}</Text>] : []),
730    ],
731    max: 5,
732  })
733
734  // 任務 完成數/總數:✓ 完成(灰)、▸ 下一項(亮)、○ 還沒做(灰)。
735  // 來源:引擎的 TaskCreated/TaskCompleted(摘錄只取回覆原句,沒有步驟清單)
736  const tasks = await read($, tasksAtom)
737  const current = tasks.findIndex(t => !t.done)
738  sections.push({
739    title: T.tasks(tasks.filter(t => t.done).length, tasks.length),
740    color: DIM,
741    rows: tasks.map((t, i) => (
742      <Text key={`task-${t.id}`}>
743        <Text color={t.done ? GREEN : i === current ? undefined : DIM}>{t.done ? '✓ ' : i === current ? '▸ ' : '○ '}</Text>
744        <Text color={i === current ? BRIGHT : DIM}>{clip(t.subject, width - 2)}</Text>
745      </Text>
746    )),
747    max: 7,
748  })
749
750  // 證據:最近一次「驗證」摘要拆成一顆顆有框的小標籤(51 pass · tsc ✓ → [✓ 51 pass] [✓ tsc]);不是這一輪的,標題註明幾輪前
751  const evidence = await read($, evidenceAtom)
752  const chips = evidence?.chips ?? []
753  const proof = evidence?.proof ?? []
754  sections.push({
755    title: evidence && evidence.age > 0 ? T.evidenceAge(evidence.age) : T.evidence,
756    color: DIM,
757    rows: chips.length === 0 ? [] : [
758      ...[
759        <Box key="chips" flexDirection="row" flexWrap="wrap">
760          {chips.map((c, i) => {
761            const chip = chipOf(c)
762            return (
763              <Box key={`chip-${i}`} borderStyle="round" borderColor={LINE} paddingX={1} marginRight={1}>
764                <Text><Text color={chip.color}>{chip.glyph}</Text>{` ${clip(chip.text, 24)}`}</Text>
765              </Box>
766            )
767          })}
768        </Box>,
769      ],
770      // 細節:回覆「驗證」段的前 4 行(指令與結果),超過的看結論框的 › 驗證
771      ...proof.slice(0, 4).map((l, i) => <Text key={`proof-${i}`} color={SOFT}>{clip(l, width)}</Text>),
772      ...(proof.length > 4 ? [<Text key="proof-more" color={DIM}>{T.moreProof(proof.length - 4)}</Text>] : []),
773    ],
774    max: 6,
775  })
776
777  // 變更 · 未 commit:這個 session 改過的檔逐檔列(+綠 −紅);其餘依最上層目錄收成一行「(不是這次改的)N 檔」
778  const changes = await read($, changesAtom)
779  const touched = new Set(await read($, touchedAtom))
780  const mine = changes.filter(c => touched.has(c.abs))
781  const others = new Map<string, number>()
782  for (const c of changes.filter(c => !touched.has(c.abs))) {
783    const top = c.path.includes('/') ? c.path.slice(0, c.path.indexOf('/')) : c.path
784    others.set(top, (others.get(top) ?? 0) + 1)
785  }
786  const pathWidth = Math.max(12, width - 14)
787  sections.push({
788    title: T.changes,
789    color: DIM,
790    rows: [
791      ...mine.map((c, i) => (
792        <Box key={`chg-${i}`} flexDirection="row">
793          <Box width={pathWidth}><Text color={SOFT}>{clip(c.path, pathWidth - 1)}</Text></Box>
794          <Box width={6}><Text color={GREEN}>{`+${c.add}`}</Text></Box>
795          <Text color={RED}>{`−${c.del}`}</Text>
796        </Box>
797      )),
798      ...[...others].map(([top, n]) => (
799        <Box key={`other-${top}`} flexDirection="row">
800          <Box width={pathWidth}><Text color={DIM}>{clip(`${top}${T.notThisTime}`, pathWidth - 1)}</Text></Box>
801          <Text color={DIM}>{T.files(n)}</Text>
802        </Box>
803      )),
804    ],
805    max: 6,
806  })
807
808  const shown = sections.filter(sec => sec.rows.length > 0)
809  if (shown.length === 0) return <Text color={DIM}>{T.nothing}</Text>
810  return (
811    <Box flexDirection="column">
812      {shown.map(sec => (
813        <Box key={`sec-${sec.title}`} flexDirection="column" marginBottom={1}>
814          <Text color={sec.color} bold={sec.color === YELLOW}>{sec.title}</Text>
815          {sec.rows.length > sec.max ? [...sec.rows.slice(0, sec.max - 1), <Text key="more" color={DIM}>{T.more(sec.rows.length - sec.max + 1)}</Text>] : sec.rows}
816        </Box>
817      ))}
818    </Box>
819  )
820}
821
822// 證據小標籤的符號:摘要裡已經有 ✓/✗/– 就拿來用;寫了「未」「沒」的當成還沒驗
823function chipOf(text: string): { glyph: string; color: string; text: string } {
824  const bare = text.replace(/[✓✔✗✘]/g, '').trim()
825  if (/[✗✘]|fail|失敗/i.test(text)) return { glyph: '✗', color: RED, text: bare }
826  if (/未|沒|–|待|\bnot\b|pending|skipped/i.test(text) && !/[✓✔]/.test(text)) return { glyph: '○', color: DIM, text: bare }
827  return { glyph: '✓', color: GREEN, text: bare }
828}
829
830// git diff HEAD --numstat:「加\t刪\t路徑」;二進位檔是「-\t-」,當成 0
831function parseNumstat(out: string, root: string): ChangeNote[] {
832  return out.split('\n').map(l => l.split('\t')).filter(f => f.length >= 3).map(([add, del, ...rest]) => {
833    const path = rest.join('\t')
834    return { path, abs: `${root}/${path}`, add: Number(add) || 0, del: Number(del) || 0 }
835  })
836}
837
838// 主對話派的子代理:第一次看到時記到這一輪的結論框下;已知的更新狀態,跑完的不再倒回
839async function trackAgents($: EngineInterface, card: string | undefined) {
840  const list = await $.agent.list().catch(() => [])
841  const now = await $.clock.now().catch(() => undefined)
842  await update($, agentsAtom, notes => {
843    const out = [...notes]
844    for (const a of list) {
845      if (a.parentId) continue
846      const at = out.findIndex(n => n.id === a.id)
847      const known = out[at]
848      if (known) {
849        // agent.spawn 先記下的還沒有結論框:補上這一輪的
850        out[at] = { ...known, ...(known.status in TASK_MARKS ? {} : { status: a.status }), ...(known.card === undefined ? { card: card ?? '' } : {}) }
851      } else {
852        // 第一次看到=這一輪派的(之前每輪都記過);子代理可能在這輪結束前就跑完(實機),所以不限還在跑的。
853        // 沒有結論框的回合記成 card '',只為了之後不再被算到別張框
854        out.push({ id: a.id, type: a.type, description: a.description, status: a.status, card: card ?? '', startedAt: now })
855      }
856    }
857    return out.slice(-KEEP_AGENTS)
858  })
859}
860
861// 有子代理在跑時每 250ms 重畫一次:轉圈字形和已跑時間證明它還活著(使用者 2026-10-08 選轉圈);都跑完就停
862function startTick($: EngineInterface) {
863  if (tick) return
864  tick = $.clock.every(250, () => {
865    void read($, agentsAtom).then(list => {
866      if (list.some(a => !(a.status in TASK_MARKS))) {
867        frame++
868        return $.ui.invalidate('ui.render')
869      }
870      tick?.cancel()
871      tick = null
872    })
873  })
874}
875
876// 結論框裡這一輪派出去的背景子代理:轉圈+執行中 已跑時間;跑完照通知列的符號(✓ 完成、! 失敗、– 中止)
877async function agentRows($: EngineInterface, e: RenderEvent, card: string) {
878  const agents = (await read($, agentsAtom)).filter(a => a.card === card)
879  const { Text } = $.ui.resolve(e)
880  const now = await $.clock.now().catch(() => null)
881  return agents.map(a => {
882    const mark = TASK_MARKS[a.status] ?? { glyph: spin(), color: BLUE }
883    const running = now !== null && a.startedAt !== undefined ? `${T.stateRunning} ${duration(now - a.startedAt)}` : T.stateRunning
884    const state = a.status === 'completed' ? (a.durationMs !== undefined ? duration(a.durationMs) : T.stateDone) : a.status === 'failed' ? T.stateFailed : a.status === 'killed' ? T.stateKilled : running
885    return (
886      <Text key={`agent-${a.id}`}>
887        <Text color={mark.color} bold>{`${mark.glyph} `}</Text>
888        <Text color={SOFT}>{`${a.type}  `}</Text>
889        <Text>{clip(a.description, 50)}</Text>
890        <Text color={DIM}>{`  ${state}`}</Text>
891      </Text>
892    )
893  })
894}
895
896// 背景工作結束的狀態:完成、中止灰;失敗紅(顏色只給需要你)
897const TASK_MARKS: Record<string, { glyph: string; color: string }> = {
898  completed: { glyph: '✓', color: DIM },
899  failed: { glyph: '!', color: RED },
900  killed: { glyph: '–', color: DIM },
901}
902
903// 耗時最接近的一筆;同樣接近時取較新的
904function matchTurn(turns: TurnNote[], durationMs: number): TurnNote | undefined {
905  let best: TurnNote | undefined
906  for (const t of turns) {
907    const d = Math.abs(t.durationMs - durationMs)
908    if (d <= MATCH_MS && (!best || d <= Math.abs(best.durationMs - durationMs))) best = t
909  }
910  return best
911}
912
913// ASCII 圖:沒標語言(或 text)的程式碼區塊,內含框線字元或箭頭
914// ```dot(或 graphviz)區塊也當成圖,標籤另附節點與邊數
915const FIG_FENCE_RE = /^```([A-Za-z]*)[ \t]*\n([\s\S]*?)\n```[ \t]*$/gm
916// 純 ASCII 圖(output style 規定回覆裡的圖用 +--+、|--、`--)也要認得
917const FIG_MARK_RE = /[─│┌┐└┘├┤┬┴┼╭╮╯╰═║]|[→←↑↓]|-->|<--|\+--|--\+|\|--|`--/
918// 文字行:中文句讀或 Markdown 清單開頭。交接草稿這類文字常寫「A → B」,箭頭出現在句子裡不算圖(實機:整份草稿被畫成灰底圖)
919const PROSE_RE = /[,。;!?]|^\s*(?:[-*]|\d+\.)\s/
920
921// 至少 2 行帶圖記號、且占非空白行三成以上才算圖;文字行裡的記號不算
922function isFigure(body: string): boolean {
923  const lines = body.split('\n').filter(l => l.trim() !== '')
924  const marked = lines.filter(l => FIG_MARK_RE.test(l) && !PROSE_RE.test(l)).length
925  return marked >= 2 && marked * 10 >= lines.length * 3
926}
927
928type Part = { kind: 'text' | 'figure' | 'dot'; text: string }
929
930// 正文依圖切段;沒有圖時回一段原文
931function splitFigures(text: string): Part[] {
932  const parts: Part[] = []
933  let at = 0
934  for (const m of text.matchAll(FIG_FENCE_RE)) {
935    const lang = (m[1] ?? '').toLowerCase()
936    const body = m[2] ?? ''
937    const kind = lang === 'dot' || lang === 'graphviz' ? 'dot' : ['', 'text', 'txt'].includes(lang) && isFigure(body) ? 'figure' : null
938    if (kind === null) continue
939    const before = text.slice(at, m.index).trim()
940    if (before !== '') parts.push({ kind: 'text', text: before })
941    parts.push({ kind, text: body })
942    at = m.index + m[0].length
943  }
944  const rest = text.slice(at).trim()
945  if (rest !== '' || parts.length === 0) parts.push({ kind: 'text', text: parts.length === 0 ? text : rest })
946  return parts
947}
948
949// dot 原文粗算:-> 或 -- 算一條邊,出現在邊或節點宣告裡的名字算節點;屬性([...]、a=b)不算
950function countDot(source: string): { nodes: number; edges: number } {
951  const body = source.replace(/\[[^\]]*\]/g, ' ').replace(/^[^{]*\{/, ' ').replace(/\b\w+\s*=\s*("[^"]*"|\S+)/g, ' ')
952  const edges = (body.match(/->|--/g) ?? []).length
953  const words = body.match(/"[^"]*"|\b[A-Za-z_][\w]*\b/g) ?? []
954  const keywords = new Set(['graph', 'digraph', 'subgraph', 'node', 'edge', 'strict'])
955  return { nodes: new Set(words.filter(w => !keywords.has(w.toLowerCase()))).size, edges }
956}
957
958// 子代理回報開頭的框架說明:從 [Subagent hand-back] 到 The report follows: 拿掉,回報本文去掉引擎加的縮排;沒有就原樣回傳
959function stripHandback(text: string): string {
960  const m = /^\s*\[Subagent hand-back\][\s\S]*?The report follows:[^\n]*\n/.exec(text)
961  if (!m) return text
962  const lines = text.slice(m[0].length).split('\n')
963  const indent = Math.min(...lines.filter(l => l.trim() !== '').map(l => /^ */.exec(l)?.[0].length ?? 0))
964  return lines.map(l => l.slice(Number.isFinite(indent) ? indent : 0)).join('\n').trim()
965}
966
967// 表格的分隔列(|---|:--:|):不是內容,不編號
968const TABLE_RULE_RE = /^\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)*\|?$/
969
970// 摘錄的候選行:程式碼區塊外的非空白行(去掉前後空白),編號從 1 起;表格分隔列不算
971function numberLines(text: string): string[] {
972  const out: string[] = []
973  let inFence = false
974  for (const raw of text.split('\n')) {
975    const l = raw.trim()
976    if (l.startsWith('```')) {
977      inFence = !inFence
978      continue
979    }
980    if (!inFence && l !== '' && !TABLE_RULE_RE.test(l)) out.push(l)
981  }
982  return out
983}
984
985// 一則回覆的 key:正文去掉前後空白後的雜湊(turn.complete 的 answer 與 AssistantMessage 的 text 對得上)
986function keyOf(text: string): string {
987  return hash(text.trim())
988}
989
990function keepLast(all: Record<string, Excerpt>): Record<string, Excerpt> {
991  return Object.fromEntries(Object.entries(all).slice(-KEEP_EXCERPTS))
992}
993
994const HEADING_RE = /^(#{1,6})\s+(.+?)\s*#*$/
995
996// 顯示用:拿掉清單符號、粗體、行內程式碼的反引號;表格列(| a | b |)的格子用 · 接起來,不留直線(實機:框裡出現整列 | 1 | … |)
997function cleanLine(l: string): string {
998  const row = /^\|(.*)\|$/.exec(l)
999  const text = row ? (row[1] ?? '').split('|').map(c => c.trim()).filter(c => c !== '').join(' · ') : l
1000  return text.replace(/^(?:[-*>]|\d+\.)\s+/, '').replace(/\*\*|`/g, '').trim()
1001}
1002
1003// 選項行:「選項 A:…」「A. …」「**A**)…」→ key+標籤;認不出字母就照順序給 A、B…
1004function optionOf(line: string, n: number): Option {
1005  const text = cleanLine(line)
1006  const m = /^(?:選項\s*|option\s+)?([A-Za-z])\s*[.))::、]\s*(.+)$/i.exec(text)
1007  return m ? { key: (m[1] ?? '').toUpperCase(), label: m[2] ?? '' } : { key: String.fromCharCode(65 + n), label: text }
1008}
1009
1010// 結論行:指到標題時,標題不是欄位名(結果、變更…)就用標題文字,是欄位名就用它之後第一個非標題行;都拿不到、超出範圍回 null
1011function outcomeOf(lines: string[], n: unknown): string | null {
1012  if (typeof n !== 'number' || !Number.isInteger(n) || n < 1 || n > lines.length) return null
1013  const line = lines[n - 1] ?? ''
1014  const m = HEADING_RE.exec(line)
1015  if (!m) return line
1016  const text = norm(m[2] ?? '')
1017  if (!OUTCOME_HEADING_RE.test(text) && !DETAIL_HEADING_RE.test(text) && !DECISION_HEADING_RE.test(text)) return text === '' ? null : text
1018  for (let i = n; i < lines.length; i++) if (!HEADING_RE.test(lines[i] ?? '') && !isShell(lines, i)) return lines[i] ?? null
1019  return null
1020}
1021
1022// 殼行:只引出下文、本身沒內容的行——冒號結尾的引言(「做法:」「理由有三個:」)或表頭(表格第一列、下一行還是表格列)。
1023// 不拿來當結論或段落摘要(實測 40 則裡約 15 處段落摘要是這種)
1024const TABLE_ROW_RE = /^\|.*\|$/
1025function isShell(lines: string[], i: number): boolean {
1026  const l = lines[i] ?? ''
1027  if (/[::]$/.test(cleanLine(l))) return true
1028  return TABLE_ROW_RE.test(l) && !TABLE_ROW_RE.test(lines[i - 1] ?? '') && TABLE_ROW_RE.test(lines[i + 1] ?? '')
1029}
1030
1031// 模型回的編號 → 結論框。結論、題目指錯(超出範圍、結論指到標題又拿不到內容)才整份不收,回 null;
1032// 選項、推薦、你要做、之後我、段落指錯只丟那一項,框照畫(使用者 2026-10-12 選逐欄降級)
1033function buildSummary(lines: string[], raw: string): Summary | null {
1034  let d: Record<string, unknown>
1035  try {
1036    const json = /\{[\s\S]*\}/.exec(raw)?.[0] ?? ''
1037    d = JSON.parse(json) as Record<string, unknown>
1038  } catch {
1039    return null
1040  }
1041  applyHeadings(lines, d)
1042  const at = (n: unknown): string | null => (typeof n === 'number' && Number.isInteger(n) && n >= 1 && n <= lines.length ? lines[n - 1] ?? null : null)
1043  const isHeading = (n: unknown) => HEADING_RE.test(at(n) ?? '')
1044  const list = (x: unknown): unknown[] => (Array.isArray(x) ? x : [])
1045  const outcome = outcomeOf(lines, d.outcome)
1046  if (outcome === null) return null
1047  const status = d.status === 'blocked' || d.status === 'partial' || d.status === 'done' ? d.status : undefined
1048  const items: Item[] = []
1049  for (const x of list(d.decisions)) {
1050    const q = x as Record<string, unknown>
1051    const question = at(q?.question)
1052    if (question === null) return null
1053    const opts = list(q?.options)
1054    // 選項有指錯的、指回題目那行、重複、或只有一個:當成沒列選項的開放題,只畫題目(實機:兩個選項都是題目那行,框裡 A、B 一模一樣)
1055    const choices = opts.length >= 2 && opts.every(o => at(o) !== null) && new Set(opts).size === opts.length && !opts.includes(q.question) ? opts : []
1056    const options = choices.map((o, i) => optionOf(at(o) ?? '', i))
1057    // 推薦常指到選項後面那句「我建議 A:…」(實測 haiku 約三成):取那句第一個提到的選項字母;指到別行又認不出就不標推薦,不整份作廢
1058    let recommended: string | undefined
1059    if (q.recommended !== undefined && choices.length > 0) {
1060      const rec = choices.indexOf(q.recommended)
1061      if (rec >= 0) recommended = options[rec]?.key
1062      else {
1063        const keys = new Set(options.map(o => o.key))
1064        recommended = [...cleanLine(at(q.recommended) ?? '').matchAll(/(?<![A-Za-z])([A-Z])(?![A-Za-z])/g)].map(m => m[1] ?? '').find(k => keys.has(k))
1065      }
1066    }
1067    // 題目指到標題(「## 待你決定」):用標題文字,不留 #
1068    const asked = HEADING_RE.exec(question)?.[2] ?? question
1069    items.push({ kind: 'decision', text: cleanLine(asked), options, ...(recommended !== undefined ? { recommended } : {}) })
1070  }
1071  // 結論只留第一句(結果段常把三句寫在同一行,框裡截成 …);比對重複時整行與第一句都算結論
1072  const whole = cleanLine(outcome)
1073  const lead = leadSentence(whole)
1074  const shown = new Set([whole, lead])
1075  for (const [field, kind] of [['todo', 'user-next'], ['next', 'agent-next']] as const) {
1076    // 跟結論或前面的項目同一句就不再列(實機:之後我把結論那句又列一次);標題行不是動作
1077    for (const n of list(d[field])) {
1078      const line = at(n)
1079      if (line === null || isHeading(n)) continue
1080      const text = cleanLine(line)
1081      if (!shown.has(text) && !items.some(i => i.text === text)) items.push({ kind, text })
1082    }
1083  }
1084  // 選項文字也算框裡已有的(實機:風險句、段落摘要就是選項 B 那行,框裡寫了兩次);比對時去掉「A.」這類選項鍵
1085  for (const i of items) {
1086    shown.add(i.text)
1087    for (const o of i.options ?? []) shown.add(o.label)
1088  }
1089  // 有題目時,「待你決定」段其餘的行(建議、理由)會畫在題目底下,也算已有(實機:「我建議選 A」同時出現在風險段與需要你段)
1090  if (decisionsOf(items).length > 0) {
1091    const ask = lines.findIndex(l => DECISION_HEADING_RE.test(HEADING_RE.exec(l)?.[2] ?? ''))
1092    for (let i = ask + 1; ask >= 0 && i < lines.length && !HEADING_RE.test(lines[i] ?? ''); i++) shown.add(cleanLine(lines[i] ?? ''))
1093  }
1094  const dup =(text: string) => shown.has(text) || shown.has(optionOf(text, 0).label)
1095  const facets: Facet[] = []
1096  for (const x of list(d.sections)) {
1097    const sec = x as Record<string, unknown>
1098    const h = typeof sec?.heading === 'number' ? sec.heading : -1
1099    const m = HEADING_RE.exec(at(h) ?? '')
1100    if (!m) continue
1101    // 摘要行要在這段裡:標題之後、下一個同級或更高的標題之前,本身不是標題
1102    const level = m[1]?.length ?? 1
1103    let end = lines.length
1104    for (let i = h; i < lines.length; i++) {
1105      const next = HEADING_RE.exec(lines[i] ?? '')
1106      if (next && (next[1]?.length ?? 7) <= level) {
1107        end = i
1108        break
1109      }
1110    }
1111    let s = sec.summary
1112    if (typeof s !== 'number' || s <= h || s > end || isHeading(s)) continue
1113    // 挑到殼行:往下找段裡第一個不是標題、不是殼行的
1114    while (s <= end && (isHeading(s) || isShell(lines, s - 1))) s++
1115    if (s > end) continue
1116    // 摘要跟結論、你要做、之後我、別段摘要同一句:這段不收合,留在正文(實測 40 則有 6 則同一句出現兩次)
1117    const text = cleanLine(at(s) ?? '')
1118    if (dup(text)) continue
1119    shown.add(text)
1120    const heading = m[2] ?? ''
1121    facets.push({ label: clip(norm(heading), 40), summary: clip(text, 200), heading })
1122  }
1123  // 風險句:風險常寫在「驗證」底下或一般條列裡,只靠風險標題認不出(實驗 25 則只有 5 則有風險標題)。
1124  // 指錯、標題行、跟框裡已有的句子重複,只丟那一項;連同風險標題段的摘要最多 4 行
1125  const room = 4 - facets.filter(f => RISK_RE.test(f.heading ?? f.label)).length
1126  const risks: string[] = []
1127  for (const n of list(d.risks)) {
1128    const line = at(n)
1129    if (line === null || isHeading(n) || risks.length >= room) continue
1130    const text = cleanLine(line)
1131    if (text === '' || dup(text)) continue
1132    shown.add(text)
1133    risks.push(text)
1134  }
1135  return { ...(status ? { status } : {}), outcome: clip(lead, 300), items, facets, ...(risks.length > 0 ? { risks } : {}) }
1136}
1137
1138const OUTCOME_HEADING_RE = /^(?:結果|結論|答案|results?|outcome|summary|answer|tl;?dr)$/i
1139const DETAIL_HEADING_RE = /變更|驗證|風險|證據|change|verif|check|test|risk|evidence/i
1140const DECISION_HEADING_RE = /決定|decision|choose|choice/i
1141// 規則認選項只認大寫字母(「e.g. …」不算),而且一段裡要從 A 起連號
1142const OPTION_KEY_RE = /^(?:選項\s*|[Oo]ption\s+)?([A-Z])\s*[.))::、]/
1143
1144// 回覆有認得的標題時,照標題改寫模型挑的編號(模型偶爾挑錯結論行、漏掉選項):
1145// 結論=「結果」這類標題下第一行;題目=「待你決定」段裡 A、B… 連號的選項行與它們前一行;
1146// 細節段(變更、驗證、風險…)的摘要=段裡第一行。認不出的欄位與狀態、你要做、之後我照模型的
1147function applyHeadings(lines: string[], d: Record<string, unknown>) {
1148  const heads = lines.flatMap((l, i) => {
1149    const m = HEADING_RE.exec(l)
1150    return m ? [{ i, level: m[1]?.length ?? 1, text: norm(m[2] ?? '') }] : []
1151  })
1152  const body = (h: { i: number; level: number }) => {
1153    const end = heads.find(x => x.i > h.i && x.level <= h.level)?.i ?? lines.length
1154    return Array.from({ length: end - h.i - 1 }, (_, k) => h.i + 1 + k).filter(i => !HEADING_RE.test(lines[i] ?? ''))
1155  }
1156  const result = heads.find(h => OUTCOME_HEADING_RE.test(h.text))
1157  const first = result ? body(result).find(i => !isShell(lines, i)) : undefined
1158  if (first !== undefined) d.outcome = first + 1
1159  const picked = Array.isArray(d.sections) ? (d.sections as Record<string, unknown>[]) : []
1160  // 細節段的摘要:模型挑的行在段裡、不是殼行就照用(實測有挑得比第一行好的),否則取段裡第一個不是殼行的
1161  const detail = heads.filter(h => h !== result && DETAIL_HEADING_RE.test(h.text) && !DECISION_HEADING_RE.test(h.text)).flatMap(h => {
1162    const rows = body(h).filter(i => !isShell(lines, i))
1163    const mine = picked.find(s => s?.heading === h.i + 1)?.summary
1164    const top = typeof mine === 'number' && rows.includes(mine - 1) ? mine - 1 : rows[0]
1165    return top === undefined ? [] : [{ heading: h.i + 1, summary: top + 1 }]
1166  })
1167  d.sections = [...picked.filter(s => !detail.some(x => x.heading === s?.heading)), ...detail]
1168  const ask = heads.find(h => DECISION_HEADING_RE.test(h.text))
1169  if (!ask) return
1170  const rows = body(ask)
1171  const keys = rows.map(r => OPTION_KEY_RE.exec(cleanLine(lines[r] ?? ''))?.[1])
1172  // 每題從 A 那行起(前一行是題目),連號到斷為止
1173  const starts = keys.flatMap((key, k) => (key === 'A' && k > 0 ? [k] : []))
1174  const old = Array.isArray(d.decisions) ? (d.decisions as Record<string, unknown>[]) : []
1175  const decisions = starts.flatMap((s, n) => {
1176    let end = s
1177    while (end < rows.length && keys[end] === String.fromCharCode(65 + end - s)) end++
1178    if (end - s < 2) return []
1179    const question = (rows[s - 1] ?? 0) + 1
1180    // 推薦:選項後面、下一題的題目之前提到「建議/recommend」的那行;沒有就沿用模型對同一題標的
1181    const tail = rows.slice(end, (starts[n + 1] ?? rows.length + 1) - 1)
1182    const said = tail.find(r => /建議|推薦|recommend|I'd pick|I would pick/i.test(lines[r] ?? ''))
1183    const recommended = said !== undefined ? said + 1 : old.find(o => o?.question === question)?.recommended
1184    return [{ question, options: rows.slice(s, end).map(r => r + 1), ...(recommended !== undefined ? { recommended } : {}) }]
1185  })
1186  if (decisions.length > 0) d.decisions = decisions
1187}
1188
1189// 要使用者選的題目(有選項的 decision);題號就是在這個陣列裡的位置
1190function decisionsOf(items: Item[]): Item[] {
1191  return items.filter(i => i.kind === 'decision' && (i.options?.length ?? 0) > 0)
1192}
1193
1194// 等你決定>卡住>等你動手>部分完成>完成。照模型標的狀態走:完成、卡住不因附了「你要做」變黃(使用者實機:幾乎每個框都黃);
1195// 只有做到一半停下來等你才是等你動手(實機 s3 原本標成進行中,兩個評審都誤判成還在跑)
1196function glyphOf(s: Summary): string {
1197  if (s.items.some(i => i.kind === 'decision')) return '?'
1198  if (s.status === 'blocked') return '!'
1199  if (s.status !== 'done' && s.items.some(i => i.kind === 'user-next')) return '>'
1200  if (s.status === 'partial') return '~'
types/index.d.ts 56 lines
1// 結論框的內容:回覆結束後由小模型挑編號、mod 用回覆原句組成(模型寫不出回覆裡沒有的字)
2export type Option = { key: string; label: string }
3export type Item = { kind: 'decision' | 'user-next' | 'agent-next'; text: string; options?: Option[]; recommended?: string }
4export type Facet = { label: string; summary: string; heading?: string }
5// risks:不在風險標題底下的風險句(0.10.2 起);0.10.1 以前存下的摘錄沒有這欄
6export type Summary = { status?: 'done' | 'blocked' | 'partial'; outcome: string; items: Item[]; facets: Facet[]; risks?: string[] }
7// 一則回覆的摘錄狀態(以回覆正文雜湊當 key):摘錄中、好了、失敗(原因照實寫在框的位置)
8export type Excerpt = { state: 'pending' } | { state: 'ready'; summary: Summary } | { state: 'failed'; reason: string }
9// 一輪結束時記下的耗時與回覆雜湊(沒摘錄就沒有 id):TurnDuration 那列沒有輪次編號,只能用耗時對回來
10export type TurnNote = { id?: string; durationMs: number }
11// 子代理:主對話派的記在派它那一輪的結論框(card=回覆正文雜湊)下;card 還沒有=剛啟動、這一輪還沒結束(''=不屬於任何框)
12export type AgentNote = {
13  id: string; type: string; description: string; status: string; card?: string; durationMs?: number; startedAt?: number
14}
15// 還沒 commit 的改動(git diff HEAD --numstat):repo 內路徑、絕對路徑(跟 touched 比)、增刪行數
16export type ChangeNote = { path: string; abs: string; add: number; del: number }
17// classic.TaskCreated/TaskCompleted 記下的任務
18export type TaskNote = { id: string; subject: string; done: boolean }
19// pane 證據段:沿用最近一輪有「驗證」段的結論,age=之後又過了幾輪有摘要的回合
20export type Evidence = { chips: string[]; proof: string[]; age: number }
21
22declare module 'claude-code' {
23  interface PluginState {
24    'sitrep': {
25      // 每則回覆(以正文雜湊當 id)的已選答案:題號 → 選項 key
26      answers: Record<string, Record<number, string>>
27      // 展開中的收合段落:`${id}:${段落序號}`
28      open: Record<string, boolean>
29      // 最近幾輪:舊框收合、框上的耗時、TurnDuration 那列對子代理輪
30      turns: TurnNote[]
31      // 最近一張結論框的待決題目,給 prompt 上方那列用;沒摘錄的回合不動它
32      // todo=要你親手做的事(user-next),沒題目時 prompt 上方那列改提示它
33      pending: { id: string; decisions: Item[]; todo: string[] } | null
34      // 背景子代理與它所屬的結論框
35      agents: AgentNote[]
36      // 最近幾則回覆的摘錄,key=正文雜湊
37      excerpts: Record<string, Excerpt>
38      // 狀態 pane:最近一張結論框、背景工作、任務、git diff --stat
39      last: { id: string; summary: Summary } | null
40      // 最近一次有「驗證」段的結論:小標籤、細節行、離現在幾輪(0=這一輪)
41      evidence: Evidence | null
42      background: string[]
43      tasks: TaskNote[]
44      // classic.* 收不收得到:guarded=主對話結束了卻沒看到 classic.Stop(Team/Enterprise 登入)
45      classic: 'unknown' | 'seen' | 'guarded'
46      changes: ChangeNote[]
47      // 這個 session 用 Edit/Write 改過的檔(絕對路徑)
48      touched: string[]
49      // pane 現在有畫出來:題目移到 pane,prompt 上方那列不畫
50      paneOpen: boolean
51      // 這一輪主對話呼叫了幾個工具、最近一個(工具名+參數第一行),回合進行中 prompt 上方那列用
52      progress: { count: number; last: string }
53    }
54  }
55}
56