memory-kit watch: rings a doorbell in the session (idle-safe) when a file the home declares in memory-kit.conf (watch_files) grows or is replaced by other…

A Claude Code mod (function hooks) for a memory-kit home, kit issue #9, reshaped 2026-10-16. It is a separate plugin from the obligations pane, which stays read-only. A home can take either one without the other. Built against Claude Code 2.1.296's plugin API and checked live on 2.1.299 (early access; the API moves between releases).
The watch is information only. It never reads a file's meaning, never empties, moves or archives anything, and never says what a signal means: that is the home's own rule. On one timer (pollSeconds, default 5) it watches two kinds of things, both declared in the home's memory-kit.conf (absent means off):
watch_files): when a declared file grows or its text is replaced, the watch rings once -- one $.prompt.submit, which queues until the session is idle and starts a turn of its own, marked as coming from the plugin.watch_idle_minutes, watch_context_percent): one report when the session has sat idle past the mark (again after each further interval, with watch_idle_repeat: true), one when its context crosses each declared percent of the window.What it costs: every ring or report is a full turn (kit #17). The turn carries the session's whole context, so on a long session one prompt costs hundreds of thousands of input tokens, even when it says nothing new. Declare only what the session must act on.
watch_files:
- label: "hub mail"
path: comms/inboxes/team-lead.json
instruction: "consume the inbox or new messages won't land"
inject: false
- label: ""
path: ~/spool/links.txt
instruction: ""
inject: true
Every entry carries the same four fields, empty where unused:
[label]. Empty: the file's name.C:\, C:/ or UNC), ~/ for the user's home (HOME, else USERPROFILE on Windows), or relative to the kit home. A * in a segment matches entries of that directory (never a dotfile); each matched file is its own bell.true: the ring includes the grown tail's non-blank lines, not just the bell. For short, line-shaped files (a spool of URLs, one-line mail summaries): the harness cuts very long lines, so a file of essays wants inject: false and a session that reads the file itself.A ring is new text. The watch remembers each file's last-seen size, a hash of its text and, for a file up to 64 KiB, a hash of each of its lines (never the text). Text added past what was seen rings once, as growth. Other non-empty text in its place rings once, as a replacement, whatever its size, when it has a line the seen text did not have: the file was consumed and refilled between two polls (kit #52); with inject, all of the new text rides along. Lines are compared trimmed and without a trailing comma, and a line of only brackets, braces and commas does not count, so a consumer that writes back what it leaves -- [], or the entries it did not take, even re-indented -- rings nothing (kit #57). A file past 64 KiB keeps no lines: any other text in its place rings, as in watch 0.7.0. Everything else only moves the bookmark: created at 0 bytes, emptied, deleted (it counts 0, so delete-then-write rings), rewritten with no line it did not already have, or the same text written again. A file that sits unconsumed is not nagged: no new text, no new ring. All of one poll's rings go as one prompt. A ring the session's guards refuse rolls its bookmark back and rings again at a later poll.
Consuming is the home's own step. An inbox-style file (inject: false) is consumed by reading it and then deleting it, emptying it, or writing back what it did not take (kit #57) -- each resets the bookmark, so the next real write rings again. Its bookmark is the session's own: a new session (a restart, a /clear) rings an unconsumed inbox once more. A tail-style file (inject: true) needs no consuming: its bookmark advances and outlives the session (kit #51). The watch keeps it in the plugin's own store, per home, never in the home, and moves it only past what reached a turn: a new session rings only the lines no ring has brought in -- those written while no session ran, and those of a ring still queued when its session ended -- and the file may grow for good. Say the habit in the entry's instruction, where the session will read it.
A consumer must take everything a ring announced, or retry by itself. A ring needs new text: a file the consumer leaves as it was never changes again, so it never rings again, and what it holds waits until something else writes to the file. esl-suvekool met this on its first live ring (2026-10-16): its consumer waits 10 s before taking fresh courier mail, the ring came inside those 10 s, and the message stayed until a hand-run. Its fix is a model: when mail is too fresh, or the harness holds the lock, wait once and pass again; if something is still left, say so (a non-zero exit, a printed line) instead of returning quietly. A consumer that takes everything at once, as the household's does, is not exposed.
A ring reads [hub mail] /home/u/kit/comms/inboxes/team-lead.json grew. consume the inbox or new messages won't land -- was replaced. in place of grew. when other text, with a new line, took the file's place; with inject, the new lines follow, one per line.
Never silently idle (kit #14): a watch_files the watch cannot read, an entry without a path, an unknown field, an inject that is not true/false -- each is one visible notice (notify, else a transcript line), never a debug line alone, and the good entries still run. A conf still declaring watch_sources (watch 0.4.x and older) gets one migration notice: declare watch_files, and let the home consume its own files.
watch_idle_minutes: 50
watch_idle_repeat: true # optional (kit #47): report again after each further interval
watch_context_percent: 50, 60, 70, 80
[watch] This session has been idle for 52 min .... If the conf declares a watch_retire_step, the report quotes it as the home's own declared step. The report is armed by a human prompt and disarmed by firing, so one working stretch gets one report -- the watch's own rings never arm it, and a session no human spoke to is never pinged idle.watch_idle_repeat: true, kit #47): a report leaves the watch armed, so while the session stays idle a report comes every watch_idle_minutes, each a full interval after the last (also when a report's turn never starts). A human prompt still arms it first. This is a prompt-cache keep-alive: each report is a turn, and a turn re-reads the cached context before the cache's hour runs out. At 50 minutes the next turn after a long idle reads the cache instead of the whole context uncached, and Claude Code's idle compaction (which fires at about 54 idle minutes; see the adapters README) never sees the session idle that long. One report re-reads the whole context at the cache-read price: about 1% of a working day's input at 240k tokens; a night of reports costs about half of one uncached re-read, and a weekend away about three (a household estimate at the usual cache prices, 19.10.2026). A home that retires by its context gauge, not by idleness, should not declare watch_retire_step with it: every report would quote that step.$.session.usage() reading. Crossing a mark gives one report naming the load and the mark; each mark fires once per session; a jump over several names the highest. A compaction that shrinks the context does not repeat old marks.Both are information only: what a report means -- checkpoint, retire, nothing -- is the home's rule (CLAUDE.md or its kin), not the watch's.
The watch reads local files only, and it never touches a hub. For mail on a remote hub, such as Lelle's stationmaster reached with evr-mail recv, a poller peeks at the hub and appends one line per new item to a local spool. The home declares that spool as an injecting doorbell:
watch_files:
- label: lelle
path: inbound/lelle-spool.txt
instruction: "collect with recv, then ack BY ID what you read"
inject: true
Each ring carries the new lines, from=… id=… subject=…. The session then collects and acks the mail with its own recv, after recording it. Custody stays with the session: the poller only looks, and the watch only rings. The spool is never consumed; the bookmark advances, from one session to the next too.
Ack only what you read, by id (kit #39). evr-mail recv without --peek acks everything waiting on the hub, not what the peek showed: mail that arrived after the spool line is acked too. framework-research acked two messages unread that way on 2026-10-15; both needed resends. The rule: ack by id the messages you have read and recorded, and nothing else; an ack with no ids acks nothing. Until a home's mail tool acks by id: recv prints every message before it acks it, so read and record everything that run printed, not only the ones the ring named.
spool/spool-poll.py (Python 3, stdlib only) is the poller, generic over the command:
python3 memory-kit/adapters/claude-code/watch/spool/spool-poll.py \
--spool inbound/lelle-spool.txt \
--match '^--- \d+/\d+\s+from=(?P<from>\S+)\s+id=(?P<id>\S+)(?:\nsubject: (?P<subject>.*))?' \
--line 'from={from} id={id} subject={subject}' --healthy '^collected' \
-- python3 tools/evr-mail.py recv --peek
-- must only look (recv --peek), never collect or ack. The poller cannot check that: it is the home's choice of command.--match in the command's output (a Python regex, multiline) is one item, keyed by its named group id. --line writes the spool line from the named groups; an absent group is empty. Without --line, the line is the match itself, on one line. A line never holds a line break..<stem>-seen.json beside the spool (the last 500, --keep). So a peeked but uncollected item is not spooled again, across restarts too.--timeout, 90 s), exits non-zero, or prints nothing matching --healthy. After 3 failures in a row (--tolerate), the spool gets one health: <why> line, then at most one per 30 min (--health-every) while the failures go on, and health: recovered once a run succeeds. Each health line grows the spool, so it rings: a full turn.--every)..<stem>.lock beside the spool and writes its pid there (flock on POSIX, msvcrt on Windows). A second poller finds the lock held, says so and exits 0.--json, kit #39, hr2): give the peek command its JSON form and --json in place of --match; the first JSON value must be a list of objects with an id.--remind N, minutes, off by default; kit #39): an id still in the peek N minutes after first seen gets one waiting: ... line..<stem>.alive; --status prints the poller's state (exit 0 running and fresh); --keep-alive makes sure one poller runs and returns at once -- put it in the home's SessionStart hook (see spool/spool-poll.py --help and the adapters README). --once polls once, for a scheduler.kit_home (kit #18)User-scope options apply to every session on the machine. That covers home set in the user's settings, not only the home's own sessions. Use a pointer conf instead: put this in the folder the session starts in:
kit_home: ../desk # absolute, or relative to this conf's own folder
memory-kit.conf declares the doorbells and sensors, with paths relative to that home. Other keys left in the pointer conf are ignored, and watch_files left there are a visible notice.home option. Then the option, then the start folder itself. The option is normalized as a pointer is (kit #46).memory-kit.conf takes the nearest one above it, as git finds .git, so a session started in a subfolder or a git worktree of a home finds that home; a pointer conf found there is followed as if the session had started in its folder. The walk stops at the filesystem root. /watch says where it looked: "<start> has no memory-kit.conf; using the nearest one above it, in <folder>".session.start, which a shell cd does not move (kit #45): an install or enable mid-session fires session.start with the shell's folder after any cd, which had made a subfolder the home.kit_home: . is just the home.memory-kit.conf, a chained pointer or a ~ path is one visible notice, and the watch rings nothing. It never falls back to the start folder. /watch names the home and the pointer.memory-kit.conf that gives a top-level key twice, the start folder's or the one a pointer names, is the same kind of notice, naming the key and both lines, and the watch rings nothing. It would read the first copy where YAML keeps the last; now neither picks.home option but which started outside that home rings nothing there (one notice); its own session sensors still run.lint/kit_home.py). This plugin's copy of the rules is hooks/kit-home.ts, identical in all three plugins; lint/run-fixtures.sh fails when the copies differ.userConfig)home: the kit home whose memory-kit.conf declares the doorbells and sensors. Empty: the session's start directory. Set user-wide, it applies to every session on the machine: prefer a kit_home pointer conf (above), which also wins over this option.pollSeconds (5, at least 5): the poll interval. It reads local files only.claude plugin configure watch@memory-kit --values-stdin takes a JSON object of strings only, e.g. {"pollSeconds": "5"} (found by mvox, 2026-10-14).retireOnIdle, idleMinutes, growthPercent are gone (watch 0.5.0): a conf setting retireOnIdle gets one notice pointing at watch_idle_minutes and watch_context_percent.Answers with the home (and pointer), each doorbell (label, path, inject, instruction), every problem in the declaration, and the sensor marks.
$.prompt.submit from a timer wakes a session idle at the prompt. This held before any turn and after one (44 s idle). It resolved about 60 ms later, as the turn started. Two submits in a row ran as two turns, in order. The model reads it as "The watch plugin sent a message: …".$.session.usage() while idle gives the last response's input. Before the first response: context.tokens and percent undefined, window 1000000. After a turn: the last response's input tokens, unchanged until the next turn. So the sensors read a stable figure.prompt.submit hook ("re-entry" in the debug log). Activity is therefore taken from prompts, tool calls and turn ends.origin.kind === 'composer'.$.ui.notify in tmux answered no-channel, hence the transcript fallback.$.fs.read returns, compared only with itself, through 32-bit hashes of the text and of its lines. Two different texts with one hash (about one in four billion) would not ring.* path is expanded per poll, so a new matching file is picked up then).It travels with the kit, beside the pane, in the same memory-kit marketplace:
claude plugin install watch@memory-kit
The marketplace entry to add upstream (adapters/claude-code/.claude-plugin/marketplace.json):
{
"name": "watch",
"source": "./watch",
"description": "Rings a doorbell when a home's declared files grow, and reports the session's idleness and context marks. Information only."
}
For one session only: claude --plugin-dir ./memory-kit/adapters/claude-code/watch.
Scope. This installs at user scope: every session on the machine loads the plugin. What it does in a folder that is not a kit home, and the project-scope alternative: Install scope.
claude plugin validate .
claude plugin test . # tests/*.test.ts; files, clock, store and the session are mocked
tsc -p . # once Claude Code has laid .claude-plugin/types/ (gitignored)hooks/register.ts 567 lines1// The watch mod (memory-kit issue #9). Information only, on one timer:
2// 1. doorbells: when a file the home declares (watch_files) grows, ring once -- one
3// $.prompt.submit, which queues until the session is idle and wakes it then. The watch never
4// reads a file's meaning and never empties, moves or archives it; consuming (read, then
5// delete, empty, or write back what is left) is the home's own step, and it is what re-arms
6// the bell;
7// 2. session reports: idleness past watch_idle_minutes and context past each
8// watch_context_percent mark. The watch never says what a ring or report means; that is the
9// home's own rule.
10
11import { atom, read } from 'claude-code'
12import type { EngineInterface, Register } from 'claude-code'
13
14import {
15 bellChange,
16 bellLabel,
17 bellsKey,
18 bookmarkFor,
19 bookmarksOf,
20 combineRings,
21 confContextPercent,
22 confIdleMinutes,
23 confIdleRepeat,
24 confValue,
25 contextReport,
26 expandHome,
27 fileKey,
28 idleReport,
29 isHuman,
30 isInside,
31 lineListOf,
32 marksCrossed,
33 matchSegment,
34 MINUTE,
35 pathSegments,
36 readDoorbells,
37 ringText,
38} from './watch'
39import type { Bookmark, Doorbell } from './watch'
40import { foundAboveNote, normalizePath, resolveKitHome } from './kit-home'
41import type { KitHome } from './kit-home'
42
43const startCwd = atom({ plugin: 'watch', key: 'startCwd' } as const, '')
44/** Context marks already reported this session: once per mark, reloads included. */
45const reportedMarks = atom({ plugin: 'watch', key: 'reportedMarks' } as const, [] as number[])
46/** Each watched file's last-seen size, by expanded path: growth past it rings. A tail-style
47 * file's is also kept in $.store, which a new session, having none of its own, reads (kit #51). */
48const bellSizes = atom({ plugin: 'watch', key: 'bellSizes' } as const, {} as Record<string, number>)
49/** Each watched file's last-seen text hash, by the same key: other text in its place rings (kit #52). */
50const bellHashes = atom({ plugin: 'watch', key: 'bellHashes' } as const, {} as Record<string, number>)
51/** Each watched file's last-seen line hashes, by the same key, with the text hash they belong to:
52 * other text in its place rings only when it adds a line (kit #57). */
53const bellLines = atom({ plugin: 'watch', key: 'bellLines' } as const, {} as Record<string, SeenLines>)
54
55/** The line hashes of one seen text, and that text's hash: lines of another text are never used. */
56type SeenLines = { hash: number; lines: number[] }
57
58type Settings = { home: string; pollMs: number }
59
60const num = (v: unknown, fallback: number) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback)
61
62// Module state: a reload starts it over, which only ever holds a report back (not armed yet).
63/** Armed by a human prompt, disarmed by the one idle report: one report per working stretch,
64 * and the report's own turn can never re-arm it. With watch_idle_repeat (kit #47) a report
65 * leaves it armed, so reports recur while the session stays idle; only a human arms it first. */
66let idleArmed = false
67let lastActivity = 0
68/** Set when register() saw a retired option: told once at session start. */
69let retiredOption: string | undefined
70let polling = false
71const logged = new Set<string>()
72/** The tail-style rings of this session whose prompt has not yet entered or been refused, by
73 * the files each carries: the kept bookmark of such a file waits for its ring (kit #51). A
74 * reload forgets them, so a ring queued across a reload and then lost with its session is not
75 * rung again. */
76const inFlight = new Set<readonly string[]>()
77
78/** One debug line per distinct message for the module's life: a poll every 5 s must not spam. */
79function logOnce($: EngineInterface, text: string): void {
80 if (logged.has(text)) return
81 logged.add(text)
82 $.ui.log(`watch: ${text}`, { to: 'debug' })
83}
84
85async function readOrEmpty($: EngineInterface, path: string): Promise<string> {
86 try {
87 return (await $.fs.exists(path)) ? await $.fs.read(path) : ''
88 } catch {
89 return ''
90 }
91}
92
93/** A file's text, undefined when it is missing or unreadable. */
94async function readMaybe($: EngineInterface, path: string): Promise<string | undefined> {
95 try {
96 return (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
97 } catch {
98 return undefined
99 }
100}
101
102/**
103 * The kit home (kit #18). The start folder's memory-kit.conf decides first: a `kit_home:` pointer
104 * names the home, one hop; a start folder without a conf takes the nearest one above it (kit
105 * #42). A home so found wins over the user-scope `home` option, which applies to every session on
106 * the machine. Otherwise the option, else the start folder. The start folder is the first
107 * session.start's; without one (a plugin installed mid-session, kit #45) the session's root,
108 * which a shell cd does not move. The option is normalized as the pointer is (kit #46).
109 */
110async function homeOf($: EngineInterface, settings: Settings): Promise<Placed> {
111 const start = (await read($, startCwd)) || (await $.session.root())
112 const found = await resolveKitHome(start, p => readMaybe($, p))
113 if ('problem' in found || found.pointer !== undefined || found.foundIn !== undefined || settings.home === '')
114 return { found, start, viaOption: false }
115 return { found: { home: normalizePath(expandHome(settings.home, start, '') ?? start), ignored: [] }, start, viaOption: true }
116}
117
118/** The folder the session started in: its root, which a shell cd does not move (kit #45); `cwd` if the engine gives none. */
119async function startFolder($: EngineInterface, cwd: string): Promise<string> {
120 try {
121 return (await $.session.root()) || cwd
122 } catch {
123 return cwd
124 }
125}
126
127/** The kit home as found, the folder the session started in, and whether the home came from the `home` option. */
128type Placed = { found: KitHome; start: string; viaOption: boolean }
129
130/** A usable home: where it is, where the session started, and whether the `home` option named it. */
131type Home = { home: string; start: string; viaOption: boolean }
132
133/** The home, or one visible notice when the pointer is broken; also when it leaves watch_files behind. */
134async function usableHome($: EngineInterface, settings: Settings): Promise<Home | undefined> {
135 const { found, start, viaOption } = await homeOf($, settings)
136 if ('problem' in found) {
137 await tellOnce($, `${found.problem}. The watch rings nothing until it is fixed.`)
138 return undefined
139 }
140 if (found.pointer !== undefined && found.ignored.includes('watch_files'))
141 await tellOnce($, `watch_files in ${found.pointer} are ignored: that conf points at the home (kit_home), and they count in ${found.home}/memory-kit.conf.`)
142 return { home: found.home, start, viaOption }
143}
144
145/** The files a path names; `*` in a segment matches the directory's entries (never dotfiles). */
146async function expand($: EngineInterface, path: string): Promise<string[]> {
147 if (!path.includes('*')) return [path]
148 const segments = pathSegments(path)
149 let bases = [segments[0] ?? '']
150 for (const segment of segments.slice(1)) {
151 const next: string[] = []
152 for (const base of bases) {
153 if (!segment.includes('*')) {
154 next.push(`${base}/${segment}`)
155 continue
156 }
157 try {
158 // '' is the POSIX root; a bare drive ('C:') is that drive's root, not its current directory.
159 const dir = base === '' ? '/' : /^[A-Za-z]:$/.test(base) ? `${base}/` : base
160 for (const entry of await $.fs.list(dir)) if (matchSegment(segment, entry.name)) next.push(`${base}/${entry.name}`)
161 } catch {
162 // A directory that is not there matches nothing.
163 }
164 }
165 bases = next.sort()
166 }
167 return bases
168}
169
170/**
171 * One prompt, fire and forget (its submit resolves only when its turn starts, which a poll must
172 * not wait for). A refusal runs `undo`, so a lost ring's baseline rolls back and the growth
173 * rings again at a later poll; a prompt that enters runs `entered`. A prompt that never resolves
174 * (its session ended first) runs neither.
175 */
176function ask($: EngineInterface, text: string, undo?: () => Promise<void>, entered?: () => Promise<void>): void {
177 void $.prompt
178 .submit({ text })
179 .then(
180 r => {
181 if (r.drop !== undefined) {
182 logOnce($, `prompt refused: ${r.drop}`)
183 return undo?.()
184 }
185 return entered?.()
186 },
187 err => {
188 logOnce($, `prompt refused: ${String(err)}`)
189 return undo?.()
190 },
191 )
192 // Run past its session, undo or entered may find their calls refused.
193 .catch(err => logOnce($, `after a ring: ${String(err)}`))
194}
195
196/**
197 * The last-seen sizes, validated out of $.state, keyed by fileKey (kit #46). A key an older watch
198 * stored under another spelling folds into its file's key, so an upgrade rings nothing again.
199 */
200async function sizesOf($: EngineInterface): Promise<Record<string, number>> {
201 const raw = await read($, bellSizes)
202 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {}
203 const sizes: Record<string, number> = {}
204 for (const [file, size] of Object.entries(raw)) {
205 if (typeof size !== 'number') continue
206 const key = fileKey(file)
207 sizes[key] = Math.max(sizes[key] ?? 0, size)
208 }
209 return sizes
210}
211
212/** The last-seen text hashes, validated out of $.state; a file with none is judged by size alone. */
213async function hashesOf($: EngineInterface): Promise<Record<string, number>> {
214 const raw = await read($, bellHashes)
215 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {}
216 const hashes: Record<string, number> = {}
217 for (const [key, hash] of Object.entries(raw)) if (typeof hash === 'number') hashes[key] = hash
218 return hashes
219}
220
221/**
222 * The last-seen line hashes, validated out of $.state (kit #57). A file with none, as an older
223 * watch kept it, rings any other text as a replacement, as in watch 0.7.0.
224 */
225async function linesOf($: EngineInterface): Promise<Record<string, SeenLines>> {
226 const raw = await read($, bellLines)
227 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {}
228 const seen: Record<string, SeenLines> = {}
229 for (const [key, entry] of Object.entries(raw)) {
230 const { hash, lines } = (typeof entry === 'object' && entry !== null ? entry : {}) as { hash?: unknown; lines?: unknown }
231 const list = lineListOf(lines)
232 if (typeof hash === 'number' && list !== undefined) seen[key] = { hash, lines: list }
233 }
234 return seen
235}
236
237/**
238 * The kept bookmarks of the home's tail-style bells (kit #51), out of $.store, which outlives the
239 * session: a new session, or one after /clear, rings only what no ring has brought in. Undefined
240 * when the store cannot be read; a session with no bookmark of its own then counts from 0, as
241 * before.
242 */
243async function keptOf($: EngineInterface, home: string): Promise<Record<string, Bookmark> | undefined> {
244 try {
245 return bookmarksOf(await $.store.get(bellsKey(home)))
246 } catch (err) {
247 logOnce($, `tail-style bookmarks last this session only: the store cannot be read (${String(err)})`)
248 return undefined
249 }
250}
251
252async function keep($: EngineInterface, home: string, kept: Record<string, Bookmark>): Promise<void> {
253 try {
254 await $.store.set(bellsKey(home), kept)
255 } catch (err) {
256 logOnce($, `tail-style bookmarks stay as last kept: the store cannot be written (${String(err)})`)
257 }
258}
259
260/**
261 * The doorbells: every declared file that grew past its last-seen text, or whose text was
262 * replaced by other non-empty text (kit #52) with a line the last-seen text did not have (kit
263 * #57), rings; all of one poll's rings as one prompt. Sizes are character counts of what $.fs.read
264 * returns -- compared only with themselves. A missing file counts 0, so delete-then-write rings and
265 * create-at-0 does not. A bookmark is a size, a hash and, up to LINES_CAP, the line hashes; both
266 * homes below keep all three, and a rollback restores all three.
267 *
268 * $.state, the session's own, keeps every bookmark and is read first. A tail-style bell (inject:
269 * true) is never consumed, so its bookmark is also kept in $.store, per home, which a session with
270 * no bookmark of its own reads (kit #51). The kept one moves only past what reached a turn: when
271 * a ring's prompt enters, and at a poll that rings nothing of the file with no ring of it queued
272 * (it was emptied, an older watch kept it in $.state alone, or a store write failed before). So a
273 * ring still queued when its session ends rings again in the next. An inbox-style bell keeps only
274 * the session's: an unconsumed inbox rings once in a new session.
275 */
276async function doorbellCheck($: EngineInterface, home: string, conf: string): Promise<void> {
277 const confPath = `${home}/memory-kit.conf`
278 if (/^watch_sources:/m.test(conf))
279 await tellOnce($, `watch_sources in ${confPath} is gone (watch 0.5.0): declare watch_files entries (label, path, instruction, inject); consuming a file is the home's own step.`)
280 const d = readDoorbells(conf)
281 for (const p of d.problems) await tellOnce($, `watch_files in ${confPath}: ${p}`)
282 if (d.bells.length === 0) return
283
284 const userHome = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
285 const sizes = await sizesOf($)
286 const hashes = await hashesOf($)
287 const lines = await linesOf($)
288 const kept = d.bells.some(b => b.inject) ? await keptOf($, home) : undefined
289 const queued = new Set([...inFlight].flat())
290 const rung: { bell: Doorbell; file: string; key: string; old: number; oldHash?: number; oldLines?: number[]; content: string; replaced: boolean }[] = []
291 const seen = new Set<string>()
292 let changed = false
293 let keptChanged = false
294 for (const bell of d.bells) {
295 const path = expandHome(bell.path, home, userHome)
296 if (path === undefined) {
297 await tellOnce($, `watch_files in ${confPath}: skipped "${bell.path}": no HOME or USERPROFILE for ~`)
298 continue
299 }
300 for (const file of await expand($, path)) {
301 const key = fileKey(file)
302 // A file two entries name is one bell, the first entry's: one bookmark, one ring (kit #46).
303 if (seen.has(key)) continue
304 seen.add(key)
305 const content = await readOrEmpty($, file)
306 const own = sizes[key]
307 const mark = bell.inject ? kept?.[key] : undefined
308 const old = own ?? mark?.size ?? 0
309 const oldHash = own !== undefined ? hashes[key] : mark?.hash
310 const ownLines = lines[key]?.hash === hashes[key] ? lines[key]?.lines : undefined
311 const oldLines = own !== undefined ? ownLines : mark?.lines
312 const change = bellChange(content, old, oldHash, oldLines)
313 if (change !== undefined) rung.push({ bell, file, key, old, oldHash, oldLines, content, replaced: change === 'replaced' })
314 // A bookmark that lags the text just seen moves to it. One an older watch kept takes its
315 // lines here while the text is still the one it saw (kit #57); only a replacement made
316 // before this watch's first look rings as in 0.7.0.
317 const now = bookmarkFor(content)
318 const lags = (size: number | undefined, hash: number | undefined, seenLines: number[] | undefined) =>
319 size !== now.size || hash !== now.hash || (seenLines === undefined) !== (now.lines === undefined)
320 if (lags(sizes[key], hashes[key], ownLines)) {
321 sizes[key] = now.size
322 hashes[key] = now.hash
323 if (now.lines === undefined) delete lines[key]
324 else lines[key] = { hash: now.hash, lines: now.lines }
325 changed = true
326 }
327 if (bell.inject && kept !== undefined && change === undefined && !queued.has(key) && lags(mark?.size, mark?.hash, mark?.lines)) {
328 kept[key] = now
329 keptChanged = true
330 }
331 }
332 }
333 if (changed) {
334 await $.state.set({ plugin: 'watch', key: 'bellSizes' }, sizes)
335 await $.state.set({ plugin: 'watch', key: 'bellHashes' }, hashes)
336 await $.state.set({ plugin: 'watch', key: 'bellLines' }, lines)
337 }
338 if (kept !== undefined && keptChanged) await keep($, home, kept)
339 if (rung.length === 0) return
340 $.ui.log(`watch: ring (${rung.map(g => bellLabel(g.bell, g.file)).join(', ')})`, { to: 'debug' })
341 const tails = rung.filter(g => g.bell.inject)
342 const carried = tails.map(g => g.key)
343 if (carried.length > 0) inFlight.add(carried)
344 ask(
345 $,
346 combineRings(rung.map(g => ringText(g.bell, g.file, g.old, g.content, g.replaced))),
347 async () => {
348 // Back to the bookmark before the ring, size, hash and lines together (kit #57), so the
349 // next poll rings again. The kept one never moved for it. Still queued until rolled back: a
350 // poll between must not move the kept one past it.
351 try {
352 const nowSizes = await sizesOf($)
353 const nowHashes = await hashesOf($)
354 const nowLines = await linesOf($)
355 for (const g of rung) {
356 nowSizes[g.key] = g.old
357 if (g.oldHash === undefined) delete nowHashes[g.key]
358 else nowHashes[g.key] = g.oldHash
359 if (g.oldHash === undefined || g.oldLines === undefined) delete nowLines[g.key]
360 else nowLines[g.key] = { hash: g.oldHash, lines: g.oldLines }
361 }
362 await $.state.set({ plugin: 'watch', key: 'bellSizes' }, nowSizes)
363 await $.state.set({ plugin: 'watch', key: 'bellHashes' }, nowHashes)
364 await $.state.set({ plugin: 'watch', key: 'bellLines' }, nowLines)
365 } finally {
366 inFlight.delete(carried)
367 }
368 },
369 async () => {
370 // The ring reached a turn: the kept bookmarks move past what it carried (kit #51).
371 try {
372 if (tails.length === 0) return
373 const nowKept = await keptOf($, home)
374 if (nowKept === undefined) return
375 for (const g of tails) nowKept[g.key] = bookmarkFor(g.content)
376 await keep($, home, nowKept)
377 } finally {
378 inFlight.delete(carried)
379 }
380 },
381 )
382}
383
384/**
385 * The session reports, both information only. A conf line that cannot be read is said once, never
386 * a silent off. Each context mark reports once per session; the idle report fires once per
387 * working stretch (armed by a human prompt, disarmed by the report itself).
388 */
389async function reportCheck($: EngineInterface, conf: string): Promise<void> {
390 const idle = confIdleMinutes(conf)
391 if (idle.problem !== undefined) logOnce($, `watch_idle_minutes: ${idle.problem}`)
392 const repeat = confIdleRepeat(conf)
393 if (repeat.problem !== undefined) logOnce($, `watch_idle_repeat: ${repeat.problem}`)
394 if (repeat.on && !idle.declared) logOnce($, 'watch_idle_repeat: true does nothing without watch_idle_minutes')
395 const marks = confContextPercent(conf)
396 if (marks.problem !== undefined) logOnce($, `watch_context_percent: ${marks.problem}`)
397 if (idle.values.length === 0 && marks.values.length === 0) return
398
399 const now = await $.clock.now()
400 const { context } = await $.session.usage()
401
402 const idleMinutes = idle.values[0]
403 if (idleMinutes !== undefined && idleArmed && now - lastActivity >= idleMinutes * MINUTE) {
404 idleArmed = repeat.on
405 const minutes = Math.round((now - lastActivity) / MINUTE)
406 // The next report waits a full interval from this one, even if this one's turn never starts
407 // (a refused prompt): a repeating report must not fire at every poll.
408 lastActivity = now
409 $.ui.log(`watch: idle report (${minutes} min${repeat.on ? ', repeating' : ''})`, { to: 'debug' })
410 ask($, idleReport(minutes, confValue(conf, 'watch_retire_step'), repeat.on))
411 }
412
413 if (marks.values.length > 0 && context.tokens !== undefined) {
414 const done = await read($, reportedMarks)
415 const reported = Array.isArray(done) ? done.filter((m): m is number => typeof m === 'number') : []
416 const crossed = marksCrossed(marks.values, reported, context.tokens, context.window)
417 if (crossed.length > 0) {
418 await $.state.set({ plugin: 'watch', key: 'reportedMarks' }, [...reported, ...crossed])
419 const top = crossed[crossed.length - 1]
420 if (top !== undefined) {
421 $.ui.log(`watch: context report (${crossed.join('%, ')}% crossed)`, { to: 'debug' })
422 ask($, contextReport(top, context.tokens, context.window))
423 }
424 }
425 }
426}
427
428/**
429 * One notice to the human. A terminal without a notification channel (tmux, live check
430 * 2026-10-14: `no-channel`) or with a bare bell shows no text, so the text also goes to the
431 * transcript as a dim line.
432 */
433async function tell($: EngineInterface, text: string): Promise<void> {
434 let shown = false
435 try {
436 const sent = await $.ui.notify(text, { title: 'watch' })
437 shown = sent.isSent && sent.channel !== 'terminal_bell'
438 } catch {
439 // Refused: the transcript line below carries it.
440 }
441 // The engine already heads a plugin's transcript line with its name (seen live).
442 if (!shown) $.ui.log(text)
443}
444
445const told = new Set<string>()
446
447/** tell, once per distinct text for the module's life. */
448async function tellOnce($: EngineInterface, text: string): Promise<void> {
449 if (told.has(text)) return
450 told.add(text)
451 await tell($, text)
452}
453
454/** What /watch answers: the doorbells active now, what was skipped and why, the session sensors. */
455async function status($: EngineInterface, settings: Settings): Promise<string> {
456 const { found, start, viaOption } = await homeOf($, settings)
457 if ('problem' in found) return `${found.problem}.\nThe watch rings nothing until it is fixed.`
458 const home = found.home
459 const conf = await readOrEmpty($, `${home}/memory-kit.conf`)
460 const confPath = `${home}/memory-kit.conf`
461 const d = readDoorbells(conf)
462 const lines: string[] = [`home: ${home}${found.pointer !== undefined ? ` (kit_home in ${found.pointer})` : ''}`]
463 if (found.foundIn !== undefined) lines.push(foundAboveNote(start, found.foundIn))
464 if (!d.declared) lines.push(`no watch_files in ${confPath}; no doorbells.`)
465 else {
466 const n = d.bells.length
467 lines.push(`${n} doorbell${n === 1 ? '' : 's'}, from ${confPath}`)
468 for (const b of d.bells)
469 lines.push(` [${b.label === '' ? `(${b.path.split(/[\\/]/).pop()})` : b.label}] ${b.path}${b.inject ? ' inject' : ''}${b.instruction === '' ? '' : ` "${b.instruction}"`}`)
470 for (const p of d.problems) lines.push(` problem: ${p}`)
471 if (viaOption && !isInside(start, home)) lines.push(`ringing here: no; this session started outside the home (${start})`)
472 }
473 const idle = confIdleMinutes(conf)
474 const marks = confContextPercent(conf)
475 const repeat = confIdleRepeat(conf)
476 const again = repeat.problem !== undefined ? ` (watch_idle_repeat unreadable: ${repeat.problem})` : repeat.on ? ', repeating' : ''
477 const idleSay = idle.problem !== undefined ? `unreadable (${idle.problem})` : idle.values[0] !== undefined ? `report at ${idle.values[0]} min${again}` : 'off'
478 const markSay = marks.problem !== undefined ? `unreadable (${marks.problem})` : marks.values.length > 0 ? `report at ${marks.values.join(', ')}% of the window` : 'off'
479 lines.push(`idle: ${idleSay}; context: ${markSay}; poll every ${settings.pollMs / 1000} s`)
480 return lines.join('\n')
481}
482
483async function tick($: EngineInterface, settings: Settings): Promise<void> {
484 if (polling) return
485 polling = true
486 try {
487 const at = await usableHome($, settings)
488 if (at === undefined) return
489 const conf = await readOrEmpty($, `${at.home}/memory-kit.conf`)
490 // The `home` option applies to every session on the machine; a session started outside that
491 // home stays silent there (the session sensors are this session's own and still run).
492 if (at.viaOption && !isInside(at.start, at.home)) {
493 if (readDoorbells(conf).declared)
494 await tellOnce(
495 $,
496 `This session started in ${at.start}, outside the watch's home ${at.home} (the home option), so it rings nothing here. To watch the home from another folder, put "kit_home: ${at.home}" in that folder's memory-kit.conf.`,
497 )
498 } else await doorbellCheck($, at.home, conf)
499 await reportCheck($, conf)
500 } catch (err) {
501 logOnce($, `poll failed: ${String(err)}`)
502 } finally {
503 polling = false
504 }
505}
506
507async function markActivity($: EngineInterface): Promise<void> {
508 lastActivity = await $.clock.now()
509}
510
511export const register: Register = (on, options) => {
512 const settings: Settings = {
513 home: typeof options.home === 'string' ? options.home.trim() : '',
514 pollMs: Math.max(5, num(options.pollSeconds, 5)) * 1_000,
515 }
516 // The retire options moved into memory-kit.conf (watch 0.5.0): say so, never silently.
517 if (options.retireOnIdle === true) {
518 retiredOption = 'the retireOnIdle option is gone: declare watch_idle_minutes and watch_context_percent in memory-kit.conf (watch 0.5.0, information-only reports)'
519 }
520 let timer: { cancel: () => void } | undefined
521
522 on('session.start', async ($, e, next) => {
523 const started = await next(e)
524 // The first start only (a reload fires it again, by then maybe after a cd). That first start
525 // may be an install or enable mid-session, whose e.cwd is the shell's folder after any cd:
526 // the session's root is not moved by a cd (kit #45).
527 if ((await read($, startCwd)) === '') await $.state.set({ plugin: 'watch', key: 'startCwd' }, await startFolder($, e.cwd))
528 if (retiredOption !== undefined) await tellOnce($, retiredOption)
529 await markActivity($)
530 await $.command.register({ name: 'watch', description: 'Show the doorbells and session reports active in this home' })
531 // A new session (a /clear) has no ring of its own queued yet; one of the last session's that
532 // still enters moves the kept bookmark then (kit #51).
533 inFlight.clear()
534 timer?.cancel()
535 timer = $.clock.every(settings.pollMs, () => void tick($, settings))
536 // Not awaited: a ring waits for its turn to start, which a start hook must not hold up.
537 void tick($, settings)
538 return started
539 })
540
541 on('command.run', { command: 'watch' }, async $ => ({ text: await status($, settings) }))
542
543 // Activity, for the idle clock. Observers: a failure here never touches the prompt or the call.
544 on('prompt.submit', async ($, e, next) => {
545 try {
546 await markActivity($)
547 // Only the human arms the idle report: the watch's own rings and reports never do,
548 // so one working stretch gets one report, not one every idle interval.
549 if (isHuman(e.origin)) idleArmed = true
550 } catch {
551 // The idle clock is not worth a lost prompt.
552 }
553 return next(e)
554 }).catch(($, e, next) => next(e))
555
556 on('turn.complete', async ($, e, next) => {
557 const done = await next(e)
558 await markActivity($)
559 return done
560 }).catch(($, e, next) => next(e))
561
562 on('tool.call', async ($, e, next) => {
563 await markActivity($)
564 return next(e)
565 }).catch(($, e, next) => next(e))
566}
567hooks/watch.ts 394 lines1// Pure logic of the watch mod: no `$`, no I/O. Everything here is unit-tested.
2//
3// The watch is information only (kit #9, reshaped 2026-10-16). It rings doorbells on files the
4// home declares and reports the session's idleness and context growth; what any ring or report
5// means is the home's own rule. Declared per kit home in memory-kit.conf:
6//
7// watch_files:
8// - label: ""
9// path: comms/inboxes/team-lead.json
10// instruction: "consume the inbox or new messages won't land"
11// inject: false
12// watch_idle_minutes: 50
13// watch_context_percent: 50, 60, 70, 80
14
15import type { PromptOrigin } from 'claude-code'
16
17// ---------------------------------------------------------------------------------------------
18// The conf.
19
20/** Strips a trailing ` # comment` and one pair of enclosing quotes. */
21function unquote(raw: string): string {
22 const text = raw.trim()
23 const quoted = /^(["'])(.*)\1(\s+#.*)?$/.exec(text)
24 if (quoted) return quoted[2] ?? ''
25 const hash = text.search(/(^|\s)#/)
26 return (hash === -1 ? text : text.slice(0, hash)).trim()
27}
28
29/** A top-level `key: value` of memory-kit.conf, unquoted; undefined when absent or empty. */
30export function confValue(conf: string, key: string): string | undefined {
31 for (const raw of conf.split(/\r?\n/)) {
32 if (!raw.startsWith(`${key}:`)) continue
33 const v = unquote(raw.slice(key.length + 1))
34 return v === '' ? undefined : v
35 }
36 return undefined
37}
38
39// ---------------------------------------------------------------------------------------------
40// Doorbells. A doorbell is a labeled file: when the file GROWS, or other text with a line the old
41// text did not have REPLACES its text (kit #52, #57), the watch rings once -- one prompt at the
42// next turn seam. The watch never reads a file's meaning, never empties, moves or archives it;
43// consuming (read, then delete, empty, or write back what is left) is the home's own step, and it
44// is what re-arms the bell. Created at 0 bytes, emptied, rewritten with none but lines it already
45// had, or the same text again only moves the bookmark.
46
47/** One declared doorbell. Every field is always present in the conf; empty means its default. */
48export type Doorbell = {
49 /** The ring's label; '' means the file's name. */
50 label: string
51 path: string
52 /** Home-authored text the ring carries verbatim; '' means just the bell. */
53 instruction: string
54 /** Ring with the grown tail's lines included (for short, line-shaped files), not just the bell. */
55 inject: boolean
56}
57
58export const DOORBELL_KEYS = ['label', 'path', 'instruction', 'inject'] as const
59
60/**
61 * What `watch_files:` declares: a block list of entries, each a map of the four keys
62 * (`- label: ...` then indented `path:`, `instruction:`, `inject:`). `declared` is whether the
63 * key is there; every entry that cannot be used is a problem said out loud, never silently off.
64 * An explicit empty list is a home ringing nothing on purpose.
65 */
66export type DoorbellList = { declared: boolean; bells: Doorbell[]; problems: string[] }
67
68export function readDoorbells(conf: string): DoorbellList {
69 const lines = conf.split(/\r?\n/)
70 const at = lines.findIndex(l => /^watch_files:/.test(l))
71 if (at === -1) return { declared: false, bells: [], problems: [] }
72 const rest = (lines[at] ?? '').slice('watch_files:'.length).trim()
73 if (rest !== '' && !rest.startsWith('#'))
74 return { declared: true, bells: [], problems: ['expected a block list of entries ("- label: ..." lines), not an inline value'] }
75
76 const bells: Doorbell[] = []
77 const problems: string[] = []
78 let entry: Partial<Record<(typeof DOORBELL_KEYS)[number], string>> | undefined
79 let entryBad = false
80 const close = () => {
81 if (entry !== undefined && !entryBad) {
82 const n = bells.length + problems.length + 1
83 if (entry.path === undefined || entry.path === '') problems.push(`entry ${n}: no path`)
84 else if (entry.inject !== undefined && entry.inject !== '' && entry.inject !== 'true' && entry.inject !== 'false')
85 problems.push(`entry ${n}: inject must be true or false, not "${entry.inject}"`)
86 else bells.push({ label: entry.label ?? '', path: entry.path, instruction: entry.instruction ?? '', inject: entry.inject === 'true' })
87 }
88 entry = undefined
89 entryBad = false
90 }
91 for (const raw of lines.slice(at + 1)) {
92 if (/^\s*(#.*)?$/.test(raw)) continue
93 // Entries may sit at column 0 under the key, as yaml.safe_dump writes them; any other
94 // column-0 line that is not a list item is the next conf key.
95 if (!/^\s/.test(raw) && !/^-(\s|$)/.test(raw)) break
96 const item = /^\s*-\s+(.*)$/.exec(raw)
97 const field = /^\s*([A-Za-z_]+):(.*)$/.exec(item?.[1] ?? raw.trim())
98 if (item) close()
99 if (!field) {
100 if (!entryBad) problems.push(`not a "key: value" line: ${raw.trim()}`)
101 entryBad = true
102 if (item) entry = {}
103 continue
104 }
105 if (entry === undefined && !item) {
106 problems.push(`a field outside any entry (missing "- "?): ${raw.trim()}`)
107 continue
108 }
109 if (item) entry = {}
110 const key = field[1] ?? ''
111 if (!(DOORBELL_KEYS as readonly string[]).includes(key)) {
112 problems.push(`unknown field "${key}" (label, path, instruction, inject)`)
113 entryBad = true
114 continue
115 }
116 if (entry !== undefined && entry[key as (typeof DOORBELL_KEYS)[number]] !== undefined) {
117 problems.push(`field "${key}" given twice in one entry`)
118 entryBad = true
119 continue
120 }
121 if (entry !== undefined) entry[key as (typeof DOORBELL_KEYS)[number]] = unquote(field[2] ?? '')
122 }
123 close()
124 if (bells.length === 0 && problems.length === 0) problems.push('no entries under it')
125 return { declared: true, bells, problems }
126}
127
128const baseOf = (path: string) => path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1)
129
130/** A doorbell's effective label: its own, else the file's name. */
131export function bellLabel(bell: Doorbell, file: string): string {
132 return bell.label !== '' ? bell.label : baseOf(file)
133}
134
135/** A text's 32-bit FNV-1a hash: the bookmark keeps it, never the text. */
136export function textHash(text: string): number {
137 let h = 0x811c9dc5
138 for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
139 return h >>> 0
140}
141
142/**
143 * The largest seen text, in characters (64 KiB of plain ASCII), whose lines a bookmark keeps (kit
144 * #57): room for a busy inbox, while a bookmark stays a list of a few thousand numbers. A bigger
145 * file's bookmark keeps no lines, and any other text in its place rings, as in watch 0.7.0.
146 */
147export const LINES_CAP = 64 * 1024
148
149/**
150 * The hashes of a text's lines, each once, sorted (kit #57). A line is compared trimmed and
151 * without a trailing comma; a line of only brackets, braces, commas or whitespace is not one. So a
152 * JSON array rewritten with fewer entries, or with another indent, has no line the old text did
153 * not have.
154 */
155export function lineHashes(text: string): number[] {
156 const hashes = new Set<number>()
157 for (const raw of text.split('\n')) {
158 if (/^[\s[\]{},]*$/.test(raw)) continue
159 hashes.add(textHash(raw.trim().replace(/,$/, '').trim()))
160 }
161 return [...hashes].sort((a, b) => a - b)
162}
163
164/** A list of line hashes out of a bookmark kept before, or undefined when it is not one. */
165export function lineListOf(raw: unknown): number[] | undefined {
166 return Array.isArray(raw) && raw.every(n => typeof n === 'number') ? (raw as number[]) : undefined
167}
168
169/**
170 * What a watched file did since its bookmark (kit #52): `grew` past the seen text, or was
171 * `replaced` by other non-empty text -- consumed and refilled between two polls, whatever the new
172 * size. Empty, or the seen text again, is nothing. Without a hash (a fresh bookmark, or one an
173 * older watch kept) growth is by size alone.
174 *
175 * With the seen text's lines (kit #57), a replacement rings only when it adds a line the seen text
176 * did not have: a consumer that writes back what it leaves (`[]`, or the entries it does not take,
177 * re-indented) adds nothing. Without them (past LINES_CAP, or an older watch's bookmark) any other
178 * text is a replacement, as in watch 0.7.0.
179 */
180export function bellChange(content: string, oldSize: number, oldHash: number | undefined, oldLines?: readonly number[]): 'grew' | 'replaced' | undefined {
181 if (content === '') return undefined
182 if (oldHash === undefined) return content.length > oldSize ? 'grew' : undefined
183 if (content.length > oldSize && textHash(content.slice(0, oldSize)) === oldHash) return 'grew'
184 if (textHash(content) === oldHash) return undefined
185 if (oldLines === undefined) return 'replaced'
186 const seen = new Set(oldLines)
187 return lineHashes(content).some(h => !seen.has(h)) ? 'replaced' : undefined
188}
189
190/**
191 * A file's bookmark: its last-seen size and, when known, the hash of its text and the hashes of
192 * its lines (kit #57; none past LINES_CAP, or from an older watch).
193 */
194export type Bookmark = { size: number; hash?: number; lines?: number[] }
195
196/** The bookmark of a text just seen: its size, its hash, and its lines up to LINES_CAP. */
197export function bookmarkFor(content: string): Bookmark & { hash: number } {
198 const mark: Bookmark & { hash: number } = { size: content.length, hash: textHash(content) }
199 if (content.length <= LINES_CAP) mark.lines = lineHashes(content)
200 return mark
201}
202
203/**
204 * The $.store key of a home's kept bookmarks (kit #51): a tail-style bell is never consumed, so
205 * its bookmark must outlive the session. One per home, however its path is spelled.
206 */
207export function bellsKey(home: string): string {
208 return `bells:${fileKey(home)}`
209}
210
211/**
212 * Kept bookmarks, validated out of the store: a size, with its hash when there is one, and beside
213 * the hash its lines when they are a list of numbers (kit #57).
214 */
215export function bookmarksOf(stored: unknown): Record<string, Bookmark> {
216 if (typeof stored !== 'object' || stored === null || Array.isArray(stored)) return {}
217 const marks: Record<string, Bookmark> = {}
218 for (const [key, raw] of Object.entries(stored)) {
219 const { size, hash, lines } = (typeof raw === 'object' && raw !== null ? raw : {}) as { size?: unknown; hash?: unknown; lines?: unknown }
220 if (typeof size !== 'number') continue
221 if (typeof hash !== 'number') {
222 marks[key] = { size }
223 continue
224 }
225 const list = lineListOf(lines)
226 marks[key] = list === undefined ? { size, hash } : { size, hash, lines: list }
227 }
228 return marks
229}
230
231/**
232 * One ring. Information plus the home's own instruction; with `inject`, the grown tail's
233 * non-blank lines ride along (meant for short, line-shaped files: the harness cuts long lines).
234 * A replaced file's whole text is new, so all of it rides along.
235 */
236export function ringText(bell: Doorbell, file: string, oldSize: number, content: string, replaced = false): string {
237 const head = `[${bellLabel(bell, file)}] ${file} ${replaced ? 'was replaced' : 'grew'}.${bell.instruction === '' ? '' : ` ${bell.instruction}`}`
238 if (!bell.inject) return head
239 const tail = content
240 .slice(replaced ? 0 : oldSize)
241 .split(/\r?\n/)
242 .map(l => l.trimEnd())
243 .filter(l => l.trim() !== '')
244 return [head, ...tail].join('\n')
245}
246
247/** One prompt for one poll's rings: every delivered prompt is a full-context turn. */
248export function combineRings(rings: readonly string[]): string {
249 if (rings.length === 1) return rings[0] ?? ''
250 return [`[watch] ${rings.length} doorbells:`, ...rings].join('\n')
251}
252
253// ---------------------------------------------------------------------------------------------
254// Paths.
255
256const ABSOLUTE = /^(\/|[A-Za-z]:[\\/]|\\\\)/
257
258/** `~/` from the user's home, a relative path from the kit home; undefined when `~` has no home. */
259export function expandHome(path: string, kitHome: string, userHome: string): string | undefined {
260 if (path === '~' || path.startsWith('~/')) return userHome === '' ? undefined : `${userHome}${path.slice(1)}`
261 return ABSOLUTE.test(path) ? path : `${kitHome}/${path}`
262}
263
264/** One path segment against a pattern with `*` wildcards. A dotfile never matches a wildcard. */
265export function matchSegment(pattern: string, name: string): boolean {
266 if (!pattern.includes('*')) return pattern === name
267 if (name.startsWith('.') && !pattern.startsWith('.')) return false
268 const re = new RegExp(`^${pattern.split('*').map(p => p.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`)
269 return re.test(name)
270}
271
272/** A path's segments for glob expansion, on either separator; a leading '' is the POSIX root. */
273export function pathSegments(path: string): string[] {
274 return path.split(/[\\/]/)
275}
276
277/** A path with `\\` as `/`, `.` and `..` resolved, no trailing slash: for comparing, never for opening. */
278export function normalPath(path: string): string {
279 const out: string[] = []
280 const parts = path.replaceAll('\\', '/').split('/')
281 for (const [i, part] of parts.entries()) {
282 if (part === '.' || (part === '' && i > 0)) continue
283 if (part === '..' && out.length > 1) out.pop()
284 else if (part !== '..') out.push(part)
285 }
286 return out.length === 1 && out[0] === '' ? '/' : out.join('/')
287}
288
289/** A drive-letter or UNC path is Windows (for case folding); anything else is not. */
290export function isWindowsPath(path: string): boolean {
291 return /^([A-Za-z]:[\\/]|\\\\)/.test(path)
292}
293
294/**
295 * The key a file's bookkeeping goes by (kit #46): one per file however its path is spelled --
296 * separators and `.`/`..` normalized, a Windows path (drive or UNC, either slash) case-folded.
297 * Two spellings of one spool once kept two bookmarks, and each new line rang twice.
298 */
299export function fileKey(path: string): string {
300 const key = normalPath(path)
301 return isWindowsPath(path.replaceAll('/', '\\')) ? key.toLowerCase() : key
302}
303
304/** Whether `dir` is `home` or lies inside it. A Windows path folds case. Symlinks are not followed. */
305export function isInside(dir: string, home: string): boolean {
306 const fold = (p: string) => (isWindowsPath(p) ? p.toLowerCase() : p)
307 const d = fold(normalPath(dir))
308 const h = fold(normalPath(home))
309 return d === h || d.startsWith(h.endsWith('/') ? h : `${h}/`)
310}
311
312// ---------------------------------------------------------------------------------------------
313// Prompts.
314
315/** A prompt the human gave: typed, through Remote Control, or a Slack ping. */
316export function isHuman(origin: PromptOrigin): boolean {
317 return origin.kind === 'composer' || origin.kind === 'bridge' || origin.kind === 'slack-ping'
318}
319
320// ---------------------------------------------------------------------------------------------
321// Session sensors: idle and context marks. Information only, declared in memory-kit.conf;
322// absent means off.
323
324export const MINUTE = 60_000
325export const HOUR = 60 * MINUTE
326
327/** A conf number list that could not be used, said out loud (never silently off). */
328export type ConfNumbers = { declared: boolean; values: number[]; problem?: string }
329
330/** `watch_idle_minutes: 50` -- one value, whole minutes, at least 1. */
331export function confIdleMinutes(conf: string): ConfNumbers {
332 return confNumbers(conf, 'watch_idle_minutes', 1)
333}
334
335/**
336 * `watch_idle_repeat: true` (kit #47): the idle report recurs after each further idle interval,
337 * instead of once per working stretch. Its turn re-reads the prompt cache before the cache's hour
338 * runs out: a keep-alive for a long session. `false` or absent: once.
339 */
340export function confIdleRepeat(conf: string): { on: boolean; problem?: string } {
341 const raw = confValue(conf, 'watch_idle_repeat')
342 if (raw === undefined || raw === 'false') return { on: false }
343 if (raw === 'true') return { on: true }
344 return { on: false, problem: `true or false, not "${raw}"` }
345}
346
347/** `watch_context_percent: 50, 60, 70, 80` -- percent marks of the window, 1-99, sorted. */
348export function confContextPercent(conf: string): ConfNumbers {
349 const read = confNumbers(conf, 'watch_context_percent', Infinity)
350 if (read.problem !== undefined) return read
351 if (read.values.some(v => v > 99)) return { declared: true, values: [], problem: 'marks are percent of the window: 1-99' }
352 return { ...read, values: [...read.values].sort((a, b) => a - b) }
353}
354
355function confNumbers(conf: string, key: string, max: number): ConfNumbers {
356 const raw = confValue(conf, key)
357 if (raw === undefined) return { declared: false, values: [] }
358 const parts = raw.split(',').map(p => p.trim())
359 const values = parts.map(p => (/^[0-9]+$/.test(p) ? Number(p) : NaN))
360 if (values.some(v => Number.isNaN(v) || v < 1)) return { declared: true, values: [], problem: `not a list of whole numbers >= 1: "${raw}"` }
361 if (values.length > max) return { declared: true, values: [], problem: `one value expected: "${raw}"` }
362 return { declared: true, values }
363}
364
365/**
366 * The marks newly crossed: declared, at or below the context's percent of the window, not yet
367 * reported this session. Several at once (a big jump) report together, highest last.
368 */
369export function marksCrossed(marks: readonly number[], reported: readonly number[], tokens: number | undefined, window: number): number[] {
370 if (tokens === undefined || window <= 0) return []
371 const pct = (tokens / window) * 100
372 return marks.filter(m => m <= pct && !reported.includes(m))
373}
374
375/** The context report: information only; the home's rules say what this level means. */
376export function contextReport(mark: number, tokens: number, window: number): string {
377 const pct = Math.round((tokens / window) * 100)
378 return [
379 `[watch] Context has reached ${pct}% of the window (${tokens.toLocaleString('en-US')} of ${window.toLocaleString('en-US')} tokens), past the ${mark}% mark declared in memory-kit.conf.`,
380 'This is information only; what to do at this level is this home\'s own rule.',
381 ].join(' ')
382}
383
384/**
385 * The idle report: information only. A declared watch_retire_step is quoted as the home's own
386 * declared step, decided by the home, not by the watch.
387 */
388export function idleReport(idleMinutes: number, retireStep: string | undefined, repeat = false): string {
389 const mark = repeat ? 'the watch_idle_minutes mark in memory-kit.conf, repeating while idle (watch_idle_repeat)' : 'the watch_idle_minutes mark in memory-kit.conf'
390 const head = `[watch] This session has been idle for ${idleMinutes} min (${mark}).`
391 const tail = retireStep === undefined ? 'This is information only; what idleness means here is this home\'s own rule.' : `The home's declared step for this (watch_retire_step): ${retireStep}.`
392 return `${head} ${tail}`
393}
394hooks/kit-home.ts 152 lines1// kit_home: a memory-kit.conf key naming the kit home (kit #18). Pure: the caller hands in how
2// to read a file.
3//
4// IDENTICAL in adapters/claude-code/{obligations-pane,watch,kit-update}/hooks/kit-home.ts: a
5// plugin loads only its own folder, so each carries a copy; lint/run-fixtures.sh fails when the
6// copies differ. The same rules for Python are lint/kit_home.py, with the same messages.
7//
8// A start folder without a memory-kit.conf takes the nearest one above it (kit #42), as git finds
9// .git: a session started in a subfolder or a worktree of a home finds that home. The walk stops at
10// the filesystem root; no conf anywhere leaves the start folder as the home, as before.
11//
12// If that memory-kit.conf says `kit_home: <path>` (absolute, or relative to that conf's folder),
13// the home is the folder it names: that home's conf, memory-kit/VERSION, memory
14// directory, update:/upstream: and watch_files count, and the pointer conf's other keys are
15// ignored (reported in `ignored`). One hop, never chained: the target's conf may not point on (a
16// loop is a chain too). `kit_home: .` is just the home. A target with no memory-kit.conf, and a
17// `~` path (not expanded), are problems said plainly, never a silent fall back.
18//
19// So is a memory-kit.conf that gives a top-level key twice (kit #55), the start folder's or the one
20// a pointer names: confValueOf and the plugins' confValue take the first copy and YAML the last,
21// so a conf with memory_dir: twice sent the memory pane and the lint to different directories.
22
23export const KIT_HOME_KEY = 'kit_home'
24
25/** `foundIn`: the folder above the start folder whose memory-kit.conf decided (kit #42); absent
26 * when the start folder's own did, or none did. */
27export type KitHome = { home: string; pointer?: string; ignored: string[]; foundIn?: string } | { problem: string; pointer: string }
28
29/** POSIX (/...), a drive letter (C:\ or C:/) or UNC (\\server\share). */
30export function isAbsolute(path: string): boolean {
31 return /^(\/|[A-Za-z]:[\\/]|\\\\)/.test(path)
32}
33
34/** `.` and `..` resolved, `/` as the separator, no trailing slash; a root (/, C:/, //server/share) kept. */
35export function normalizePath(path: string): string {
36 const unc = /^\\\\|^\/\//.test(path)
37 const drive = /^[A-Za-z]:[\\/]/.exec(path)?.[0].slice(0, 2)
38 const root = unc ? '//' : drive !== undefined ? `${drive}/` : path.startsWith('/') ? '/' : ''
39 const parts: string[] = []
40 for (const part of path.slice(unc ? 2 : drive !== undefined ? 3 : root.length).split(/[\\/]+/)) {
41 if (part === '' || part === '.') continue
42 if (part === '..' && parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
43 else if (part !== '..' || root === '') parts.push(part)
44 }
45 return `${root}${parts.join('/')}` || '.'
46}
47
48/** `name` inside `dir`; a root (/, C:/) already ends in its separator. */
49const inside = (dir: string, name: string) => (dir.endsWith('/') ? `${dir}${name}` : `${dir}/${name}`)
50
51/** The folder above `path`, normalized; undefined at a root (/, C:/, //server/share). */
52export function parentOf(path: string): string | undefined {
53 const p = normalizePath(path)
54 if (p === '/' || /^[A-Za-z]:\/$/.test(p) || /^\/\/[^/]+(\/[^/]+)?$/.test(p)) return undefined
55 const cut = p.lastIndexOf('/')
56 if (cut === -1) return undefined
57 if (cut === 0) return '/'
58 const up = p.slice(0, cut)
59 return /^[A-Za-z]:$/.test(up) ? `${up}/` : up
60}
61
62const sameAs = (a: string, b: string) => {
63 const [x, y] = [normalizePath(a), normalizePath(b)]
64 return /^[A-Za-z]:\//.test(x) || x.startsWith('//') ? x.toLowerCase() === y.toLowerCase() : x === y
65}
66
67/** A top-level `key: value` of memory-kit.conf, a trailing comment and quotes stripped; '' when absent. */
68export function confValueOf(conf: string, key: string): string {
69 for (const line of conf.split(/\r?\n/)) {
70 if (!line.startsWith(`${key}:`)) continue
71 const raw = line.slice(key.length + 1)
72 const hash = raw.search(/\s#/)
73 return (hash === -1 ? raw : raw.slice(0, hash)).trim().replace(/^["']|["']$/g, '')
74 }
75 return ''
76}
77
78/** What a reader says when the folder it took for the home has no memory-kit.conf (kit #31): silence
79 * there looked the same as "nothing newer". lint/kit_home.py no_conf_notice says it alike. */
80export function noConfNotice(folder: string): string {
81 return `${normalizePath(folder)} has no memory-kit.conf, so it is not a kit home; if the home is elsewhere, put kit_home: <path> in a memory-kit.conf here`
82}
83
84/** What a reader says when the home came from a conf above the start folder (kit #42), so a
85 * surprising home is visible. lint/kit_home.py found_above_note says it alike. */
86export function foundAboveNote(start: string, foundIn: string): string {
87 return `${normalizePath(start)} has no memory-kit.conf; using the nearest one above it, in ${normalizePath(foundIn)}`
88}
89
90const topKeys = (conf: string) => conf.split(/\r?\n/).flatMap(line => /^([A-Za-z_][\w-]*):/.exec(line)?.[1] ?? [])
91
92/** The first top-level key a memory-kit.conf gives twice, its line and the first one's; undefined
93 * when it gives each once (kit #55). lint/kit_home.py repeated_key reads it alike. */
94export function repeatedKey(conf: string): { key: string; line: number; first: number } | undefined {
95 const seen = new Map<string, number>()
96 for (const [i, line] of conf.split(/\r?\n/).entries()) {
97 const key = /^([A-Za-z_][\w-]*):/.exec(line)?.[1]
98 if (key === undefined) continue
99 const first = seen.get(key)
100 if (first !== undefined) return { key, line: i + 1, first }
101 seen.set(key, i + 1)
102 }
103 return undefined
104}
105
106/** The problem a conf giving a top-level key twice is (kit #55); undefined when it gives each once.
107 * lint/kit_home.py repeated_key_problem says it alike. */
108export function repeatedKeyProblem(path: string, conf: string): string | undefined {
109 const twice = repeatedKey(conf)
110 if (twice === undefined) return undefined
111 return `${path}: duplicate key '${twice.key}' on line ${twice.line} (first on line ${twice.first}); the plugins would take the first and the lint the last, so keep only one`
112}
113
114/** The home for a start folder, by its memory-kit.conf's kit_home (see the head of this file). */
115export async function resolveKitHome(start: string, read: (path: string) => Promise<string | undefined>): Promise<KitHome> {
116 const begin = normalizePath(start)
117 let from: string | undefined = begin
118 let conf: string | undefined
119 for (; from !== undefined; from = parentOf(from)) {
120 try {
121 conf = await read(inside(from, 'memory-kit.conf'))
122 } catch (err) {
123 // A folder above that cannot be read (a network share refuses) ends the walk, as no conf would.
124 if (from === begin) throw err
125 break
126 }
127 if (conf !== undefined) break
128 }
129 if (from === undefined || conf === undefined) return { home: begin, ignored: [] }
130 const above = from === begin ? {} : { foundIn: from }
131 const pointer = inside(from, 'memory-kit.conf')
132 const twice = repeatedKeyProblem(pointer, conf)
133 if (twice !== undefined) return { pointer, problem: twice }
134 const raw = confValueOf(conf, KIT_HOME_KEY)
135 if (raw === '') return { home: from, ignored: [], ...above }
136 if (raw.startsWith('~'))
137 return { pointer, problem: `${pointer}: kit_home: ${raw} -- write it absolute or relative to this conf's folder (~ is not expanded)` }
138 const target = normalizePath(isAbsolute(raw) ? raw : inside(from, raw))
139 if (sameAs(target, from)) return { home: from, ignored: [], ...above }
140 const targetConf = await read(inside(target, 'memory-kit.conf'))
141 if (targetConf === undefined) return { pointer, problem: `${pointer}: kit_home: ${raw} -> ${target}: no memory-kit.conf there, so it is not a kit home` }
142 const targetTwice = repeatedKeyProblem(inside(target, 'memory-kit.conf'), targetConf)
143 if (targetTwice !== undefined) return { pointer, problem: targetTwice }
144 const onward = confValueOf(targetConf, KIT_HOME_KEY)
145 if (onward !== '' && !sameAs(isAbsolute(onward) ? onward : inside(target, onward), target))
146 return {
147 pointer,
148 problem: `${pointer}: kit_home: ${raw} -> ${target}, whose own conf points on (kit_home: ${onward}); a pointer is followed one hop, never chained`,
149 }
150 return { home: target, pointer, ignored: topKeys(conf).filter(k => k !== KIT_HOME_KEY), ...above }
151}
152types/index.d.ts 21 lines1// The watch mod's $.state contract. Self-contained: no imports.
2
3declare module 'claude-code' {
4 interface PluginState {
5 watch: {
6 /** The session's working directory at its first session.start: the default kit home. */
7 startCwd: string
8 /** Each watched file's last-seen size, by expanded path: growth past it rings the doorbell.
9 * A tail-style file's is also kept in $.store, per home, which a new session, having none of its own, reads (kit #51). */
10 bellSizes: Record<string, number>
11 /** Each watched file's last-seen text hash, by the same key: other text in its place rings (kit #52). */
12 bellHashes: Record<string, number>
13 /** Each watched file's last-seen line hashes, by the same key, with the text hash they belong
14 * to: other text in its place rings only when it adds a line (kit #57). None past the size cap. */
15 bellLines: Record<string, { hash: number; lines: number[] }>
16 /** Context marks already reported this session: once per mark, reloads included. */
17 reportedMarks: number[]
18 }
19 }
20}
21