SLOPSHOPPER

todo-pane

Shows this session's todo list (what we are working on) and pin board (pinned notes) in side panes, one file per session under a directory

paneguardcommandtoaststatusprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · todo-pane
│ ┃ TODO ✕ › fix the failing auth test and add an audit log call │ ┃ (No TODO yet) │ ┃ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /todo-pane │ ⎿ todo-pane: Brought forward. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · TODO
(No TODO yet)
Pane · Pins
(Nothing pinned yet)
README

todo-pane

日本語

A plugin that keeps Claude's current task list in a pane next to the conversation.

During a long session in Claude Code, side trips and confirmations make it easy to lose track of what is being done now and what is left. With todo-pane installed, Claude writes each piece of work to the task list before starting it, and when it finishes, checks it off and moves it under "Done (date)". Look at the right-hand pane at any time to see the current work and what remains.

Claude Code conversation on the left, a pane with "TODO" and "Pins" tabs on the right

The pane has two tabs.

  • TODO shows progress. Claude writes what it is doing now, what remains and what is done, and updates it as the work goes on. Things you are waiting to confirm or want to check later go here too, as part of the work.
  • Pins (「ピン留め」 in Japanese) holds reference material you want to look back at while working: an explanation Claude gave, a comparison table, a summary of what you decided. Claude writes to it only when asked to pin something, and does not update it as work progresses.

Some ways to use pins:

  • Ask Claude to explain how something works or walk through a procedure, then ask it to pin the answer. The answer stays beside the conversation instead of scrolling away.
  • Ask Claude to pin research results such as URLs, commands and setting values. You can check them in the pane when needed instead of asking again.

Both tabs are plain Markdown files, one file per session. When Claude rewrites a file, the pane updates right away.

The pane and the instructions to Claude are implemented by a mod (a function hook that runs inside Claude Code) in the plugin. Mods arrived in Claude Code 2.1.287, so 2.1.287 or later is required.

Install

/plugin marketplace add aromarious/claude-code-plugins
/plugin install todo-pane@aromarious

Right after installing, a "Configure todo-pane" screen appears. Skip it without entering anything and the files are created under the default .claude.

Commands

CommandKindWhat it does
/todo-paneMod commandOpens the TODO pane, or closes it if it is open. Opening creates the todo file if it is missing
/todo-pane-pinboardMod commandOpens the Pins pane, or closes it if it is open
/todo-pane-wrapMod commandSwitches long lines in the tab in front between being cut with "…" and wrapping onto the next row. Each tab keeps its own choice across sessions; TODO starts cut, Pins start wrapped. With neither tab in front it does nothing
/todo-pane:pin [what to pin]SkillPins the main content of Claude's last reply. With text after it, pins what the text describes

The ✕ button at the top right of a pane also closes it. Run the command again to reopen it.

To toggle wrapping with a key, bind the command in ~/.claude/keybindings.json. Claude Code keybindings can run a slash command with the action "command:<name>":

{ "bindings": [ { "context": "Chat", "bindings": { "meta+z": "command:todo-pane-wrap" } } ] }

On macOS, Option+Z reaches Claude Code as Meta+Z only if the terminal sends it that way. In Ghostty, add keybind = alt+z=esc:z to its config (and keybind = cmd+alt+z=esc:z to also use Cmd+Alt+Z). The command: action is not in the official keybindings documentation (it was found in Claude Code itself), so it may change.

When the TODO pane is not visible

If Claude Code's own diff pane (the pane that shows git changes) is open, the TODO pane is hidden behind it, and running /todo-pane does not bring it forward. If the right side shows a list of changed files or "Diff unavailable", that is the diff pane. Run /diff or click the ✕ at its top right to close it.

The diff pane can open by itself in a git repository when the screen is wide. Once you close it with /diff or ✕, that state is saved as diffSidebarOpen in ~/.claude.json and it no longer opens automatically.

Components

ComponentUsedFilesRole
Function hook (mod)Yesmodules in hooks/hooks.json, hooks/register.tsxDraws the panes, adds instructions for Claude on every prompt, detects a missed update, provides the /todo-pane and /todo-pane-pinboard commands
Setting (userConfig)Yes.claude-plugin/plugin.jsonLets you change the directory dir where files are kept (Settings)
CommandsYeshooks/register.tsx/todo-pane and /todo-pane-pinboard. Not command files; the mod registers them at startup
SkillYesskills/pin/SKILL.md/todo-pane:pin, which pins something to the Pins pane
Shell command hookNo——
Command files, agents, MCP serversNo——

Claude Code has two kinds of hooks: hooks that run a shell command when an event occurs, and hooks that run a function inside Claude Code (mods). todo-pane uses function hooks only. hooks/hooks.json just tells Claude Code to load the module that holds them (register.tsx).

The mod registers functions for these events.

EventWhat it does
session.startDetects the display language, opens the panes, starts re-reading the files every 3 seconds, and last registers /todo-pane and /todo-pane-pinboard (a name already taken does not stop the rest)
prompt.submitOn every prompt, attaches instructions for Claude that match the current state
turn.startRemembers the contents of the todo file at the start of the turn
tool.callRecords whether a tool that changes files or Notion was called
turn.completeIf something was changed but the todo file was not, shows a notice and a status line
command.runOn /todo-pane or /todo-pane-pinboard, opens the pane in front if it is closed, brings it forward if another tab is in front, and closes it if it is already in front. Opening with /todo-pane also creates the todo file if it is missing
ui.closeRemembers that a pane was closed (by a command or by ✕), so the next command opens it again
skill.promptWhen /todo-pane:pin runs, adds the session's pin file path to the skill text and opens the Pins pane
ui.renderDraws the pane contents (the Markdown of the todo file and the pin file)

External commands

The mod runs the following commands. All of them come with macOS and Linux. Windows has not been tested.

CommandPurpose
sh, ls, tailRead the last 500 lines of the session transcript (JSONL) to get the session name (every 3 seconds)
rmDelete the old-name files when the session name changes and the files are renamed

Files shown

One file of each kind is kept per session, under .claude/ relative to the directory where the session was started.

FilePane nameWhen it opens
.claude/todo/<name>.mdTODOAlways opens at session start
.claude/pin/<name>.mdPinsOpens at session start if the file exists
.claude/todo/done/<date>.md(no pane; the latest three are shown under the TODO tab)Where the previous day's done items are moved when the date changes
.claude/todo/<name>.off(no pane)Records that you answered "don't create" in this session

<name> is <session name>-<first 6 characters of the session ID> when the session has a name, and the first 8 characters of the session ID otherwise. /, \, : and control characters in the session name are replaced with _. Emoji and Japanese are kept as they are.

The pane re-reads the files every 3 seconds. A closed pane can be reopened with /todo-pane or /todo-pane-pinboard, and the ✕ button at the top right of a pane closes it, just like running the command again.

The session name comes from the latest custom-title line in the session transcript (JSONL). When the name changes mid-session, <name> is recomputed during the 3-second re-read, and the existing todo, pin and off files are moved to the new name.

When the date changes

The date in the todo file's "## Done (YYYY-MM-DD)" heading (in Japanese, "## やったこと(YYYY-MM-DD)") is today's date in local time. When the date changes, at the next prompt or pane re-read, the contents of every earlier day's done section (more than one can pile up in the todo file) are moved to <dir>/todo/done/<date>.md and the todo file's heading is changed to today's date. In the destination file they go under a "## Session <name>" heading. There is one file per date, shared by the sessions in the same directory. The older "## 今日やったこと" heading is read as the dated heading. A done heading in any language is accepted, and the heading written afterwards is in the current language.

Under the TODO tab, a divider follows the todo file, then this session's completed items (- [x], found under its own "## Session" headings, so other sessions' items sharing the same done files are left out) of up to three earlier days on which the session has any, newest first, drawn faint and each under a #### Done (date) heading. The newest of them is always shown in full. The next two are added only while the pane has rows left: a day that does not fit is cut to its last items that do, followed by a line "…and N more" with the location of the source file, and the days after it are left out. When some earlier day is not fully shown, or the session has items on a still earlier day, a last line "Earlier: <dir>/todo/done/" points to the folder. This is display only; it is not written to the todo file.

A "## " section with nothing under it is shown with an italic "(none)" below its heading (in Japanese, "(なし)"). This is display only too; the todo file is not changed. "###" sub-headings are shown prefixed with their parent heading and a number (e.g. "待ち-1."), and an empty sub-heading gets the label too.

/todo-pane-wrap acts on the tab in front, and each tab remembers its own setting. The TODO tab starts out cutting long lines with "…" to fit the pane's current width instead of wrapping, and the cut is recomputed when the width changes. The Pins tab starts out wrapping; when it is switched to cutting, tables are fitted too, by shortening the cells of the widest columns with "…" (wrap mode shows them in full), and code blocks are left whole. The todo and pin files keep the full text.

