SLOPSHOPPER

reply-annotate

No description.

panebandcommandtoastprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · reply-annotate
│ ┃ reply-annotate ✕ › fix the failing auth test and add an audit log call │ ┃ 注釈はまだない │ ┃ 選択して /an コメント で追加 ⏺ 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 │ │ › /an │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · reply-annotate
注釈はまだない 選択して /an コメント で追加
README

Dotfiles

chezmoi で管理している。

QuickStart

brew install chezmoi age mise

age 秘密鍵を ~/.config/chezmoi/key.txt へ配置する。

chmod 600 ~/.config/chezmoi/key.txt
git clone git@github.com:TakeshiOnishi/dotfiles.git ~/dotfiles
chezmoi init --source ~/dotfiles
chezmoi apply

init 時にマシン種別(personal / work)を尋ねられる。

言語のバージョンは、マシンごとに mise で入れる。 バージョンは ~/.config/mise/config.toml に書かれ、dotfiles では管理しない。

mise use -g node@22

git のユーザー名とメールアドレスは、~/.gitconfig.local に手で書く。

[user]
  name = <名前>
  email = <メールアドレス>

apply 前のバックアップ

chezmoi apply の直前に、上書き・削除されるファイルを退避する。 手で編集したファイルを、apply で誤って消す事故への備え。

  • 仕組み
  • .chezmoi.toml.tmpl の [hooks.apply.pre] から .chezmoi-backup.sh を呼ぶ
  • 設定は chezmoi init で作られるため、初めて使うマシンの最初の apply から効く
  • 退避先
  • ~/.local/state/chezmoi-backups/<日時>/<ホームからの相対パス>
  • 各世代の status.txt に、退避したファイルの chezmoi status の行を残す
  • 保持
  • 30 日を過ぎた世代を、次の apply のときに消す
  • 期限に関係なく、最新 5 世代は残す
  • 退避に失敗したときは、apply を止める

復元するときは、退避先から cp で戻す。

ls ~/.local/state/chezmoi-backups/
cp -p ~/.local/state/chezmoi-backups/<日時>/.zshrc ~/.zshrc

構成

パス配置先
dot_*ホーム直下
dot_config/~/.config/
dot_claude/~/.claude/
.chezmoi*配置しない。chezmoi 自身の設定

exact_ の付いたディレクトリは、ソースにないファイルを apply のときに消す。 ホーム側に直接ファイルを置かない(例: ~/.config/nvim/lua/plugins)。

管理しないもの

