Hand off unfinished work before a session loses it, and pick it up again at the next start.

Claude Code Mod。在 session 即將失去狀態之前(context 快滿、/clear、結束)協助你留下一份交接檔;下次在同一個專案開新 session 時,列出還沒做完的交接,讓你一鍵接續。零模型成本:Mod 本身不呼叫模型,只有你自己執行交接 skill 時才花一個回合。
狀態:原型。 可以從 marketplace 安裝。
claude plugin update的更新流程實際跑過(0.1.6 → 0.2.0);第一次用claude plugin install安裝的流程我還沒實際跑過。在作者的 macOS(Claude Code 2.1.292)和 Cloud container(Linux)驗證過,見最下方「驗證狀態」。其他環境、終端機與預設的 60% 門檻實際用起來的感覺,還沒有人驗證。
| 時機 | 行為 |
|---|---|
你執行 /handoff-mod:handoff | 內建 skill:唯讀收集 git 狀態,先把完整草稿給你看、問你對不對,你確認後才寫檔。「已驗證」只列這個回合真的跑過的指令,並標明是 AI 自述。寫完後 Mod 會檢查檔案是否有效,右上角顯示 toast。 |
| context 用量到門檻(預設已用 60%) | 一個回合結束後,在輸入框上方問你要不要先交接:「同意」「再多 10% 再問」「這個 session 別再問」。不看工作樹乾不乾淨,非 git 目錄也會問。同時在輸入框下方放一行狀態。每個門檻只問一次。 |
你下 /clear | 一律問:取消、寫交接檔(寫完再 /clear)、不交接直接清除(預設在「取消」,按 Enter 不會誤清)。選「寫交接檔」會暫停這次清除,不會自動幫你清;交接檔寫完後,請自己再下一次 /clear。 |
| 開新 session | 列出同一專案還沒做完的交接(任務、分支、幾分鐘前、下一步、與現況的差異),可按「接續」;或輸入 /handoff-resume,/handoff-resume 2 接續第 2 筆。超過 3 筆、或建立超過 14 天的交接,會折疊成「還有 N 筆」按鈕,按下去展開;/handoff-resume all 也能列出全部。同一個 branch 較舊的自動筆記預設折在裡面。不要的交接可以用 /handoff-resume drop <編號>(或 drop all)放棄,清單標頭那一行也有這個提示;清單上的「本 session 忽略」只對這個 session 有效,下次開 session 還會再出現。接續只會把「請先讀這份交接、驗證前提再接續」填進輸入框,不會自動送出。 |
session 結束(/exit、Ctrl-C 兩次、關分頁) | 若這個 session 改動了工作樹(新增、修改、刪除或 stage 了檔案),自動留下一份只含事實的筆記(最後一個要求、最後一段回應、branch、HEAD、有改動的檔案)。session 開始前就有、這次沒再動過的變更,不會觸發筆記。含對話原文,見下方風險。 |
/handoff-stats | 顯示這台機器上交接寫入與接續的次數。 |
交接檔放在 <git 根目錄>/.claude/handoffs/,並寫進 .git/info/exclude 避免弄髒 git status(如果你的全域 gitignore 已涵蓋就不改)。多個 worktree 會一起列出;同一份交接(檔名與建立時間相同)在幾個 worktree 都有副本時,只列一筆。不在 git 內時用 session 的根目錄。
作者測的是 Claude Code 2.1.291 與 2.1.292,最低可用版本沒有驗證。
從 marketplace 安裝(第一次安裝的流程沒有驗證過):
claude plugin marketplace add tomwangowa/agent-skills
claude plugin install handoff-mod@tomwangowa --scope user
已經裝過、要更新到新版(這條流程驗證過):
claude plugin marketplace update tomwangowa
claude plugin update handoff-mod@tomwangowa
更新完要重新開一個 session 才會生效。
只想試用,用本機載入:
git clone https://github.com/tomwangowa/agent-skills.git
claude --plugin-dir "<clone 路徑>/plugins/handoff-mod"
--plugin-dir 只在那一次 session 有效,不會安裝任何東西。Mod 不在 sandbox 裡執行,會以你的使用者權限跑在 Claude Code 裡,載入前請先看過 hooks/ 的程式碼。
如果同時載入 attention-mod,展開的 inline 面板會把輸入框上方的提示遮住;輸入框下方那一行狀態仍然看得到,/handoff-resume 與 /handoff-mod:handoff 照常可用。
在 /config 裡有三項。改任何設定都會讓 Mod 重新載入,不影響進行中的 session。
| 設定 | 預設 | 說明 |
|---|---|---|
thresholdPct | 60 | 已用百分比(1 到 99)。百分比是對模型的 context window 算的,同一個數字在不同模型是不同的 token 數。 |
lang | zh-TW | 介面與 skill 草稿的語言:zh-TW 或 en。沒存過這個設定時,skill 看到的是未替換的字面值,會退回 zh-TW。 |
autoNote | 開 | 是否在結束時自動留下筆記。 |
開發與測試用的環境變數(不影響 skill 的語言):HANDOFF_THRESHOLD_PCT、HANDOFF_LANG、HANDOFF_AUTO_NOTE(off 或 on)、HANDOFF_DEBUG(1 時用 $.ui.log 印出偵測過程,行首是 [handoff-mod debug])。
--auto.md(檔案權限 0600,下次啟動標示「自動留下,未經審查」,超過 7 天不再顯示)。password = …、sk-…、Authorization: Bearer … 等九種)。單獨出現在文字裡的密碼不會被遮蔽。需要時把 autoNote 關掉,或設 HANDOFF_AUTO_NOTE=off。~/.claude/plugins/store/;在 Cloud 查過是明文 JSON)。檔案權限在 macOS 是 0600,但目錄是 0755(同機器的其他使用者看得到檔名,讀不到內容)。session 結束時一律刪除,當機留下的殘餘超過 7 天會在下次啟動時清掉。/handoff-stats 的數字只存在這台機器的 store。claude plugin validate --strict .
claude plugin test .
| 範圍 | 狀態 |
|---|---|
| 自動測試 | 原生測試 225 項,另有變異檢查;0.1.x 在 Cloud 跑,0.2.x 在作者的 macOS 跑。 |
啟動清單、/handoff-resume、按鈕(Tab 與滑鼠)、/clear 的對話框、門檻提示、結束筆記(三種結束方式)、與 attention-mod 同載入、en 介面 | 作者的 macOS 驗證過(Claude Code 2.1.292)。 |
/handoff-stats 的寫入計數、新 session 啟動清單對自動筆記的標示 | 作者的 macOS 驗證過。 |
/clear 對話框「打字後再按 Enter」 | macOS 只確認 Enter 選到預設的取消;是否有先打字沒有記錄。 |
/handoff-resume <編號> 與接續計數 | 作者的 macOS 驗證過一次(/handoff-resume 2 填入輸入框,接續次數 2 變 3,與 store 紀錄一致)。第一次試(第 1 筆)沒有任何效果也沒有留下紀錄,原因不明、無法重現。 |
真實 worktree:同一份交接在兩個 worktree 只列一筆,drop 寫入兩個副本的狀態 | 作者的 macOS 驗證過(0.2.0)。 |
| 預設 60% 門檻、Warp 以外的終端機、Windows、非 git 目錄 | 沒有驗證。 |
| 交接內容的準確度與成本 | 沒有量測。 |
測試結果、限制與每項決定的依據在 docs/implementation-results.md、docs/poc-results.md、設計、實作計畫。
hooks/register.js 836 lines1import {atom, read, update} from 'claude-code';
2import {resolveConfig} from './config.js';
3import {t, clearOptions} from './i18n.js';
4import {parseHandoff} from './handoff-file.js';
5import {rankHandoffs} from './rank.js';
6import {freshnessFacts} from './freshness.js';
7import {tryClaim, claimView} from './claim.js';
8import {mergeCopies, stateKeys, claimKeys, newestState} from './identity.js';
9import {parseStatusZ, takeBaseline, hasNewEntry, changedSince, BASELINE_MAX} from './snapshot.js';
10import {ensureExcluded} from './exclude.js';
11import {cleanForNote} from './sanitize.js';
12import {shouldWriteNote, buildEndNote, withDeadline} from './note.js';
13import {decideTrigger, effectiveThreshold, snooze, onPercentSeen, hasUnfinishedSign} from './trigger.js';
14
15/*
16 * Wiring for the handoff mod. Every pure decision lives in its own module; this file only connects events to them.
17 * Invariants (see docs/superpowers/plans/2026-10-07-handoff-mod.md): never touch a tool call, a permission decision or
18 * Claude's prompt; every hook body is wrapped in try/catch; session-scoped state lives in $.state, not in module variables,
19 * because changing any setting reloads the module; list output goes through $.ui.log, which Claude does not read.
20 */
21
22const SKILL = 'handoff-mod:handoff';
23const SKILL_COMMAND = new RegExp(`^/${SKILL}(\\s|$)`);
24const DIR = '.claude/handoffs';
25const PATTERN = `${DIR}/`;
26const MAX_DIRS = 20;
27const MAX_PER_DIR = 30;
28const GIVE_UP_TURNS = 10;
29const WARN_AT_TURN = 4;
30const GIVE_UP_MS = 60 * 60 * 1000;
31// D4, route B: session.end cannot read the conversation, so the last request and answer are kept (masked) in $.store.
32const LAST_PREFIX = 'last:';
33const QUOTE_MAX = 2000;
34const RECORD_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
35const NOTE_DEADLINE_MS = 1500;
36// D23: -z keeps non-ASCII names unquoted so that they can be stat-ed; all untracked files, because a folder's mtime does
37// not move when a file inside it changes.
38const STATUS_ARGS = ['status', '--porcelain', '-z', '--untracked-files=all'];
39const COMPARE_DEADLINE_MS = 500;
40const CLEAR_POLL_MS = 200;
41const CLEAR_POLL_TRIES = 50;
42
43// Session-scoped state, kept in $.state: it survives a module reload and is reset by /clear, /resume and /branch.
44const handoffStartedAt = atom({plugin: 'handoff-mod', key: 'handoffStartedAt'}, 0);
45const handoffTurns = atom({plugin: 'handoff-mod', key: 'handoffTurns'}, 0);
46const listDone = atom({plugin: 'handoff-mod', key: 'listDone'}, false);
47// D16: whether the folded part of the start-up list has been asked for; reset by /clear like the other session state.
48const expanded = atom({plugin: 'handoff-mod', key: 'expanded'}, false);
49const askPending = atom({plugin: 'handoff-mod', key: 'askPending'}, false);
50// T1 (D12): the next threshold after "ask again in 10%", the threshold last asked about, "never ask again", and the
51// percentage the open prompt reports (0 while no prompt is open).
52const nextAt = atom({plugin: 'handoff-mod', key: 'nextAt'}, 0);
53const askedAt = atom({plugin: 'handoff-mod', key: 'askedAt'}, 0);
54const suppressed = atom({plugin: 'handoff-mod', key: 'suppressed'}, false);
55const t1Percent = atom({plugin: 'handoff-mod', key: 't1Percent'}, 0);
56
57// Rebuilt from userConfig and disk whenever the module (re)loads or a session starts.
58let USER_CONFIG = {};
59let config = resolveConfig({});
60let list = null; // {items, total} while the start-up list is showing
61let listing = false;
62let debugOn = false; // HANDOFF_DEBUG=1: trace the post-write detection through $.ui.log (Claude does not read it)
63
64/** Run git without a shell; resolves to {exitCode, stdout} and never throws. */
65async function git($, args) {
66 try {
67 const result = await $.process.run(['git', ...args], {timeoutMs: 5000});
68 return {exitCode: result.exitCode, stdout: String(result.stdout ?? '')};
69 } catch {
70 return {exitCode: -1, stdout: ''};
71 }
72}
73
74/** One diagnostic line, only when HANDOFF_DEBUG is set. Never throws. */
75function trace($, text) {
76 if (!debugOn) return;
77 try { $.ui.log(`[handoff-mod debug] ${text}`); } catch { /* ignore */ }
78}
79
80/** Test-only env overrides (literal names, so validate can list them), then userConfig, then defaults. */
81async function loadConfig($) {
82 try {
83 const env = {
84 HANDOFF_THRESHOLD_PCT: await $.env.get('HANDOFF_THRESHOLD_PCT'),
85 HANDOFF_LANG: await $.env.get('HANDOFF_LANG'),
86 HANDOFF_AUTO_NOTE: await $.env.get('HANDOFF_AUTO_NOTE'),
87 };
88 debugOn = ['1', 'on', 'true'].includes(String((await $.env.get('HANDOFF_DEBUG')) ?? '').toLowerCase());
89 return resolveConfig({env, userConfig: USER_CONFIG});
90 } catch {
91 return resolveConfig({userConfig: USER_CONFIG});
92 }
93}
94
95/** The handoff directory's base: the git toplevel of this working tree, else the session root (D10). */
96async function projectBase($) {
97 const top = await git($, ['rev-parse', '--show-toplevel']);
98 const line = top.exitCode === 0 ? top.stdout.trim() : '';
99 return line || (await $.session.root());
100}
101
102async function repoRoot($) {
103 try {
104 return (await $.session.repo())?.root ?? null;
105 } catch {
106 return null;
107 }
108}
109
110/** The working tree's own directory, the main checkout's, and every other worktree's (D2); no index, bounded. */
111async function candidateDirs($, base, repo) {
112 const dirs = [`${base}/${DIR}`];
113 if (repo) {
114 dirs.push(`${repo}/${DIR}`);
115 const trees = await git($, ['worktree', 'list', '--porcelain']);
116 if (trees.exitCode === 0) {
117 for (const line of trees.stdout.split('\n')) if (line.startsWith('worktree ')) dirs.push(`${line.slice(9).trim()}/${DIR}`);
118 }
119 }
120 return [...new Set(dirs)].slice(0, MAX_DIRS);
121}
122
123/** Newest first by the timestamp in the file name, then by name. */
124const byStamp = (a, b) => {
125 const key = (name) => /--(\d{8}-\d{6})/.exec(name)?.[1] ?? '';
126 return key(b).localeCompare(key(a)) || (a < b ? 1 : a > b ? -1 : 0);
127};
128
129async function readHandoffs($, dirs) {
130 const found = [];
131 for (const dir of dirs) {
132 try {
133 if (!(await $.fs.exists(dir))) continue;
134 const names = (await $.fs.list(dir)).filter((entry) => entry.kind === 'file' && entry.name.endsWith('.md')).map((entry) => entry.name).sort(byStamp).slice(0, MAX_PER_DIR);
135 for (const name of names) {
136 const path = `${dir}/${name}`;
137 try {
138 const parsed = parseHandoff(await $.fs.read(path));
139 if (parsed.ok) found.push({path, meta: parsed.meta, fields: parsed.fields, closed: false});
140 // D20: a closed copy is kept so that it can close its copies in other working trees; it is never listed.
141 else if (parsed.reason === 'status' && parsed.meta) found.push({path, meta: parsed.meta, fields: parsed.fields, closed: true});
142 } catch { /* An unreadable file is skipped. */ }
143 }
144 } catch { /* An unreadable directory counts as no handoffs. */ }
145 }
146 return found;
147}
148
149const age = (lang, ms) => {
150 const minutes = Math.max(1, Math.round(ms / 60000));
151 if (minutes < 60) return t(lang, 'age.minutes', {n: minutes});
152 const hours = Math.round(minutes / 60);
153 return hours < 48 ? t(lang, 'age.hours', {n: hours}) : t(lang, 'age.days', {n: Math.round(hours / 24)});
154};
155
156const factText = (lang, fact) =>
157 fact.kind === 'branchGone' ? t(lang, 'fresh.branchGone', {branch: fact.branch})
158 : fact.kind === 'ahead' ? t(lang, 'fresh.ahead', {branch: fact.branch, count: fact.count})
159 : fact.kind === 'merged' ? t(lang, 'fresh.merged', {base: fact.base})
160 : t(lang, 'fresh.unverifiable');
161
162async function storeGet($, key) {
163 try {
164 return await $.store.get(key);
165 } catch {
166 return undefined;
167 }
168}
169
170/** Read `keys` one by one; a failed read is undefined. */
171async function storeGetAll($, keys) {
172 const values = [];
173 for (const key of keys) values.push(await storeGet($, key));
174 return values;
175}
176
177/** Collect, merge (D20), rank and describe the unfinished handoffs for this working tree and its repository. */
178async function buildList($) {
179 const lang = config.lang;
180 const sessionId = await $.session.id();
181 const now = await $.clock.now();
182 const base = await projectBase($);
183 const repo = await repoRoot($);
184 const found = await readHandoffs($, await candidateDirs($, base, repo));
185 const items = [];
186 for (const group of mergeCopies(found, {base, repo, dir: DIR})) {
187 // D21: the new key first, then each copy's old path key, so that records written by 0.1.x still count.
188 const record = newestState(await storeGetAll($, stateKeys(group)));
189 const claims = await storeGetAll($, claimKeys(group));
190 items.push({
191 ...group,
192 effectiveStatus: record ? record.status : group.fileClosed ? 'closed' : group.meta.status,
193 claimedByOther: claims.some((claim) => claimView(claim, sessionId, now).state === 'other'),
194 });
195 }
196 const ranked = rankHandoffs(items, {base, repo, now});
197 const picked = (await read($, expanded)) ? [...ranked.shown, ...ranked.rest] : ranked.shown;
198 const views = [];
199 for (const item of picked) {
200 const facts = await freshnessFacts({meta: item.meta, git: (args) => git($, args)});
201 views.push({
202 id: item.key,
203 path: item.path,
204 stateKeys: stateKeys(item),
205 claimKeys: claimKeys(item),
206 title: t(lang, 'list.item', {n: views.length + 1, task: item.fields.task || item.path.split('/').pop(), branch: item.meta.branch ?? '-', age: age(lang, now - item.meta.created)}),
207 next: item.fields.next ? t(lang, 'list.next', {next: item.fields.next}) : '',
208 facts: facts.map((fact) => factText(lang, fact)),
209 auto: item.meta.source === 'auto',
210 older: Boolean(item.olderAuto),
211 claimed: item.claimedByOther,
212 });
213 }
214 return {items: views, total: ranked.shown.length + ranked.collapsed};
215}
216
217/** A plugin has one status line: the start-up list wins, else an open T1 prompt, else nothing. Redraws the band too. */
218async function syncStatus($) {
219 const open = await read($, t1Percent);
220 $.ui.status(list ? t(config.lang, 'status.pending', {count: list.total}) : open > 0 ? t(config.lang, 'status.threshold', {percent: open}) : undefined);
221 $.ui.invalidate('ui.render');
222}
223
224async function showList($, built) {
225 list = built.items.length ? built : null;
226 await syncStatus($);
227}
228
229async function clearList($) {
230 list = null;
231 await syncStatus($);
232}
233
234async function closeT1($) {
235 await update($, t1Percent, () => 0);
236 await syncStatus($);
237}
238
239const readT1 = async ($) => ({
240 nextAt: await read($, nextAt), askedAt: await read($, askedAt), suppressed: await read($, suppressed), askPending: await read($, askPending),
241});
242
243/**
244 * T1: after a turn, ask once per threshold when the context is filling up (D1, design component 2). Since D24 the working
245 * tree is not looked at: a clean tree and a folder outside git are asked too. No percentage still means do not ask.
246 */
247async function checkThreshold($) {
248 const percent = (await $.session.usage())?.context?.percent;
249 const state = await readT1($);
250 const seen = onPercentSeen(state, percent);
251 if (seen !== state) {
252 // Compaction or /clear made the percentage fall: forget which thresholds were asked, and take any open prompt down.
253 await update($, nextAt, () => seen.nextAt);
254 await update($, askedAt, () => seen.askedAt);
255 if ((await read($, t1Percent)) > 0) await closeT1($);
256 }
257 if (typeof percent !== 'number' || percent < effectiveThreshold(seen, config)) return;
258 const decision = decideTrigger({
259 percent, config, state: seen, idle: true,
260 hasUnfinishedSign: true,
261 handoffRunning: (await read($, handoffStartedAt)) > 0,
262 });
263 trace($, `threshold: percent=${percent} at=${decision.at} -> ${decision.action}`);
264 if (decision.action !== 'ask') return;
265 await update($, askedAt, () => decision.at);
266 await update($, t1Percent, () => Math.max(1, percent));
267 await syncStatus($);
268}
269
270/** The prompt's three answers. Each takes it down; a press on a prompt that is already gone does nothing. */
271async function answerT1($, answer) {
272 const percent = await read($, t1Percent);
273 if (percent <= 0) return;
274 if (answer === 'snooze') {
275 const next = snooze({}, {percent, at: await read($, askedAt)}).nextAt;
276 await update($, nextAt, () => next);
277 }
278 if (answer === 'suppress') await update($, suppressed, () => true);
279 await closeT1($);
280 if (answer === 'agree') startHandoffLater($);
281}
282
283/** Compute the start-up list once per call; `force` ignores "already dismissed" (used by /handoff-resume). */
284async function refreshList($, {force = false} = {}) {
285 if (listing) return;
286 listing = true;
287 try {
288 if (!force && (await read($, listDone))) return;
289 await showList($, await buildList($));
290 } catch {
291 /* The list is a convenience; never let it break the session. */
292 } finally {
293 listing = false;
294 }
295}
296
297/** D16: build the folded part too. Setting the flag first means a press during a rebuild still ends up expanded. */
298async function expandList($) {
299 await update($, expanded, () => true);
300 await refreshList($, {force: true});
301}
302
303async function bumpStat($, field) {
304 try {
305 const stats = (await $.store.get('stats')) ?? {};
306 await $.store.set('stats', {written: 0, resumed: 0, ...stats, [field]: (Number(stats[field]) || 0) + 1});
307 } catch { /* Counts are local and optional. */ }
308}
309
310/** stat each entry under `root`. A deletion is null without a stat; any other failure throws when `strict`, else is null. */
311async function statEntries($, root, entries, {strict}) {
312 const out = [];
313 for (const entry of entries) {
314 if (entry.code.includes('D')) {
315 out.push({...entry, mtimeMs: null});
316 continue;
317 }
318 try {
319 out.push({...entry, mtimeMs: (await $.fs.stat(`${root}/${entry.path}`)).mtimeMs});
320 } catch (error) {
321 if (strict) throw error;
322 out.push({...entry, mtimeMs: null});
323 }
324 }
325 return out;
326}
327
328/** D23: what was already dirty before this session did anything, or null when that cannot be told (the old rule then applies). */
329async function takeSessionBaseline($) {
330 try {
331 const status = await git($, STATUS_ARGS);
332 if (status.exitCode !== 0) return null;
333 const entries = parseStatusZ(status.stdout);
334 return takeBaseline(await statEntries($, await projectBase($), entries.slice(0, BASELINE_MAX), {strict: true}), entries.length);
335 } catch (error) {
336 trace($, `baseline not taken: ${String(error?.message ?? error)}`);
337 return null;
338 }
339}
340
341/**
342 * Keep the newest request, masked and cut, for the end-of-session note. One record per session; each prompt replaces it.
343 * The first request also fixes the baseline (D23); later requests keep it, even when it is null, so that a baseline is
344 * never taken after the session has started changing files.
345 */
346async function recordRequest($, text) {
347 if (!config.autoNote || !text.trim() || (await $.session.surfaces()).length === 0) return;
348 const key = `${LAST_PREFIX}${await $.session.id()}`;
349 const previous = await storeGet($, key);
350 const baseline = previous && typeof previous === 'object' && 'baseline' in previous ? previous.baseline : await takeSessionBaseline($);
351 await $.store.set(key, {request: cleanForNote(text, QUOTE_MAX), response: '', at: await $.clock.now(), baseline});
352}
353
354/** Attach the answer to the request it belongs to. With no recorded request there is nothing to attach it to. */
355async function recordResponse($, answer) {
356 if (!config.autoNote) return;
357 const key = `${LAST_PREFIX}${await $.session.id()}`;
358 const record = await storeGet($, key);
359 if (!record || typeof record.request !== 'string') return;
360 await $.store.set(key, {...record, response: cleanForNote(String(answer ?? ''), QUOTE_MAX), at: await $.clock.now()});
361}
362
363/** A crash or kill -9 leaves a record behind; drop any that is a week old. */
364async function sweepOldRecords($) {
365 const now = await $.clock.now();
366 for (const key of await $.store.keys()) {
367 if (!key.startsWith(LAST_PREFIX)) continue;
368 const record = await storeGet($, key);
369 if (!record || !(now - Number(record.at) < RECORD_MAX_AGE_MS)) await $.store.delete(key);
370 }
371}
372
373/**
374 * D23: did this session change the working tree? With no usable baseline, or when git status and the stats miss the
375 * sub-deadline, the answer is yes: the old rule (dirty means write) is kept rather than losing a note.
376 * `statusRun` is the git status already started by the caller, so that the sub-deadline covers it too.
377 */
378async function sessionChanged($, baseline, statusRun, root, budget) {
379 if (!baseline || typeof baseline !== 'object' || baseline.truncated || !Array.isArray(baseline.entries)) return true;
380 const verdict = await withDeadline(async () => {
381 const status = await statusRun;
382 if (status.exitCode !== 0) return true;
383 const current = parseStatusZ(status.stdout);
384 if (current.length > BASELINE_MAX || hasNewEntry(baseline, current)) return true;
385 return changedSince(baseline, await statEntries($, root, current, {strict: false}));
386 }, Math.min(COMPARE_DEADLINE_MS, budget / 2), (ms, callback) => $.clock.after(ms, callback));
387 if (!('value' in verdict)) trace($, `end note: comparison ${verdict.timedOut ? 'ran out of time' : 'failed'}, writing as before`);
388 return 'value' in verdict ? verdict.value : true;
389}
390
391/**
392 * D4, D23: at the end of an interactive session that changed the working tree, write the facts-only note (the last request and
393 * answer, git state, changed files) without asking a model. Gives up at the exit's short budget and writes nothing then.
394 * The record is always deleted afterwards: it holds the only copy of that text outside the note.
395 */
396async function writeEndNote($, e, next) {
397 const key = `${LAST_PREFIX}${e.sessionId}`;
398 try {
399 const record = await storeGet($, key);
400 if (!record || typeof record.request !== 'string') return;
401 const remaining = Number(next.budget?.remainingMs);
402 const budget = Math.min(NOTE_DEADLINE_MS, Number.isFinite(remaining) ? remaining - 200 : NOTE_DEADLINE_MS);
403 if (budget < 200) { trace($, `end note skipped: ${remaining} ms left`); return; }
404 let abandoned = false;
405 const outcome = await withDeadline(async () => {
406 const base = await projectBase($);
407 const statusRun = git($, STATUS_ARGS);
408 const changed = await sessionChanged($, record.baseline, statusRun, base, budget);
409 const status = await statusRun;
410 const dirty = status.exitCode === 0 ? parseStatusZ(status.stdout).map((entry) => entry.path) : [];
411 const write = shouldWriteNote({interactive: true, turns: 1, hasUnfinishedSign: hasUnfinishedSign({gitDirty: dirty.length > 0 && changed}), reason: e.reason, config});
412 trace($, `end note: reason=${e.reason} dirty=${dirty.length} changed=${changed} write=${write}`);
413 if (!write) return false;
414 const branch = (await git($, ['branch', '--show-current'])).stdout.trim();
415 const head = (await git($, ['rev-parse', '--short', 'HEAD'])).stdout.trim();
416 let root = base;
417 try { root = (await $.session.root()) || base; } catch { /* The git toplevel stands in. */ }
418 const note = buildEndNote({
419 lastRequest: record.request, lastResponse: record.response, branch, head, dirtyFiles: dirty,
420 root, repo: await repoRoot($), now: await $.clock.now(), lang: config.lang,
421 });
422 if (abandoned) return false;
423 await ensureExcluded({
424 git: (args) => git($, args),
425 fs: {exists: (path) => $.fs.exists(path), read: (path) => $.fs.read(path), write: (path, text) => $.fs.write(path, text)},
426 pattern: PATTERN,
427 });
428 const path = `${base}/${DIR}/${note.fileName}`;
429 await $.fs.write(path, note.content);
430 let chmodExit = -1;
431 try { chmodExit = (await $.process.run(['chmod', '600', path], {timeoutMs: 1000})).exitCode; } catch { /* The trace shows it. */ }
432 trace($, `end note written to ${path} (chmod exit ${chmodExit})`);
433 return true;
434 }, budget, (ms, callback) => $.clock.after(ms, callback));
435 if (outcome.timedOut) { abandoned = true; trace($, 'end note abandoned: out of time'); }
436 if (outcome.error) trace($, `end note failed: ${String(outcome.error?.message ?? outcome.error)}`);
437 } finally {
438 try { await $.store.delete(key); } catch { /* The weekly sweep removes it. */ }
439 }
440}
441
442/** D22: write the new key and every copy's old path key. The new key decides success; an old key that fails is only traced. */
443async function writeState($, item, record) {
444 const [first, ...old] = item.stateKeys;
445 await $.store.set(first, record);
446 for (const key of old) {
447 try { await $.store.set(key, record); } catch (error) { trace($, `old state key not written: ${key}: ${String(error?.message ?? error)}`); }
448 }
449}
450
451/** Resume one handoff: claim it, remember that, and put a prompt in the input box for the user to send. */
452async function resume($, item) {
453 const lang = config.lang;
454 const now = await $.clock.now();
455 const sessionId = await $.session.id();
456 const claim = await tryClaim({keys: item.claimKeys, sessionId, now, store: {get: (key) => $.store.get(key), set: (key, value) => $.store.set(key, value)}});
457 if (!claim.won) {
458 $.ui.toast(t(lang, 'resume.claimedElsewhere'));
459 return;
460 }
461 try { await writeState($, item, {status: 'resumed', at: now, sessionId}); } catch { /* Resuming still works without the record. */ }
462 await bumpStat($, 'resumed');
463 await $.prompt.fill({text: t(lang, 'resume.prompt', {path: item.path})});
464 await update($, listDone, () => true);
465 await clearList($);
466}
467
468/** D17: mark a handoff abandoned on this machine. Only the store record changes; the file is never touched (invariant 6). */
469async function abandon($, item, now, sessionId) {
470 try {
471 await writeState($, item, {status: 'abandoned', at: now, sessionId});
472 return true;
473 } catch {
474 return false;
475 }
476}
477
478/** `/handoff-resume drop <n|all>`: abandon one listed item, or every listed item that no other session is resuming. */
479async function dropCommand($, target) {
480 const lang = config.lang;
481 const isAll = target === 'all';
482 const n = Number(target);
483 if (!isAll && !(target !== undefined && Number.isInteger(n))) {
484 $.ui.log(t(lang, 'drop.usage'));
485 return;
486 }
487 if (!list) {
488 $.ui.log(t(lang, 'list.none'));
489 return;
490 }
491 // A number past the shown items may still be a folded one (D16): expand, then look again.
492 if (!isAll && n > list.items.length && list.total > list.items.length) await expandList($);
493 const picked = isAll ? [...list.items] : [list?.items[n - 1]].filter(Boolean);
494 if (picked.length === 0) {
495 $.ui.log(t(lang, 'list.bad', {n: target}));
496 return;
497 }
498 const skipped = picked.filter((item) => item.claimed);
499 if (!isAll && skipped.length) {
500 $.ui.log(t(lang, 'drop.claimed', {title: skipped[0].title}));
501 return;
502 }
503 const now = await $.clock.now();
504 const sessionId = await $.session.id();
505 const done = [];
506 for (const item of picked) {
507 if (!item.claimed && (await abandon($, item, now, sessionId))) done.push(item);
508 }
509 if (done.length === 0) {
510 for (const item of skipped) $.ui.log(t(lang, 'drop.claimed', {title: item.title}));
511 $.ui.log(t(lang, 'drop.none'));
512 return;
513 }
514 await refreshList($, {force: true});
515 $.ui.log(t(lang, 'drop.header', {count: done.length}));
516 for (const item of done) $.ui.log(item.title);
517 for (const item of skipped) $.ui.log(t(lang, 'drop.claimed', {title: item.title}));
518}
519
520/** A handoff run starts when the skill is expanded, however it was started (typed, or run by this mod). */
521async function markHandoffStarted($) {
522 const already = await read($, handoffStartedAt);
523 if (already > 0) {
524 trace($, `start signal ignored, a run is already pending since ${already}`);
525 return;
526 }
527 const now = Math.max(1, await $.clock.now());
528 await update($, handoffStartedAt, () => now);
529 await update($, handoffTurns, () => 0);
530 trace($, `handoff run started at ${now}`);
531 if ((await read($, t1Percent)) > 0) await closeT1($);
532}
533
534/** The newest valid handoff file written since `since`, or null. Never trusts that the model wrote one. */
535async function findNewHandoff($, since) {
536 const dir = `${await projectBase($)}/${DIR}`;
537 const exists = await $.fs.exists(dir);
538 trace($, `looking in ${dir} (exists=${exists}), since=${since}`);
539 if (!exists) return null;
540 let newest = null;
541 for (const entry of await $.fs.list(dir)) {
542 if (entry.kind !== 'file' || !entry.name.endsWith('.md')) {
543 trace($, `skip ${entry.name}: kind=${entry.kind}`);
544 continue;
545 }
546 const path = `${dir}/${entry.name}`;
547 try {
548 const stat = await $.fs.stat(path);
549 if (stat.mtimeMs < since - 2000 || (newest && stat.mtimeMs <= newest.mtimeMs)) {
550 trace($, `skip ${entry.name}: mtimeMs=${stat.mtimeMs}, older than the run or not newest`);
551 continue;
552 }
553 const parsed = parseHandoff(await $.fs.read(path));
554 trace($, `${entry.name}: mtimeMs=${stat.mtimeMs}, valid=${parsed.ok}${parsed.ok ? '' : `, reason=${String(parsed.reason ?? "?")}`}`);
555 if (parsed.ok) newest = {path, mtimeMs: stat.mtimeMs};
556 } catch (error) {
557 trace($, `${entry.name}: ${String(error?.message ?? error)}`); // Skip files that cannot be read.
558 }
559 }
560 return newest;
561}
562
563/**
564 * After each turn while a handoff is pending: report the file once a valid one exists. The review gate makes a handoff
565 * span at least two turns (draft, then confirm), so "no file yet" is only reported after WARN_AT_TURN turns, once.
566 */
567async function checkHandoff($) {
568 const since = await read($, handoffStartedAt);
569 if (since <= 0) return;
570 const lang = config.lang;
571 const turns = (await read($, handoffTurns)) + 1;
572 await update($, handoffTurns, () => turns);
573 const found = await findNewHandoff($, since);
574 trace($, `check after turn ${turns}: ${found ? `found ${found.path}` : 'nothing valid yet'}`);
575 if (found) {
576 await ensureExcluded({
577 git: (args) => git($, args),
578 fs: {exists: (path) => $.fs.exists(path), read: (path) => $.fs.read(path), write: (path, text) => $.fs.write(path, text)},
579 pattern: PATTERN,
580 });
581 await bumpStat($, 'written');
582 $.ui.toast(t(lang, 'toast.written', {path: found.path}));
583 await update($, handoffStartedAt, () => 0);
584 return;
585 }
586 if (turns === WARN_AT_TURN) $.ui.toast(t(lang, 'toast.invalid'));
587 if (turns >= GIVE_UP_TURNS || (await $.clock.now()) - since > GIVE_UP_MS) await update($, handoffStartedAt, () => 0);
588}
589
590/** Start the handoff skill the way a user would. Must run from a timer: the host refuses it inside a command.run hook. */
591function startHandoffLater($) {
592 $.clock.after(300, async () => {
593 try { await $.command.run({command: SKILL}); } catch { /* The user can still run /handoff-mod:handoff by hand. */ }
594 });
595}
596
597/**
598 * T2: ask what to do with a /clear. The question is the only $.ui.ask this mod makes: it is awaited inside the held command,
599 * so it never outlives the command, and a flag keeps a second /clear from stacking another question.
600 * Returns 'clear', 'handoff', 'cancel' or 'stale' (the session changed while the question was open).
601 */
602async function askBeforeClear($) {
603 if (await read($, askPending)) return 'cancel';
604 const lang = config.lang;
605 const options = clearOptions(lang);
606 const sessionId = await $.session.id();
607 await update($, askPending, () => true);
608 let answer = null;
609 try {
610 answer = await $.ui.ask(t(lang, 'ask.clear.question'), options);
611 } catch {
612 answer = null; // dismissed (Esc) or nobody to ask: treated as cancel
613 } finally {
614 await update($, askPending, () => false);
615 }
616 if ((await $.session.id()) !== sessionId) return 'stale';
617 // Anything but an exact label, including text typed under "Other", cancels: never clear on a guess.
618 return answer === options[2] ? 'clear' : answer === options[1] ? 'handoff' : 'cancel';
619}
620
621/**
622 * /clear goes on under a new session id with no session.start, and the classic SessionStart that says so does not
623 * reach a user-tier plugin on a managed machine (cc-plugin-sec-default sends classic.* past it); poll for the new id.
624 */
625function awaitClearedSession($, endedId, tries = 0) {
626 $.clock.after(CLEAR_POLL_MS, () => void (async () => {
627 try {
628 if ((await $.session.id()) === endedId) {
629 if (tries + 1 < CLEAR_POLL_TRIES) awaitClearedSession($, endedId, tries + 1);
630 return;
631 }
632 await startFreshConversation($);
633 } catch { /* The list is a convenience; never let it break the session. */ }
634 })());
635}
636
637// Only reached after a session.end(clear) and a new session id, so the conversation is fresh by definition. Not gated on
638// $.session.turns(): the /clear command itself already counts as one turn by the time the new id shows (turns=1 observed).
639async function startFreshConversation($) {
640 if ((await $.session.surfaces()).length === 0) return;
641 config = await loadConfig($);
642 // A fresh conversation: $.state is already reset by the host, say so explicitly (design component 2), and redraw.
643 await update($, nextAt, () => 0);
644 await update($, askedAt, () => 0);
645 await update($, t1Percent, () => 0);
646 void refreshList($);
647}
648
649/** Register the handoff hooks. */
650export function register(on, options) {
651 USER_CONFIG = options ?? {};
652 config = resolveConfig({userConfig: USER_CONFIG});
653
654 on('session.start', async ($, e, next) => {
655 const result = await next(e);
656 try {
657 config = await loadConfig($);
658 await $.command.register({name: 'handoff-resume', description: t(config.lang, 'cmd.resume'), argumentHint: t(config.lang, 'cmd.resume.hint')});
659 } catch { /* A taken name or a failed read must not stop the session. */ }
660 try {
661 await $.command.register({name: 'handoff-stats', description: t(config.lang, 'cmd.stats')});
662 } catch { /* Same: a taken name must not stop the session, nor the other command. */ }
663 try { await sweepOldRecords($); } catch { /* ignore */ }
664 try {
665 // A reload of this module re-fires session.start; only a session with no prompts yet gets the list.
666 if (e.isInteractive && (await $.session.turns()) === 0) void refreshList($);
667 } catch { /* ignore */ }
668 return result;
669 });
670
671 on('prompt.submit', async ($, e, next) => {
672 const result = await next(e);
673 try {
674 if ('drop' in result) return result;
675 const text = result.text ?? e.text ?? '';
676 if (text.startsWith('/')) trace($, `prompt.submit origin=${e.origin?.kind ?? '-'} command=${text.trim().split(/\s/)[0]}`);
677 if (['composer', 'bridge', 'sdk'].includes(e.origin?.kind) && !text.startsWith('/')) await recordRequest($, text);
678 // The typed command text starts a run; a machine with cc-plugin-sec-default does not deliver skill.prompt.
679 if (SKILL_COMMAND.test(text.trim())) await markHandoffStarted($);
680 // The first real prompt ends the start-up list; slash commands such as /handoff-resume do not.
681 if (list && ['composer', 'bridge', 'sdk'].includes(e.origin?.kind) && !text.startsWith('/')) {
682 await update($, listDone, () => true);
683 await clearList($);
684 }
685 } catch { /* ignore */ }
686 return result;
687 });
688
689 // No skill.prompt hook on purpose: cc-plugin-sec-default passes that event over a user-tier plugin on a managed machine
690 // (managed settings, Team or Enterprise), which only produced a "hook was skipped" notice. The skill sets
691 // disable-model-invocation, so it starts only by being typed (prompt.submit above) or run as a command (below).
692 // The skill is a command, however it was started (typed, or run by this mod).
693 on('command.run', {command: SKILL}, async ($, e, next) => {
694 const result = await next(e);
695 try {
696 trace($, `command.run command=${SKILL}`);
697 await markHandoffStarted($);
698 } catch (error) { trace($, `markHandoffStarted failed: ${String(error?.message ?? error)}`); }
699 return result;
700 });
701
702 on('turn.complete', async ($, e, next) => {
703 const result = await next(e);
704 trace($, `turn.complete agentId=${e.agentId ?? '-'} aborted=${Boolean(e.isAborted)}`);
705 if (e.agentId || e.isAborted) return result;
706 try { await checkHandoff($); } catch (error) { trace($, `checkHandoff failed: ${String(error?.message ?? error)}`); }
707 try { await checkThreshold($); } catch (error) { trace($, `checkThreshold failed: ${String(error?.message ?? error)}`); }
708 try { await recordResponse($, e.answer); } catch { /* ignore */ }
709 return result;
710 });
711
712 on('session.end', async ($, e, next) => {
713 try { await writeEndNote($, e, next); } catch (error) { trace($, `writeEndNote failed: ${String(error?.message ?? error)}`); }
714 const result = await next(e);
715 // resume and fork keep a conversation that already has its context; only /clear starts a fresh one to list for.
716 if (e.reason === 'clear') { try { awaitClearedSession($, e.sessionId); } catch { /* ignore */ } }
717 return result;
718 });
719
720 on('command.run', {command: 'clear'}, async ($, e, next) => {
721 try {
722 // Only a person's own /clear in an interactive session that has had prompts (D3); not another plugin's, not headless.
723 if (e.origin?.kind === 'plugin') return next(e);
724 if ((await $.session.surfaces()).length === 0 || (await $.session.turns()) === 0) return next(e);
725 } catch {
726 return next(e);
727 }
728 let choice = 'clear';
729 try {
730 choice = await askBeforeClear($);
731 } catch {
732 return next(e); // if asking itself fails, do what the user asked rather than swallow the /clear
733 }
734 if (choice === 'clear') return next(e);
735 if (choice === 'stale') return {};
736 if (choice === 'handoff') {
737 startHandoffLater($);
738 return {text: t(config.lang, 'clear.held')};
739 }
740 return {text: t(config.lang, 'clear.cancelled')};
741 });
742
743 // D5: the counts live in $.store on this machine only; this command is the one place they are shown.
744 on('command.run', {command: 'handoff-stats'}, async ($) => {
745 try {
746 const stats = (await storeGet($, 'stats')) ?? {};
747 $.ui.log(t(config.lang, 'stats.line', {written: Number(stats.written) || 0, resumed: Number(stats.resumed) || 0}));
748 } catch { /* ignore */ }
749 return {};
750 });
751
752 on('command.run', {command: 'handoff-resume'}, async ($, e) => {
753 try {
754 config = await loadConfig($);
755 const lang = config.lang;
756 const arg = String(e.args ?? '').trim();
757 const words = arg === '' ? [] : arg.split(/\s+/);
758 const dropping = words[0] === 'drop';
759 if (arg === 'all' || (dropping && words[1] === 'all')) await update($, expanded, () => true);
760 await refreshList($, {force: true});
761 if (dropping) {
762 await dropCommand($, words[1]);
763 } else if (!list) {
764 $.ui.log(t(lang, 'list.none'));
765 } else if (arg === '' || arg === 'all') {
766 $.ui.log(t(lang, 'list.header', {count: list.total}));
767 for (const item of list.items) {
768 const extra = [item.next, ...item.facts, item.auto ? t(lang, 'list.auto') : '', item.older ? t(lang, 'list.older') : '', item.claimed ? t(lang, 'list.claimed') : ''].filter(Boolean);
769 $.ui.log(extra.length ? `${item.title} — ${extra.join(';')}` : item.title);
770 }
771 if (list.total > list.items.length) $.ui.log(t(lang, 'list.moreCmd', {count: list.total - list.items.length}));
772 $.ui.log(t(lang, 'list.dropHint'));
773 } else {
774 const n = Number(arg);
775 // A number past the shown items may still be a folded one (D15, D16): expand, then look again.
776 if (Number.isInteger(n) && n > list.items.length && list.total > list.items.length) await expandList($);
777 const item = Number.isInteger(n) ? list?.items[n - 1] : undefined;
778 if (item) await resume($, item);
779 else $.ui.log(t(lang, 'list.bad', {n: arg}));
780 }
781 } catch { /* ignore */ }
782 return {};
783 });
784
785 on('ui.render', {component: 'AbovePrompt'}, async ($, e, next) => {
786 const open = await read($, t1Percent);
787 if (!list && open <= 0) return next(e);
788 const {Box, Text, Button} = $.ui.resolve(e);
789 const theirs = await next(e);
790 const lang = config.lang;
791 const blocks = [theirs];
792 if (list) {
793 const rows = [];
794 list.items.forEach((item, i) => {
795 rows.push(Text({bold: true, wrap: 'wrap', children: [item.title]}));
796 if (item.next) rows.push(Text({wrap: 'wrap', children: [item.next]}));
797 for (const [j, fact] of item.facts.entries()) rows.push(Text({dimColor: true, wrap: 'wrap', children: [fact]}));
798 if (item.auto) rows.push(Text({dimColor: true, children: [t(lang, 'list.auto')]}));
799 if (item.older) rows.push(Text({dimColor: true, children: [t(lang, 'list.older')]}));
800 rows.push(item.claimed
801 ? Text({dimColor: true, children: [t(lang, 'list.claimed')]})
802 : Button({key: `resume-${i}`, label: t(lang, 'list.resume'), variant: 'primary', onPress: () => resume($, item)}));
803 });
804 // Theme keys, not raw colors, so the borders follow the person's theme. Buttons are not `plain`: plain ones draw as bare text.
805 blocks.push(Box({
806 flexDirection: 'column', borderStyle: 'round', borderColor: 'suggestion', paddingX: 1,
807 children: [
808 // The hint shares the header row (D19); it wraps below the count on a narrow terminal instead of being cut off.
809 Box({flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: [
810 Text({bold: true, children: [t(lang, 'list.header', {count: list.total})]}),
811 Text({dimColor: true, children: [t(lang, 'list.bandHint')]}),
812 ]}),
813 ...rows,
814 ...(list.total > list.items.length ? [Button({key: 'more', label: t(lang, 'list.more', {count: list.total - list.items.length}), variant: 'secondary', onPress: () => expandList($)})] : []),
815 Button({key: 'skip', label: t(lang, 'list.skip'), variant: 'secondary', onPress: async () => { await update($, listDone, () => true); await clearList($); }}),
816 ],
817 }));
818 }
819 if (open > 0) {
820 // No digit hotkeys: a digit typed at the start of a message in an empty prompt would answer the question.
821 blocks.push(Box({
822 flexDirection: 'column', borderStyle: 'round', borderColor: 'warning', paddingX: 1,
823 children: [
824 Text({bold: true, wrap: 'wrap', children: [t(lang, 'band.question', {percent: open})]}),
825 Box({flexDirection: 'row', flexWrap: 'wrap', columnGap: 1, children: [
826 Button({key: 't1-agree', label: t(lang, 'band.agree'), variant: 'primary', onPress: () => answerT1($, 'agree')}),
827 Button({key: 't1-snooze', label: t(lang, 'band.snooze', {step: 10}), variant: 'secondary', onPress: () => answerT1($, 'snooze')}),
828 Button({key: 't1-suppress', label: t(lang, 'band.suppress'), variant: 'secondary', onPress: () => answerT1($, 'suppress')}),
829 ]}),
830 ],
831 }));
832 }
833 return Box({flexDirection: 'column', children: blocks});
834 });
835}
836hooks/config.js 17 lines1const DEFAULTS = {thresholdPct: 60, lang: 'zh-TW', autoNote: true};
2const LANGS = ['zh-TW', 'en'];
3
4/** A whole percentage from 1 to 99, given as a number or a digit string; anything else is undefined. */
5const asPct = (value) => {
6 const n = typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : value;
7 return Number.isInteger(n) && n >= 1 && n <= 99 ? n : undefined;
8};
9
10/** Resolve settings: test-only env overrides win, then userConfig, then defaults. Never throws. */
11export function resolveConfig({env = {}, userConfig = {}} = {}) {
12 const lang = LANGS.includes(env.HANDOFF_LANG) ? env.HANDOFF_LANG : LANGS.includes(userConfig.lang) ? userConfig.lang : DEFAULTS.lang;
13 const flag = String(env.HANDOFF_AUTO_NOTE ?? '').toLowerCase();
14 const autoNote = flag === 'off' ? false : flag === 'on' ? true : typeof userConfig.autoNote === 'boolean' ? userConfig.autoNote : DEFAULTS.autoNote;
15 return {thresholdPct: asPct(env.HANDOFF_THRESHOLD_PCT) ?? asPct(userConfig.thresholdPct) ?? DEFAULTS.thresholdPct, lang, autoNote};
16}
17hooks/i18n.js 143 lines1/** All user-facing strings, in one file (D8, D11). Both languages must define the same keys and placeholders. */
2export const STRINGS = {
3 'zh-TW': {
4 'band.question': 'Context 已用 {percent}%,要先交接嗎?',
5 'band.agree': '同意',
6 'band.snooze': '再多 {step}% 再問',
7 'band.suppress': '這個 session 別再問',
8 'status.threshold': 'Context 已用 {percent}%。需要時輸入 /handoff-mod:handoff 交接',
9 'ask.clear.question': '清除前要留交接檔嗎?',
10 'ask.clear.cancel': '取消',
11 'ask.clear.handoffFirst': '寫交接檔(寫完再 /clear)',
12 'ask.clear.clearNow': '不交接,直接清除',
13 'clear.held': '已暫停清除,交接完成後請再下 /clear。',
14 'clear.cancelled': '已取消清除。',
15 'list.header': '有 {count} 筆未完成交接',
16 'list.bandHint': '(若想放棄交接檔:/handoff-resume drop <編號|all>)',
17 'list.item': '{n}. {task}({branch}・{age})',
18 'list.next': '下一步:{next}',
19 'list.auto': '自動留下,未經審查',
20 'list.more': '還有 {count} 筆',
21 'list.moreCmd': '還有 {count} 筆,輸入 /handoff-resume all 全部列出',
22 'list.older': '同 branch 較舊的自動筆記',
23 'list.claimed': '另一個 session 正在接續',
24 'list.resume': '接續',
25 'list.skip': '本 session 忽略',
26 'list.none': '目前沒有未完成的交接。',
27 'status.pending': '有 {count} 筆未完成交接,輸入 /handoff-resume 查看',
28 'resume.prompt': '請先讀 {path},驗證其中前提是否仍成立,再接續「下一步」。',
29 'resume.claimedElsewhere': '這份交接正由另一個 session 接續。',
30 'toast.written': '交接已寫入 {path}',
31 'toast.invalid': '未偵測到有效交接檔',
32 'fresh.branchGone': 'branch {branch} 已不存在',
33 'fresh.ahead': '交接後 {branch} 多了 {count} 個 commit',
34 'fresh.merged': '交接的 HEAD 已包含在 {base}',
35 'fresh.unverifiable': '無法驗證(不在 git 內或缺少資料)',
36 'age.minutes': '{n} 分鐘前',
37 'age.hours': '{n} 小時前',
38 'age.days': '{n} 天前',
39 'stats.line': '交接寫入 {written} 次,接續 {resumed} 次',
40 'cmd.resume': '列出未完成的交接;/handoff-resume <編號> 接續其中一筆;drop <編號|all> 放棄',
41 'cmd.resume.hint': '[編號|all|drop]',
42 'cmd.stats': '顯示這台機器上交接寫入與接續的次數(只存在本機,不外傳)',
43 'list.bad': '沒有第 {n} 筆。',
44 'list.dropHint': '(若想放棄交接檔:/handoff-resume drop <編號|all>)',
45 'drop.usage': '用法:/handoff-resume drop <編號|all>',
46 'drop.header': '已放棄 {count} 筆,剩下的編號已重排:',
47 'drop.claimed': '另一個 session 正在接續,沒有放棄:{title}',
48 'drop.none': '沒有可以放棄的交接。',
49 'note.task': '## 任務',
50 'note.next': '## 下一步',
51 'note.nextText': '請先看「最後一個要求」與「最後一段回應」,確認現況再接續。',
52 'note.unreviewed': '> 自動留下,未經審查。',
53 'note.lastRequest': '## 最後一個要求',
54 'note.lastResponse': '## 最後一段回應',
55 'note.state': '## 狀態(事實)',
56 'note.branchLine': 'branch:{branch}',
57 'note.headLine': 'HEAD:{head}',
58 'note.changed': '## 有改動的檔案',
59 },
60 en: {
61 'band.question': 'Context is {percent}% full. Write a handoff first?',
62 'band.agree': 'Yes',
63 'band.snooze': 'Ask again in {step}%',
64 'band.suppress': 'Not this session',
65 'status.threshold': 'Context is {percent}% full. Run /handoff-mod:handoff to hand off',
66 'ask.clear.question': 'Create a handoff file before clearing?',
67 'ask.clear.cancel': 'Cancel',
68 'ask.clear.handoffFirst': 'Write a handoff (then run /clear)',
69 'ask.clear.clearNow': 'Clear without a handoff',
70 'clear.held': 'Clear is on hold. Run /clear again once the handoff is written.',
71 'clear.cancelled': 'Clear cancelled.',
72 'list.header': '{count} unfinished handoff(s)',
73 'list.bandHint': '(To abandon a handoff: /handoff-resume drop <n|all>)',
74 'list.item': '{n}. {task} ({branch}, {age})',
75 'list.next': 'Next: {next}',
76 'list.auto': 'Saved automatically, not reviewed',
77 'list.more': '{count} more',
78 'list.moreCmd': '{count} more. Run /handoff-resume all to list them all',
79 'list.older': 'Older automatic note on the same branch',
80 'list.claimed': 'Another session is resuming this',
81 'list.resume': 'Resume',
82 'list.skip': 'Ignore for this session',
83 'list.none': 'No unfinished handoffs.',
84 'status.pending': '{count} unfinished handoff(s). Run /handoff-resume to see them',
85 'resume.prompt': 'Read {path} first, check that its premises still hold, then continue from "Next".',
86 'resume.claimedElsewhere': 'Another session is already resuming this handoff.',
87 'toast.written': 'Handoff written to {path}',
88 'toast.invalid': 'No valid handoff file was found',
89 'fresh.branchGone': 'Branch {branch} no longer exists',
90 'fresh.ahead': '{branch} has {count} new commit(s) since the handoff',
91 'fresh.merged': 'The handoff HEAD is already in {base}',
92 'fresh.unverifiable': 'Cannot verify (not in git, or data missing)',
93 'age.minutes': '{n} min ago',
94 'age.hours': '{n} h ago',
95 'age.days': '{n} d ago',
96 'stats.line': 'Handoffs written: {written}, resumed: {resumed}',
97 'cmd.resume': 'List unfinished handoffs; "/handoff-resume <n>" resumes one; "drop <n|all>" abandons',
98 'cmd.resume.hint': '[n|all|drop]',
99 'cmd.stats': 'Show how many handoffs were written and resumed on this machine (kept local, never sent)',
100 'list.bad': 'There is no item {n}.',
101 'list.dropHint': '(To abandon a handoff: /handoff-resume drop <n|all>)',
102 'drop.usage': 'Usage: /handoff-resume drop <n|all>',
103 'drop.header': 'Abandoned {count}; the remaining items are renumbered:',
104 'drop.claimed': 'Another session is resuming this, not abandoned: {title}',
105 'drop.none': 'Nothing to abandon.',
106 'note.task': '## Task',
107 'note.next': '## Next',
108 'note.nextText': 'Read "Last request" and "Last response" first, check the current state, then continue.',
109 'note.unreviewed': '> Saved automatically; not reviewed.',
110 'note.lastRequest': '## Last request',
111 'note.lastResponse': '## Last response',
112 'note.state': '## State (facts)',
113 'note.branchLine': 'Branch: {branch}',
114 'note.headLine': 'HEAD: {head}',
115 'note.changed': '## Changed files',
116 },
117};
118
119/** Look up a string and fill its {placeholders}. An unknown language falls back to zh-TW; a missing key or variable throws, so mistakes show up in tests. */
120export function t(lang, key, vars = {}) {
121 const table = STRINGS[lang] ?? STRINGS['zh-TW'];
122 if (!Object.hasOwn(table, key)) throw new Error(`i18n: unknown key ${key}`);
123 return table[key].replace(/\{(\w+)\}/g, (_, name) => {
124 if (!Object.hasOwn(vars, name)) throw new Error(`i18n: missing variable ${name} for ${key}`);
125 return String(vars[name]);
126 });
127}
128
129/** The three choices of the /clear prompt, in the order shown: the first one is what a stray Enter picks (D13). */
130export const clearOptions = (lang) => [t(lang, 'ask.clear.cancel'), t(lang, 'ask.clear.handoffFirst'), t(lang, 'ask.clear.clearNow')];
131
132const isWide = (cp) =>
133 (cp >= 0x1100 && cp <= 0x115f) || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) ||
134 (cp >= 0xf900 && cp <= 0xfaff) || (cp >= 0xfe30 && cp <= 0xfe4f) || (cp >= 0xff00 && cp <= 0xff60) ||
135 (cp >= 0xffe0 && cp <= 0xffe6) || (cp >= 0x1f300 && cp <= 0x1faff) || (cp >= 0x20000 && cp <= 0x3fffd);
136
137/** Terminal columns a string takes: CJK and emoji count as two. */
138export function displayWidth(text) {
139 let width = 0;
140 for (const ch of String(text)) width += isWide(ch.codePointAt(0)) ? 2 : 1;
141 return width;
142}
143hooks/handoff-file.js 79 lines1import {stripControl, truncateCodePoints} from './sanitize.js';
2
3const MAX_READ = 64 * 1024;
4export const OPEN_STATUSES = ['in-progress', 'blocked', 'ready-for-review'];
5
6/** Section headings, Chinese or English (D11), matched on the start of the heading text. */
7const HEADINGS = [
8 ['task', /^(任務|task)/i],
9 ['done', /^(已完成|done|completed)/i],
10 ['todo', /^(未完成|remaining|todo|to-do|not done)/i],
11 ['next', /^(下一步|next)/i],
12 ['premises', /^(前提|premises|assumptions)/i],
13 ['rules', /^(規矩|rules|constraints)/i],
14 ['verified', /^(已驗證|verified)/i],
15];
16
17const oneLine = (text, max) => truncateCodePoints(stripControl(String(text)).replace(/\s+/g, ' ').trim(), max);
18const value = (raw) => {
19 const text = String(raw).replace(/\s+#.*$/, '').trim();
20 return /^(["']).*\1$/.test(text) ? text.slice(1, -1) : text;
21};
22const firstLine = (lines = []) => {
23 const line = lines.map((l) => l.trim()).find(Boolean);
24 return line === undefined ? undefined : line.replace(/^(?:[-*+]\s+|\d+[.)]\s+)?(?:\[[ xX]\]\s*)?/, '');
25};
26
27/** Split `---` frontmatter from the body; null when the file has none. */
28function split(text) {
29 const t = text.replace(/^/, '').replace(/\r\n?/g, '\n');
30 if (!t.startsWith('---\n')) return null;
31 let from = 3;
32 for (;;) {
33 const at = t.indexOf('\n---', from);
34 if (at === -1) return null;
35 const after = t[at + 4];
36 if (after === undefined || after === '\n') return {front: t.slice(4, at + 1), body: t.slice(at + 5)};
37 from = at + 4;
38 }
39}
40
41/**
42 * Parse a handoff file. Returns {ok:true, meta, fields} or {ok:false, reason}.
43 * A closed file (a status that is set but not open) is {ok:false, reason:'status', meta, fields}: still not a handoff to
44 * list, but its meta lets it close its copies in other working trees (D20).
45 * Everything from the file is a plain string: nothing is executed, and branch/head are validated later, before git sees them.
46 */
47export function parseHandoff(input) {
48 const parts = split(String(input ?? '').slice(0, MAX_READ));
49 if (!parts) return {ok: false, reason: 'frontmatter'};
50 const fm = {};
51 for (const line of parts.front.split('\n')) {
52 const m = /^([A-Za-z_][A-Za-z0-9_-]*):[ \t]*(.*)$/.exec(line);
53 if (m && !(m[1] in fm)) fm[m[1]] = value(m[2]);
54 }
55 const open = OPEN_STATUSES.includes(fm.status);
56 if (!open && (typeof fm.status !== 'string' || fm.status === '')) return {ok: false, reason: 'status'};
57 const created = Date.parse(fm.created);
58 if (!Number.isFinite(created)) return {ok: false, reason: open ? 'created' : 'status'};
59 const text = (v) => (v === undefined || v === '' ? undefined : oneLine(v, 500));
60
61 const sections = {};
62 let current = null;
63 for (const line of parts.body.split('\n')) {
64 if (line.startsWith('## ')) {
65 const heading = line.slice(3).trim();
66 current = HEADINGS.find(([, pattern]) => pattern.test(heading))?.[0] ?? null;
67 if (current && !sections[current]) sections[current] = [];
68 } else if (current) sections[current].push(line);
69 }
70 const parsed = {
71 meta: {
72 schema: text(fm.schema), root: text(fm.root ?? fm.worktree), repo: text(fm.repo), branch: text(fm.branch),
73 head: text(fm.head), created, status: fm.status, source: text(fm.source),
74 },
75 fields: {task: oneLine(fm.task ?? firstLine(sections.task) ?? '', 80), next: oneLine(firstLine(sections.next) ?? '', 120)},
76 };
77 return open ? {ok: true, ...parsed} : {ok: false, reason: 'status', ...parsed};
78}
79hooks/rank.js 37 lines1import {OPEN_STATUSES} from './handoff-file.js';
2
3const DAY = 24 * 3600 * 1000;
4const FOLD_AFTER = 14 * DAY;
5const AUTO_HIDE_AFTER = 7 * DAY;
6const SHOWN = 3;
7
8/** Newest first; the path settles a tie so the order never depends on the input order. */
9const byNewest = (a, b) => b.meta.created - a.meta.created || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
10/** Automatic notes of one working tree and branch; with no branch, of one working tree. */
11const groupKey = (item) => `${item.meta.root ?? ''}\u0000${item.meta.branch ?? ''}`;
12
13/**
14 * Pick what the start-up list shows. `items` are {path, meta, effectiveStatus, claimedByOther}.
15 * Same working tree first, then same repository, then newest; the order never depends on the input order.
16 * Returns {shown, rest, collapsed, hidden}: `rest` is everything not shown (folded by age, by the limit of three, or because
17 * it is an older automatic note on a branch that has a newer one, D15; those carry `olderAuto: true`). `collapsed` is
18 * `rest.length`. `hidden` counts automatic notes older than 7 days, which are neither shown nor in `rest`.
19 */
20export function rankHandoffs(items, {base, repo, now}) {
21 const open = items.filter((item) => OPEN_STATUSES.includes(item.effectiveStatus));
22 const live = open.filter((item) => !(item.meta.source === 'auto' && now - item.meta.created > AUTO_HIDE_AFTER));
23 const hidden = open.length - live.length;
24 const newestAuto = new Map();
25 for (const item of live) {
26 if (item.meta.source !== 'auto') continue;
27 const best = newestAuto.get(groupKey(item));
28 if (!best || byNewest(item, best) < 0) newestAuto.set(groupKey(item), item);
29 }
30 const flagged = live.map((item) => (item.meta.source === 'auto' && newestAuto.get(groupKey(item)) !== item ? {...item, olderAuto: true} : item));
31 const score = (item) => (base && item.meta.root === base ? 0 : repo && item.meta.repo === repo ? 1 : 2);
32 const sorted = flagged.sort((a, b) => score(a) - score(b) || byNewest(a, b));
33 const shown = sorted.filter((item) => !item.olderAuto && now - item.meta.created <= FOLD_AFTER).slice(0, SHOWN);
34 const rest = sorted.filter((item) => !shown.includes(item));
35 return {shown, rest, collapsed: rest.length, hidden};
36}
37hooks/freshness.js 47 lines1const HEAD_RE = /^[0-9a-f]{4,40}$/;
2const BRANCH_RE = /^[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
3
4/** A branch name that cannot be read as an option or a path trick. Values from a handoff file are untrusted. */
5const validBranch = (name) => typeof name === 'string' && BRANCH_RE.test(name) && !name.includes('..') && !name.endsWith('/') && !name.endsWith('.lock');
6const validHead = (head) => typeof head === 'string' && HEAD_RE.test(head);
7
8/**
9 * Facts about how the repository moved since a handoff was written. `git(args)` is injected and resolves to {exitCode, stdout}.
10 * The result is a list of facts, never a verdict; any git command that fails only drops its own line.
11 */
12export async function freshnessFacts({meta, git}) {
13 const branch = validBranch(meta.branch) ? meta.branch : null;
14 const head = validHead(meta.head) ? meta.head : null;
15 if (!meta.repo || (!branch && !head)) return [{kind: 'unverifiable'}];
16
17 const run = async (args) => {
18 try {
19 const result = await git(args);
20 return result && typeof result.exitCode === 'number' ? result : null;
21 } catch {
22 return null;
23 }
24 };
25 const facts = [];
26 let branchExists = false;
27 if (branch) {
28 const found = await run(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
29 if (found && found.exitCode !== 0) facts.push({kind: 'branchGone', branch});
30 else if (found) branchExists = true;
31 }
32 if (branch && head && branchExists) {
33 const counted = await run(['rev-list', '--count', `${head}..refs/heads/${branch}`]);
34 const count = counted && counted.exitCode === 0 ? Number.parseInt(String(counted.stdout).trim(), 10) : NaN;
35 if (Number.isFinite(count) && count > 0) facts.push({kind: 'ahead', branch, count});
36 }
37 if (head) {
38 const named = await run(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']);
39 const base = named && named.exitCode === 0 ? String(named.stdout).trim() : '';
40 if (validBranch(base)) {
41 const contained = await run(['merge-base', '--is-ancestor', head, base]);
42 if (contained && contained.exitCode === 0) facts.push({kind: 'merged', base});
43 }
44 }
45 return facts;
46}
47hooks/claim.js 31 lines1export const CLAIM_TTL_MS = 12 * 3600 * 1000;
2
3const valid = (entry) => entry && typeof entry === 'object' && typeof entry.sessionId === 'string' && typeof entry.at === 'number';
4
5/** How a stored claim looks to this session: free, mine, other (live) or expired. */
6export function claimView(entry, sessionId, now) {
7 if (!valid(entry)) return {state: 'free'};
8 if (now - entry.at > CLAIM_TTL_MS) return {state: 'expired', holder: entry.sessionId};
9 return entry.sessionId === sessionId ? {state: 'mine'} : {state: 'other', holder: entry.sessionId};
10}
11
12/**
13 * Claim a handoff for this session under every key in `keys` (the new key first, then each copy's old path key, D22).
14 * A live claim by another session under any key wins. A get followed by a set is not atomic, so the first key is read
15 * back and the winner is whoever is there. If the store fails, resuming is still allowed: `degraded` says the duplicate
16 * guard is off.
17 */
18export async function tryClaim({keys, sessionId, now, store}) {
19 try {
20 for (const key of keys) {
21 const view = claimView(await store.get(key), sessionId, now);
22 if (view.state === 'other') return {won: false, holder: view.holder};
23 }
24 for (const key of keys) await store.set(key, {sessionId, at: now});
25 const back = await store.get(keys[0]);
26 return valid(back) && back.sessionId === sessionId ? {won: true} : {won: false, holder: valid(back) ? back.sessionId : undefined};
27 } catch {
28 return {won: true, degraded: true};
29 }
30}
31hooks/identity.js 49 lines1/*
2 * D20 to D22: one handoff is its file name plus its created time, so copies of one file in several working trees (or
3 * left behind by a moved folder) are one handoff. State is kept under a key built from that, and, for 0.1.x, under each
4 * copy's absolute path as well.
5 */
6
7const nameOf = (path) => path.slice(path.lastIndexOf('/') + 1);
8const dirOf = (path) => path.slice(0, path.lastIndexOf('/'));
9
10/** D20: `<file name>|<created as ISO>`; `created` is milliseconds, so two spellings of one instant give one key. */
11export function handoffKey(name, created) {
12 return `${name}|${new Date(created).toISOString()}`;
13}
14
15/**
16 * Group `found` ({path, meta, fields, closed}) by key. Each item shows one copy: the one in `base`'s handoff folder,
17 * else the one in `repo`'s, else the first found. `paths` keeps every copy in scan order; `fileClosed` is true when any
18 * copy's own status is closed.
19 */
20export function mergeCopies(found, {base, repo, dir}) {
21 const groups = new Map();
22 for (const f of found) {
23 const key = handoffKey(nameOf(f.path), f.meta.created);
24 if (!groups.has(key)) groups.set(key, []);
25 groups.get(key).push(f);
26 }
27 const rank = (f) => (dirOf(f.path) === `${base}/${dir}` ? 0 : repo && dirOf(f.path) === `${repo}/${dir}` ? 1 : 2);
28 return [...groups].map(([key, copies]) => {
29 const shown = copies.reduce((best, f) => (rank(f) < rank(best) ? f : best));
30 return {key, path: shown.path, paths: copies.map((f) => f.path), meta: shown.meta, fields: shown.fields, fileClosed: copies.some((f) => f.closed)};
31 });
32}
33
34/** D21, D22: the new key first, then every copy's old `state:<path>`. New keys start with `id:`, old ones with `/`. */
35export const stateKeys = (item) => [`state:id:${item.key}`, ...item.paths.map((path) => `state:${path}`)];
36
37/** The same for claims. */
38export const claimKeys = (item) => [`claim:id:${item.key}`, ...item.paths.map((path) => `claim:${path}`)];
39
40/** The newest stored record that has a status, or undefined. Anything else in the store is ignored. */
41export function newestState(records) {
42 let best;
43 for (const record of records) {
44 if (!record || typeof record !== 'object' || typeof record.status !== 'string') continue;
45 if (!best || Number(record.at) > Number(best.at)) best = record;
46 }
47 return best;
48}
49hooks/snapshot.js 55 lines1/*
2 * D23: an end-of-session note is written only when this session changed the working tree. The first request records
3 * what was already dirty (code, path, mtime); the end compares against it.
4 */
5
6export const BASELINE_MAX = 50;
7
8const isDeletion = (code) => code.includes('D');
9const idOf = (entry) => `${entry.code}\u0000${entry.path}`;
10
11/**
12 * Parse `git status --porcelain -z`: NUL-separated `XY path` entries, paths relative to the repository root and never
13 * quoted. A rename or copy is followed by its old path as one more field, which is skipped.
14 */
15export function parseStatusZ(stdout) {
16 const fields = String(stdout ?? '').split('\0');
17 const entries = [];
18 for (let i = 0; i < fields.length; i++) {
19 const field = fields[i];
20 if (field.length < 4) continue;
21 const code = field.slice(0, 2);
22 entries.push({code, path: field.slice(3)});
23 if (/[RC]/.test(code)) i++;
24 }
25 return entries;
26}
27
28/** `statted` are {code, path, mtimeMs} (a deletion has null); `total` is how many entries git listed. */
29export function takeBaseline(statted, total) {
30 return {
31 entries: statted.slice(0, BASELINE_MAX).map(({code, path, mtimeMs}) => ({code, path, mtimeMs: mtimeMs ?? null})),
32 truncated: total > BASELINE_MAX,
33 };
34}
35
36/** Is any of `current` ({code, path}) missing from the baseline? Needs no stat. */
37export function hasNewEntry(baseline, current) {
38 const known = new Set(baseline.entries.map(idOf));
39 return current.some((entry) => !known.has(idOf(entry)));
40}
41
42/**
43 * Did the session change anything? Yes for a new code and path, a different mtime, or an unreadable file that is not a
44 * deletion. A deletion from before the session that was left alone is null on both sides, which is no change.
45 */
46export function changedSince(baseline, current) {
47 const before = new Map(baseline.entries.map((entry) => [idOf(entry), entry.mtimeMs]));
48 for (const entry of current) {
49 if (!before.has(idOf(entry))) return true;
50 if (entry.mtimeMs === null && !isDeletion(entry.code)) return true;
51 if (before.get(idOf(entry)) !== entry.mtimeMs) return true;
52 }
53 return false;
54}
55hooks/exclude.js 23 lines1/**
2 * Keep a path pattern (such as ".claude/handoffs/") out of `git status` by adding it to .git/info/exclude.
3 * `git(args)` resolves to {exitCode, stdout}; `fs` has exists/read/write. Idempotent, never throws.
4 * Returns {ok, changed} or {ok:false, skipped:true} outside a git repository.
5 */
6export async function ensureExcluded({git, fs, pattern}) {
7 try {
8 const ignored = await git(['check-ignore', '-q', '--', `${pattern}_probe`]);
9 if (ignored.exitCode === 0) return {ok: true, changed: false};
10 if (ignored.exitCode !== 1) return {ok: false, skipped: true};
11 const located = await git(['rev-parse', '--git-path', 'info/exclude']);
12 const path = located.exitCode === 0 ? String(located.stdout).trim() : '';
13 if (!path) return {ok: false};
14 const current = (await fs.exists(path)) ? await fs.read(path) : '';
15 if (current.split('\n').some((line) => line.trim() === pattern)) return {ok: true, changed: false};
16 const separator = current === '' || current.endsWith('\n') ? '' : '\n';
17 await fs.write(path, `${current}${separator}${pattern}\n`);
18 return {ok: true, changed: true};
19 } catch {
20 return {ok: false};
21 }
22}
23hooks/sanitize.js 53 lines1/*
2 * Cleaning for text that came from a file or a conversation before it is shown or stored.
3 *
4 * redactSecrets covers these shapes, no more. It lowers the risk; it is NOT a guarantee that a secret never survives.
5 * 1 private key blocks (terminated, or cut off) 2 Authorization: Bearer/Basic/Token values
6 * 3 user:password@ in URLs 4 JWTs (three dot-separated base64url parts)
7 * 5 AWS access key ids (AKIA/ASIA) 6 GitHub tokens (ghp_/gho_/ghu_/ghs_/ghr_, github_pat_)
8 * 7 Slack tokens (xox[baprs]-) 8 sk- style API keys
9 * 9 name=value / name: value where the name contains api key, secret, token, passwd, password, pwd, access key or private key
10 * Words about secrets without an assignment ("password policy", "token count") are left alone; an assignment such as
11 * "tokens: 1000" is redacted even though it is harmless, which is the safe direction.
12 */
13const REDACTED = '[redacted]';
14const RULES = [
15 [/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g, REDACTED],
16 [/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*$/g, REDACTED],
17 [/(\bAuthorization\s*:\s*(?:Bearer|Basic|Token)\s+)[^\s'"]+/gi, `$1${REDACTED}`],
18 [/(\b[a-z][a-z0-9+.-]*:\/\/)[^\s/:@]+:[^\s/@]+@/gi, `$1${REDACTED}@`],
19 [/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g, REDACTED],
20 [/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, REDACTED],
21 [/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, REDACTED],
22 [/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, REDACTED],
23 [/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, REDACTED],
24 [/\bsk-[A-Za-z0-9_-]{20,}\b/g, REDACTED],
25 [/([A-Za-z0-9_-]*(?:api[_-]?key|secret|token|passwd|password|pwd|access[_-]?key|private[_-]?key)[A-Za-z0-9_-]*\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, `$1${REDACTED}`],
26];
27
28/** Remove terminal escapes and control characters; keep newlines, tabs, CJK and emoji. CRLF becomes LF. */
29export function stripControl(text) {
30 return String(text)
31 .replace(/\r\n?/g, '\n')
32 .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, '')
33 .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
34 .replace(/\x1b[@-Z\\-_]/g, '')
35 .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
36}
37
38/** Cut to at most `max` Unicode code points, ending with an ellipsis when something was removed. */
39export function truncateCodePoints(text, max) {
40 const value = String(text);
41 const points = [...value];
42 return points.length <= max ? value : `${points.slice(0, Math.max(0, max - 1)).join('')}…`;
43}
44
45export function redactSecrets(text) {
46 let out = String(text);
47 for (const [pattern, replacement] of RULES) out = out.replace(pattern, replacement);
48 return out;
49}
50
51/** The pipeline for quoted text. The order matters: redact before truncating, so a cut can never leave half a secret. */
52export const cleanForNote = (text, max) => truncateCodePoints(redactSecrets(stripControl(text)), max);
53hooks/note.js 66 lines1import {cleanForNote} from './sanitize.js';
2import {t} from './i18n.js';
3
4const QUOTE_MAX = 2000;
5const FILES_MAX = 50;
6
7/** The end-of-session note is written only for an interactive session that did something and is not being cleared (T2 handles /clear). */
8export const shouldWriteNote = ({interactive, turns, hasUnfinishedSign, reason, config}) =>
9 Boolean(interactive && turns > 0 && hasUnfinishedSign && reason !== 'clear' && config?.autoNote);
10
11const pad = (n) => String(n).padStart(2, '0');
12const stamp = (ms) => {
13 const d = new Date(ms);
14 return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
15};
16const safeBranch = (branch) => String(branch ?? '').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'no-branch';
17const single = (text, max) => cleanForNote(text, max).replace(/\s+/g, ' ').trim();
18/** Quote each line, so a "## heading" inside quoted text can never become a section of the note. */
19const quote = (text) => text.split('\n').map((line) => `> ${line}`).join('\n');
20
21/** Build the facts-only note: the last request, the last response, git state and changed files. No tool output, nothing earlier. */
22export function buildEndNote({lastRequest, lastResponse, branch, head, dirtyFiles = [], root, repo, now, lang}) {
23 const request = cleanForNote(lastRequest ?? '', QUOTE_MAX);
24 const response = cleanForNote(lastResponse ?? '', QUOTE_MAX);
25 const task = single(request.split('\n').find((line) => line.trim()) ?? '', 80);
26 const front = ['schema: 1', `root: ${single(root ?? '', 300)}`];
27 if (repo) front.push(`repo: ${single(repo, 300)}`);
28 if (branch) front.push(`branch: ${single(branch, 200)}`);
29 if (head) front.push(`head: ${single(head, 64)}`);
30 front.push(`created: ${new Date(now).toISOString()}`, `task: ${task}`, 'status: in-progress', 'source: auto');
31
32 const state = [];
33 if (branch) state.push(`- ${t(lang, 'note.branchLine', {branch: single(branch, 200)})}`);
34 if (head) state.push(`- ${t(lang, 'note.headLine', {head: single(head, 64)})}`);
35 const files = dirtyFiles.slice(0, FILES_MAX).map((file) => `- ${single(file, 200)}`);
36
37 const body = [
38 t(lang, 'note.task'), task, '',
39 t(lang, 'note.next'), t(lang, 'note.nextText'), '',
40 t(lang, 'note.unreviewed'), '',
41 t(lang, 'note.lastRequest'), quote(request), '',
42 t(lang, 'note.lastResponse'), quote(response), '',
43 ...(state.length ? [t(lang, 'note.state'), ...state, ''] : []),
44 ...(files.length ? [t(lang, 'note.changed'), ...files, ''] : []),
45 ];
46 return {fileName: `${safeBranch(branch)}--${stamp(now)}--auto.md`, content: `---\n${front.join('\n')}\n---\n\n${body.join('\n')}`};
47}
48
49/**
50 * Run `run()` but give up after `ms`. `after(ms, cb)` is $.clock.after, injected because a hooks module has no timers of its own.
51 * Resolves to {value}, {timedOut: true} or {error}; the caller must write nothing when it timed out.
52 */
53export function withDeadline(run, ms, after) {
54 return new Promise((resolve) => {
55 let settled = false;
56 const finish = (result, timer) => {
57 if (settled) return;
58 settled = true;
59 timer?.cancel?.();
60 resolve(result);
61 };
62 const timer = after(ms, () => finish({timedOut: true}));
63 run().then((value) => finish({value}, timer), (error) => finish({error}, timer));
64 });
65}
66