Settings

One setting can be changed. It is a path relative to the working directory; an absolute path also works. A changed setting takes effect from the next session.

SettingDefaultMeaning
dir.claudeDirectory that holds todo/ and pin/

Write the value in pluginConfigs in ~/.claude/settings.json. The key is todo-pane@aromarious when installed from the marketplace, and todo-pane or todo-pane@inline when loaded with --plugin-dir.

{
  "pluginConfigs": {
    "todo-pane@aromarious": {
      "options": { "dir": "out" }
    }
  }
}

With this example, the files are out/todo/<name>.md, out/pin/<name>.md and out/todo/<name>.off.

Instructions to Claude

Every time you send a prompt, the following instructions are attached after it and passed to Claude. They are not shown on screen and the prompt text is not changed. They are rebuilt for every prompt, so they reflect the current state, such as whether the todo file exists or whether the session name changed.

The instructions are written in English. The headings in them follow Claude Code's language setting (see Display language): "## Now" and "## Done (date)" in English, "## 今" and "## やったこと(日付)" when the language is Japanese. The instructions also tell Claude to write the items in the language you are writing in, so talking to Claude in Japanese gives Japanese items. The instructions say:

  • The session's todo file is the TODO list shown in the right-hand pane.
  • Write every item as a checkbox: - [ ] for open, - [x] for done. Never use a plain - bullet.
  • Before starting any work that changes files or Notion, first write it under the "now" heading of the todo file.
  • When the work is done, check it and move it under the "done (today's date)" heading, and keep remaining items in their sections.
  • When the topic changes, update the "now" section to match.
  • Write the items in the language the user is writing in.

For pins, the following instruction is attached every time, whether or not the todo file exists and whether or not you answered "don't create".

  • When asked to pin something ("pin that", 「ピン留めして」), write the target (the explanation, comparison table, summary, etc. just given) as Markdown to the session's pin file, creating it if missing. This is the pin tab of this plugin's side pane, not claude.ai Artifact pinning. The instruction also mentions the /todo-pane:pin skill. Write only when asked; do not update it as work progresses.

If a turn changed files or Notion but the todo file did not change, a notice and a status line tell you, and Claude is told to bring the todo file up to date at the start of the next turn. Changes made by subagents are not counted.

Display language

Tab titles, todo-file headings, empty-pane placeholders, the earlier-days block and notices follow Claude Code's language setting. If language names one of the supported languages below, they are in that language; otherwise they are in English. English names, native names and codes all work, in any case (German, Deutsch, de; Traditional Chinese, 繁體中文, zh-TW; pt-BR). A plain Chinese or 中文 is Simplified. The check runs once, at session start.

Supported languages: English, Japanese (日本語), Simplified Chinese (简体中文), Traditional Chinese (繁體中文), Korean (한국어), Spanish (Español), French (Français), German (Deutsch), Portuguese (Português), Italian (Italiano) and Russian (Русский). Other languages are welcome: please open an issue or a pull request. The strings are in the L table at the top of hooks/register.tsx.

The table shows the Japanese and English wording as examples.

ItemJapaneseEnglish
Now heading## 今## Now
Done heading## やったこと(date)## Done (date)
Pin tab titleピン留めPins
Earlier-days heading#### やったこと(date)#### Done (date)
Link to older done filesそれより前: <folder>Earlier: <folder>
Done file title# date にやったこと# Done on date
Done file session heading## セッション <name>## Session <name>
Missed-update notice<file> が更新されていません<file> was not updated

The date rollover described above recognises the done heading of any supported language (## Done (YYYY-MM-DD), ## やったこと(YYYY-MM-DD), ## Erledigt (YYYY-MM-DD), and so on). Any other heading is left alone, even one that ends with a date, such as ## Meeting notes (2026-10-01). A newly written heading uses the current language.

When there is no todo file

In a session that has no todo file of its own, Claude asks in the first turn whether to create one. The question is asked once per session.

  • If you say yes, Claude creates the session's todo file with the "now" and "done (today's date)" headings (in the language from the table above).
  • If you say no, Claude creates an empty file <dir>/todo/<name>.off and does not ask again in this session.

In either case, running /todo-pane creates a todo file containing only the "## Now" and "## Done (today's date)" headings (Japanese equivalents when the language is Japanese) and shows it in the pane. It also deletes the .off file, so you can start using it with /todo-pane even after answering "don't create".

