memory-kit kit-update: checks upstream for a newer release on the home's channel (memory-kit.conf update: pinned|verified|latest) and prompts the session, once…

A Claude Code mod (function hooks) for a memory-kit home, kit issue #15 part 3. It is the third plugin in the memory-kit marketplace, beside the obligations pane and the watch. Each installs, switches off and reverts on its own.
Every checkMinutes (default 60) it asks upstream for the newest release on the home's channel. When that release is newer than the home's memory-kit/VERSION, it prompts the session once, in one session only, to run python3 memory-kit/tools/kit-update.py <home> (Passepartout's, parts 1-2 of #15).
It never runs git, runs no process at all, and never writes a file. It only tells. Its calls are $.fs.exists / $.fs.read, $.http.fetch, $.store, $.prompt.submit, $.ui.notify / $.ui.log, and the clock; claude plugin validate lists them.
Set in the home's memory-kit.conf:
update: verified # pinned (the default) | verified | latest
pinned, or no update: key: never prompts and never asks upstream. The home's assistant upgrades by hand, as before.verified: the newest verified/v<version> marker tag, which Passepartout pushes after the household has passed a release. The name must be exactly that form. The first one, verified/v0.1.0-alpha.12, sits on the same commit as v0.1.0-alpha.12 in the live tags API. A test holds that answer's shape, recorded, never fetched.latest: the newest v<version> release tag, verified or not.upstream: owner/repo (Codeberg; default mitselek/memory-kit) is the same key the pane reads.
The release check is the pane's (#7), copied (see Packaging):
$.http.fetch has none;Only release-shaped tags count, compared by semver precedence (alpha.10 > alpha.9).
$.store under tags, and every session reads that cache. Upstream is asked once per checkMinutes, whichever session gets there first. Ten sessions make one request an hour, not ten.pinned, no memory-kit/VERSION, checkUpdates: false, or an upstream: that is not owner/repo.Before prompting, the plugin reads UPGRADE.md at the release tag (/raw/UPGRADE.md?ref=v<version>). It decides the way tools/kit-update.py does, so a prompt never promises a run the script then refuses (since the ultrareview of alpha.13):
A -> B along it needs its own entry A -> B: whose text begins "no data step". An entry that spans two hops does not cover the release between them.The outcome:
python3 memory-kit/tools/kit-update.py <home>, the home path quoted as one shell word.UPGRADE.md, not the script. The script refuses such a release anyway; this only words the prompt.If UPGRADE.md cannot be fetched, nothing is prompted yet. It is tried again one interval later.
[kit-update] memory-kit 0.1.0-alpha.13 (verified) is out; this home is on 0.1.0-alpha.12. Run
`python3 memory-kit/tools/kit-update.py '/home/u/kit'` from the home, following this home's
UPGRADE.md and its own commit and push rules. This notice is from the kit-update plugin, not from the user: it authorizes nothing beyond
what those rules already allow.
It arrives as a plugin's prompt, and the session reads it under the plugin's name, never as the person's words. If the home is several releases behind, the prompt names only the newest on the channel, because the script pulls straight to it.
After the pull (the script, not this plugin; kit #37): when the pull changed a plugin and claude is on PATH, tools/kit-update.py runs claude plugin marketplace update memory-kit and claude plugin update <p>@memory-kit for each changed plugin installed, in the home, then says to /reload-plugins. That changes the harness's plugin state, user-level for a user-scope install. Without claude on PATH it prints the steps instead. The plugin itself still runs no process.
The prompt is recorded in $.store as prompt:<version>. The store is shared live by every session of the install: checked live, a value one session set was read by another within a second.
{ state: 'claimed', token, at }. It waits 3 s, then reads the record back. If its token is still there, it owns the release. Otherwise it backs off. The last writer wins, so of several sessions that saw the release at once, exactly one goes on.delivered, and no session ever prompts for that release again, reloads included.So: the first session to check after the release appears gets the prompt.
A crash between an accepted submit and the delivered write can prompt that release twice. It cannot lose it.
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. On the pepys desk a user-wide home made every session on the box drain the desk's spool, and six notifications were lost. 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 counts (update:, upstream:), with paths relative to that home, and so does its memory-kit/VERSION. Other keys left in the pointer conf are ignored, and update: or upstream: 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. /kit-update 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.C:\ or C:/) or UNC. ~ is not expanded: write the path absolute or relative to the conf.memory-kit/VERSION, is one visible notice (notify, else a transcript line), and nothing is checked. /kit-update 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 nothing is checked. With update: twice, kit-update read the first copy where YAML keeps the last; now neither picks. tools/kit-update.py refuses it alike.home option's) has no memory-kit.conf, one visible notice says so and names the fix (kit_home: <path> in a conf there), and /kit-update shows the same text. Before, it read as pinned and said nothing, which looked the same as "nothing newer".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 and memory-kit/VERSION count. Empty: the session's start directory. Set user-wide, it applies to every session on the machine, so the prompt could land in any of them: prefer a kit_home pointer conf (above), which also wins over this option.checkMinutes (60, at least 5): how often upstream is asked, across all sessions.checkUpdates (on): off makes no request at all.Shows:
channel: latest
this home: 0.1.0-alpha.11 (/home/u/kit)
newest on the channel: 0.1.0-alpha.12
last check: 2026-10-14T11:19 UTC (every 60 min)
0.1.0-alpha.12: prompted 2026-10-14T11:19 UTC in another session
update: latest, against the real Codeberg (alpha.12 out, and its verified/ marker)./kit-update showed "prompted ... in another session".--plugin-dir install's own store (~/.claude/plugins/store/kit-update_inline-*.json). kit-update@memory-kit has its own.The pane's release check (parseRelease, compareRelease, tagNamesOf, isFresh, confValue, kitVersionOf, the owner/repo upstream) is copied into hooks/release.ts, with a note there. A plugin loads only files inside its own folder. A remote install copies the plugin's folder alone, and each plugin must install, switch off and revert on its own. An import across plugin folders would break all three.
Change one copy, change the other: the copied functions are marked.
In the memory-kit marketplace, beside the pane and the watch. The entry to add upstream (adapters/claude-code/.claude-plugin/marketplace.json):
{
"name": "kit-update",
"source": "./kit-update",
"description": "Checks upstream for a newer kit release on the home's channel and prompts once to run tools/kit-update.py; never runs git."
}
Then claude plugin install kit-update@memory-kit. For one session: claude --plugin-dir ./memory-kit/adapters/claude-code/kit-update.
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; upstream, files, store, clock and the session are mocked
tsc -p . # once Claude Code has laid .claude-plugin/types/ (gitignored)hooks/register.ts 352 lines1// The kit-update plugin (memory-kit issue #15, part 3): every checkMinutes it asks upstream for the
2// newest release on the home's channel (memory-kit.conf `update: pinned | verified | latest`) and,
3// once per release across every session, prompts the session to run memory-kit/tools/kit-update.py.
4// It never runs git and never changes a file: it only tells.
5
6import type { EngineInterface, Register } from 'claude-code'
7
8import {
9 backoffMs,
10 channelOf,
11 compareRelease,
12 confValue,
13 isFresh,
14 kitVersionOf,
15 parseRelease,
16 promptText,
17 stepCheck,
18 tagNamesOf,
19 tagsUrl,
20 targetOf,
21 upgradeUrl,
22} from './release'
23import type { Channel } from './release'
24import { foundAboveNote, isAbsolute, noConfNotice, normalizePath, resolveKitHome } from './kit-home'
25import type { KitHome } from './kit-home'
26
27const MINUTE = 60_000
28/** The local tick: cheap (store and file reads); upstream is asked only once per checkMinutes. */
29const TICK_MS = MINUTE
30/** $.http.fetch has no timeout of its own (the pane's lesson, #7). */
31const FETCH_TIMEOUT_MS = 10_000
32/** A claim is read back after this long; the last writer owns the release. */
33const CLAIM_SETTLE_MS = 3_000
34/** A claim not refreshed this long belongs to a session that is gone: another may take it over. */
35const CLAIM_STALE_MS = 30 * MINUTE
36/** At most this many tag pages (50 each). */
37const MAX_PAGES = 10
38
39/** $.store, shared by every session: the tags cache, and one record per prompted release. */
40const TAGS = 'tags'
41const promptKey = (version: string) => `prompt:${version}`
42
43type TagsCache = Record<string, { checkedAt: number; names: string[] }>
44type PromptRecord = { state: 'claimed' | 'delivered'; token: string; at: number }
45
46type Settings = { home: string; checkMs: number; checkUpdates: boolean }
47
48// Module state: a reload starts it over; the store keeps what must survive (the dedupe).
49let checking = false
50let refusals = 0
51let nextTryAt = 0
52let upgradeRetryAt = 0
53const upgradeTexts = new Map<string, string>()
54const told = new Set<string>()
55/** This module's claim token: a reload gets a new one, and finds its old claim by the store's time. */
56let token = ''
57
58async function readOrEmpty($: EngineInterface, path: string): Promise<string> {
59 try {
60 return (await $.fs.exists(path)) ? await $.fs.read(path) : ''
61 } catch {
62 return ''
63 }
64}
65
66/**
67 * The kit home (kit #18). The start folder's memory-kit.conf decides first: a `kit_home:` pointer
68 * names the home, one hop; a start folder without a conf takes the nearest one above it (kit
69 * #42). A home so found wins over the user-scope `home` option, which applies to every session on
70 * the machine. Otherwise the option (normalized as the pointer is, kit #46), else the start folder.
71 */
72async function homeOf($: EngineInterface, settings: Settings): Promise<KitHome> {
73 const start = await startOf($)
74 const found = await resolveKitHome(start, async p => ((await $.fs.exists(p)) ? $.fs.read(p) : undefined))
75 if ('problem' in found || found.pointer !== undefined || found.foundIn !== undefined || settings.home === '') return found
76 return { home: normalizePath(isAbsolute(settings.home) ? settings.home : `${start}/${settings.home}`), ignored: [] }
77}
78/** The folder the session started in, set at the first session.start (see there). */
79let startCwd = ''
80
81/** The start folder: the first session.start's, else the session's root. */
82const startOf = async ($: EngineInterface) => startCwd || (await startFolder($, ''))
83
84/** The folder the session started in: its root, which a shell cd does not move (kit #45); `cwd` if the engine gives none. */
85async function startFolder($: EngineInterface, cwd: string): Promise<string> {
86 try {
87 return (await $.session.root()) || cwd || (await $.session.cwd())
88 } catch {
89 return cwd || (await $.session.cwd())
90 }
91}
92
93/** tools/kit-update.py says the same. */
94const noConfText = (home: string) => `${noConfNotice(home)}. kit-update checks nothing until it has one.`
95
96async function existsOrNot($: EngineInterface, path: string): Promise<boolean> {
97 try {
98 return await $.fs.exists(path)
99 } catch {
100 return false
101 }
102}
103
104/** One notice to the human, once per text: notify, else a transcript line (the watch's lesson). */
105async function tellOnce($: EngineInterface, text: string): Promise<void> {
106 if (told.has(text)) return
107 told.add(text)
108 let shown = false
109 try {
110 const sent = await $.ui.notify(text, { title: 'kit-update' })
111 shown = sent.isSent && sent.channel !== 'terminal_bell'
112 } catch {
113 // Refused: the transcript line carries it.
114 }
115 if (!shown) $.ui.log(text)
116}
117
118/** A GET that fails after FETCH_TIMEOUT_MS; undefined (and one debug line) on any failure. */
119async function fetchText($: EngineInterface, url: string): Promise<string | undefined> {
120 let timer: { cancel: () => void } | undefined
121 try {
122 const expired = new Promise<never>((_, reject) => {
123 timer = $.clock.after(FETCH_TIMEOUT_MS, () => reject(new Error(`timed out after ${FETCH_TIMEOUT_MS / 1000} s`)))
124 })
125 const answer = await Promise.race([$.http.fetch(url, { headers: { accept: 'application/json, text/plain' } }), expired])
126 if (!answer.ok) throw new Error(`HTTP ${answer.status}`)
127 return answer.text
128 } catch (err) {
129 $.ui.log(`kit-update: ${url} failed: ${String(err)}`, { to: 'debug' })
130 return undefined
131 } finally {
132 timer?.cancel()
133 }
134}
135
136/**
137 * Upstream's tag names, from the shared cache while it is younger than checkMinutes, else asked
138 * (every page). A failure is silent and counts as a check, so the next try is one interval on,
139 * for every session; undefined then.
140 */
141async function tagNames($: EngineInterface, upstream: string | undefined, settings: Settings, now: number): Promise<string[] | undefined> {
142 const key = tagsUrl(upstream, 1) ?? ''
143 const stored = await $.store.get(TAGS)
144 const cache: TagsCache = typeof stored === 'object' && stored !== null ? (stored as TagsCache) : {}
145 const entry = cache[key]
146 if (entry !== undefined && Array.isArray(entry.names) && isFresh(entry.checkedAt, now, settings.checkMs)) return entry.names
147 const names: string[] = []
148 let failed = false
149 for (let page = 1; page <= MAX_PAGES; page++) {
150 const text = await fetchText($, tagsUrl(upstream, page) ?? '')
151 const batch = text === undefined ? undefined : tagNamesOf(text)
152 if (batch === undefined) {
153 failed = true
154 break
155 }
156 names.push(...batch)
157 if (batch.length < 50) break
158 }
159 // Only release-shaped names are kept: the cache stays small.
160 const kept = failed ? (entry?.names ?? []) : names.filter(n => /^(verified\/)?v\d/.test(n))
161 await $.store.set(TAGS, { ...cache, [key]: { checkedAt: now, names: kept } })
162 return failed ? undefined : kept
163}
164
165function recordOf(value: unknown): PromptRecord | undefined {
166 const r = value as Partial<PromptRecord> | null | undefined
167 if (r == null || (r.state !== 'claimed' && r.state !== 'delivered') || typeof r.token !== 'string' || typeof r.at !== 'number') return undefined
168 return r as PromptRecord
169}
170
171/**
172 * The prompt for `target`, once across every session: a session claims the release in $.store,
173 * reads the claim back after CLAIM_SETTLE_MS (the last writer owns it), submits, and marks it
174 * delivered. A refused submit keeps the claim, refreshed each tick, and retries with backoff; a
175 * claim left CLAIM_STALE_MS (its session gone) is taken over.
176 */
177async function offer(
178 $: EngineInterface,
179 target: string,
180 channel: Channel,
181 current: string,
182 home: string,
183 upstream: string | undefined,
184 releases: readonly string[],
185 settings: Settings,
186): Promise<void> {
187 const key = promptKey(target)
188 const now = await $.clock.now()
189 const rec = recordOf(await $.store.get(key))
190 if (rec?.state === 'delivered') return
191 const ours = rec?.token === token
192 if (rec !== undefined && !ours && now - rec.at < CLAIM_STALE_MS) return
193 if (ours && now < nextTryAt) {
194 await $.store.set(key, { state: 'claimed', token, at: now })
195 return
196 }
197
198 let md = upgradeTexts.get(target)
199 if (md === undefined) {
200 if (now < upgradeRetryAt) return
201 md = await fetchText($, upgradeUrl(upstream, target) ?? '')
202 if (md === undefined) {
203 upgradeRetryAt = now + settings.checkMs
204 return
205 }
206 upgradeTexts.set(target, md)
207 }
208 const steps = stepCheck(md, current, target, releases)
209
210 if (!ours) {
211 await $.store.set(key, { state: 'claimed', token, at: now })
212 await $.clock.sleep(CLAIM_SETTLE_MS)
213 if (recordOf(await $.store.get(key))?.token !== token) return
214 }
215 const text = promptText(
216 steps.manual ? { version: target, channel, current, home, manual: true, reason: steps.reason } : { version: target, channel, current, home, manual: false },
217 )
218 let refused: string | undefined
219 try {
220 const result = await $.prompt.submit({ text })
221 if (result.drop !== undefined) refused = result.drop
222 } catch (err) {
223 refused = String(err)
224 }
225 const after = await $.clock.now()
226 if (refused !== undefined) {
227 refusals++
228 nextTryAt = after + backoffMs(refusals)
229 await $.store.set(key, { state: 'claimed', token, at: after })
230 $.ui.log(`kit-update: the prompt for ${target} was refused (${refused}); retrying in ${backoffMs(refusals) / MINUTE} min`, { to: 'debug' })
231 return
232 }
233 refusals = 0
234 await $.store.set(key, { state: 'delivered', token, at: after })
235}
236
237/** What the home declares and holds now. */
238async function homeState($: EngineInterface, settings: Settings) {
239 const found = await homeOf($, settings)
240 const pointerProblem = 'problem' in found ? found.problem : undefined
241 const home = 'problem' in found ? '' : found.home
242 const pointer = found.pointer
243 const ignored = 'problem' in found ? [] : found.ignored
244 const foundAbove = !('problem' in found) && found.foundIn !== undefined ? foundAboveNote(await startOf($), found.foundIn) : ''
245 const conf = pointerProblem !== undefined ? '' : await readOrEmpty($, `${home}/memory-kit.conf`)
246 // kit #31: no conf reads as pinned and checks nothing, which looked the same as "nothing newer".
247 const noConf = pointerProblem === undefined && !(await existsOrNot($, `${home}/memory-kit.conf`))
248 const version = pointerProblem !== undefined ? undefined : kitVersionOf(await readOrEmpty($, `${home}/memory-kit/VERSION`))
249 return { home, pointer, pointerProblem, noConf, ignored, foundAbove, conf, version, ...channelOf(conf), upstream: confValue(conf, 'upstream') }
250}
251
252async function tick($: EngineInterface, settings: Settings): Promise<void> {
253 if (checking) return
254 checking = true
255 try {
256 const h = await homeState($, settings)
257 if (h.pointerProblem !== undefined) {
258 await tellOnce($, `${h.pointerProblem}. Nothing is checked until it is fixed.`)
259 return
260 }
261 if (h.noConf) {
262 await tellOnce($, noConfText(h.home))
263 return
264 }
265 if (h.pointer !== undefined) {
266 const lost = h.ignored.filter(k => k === 'update' || k === 'upstream')
267 if (lost.length > 0)
268 await tellOnce($, `${lost.join(' and ')} in ${h.pointer} ${lost.length === 1 ? 'is' : 'are'} ignored: that conf points at the home (kit_home), and ${lost.length === 1 ? 'it counts' : 'they count'} in ${h.home}/memory-kit.conf.`)
269 if (h.version === undefined) {
270 await tellOnce($, `${h.home} has no memory-kit/VERSION, though kit_home in ${h.pointer} names it as the kit home; nothing is checked.`)
271 return
272 }
273 }
274 if (h.problem !== undefined) await tellOnce($, `${h.home}/memory-kit.conf: ${h.problem}.`)
275 if (!settings.checkUpdates || h.channel === 'pinned' || h.version === undefined) return
276 if (tagsUrl(h.upstream, 1) === undefined) {
277 await tellOnce($, `${h.home}/memory-kit.conf: upstream: ${h.upstream} is not owner/repo on Codeberg; nothing is checked.`)
278 return
279 }
280 const names = await tagNames($, h.upstream, settings, await $.clock.now())
281 if (names === undefined) return
282 const target = targetOf(h.channel, names)
283 const mine = parseRelease(h.version)
284 const theirs = target === undefined ? undefined : parseRelease(target)
285 if (target === undefined || mine === undefined || theirs === undefined || compareRelease(theirs, mine) <= 0) return
286 await offer($, target, h.channel, h.version, h.home, h.upstream, names, settings)
287 } catch (err) {
288 $.ui.log(`kit-update: check failed: ${String(err)}`, { to: 'debug' })
289 } finally {
290 checking = false
291 }
292}
293
294/** What /kit-update answers. */
295async function status($: EngineInterface, settings: Settings): Promise<string> {
296 const h = await homeState($, settings)
297 if (h.pointerProblem !== undefined) return `${h.pointerProblem}.\nNothing is checked until it is fixed.`
298 if (h.noConf) return noConfText(h.home)
299 const via = h.pointer !== undefined ? `, by kit_home in ${h.pointer}` : ''
300 const lines = [`channel: ${h.channel}${h.problem !== undefined ? ` (${h.problem})` : ''}`, `this home: ${h.version ?? 'no memory-kit/VERSION'} (${h.home}${via})`]
301 if (h.foundAbove !== '') lines.push(h.foundAbove)
302 if (h.channel === 'pinned') {
303 lines[0] += ' -- no checks; set update: verified or latest in memory-kit.conf to follow releases'
304 return lines.join('\n')
305 }
306 if (!settings.checkUpdates) lines.push('checkUpdates is off: no checks')
307 const stored = await $.store.get(TAGS)
308 const entry = (typeof stored === 'object' && stored !== null ? (stored as TagsCache) : {})[tagsUrl(h.upstream, 1) ?? '']
309 const target = entry === undefined ? undefined : targetOf(h.channel, entry.names)
310 lines.push(`newest on the channel: ${target ?? 'not known yet'}`)
311 lines.push(`last check: ${entry === undefined ? 'none yet' : `${new Date(entry.checkedAt).toISOString().slice(0, 16)} UTC`} (every ${settings.checkMs / MINUTE} min)`)
312 if (target !== undefined) {
313 const rec = recordOf(await $.store.get(promptKey(target)))
314 const when = (at: number) => `${new Date(at).toISOString().slice(0, 16)} UTC`
315 lines.push(
316 `${target}: ${
317 rec === undefined
318 ? 'not prompted'
319 : rec.state === 'delivered'
320 ? `prompted ${when(rec.at)}${rec.token === token ? ' in this session' : ' in another session'}`
321 : `claimed ${when(rec.at)}${rec.token === token ? ' by this session (prompt refused, retrying)' : ' by another session'}`
322 }`,
323 )
324 }
325 return lines.join('\n')
326}
327
328export const register: Register = (on, options) => {
329 const settings: Settings = {
330 home: typeof options.home === 'string' ? options.home.trim() : '',
331 checkMs: Math.max(5, typeof options.checkMinutes === 'number' && Number.isFinite(options.checkMinutes) ? options.checkMinutes : 60) * MINUTE,
332 checkUpdates: options.checkUpdates !== false,
333 }
334 let timer: { cancel: () => void } | undefined
335
336 on('session.start', async ($, e, next) => {
337 const started = await next(e)
338 // The first start only. It may be an install or enable mid-session, whose e.cwd is the
339 // shell's folder after any cd: the session's root is not moved by a cd (kit #45).
340 if (startCwd === '') startCwd = await startFolder($, e.cwd)
341 if (token === '') token = `${await $.clock.now()}-${Math.random().toString(36).slice(2, 10)}`
342 await $.command.register({ name: 'kit-update', description: "Show the kit's update channel, this home's version, the newest release and the last check" })
343 timer?.cancel()
344 timer = $.clock.every(TICK_MS, () => void tick($, settings))
345 // Never awaited: a check may wait on the network, and a prompt on its turn.
346 void tick($, settings)
347 return started
348 })
349
350 on('command.run', { command: 'kit-update' }, async $ => ({ text: await status($, settings) }))
351}
352hooks/release.ts 199 lines1// Pure logic of the kit-update plugin: no `$`, no I/O. Everything here is unit-tested.
2//
3// The release check is a COPY of the obligations pane's (kit #7), from
4// adapters/claude-code/obligations-pane/hooks/obligations.ts: parseRelease, compareRelease,
5// tagNamesOf, isFresh, confValue, kitVersionOf, the owner/repo upstream. A plugin loads only
6// files inside its own folder, and each plugin installs and reverts on its own, so the two
7// cannot share one module. Change one, change both.
8
9// ---------------------------------------------------------------------------------------------
10// Copied from the pane.
11
12export type Release = { major: number; minor: number; patch: number; pre?: { kind: 'alpha' | 'beta' | 'rc'; n: number } }
13
14const NUM = '(0|[1-9]\\d*)'
15const RELEASE = new RegExp(`^v?${NUM}\\.${NUM}\\.${NUM}(?:-(alpha|beta|rc)\\.${NUM})?$`)
16
17/** A release tag or version: v<maj>.<min>.<patch>, optional -alpha.N, -beta.N or -rc.N; else undefined. */
18export function parseRelease(tag: string): Release | undefined {
19 const m = RELEASE.exec(tag.trim())
20 if (!m) return undefined
21 const core = { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) }
22 return m[4] === undefined ? core : { ...core, pre: { kind: m[4] as 'alpha' | 'beta' | 'rc', n: Number(m[5]) } }
23}
24
25const PRE_ORDER = { alpha: 0, beta: 1, rc: 2 } as const
26
27/** Semver precedence: core numbers, then a release above its pre-releases, then alpha < beta < rc, then N. */
28export function compareRelease(a: Release, b: Release): number {
29 const core = a.major - b.major || a.minor - b.minor || a.patch - b.patch
30 if (core !== 0) return core
31 if (a.pre === undefined || b.pre === undefined) return (a.pre === undefined ? 1 : 0) - (b.pre === undefined ? 1 : 0)
32 return PRE_ORDER[a.pre.kind] - PRE_ORDER[b.pre.kind] || a.pre.n - b.pre.n
33}
34
35export const versionText = (r: Release) =>
36 `${r.major}.${r.minor}.${r.patch}${r.pre === undefined ? '' : `-${r.pre.kind}.${r.pre.n}`}`
37
38/** Tag names from a tags API answer (a JSON list of `{ name }`); undefined for anything else. */
39export function tagNamesOf(text: string): string[] | undefined {
40 let data: unknown
41 try {
42 data = JSON.parse(text)
43 } catch {
44 return undefined
45 }
46 if (!Array.isArray(data)) return undefined
47 const names: string[] = []
48 for (const tag of data) {
49 const name = (tag as { name?: unknown } | null)?.name
50 if (typeof name !== 'string') return undefined
51 names.push(name)
52 }
53 return names
54}
55
56/** A check made within the interval. A clock that went back makes it stale. */
57export function isFresh(checkedAt: number, now: number, intervalMs: number): boolean {
58 const age = now - checkedAt
59 return age >= 0 && age < intervalMs
60}
61
62/** Strips a trailing ` # comment` from a plain scalar. */
63function plainScalar(raw: string): string {
64 const hash = raw.search(/(^|\s)#/)
65 return (hash === -1 ? raw : raw.slice(0, hash)).trim()
66}
67
68/** A top-level `key: value` of a kit home's memory-kit.conf, unquoted; undefined when absent or empty. */
69export function confValue(conf: string, key: string): string | undefined {
70 for (const raw of conf.split(/\r?\n/)) {
71 if (!raw.startsWith(`${key}:`)) continue
72 const v = plainScalar(raw.slice(key.length + 1)).replace(/^["']|["']$/g, '')
73 return v === '' ? undefined : v
74 }
75 return undefined
76}
77
78/** The version a home's memory-kit/VERSION names: line 1, trimmed; undefined when empty. */
79export function kitVersionOf(text: string): string | undefined {
80 const first = (text.split(/\r?\n/)[0] ?? '').trim()
81 return first === '' ? undefined : first
82}
83
84export const DEFAULT_UPSTREAM = 'mitselek/memory-kit'
85const REPO_PART = '[A-Za-z0-9_][A-Za-z0-9_.-]*'
86const OWNER_REPO = new RegExp(`^${REPO_PART}/${REPO_PART}$`)
87
88function repoOf(upstream: string | undefined): string | undefined {
89 const repo = upstream ?? DEFAULT_UPSTREAM
90 return OWNER_REPO.test(repo) && !repo.split('/').some(p => /^\.+$/.test(p)) ? repo : undefined
91}
92
93// ---------------------------------------------------------------------------------------------
94// Channels (kit #15): memory-kit.conf `update: pinned | verified | latest`.
95
96export type Channel = 'pinned' | 'verified' | 'latest'
97
98/** The home's channel; pinned when absent. Anything else is a problem, read as pinned (no request). */
99export function channelOf(conf: string): { channel: Channel; problem?: string } {
100 const v = confValue(conf, 'update')
101 if (v === undefined || v === 'pinned') return { channel: 'pinned' }
102 if (v === 'verified' || v === 'latest') return { channel: v }
103 return { channel: 'pinned', problem: `update: ${v} is not a channel (pinned, verified or latest); nothing is checked` }
104}
105
106/** The newest release on the channel: `latest`, every `v...` tag; `verified`, the `verified/v...` markers. */
107export function targetOf(channel: Channel, names: readonly string[]): string | undefined {
108 if (channel === 'pinned') return undefined
109 let best: Release | undefined
110 for (const name of names) {
111 // Exactly `verified/v<version>` (a marker) or `v<version>` (a release tag).
112 const marker = name.startsWith('verified/v')
113 if (marker !== (channel === 'verified')) continue
114 const tag = marker ? name.slice('verified/'.length) : name
115 if (!tag.startsWith('v')) continue
116 const r = parseRelease(tag)
117 if (r !== undefined && (best === undefined || compareRelease(r, best) > 0)) best = r
118 }
119 return best === undefined ? undefined : versionText(best)
120}
121
122/** One page of the tags API (50 to a page); undefined for an upstream that is not owner/repo. */
123export function tagsUrl(upstream: string | undefined, page: number): string | undefined {
124 const repo = repoOf(upstream)
125 return repo === undefined ? undefined : `https://codeberg.org/api/v1/repos/${repo}/tags?limit=50&page=${page}`
126}
127
128/** UPGRADE.md as the release tag has it. */
129export function upgradeUrl(upstream: string | undefined, version: string): string | undefined {
130 const repo = repoOf(upstream)
131 return repo === undefined ? undefined : `https://codeberg.org/api/v1/repos/${repo}/raw/UPGRADE.md?ref=v${version}`
132}
133
134// ---------------------------------------------------------------------------------------------
135// Auto or manual: UPGRADE.md's per-version steps, `- **A -> B:** ...`.
136
137/**
138 * Whether going from `current` to `target` can run tools/kit-update.py, decided as the script
139 * decides it (its step_path and data_steps_ok), so the prompt never promises what the script
140 * refuses (ultrareview alpha.13, finding 3). The path is the home's current version, always (even
141 * when its tag is gone upstream), then every release tag in `releases` after it up to the target.
142 * Every hop A -> B needs its own UPGRADE.md entry `**A -> B:**` whose text begins "no data step";
143 * a missing entry, a data step, or a new major is a manual upgrade, with the reason. The script
144 * makes the same refusal; this only words the prompt.
145 */
146export function stepCheck(
147 upgradeMd: string,
148 current: string,
149 target: string,
150 releases: readonly string[],
151): { manual: false } | { manual: true; reason: string } {
152 const from = parseRelease(current)
153 const to = parseRelease(target)
154 if (from === undefined || to === undefined) return { manual: true, reason: 'a version that is not a release' }
155 if (to.major !== from.major) return { manual: true, reason: 'a new major version' }
156 const between = releases
157 .filter(name => name.startsWith('v'))
158 .map(name => parseRelease(name))
159 .filter((r): r is Release => r !== undefined && compareRelease(r, from) > 0 && compareRelease(r, to) < 0)
160 .sort(compareRelease)
161 .map(versionText)
162 const path = [current, ...new Set(between), target]
163 for (let i = 0; i + 1 < path.length; i++) {
164 const [a = '', b = ''] = [path[i], path[i + 1]]
165 const entry = upgradeMd.indexOf(`**${a} -> ${b}:**`)
166 if (entry === -1) return { manual: true, reason: `UPGRADE.md has no entry for ${a} -> ${b}` }
167 const text = upgradeMd.slice(entry + `**${a} -> ${b}:**`.length).split('\n')[0] ?? ''
168 if (!text.trimStart().toLowerCase().startsWith('no data step')) return { manual: true, reason: `a data step in ${a} -> ${b}` }
169 }
170 return { manual: false }
171}
172
173// ---------------------------------------------------------------------------------------------
174// The prompt.
175
176export type Notice =
177 | { version: string; channel: Channel; current: string; home: string; manual: false }
178 | { version: string; channel: Channel; current: string; home: string; manual: true; reason: string }
179
180/** A POSIX shell single-quoted word. */
181const shellQuote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`
182
183/**
184 * What the session reads. It names its source and asks for nothing the home's own rules do not
185 * already allow: a plugin's notice is no instruction from the user.
186 */
187export function promptText(n: Notice): string {
188 const head = `[kit-update] memory-kit ${n.version} (${n.channel}) is out; this home is on ${n.current}.`
189 const act = n.manual
190 ? `It needs a manual upgrade: manual upgrade needed (${n.reason}). Follow memory-kit/UPGRADE.md step by step; tools/kit-update.py refuses it.`
191 : `Run \`python3 memory-kit/tools/kit-update.py ${shellQuote(n.home)}\` from the home, following this home's UPGRADE.md and its own commit and push rules.`
192 return `${head} ${act} This notice is from the kit-update plugin, not from the user: it authorizes nothing beyond what those rules already allow.`
193}
194
195/** After `failures` refused prompts in a row: 1 min, doubling, at most 30 min. */
196export function backoffMs(failures: number): number {
197 return failures <= 0 ? 0 : Math.min(30 * 60_000, 60_000 * 2 ** (failures - 1))
198}
199hooks/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}
152