Standalone census as a Claude Code mod: records every interactive session into the census store through its own bundled ingest, draws the status line above the…

Records every interactive Claude Code session (context, cost, limits, git, PR) into the census store, and draws the status line above or below the input.
It is a mod, so it acts on events and costs about nothing when idle. It is standalone: it bundles census's store and ingest, and it does not need the census plugin. Install census-mod or the census plugin, never both. Deep detail is in REFERENCE.md.
<!-- Install lines differ by repo (pip-skills vs wf-claude-market). Keep them in this block only. -->
# marketplace, inside a Claude Code session
/plugin marketplace add ppryde/pip-skills
/plugin install census-mod@pip-skills
# or load a checkout for one session
claude --plugin-dir plugins/census-mod/plugin
To load a checkout in every session, add its folder to CLAUDE_CODE_PLUGIN_DIRS under env in the account's settings.json.
claude plugin disable census@<marketplace>. /census-setup
CENSUS_MOD_STORE=~/.claude/census-shadow claude.| Command | What it does | Example | ||
|---|---|---|---|---|
| `/census-setup [off\ | style\ | budget]` | Guided setup: record, draw, style, layout, budget, PR lookup. Dialogs only; nothing goes to the model. | /census-setup |
/census-setup style | Jumps straight to the Style question only; the saved Layout is kept. Needs drawing on. | /census-setup style | ||
/census-setup budget | Jumps straight to the Budget question. Needs drawing on and a cost bar in the effective segments. | /census-setup budget | ||
/census-setup off | Stops recording and drawing. Puts a removed status line back if settings still have none. | /census-setup off | ||
/census-mod:pr-refresh | Asks gh once for this branch's open PR and records it. Does not turn gh on. | /census-mod:pr-refresh |
Answers from /census-setup are stored per account. An environment variable beats an answer, and an answer beats the default.
| Setting | Default | What it changes | |
|---|---|---|---|
| Record (setup answer) | Yes if your status line does not already record | Records sessions into the census store. | |
| 💸 Budget (setup answer) | $20 | Main-session cost budget the 💸 bar fills to. Asked only when the effective segments include cost (the Pac-Man layouts do; the Clean layouts do not, unless CENSUS_STATUSLINE_SEGMENTS adds it). Options: $10, $20 (recommended), $50, $100 or any amount. | |
| Draw (setup answer) | above the input | Draws the status line: above, below, or off. | |
🎨 Style (style) | pacman | pacman (the bars) or clean (plain text, ` | separators). A missing value means pacman`. |
| 📐 Layout (setup answer) | Full — two lines | Full, Compact (one line) or Minimal. Applies to both styles. | |
| PR lookup (setup answer) | No | Lets the mod call gh pr list. PRs the session itself opens still show. | |
CENSUS_MOD_STORE | unset | Records to this census dir instead (shadow mode). Forces shadow. | |
CENSUS_STORE | <config dir>/census | Census dir for the recorder. ~ expands. | |
CENSUS_MOD_PLACEMENT | answer, else above | above or below. Overrides the answer. | |
CENSUS_MOD_PR_HINT | unset | 1 confirms a grey PR from the prompt hint. | |
CENSUS_STATUSLINE_SEGMENTS | context,cache,limits,cost/model,git,dir,changes,pr | Segments, for both styles; overrides Style and Layout. , joins on a line, / starts the next. | |
CENSUS_STATUSLINE_MASCOT | bold ✻ in #D97757 | Mascot string, drawn as given. | |
CLAUDE_COST_BUDGET | unset | Cost budget. Overrides the saved Budget answer, which overrides the $20 default. | |
CLAUDE_PROFILE | unset | personal, home or p means a personal account; any other value means work. | |
CLAUDE_CONFIG_DIR | ~/.claude | The account's config dir. |
scripts/cli.py ingest on session events. Writes are coalesced: at most one every 2 s.-p runs and subagents are not recorded.gh runs only when the PR lookup is Yes, or once per /census-mod:pr-refresh.pr segment, such as 🔀 #12 approved, is hidden without an open PR and grey when unconfirmed.CENSUS_MOD_STORE, check census read against both dirs, then unset it.Setup asks 🎨 Style after Draw: "Pip's Pac-Man flavour" (recommended; the bars), "Dave's Nice 'n' Clean" (plain text, | separators), or "Show me", which asks again with a sample line of each. Then 📐 Layout: Full (two lines, recommended), Compact (one line) or Minimal.
Clean style layouts (sample data):
Full, two lines:
🤖 Opus 5.5 | 🧠 85k/200k 42% | 💵 $1.37 | 🕔 5h 38% 0.8x | 🗓️ 7d 12% 0.7x
📁 pip-skills | 🌿 feat/x +2 ~3 | 🔀 #187 approved
Compact, line one alone:
🤖 Opus 5.5 | 🧠 85k/200k 42% | 💵 $1.37 | 🕔 5h 38% 0.8x | 🗓️ 7d 12% 0.7x
Minimal:
🧠 42% | 🕔 5h 38% | 🗓️ 7d 12%
Notes on Clean:
0.8x) is used % ÷ the share of the window gone. Under 1.0x means under even pace.python3 (3.9 or later) and the bundled scripts/cli.py. A broken install still draws the band and logs one line./census-setup and choose to replace the status line, or disable the census plugin./census-mod:pr-refresh, or answer Yes in /census-setup.gh answer or /census-mod:pr-refresh confirms it.statusLine is still set. Remove it in /census-setup; the backup is <census dir>/census-mod.statusline.json.Other mods in this family: context-vigil-mod, agent-roster.
hooks/register.tsx 1296 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2import { COUNTER_KEEP_MS, EMPTY_COUNTERS, STORE_PREFIX, TAIL_CMD, addTurn, compacted, counterKey, DEFAULT_TTL, expiresAtMs, isWarm, parseWrites, ttlFromWrites, ttlMs, withTtl } from '../core/cache'
3import { INGEST_TIMEOUT_MS, bundledCli, censusDir, delayFor, endTimeoutMs, ingestArgv, ingestEnv } from '../core/census'
4import type { CensusEnv } from '../core/census'
5import { GH_TIMEOUT_MS, ghArgv, ghKey, parsePrList, shouldRefresh, touchesPr } from '../core/gh'
6import type { GhEntry, Why } from '../core/gh'
7import { COALESCE_MS as GIT_COALESCE_MS, GIT_DIR_ARGV, GIT_STATUS_ARGV, parseStatus, touchesGit, watchPaths, worktreeOf } from '../core/git'
8import { homeOf, joinPath } from '../core/home'
9import { HINT_CONFIRM_MS, applyPatch, gitOperationOf, hasDraftFlag, hintPrNumber, markStale, patchFor, payloadPrOf, prKey, prPrefix, repoOf, toPr } from '../core/prstate'
10import type { PrRecord } from '../core/prstate'
11import { configRoot, transcriptPathFor } from '../core/name'
12import { PYTHON_CANDIDATES, cacheLinesFromText, copyModeArgv, moveArgv, pickPython, removeArgv, titleLinesFromText } from '../core/portable'
13import { buildPayload, modelOf, rateLimitsOf } from '../core/payload'
14import type { Event } from '../core/payload'
15import { TITLE_ARGV, TITLE_TAIL_CMD, findProc, lastTitle } from '../core/registry'
16import { TONE_COLOR, draw, fit } from '../core/render'
17import { BACKUP_FILE, backupBlocks, budgetFrom, hasCostBar, CLEAN_PRESETS, isShowMe, styleFrom, placementFrom, replaceFrom, L, NO_DETECTION, PRESETS, Q, SETUP_KEY, commandIsCensus, continueAnyway, enabledCensusPlugins, effective, hasIngestBlock, parseSettings, presetFrom, recordFrom, removeStatusLine, restoreStatusLine, scriptCandidates, settingsTmp, statusLineCommand, writerActive, writersFrom, is } from '../core/setup'
18import type { Detection, Effective, Saved, Style } from '../core/setup'
19import type { Line, RenderEnv, RenderInput } from '../core/render'
20import type { Counters, RateLimit, Snap } from '../core/types'
21
22// The effectful shell: the ONLY file that touches `$`. Decisions live in ../core.
23//
24// State is module variables plus $.store (counters, gh cache): a hot reload loses the variables, and
25// session.start (which re-fires on a reload) rebuilds them. Nothing is kept in $.state, so a /clear
26// has nothing to wipe and classic.SessionStart(clear) simply binds the new session.
27
28type Env = CensusEnv & RenderEnv & { USERPROFILE?: string; CENSUS_MOD_PLACEMENT?: string; CENSUS_MOD_PR_HINT?: string }
29
30let env: Env = {} // what the mod runs on: the environment, then the answers laid over it
31let rawEnv: Env = {} // the environment alone: it outranks an answer
32let saved: Saved = {}
33let det: Detection = NO_DETECTION
34let eff: Effective = effective({}, {}, NO_DETECTION, null)
35let setupRun: object | null = null
36const titleScanned = new WeakMap<Snap, string>() // snapshot -> the transcript path whose whole file was scanned
37let offerTimer: Timer | null = null
38let interactive: boolean | null = null
39let snap: Snap | null = null
40let hydrating: Promise<void> | null = null
41let gitReady: Promise<void> | null = null // the first `git status` of the bound session, so the first write carries it
42let gitReadyDone: (() => void) | null = null
43const ended = new Set<string>()
44let lastActiveAt: number | null = null
45let limitsKey = ''
46let ingestTimer: Timer | null = null
47let lastIngestAt: number | null = null
48let pending: Event | null = null
49let coldTimer: Timer | null = null
50let tickTimer: Timer | null = null
51let gitTimer: Timer | null = null
52let lastGitAt: number | null = null
53let cli: string | null | undefined // census-mod's own bundled recorder, once found there
54let saidNoCli = false
55let python: string[] | null | undefined // the launcher that passed the Python 3.9+ probe, once; null = none found
56let shell: boolean | undefined // whether `sh` runs here (it does not on Windows)
57let saidNoGh = false
58const repoByDir = new Map<string, string | null>() // working dir -> owner/name of origin (null = none), asked once per dir
59
60const TICK_MS = 30_000
61
62async function nowMs($: EngineInterface): Promise<number> {
63 return $.clock.now()
64}
65
66async function loadEnv($: EngineInterface): Promise<Env> {
67 return {
68 CENSUS_MOD_STORE: await $.env.get('CENSUS_MOD_STORE'),
69 CENSUS_STORE: await $.env.get('CENSUS_STORE'),
70 CLAUDE_CONFIG_DIR: await $.env.get('CLAUDE_CONFIG_DIR'),
71 HOME: await $.env.get('HOME'),
72 USERPROFILE: await $.env.get('USERPROFILE'),
73 HOMEDRIVE: await $.env.get('HOMEDRIVE'),
74 HOMEPATH: await $.env.get('HOMEPATH'),
75 CENSUS_STATUSLINE_SEGMENTS: await $.env.get('CENSUS_STATUSLINE_SEGMENTS'),
76 CENSUS_MOD_PLACEMENT: await $.env.get('CENSUS_MOD_PLACEMENT'),
77 CENSUS_MOD_PR_HINT: await $.env.get('CENSUS_MOD_PR_HINT'),
78 CENSUS_STATUSLINE_MASCOT: await $.env.get('CENSUS_STATUSLINE_MASCOT'),
79 CLAUDE_COST_BUDGET: await $.env.get('CLAUDE_COST_BUDGET'),
80 CLAUDE_PROFILE: await $.env.get('CLAUDE_PROFILE'),
81 }
82}
83
84function fresh(id: string, cwd: string): Snap {
85 return {
86 sessionId: id, transcriptPath: null, cwd, worktreePath: null, version: null, model: null, sessionName: null,
87 ctxPct: null, ctxWindow: null, costUsd: null, startedAt: null, rateLimits: [],
88 counters: EMPTY_COUNTERS, ttl: DEFAULT_TTL, git: null, pr: null, proc: null,
89 }
90}
91
92const repaint = ($: EngineInterface) => void $.ui.invalidate('ui.render')
93
94// ---- engine facts -------------------------------------------------------------------------
95
96async function refreshEngine($: EngineInterface) {
97 if (!snap) return
98 const usage = await $.session.usage().catch(() => null)
99 if (usage) {
100 snap.ctxPct = usage.context.percent ?? null
101 snap.ctxWindow = usage.context.window ?? null
102 snap.costUsd = usage.cost?.usd ?? null
103 snap.startedAt = usage.startedAt
104 snap.rateLimits = usage.rateLimits as RateLimit[]
105 limitsKey = limitsFingerprint(snap.rateLimits)
106 }
107 const model = await $.session.model().catch(() => null)
108 if (model) snap.model = modelOf(model)
109}
110
111const limitsFingerprint = (l: RateLimit[]): string => l.map(x => `${x.kind}:${x.percentUsed}:${x.resetsAt ?? ''}`).sort().join('|')
112
113async function locateProc($: EngineInterface) {
114 if (!snap || snap.proc) return // looked for again on every write until found: it is one small read
115 try {
116 const root = configRoot(env)
117 if (!root) return
118 const sessions = joinPath(root, 'sessions')
119 const entries = await $.fs.list(sessions)
120 const files: { text: string }[] = []
121 for (const f of entries) {
122 if (!f.name.endsWith('.json')) continue
123 const text = await $.fs.read(joinPath(sessions, f.name)).catch(() => undefined)
124 if (typeof text === 'string') files.push({ text })
125 }
126 const proc = findProc(files, snap.sessionId)
127 if (proc) {
128 snap.proc = proc
129 snap.version = proc.version ?? snap.version
130 }
131 } catch {
132 // the registry is a nicety for liveness; recording goes on without it
133 }
134}
135
136/**
137 * The session's title from its transcript. Whole file once (at bind); after that only the tail, where a later
138 * /rename lands, so a long session is not re-read end to end on every turn. Applied to `s`, the snapshot the
139 * read was asked for, never to whatever the module holds by the time the read returns.
140 */
141async function readName($: EngineInterface, s: Snap | null = snap, whole = false) {
142 if (!s?.transcriptPath) return
143 try {
144 if (!(await hasShell($))) {
145 s.sessionName = lastTitle(titleLinesFromText(await transcriptText($, s.transcriptPath), whole ? undefined : 262144)) ?? s.sessionName
146 return
147 }
148 const argv = whole ? TITLE_ARGV(s.transcriptPath) : ['sh', '-c', TITLE_TAIL_CMD, 'sh', s.transcriptPath]
149 const r = await $.process.run(argv)
150 if (r.exitCode === 0) s.sessionName = lastTitle(r.stdout) ?? s.sessionName
151 } catch {
152 // keep the last name
153 }
154}
155
156async function readTtl($: EngineInterface, s: Snap | null = snap) {
157 if (!s?.transcriptPath) return
158 try {
159 const out = (await hasShell($))
160 ? await $.process.run(['sh', '-c', TAIL_CMD, 'sh', s.transcriptPath]).then(r => (r.exitCode === 0 ? r.stdout : ''))
161 : cacheLinesFromText(await transcriptText($, s.transcriptPath))
162 const found = out ? ttlFromWrites(parseWrites(out)) : null
163 if (found) {
164 s.ttl = found
165 s.counters = withTtl(s.counters, found)
166 }
167 } catch {
168 // keep the last known (default 5m)
169 }
170}
171
172// ---- counters (survive a reload or restart) ------------------------------------------------
173
174async function loadCounters($: EngineInterface, id: string): Promise<Counters> {
175 const stored = (await $.store.get(counterKey(id)).catch(() => undefined)) as Counters | undefined
176 return stored && typeof stored.requests === 'number' ? { ...EMPTY_COUNTERS, ...stored } : EMPTY_COUNTERS
177}
178
179async function saveCounters($: EngineInterface, s: Snap | null = snap) {
180 if (s) await $.store.set(counterKey(s.sessionId), s.counters).catch(() => undefined)
181}
182
183async function pruneCounters($: EngineInterface, keep: string, now: number) {
184 try {
185 for (const key of await $.store.keys()) {
186 if (!key.startsWith(STORE_PREFIX) || key === counterKey(keep)) continue
187 const c = (await $.store.get(key)) as Counters | undefined
188 if (!c || now - (c.updatedAt ?? 0) > COUNTER_KEEP_MS) await $.store.delete(key)
189 }
190 } catch {
191 // housekeeping only
192 }
193}
194
195// ---- recording -----------------------------------------------------------------------------
196
197/** census-mod records through its own bundled copy of census's ingest: no census plugin is ever needed or looked for. */
198async function discover($: EngineInterface): Promise<string | null> {
199 if (cli) return cli
200 let root: string | undefined
201 try {
202 root = $.plugin.root
203 } catch {
204 root = undefined
205 }
206 const path = root ? bundledCli(root) : null
207 if (path && (await $.fs.exists(path).catch(() => false))) return (cli = path)
208 if (!saidNoCli) {
209 saidNoCli = true
210 $.ui.log('census-mod\'s bundled recorder is missing (scripts/cli.py): reinstall census-mod. The band is drawn, nothing is recorded')
211 }
212 return null
213}
214
215/** `python3`, `python` or `py -3`, the first that passes the Python 3.9+ probe; asked once per process. null: none, said once in the log. */
216async function pythonLauncher($: EngineInterface, budgetMs = INGEST_TIMEOUT_MS): Promise<string[] | null> {
217 if (python !== undefined) return python
218 // Three probes share the hook's budget (a session.end has little): too little left, and the probe waits for a later ingest.
219 const probeMs = Math.min(2000, Math.floor(budgetMs / 6))
220 if (probeMs < 200) return null
221 const found = await pickPython(async argv => (await $.process.run(argv, { timeoutMs: probeMs })).exitCode === 0)
222 python = found
223 if (!python) $.ui.log('census-mod found no Python (tried python3, python, py -3): the band is drawn, nothing is recorded')
224 return python
225}
226
227/** Whether `sh` runs here; asked once per process. */
228async function hasShell($: EngineInterface): Promise<boolean> {
229 if (shell === undefined) shell = await $.process.run(['sh', '-c', 'exit 0'], { timeoutMs: 5000 }).then(r => r.exitCode === 0, () => false)
230 return shell
231}
232
233/** The transcript's text (a file over the engine's read cap reads as nothing): for where there is no sh/tail/grep. */
234let lastRead: { path: string; at: number; text: Promise<string> } | undefined
235const transcriptText = async ($: EngineInterface, path: string): Promise<string> => {
236 // The TTL and the title are read together every turn: one read serves both.
237 const now = await nowMs($)
238 if (lastRead && lastRead.path === path && now - lastRead.at < 2000) return lastRead.text
239 const text = Promise.resolve($.fs.read(path)).then(t => (typeof t === 'string' ? t : ''), () => '')
240 lastRead = { path, at: now, text }
241
242 return text
243}
244
245async function ingest($: EngineInterface, event: Event, endedReason?: string, timeoutMs = INGEST_TIMEOUT_MS, of: Snap | null = snap) {
246 if (!of) return
247 if (eff.record === 'no') return
248 const path = await discover($)
249 if (!path) return
250 const py = await pythonLauncher($, timeoutMs)
251 const payload = buildPayload(of, await nowMs($), event, endedReason)
252 const run = (launcher: readonly string[]) => $.process.run(ingestArgv(path, launcher), { stdin: JSON.stringify(payload), env: ingestEnv(env), timeoutMs })
253 try {
254 if (!py) {
255 // Not chosen yet and too little budget to probe (a session.end has about a second, and no later ingest): run the
256 // ingest itself through each launcher in turn. One that cannot be spawned (or is missing: 127, 9009) is skipped.
257 if (python !== undefined) return
258 for (const candidate of PYTHON_CANDIDATES) {
259 const out = await run(candidate).catch(() => undefined)
260 if (!out || out.exitCode === 127 || out.exitCode === 9009) continue
261 python = [...candidate]
262 if (out.exitCode !== 0) cli = undefined
263 return
264 }
265 return
266 }
267 const out = await run(py)
268 if (out.exitCode !== 0) cli = undefined // the bundle moved or broke: look again next time
269 } catch {
270 cli = undefined
271 }
272}
273
274/** Ask for an ingest. At most one per COALESCE_MS; the one that runs carries the latest state. */
275function record($: EngineInterface, event: Event) {
276 if (!interactive || !snap) return
277 pending = event
278 if (ingestTimer) return
279 void (async () => {
280 const wait = delayFor(await nowMs($), lastIngestAt)
281 if (ingestTimer) return
282 ingestTimer = $.clock.after(wait, () => void flush($).catch(() => undefined))
283 })()
284}
285
286async function flush($: EngineInterface) {
287 ingestTimer = null
288 const event = pending
289 pending = null
290 if (!event || !snap) return
291 lastIngestAt = await nowMs($)
292 await hydrating
293 // The first write waits (briefly) for the first git status, or census_mod.git would be null until the next one.
294 if (gitReady) await Promise.race([gitReady, new Promise<void>(done => $.clock.after(3000, done))])
295 await refreshEngine($)
296 await locateProc($)
297 await ingest($, event)
298}
299
300// ---- git and gh ----------------------------------------------------------------------------
301
302function scheduleGit($: EngineInterface) {
303 if (!interactive || gitTimer) return
304 void (async () => {
305 const wait = lastGitAt === null ? 0 : Math.max(0, lastGitAt + GIT_COALESCE_MS - (await nowMs($)))
306 if (gitTimer) return
307 gitTimer = $.clock.after(wait, () => void runGit($).catch(() => undefined))
308 })()
309}
310
311async function runGit($: EngineInterface) {
312 gitTimer = null
313 if (!snap) return
314 lastGitAt = await nowMs($)
315 const cwd = snap.cwd
316 const r = await $.process.run(GIT_STATUS_ARGV, { cwd }).catch(() => undefined)
317 const first = gitReadyDone
318 gitReadyDone = null
319 first?.()
320 if (!snap || snap.cwd !== cwd) return
321 const before = snap.git
322 snap.git = r && r.exitCode === 0 ? parseStatus(r.stdout) : null
323 if (before?.branch !== snap.git?.branch) {
324 snap.pr = await prFromEvents($) // a PR the mod saw on this branch (any session) draws at once; else none until gh says
325 // The first sight of a branch is not a change of it.
326 if (before !== null) record($, 'branch')
327 scheduleGh($, before === null ? 'start' : 'branch')
328 }
329 repaint($)
330}
331
332function scheduleGh($: EngineInterface, why: Why) {
333 if (!interactive || !eff.pr) return
334 $.clock.after(0, () => void refreshGh($, why).catch(() => undefined))
335}
336
337/** What a lookup came to: `answered` = gh spoke (a PR or none), `failed` = it did not and nothing changed, `skipped` = not asked. */
338type GhOutcome = 'answered' | 'failed' | 'skipped' | 'no-branch'
339
340/** `manual` (/census-mod:pr-refresh) asks once whatever the PR answer is; every other trigger needs it Yes. */
341async function refreshGh($: EngineInterface, why: Why): Promise<GhOutcome> {
342 if (!eff.pr && why !== 'manual') return 'skipped' // the PR answer is No (the default): gh is never called on its own
343 await hydrating // the worktree path gh runs in is read there
344 if (!snap?.git?.branch || snap.git.detached) return 'no-branch'
345 const key = ghKey(snap.worktreePath ?? snap.cwd, snap.git.branch)
346 const branch = snap.git.branch
347 const now = await nowMs($)
348 const cached = (await $.store.get(key).catch(() => undefined)) as GhEntry | undefined
349 if (cached) {
350 const recorded = await recordedPr($)
351 snap.pr = recorded === undefined ? cached.pr : recorded
352 } // a record that says "not open" (null) beats the gh cache; no record (undefined) falls back to it
353 if (!shouldRefresh(why, cached, now, lastActiveAt)) return 'skipped'
354 const before = snap.pr
355 let entry: GhEntry
356 let answered = false
357 try {
358 const r = await $.process.run(ghArgv(branch), { cwd: snap.worktreePath ?? snap.cwd, timeoutMs: GH_TIMEOUT_MS })
359 const pr = r.exitCode === 0 ? parsePrList(r.stdout) : undefined
360 entry = pr === undefined ? { at: cached?.at ?? 0, pr: cached?.pr ?? null, failedAt: now } : { at: now, pr }
361 answered = pr !== undefined
362 } catch {
363 if (!saidNoGh) {
364 saidNoGh = true
365 $.ui.log('gh unavailable: no PR segment (is gh installed and logged in?)')
366 }
367 entry = { at: cached?.at ?? 0, pr: cached?.pr ?? null, failedAt: now }
368 }
369 await $.store.set(key, entry).catch(() => undefined)
370 if (!snap || snap.git?.branch !== branch) return answered ? 'answered' : 'failed'
371 // Only an answer is a word about the PR: a failed or backed-off gh must not reopen or refresh a record.
372 if (answered) await recordGhAnswer($, branch, entry, now)
373 // One precedence decides every draw (events > status-line pr > gh), as on the tick; no record falls back to the cache.
374 const recorded = await recordedPr($)
375 if (!snap) return answered ? 'answered' : 'failed'
376 snap.pr = recorded === undefined ? entry.pr : recorded
377 if (before?.number !== snap.pr?.number || before?.reviewState !== snap.pr?.reviewState) record($, 'pr')
378 repaint($)
379
380 return answered ? 'answered' : 'failed'
381}
382
383// ---- PR state from tool events (WF-269) ---------------------------------------------------------
384// The engine reports `gitOperation` on a Bash result: a created, readied, closed or merged PR and a push. That is
385// kept per repo+branch in $.store (shared by every session of the account), so the PR segment needs no gh call and
386// works with the PR setting off. gh, where it is on, only adds the review state and what happened outside the session.
387
388/** `owner/name` of the origin of the directory the session works in; null when there is none. Asked once per directory. */
389async function repoName($: EngineInterface): Promise<string | null> {
390 if (!snap) return null
391 const dir = snap.worktreePath ?? snap.cwd
392 if (repoByDir.has(dir)) return repoByDir.get(dir) ?? null
393 const r = await $.process.run(['git', 'remote', 'get-url', 'origin'], { cwd: dir, timeoutMs: 5000 }).catch(() => undefined)
394 const repo = r && r.exitCode === 0 ? repoOf(r.stdout) : null
395 repoByDir.set(dir, repo)
396
397 return repo
398}
399
400const currentBranch = (): string | null => (snap?.git?.branch && !snap.git.detached ? snap.git.branch : null)
401
402async function readRecord($: EngineInterface, key: string): Promise<PrRecord | undefined> {
403 const got = (await $.store.get(key).catch(() => undefined)) as PrRecord | undefined
404
405 return got && typeof got === 'object' && typeof got.number === 'number' ? got : undefined
406}
407
408/** The drawn PR of the current branch from its record; null when the record says none; undefined when there is no record. */
409async function recordedPr($: EngineInterface): Promise<Snap['pr'] | undefined> {
410 const branch = currentBranch()
411 if (!branch) return undefined
412 const repo = await repoName($)
413 const rec = repo ? await readRecord($, prKey(repo, branch)) : undefined
414 const now = await nowMs($)
415 // The session's own events outrank the status-line payload's pr, which outranks gh.
416 if (rec?.source === 'event') return toPr(rec, now)
417 const line = await payloadPr($, branch, now)
418 if (line) return line
419
420 return rec ? toPr(rec, now) : undefined
421}
422
423/** The pr a status-line COMMAND wrote into this session's census record (census's ingest keeps it as `status_line_pr`). */
424async function payloadPr($: EngineInterface, branch: string, now: number): Promise<Snap['pr']> {
425 const sid = snap?.sessionId
426 const dir = censusDir(rawEnv)
427 if (!sid || !dir || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sid)) return null
428 const text = await $.fs.read(joinPath(dir, 'sessions', `${sid}.json`)).catch(() => undefined)
429
430 return typeof text === 'string' ? payloadPrOf(text, now, branch) : null
431}
432
433/** The drawn PR of the current branch from its record; null when the record says none (or there is none). */
434async function prFromEvents($: EngineInterface): Promise<Snap['pr']> {
435 return (await recordedPr($)) ?? null
436}
437
438/** Every record of the repo, so a PR can be found by number whatever branch the command ran on. */
439async function recordsOf($: EngineInterface, repo: string): Promise<{ key: string; rec: PrRecord }[]> {
440 const keys = ((await $.store.keys().catch(() => [])) as string[]).filter(k => k.startsWith(prPrefix(repo)))
441 const out: { key: string; rec: PrRecord }[] = []
442 for (const key of keys) {
443 const rec = await readRecord($, key)
444 if (rec) out.push({ key, rec })
445 }
446
447 return out
448}
449
450/** Re-derive the snapshot's PR after a record moved, and record the change. */
451async function pushPrToSnap($: EngineInterface, always = true) {
452 if (!snap) return
453 const before = snap.pr
454 const after = await prFromEvents($)
455 if (!snap) return
456 snap.pr = after
457 const changed = before?.number !== after?.number || before?.reviewState !== after?.reviewState || before?.stale !== after?.stale
458 if (changed) record($, 'pr')
459 if (always || changed) repaint($)
460}
461
462/** One Bash result's `gitOperation`: a PR action updates (or, when created, starts) the record; a push marks it stale. */
463async function applyGitOperation($: EngineInterface, result: unknown, command: string) {
464 const op = gitOperationOf(result)
465 if (!op || !snap) return
466 const repo = await repoName($)
467 if (!repo || !snap) return
468 const now = await nowMs($)
469 const ctx = { sessionId: snap.sessionId, worktree: snap.worktreePath ?? snap.cwd }
470 if (op.pr) {
471 const all = await recordsOf($, repo)
472 const byNumber = all.filter(r => r.rec.number === op.pr!.number).sort((a, b) => b.rec.at - a.rec.at)[0]
473 const branch = currentBranch()
474 // By number first; the current branch only for a creation (`gh pr close N` can run from any branch).
475 const key = byNumber?.key ?? (op.pr.action === 'created' && branch ? prKey(repo, branch) : null)
476 if (key) {
477 const next = applyPatch(byNumber?.rec, patchFor(op.pr, hasDraftFlag(command)), now, ctx)
478 if (next) await $.store.set(key, next).catch(() => undefined)
479 }
480 }
481 if (op.push) {
482 const key = prKey(repo, op.push.branch)
483 const old = await readRecord($, key)
484 if (old) await $.store.set(key, markStale(old)).catch(() => undefined)
485 }
486 await pushPrToSnap($)
487}
488
489/** gh's answer for the branch, as the newest word in its record. An empty answer closes an event record only once it has had time to be listed. */
490async function recordGhAnswer($: EngineInterface, branch: string, entry: GhEntry, now: number): Promise<void> {
491 const repo = await repoName($)
492 if (!repo) return
493 const key = prKey(repo, branch)
494 const old = await readRecord($, key)
495 const ctx = { sessionId: snap?.sessionId ?? '', worktree: snap?.worktreePath ?? snap?.cwd ?? '', source: 'gh' as const }
496 let next: PrRecord | undefined = old
497 if (entry.pr) {
498 next = applyPatch(old, { number: entry.pr.number, ...(entry.pr.url ? { url: entry.pr.url } : {}), state: 'open', ...(entry.pr.reviewState ? { review: entry.pr.reviewState } : old?.review === 'draft' || old?.review === 'pending' ? { review: null } : {}), lastAction: 'gh' }, now, ctx)
499 } else if (old && old.state === 'open' && !(old.source === 'event' && now - old.at < GH_LISTING_GRACE_MS)) {
500 next = applyPatch(old, { number: old.number, state: 'closed', lastAction: 'gh' }, now, ctx)
501 }
502 if (next && next !== old) await $.store.set(key, next).catch(() => undefined)
503}
504
505const GH_LISTING_GRACE_MS = 2 * 60_000
506
507async function readGitDir($: EngineInterface, cwd: string) {
508 return $.process.run(GIT_DIR_ARGV, { cwd }).then(r => ({ exitCode: r.exitCode, stdout: r.stdout })).catch(() => ({ exitCode: 1, stdout: '' }))
509}
510
511/**
512 * Opt-in (CENSUS_MOD_PR_HINT): the engine's prompt hint names the branch's open PR as `PR #N`. That is the engine's own
513 * word, so it confirms an OPEN record of that number (clears "unconfirmed", keeps the record's own source) and nothing
514 * else: it never closes or reopens one (the hint lags a close by seconds), and never starts one (it carries no url).
515 */
516let hintConfirmedAt = 0
517async function confirmFromHint($: EngineInterface, hint: unknown) {
518 const number = hintPrNumber(hint)
519 const branch = currentBranch()
520 if (number === null || !branch || !snap) return
521 const now = await nowMs($)
522 if (now - hintConfirmedAt < HINT_CONFIRM_MS) return
523 const repo = await repoName($)
524 if (!repo || !snap) return
525 const key = prKey(repo, branch)
526 const old = await readRecord($, key)
527 if (!old || old.number !== number || old.state !== 'open') return
528 hintConfirmedAt = now
529 if (!old.stale && now - old.at < HINT_CONFIRM_MS) return
530 const ctx = { sessionId: snap.sessionId, worktree: snap.worktreePath ?? snap.cwd, source: old.source }
531 const next = applyPatch(old, { number, state: 'open', lastAction: 'hint' }, now, ctx)
532 if (next) await $.store.set(key, next).catch(() => undefined)
533 await pushPrToSnap($)
534}
535
536// ---- lifecycle -----------------------------------------------------------------------------
537
538function cancelTimers() {
539 for (const t of [ingestTimer, coldTimer, tickTimer, gitTimer, offerTimer]) t?.cancel()
540 ingestTimer = coldTimer = tickTimer = gitTimer = offerTimer = null
541}
542
543function armCold($: EngineInterface) {
544 coldTimer?.cancel()
545 coldTimer = null
546 if (!snap) return
547 const at = expiresAtMs(snap.counters, snap.ttl)
548 if (at === null || snap.counters.cold) return
549 void (async () => {
550 const wait = at - (await nowMs($))
551 if (wait <= 0 || !snap) return
552 coldTimer = $.clock.after(wait, () => {
553 coldTimer = null
554 repaint($)
555 record($, 'cache.cold')
556 })
557 })()
558}
559
560function armTimers($: EngineInterface) {
561 tickTimer?.cancel()
562 // Countdowns only: redraws, never records.
563 tickTimer = $.clock.every(TICK_MS, () => {
564 repaint($)
565 scheduleGh($, 'age')
566 void pushPrToSnap($, false).catch(() => undefined) // a status-line command may have written a pr since
567 })
568 armCold($)
569}
570
571/** The git dir (worktree) and the session name: shell-outs kept off the start hooks' path. The first write waits for them. */
572function hydrate($: EngineInterface, known?: { exitCode: number; stdout: string }) {
573 hydrating = new Promise<void>(done => {
574 $.clock.after(0, () => {
575 void (async () => {
576 await loadSetup($)
577 if (!snap) return
578 const gitDir = known ?? (await readGitDir($, snap.cwd))
579 if (snap) snap.worktreePath = worktreeOf(gitDir)
580 const scanned = snap ? titleScanned.get(snap) : undefined
581 if (snap) titleScanned.set(snap, snap.transcriptPath ?? '')
582 await readName($, snap, scanned !== snap?.transcriptPath)
583 repaint($)
584 offerOnce($)
585 })()
586 .catch(() => undefined)
587 .finally(done)
588 })
589 })
590}
591
592/** An ended record for a session this process is leaving, from its last snapshot; once per session. */
593function closeOld($: EngineInterface, old: Snap | null, why: string) {
594 if (!old || ended.has(old.sessionId)) return
595 ended.add(old.sessionId)
596 $.clock.after(0, () => void ingest($, 'session.end', why, INGEST_TIMEOUT_MS, old).catch(() => undefined))
597}
598
599/** (Re)bind the live state to a session. Idempotent: a reload or a repeated start finds it bound. */
600async function bind($: EngineInterface, id: string, cwd: string, transcript: string | null, event: Event, gitDir?: { exitCode: number; stdout: string }) {
601 const same = snap?.sessionId === id
602 ended.delete(id) // a resumed id is live again
603 if (!same) {
604 const old = snap
605 snap = fresh(id, cwd)
606 limitsKey = ''
607 lastGitAt = null // a new session's first git status is not held back by the old one's
608 if (old && event !== 'session.start') {
609 closeOld($, old, event.replace('session.', ''))
610 setupRun = null // an open setup dialog belongs to the session that is gone
611 }
612 cancelTimers()
613 pending = null
614 snap.counters = await loadCounters($, id)
615 snap.ttl = snap.counters.ttl ?? DEFAULT_TTL
616 }
617 if (!snap) return
618 const root = configRoot(env)
619 snap.transcriptPath = transcript ?? snap.transcriptPath ?? (root ? transcriptPathFor(root, snap.cwd, id) : null)
620 await refreshEngine($)
621 await locateProc($)
622 hydrate($, gitDir)
623 armTimers($)
624 if (!same || !gitReady) gitReady = new Promise<void>(done => { gitReadyDone = done })
625 scheduleGit($)
626 record($, event)
627 void pruneCounters($, id, await nowMs($))
628}
629
630async function isInteractive($: EngineInterface): Promise<boolean> {
631 if (interactive !== null) return interactive
632 return (await $.session.surfaces().catch(() => [])).length > 0
633}
634
635// ---- /census-setup -------------------------------------------------------------------------------------
636//
637// Asks through $.ui.ask, one question at a time: nothing is submitted, nothing reaches the model, and a
638// phone can answer. Each answer is saved the moment it is given, so a /clear or a dismissal loses only
639// what was not yet asked. The precedence is the environment, then these answers, then the defaults.
640
641async function loadSetup($: EngineInterface) {
642 saved = ((await $.store.get(SETUP_KEY).catch(() => undefined)) as Saved | undefined) ?? {}
643 det = await detect($)
644 applyEffective($)
645}
646
647function applyEffective($: EngineInterface) {
648 const before = env.CENSUS_MOD_STORE
649 eff = effective(saved, rawEnv, det, configRoot(rawEnv))
650 env = { ...rawEnv, CENSUS_MOD_STORE: eff.shadowDir ?? undefined, CENSUS_STATUSLINE_SEGMENTS: eff.segments, CLAUDE_COST_BUDGET: String(eff.budget) }
651 repaint($)
652}
653
654async function saveAnswer($: EngineInterface, patch: Partial<Saved>) {
655 saved = { ...saved, ...patch }
656 await $.store.set(SETUP_KEY, saved).catch(() => undefined)
657 applyEffective($)
658}
659
660const settingsPath = (): string | null => {
661 const root = configRoot(rawEnv)
662 return root ? joinPath(root, 'settings.json') : null
663}
664const realCensusDir = (): string | null => censusDir(rawEnv)
665
666/** Step 1 of setup, no questions: this account's status line, any other writer, whether the census plugin is enabled. */
667async function detect($: EngineInterface): Promise<Detection> {
668 const out: Detection = { ...NO_DETECTION }
669 try {
670 const path = settingsPath()
671 const text = path ? await $.fs.read(path).catch(() => undefined) : undefined
672 if (typeof text === 'string') {
673 const parsed = parseSettings(text)
674 if (!parsed.ok) out.settingsInvalid = true
675 else {
676 out.censusPlugins = enabledCensusPlugins(parsed.data)
677 const command = statusLineCommand(parsed.data)
678 out.statusLineCommand = command
679 if (command) {
680 out.ingestBlock = commandIsCensus(command)
681 for (const file of scriptCandidates(command, homeOf(rawEnv) ?? undefined, rawEnv.USERPROFILE)) {
682 const script = await $.fs.read(file).catch(() => undefined)
683 if (typeof script === 'string' && hasIngestBlock(script)) out.ingestBlock = true
684 }
685 }
686 }
687 }
688 const dir = realCensusDir()
689 if (dir) {
690 const files = ((await $.fs.list(joinPath(dir, 'sessions')).catch(() => [])) as { name: string; mtimeMs: number }[])
691 .filter(f => f.name.endsWith('.json'))
692 .sort((a, b) => b.mtimeMs - a.mtimeMs)
693 .slice(0, 20)
694 const entries: { updatedAt: number; hasCensusMod: boolean }[] = []
695 for (const f of files) {
696 const body = await $.fs.read(joinPath(dir, 'sessions', f.name)).catch(() => undefined)
697 try {
698 const d = JSON.parse(typeof body === 'string' ? body : '{}') as { updated_at?: number; payload?: { census_mod?: unknown } }
699 if (typeof d.updated_at === 'number') entries.push({ updatedAt: d.updated_at * 1000, hasCensusMod: d.payload?.census_mod !== undefined })
700 } catch {
701 // a file caught mid-write
702 }
703 }
704 out.otherWriter = writerActive(entries, await nowMs($))
705 }
706 } catch {
707 // detection is advice; setup goes on with what it has
708 }
709 return out
710}
711
712function say($: EngineInterface, headline: string, lines: string[] = []) {
713 $.ui.toast(headline)
714 for (const l of [headline, ...lines]) $.ui.log(l)
715}
716
717/** Remove a file. Windows has no argv-only delete, so there it is emptied, and an empty backup reads as none. */
718const removeFile = async ($: EngineInterface, path: string): Promise<void> => {
719 const argv = removeArgv(path)
720 if (argv) await $.process.run(argv).catch(() => undefined)
721 else await $.fs.write(path, '').catch(() => undefined)
722}
723
724/** The backup's text; an emptied one (Windows) is no backup. */
725const readBackup = async ($: EngineInterface, path: string): Promise<string | null> => {
726 const text = (await $.fs.read(path).catch(() => undefined)) as string | undefined
727
728 return typeof text === 'string' && text.trim() ? text : null
729}
730
731/**
732 * Write `text` over `path`, which `expected` is the text it was derived from. Nothing is written when the file no
733 * longer holds `expected` (Claude Code or another session changed it since we read it): their edit is never lost.
734 * POSIX: a unique temp file beside the target (started as a copy so the mode survives), re-checked, then renamed
735 * over it, so a reader never sees half a file. Windows has no rename to call (cmd would parse the path), so the
736 * file is written in place, read back, and put back as it was if what is there is not what we wrote.
737 */
738const writeSettings = async ($: EngineInterface, path: string, text: string, expected: string): Promise<boolean> => {
739 // Through a symlink to its target (a dotfiles repo), never replacing the link.
740 const target = (await $.fs.stat(path, { resolve: true }).catch(() => undefined))?.realPath ?? path
741 const unchanged = async (): Promise<boolean> => (await $.fs.read(target).catch(() => undefined)) === expected
742 if (!moveArgv(path, target)) {
743 if (!(await unchanged())) return false
744 try {
745 await $.fs.write(target, text)
746 if ((await $.fs.read(target).catch(() => undefined)) === text) return true
747 } catch {
748 // fall through to the put-back
749 }
750 await $.fs.write(target, expected).catch(() => undefined) // a torn write: the file as it was
751 return false
752 }
753 const tmp = settingsTmp(target, `${(await $.session.id().catch(() => 'x')).slice(0, 8)}-${await nowMs($)}`)
754 try {
755 const copy = copyModeArgv(target, tmp) // keeps the mode on POSIX; a Windows file has none
756 if (copy) await $.process.run(copy).catch(() => undefined)
757 await $.fs.write(tmp, text)
758 if (await unchanged()) {
759 const mv = await $.process.run(moveArgv(tmp, target)!)
760 if (mv.exitCode === 0) return true
761 }
762 } catch {
763 // fall through to the cleanup
764 }
765 await removeFile($, tmp)
766 return false
767}
768
769/** Remove this account's statusLine for the band to replace; false (and a message) when it was left alone. */
770async function removeOwnStatusLine($: EngineInterface): Promise<{ done: boolean; backup?: string }> {
771 const path = settingsPath()
772 const dir = realCensusDir()
773 if (!path || !dir) return { done: false }
774 const text = await $.fs.read(path).catch(() => undefined)
775 if (typeof text !== 'string') return { done: false }
776 const r = removeStatusLine(text, path, new Date(await nowMs($)).toISOString())
777 if (!r.ok) {
778 if (r.reason === 'invalid') say($, `🧭 census-setup: ${path} is not valid JSON, so I left your status line alone`)
779 return { done: r.reason === 'none' }
780 }
781 const backup = joinPath(dir, BACKUP_FILE)
782 const existing = await readBackup($, backup)
783 if (backupBlocks(existing, r.backup)) {
784 say($, `🧭 census-setup: the backup already holds a different status line (${backup}), so I left your status line alone`)
785 return { done: false }
786 }
787 try {
788 await $.fs.write(backup, r.backup) // first: the removal is undoable before it happens
789 } catch {
790 say($, `🧭 census-setup: could not write the backup ${backup}, so I left your status line alone`)
791 return { done: false }
792 }
793 if (!(await writeSettings($, path, r.text, text))) {
794 say($, `🧭 census-setup: could not write ${path}, so I left your status line alone`)
795 return { done: false }
796 }
797 return { done: true, backup }
798}
799
800/** `/census-setup off`: stop recording and drawing, and put a status line we removed back exactly. */
801async function turnOff($: EngineInterface) {
802 await saveAnswer($, { record: 'no', draw: false, answeredAt: await nowMs($), offered: true })
803 const lines: string[] = ['recording: off', 'band: off']
804 const path = settingsPath()
805 const dir = realCensusDir()
806 const backupPath = dir ? joinPath(dir, BACKUP_FILE) : null
807 const backup = backupPath ? await readBackup($, backupPath) : null
808 if (path && backupPath && backup !== null) {
809 const text = await $.fs.read(path).catch(() => undefined)
810 const r = restoreStatusLine(typeof text === 'string' ? text : '', backup)
811 if (r.done === 'restored') {
812 if (await writeSettings($, path, r.text, typeof text === 'string' ? text : '')) {
813 await removeFile($, backupPath)
814 lines.push(`your status line is back in ${path}`)
815 } else lines.push(`could not write ${path}: your status line is still backed up in ${backupPath}`)
816 } else if (r.done === 'already') {
817 await removeFile($, backupPath)
818 lines.push('your status line is already in place')
819 } else lines.push(`left ${path} alone (${r.why === 'present' ? 'it has a different status line now' : r.why === 'invalid' ? 'it is not valid JSON' : 'no usable backup'}); the backup stays in ${backupPath}`)
820 }
821 say($, '🧭 census-mod is off', [...lines, 'run /census-setup to turn it on again'])
822}
823
824type Answer = { a: string } | 'dismissed' | 'superseded'
825
826async function askOne($: EngineInterface, run: object, q: { header: string; question: string; options: string[] }): Promise<Answer> {
827 const got = await $.ui.ask(q.question, { header: q.header, options: q.options }).then(a => ({ a: String(a) }), () => null)
828 if (setupRun !== run) return 'superseded' // a /clear or another setup took over while the dialog was open
829 return got ?? 'dismissed'
830}
831
832/** The 💸 budget question: asked again until the answer is a positive number. */
833async function askBudget($: EngineInterface, run: object): Promise<Answer | null> {
834 for (let retry = false; ; retry = true) {
835 const a = await askOne($, run, Q.budget(retry))
836 if (typeof a !== 'object') return a
837 const budget = budgetFrom(a.a)
838 if (budget === null) continue
839 await saveAnswer($, { budget })
840 return null
841 }
842}
843
844/**
845 * The 🎨 style question. Show me asks again with both samples (the ask call takes labels, not previews).
846 * Returns the style, or why it stopped. The saved layout is left alone.
847 */
848async function askStyle($: EngineInterface, run: object): Promise<{ style: Style } | Answer> {
849 for (let showMe = false; ; showMe = true) {
850 const a = await askOne($, run, Q.style(showMe))
851 if (typeof a !== 'object') return a
852 if (isShowMe(a.a)) continue
853 const style = styleFrom(a.a) ?? 'pacman'
854 await saveAnswer($, { style })
855 return { style }
856 }
857}
858
859/** The 📐 layout question (either style has all three). Returns null, or why it stopped. */
860async function askLayout($: EngineInterface, run: object): Promise<Answer | null> {
861 const l = await askOne($, run, Q.preset())
862 if (typeof l !== 'object') return l
863 await saveAnswer($, { preset: presetFrom(l.a) ?? 'two' })
864 return null
865}
866
867/** `/census-setup style` or `budget`: only that question, and only where the line is drawn. */
868async function setupOne($: EngineInterface, run: object, only: 'style' | 'budget') {
869 await loadSetup($)
870 if (!eff.draw) {
871 say($, `🧭 census-setup: draw is off, so there is no ${only === 'budget' ? 'cost bar' : 'band'} to ${only === 'budget' ? 'size' : 'style'}. Run /census-setup to turn the status line on`)
872 if (setupRun === run) setupRun = null
873 return
874 }
875 if (only === 'budget' && !hasCostBar(eff)) {
876 say($, '🧭 census-setup: the status line has no cost bar (the style or layout leaves it out), so there is no budget to set. Run /census-setup style to change the style')
877 if (setupRun === run) setupRun = null
878 return
879 }
880 const got = only === 'style' ? await askStyle($, run) : await askBudget($, run)
881 if (got === 'superseded') return
882 if (setupRun === run) setupRun = null
883 if (got === 'dismissed') say($, '🧭 census-setup stopped; what you answered is saved')
884 else say($, only === 'style' ? `🧭 census-mod: style is ${eff.style === 'clean' ? "Dave's Nice 'n' Clean" : "Pip's Pac-Man flavour"}` : `🧭 census-mod: the cost bar fills at $${eff.budget}${rawEnv.CLAUDE_COST_BUDGET?.trim() ? ' (CLAUDE_COST_BUDGET overrides this)' : ''}`)
885}
886
887async function setup($: EngineInterface, run: object, mode: 'full' | 'offer') {
888 await loadSetup($)
889 if (!saved.offered) await saveAnswer($, { offered: true }) // asked, so never offered again, whatever the answer
890 const stop = async (why: Answer) => {
891 if (why === 'dismissed') say($, '🧭 census-setup stopped; what you answered is saved. Run /census-setup to carry on')
892 if (setupRun === run) setupRun = null
893 }
894 if (mode === 'offer') {
895 await saveAnswer($, { offered: true })
896 const a = await askOne($, run, Q.offer())
897 if (typeof a !== 'object' || !is(a.a, L.offerYes)) {
898 if (setupRun === run) setupRun = null // not now, or dismissed: the defaults stand and it is not offered again
899 return
900 }
901 }
902 // step 1, no questions
903 const d = det
904 say($, '🧭 census-setup: looking around', [
905 `status line: ${d.statusLineCommand ?? 'none'}${d.ingestBlock ? ' (it records into census)' : ''}${d.settingsInvalid ? ' (settings.json is not valid JSON)' : ''}`,
906 `another writer on the store: ${d.otherWriter ? 'yes, active in the last few minutes' : 'no'}`,
907 `the census plugin: ${d.censusPlugins.length ? `enabled (${d.censusPlugins.join(', ')})` : 'not enabled'}`,
908 ])
909 // census and census-mod are alternatives: with the census plugin enabled there would be two writers on one store.
910 if (d.censusPlugins.length) {
911 const a = await askOne($, run, Q.exclusive(d.censusPlugins))
912 if (typeof a !== 'object') return stop(a)
913 if (!continueAnyway(a.a)) {
914 say($, `🧭 census-setup: census-mod replaces the census plugin — disable it first: ${d.censusPlugins.map(k => `claude plugin disable ${k}`).join('; ')}. Then run /census-setup again`)
915 if (setupRun === run) setupRun = null
916 return
917 }
918 say($, '🧭 census-setup: continuing with the census plugin still enabled — two writers on one store; expect muddled liveness')
919 }
920 let recordMode: 'yes' | 'shadow' | 'no' | null = null
921 let replace = false
922 if (recordMode === null) {
923 const a = await askOne($, run, Q.record(d, Boolean(rawEnv.CENSUS_MOD_STORE?.trim())))
924 if (typeof a !== 'object') return stop(a)
925 recordMode = recordFrom(a.a) ?? 'no'
926 replace = replaceFrom(a.a)
927 await saveAnswer($, { record: recordMode })
928 }
929 // Replacing the status line means census-mod must draw: only ask where.
930 const band = await askOne($, run, replace ? Q.place() : Q.draw())
931 if (typeof band !== 'object') return stop(band)
932 const placement = placementFrom(band.a)
933 const drawOn = placement !== null
934 await saveAnswer($, placement ? { draw: true, placement } : { draw: false })
935 // CENSUS_MOD_STORE outranks the answer: census-mod records to the shadow store, so the status line is still the
936 // real store's only writer. Removing it would stop that store before the comparison is done.
937 const shadowByEnv = Boolean(rawEnv.CENSUS_MOD_STORE?.trim())
938 const keptForShadow = shadowByEnv && recordMode === 'yes' && d.ingestBlock
939 let removed: string | undefined
940 if (recordMode === 'yes' && d.ingestBlock && !shadowByEnv) {
941 let choice: ReturnType<typeof writersFrom>
942 if (replace && drawOn) choice = 'remove'
943 else {
944 const a = await askOne($, run, Q.writers(drawOn, d.otherWriter))
945 if (typeof a !== 'object') return stop(a)
946 choice = writersFrom(a.a)
947 }
948 if (choice === 'remove') {
949 const r = await removeOwnStatusLine($)
950 if (r.done) {
951 removed = r.backup
952 det = await detect($)
953 } else {
954 recordMode = 'no'
955 await saveAnswer($, { record: recordMode })
956 }
957 } else if (choice === 'keep') {
958 recordMode = 'no'
959 await saveAnswer($, { record: recordMode })
960 }
961 }
962 if (recordMode === 'no' && !drawOn) {
963 await turnOff($)
964 if (setupRun === run) setupRun = null
965 return
966 }
967 let preset = saved.preset
968 if (drawOn) {
969 const st = await askStyle($, run)
970 if (typeof st !== 'object' || !('style' in st)) return stop(st)
971 const lay = await askLayout($, run)
972 if (lay) return stop(lay)
973 preset = saved.preset
974 if (hasCostBar(eff)) {
975 const stopped = await askBudget($, run) // only where the effective segments draw the cost bar
976 if (stopped) return stop(stopped)
977 }
978 }
979 const pr = await askOne($, run, Q.pr())
980 if (typeof pr !== 'object') return stop(pr)
981 await saveAnswer($, { pr: is(pr.a, L.prYes), answeredAt: await nowMs($), offered: true })
982 if (setupRun !== run) return
983 setupRun = null
984 say($, '🧭 census-mod is set up', [
985 `recording: ${eff.record === 'yes' ? 'into census (the real store)' : eff.record === 'shadow' ? `shadow store ${eff.shadowDir ?? ''} — the dashboards do not read it; run /census-setup and answer Yes to record into census itself` : 'off'}`,
986 `band: ${drawOn ? `on, ${eff.placement === 'below' ? 'below the input' : 'above the input'}, ${eff.style === 'clean' ? `Dave's Nice 'n' Clean, ${CLEAN_PRESETS[preset ?? 'two']}` : PRESETS[preset ?? 'two']}` : 'off'}${rawEnv.CENSUS_STATUSLINE_SEGMENTS?.trim() ? ' (CENSUS_STATUSLINE_SEGMENTS overrides the layout)' : ''}`,
987 ...(drawOn && hasCostBar(eff) ? [`cost bar: fills at $${eff.budget}${rawEnv.CLAUDE_COST_BUDGET?.trim() ? ' (CLAUDE_COST_BUDGET overrides your answer)' : ''}`] : []),
988 `PR segment: ${eff.pr ? 'on, with gh lookups' : 'gh is never called (run /census-mod:pr-refresh to ask it once); PRs this session creates, readies or merges still show'}`,
989 ...(removed ? [`your status line was removed from settings.json; it is backed up in ${removed}`] : []),
990 ...(keptForShadow ? ['your status line was kept: CENSUS_MOD_STORE makes census-mod record to a shadow store, so the status line is still the real store\'s writer. Unset it and run /census-setup again to replace it'] : []),
991 'undo any time: /census-setup off (it restores a removed status line exactly), or /census-setup to answer again',
992 ])
993}
994
995function startSetup($: EngineInterface, mode: 'full' | 'offer' | 'budget' | 'style') {
996 const run = {}
997 setupRun = run
998 // After the command has replied: the dialogs follow it rather than holding it open.
999 $.clock.after(0, () => void (mode === 'budget' || mode === 'style' ? setupOne($, run, mode) : setup($, run, mode)).catch(() => { if (setupRun === run) setupRun = null }))
1000}
1001
1002/** The first session after install: say so once, ever. An answer or a dismissal both count. */
1003function offerOnce($: EngineInterface) {
1004 if (saved.offered || setupRun || !interactive || offerTimer) return
1005 const id = snap?.sessionId
1006 offerTimer = $.clock.after(3000, () => {
1007 offerTimer = null
1008 // A quick exit (or a /clear) in between: there is no session left to ask in.
1009 if (saved.offered || setupRun || !id || snap?.sessionId !== id) return
1010 startSetup($, 'offer')
1011 })
1012}
1013
1014const DEFAULT_COLUMNS = 100
1015
1016/** The status line as runs, from the live snapshot: the same lines whichever site draws them. */
1017async function statusLines($: EngineInterface): Promise<Line[]> {
1018 if (!snap) return []
1019 const now = (await nowMs($)) / 1000
1020 const c = snap.counters
1021 const expires = expiresAtMs(c, snap.ttl)
1022 const input: RenderInput = {
1023 now,
1024 ctxPct: snap.ctxPct,
1025 ctxWindow: snap.ctxWindow,
1026 cache: { hitRatio: c.lastRatio, requests: c.requests, warm: isWarm(c, snap.ttl, now * 1000), expiresAt: expires === null ? null : expires / 1000, misses: 0 },
1027 limits: rateLimitsOf(snap.rateLimits),
1028 costUsd: snap.costUsd,
1029 durationMs: snap.startedAt === null ? null : now * 1000 - snap.startedAt,
1030 modelName: snap.model?.display_name ?? null,
1031 git: snap.git,
1032 pr: snap.pr,
1033 cwd: snap.worktreePath ?? snap.cwd,
1034 env,
1035 }
1036 return draw(input)
1037}
1038
1039/** One <Box> row per line, a <Text> per coloured run. */
1040function statusRows($: EngineInterface, e: Parameters<typeof $.ui.resolve>[0], lines: Line[]) {
1041 const { Box, Text } = $.ui.resolve(e)
1042 return lines.map((line, i) => (
1043 <Box key={`census-${i}`}>
1044 {line.map((run, j) => (
1045 <Text key={`r${j}`} color={run.tone ? TONE_COLOR[run.tone] : undefined} bold={run.bold} wrap="truncate-end">
1046 {run.t}
1047 </Text>
1048 ))}
1049 </Box>
1050 ))
1051}
1052
1053/** Our work after `next`: whatever it throws must not cost the other mods their result. */
1054async function quietly(work: () => Promise<void>): Promise<void> {
1055 try {
1056 await work()
1057 } catch {
1058 // recording is best-effort; the session carries on
1059 }
1060}
1061
1062export const register: Register = on => {
1063 on('session.start', async ($, e, next) => {
1064 const r = await next(e)
1065 interactive = e.isInteractive
1066 if (!interactive) return r
1067 await quietly(async () => {
1068 await $.command.register({ name: 'census-setup', description: 'Guided census-mod setup: record, draw, style, layout, cost budget, gh. `style` or `budget` asks only that question; `off` stops it.', argumentHint: '[off|style|budget]' }).catch(() => undefined)
1069 await $.command.register({ name: 'pr-refresh', description: "Ask gh once for this branch's open PR (number, review state) and record it." }).catch(() => undefined)
1070 rawEnv = await loadEnv($)
1071 env = { ...rawEnv }
1072 await bind($, await $.session.id(), e.cwd, null, 'session.start')
1073 })
1074 return r
1075 })
1076
1077 // Every source: startup, resume, clear (a new session id), compact, fork.
1078 on('classic.SessionStart', async ($, e, next) => {
1079 const r = await next(e)
1080 let watch: string[] = []
1081 await quietly(async () => {
1082 if (!(await isInteractive($))) return
1083 interactive = true
1084 if (Object.keys(rawEnv).length === 0) {
1085 rawEnv = await loadEnv($)
1086 env = { ...rawEnv }
1087 }
1088 // watchPaths are this hook's answer, so this one git call is awaited; bind reuses it.
1089 const gitDir = await readGitDir($, e.cwd)
1090 watch = watchPaths(gitDir)
1091 if (e.source !== 'compact') {
1092 const event: Event = e.source === 'startup' ? 'session.start' : (`session.${e.source}` as Event)
1093 await bind($, e.session_id, e.cwd, e.transcript_path || null, event, gitDir)
1094 } else if (snap && e.transcript_path) snap.transcriptPath = e.transcript_path
1095 })
1096 return watch.length ? { ...r, watchPaths: [...(r.watchPaths ?? []), ...watch] } : r
1097 })
1098
1099 on('turn.complete', async ($, e, next) => {
1100 const r = await next(e)
1101 if (!interactive || !snap || e.agentId !== undefined || !e.usage) return r
1102 const usage = e.usage
1103 await quietly(async () => {
1104 if (!snap) return
1105 const now = await nowMs($)
1106 lastActiveAt = now
1107 snap.counters = addTurn(snap.counters, usage, now)
1108 await saveCounters($)
1109 // The reads below shell out: off the turn's path. They belong to THIS session's snapshot: a /clear
1110 // that rebinds meanwhile must not get this transcript's ttl or title, nor a turn.complete write.
1111 const mine = snap
1112 $.clock.after(0, () => {
1113 void (async () => {
1114 await readTtl($, mine)
1115 await readName($, mine)
1116 await saveCounters($, mine)
1117 if (snap !== mine) return
1118 armCold($)
1119 repaint($)
1120 record($, 'turn.complete')
1121 })().catch(() => undefined)
1122 })
1123 })
1124 return r
1125 })
1126
1127 on('session.measure', async ($, e, next) => {
1128 const r = await next(e)
1129 if (!interactive || !snap) return r
1130 await quietly(async () => {
1131 if (!snap) return
1132 snap.ctxPct = e.context.percent ?? null
1133 snap.ctxWindow = e.context.window ?? snap.ctxWindow
1134 snap.costUsd = e.cost?.usd ?? snap.costUsd
1135 const rates = e.rateLimits as RateLimit[]
1136 const key = limitsFingerprint(rates)
1137 if (key !== limitsKey) {
1138 limitsKey = key
1139 snap.rateLimits = rates
1140 record($, 'rate-limit')
1141 }
1142 repaint($)
1143 })
1144 return r
1145 })
1146
1147 on('classic.PostModelSwitch', async ($, e, next) => {
1148 const r = await next(e)
1149 if (!interactive || !snap) return r
1150 await quietly(async () => {
1151 if (!snap) return
1152 if (e.to_model) snap.model = modelOf(e.to_model)
1153 const label = (e as unknown as { cache_ttl?: unknown }).cache_ttl
1154 if (label === '1h' || label === '5m') {
1155 snap.ttl = label
1156 snap.counters = withTtl(snap.counters, label)
1157 armCold($)
1158 }
1159 repaint($)
1160 record($, 'model')
1161 })
1162 return r
1163 })
1164
1165 on('classic.CwdChanged', async ($, e, next) => {
1166 const r = await next(e)
1167 if (!interactive || !snap) return r
1168 await quietly(async () => {
1169 if (!snap) return
1170 snap.cwd = e.new_cwd
1171 snap.worktreePath = worktreeOf(await readGitDir($, e.new_cwd))
1172 lastGitAt = null
1173 scheduleGit($)
1174 repaint($)
1175 record($, 'cwd')
1176 })
1177 return r
1178 })
1179
1180 // A compaction rewrites the prefix: the next request writes the cache afresh.
1181 on('classic.PostCompact', async ($, e, next) => {
1182 const r = await next(e)
1183 if (!interactive || !snap) return r
1184 await quietly(async () => {
1185 if (!snap) return
1186 snap.counters = compacted(snap.counters, await nowMs($))
1187 await saveCounters($)
1188 coldTimer?.cancel()
1189 coldTimer = null
1190 repaint($)
1191 record($, 'compact')
1192 })
1193 return r
1194 })
1195
1196 on('classic.FileChanged', async ($, e, next) => {
1197 scheduleGit($)
1198 return next(e)
1199 })
1200core/cache.ts 93 lines1import type { Counters, Ttl } from './types'
2
3// The prompt-cache lifetime the session's main conversation writes. Read once per turn off the
4// transcript tail; ported from context-vigil-mod's core/cache-ttl.ts (same TAIL_CMD, same rule:
5// any 5m write makes it 5m). Unknown is treated as 5m, the shorter and so the safer claim.
6export type Writes = { h1: number; m5: number }
7export const TAIL_CMD = 'tail -c 65536 "$1" | grep -o \'"cache_creation":{[^}]*}\''
8export const DEFAULT_TTL: Ttl = '5m'
9
10const field = (line: string, key: string): number => {
11 const m = new RegExp(`"ephemeral_${key}_input_tokens":(\\d+)`).exec(line)
12 return m ? Number.parseInt(m[1] ?? '0', 10) : 0
13}
14
15export function parseWrites(stdout: string): Writes | null {
16 const lines = stdout.split('\n')
17 for (let i = lines.length - 1; i >= 0; i--) {
18 const line = lines[i] ?? ''
19 if (!line.includes('"cache_creation"')) continue
20 const w = { h1: field(line, '1h'), m5: field(line, '5m') }
21 if (w.h1 > 0 || w.m5 > 0) return w
22 }
23 return null
24}
25
26/** null = nothing found in the tail. */
27export function ttlFromWrites(w: Writes | null): Ttl | null {
28 if (w === null) return null
29 return w.m5 > 0 ? '5m' : '1h'
30}
31
32export const ttlMs = (ttl: Ttl): number => (ttl === '1h' ? 3_600_000 : 300_000)
33
34export const EMPTY_COUNTERS: Counters = {
35 requests: 0, input: 0, read: 0, create: 0, output: 0,
36 lastTurnAt: null, ttl: null, lastRatio: null, cold: false, updatedAt: 0,
37}
38
39export type TurnTokens = {
40 input_tokens: number
41 output_tokens: number
42 cache_read_input_tokens: number
43 cache_creation_input_tokens: number
44}
45
46/** read / (read + creation + uncached input); null when the turn read no input at all. */
47export function ratio(read: number, create: number, input: number): number | null {
48 const total = read + create + input
49 return total > 0 ? read / total : null
50}
51
52/**
53 * Fold one main-thread turn in. `TurnUsage` is the turn's real requests SUMMED (typings), so a
54 * turn that ran several tool steps reports one ratio over all of them, and `requests` counts
55 * turns, not API calls.
56 */
57export function addTurn(c: Counters, u: TurnTokens, now: number): Counters {
58 return {
59 requests: c.requests + 1,
60 input: c.input + u.input_tokens,
61 read: c.read + u.cache_read_input_tokens,
62 create: c.create + u.cache_creation_input_tokens,
63 output: c.output + u.output_tokens,
64 lastTurnAt: now,
65 ttl: c.ttl,
66 lastRatio: ratio(u.cache_read_input_tokens, u.cache_creation_input_tokens, u.input_tokens),
67 cold: false,
68 updatedAt: now,
69 }
70}
71
72export const sessionRatio = (c: Counters): number | null => ratio(c.read, c.create, c.input)
73export const totalInputTokens = (c: Counters): number => c.input + c.read + c.create
74
75/** Epoch ms the cache goes cold, or null before any counted turn. */
76export function expiresAtMs(c: Counters, ttl: Ttl): number | null {
77 return c.lastTurnAt === null ? null : c.lastTurnAt + ttlMs(ttl)
78}
79
80export function isWarm(c: Counters, ttl: Ttl, now: number): boolean {
81 const at = expiresAtMs(c, ttl)
82 return !c.cold && at !== null && now < at
83}
84
85/** A compaction rewrites the prefix: the next request writes the cache afresh. */
86export const compacted = (c: Counters, now: number): Counters => ({ ...c, cold: true, updatedAt: now })
87
88export const withTtl = (c: Counters, ttl: Ttl): Counters => ({ ...c, ttl })
89
90export const STORE_PREFIX = 'counters:'
91export const counterKey = (sessionId: string): string => `${STORE_PREFIX}${sessionId}`
92export const COUNTER_KEEP_MS = 7 * 24 * 3_600_000
93core/census.ts 66 lines1import { configRootOf, expandHome, joinPath, trimSeps } from './home'
2import type { HomeEnv } from './home'
3
4export type CensusEnv = HomeEnv & {
5 CENSUS_MOD_STORE?: string
6 CENSUS_STORE?: string
7}
8
9/** Census reads a store ending `.json` as that FILE: its census dir is the parent (store.census_dir). */
10const asDir = (p: string): string => (p.endsWith('.json') ? trimSeps(p.slice(0, Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'))) || '/') : p)
11
12/** Shadow mode: the store value as given (`~` expanded), which census itself reads, `.json` and all. */
13export function shadowStore(env: CensusEnv): string | null {
14 return env.CENSUS_MOD_STORE ? trimSeps(expandHome(env.CENSUS_MOD_STORE, env)) : null
15}
16
17/** Shadow mode: the DIR that store lives in, where `cli.path` sits. */
18export function shadowDir(env: CensusEnv): string | null {
19 const store = shadowStore(env)
20 return store ? asDir(store) : null
21}
22
23/** The census dir readers use: `CENSUS_STORE`, else `<config dir>/census`. */
24export function censusDir(env: CensusEnv): string | null {
25 if (env.CENSUS_STORE) return asDir(trimSeps(expandHome(env.CENSUS_STORE, env)))
26 const root = configRootOf(env)
27 return root ? joinPath(root, 'census') : null
28}
29
30/**
31 * census-mod records through its OWN bundled copy of census's ingest (`<plugin root>/scripts/cli.py`), never through a
32 * census plugin: a Python script run under python3 with a list argv.
33 */
34export const bundledCli = (pluginRoot: string): string => joinPath(pluginRoot, 'scripts', 'cli.py')
35
36/** The ingest argv for a launcher that passed the Python 3.9+ probe. */
37export const ingestArgv = (cli: string, python: readonly string[] = ['python3']): string[] => [...python, cli, 'ingest']
38
39/** Shadow mode points the child's census at the shadow dir; ingest honours `CENSUS_STORE`. */
40export function ingestEnv(env: CensusEnv): Record<string, string> | undefined {
41 // Unchanged, `.json` included: census reads a file-valued store itself; only our pointer lookup wants the parent.
42 const store = shadowStore(env)
43 return store ? { CENSUS_STORE: store } : undefined
44}
45
46/** Time budgets (ms) */
47export const INGEST_TIMEOUT_MS = 10_000
48export const COALESCE_MS = 2000
49export const END_RESERVE_MS = 200
50export const END_MIN_MS = 300
51
52/**
53 * `timeoutMs` for the final ingest so it finishes inside `session.end`'s shared budget, or null to
54 * skip it: with under END_MIN_MS left an ingest would only overrun the exit.
55 */
56export function endTimeoutMs(remainingMs: number): number | null {
57 if (!Number.isFinite(remainingMs)) return 1000
58 if (remainingMs < END_MIN_MS) return null
59 return Math.min(1000, Math.floor(remainingMs) - END_RESERVE_MS)
60}
61
62/** How long to wait before the next ingest may run: 0 when the last was over `COALESCE_MS` ago. */
63export function delayFor(now: number, lastAt: number | null): number {
64 return lastAt === null ? 0 : Math.max(0, lastAt + COALESCE_MS - now)
65}
66core/gh.ts 56 lines1import type { Pr } from './types'
2
3export const GH_TIMEOUT_MS = 5000
4export const BACKOFF_MS = 10 * 60_000
5export const MAX_AGE_MS = 10 * 60_000
6export const ACTIVE_MS = 10 * 60_000
7
8/** Exactly: gh pr list --head <branch> --state open --limit 1 --json number,url,reviewDecision */
9export const ghArgv = (branch: string): string[] =>
10 ['gh', 'pr', 'list', '--head', branch, '--state', 'open', '--limit', '1', '--json', 'number,url,reviewDecision']
11
12/** What is kept per repo+branch. `pr: null` = checked, no open PR. */
13export type GhEntry = { at: number; pr: Pr | null; failedAt?: number }
14
15const REVIEW: Record<string, string> = {
16 APPROVED: 'approved',
17 REVIEW_REQUIRED: 'pending',
18 CHANGES_REQUESTED: 'changes_requested',
19}
20
21/** `gh pr list` JSON to a PR; empty list = no open PR; undefined = not parseable. */
22export function parsePrList(stdout: string): Pr | null | undefined {
23 let data: unknown
24 try {
25 data = JSON.parse(stdout)
26 } catch {
27 return undefined
28 }
29 if (!Array.isArray(data)) return undefined
30 const first = data[0] as { number?: unknown; url?: unknown; reviewDecision?: unknown } | undefined
31 if (first === undefined) return null
32 if (typeof first.number !== 'number') return undefined
33 const pr: Pr = { number: first.number, url: typeof first.url === 'string' ? first.url : '' }
34 const state = typeof first.reviewDecision === 'string' ? REVIEW[first.reviewDecision] : undefined
35 if (state) pr.reviewState = state
36 return pr
37}
38
39/** `manual`: /census-mod:pr-refresh, which asks once, backoff or not. `start`: the first sight of a branch by a bound session (a start, a /clear, a restart): a fresh cached answer stands. */
40export type Why = 'branch' | 'push' | 'age' | 'start' | 'manual'
41
42/** A Bash command that can have opened, updated or closed a PR. */
43export const touchesPr = (command: string): boolean => command.includes('git push') || command.includes('gh pr')
44
45export function shouldRefresh(why: Why, entry: GhEntry | undefined, now: number, lastActiveAt: number | null): boolean {
46 if (why === 'manual') return true
47 if (entry?.failedAt !== undefined && now < entry.failedAt + BACKOFF_MS) return false
48 if (entry === undefined) return true
49 if (why === 'branch' || why === 'push') return true
50 if (why === 'start') return now - entry.at > MAX_AGE_MS
51 return now - entry.at > MAX_AGE_MS && lastActiveAt !== null && now - lastActiveAt < ACTIVE_MS
52}
53
54/** JSON-encoded pair: any root/branch (a `|` in either included) maps to its own key. */
55export const ghKey = (root: string, branch: string): string => `gh:${JSON.stringify([root, branch])}`
56core/git.ts 52 lines1import { isAbsolute } from './home'
2import type { GitState } from './types'
3
4// Exactly one status call (no untracked scan: the changes segment never counted untracked files).
5export const GIT_STATUS_ARGV = ['git', '--no-optional-locks', 'status', '--porcelain=2', '--branch', '-uno'] as const
6// Line 1: the git dir (HEAD and index live there, elsewhere for a linked worktree); line 2: the top level.
7export const GIT_DIR_ARGV = ['git', 'rev-parse', '--absolute-git-dir', '--show-toplevel'] as const
8export const COALESCE_MS = 5000
9
10export type RunOut = { exitCode: number; stdout: string }
11
12/**
13 * Port of census's gitcache.parse_status. Detached HEAD reports the short oid; an unborn branch
14 * (oid `(initial)`) has no branch to report; untracked (`?`) and ignored (`!`) never count.
15 */
16export function parseStatus(stdout: string): GitState {
17 let head: string | null = null
18 let oid: string | null = null
19 let upstream: string | null = null
20 let ahead = 0
21 let uncommitted = 0
22 for (const line of stdout.split('\n')) {
23 if (line.startsWith('# branch.head ')) head = line.slice('# branch.head '.length).trim()
24 else if (line.startsWith('# branch.oid ')) oid = line.slice('# branch.oid '.length).trim()
25 else if (line.startsWith('# branch.upstream ')) upstream = line.slice('# branch.upstream '.length).trim()
26 else if (line.startsWith('# branch.ab ')) {
27 for (const part of line.split(/\s+/).slice(2)) if (/^\+\d+$/.test(part)) ahead = Number.parseInt(part.slice(1), 10)
28 } else if (['1 ', '2 ', 'u '].includes(line.slice(0, 2))) uncommitted++
29 }
30 const detached = head === '(detached)'
31 const unborn = oid === '(initial)'
32 const branch = detached ? (oid && !unborn ? oid.slice(0, 7) : null) : unborn ? null : head || null
33 return { branch, detached, uncommitted, ahead: upstream ? ahead : 0, hasUpstream: upstream !== null }
34}
35
36/** What to watch for a `rev-parse --absolute-git-dir --show-toplevel` answer; nothing when it failed. */
37export function watchPaths(out: RunOut): string[] {
38 const dir = out.exitCode === 0 ? (out.stdout.split('\n')[0] ?? '').trim() : ''
39 // git prints forward slashes even on Windows (`C:/repo/.git`)
40 return isAbsolute(dir) ? [`${dir}/HEAD`, `${dir}/index`] : []
41}
42
43/** The linked worktree's top level, or null in the main checkout (git dir is `<repo>/.git`). */
44export function worktreeOf(out: RunOut): string | null {
45 if (out.exitCode !== 0) return null
46 const [dir = '', top = ''] = out.stdout.split('\n').map(l => l.trim())
47 return /[\\/]\.git[\\/]worktrees[\\/][^\\/]+$/.test(dir) && isAbsolute(top) ? top : null
48}
49
50const TOUCH = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash'])
51export const touchesGit = (tool: string): boolean => TOUCH.has(tool)
52core/home.ts 76 lines1// Where "home" and the config dir are, on macOS, Linux and Windows. THE SAME FILE lives in census-mod, context-vigil-mod
2// and agent-roster (plugins share no code); a test_home_copies.py test fails if the copies differ.
3//
4// Rule: the config dir is CLAUDE_CONFIG_DIR, else <home>/.claude; <home> is HOME, else USERPROFILE, else
5// HOMEDRIVE+HOMEPATH. `~`, `~/x` and `~\x` expand with the same home.
6
7export type HomeEnv = {
8 CLAUDE_CONFIG_DIR?: string
9 HOME?: string
10 USERPROFILE?: string
11 HOMEDRIVE?: string
12 HOMEPATH?: string
13}
14
15/** What was looked at, for messages: name the variables actually checked. */
16export const HOME_VARS_CHECKED = 'CLAUDE_CONFIG_DIR, HOME, USERPROFILE and HOMEDRIVE+HOMEPATH'
17
18const nonEmpty = (v: string | undefined): string | undefined => (v && v.trim() ? v : undefined)
19
20/** The home dir: HOME, else USERPROFILE, else HOMEDRIVE+HOMEPATH; null when none is set. */
21export function homeOf(env: HomeEnv): string | null {
22 const home = nonEmpty(env.HOME) ?? nonEmpty(env.USERPROFILE)
23 if (home) return home
24 const drive = nonEmpty(env.HOMEDRIVE)
25 const path = nonEmpty(env.HOMEPATH)
26 return drive && path ? `${drive}${path}` : null
27}
28
29/** The separator a base path uses: a backslash when it has one and no slash (`C:\Users\x`), else a slash. */
30export const sepOf = (p: string): '/' | '\\' => (p.includes('\\') && !p.includes('/') ? '\\' : '/')
31
32/** Whether a path is absolute on either platform: `/x`, `C:\x`, `C:/x`, `\\server\share`. */
33export const isAbsolute = (p: string): boolean => p.startsWith('/') || p.startsWith('\\\\') || /^[A-Za-z]:[\\/]/.test(p)
34
35/**
36 * Trailing separators dropped (slash or backslash), the root kept: `/a/b//` -> `/a/b`, `/` -> `/`,
37 * `C:\Users\x\` -> `C:\Users\x`, `C:\` -> `C:\`.
38 */
39export function trimSeps(p: string): string {
40 if (/^[A-Za-z]:$/.test(p)) return p // `C:` is the drive-relative cwd of C:, not the root `C:\`
41 if (/^[A-Za-z]:[\\/]+$/.test(p)) return `${p.slice(0, 2)}${p.includes('/') ? '/' : '\\'}`
42 const t = p.replace(/[\\/]+$/, '')
43 return t || (/^[\\/]/.test(p) ? p[0] ?? '/' : p)
44}
45
46/** `base` + parts, joined with the separator the base uses, so `C:\Users\x` + `.claude` stays all backslashes. */
47export function joinPath(base: string, ...parts: string[]): string {
48 const sep = sepOf(base)
49 const root = trimSeps(base)
50 const tail = parts.map(p => p.replace(/^[\\/]+|[\\/]+$/g, '')).filter(Boolean).join(sep)
51 const joined = root.endsWith('/') || root.endsWith('\\') || /^[A-Za-z]:$/.test(root) ? `${root}${tail}` : `${root}${sep}${tail}`
52 return tail ? joined.replace(sep === '\\' ? /\//g : /\\/g, sep) : root
53}
54
55/** `~`, `~/x` or `~\x` with the home dir (in the home's own separator); anything else unchanged. */
56export function expandHome(p: string, env: HomeEnv): string {
57 const home = homeOf(env)
58 if (!home || !(p === '~' || p.startsWith('~/') || p.startsWith('~\\'))) return p
59 return p === '~' ? trimSeps(home) : joinPath(home, p.slice(2))
60}
61
62/** The config dir: CLAUDE_CONFIG_DIR, else <home>/.claude; null when neither can be told. */
63export function configRootOf(env: HomeEnv): string | null {
64 const set = nonEmpty(env.CLAUDE_CONFIG_DIR)
65 if (set) return trimSeps(set)
66 const home = homeOf(env)
67 return home ? joinPath(home, '.claude') : null
68}
69
70/** A path as a comparison key: one separator, no trailing one, lower-cased when it is a Windows (drive or UNC) path. */
71export function pathKey(p: string): string {
72 const flat = p.replace(/\\/g, '/')
73 const trimmed = flat.length > 1 ? flat.replace(/\/+$/, '') || '/' : flat
74 return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') ? trimmed.toLowerCase() : trimmed
75}
76core/prstate.ts 159 lines1// PR state learned from mod events, never from GitHub (WF-269). Pure: no `$`.
2//
3// What the engine gives a mod in a local session (proved live, see the field notes): the Bash tool result carries
4// `gitOperation` for commits, pushes and PR-changing `gh` commands (created, ready, draft, closed, merged,
5// reopened, commented, edited, auto-merge), and nothing for `gh pr view` or checkout. The status-line payload's `pr`
6// is not readable by a mod, and a local session gets no GitHub `session.receive`. So a record is kept per
7// repo+branch from those operations, newest `at` winning, and a field an event lacks keeps its old value.
8import type { Pr } from './types'
9
10export type PrAction = 'created' | 'edited' | 'merged' | 'commented' | 'closed' | 'reopened' | 'ready' | 'draft' | 'auto-merge-enabled' | 'auto-merge-disabled'
11export type GitOperation = { push?: { branch: string }; pr?: { number: number; url?: string; action: string } }
12export type PrState = 'open' | 'closed' | 'merged'
13
14export type PrRecord = {
15 number: number
16 url?: string
17 state: PrState
18 review?: string
19 lastAction: string
20 /** Where the newest word came from: a tool event, or the opt-in `gh` lookup. */
21 source: 'event' | 'gh'
22 /** `$.clock.now()` ms of that word. */
23 at: number
24 /** A push since: the review state may have moved, so it draws dimmed until something confirms it. */
25 stale?: boolean
26 sessionId: string
27 worktree: string
28}
29
30/** Drawn dimmed after this long with nothing confirming it. */
31export const DIM_AFTER_MS = 24 * 3600_000
32
33const ACTIONS: ReadonlySet<string> = new Set(['created', 'edited', 'merged', 'commented', 'closed', 'reopened', 'ready', 'draft', 'auto-merge-enabled', 'auto-merge-disabled'])
34
35/** `owner/name` from an origin URL (https, ssh or scp-like); null for anything that is not a plain two-part path. */
36export function repoOf(url: string): string | null {
37 const m = url.trim().match(/^(?:[a-z+]+:\/\/(?:[^@/]+@)?[^/:]+(?::\d+)?\/|[^@\s]+@[^:\s]+:)([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i)
38 return m ? `${m[1]}/${m[2]}` : null
39}
40
41export const prKey = (repo: string, branch: string): string => `pr:${repo}#${branch}`
42export const prPrefix = (repo: string): string => `pr:${repo}#`
43
44/** The `gitOperation` block of a Bash tool result, or null when the result has none (or is not a Bash result). */
45export function gitOperationOf(result: unknown): GitOperation | null {
46 if (typeof result !== 'object' || result === null) return null
47 const op = (result as { gitOperation?: unknown }).gitOperation
48 if (typeof op !== 'object' || op === null) return null
49 const out: GitOperation = {}
50 const push = (op as { push?: { branch?: unknown } }).push
51 if (push && typeof push.branch === 'string' && push.branch) out.push = { branch: push.branch }
52 const pr = (op as { pr?: { number?: unknown; url?: unknown; action?: unknown } }).pr
53 if (pr && typeof pr.number === 'number' && Number.isInteger(pr.number) && pr.number > 0 && typeof pr.action === 'string' && ACTIONS.has(pr.action)) {
54 out.pr = { number: pr.number, action: pr.action, ...(typeof pr.url === 'string' && pr.url ? { url: pr.url } : {}) }
55 }
56
57 return out.push || out.pr ? out : null
58}
59
60/** What a PR action changes: only the fields it speaks about. */
61/** `review: null` clears the review state (gh says the PR needs none). */
62export type Patch = { number: number; url?: string; state?: PrState; review?: string | null; lastAction: string }
63
64/**
65 * The patch for one `gitOperation.pr`. `draftFlag`: the command passed --draft. Actions that only touch the PR
66 * (comment, edit, auto-merge) change nothing but the time and the action.
67 */
68export function patchFor(pr: NonNullable<GitOperation['pr']>, draftFlag: boolean): Patch {
69 const base: Patch = { number: pr.number, lastAction: pr.action, ...(pr.url ? { url: pr.url } : {}) }
70 switch (pr.action) {
71 case 'created': return { ...base, state: 'open', ...(draftFlag ? { review: 'draft' } : {}) }
72 case 'ready': return { ...base, state: 'open', review: 'pending' }
73 case 'draft': return { ...base, state: 'open', review: 'draft' }
74 case 'reopened': return { ...base, state: 'open' }
75 case 'closed': return { ...base, state: 'closed' }
76 case 'merged': return { ...base, state: 'merged' }
77 default: return base
78 }
79}
80
81/** Newest `at` wins; a field the patch lacks keeps its old value; a different PR number replaces the record. */
82export function applyPatch(old: PrRecord | undefined, patch: Patch, at: number, ctx: { sessionId: string; worktree: string; source?: 'event' | 'gh' }): PrRecord | undefined {
83 if (old && old.number === patch.number && at < old.at) return old
84 const keep = old && old.number === patch.number ? old : undefined
85 // Only a word that settles the state or the review confirms the record; a comment, edit or auto-merge does not.
86 const confirms = patch.state !== undefined || patch.review !== undefined || ctx.source === 'gh'
87 const { stale, review: _old, ...rest } = keep ?? {}
88 const review = patch.review === null ? undefined : (patch.review ?? keep?.review)
89
90 return {
91 ...rest,
92 ...(stale && !confirms ? { stale } : {}),
93 number: patch.number,
94 state: patch.state ?? keep?.state ?? 'open',
95 lastAction: patch.lastAction,
96 source: ctx.source ?? 'event',
97 at,
98 sessionId: ctx.sessionId,
99 worktree: ctx.worktree,
100 ...(patch.url ?? keep?.url ? { url: patch.url ?? keep?.url } : {}),
101 ...(review ? { review } : {}),
102 }
103}
104
105/** A push can change the PR's review state behind our back: keep the record, mark it unconfirmed. */
106export const markStale = (rec: PrRecord): PrRecord => (rec.stale ? rec : { ...rec, stale: true })
107
108/** The PR to draw from a record: open ones only; dimmed when a push has gone unconfirmed or it is a day old. */
109export function toPr(rec: PrRecord | undefined, now: number): Pr | null {
110 if (!rec || rec.state !== 'open') return null
111 const dim = rec.stale === true || now - rec.at > DIM_AFTER_MS
112
113 return { number: rec.number, url: rec.url ?? '', ...(rec.review ? { reviewState: rec.review } : {}), ...(dim ? { stale: true } : {}) }
114}
115
116/** Does the command pass --draft to `gh pr create`? */
117export const hasDraftFlag = (command: string): boolean => /(?:^|\s)(?:--draft|-d)(?:\s|=|$)/.test(command)
118
119// ---- the two optional sources below the session's own events (decision 24) --------------------------------------
120// Precedence: the session's own events > the status-line payload's `pr` > gh. Neither source here is read from GitHub by
121// the mod, and neither can prove a close: a payload without `pr` is "none open OR not fetched yet", and a hint
122// without the text means nothing.
123
124/** A status-line command that wrote its payload's `pr` longer ago than this is not running: its word is not used. */
125export const PAYLOAD_PR_FRESH_MS = 5 * 60_000
126
127/**
128 * The `status_line_pr` of a census session record (written by census's ingest when a status-line command sends a
129 * payload with `pr`): a drawable PR when it is well-formed, fresh and of `branch` (the one the ingest saw; after a
130 * checkout the word is the old branch's until the command runs again), else null. `at` is the writer's epoch seconds.
131 */
132export function payloadPrOf(recordText: string, now: number, branch: string): Pr | null {
133 let data: unknown
134 try {
135 data = JSON.parse(recordText)
136 } catch {
137 return null
138 }
139 const pr = typeof data === 'object' && data !== null ? (data as { status_line_pr?: { number?: unknown; branch?: unknown; url?: unknown; review_state?: unknown; at?: unknown } }).status_line_pr : undefined
140 if (!pr || typeof pr !== 'object') return null
141 if (typeof pr.number !== 'number' || !Number.isInteger(pr.number) || pr.number <= 0) return null
142 if (pr.branch !== branch) return null
143 if (typeof pr.at !== 'number' || !Number.isFinite(pr.at) || now - pr.at * 1000 > PAYLOAD_PR_FRESH_MS) return null
144
145 return { number: pr.number, url: typeof pr.url === 'string' ? pr.url : '', ...(typeof pr.review_state === 'string' && pr.review_state ? { reviewState: pr.review_state } : {}) }
146}
147
148/** The PR number the engine's prompt hint names (`PR #158`), or null. Only a number: the rest of the text is the engine's. */
149export function hintPrNumber(hint: unknown): number | null {
150 if (typeof hint !== 'string') return null
151 const m = /\bPR #(\d{1,9})\b/.exec(hint)
152 const n = m ? Number(m[1]) : 0
153
154 return n > 0 ? n : null
155}
156
157/** Re-confirm an event-or-gh record the hint names: no more than this often, and only when it has something to say. */
158export const HINT_CONFIRM_MS = 5 * 60_000
159core/name.ts 20 lines1import { configRootOf, joinPath, trimSeps } from './home'
2import type { HomeEnv } from './home'
3
4export const NAME = 'census-mod'
5export const SCHEMA = 1
6
7/** `/a/b//` -> `/a/b`; `C:\x\` -> `C:\x`; a root stays a root (a bare trim would leave the empty string). */
8export const trimSlashes = trimSeps
9
10/** The config dir: CLAUDE_CONFIG_DIR, else <home>/.claude (home: HOME, USERPROFILE, HOMEDRIVE+HOMEPATH); null if none can be told. */
11export function configRoot(env: HomeEnv): string | null {
12 return configRootOf(env)
13}
14
15// Where Claude Code keeps a session's transcript, for when no hook has carried the path yet (a hot
16// reload fires session.start but not classic.SessionStart). Ported from context-vigil-mod.
17export function transcriptPathFor(root: string, cwd: string, sessionId: string): string {
18 return joinPath(root, 'projects', cwd.replace(/[^A-Za-z0-9]/g, '-'), `${sessionId}.jsonl`)
19}
20core/portable.ts 62 lines1// What the hooks file runs outside the engine, per platform. Pure: no `$`. A path says which platform it is on
2// (`C:\x` and `\\server\x` are Windows, `/x` is POSIX), so nothing here sniffs the OS.
3import { isAbsolute } from './home'
4
5export const onWindows = (path: string): boolean => isAbsolute(path) && !path.startsWith('/')
6
7/** Python launchers to try, in order: `python3` (macOS, Linux), `python`, then the Windows launcher `py -3`. */
8export const PYTHON_CANDIDATES: readonly (readonly string[])[] = [['python3'], ['python'], ['py', '-3']]
9
10/**
11 * What the probe runs: exits 0 only on Python 3.9 or newer. `--version` would also pass a `python` that is Python 2
12 * (and the Windows Store stub fails it, as it opens the Store instead of running), and the recorder's code needs 3.9+.
13 */
14export const PYTHON_PROBE = 'import sys; sys.exit(sys.version_info < (3, 9))'
15
16/** The first launcher whose probe ran, given a probe that says whether one did; null when none. */
17export async function pickPython(works: (argv: string[]) => Promise<boolean>): Promise<string[] | null> {
18 for (const candidate of PYTHON_CANDIDATES) {
19 const argv = [...candidate, '-c', PYTHON_PROBE]
20 if (await works(argv).catch(() => false)) return [...candidate]
21 }
22 return null
23}
24
25// Windows has no argv-only move/delete: `cmd /c` would parse the paths as a command line. So there, nothing is spawned:
26// the caller writes the file in place and empties a backup instead of deleting it (see the hooks file).
27
28/** Rename `from` over `to` with `mv -f`; null on Windows. */
29export const moveArgv = (from: string, to: string): string[] | null => (onWindows(to) ? null : ['mv', '-f', from, to])
30
31/** Remove a file, quietly when it is not there, with `rm -f`; null on Windows. */
32export const removeArgv = (path: string): string[] | null => (onWindows(path) ? null : ['rm', '-f', path])
33
34/** Copy keeping the mode (POSIX only: a Windows file has no mode to keep, so there is nothing to run). */
35export const copyModeArgv = (from: string, to: string): string[] | null => (onWindows(to) ? null : ['cp', '-p', from, to])
36
37/** The last `bytes` UTF-8 bytes of the text (as `tail -c` takes them), not the last UTF-16 units: a cut mid-character is dropped. */
38export function tailBytes(text: string, bytes: number): string {
39 let used = 0
40 let i = text.length
41 while (i > 0) {
42 const code = text.charCodeAt(i - 1)
43 const isLow = code >= 0xdc00 && code <= 0xdfff && i > 1
44 const size = isLow ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3
45 if (used + size > bytes) break
46 used += size
47 i -= isLow ? 2 : 1
48 }
49
50 return text.slice(i)
51}
52
53/** What `tail -c N file | grep -o '"cache_creation":{[^}]*}'` prints, from the file's text (for where there is no sh). */
54export function cacheLinesFromText(text: string, bytes = 65536): string {
55 return (tailBytes(text, bytes).match(/"cache_creation":\{[^}]*\}/g) ?? []).join('\n')
56}
57
58/** What `grep -F '"type":"custom-title"'` prints (the last `bytes` of the file only when given). */
59export function titleLinesFromText(text: string, bytes?: number): string {
60 return (bytes ? tailBytes(text, bytes) : text).split('\n').filter(l => l.includes('"type":"custom-title"')).join('\n')
61}
62core/payload.ts 79 lines1import { SCHEMA } from './name'
2import { expiresAtMs, isWarm, sessionRatio, totalInputTokens } from './cache'
3import type { RateLimit, Snap } from './types'
4
5export type Event =
6 | 'session.start' | 'session.clear' | 'session.resume' | 'session.fork' | 'turn.complete'
7 | 'rate-limit' | 'model' | 'cwd' | 'branch' | 'pr' | 'cache.cold' | 'compact' | 'session.end'
8
9/** `claude-opus-5-5[1m]` -> `{ id: 'claude-opus-5-5', display_name: 'Opus 5.5' }`. */
10export function modelOf(raw: string): { id: string; display_name: string } {
11 const id = raw.replace(/\[[^\]]*\]$/, '')
12 const m = /^claude-(opus|sonnet|haiku|fable)-(\d+)-(\d+)/.exec(id)
13 const name = m ? `${(m[1] ?? '').charAt(0).toUpperCase()}${(m[1] ?? '').slice(1)} ${m[2]}.${m[3]}` : id
14 return { id, display_name: name }
15}
16
17/** ISO `resetsAt` and decimal `percentUsed` to census's windows: epoch SECONDS, or census drops it. */
18export function rateLimitsOf(limits: RateLimit[]): Record<string, { used_percentage: number; resets_at: number }> {
19 const out: Record<string, { used_percentage: number; resets_at: number }> = {}
20 for (const l of limits) {
21 const ms = l.resetsAt ? Date.parse(l.resetsAt) : Number.NaN
22 if (!Number.isFinite(ms) || !Number.isFinite(l.percentUsed)) continue
23 out[l.kind] = { used_percentage: l.percentUsed, resets_at: Math.floor(ms / 1000) }
24 }
25 return out
26}
27
28/**
29 * The status-line payload shape census reads, plus `census_mod`. `now` in ms. Keys census does not
30 * know are stored verbatim, so every extra here is free; a key this cannot fill is OMITTED, not
31 * faked (census keeps the prior value of a null, and drops a half-formed window).
32 */
33export function buildPayload(s: Snap, now: number, event: Event, ended?: string): Record<string, unknown> {
34 const c = s.counters
35 const expires = expiresAtMs(c, s.ttl)
36 const cache: Record<string, unknown> = {
37 warm: isWarm(c, s.ttl, now),
38 ttl: s.ttl,
39 requests: c.requests,
40 }
41 if (expires !== null) cache.expires_at = Math.floor(expires / 1000)
42 if (c.lastRatio !== null) cache.hit_ratio = c.lastRatio
43 const whole = sessionRatio(c)
44 if (whole !== null) cache.session_hit_ratio = whole
45
46 const p: Record<string, unknown> = { session_id: s.sessionId }
47 if (s.transcriptPath) p.transcript_path = s.transcriptPath
48 p.cwd = s.cwd
49 // No project_dir: the mod tracks the current directory, not a project root, and would go stale after a cd.
50 p.workspace = { current_dir: s.cwd }
51 if (s.worktreePath) p.worktree = { path: s.worktreePath }
52 if (s.model) p.model = s.model
53 p.context_window = {
54 used_percentage: s.ctxPct,
55 ...(s.ctxWindow !== null ? { context_window_size: s.ctxWindow } : {}),
56 total_input_tokens: totalInputTokens(c),
57 total_output_tokens: c.output,
58 }
59 const cost: Record<string, number> = {}
60 if (s.costUsd !== null) cost.total_cost_usd = s.costUsd
61 if (s.startedAt !== null) cost.total_duration_ms = Math.max(0, Math.round(now - s.startedAt))
62 p.cost = cost
63 const limits = rateLimitsOf(s.rateLimits)
64 if (Object.keys(limits).length) p.rate_limits = limits
65 p.prompt_cache = cache
66 if (s.sessionName) p.session_name = s.sessionName
67 if (s.pr) p.pr = { number: s.pr.number, url: s.pr.url, ...(s.pr.reviewState ? { review_state: s.pr.reviewState } : {}) }
68 if (s.version) p.version = s.version
69 p.census_mod = {
70 version: SCHEMA,
71 ...(s.proc ? { pid: s.proc.pid, proc_start: s.proc.procStart } : {}),
72 event,
73 ...(ended !== undefined ? { ended } : {}),
74 // The `-uno` git pass, in gitcache's field names, so readers never shell out to git themselves.
75 git: s.git ? { branch: s.git.branch, uncommitted: s.git.uncommitted, ahead: s.git.ahead, has_upstream: s.git.hasUpstream, detached: s.git.detached } : null,
76 }
77 return p
78}
79core/registry.ts 42 lines1import type { Proc } from './types'
2
3/**
4 * Claude Code's own session registry holds `<config dir>/sessions/<pid>.json` per live process,
5 * with the `procStart` string (ps lstart text, in another zone: only ever compared as a string)
6 * and the version. The entry whose `sessionId` is ours names our process.
7 */
8export function findProc(files: { text: string }[], sessionId: string): Proc | null {
9 for (const f of files) {
10 let d: unknown
11 try {
12 d = JSON.parse(f.text)
13 } catch {
14 continue
15 }
16 if (!d || typeof d !== 'object' || Array.isArray(d)) continue // null, a scalar or an array is no registry entry
17 const r = d as { pid?: unknown; sessionId?: unknown; procStart?: unknown; version?: unknown }
18 if (r.sessionId !== sessionId || typeof r.pid !== 'number' || r.pid <= 1 || typeof r.procStart !== 'string') continue
19 return { pid: r.pid, procStart: r.procStart, ...(typeof r.version === 'string' ? { version: r.version } : {}) }
20 }
21 return null
22}
23
24/** The last `custom-title` row of `grep -F '"type":"custom-title"'` output. */
25export function lastTitle(stdout: string): string | null {
26 const lines = stdout.split('\n').filter(l => l.includes('"custom-title"'))
27 for (let i = lines.length - 1; i >= 0; i--) {
28 try {
29 const t = (JSON.parse(lines[i] ?? '') as { customTitle?: unknown }).customTitle
30 if (typeof t === 'string' && t.trim()) return t.trim()
31 } catch {
32 // a row cut mid-write; try the one before
33 }
34 }
35 return null
36}
37
38/** The whole transcript, once per bound session. */
39export const TITLE_ARGV = (path: string): string[] => ['grep', '-h', '-F', '"type":"custom-title"', path]
40/** After each turn: only the tail, where a later /rename lands, so a long session is not re-read whole every turn. */
41export const TITLE_TAIL_CMD = 'tail -c 262144 "$1" | grep -F \'"type":"custom-title"\''
42core/render.ts 311 lines1// The status line as data: a port of census's render.py (segments, glyphs, thresholds, the `/` line
2// syntax). A line is a list of runs; the shell turns runs into <Text>, tests read them as text.
3import type { GitState, Pr } from './types'
4
5export type Tone = 'grey' | 'cyan' | 'green' | 'yellow' | 'magenta' | 'pac' | 'white' | 'red' | 'orange' | 'claude'
6export type Run = { t: string; tone?: Tone; bold?: boolean }
7export type Line = Run[]
8
9/** render.py's ANSI palette as Text colours (names the surface's chalk-style colours accept; orange is 256-colour 208). */
10export const TONE_COLOR: Record<Tone, string> = {
11 grey: 'gray', cyan: 'cyan', green: 'green', yellow: 'yellow', magenta: 'magenta',
12 pac: 'yellowBright', white: 'whiteBright', red: 'red', orange: '#ff8700',
13 claude: '#D97757', // the asterisk's own orange (proven live as a raw hex Text colour)
14}
15
16export type RenderEnv = {
17 CENSUS_STATUSLINE_SEGMENTS?: string
18 CENSUS_STATUSLINE_MASCOT?: string
19 CLAUDE_COST_BUDGET?: string
20 CLAUDE_PROFILE?: string
21 CLAUDE_CONFIG_DIR?: string
22}
23
24export type RenderInput = {
25 now: number // epoch seconds
26 ctxPct: number | null
27 cache: { hitRatio: number | null; requests: number; warm: boolean; expiresAt: number | null; misses: number }
28 limits: Record<string, { used_percentage: number; resets_at: number } | undefined>
29 /** The context window's size in tokens, when known (the Clean preset shows used/size). */
30 ctxWindow?: number | null
31 costUsd: number | null
32 durationMs: number | null
33 modelName: string | null
34 git: Pick<GitState, 'branch' | 'uncommitted' | 'ahead' | 'hasUpstream'> | null
35 pr: Pr | null
36 cwd: string
37 env: RenderEnv
38}
39
40export const DEFAULT_SEGMENTS = 'context,cache,limits,cost/model,git,dir,changes,pr'
41export const DEFAULT_BUDGET = 20
42export const BAR_WIDTH = 10
43
44/** printf "%.0f": round half to even. */
45export function roundHalfEven(x: number): number {
46 const f = Math.floor(x)
47 const d = x - f
48 if (d < 0.5) return f
49 if (d > 0.5) return f + 1
50 return f % 2 === 0 ? f : f + 1
51}
52
53export const levelTone = (pct: number): Tone => (pct >= 90 ? 'red' : pct >= 75 ? 'orange' : 'green')
54export const levelToneInv = (pct: number): Tone => (pct >= 90 ? 'green' : pct >= 75 ? 'orange' : 'red')
55
56export function pacBar(pct: number, width = BAR_WIDTH, glyph = '•', ahead?: string): Run[] {
57 const track = ahead ?? glyph
58 const filled = Math.max(0, Math.min(Math.floor((pct / 100) * width + 0.5), width))
59 const pac = Math.min(filled, width - 1)
60 const out: Run[] = []
61 for (let j = 0; j < width; j++) {
62 if (j < pac) out.push({ t: glyph, tone: levelTone(Math.floor(((j + 1) * 100) / width)) })
63 else if (j === pac) out.push({ t: 'ᗧ', tone: 'pac' })
64 else out.push({ t: track, tone: 'white' })
65 }
66 return out
67}
68
69export function fmtReset(target: number, now: number): string {
70 const diff = Math.max(0, Math.floor(target - now))
71 if (diff >= 86400) return `${Math.floor(diff / 86400)}d${Math.floor((diff % 86400) / 3600)}h`
72 if (diff >= 3600) return `${Math.floor(diff / 3600)}h${Math.floor((diff % 3600) / 60)}m`
73 return `${Math.floor(diff / 60)}m`
74}
75
76const sp: Run = { t: ' ' }
77const grey = (t: string): Run => ({ t, tone: 'grey' })
78
79function segContext(i: RenderInput): Line[] {
80 if (i.ctxPct === null) {
81 return [[grey('🧠'), sp, { t: 'ᗧ', tone: 'pac' }, { t: '•'.repeat(BAR_WIDTH - 1), tone: 'white' }, sp, grey('--%')]]
82 }
83 const shown = roundHalfEven(i.ctxPct)
84 return [[grey('🧠'), sp, ...pacBar(i.ctxPct), sp, { t: `${shown}%`, tone: levelTone(shown) }]]
85}
86
87function segCache(i: RenderInput): Line[] {
88 const { hitRatio, requests, warm, expiresAt, misses } = i.cache
89 if (hitRatio === null || !(requests > 0)) return []
90 const pct = roundHalfEven(Math.max(0, Math.min(100, hitRatio * 100)))
91 const line: Line = [grey(warm ? '🎯' : '🧊'), sp, { t: `${pct}%`, tone: levelToneInv(pct) }]
92 if (warm && expiresAt !== null) line.push(sp, grey(`⟳ ${fmtReset(expiresAt, i.now)}`))
93 if (misses > 0) line.push(sp, { t: `✗${misses}`, tone: 'red' })
94 return [line]
95}
96
97function usageBar(i: RenderInput, w: { used_percentage: number; resets_at: number }): Line {
98 const shown = roundHalfEven(w.used_percentage)
99 return [...pacBar(w.used_percentage), sp, { t: `${shown}%`, tone: levelTone(shown) }, sp, grey(`⟳ ${fmtReset(w.resets_at, i.now)}`)]
100}
101
102function segLimits(i: RenderInput): Line[] {
103 const out: Line[] = []
104 for (const [key, emoji] of [['five_hour', '⏳'], ['seven_day', '📅']] as const) {
105 const w = i.limits[key]
106 if (!w) continue
107 if (w.resets_at <= i.now) continue // an expired window is a fossil
108 out.push([grey(emoji), sp, ...usageBar(i, w)])
109 }
110 return out
111}
112
113/** The whole value or nothing: "5oops" is not a $5 budget. */
114export function parseBudget(raw: string | undefined): number | null {
115 const t = (raw ?? '').trim()
116 const v = /^-?\d+(\.\d+)?$/.test(t) ? Number(t) : null
117 return v !== null && Number.isFinite(v) ? v : null
118}
119
120const budget = (env: RenderEnv): number => parseBudget(env.CLAUDE_COST_BUDGET) ?? DEFAULT_BUDGET
121
122function segCost(i: RenderInput): Line[] {
123 if (i.costUsd === null) return []
124 const b = budget(i.env)
125 const pct = b <= 0 ? 0 : Math.max(0, roundHalfEven((i.costUsd / b) * 100))
126 const out: Line[] = [[grey('💸'), sp, ...pacBar(Math.min(pct, 100), BAR_WIDTH, '•', '$'), sp, { t: `$${i.costUsd.toFixed(2)}`, tone: levelTone(pct) }]]
127 if (i.durationMs !== null && i.durationMs > 0) {
128 const burn = i.costUsd / (i.durationMs / 3_600_000)
129 const bi = roundHalfEven(burn)
130 const [tone, emoji]: [Tone, string] = bi >= 20 ? ['red', '🚀'] : bi >= 8 ? ['orange', '🔥'] : ['green', '🐌']
131 out.push([{ t: `${emoji} ` }, { t: `$${bi >= 100 ? String(bi) : burn.toFixed(2)}/hr`, tone }])
132 }
133 return out
134}
135
136export function detectAccount(env: RenderEnv): 'personal' | 'work' {
137 if (env.CLAUDE_PROFILE) return ['personal', 'home', 'p'].includes(env.CLAUDE_PROFILE) ? 'personal' : 'work'
138 if (env.CLAUDE_CONFIG_DIR) return env.CLAUDE_CONFIG_DIR.includes('personal') ? 'personal' : 'work'
139 return 'work'
140}
141
142export const DEFAULT_MASCOT = '✻'
143export const mascot = (env: RenderEnv): string => env.CENSUS_STATUSLINE_MASCOT || DEFAULT_MASCOT
144
145function segModel(i: RenderInput): Line[] {
146 const custom = i.env.CENSUS_STATUSLINE_MASCOT
147 // The default is a coloured run of its own; an override is drawn as given.
148 const glyph: Run = custom ? { t: `${custom} ` } : { t: `${DEFAULT_MASCOT} `, tone: 'claude', bold: true } // bold, and the glyph plus one space: a two-column slot like an emoji
149 return [[glyph, ...(custom ? [] : [sp]), { t: i.modelName || 'Claude', tone: 'cyan' }]]
150}
151
152function segGit(i: RenderInput): Line[] {
153 if (!i.git?.branch) return []
154 return [[{ t: `🌿 ${i.git.branch}`, tone: 'green' }]]
155}
156
157function segDir(i: RenderInput): Line[] {
158 const parts = i.cwd.split(/[\\/]/)
159 const shown = parts.length <= 3 ? i.cwd : `…${parts.slice(-3).map(p => `/${p}`).join('')}`
160 return [[{ t: `📁 ${shown}`, tone: 'magenta' }]]
161}
162
163function segChanges(i: RenderInput): Line[] {
164 if (!i.git?.branch) return []
165 const line: Line = [{ t: `✏️ ${i.git.uncommitted}`, tone: 'yellow' }]
166 if (i.git.ahead > 0 && i.git.hasUpstream) line.push({ t: ' ' }, { t: `⬆️ ${i.git.ahead}`, tone: 'yellow' })
167 return [line]
168}
169
170const REVIEW_TONE: Record<string, Tone> = { approved: 'green', pending: 'yellow', changes_requested: 'red' }
171
172/** The branch's open PR (from tool events, else the gh cache): `🔀 #12 approved`, the state coloured, all grey when unconfirmed; hidden without one. */
173function segPr(i: RenderInput): Line[] {
174 if (!i.pr || !(i.pr.number > 0)) return []
175 if (i.pr.stale) return [[{ t: `🔀 #${i.pr.number}${i.pr.reviewState ? ` ${i.pr.reviewState}` : ''}`, tone: 'grey' }]] // unconfirmed: dimmed
176 const line: Line = [{ t: `🔀 #${i.pr.number}` }]
177 if (i.pr.reviewState) line.push(sp, { t: i.pr.reviewState, tone: REVIEW_TONE[i.pr.reviewState] ?? 'grey' })
178 return [line]
179}
180
181// ---- Clean: one plain line, `🤖 Opus 5.5 | 🧠 85k/200k 42% | 💵 $1.37 | 🕔 5h 38% 0.8x | 🗓️ 7d 12% 0.7x` ----------------
182
183/** 85000 -> 85k, 1000000 -> 1M, 1250000 -> 1.3M. */
184export function fmtTokens(n: number): string {
185 if (n >= 1_000_000) return `${String(Math.round((n / 1_000_000) * 10) / 10)}M`
186 if (n >= 1000) return `${Math.round(n / 1000)}k`
187 return String(Math.round(n))
188}
189
190/** used% over the share of the window gone (resets_at is when it ends); null when under 1% has gone or the reset is not inside the window. */
191export function paceMultiplier(usedPct: number, resetsAt: number, windowSec: number, now: number): number | null {
192 const elapsed = 1 - (resetsAt - now) / windowSec
193 if (!(elapsed >= 0.01) || elapsed > 1) return null
194 return usedPct / (elapsed * 100)
195}
196
197const CLEAN_SEPARATOR: Run = { t: ' | ', tone: 'grey' }
198
199function cleanWindow(i: RenderInput, key: 'five_hour' | 'seven_day', emoji: string, label: string, windowSec: number, withPace = true): Run[] | null {
200 const w = i.limits[key]
201 if (!w || w.resets_at <= i.now) return null // absent, or an expired window: a fossil
202 const shown = roundHalfEven(w.used_percentage)
203 const pace = withPace ? paceMultiplier(w.used_percentage, w.resets_at, windowSec, i.now) : null
204 return [{ t: `${emoji} ${label} ` }, { t: `${shown}%`, tone: levelTone(shown) }, ...(pace === null ? [] : [{ t: ` ${pace.toFixed(1)}x` }])]
205}
206
207const cleanLine = (parts: Run[][]): Line[] => (parts.length ? [parts.flatMap((p, k) => (k === 0 ? p : [CLEAN_SEPARATOR, ...p]))] : [])
208
209/** Clean Minimal: `🧠 42% | 🕔 5h 38% | 🗓️ 7d 12%`, no model, cost or multipliers. */
210function segCleanMin(i: RenderInput): Line[] {
211 const parts: Run[][] = []
212 if (i.ctxPct !== null) {
213 const shown = roundHalfEven(i.ctxPct)
214 parts.push([{ t: '🧠 ' }, { t: `${shown}%`, tone: levelTone(shown) }])
215 }
216 for (const w of [cleanWindow(i, 'five_hour', '🕔', '5h', 5 * 3600, false), cleanWindow(i, 'seven_day', '🗓️', '7d', 7 * 86400, false)]) if (w) parts.push(w)
217 return cleanLine(parts)
218}
219
220/** Clean's second line: `📁 pip-skills | 🌿 feat/x +2 ~3 | 🔀 #187 approved`; what is absent goes, separator with it. */
221function segCleanWhere(i: RenderInput): Line[] {
222 const parts: Run[][] = [[{ t: `📁 ${i.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? i.cwd}`, tone: 'magenta' }]]
223 if (i.git?.branch) {
224 const ahead = i.git.ahead > 0 && i.git.hasUpstream ? ` +${i.git.ahead}` : ''
225 const dirty = i.git.uncommitted > 0 ? ` ~${i.git.uncommitted}` : ''
226 parts.push([{ t: `🌿 ${i.git.branch}${ahead}${dirty}`, tone: 'green' }])
227 }
228 if (i.pr && i.pr.number > 0) {
229 const pr: Run[] = [i.pr.stale ? { t: `🔀 #${i.pr.number}`, tone: 'grey' } : { t: `🔀 #${i.pr.number}` }] // unconfirmed: dimmed
230 if (i.pr.reviewState) pr.push({ t: ` ${i.pr.reviewState}`, tone: i.pr.stale ? 'grey' : REVIEW_TONE[i.pr.reviewState] ?? 'grey' })
231 parts.push(pr)
232 }
233 return cleanLine(parts)
234}
235
236function segClean(i: RenderInput): Line[] {
237 const parts: Run[][] = [[{ t: '🤖 ' }, { t: i.modelName || 'Claude', tone: 'cyan' }]]
238 if (i.ctxPct !== null) {
239 const shown = roundHalfEven(i.ctxPct)
240 const size = i.ctxWindow && i.ctxWindow > 0 ? i.ctxWindow : null
241 // The engine reports a percentage and the window, not a token count: used is their product.
242 parts.push([{ t: `🧠 ${size ? `${fmtTokens((i.ctxPct / 100) * size)}/${fmtTokens(size)} ` : ''}` }, { t: `${shown}%`, tone: levelTone(shown) }])
243 }
244 if (i.costUsd !== null) parts.push([{ t: `💵 $${i.costUsd.toFixed(2)}` }])
245 for (const w of [cleanWindow(i, 'five_hour', '🕔', '5h', 5 * 3600), cleanWindow(i, 'seven_day', '🗓️', '7d', 7 * 86400)]) if (w) parts.push(w)
246 return cleanLine(parts)
247}
248
249export const SEGMENTS: Record<string, (i: RenderInput) => Line[]> = {
250 context: segContext, cache: segCache, limits: segLimits, cost: segCost, model: segModel, clean: segClean, cleanmin: segCleanMin, cleanwhere: segCleanWhere, git: segGit, dir: segDir, changes: segChanges, pr: segPr,
251}
252
253/** The configured segments as lines of names; `/` starts a new line, unknown names are dropped. */
254export function layout(spec: string | undefined): string[][] {
255 const text = spec?.trim() || DEFAULT_SEGMENTS
256 return text.split('/').map(line => line.split(',').map(s => s.trim()).filter(n => Object.hasOwn(SEGMENTS, n)))
257}
258
259const SEPARATOR: Run = { t: ' │ ', tone: 'grey' }
260
261/** Each configured line as runs, parts joined by the grey bar; an empty line is dropped. */
262export function draw(i: RenderInput): Line[] {
263 const lines: Line[] = []
264 for (const names of layout(i.env.CENSUS_STATUSLINE_SEGMENTS)) {
265 const parts = names.flatMap(n => (Object.hasOwn(SEGMENTS, n) ? SEGMENTS[n]?.(i) : undefined) ?? [])
266 if (parts.length) lines.push(parts.flatMap((p, k) => (k === 0 ? p : [SEPARATOR, ...p])))
267 }
268 return lines
269}
270
271export const plain = (line: Line): string => line.map(r => r.t).join('')
272
273/** Terminal columns a string takes: wide emoji and CJK count 2, a variation selector widens its base. */
274export function displayWidth(text: string): number {
275 let w = 0
276 let joined = false // after a zero-width joiner the next emoji is part of the same grapheme
277 for (const ch of text) {
278 const cp = ch.codePointAt(0) ?? 0
279 if (joined) {
280 joined = false
281 if (cp >= 0x1f000 || WIDE_BMP.has(cp) || cp === 0x2640 || cp === 0x2642 || cp === 0x2695 || cp === 0x2764) continue
282 }
283 if (cp === 0x200d) joined = true
284 if (cp === 0xfe0f) w += 1
285 else if (cp === 0x200d || (cp >= 0x300 && cp <= 0x36f)) w += 0
286 else if (cp >= 0x1f000 || (cp >= 0x2e80 && cp <= 0xa4cf) || (cp >= 0xac00 && cp <= 0xd7a3) || (cp >= 0xff00 && cp <= 0xff60) || WIDE_BMP.has(cp)) w += 2
287 else w += 1
288 }
289 return w
290}
291const WIDE_BMP = new Set([0x231a, 0x231b, 0x23e9, 0x23ea, 0x23eb, 0x23ec, 0x23f0, 0x23f3, 0x2614, 0x2615, 0x26a1, 0x2705, 0x270a, 0x270b, 0x2728, 0x274c, 0x2753, 0x2754, 0x2755, 0x2757, 0x2b50, 0x2b55])
292export const lineWidth = (line: Line): number => displayWidth(plain(line))
293
294/** Drop whole trailing parts until the line fits `columns`; a lone part is kept (the surface truncates it). */
295export function fit(line: Line, columns: number): Line {
296 const parts: Line[] = [[]]
297 const seps: Run[] = []
298 for (const r of line) {
299 if (r === SEPARATOR || r === CLEAN_SEPARATOR) {
300 parts.push([])
301 seps.push(r)
302 } else parts[parts.length - 1]?.push(r)
303 }
304 const join = () => parts.flatMap((p, k) => (k === 0 ? p : [seps[k - 1] ?? SEPARATOR, ...p]))
305 while (parts.length > 1 && lineWidth(join()) > columns) {
306 parts.pop()
307 seps.pop()
308 }
309 return join()
310}
311