Source 2 files
hooks/register.tsx 1022 lines
1import { atom, read, update } from 'claude-code'
2import type { PluginOptions, Register } from 'claude-code'
3
4// Claude rewrites these files; each pane shows whatever its file says.
5// Files live under the "dir" setting (relative to the session's working directory unless absolute):
6// <dir>/todo/<base>.md, <dir>/pin/<base>.md, and the off marker <dir>/todo/<base>.off. One set per session.
7const dirFrom = (options: PluginOptions) => {
8  const v = options.dir
9  return (typeof v === 'string' && v ? v : '.claude').replace(/\/+$/, '')
10}
11// Session name (control characters and path separators become _) plus the id's first 6 characters;
12// without a name, the id's first 8.
13export const sanitize = (name: string) => name.replace(/[\/\\:\u0000-\u001f\u007f]/g, '_')
14export const baseName = (title: string | undefined, id: string) => {
15  const t = title ? sanitize(title.trim()) : ''
16  return t ? `${t}-${id.slice(0, 6)}` : id.slice(0, 8)
17}
18export const pathsFor = (dir: string, base: string) => ({
19  todo: `${dir}/todo/${base}.md`,
20  pin: `${dir}/pin/${base}.md`,
21  off: `${dir}/todo/${base}.off`,
22})
23// Local date as YYYY-MM-DD (toISOString would be UTC)
24export const today = () => {
25  const d = new Date()
26  const z = (n: number) => String(n).padStart(2, '0')
27  return `${d.getFullYear()}-${z(d.getMonth() + 1)}-${z(d.getDate())}`
28}
29
30// Fixed strings the person sees (headings, tab titles, placeholders, toasts). Prompts to Claude stay English.
31export type Lang = 'ja' | 'en' | 'zh-Hans' | 'zh-Hant' | 'ko' | 'es' | 'fr' | 'de' | 'pt' | 'it' | 'ru'
32export const L = {
33  ja: {
34    now: '## 今',
35    done: (d: string) => `## やったこと(${d})`,
36    todoTitle: 'TODO',
37    pinTitle: 'ピン留め',
38    emptyTodo: '(TODO はまだありません)',
39    emptyPin: '(ピン留めはまだありません)',
40    empty: '(なし)',
41    older: (path: string) => `それより前: ${path}`,
42    more: (n: number, path: string) => `…ほか ${n} 件(${path})`,
43    doneTitle: (d: string) => `# ${d} にやったこと`,
44    session: (label: string) => `## セッション ${label}`,
45    missedToast: (f: string) => `${f} が更新されていません。次の発言のときに Claude が直すので、操作は不要です`,
46    missedStatus: (f: string) => `${f} 未更新(次の発言で Claude が直します)`,
47  },
48  en: {
49    now: '## Now',
50    done: (d: string) => `## Done (${d})`,
51    todoTitle: 'TODO',
52    pinTitle: 'Pins',
53    emptyTodo: '(No TODO yet)',
54    emptyPin: '(Nothing pinned yet)',
55    empty: '(none)',
56    older: (path: string) => `Earlier: ${path}`,
57    more: (n: number, path: string) => `…and ${n} more (${path})`,
58    doneTitle: (d: string) => `# Done on ${d}`,
59    session: (label: string) => `## Session ${label}`,
60    missedToast: (f: string) => `${f} was not updated. Claude will update it on your next message; nothing to do.`,
61    missedStatus: (f: string) => `${f} not updated (Claude updates it on your next message)`,
62  },
63  'zh-Hans': {
64    now: '## 现在',
65    done: (d: string) => `## 已完成(${d})`,
66    todoTitle: 'TODO',
67    pinTitle: '固定',
68    emptyTodo: '(暂无 TODO)',
69    emptyPin: '(暂无固定内容)',
70    empty: '(无)',
71    older: (path: string) => `更早: ${path}`,
72    more: (n: number, path: string) => `…另有 ${n} 项(${path})`,
73    doneTitle: (d: string) => `# ${d} 已完成事项`,
74    session: (label: string) => `## 会话 ${label}`,
75    missedToast: (f: string) => `${f} 尚未更新。Claude 会在你下一条消息时更新,无需任何操作`,
76    missedStatus: (f: string) => `${f} 未更新(Claude 将在你下次发言时更新)`,
77  },
78  'zh-Hant': {
79    now: '## 現在',
80    done: (d: string) => `## 已完成(${d})`,
81    todoTitle: 'TODO',
82    pinTitle: '釘選',
83    emptyTodo: '(尚無 TODO)',
84    emptyPin: '(尚無釘選內容)',
85    empty: '(無)',
86    older: (path: string) => `更早: ${path}`,
87    more: (n: number, path: string) => `…另有 ${n} 項(${path})`,
88    doneTitle: (d: string) => `# ${d} 已完成事項`,
89    session: (label: string) => `## 工作階段 ${label}`,
90    missedToast: (f: string) => `${f} 尚未更新。Claude 會在你下一則訊息時更新,無需任何操作`,
91    missedStatus: (f: string) => `${f} 未更新(Claude 會在你下次發言時更新)`,
92  },
93  'ko': {
94    now: '## 지금',
95    done: (d: string) => `## 완료 (${d})`,
96    todoTitle: 'TODO',
97    pinTitle: '고정',
98    emptyTodo: '(TODO가 아직 없습니다)',
99    emptyPin: '(고정된 항목이 없습니다)',
100    empty: '(없음)',
101    older: (path: string) => `이전: ${path}`,
102    more: (n: number, path: string) => `…외 ${n}건 (${path})`,
103    doneTitle: (d: string) => `# ${d} 완료한 일`,
104    session: (label: string) => `## 세션 ${label}`,
105    missedToast: (f: string) => `${f} 업데이트되지 않았습니다. 다음 메시지를 보내면 Claude가 업데이트하므로 별도 조치는 필요 없습니다`,
106    missedStatus: (f: string) => `${f} 업데이트 안 됨 (다음 메시지에서 Claude가 업데이트)`,
107  },
108  'es': {
109    now: '## Ahora',
110    done: (d: string) => `## Hecho (${d})`,
111    todoTitle: 'TODO',
112    pinTitle: 'Fijados',
113    emptyTodo: '(Aún no hay TODO)',
114    emptyPin: '(Nada fijado todavía)',
115    empty: '(nada)',
116    older: (path: string) => `Anteriores: ${path}`,
117    more: (n: number, path: string) => `…y ${n} más (${path})`,
118    doneTitle: (d: string) => `# Hecho el ${d}`,
119    session: (label: string) => `## Sesión ${label}`,
120    missedToast: (f: string) => `${f} no se ha actualizado. Claude lo actualizará en tu próximo mensaje; no tienes que hacer nada.`,
121    missedStatus: (f: string) => `${f} sin actualizar (Claude lo actualiza en tu próximo mensaje)`,
122  },
123  'fr': {
124    now: '## En cours',
125    done: (d: string) => `## Terminé (${d})`,
126    todoTitle: 'TODO',
127    pinTitle: 'Épinglés',
128    emptyTodo: '(Aucun TODO pour l’instant)',
129    emptyPin: '(Rien d’épinglé pour l’instant)',
130    empty: '(rien)',
131    older: (path: string) => `Plus ancien : ${path}`,
132    more: (n: number, path: string) => `…et ${n} de plus (${path})`,
133    doneTitle: (d: string) => `# Terminé le ${d}`,
134    session: (label: string) => `## Session ${label}`,
135    missedToast: (f: string) => `${f} n’a pas été mis à jour. Claude le mettra à jour à votre prochain message ; rien à faire.`,
136    missedStatus: (f: string) => `${f} non mis à jour (Claude le met à jour au prochain message)`,
137  },
138  'de': {
139    now: '## Jetzt',
140    done: (d: string) => `## Erledigt (${d})`,
141    todoTitle: 'TODO',
142    pinTitle: 'Angepinnt',
143    emptyTodo: '(Noch keine TODOs)',
144    emptyPin: '(Noch nichts angepinnt)',
145    empty: '(nichts)',
146    older: (path: string) => `Früher: ${path}`,
147    more: (n: number, path: string) => `…und ${n} weitere (${path})`,
148    doneTitle: (d: string) => `# Erledigt am ${d}`,
149    session: (label: string) => `## Sitzung ${label}`,
150    missedToast: (f: string) => `${f} wurde nicht aktualisiert. Claude aktualisiert es bei deiner nächsten Nachricht; du musst nichts tun.`,
151    missedStatus: (f: string) => `${f} nicht aktualisiert (Claude aktualisiert es bei deiner nächsten Nachricht)`,
152  },
153  'pt': {
154    now: '## Agora',
155    done: (d: string) => `## Concluído (${d})`,
156    todoTitle: 'TODO',
157    pinTitle: 'Fixados',
158    emptyTodo: '(Nenhum TODO ainda)',
159    emptyPin: '(Nada fixado ainda)',
160    empty: '(nada)',
161    older: (path: string) => `Anteriores: ${path}`,
162    more: (n: number, path: string) => `…e mais ${n} (${path})`,
163    doneTitle: (d: string) => `# Concluído em ${d}`,
164    session: (label: string) => `## Sessão ${label}`,
165    missedToast: (f: string) => `${f} não foi atualizado. O Claude atualizará na sua próxima mensagem; nada a fazer.`,
166    missedStatus: (f: string) => `${f} não atualizado (o Claude atualiza na sua próxima mensagem)`,
167  },
168  'it': {
169    now: '## Ora',
170    done: (d: string) => `## Fatto (${d})`,
171    todoTitle: 'TODO',
172    pinTitle: 'Fissati',
173    emptyTodo: '(Nessun TODO per ora)',
174    emptyPin: '(Nulla di fissato per ora)',
175    empty: '(niente)',
176    older: (path: string) => `Precedenti: ${path}`,
177    more: (n: number, path: string) => `…e altri ${n} (${path})`,
178    doneTitle: (d: string) => `# Fatto il ${d}`,
179    session: (label: string) => `## Sessione ${label}`,
180    missedToast: (f: string) => `${f} non è stato aggiornato. Claude lo aggiornerà al tuo prossimo messaggio; non devi fare nulla.`,
181    missedStatus: (f: string) => `${f} non aggiornato (Claude lo aggiorna al tuo prossimo messaggio)`,
182  },
183  'ru': {
184    now: '## Сейчас',
185    done: (d: string) => `## Готово (${d})`,
186    todoTitle: 'TODO',
187    pinTitle: 'Закреплено',
188    emptyTodo: '(TODO пока нет)',
189    emptyPin: '(Ничего не закреплено)',
190    empty: '(нет)',
191    older: (path: string) => `Ранее: ${path}`,
192    more: (n: number, path: string) => `…и ещё ${n} (${path})`,
193    doneTitle: (d: string) => `# Сделано за ${d}`,
194    session: (label: string) => `## Сессия ${label}`,
195    missedToast: (f: string) => `${f} не был обновлён. Claude обновит его при вашем следующем сообщении; ничего делать не нужно.`,
196    missedStatus: (f: string) => `${f} не обновлён (Claude обновит при следующем сообщении)`,
197  },
198}
199// Maps Claude Code's free-text `language` setting (English or native name, or a code) to a table key; anything else is English.
200// Traditional Chinese is tested before the general Chinese pattern.
201const LANG_PATTERNS: [Lang, RegExp][] = [
202  ['zh-Hant', /繁|traditional|^zh[-_ ]?(tw|hk|mo|hant)(?!\p{L})/iu],
203  ['zh-Hans', /^(中文|简|汉)|^(chinese|simplified|zh)(?!\p{L})/iu],
204  ['ja', /^(ja|japanese|日本語)/i],
205  ['ko', /^(ko|korean|한국어)(?!\p{L})/iu],
206  ['es', /^(es|spanish|español|espanol)(?!\p{L})/iu],
207  ['fr', /^(fr|french|français|francais)(?!\p{L})/iu],
208  ['de', /^(de|german|deutsch)(?!\p{L})/iu],
209  ['pt', /^(pt|portuguese|português|portugues)(?!\p{L})/iu],
210  ['it', /^(it|italian|italiano)(?!\p{L})/iu],
211  ['ru', /^(ru|russian|русский)(?!\p{L})/iu],
212]
213export const langFrom = (language: unknown): Lang => {
214  const s = String(language ?? '').trim()
215  return LANG_PATTERNS.find(([, re]) => re.test(s))?.[0] ?? 'en'
216}
217// Set once in session.start; English until then.
218let lang: Lang = 'en'
219let langRead = false
220
221// The done heading of any language in L, built from the table so a dated heading of the user's own
222// (e.g. "## Meeting notes (2026-10-01)") is never taken for it.
223const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
224const DONE_RE = new RegExp(`^(?:${[...new Set(Object.values(L).map(t => esc(t.done('\u0000')).replace('\u0000', '\\d{4}-\\d{2}-\\d{2}')))].join('|')})\\s*$`)
225// The session heading of any language in L, with the label captured.
226const SESSION_RE = new RegExp(`^(?:${[...new Set(Object.values(L).map(t => esc(t.session('\u0000')).replace('\u0000', '(.+?)')))].join('|')})\\s*$`)
227const LEGACY_RE = /^## 今日やったこと\s*$/
228
229// Date changed: move every earlier done section (any language) out of the todo text, each with its body (up to the
230// next "## " heading or "---" rule). Today's heading is kept, or made from the first earlier one. Pure; the caller does the I/O.
231const RULE_RE = /^---+\s*$/
232const dateOf = (l: string) => l.match(/\d{4}-\d{2}-\d{2}/)![0]
233export const rollover = (text: string, today: string, lang: Lang): { text: string; archived: { date: string; body: string }[] } => {
234  const lines = text.split('\n')
235  const first = lines.findIndex(l => DONE_RE.test(l) || LEGACY_RE.test(l))
236  if (first < 0) return { text, archived: [] }
237  if (LEGACY_RE.test(lines[first])) {
238    lines[first] = L[lang].done(today)
239    return { text: lines.join('\n'), archived: [] }
240  }
241  let hasToday = lines.some(l => DONE_RE.test(l) && dateOf(l) === today)
242  const archived: { date: string; body: string }[] = []
243  const out: string[] = []
244  let changed = false
245  for (let i = 0; i < lines.length; i++) {
246    const l = lines[i]
247    if (!DONE_RE.test(l) || dateOf(l) >= today) {
248      out.push(l)
249      continue
250    }
251    let j = i + 1
252    while (j < lines.length && !lines[j].startsWith('## ') && !RULE_RE.test(lines[j])) j++
253    const body = lines.slice(i + 1, j).join('\n').trim()
254    if (body) archived.push({ date: dateOf(l), body })
255    if (!hasToday) {
256      out.push(L[lang].done(today), '')
257      hasToday = true
258    }
259    changed = true
260    i = j - 1
261  }
262  if (!changed) return { text, archived }
263  // Tidy what the removal left: rules that now follow another rule, runs of blank lines, and the tail of the file.
264  const tidy: string[] = []
265  let fence = false
266  let lastText = ''
267  for (const l of out) {
268    if (/^(```|~~~)/.test(l.trimStart())) fence = !fence
269    if (!fence && RULE_RE.test(l) && RULE_RE.test(lastText)) continue
270    if (!fence && !l.trim() && tidy.length && !tidy[tidy.length - 1].trim()) continue
271    tidy.push(l)
272    if (l.trim()) lastText = l
273  }
274  while (tidy.length && (!tidy[tidy.length - 1].trim() || RULE_RE.test(tidy[tidy.length - 1]))) tidy.pop()
275  return { text: tidy.join('\n') + (text.endsWith('\n') ? '\n' : ''), archived }
276}
277
278// New content for <dir>/todo/done/<date>.md with this session's section appended.
279export const appendDone = (existing: string | undefined, date: string, sessionLabel: string, body: string, lang: Lang) => {
280  const head = existing ? existing.replace(/\s+$/, '') + '\n\n' : `${L[lang].doneTitle(date)}\n\n`
281  return `${head}${L[lang].session(sessionLabel)}\n\n${body}\n`
282}
283
284// Lines of `body` that are checkbox items already present verbatim in `existing` are dropped (a done file is
285// shared by sessions and can be archived into more than once).
286export const dropExisting = (existing: string | undefined, body: string) => {
287  const have = new Set((existing ?? '').split('\n').filter(l => ITEM_RE.test(l)))
288  return body.split('\n').filter(l => !(ITEM_RE.test(l) && have.has(l))).join('\n').trim()
289}
290const ITEM_RE = /^\s*- \[[ xX]\]/
291
292// The "- [x]" lines in this session's sections of a done file, in file order. A section is a session heading whose label
293// is this session's (by id, so a rename still matches) up to the next "## " heading.
294export const sessionItems = (text: string, id: string): string[] => {
295  const mine = (label: string) => label === id.slice(0, 8) || label.endsWith('-' + id.slice(0, 6))
296  const items: string[] = []
297  let on = false
298  for (const l of text.split('\n')) {
299    if (l.startsWith('## ')) {
300      const m = l.match(SESSION_RE)
301      on = !!m && mine((m.slice(1).find(Boolean) ?? '').trim())
302    } else if (on && l.startsWith('- [x]')) items.push(l)
303  }
304  return items
305}
306
307// An earlier day with a done file: its "- [x]" lines in file order, and where the file is.
308export type PastDay = { date: string; items: string[]; path: string }
309
310// Rows `text` takes in the pane: one per line when cut, wrapped lines take more.
311// ponytail: wrap mode estimates ceil(width / columns) per line; word wrapping and Markdown padding can take a row more.
312export const rowsOf = (text: string, cols: number, wrap: boolean): number => {
313  // ponytail: tables are drawn by layoutTable, so they count their drawn height; the heading-before-table blank row is not counted.
314  if (cols > 0 && text.includes('|')) {
315    const parts = splitTables(text)
316    if (parts.some(p => 'table' in p))
317      return parts.reduce((n, p) => n + ('table' in p ? layoutTable(p.table, cols).length : rowsOf(p.text, cols, wrap)), 0)
318  }
319  const lines = text.split('\n')
320  // The Markdown element adds a blank row under a heading that has no blank line after it.
321  return lines.reduce((n, l, i) => n + (wrap && cols > 0 ? Math.max(1, Math.ceil(displayWidth(l) / cols)) : 1) +
322    (/^#{1,6}\s/.test(l) && lines[i + 1]?.trim() ? 1 : 0), 0)
323}
324
325// Display only: the earlier days' finished items under the TODO tab, appended after the todo text (`usedRows` rows).
326// `days` are newest first (at most 3), `hasOlder` says more done files exist. The newest is always shown whole; the next
327// ones only while `bodyRows` leaves room (then the last items that fit, plus the "more" line). A line points to the folder
328// when anything earlier is not fully shown. Without a usable `bodyRows` only the newest day is shown.
329export const pastDaysBlock = (days: PastDay[], hasOlder: boolean, olderPath: string, usedRows: number, bodyRows: number, cols: number, wrap: boolean, lang: Lang) => {
330  if (!days.length) return ''
331  const sect = (d: PastDay, items: string[], more = 0) =>
332    [L[lang].done(d.date).replace(/^## /, '#### '), '', ...items, ...(more ? [L[lang].more(more, d.path)] : [])].join('\n')
333  const tail = (s: string, left: boolean) => (left ? `${s}\n\n${L[lang].older(olderPath)}` : s)
334  // The block starts on the todo text's last row.
335  const rows = (s: string) => usedRows + rowsOf(s, cols, wrap) - 1
336  let out = '\n\n---\n\n' + sect(days[0], days[0].items)
337  if (!(bodyRows > 0)) return tail(out, days.length > 1 || hasOlder)
338  for (let i = 1; i < days.length; i++) {
339    const d = days[i]
340    const full = `${out}\n\n${sect(d, d.items)}`
341    if (rows(tail(full, i < days.length - 1 || hasOlder)) <= bodyRows) {
342      out = full
343      continue
344    }
345    const part = (k: number) => `${out}\n\n${sect(d, d.items.slice(-k), d.items.length - k)}`
346    let k = d.items.length - 1
347    while (k >= 1 && rows(tail(part(k), true)) > bodyRows) k--
348    return tail(k >= 1 ? part(k) : out, true)
349  }
350  return tail(out, hasOlder)
351}
352
353// Display width of one code point: East Asian Wide/Fullwidth and emoji take 2 columns, the rest 1.
354// ponytail: range table, not full Unicode width data; combining marks and ambiguous-width characters count as 1.
355const isWide = (c: number) =>
356  (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0x303e) || (c >= 0x3041 && c <= 0x33ff) ||
357  (c >= 0x3400 && c <= 0x4dbf) || (c >= 0x4e00 && c <= 0x9fff) || (c >= 0xa000 && c <= 0xa4cf) ||
358  (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff) || (c >= 0xfe30 && c <= 0xfe6f) ||
359  (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff) ||
360  (c >= 0x20000 && c <= 0x3fffd)
361// Splits `s` into drawn units with their widths; a VS16 or skin tone joins the character before it as one 2-column unit.
362// ponytail: ZWJ sequences still count per part.
363const units = (s: string) => {
364  const out: [string, number][] = []
365  for (const ch of s) {
366    const c = ch.codePointAt(0)!
367    const last = out[out.length - 1]
368    if (last && (c === 0xfe0f || (c >= 0x1f3fb && c <= 0x1f3ff))) {
369      last[0] += ch
370      last[1] = 2
371    } else out.push([ch, isWide(c) || /\p{Emoji_Presentation}/u.test(ch) ? 2 : 1])
372  }
373  return out
374}
375export const displayWidth = (s: string) => units(s).reduce((w, [, cw]) => w + cw, 0)
376
377// An emoji that defaults to text style with a skin tone (✍🏻) is counted 4 columns by the Markdown table and fewer
378// by the terminal, which breaks the row. Display only: the tone becomes VS16 (✍️), which both draw 2 columns wide.
379export const fixSkinTone = (s: string) =>
380  s.replace(/(\p{Extended_Pictographic})(?<!\p{Emoji_Presentation})\uFE0F?[\u{1F3FB}-\u{1F3FF}]/gu, '$1\uFE0F')
381const LIST_RE = /^(\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)/
382const HEADING_RE = /^(#{1,6}\s+)/
383const MARGIN = 2
384
385// Cuts `s` to at most `budget` display columns, ending with "…" (so budget-1 columns of text).
386const cutTo = (s: string, budget: number) => {
387  let cut = ''
388  let w = 0
389  for (const [ch, cw] of units(s)) {
390    if (w + cw > budget - 1) break
391    cut += ch
392    w += cw
393  }
394  // No half-open link, code span, bold or strikethrough: each would be drawn as raw marks.
395  const lb = cut.lastIndexOf('[')
396  if (lb >= 0 && !/\]\([^)]*\)/.test(cut.slice(lb))) cut = cut.slice(0, lb)
397  for (const m of ['`', '**', '~~'])
398    if (cut.split(m).length % 2 === 0) cut = cut.slice(0, cut.lastIndexOf(m))
399  return cut.replace(/\\$/, '') + '…'
400}
401
402// Splits a table row into trimmed cells on unescaped "|"; a "|" inside a backtick span stays in its cell.
403// ponytail: GFM itself splits inside code spans unless the pipe is escaped; we keep the span whole instead.
404const splitRow = (line: string): string[] => {
405  let t = line.trim()
406  if (t.startsWith('|')) t = t.slice(1)
407  if (t.endsWith('|') && !t.endsWith('\\|')) t = t.slice(0, -1)
408  const cells: string[] = []
409  let cur = ''
410  let code = false
411  for (let i = 0; i < t.length; i++) {
412    const c = t[i]
413    if (c === '\\' && i + 1 < t.length) {
414      cur += c + t[++i]
415      continue
416    }
417    if (c === '`') code = !code
418    if (c === '|' && !code) {
419      cells.push(cur.trim())
420      cur = ''
421    } else cur += c
422  }
423  cells.push(cur.trim())
424  return cells
425}
426const isDelimiter = (cells: string[]) => cells.length > 0 && cells.every(c => /^:?-+:?$/.test(c))
427
428// Rendered width is sum(column widths) + 3 per column + 1 ("│ a │ b │"), kept MARGIN columns short of the pane.
429const TABLE_MIN = 3
430
431// Column widths for `rows` (row 0 header, row 1 the delimiter row, ignored) so the table fits `columns`:
432// the widest column loses a column at a time, down to its minimum.
433export const tableWidths = (rows: string[][], columns: number): number[] => {
434  const n = Math.max(...rows.map(r => r.length))
435  const widths = Array.from({ length: n }, (_, i) =>
436    Math.max(1, ...rows.map((r, k) => (k === 1 ? 1 : displayWidth(r[i] ?? '')))))
437  const mins = widths.map((_, i) => Math.min(TABLE_MIN, displayWidth(rows[0][i] ?? '') || 1))
438  const total = () => widths.reduce((a, b) => a + b, 0) + 3 * n + 1
439  const avail = columns - MARGIN
440  while (total() > avail) {
441    let k = -1
442    for (let i = 0; i < n; i++) if (widths[i] > mins[i] && (k < 0 || widths[i] > widths[k])) k = i
443    if (k < 0) break
444    widths[k]--
445  }
446  return widths
447}
448
449// Shrinks a GFM table (header, delimiter row, body rows) so it fits `columns`: columns shrink by tableWidths,
450// then cells wider than their column are cut with "…". Not a table (no valid delimiter row): unchanged.
451export const fitTable = (lines: string[], columns: number): string[] => {
452  if (lines.length < 2) return lines
453  const rows = lines.map(splitRow)
454  if (!isDelimiter(rows[1])) return lines
455  const widths = tableWidths(rows, columns)
456  return rows.map((r, k) => {
457    if (k === 1) return lines[1]
458    const cells = r.map((c, i) => (displayWidth(c) > widths[i] ? cutTo(c, widths[i]) : c))
459    return `| ${cells.join(' | ')} |`
460  })
461}
462
463// A drawn piece of a table cell or border: plain text plus the marks it carries.
464export type Span = { text: string; bold?: boolean; code?: boolean; strike?: boolean }
465
466// Cell source to spans: `code`, **bold**, ~~strike~~, [text](url) -> text, "\\|" -> "|"; other marks stay as typed.
467// ponytail: no nesting (bold inside a link, code inside bold are drawn flat); one mark per span.
468export const parseSpans = (cell: string): Span[] => {
469  const out: Span[] = []
470  const re = /`([^`]+)`|\*\*(.+?)\*\*|~~(.+?)~~|\[([^\]]+)\]\([^)]*\)/g
471  const plain = (t: string) => t && out.push({ text: t.replace(/\\\|/g, '|') })
472  let at = 0
473  for (const m of cell.matchAll(re)) {
474    plain(cell.slice(at, m.index))
475    if (m[1] !== undefined) out.push({ text: m[1], code: true })
476    else if (m[2] !== undefined) out.push({ text: m[2], bold: true })
477    else if (m[3] !== undefined) out.push({ text: m[3], strike: true })
478    else plain(m[4])
479    at = m.index! + m[0].length
480  }
481  plain(cell.slice(at))
482  return out
483}
484const plainOf = (spans: Span[]) => spans.map(s => s.text).join('')
485
486// Wraps spans to lines of at most `width` display columns. Breaks at the last space when there is one, else at any unit.
487export const wrapSpans = (spans: Span[], width: number): Span[][] => {
488  type U = { ch: string; cw: number; sp: Span }
489  const us: U[] = spans.flatMap(sp => units(sp.text).map(([ch, cw]) => ({ ch, cw, sp })))
490  const lines: U[][] = []
491  let cur: U[] = []
492  let w = 0
493  for (const u of us) {
494    if (w + u.cw > width && cur.length) {
495      const sp = cur.map(x => x.ch).lastIndexOf(' ')
496      if (sp > 0) {
497        lines.push(cur.slice(0, sp))
498        cur = cur.slice(sp + 1)
499      } else {
500        lines.push(cur)
501        cur = []
502      }
503      w = cur.reduce((a, x) => a + x.cw, 0)
504    }
505    cur.push(u)
506    w += u.cw
507  }
508  lines.push(cur)
509  return lines.map(l => {
510    const out: Span[] = []
511    for (const u of l) {
512      const last = out[out.length - 1]
513      if (last && last.bold === u.sp.bold && last.code === u.sp.code && last.strike === u.sp.strike) last.text += u.ch
514      else out.push({ ...u.sp, text: u.ch })
515    }
516    return out
517  })
518}
519
520// Lays out a GFM table (header, delimiter row, rows) in `columns`: box-drawing lines, each a list of spans.
521// Cells wrap inside their column; a header is bold and centered, body cells follow the delimiter row's alignment.
522export const layoutTable = (lines: string[], columns: number): Span[][] => {
523  const rows = lines.map(splitRow)
524  const cells = rows.map((r, k) => (k === 1 ? r : r.map(c => parseSpans(c))))
525  const drawn = rows.map((r, k) => (k === 1 ? r : (cells[k] as Span[][]).map(plainOf)))
526  const widths = tableWidths(drawn, columns)
527  const n = widths.length
528  const align = Array.from({ length: n }, (_, i) => {
529    const d = rows[1][i] ?? ''
530    return d.startsWith(':') && d.endsWith(':') ? 'c' : d.endsWith(':') ? 'r' : 'l'
531  })
532  const border = (l: string, m: string, r: string): Span[] => [{ text: l + widths.map(x => '─'.repeat(x + 2)).join(m) + r }]
533  const out: Span[][] = [border('┌', '┬', '┐')]
534  rows.forEach((_, k) => {
535    if (k === 1) return
536    const wrapped = Array.from({ length: n }, (_, i) => wrapSpans((cells[k] as Span[][])[i] ?? [], widths[i]))
537    const h = Math.max(...wrapped.map(c => c.length))
538    for (let j = 0; j < h; j++) {
539      const line: Span[] = [{ text: '│' }]
540      wrapped.forEach((c, i) => {
541        const sp = (c[j] ?? []).map(s => (k === 0 ? { ...s, bold: true } : s))
542        const gap = widths[i] - displayWidth(plainOf(sp))
543        const a = k === 0 ? 'c' : align[i]
544        const left = a === 'c' ? Math.floor(gap / 2) : a === 'r' ? gap : 0
545        line.push({ text: ' ' + ' '.repeat(left) }, ...sp, { text: ' '.repeat(gap - left) + ' │' })
546      })
547      out.push(line)
548    }
549    out.push(border(...(k === rows.length - 1 ? ['└', '┴', '┘'] : ['├', '┼', '┤']) as [string, string, string]))
550  })
551  return out
552}
553
554// Splits Markdown into text pieces and GFM tables (lines starting with "|" whose 2nd line is a delimiter row).
555// Fenced code is never a table.
556export const splitTables = (markdown: string): ({ text: string } | { table: string[] })[] => {
557  const lines = markdown.split('\n')
558  const out: ({ text: string } | { table: string[] })[] = []
559  let buf: string[] = []
560  let fence = false
561  const flush = () => {
562    if (buf.length) out.push({ text: buf.join('\n') })
563    buf = []
564  }
565  for (let i = 0; i < lines.length; i++) {
566    const t = lines[i].trimStart()
567    if (/^(```|~~~)/.test(t)) fence = !fence
568    if (!fence && t.startsWith('|') && lines[i + 1]?.trimStart().startsWith('|') && isDelimiter(splitRow(lines[i + 1]))) {
569      let j = i
570      while (j < lines.length && lines[j].trimStart().startsWith('|')) j++
571      flush()
572      out.push({ table: lines.slice(i, j) })
573      i = j - 1
574    } else buf.push(lines[i])
575  }
576  flush()
577  return out
578}
579
580// Cuts each over-long line to `columns` display columns and ends it with "…", so the Markdown element
581// never wraps it. Table rows are fitted as a block by fitTable. Display only. Blank lines and fenced code are left alone.
582export const truncateForWidth = (markdown: string, columns: number): string => {
583  let fence = false
584  const out: string[] = []
585  const lines = markdown.split('\n')
586  for (let i = 0; i < lines.length; i++) {
587    const line = lines[i]
588    const t = line.trimStart()
589    if (/^(```|~~~)/.test(t)) {
590      fence = !fence
591      out.push(line)
592      continue
593    }
594    if (fence || !t) {
595      out.push(line)
596      continue
597    }
598    if (t.startsWith('|')) {
599      let j = i
600      while (j < lines.length && lines[j].trimStart().startsWith('|')) j++
601      out.push(...fitTable(lines.slice(i, j), columns))
602      i = j - 1
603      continue
604    }
605    const list = line.match(LIST_RE)?.[1]
606    const heading = list ? undefined : line.match(HEADING_RE)?.[1]
607    const head = list ?? heading ?? ''
608    const rest = line.slice(head.length)
609    // A heading's # marks are not drawn; a list marker is drawn about as wide as its source.
610    const budget = columns - MARGIN - (heading ? 0 : displayWidth(head))
611    out.push(budget < 4 || displayWidth(rest) <= budget ? line : head + cutTo(rest, budget))
612  }
613  return out.join('\n')
614}
615
616// Display only: puts `label` (italic, the closest Markdown has to dim) under each "##" to "######" heading that has
617// no content before the next heading of the same or higher level (same or fewer #), the "---" rule that starts the
618// past-days block, or the end of the todo part. A heading followed by a deeper one (e.g. "###" under "##") is not
619// empty. Fenced code is skipped. The todo file itself is never changed.
620export const markEmptySections = (text: string, label: string): string => {
621  const lines = text.split('\n')
622  const out: string[] = []
623  let fence = false
624  let open = 0 // level of the heading that has had no content yet (0 = none)
625  let mark = 0
626  const close = () => {
627    if (open) out.splice(mark, 0, `_${label}_`)
628    open = 0
629  }
630  for (let i = 0; i < lines.length; i++) {
631    const line = lines[i]
632    const t = line.trimStart()
633    const level = fence ? 0 : (line.match(/^(#{2,6})\s/)?.[1].length ?? 0)
634    if (/^(```|~~~)/.test(t)) {
635      fence = !fence
636      open = 0
637    } else if (!fence && /^---+\s*$/.test(line)) {
638      close()
639      out.push(...lines.slice(i))
640      return out.join('\n')
641    } else if (level) {
642      if (level <= open) close()
643      else open = 0
644      out.push(line)
645      open = level
646      mark = out.length
647      continue
648    } else if (t) open = 0
649    out.push(line)
650  }
651  close()
652  return out.join('\n')
653}
654
655// Display only: in the todo part, rewrites each "### " heading under a "## " heading to
656// "### <parent>-<n>. <title>" (n restarts at each "## "), since "##" to "####" all look alike when drawn.
657// Fenced code is skipped; everything from the "---" rule on is passed through unchanged.
658export const numberSubsections = (text: string): string => {
659  const lines = text.split('\n')
660  let fence = false
661  let parent = ''
662  let n = 0
663  for (let i = 0; i < lines.length; i++) {
664    const line = lines[i]
665    if (/^(```|~~~)/.test(line.trimStart())) fence = !fence
666    else if (fence) continue
667    else if (/^---+\s*$/.test(line)) break
668    else if (line.startsWith('## ')) {
669      parent = line.slice(3).trim()
670      n = 0
671    } else if (parent && line.startsWith('### ')) lines[i] = `### ${parent}-${++n}. ${line.slice(4)}`
672  }
673  return lines.join('\n')
674}
675
676const NOW_PANE = 'todo-pane'
677const PIN_PANE = 'pin-board'
678
679// The engine's scan needs each atom named directly where read/update use it, so the two boards are spelled out.
680const nowText = atom({ plugin: 'todo-pane', key: 'text' } as const, '')
681const pinText = atom({ plugin: 'todo-pane', key: 'pin' } as const, '')
682// JSON of { days: PastDay[], older: boolean }: earlier days' finished items, laid out by the render handler (it knows the rows).
683const pastText = atom({ plugin: 'todo-pane', key: 'past' } as const, '')
684// true: long TODO lines wrap; false (default): they are cut with "…". Saved with $.store so it outlives the session.
685const wrapOn = atom({ plugin: 'todo-pane', key: 'wrap' } as const, false)
686// Same for the pins pane, which defaults to wrapping.
687const pinWrapOn = atom({ plugin: 'todo-pane', key: 'pinWrap' } as const, true)
688// The topic name from the classic hooks' session_title: undefined = not heard yet, null = the session has no name.
689const titleState = atom({ plugin: 'todo-pane', key: 'title' } as const, undefined as string | null | undefined)
690
691// Sent to the model every turn, so the board stays current without relying on memory.
692const rule = (f: string, lang: Lang) => [
693  `${f} is the TODO list shown in the right-hand pane.`,
694  '- Write every item as a checkbox: `- [ ] ` for open, `- [x] ` for done. Never use a plain `- ` bullet.',
695  `- Before starting any work that changes files or Notion, first write it under "${L[lang].now}" in ${f}.`,
696  `- When the work is done, check it and move it under "${L[lang].done(today())}"; keep remaining items in their sections.`,
697  `- Only today's done heading ("${L[lang].done(today())}") belongs in ${f}; never write done headings for earlier days, the plugin moves them to the done/ folder.`,
698  `- When the topic changes, update the "${L[lang].now}" section to match.`,
699  '- Write the items in the language the user is writing in.',
700].join('\n')
701const ask = (f: string, off: string, lang: Lang) =>
702  `The TODO file ${f} (the TODO list shown in the right-hand pane) does not exist. At the very start of this turn, before anything else, ask the user with AskUserQuestion whether to create a TODO list.\n- Yes: create ${f} with the headings "${L[lang].now}" and "${L[lang].done(today())}", and write the current task under "${L[lang].now}" as \`- [ ] \`.\n- No: create an empty file at ${off} (do not ask again this session).`
703// Sent every turn too, even after a "no" to the todo list: the pin board is independent of it.
704const pinRule = (f: string, lang: Lang) =>
705  `When asked to "pin" something (e.g. "pin that", 「ピン留めして」), write the target (the explanation, comparison table, summary, etc. you just gave) as Markdown to ${f}, creating it if missing. This is the "${L[lang].pinTitle}" tab of this plugin's side pane, not claude.ai Artifact pinning. The user can also run the /todo-pane:pin skill. Only write it when asked; do not update it as work progresses.`
706const emptyBoard = (lang: Lang) => `${L[lang].now}\n\n${L[lang].done(today())}\n`
707const missedText = (f: string) =>
708  `In the previous turn files or Notion were changed, but ${f} was not updated. At the start of this turn, update ${f} to the current state.`
709
710// Tools that change something the person would expect the board to mention.
711export const isWrite = (tool: string, path: string, now: string, off: string) =>
712  (['Write', 'Edit', 'NotebookEdit'].includes(tool) && !path.endsWith(now) && !path.endsWith(off)) ||
713  /notion.*(update|create|patch|post|delete|move|duplicate)/i.test(tool)
714
715// ponytail: per-session flags in module scope; a reload resets them, which only skips one check
716let before: string | undefined
717let wrote = false
718let missed = false
719
720let dir = '.claude'
721let sessionId = ''
722let base = ''
723let p = pathsFor(dir, '')
724
725// Where the files may still be, if the name changed: the previous base and the id-only name (what an unreadable title left behind).
726export const renameSources = (prev: string, next: string, id: string) =>
727  [prev, id.slice(0, 8)].filter((b, i, a) => b && b !== next && a.indexOf(b) === i)
728
729// <base> for a remembered title: not heard yet keeps the current base (or starts from the id if there is none).
730export const baseFor = (title: string | null | undefined, id: string, current: string) =>
731  title === undefined && current ? current : baseName(title ?? undefined, id)
732
733// Recompute <base>; if it changed, carry the old files (todo, pin and off) to the new names.
734async function sync($: any) {
735  // Claude Code's `language` setting picks the fixed strings (settings can fail to read: English).
736  // Read here, not only in session.start, so a hot reload that skips session.start still gets it.
737  if (!langRead) {
738    lang = langFrom((await $.settings.read().catch(() => undefined))?.language)
739    langRead = true
740  }
741  if (!sessionId) sessionId = await $.session.id()
742  const next = baseFor(await read($, titleState), sessionId, base)
743  const prev = base
744  base = next
745  p = pathsFor(dir, base)
746  // Even with the name unchanged: files an earlier version left under the id-only name come back.
747  for (const from of renameSources(prev, next, sessionId)) {
748    const old = pathsFor(dir, from)
749    for (const k of ['todo', 'pin', 'off'] as const) {
750      if (!(await $.fs.exists(old[k])) || (await $.fs.exists(p[k]))) continue
751      await $.fs.write(p[k], String(await $.fs.read(old[k])))
752      await $.process.run(['rm', '-f', old[k]])
753    }
754  }
755}
756
757// session_title is the topic name now (absent: no name). Remember it, then sync so the files follow a /rename.
758async function hear($: any, e: { session_title?: string }) {
759  await update($, titleState, () => e.session_title ?? null)
760  await sync($).catch(() => {})
761}
762
763// Roll the done section over when the date changed. Runs outside Claude's tool calls and before turn.start
764// snapshots `before`, so it never reads as a missed update.
765// The 3s refresh and prompt.submit can both get here; one run at a time, or a section could be archived twice.
766let archiving: Promise<void> | undefined
767function archiveIfNeeded($: any) {
768  archiving ??= rollOver($).finally(() => { archiving = undefined })
769  return archiving
770}
771async function rollOver($: any) {
772  if (!(await $.fs.exists(p.todo))) return
773  const text = String(await $.fs.read(p.todo))
774  const r = rollover(text, today(), lang)
775  if (r.text !== text) await $.fs.write(p.todo, r.text)
776  for (const a of r.archived) {
777    const file = `${dir}/todo/done/${a.date}.md`
778    await $.process.run(['mkdir', '-p', `${dir}/todo/done`])
779    const existing = await $.fs.read(file).then(String).catch(() => undefined)
780    const body = dropExisting(existing, a.body)
781    if (body) await $.fs.write(file, appendDone(existing, a.date, base, body, lang))
782  }
783}
784
785// The latest 3 earlier days with this session's finished items, shown under the TODO tab only (as JSON for pastText).
786// Done files are newest-first scanned; a 4th matching day tells there is more (older).
787async function pastDays($: any) {
788  const names: { name: string }[] = await $.fs.list(`${dir}/todo/done`).catch(() => [])
789  const t = today()
790  const all = names.map(n => n.name).filter(n => /^\d{4}-\d{2}-\d{2}\.md$/.test(n) && n.slice(0, 10) < t).sort().reverse()
791  const days: PastDay[] = []
792  let older = false
793  for (const n of all) {
794    const path = `${dir}/todo/done/${n}`
795    const items = sessionItems(String(await $.fs.read(path).catch(() => '')), sessionId)
796    if (!items.length) continue
797    if (days.length === 3) {
798      older = true
799      break
800    }
801    days.push({ date: n.slice(0, 10), items, path })
802  }
803  return JSON.stringify({ days, older })
804}
805
806// What a pane command does: not open -> open it in front; open but behind another tab -> bring it forward; in front -> close.
807export const paneAction = ({ isOpen, isFront }: { isOpen: boolean; isFront: boolean }): 'open' | 'front' | 'close' =>
808  !isOpen ? 'open' : isFront ? 'close' : 'front'
809// $.ui.open with focus raises the tab (and retitles an open one), so open and front are the same call.
810const openPane = ($: any, id: string, title: string) => $.ui.open({ id, title, focus: true })
811// The engine's record of this plugin's panes; isShown marks the one tab in front. An unplaced pane counts as not open.
812async function stateOf($: any, id: string) {
813  const pane = ((await $.ui.panes().catch(() => [])) as { id: string; isShown: boolean; isPlaced: boolean }[]).find(x => x.id === id)
814  return { isOpen: !!pane?.isPlaced, isFront: !!pane?.isShown }
815}
816
817// Which of this plugin's panes /todo-pane-wrap acts on: the one the dock is showing; undefined when neither is.
818export const wrapTarget = (panes: readonly { id: string; isShown: boolean }[]): 'todo' | 'pin' | undefined => {
819  const shown = panes.find(x => x.isShown && (x.id === NOW_PANE || x.id === PIN_PANE))?.id
820  return shown === NOW_PANE ? 'todo' : shown === PIN_PANE ? 'pin' : undefined
821}
822
823// Markdown for a pane `cols` wide: tables are drawn by layoutTable, fitted to the pane (Markdown wraps them at the
824// terminal width instead); the rest stays Markdown, through `cut`. Without a width it is plain Markdown.
825const mdOf = ({ Box, Markdown, Text }: any, cols: number, cut: (x: string) => string) => (x: string, dimColor?: boolean) =>
826  cols > 0
827    ? splitTables(x).map((p, i) =>
828        'table' in p ? (
829          <Box flexDirection="column">
830            {layoutTable(p.table, cols).map((l, j) => (
831              <Text wrap="truncate" dimColor={dimColor}>
832                {l.map((s, k) => (
833                  <Text bold={s.bold} strikethrough={s.strike} color={s.code ? 'suggestion' : undefined}>{s.text}</Text>
834                ))}
835              </Text>
836            ))}
837          </Box>
838        ) : (
839          <Markdown dimColor={dimColor} text={cut(p.text)} />
840        ))
841    : <Markdown dimColor={dimColor} text={x} />
842
843export const register: Register = (on, options) => {
844  dir = dirFrom(options)
845  p = pathsFor(dir, base)
846
847  on('session.start', async ($, e, next) => {
848    await sync($)
849    const savedWrap = (await $.store.get('wrap').catch(() => undefined)) === true
850    const savedPinWrap = (await $.store.get('pinWrap').catch(() => undefined)) !== false
851    const refresh = async () => {
852      await sync($).catch(() => {})
853      await archiveIfNeeded($).catch(() => {})
854      const file = String(await $.fs.read(p.todo).catch(() => '')).slice(0, 9000)
855      const now = file
856      const past = file ? await pastDays($) : ''
857      const pin = String(await $.fs.read(p.pin).catch(() => '')).slice(0, 9000)
858      await update($, nowText, prev => (prev === now ? prev : now))
859      await update($, pastText, prev => (prev === past ? prev : past))
860      await update($, pinText, prev => (prev === pin ? prev : pin))
861      return pin
862    }
863    await update($, wrapOn, () => savedWrap)
864    await update($, pinWrapOn, () => savedPinWrap)
865    const pin = await refresh()
866    // ponytail: polls every 3s; a file watch would be nicer if the API grows one
867    $.clock.every(3000, () => void refresh())
868    void openPane($, NOW_PANE, L[lang].todoTitle)
869    // The pin board opens at start only when this session's file exists; /todo-pane-pinboard opens it later.
870    if (pin) void openPane($, PIN_PANE, L[lang].pinTitle)
871    // Last, and each guarded: a taken name must not stop the panes or the timer above. Immediate: they only open,
872    // close or toggle a pane, so they run mid-turn instead of waiting for Claude to finish.
873    for (const [name, description] of [['todo-pane', 'Open, bring forward, or close the TODO pane'], ['todo-pane-pinboard', 'Open, bring forward, or close the pinboard pane'], ['todo-pane-wrap', 'Toggle wrapping long lines in the pane in front']])
874      try { await $.command.register({ name, description, immediate: true }) } catch (err) { $.ui.log(`command ${name} not registered: ${err}`, { to: 'debug' }) }
875
876    return next(e)
877  })
878
879  // Attached to every prompt as context the model reads beside it (never shown, text untouched),
880  // so the instruction reflects the board's state at that turn; prompt.compose is frozen after the first turn.
881  on('classic.SessionStart', async ($, e, next) => {
882    await hear($, e)
883    return next(e)
884  })
885
886  // Attached to every prompt as context the model reads beside it (never shown, text untouched),
887  // so the instruction reflects the board's state at that turn; prompt.compose is frozen after the first turn.
888  // Built here, not in prompt.submit: next(e) there runs the UserPromptSubmit hooks beneath, so this is the first
889  // point where the turn's session_title is known and the file names in the rule are the new ones.
890  on('classic.UserPromptSubmit', async ($, e, next) => {
891    await hear($, e)
892    await archiveIfNeeded($).catch(() => {})
893    const pin = pinRule(p.pin, lang)
894    const texts = (await $.fs.exists(p.off))
895      ? [pin]
896      : [(await $.fs.exists(p.todo)) ? (missed ? `${rule(p.todo, lang)}\n${missedText(p.todo)}` : rule(p.todo, lang)) : ask(p.todo, p.off, lang), pin]
897    const r = await next(e)
898    return { ...r, additionalContext: [...(r?.additionalContext ?? []), ...texts] }
899  })
900
901  on('turn.start', async ($, e, next) => {
902    before = await $.fs.read(p.todo).then(String).catch(() => undefined)
903    wrote = false
904    return next(e)
905  })
906
907  on('tool.call', async ($, e, next) => {
908    if (!e.agentId) {
909      const path = 'file_path' in e ? String(e.file_path) : ''
910      if (isWrite(e.tool, path, p.todo, p.off)) wrote = true
911    }
912    return next(e)
913  })
914
915  on('turn.complete', async ($, e, next) => {
916    if (!e.agentId && !e.isAborted && before !== undefined) {
917      const after = await $.fs.read(p.todo).then(String).catch(() => undefined)
918      missed = wrote && after === before
919      if (missed) $.ui.toast(L[lang].missedToast(p.todo))
920      $.ui.status(missed ? L[lang].missedStatus(p.todo) : undefined)
921    }
922    return next(e)
923  })
924
925  // Both commands: open in front / bring forward / close (see paneAction). /todo-pane opening is an explicit yes: create the board if missing and drop an earlier "no" (.off).
926  on('command.run', { command: 'todo-pane' }, async $ => {
927    const act = paneAction(await stateOf($, NOW_PANE))
928    if (act === 'close') {
929      await $.ui.close({ id: NOW_PANE })
930      return { text: 'Closed.' }
931    }
932    if (act === 'front') {
933      await openPane($, NOW_PANE, L[lang].todoTitle)
934      return { text: 'Brought forward.' }
935    }
936    // Pick up a name set by -n / /rename first, or the file is created under the bare id and renamed 3s later.
937    await sync($).catch(() => {})
938    let created = false
939    if (!(await $.fs.exists(p.todo))) {
940      // $.fs has no mkdir or remove, so those go through the shell tools.
941      await $.process.run(['mkdir', '-p', `${dir}/todo`]).catch(() => {})
942      await $.fs.write(p.todo, emptyBoard(lang))
943      created = true
944    }
945    if (await $.fs.exists(p.off)) await $.process.run(['rm', '-f', p.off]).catch(() => {})
946    if (created) await update($, nowText, () => emptyBoard(lang))
947    await openPane($, NOW_PANE, L[lang].todoTitle)
948    return { text: created ? `Created ${p.todo} and opened.` : 'Opened.' }
949  })
950
951  on('command.run', { command: 'todo-pane-pinboard' }, async $ => {
952    const act = paneAction(await stateOf($, PIN_PANE))
953    if (act === 'close') {
954      await $.ui.close({ id: PIN_PANE })
955      return { text: 'Closed.' }
956    }
957    await openPane($, PIN_PANE, L[lang].pinTitle)
958    return { text: act === 'front' ? 'Brought forward.' : 'Opened.' }
959  })
960
961  on('command.run', { command: 'todo-pane-wrap' }, async $ => {
962    const target = wrapTarget(await $.ui.panes().catch(() => []))
963    if (!target) return { text: 'No todo-pane pane is shown.' }
964    const v = target === 'todo' ? !(await read($, wrapOn)) : !(await read($, pinWrapOn))
965    if (target === 'todo') await update($, wrapOn, () => v)
966    else await update($, pinWrapOn, () => v)
967    await $.store.set(target === 'todo' ? 'wrap' : 'pinWrap', v).catch(() => {})
968    return { text: `${target === 'todo' ? 'TODO' : 'Pins'}: ${v ? 'wrap on.' : 'wrap off (truncate).'}` }
969  })
970
971  // The pin skill: tell it the concrete file and show the pins pane.
972  on('skill.prompt', async ($, e, next) => {
973    const r = await next(e)
974    if (e.skill !== 'todo-pane:pin' || !r || !('text' in r)) return r
975    await sync($).catch(() => {})
976    if (!(await stateOf($, PIN_PANE)).isOpen) await openPane($, PIN_PANE, L[lang].pinTitle).catch(() => {})
977    return { text: `${r.text}\n\nPin file for this session: ${p.pin} (create it if missing).` }
978  })
979
980  on('ui.render', { component: 'Pane', requestId: NOW_PANE }, async ($, e) => {
981    const { Box, Markdown, Text } = $.ui.resolve(e)
982    const body = fixSkinTone(await read($, nowText))
983    // Width of this draw; the engine redraws when it changes. Without one, nothing is cut.
984    const cols = Number((e.props as any)?.bodyColumns)
985    const todo = body ? markEmptySections(numberSubsections(body), L[lang].empty) : L[lang].emptyTodo
986    const wrap = await read($, wrapOn)
987    // Rows of this draw; without them only the newest earlier day is shown.
988    const rows = Number((e.props as any)?.scroll?.bodyRows)
989    let past = { days: [] as PastDay[], older: false }
990    try { past = JSON.parse((await read($, pastText)) || 'null') ?? past } catch {}
991    // The block starts "\n\n---"; the blank row between the parts becomes marginTop, and the block is drawn faint.
992    const block = body ? fixSkinTone(pastDaysBlock(past.days, past.older, `${dir}/todo/done/`, rowsOf(todo, cols, wrap), rows, cols, wrap, lang)) : ''
993    const cut = (x: string) => (wrap || !(cols > 0) ? x : truncateForWidth(x, cols))
994    const md = mdOf({ Box, Markdown, Text }, cols, cut)
995    return (
996      <Box flexDirection="column">
997        {md(todo)}
998        {block && (
999          <Box marginTop={1}>
1000            {md(block.replace(/^\n+/, ''), true)}
1001          </Box>
1002        )}
1003      </Box>
1004    )
1005  })
1006
1007  on('ui.render', { component: 'Pane', requestId: PIN_PANE }, async ($, e) => {
1008    const { Box, Markdown, Text } = $.ui.resolve(e)
1009    const body = fixSkinTone(await read($, pinText))
1010    const cols = Number((e.props as any)?.bodyColumns)
1011    const text = body || L[lang].emptyPin
1012    const wrap = await read($, pinWrapOn)
1013    const cut = (x: string) => (wrap || !(cols > 0) ? x : truncateForWidth(x, cols))
1014    const md = mdOf({ Box, Markdown, Text }, cols, cut)
1015    return (
1016      <Box flexDirection="column">
1017        {md(text)}
1018      </Box>
1019    )
1020  })
1021}
1022
types/index.d.ts 8 lines
1export type NowText = string
2
3declare module 'claude-code' {
4  interface PluginState {
5    'todo-pane': { text: NowText; pin: NowText; past: string; wrap: boolean; pinWrap: boolean; title: string | null | undefined }
6  }
7}
8