SLOPSHOPPER

ctx-relay

A band above the prompt with context size, per-turn cost and the prompt-cache countdown. Past the handoff line it counts down 60 s, writes a handoff file with…

panebandcommandtoastpromptmodel
★ 1v0.12.0MITupdated 2026-10-25mangow314/mango-mods/ctx-relay
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ctx-relay
│ ┃ ctx-relay notes ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ Cannot locate the harness root. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ q: close ⏺ 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 │ │ › /ctx-relay-status │ ⎿ ctx-relay: [ctx-relay] context 97400; handoff line 170000 (85% o │ ⎿ ctx-relay: auto handoff: idle │ ⎿ ctx-relay: background work: none │ ⎿ ctx-relay: cache: ttl 1h (subscription, estimated) · last reques │ ⎿ ctx-relay: last handoff file: none │ │ ⟨Claude Code's own drawing⟩ 󰯉  97K/170K 57% · +0K $0.00 42s · cache 59m ▅▅ · Writing handoff file… ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ 󰯉  97K/170K 57% · +0K $0.00 42s · cache 59m ▅▅ · Writing handoff file…
Pane · ctx-relay notes
Cannot locate the harness root. q: close
README

ctx-relay

繁體中文版:README.zh-TW.md. The band and commands are in English. Handoff files use English headings with the body in the conversation's language; the optional full format is in Traditional Chinese (see "Handoff file format").

It needs no other skill or hook: the mod writes the handoff file itself.

A Claude Code mod that draws a band above the prompt: current context / the handoff line, this turn's cost, and how long the prompt cache stays warm. When the main conversation crosses the automatic handoff line, it hands off on its own: it writes a handoff file, runs /clear, and resumes in the new conversation. When a new conversation starts and there is a handoff file nobody has picked up, the band gets a second line, Pending handoff; press 1 to send the resume prompt.

Tested on Claude Code 2.1.289 to 2.1.296. The mods API is still in early access, so a Claude Code release may require changes.

What it does

WhenWhat happens
A main-conversation turn ends (not interrupted) with context ≥ the handoff lineIf Claude Code reports background work (shells, subagents, monitors, workflows, …) or a one-shot scheduled task, the handoff is deferred and the band shows why; recurring schedules do not block it. Otherwise a 60-second countdown starts. Signed in with a Team or Enterprise plan, Claude Code's built-in guard keeps the Stop report from user mods, so only running subagents defer it
While deferred, context reaches the cap (halfway between the handoff line and the compaction point)The countdown runs anyway; the handoff file header lists the work still running (its completion notice may never arrive)
Another Stop hook blocks the stop (the turn has not really ended)No decision; wait for the stop that really ends the turn
During the countdownPress Cancel (hotkey 1) to cancel; for the rest of this conversation it only reminds you. Sending any message only postpones it: if you are still past the line when that turn ends, the countdown starts again
A new turn starts during the countdown or preparation (a schedule, a background notification, a message from another session)This switch is dropped; it decides again when the turn ends
The countdown endsThe mod collects git state → $.model.fork fills in only the body of each field, one === KEY === line per field (gives up after 3 minutes without an answer) → the mod assembles the handoff file under its own hard-coded ## headings, so the model has no chance to mistype a heading → machine check (a missing field is marked thin:; no section marker at all counts as a failure) → write the file and read it back → confirm the conversation has not changed → /clear → send the handoff file path and the pickup rules in the new conversation
Any step fails before /clearStays in the original conversation, the band shows why, no retry

In the full format, the mod appends the coordination contract verbatim, without the model: a === CONTRACT === section written by the fork, and any ## 協調契約 ("coordination contract") section in its body, are always dropped. Any other ## line in the fork's body is demoted to ### , so the only second-level headings in a handoff file are the mod's own. A section whose key is mistyped (for example === VERIFED ===): that field is marked thin:, and its body is kept, appended at the end of Next (full: 關鍵細節備忘, "key details") with a note. A `ui-summary block in the fork's output (written by sitrep versions before 0.3.0) is removed.

Thresholds

  • Compaction point: the auto-compact trigger Claude Code reports itself (autoCompactThreshold from $.session.usage({ breakdown })). With auto-compact off, the model's context window is used instead.
  • Handoff line: the handoffTokens setting if set; if not (0), 85% of the compaction point. A setting above 85% of the compaction point (for example after switching to a 200K model) falls back to 85%, and /ctx-relay-status says so.
  • Orange warning line: 88% of the handoff line.
  • Deferral cap: with background work, the handoff can be deferred at most to halfway between the handoff line and the compaction point.

Set the handoff line from the ctx-relay row in /config, or from a shell:

echo '{"handoffTokens": "400000"}' | claude plugin configure ctx-relay@mango-mods --values-stdin

A setting changed from the shell takes effect after restarting Claude Code or running /reload-plugins in the session. For end-to-end tests you can set it very low (for example 1).

Note: with CLAUDE_AUTOCOMPACT_PCT_OVERRIDE set, the compaction point Claude Code reports may not apply that percentage. Measured on 2.1.288: with CLAUDE_CODE_AUTO_COMPACT_WINDOW=600000 and CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=88, it reported 567,000 (=600,000−33,000). Measured on 2.1.289 with a 120,000 window: it reported 87,000, and compaction happened on the turn where context grew from 86,412 to 88,335; both the reported value and (120,000−20,000)×88% = 88,000 fall in that range, so it is impossible to tell which is right. With a 600K window the real compaction point may still be 510K, 528K, or 567K. If you use this environment variable, set handoffTokens.

When loaded with claude --plugin-dir, the installed copy's handoffTokens is not read, so the handoff line is the automatic value.

The band

ctx-relay band: icon, capsule progress bar, tokens, cost, cache countdown

One line, left to right:

  1. A space invader icon and a 10-cell capsule progress bar, both colored by how close context is to the handoff line (tokens ÷ handoff line):
Tokens ÷ handoff lineColor
below 70%green
70% up to the warning lineyellow
warning line up to the handoff lineorange
at or past the handoff linevermilion

The bar stays still; when a turn ends, the cells that turn added light up for half a second (the leading cell, when it added less than a cell). The icon pulses, one frame every 250 ms. Once the prompt cache has expired (you are probably away), the pulse stops; it starts again when the next turn ends.

  1. 220K/434K 51%: current context / handoff line, and the share.
  2. · +20K $0.50 12s: how much context this turn added, what it cost, and how long it took. When this turn's cache hit rate (summed over every request in the turn) is below 40%, 󰜗 12% follows: the turn ran on a cold cache and cost more, usually because the cache expired while you were idle.
  3. · cache 42m: the prompt cache countdown; see "Cache countdown". Hidden while a turn runs.
  4. Bars: context at the end of each recent turn, a full bar = at the handoff line, each in that turn's color from the table above. Drawn only when it fits on the line (with a dock pane open, the narrower width counts).
  5. · <status>: handoff deferred (with the reason), writing the handoff file, failed, cancelled, or which file this conversation resumed from.
  • Foreground colors only; no backgrounds.
  • Text colors use Claude Code theme names (text, inactive, warning, error…), so they follow your /theme, light and daltonized included. The icon and progress bar keep the fixed colors in the table above: the bar is a Raster, which takes RGB only.
  • Below 80 columns the progress bar is dropped (the icon and numbers stay); whatever still does not fit is cut at the end.
  • During the countdown the whole line becomes 󰚌 Handoff in 42s · at 400K · send a message to postpone, with a Cancel [1] button next to it.
  • After a handoff (automatic, or Resume [1] on a pending one) the status reads Resumed from <file> · next: <first line of the next-step field> · /ctx-relay-notes, and an automatic handoff also shows a toast. The "next" part goes away as soon as you type.
  • If /clear succeeded but the resume message could not be sent, the line reads Cleared, but <reason>. Type: Read <path> and continue from it. The part after "Type:" is what you paste into the conversation; with the full format it is in Chinese (讀 <path> 並依其接續).
  • When another mod also draws a band, its content goes on top and the ctx-relay line below. When there is not enough height, or the other mod does not give way, the ctx-relay line can be hidden; see "Known limits".
  • The icons, the snowflake, and the capsule (U+EE00–EE05, in Nerd Fonts 3.0 and later) need a Nerd Font, for example Symbols Nerd Font as a fallback; without one they render as boxes.
  • Inside tmux, Claude Code uses only 256 colors by default. If tmux has RGB enabled, set CLAUDE_CODE_TMUX_TRUECOLOR=1 to get the exact colors.

Cache countdown

The prompt cache lets the next request re-read the conversation cheaply. It expires after a stretch with no requests (its time to live, TTL), and every request restarts the clock. The countdown tells you how long it has left, so you can decide whether to keep going, compact first, or start a new session.

  • Time left = TTL − (now − when the last main-conversation turn ended). Shown in minutes, in seconds under one minute, orange in the last 5 minutes, and 󰜗 cold once expired (the last turn's hit rate is hidden then).
  • Mods do not receive Claude Code's own cache state (prompt_cache is only in the status line's input), so ctx-relay works it out itself. It measures from the end of the turn, which is later than the start of the turn's last request, so it can run long by about the length of the last reply. Treat it as a guide.
  • TTL, first match wins, in the order Claude Code uses (prompt caching):
  • FORCE_PROMPT_CACHING_5M set → 5 minutes
  • CLAUDE_CODE_PROMPT_CACHE_TTL (5m or 1h)
  • the promptCacheTtl setting (5m or 1h)
  • ENABLE_PROMPT_CACHING_1H set → 1 hour
  • a Claude subscription (the session reports rate limits) → 1 hour; otherwise (API key, cloud provider) → 5 minutes
  • The TTL is an estimate; /ctx-relay-status marks it estimated. If you come back after more than 5 minutes but before the assumed TTL, and that turn's hit rate is below 40%, /ctx-relay-status notes it. The TTL is not changed: a subscription over its included usage drops to 5 minutes, but switching the model, tools or system prompt also starts a cold cache, and the mod cannot tell which happened.
  • After the main conversation is compacted (/compact, auto-compact, or idle compaction), the old cache no longer matches the start of the conversation, so the countdown is dropped until the next turn ends.
  • Idle compaction: Claude Code can compact a long conversation by itself while you are idle, before the cache expires, and then shows "Compacted while idle, before the prompt cache expired". This is not in the docs; read from the 2.1.294 executable: it runs only when the cache is a one-hour one and still warm, context is at least 200K (CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS, no lower than 100K), you have been idle for about 90% of the TTL (about 54 minutes), and Anthropic has turned the feature on for your account. Turn it off with "idleCompaction": false in settings. It shrinks the context, so the handoff line is not reached.
  • ctx-relay does not keep the cache warm. A request sent with $.model.fork does not read the main conversation's cache (see "Known limits"), so it cannot extend it.

Handoff file format

The handoffFormat setting picks one of two formats:

FormatFieldsLanguage
lite (default)Goal, Files, Verified, NextEnglish headings and instructions; the fork writes the body in the conversation's language
fullAuthor-specific: the 8 fields of the author's own handoff format (goal + latest instruction, files, verified vs gaps, unrelated dirty files, next step, key details, hard constraints as YAML, pointers), plus the source handoff file's coordination contract and the session's progress INDEX.mdTraditional Chinese

full follows conventions from the author's own setup; most people want lite. The notes pane and the pickup line read either format, whatever the setting says.

echo '{"handoffFormat": "full"}' | claude plugin configure ctx-relay@mango-mods --values-stdin

Where handoff files go

In a git repo: <git-common-dir>/harness/handoff/ (inside .git, so never committed; delete the folder to clean up); outside git: ~/.claude/harness/<directory name>-<first 8 chars of sha256>/handoff/. The folder above handoff/ is called the harness root below. File name: <timestamp>-<slug>-<first 8 chars of the source session id>-<batch number>.md, so two batches in the same second, or two sessions sharing one git-common-dir, never overwrite each other. The header records HEAD at handoff time (git rev-parse --short HEAD). The resume message tells the new session to run git log --oneline <HEAD>..HEAD; any output means commits landed after the handoff, so it reports the file may be stale first. It compares commits, not times: another session's commits can be recorded in UTC and would be missed against the header's local timestamp. In the full format, if <same root>/progress/<session id>/INDEX.md exists, it is passed to the fork as well.

Waiting to be picked up (handoff-pickup)

ctx-relay pickup line: an unclaimed handoff file, press 1 to resume

The line reads 󰯉 Pending handoff: <file name> (2h ago, from 1f3a9c2e), with a Resume [1] button. When more handoff files are waiting, a +N follows.

WhenWhat happens
A new conversation starts (no messages yet at startup; an old conversation reopened with --resume does not count), or after you run /clear yourselfLook for handoff files in the handoff folder that nobody has picked up, and show the newest; the count of the others goes in +N
Press 1 while the prompt is empty (or click the button)Sends "Read <full path> and continue from it; check the git state and the next step before acting.", followed by: if the header has a head line, git log --oneline <head>..HEAD printing any commit means the file may be stale, so say so first (the Chinese version for a full file), and marks this file as picked up
The main conversation starts a new turn (you send a message, press resume, a schedule fires)The line goes away
  • "Picked up" is recorded as <handoff folder>/.picked/<handoff file name> (an empty file); the handoff file itself is not touched. Because the folder name starts with a dot, a plain ls -t for the newest handoff file does not see it.
  • A file is marked as picked up in three cases: you press resume; a message you send contains the full path of a handoff file (you pasted a resume prompt by hand); ctx-relay hands off automatically (marked before /clear, so the new conversation does not list it).
  • On first enable, ctx-relay stores the current time in its own store (pickupSince): handoff files modified before that count as picked up, so a fresh install does not list a pile of old files.
  • "How long ago" uses the file's modification time; "from" is the first 8 characters of the first session \<id>\`` in the handoff file, and is omitted if not found.
  • The message sent by pressing 1 is labeled as coming from ctx-relay (the mod sends it for you; the model sees the original text).
  • While the pickup line is shown, typing "1" into an empty prompt presses resume instead of typing. The countdown's cancel button is also 1, but the countdown only appears after a turn ends, when the pickup line is already gone, so the two never appear together.
  • If sending the resume prompt is blocked (for example by a hook in settings), the line stays and the file is not marked as picked up.

Commands

  • /ctx-relay-status: shows thresholds, readings, handoff state, background work, the cache TTL (with where it came from) and time left, and the last three handoff failures. Every failed handoff (before /clear) is appended to <harness root>/ctx-relay/failures.jsonl (time, auto or manual, tokens, minutes since you last typed, reason; last 100 kept). It also counts the handoff ledger, <harness root>/ctx-relay/handoffs.jsonl (last 500 kept): one line per countdown, cancel, postponement (you sent a message or a new turn started), completed handoff, and failure. A completed handoff records the tokens before it, the fork's token usage (input, cache read, cache write, output), and whether the resume message was sent. Use it to judge whether the automatic handoff earns its keep.
  • /ctx-relay-notes: opens (or, typed again, closes) a notes pane for checking where things stood: the handoff file this conversation resumed from (or the newest one in handoff/), plus the phase from the INDEX.md of the session named in its header. After an automatic handoff it opens by itself once, without taking the prompt's focus, when the terminal is wide enough; otherwise the toast points to the command. Two pages: s status (next steps, don'ts, gaps, then goal, phase and files) and v evidence (the verified notes as written, and where the handoff came from). One accent color and gray text; red, yellow and green mark only the ✓ ▲ ✗ symbols. Long lines wrap. The pane paints its own dark background, so it reads the same over a transparent terminal. q closes it.
  • /ctx-relay-now: hand off right away; with background work running, type /ctx-relay-now yes. The fork instructions, the handoff file header, and the resume message in the new conversation all say this was a manual /ctx-relay-now handoff, not "crossed the automatic handoff line".
  • You can append your latest instruction, for example /ctx-relay-now yes, a newline, then "do B and install the new mod". Only a first word of yes counts as confirmation; the rest is the instruction. Without background work, yes is not needed and all the arguments are the instruction.
  • The instruction is passed verbatim to the fork for writing the goal and next-step fields (Goal / Next; in full, "goal + latest instruction" and "next step"), and written verbatim into the handoff file header and the resume message (each line prefixed with > , so a ## in the instruction never becomes a handoff file heading).
  • With an instruction attached, the resume message tells the new conversation to check git state and then follow the instruction, without waiting for you to repeat it. Without one, as before: report the current state and wait for you.
  • Exception (full only): when the handoff file is missing 硬約束 ("hard constraints"; the header's thin lists 硬約束), the task's constraints may not have been written down, so the resume message instead asks the new conversation to first report how it plans to follow the instruction and wait for your confirmation.

Known limits

  • Background work never times out: a long-running server defers the handoff until the cap forces a countdown; to hand off earlier, use /ctx-relay-now yes.
  • The background work the commands see is the list from the last time the main conversation stopped, plus the subagents running right now.
  • A subagent may appear in both Claude Code's background-work list and its subagent list, so the count in the deferral reason can be too high.
  • Requests sent to other Claude sessions and not yet answered are not detected: check them yourself before /clear.
  • Another mod that draws a tall box in the band's slot (seen with a confirmation-box mod in an 80-column terminal) can hide the ctx-relay line while its box is up; the buttons still work and the band comes back after. If that mod draws first and does not pass the slot on, no terminal height is enough; which mod draws first depends on load order.
  • Writing the handoff file costs about as much as one turn on a cold cache. The fork does not read the main conversation's cache: measured on 2.1.294, a fork sent 30 seconds after a turn hit 43% (only the shared system prompt and tools), while the main conversation's next turn hit 100%.
  • After a compaction, the band's token count is still the reading from before it until the next turn ends.
  • The handoff content comes from the fork; the machine check only looks for empty fields and does not guarantee the content is correct. The new conversation is asked to check against git first.
  • After /clear, $.state is reset; module variables and timers survive (measured), so the mod cancels its timers before clearing.
  • Needs bash and git on PATH; outside git, also realpath (GNU, with -m) and sha256sum or shasum.
  • The handoff folder layout matches the author's own handoff tooling, so both find the same files.
Source 2 files
hooks/register.tsx 1606 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, RenderInput, SessionContextUsage, Timer, TurnCompleteInput } from 'claude-code'
3
4import type { Auto, Cache, Limits, Pickup, Reading, Receipt } from '../types'
5
6// ctx-relay:提示框上方一行,顯示每輪花費與距交接線的剩餘空間;
7// 主對話回合結束(turn.complete)時 context 越過自動交接線 → 沒有背景工作就倒數 60 秒 →
8// mod 自己收集 git/INDEX、用 $.model.fork 產生交接檔、機器檢查後寫檔 → /clear → 在新對話送出交接檔路徑。
9// 倒數或準備中有新回合開始(排程、通知、你送訊息)就作廢這次切換。
10// 壓縮點取自 Claude Code 自己回報的 autoCompactThreshold,本檔不寫窗口數字;
11// 交接線=userConfig handoffTokens,沒設或超過壓縮點的 HANDOFF_PCT 時用後者。
12//
13// /clear 之後(P1 probe 實測):$.state 歸零、模組變數與 $.clock 計時器保留、session.start 不重跑。
14// 所以要撐過 clear 的東西放模組變數,clear 前先取消計時器。
15//
16// handoff-pickup:新對話開場(session.start 且還沒有訊息,或 /clear 之後)找還沒人接手的交接檔,
17// band 多一行「待接手」+接續按鈕(hotkey 1);新回合開始就收掉。
18// 已接手=<root>/handoff/.picked/<檔名> 空檔:按接續、你送出的訊息含交接檔完整路徑、mod 自己自動交接時寫。
19// 第一次啟用前就有的交接檔(mtime 早於 $.store 的 pickupSince)一律算已接手。
20
21const HISTORY = 12
22const COUNTDOWN_MS = 60_000
23// fork 沒有取消參數:超過這個時間就放棄等待、記失敗,不 clear(回來的結果不再使用)
24const FORK_TIMEOUT_MS = 180_000
25const BARS = '▁▂▃▄▅▆▇█'
26const TAG = '[ctx-relay]'
27
28// handoff skill(~/.claude/skills/handoff/SKILL.md)的 8 欄位。中文標題由 mod 寫死,fork 只用左欄的 ASCII 鍵名分段填內文:
29// 模型沒有機會把標題打錯(2026-10-05 實例:標題一個形近字就過不了讀回檢查,整次交接中止)
30const SLOTS = [
31  ['GOAL', '目標 + 最新指令'],
32  ['FILES', '已改/將改檔'],
33  ['VERIFIED', '已驗證 vs 驗證缺口'],
34  ['DIRTY', 'dirty 無關項'],
35  ['NEXT', '下一步具體動作'],
36  ['NOTES', '關鍵細節備忘'],
37  ['CONSTRAINTS', '硬約束(結構化)'],
38  ['POINTERS', '指標'],
39] as const
40// 精簡版(userConfig handoffFormat 的預設 lite):只有四欄、英文標題,fork 照對話語言寫內文;不讀 INDEX、不帶協調契約與硬約束。
41// 給沒有 handoff skill 那套慣例的人用;8 欄中文版=full
42const LITE_SLOTS = [
43  ['GOAL', 'Goal'],
44  ['FILES', 'Files'],
45  ['VERIFIED', 'Verified'],
46  ['NEXT', 'Next'],
47] as const
48type Format = 'lite' | 'full'
49const slotsOf = (format: Format): readonly (readonly [string, string])[] => (format === 'full' ? SLOTS : LITE_SLOTS)
50const fieldsOf = (format: Format) => slotsOf(format).map(([, title]) => title)
51// 交接檔用哪一版:看第一欄標題,不看設定(改過設定、或 handoff skill 寫的舊檔都讀得懂)
52// 中文版檔案第一行是「讀 <路徑> …」(handoff skill 寫的也是)
53const formatOf = (text: string): Format => (text.startsWith('讀 ') || hasHeading(text, SLOTS[0][1]) ? 'full' : 'lite')
54// 交接檔裡某個鍵的段落;這一版沒有這個鍵就是空字串
55function part(text: string, key: string): string {
56  const title = slotsOf(formatOf(text)).find(([k]) => k === key)?.[1]
57  return title === undefined ? '' : section(text, title)
58}
59// 已接手標記的資料夾:點開頭,handoff skill 用 `ls -t handoff/ | head -1` 找最新交接檔時看不到它
60const PICKED = '.picked'
61const SINCE_KEY = 'pickupSince'
62const CONTRACT = '協調契約'
63const CONSTRAINT_KEYS = ['stop_status', 'unresolved_prerequisite', 'responsible_authority', 'admissible_fallback'] as const
64
65// band 文字用引擎的主題色名稱,跟著使用者的 Claude Code 主題(含淺色、daltonized)走:
66// 天藍=正常、橘=過出場提醒線、紅=交接線/倒數/失敗
67const SKY = 'suggestion'
68const WARN = 'warning'
69const ERR = 'error'
70const OK = 'success'
71
72// 開頭圖示+進度條+長條圖的比例色維持 hex:Raster 只吃 RGB,圖示的呼吸要拿 RGB 調暗(mood、bar、breathe、spark)。
73// 只用前景色(深色底在 tmux 256 色下會變刺眼的 #00005f)
74const ORANGE = '#E69F00'
75const VERMILION = '#D55E00'
76const GREEN = '#009E73'
77const YELLOW = '#F0E442'
78const BAR_CELLS = 10
79// Nerd Font 的 Fira Code 進度字形:U+EE00/EE01/EE02=空心左/中/右,+3=實心
80const FIRA = 0xee00
81const FIRA_FILLED = 3
82// Raster 的顏色是 0xRRGGBB 整數;0x01000000=終端預設色
83const TRACK = 0x464e5a
84const TERMINAL_DEFAULT = 0x01000000
85// 動畫一幀(圖示呼吸、新增格閃亮)
86const FRAME_MS = 250
87// 每輪結束,這輪新增的格子亮幾幀(2=0.5 秒),之後進度條靜止(使用者 2026-10-10 選 A1:取代一直跑的掃光)
88const FRESH_FRAMES = 2
89// 比例=token ÷ 交接線:<70% 綠、到提醒線前黃、過提醒線橘、過交接線朱紅;圖示固定小怪獸
90const MOOD_YELLOW = 0.7
91// 窄終端:<80 欄拿掉進度條;長條圖放不下就不畫(drawBand 依文字寬度算)
92const BAR_COLUMNS = 80
93const LABEL = 'inactive'
94const VALUE = 'text'
95const DOT = 'subtle'
96// notes pane 自帶實心深底、整套自訂色,不跟主題(底和字一起換才不會在淺色主題下變黑底黑字);色值與對比(APCA Lc 為自算估值)見 scratchpad tui-ux/r3-color-ux.md。
97// 深底上 Okabe-Ito 原色偏暗(Lc 33–56),pane 內改用自訂深底語意色;色盲靠符號(✓ ▲ ✗)+文字區分。band 不動
98const N = {
99  PANE: '#181818',
100  CARD: '#262626',
101  RULE: '#5a616b',
102  TITLE: '#f5f7fa',
103  TEXT: '#e6e9ee',
104  MUTED: '#b1b8bf',
105  ACCENT: '#6CC0F0',
106  SUCCESS: '#3DD68C',
107  WARNING: '#F0C040',
108  DANGER: '#FF8F66',
109}
110const INVADER = '󰯉' // Nerd Font md-space_invaders U+F0BC9
111const SKULL = '󰚌' // md-skull U+F068C
112// cache 冷暖:熱=大多命中(便宜),冷=大多重算(貴,例如閒置超過 cache 存活時間)
113const SNOW = '󰜗' // md-snowflake U+F0717
114// 命中率低於這個才顯示(偏冷=這輪比較貴,多半是閒置超過快取存活時間)
115const CACHE_COLD = 40
116// 快取存活時間:Claude Code 訂閱額度內主對話 1h,API key/超額 5m(code.claude.com/docs/en/prompt-caching)
117const TTL_5M = 5 * 60_000
118const TTL_1H = 60 * 60_000
119// 剩這麼多以內倒數改橘色
120const CACHE_SOON_MS = 5 * 60_000
121
122// 自動交接線=壓縮點的 85%(大輪 +45K+交接輪 +19K 仍在壓縮點前);橘色提醒線=交接線的 88%
123const HANDOFF_PCT = 85
124const NUDGE_PCT = 88
125
126// harness 狀態根目錄:git repo → <git-common-dir>/harness;非 git → ~/.claude/harness/<目錄名>-<sha256 前 8 碼>;
127// 任何一步失敗印空字串。照抄 mango 的 dotfiles hooks/_lib/harness-paths.sh(契約:vault Harness-State-Layer-Contract.md),
128// 刻意偏離該檔「hash 演算法只存一份」:plugin 要能在沒有那份 dotfiles 的環境獨立運作。改演算法時兩邊一起改。
129const ROOT_SH = [
130  'real=$(realpath -m "$1" 2>/dev/null) || true',
131  '[ -n "$real" ] || exit 0',
132  'common=$(git -C "$real" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || true',
133  'if [ -n "$common" ]; then',
134  '  common=$(realpath -m "$common" 2>/dev/null) || true',
135  '  [ -n "$common" ] && printf "%s/harness\\n" "$common"',
136  '  exit 0',
137  'fi',
138  '[ -n "${HOME:-}" ] || exit 0',
139  'hash=""',
140  'if command -v sha256sum >/dev/null 2>&1; then hash=$(printf "%s" "$real" | sha256sum 2>/dev/null) || true',
141  'elif command -v shasum >/dev/null 2>&1; then hash=$(printf "%s" "$real" | shasum -a 256 2>/dev/null) || true; fi',
142  'hash=${hash%% *}; hash=${hash:0:8}',
143  '[ -n "$hash" ] || exit 0',
144  'printf "%s/.claude/harness/%s-%s\\n" "$HOME" "${real##*/}" "$hash"',
145].join('\n')
146
147const readingsAtom = atom({ plugin: 'ctx-relay', key: 'readings' } as const, [] as Reading[])
148const receiptAtom = atom({ plugin: 'ctx-relay', key: 'receipt' } as const, null as Receipt | null)
149const limitsAtom = atom({ plugin: 'ctx-relay', key: 'limits' } as const, null as Limits | null)
150const autoAtom = atom({ plugin: 'ctx-relay', key: 'auto' } as const, { phase: 'idle' } as Auto)
151const cacheAtom = atom({ plugin: 'ctx-relay', key: 'cache' } as const, { lastRequestAt: null, turnStartedAt: null, ttlMs: TTL_1H, ttlSource: 'default', observed: '', keepalives: 0 } as Cache)
152
153// 模組變數:hot reload 會清掉;/clear 不會
154let tick: Timer | null = null
155// band 動畫計時器(startFrames);跟交接倒數的 tick 分開,disarm() 不會停到它
156let frameTimer: Timer | null = null
157// 最近一次讀數時的 frame;進度條拿來決定新增格還亮不亮
158let freshFrame = -FRESH_FRAMES
159let frame = 0
160let fireTimer: Timer | null = null
161let mainTurns = 0
162// 上一次主對話停下(classic.Stop)時引擎回報、會再叫醒這個 session 的工作;給指令用,換 session 就清掉
163let stopWork: string[] = []
164// 上一次切換的結果,撐過 /clear 顯示在新對話的 band;之後你自己 clear 就清掉
165let lastHandoff: { path: string; error?: string } | null = null
166// mod 自己正在執行 /clear(這時的 session.end 不清 lastHandoff)
167let ownClear = false
168// 準備批次編號:每次開始準備或取消都 +1;準備流程每個檢查點都要求編號沒變,
169// 避免「取消 A → /ctx-relay-now 開 B → A 的 fork 回來」時 A 誤用 B 的 preparing 狀態
170let prepGen = 0
171// userConfig handoffTokens(0=自動);改設定會重新載入模組,所以每次 register 讀一次就好
172let handoffTokens = 0
173// userConfig handoffFormat:lite(預設)或 full
174let handoffFormat: Format = 'lite'
175// 待接手的交接檔(撐過 /clear)與 session.start 時算好的 harness root(prompt.submit 比對路徑用,免得每則訊息都跑 bash)
176let pickup: Pickup | null = null
177let pickupRoot = ''
178// 接手後 band 上的「下一步」(取自交接檔的「下一步具體動作」第一行);你一打字就收掉
179let resumeNext = ''
180// /ctx-relay-notes pane 的內容:打開時讀檔整理一次存在這裡,render 只畫(band 每 250ms 重畫,不能每幀讀檔)
181let notes: Notes | null = null
182type NotesView = 'resume' | 'evidence'
183let notesView: NotesView = 'resume'
184const NOTES = 'ctx-relay-notes'
185// 你上一次親手送出訊息的時間(交接失敗紀錄用:失敗時你離開多久)
186let lastTypedAt: number | null = null
187
188export const register: Register = (on, options) => {
189  handoffTokens = typeof options.handoffTokens === 'number' ? options.handoffTokens : 0
190  handoffFormat = options.handoffFormat === 'full' ? 'full' : 'lite'
191
192  // 你手動 /clear 或 session 結束:停掉倒數與進行中的準備(計時器會撐過 clear)
193  on('session.end', async ($, e, next) => {
194    disarm()
195    prepGen += 1
196    stopWork = []
197    if (!ownClear) lastHandoff = null
198    pickup = null
199    // 你手動 /clear:接下來是新對話(session.start 不會再跑),在這裡找待接手的交接檔。
200    // mod 自己的 clear 不找:它接著就送出交接檔路徑
201    if (e.reason === 'clear' && !ownClear) {
202      await scanPickup($)
203      $.ui.invalidate('ui.render')
204    }
205    return next(e)
206  })
207
208  on('session.start', async ($, e, next) => {
209    const result = await next(e)
210    const usage = await $.session.usage({ breakdown: 'summary' })
211    // 第一輪也要有收據:沒有歷史時記一筆起點基準(reload 時歷史還在,不覆蓋)
212    const tokens = usage.context.tokens ?? 0
213    await update($, readingsAtom, list => (list.length > 0 ? list : [{ tokens, costUsd: usage.cost?.usd ?? 0 }]))
214    await update($, limitsAtom, () => deriveLimits(usage.context))
215    await rearm($)
216    pickupRoot = await harnessRoot($)
217    startFrames($)
218    // 還沒有任何訊息=新對話;--resume 接回的舊對話與 hot reload 不找
219    if (await $.session.messages().then(m => m.length === 0, () => false)) {
220      await scanPickup($)
221    }
222    $.ui.invalidate('ui.render')
223    // 名稱衝突會丟例外並中斷本 hook,所以放最後並各自包住
224    for (const [name, description] of [
225      ['ctx-relay-status', 'ctx-relay: thresholds, readings, auto handoff state and background work'],
226      ['ctx-relay-now', 'ctx-relay: write a handoff file now and /clear to resume (add yes when background work runs; text after it is passed on)'],
227      [NOTES, 'ctx-relay: open or close a pane with the latest handoff file and its session progress (INDEX.md)'],
228    ] as const) {
229      try {
230        await $.command.register({ name, description })
231      } catch (err) {
232        $.ui.log(`${TAG} failed to register /${name}: ${String(err)}`)
233      }
234    }
235    return result
236  })
237
238  on('turn.complete', async ($, e, next) => {
239    const result = await next(e)
240    if (e.agentId) {
241      return result
242    }
243    mainTurns += 1
244    await takeReading($, e)
245    // 要不要交接在這裡判斷:Team/Enterprise 登入時內建守門 mod(sec-default)讓 classic.* 跳過使用者裝的 mod,
246    // classic.Stop 永遠不會到這裡;中斷的回合(Esc)不判斷
247    if (!e.isAborted) await afterStop($)
248    $.ui.invalidate('ui.render')
249    return result
250  })
251
252  // 主對話停下時引擎回報的背景工作與排程(shell、monitor、workflow…),給上面的判斷用。
253  // 實測(2.1.296 -p):classic.Stop 在 turn.complete 之前結束;被別的 Stop hook 擋下時回合繼續,真正停下才有 turn.complete。
254  // Team 帳號收不到這個事件,只剩 $.agent.list() 的子代理擋交接
255  on('classic.Stop', async ($, e, next) => {
256    const result = await next(e)
257    if (result.block !== undefined) {
258      return result
259    }
260    stopWork = [
261      ...(e.background_tasks ?? []).map(t => `${t.type} ${t.description}`.slice(0, 80)),
262      // 一次性排程會再叫醒這個 session;循環排程每次都會醒,不擋交接
263      ...(e.session_crons ?? []).filter(c => !c.recurring).map(c => `one-shot schedule ${c.prompt}`.slice(0, 80)),
264    ]
265    return result
266  })
267
268  on('prompt.submit', async ($, e, next) => {
269    // 你親手送出(或遠端轉來你的訊息)=人在場 → 這次倒數或準備作廢、回到 idle,
270    // 這輪結束時還在線上就重新倒數(只延後不停用,使用者 2026-10-08 選 A;要停用按取消鈕)
271    if (e.origin.kind === 'composer' || e.origin.kind === 'bridge') {
272      lastTypedAt = await $.clock.now()
273      if (resumeNext !== '') {
274        resumeNext = ''
275        $.ui.invalidate('ui.render')
276      }
277      const auto = await read($, autoAtom)
278      if (auto.phase === 'countdown' || auto.phase === 'preparing') {
279        disarm()
280        prepGen += 1
281        await setAuto($, { phase: 'idle' })
282        $.ui.invalidate('ui.render')
283        await recordLedger($, { event: 'postponed', manual: false, detail: `you sent a message during ${auto.phase}` })
284      }
285      // 訊息裡帶交接檔完整路徑=你接手了那份(手動貼上的接續指令)
286      if (pickupRoot !== '' && e.text.includes('/handoff/')) {
287        for (const m of e.text.matchAll(handoffPattern(pickupRoot, 'g'))) await markPicked($, m[0])
288      }
289    }
290    return next(e)
291  })
292
293  // 主對話開了新回合(排程、背景通知、別的 session 傳訊;子代理不發 turn.start):
294  // 這次倒數或準備作廢、回到 idle,回合結束時再重新判斷(你親手送出的訊息在上面已先處理)
295  on('turn.start', async ($, e, next) => {
296    const startedAt = await $.clock.now()
297    await update($, cacheAtom, c => ({ ...c, turnStartedAt: startedAt }))
298    // 主對話開始跑(你送出、按接續、排程)=不再是新對話開場,待接手那行收掉
299    if (pickup !== null) {
300      pickup = null
301      $.ui.invalidate('ui.render')
302    }
303    const auto = await read($, autoAtom)
304    if (auto.phase === 'countdown' || auto.phase === 'preparing') {
305      disarm()
306      prepGen += 1
307      await setAuto($, { phase: 'idle' })
308      $.ui.invalidate('ui.render')
309      await recordLedger($, { event: 'postponed', manual: false, detail: `a new turn started during ${auto.phase}` })
310    }
311    return next(e)
312  })
313
314  // 主對話真的壓縮了(/compact、自動、閒置壓縮):舊快取對不上新的對話開頭,倒數作廢,等下一輪結束再算
315  on('session.compact', async ($, e, next) => {
316    const result = await next(e)
317    if (e.agentId === undefined && e.trigger !== 'precompute' && !('skip' in result)) {
318      await update($, cacheAtom, c => ({ ...c, lastRequestAt: null, turnStartedAt: null }))
319      $.ui.invalidate('ui.render')
320    }
321    return result
322  })
323
324  // 只觀察:本 session 已載入 handoff skill(你手動交接)→ 之後不再自動交接
325  on('skill.prompt', { skill: 'handoff' }, async ($, e, next) => {
326    const auto = await read($, autoAtom)
327    if (auto.phase === 'idle' || auto.phase === 'deferred') {
328      await setAuto($, { phase: 'done', detail: 'Handed off manually; auto handoff off for this session' })
329      $.ui.invalidate('ui.render')
330    }
331    return next(e)
332  })
333
334  on('command.run', { command: 'ctx-relay-status' }, async $ => {
335    const limits = await read($, limitsAtom)
336    const auto = await read($, autoAtom)
337    const readings = await read($, readingsAtom)
338    const work = await runningWork($)
339    return {
340      text: [
341        `${TAG} context ${readings.at(-1)?.tokens ?? '?'}; handoff line ${limits?.handoff ?? '?'}${limits ? ` (${sourceLabel(limits.source)})` : ''}; compaction point ${limits?.fuse ?? '?'}; warning line ${limits?.nudge ?? '?'}; deferral cap ${limits?.cap ?? '?'}`,
342        `auto handoff: ${auto.phase}${auto.detail ? ` (${auto.detail})` : ''}`,
343        `background work: ${work.length === 0 ? 'none' : work.join(', ')}`,
344        ...(await cacheStatus($)),
345        `last handoff file: ${lastHandoff ? lastHandoff.path + (lastHandoff.error ? ` (${lastHandoff.error})` : '') : 'none'}`,
346        ...(await failureStatus($)),
347        ...(await ledgerStatus($)),
348      ].join('\n'),
349    }
350  })
351
352  // 你打的指令=asked:任何寬度都畫;再打一次關掉
353  on('command.run', { command: NOTES }, async $ => {
354    if ((await $.ui.panes()).some(p => p.id === NOTES)) {
355      await $.ui.close({ id: NOTES })
356      return { text: `${TAG} closed the notes pane` }
357    }
358    notes = await loadNotes($)
359    notesView = 'resume'
360    await $.ui.open({ id: NOTES, title: 'ctx-relay notes', focus: true })
361    return { text: `${TAG} opened the notes pane` }
362  })
363
364  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
365    if (e.requestId !== NOTES) return next(e)
366    return drawNotes($, e)
367  })
368
369  on('command.run', { command: 'ctx-relay-now' }, async ($, e) => {
370    const auto = await read($, autoAtom)
371    if (auto.phase === 'preparing') {
372      return { text: `${TAG} already writing a handoff file` }
373    }
374    const work = await runningWork($)
375    const { isYes, note } = parseNowArgs(e.args)
376    if (work.length > 0 && !isYes) {
377      return { text: `${TAG} background work still running: ${work.join(', ')}. The handoff runs /clear, so their completion notices may never arrive; to go ahead type /ctx-relay-now yes (text after it is passed on)` }
378    }
379    disarm()
380    await setAuto($, { phase: 'preparing' })
381    $.ui.invalidate('ui.render')
382    const gen = ++prepGen
383    $.clock.after(0, () => void prepare($, gen, true, note))
384    return { text: `${TAG} writing a handoff file; then /clear and resume in the new conversation` }
385  })
386
387  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
388    if (e.props.hasSurvey) {
389      return next(e)
390    }
391    // band 只有一個:先讓排在下面的 mod 畫(例如 blast-radius 在窄終端機把 Proceed/Cancel 畫在這裡),
392    // 自己這行疊在它下面;只回自己的 tree 會把它整個蓋掉
393    const below = await next(e)
394    // 待接手那行獨立畫:/clear 後還沒有讀數時 drawBand 回 null,這行仍要出現
395    const mine = [await drawBand($, e), await drawPickup($, e)].filter((x): x is RenderElement => x !== null)
396    const [only, ...rest] = mine
397    if (only === undefined) return below
398    if (!below && rest.length === 0) return only
399    const { Box } = $.ui.resolve(e)
400    return (
401      <Box flexDirection="column">
402        {below}
403        {mine}
404      </Box>
405    )
406  })
407}
408
409// 沒有東西要畫時回 null
410async function drawBand($: EngineInterface, e: RenderInput<'AbovePrompt'>): Promise<RenderElement | null> {
411  const readings = await read($, readingsAtom)
412  const limits = await read($, limitsAtom)
413  const { Box, Button, Text } = $.ui.resolve(e)
414  if (readings.length === 0 || limits === null) {
415    // /clear 後還沒有讀數:送出失敗時新對話不會自己跑回合,這裡仍要畫出手動接續的指示
416    if (lastHandoff?.error) {
417      return (
418        <Text color={ERR} bold wrap="truncate-end">
419          {` ${SKULL} ${TAG} ${clearedButFailed(lastHandoff)} `}
420        </Text>
421      )
422    }
423    return null
424  }
425  const receipt = await read($, receiptAtom)
426  const auto = await read($, autoAtom)
427  const now = await $.clock.now()
428  const tokens = readings.at(-1)?.tokens ?? 0
429  const columns = e.props.bodyColumns
430
431  if (auto.phase === 'countdown') {
432    const left = Math.max(0, Math.ceil(((auto.deadline ?? now) - now) / 1000))
433    return (
434      <Box flexDirection="row">
435        <Text color={ERR} bold wrap="truncate-end">
436          {` ${SKULL} Handoff in `}
437          <Text color={VALUE}>{`${left}s`}</Text>
438          <Text color={LABEL}>{` · at ${k(limits.handoff)} · send a message to postpone `}</Text>
439        </Text>
440        <Button key="cancel" label="Cancel [1]" hotkey="1" onPress={() => cancel($, 'you pressed Cancel')} />
441      </Box>
442    )
443  }
444
445  let status = ''
446  let statusColor = LABEL
447  if (auto.phase === 'deferred') [status, statusColor] = [`Handoff deferred: ${auto.detail ?? ''}`, WARN]
448  if (auto.phase === 'preparing') [status, statusColor] = ['Writing handoff file…', ERR]
449  if (auto.phase === 'done') status = auto.detail ?? ''
450  if (auto.phase === 'failed') [status, statusColor] = [`Auto handoff failed: ${auto.detail ?? ''}. Hand off manually`, ERR]
451  if (auto.phase === 'cancelled') [status, statusColor] = [`Auto handoff cancelled (${auto.detail ?? ''}; reminders only)`, WARN]
452  if (auto.phase === 'idle' && lastHandoff) {
453    ;[status, statusColor] = lastHandoff.error
454      ? [clearedButFailed(lastHandoff), ERR]
455      : [`Resumed from ${basename(lastHandoff.path)}${resumeNext === '' ? '' : ` · next: ${resumeNext}`} · /${NOTES}`, LABEL]
456  }
457
458  // 圖示與進度條用比例色、標籤灰、數值白
459  const ratio = tokens / Math.max(limits.handoff, 1)
460  const color = mood(tokens, limits)
461  const icon = <Text color={breathe(color)} bold>{` ${INVADER} `}</Text>
462  const cache = await read($, cacheAtom)
463  const isCold = cache.lastRequestAt !== null && cacheLeft(cache, now) <= 0
464  // Raster 只有終端機有(桌面版沒有)
465  const Raster = e.surface === 'terminal' && columns >= BAR_COLUMNS ? $.ui.resolve(e).Raster : null
466  // 文字寬度照字數估(都是單寬字元):長條圖放得下才畫,不再看固定欄數(旁邊開了 dock pane 時 body 會變窄)
467  let width = 3 + (Raster === null ? 0 : BAR_CELLS + 1)
468  const say = (text: string, color: string, bold = false) => {
469    width += text.length
470    return <Text color={color} bold={bold}>{text}</Text>
471  }
472  const sep = () => say(' · ', DOT)
473  const segments = [say(k(tokens), VALUE, true), say(`/${k(limits.handoff)} `, LABEL), say(`${Math.round(ratio * 100)}%`, color)]
474  if (receipt) {
475    segments.push(sep(), say(`${signed(receipt.deltaTokens)} $${receipt.deltaCost.toFixed(2)}`, VALUE, true))
476    segments.push(say(` ${duration(receipt.durationMs)}`, LABEL))
477    // 快取已過期就不再顯示上一輪的命中率,免得一列兩個雪花
478    if (!isCold && receipt.cachePct !== null && receipt.cachePct < CACHE_COLD) {
479      segments.push(say(` ${SNOW} ${receipt.cachePct}%`, SKY))
480    }
481  }
482  if (!e.props.isWorking && cache.lastRequestAt !== null) {
483    const [text, c] = cacheLabel(cache, now)
484    segments.push(sep(), say(text, c))
485  }
486  const tail = status === '' ? 1 : status.length + 4
487  if (readings.length >= 2 && width + 1 + readings.length + tail <= columns) {
488    segments.push(<Text> </Text>, ...spark(readings, limits).map(([ch, c]) => <Text color={c}>{ch}</Text>))
489  }
490  if (status !== '') segments.push(sep(), <Text color={statusColor}>{status}</Text>)
491  segments.push(<Text> </Text>)
492
493  const rest = <Text wrap="truncate-end">{segments}</Text>
494  if (Raster === null) return <Box flexDirection="row">{icon}{rest}</Box>
495  return (
496    <Box flexDirection="row">
497      {icon}
498      <Raster key="bar" columns={BAR_CELLS} rows={1} cells={bar(ratio, receipt ? (tokens - receipt.deltaTokens) / Math.max(limits.handoff, 1) : ratio, color)} />
499      <Text> </Text>
500      {rest}
501    </Box>
502  )
503}
504
505// 待接手那行;沒有待接手的交接檔時回 null
506async function drawPickup($: EngineInterface, e: RenderInput<'AbovePrompt'>): Promise<RenderElement | null> {
507  const p = pickup
508  if (p === null) return null
509  const { Box, Button, Text } = $.ui.resolve(e)
510  const now = await $.clock.now()
511  const segments = [
512    <Text color={OK} bold>{` ${INVADER} `}</Text>,
513    <Text color={LABEL}>{'Pending handoff: '}</Text>,
514    <Text color={VALUE} bold>{p.name}</Text>,
515    <Text color={LABEL}>{` (${ago(now - p.mtimeMs)}${p.from === '' ? '' : `, from ${p.from}`})`}</Text>,
516  ]
517  if (p.more > 0) segments.push(<Text color={WARN} bold>{` +${p.more}`}</Text>)
518  segments.push(<Text> </Text>)
519  return (
520    <Box flexDirection="row">
521      <Text wrap="truncate-end">{segments}</Text>
522      <Button key="pickup" label="Resume [1]" hotkey="1" onPress={() => pickUp($, p)} />
523    </Box>
524  )
525}
526
527// 已 /clear 但接續訊息沒送出去:Type: 後面是要你貼進對話的接續指令,跟交接檔同一種語言
528function clearedButFailed(h: { path: string; error?: string }): string {
529  return `Cleared, but ${h.error ?? ''}. Type: ${handoffFormat === 'full' ? `讀 ${h.path} 並依其接續` : `Read ${h.path} and continue from it`}`
530}
531
532// 壓縮點取引擎回報值;auto-compact 關掉時沒有壓縮點,改以模型窗為基準
533function deriveLimits(context: SessionContextUsage): Limits {
534  const fuse = context.breakdown?.autoCompactThreshold ?? context.window
535  const auto = Math.floor((fuse * HANDOFF_PCT) / 100)
536  // 設定值超過自動上限(例:400K 設定換到 200K 模型)會在交接前先被壓縮,改用自動值
537  const handoff = handoffTokens > 0 ? Math.min(handoffTokens, auto) : auto
538  const source = handoffTokens <= 0 ? 'auto' : handoffTokens <= auto ? 'config' : 'capped'
539  // 背景工作一直不結束時,延後到交接線與壓縮點的中點就強制倒數(使用者 2026-10-04 選 B)
540  const cap = handoff + Math.floor((fuse - handoff) / 2)
541  return { window: context.window, fuse, nudge: Math.floor((handoff * NUDGE_PCT) / 100), handoff, cap, source }
542}
543
544// /ctx-relay-status 的快取行
545async function cacheStatus($: EngineInterface): Promise<string[]> {
546  const cache = await read($, cacheAtom)
547  if (cache.lastRequestAt === null) return ['cache: no request yet']
548  const now = await $.clock.now()
549  const ttl = cache.ttlMs === TTL_1H ? '1h' : '5m'
550  const left = cacheLeft(cache, now)
551  const lines = [`cache: ttl ${ttl} (${cache.ttlSource}, estimated) · last request ${duration(now - cache.lastRequestAt)} ago · ${left <= 0 ? 'cold' : `${cacheLabel(cache, now)[0].replace(/^cache /, '')} left`}`]
552  if (cache.observed !== '') lines.push(`cache note: last turn ${cache.observed}; the TTL may be 5m, or the model, tools or system prompt changed`)
553  return lines
554}
555
556function sourceLabel(source: Limits['source']): string {
557  if (source === 'config') return 'setting handoffTokens'
558  if (source === 'capped') return `setting ${handoffTokens} is above ${HANDOFF_PCT}% of the compaction point; using that instead`
559  return `${HANDOFF_PCT}% of the compaction point`
560}
561
562async function takeReading($: EngineInterface, e: TurnCompleteInput) {
563  const usage = await $.session.usage({ breakdown: 'summary' })
564  const tokens = usage.context.tokens ?? 0
565  const costUsd = usage.cost?.usd ?? 0
566  const readings = await read($, readingsAtom)
567  const prev = readings.at(-1) ?? null
568  if (prev) {
569    const u = e.usage
570    const total = u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : 0
571    await update($, receiptAtom, () => ({
572      deltaTokens: tokens - prev.tokens,
573      deltaCost: costUsd - prev.costUsd,
574      durationMs: e.durationMs,
575      cachePct: u && total > 0 ? Math.round((u.cache_read_input_tokens * 100) / total) : null,
576    }))
577  }
578  await update($, readingsAtom, list => [...list, { tokens, costUsd }].slice(-HISTORY))
579  freshFrame = frame
580  // 快取倒數只是附加資訊:讀不到 env/settings 也不能拖垮讀數與交接判斷
581  // context 比上一輪少一半以上=這輪中間壓縮過(auto-compact)。Team/Enterprise 登入時守門 mod 不讓使用者 mod 收到
582  // session.compact,那邊的重設不會跑;這輪偏冷是壓縮造成的,不能拿來判 TTL
583  const compacted = prev !== null && tokens < prev.tokens / 2
584  await noteCache($, e, compacted).catch(err => $.ui.log(`${TAG} cache countdown skipped: ${String(err)}`))
585  await update($, limitsAtom, () => deriveLimits(usage.context))
586}
587
588// 主線回合結束:記下時間、這段閒置的保溫次數歸零、推定 TTL。
589// 閒置超過 5 分鐘、還沒到推定 TTL,這輪卻偏冷:只記下來給 /ctx-relay-status,不改判 TTL——
590// 換模型、工具或系統提示也會偏冷,分不出是不是 TTL 掉成 5m(例如訂閱超額),改判一次會錯整個 session
591async function noteCache($: EngineInterface, e: TurnCompleteInput, compacted: boolean) {
592  const now = await $.clock.now()
593  const cache = await read($, cacheAtom)
594  const u = e.usage
595  const total = u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : 0
596  const pct = u && total > 0 ? Math.round((u.cache_read_input_tokens * 100) / total) : null
597  const idle = !compacted && cache.lastRequestAt !== null && cache.turnStartedAt !== null ? cache.turnStartedAt - cache.lastRequestAt : null
598  const observed = idle !== null && pct !== null && pct < CACHE_COLD && idle > TTL_5M && idle < cache.ttlMs
599    ? `came back cold (${pct}%) after ${duration(idle)} idle`
600    : ''
601  const ttl = await resolveTtl($)
602  await update($, cacheAtom, () => ({ lastRequestAt: now, turnStartedAt: null, ...ttl, observed, keepalives: 0 }))
603  startFrames($)
604}
605
606// band 動畫,快取倒數也靠它每幀更新。快取冷了=人多半不在(閒置超過 TTL),停下省得整晚每秒重畫 4 次;
607// 下一輪結束再開
608function startFrames($: EngineInterface) {
609  frameTimer?.cancel()
610  frameTimer = $.clock.every(FRAME_MS, () => {
611    void (async () => {
612      const cache = await read($, cacheAtom)
613      if (cache.lastRequestAt !== null && cacheLeft(cache, await $.clock.now()) <= 0) {
614        frameTimer?.cancel()
615        frameTimer = null
616      } else frame += 1
617      $.ui.invalidate('ui.render')
618    })()
619  })
620}
621
622// TTL 依序:FORCE_PROMPT_CACHING_5M → CLAUDE_CODE_PROMPT_CACHE_TTL → 設定 promptCacheTtl → ENABLE_PROMPT_CACHING_1H →
623// 有 rateLimits(訂閱)1h、沒有 5m。rateLimits 取自上一次 API 回應,所以只在回合結束後判斷
624async function resolveTtl($: EngineInterface): Promise<{ ttlMs: number; ttlSource: string }> {
625  const ttlOf = (v: unknown) => (v === '5m' ? TTL_5M : v === '1h' ? TTL_1H : null)
626  const isOn = (v: string | undefined) => v !== undefined && v !== '' && v !== '0'
627  if (isOn(await $.env.get('FORCE_PROMPT_CACHING_5M'))) return { ttlMs: TTL_5M, ttlSource: 'FORCE_PROMPT_CACHING_5M' }
628  const fromEnv = ttlOf(await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'))
629  if (fromEnv !== null) return { ttlMs: fromEnv, ttlSource: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
630  const fromSetting = ttlOf((await $.settings.read().catch(() => ({} as Record<string, unknown>))).promptCacheTtl)
631  if (fromSetting !== null) return { ttlMs: fromSetting, ttlSource: 'promptCacheTtl setting' }
632  if (isOn(await $.env.get('ENABLE_PROMPT_CACHING_1H'))) return { ttlMs: TTL_1H, ttlSource: 'ENABLE_PROMPT_CACHING_1H' }
633  const usage = await $.session.usage()
634  return usage.rateLimits.length > 0 ? { ttlMs: TTL_1H, ttlSource: 'subscription' } : { ttlMs: TTL_5M, ttlSource: 'no subscription' }
635}
636
637// 剩餘時間=TTL −(現在 − 上一次請求)
638function cacheLeft(cache: Cache, now: number): number {
639  return cache.lastRequestAt === null ? 0 : cache.ttlMs - (now - cache.lastRequestAt)
640}
641
642// ≥1 分鐘以分計、<1 分鐘以秒計、到了就是雪花 cold
643function cacheLabel(cache: Cache, now: number): [string, string] {
644  const left = cacheLeft(cache, now)
645  if (left <= 0) return [`${SNOW} cold`, SKY]
646  const text = left < 60_000 ? `cache ${Math.ceil(left / 1000)}s` : `cache ${Math.floor(left / 60_000)}m`
647  return [text, left <= CACHE_SOON_MS ? WARN : LABEL]
648}
649
650async function afterStop($: EngineInterface) {
651  const auto = await read($, autoAtom)
652  const limits = await read($, limitsAtom)
653  if ((auto.phase !== 'idle' && auto.phase !== 'deferred') || limits === null) {
654    return
655  }
656  // 讀當下的 token 數(不要 breakdown,免費)
657  const tokens = (await $.session.usage()).context.tokens ?? 0
658  if (tokens < limits.handoff) {
659    return
660  }
661  // 還有背景工作就先不交接:它結束時的通知會再跑一個主線回合,到時再判斷;
662  // 到上限還沒結束就照樣倒數(交接檔會寫明還在跑的工作),免得滑到壓縮點被原生摘要取代
663  const work = await runningWork($)
664  if (work.length > 0 && tokens < limits.cap) {
665    await setAuto($, { phase: 'deferred', detail: `${work.length} background task${work.length === 1 ? '' : 's'} still running (forced at ${k(limits.cap)}; /ctx-relay-now yes hands off now)` })
666    return
667  }
668  const now = await $.clock.now()
669  await setAuto($, { phase: 'countdown', deadline: now + COUNTDOWN_MS })
670  arm($, COUNTDOWN_MS)
671  await recordLedger($, { event: 'countdown', manual: false })
672}
673
674// 在跑的子代理+上一次 Stop 時引擎回報的背景工作與一次性排程。不設逾時作廢(使用者 2026-10-03 選 B):
675// 常駐 server 會一直延後,band 顯示原因,要交接就用 /ctx-relay-now yes
676async function runningWork($: EngineInterface): Promise<string[]> {
677  let agents: string[] = []
678  try {
679    agents = (await $.agent.list()).filter(a => a.status === 'running').map(a => `subagent ${a.description || a.id}`)
680  } catch (err) {
681    // 查不到就當作可能有工作在跑(寧可延後,/ctx-relay-now yes 可強制)
682    agents = [`cannot list subagents (${String(err).slice(0, 80)})`]
683  }
684  return [...agents, ...stopWork]
685}
686
687function arm($: EngineInterface, ms: number) {
688  disarm()
689  tick = $.clock.every(1000, () => $.ui.invalidate('ui.render'))
690  fireTimer = $.clock.after(Math.max(0, ms), () => {
691    void fire($)
692  })
693}
694
695function disarm() {
696  tick?.cancel()
697  fireTimer?.cancel()
698  tick = null
699  fireTimer = null
700}
701
702// hot reload 後:倒數中就依剩餘時間重新掛計時器;準備到一半被 reload 中斷 → 記失敗,不自動重來
703async function rearm($: EngineInterface) {
704  const auto = await read($, autoAtom)
705  if (auto.phase === 'preparing') {
706    await setAuto($, { phase: 'failed', detail: 'a reload interrupted the handoff' })
707    return
708  }
709  if (auto.phase !== 'countdown') {
710    return
711  }
712  const now = await $.clock.now()
713  arm($, (auto.deadline ?? now) - now)
714}
715
716async function cancel($: EngineInterface, why: string) {
717  disarm()
718  prepGen += 1
719  await setAuto($, { phase: 'cancelled', detail: why })
720  $.ui.invalidate('ui.render')
721  await recordLedger($, { event: 'cancelled', manual: false, detail: why })
722}
723
724async function fire($: EngineInterface) {
725  disarm()
726  // 同一次 update 裡確認仍在倒數才取得準備權(期間你可能已取消)
727  const after = await update($, autoAtom, (a): Auto => (a.phase === 'countdown' ? { phase: 'preparing' } : a))
728  $.ui.invalidate('ui.render')
729  if (after.phase === 'preparing') {
730    await prepare($, ++prepGen, false, '')
731  }
732}
733
734// 收集 → fork → 檢查 → 寫檔讀回 → 確認來源沒變 → /clear → 送出。
735// /clear 之前任何一步失敗都留在原對話;/clear 之後失敗只能顯示交接檔路徑讓你手動接續。
736// isManual=你打 /ctx-relay-now 觸發:fork 指示、檔頭、接續訊息都寫「手動交接」,不寫「越過自動交接線」
737// note=你打 /ctx-relay-now 時附的最新指令(原話):交給 fork 寫 GOAL/NEXT,並原樣寫進檔頭與接續訊息
738async function prepare($: EngineInterface, gen: number, isManual: boolean, note: string) {
739  // 仍是本批次、而且仍在準備中(期間被取消、手動 clear 或另開一批都算不是)
740  // 先等狀態讀回來再比批次編號:比完才 await 的話,等待期間被取消又另開一批就會漏判
741  const isMine = async () => {
742    const phase = (await read($, autoAtom)).phase
743    return gen === prepGen && phase === 'preparing'
744  }
745  const fail = async (detail: string) => {
746    if (await isMine()) {
747      await setAuto($, { phase: 'failed', detail })
748      await recordFailure($, detail, isManual)
749    }
750    $.ui.invalidate('ui.render')
751  }
752  try {
753    if (!(await isMine())) return
754    const source = { id: await $.session.id(), turns: mainTurns }
755    const cwd = await $.session.cwd()
756    const root = await harnessRoot($)
757    if (root === '') return await fail('cannot locate the harness root')
758
759    const git = await gitTruth($, cwd)
760    if (git === null) return await fail('cannot read git state (git failed, and this is not a non-git directory)')
761    const format = handoffFormat
762    const isFull = format === 'full'
763    const index = isFull ? await readOr($, `${root}/progress/${source.id}/INDEX.md`, '') : ''
764    const sourceHandoff = isFull ? await findSourceHandoff($, root) : null
765    const contract = sourceHandoff ? section(await readOr($, sourceHandoff, ''), CONTRACT) : ''
766    const readings = await read($, readingsAtom)
767    const limits = await read($, limitsAtom)
768    const tokens = readings.at(-1)?.tokens ?? 0
769    // 強制交接(延後到上限、/ctx-relay-now yes)時還在跑的工作:寫進檔頭,新對話才知道有通知會收不到
770    const work = await runningWork($)
771
772    const r = await Promise.race([
773      $.model.fork({ prompt: isFull ? forkPrompt({ tokens, limits, git, index, contract, isManual, note }) : liteForkPrompt({ tokens, limits, git, isManual, note }) }),
774      $.clock.sleep(FORK_TIMEOUT_MS).then(() => null),
775    ])
776    if (r === null) return await fail(`handoff fork timed out (${FORK_TIMEOUT_MS / 60_000} min)`)
777    if (!r.isAnswered) return await fail(`handoff fork failed: ${r.reason}`)
778    if (!(await isMine())) return
779
780    const split = splitSlug(r.text)
781    const slug = split.slug
782    const slots = parseSlots(split.body)
783    if (!slotsOf(format).some(([key]) => slots.has(key))) return await fail('the fork output has no recognised "=== KEY ===" section markers')
784    // 協調契約由 mod 原樣附上,不經模型:fork 寫的 CONTRACT 分段與內文裡的「## 協調契約」段都丟掉
785    const body = assemble(slots, contract, format)
786    const thin = checkThin(body, format)
787    // 精簡版把不認得的分段併進 Next:Next 有沒有缺,看 fork 原本有沒有寫 NEXT,不看併完的結果
788    if (format === 'lite' && (slots.get('NEXT') ?? '').trim() === '' && !thin.includes('Next')) thin.push('Next')
789    const stamp = formatStamp(await $.clock.now())
790    const dir = `${root}/handoff`
791    // 檔名帶來源 session 與批次編號:同一秒、同 slug 的兩批(或共用 git-common-dir 的兩個 session)不會互相覆寫
792    const path = `${dir}/${stamp}-${slug}-${source.id.slice(0, 8)}-${gen}.md`
793    const how = `- how: ${isManual ? 'manual' : 'auto'}`
794    const header = (isFull
795      ? [
796          pickupText(format, path),
797          `- 時間戳:${stamp}`,
798          ...(git.head !== '' ? [`- HEAD:\`${git.head}\``] : []),
799          `- task slug:${slug}`,
800          `- 來源:branch \`${git.branch || '(非 git)'}\` · cwd \`${cwd}\` · 前一個 session \`${source.id}\`(ctx ≈${k(tokens)},由 ctx-relay mod ${isManual ? '依 /ctx-relay-now 手動交接' : '自動交接'})`,
801          how,
802          '- unattended: true',
803          '- producer: ctx-relay-mod',
804          ...(work.length > 0 ? [`- 交接時仍在跑(完成通知可能收不到):${work.join('、')}`] : []),
805          ...(thin.length > 0 ? [`- thin: ${thin.join('、')}`] : []),
806          ...(note !== '' ? ['- 使用者交接時附的最新指令(原話):', quote(note)] : []),
807        ]
808      : [
809          pickupText(format, path),
810          `- time: ${stamp}`,
811          ...(git.head !== '' ? [`- head: \`${git.head}\``] : []),
812          `- task slug: ${slug}`,
813          `- source: branch \`${git.branch || '(not git)'}\` · cwd \`${cwd}\` · previous session \`${source.id}\` (ctx ≈${k(tokens)}, ${isManual ? 'manual handoff via /ctx-relay-now' : 'auto handoff'} by the ctx-relay mod)`,
814          how,
815          '- unattended: true',
816          '- producer: ctx-relay-mod',
817          ...(work.length > 0 ? [`- still running at handoff (completion notices may not arrive): ${work.join(', ')}`] : []),
818          ...(thin.length > 0 ? [`- thin: ${thin.join(', ')}`] : []),
819          ...(note !== '' ? ["- the user's latest instruction at handoff (verbatim):", quote(note)] : []),
820        ]
821    ).join('\n')
822    const content = `${header}\n\n${body.trim()}\n`
823
824    const mk = await $.process.run(['mkdir', '-p', dir])
825    if (mk.exitCode !== 0) return await fail(`failed to create ${dir}`)
826    await $.fs.write(path, content)
827    const back = await readOr($, path, '')
828    if (!back.startsWith(pickupText(format, path)) || fieldsOf(format).some(f => !hasHeading(back, f))) return await fail(`handoff file read-back incomplete: ${path}`)
829
830    // 準備期間你送了訊息、手動 clear 或又跑了一輪 → 交接檔已過時,作廢切換(檔案留著)
831    const currentId = await $.session.id()
832    if (!(await isMine())) return
833    if (currentId !== source.id || mainTurns !== source.turns) {
834      return await fail(`the conversation changed while preparing; switch dropped (handoff file kept at ${path})`)
835    }
836
837    disarm()
838    lastHandoff = { path }
839    // clear 前就記已接手:新對話開場不會先閃一行「待接手」;送出失敗時 band 另有手動接續的提示
840    await markPicked($, path)
841    ownClear = true
842    try {
843      await $.command.run({ command: 'clear' })
844    } catch (err) {
845      // clear 途中 session.end 可能已改了批次編號,這裡不經 isMine,直接記失敗
846      lastHandoff = null
847      await setAuto($, { phase: 'failed', detail: `/clear failed: ${String(err)} (handoff file at ${path})` })
848      $.ui.invalidate('ui.render')
849      await recordLedger($, { event: 'failed', session: source.id, tokens, manual: isManual, detail: `/clear failed: ${String(err)}` })
850      return
851    } finally {
852      ownClear = false
853    }
854    // 實際引擎在 /clear 後會把 $.state 歸零;這裡再明確設回 idle,新對話才能再次自動交接
855    await setAuto($, { phase: 'idle' })
856    try {
857      const sent = await $.prompt.submit({ text: resumeText(format, path, slug, isManual, note, thin.includes('硬約束'), git.head) })
858      if (sent.drop !== undefined) lastHandoff = { path, error: `the resume message was blocked: ${sent.drop}` }
859      else {
860        resumeNext = firstLine(part(content, 'NEXT'))
861        // 交接後是 notes 唯一獨有價值的時刻(新對話沒有歷史,官方 recap 沒東西可總結):自動開一次,不搶輸入框焦點。
862        // 太窄放不下或開不了就退回 toast 提示;開 pane 只是顯示,失敗不影響交接
863        notes = await loadNotes($)
864        notesView = 'resume'
865        const shown = await $.ui.open({ id: NOTES, title: 'ctx-relay notes' }).then(o => o.isPlaced, () => false)
866        $.ui.toast(shown ? `${TAG} handed off to a new conversation; the notes pane shows the handoff (q closes)` : `${TAG} handed off to a new conversation; /${NOTES} shows the handoff file and progress`, { timeoutMs: 8000 })
867      }
868    } catch (err) {
869      lastHandoff = { path, error: `the resume message failed: ${String(err)}` }
870    }
871    const u = r.usage
872    await recordLedger($, {
873      event: 'handed-off',
874      session: source.id,
875      tokens,
876      manual: isManual,
877      fork: { input: u.input_tokens, cacheRead: u.cache_read_input_tokens, cacheWrite: u.cache_creation_input_tokens, output: u.output_tokens },
878      resumed: lastHandoff?.error === undefined,
879    })
880    $.ui.invalidate('ui.render')
881  } catch (err) {
882    await fail(`unexpected error: ${String(err)}`)
883  }
884}
885
886type Git = { branch: string; head: string; status: string; stat: string; log: string }
887
888// 非 git 目錄回傳空欄位(handoff skill 支援非 git);其他任何 git 失敗回 null,交接要停下
889async function gitTruth($: EngineInterface, cwd: string): Promise<Git | null> {
890  const run = async (args: string[]) => {
891    try {
892      const r = await $.process.run(['git', '-C', cwd, ...args])
893      // 只去尾端:git status --short 開頭的空白有意義(" M" 與 "M " 不同)
894      return { ok: r.exitCode === 0, out: r.stdout.trimEnd(), err: r.stderr }
895    } catch (err) {
896      return { ok: false, out: '', err: String(err) }
897    }
898  }
899  const branch = await run(['rev-parse', '--abbrev-ref', 'HEAD'])
900  if (!branch.ok) {
901    return /not a git repository/i.test(branch.err) ? { branch: '', head: '', status: '', stat: '', log: '' } : null
902  }
903  const status = await run(['status', '--short'])
904  const stat = await run(['diff', '--stat'])
905  const log = await run(['log', '--oneline', '-6'])
906  if (!status.ok || !stat.ok || !log.ok) return null
907  // 寫進檔頭,接手方用 git log <head>..HEAD 看交接後有沒有新 commit。取不到就不寫
908  // (還沒有 commit 的 repo 走不到這裡:上面的 rev-parse --abbrev-ref 就會失敗,整次交接記失敗)
909  const head = await run(['rev-parse', '--short', 'HEAD'])
910  return { branch: branch.out, head: head.ok ? head.out : '', status: status.out, stat: stat.out, log: log.out }
911}
912
913// 交接失敗紀錄:<harness root>/ctx-relay/failures.jsonl,一次一行,只留最近 FAILURES_KEPT 筆。
914// 目前沒有失敗的持久紀錄,不知道多久失敗一次;先記下來,再決定要不要做 fork 失敗時的降級交接(使用者 2026-10-08 選 B)
915const FAILURES_KEPT = 100
916type Failure = { at: string; session: string; manual: boolean; tokens: number; idleMin: number | null; detail: string }
917
918async function recordFailure($: EngineInterface, detail: string, isManual: boolean) {
919  try {
920    const root = await harnessRoot($)
921    if (root === '') return $.ui.log(`${TAG} handoff failed but the harness root is unknown; failure not recorded: ${detail}`)
922    const now = await $.clock.now()
923    const entry: Failure = {
924      at: new Date(now).toISOString(),
925      session: await $.session.id(),
926      manual: isManual,
927      tokens: (await read($, readingsAtom)).at(-1)?.tokens ?? 0,
928      idleMin: lastTypedAt === null ? null : Math.round((now - lastTypedAt) / 60_000),
929      detail,
930    }
931    const dir = `${root}/ctx-relay`
932    const path = `${dir}/failures.jsonl`
933    const mk = await $.process.run(['mkdir', '-p', dir])
934    if (mk.exitCode !== 0) return $.ui.log(`${TAG} failed to create ${dir}; failure not recorded: ${detail}`)
935    const lines = (await readOr($, path, '')).split('\n').filter(l => l.trim() !== '')
936    await $.fs.write(path, [...lines, JSON.stringify(entry)].slice(-FAILURES_KEPT).join('\n') + '\n')
937  } catch (err) {
938    $.ui.log(`${TAG} failed to record a handoff failure: ${String(err)}`)
939  }
940  await recordLedger($, { event: 'failed', manual: isManual, detail })
941}
942
943// /ctx-relay-status 的失敗段:筆數+最近 3 筆(新的在前)
944async function failureStatus($: EngineInterface): Promise<string[]> {
945  const root = await harnessRoot($)
946  if (root === '') return []
947  const lines = (await readOr($, `${root}/ctx-relay/failures.jsonl`, '')).split('\n').filter(l => l.trim() !== '')
948  if (lines.length === 0) return ['handoff failures: none recorded']
949  const recent = lines.slice(-3).reverse().map(l => {
950    try {
951      const f = JSON.parse(l) as Failure
952      return `  ${f.at} ${f.manual ? 'manual' : 'auto'} ctx ${k(f.tokens)}${f.idleMin === null ? '' : `, idle ${f.idleMin}m`}: ${f.detail}`
953    } catch {
954      return `  (unreadable line) ${l.slice(0, 80)}`
955    }
956  })
957  return [`handoff failures: ${lines.length} recorded (${root}/ctx-relay/failures.jsonl)`, ...recent]
958}
959
960// 交接帳本:<harness root>/ctx-relay/handoffs.jsonl,記每次倒數、取消、延後、交接完成、失敗。
961// failures.jsonl 只有失敗、沒有分母,判斷不了自動交接值不值得(council 2026-10-25 待答 2);先記,再決定要不要簡化成手動
962const LEDGER_KEPT = 500
963type LedgerEntry = {
964  at: string
965  session: string
966  event: 'countdown' | 'cancelled' | 'postponed' | 'handed-off' | 'failed'
967  manual: boolean
968  tokens: number
969  // handed-off:fork 的用量(cache_read 接近 0=整段前綴重付),接續訊息有沒有送出
970  fork?: { input: number; cacheRead: number; cacheWrite: number; output: number }
971  resumed?: boolean
972  detail?: string
973}
974
975// /clear 之後 $.state 歸零、session id 換新:交接完成那筆由呼叫端帶來源 session 與交接前的 tokens
976async function recordLedger($: EngineInterface, entry: Omit<LedgerEntry, 'at' | 'session' | 'tokens'> & { session?: string; tokens?: number }) {
977  try {
978    const root = await harnessRoot($)
979    if (root === '') return $.ui.log(`${TAG} harness root unknown; handoff ledger not written: ${entry.event}`)
980    const full: LedgerEntry = {
981      at: new Date(await $.clock.now()).toISOString(),
982      session: await $.session.id(),
983      tokens: (await read($, readingsAtom)).at(-1)?.tokens ?? 0,
984      ...entry,
985    }
986    const dir = `${root}/ctx-relay`
987    const path = `${dir}/handoffs.jsonl`
988    const mk = await $.process.run(['mkdir', '-p', dir])
989    if (mk.exitCode !== 0) return $.ui.log(`${TAG} failed to create ${dir}; handoff ledger not written: ${entry.event}`)
990    const lines = (await readOr($, path, '')).split('\n').filter(l => l.trim() !== '')
991    await $.fs.write(path, [...lines, JSON.stringify(full)].slice(-LEDGER_KEPT).join('\n') + '\n')
992  } catch (err) {
993    // 帳本只是統計,寫不進去不能擋交接;記 log 就好
994    $.ui.log(`${TAG} failed to write the handoff ledger: ${String(err)}`)
995  }
996}
997
998// /ctx-relay-status 的帳本行:各事件筆數
999async function ledgerStatus($: EngineInterface): Promise<string[]> {
1000  const root = await harnessRoot($)
1001  if (root === '') return []
1002  const path = `${root}/ctx-relay/handoffs.jsonl`
1003  const lines = (await readOr($, path, '')).split('\n').filter(l => l.trim() !== '')
1004  if (lines.length === 0) return ['handoff ledger: none recorded']
1005  const n: Record<string, number> = {}
1006  let manual = 0
1007  for (const l of lines) {
1008    try {
1009      const e = JSON.parse(l) as LedgerEntry
1010      n[e.event] = (n[e.event] ?? 0) + 1
1011      if (e.event === 'handed-off' && e.manual) manual += 1
1012    } catch {
1013      n.unreadable = (n.unreadable ?? 0) + 1
1014    }
1015  }
1016  const since = /"at":"([^"]+)"/.exec(lines[0] ?? '')?.[1] ?? '?'
1017  const handed = n['handed-off'] ?? 0
1018  return [
1019    `handoff ledger since ${since}: ${n.countdown ?? 0} countdowns, ${n.cancelled ?? 0} cancelled, ${n.postponed ?? 0} postponed, ${handed} handed off (${manual} manual), ${n.failed ?? 0} failed${n.unreadable ? `, ${n.unreadable} unreadable` : ''} (${path})`,
1020  ]
1021}
1022
1023// notes pane:這次接手的交接檔(沒有就拿 handoff/ 裡最新一份)整理成總覽卡,加上檔頭來源 session 的 INDEX.md 進度。
1024// 先給結論、原文不進這頁(使用者 2026-10-08:原文直接塞進 pane 沒人想看,選 B 先做總覽頁+r/q)
1025type Notes =
1026  | { kind: 'none'; reason: string }
1027  | {
1028      kind: 'file'
1029      path: string
1030      name: string
1031      mtimeMs: number
1032      from: string
1033      branch: string
1034      how: string
1035      thin: string
1036      next: string[]
1037      moreNext: number
1038      goal: string
1039      verified: string
1040      gaps: string
1041      raw: string[]
1042      dont: string[]
1043      task: string
1044      phase: string
1045      files: number
1046      dirty: string
1047    }
1048
1049async function loadNotes($: EngineInterface): Promise<Notes> {
1050  const root = await harnessRoot($)
1051  if (root === '') return { kind: 'none', reason: 'Cannot locate the harness root.' }
1052  const dir = `${root}/handoff`
1053  const list = (await $.fs.exists(dir)) ? (await $.fs.list(dir)).filter(f => f.kind === 'file' && f.name.endsWith('.md')) : []
1054  const want = lastHandoff ? basename(lastHandoff.path) : ''
1055  const file = list.find(f => f.name === want) ?? list.sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
1056  if (file === undefined) return { kind: 'none', reason: 'No handoff file yet.' }
1057  const path = `${dir}/${file.name}`
1058  const text = await readOr($, path, '')
1059  const session = /session `([^`\s]+)`/.exec(text)?.[1] ?? ''
1060  const index = session === '' ? '' : await readOr($, `${root}/progress/${session}/INDEX.md`, '')
1061  const items = (key: string) => part(text, key).split('\n').map(l => l.trim()).filter(l => l !== '' && !l.startsWith('```'))
1062  const bullet = (l: string) => l.replace(/^(?:[-*]|\d+[.)])\s+/, '')
1063  // 下一步:有清單就取最外層清單項(略過說明行),沒有清單就整段每行一項;子項併進上一項
1064  const nextTop = outline(part(text, 'NEXT'))
1065  const listed = nextTop.filter(t => t.isList)
1066  const next = (listed.length > 0 ? listed : nextTop).map(t => t.text)
1067  const check = outline(part(text, 'VERIFIED')).map(t => t.text)
1068  const after = (re: RegExp) => check.filter(l => re.test(l)).map(l => l.replace(/^[^::]*[::]\s*/, '')).join(' · ')
1069  const stop = /stop_status:\s*(.+)/.exec(part(text, 'CONSTRAINTS'))?.[1] ?? ''
1070  // 檔頭的 how 行(新檔)優先;舊檔才看中文字樣
1071  const how = /^- how: (auto|manual)$/m.exec(text)?.[1]
1072  return {
1073    kind: 'file',
1074    path,
1075    name: file.name.replace(/\.md$/, ''),
1076    mtimeMs: file.mtimeMs,
1077    from: session.slice(0, 8),
1078    branch: /branch[::]?\s*`?([^`((\s·]+)/.exec(text)?.[1] ?? '',
1079    how: how !== undefined ? `${how} handoff` : /手動交接/.test(text) ? 'manual handoff' : /自動交接/.test(text) ? 'auto handoff' : 'handoff skill',
1080    thin: /^- thin: (.+)$/m.exec(text)?.[1] ?? '',
1081    next: next.slice(0, 3),
1082    moreNext: Math.max(0, next.length - 3),
1083    goal: bullet(items('GOAL')[0] ?? ''),
1084    verified: after(/^(?:已驗證|verified|done)/i),
1085    gaps: after(/^(?:缺口|驗證缺口|未驗證|gaps?|not verified|unverified)/i),
1086    raw: check.slice(0, 2),
1087    dont: stop.split(/[;;]/).map(x => x.trim()).filter(x => x !== ''),
1088    task: /^#\s+(.+)$/m.exec(index)?.[1] ?? '',
1089    phase: /^phase:\s*(.+)$/m.exec(index)?.[1] ?? '',
1090    files: (l => l.filter(t => t.isList).length || l.length)(outline(part(text, 'FILES'))),
1091    dirty: bullet(items('DIRTY')[0] ?? ''),
1092  }
1093}
1094
1095// 總覽卡(2026-10-09 TUI 競品研究+codex/agy 互評定稿,scratchpad tui-ux/design.md):
1096// 一個強調色+灰階,語意色只染符號;順序 NEXT → DON'T → GAPS → 背景;DONE 原文與來源放 evidence 頁
1097async function drawNotes($: EngineInterface, e: RenderInput<'Pane'>): Promise<RenderElement> {
1098  const { Box, Button, Text } = $.ui.resolve(e)
1099  const n = notes
1100  const close = <Button key="close" plain hotkey="q" label="close" onPress={() => $.ui.close({ id: NOTES })} />
1101  if (n === null || n.kind === 'none') {
1102    return (
1103      <Box flexDirection="column" backgroundColor={N.PANE} paddingX={1} paddingY={1}>
1104        <Text color={N.TEXT}>{n?.reason ?? 'Not loaded.'}</Text>
1105        <Box marginTop={1}>{close}</Box>
1106      </Box>
1107    )
1108  }
1109  const now = await $.clock.now()
1110  // 區塊標題:符號染語意色、標籤亮白、數字前置,細線吃剩下的寬(扣 pane 左右 padding;不夠 3 格就不畫)
1111  const head = (key: string, sym: string, symColor: string, label: string, count?: number) => {
1112    const title = `${sym} ${count === undefined ? '' : `${count} `}${label} `
1113    const fill = e.props.bodyColumns - 2 - title.length
1114    return (
1115      <Box key={key} flexDirection="row" marginTop={1}>
1116        <Text color={symColor} bold>{`${sym} `}</Text>
1117        <Text color={N.TITLE} bold>{`${count === undefined ? '' : `${count} `}${label}`}</Text>
1118        {fill >= 3 ? <Text color={N.RULE}>{` ${'─'.repeat(fill)}`}</Text> : <Text>{''}</Text>}
1119      </Box>
1120    )
1121  }
1122  const para = (key: string, text: string, color = N.TEXT) => (
1123    <Box key={key} paddingLeft={2}><Text color={color} wrap="wrap">{text}</Text></Box>
1124  )
1125  const field = (key: string, label: string, text: string) => (
1126    <Box key={key} flexDirection="row">
1127      <Box width={9} flexShrink={0}><Text color={N.MUTED}>{label}</Text></Box>
1128      <Box flexGrow={1} flexShrink={1}><Text color={N.TEXT} wrap="wrap">{text}</Text></Box>
1129    </Box>
1130  )
1131  const tab = (view: NotesView, hotkey: string, label: string) => (
1132    <Box key={`tab-${view}`} backgroundColor={notesView === view ? N.CARD : undefined} paddingX={1}>
1133      <Button key={`view-${view}`} plain hotkey={hotkey} label={label} dimColor={notesView !== view} onPress={() => showNotes($, view)} />
1134    </Box>
1135  )
1136  const meta = [n.from === '' ? '' : `from ${n.from}`, n.how, n.thin === '' ? '' : `thin: ${n.thin}`].filter(x => x !== '').join(' · ')
1137  const body: RenderElement[] = [
1138    <Box key="title" flexDirection="row" backgroundColor={N.CARD} paddingX={1}>
1139      <Text color={N.TITLE} bold wrap="truncate-end">{n.branch === '' ? n.name : n.branch}</Text>
1140      <Box flexGrow={1} />
1141      <Text color={N.MUTED}>{`  ${ago(now - n.mtimeMs)}`}</Text>
1142    </Box>,
1143    <Box key="meta" paddingX={1}><Text color={N.MUTED} wrap="truncate-end">{meta}</Text></Box>,
1144    <Box key="tabs" flexDirection="row" marginTop={1}>
1145      {tab('resume', 's', 'status')}
1146      {tab('evidence', 'v', 'evidence')}
1147      <Box flexGrow={1} />
1148      {close}
1149    </Box>,
1150  ]
1151  if (notesView === 'resume') {
1152    body.push(head('next-h', '▶', N.ACCENT, 'NEXT', n.next.length + n.moreNext))
1153    if (n.next.length === 0) body.push(para('next-none', 'No next step written; read the gaps and goal first.', N.MUTED))
1154    n.next.forEach((t, i) => body.push(
1155      <Box key={`next-${i}`} flexDirection="row">
1156        <Box width={2} flexShrink={0}><Text color={N.ACCENT}>{'▌'}</Text></Box>
1157        <Box width={3} flexShrink={0}><Text color={N.ACCENT} bold>{`${i + 1}.`}</Text></Box>
1158        <Box flexGrow={1} flexShrink={1}><Text color={i === 0 ? N.TITLE : N.TEXT} bold={i === 0} wrap="wrap">{t}</Text></Box>
1159      </Box>,
1160    ))
1161    if (n.moreNext > 0) body.push(<Box key="next-more" paddingLeft={5}><Text color={N.MUTED} wrap="wrap">{`+${n.moreNext} more in the handoff file (path on evidence)`}</Text></Box>)
1162    if (n.dont.length > 0) {
1163      body.push(head('dont-h', '✗', N.DANGER, "DON'T", n.dont.length))
1164      body.push(
1165        <Box key="dont" paddingLeft={2}>
1166          <Text wrap="wrap">{n.dont.flatMap((d, i) => [
1167            ...(i > 0 ? [<Text key={`ds-${i}`} color={N.MUTED}>{' · '}</Text>] : []),
1168            <Text key={`d-${i}`} color={N.TEXT}>{d}</Text>,
1169          ])}</Text>
1170        </Box>,
1171      )
1172    }
1173    body.push(head('gap-h', '▲', N.WARNING, 'GAPS'))
1174    body.push(n.gaps === '' ? para('gap', 'None recorded.', N.MUTED) : para('gap', n.gaps))
1175    body.push(<Box key="ctx-gap" marginTop={1} />)
1176    if (n.goal !== '') body.push(field('goal', 'goal', n.goal))
1177    if (n.task !== '' || n.phase !== '') body.push(field('phase', 'phase', [n.phase, n.task === '' ? '' : `(${n.task})`].filter(x => x !== '').join(' ')))
1178    body.push(field('files', 'files', `${n.files} listed in the handoff${n.dirty === '' ? '' : ` · dirty: ${n.dirty}`}`))
1179  } else {
1180    body.push(head('ok-h', '✓', N.SUCCESS, 'VERIFIED'))
1181    if (n.verified !== '') body.push(para('ok', n.verified))
1182    else if (n.raw.length > 0) {
1183      body.push(para('raw-h', 'Check notes (not classified):', N.MUTED))
1184      n.raw.forEach((t, i) => body.push(para(`raw-${i}`, t)))
1185    } else body.push(para('ok', 'No verified items recorded.', N.MUTED))
1186    body.push(head('src-h', '·', N.MUTED, 'SOURCE'))
1187    body.push(field('src-file', 'file', `${n.name}.md`))
1188    body.push(field('src-path', 'path', n.path))
1189    if (n.from !== '') body.push(field('src-from', 'session', n.from))
1190    body.push(field('src-how', 'how', n.how))
1191    if (n.dirty !== '') body.push(field('src-dirty', 'dirty', n.dirty))
1192  }
1193  return <Box flexDirection="column" backgroundColor={N.PANE} paddingX={1} paddingY={1}>{body}</Box>
1194}
1195
1196// 切分頁:換頁、重畫、捲回頂端(同一個 pane 共用捲動位置,不回頂會停在上一頁的位置)。
1197// 捲不動不影響換頁;測試環境沒有 ui.scroll 的實作會丟錯,所以吞掉
1198async function showNotes($: EngineInterface, view: NotesView) {
1199  notesView = view
1200  $.ui.invalidate('ui.render')
types/index.d.ts 34 lines
1// 一筆主線回合結束時的讀數
2export type Reading = { tokens: number; costUsd: number }
3
4// 上一個主線回合的收據
5export type Receipt = { deltaTokens: number; deltaCost: number; durationMs: number; cachePct: number | null }
6
7// 門檻(token 數):fuse=引擎回報的壓縮點;handoff 來源 auto=壓縮點 85%、config=handoffTokens、capped=設定值超過 auto 改用 auto;
8// cap=有背景工作時延後的上限(交接線與壓縮點的中點)
9export type Limits = { window: number; fuse: number; nudge: number; handoff: number; cap: number; source: 'auto' | 'config' | 'capped' }
10
11// 快取倒數:lastRequestAt=上一次主線回合(或保溫 fork)結束的時間,turnStartedAt=這一輪開始的時間(算閒置多久);
12// ttlMs/ttlSource=推定的快取存活時間與依據;observed=上一輪閒置未到 TTL 卻偏冷的觀測(只顯示,不改判);keepalives=這段閒置已保溫幾次
13export type Cache = { lastRequestAt: number | null; turnStartedAt: number | null; ttlMs: number; ttlSource: string; observed: string; keepalives: number }
14
15// 自動交接狀態機:idle →(deferred ⇄)countdown → preparing → 切換;failed/cancelled/done 為本對話終態。
16// $.state 在 /clear 後歸零,所以新對話一律從 idle 開始。
17export type AutoPhase = 'idle' | 'deferred' | 'countdown' | 'preparing' | 'done' | 'failed' | 'cancelled'
18export type Auto = { phase: AutoPhase; deadline?: number; detail?: string }
19
20// handoff-pickup:新對話開場時待接手的交接檔(最新一份);from=來源 session 前 8 碼(讀不到為空),more=其他待接手份數
21export type Pickup = { path: string; name: string; mtimeMs: number; from: string; more: number }
22
23declare module 'claude-code' {
24  interface PluginState {
25    'ctx-relay': {
26      readings: Reading[]
27      receipt: Receipt | null
28      limits: Limits | null
29      auto: Auto
30      cache: Cache
31    }
32  }
33}
34