認証情報と、万が一露出して困るものは、このリポジトリに一切入れない。 暗号化していても入れない。

  • 対象の例
  • API トークン・アクセスキー・パスワード
  • 秘密鍵・証明書の秘密部分
  • 置き場所は ~/.zsh/rc/*_local.zsh にする
  • init.zsh が、各設定の最後に読み込む
  • .chezmoiignore に入れてあり、chezmoi の管理対象にならない
  • マシンごとに手で作る

暗号化の目的

暗号化は、個人の思考フローを公開しないためだけに使う。 秘密情報を守る手段としては使わない。 漏れても問題ない設計にする。

  • 対象は encrypted_* のファイル
  • マシン種別(personal / work)ごとのファイルは、接尾辞で分ける
  • *_personal.zsh:personal のマシンだけに置く
  • *_work.zsh:work のマシンだけに置く
  • *_local.zsh:そのマシンだけに置き、chezmoi で管理しない

日常の操作

<target> はホーム側の配置先パスを指す(例: ~/.zshrc)。 ソース側のパスを渡すと not managed になる。

chezmoi diff                   # 適用したら何が変わるかを見る
chezmoi apply                  # ソースの内容をホームへ反映する
chezmoi edit --apply <target>  # ソースを編集して即座に反映する
chezmoi merge <target>         # ホーム側の変更をソースへ取り込む

chezmoi re-add はテンプレートに効かない。 アプリが書き換えた設定を取り込むときは chezmoi merge を使う。

Source 2 files
hooks/register.tsx 343 lines
1// 選択範囲に注釈を貯めて、次の発言にまとめて添える
2//   /an <コメント> : 選択範囲とコメントを 1 件貯める(Claude には送らない)
3//   /an paste      : 貯めた注釈を入力欄へ入れて、貯めた分を空にする
4//   /an undo       : 最後の 1 件を消す
5//   /an clear      : 全件を消す
6//   /an            : ペインを開く
7//   選択なしで Enter : 貯めた注釈を発言に添えて送る。発言は [その他] として注釈の後ろに置く
8// 選択中に herdr の ctrl+t → m を押すと、入力欄の上の帯にコメント欄を出す。m は目印の文字を送り、
9// 続けて ctrl+x tab で帯へ移る。Enter で 1 件貯める。プロンプトを送らないので、会話ログは最下部へ飛ばない
10// ctrl+t → M を押すと、貯めた注釈を入力欄へ入れる。書きかけの文字は [その他] として注釈の後ろに置く。送信はしない
11import { atom, read, update } from 'claude-code'
12import type { EngineInterface, Register } from 'claude-code'
13
14import type { Annotation } from '../types'
15
16const PANE = 'reply-annotate'
17const COMMAND = 'an'
18// 入力欄が /an を書きかけているか
19const COMPOSING = new RegExp(`^/${COMMAND}(\\s|$)`)
20// herdr の m が送る目印の文字(私用領域)。入力欄には入れずに捨てる
21const MARK = '\uE000'
22// herdr の M が送る目印の文字。貯めた注釈を入力欄へ入れる
23const PASTE_MARK = '\uE001'
24// 選択の有無を見に行く間隔
25const POLL_MS = 300
26// ペインの幅。端末幅に対する割合と、読める下限の桁数
27const PANE_RATIO = 0.15
28const PANE_MIN_COLUMNS = 24
29// 端末幅が分からないとき(プラグインからの実行など)に使う幅
30const FALLBACK_COLUMNS = 80
31// 帯の右端にエンジンが取る桁数([-] の分)
32const BAND_MARK_COLUMNS = 5
33
34const annotations = atom({ plugin: 'reply-annotate', key: 'annotations' } as const, [])
35const selected = atom({ plugin: 'reply-annotate', key: 'selected' } as const, null)
36// 注釈に使った選択範囲。同じ選択で 2 件目を作らないよう覚えておく
37const used = atom({ plugin: 'reply-annotate', key: 'used' } as const, null)
38// 編集中の注釈の番号(0 始まり)
39const editing = atom({ plugin: 'reply-annotate', key: 'editing' } as const, null)
40// 入力欄が /an で始まっているか。選択中の帯は、このときだけ出す
41const composing = atom({ plugin: 'reply-annotate', key: 'composing' } as const, false)
42// 前回見た入力欄の文字。選択後に変わったら、コピー用の選択とみなして帯を消す
43const draft = atom({ plugin: 'reply-annotate', key: 'draft' } as const, '')
44// m で帯のコメント欄を出しているか。選択しただけでは出さない
45const writing = atom({ plugin: 'reply-annotate', key: 'writing' } as const, false)
46
47// 先頭に見出しを置き、「番号: 引用」の後に空行を挟んでコメントを書く。引用の 2 行目以降は字下げする
48// 全体へのコメントがあれば、見出し [その他] を付けて最後に置く
49const format = (list: readonly Annotation[], rest = '') =>
50  [
51    '[引用して指摘・質問]',
52    ...list.map((annotation, i) => {
53      const quote = annotation.quote.replace(/\n/g, '\n   ')
54      return `${i + 1}: ${quote}\n\n${annotation.comment}`
55    }),
56    ...(rest.trim() === '' ? [] : ['[その他]', rest.trim()]),
57  ].join('\n\n')
58
59const firstLine = (text: string) => text.split('\n')[0] ?? ''
60
61const open = ($: EngineInterface, terminalColumns: number) =>
62  $.ui.open({
63    id: PANE,
64    title: 'reply-annotate',
65    columns: Math.max(PANE_MIN_COLUMNS, Math.round(terminalColumns * PANE_RATIO)),
66  })
67
68// ペインを閉じる。失敗しても、注釈の送信や消去は止めない
69const close = ($: EngineInterface) => $.ui.close({ id: PANE }).catch(() => undefined)
70
71// 注釈を空にして、ペインも閉じる
72const clear = async ($: EngineInterface) => {
73  await update($, annotations, () => [])
74  await update($, editing, () => null)
75  await close($)
76}
77
78// 選択範囲とコメントを 1 件貯める。選択がなければ toast で伝える
79const add = async ($: EngineInterface, comment: string, terminalColumns: number) => {
80  const quote = await read($, selected)
81  if (quote === null) {
82    $.ui.toast('選択範囲がない。注釈する箇所を選択してから実行する')
83    return
84  }
85  await update($, annotations, list => [...list, { quote, comment }])
86  await update($, used, () => quote)
87  await update($, selected, () => null)
88  await update($, writing, () => false)
89  await open($, terminalColumns)
90  const count = (await read($, annotations)).length
91  $.ui.toast(`注釈 ${count} 件目を追加した`)
92}
93
94// 1 件消す。0 件になったらペインを閉じる
95const remove = async ($: EngineInterface, index: number) => {
96  await update($, annotations, list => list.filter((_, i) => i !== index))
97  await update($, editing, () => null)
98  if ((await read($, annotations)).length === 0) {
99    await close($)
100  }
101}
102
103// コメントを入力欄に戻して、編集を始める
104const edit = async ($: EngineInterface, index: number) => {
105  const annotation = (await read($, annotations))[index]
106  if (annotation === undefined) {
107    return
108  }
109  await update($, editing, () => index)
110  await $.prompt.fill({ text: annotation.comment, mode: 'replace' })
111}
112
113export const register: Register = on => {
114  on('session.start', async ($, e, next) => {
115    await $.command.register({
116      name: COMMAND,
117      description: '選択範囲に注釈を貯める。paste で入力欄へ入れる、undo で最後の 1 件、clear で全件を消す',
118      argumentHint: '<コメント>|paste|undo|clear',
119    })
120
121    // 選択や入力欄が変わったら帯を描き直す。編集中に入力欄が空になったら、編集を取り消す
122    $.clock.every(POLL_MS, async () => {
123      const text = (await $.ui.selection())?.text.trim() || null
124      const fresh = text !== null && text !== (await read($, used)) ? text : null
125      if (fresh !== (await read($, selected))) {
126        await update($, selected, () => fresh)
127        await update($, writing, () => false)
128      }
129      const typed = (await $.prompt.read()).text
130      const isComposing = COMPOSING.test(typed)
131      if (isComposing !== (await read($, composing))) {
132        await update($, composing, () => isComposing)
133      }
134      // 選択したまま入力欄に打ち続けたら、注釈ではなくコピー用の選択だったとみなす。
135      // /an を打ちかけている途中(/ や /a)では消さない
136      if (typed !== (await read($, draft))) {
137        await update($, draft, () => typed)
138        const quote = await read($, selected)
139        if (quote !== null && !typed.startsWith('/')) {
140          await update($, used, () => quote)
141          await update($, selected, () => null)
142          await update($, writing, () => false)
143        }
144      }
145      if ((await read($, editing)) !== null && typed === '') {
146        await update($, editing, () => null)
147      }
148    })
149
150    return next(e)
151  })
152
153  // 結果は toast で伝え、command の出力行には何も出さない(Claude に読ませない)
154  on('command.run', { command: COMMAND }, async ($, e) => {
155    const args = e.args.trim()
156    switch (args) {
157      case '':
158        await open($, e.presentation?.columns ?? FALLBACK_COLUMNS)
159        return {}
160      case 'paste': {
161        const list = await read($, annotations)
162        if (list.length === 0) {
163          $.ui.toast('貯めた注釈がない')
164          return {}
165        }
166        await clear($)
167        await $.prompt.fill({ text: format(list), mode: 'insert' })
168        return {}
169      }
170      case 'undo':
171        await update($, annotations, list => list.slice(0, -1))
172        await update($, editing, () => null)
173        if ((await read($, annotations)).length === 0) {
174          await close($)
175        }
176        $.ui.toast('最後の注釈を消した')
177        return {}
178      case 'clear':
179        await clear($)
180        $.ui.toast('注釈を全件消した')
181        return {}
182    }
183
184    await add($, args, e.presentation?.columns ?? FALLBACK_COLUMNS)
185
186    return {}
187  })
188
189  on('prompt.submit', async ($, e, next) => {
190    // 自分の Enter だけを扱う。プラグインや通知からの発言は素通しする
191    if (e.origin.kind !== 'composer') {
192      return next(e)
193    }
194
195    const index = await read($, editing)
196    if (index !== null) {
197      const comment = e.text.trim()
198      await update($, annotations, list =>
199        list.map((annotation, i) => (i === index ? { ...annotation, comment } : annotation)),
200      )
201      await update($, editing, () => null)
202
203      return { drop: `注釈 ${index + 1} 件目を更新した` }
204    }
205
206    const list = await read($, annotations)
207    if (list.length === 0) {
208      return next(e)
209    }
210    await clear($)
211
212    return next({ ...e, text: format(list, e.text) })
213  })
214
215  // 目印を拾う。目印は入力欄に入れない
216  //   M : 書きかけの文字を後ろに回して、貯めた注釈を入力欄へ入れる
217  //   m : 帯にコメント欄を出す
218  on('prompt.edit', async ($, e, next) => {
219    if (e.inputText.includes(PASTE_MARK)) {
220      const list = await read($, annotations)
221      if (list.length === 0) {
222        $.ui.toast('貯めた注釈がない')
223        return { text: e.text, cursor: e.cursor }
224      }
225      await clear($)
226      const text = format(list, e.text)
227      return { text, cursor: text.length }
228    }
229    if (!e.inputText.includes(MARK)) {
230      return next(e)
231    }
232    if ((await read($, selected)) !== null) {
233      await update($, writing, () => true)
234    }
235    const inputText = e.inputText.split(MARK).join('')
236    if (inputText === '' && e.start === e.end) {
237      return { text: e.text, cursor: e.cursor }
238    }
239    return next({ ...e, inputText })
240  })
241
242  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
243    if (e.props.hasSurvey) {
244      return next(e)
245    }
246
247    const { Box, Input, Text } = $.ui.resolve(e)
248    const list = await read($, annotations)
249    const index = await read($, editing)
250
251    if (index !== null) {
252      return (
253        <Text color="yellow" wrap="truncate-end">
254          📝 {index + 1} 件目「{firstLine(list[index]?.quote ?? '')}」を編集中:Enter で更新 ・ 入力欄を空にすると取り消し
255        </Text>
256      )
257    }
258    const quote = await read($, selected)
259    if (quote !== null && (await read($, composing))) {
260      return (
261        <Text color="yellow" wrap="truncate-end">
262          📝 「{firstLine(quote)}」 → /an コメント で注釈に追加
263        </Text>
264      )
265    }
266    // 送信せずに貯めるコメント欄。m で出し、帯へ移ったらすぐ打てるよう autoFocus にする
267    if (quote !== null && (await read($, writing))) {
268      return (
269        <Box flexDirection="column">
270          <Text color="yellow" wrap="truncate-end">
271            📝 「{firstLine(quote)}」 にコメントを書き、Enter で注釈に追加
272          </Text>
273          <Input
274            key="comment"
275            label="注釈"
276            placeholder="コメント"
277            submitLabel="貯める"
278            autoFocus
279            onSubmit={async value => {
280              const comment = value.trim()
281              if (comment !== '') {
282                // 帯の幅に、エンジンが右端に取る 5 桁を足して端末幅とみなす
283                await add($, comment, e.props.bodyColumns + BAND_MARK_COLUMNS)
284              }
285            }}
286          />
287        </Box>
288      )
289    }
290    if (list.length > 0) {
291      return <Text dimColor>📝 注釈 {list.length} 件:次の発言に添えて送る</Text>
292    }
293
294    return next(e)
295  })
296
297  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
298    const { Box, Button, Text } = $.ui.resolve(e)
299    const list = await read($, annotations)
300
301    if (list.length === 0) {
302      return (
303        <Box flexDirection="column">
304          <Text dimColor>注釈はまだない</Text>
305          <Text dimColor>選択して /an コメント で追加</Text>
306        </Box>
307      )
308    }
309
310    return (
311      <Box flexDirection="column">
312        {list.map((annotation, i) => (
313          <Box key={`annotation-${i}`} flexDirection="column" marginBottom={1}>
314            <Text dimColor wrap="truncate-end">
315              {i + 1} &gt; {firstLine(annotation.quote)}
316            </Text>
317            <Text>  → {annotation.comment}</Text>
318            <Box>
319              <Text>  </Text>
320              <Button key={`edit-${i}`} label="編集" onPress={() => edit($, i)} />
321              <Text> </Text>
322              <Button key={`remove-${i}`} label="削除" onPress={() => remove($, i)} />
323            </Box>
324          </Box>
325        ))}
326        <Box>
327          <Button
328            key="send"
329            label="送信"
330            onPress={async () => {
331              const text = format(await read($, annotations))
332              await clear($)
333              await $.prompt.submit({ text })
334            }}
335          />
336          <Text> </Text>
337          <Button key="clear" label="全消去" onPress={() => clear($)} />
338        </Box>
339      </Box>
340    )
341  })
342}
343
types/index.d.ts 16 lines
1export type Annotation = { quote: string; comment: string }
2
3declare module 'claude-code' {
4  interface PluginState {
5    'reply-annotate': {
6      annotations: Annotation[]
7      selected: string | null
8      used: string | null
9      editing: number | null
10      composing: boolean
11      draft: string
12      writing: boolean
13    }
14  }
15}
16