Shares notices with every session in the same repository, or on the machine

マシン上で同時に動く Claude Code のセッションへ、リポジトリ単位でお知らせを届ける mod です。 「CI を止めているので Codex のレビューだけ見ればよい」のような状況の変化を、セッションごとに打ち直さずに済みます。
notice 2h: CI is paused, check the Codex review only
notice (all) 1d: Rate limits are tight this week
/notice <本文> 同じリポジトリのセッション全体に出す
/notice --all <本文> リポジトリを問わず、マシン上の全セッションに出す
/notice clear このセッションの帯に出ているお知らせをすべて消す
投稿したセッションが終わっても、お知らせは残ります。 期限はなく、消えるのは /notice clear を実行したときだけです。 帯には投稿からの経過時間を出すので、古いお知らせは見ればわかります。
mod が動く Claude Code のバージョンは usage-meter と同じです。
Claude Code のプロンプトで、次の 3 つを順に実行します。
/plugin marketplace add HolyGrail/claude-mods
/plugin install notice-board@claude-mods
/reload-plugins
更新の手順と注意点は、リポジトリの README にまとめてあります。
clone したリポジトリのルートで、次のように起動します。
claude --plugin-dir ./plugins/notice-board
手元のコードを常に読み込むなら、~/.claude/settings.json の env に CLAUDE_CODE_PLUGIN_DIRS としてこのディレクトリの絶対パスを書きます。
各セッションは 60 秒ごとにお知らせを読み直します。 別のセッションで投稿したお知らせは、遅くとも 1 分後には帯に出ます。
モデルには、お知らせごとに 1 回だけ、会話へ 1 行足して伝えます。 足すのは、次のターンが始まる瞬間です。 プロンプトが会話に入ったあと、最初のリクエストを送る前にあたります。 帯にはすぐ出ますが、モデルが知るのは次のターンからです。 長いターンの途中で届いたお知らせも、そのターンのあいだはモデルに伝わりません。
もっと早く足せそうに見えます。 しかし、モデルが会話を読むのはリクエストを送るときなので、ターンの合間に足しても読まれる時期は変わりません。 ターンの途中で足すと、行は応答の途中に入ります。 advisor のようなサーバー側ツールは、呼び出しと結果が 1 つのアシスタントメッセージに収まります。 そのあいだに行が入ると、API はそれ以後のリクエストをすべて拒否し、会話は使えなくなります。 バージョン 0.2 までは 60 秒ごとに足していたので、これが実際に起きていました。
system prompt には書き込みません。 書き込むと、お知らせが変わるたびに prompt cache が無効になるからです。 伝えたお知らせが /notice clear で消えたときや、セッションが別のリポジトリへ移って対象から外れたときも、取り下げを 1 回だけ伝えます。 伝えなければ、モデルはもう当てはまらないお知らせに従い続けます。 ただし、同じ本文のお知らせがほかに出ているあいだは、取り下げを伝えません。
投稿したセッションのモデルにも、同じ経路で伝えます。 対話セッションでは、コマンドの出力はモデルが読む会話に入らないからです。
どのお知らせを伝えたかは、会話そのものから読み直します。 mod はお知らせ 1 件ごと、取り下げ 1 件ごとに会話へ 1 行足し、その行を会話の頭から順にたどって、伝えたものと取り下げたものを突き合わせます。 読むのは会話の Messages API 形式($.session.messages({ as: 'api' }))です。 引数なしで返る行の形式には mod が足した行が含まれません。 そちらを読んでいたバージョン 0.2 までは、毎回「まだ伝えていない」と判定して、同じお知らせを足し続けていました。 行の末尾には (notice-board ref …) を付けます。これはマシンごとの秘密の値で本文から作った印で、印の合わない行(同じ文面を手で打ったプロンプトなど)は mod の行として扱いません。 印のないバージョン 0.1 の行は、そのセッションで 0.1 が伝えたと記録しているお知らせに限って読みます。 お知らせ自体は 60 秒ごとと /notice の実行時にも読み直して帯に出しますが、会話を読み直してモデルに伝えるのはターンの始まりだけです。 そのため、会話が入れ替わったり縮んだりしても、次のターンでいまの会話に合わせて伝え直します。
/clear、コンパクションのあとは、会話に行が残っていないので、いま出ているものを改めて伝えます/resume や --resume で読み込んだ会話には、その会話にない分だけを伝えます。読み込んだ会話で伝えたお知らせがその後消えていれば、取り下げを伝えます/rewind や復元ピッカーで巻き戻して行が消えたときは、次のターンの始まりに改めて伝えます/branch で分けた会話は元の会話の行を引き継ぐので、重ねては伝えません/resume は新しい会話を mod の受け取るイベントのあとに読み込むので、その間に始まったターンの読み直しが元の会話へ伝えることがあります。 新しい会話には、次のターンで伝えます。
origin の URL を host/owner/name の形にそろえて比べます。 git@github.com:owner/app と https://github.com/owner/app.git は同じリポジトリです。 ホスト名の大文字小文字は区別しませんが、パスの大文字小文字は区別します。パスを区別する Git サーバーもあるからです。 ポート番号も残すので、同じホストの別ポートにあるリポジトリは別物として扱います。 同じリポジトリの worktree も別のクローンも、同じお知らせを受け取ります。 origin がないリポジトリと、origin がローカルのパスや file:// のリポジトリは、main working tree のパスで比べます。 ローカルの origin は ../upstream.git のように相対パスで書けるので、綴りが同じでも別のリポジトリを指すことがあるからです。
$.store は mod ごとに分かれていて、ほかの mod からはお知らせのキーを書けません。 ほかの mod は、/notice を $.command.run で呼んで投稿します。
await $.command.run({ command: 'notice', args: 'main advanced (#12). Rebase before the next push.' })
pr-relay は、監視中の PR のマージを検知したときに、この形で「main が進んだ」と出します。 文面には、次の push の前に rebase するよう書くことを勧めます。 作業の途中で rebase すると、コンフリクトの解消が実装の変更と混ざるからです。 $.command.run はセッションが待機中になってから実行されるので、投稿は数分遅れることがあります。
$.store には atomic な更新がないため、お知らせごとに notice:<id> のキーを分けています。 投稿がほかのお知らせを上書きすることはありません。 ただし、/notice clear の実行中に投稿されたお知らせは、消えずに残ることがあります。
伝えたかどうかは、お知らせの範囲(リポジトリかマシン全体か)と本文で見分けます。 範囲と本文が同じお知らせが二つ出ていても、モデルには 1 回だけ伝えます。 $.session.messages() が返すのは新しい 4096 件までなので、それより前に伝えた行は会話にないものとして、もう一度伝えます。 会話が 4096 件を超えたり compaction で要約されたりして伝えた行が見えなくなっても取り下げを伝えられるよう、会話ごとに伝えたお知らせを $.store の told:<セッション ID> にも残します。 この記録は取り下げにだけ使い、まだ出ているお知らせの行が見えなくなったときはもう一度伝えます。 この記録は 8 日間読み込まれなかった会話の分から消します。
モデルへの伝達が拒否されたとき(プラグインが会話を変えられない実行や、上位のプラグインによる拒否)は、同じ会話のうちは再試行しません。 どちらも次の試行で結果が変わらないからです。帯には出たままになり、伝えられなかった行は debug ログに残ります。 会話が入れ替わったときや巻き戻したとき、および mod の再読み込みのあとは、一度だけ試し直します。
cd plugins/notice-board
claude plugin test
テストキットは mod の $.session.append を受け取り、mock.session(on) で記録します。 テストは session.append のフック({ door: 'note' })でその行を取り、モデルに渡す内容を確かめます。 テストの $.session.messages({ as: 'api' }) は、エンジンと同じように、その行を隣の user メッセージへテキストブロックとして畳み込んだ形で返します。 行の形式には足した行を含めません。 ターンは $.turn.start で始めます。 /clear、/resume、/rewind は、テストが会話を入れ替えて再現します。
hooks/register.js 518 lines1// Shares notices across the sessions on this machine: /notice posts one to every session in the
2// same repository (or, with --all, to every session), each shows it above the prompt and passes
3// it on to its model once, at the start of its next turn, and /notice clear takes it down
4// everywhere.
5
6// The notices this session shows, newest first
7let notices = []
8let sessionId = null
9// The timer that picks up other sessions' notices, kept so a later session.start can stop it
10let ticker = null
11// Loads run one at a time, so a tick and a command can't pass the same notice on twice
12let queue = Promise.resolve()
13// The rows the host refused to add, by key, so a refusal is not retried every tick. Forgotten
14// when the conversation is replaced or rewound, which may want them again.
15const refused = new Set()
16// The conversation as the last load read it while refusals were held, one fingerprint per message
17let seen = []
18// Bumped by every session.start and conversation switch, so a load begun before one doesn't record
19// its refusals against the conversation that follows
20let generation = 0
21// The texts version 0.1 told this session of, from its $.state record, which vouch for its
22// unsigned rows. A promise, set along with sessionId and with no wait between, so a load that
23// takes the id takes the record of the same conversation, however long it takes to read
24let legacy = Promise.resolve(new Set())
25// Counts this module's posts, so two in the same millisecond get keys of their own
26let posts = 0
27
28// $.store has no atomic update, so each notice has a key of its own: posting never overwrites
29// another session's notice, and clearing deletes keys instead of rewriting a shared list
30const KEY_PREFIX = 'notice:'
31// What the model was told is read back from the conversation itself, so a reload, /clear,
32// compaction, /resume, /rewind and /branch each leave it right. It is read in its Messages API
33// form: the rows form leaves out the rows a plugin adds, while the API form carries each as a
34// text block of its own, folded into the user message beside it. Each notice or withdrawal is a
35// block of its own, whose whole text is one of these, so a notice's body may hold anything, new
36// lines that look like another row included. The ref that ends a row is a hash of its body under a
37// secret kept in $.store, so a prompt that only reads like a row is not taken for one. Each
38// secret has a key of its own, so one that signed a row is never overwritten by another.
39const TOLD = /^Notice to every Claude Code session (on this machine|in this repository), posted \d+[mhd] ago with \/notice: ([\s\S]*)\n\(notice-board ref ([0-9a-f]{8})\)$/
40const WITHDRAWN = /^This notice no longer applies: ([\s\S]*)\n\(notice-board ref ([0-9a-f]{8})\)$/
41const SECRET_PREFIX = 'secret:'
42// Version 0.1 joined its lines into one row, unsigned
43const TOLD_V1 = /^Notice to every Claude Code session (on this machine|in this repository), posted \d+[mhd] ago with \/notice: ([\s\S]*)$/
44const WITHDRAWN_V1 = /^This notice no longer applies: ([\s\S]*)$/
45const LINE_START_V1 = /\n(?=Notice to every Claude Code session |This notice no longer applies: )/
46const KNOWN_V1 = { plugin: 'notice-board', key: 'known' }
47// $.session.messages() returns at most this many messages, the newest
48const WINDOW = 4096
49// The text blocks left out of a message's fingerprint: a row this module added, whichever version
50// added it, since a row folded into a message must not read as a change to it; and a reminder the
51// engine folds into the newest user message when its request goes out, after the turn.start that
52// read it without
53const UNSTABLE_BLOCK = /^(?:Notice to every Claude Code session |This notice no longer applies: |<system-reminder>)/
54// What each conversation was told, under the session id, for the rows a full window no longer
55// returns: { at, told: [{ key, text }] }
56const RECORD_PREFIX = 'told:'
57// A record not written for this long is deleted
58const DAY_MS = 24 * 60 * 60 * 1000
59const STALE_MS = 8 * DAY_MS
60// How often to pick up notices other sessions posted or cleared
61const TICK_MS = 60_000
62// The band shows this many notices, newest first, and counts the rest
63const MAX_SHOWN = 3
64
65// The session.end reasons after which this module stops; /clear, /resume and logout leave it running
66const FINAL_REASONS = ['prompt_input_exit', 'other']
67
68const USAGE = 'Usage: /notice <text> | /notice --all <text> | /notice clear'
69
70export function register(on) {
71 // Fires again on an enable or a worker respawn, which may keep this module's variables
72 on('session.start', async ($, e, next) => {
73 ticker?.cancel()
74 // The queue stays: a load the previous start began may still be running
75 notices = []
76 forgetRefusals()
77 sessionId = await $.session.id()
78 legacy = legacyOf($)
79 await prune($)
80 await $.command.register({
81 name: 'notice',
82 description: 'Post a notice to every session in this repository (--all: on this machine), or clear them',
83 argumentHint: '[--all] <text> | clear',
84 })
85 // Fills the band; the model is told at its next turn. This start may be a respawn in the
86 // middle of a turn, which nothing says, so nothing is added to the conversation here.
87 await refresh($)
88 ticker = $.clock.every(TICK_MS, () => refresh($))
89 return next(e)
90 })
91
92 // The conversation is brought up to date here, after the prompt joined it and before the turn's
93 // first request goes out, and nowhere else. The model reads the conversation only when a request
94 // is sent, so telling it sooner gains nothing; and a row added while a turn runs lands wherever
95 // the response stands, even between a server tool's use and its result inside one assistant
96 // message, which the API then refuses on every later request, so the conversation is lost. The
97 // ticker, /notice and session.start only fill the band. The engine waits on this hook before
98 // its first request, so the rows are in when the model reads. Subagents raise no turn.start; a
99 // queued prompt's turn raises one of its own, so a prompt typed over a running turn is covered.
100 // A load that fails must not hold the turn back; the next turn tries again. Past the hook's
101 // budget the engine goes on without it, and a row added then would land in the turn: the load
102 // takes the hook's signal and adds nothing once it aborted.
103 on('turn.start', async ($, e, next) => {
104 await refresh($, true, next.signal).catch(() => {})
105 return next(e)
106 })
107
108 // /clear, /resume and /branch (fork) switch to another session id, which later posts carry. The
109 // conversation they leave is read at the next load: /resume installs its own only after this hook,
110 // so a tick in between may tell the outgoing one, and the load after it tells the new one
111 on('classic.SessionStart', { source: ['clear', 'compact', 'resume', 'fork'] }, async ($, e, next) => {
112 const outgoing = sessionId
113 // The host has moved to the new id already; it is taken up only once the switch is done, with
114 // no wait in between, so a tick during the switch still reads the outgoing conversation and
115 // keeps its record and refusals to it, and one after it reads the new one under the new id
116 const incoming = await $.session.id()
117 forgetRefusals()
118 const result = await next(e)
119 sessionId = incoming
120 legacy = legacyOf($)
121 forgetRefusals()
122 // A fork copies the conversation, and with it what was told before its window. In the queue,
123 // so no load of either conversation writes its record meanwhile; one under the new id may have
124 // written a record already, from the rows its window shows, so the two are merged. Not awaited:
125 // a load ahead of it may be waiting on the host, which may be waiting on this hook
126 if (e.source === 'fork' && outgoing !== null && outgoing !== sessionId) {
127 const target = sessionId
128 void serially(async () => {
129 const record = await $.store.get(RECORD_PREFIX + outgoing)
130 if (!isRecord(record)) return
131 const current = await $.store.get(RECORD_PREFIX + target)
132 const told = isRecord(current) ? current.told : []
133 const merged = [...told, ...record.told.filter((r) => !told.some((t) => t.key === r.key))]
134 if (merged.length === told.length) return
135 await $.store.set(RECORD_PREFIX + target, { at: isRecord(current) ? current.at : record.at, told: merged })
136 }).catch(() => {})
137 }
138 return result
139 })
140
141 on('session.end', async ($, e, next) => {
142 if (FINAL_REASONS.includes(e.reason)) ticker?.cancel()
143 return next(e)
144 })
145
146 // Answers /notice, from the person or from another plugin's $.command.run (pr-relay posts
147 // "main advanced" this way, since a plugin's $.store is its own)
148 on('command.run', { command: 'notice' }, async ($, e) => {
149 const args = e.args.trim()
150 if (args === 'clear') return { text: await clear($) }
151 const all = /^--all(\s|$)/.test(args)
152 const text = (all ? args.slice('--all'.length) : args).trim()
153 if (!text) return { text: USAGE }
154 return { text: await post($, text, all) }
155 })
156
157 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
158 if (notices.length === 0) return next(e)
159 const { Box, Text } = $.ui.resolve(e)
160 const now = await $.clock.now()
161 const rows = notices.slice(0, MAX_SHOWN).map((notice) =>
162 Box({
163 key: 'notice-' + notice.id,
164 flexDirection: 'row',
165 columnGap: 1,
166 children: [
167 Text({ dimColor: true, children: [label(notice, now)] }),
168 Text({ wrap: 'truncate-end', children: [notice.text] }),
169 ],
170 }),
171 )
172 const hidden = notices.length - MAX_SHOWN
173 if (hidden > 0) rows.push(Text({ key: 'notice-more', dimColor: true, children: ['+' + hidden + ' more'] }))
174 const board = Box({ flexDirection: 'column', children: rows })
175 // Keep what the mods after this one draw in the band
176 const rest = await next(e)
177 if (!rest) return board
178 return Box({ flexDirection: 'column', children: [board, rest] })
179 })
180}
181
182async function post($, text, all) {
183 const repoKey = repoKeyOf(await $.session.repo())
184 if (!all && repoKey === null) return 'Not in a git repository. Use /notice --all <text> to post to every session.'
185 const postedAt = await $.clock.now()
186 posts += 1
187 await $.store.set(KEY_PREFIX + postedAt + '-' + sessionId + '-' + posts, { text, repo: all ? null : repoKey, postedAt })
188 await refresh($)
189 return all ? 'Posted to every session on this machine.' : 'Posted to every session in this repository.'
190}
191
192// Takes down every notice this session shows; each other session tells its model at its next tick
193async function clear($) {
194 await refresh($)
195 const cleared = notices
196 await Promise.all(cleared.map((notice) => $.store.delete(KEY_PREFIX + notice.id)))
197 await refresh($)
198 if (cleared.length === 0) return 'No notices to clear.'
199 return 'Cleared ' + cleared.length + (cleared.length === 1 ? ' notice.' : ' notices.')
200}
201
202// Loads the notices after every earlier load has settled, whether it succeeded or not, and redraws.
203// With tell, the model is told too; only turn.start asks for that, and the permission is the
204// load's own, so a tick's load queued behind it never inherits it.
205function refresh($, tell = false, signal = null) {
206 return serially(() => load($, tell, signal)).then(() => $.ui.invalidate('ui.render'))
207}
208
209// Runs task once every earlier one has settled
210function serially(task) {
211 const run = queue.then(task, task)
212 queue = run.catch(() => {})
213 return run
214}
215
216// Reads the notices meant for this session and, with tell, tells the model about the ones its
217// conversation does not hold and the ones it holds that have since been cleared; nothing is added
218// once signal aborted
219async function load($, tell, signal) {
220 // Before any wait, so a restart or a switch that lands during one is seen
221 const started = generation
222 const id = sessionId
223 const known = legacy
224 const repoKey = repoKeyOf(await $.session.repo())
225 const keys = (await $.store.keys()).filter((key) => key.startsWith(KEY_PREFIX))
226 const values = await Promise.all(keys.map((key) => $.store.get(key)))
227 const shown = []
228 keys.forEach((key, i) => {
229 const notice = values[i]
230 if (!isNotice(notice)) return
231 const id = key.slice(KEY_PREFIX.length)
232 if (notice.repo === null || (repoKey !== null && notice.repo === repoKey)) shown.push({ id, ...notice })
233 })
234 // At an equal time the later id comes first, so every session lists them alike
235 shown.sort((a, b) => b.postedAt - a.postedAt || (a.id < b.id ? 1 : -1))
236 notices = shown
237 // Between turns the conversation is not read either: its form while a turn runs is not settled
238 // (a row added then is folded into a message only once the turn ends)
239 if (!tell) return
240
241 const messages = await $.session.messages({ as: 'api' })
242 if (refused.size > 0) {
243 const now = messages.map(fingerprint)
244 if (!continues(seen, now)) refused.clear()
245 seen = now
246 }
247 const secrets = await secretsOf($)
248 const { told, withdrawals } = await toldIn(messages, secrets, await known)
249 // Rows this conversation was told may be gone from what is read, dropped by a full window or
250 // folded into a compaction's summary: the record keeps those, less what the conversation shows
251 // was withdrawn since. They only count for withdrawing; a notice still shown whose row is gone is
252 // told again
253 const record = await $.store.get(RECORD_PREFIX + id)
254 const recorded = isRecord(record) ? record.told : []
255 const earlier = recorded.filter((r) => !told.has(r.key) && !withdrawals.has(r.text))
256 const shownTexts = new Set(shown.map((notice) => notice.text))
257 // This session's own posts too: a command's output is not part of what the model reads. Oldest
258 // first, and one row for notices that read the same
259 const fresh = []
260 for (const notice of [...shown].reverse()) {
261 const key = toldKey(notice)
262 if (!told.has(key) && !refused.has(key) && !fresh.some((f) => toldKey(f) === key)) fresh.push(notice)
263 }
264 // Cleared, or meant for a repository this session has left; one whose text another notice shown
265 // here still carries still applies
266 const toldTexts = new Set([...told.values(), ...earlier.map((r) => r.text)])
267 const withdrawn = [...toldTexts].filter((text) => !shownTexts.has(text) && !refused.has('withdrawn\n' + text))
268
269 // What the conversation holds once this load's rows are in
270 const holds = new Map([...earlier.map((r) => [r.key, r.text]), ...told])
271 if (fresh.length > 0 || withdrawn.length > 0) {
272 const now = await $.clock.now()
273 const rows = [
274 ...fresh.map((notice) => ({
275 key: toldKey(notice),
276 text: notice.text,
277 line:
278 'Notice to every Claude Code session ' +
279 (notice.repo === null ? 'on this machine' : 'in this repository') +
280 ', posted ' + ago(now - notice.postedAt) + ' ago with /notice: ' + notice.text,
281 })),
282 ...withdrawn.map((text) => ({ key: 'withdrawn\n' + text, text, line: 'This notice no longer applies: ' + text })),
283 ]
284 for (const row of rows) {
285 const line = row.line + '\n(notice-board ref ' + (await ref(secrets[0], row.text)) + ')'
286 // A restart or a switch since this load read the conversation: its rows may not fit the one
287 // installed now, which the next load reads afresh. Checked after the last wait before the
288 // append. A turn the engine began without waiting for this load any longer is left alone.
289 if (generation !== started || signal?.aborted) return
290 const result = await $.session
291 .append({ message: { type: 'user', content: [{ type: 'text', text: line }] } })
292 .catch((error) => ({ deny: error instanceof Error ? error.message : String(error) }))
293 if (result.deny === undefined) {
294 if (row.key.startsWith('withdrawn\n')) {
295 for (const [key, text] of holds) if (text === row.text) holds.delete(key)
296 } else holds.set(row.key, row.text)
297 continue
298 }
299 // A run no plugin may shape refuses the row; the band still shows the notices. A refusal met
300 // before a restart or a switch is not held against what follows it.
301 if (generation === started) {
302 if (refused.size === 0) seen = messages.map(fingerprint)
303 refused.add(row.key)
304 }
305 $.ui.log('notice-board could not tell the model: ' + result.deny + '\n' + line, { to: 'debug' })
306 }
307 }
308 // Only a load the switch didn't overtake writes, so the record stays the conversation's own
309 if (generation !== started) return
310 const holding = [...holds].map(([key, text]) => ({ key, text }))
311 const now = await $.clock.now()
312 // Unchanged, it is still written now and then, so prune keeps a conversation still in use
313 if (JSON.stringify(holding) === JSON.stringify(recorded) && (holding.length === 0 || now - record.at < DAY_MS)) return
314 if (holding.length === 0) await $.store.delete(RECORD_PREFIX + id)
315 else await $.store.set(RECORD_PREFIX + id, { at: now, told: holding })
316}
317
318function forgetRefusals() {
319 generation += 1
320 refused.clear()
321 seen = []
322}
323
324// The notices the conversation tells the model of, by key, with their text: each row this module
325// added in order, a withdrawal taking back every notice of its text; and the texts withdrawn. A
326// row is a text block of a user message, read whole.
327async function toldIn(messages, secrets, legacy) {
328 const signs = async (text, r) => {
329 for (const secret of secrets) if (r === (await ref(secret, text))) return true
330 return false
331 }
332 const told = new Map()
333 const withdrawals = new Set()
334 for (const message of messages) {
335 if (message.role !== 'user') continue
336 for (const text of textsOf(message)) {
337 const added = TOLD.exec(text)
338 if (added && (await signs(added[2], added[3]))) {
339 told.set((added[1] === 'on this machine' ? 'all' : 'repo') + '\n' + added[2], added[2])
340 withdrawals.delete(added[2])
341 continue
342 }
343 const withdrawn = WITHDRAWN.exec(text)
344 if (withdrawn && (await signs(withdrawn[1], withdrawn[2]))) {
345 for (const [key, value] of told) if (value === withdrawn[1]) told.delete(key)
346 withdrawals.add(withdrawn[1])
347 continue
348 }
349 // A row of version 0.1 counts where that version's record says it told the text
350 if (legacy.size === 0) continue
351 const parts = partsV1(text, legacy)
352 if (parts === null) continue
353 for (const part of parts) {
354 const added = TOLD_V1.exec(part)
355 if (added && legacy.has(added[2])) {
356 told.set((added[1] === 'on this machine' ? 'all' : 'repo') + '\n' + added[2], added[2])
357 withdrawals.delete(added[2])
358 }
359 const withdrawnV1 = WITHDRAWN_V1.exec(part)
360 if (withdrawnV1 && legacy.has(withdrawnV1[1])) {
361 for (const [key, value] of told) if (value === withdrawnV1[1]) told.delete(key)
362 withdrawals.add(withdrawnV1[1])
363 }
364 }
365 }
366 }
367 return { told, withdrawals }
368}
369
370// The texts of a message's text blocks, in order
371function textsOf(message) {
372 const blocks = Array.isArray(message.content) ? message.content : []
373 return blocks.filter((block) => block?.type === 'text' && typeof block.text === 'string').map((block) => block.text)
374}
375
376// Splits a row of version 0.1 into its lines. A body may itself hold a new line that starts like
377// another line, so a body the record lists is taken whole first, the longest such; any other runs
378// to the next line start.
379function partsV1(text, legacy) {
380 const parts = []
381 let rest = text
382 while (rest !== '') {
383 const head = /^(?:Notice to every Claude Code session (?:on this machine|in this repository), posted \d+[mhd] ago with \/notice: |This notice no longer applies: )/.exec(rest)
384 if (!head) return null
385 const body = rest.slice(head[0].length)
386 const known = [...legacy]
387 .filter((t) => body.startsWith(t) && (body.length === t.length || body.slice(t.length).search(LINE_START_V1) === 0))
388 .sort((a, b) => b.length - a.length)[0]
389 const end = known !== undefined ? known.length : body.search(LINE_START_V1)
390 const length = end === -1 ? body.length : end
391 parts.push(head[0] + body.slice(0, length))
392 rest = body.slice(length).replace(/^\n/, '')
393 }
394 return parts
395}
396
397// The texts version 0.1's record holds, if this session ran it
398async function legacyOf($) {
399 try {
400 const known = (await $.state.get(KNOWN_V1)).value
401 return new Set(Array.isArray(known) ? known.map((k) => k?.text).filter((t) => typeof t === 'string') : [])
402 } catch {
403 return new Set()
404 }
405}
406
407// The secrets rows on this machine are signed with, the one new rows are signed with first. The
408// first session that needs one makes it; sessions that make one at once each keep theirs, so every
409// row any of them signed stays readable, and all of them sign with the same one from then on.
410async function secretsOf($) {
411 const read = async () => {
412 const keys = (await $.store.keys()).filter((key) => key.startsWith(SECRET_PREFIX)).sort()
413 const values = await Promise.all(keys.map((key) => $.store.get(key)))
414 return values.filter((value) => typeof value === 'string')
415 }
416 const secrets = await read()
417 if (secrets.length > 0) return secrets
418 const made = hex(crypto.getRandomValues(new Uint8Array(16)))
419 await $.store.set(SECRET_PREFIX + made, made)
420 const kept = await read()
421 return kept.length > 0 ? kept : [made]
422}
423
424async function ref(secret, text) {
425 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret + '\n' + text))
426 return hex(new Uint8Array(digest)).slice(0, 8)
427}
428
429function hex(bytes) {
430 return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')
431}
432
433function isRecord(value) {
434 return (
435 value != null &&
436 typeof value.at === 'number' &&
437 Array.isArray(value.told) &&
438 value.told.every((r) => r != null && typeof r.key === 'string' && typeof r.text === 'string')
439 )
440}
441
442// Deletes the records of conversations not loaded for STALE_MS
443async function prune($) {
444 const now = await $.clock.now()
445 const keys = (await $.store.keys()).filter((key) => key.startsWith(RECORD_PREFIX))
446 for (const key of keys) {
447 const record = await $.store.get(key)
448 if (!isRecord(record) || now - record.at > STALE_MS) await $.store.delete(key)
449 }
450}
451
452// Notices of one scope that read the same are told once
453function toldKey(notice) {
454 return (notice.repo === null ? 'all' : 'repo') + '\n' + notice.text
455}
456
457// A message's identity for continues: its role, its tool calls and results, and its text less the
458// rows this module added, which are folded into the message beside them as they are added
459function fingerprint(message) {
460 const blocks = Array.isArray(message.content) ? message.content : []
461 const ids = blocks.map((b) => (b?.type === 'tool_use' ? b.id : b?.type === 'tool_result' ? b.tool_use_id : null)).filter((id) => id)
462 const texts = textsOf(message).filter((text) => !UNSTABLE_BLOCK.test(text))
463 return message.role + '\n' + ids.join(' ') + '\n' + texts.join('\n')
464}
465
466// Whether now is before carried on: before's messages, less the oldest ones the capped window
467// dropped, start it, so nothing before held was rewound or replaced
468function continues(before, now) {
469 if (before.length === 0) return true
470 // Where before's newest message sits in now, tried from the newest so a repeated one doesn't hide
471 // a longer match
472 for (let end = now.length - 1; end >= 0; end--) {
473 if (now[end] !== before[before.length - 1]) continue
474 const dropped = before.length - 1 - end
475 // Only a full window drops its oldest messages
476 if (dropped < 0 || (dropped > 0 && now.length < WINDOW)) continue
477 if (now.slice(0, end + 1).every((fp, i) => fp === before[dropped + i])) return true
478 }
479 return false
480}
481
482// Names a repository the same in each of its worktrees and clones: the origin remote as
483// host[:port]/path, whether it is spelled as a URL (https://, ssh://) or scp-style (git@host:path),
484// with or without a user or .git. The path keeps its case, which some servers tell apart. With no
485// remote, or a local one (a path or file://, whose spelling may be relative), the main working
486// tree's path.
487function repoKeyOf(repo) {
488 if (!repo) return null
489 const remote = repo.remote?.trim() ?? ''
490 // A host is a name or a bracketed IPv6 address
491 const url = /^(?!file:)[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?(\[[^\]]+\]|[^/:]+)(:\d+)?\/(.+)$/i.exec(remote)
492 const scp = url ? null : /^(?:[^@/]+@)?(\[[^\]]+\]|[^/:]+):(?!\/\/)(.+)$/.exec(remote)
493 const parts = url ? [url[1] + (url[2] ?? ''), url[3]] : scp ? [scp[1], scp[2]] : null
494 if (!parts) return 'path:' + repo.root
495 return parts[0].toLowerCase() + '/' + parts[1].replace(/^\/+|\/+$/g, '').replace(/\.git$/, '')
496}
497
498function isNotice(value) {
499 return (
500 value != null &&
501 typeof value.text === 'string' &&
502 typeof value.postedAt === 'number' &&
503 (value.repo === null || typeof value.repo === 'string')
504 )
505}
506
507function label(notice, now) {
508 return 'notice' + (notice.repo === null ? ' (all)' : '') + ' ' + ago(now - notice.postedAt) + ':'
509}
510
511function ago(ms) {
512 const minutes = Math.max(0, Math.floor(ms / 60_000))
513 if (minutes < 60) return minutes + 'm'
514 const hours = Math.floor(minutes / 60)
515 if (hours < 24) return hours + 'h'
516 return Math.floor(hours / 24) + 'd'
517}
518types/index.d.ts 10 lines1// What version 0.1 kept of the notices it passed on to the model: an id, and the text. Read once
2// per session.start to recognise that version's unsigned rows; never written.
3export type NoticeBoardKnown = { id: string; text: string }
4
5declare module 'claude-code' {
6 interface PluginState {
7 'notice-board': { known: NoticeBoardKnown[] }
8 }
9}
10