KB health in the status line: the kb-intelligence snapshot's verdicts, and whether kb-serve runs the code on disk

Private Claude Code marketplace for Tuncer's mods: function-hook plugins that run inside every Claude Code session on his machines (MacBook Pro, MacBook Air, therig, the 5090 PC, the 4090 work PC).
| Plugin | What it does |
|---|---|
memory-guards | Refuses the footgun commands Claude's memory notes warn about (for example impeccable update --help, routing shiftyeyegames.com DNS through cloudflared, /logout before cswap add) and says why, with the safe alternative. It also refuses every copy of the Graves23 and Castaway projects (~370 GB each): worktrees by any route (shell, EnterWorktree, agent or workflow isolation, a session with its own worktree), clones, git archive, --work-tree, robocopy/xcopy/Copy-Item/cp/rsync of the project, MI, MI/Assets or MI/Library, and junctions or links, pointing at ~/.claude/rules/big-project-branches.md. |
kb-health | Shows KB health in the status line on the machine that runs the KB. It stays quiet on machines without the KB snapshot job. |
machine-tag | Prefixes session titles with the machine's emoji tag (💻 MBP, 🪶 Air, 🎮 Rig, 🔥 5090, ⚡ 4090), so pinned sessions show which computer they run on. /machine-tag <emoji> <word> overrides it per machine. |
pin-everywhere | A pinned session keeps its Remote Control on once machine-tag has put the machine icon in the title, so the session shows by name and icon on every other computer and the phone. Every open session checks all of the machine's pinned sessions every 2 minutes and reconnects any that dropped (an app restart drops them), including ones nobody has opened. Unpinning turns Remote Control back off when this mod turned it on; to keep a pinned session off Remote Control, unpin it. A title is published when Remote Control connects, so after renaming a pinned session, unpin and pin it again to publish the new name. |
claude plugin marketplace add Shifty-Eye-Games/claude-mods
claude plugin install memory-guards@claude-mods
claude plugin install kb-health@claude-mods
claude plugin install machine-tag@claude-mods
claude plugin install pin-everywhere@claude-mods
Then turn on auto-update: in /plugin, open Marketplaces, pick claude-mods and enable auto-update, or set it in ~/.claude/settings.json:
"extraKnownMarketplaces": {
"claude-mods": {
"source": { "source": "github", "repo": "Shifty-Eye-Games/claude-mods" },
"autoUpdate": true
}
}
Each session start then pulls main. No versions are set, so every commit is an update.
The repo is private, so each machine needs GitHub access without a prompt: an SSH key GitHub knows (Claude Code tries ssh -T git@github.com first), or stored HTTPS credentials (gh auth login then gh auth setup-git, or Git Credential Manager on Windows). Without them the clone and the updates fail silently and the machine keeps its last copy.
Machines that loaded these mods from local folders before must drop those folders from CLAUDE_CODE_PLUGIN_DIRS in ~/.claude/settings.json, or each mod loads twice.
plugins/<name>/.claude plugin validate plugins/<name> and claude plugin test plugins/<name>.main. Versions are left unset on purpose, so each commit reaches every machine at its next session start.How mods work, and the engine rules that bite, are in Claude's memory note on Claude Code mods.
Auto-update is on, so whatever lands on main runs in every session on all four machines. Only org admins can push here (the org's default member permission is read). Keep it that way: never give anyone else write access.
hooks/register.ts 148 lines1import type { EngineInterface, Register } from 'claude-code'
2
3// KB health in the status line: the verdicts of the 30-minute kb-intelligence snapshot, whether the hourly
4// kb-refresh still succeeds, and whether kb-serve runs the code on disk. It only reads files and asks lsof and
5// ps (from the home folder): an untracked file in ~/.hermes would stop the hourly kb-refresh cycle.
6const HOME = '/Users/tuncer'
7const HERMES = `${HOME}/.hermes`
8const SNAPSHOT_JOB = `${HOME}/Library/LaunchAgents/com.leela.kb-intelligence-snapshot.plist`
9const SNAPSHOT = `${HERMES}/profiles/leela/wiki/kb-site/data/kb-intelligence.json`
10const REFRESH_STATUS = `${HERMES}/state/kb-refresh/status.json`
11// kb-serve's code: what serve_kb_site.py imports at start, and the chat_service it loads lazily.
12const CODE_DIRS = [`${HERMES}/scripts/api`, `${HERMES}/scripts/lib`]
13const CODE_FILES = [`${HERMES}/scripts/serve_kb_site.py`, `${HERMES}/scripts/chat_service.py`]
14const PORT = '3901'
15const CHECK_MS = 5 * 60_000
16const SNAPSHOT_MAX_AGE_MS = 90 * 60_000 // the snapshot job runs every 30 minutes
17const REFRESH_MAX_AGE_MS = 150 * 60_000 // kb-refresh runs hourly at :30 and skips 02:30
18// kb-intelligence-status.py's healthy verdicts; every other status shows, UNKNOWN and new ones included.
19const GOOD = new Set(['FRESH', 'IN_SYNC', 'INFO', 'OK'])
20// Known, accepted verdicts. pr-deploy DIVERGED is the publish lane's standing lag (the served tree carries local
21// publish commits origin/main doesn't have yet); a stuck hourly kb-refresh, the failure it could hide, shows as
22// "kb-refresh last ok ... ago". Its other verdicts still show.
23const ACCEPTED = new Set(['pr-deploy DIVERGED'])
24
25type Snapshot = { generated_at?: unknown; workflows?: { id: string; status: string }[] }
26
27const state = { timer: undefined as { cancel: () => void } | undefined, stale: new Set<string>() }
28
29// `ps -o etime=` prints [[dd-]hh:]mm:ss.
30function etimeSeconds(etime: string): number | undefined {
31 const m = etime.trim().match(/^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/)
32 if (!m) {
33 return undefined
34 }
35 return ((Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0)) * 60 + Number(m[3])) * 60 + Number(m[4])
36}
37
38// Python writes microseconds; keep milliseconds so Date.parse reads it everywhere.
39const parseIso = (text: unknown) => Date.parse(String(text).replace(/(\.\d{3})\d+/, '$1'))
40
41function ago(ms: number): string {
42 const minutes = Math.max(0, Math.round(ms / 60_000))
43 return minutes < 120 ? `${minutes} min` : `${Math.round(minutes / 60)} h`
44}
45
46// Staleness counts on the second check in a row, so the minutes after the Mac wakes don't raise an alarm.
47function confirmed(key: string, isStale: boolean): boolean {
48 const wasStale = state.stale.has(key)
49 if (isStale) {
50 state.stale.add(key)
51 } else {
52 state.stale.delete(key)
53 }
54 return isStale && wasStale
55}
56
57async function snapshotProblems($: EngineInterface, now: number): Promise<string[]> {
58 let snap: Snapshot
59 try {
60 snap = JSON.parse(String(await $.fs.read(SNAPSHOT))) as Snapshot
61 } catch {
62 return ['snapshot missing']
63 }
64 const workflows = Array.isArray(snap.workflows) ? snap.workflows : []
65 if (workflows.length === 0) {
66 return ['snapshot empty']
67 }
68 const problems = workflows
69 .filter(w => !GOOD.has(w.status) && !ACCEPTED.has(`${w.id} ${w.status}`))
70 .map(w => `${w.id} ${String(w.status).toLowerCase().replace(/_/g, ' ')}`)
71 const age = now - parseIso(snap.generated_at)
72 if (confirmed('snapshot', !(age <= SNAPSHOT_MAX_AGE_MS))) {
73 problems.push(Number.isNaN(age) ? 'snapshot undated' : `snapshot ${ago(age)} old`)
74 }
75 return problems
76}
77
78async function refreshProblem($: EngineInterface, now: number): Promise<string | undefined> {
79 let age = NaN
80 try {
81 age = now - parseIso((JSON.parse(String(await $.fs.read(REFRESH_STATUS))) as { last_successful_at?: unknown }).last_successful_at)
82 } catch {
83 age = NaN
84 }
85 if (!confirmed('refresh', !(age <= REFRESH_MAX_AGE_MS))) {
86 return undefined
87 }
88 return Number.isNaN(age) ? 'kb-refresh status unreadable' : `kb-refresh last ok ${ago(age)} ago`
89}
90
91// The process listening on :3901 is kb-serve (launchd's PID can be a relaunch that never bound the port).
92// ponytail: imports beyond CODE_DIRS/CODE_FILES are missed; add them if the server grows new ones.
93async function kbServeProblem($: EngineInterface, now: number): Promise<string | undefined> {
94 const listening = await $.process.run(['/usr/sbin/lsof', '-nP', '-t', `-iTCP:${PORT}`, '-sTCP:LISTEN'], { cwd: HOME }).catch(() => undefined)
95 const pid = listening?.stdout.trim().split('\n')[0]
96 if (!pid) {
97 return 'kb-serve down'
98 }
99 const ps = await $.process.run(['/bin/ps', '-o', 'etime=', '-p', pid], { cwd: HOME }).catch(() => undefined)
100 const up = ps === undefined ? undefined : etimeSeconds(ps.stdout)
101 if (up === undefined) {
102 return 'kb-serve ?'
103 }
104 let newest = 0
105 try {
106 for (const dir of CODE_DIRS) {
107 for (const entry of await $.fs.list(dir)) {
108 if (entry.kind === 'file' && entry.name.endsWith('.py')) {
109 newest = Math.max(newest, entry.mtimeMs)
110 }
111 }
112 }
113 for (const file of CODE_FILES) {
114 newest = Math.max(newest, (await $.fs.stat(file)).mtimeMs)
115 }
116 } catch {
117 return 'kb-serve ?'
118 }
119 return newest > now - up * 1000 + 2_000 ? 'kb-serve restart needed' : undefined
120}
121
122async function check($: EngineInterface) {
123 const now = await $.clock.now()
124 const problems = await snapshotProblems($, now)
125 for (const problem of [await refreshProblem($, now), await kbServeProblem($, now)]) {
126 if (problem) {
127 problems.push(problem)
128 }
129 }
130 const shown = problems.length > 4 ? [...problems.slice(0, 4), `+${problems.length - 4} more`] : problems
131 // The status line is plain text (no colour codes), so a coloured emoji carries the verdict.
132 $.ui.status(shown.length > 0 ? `🔴 KB: ${shown.join(' · ')}` : '🟢 KB ok')
133}
134
135export const register: Register = on => {
136 on('session.start', async ($, e, next) => {
137 const ran = await next(e)
138 // The snapshot job's plist marks the KB Mac; anywhere else the mod stays silent.
139 if (await $.fs.exists(SNAPSHOT_JOB)) {
140 state.timer?.cancel()
141 state.timer = $.clock.every(CHECK_MS, () => void check($))
142 void check($)
143 }
144
145 return ran
146 })
147}
148