Test harness only: lets claude plugin test run tests/ against plugin/. Never installed; the marketplace points at plugin/.

A personal collection of Claude Code skills for serious engineering work — from PR review to architectural auditing. Built for real workflows, shared because they might help yours.
Four plugins, each with a distinct purpose:
| Plugin | Purpose |
|---|---|
| Puritan | Architectural doctrine enforcement — plan patterns, audit code, author rules |
| Tribunal | PR review workflow — fetch, triage, validate, action, and resolve GitHub PR comments |
| email-absolution | HTML email auditing and generation — doctrines, visitation, and absolution |
| django-inquisition | Django ORM performance auditor — ~70 heuristics, tier-grouped findings, signal-aware |
You can also install via Claude Code's plugin commands. From within a Claude Code session:
/plugin marketplace add ppryde/pip-skills
/plugin install puritan@ppryde/pip-skills
/plugin install tribunal@ppryde/pip-skills
/plugin install email-absolution@ppryde/pip-skills
/plugin install django-inquisition@ppryde/pip-skills
Or from the terminal CLI:
# Install all plugins
claude plugin install puritan@ppryde/pip-skills
claude plugin install tribunal@ppryde/pip-skills
claude plugin install email-absolution@ppryde/pip-skills
claude plugin install django-inquisition@ppryde/pip-skills
After installing, the skills are available as slash commands:
/puritan:covenant — architecture planning and pattern selection
/puritan:inquisition — audit codebase against configured doctrines
/puritan:scriptorium — author new architecture doctrines
/tribunal:reckoning — triage and action GitHub PR review comments
/email-absolution:elder — email planning, Q&A, and config setup
/email-absolution:visitation — audit an email template against doctrine
/email-absolution:scribe — generate a template correct by construction
/django-inquisition:optimise-orm — audit a Django file or symbol for ORM performance issues
These skills are built around two ideas:
1. Architecture should be codified, not tribal knowledge. Architectural decisions that live only in people's heads — or in an ADR doc nobody reads — don't survive team turnover or code reviews. Puritan turns those decisions into auditable doctrine files that Claude can check your code against, commit by commit.
2. PR review is a workflow, not a scroll. Bot reviewers and human reviewers leave dozens of comments across multiple rounds. Tribunal treats this as a structured workflow: fetch everything, categorise by source and type, validate each comment against the actual current code, propose fixes, apply them with your approval, and resolve the threads.
All plugins operate in the voice of a deeply principled but self-aware Puritan inspector. Violations are heresies. Fixes are absolution. The codebase is the sanctum.
The persona is flavour, not a barrier to clarity — every verdict is technically precise and actionable. The Witchfinder is dramatic, not obscure.
settings.snippets.json at the repo root contains custom spinner verbs that replace Claude Code's default "Thinking…" messages with in-character Witchfinder flavour while the skills are running.
To use them, copy the file into your Claude Code settings directory:
cp settings.snippets.json ~/.claude/settings.snippets.json
If you already have a settings.snippets.json, merge the spinnerVerbs block into it manually.
The
mode: "replace"setting replaces all default spinner verbs with these. If you'd prefer to add them alongside the defaults, change it to"append".
Issues and PRs welcome. If you extend a doctrine or add a new one, the Scriptorium skill can help you author it to the required standard.
A personal collection of Claude Code skills for serious engineering work — from PR review to architectural auditing. Built for my own workflows, shared because they might help yours.
plugin/hooks/register.tsx 1923 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { Activity, Awaiting, Consent, EventKind, EventRecord, Git, Latch, Mode, Pending, PhoneFacts, PendingReason, RateLimit, Override, Settings, StepId } from '../types'
4import { ASK, DEFAULT_OVERRIDES, checkOverrides, fromModelThresholds, formatKey, formatOverride, formatWindow, overridesJson, ordered, parseKey, parseOverridesArgs, patternFor, removeOverride, resolve, sameKey, setOverride } from '../core/overrides'
5import type { Resolved } from '../core/overrides'
6import { COMMANDS, TOOL, TOOL_FULL, classicSessionPath, configRoot, eventsPath, handoverPath, overridesPath } from '../core/name'
7import { DEFAULTS, PENDING_KEEP_MS, PENDING_PREFIX, STORE_KEY, STRANDED_PREFIX, loadSettings, pendingKey, standingKey, strandedKey } from '../core/settings'
8import type { Stranded } from '../core/settings'
9import { EMPTY_ACTIVITY, WORKING_MS, armed, classifyOrigin, mode, onPhone, record, transition } from '../core/arming'
10import type { Signal } from '../core/arming'
11import { appendLine, dayKey, makeRecord } from '../core/eventlog'
12import { COALESCE_MS, GIT_ARGV, GIT_DIR_ARGV, parseGit, touchesGit, watchPaths } from '../core/git'
13import { INPUT_SCHEMA, SENT_MAX, mergeStanding, sentSection, TOOL_DESCRIPTION, fresh, grownEnough, injectText, instructionText, isHandoverRequest, limitResumeText, mentionsHandover, STOP_NOW, nextThreshold, parseFields, renderHandover, resumeText, reusable } from '../core/handover'
14import { HOME_VARS_CHECKED } from '../core/home'
15import { TITLE_CMD, archiveName, isArchived, lastTitle } from '../core/title'
16import { TAIL_CMD, type CacheTtl, cacheLinesFromText, parseWrites, transcriptPathFor, ttlFromWrites } from '../core/cache-ttl'
17import { TTL_1H, fireAt, holdOnReturn, rearm, shouldFire } from '../core/last-light'
18import { clearGate, needsRcHint } from '../core/surfaces'
19import { applyAnswers, extractAnswers, isStep, nextCard, questionFor } from '../core/setup'
20import { RESUME_DELAY_MS, earlyStopDue, formatHHMM, latchCleared, latchFromMeasure, latchFromStopFailure, nextHop } from '../core/limits'
21import { classicHooksInstalled } from '../core/interlock'
22import { messagesAfterHandover, renderTail } from '../core/tail'
23import { V } from '../core/voice'
24import type { WaitReason } from '../core/voice'
25
26// The effectful shell: the ONLY file that touches `$`. Decisions live in ../core.
27
28// $.state is per session and every /clear wipes it (PROBES §9): these atoms hold only what a
29// fresh session may forget.
30const modeA = atom({ plugin: 'context-vigil-mod', key: 'mode' } as const, 'idle')
31const contextA = atom({ plugin: 'context-vigil-mod', key: 'contextPct' } as const, null)
32const windowA = atom({ plugin: 'context-vigil-mod', key: 'contextWindow' } as const, null as number | null)
33const modelA = atom({ plugin: 'context-vigil-mod', key: 'contextModel' } as const, null as string | null)
34const baselineA = atom({ plugin: 'context-vigil-mod', key: 'baselinePct' } as const, null as number | null)
35const lastNudgedA = atom({ plugin: 'context-vigil-mod', key: 'lastNudged' } as const, null)
36const barShownA = atom({ plugin: 'context-vigil-mod', key: 'barShown' } as const, false)
37const barDismissedA = atom({ plugin: 'context-vigil-mod', key: 'barDismissed' } as const, false)
38const pendingA = atom({ plugin: 'context-vigil-mod', key: 'pending' } as const, null)
39const pausedA = atom({ plugin: 'context-vigil-mod', key: 'paused' } as const, false)
40const draftWaitA = atom({ plugin: 'context-vigil-mod', key: 'draftWait' } as const, false)
41const countdownA = atom({ plugin: 'context-vigil-mod', key: 'countdownEndsAt' } as const, null)
42const transcriptA = atom({ plugin: 'context-vigil-mod', key: 'transcriptPath' } as const, null as string | null)
43// Information only (PROBES §11): what the session's cache is. The fire-time check stays the gate.
44const cacheTtlA = atom({ plugin: 'context-vigil-mod', key: 'cacheTtl' } as const, 'unknown' as CacheTtl)
45const ttlReadA = atom({ plugin: 'context-vigil-mod', key: 'ttlRead' } as const, false)
46const ttlInfoDismissedA = atom({ plugin: 'context-vigil-mod', key: 'ttlInfoDismissed' } as const, false)
47// Did the person's latest message mention a handover at all? Lets the model's tool call count as asked for.
48const handoverMentionedA = atom({ plugin: 'context-vigil-mod', key: 'handoverMentioned' } as const, false)
49// The person started a handover (types: Consent). In $.state, so the clear that ends it also wipes it.
50const consentA = atom({ plugin: 'context-vigil-mod', key: 'consent' } as const, null as Consent | null)
51const lastApiA = atom({ plugin: 'context-vigil-mod', key: 'lastApiAt' } as const, null)
52const awaitingA = atom({ plugin: 'context-vigil-mod', key: 'awaiting' } as const, null as Awaiting | null)
53const deferredA = atom({ plugin: 'context-vigil-mod', key: 'deferred' } as const, null as Awaiting | null)
54// Prompts the person sent since the handover was asked for and before its tool call (WF-303).
55const sentDuringA = atom({ plugin: 'context-vigil-mod', key: 'sentDuring' } as const, [] as string[])
56const handoverCountA = atom({ plugin: 'context-vigil-mod', key: 'handoverCount' } as const, 0)
57// The phone facts of `activity`, written through so a hot reload (which keeps $.state) restores
58// them; a clear wipes this, so the clear branch writes it again from the module copy.
59// The prompts held while the return question is open (R1-19, R2-11). In $.state so a hot reload
60// that kills the module (and its ask's closure) still knows what is owed; a clear wipes it.
61// R3-02: the held text also lives here, because a /clear or /resume wipes $.state while the ask stays open.
62let returnHeldMirror: string[] | null = null
63const returnHeldA = atom({ plugin: 'context-vigil-mod', key: 'returnHeld' } as const, null as string[] | null)
64const phoneA = atom({ plugin: 'context-vigil-mod', key: 'phoneFacts' } as const, null as PhoneFacts | null)
65
66// An account fact in $.store: the limit latch, shared by every session of the account.
67const LATCH_KEY = 'latch'
68
69// Facts about the person and the install that a /clear must not forget: module variables
70// survive it (same process). A new session or a hot reload (bindSession) starts them fresh,
71// counting that moment as the person being here for one idle window.
72let activity: Activity = EMPTY_ACTIVITY
73let lastLightArmed = false
74let standDown = false
75// Per process, never reset: each running session owes its own early stop before a hard limit,
76// and a clear (new session id) must not re-fire one for the same window. A reload may re-fire once.
77let firedEarlyStops: string[] = []
78// The limit resume waiting on its handover file; the tool call fills `path` when it is written.
79let limitResume: { path: string | null; at: number; stoppedAt: number; gen: number } | null = null
80let resumeChain: { cancel: () => void } | null = null
81let resumeGen = 0
82// The timer that lifts the account latch for this process: one, replaced never stacked (R2-04).
83let latchTimer: { cancel: () => void } | null = null
84// The RC hint is shown once per session: a clear wipes $.state, so it cannot live there.
85// A new session (bindSession) resets it; resetCaches leaves it alone.
86let rcHinted = false
87
88// Module caches: rebuilt at session.start / after a hot reload.
89let root: string | null = null // null: no config dir known, so nothing is written (configRoot)
90let session = 'unknown'
91let cwd = ''
92let settings: Settings = DEFAULTS
93let git: Git = { branch: null, dirty: [] }
94let gitTimer: { cancel: () => void } | null = null
95const edited = new Set<string>()
96let dayText: Record<string, string> = {}
97// lastApiAt, mirrored out of $.state: a /clear wipes the atom, and the clear branch must still
98// know whether turns have run since a parked handover was written (R1-10).
99let lastApiMirror: number | null = null
100let clearParked = false
101let unattendedClear = false
102let lastWait: WaitReason | null = null
103let retryTimer: { cancel: () => void } | null = null
104// A /clear handed to the engine and not yet run: it is queued until the session is idle (R2-10),
105// so a second one must not follow it. Cleared when the command settles.
106// /vigil-pause: per process, so it outlives a /clear (which wipes $.state); pausedA mirrors it for the band.
107let paused = false
108let lastPausedDue: number | null = null
109let clearInFlight = false
110let draftAsked: string | null = null // the pending whose draft wait was already asked about: once per handover
111let skipDraftFor: string | null = null // the pending the person chose "Clear and resume now" for: the draft gate is off for that one clear
112// Prompts from other sessions, schedules and background tasks: held while a clear-bound handover waits for its clear.
113const HOLD_ORIGINS = new Set(['task-notification', 'scheduled-trigger', 'peer', 'peer-send-message', 'projects-relay', 'coordinator', 'observer', 'observer-activity'])
114// The last API turn as the mod issued its own clear, for the handover it clears into: the engine queues
115// the clear behind the running turn, and turns that finish meanwhile must not make the handover stale.
116let issuedClear: { path: string; apiAt: number } | null = null
117let setupRun: { only: string | undefined; asked: StepId[] } | null = null
118let lastLightTimer: { cancel: () => void } | null = null
119let countdownTick: { cancel: () => void } | null = null
120
121// A timer-driven job that threw: logged, never an unhandled rejection (R2-15).
122async function timerFailed($: EngineInterface, job: string, err: unknown) {
123 await log($, 'guard.wait', { reason: 'timer-error', job, error: String(err) }).catch(() => {})
124}
125
126async function nowMs($: EngineInterface): Promise<number> {
127 return $.clock.now()
128}
129
130// Appends are serialised through one chain, so a day file's first read-then-append cannot be raced
131// by a second hook (R1-15). A day file that exists but cannot be read is never overwritten.
132let logChain: Promise<void> = Promise.resolve()
133const logWriteFailed = new Set<string>()
134
135async function appendToDayFile($: EngineInterface, path: string, rec: EventRecord) {
136 if (dayText[path] === undefined) {
137 try {
138 dayText[path] = String(await $.fs.read(path))
139 } catch (err) {
140 if (!/ENOENT|no such file|not found/i.test(String((err as { code?: string; message?: string })?.code ?? '') + String((err as Error)?.message ?? err))) {
141 try { await $.ui.log(`context-vigil-mod: event log skipped, ${path} is unreadable: ${String(err)}`) } catch { /* nowhere left to say it */ }
142 return
143 }
144 dayText[path] = ''
145 }
146 }
147 dayText[path] = appendLine(dayText[path] ?? '', rec)
148 await $.fs.write(path, dayText[path] ?? '').catch(async (err: unknown) => {
149 // A log that cannot be written must not be silent, and must not become a loop: say it once per path.
150 if (logWriteFailed.has(path)) return
151 logWriteFailed.add(path)
152 try { await $.ui.log(`context-vigil-mod: event log not written, ${path}: ${String(err)}`) } catch { /* nowhere left to say it */ }
153 })
154}
155
156async function log($: EngineInterface, kind: EventKind, fields: Record<string, unknown> = {}) {
157 if (!root) return
158 const now = await nowMs($)
159 const path = eventsPath(root, dayKey(now), session)
160 const rec = makeRecord(now, session, kind, fields)
161 const turn = logChain.then(() => appendToDayFile($, path, rec))
162 logChain = turn.catch(() => {})
163 await turn
164}
165
166// PROBES.md §1 decides the channel; both are sent until it says otherwise.
167async function notify($: EngineInterface, text: string) {
168 await Promise.all([$.ui.toast(text), $.ui.log(text)]).catch(() => {})
169}
170
171// Every plugin prompt goes through here: from a timer, never awaited by the hook the turn waits on.
172function submitSoon($: EngineInterface, prompt: { text: string; asUser?: true }, delayMs = 0, onSent?: () => void, onFailed?: () => void) {
173 $.clock.after(delayMs, () => { void $.prompt.submit(prompt).then(() => onSent?.(), () => onFailed?.()) })
174}
175
176// A prompt sent right after a clear can be refused while the session is still starting (slow SessionStart
177// hooks). Retry with backoff -- the first attempt after `firstDelayMs`, then 1, 2, 4 and 8 s later -- and
178// give up only after the last. A success ends the chain (never two submits); a human prompt or a newer
179// chain cancels it: the person's own words win. The engine offers no readiness signal, hence the backoff.
180const RETRY_AFTER_MS = [1000, 2000, 4000, 8000]
181let submitGen = 0 // bumped by a human prompt and by every new chain
182
183function sleepMs($: EngineInterface, ms: number): Promise<void> {
184 return new Promise(resolve => { $.clock.after(ms, () => resolve()) })
185}
186
187async function submitWithRetry($: EngineInterface, prompt: { text: string; asUser?: true }, firstDelayMs: number): Promise<'sent' | 'cancelled' | 'failed'> {
188 const gen = ++submitGen
189 const delays = [firstDelayMs, ...RETRY_AFTER_MS]
190 for (let attempt = 1; attempt <= delays.length; attempt++) {
191 await sleepMs($, delays[attempt - 1]!)
192 if (gen !== submitGen) {
193 await log($, 'guard.wait', { reason: 'resume-cancelled', attempt })
194 return 'cancelled'
195 }
196 try {
197 await $.prompt.submit(prompt)
198 } catch (err) {
199 await log($, 'guard.wait', { reason: 'resume-retry', attempt, error: String(err) })
200 continue
201 }
202 await log($, 'resume.sent', { attempt })
203 return 'sent'
204 }
205 return 'failed'
206}
207
208// What the model is told about its standing orders after a save: nothing when nothing needs saying.
209function standingNote(o: ReturnType<typeof mergeStanding>): string {
210 const parts = [
211 o.retired.length ? `Retired standing orders: ${o.retired.join('; ')}.` : '',
212 o.unmatched.length ? `No standing order matched these retirements (nothing was retired): ${o.unmatched.join('; ')}.` : '',
213 o.warning ?? '',
214 ].filter(Boolean)
215 return parts.length ? `. ${parts.join(' ')}` : ''
216}
217
218// WF-303: a prompt from the person while a handover is being written (asked for, or saved and not yet
219// cleared) is kept verbatim for the resume. Slash commands are not prompts to answer.
220async function recordSent($: EngineInterface, text: string) {
221 if (standDown || !text.trim() || text.trimStart().startsWith('/')) return
222 if (await read($, awaitingA)) {
223 await update($, sentDuringA, l => (l.length < SENT_MAX ? [...l, text] : l))
224 return
225 }
226 const pending = await read($, pendingA)
227 if (pending && (pending.sent?.length ?? 0) < SENT_MAX) {
228 await savePending($, { ...pending, sent: [...(pending.sent ?? []), text] })
229 }
230}
231
232// Prompts held for a clear that then parked never reach the next session soon: give them back to this one.
233async function releaseHeld($: EngineInterface) {
234 const pending = await read($, pendingA)
235 if (!pending?.held?.length) return
236 const held = pending.held
237 const { held: _spent, ...rest } = pending
238 await savePending($, rest)
239 await log($, 'prompt.released', { count: held.length })
240 // Never silently: a refused or overtaken submit shows the held text instead.
241 const text = held.join('\n\n')
242 void submitWithRetry($, { text }, 500)
243 .then(outcome => (outcome === 'sent' ? undefined : notify($, V.heldNotSent(text))))
244 .catch(err => timerFailed($, 'held-release', err))
245}
246
247function resumeSoon($: EngineInterface, prompt: { text: string; asUser?: true }, path: string | null, held: string | null) {
248 void submitWithRetry($, prompt, 500)
249 .then(outcome => (outcome === 'failed' ? resumeFailed($, path, held) : undefined))
250 .catch(err => timerFailed($, 'resume-submit', err))
251}
252
253// A resume or held-prompt submit that is refused: say so, with the handover and the held text.
254async function resumeFailed($: EngineInterface, path: string | null, held: string | null) {
255 await notify($, V.resumeFailed(path, held))
256 await log($, 'guard.wait', { reason: 'resume-rejected', path, held: held !== null })
257}
258
259// An awaited handover that ends without a save: the prompts sent during it go with it.
260async function abandonAwaiting($: EngineInterface) {
261 await update($, awaitingA, () => null)
262 await update($, sentDuringA, () => [])
263}
264
265// PROBES.md §7: a mod never sees its own submit in prompt.submit, so `started` is marked here.
266function submitInstruction($: EngineInterface, reason: PendingReason) {
267 submitSoon($, { text: instructionText(reason) }, 0, () => {
268 void update($, awaitingA, a => (a ? { ...a, started: true } : a))
269 }, () => {
270 // A rejected submit must not leave the handover waiting for a turn that never comes.
271 void (async () => {
272 await abandonAwaiting($)
273 await withdrawConsent($) // told it failed: a later save is asked about, never cleared silently
274 await notify($, V.handoverFailed)
275 await log($, 'guard.wait', { reason: 'submit-rejected' })
276 })()
277 })
278}
279
280async function observe($: EngineInterface, signal: Signal) {
281 const now = await nowMs($)
282 // Every change is computed from the value it replaces, so overlapping observers cannot erase each other.
283 activity = record(activity, signal)
284 if (signal.kind === 'prompt' && classifyOrigin(signal.origin) === 'human') await savePhoneFacts($)
285 // R1-09: an explicit act from the person cancels a handover that waited on the latch.
286 if ((signal.kind === 'human-command' || (signal.kind === 'prompt' && classifyOrigin(signal.origin) === 'human')) && (await read($, deferredA))) {
287 const dropped = await read($, deferredA)
288 await update($, deferredA, () => null)
289 await notify($, V.deferredDropped)
290 await log($, 'guard.wait', { reason: 'deferred-dropped', deferred: dropped?.reason })
291 }
292 // R2-01: the same act turns a clear the latch parked into an offer; the handover stays pending.
293 if (clearParked && lastWait === 'latched' && (signal.kind === 'human-command' || (signal.kind === 'prompt' && classifyOrigin(signal.origin) === 'human'))) {
294 const parked = await read($, pendingA)
295 if (parked) await dropParkedClear($, parked, 'human')
296 }
297 // Spec §2: a non-empty draft in the terminal box is you being here.
298 if (signal.kind === 'agent-step' && (await $.prompt.read()).text.trim()) activity = record(activity, { kind: 'edit', at: now })
299 const act = activity // this observation's view: later awaits may move `activity` on
300 const next = mode(act, now, settings)
301 let prev: string | undefined
302 await update($, modeA, p => { prev = p; return next })
303 if (prev === undefined || prev === next) return
304 const t = transition(prev as Mode, next)
305 if (t && settings.auto) {
306 await log($, t, { from: prev, to: next, idleMs: act.lastHumanAt === null ? null : now - act.lastHumanAt, origin: act.lastHumanOrigin })
307 }
308 if (t === 'arm') await maybeHintRc($)
309}
310
311// A clear the latch parked is no longer going to run: it is offered instead (spec §5). Pending and
312// file stay; `clearParked` stays so the latch's lift leaves it alone. Never silent.
313async function dropParkedClear($: EngineInterface, pending: Pending, cause: 'human' | 'auto-off' | 'attended' | 'stale') {
314 lastWait = null
315 await notify($, V.pendingOffer(pending.path))
316 await log($, 'guard.wait', { reason: 'parked-dropped', cause })
317 await releaseHeld($)
318}
319
320// Setup asks through $.ui.ask, one step at a time: no prompt is submitted and nothing
321// reaches the model. The dialog does not pass through this mod's own tool.call hook
322// (PROBES.md §6), so answers are applied here, not there.
323async function startSetup($: EngineInterface, only?: string) {
324 if (only !== undefined && !isStep(only)) { await notify($, V.setupUsage); return }
325 const run = { only, asked: [] as StepId[] }
326 setupRun = run
327 if (!nextCard(settings, [], only).length) { setupRun = null; await notify($, V.setupSaved); return }
328 // After the command has replied: the dialogs follow it rather than holding it open.
329 $.clock.after(0, () => { void askSteps($, run).catch(err => timerFailed($, 'setup', err)) })
330}
331
332async function askSteps($: EngineInterface, run: NonNullable<typeof setupRun>) {
333 for (;;) {
334 // A clear can land inside any await (a store write included): never ask into the new session.
335 if (setupRun !== run) return
336 const id = nextCard(settings, run.asked, run.only)[0]
337 if (id === undefined) break
338 let explain = false
339 for (;;) {
340 const q = questionFor(id, explain)
341 const answer = await $.ui
342 .ask(q.question, { header: q.header, options: q.options, ...(q.multiSelect ? { multiSelect: true as const } : {}) })
343 .then(a => ({ a }), (err: unknown) => ({ err }))
344 // A clear or another /vigil-setup took over while the dialog was open: its answer is not ours.
345 if (setupRun !== run) return
346 // A dismissal and a failed dialog reject alike (no reason is typed): either way stop, log
347 // why, and say so, so a failure is never silent. What was answered is already saved.
348 if ('err' in answer) {
349 setupRun = null
350 await log($, 'setup', { steps: [id], stopped: String(answer.err).slice(0, 200) })
351 await notify($, V.setupStopped)
352 return
353 }
354 await observe($, { kind: 'human-command', at: await nowMs($) })
355 await reloadSettings($)
356 const applied = applyAnswers(settings, [{ step: id, answer: answer.a }])
357 if (setupRun !== run) return
358 await log($, 'setup', { steps: [id], retell: applied.retell })
359 // The log write is an await too: a newer /vigil-setup or a clear may have taken over during it.
360 if (setupRun !== run) return
361 if (applied.retell.length) { explain = true; continue }
362 settings = applied.settings
363 await $.store.set(STORE_KEY, settings)
364 if (id === 'rc') await log($, 'rc.answer', { answer: settings.rcAutoClear })
365 break
366 }
367 run.asked.push(id)
368 }
369 if (setupRun !== run) return
370 setupRun = null
371 await notify($, V.setupSaved)
372 // The person who just answered is here: a clear parked while they were away is offered, never run.
373 const parked = clearParked ? await read($, pendingA) : null
374 if (parked) await notify($, V.pendingOffer(parked.path))
375}
376
377// Never a dialog mid-run (WF-262): the question lives in /vigil-setup. Unanswered follows auto mode
378// (clears on the phone, safeguards kept); this says so once per session, and only when the stand-down and the latch leave the mod free to speak.
379async function maybeHintRc($: EngineInterface) {
380 if (!needsRcHint(onPhone(activity), settings.rcAutoClear, settings.auto)) return
381 if (rcHinted || standDown || (await readLatch($))) return
382 rcHinted = true
383 await notify($, V.rcHint)
384 await log($, 'rc.answer', { hinted: true })
385}
386
387async function refreshGit($: EngineInterface) {
388 gitTimer = null
389 const run = (argv: readonly string[]) =>
390 $.process.run(argv, { cwd }).then(r => ({ exitCode: r.exitCode, stdout: r.stdout })).catch(() => ({ exitCode: 1, stdout: '' }))
391 const [b, s] = await Promise.all([run(GIT_ARGV.branch), run(GIT_ARGV.status)])
392 git = parseGit(b, s)
393}
394
395function scheduleGit($: EngineInterface) {
396 if (gitTimer) return
397 gitTimer = $.clock.after(COALESCE_MS, () => { void refreshGit($) })
398}
399
400// RESET: every module cache and timer (pre-flight F3), in one place — a hot reload, a reused
401// module or a /clear must start clean. Tasks 13–15 add their own module variables here.
402function resetCaches() {
403 gitTimer?.cancel()
404 gitTimer = null
405 git = { branch: null, dirty: [] }
406 edited.clear()
407 dayText = {}
408 retryTimer?.cancel()
409 retryTimer = null
410 clearParked = false
411 unattendedClear = false
412 lastWait = null
413 lastLightTimer?.cancel()
414 lastLightTimer = null
415 setupRun = null
416 overridesRun = null
417 ambiguityTold.clear()
418 countdownTick?.cancel()
419 countdownTick = null
420}
421
422async function savePhoneFacts($: EngineInterface) {
423 const { lastHumanOrigin, lastBridgeAt } = activity
424 await update($, phoneA, () => ({ lastHumanOrigin, lastBridgeAt }))
425}
426
427// overrides.json is the person's to edit: read whenever a threshold is decided, written only when
428// missing (the default override, so it is visible) or by /vigil-overrides. A fault drops only its override,
429// and is told once per distinct file text.
430let overrides: Override[] = DEFAULT_OVERRIDES
431let faultsToldFor: string | null = null
432const ambiguityTold = new Set<string>()
433
434async function loadOverrides($: EngineInterface): Promise<{ faults: string[] }> {
435 if (!root) { overrides = DEFAULT_OVERRIDES; return { faults: [] } }
436 const path = overridesPath(root)
437 const text = await $.fs.read(path).then(t => String(t), () => null)
438 if (text === null) {
439 overrides = DEFAULT_OVERRIDES
440 await $.fs.write(path, overridesJson(DEFAULT_OVERRIDES)).catch(() => {})
441 return { faults: [] }
442 }
443 const checked = checkOverrides(text)
444 // A file that does not parse names no override to drop: keep the last good read (the default
445 // override before any) rather than lose every override to one stray comma.
446 if (!checked.fileFault) overrides = checked.overrides
447 if (checked.faults.length && text !== faultsToldFor) {
448 faultsToldFor = text
449 await notify($, checked.fileFault
450 ? V.overridesFileFault(path, checked.faults[0] ?? '', ordered(overrides).map(o => ` ${formatOverride(o)}`).join('\n') || ' (no overrides)')
451 : V.overridesFaults(path, checked.faults.length, checked.faults.map(f => ` ${f}`).join('\n')))
452 }
453 return { faults: checked.faults }
454}
455
456async function saveOverrides($: EngineInterface, next: Override[]): Promise<boolean> {
457 if (!root) return false
458 const ok = await $.fs.write(overridesPath(root), overridesJson(next)).then(() => true, () => false)
459 if (ok) { overrides = next; await log($, 'setup', { overrides: next }) }
460 return ok
461}
462
463// Overrides 0.1.3 saved in the settings store move to overrides.json once; one already in the file
464// for the same key stands. The store field is dropped only after the file is written.
465async function migrateModelThresholds($: EngineInterface) {
466 const raw = await $.store.get(STORE_KEY)
467 if (!root || !raw || typeof raw !== 'object' || !('modelThresholds' in raw)) return
468 const { overrides: moved, dropped } = fromModelThresholds(raw)
469 const fresh = moved.filter(m => !overrides.some(o => sameKey(o, m)))
470 const kept = moved.filter(m => !fresh.includes(m))
471 if (fresh.length && !(await saveOverrides($, fresh.reduce(setOverride, overrides)))) return
472 const { modelThresholds: _gone, ...rest } = raw as Record<string, unknown>
473 await $.store.set(STORE_KEY, rest)
474 settings = loadSettings(rest)
475 if (moved.length || dropped.length) {
476 await notify($, V.overridesMigrated(overridesPath(root), fresh.map(o => ` ${formatOverride(o)}`).join('\n'), kept.map(o => formatKey(o)).join(', '), dropped.join(', ')))
477 }
478}
479
480async function thresholds($: EngineInterface): Promise<Resolved> {
481 return resolve({ nudgeAt: settings.nudgeAt, step: settings.step, lastLightAt: settings.lastLightAt }, overrides, await read($, modelA), await read($, windowA))
482}
483
484async function tellAmbiguity($: EngineInterface, r: Resolved) {
485 if (!r.ambiguous) return
486 const { model, window, fields } = r.ambiguous
487 const key = `${formatKey(model)}|${formatKey(window)}`
488 if (ambiguityTold.has(key)) return
489 ambiguityTold.add(key)
490 await notify($, V.overridesAmbiguous(formatKey(model), formatKey(window), fields.map(f => `${f} ${r.values[f]}%`).join(', '), formatKey({ ...model, ...window })))
491}
492
493async function overridesReport($: EngineInterface, faults: string[]): Promise<string> {
494 const here = await thresholds($)
495 const model = await read($, modelA)
496 const window = await read($, windowA)
497 const from = (k: 'nudgeAt' | 'step' | 'lastLightAt') => here.from[k] ? formatKey(here.from[k]!) : 'settings'
498 const ambiguous = here.ambiguous ? [`⚠️ ${formatKey(here.ambiguous.model)} and ${formatKey(here.ambiguous.window)} both set ${here.ambiguous.fields.join(', ')}; the window wins`] : []
499 return V.overridesList(
500 root ? overridesPath(root) : '',
501 ordered(overrides).map(o => ` ${formatOverride(o)}`).join('\n'),
502 `nudge ${settings.nudgeAt}%, step ${settings.step}%, last light ${settings.lastLightAt}%`,
503 `${model ?? 'model unknown'} · ${window === null ? 'window not measured yet' : formatWindow(window)}`,
504 `nudge ${here.values.nudgeAt}% (${from('nudgeAt')}), step ${here.values.step}% (${from('step')}), last light ${here.values.lastLightAt}% (${from('lastLightAt')})`,
505 [...ambiguous, ...faults.map(f => `⚠️ ${f} — ignored`)].join('\n'),
506 )
507}
508
509// /vigil-overrides add: an override for the session you are in, asked through $.ui.ask like setup.
510let overridesRun: object | null = null
511
512async function askOverrides($: EngineInterface, run: object) {
513 const ask = async (question: string, header: string, options: string[]) => {
514 const a = await $.ui.ask(question, { header, options }).then(x => String(x), () => null)
515 if (overridesRun !== run) return null
516 // An answer is the person here, as in setup: the idle window starts again.
517 if (a !== null) {
518 await observe($, { kind: 'human-command', at: await nowMs($) })
519 if (overridesRun !== run) return null
520 }
521 return a
522 }
523 const model = await read($, modelA)
524 const window = await read($, windowA)
525 const pattern = model ? patternFor(model) : null
526 const keys: { label: string; key: Pick<Override, 'model' | 'window'> }[] = []
527 if (pattern && window !== null) keys.push({ label: `${pattern} on ${formatWindow(window)}`, key: { model: pattern, window } })
528 if (window !== null) keys.push({ label: `Any model on ${formatWindow(window)}`, key: { window } })
529 if (pattern) keys.push({ label: `${pattern} on any window`, key: { model: pattern } })
530 for (const w of [1_000_000, 200_000]) if (keys.length < 2 && w !== window) keys.push({ label: `Any model on ${formatWindow(w)}`, key: { window: w } })
531 const which = await ask(ASK.key, '🔧 Covers', keys.map(k => k.label))
532 if (which === null) { await notify($, V.overridesStopped); return }
533 const key = keys.find(k => k.label === which)?.key ?? parseKey(which)
534 if (!key) { await notify($, V.overridesBadKey(which)); return }
535 const base = (await thresholds($)).values
536 const pct = (label: string | null, lo: number, hi: number): number | null | undefined => {
537 if (label === null) return undefined
538 if (label.startsWith('Inherit')) return null
539 const n = Number(label.replace(/%.*$/, '').trim())
540 return Number.isInteger(n) && n >= lo && n <= hi ? n : undefined
541 }
542 const nudgeAt = pct(await ask(ASK.nudge(formatKey(key)), '🎚️ Nudge at', [`Inherit (${base.nudgeAt}%)`, '25%', '35%', '50%']), 1, 100)
543 if (nudgeAt === undefined) { await notify($, V.overridesStopped); return }
544 const step = pct(await ask(ASK.step, '📏 Step', [`Inherit (${base.step}%)`, '5%', '10%']), 1, 50)
545 if (step === undefined) { await notify($, V.overridesStopped); return }
546 const lastLightAt = pct(await ask(ASK.lastLight, 'Last light', [`Inherit (${base.lastLightAt}%)`, '25%', '50%']), 1, 100)
547 if (lastLightAt === undefined) { await notify($, V.overridesStopped); return }
548 const override: Override = { ...key, ...(nudgeAt !== null ? { nudgeAt } : {}), ...(step !== null ? { step } : {}), ...(lastLightAt !== null ? { lastLightAt } : {}) }
549 if (nudgeAt === null && step === null && lastLightAt === null) { await notify($, V.overridesNothingSet); return }
550 const { faults } = await loadOverrides($)
551 if (overridesRun !== run) return
552 if (!(await saveOverrides($, setOverride(overrides, override)))) { await notify($, V.overridesUnwritable); return }
553 overridesRun = null
554 await notify($, await overridesReport($, faults))
555}
556
557async function bindSession($: EngineInterface) {
558 resetCaches()
559 // A reload keeps $.state: the phone facts come back so the RC gate still sees the phone.
560 activity = { ...EMPTY_ACTIVITY, ...(await read($, phoneA)), lastHumanAt: await nowMs($) }
561 lastLightArmed = false
562 standDown = false
563 rcHinted = false
564 paused = await read($, pausedA) // a hot reload keeps $.state; a new process starts on
565 lastPausedDue = null
566 root = configRoot({
567 CLAUDE_CONFIG_DIR: await $.env.get('CLAUDE_CONFIG_DIR'),
568 HOME: await $.env.get('HOME'),
569 USERPROFILE: await $.env.get('USERPROFILE'),
570 HOMEDRIVE: await $.env.get('HOMEDRIVE'),
571 HOMEPATH: await $.env.get('HOMEPATH'),
572 })
573 session = await $.session.id()
574 cwd = await $.session.cwd()
575 settings = loadSettings(await $.store.get(STORE_KEY))
576 await loadOverrides($)
577 await migrateModelThresholds($)
578 lastApiMirror = await read($, lastApiA)
579}
580
581// Settings are an account fact other sessions write too: re-read before a decision that matters
582// (R1-06). One cheap store read; loadSettings fills what is missing.
583async function reloadSettings($: EngineInterface) {
584 settings = loadSettings(await $.store.get(STORE_KEY))
585}
586
587async function checkInterlock($: EngineInterface) {
588 const at = root
589 const text = at ? await $.fs.read(`${at}/settings.json`).then(t => String(t)).catch(() => null) : null
590 const record = at ? await $.fs.exists(classicSessionPath(at, session)).catch(() => false) : false
591 const classic = classicHooksInstalled(text) || record
592 const was = standDown
593 standDown = classic
594 if (classic && !was) {
595 await notify($, V.classicActive)
596 await log($, 'standdown', { settingsHooks: classicHooksInstalled(text), sessionRecord: record })
597 }
598}
599
600async function readLatch($: EngineInterface): Promise<Latch> {
601 return ((await $.store.get(LATCH_KEY)) as Latch | undefined) ?? null
602}
603
604// Per-session state the new session must not inherit. After a clear the wipe already empties
605// these; reset anyway so nothing leans on it.
606async function resetSessionState($: EngineInterface) {
607 await update($, awaitingA, () => null)
608 await update($, deferredA, () => null)
609 await update($, lastNudgedA, () => null)
610 await update($, baselineA, () => null)
611 await update($, barShownA, () => false)
612 await update($, barDismissedA, () => false)
613 await update($, pausedA, () => paused) // a pause is the person's, not the conversation's
614 await update($, countdownA, () => null)
615 await update($, handoverCountA, () => 0)
616 await update($, cacheTtlA, () => 'unknown')
617 await update($, ttlReadA, () => false)
618 await update($, ttlInfoDismissedA, () => false)
619 await update($, returnHeldA, () => null)
620 await update($, consentA, () => null)
621 // A resume or fork may be a different model and window: never keep the last session's until the
622 // next measure, or /vigil-overrides would list or add for the wrong session.
623 const model = await $.session.model().catch(() => null)
624 const window = (await $.session.usage().catch(() => null))?.context?.window ?? null
625 await update($, modelA, () => model)
626 await update($, windowA, () => window)
627}
628
629async function prunePending($: EngineInterface) {
630 const now = await nowMs($)
631 for (const key of await $.store.keys().catch(() => [] as string[])) {
632 if (key.startsWith(STRANDED_PREFIX)) {
633 const s = (await $.store.get(key)) as Stranded | null | undefined
634 if (!s || typeof s.at !== 'number' || now - s.at > PENDING_KEEP_MS) await $.store.delete(key)
635 continue
636 }
637 if (!key.startsWith(PENDING_PREFIX)) continue
638 const p = (await $.store.get(key)) as Pending | null | undefined
639 if (!p || now - p.createdAt > PENDING_KEEP_MS) await $.store.delete(key)
640 }
641}
642
643async function savePending($: EngineInterface, p: Pending | null) {
644 const prev = await read($, pendingA)
645 await update($, pendingA, () => p)
646 if (p) await $.store.set(pendingKey(p.session), p)
647 else await $.store.delete(pendingKey(prev?.session ?? session))
648}
649
650// An instruction nobody answered for this long, with the agent idle, is lost (R2-03).
651const AWAITING_LOST_MS = 10 * 60_000
652
653// How long a handover the person started keeps counting as asked for, with no clear issued yet:
654// long enough for an instruction queued behind a long turn, short of a later volunteer.
655const CONSENT_MS = 30 * 60_000
656
657// Called by every explicit control that starts a handover, before it starts.
658async function giveConsent($: EngineInterface) {
659 const at = await nowMs($)
660 await update($, consentA, () => ({ at }))
661}
662
663async function hasConsent($: EngineInterface, now: number): Promise<boolean> {
664 const c = await read($, consentA)
665 return c !== null && now - c.at < CONSENT_MS
666}
667
668async function withdrawConsent($: EngineInterface) {
669 await update($, consentA, () => null)
670}
671
672// What startHandover did, so a caller can say it truthfully (R2-14).
673type Started = 'started' | 'reused' | 'covered' | 'standdown' | 'latched' | 'in-flight' | 'paused'
674
675// `rewrite`: never reuse the pending handover, ask for a fresh one (the dialog's "Update it, then clear").
676async function startHandover($: EngineInterface, reason: PendingReason, resume: boolean, unattended: boolean = reason === 'threshold', rewrite = false): Promise<Started> {
677 if (standDown) return 'standdown'
678 if (paused && reason === 'threshold') { await log($, 'paused.skip', { what: 'handover' }); return 'paused' }
679 const now = await nowMs($)
680 // R2-12: a fresh handover is already on disk (one asked for, waiting to clear): an early stop needs
681 // no second one — the limit resume names this file and the waiting clear is left alone.
682 if (reason === 'limit' && reusable(await read($, pendingA), await read($, lastApiA), now)) {
683 await log($, 'guard.wait', { reason: 'limit-covered' })
684 return 'covered'
685 }
686 if (await readLatch($)) {
687 // Spec §5: while latched the mod never submits; Task 14's checkLatch starts it later.
688 await update($, deferredA, () => ({ reason, resume, attempts: 1, started: false, unattended, since: now }))
689 await notify($, V.waiting('latched'))
690 await log($, 'guard.wait', { reason: 'latched', deferred: reason })
691 return 'latched'
692 }
693 // R1-11: one handover in flight at a time; a second instruction would produce a second tool call.
694 // Lost = old AND nothing is running (a queued instruction would have started), so one waiting
695 // behind a long turn is never re-sent; a deleted or altered instruction no longer blocks forever.
696 const inFlight = await read($, awaitingA)
697 if (inFlight) {
698 const idle = activity.lastAgentAt === null || now - activity.lastAgentAt >= WORKING_MS
699 if (now - inFlight.since < AWAITING_LOST_MS || !idle) {
700 await notify($, V.handoverInProgress)
701 await log($, 'guard.wait', { reason: 'handover-in-flight', asked: reason })
702 return 'in-flight'
703 }
704 await abandonAwaiting($)
705 await notify($, V.handoverLost)
706 await log($, 'guard.wait', { reason: 'awaiting-expired', asked: reason })
707 }
708 const pending = await read($, pendingA)
709 if (!rewrite && (reason === 'threshold' || reason === 'request') && reusable(pending, await read($, lastApiA), now)) {
710 // R3-01: the person's /vho wants the resume; a volunteered pending saved resume:false.
711 if (pending && (pending.resume !== resume || (unattended && !pending.unattended))) await savePending($, { ...pending, resume, unattended: pending.unattended || unattended })
712 if (!clearInFlight) scheduleClear($, unattended)
713 return 'reused'
714 }
715 if (pending) await supersedePending($)
716 await update($, sentDuringA, () => []) // the handover starts now: only prompts after this count
717 await update($, awaitingA, () => ({ reason, resume, attempts: 1, started: false, unattended, since: now }))
718 await log($, 'handover.requested', { reason, resume })
719 submitInstruction($, reason)
720 return 'started'
721}
722
723// A stale pending handover gives way to the fresh one: its clear stops waiting and a /clear
724// in between injects nothing old. The file stays on disk.
725async function supersedePending($: EngineInterface) {
726 skipDraftFor = null
727 retryTimer?.cancel()
728 retryTimer = null
729 clearParked = false
730 lastWait = null
731 await setCountdown($, null)
732 await savePending($, null)
733}
734
735// The band draws the seconds left from the clock, which never redraws it: tick while it runs.
736async function setCountdown($: EngineInterface, endsAt: number | null) {
737 await update($, countdownA, () => endsAt)
738 countdownTick?.cancel()
739 countdownTick = endsAt === null ? null : $.clock.every(1000, () => { $.ui.invalidate('ui.render') })
740}
741
742function scheduleClear($: EngineInterface, unattended: boolean) {
743 unattendedClear = unattended
744 clearParked = false
745 retryTimer?.cancel()
746 retryTimer = $.clock.after(0, () => { void tryClear($) })
747}
748
749// The clear waits on a draft: say so once per handover and let the person choose. A dismissed dialog is Postpone.
750async function askDraft($: EngineInterface, path: string) {
751 try {
752 const { step } = (await thresholds($)).values
753 const choice = String(await $.ui.ask(V.draftTitle, [V.draftClearNow, V.draftPostpone(step)]).catch(() => V.draftPostpone(step)))
754 const pending = await read($, pendingA)
755 if (!pending || pending.path !== path || clearInFlight) return // the draft went and the clear ran, or it was superseded
756 await observe($, { kind: 'human-command', at: await nowMs($) })
757 await update($, draftWaitA, () => false)
758 if (choice === V.draftClearNow) {
759 await log($, 'draft.choice', { choice: 'clear' })
760 const draft = (await $.prompt.read()).text
761 if (draft.trim()) {
762 await savePending($, { ...pending, followUp: [pending.followUp, draft].filter(Boolean).join('\n\n') })
763 await $.prompt.fill({ text: '', mode: 'replace' }).catch(() => undefined)
764 }
765 skipDraftFor = path
766 scheduleClear($, false) // the person's own choice: an attended clear, even for an auto handover
767 return
768 }
769 await log($, 'draft.choice', { choice: 'postpone' })
770 retryTimer?.cancel()
771 retryTimer = null
772 clearParked = true
773 skipDraftFor = null
774 lastWait = null
775 await setCountdown($, null)
776 await releaseHeld($)
777 await savePending($, null)
778 // The ladder moves past the step in force, so the next handover is one step on, not the same one again.
779 const { nudgeAt, step: every } = (await thresholds($)).values
780 const crossed = nextThreshold((await read($, contextA)) ?? 0, { nudgeAt, step: every }, null)
781 if (crossed !== null) await update($, lastNudgedA, n => Math.max(n ?? 0, crossed))
782 await notify($, V.draftPostponed(((await read($, lastNudgedA)) ?? nudgeAt) + every))
783 } catch (err) {
784 await log($, 'guard.wait', { reason: 'draft-ask-failed', error: String(err) }).catch(() => {})
785 }
786}
787
788// R2-15: a timer-driven attempt has nobody to throw to. A failure parks the handover as an offer,
789// with a notice, instead of leaving it pending with no retry.
790async function tryClear($: EngineInterface) {
791 try {
792 await tryClearInner($)
793 } catch (err) {
794 clearParked = true
795 skipDraftFor = null
796 lastWait = null
797 await notify($, V.clearRejected)
798 await log($, 'guard.wait', { reason: 'clear-error', error: String(err) }).catch(() => {})
799 await releaseHeld($).catch(() => {})
800 }
801}
802
803async function tryClearInner($: EngineInterface) {
804 retryTimer = null
805 const pendingNow = await read($, pendingA)
806 if (clearInFlight || !pendingNow) return
807 await reloadSettings($)
808 await checkInterlock($) // spec §7: at session start AND before every clear (TEMPORARY)
809 const now = await nowMs($)
810 // An unattended clear is only for an unattended session with auto mode on: re-checked here, not
811 // just when it began (R1-06, R2-08). Every exit leaves the handover offered, with a notice.
812 const autoOff = unattendedClear && !settings.auto
813 if (autoOff || (unattendedClear && mode(activity, now, settings) === 'attended')) {
814 await setCountdown($, null)
815 await update($, draftWaitA, () => false)
816 skipDraftFor = null
817 lastWait = null
818 clearParked = true
819 await notify($, autoOff ? V.clearSkippedAutoOff : V.clearSkippedAttended)
820 await log($, 'clear.skipped', { reason: autoOff ? 'auto-off' : 'attended' })
821 await releaseHeld($)
822 return
823 }
824 const gate = clearGate({
825 now, draft: skipDraftFor === pendingNow.path ? '' : (await $.prompt.read()).text, onPhone: onPhone(activity), lastBridgeAt: activity.lastBridgeAt,
826 rcAutoClear: settings.rcAutoClear, latched: (await readLatch($)) !== null,
827 countdownEndsAt: await read($, countdownA), classicActive: standDown, unattended: unattendedClear,
828 })
829 await update($, draftWaitA, () => !gate.go && gate.reason === 'draft')
830 if (!gate.go && gate.recheckMs === null) skipDraftFor = null // parked: the choice does not outlive this clear
831 if (gate.go) {
832 skipDraftFor = null
833 lastWait = null
834 await setCountdown($, null)
835 await log($, 'clear', { unattended: unattendedClear })
836 // The person's request ends with its clear: a save after this one is volunteered again.
837 await withdrawConsent($)
838 clearInFlight = true
839 const issuing = await read($, pendingA)
840 issuedClear = issuing ? { path: issuing.path, apiAt: lastApiMirror ?? now } : null
841 const archived = await archiveOutgoing($)
842 try {
843 await $.command.run({ command: 'clear' })
844 } catch {
845 issuedClear = null
846 if (archived !== null) await unarchive($, archived)
847 clearParked = true
848 skipDraftFor = null
849 await notify($, V.clearRejected)
850 await log($, 'guard.wait', { reason: 'clear-rejected' })
851 await releaseHeld($)
852 } finally {
853 clearInFlight = false
854 }
855 return
856 }
857 if (gate.reason === 'draft' && draftAsked !== pendingNow.path) {
858 draftAsked = pendingNow.path
859 void askDraft($, pendingNow.path)
860 }
861 if (gate.reason !== lastWait) {
862 lastWait = gate.reason
863 await notify($, V.waiting(gate.reason))
864 await log($, 'guard.wait', { reason: gate.reason, recheckMs: gate.recheckMs })
865 }
866 if (gate.reason === 'countdown-start') await setCountdown($, now + (gate.recheckMs ?? 0))
867 if (gate.recheckMs === null) { clearParked = true; await releaseHeld($); return }
868 retryTimer = $.clock.after(gate.recheckMs, () => { void tryClear($) })
869}
870
871async function setLatch($: EngineInterface, l: Latch) {
872 if (!l) return
873 const existing = await readLatch($)
874 if (!existing) {
875 await $.store.set(LATCH_KEY, l)
876 await log($, 'limit.latched', { window: l.kind, resetsAtMs: l.resetsAtMs })
877 await notify($, V.limitLatched(formatHHMM(l.resetsAtMs)))
878 } else if (latchTimer) return
879 // R2-04: a latch another session set is lifted by this process too, or an idle one waits forever.
880 const target = existing ?? l
881 latchTimer?.cancel()
882 latchTimer = $.clock.after(Math.max(0, target.resetsAtMs - (await nowMs($))) + 1000, () => { latchTimer = null; void checkLatch($, []).catch(err => timerFailed($, 'latch-lift', err)) })
883}
884
885// The latch is account-wide: another session may lift it (delete the key) and drain only its
886// own work, so an absent latch drains this session's deferred handover too.
887async function checkLatch($: EngineInterface, limits: RateLimit[]) {
888 const l = await readLatch($)
889 if (l) {
890 if (!latchCleared(l, await nowMs($), limits)) return
891 await $.store.delete(LATCH_KEY)
892 await log($, 'limit.cleared', { window: l.kind })
893 await notify($, V.limitCleared)
894 }
895 const deferred = await read($, deferredA)
896 if (deferred) {
897 await reloadSettings($)
898 await update($, deferredA, () => null)
899 // R1-09: hours later the person may be anywhere. A threshold or request runs only if auto mode
900 // is on and they are not attended, and then as an unattended handover (attended re-check, RC
901 // gate). A last light should not get here (shouldFire refuses under a latch); drop it quietly.
902 if (deferred.reason === 'limit') await startHandover($, deferred.reason, deferred.resume, false)
903 else if (deferred.reason !== 'last_light' && settings.auto && mode(activity, await nowMs($), settings) !== 'attended') {
904 await startHandover($, deferred.reason, deferred.resume, true)
905 } else {
906 if (deferred.reason !== 'last_light') await notify($, V.deferredDropped)
907 await log($, 'guard.wait', { reason: 'deferred-dropped', deferred: deferred.reason })
908 }
909 return
910 }
911 // Only a clear the latch parked: one parked for a cancelled countdown or a refusal stays put.
912 // R2-01: hours later it follows the deferred handover's rule — only if auto mode is on, the person
913 // is still away and no turn has run since the write, and then as an unattended clear. Else offered.
914 if (!clearParked || lastWait !== 'latched') return
915 const parked = await read($, pendingA)
916 if (!parked) return
917 await reloadSettings($)
918 const now = await nowMs($)
919 const away = mode(activity, now, settings) !== 'attended'
920 if (settings.auto && away && fresh(parked, await read($, lastApiA), now)) scheduleClear($, true)
921 else await dropParkedClear($, parked, !settings.auto ? 'auto-off' : !away ? 'attended' : 'stale')
922}
923
924// Waits in hops of at most an hour; never submits while latched (spec §5); drops the limit
925// handover once the resume is sent so a later /clear does not re-inject it. One chain per process
926// (R1-12): a second early stop moves the existing job's time out, it never starts a second chain.
927// Nothing is sent over a person who has come back since the stop, or over a draft: a notice names
928// the handover instead. The path lives on the job, so a clear that consumed the pending handover
929// in between still names the file.
930async function scheduleResume($: EngineInterface, at: number) {
931 const stoppedAt = await nowMs($)
932 resumeChain?.cancel()
933 limitResume = { path: limitResume?.path ?? null, at: Math.max(limitResume?.at ?? 0, at), stoppedAt: limitResume?.stoppedAt ?? stoppedAt, gen: ++resumeGen }
934 hopResume($, 0, limitResume)
935}
936
937function hopResume($: EngineInterface, delayMs: number, job: NonNullable<typeof limitResume>) {
938 resumeChain = $.clock.after(delayMs, async () => {
939 if (job.gen !== resumeGen) return
940 const wait = nextHop(await nowMs($), job.at)
941 if (wait > 0) { hopResume($, wait, job); return }
942 await checkLatch($, []) // R2-04: an expired latch nobody lifted is lifted here
943 if (await readLatch($)) { hopResume($, 60_000, job); return }
944 const pending = await read($, pendingA)
945 const path = job.path ?? pending?.path ?? null
946 const back = activity.lastHumanAt !== null && activity.lastHumanAt > job.stoppedAt
947 if (back || (await $.prompt.read()).text.trim()) {
948 await notify($, V.resumeSkipped(path))
949 await log($, 'guard.wait', { reason: 'resume-skipped', human: true })
950 limitResume = null
951 return
952 }
953 const outcome = await submitWithRetry($, { text: limitResumeText(path) }, 0)
954 if (outcome === 'cancelled') {
955 await notify($, V.resumeSkipped(path))
956 limitResume = null
957 return
958 }
959 if (outcome === 'failed') {
960 await notify($, V.resumeFailed(path, null))
961 await log($, 'guard.wait', { reason: 'submit-rejected' })
962 limitResume = null // R3-05: the chain has ended; the next early stop starts its own job
963 resumeChain = null
964 return
965 }
966 limitResume = null
967 if (pending?.reason === 'limit') await savePending($, null)
968 })
969}
970
971async function cancelCountdown($: EngineInterface) {
972 if ((await read($, countdownA)) === null) return
973 await setCountdown($, null)
974 retryTimer?.cancel()
975 retryTimer = null
976 clearParked = true
977 lastWait = null
978 await notify($, V.countdownCancelled)
979 await log($, 'guard.wait', { reason: 'countdown-cancelled' })
980 await releaseHeld($)
981}
982
983async function showNudge($: EngineInterface, pct: number) {
984 if (paused) return
985 if (settings.bar) {
986 if (await read($, barDismissedA)) return // 0 hid it for this cycle: silent
987 if (onPhone(activity)) { void askNudge($, pct); return }
988 await update($, barShownA, () => true)
989 await log($, 'bar', { action: 'shown', pct })
990 return
991 }
992 await notify($, V.nudge(pct))
993}
994
995// On the phone the bar and toasts never arrive; a dialog does (it raises Remote Control's
996// "action required" push, PROBES.md §1). Same three choices as the bar. One ask at a time: a later
997// threshold while one is open is not asked again. A dismissed dialog or free text is "remind me later".
998let nudgeAsking = false
999async function askNudge($: EngineInterface, pct: number) {
1000 if (nudgeAsking) return
1001 nudgeAsking = true
1002 try {
1003 const { nudgeAt, step: every } = (await thresholds($)).values
1004 const next = ((await read($, lastNudgedA)) ?? nudgeAt) + every
1005 await log($, 'bar', { action: 'asked', pct })
1006 const options = [V.barHandover, V.barLater(next), V.barDismiss]
1007 const choice = String(await $.ui.ask(V.nudgeAsk(pct), options).catch(() => V.barLater(next)))
1008 await barChoice($, choice === V.barHandover ? 'handover' : choice === V.barDismiss ? 'dismiss' : 'later')
1009 } finally {
1010 nudgeAsking = false
1011 }
1012}
1013
1014async function barChoice($: EngineInterface, action: 'handover' | 'later' | 'dismiss') {
1015 // R2-07: a pressed button is the person being here, same as the countdown's Cancel (R1-22).
1016 await observe($, { kind: 'human-command', at: await nowMs($) })
1017 await update($, barShownA, () => false)
1018 if (action === 'dismiss') await update($, barDismissedA, () => true)
1019 await log($, 'bar', { action })
1020 if (action === 'dismiss') await notify($, V.barDismissedNote)
1021 if (action === 'handover') {
1022 await giveConsent($)
1023 await startHandover($, 'request', true)
1024 }
1025}
1026
1027// Whether `sh` runs here (it does not on Windows); asked once per process.
1028let shellRuns: boolean | undefined
1029async function hasShell($: EngineInterface): Promise<boolean> {
1030 if (shellRuns === undefined) shellRuns = await $.process.run(['sh', '-c', 'exit 0'], { timeoutMs: 5000 }).then(r => r.exitCode === 0, () => false)
1031 return shellRuns
1032}
1033
1034// The messages the old session saw after its last handover call: null = could not tell (no file, no call
1035// within the last 2 MB, no shell and an unreadable file).
1036const TAIL_CHUNKS = [256 * 1024, 1024 * 1024, 2 * 1024 * 1024]
1037async function transcriptTail($: EngineInterface, path: string): Promise<string[] | null> {
1038 try {
1039 if (!(await hasShell($))) {
1040 const text = await $.fs.read(path).catch(() => undefined)
1041 return typeof text === 'string' ? messagesAfterHandover(text, TOOL_FULL) : null
1042 }
1043 for (const n of TAIL_CHUNKS) {
1044 const r = await $.process.run(['sh', '-c', 'tail -c "$2" "$1"', 'sh', path, String(n)])
1045 if (r.exitCode !== 0 || r.isStdoutTruncated) return null
1046 const found = messagesAfterHandover(r.stdout, TOOL_FULL)
1047 if (found || r.stdout.length < n) return found
1048 }
1049 } catch { /* unknown */ }
1050 return null
1051}
1052
1053// The transcript's last custom title: null = unnamed, undefined = could not tell.
1054async function transcriptTitle($: EngineInterface, transcriptPath: string): Promise<string | null | undefined> {
1055 try {
1056 if (!(await hasShell($))) {
1057 const text = await $.fs.read(transcriptPath).catch(() => undefined) // over the read cap or missing: cannot tell
1058 return typeof text === 'string' ? lastTitle(text) : undefined
1059 }
1060 const r = await $.process.run(['sh', '-c', TITLE_CMD, 'sh', transcriptPath])
1061 if (r.exitCode === 0) return lastTitle(r.stdout)
1062 return r.exitCode === 1 ? null : undefined
1063 } catch {
1064 return undefined
1065 }
1066}
1067
1068// PROBES §15: just before the handover's /clear, a named session is renamed `Archive: <name>` so
1069// /resume tells it from its successor, and the pending handover records `<name>` for the
1070// successor. An unnamed one is left as it is: nothing duplicates it, and a name once given cannot
1071// be taken back if the clear is then refused. A name that already starts with the prefix is the
1072// person's (or an old archive's) and is left alone. Never blocks the clear.
1073// Returns the name it replaced, to put back if the clear fails; null when it renamed nothing.
1074async function archiveOutgoing($: EngineInterface): Promise<string | null> {
1075 try {
1076 const path = (await read($, transcriptA)) ?? (root ? transcriptPathFor(root, await $.session.cwd(), await $.session.id()) : null)
1077 const title = path === null ? undefined : await transcriptTitle($, path)
1078 if (title === undefined) {
1079 await log($, 'guard.wait', { reason: 'archive-unknown' })
1080 return null
1081 }
1082 if (title === null) return null
1083 if (isArchived(title)) {
1084 // Ours only when an earlier rename back failed (a stranded mark for this session): already
1085 // archived, so just recorded, and the successor gets the name back. Otherwise the person's.
1086 const key = strandedKey(await $.session.id())
1087 const stranded = (await $.store.get(key).catch(() => null)) as Stranded | null | undefined
1088 const ours = !!stranded && title === archiveName(stranded.name)
1089 if (ours && (await recordArchived($, stranded.name))) await $.store.delete(key).catch(() => {})
1090 await log($, 'archive', { kept: true, ours })
1091 return null
1092 }
1093 // Recorded first: an archive the successor could not undo is worse than none. A rename that
1094 // then fails leaves a record no carried name will match (the name was never changed).
1095 if (!(await recordArchived($, title))) return null
1096 await $.command.run({ command: 'rename', args: archiveName(title) })
1097 await log($, 'archive', { name: archiveName(title) })
1098 return title
1099 } catch {
1100 await notify($, V.archiveFailed)
1101 await log($, 'guard.wait', { reason: 'archive-rejected' })
1102 return null
1103 }
1104}
1105
1106// The pending handover carries the archived name across the clear, for the successor. False when
1107// it could not be saved: the caller then archives nothing.
1108async function recordArchived($: EngineInterface, name: string): Promise<boolean> {
1109 const pending = await read($, pendingA)
1110 if (!pending) return false
1111 try {
1112 await savePending($, { ...pending, archived: name })
1113 return true
1114 } catch {
1115 await log($, 'guard.wait', { reason: 'archive-unrecorded' })
1116 return false
1117 }
1118}
1119
1120// A clear of your own carries a stranded `Archive: <name>` into the new session: so does its mark,
1121// with its 14 days counted again from the move (the session is still in use).
1122async function moveStranded($: EngineInterface, from: string, to: string) {
1123 try {
1124 const mark = (await $.store.get(strandedKey(from))) as Stranded | null | undefined
1125 if (!mark) return
1126 const moved: Stranded = { ...mark, at: await nowMs($) }
1127 await $.store.set(strandedKey(to), moved)
1128 await $.store.delete(strandedKey(from))
1129 } catch { /* the mark stays where it was; nothing is renamed on its account */ }
1130}
1131
1132// The clear was refused, so this is still the archived session: its own name back, and no record
1133// left for a later clear to act on. A failed restore keeps the record (the name is still the archive's).
1134async function unarchive($: EngineInterface, name: string) {
1135 try {
1136 await $.command.run({ command: 'rename', args: name })
1137 } catch {
1138 await log($, 'guard.wait', { reason: 'archive-unrestored' })
1139 return
1140 }
1141 const pending = await read($, pendingA)
1142 if (pending?.archived !== undefined) {
1143 const { archived: _, ...rest } = pending
1144 await savePending($, rest).catch(() => {})
1145 }
1146}
1147
1148// /clear carries the outgoing session's name into the new one (PROBES §8). After the mod's own
1149// archive that is `Archive: <archived>`, and the new session gets `<archived>` back; any other
1150// carried name (the person's, even one starting `Archive: `) is kept; an unnamed one takes the
1151// handover's session_name. `carried` is the engine's session_title on the clear when it gives one
1152// (§15: null = unnamed); absent, the old transcript is read.
1153// Never blocks the resume: a failed rename is a notice, not an error.
1154// `successor` is the new session's id as the clear's SessionStart saw it (null: not known), for the stranded mark.
1155async function renameSession($: EngineInterface, handoverName: string | undefined, archived: string | undefined, oldTranscript: string | undefined, carried: string | null | undefined, successor: string | null) {
1156 const title = carried !== undefined ? carried : oldTranscript === undefined ? undefined : await transcriptTitle($, oldTranscript)
1157 if (title === undefined) return void (await log($, 'guard.wait', { reason: 'rename-unknown' }))
1158 if (title !== null && (archived === undefined || title !== archiveName(archived))) return void (await log($, 'rename', { kept: true }))
1159 const name = title === null ? handoverName?.trim() : archived
1160 if (!name) return // an older stored handover may carry no name
1161 await log($, 'rename', { name })
1162 try {
1163 await $.command.run({ command: 'rename', args: name })
1164 } catch {
1165 // Left as `Archive: <name>` by us: a mark in $.store lets this session's next handover (after a
1166 // /resume or a restart too) give its successor the name back.
1167 if (title !== null && successor === null) await log($, 'guard.wait', { reason: 'stranded-unkeyed' })
1168 else if (title !== null && successor !== null) {
1169 const mark: Stranded = { name, at: await nowMs($) }
1170 await $.store.set(strandedKey(successor), mark).catch(() => log($, 'guard.wait', { reason: 'stranded-unsaved' }))
1171 }
1172 await notify($, V.renameFailed)
1173 await log($, 'guard.wait', { reason: 'rename-rejected' })
1174 }
1175}
1176
1177function scheduleLastLight($: EngineInterface, lastApiAt: number, now: number) {
1178 lastLightTimer?.cancel()
1179 lastLightTimer = null
1180 if (!settings.lastLight) return
1181 if (now >= lastApiAt + TTL_1H) return // no fire for a cache that is already cold
1182 lastLightTimer = $.clock.after(Math.max(0, fireAt(lastApiAt) - now), () => { void maybeFireLastLight($).catch(err => timerFailed($, 'last-light', err)) })
1183}
1184
1185// The one place the cache lifetime is asked (PROBES §11): scheduling assumed 1 hour, the latest
1186// write in the transcript's tail says whether that held. Nothing found is no fire; no retry.
1187async function readTtl($: EngineInterface): Promise<CacheTtl> {
1188 let writes = null
1189 try {
1190 const path = (await read($, transcriptA)) ?? (root ? transcriptPathFor(root, await $.session.cwd(), await $.session.id()) : null)
1191 if (!path) return ttlFromWrites(null)
1192 if (await hasShell($)) {
1193 const r = await $.process.run(['sh', '-c', TAIL_CMD, 'sh', path])
1194 if (r.exitCode === 0) writes = parseWrites(r.stdout)
1195 } else {
1196 const text = await $.fs.read(path).catch(() => undefined)
1197 if (typeof text === 'string') writes = parseWrites(cacheLinesFromText(text))
1198 }
1199 } catch { /* unknown */ }
1200 return ttlFromWrites(writes)plugin/core/overrides.ts 229 lines1import type { Override, OverrideValues } from '../types'
2
3// Threshold overrides keyed by model, window or both, in a hand-editable overrides.json.
4// Each value comes from the most specific matching override that sets it, field by field; the
5// account settings sit beneath them all.
6//
7// { model: 'opus5.5', window: 1M } > { model: 'opus', window: 1M } > { window: 1M }
8// > { model: 'opus5.5' } > { model: 'opus' } > settings
9
10export const VALUE_KEYS = ['nudgeAt', 'step', 'lastLightAt'] as const
11type ValueKey = typeof VALUE_KEYS[number]
12
13export const DEFAULT_OVERRIDES: Override[] = [{ window: 200_000, nudgeAt: 70 }]
14
15// 'claude-opus-5-5[1m]', 'Opus 5.5 (1M context)' and 'opus5.5' all lead with opus·5·5.
16export function modelTokens(model: string): string[] {
17 const t = model.toLowerCase().match(/[a-z]+|\d+/g) ?? []
18 return t[0] === 'claude' ? t.slice(1) : t
19}
20
21// A pattern is a family and at most a major.minor version: 'opus', 'opus5', 'opus5.5'.
22export function validPattern(pattern: string): boolean {
23 const t = modelTokens(pattern)
24 return t.length >= 1 && t.length <= 3 && /^[a-z]+$/.test(t[0]!) && t.slice(1).every(x => /^\d+$/.test(x))
25}
26
27// The pattern naming a model's version: 'claude-haiku-4-5-20251001' → 'haiku4.5'.
28export function patternFor(model: string): string | null {
29 const t = modelTokens(model)
30 if (!t[0] || !/^[a-z]+$/.test(t[0])) return null
31 const nums: string[] = []
32 for (const x of t.slice(1)) { if (!/^\d+$/.test(x) || x.length > 2 || nums.length === 2) break; nums.push(x) }
33 return t[0] + nums.join('.')
34}
35
36export function modelMatches(pattern: string, model: string): boolean {
37 const p = modelTokens(pattern)
38 const m = modelTokens(model)
39 return p.length > 0 && p.length <= m.length && p.every((x, i) => x === m[i])
40}
41
42// Both keys beat one; of one, window beats model; between models, the longer pattern wins.
43function specificity(r: Override): number {
44 const tier = r.model !== undefined && r.window !== undefined ? 3 : r.window !== undefined ? 2 : 1
45 return tier * 1_000 + (r.model === undefined ? 0 : modelTokens(r.model).length)
46}
47
48const matches = (r: Override, model: string | null, window: number | null): boolean =>
49 (r.model === undefined || (model !== null && modelMatches(r.model, model)))
50 && (r.window === undefined || r.window === window)
51
52export type Ambiguity = { model: Override; window: Override; fields: ValueKey[] }
53
54export type Resolved = {
55 values: OverrideValues
56 from: Partial<Record<ValueKey, Override>>
57 // A window-only and a model-only override both set a field and nothing with both keys settles it.
58 ambiguous: Ambiguity | null
59}
60
61export function resolve(base: OverrideValues, overrides: Override[], model: string | null, window: number | null): Resolved {
62 const hits = ordered(overrides.filter(r => matches(r, model, window)))
63 const values: OverrideValues = { ...base }
64 const from: Partial<Record<ValueKey, Override>> = {}
65 for (const k of VALUE_KEYS) {
66 const r = hits.find(h => h[k] !== undefined)
67 if (r) { values[k] = r[k]!; from[k] = r }
68 }
69 const byWindow = hits.find(h => h.model === undefined)
70 const modelOnly = hits.filter(h => h.window === undefined)
71 const fields = byWindow ? VALUE_KEYS.filter(k => from[k] === byWindow && modelOnly.some(h => h[k] !== undefined)) : []
72 const byModel = modelOnly.find(h => fields.some(k => h[k] !== undefined))
73 return { values, from, ambiguous: byWindow && byModel ? { model: byModel, window: byWindow, fields } : null }
74}
75
76export function ordered(overrides: Override[]): Override[] {
77 return [...overrides].sort((a, b) => specificity(b) - specificity(a))
78}
79
80const keyOf = (r: Pick<Override, 'model' | 'window'>): string =>
81 `${r.model === undefined ? '*' : modelTokens(r.model).join('.')}@${r.window ?? '*'}`
82
83export const sameKey = (a: Pick<Override, 'model' | 'window'>, b: Pick<Override, 'model' | 'window'>): boolean => keyOf(a) === keyOf(b)
84
85// Adding an override replaces the one with the same key.
86export function setOverride(overrides: Override[], override: Override): Override[] {
87 return [...overrides.filter(r => !sameKey(r, override)), override]
88}
89
90export function removeOverride(overrides: Override[], key: Pick<Override, 'model' | 'window'>): { overrides: Override[]; removed: boolean } {
91 const next = overrides.filter(r => !sameKey(r, key))
92 return { overrides: next, removed: next.length !== overrides.length }
93}
94
95// '1m', '1M', '200k', '1000000' → tokens.
96export function parseWindow(s: string): number | null {
97 const m = /^(\d+(?:\.\d+)?)([km]?)$/i.exec(s.trim())
98 if (!m) return null
99 const unit = m[2]?.toLowerCase()
100 const scaled = Number(m[1]) * (unit === 'k' ? 1_000 : unit === 'm' ? 1_000_000 : 1)
101 // Only float noise is rounded (1.1m); a count that is not whole (1.4, 1.0005k) is refused, so
102 // `rm window=1.4` can never take out window=1.
103 const n = Math.round(scaled)
104 return Math.abs(scaled - n) < 1e-6 && n > 0 ? n : null
105}
106
107export function formatWindow(n: number): string {
108 return n % 1_000_000 === 0 ? `${n / 1_000_000}M` : n % 1_000 === 0 ? `${n / 1_000}k` : `${n}`
109}
110
111export function formatKey(r: Pick<Override, 'model' | 'window'>): string {
112 return [r.model !== undefined ? `model=${r.model}` : '', r.window !== undefined ? `window=${formatWindow(r.window)}` : ''].filter(Boolean).join(' ')
113}
114
115const LABEL: Record<ValueKey, string> = { nudgeAt: 'nudge', step: 'step', lastLightAt: 'last light' }
116
117export function formatOverride(r: Override): string {
118 return `${formatKey(r)} → ${VALUE_KEYS.filter(k => r[k] !== undefined).map(k => `${LABEL[k]} ${r[k]}%`).join(', ')}`
119}
120
121// overrides.json: { "overrides": [ ... ] }. A fault drops only the override it is in; each is named for the person.
122// A file that cannot be read as a list at all (`fileFault`) names no override: the caller keeps what it had.
123export type Checked = { overrides: Override[]; faults: string[]; fileFault?: true }
124
125const KEYS = new Set<string>(['model', 'window', ...VALUE_KEYS])
126const isPct = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 100
127
128export function checkOverrides(text: string): Checked {
129 let raw: unknown
130 try { raw = JSON.parse(text) } catch (err) { return { overrides: [], faults: [`not valid JSON (${String((err as Error).message).slice(0, 80)})`], fileFault: true } }
131 const list = (raw as { overrides?: unknown } | null)?.overrides
132 if (!raw || typeof raw !== 'object' || !Array.isArray(list)) return { overrides: [], faults: ['expected { "overrides": [ … ] }'], fileFault: true }
133 const overrides: Override[] = []
134 const faults: string[] = []
135 list.forEach((v, i) => {
136 const at = `override ${i + 1}`
137 if (!v || typeof v !== 'object' || Array.isArray(v)) { faults.push(`${at}: not an object`); return }
138 const o = v as Record<string, unknown>
139 const unknown = Object.keys(o).filter(k => !KEYS.has(k))
140 if (unknown.length) { faults.push(`${at}: unknown key ${unknown.map(k => `"${k}"`).join(', ')} (allowed: ${[...KEYS].join(', ')})`); return }
141 if (o.model !== undefined && (typeof o.model !== 'string' || !validPattern(o.model))) { faults.push(`${at}: model must be a family and optional version, like "opus" or "opus5.5"`); return }
142 if (o.window !== undefined && !(typeof o.window === 'number' && Number.isInteger(o.window) && o.window > 0)) { faults.push(`${at}: window must be a whole number of tokens, like 1000000`); return }
143 if (o.model === undefined && o.window === undefined) { faults.push(`${at}: needs a model, a window or both`); return }
144 for (const k of ['nudgeAt', 'lastLightAt'] as const) if (o[k] !== undefined && !isPct(o[k])) { faults.push(`${at}: ${k} must be a whole % from 1 to 100`); return }
145 if (o.step !== undefined && !(typeof o.step === 'number' && Number.isInteger(o.step) && o.step >= 1 && o.step <= 50)) { faults.push(`${at}: step must be a whole % from 1 to 50`); return }
146 if (!VALUE_KEYS.some(k => o[k] !== undefined)) { faults.push(`${at}: sets nothing (give it ${VALUE_KEYS.join(', ')} or any of them)`); return }
147 const r = o as Override
148 const dup = overrides.findIndex(x => sameKey(x, r))
149 if (dup !== -1) { faults.push(`${at}: same key as an earlier override (${formatKey(r)}); the earlier one stands`); return }
150 overrides.push(r)
151 })
152 return { overrides, faults }
153}
154
155export function overridesJson(overrides: Override[]): string {
156 return `${JSON.stringify({ overrides }, null, 2)}\n`
157}
158
159// 0.1.3 kept per-model overrides in the settings store (`modelThresholds`, substring patterns such
160// as `opus` or `[1m]`). They move into overrides.json once: `[1m]` becomes window=1M, the rest a
161// model pattern. One that does not fit this format is named in `dropped`, with why. Entries go in
162// 0.1.3's own order (longest pattern first, then by name), so when two collapse to one key
163// (`claude-opus`, `opus`) the one that used to win is the one kept.
164export function fromModelThresholds(raw: unknown): { overrides: Override[]; dropped: string[] } {
165 const table = (raw as { modelThresholds?: unknown } | null)?.modelThresholds
166 const out: Override[] = []
167 const dropped: string[] = []
168 if (!table || typeof table !== 'object' || Array.isArray(table)) return { overrides: out, dropped }
169 const entries = Object.entries(table as Record<string, unknown>)
170 .sort(([a], [b]) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0))
171 for (const [key, v] of entries) {
172 const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>
173 const lower = key.trim().toLowerCase()
174 const window = lower.includes('[1m]') ? 1_000_000 : undefined
175 const rest = lower.replace('[1m]', '').replace(/^[-\s]+|[-\s]+$/g, '')
176 const tokens = modelTokens(rest)
177 const model = rest ? (validPattern(rest) ? tokens[0]! + tokens.slice(1).join('.') : null) : undefined
178 const values = { ...(isPct(o.nudgeAt) ? { nudgeAt: o.nudgeAt } : {}), ...(isPct(o.lastLightAt) ? { lastLightAt: o.lastLightAt } : {}) }
179 if (model === null || (model === undefined && window === undefined)) { dropped.push(`${key} (no equivalent)`); continue }
180 if (!Object.keys(values).length) { dropped.push(`${key} (sets nothing)`); continue }
181 const r: Override = { ...(model !== undefined ? { model } : {}), ...(window !== undefined ? { window } : {}), ...values }
182 const winner = out.find(x => sameKey(x, r))
183 if (winner) { dropped.push(`${key} (${formatKey(winner)} from a longer pattern won)`); continue }
184 out.push(r)
185 }
186 return { overrides: out, dropped }
187}
188
189// /vigil-overrides · /vigil-overrides add · /vigil-overrides rm [model=<m>] [window=<w>]
190export type OverridesCommand =
191 | { op: 'list' }
192 | { op: 'add' }
193 | { op: 'rm'; key: Pick<Override, 'model' | 'window'> }
194 | { op: 'error' }
195
196export function parseOverridesArgs(args: string): OverridesCommand {
197 const words = args.trim().split(/\s+/).filter(Boolean)
198 if (words.length === 0 || (words.length === 1 && (words[0] === 'list' || words[0] === 'check'))) return { op: 'list' }
199 if (words.length === 1 && words[0] === 'add') return { op: 'add' }
200 if (words[0] !== 'rm') return { op: 'error' }
201 const key = parseKey(words.slice(1).join(' '))
202 return key ? { op: 'rm', key } : { op: 'error' }
203}
204
205// 'model=opus5.5 window=1m' (either or both) → an override key; null when it names neither or is malformed.
206export function parseKey(text: string): Pick<Override, 'model' | 'window'> | null {
207 let model: string | undefined
208 let window: number | undefined
209 for (const w of text.trim().split(/\s+/).filter(Boolean)) {
210 const eq = w.indexOf('=')
211 const k = eq > 0 ? w.slice(0, eq).toLowerCase() : ''
212 const v = w.slice(eq + 1)
213 if (k === 'model' && model === undefined && validPattern(v)) { model = v; continue }
214 const n = k === 'window' && window === undefined ? parseWindow(v) : null
215 if (n !== null) { window = n; continue }
216 return null
217 }
218 if (model === undefined && window === undefined) return null
219 return { ...(model !== undefined ? { model } : {}), ...(window !== undefined ? { window } : {}) }
220}
221
222// The /vigil-overrides add dialog: questions, like setup's, are not notices and carry no emoji.
223export const ASK = {
224 key: 'Which sessions should this override cover? (Other: model=… window=…, either or both)',
225 nudge: (key: string) => `For ${key}: at what % of context should I suggest a handover?`,
226 step: 'Then nudge again every how many %?',
227 lastLight: 'Last light: only write its handover from what % of context?',
228}
229plugin/core/name.ts 31 lines1import { configRootOf, joinPath } from './home'
2import type { HomeEnv } from './home'
3
4export const NAME = 'context-vigil-mod'
5export const TOOL = 'vigil_handover'
6export const TOOL_FULL = `mcp__${NAME}__${TOOL}`
7export const COMMANDS = { handover: 'vigil-handover', handoverShort: 'vho', setup: 'vigil-setup', overrides: 'vigil-overrides', pause: 'vigil-pause', resume: 'vigil-resume' } as const
8
9// null when no home can be told (CLAUDE_CONFIG_DIR, HOME, USERPROFILE, HOMEDRIVE+HOMEPATH): a relative `.claude`
10// would land under the session's cwd, so callers write nothing.
11export function configRoot(env: HomeEnv): string | null {
12 return configRootOf(env)
13}
14
15export function handoverPath(root: string, session: string, n: number): string {
16 return joinPath(root, NAME, 'handovers', `${session}-${n}.md`)
17}
18
19export function overridesPath(root: string): string {
20 return joinPath(root, NAME, 'overrides.json')
21}
22
23export function eventsPath(root: string, day: string, session: string): string {
24 return joinPath(root, NAME, 'events', day, `${session}.jsonl`)
25}
26
27// TEMPORARY (interlock): where classic context-vigil keeps a session record.
28export function classicSessionPath(root: string, session: string): string {
29 return joinPath(root, 'context-vigil', 'sessions', `${session}.json`)
30}
31plugin/core/settings.ts 59 lines1import type { Settings, Window } from '../types'
2
3export const STORE_KEY = 'settings'
4
5// Per session: a second session on the account must never see or wipe this one's handover.
6export function pendingKey(session: string): string {
7 return `pending:${session}`
8}
9
10// A parked handover nobody came back for is not kept forever: $.store refuses writes past 4 MiB (R1-17).
11export const PENDING_KEEP_MS = 14 * 86_400_000
12export const PENDING_PREFIX = 'pending:'
13
14// PROBES §15: a session left named `Archive: <name>` because the mod's rename back failed. Per
15// session id, so a /resume or restart still knows it; pruned like a pending handover.
16export type Stranded = { name: string; at: number }
17export const STRANDED_PREFIX = 'stranded:'
18// The standing orders of the chain this session belongs to; moved to the successor's id by the clear.
19export function standingKey(session: string): string {
20 return `standing:${session}`
21}
22
23export function strandedKey(session: string): string {
24 return `${STRANDED_PREFIX}${session}`
25}
26
27export const DEFAULTS: Settings = {
28 nudgeAt: 35, step: 5, bar: true, auto: false, idleMin: 30,
29 lastLight: true, lastLightAt: 25, limits: true, limitPct: 98,
30 limitWindows: ['seven_day', 'spend_limit'], rcAutoClear: 'unanswered',
31}
32
33const isPct = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v >= 1 && v <= 100
34const inRange = (v: unknown, lo: number, hi: number): v is number =>
35 typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi
36
37export function loadSettings(raw: unknown): Settings {
38 const s: Settings = { ...DEFAULTS, limitWindows: [...DEFAULTS.limitWindows] }
39 if (!raw || typeof raw !== 'object') return s
40 const r = raw as Record<string, unknown>
41 if (r.modelThresholds !== undefined) s.modelThresholds = r.modelThresholds
42 if (isPct(r.nudgeAt)) s.nudgeAt = r.nudgeAt
43 if (inRange(r.step, 1, 50)) s.step = r.step
44 if (typeof r.bar === 'boolean') s.bar = r.bar
45 if (typeof r.auto === 'boolean') s.auto = r.auto
46 if (inRange(r.idleMin, 1, 1440)) s.idleMin = r.idleMin
47 if (typeof r.lastLight === 'boolean') s.lastLight = r.lastLight
48 if (isPct(r.lastLightAt)) s.lastLightAt = r.lastLightAt
49 if (typeof r.limits === 'boolean') s.limits = r.limits
50 if (isPct(r.limitPct)) s.limitPct = r.limitPct
51 if (Array.isArray(r.limitWindows)) {
52 const ok = r.limitWindows.filter((w): w is Window => w === 'seven_day' || w === 'spend_limit' || w === 'five_hour')
53 // An empty list would watch nothing while limits reads On: keep the defaults instead.
54 if (ok.length) s.limitWindows = [...new Set(ok)]
55 }
56 if (r.rcAutoClear === 'yes' || r.rcAutoClear === 'no' || r.rcAutoClear === 'unanswered') s.rcAutoClear = r.rcAutoClear
57 return s
58}
59plugin/core/arming.ts 67 lines1import type { Activity, Mode, Settings, Who } from '../types'
2
3const HUMAN = new Set(['composer', 'bridge', 'slack-ping'])
4// Presence evidence that is not attestably the person's own message: a same-user channel the engine
5// cannot attest (R1-24), a message relayed by an MCP channel server, the engine's follow-up to a UI
6// action (R2-06). They disarm auto mode and nothing else.
7const DISARM_ONLY = new Set(['unclassified', 'channel', 'auto-continuation'])
8
9export function classifyOrigin(kind: string): Who {
10 if (HUMAN.has(kind)) return 'human'
11 if (kind === 'sdk') return 'headless'
12 return 'agent'
13}
14
15export const EMPTY_ACTIVITY: Activity = {
16 lastHumanAt: null, lastHumanOrigin: null, lastBridgeAt: null, lastAgentAt: null, headless: false,
17}
18
19export type Signal =
20 | { kind: 'prompt'; origin: string; at: number }
21 | { kind: 'human-command'; at: number }
22 | { kind: 'edit'; at: number }
23 | { kind: 'agent-step'; at: number }
24
25export function record(a: Activity, s: Signal): Activity {
26 switch (s.kind) {
27 case 'prompt': {
28 // An origin the engine cannot attest might be a person: it disarms auto mode and restarts the
29 // idle clock, and counts for nothing else (not a phone fact, not a return, not agent work). R1-24.
30 if (DISARM_ONLY.has(s.origin)) return { ...a, lastHumanAt: s.at }
31 const who = classifyOrigin(s.origin)
32 if (who === 'human') {
33 return { ...a, lastHumanAt: s.at, lastHumanOrigin: s.origin, lastBridgeAt: s.origin === 'bridge' ? s.at : a.lastBridgeAt }
34 }
35 return { ...a, lastAgentAt: s.at, headless: a.headless || who === 'headless' }
36 }
37 case 'human-command':
38 case 'edit':
39 return { ...a, lastHumanAt: s.at }
40 case 'agent-step':
41 return { ...a, lastAgentAt: s.at }
42 }
43}
44
45export const WORKING_MS = 120_000
46
47export function mode(a: Activity, now: number, s: Pick<Settings, 'idleMin'>): Mode {
48 const engaged = !a.headless && a.lastHumanAt !== null && now - a.lastHumanAt < s.idleMin * 60_000
49 if (engaged) return 'attended'
50 const working = a.lastAgentAt !== null && now - a.lastAgentAt < WORKING_MS
51 return working ? 'auto' : 'idle'
52}
53
54export function armed(a: Activity, now: number, s: Pick<Settings, 'idleMin' | 'auto'>): boolean {
55 return s.auto && mode(a, now, s) === 'auto'
56}
57
58export function transition(prev: Mode, next: Mode): 'arm' | 'disarm' | null {
59 if (next === 'auto' && prev !== 'auto') return 'arm'
60 if (prev === 'auto' && next !== 'auto') return 'disarm'
61 return null
62}
63
64export function onPhone(a: Activity): boolean {
65 return a.lastHumanOrigin === 'bridge'
66}
67plugin/core/eventlog.ts 15 lines1import type { EventKind, EventRecord } from '../types'
2
3export function dayKey(ms: number): string {
4 return new Date(ms).toISOString().slice(0, 10)
5}
6
7export function makeRecord(ms: number, session: string, kind: EventKind, fields: Record<string, unknown>): EventRecord {
8 return { ...fields, ts: new Date(ms).toISOString(), session, kind }
9}
10
11export function appendLine(existing: string, rec: EventRecord): string {
12 const base = existing === '' || existing.endsWith('\n') ? existing : `${existing}\n`
13 return `${base}${JSON.stringify(rec)}\n`
14}
15plugin/core/git.ts 36 lines1import type { Git } from '../types'
2import { isAbsolute } from './home'
3
4// Two questions only: `ahead` was dropped while the status-line band is parked (pre-flight F30).
5export const GIT_ARGV = {
6 branch: ['git', 'symbolic-ref', '--short', 'HEAD'],
7 status: ['git', 'status', '--porcelain'],
8} as const
9
10export const COALESCE_MS = 1500
11
12export type RunOut = { exitCode: number; stdout: string }
13
14export function parseGit(branch: RunOut, status: RunOut): Git {
15 const b = branch.exitCode === 0 ? branch.stdout.trim() || null : null
16 const dirty = status.exitCode === 0
17 ? status.stdout.split('\n').filter(l => l.length > 3 && !l.startsWith('??')).map(l => l.slice(3))
18 : []
19 return { branch: b, dirty }
20}
21
22const TOUCH = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash'])
23export function touchesGit(tool: string): boolean {
24 return TOUCH.has(tool)
25}
26
27// The session's own git dir: in a worktree `<root>/.git` is a file, so HEAD and index live elsewhere.
28export const GIT_DIR_ARGV = ['git', 'rev-parse', '--absolute-git-dir'] as const
29
30/** What to watch for a `git rev-parse --absolute-git-dir` answer; nothing when it failed. */
31export function watchPaths(gitDir: RunOut): string[] {
32 const dir = gitDir.exitCode === 0 ? gitDir.stdout.trim() : ''
33 // git prints forward slashes even on Windows (`C:/repo/.git`)
34 return isAbsolute(dir) ? [`${dir}/HEAD`, `${dir}/index`] : []
35}
36plugin/core/handover.ts 206 lines1import type { Fields, Pending, PendingReason, Settings, Snapshot } from '../types'
2import { TOOL_FULL } from './name'
3
4export function nextThreshold(pct: number, s: Pick<Settings, 'nudgeAt' | 'step'>, lastNudged: number | null): number | null {
5 if (pct < s.nudgeAt) return null
6 const crossed = s.nudgeAt + Math.floor((pct - s.nudgeAt) / s.step) * s.step
7 if (lastNudged !== null && crossed <= lastNudged) return null
8 return crossed
9}
10
11// An unattended (auto-mode) handover waits until context has grown at least one step above the
12// session's baseline (its first reading), so a session that starts just under the threshold
13// cannot hand over, clear and hand over again within a turn. Attended nudges ignore this.
14export function grownEnough(pct: number, baseline: number | null, step: number): boolean {
15 return baseline !== null && pct - baseline >= step
16}
17
18// The turn that wrote a handover ends just after the tool call; a turn ending later than this
19// means the conversation moved on and the handover is stale.
20export const REUSE_SLACK_MS = 60_000
21
22// Is a handover still the latest word on the session? No turn has completed since it was written
23// (give or take the slack). A process that has seen no turn yet (a restart, a --resume) knows only
24// the clock: the handover must be young. One rule for reuse (R1-04) and for a manual /clear's
25// automatic resume (R1-10).
26export function fresh(p: Pick<Pending, 'createdAt'>, lastApiAt: number | null, now: number): boolean {
27 return (lastApiAt ?? now) <= p.createdAt + REUSE_SLACK_MS
28}
29
30// A pending handover is reused (cleared into) only when it was written for a clear and is fresh;
31// anything else gets a fresh handover.
32export function reusable(p: Pick<Pending, 'reason' | 'createdAt'> | null, lastApiAt: number | null, now: number): boolean {
33 if (!p || (p.reason !== 'threshold' && p.reason !== 'request')) return false
34 return fresh(p, lastApiAt, now)
35}
36
37export const FIELD_NAMES = ['goal', 'state', 'decisions', 'next_step', 'open_questions', 'failed_attempts', 'standing', 'standing_retire', 'session_name'] as const
38const REQUIRED = ['goal', 'state', 'next_step', 'session_name'] as const
39
40const DESCRIBE: Record<(typeof FIELD_NAMES)[number], string> = {
41 goal: 'What this session is trying to achieve, in a sentence or two.',
42 state: 'Where the work stands right now: done, in flight, blocked.',
43 decisions: 'Decisions and rulings made, each with its reason.',
44 next_step: 'The very next concrete action on resume.',
45 open_questions: 'Questions still waiting on the person.',
46 failed_attempts: 'Approaches tried that did not work, and why.',
47 standing: 'NEW standing orders only: rules and facts that hold for the whole chain of sessions, not just this one (one per line). The earlier ones are carried forward for you; do not repeat them.',
48 standing_retire: 'Standing orders to retire, each named exactly as it was written, one per line. Only retire what is no longer true.',
49 session_name: 'A short name for the session that resumes this work: 2–6 words saying what it will do next (e.g. "vigil-mod: shell handover flow"). It becomes the new session\'s name after the clear.',
50}
51
52export const INPUT_SCHEMA = {
53 type: 'object',
54 properties: Object.fromEntries(FIELD_NAMES.map(n => [n, { type: 'string', description: DESCRIBE[n] }])),
55 required: [...REQUIRED],
56} as const
57
58export const TOOL_DESCRIPTION =
59 'Save a handover for this session so work can resume after the context is cleared. ' +
60 'Call it when context-vigil-mod asks you to, or when the person asks you for a handover. Never write a handover any other way: no ad-hoc files or summaries. ' +
61 'Write for a fresh reader who knows nothing of this conversation.'
62
63export function cleanName(raw: string): string {
64 return raw.replace(/\s+/g, ' ').trim().replace(/^\/+/, '').slice(0, 60).trim()
65}
66
67export function parseFields(input: Record<string, unknown>): { ok: true; fields: Fields } | { ok: false; error: string } {
68 const out: Record<string, string> = {}
69 for (const name of FIELD_NAMES) {
70 const v = input[name]
71 if (v === undefined || v === null) { out[name] = ''; continue }
72 if (typeof v !== 'string') return { ok: false, error: `${name} must be a string` }
73 out[name] = name === 'session_name' ? cleanName(v) : v.trim()
74 }
75 for (const name of REQUIRED) if (!out[name]) return { ok: false, error: `${name} is required and must not be blank` }
76 return { ok: true, fields: out as Fields }
77}
78
79const TITLES: Record<(typeof FIELD_NAMES)[number], string> = {
80 goal: 'Goal', state: 'State', decisions: 'Decisions', next_step: 'Next step',
81 open_questions: 'Open questions', failed_attempts: 'Failed attempts', standing: 'Standing orders',
82 standing_retire: 'Standing orders retired', session_name: 'Session name',
83}
84
85// Standing orders come right after the goal, so a resumed session reads the chain's rules first.
86const RENDER_ORDER = ['goal', 'standing', 'standing_retire', 'state', 'decisions', 'next_step', 'open_questions', 'failed_attempts'] as const
87
88export const STANDING_MAX_ITEMS = 40
89export const STANDING_MAX_BYTES = 4096
90
91const BULLET = /^\s*(?:[-*\u2022]|\d+[.)])\s+/
92const QUOTES = /^["'\u201c\u2018`]+|["'\u201d\u2019`]+$/g
93const norm = (s: string) => s.toLowerCase().replace(/\s+/g, ' ').trim()
94const lines = (text: string, unquote: boolean) =>
95 text.split('\n').map(l => { const b = l.replace(BULLET, '').trim(); return unquote ? b.replace(QUOTES, '').trim() : b }).filter(Boolean)
96
97// Standing orders hold for the whole chain of sessions. The mod keeps the previous list verbatim, adds the
98// model's new items and removes only what the model names; whatever it names is reported either way.
99export function mergeStanding(prev: string[], added: string, retire: string): { items: string[]; retired: string[]; unmatched: string[]; warning: string | null } {
100 const items = [...prev]
101 for (const a of lines(added, false)) if (!items.some(i => norm(i) === norm(a))) items.push(a)
102 const retired: string[] = []
103 const unmatched: string[] = []
104 for (const r of lines(retire, false)) {
105 const bare = r.replace(QUOTES, '').trim()
106 const exact = items.findIndex(i => norm(i) === norm(r))
107 const at = exact >= 0 ? exact : items.findIndex(i => norm(i) === norm(bare) || norm(i.replace(QUOTES, '')) === norm(bare))
108 if (at < 0) { unmatched.push(r); continue }
109 retired.push(items[at]!)
110 items.splice(at, 1)
111 }
112 const bytes = new TextEncoder().encode(items.join('\n')).length
113 const warning = items.length > STANDING_MAX_ITEMS || bytes > STANDING_MAX_BYTES
114 ? `Standing orders are over the cap (${STANDING_MAX_ITEMS} items or ${STANDING_MAX_BYTES} bytes; now ${items.length} items, ${bytes} bytes): retire what no longer holds.`
115 : null
116 return { items, retired, unmatched, warning }
117}
118
119export function renderHandover(f: Fields, s: Snapshot): string {
120 const parts = [`# 📜 Handover — ${s.session} (${s.at})`, `**Next session:** ${f.session_name}`, '']
121 for (const name of RENDER_ORDER) {
122 if (!f[name]) continue
123 parts.push(`## ${TITLES[name]}`, '', f[name], '')
124 }
125 parts.push('## Snapshot', '',
126 `- cwd: ${s.cwd}`,
127 `- branch: ${s.branch ?? '(not a git repo)'}`,
128 `- context: ${s.contextPct === null ? 'unknown' : `${s.contextPct}%`}`,
129 `- dirty: ${s.dirty.length ? s.dirty.join(', ') : 'none'}`,
130 `- edited this session: ${s.edited.length ? s.edited.join(', ') : 'none'}`,
131 '')
132 return parts.join('\n')
133}
134
135const WHY: Record<PendingReason, string> = {
136 threshold: 'Context is past the handover threshold.',
137 request: 'The person asked for a handover.',
138 last_light: 'The session has gone idle and the prompt cache is about to go cold. Do not clear; just save the handover.',
139 limit: 'A usage limit is close. Save the handover so work can resume after the reset.',
140}
141
142const FIELDS = '(goal, state, decisions, next step, open questions, failed attempts, any new standing orders, session name). Earlier standing orders are carried forward for you: give only new standing orders, and retire one only by naming it.'
143
144export function instructionText(reason: PendingReason): string {
145 // A clear follows the save: wait for a sensible stopping point. The time-critical reasons save now.
146 const when = reason === 'threshold' || reason === 'request'
147 ? `At your next sensible stopping point (finish the step in hand, start no new work, leave no edit half-done) call the ${TOOL_FULL} tool with a complete handover `
148 : `Call the ${TOOL_FULL} tool now with a complete handover `
149 return `[context-vigil-mod] ${WHY[reason]} ${when}${FIELDS}${reason === 'threshold' || reason === 'request' ? '' : ' Do nothing else this turn.'}`
150}
151
152export const STOP_NOW = 'Stop now: end your turn with no further tool calls or work; context-vigil-mod clears and resumes from this handover.'
153
154// Prompts the person sent while the handover was being written: carried verbatim, answered first.
155export const SENT_MAX = 10
156export function sentSection(sent: readonly string[] | undefined): string {
157 if (!sent?.length) return ''
158 return `## Sent during handover\n\nThe person sent ${sent.length === 1 ? 'this' : 'these'} while the handover was being written, so the handover does not cover ${sent.length === 1 ? 'it' : 'them'}. Answer ${sent.length === 1 ? 'it' : 'them'} before the handover's next step:\n\n` +
159 sent.map(t => t.split('\n').map(l => `> ${l}`).join('\n')).join('\n\n')
160}
161
162export function resumeText(path: string): string {
163 return `[context-vigil-mod] Resume from the handover injected above (saved at ${path}). Start with its next step.`
164}
165
166export function injectText(markdown: string): string {
167 return `[context-vigil-mod] Handover from before the clear:\n\n${markdown}`
168}
169
170// After a limit early stop there was no clear: the conversation is still here.
171export function limitResumeText(path: string | null): string {
172 if (path === null) {
173 return '[context-vigil-mod] The usage limit has reset. No handover was written before the stop (it was deferred or classic was active); pick up from the conversation as it stands.'
174 }
175 return `[context-vigil-mod] The usage limit has reset. Continue the work; the handover you wrote is saved at ${path} if you need it.`
176}
177
178// Any mention of a handover at all: the looser net behind the tool (a person who said "handover" and
179// then had the model call the tool meant it).
180export function mentionsHandover(text: string): boolean {
181 return /hand[ -]?over|hand(?:ing)?[ -]?off/i.test(text)
182}
183
184const REQUEST_MAX_WORDS = 12
185const REQUEST_CORE = /\bhand[ -]?over\b|\bhand(?:ing)?[ -]?off\b|\bhand\s+(?:this|it|that|things|everything|us|work|session|this session)\s+(?:over|off)\b|\bhand\s+this\s+session\s+(?:over|off)\b/
186const REQUEST_NEGATION = /\b(?:don'?t|do not|dont|never|no|not|stop|cancel|without|skip|instead|isn'?t|won'?t|can'?t)\b/
187// Questions about handovers, and talk about the mod's code, files and behaviour.
188const REQUEST_ABOUT = /\b(?:how|what|what'?s|whats|why|when|where|which|who|does|did|is|are|was|were|has|have|bug|bugs|fix|fixing|fixed|broken|broke|fail|fails|failed|failing|wrong|work|works|working|implement|code|file|files|test|tests|spec|docs?|document|explain|show|read|review|check|debug|issue|error|last|previous|latest|update|improve|refactor|think|tool|mod|hook|slow|empty|status|summary|details?|info|information|list|history|log|logs|count|size|path|location|contents?|diff|name)\b/
189const REQUEST_CONDITION = /\b(?:if|unless|after|before|once|whenever|until)\b/
190const REQUEST_LEAD = new Set([
191 'handover', 'handoff', 'hand', 'do', 'run', 'start', 'begin', 'make', 'write', 'create', 'give', 'trigger', 'initiate', 'time', "let's", 'lets', 'let',
192 'go', 'ok', 'okay', 'alright', 'right', 'so', 'now', 'please', 'pls', 'can', 'could', 'would', 'will', 'shall', 'i', 'we', "it's", 'its', 'ready',
193 'need', 'needs', 'want', 'yes', 'yep', 'yeah', 'sure', 'just', 'then', 'kindly', 'hey', 'hi',
194])
195
196/** Is this short human message a request to hand over now (not a question or talk about handovers)? */
197export function isHandoverRequest(text: string): boolean {
198 const clean = text.toLowerCase().replace(/[.!?,;:-]+/g, ' ').replace(/\s+/g, ' ').trim()
199 if (!clean || clean.startsWith('/')) return false
200 const words = clean.split(' ')
201 if (words.length > REQUEST_MAX_WORDS) return false
202 if (!REQUEST_CORE.test(clean)) return false
203 if (REQUEST_NEGATION.test(clean) || REQUEST_ABOUT.test(clean) || REQUEST_CONDITION.test(clean)) return false
204 return REQUEST_LEAD.has(words[0]!)
205}
206plugin/core/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}
76plugin/core/title.ts 37 lines1// The session's name as the transcript holds it, and the archive name a handover gives the
2// outgoing session — PROBES §8, §15. Only a `custom-title` line is a name; Claude Code's own
3// `ai-title` is not.
4
5export const ARCHIVE_PREFIX = 'Archive: '
6
7// A title row as the engine writes it: `type` is its first key (all 2,419 custom-title rows in two
8// accounts' transcripts, 2026-10-12). Anchored, so text nested in another row (a tool input) never matches.
9export const TITLE_ROW = '{"type":"custom-title"'
10
11// Prints the transcript's last title row; exits 1 when it has none, 2 when grep cannot read it.
12// Positional args: $1 = transcript path. (BRE: `{` is literal.)
13export const TITLE_CMD = `out=$(grep '^${TITLE_ROW}' "$1"); s=$?; [ "$s" -eq 0 ] && printf '%s\\n' "$out" | tail -n 1; exit $s`
14
15/** The last custom title in transcript text: null = none, undefined = a title line that does not parse (cannot tell). */
16export function lastTitle(text: string): string | null | undefined {
17 const lines = text.split('\n')
18 for (let i = lines.length - 1; i >= 0; i--) {
19 const line = lines[i] ?? ''
20 if (!line.startsWith(TITLE_ROW)) continue
21 let row: { type?: unknown; customTitle?: unknown }
22 try {
23 row = JSON.parse(line) as typeof row
24 } catch {
25 return undefined
26 }
27 if (row?.type !== 'custom-title') continue
28 return typeof row.customTitle === 'string' ? row.customTitle : undefined
29 }
30 return null
31}
32
33export const isArchived = (name: string): boolean => name.startsWith(ARCHIVE_PREFIX)
34
35/** The outgoing session's name: one prefix, never nested. */
36export const archiveName = (name: string): string => (isArchived(name) ? name : `${ARCHIVE_PREFIX}${name}`)
37plugin/core/cache-ttl.ts 63 lines1// Which prompt-cache lifetime the session's main conversation is writing — PROBES §11.
2// Asked once, when last light is about to act. 'unknown' (nothing found) never fires: warming
3// a cold 5-minute cache is the opposite of what last light is for.
4import { joinPath } from './home'
5
6export type CacheTtl = '1h' | '5m' | 'unknown'
7export type Writes = { h1: number; m5: number }
8
9// Reads the usage split off the end of the transcript without ever loading a whole row: grep -o
10// prints only each row's `cache_creation` object. Positional args: $1 = transcript path.
11export const TAIL_CMD = 'tail -c 65536 "$1" | grep -o \'"cache_creation":{[^}]*}\''
12
13/** 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. */
14export function tailBytes(text: string, bytes: number): string {
15 let used = 0
16 let i = text.length
17 while (i > 0) {
18 const code = text.charCodeAt(i - 1)
19 const isLow = code >= 0xdc00 && code <= 0xdfff && i > 1
20 const size = isLow ? 4 : code < 0x80 ? 1 : code < 0x800 ? 2 : 3
21 if (used + size > bytes) break
22 used += size
23 i -= isLow ? 2 : 1
24 }
25
26 return text.slice(i)
27}
28
29/** What TAIL_CMD prints, from the file's text: for where there is no sh/tail/grep (Windows). */
30export function cacheLinesFromText(text: string, bytes = 65536): string {
31 return (tailBytes(text, bytes).match(/"cache_creation":\{[^}]*\}/g) ?? []).join('\n')
32}
33
34const field = (line: string, key: string): number => {
35 const m = new RegExp(`"ephemeral_${key}_input_tokens":(\\d+)`).exec(line)
36 return m ? Number.parseInt(m[1] ?? '0', 10) : 0
37}
38
39// The split of the LAST response that wrote to the cache. A pure cache read writes nothing and
40// says nothing about the lifetime, so it is skipped. null = no write in the tail.
41export function parseWrites(stdout: string): Writes | null {
42 const lines = stdout.split('\n')
43 for (let i = lines.length - 1; i >= 0; i--) {
44 const line = lines[i] ?? ''
45 if (!line.includes('"cache_creation"')) continue
46 const w = { h1: field(line, '1h'), m5: field(line, '5m') }
47 if (w.h1 > 0 || w.m5 > 0) return w
48 }
49 return null
50}
51
52// Any 5m write makes it 5m: content written for five minutes goes cold first, and the cost of
53// warming a cold cache is worse than the cost of skipping a warm one. No write found: unknown.
54export function ttlFromWrites(w: Writes | null): CacheTtl {
55 if (w === null) return 'unknown'
56 return w.m5 > 0 ? '5m' : '1h'
57}
58
59// Where Claude Code keeps a session's transcript, for when no event has carried the path yet.
60export function transcriptPathFor(configRoot: string, cwd: string, sessionId: string): string {
61 return joinPath(configRoot, 'projects', cwd.replace(/[^A-Za-z0-9]/g, '-'), `${sessionId}.jsonl`)
62}
63plugin/core/last-light.ts 40 lines1import { classifyOrigin } from './arming'
2
3export const LEAD_MS = 300_000
4export const TTL_1H = 3_600_000
5
6// Scheduled on the assumption of a 1-hour cache; the fire checks the assumption (PROBES §11).
7export function fireAt(lastApiAt: number): number {
8 return lastApiAt + TTL_1H - LEAD_MS
9}
10
11export type FireFacts = {
12 enabled: boolean
13 youIdle: boolean // nothing from the person since the agent's last API activity
14 agentIdle: boolean // no step in the last WORKING_MS
15 contextPct: number | null
16 threshold: number
17 pending: boolean
18 latched: boolean
19 armed: boolean
20}
21
22export function shouldFire(f: FireFacts):
23 { fire: true } | { fire: false; reason: 'off' | 'not-idle' | 'small' | 'pending' | 'latched' | 'disarmed' } {
24 if (!f.enabled) return { fire: false, reason: 'off' }
25 if (!f.youIdle || !f.agentIdle) return { fire: false, reason: 'not-idle' }
26 if (f.contextPct === null || f.contextPct < f.threshold) return { fire: false, reason: 'small' }
27 if (f.pending) return { fire: false, reason: 'pending' }
28 if (f.latched) return { fire: false, reason: 'latched' }
29 if (!f.armed) return { fire: false, reason: 'disarmed' }
30 return { fire: true }
31}
32
33export function rearm(prev: boolean, origin: string): boolean {
34 return classifyOrigin(origin) === 'human' ? true : prev
35}
36
37export function holdOnReturn(f: { pendingIsLastLight: boolean; origin: string; now: number; cacheExpiresAt: number | null }): boolean {
38 return f.pendingIsLastLight && classifyOrigin(f.origin) === 'human' && f.cacheExpiresAt !== null && f.now >= f.cacheExpiresAt
39}
40