SLOPSHOPPER

sandcastle

Shows a live sandcastle run in the Claude Code session: a row above the prompt, a notice when a ticket needs a person, and a prompt when the run ends; between…

bandcommandtoaststatuspromptmodel
★ 1v0.1.0MITupdated 2026-10-17henkisdabro/sandcastle-kit/mod
A shopper browsing a rack in a slop shop
Source 7 files
hooks/register.tsx 727 lines
1// The sandcastle mod: shows a live run in the Claude Code session, in the status view's own
2// castle, glyphs and colours - a band above the prompt, a notice when a ticket needs a person -
3// and submits a prompt when the run ends, so the session that started it closes it. Between runs,
4// in a project `sandcastle init` has set up, it draws a quiet idle mark in sand above the prompt.
5//
6// It reads `.sandcastle/logs/run.json` under the session's root and asks whether the run's
7// process is alive. Once the session has used the sandcastle skill it also follows a run this
8// session started in another directory: every run records the id of the Claude Code session
9// that started it, and lists itself in a machine-wide directory while it lives. It writes
10// nothing, opens no pane and calls no model but for one thing: while a run this session started is
11// live, it refreshes the session's prompt cache (keep-warm.ts). It does nothing at all in a
12// project with no `.sandcastle/` until the skill is used.
13
14import { atom, read, update } from "claude-code";
15import type { EngineInterface, Register } from "claude-code";
16
17import { band, building, CASTLE_FRAMES, endedHow, endPrompt, followable, HELD, line, needing, parse, parseRegistry, REGISTRY_SCRIPT, rows, type Run, SAND, startedBy, summarise } from "./run-state.ts";
18import { kitRunning } from "./run-live.ts";
19import { activity, afterTurn, keepWarm, parseWarmth, settle, withLaterTurn, type Warmth } from "./keep-warm.ts";
20import { afterRead, afterVersionRead, type Choice, choiceAfter, dismissalEnded, due, heldRelease, type Mark, MARK_USAGE, machineSwitch, markAction, markReport, markText, type MarkInput, parseChoice, parseEntry, parseVersionEntry, parseVersionFacts, readyIds, SETTINGS_SCRIPT, type Tone, type Trigger } from "./idle.ts";
21
22const view = atom({ plugin: "sandcastle", key: "view" } as const, null);
23/** The castle frame the band draws: an index into CASTLE_FRAMES. */
24const castle = atom({ plugin: "sandcastle", key: "castle" } as const, HELD);
25/** The castle tower (a chess rook: one cell, text style, no emoji form) that leads the idle mark's row. */
26const MARK_ICON = "♜";
27/** The idle mark's line the band draws between runs, as sand-coloured parts; null for none. */
28const markLine = atom({ plugin: "sandcastle", key: "mark" } as const, null);
29/** The sand each tone of the mark's line is drawn in: the hint in the castle's bright sand and bold, never Claude Code's notice colour. */
30const TONES: Record<Tone, { color: string; bold?: boolean }> = { name: { color: SAND.name }, hint: { color: SAND.top, bold: true } };
31/** The cache refresh's row the band draws under the castle; null for none. */
32const warmLine = atom({ plugin: "sandcastle", key: "warm" } as const, null);
33/** What the cache refresh remembers; `$.state`, because a reload restarts module variables and not state. */
34const warmth = atom({ plugin: "sandcastle", key: "warmth" } as const, { misses: 0 } as Warmth);
35
36const RECORD = ".sandcastle/logs/run.json";
37// What makes a project set up: `sandcastle init` writes it.
38const CONFIG = ".sandcastle/config.ts";
39const LIVE_MS = 3000;
40// A read of the queue is given up after this long, so one stuck tracker call never blocks the next.
41const READ_TIMEOUT_MS = 20000;
42// With no run alive the record is read this often: a run started by hand shows within it.
43const IDLE_MS = 15000;
44// Room for the control Claude Code draws at the band's right end.
45const BAND_MARGIN = 4;
46// The mark, the band and the cache row stand one column in from the screen's edge: flush to it, they read as cut off.
47const BAND_INDENT = 1;
48
49const NOTE =
50  "\n\n---\nThe sandcastle mod is loaded in this Claude Code session. When a run this session started ends, in this project or any other directory, the mod submits a prompt that says so: skip `sandcastle wait` in step 3 of the run action, and close the run (run.md) when that prompt arrives. The mod also keeps this session's prompt cache warm while the run is live, so skip the skill's keep-warm tick.";
51
52// Module variables on purpose: a reload starts the watch over, and the first look at the
53// record rebuilds all of it but `armed` and each project's `since`, which `$.store` keeps.
54let starting: Promise<boolean> | undefined;
55/** The project the watch reads. A `/cd` does not move it. */
56let watched: string | undefined;
57/** The sandcastle skill was used in this session, so this session closes the run. */
58let armed = false;
59/** The session root's own record and store entry are taken up (once `.sandcastle/` exists). */
60let adopted = false;
61/** What one watched project's looks remember. */
62type Seen = {
63  /**
64   * `startedAt` of the last record whose end this session has accounted for. A record that
65   * differs and whose process is gone is a run that ended - whether or not a look ever saw it
66   * alive: a run that dies on a missing Docker lasts seconds, inside one idle look.
67   */
68  since?: string;
69  /** False until the first look: what that finds was there before, so it announces nothing new. */
70  primed: boolean;
71  needs: string[];
72};
73const seen = new Map<string, Seen>();
74const seenAt = (root: string): Seen => seen.get(root) ?? (seen.set(root, { primed: false, needs: [] }).get(root) as Seen);
75/**
76 * Roots, resolved, of runs this session started outside its own root. Kept once seen: the
77 * registry file goes when the run exits (or later, once its Herdr tab has its report), and the end
78 * is still to be announced.
79 */
80const followed = new Set<string>();
81/**
82 * Every id this session has had in this process. `/clear` gives the session a new one, and a run
83 * started before it records the old: the terminal that started the run still closes it.
84 */
85const known = new Set<string>();
86/** What makes the next idle look read the queue ahead of the entry's age; one is enough, they all mean "now". */
87let trigger: Trigger | undefined;
88/** A queue read is under way in this session: one at a time. */
89let reading = false;
90/** A trigger fired during that read, which may have started before what the trigger is about. */
91let again = false;
92/** The same two for the version read, which has its own: a slow queue never holds it up. */
93let readingVersion = false;
94let againVersion = false;
95/** The sandcastle skill was used and its turn has not ended: the labelling it may do is still to come. */
96let skillTurn = false;
97/** The `sandcastle` to run, found once: the kit's own `bin/sandcastle` beside the mod, else the one on PATH. */
98let kitBin: string | undefined;
99/** The last round drew the idle mark (no needs-you text, no live run of the root): a choice made now redraws it at once. */
100let idling = false;
101let drawn = "";
102/** The cache refresh's timer while a run of this session is live; undefined otherwise. */
103let warmTimer: { cancel: () => void } | undefined;
104/** The run the refresh looks after: this session's newest live one. */
105let warmRun: Run | undefined;
106/** A refresh request is under way: one at a time, and a tick that finds it waits for the next. */
107let refreshing = false;
108/** The cache refresh's row the band was last told to draw. */
109let warmed: string | null = null;
110/** null: nothing pinned or cleared since this load, so the first call always reaches Claude Code. */
111let pinned: string | undefined | null = null;
112
113/**
114 * Whether `path` is a plain file. A plain file only: in a stranger's repository the path could be
115 * a link to a device that never ends.
116 */
117async function plain($: EngineInterface, path: string): Promise<boolean> {
118  const at = await stat($, path);
119  return at !== undefined && at.kind === "file" && !at.isLink;
120}
121
122/** The one place the mod stats a path; `resolve` also answers where the path lands. Undefined when it cannot be read. */
123async function stat($: EngineInterface, path: string, resolve = false) {
124  try {
125    return await $.fs.stat(path, resolve ? { resolve: true } : undefined);
126  } catch {
127    return undefined;
128  }
129}
130
131async function record($: EngineInterface, root: string): Promise<Run | undefined> {
132  const path = `${root}/${RECORD}`;
133  try {
134    if (!(await plain($, path))) return undefined;
135    return parse(await $.fs.read(path));
136  } catch {
137    return undefined;
138  }
139}
140
141const isProject = ($: EngineInterface, root: string) => $.fs.exists(`${root}/.sandcastle`);
142
143/** The one place the mod starts a process. */
144const exec = ($: EngineInterface, argv: string[], init?: { cwd?: string; timeoutMs?: number }) => $.process.run(argv, init);
145
146// Asks for the process's command line and sends nothing to it; that it is the kit's is
147// run-live.ts's rule, the same everywhere a run is asked about. The record's `finishedAt` is
148// left out on purpose: every turn of one run writes one, a killed run none, and between two
149// turns the run is still going.
150async function alive($: EngineInterface, pid: number): Promise<boolean> {
151  try {
152    // `-p` and `-o command=` are the flags BSD `ps` (macOS) and procps-ng share. BusyBox has no
153    // `-p`: the call fails, so there it is no live run and no false end.
154    const ps = await exec($, ["ps", "-p", String(pid), "-o", "command="]);
155    return kitRunning(pid, () => (ps.exitCode === 0 ? ps.stdout : undefined));
156  } catch {
157    return false;
158  }
159}
160
161type Kept = { session?: string; since?: string } | undefined;
162
163// Kept across a restart of Claude Code: a resumed session still hears that its run ended.
164// One entry per project, so of two sessions that used the skill there the later one owns it.
165async function remember($: EngineInterface, root: string) {
166  const since = seenAt(root).since;
167  await $.store.set(root, { session: await $.session.id(), ...(since === undefined ? {} : { since }) });
168}
169
170/** The session's id, kept in `known`. */
171async function me($: EngineInterface): Promise<string> {
172  const id = await $.session.id();
173  known.add(id);
174  return id;
175}
176
177/** Whether `run` records an id this session has had. */
178const ours = (run: Run | undefined) => [...known].some((id) => startedBy(run, id));
179
180async function owns($: EngineInterface, kept: Kept): Promise<boolean> {
181  return kept?.session === (await $.session.id());
182}
183
184/** The idle mark the band was last told to draw, as its parts in JSON; undefined until the first look of this load. */
185let marked: string | null | undefined;
186
187/**
188 * The idle mark is drawn by the band, not pinned as a status line: Claude Code prefixes every
189 * pinned status line with its warning triangle and paints it in its notice colour, and a mod
190 * cannot change either. The pinned line stays for what needs a person.
191 */
192async function place($: EngineInterface, mark: Mark | undefined) {
193  const key = mark ? JSON.stringify(mark.parts) : null;
194  if (key === marked) return;
195  marked = key;
196  await update($, markLine, () => mark?.parts ?? null);
197}
198
199function pin($: EngineInterface, text: string | undefined) {
200  if (text === pinned) return;
201  pinned = text;
202  $.ui.status(text);
203}
204
205/** The castle's timer while it builds; undefined while it stands still. */
206let tick: { cancel: () => void } | undefined;
207
208// A timer of its own, apart from the look at the record: a frame writes the one atom and reads
209// nothing, and a look never waits for a frame. One write per frame, about one a second while it
210// builds and none while it holds - far inside the band's redraw rate, so the prompt never flickers.
211function animate($: EngineInterface, on: boolean) {
212  if (on === (tick !== undefined)) return;
213  if (!on) {
214    tick?.cancel();
215    tick = undefined;
216    void update($, castle, () => HELD);
217    return;
218  }
219  const show = (i: number) => {
220    void update($, castle, () => i);
221    tick = $.clock.after(CASTLE_FRAMES[i]!.ms, () => show((i + 1) % CASTLE_FRAMES.length));
222  };
223  show(0);
224}
225
226async function draw($: EngineInterface, run: Run | undefined) {
227  const next = run ? summarise(run) : null;
228  animate($, next !== null && building(next));
229  if (JSON.stringify(next) === drawn) return;
230  drawn = JSON.stringify(next);
231  await update($, view, () => next);
232}
233
234/**
235 * One look at one project's record: the live run, if there is one. `follow` is set for a
236 * followed root: its run is this session's by the id it records, so it is never "old" and needs
237 * no store entry; a record that is another session's run, or none, ends the following.
238 */
239async function look($: EngineInterface, root: string, follow = false): Promise<Run | undefined> {
240  const run = await record($, root);
241  const w = seenAt(root);
242  const first = !follow && !w.primed;
243  w.primed = true;
244  if (follow && !ours(run)) {
245    followed.delete(root);
246    seen.delete(root);
247    return undefined;
248  }
249  if (run?.pid !== undefined && (await alive($, run.pid))) {
250    const now = needing(run);
251    const fresh = now.filter((n) => !w.needs.includes(n));
252    // What the first look finds needed a person already: the status line names it, no notice.
253    if (!first && fresh.length) $.ui.toast(`${fresh.join(", ")} ${fresh.length > 1 ? "need" : "needs"} you`, { timeoutMs: 10000 });
254    w.needs = now;
255    return run;
256  }
257  w.needs = [];
258  if (!run?.startedAt || run.startedAt === w.since) return undefined;
259  // Read before `since` moves: a store that cannot be read leaves the end to the next look.
260  // A run that records the session that started it is that session's, wherever it was started
261  // from: the store's "later session owns the project" would have a second session close it too.
262  // A run with no id (a plain terminal, Codex, OpenCode) is the store's.
263  const mine = armed && (follow || (run.session ? ours(run) : await owns($, (await $.store.get(root)) as Kept)));
264  w.since = run.startedAt;
265  // The end is accounted for: a later run of this session in that root is found again.
266  if (follow) {
267    followed.delete(root);
268    seen.delete(root);
269  }
270  // A session that was not waiting for a run meets an old record: nothing ended on its watch.
271  if (first && !armed) return undefined;
272  // The run closed or left tickets: the count is read again at the next idle look. A followed run
273  // too - it may be a second clone of this project, burning down the same tracker.
274  trigger = "run-ended";
275  const how = endedHow(run);
276  if (mine) {
277    // The store keeps the old `since` until the turn this starts has begun, which may be much
278    // later: a session quit with the prompt still queued hears it again when it is resumed.
279    const text = endPrompt(root, run);
280    void $.prompt.submit({ text }).then(() => (follow ? undefined : remember($, root))).catch(() => {});
281  }
282  $.ui.toast(`run ${how}`, { timeoutMs: 10000 });
283  return undefined;
284}
285
286/**
287 * Finds runs this session started outside its own root: the registered live runs whose record
288 * names an id this session has had. Fails closed - a shell or a record that cannot be read adds
289 * nothing.
290 */
291async function discover($: EngineInterface, root: string) {
292  let out: string;
293  try {
294    const ls = await exec($, ["sh", "-c", REGISTRY_SCRIPT, "sh", root]);
295    if (ls.exitCode !== 0) return;
296    out = ls.stdout;
297  } catch {
298    return;
299  }
300  for (const other of followable(parseRegistry(out))) {
301    if (followed.has(other)) continue;
302    const run = await record($, other);
303    if (ours(run) && run?.pid !== undefined && (await alive($, run.pid))) followed.add(other);
304  }
305}
306
307/** The session root's store entry, `/sandcastle-status` and `/sandcastle-mark`, once `.sandcastle/` exists. */
308async function adopt($: EngineInterface, root: string) {
309  if (adopted || !(await isProject($, root))) return;
310  adopted = true;
311  const kept = (await $.store.get(root)) as Kept;
312  if (await owns($, kept)) {
313    armed = true;
314    seenAt(root).since = kept?.since;
315  }
316  await $.command.register({ name: "sandcastle-status", description: "Show the sandcastle run in this project, with no model turn", immediate: true });
317  await $.command.register({ name: "sandcastle-mark", description: "Dismiss the idle mark's ready count and newer release, or hide or show the mark, with no model turn", argumentHint: "[dismiss|hide|show]", immediate: true });
318}
319
320/** The shared cache entry's key: one per project root, apart from the session entry under the bare root. */
321const readyKey = (root: string) => `ready:${root}`;
322
323/**
324 * The command that reads the queue. The mod is linked from the kit's checkout, so `bin/sandcastle`
325 * sits beside it; a mod copied elsewhere finds none and uses the `sandcastle` on PATH.
326 */
327async function sandcastle($: EngineInterface): Promise<string> {
328  if (kitBin !== undefined) return kitBin;
329  kitBin = "sandcastle";
330  // No stat of the mod's own folder, or no file beside it: the one on PATH.
331  const dir = ((await stat($, $.plugin.root, true))?.realPath ?? $.plugin.root).replace(/\/+$/, "");
332  const bin = `${dir.slice(0, Math.max(dir.lastIndexOf("/"), 0))}/bin/sandcastle`;
333  if (await plain($, bin)) kitBin = bin;
334  return kitBin;
335}
336
337/** The ready ids from `sandcastle queue --json`, or undefined when the read failed or timed out. */
338async function readQueue($: EngineInterface, root: string): Promise<string[] | undefined> {
339  try {
340    const out = await exec($, [await sandcastle($), "queue", "--json"], { cwd: root, timeoutMs: READ_TIMEOUT_MS });
341    return out.exitCode === 0 && !out.isStdoutTruncated ? readyIds(out.stdout) : undefined;
342  } catch {
343    return undefined;
344  }
345}
346
347/**
348 * Reads the queue into the shared entry, one read at a time in this session; never awaited by a
349 * look or a render, so a slow or hung tracker holds nothing up. A failed read keeps the last good
350 * ids and their time. Another session racing to the same stale entry may read too: accepted.
351 */
352async function refresh($: EngineInterface, root: string, forced: boolean) {
353  if (reading) {
354    // An age that is due again is the read under way; only a trigger asks for another after it.
355    if (forced) again = true;
356    return;
357  }
358  reading = true;
359  try {
360    do {
361      again = false;
362      const ids = await readQueue($, root);
363      const prior = parseEntry(await $.store.get(readyKey(root)));
364      await $.store.set(readyKey(root), afterRead(prior, ids, await $.clock.now()));
365    } while (again);
366  } catch {
367    // A store or clock that cannot be reached leaves the entry as it was: the next look reads again.
368  } finally {
369    reading = false;
370  }
371}
372
373/** The version entry's key, beside the ready entry's: one per project root, shared by every session on the machine. */
374const versionKey = (root: string) => `version:${root}`;
375
376/** The facts from `sandcastle --version --json`, or undefined when the read failed or timed out. */
377async function readVersion($: EngineInterface, root: string) {
378  try {
379    const out = await exec($, [await sandcastle($), "--version", "--json"], { cwd: root, timeoutMs: READ_TIMEOUT_MS });
380    return out.exitCode === 0 && !out.isStdoutTruncated ? parseVersionFacts(out.stdout) : undefined;
381  } catch {
382    return undefined;
383  }
384}
385
386/** Reads the version facts into the shared entry, as `refresh` does the queue: one at a time, never awaited by a look. */
387async function refreshVersion($: EngineInterface, root: string, forced: boolean) {
388  if (readingVersion) {
389    if (forced) againVersion = true;
390    return;
391  }
392  readingVersion = true;
393  try {
394    do {
395      againVersion = false;
396      const facts = await readVersion($, root);
397      const prior = parseVersionEntry(await $.store.get(versionKey(root)));
398      await $.store.set(versionKey(root), afterVersionRead(prior, facts, await $.clock.now()));
399    } while (againVersion);
400  } catch {
401    // A store or clock that cannot be reached leaves the entry as it was: the next look reads again.
402  } finally {
403    readingVersion = false;
404  }
405}
406
407/** The person's choices for a project's mark: the store's entry, none when it holds nothing usable. */
408const markKey = (root: string) => `mark:${root}`;
409
410/** The machine switch: one read of the personal settings, on unless they say `"idleMark": false`. */
411async function machineOn($: EngineInterface): Promise<boolean> {
412  try {
413    const out = await exec($, ["sh", "-c", SETTINGS_SCRIPT]);
414    if (out.exitCode === 0) return machineSwitch(out.stdout);
415  } catch {
416    // Settings that cannot be read leave the switch on.
417  }
418  return true;
419}
420
421/**
422 * Everything the idle mark is decided from that the mod already holds: set up is one `stat` of
423 * `.sandcastle/config.ts`, the machine switch one read of the personal settings, the choices and
424 * the count what the store holds. Nothing here reaches the tracker.
425 */
426async function facts($: EngineInterface, root: string): Promise<MarkInput> {
427  const setUp = await plain($, `${root}/${CONFIG}`);
428  const idleMark = setUp ? await machineOn($) : true;
429  const now = await $.clock.now();
430  const entry = parseEntry(await $.store.get(readyKey(root)));
431  const versionRead = parseVersionEntry(await $.store.get(versionKey(root)));
432  const choice = parseChoice(await $.store.get(markKey(root)));
433  return { setUp, idleMark, hidden: choice?.hidden, dismissed: choice?.dismissed, dismissedRelease: choice?.dismissedRelease, entry, versionRead, now };
434}
435
436/**
437 * The idle mark's text for the session root's project, which no followed run changes - a read it
438 * starts is for the next look to show.
439 */
440async function mark($: EngineInterface, root: string): Promise<Mark | undefined> {
441  const input = await facts($, root);
442  if (!input.setUp || !input.idleMark) return markText(input);
443  if (input.dismissed && dismissalEnded(input.dismissed, input.entry, input.now)) {
444    // A ticket not in the dismissal is ready: the dismissal is over for good, not only while it shows.
445    // The dismissed release is its own: it stays as it was.
446    await $.store.set(markKey(root), { hidden: input.hidden === true, ...(input.dismissedRelease ? { dismissedRelease: input.dismissedRelease } : {}) });
447    input.dismissed = undefined;
448  }
449  if (!input.hidden) {
450    // Both reads see the trigger before either consumes it: the end of a skill's turn re-reads the count and the version.
451    const forced = trigger !== undefined;
452    if (due(input.entry, input.now!, trigger)) void refresh($, root, forced);
453    if (due(input.versionRead, input.now!, trigger)) void refreshVersion($, root, forced);
454    trigger = undefined;
455  }
456  return markText(input);
457}
458
459/** `/sandcastle-mark`: the choice is kept, the line redrawn at once if the mark is what it shows, the reply is text. */
460async function choose($: EngineInterface, root: string, args: string): Promise<string> {
461  const action = markAction(args);
462  if (action === undefined) return MARK_USAGE;
463  if (action !== "report") {
464    const input = await facts($, root);
465    const prior: Choice = { hidden: input.hidden === true, ...(input.dismissed ? { dismissed: input.dismissed } : {}), ...(input.dismissedRelease ? { dismissedRelease: input.dismissedRelease } : {}) };
466    await $.store.set(markKey(root), choiceAfter(action, prior, input.entry, input.now, input.versionRead));
467    if (idling) await place($, await mark($, root));
468  }
469  const input = await facts($, root);
470  // A release kept from an earlier dismissal that a newer tag has ended is not named: the report below would contradict it.
471  const held = action === "dismiss" ? heldRelease(input) : undefined;
472  const out = held ? ` The ${held} release stays quiet until a newer one is tagged.` : "";
473  const done = { dismiss: `Dismissed: the count stays quiet until a ticket not ready now becomes ready.${out}`, hide: "Hidden in this project until /sandcastle-mark show.", show: "Shown." };
474  return action === "report" ? markReport(input) : `${done[action]}\n${markReport(input)}`;
475}
476
477const REFRESH_PROMPT = "Reply with the single word: ok";
478
479/**
480 * One tick of the cache refresh: builds the rule's input, sends the request when it says so, keeps
481 * what it found in `$.state` and redraws the row. A request that is not answered is a miss, logged.
482 * Nothing here throws into the timer: a failed read leaves the row as it was.
483 */
484async function warm($: EngineInterface) {
485  const run = warmRun;
486  if (!run || refreshing) return;
487  try {
488    const now = await $.clock.now();
489    let memory = parseWarmth(await read($, warmth));
490    // Another run starts the count of misses over; the turn that ended last still counts.
491    if (memory.run !== run.startedAt) memory = { misses: 0, ...(memory.turnEnd === undefined ? {} : { turnEnd: memory.turnEnd }), ...(run.startedAt === undefined ? {} : { run: run.startedAt }) };
492    const usage = await $.session.usage();
493    // The run's start is the floor: the turn that started it ended about then, and a reload forgets the later ones.
494    const input = (m: Warmth) => ({ enabled: run.keepWarm, live: true, lastActivity: activity(m, Date.parse(run.startedAt ?? "")), last: m.last, misses: m.misses, rateLimits: usage.rateLimits, now });
495    let verdict = keepWarm(input(memory));
496    if (verdict.refresh) {
497      refreshing = true;
498      try {
499        const result = await $.model.fork({ prompt: REFRESH_PROMPT });
500        if (!result.isAnswered) $.ui.log(`sandcastle: the cache refresh was not answered (${result.reason}); counted as a miss`);
501        memory = settle(memory, result, usage.context.tokens ?? 0, await $.clock.now());
502        verdict = keepWarm(input(memory));
503      } finally {
504        refreshing = false;
505      }
506    }
507    await update($, warmth, (m) => withLaterTurn(memory, parseWarmth(m)));
508    await shine($, verdict.band ?? null);
509  } catch {
510    // A usage or request that failed is tried again at the next tick.
511  }
512}
513
514async function shine($: EngineInterface, line: string | null) {
515  if (line === warmed) return;
516  warmed = line;
517  await update($, warmLine, () => line);
518}
519
520/** Starts the refresh's timer while `run` is live and stops it when none is; the tick itself decides whether to send. */
521function keepCacheOf($: EngineInterface, run: Run | undefined) {
522  warmRun = run;
523  if (run && !warmTimer) {
524    warmTimer = $.clock.every(60_000, () => void warm($));
525    void warm($);
526  } else if (!run && warmTimer) {
527    warmTimer.cancel();
528    warmTimer = undefined;
529    void shine($, null);
530  }
531}
532
533/** One round: every watched project once; true while a run is alive. The newest live run is the one drawn. */
534async function round($: EngineInterface, root: string): Promise<boolean> {
535  await adopt($, root);
536  await me($);
537  if (armed) await discover($, root);
538  const live: Run[] = [];
539  const own = adopted ? await look($, root) : undefined;
540  if (own) live.push(own);
541  // oxlint-disable-next-line no-useless-spread -- a snapshot: `look` deletes from `followed`, and other rounds change it across the awaits
542  for (const other of [...followed]) {
543    const run = await look($, other, true);
544    if (run) live.push(run);
545  }
546  const shown = live.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))[0];
547  const now = shown ? needing(shown) : [];
548  // The line is the needs-you text while a live run needs a person, and otherwise the idle mark -
549  // unless a run is alive, here or followed elsewhere: its castle and counts take over, and a
550  // mark above them would read as a second, stale queue. Last, so after the end notice: the mark
551  // returns once the run is over.
552  idling = !now.length && !shown && adopted;
553  // The refresh looks after a run this session started or follows (or its root's, when it records no session and this one closes it).
554  keepCacheOf($, live.filter((run) => armed && (ours(run) || !run.session)).sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))[0]);
555  pin($, now.length ? `${now.join(", ")} - /sandcastle-status` : undefined);
556  await place($, idling ? await mark($, root) : undefined);
557  await draw($, shown);
558  return live.length > 0;
559}
560
561async function watch($: EngineInterface, root: string) {
562  let live = false;
563  try {
564    live = await round($, root);
565  } catch {
566    // A look that failed is tried again at the next one.
567  }
568  $.clock.after(live ? LIVE_MS : IDLE_MS, () => void watch($, root));
569}
570
571/**
572 * Starts the loop. In a project with no `.sandcastle/` it starts only when the session has used
573 * the skill (`used`): the loop then watches runs started from here, and the project's own record
574 * once `sandcastle init` makes it.
575 */
576async function start($: EngineInterface, root: string, used: boolean): Promise<boolean> {
577  if (!used && !(await isProject($, root))) return false;
578  watched = root;
579  // Awaited: what the first look finds is what every later one is compared with.
580  await watch($, root);
581  return true;
582}
583
584/** Starts the watch, once however many callers ask at the same time; false in a project with no `.sandcastle/` unless `used`. */
585function begin($: EngineInterface, root: string, used = false): Promise<boolean> {
586  starting ??= start($, root, used).then(
587    (ok) => {
588      if (!ok) starting = undefined;
589      return ok;
590    },
591    (error) => {
592      starting = undefined;
593      throw error;
594    },
595  );
596  return starting;
597}
598
599export const register: Register = (on) => {
600  on("session.start", async ($, e, next) => {
601    const out = await next(e);
602    await begin($, await $.session.root());
603    return out;
604  });
605
606  // `/clear` and a `/resume` inside Claude Code change the session under the same process and
607  // start no session anew. The arming stays with this terminal, and the store learns the new
608  // session id, so it is still this one's after a restart.
609  on("classic.SessionStart", { source: ["clear", "resume", "fork"] }, async ($, e, next) => {
610    const out = await next(e);
611    if (watched === undefined) return out;
612    if (await owns($, (await $.store.get(watched)) as Kept)) armed = true;
613    else if (armed) await remember($, watched);
614    return out;
615  });
616
617  on("skill.prompt", { skill: "sandcastle" }, async ($, e, next) => {
618    const out = await next(e);
619    const root = await $.session.root();
620    // Whatever the root, the note is true: a run this session starts records the session's id and
621    // is followed wherever it lives, so the end prompt arrives. (`sandcastle init` may have made
622    // the project after this session started; a `/cd` leaves the watch on the first root, which
623    // the id-based follow does not depend on.)
624    await me($);
625    // The skill may just have labelled tickets: the next idle look reads the count. Triaging
626    // labels them well after this hook, so the end of the turn asks for one more read.
627    trigger = "skill";
628    skillTurn = true;
629    await begin($, root, true);
630    await remember($, root);
631    armed = true;
632    return { text: out.text + NOTE };
633  });
634
635  // The turn that used the skill is over: whatever it labelled is labelled, so the count is read
636  // again. A subagent's turn (one with an `agentId`) is not it: triage reads tickets through
637  // subagents before it labels, so their ends would spend the read too early.
638  on("turn.complete", async ($, e, next) => {
639    const out = await next(e);
640    if (skillTurn && e.agentId === undefined) {
641      skillTurn = false;
642      trigger = "skill";
643    }
644    // The main thread's turn used the cache; a subagent's has its own.
645    if (e.agentId === undefined) {
646      const at = await $.clock.now();
647      await update($, warmth, (m) => afterTurn(parseWarmth(m), at));
648    }
649    return out;
650  });
651
652  on("command.run", { command: "sandcastle-status" }, async ($) => {
653    const roots = [await $.session.root(), ...followed];
654    const blocks: string[] = [];
655    for (const root of roots) {
656      const run = await record($, root);
657      if (!run) continue;
658      const live = run.pid !== undefined && (await alive($, run.pid));
659      const head = live ? "live" : run.finishedAt ? `ended (exit ${run.exitCode ?? "unknown"})` : "ended without a clean exit";
660      blocks.push(
661        [
662          ...(roots.length > 1 ? [root] : []),
663          `${head} · ${line(run, live)}`,
664          ...rows(run),
665          ...(live ? [] : ["`sandcastle report` prints the closing summary."]),
666        ].join("\n"),
667      );
668    }
669    return { text: blocks.join("\n\n") || "No sandcastle run on record in this project." };
670  });
671
672  on("command.run", { command: "sandcastle-mark" }, async ($, e) => ({ text: await choose($, await $.session.root(), e.args) }));
673
674  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
675    const now = await read($, view);
676    const line = await read($, markLine);
677    const cache = await read($, warmLine);
678    if ((now === null && line === null && cache === null) || e.props.hasSurvey) return next(e);
679    const frame = CASTLE_FRAMES[await read($, castle)] ?? CASTLE_FRAMES[HELD];
680    const { Box, Text } = $.ui.resolve(e);
681    return (
682      <Box flexDirection="column">
683        <Box flexDirection="column" paddingLeft={BAND_INDENT}>
684          {/* A session reloaded from an older mod still holds the mark as a string: draw nothing until it is set again. */}
685          {!Array.isArray(line) ? null : (
686            <Box flexDirection="row" columnGap={1}>
687              <Text color={SAND.top} bold>
688                {MARK_ICON}
689              </Text>
690              {line.map((part) => {
691                // A mark set by an older mod can hold a tone this one has dropped (`muted`): drawn as the name, never a throw.
692                const tone = TONES[part.tone] ?? TONES.name;
693                return (
694                  <Text color={tone.color} bold={tone.bold}>
695                    {part.text}
696                  </Text>
697                );
698              })}
699            </Box>
700          )}
701          {now === null
702            ? null
703            : band(now, e.props.bodyColumns - BAND_MARGIN - BAND_INDENT, frame, cache).map((row) => (
704                <Box flexDirection="row" columnGap={2}>
705                  {row.map((seg) => (
706                    <Box flexDirection="row" columnGap={1}>
707                      <Text color={seg.colour} bold={seg.bold}>
708                        {seg.text}
709                      </Text>
710                      {seg.count === undefined ? null : (
711                        <Text color={seg.colour} bold>
712                          {String(seg.count)}
713                        </Text>
714                      )}
715                    </Box>
716                  ))}
717                </Box>
718              ))}
719          {/* With a run on screen the band places the cache row itself (beside the title, or lined up with it). */}
720          {cache === null || now !== null ? null : <Text color={SAND.name}>{cache}</Text>}
721        </Box>
722        {await next(e)}
723      </Box>
724    );
725  });
726};
727
hooks/run-state.ts 246 lines
1// What the mod says about a run record (.sandcastle/logs/run.json). Pure: nothing here
2// touches Claude Code, so the kit's own tests import this file and hold it to the status
3// view's vocabulary (src/status-rows.ts and src/status-render.ts). The record's types, the ticket states and the
4// tables from state to group and word live in run-record.ts.
5
6import { GROUPS, type Group, isTicketState, type RunRecord, sessionId, WORDS } from "./run-record.ts";
7
8/** A ticket as read from a file that may be a stranger's: its state is any short text until `isTicketState` says otherwise. */
9export type Ticket = { state?: string; note?: string; title?: string; order?: number };
10
11/** The run record as the mod reads it: the fields it shows, and tickets whose state is not yet trusted. */
12export type Run = Pick<RunRecord, "orchestrator" | "pid" | "session" | "startedAt" | "finishedAt" | "exitCode" | "stage" | "tokens"> & {
13  /** The record's `settings.keepWarm` when it is a boolean; absent for an older kit's record, which reads as on (keep-warm.ts). */
14  keepWarm?: boolean;
15  tickets?: Record<string, Ticket>;
16};
17
18// The status view's sand palette, as hex: a mod's Text takes no 256-colour index. Dry sand at
19// the castle's top, wet sand at its base.
20export const SAND = { top: "#e8d6b4", mid: "#cdb894", base: "#705c42", name: "#cdb894", stage: "#c0a478", muted: "#927c5e" };
21
22/** The castle's three rows, each five cells wide. */
23export type Castle = { top: string; mid: string; base: string };
24
25// The status view's three-row castle: the battlements stand a row above the text beside it.
26// A castle cut to one row (a bare slab) reads as no castle at all, so the view's one-row fold
27// draws none, only the wordmark.
28export const CASTLE: Castle = { top: "▄ ▄ ▄", mid: "█████", base: "██▀██" };
29
30// While a ticket is in work the castle builds from level sand, half a row at a time, and holds
31// complete before it starts again: a loop the eye follows as work going on, where a long hold
32// read as the run standing still. Every frame is a whole number of one 500 ms beat and the loop
33// is twelve of them (three bars of four), so the build keeps time and the restart lands on the
34// bar; the hold is never shorter than the build, so the finished castle is what the eye mostly sees. Every row of every frame is five cells, so the
35// text beside it never moves, and the band's height never changes.
36const AIR = "     ";
37export const CASTLE_FRAMES: (Castle & { ms: number })[] = [
38  { top: AIR, mid: AIR, base: "▁▁▁▁▁", ms: 500 },
39  { top: AIR, mid: AIR, base: "▄▄▄▄▄", ms: 500 },
40  { top: AIR, mid: AIR, base: CASTLE.base, ms: 500 },
41  { top: AIR, mid: "▄▄▄▄▄", base: CASTLE.base, ms: 500 },
42  { top: AIR, mid: CASTLE.mid, base: CASTLE.base, ms: 500 },
43  { ...CASTLE, ms: 3500 },
44];
45/** The held frame: the castle as the status view draws it. */
46export const HELD = CASTLE_FRAMES.length - 1;
47
48/** The status view's legend: its order, glyphs, words and colours. */
49export const LEGEND: { group: Group; glyph: string; label: string; colour: string }[] = [
50  { group: "working", glyph: "●", label: "working", colour: "#ffd75f" },
51  { group: "needs you", glyph: "!", label: "needs you", colour: "#ff5f5f" },
52  { group: "ready", glyph: ">", label: "ready to land", colour: "#5fd7d7" },
53  { group: "queued", glyph: "○", label: "queued", colour: "#87afff" },
54  { group: "blocked", glyph: "~", label: "blocked", colour: "#87afff" },
55  { group: "merged", glyph: "+", label: "merged", colour: "#5fd75f" },
56];
57
58// A state that is no ticket state (`constructor` included) is in no group and has no word of its own.
59const group = (t: Ticket): Group => (isTicketState(t.state) ? GROUPS[t.state] : "other");
60
61const word = (state: string | undefined) => (isTicketState(state) ? WORDS[state] : undefined) ?? state ?? "unknown";
62
63// The record is a file in a repository, which may be a stranger's: nothing in it is trusted to
64// be what src/run.ts writes. Text is cut to one short line with nothing in it that draws no
65// glyph - control, format (direction marks, tag characters), line separators, variation
66// selectors, private-use and half a surrogate pair - so it cannot pose as a line of its own in
67// what Claude reads, carry words a person cannot see, or redraw the terminal. Cut by code
68// point: a cut through an emoji would leave half of one. A number is a whole number or absent.
69const text = (v: unknown, max: number) =>
70  typeof v === "string"
71    ? Array.from(v.replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Zl}\p{Zp}\p{Variation_Selector}]+/gu, " ").trim())
72        .slice(0, max)
73        .join("") || undefined
74    : undefined;
75const whole = (v: unknown) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : undefined);
76const MAX_TICKETS = 200;
77
78export { RUN_COMMAND } from "./run-live.ts";
79
80// A ticket as the kit writes it (src/tracker.ts, `refOf`): `#12` for a number, the id itself
81// for a ticket file.
82const ref = (id: string) => (/^\d+$/.test(id) ? `#${id}` : id);
83
84/** How a run ended, from its exit code alone: a whole number or the word `unknown`, never record text. */
85export const endedHow = (run: Run): string => (run.finishedAt ? `ended (exit ${whole(run.exitCode) ?? "unknown"})` : "ended without a clean exit");
86
87/**
88 * The prompt that has the session close a run that ended. It names the run by numbers only - the
89 * pid when it is a whole number, the start time re-rendered as local `HH:MM` (as the closing
90 * summary's Run line prints it) when `startedAt` parses as a date - and leaves out anything else:
91 * the record is a file in a repository that may be a stranger's. The text is fixed when the end is
92 * seen and read when the session is idle, by which time a later run may be live in the same
93 * root; the numbers are how the agent tells the run that ended from that one.
94 */
95export const endPrompt = (root: string, run: Run): string => {
96  const pid = run.pid !== undefined && Number.isSafeInteger(run.pid) && run.pid > 0 ? `pid ${run.pid}` : undefined;
97  const at = run.startedAt === undefined ? NaN : Date.parse(run.startedAt);
98  const started = Number.isFinite(at) ? `started ${new Date(at).toTimeString().slice(0, 5)}` : undefined;
99  const named = [pid, started].filter(Boolean).join(", ");
100  return `The sandcastle run in ${root}${named ? ` (${named})` : ""} ${endedHow(run)}. Close that run now: read run.md in the sandcastle skill's directory and follow it.`;
101};
102
103const settingOf = (settings: unknown, key: string): boolean | undefined => {
104  const value = settings && typeof settings === "object" ? (settings as Record<string, unknown>)[key] : undefined;
105  return typeof value === "boolean" ? value : undefined;
106};
107
108/** A half-written or foreign file reads as no record. */
109export const parse = (raw: string): Run | undefined => {
110  let r: Record<string, unknown>;
111  try {
112    r = JSON.parse(raw);
113  } catch {
114    return undefined;
115  }
116  if (!r || typeof r !== "object") return undefined;
117  const tickets = r.tickets && typeof r.tickets === "object" ? Object.entries(r.tickets as Record<string, Record<string, unknown> | null>) : [];
118  return {
119    orchestrator: text(r.orchestrator, 40),
120    // 0 is no process.
121    pid: whole(r.pid) || undefined,
122    session: sessionId(r.session),
123    startedAt: text(r.startedAt, 40),
124    finishedAt: text(r.finishedAt, 40),
125    exitCode: whole(r.exitCode),
126    stage: text(r.stage, 40),
127    tokens: text(r.tokens, 40),
128    keepWarm: settingOf(r.settings, "keepWarm"),
129    tickets: Object.fromEntries(
130      // A ticket file's id is a whole slug: cut short, two tickets of one feature would share a key.
131      tickets.slice(0, MAX_TICKETS).map(([id, t]) => [text(id, 100) ?? "?", { state: text(t?.state, 24), note: text(t?.note, 100), title: text(t?.title, 100), order: whole(t?.order) }]),
132    ),
133  };
134};
135
136const tickets = (run: Run) => Object.entries(run.tickets ?? {});
137
138/** The tickets a person has to act on: `#105 conflict`. */
139export const needing = (run: Run): string[] =>
140  tickets(run)
141    .filter(([, t]) => group(t) === "needs you")
142    .map(([id, t]) => `${ref(id)} ${word(t.state)}`);
143
144/** What the band above the prompt draws from: plain data, so it can live in `$.state`. */
145export type Summary = { name: string; stage: string; counts: number[]; tokens: string };
146
147/** `counts` runs parallel to LEGEND. */
148export const summarise = (run: Run): Summary => ({
149  name: run.orchestrator ?? "",
150  // One process can hold several turns: a finished record with a live process is between two.
151  stage: run.finishedAt ? "turn finished" : run.stage && run.stage !== "running" ? run.stage : "",
152  counts: LEGEND.map((g) => tickets(run).filter(([, t]) => group(t) === g.group).length),
153  tokens: run.tokens ?? "",
154});
155
156export type Segment = { text: string; colour: string; bold?: true; count?: number };
157
158/** Whether the run has a ticket in work: the castle builds only then. */
159export const building = (s: Summary): boolean => (s.counts[LEGEND.findIndex((g) => g.group === "working")] ?? 0) > 0;
160
161/**
162 * The band's three rows, each cut to the width it is drawn in: the castle's battlements alone,
163 * its walls with the run (name, stage, tokens), and its base with the legend - in words while
164 * they fit, then the glyphs alone. A row that wraps would push the prompt down every time a
165 * count gains a digit.
166 */
167/**
168 * The band's rows: the castle's three rows with the run's name and stage beside the middle one and the legend beside the
169 * base. `cache` (the keep-warm row) goes at the end of the name row when it fits there, before the tokens are dropped;
170 * else on a row of its own, lined up with the text beside the castle - drawn flush under the castle, it read as part of it.
171 */
172export const band = (s: Summary, columns: number, castle: Castle = CASTLE, cache?: string | null): Segment[][] => {
173  // Two columns between segments, one between a segment's text and its count.
174  const width = (row: Segment[]) => row.reduce((n, seg) => n + seg.text.length + (seg.count === undefined ? 0 : 1 + String(seg.count).length), 2 * (row.length - 1));
175  const fit = (tries: Segment[][]) => tries.find((row) => width(row) <= columns) ?? tries.at(-1) ?? [];
176  const run = (name: boolean, tokens: boolean): Segment[] =>
177    [
178      { text: castle.mid, colour: SAND.mid },
179      { text: "sandcastle", colour: SAND.top, bold: true as const },
180      { text: name ? s.name : "", colour: SAND.name },
181      { text: s.stage, colour: SAND.stage },
182      { text: tokens ? s.tokens : "", colour: SAND.muted },
183    ].filter((seg) => seg.text);
184  const legend = (words: boolean): Segment[] => [
185    { text: castle.base, colour: SAND.base },
186    ...LEGEND.map((g, i) => ({ text: words ? `${g.glyph} ${g.label}` : g.glyph, count: s.counts[i] ?? 0, colour: g.colour })).filter((seg) => seg.count),
187  ];
188  const rows = [[{ text: castle.top, colour: SAND.top }], fit([run(true, true), run(true, false), run(false, false)]), fit([legend(true), legend(false)])];
189  if (!cache) return rows;
190  const note: Segment = { text: cache, colour: SAND.name };
191  const beside = [run(true, true), run(true, false), run(false, false)].map((row) => [...row, note]).find((row) => width(row) <= columns);
192  if (beside) return [rows[0]!, beside, rows[2]!];
193  // The castle's width in blank cells, so the row starts where the text beside the castle does.
194  return [...rows, [{ text: " ".repeat(castle.mid.length), colour: SAND.name }, note]];
195};
196
197/** The same summary as one line of text, for `/sandcastle-status`. A run that is over has no stage. */
198export const line = (run: Run, live: boolean): string => {
199  const s = summarise(run);
200  return [live && s.stage, ...LEGEND.flatMap((g, i) => (s.counts[i] ? [`${g.glyph} ${g.label} ${s.counts[i]}`] : [])), s.tokens].filter(Boolean).join(" · ");
201};
202
203/** One line per ticket, in the status view's order: working first, then what needs a person. */
204export const rows = (run: Run): string[] => {
205  const place = (t: Ticket) => LEGEND.findIndex((g) => g.group === group(t));
206  const rank = (t: Ticket) => (place(t) < 0 ? LEGEND.length : place(t));
207  return tickets(run)
208    .sort(([, a], [, b]) => rank(a) - rank(b) || (a.order ?? 0) - (b.order ?? 0))
209    .map(([id, t]) => `${LEGEND[place(t)]?.glyph ?? "·"} ${ref(id)} ${word(t.state)}${t.note ? ` (${t.note})` : ""}${t.title ? ` - ${t.title}` : ""}`);
210};
211
212/**
213 * Lists the machine-wide live-runs registry (src/live-runs.ts): its directory is
214 * `$XDG_CACHE_HOME`, or `~/.cache` when that is unset or empty, on Linux and macOS alike. Prints
215 * the session root's resolved path (`pwd -P`: `/tmp` is `/private/tmp` on macOS, and one project
216 * must not read as two), then one resolved root per registered run, a line each. POSIX sh, and
217 * `cat`, `cd` and `pwd -P` only: BSD and GNU alike. A root that is gone prints nothing.
218 * `$1` is the session's root.
219 */
220export const REGISTRY_SCRIPT = [
221  'dir="${XDG_CACHE_HOME:-$HOME/.cache}/sandcastle-kit/runs"',
222  '(cd -- "$1" 2>/dev/null && pwd -P) || echo',
223  'for f in "$dir"/*; do',
224  '  [ -f "$f" ] || continue',
225  '  r=$(cat -- "$f" 2>/dev/null)',
226  '  [ -n "$r" ] && (cd -- "$r" 2>/dev/null && pwd -P)',
227  "done",
228  "exit 0",
229].join("\n");
230
231/** The script's output: the session's own root (empty when it could not be resolved) and the registered ones, as resolved strings compared as they are (no case folding). */
232export const parseRegistry = (stdout: string): { own: string; roots: string[] } => {
233  const [own = "", ...rest] = stdout.split("\n");
234  return { own, roots: [...new Set(rest.filter(Boolean))] };
235};
236
237/**
238 * The registered roots this session may follow: every one but its own, which the watch of the
239 * session's root already covers. With no resolved root of its own it follows none - failing closed
240 * (a shell that cannot resolve it, BusyBox `ps` and the like) beats watching one run twice.
241 */
242export const followable = ({ own, roots }: { own: string; roots: string[] }): string[] => (own ? roots.filter((r) => r !== own) : []);
243
244/** Whether `run` is the run of the session with this id. A run with no recorded id (a plain terminal, Codex, OpenCode) has no owner. */
245export const startedBy = (run: Run | undefined, session: string): boolean => !!run?.session && run.session === session;
246
hooks/run-live.ts 60 lines
1// Whether a run is live: the one rule behind the status view, the Herdr tab bar, the closing
2// summary, `sandcastle wait` and the Claude Code mod. A run is live when its record has not
3// finished and its pid is a process whose command line contains RUN_COMMAND: the pid alone
4// comes round again as some other process, and a run that was SIGKILLed would read as live
5// for as long as that process lasts. Pure and importing nothing, so the mod (which cannot
6// import the kit's source) and the kit's own tests can both read it; the process check is
7// passed in (`test/run-live-contract.test.ts` holds the status view to it). A paused run (`sandcastle pause`; the record's `paused`) is live by this
8// rule, and rightly: its process runs and its record has not finished, so no view offers an end
9// prompt for it. Terms are GLOSSARY.md's.
10
11/** What the run's process shows in its command line (bin/sandcastle starts it): how a look tells it from a process that got its pid later. */
12export const RUN_COMMAND = "src/cli.ts";
13
14/**
15 * The process check: the command line of the process with this pid, or undefined when there is
16 * none. A process another user owns exists all the same (EPERM on a signal says so): the probe
17 * reads its command line like any other, as `ps -p <pid> -o command=` does.
18 */
19export type Probe = (pid: number) => string | undefined;
20
21/** The pid is a process of the kit, not one that has since taken the number. */
22export const isKit = (command: string | undefined): boolean => command !== undefined && command.includes(RUN_COMMAND);
23
24/** The pid names a process of the kit that is running now. */
25export const kitRunning = (pid: number | undefined, probe: Probe): boolean => Number.isInteger(pid) && (pid as number) > 0 && isKit(probe(pid as number));
26
27/** The fields of a run record that decide it; the rest of the record is not read. */
28export type LiveRecord = { pid?: unknown; finishedAt?: unknown; exitCode?: unknown };
29
30/**
31 * What a run is:
32 * - `live`: its process is running (the pid it holds the run lock under, or the one its
33 *   unfinished record names);
34 * - `finished`: its record says it ended, with the exit code it wrote (none for a run that was
35 *   not given one);
36 * - `own`: its record is unfinished and names the asking process itself - the run that is
37 *   summing itself up, between its own turns, which is not "another live run" and not a killed
38 *   one either;
39 * - `dead`: no record, or an unfinished one whose process is gone or is not the kit's: killed.
40 */
41export type Liveness = { state: "live"; pid: number } | { state: "finished"; exitCode?: number } | { state: "own" } | { state: "dead" };
42
43const finished = (record: LiveRecord) => (typeof record.finishedAt === "string" && record.finishedAt !== "") || Number.isInteger(record.exitCode);
44
45/**
46 * The lock goes before the process does (its exit handlers run in turn, and the record's end is
47 * written after the lock is released), so the lock's pid decides first: a process that still
48 * holds it is live whatever the record says, and a record that has not finished is live while its
49 * own pid is.
50 */
51export const liveness = ({ record, lockPid, self }: { record?: LiveRecord; lockPid?: number; self?: number }, probe: Probe): Liveness => {
52  if (kitRunning(lockPid, probe)) return { state: "live", pid: lockPid as number };
53  if (!record) return { state: "dead" };
54  if (finished(record)) return { state: "finished", ...(Number.isInteger(record.exitCode) ? { exitCode: record.exitCode as number } : {}) };
55  const pid = record.pid;
56  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return { state: "dead" };
57  if (pid === self) return { state: "own" };
58  return kitRunning(pid, probe) ? { state: "live", pid } : { state: "dead" };
59};
60
hooks/keep-warm.ts 127 lines
1// The cache refresh: while a run this session started is live, the session sits idle and Claude
2// Code's prompt cache lapses after an hour of silence (5 minutes on overage), so the turn that
3// closes the run would re-read the whole conversation at the full input price. A refresh is one
4// tool-less request over the main thread's transcript (`$.model.fork`), which reads it from the
5// cache at about a tenth of that price and resets the timer. Pure, and like idle.ts it imports
6// nothing: register.tsx gathers the facts and this module decides.
7
8/** A refresh is due when the session has been silent this long: under the 1-hour lifetime, with margin. */
9export const INTERVAL_MS = 55 * 60 * 1000;
10
11/** The last refresh: when, how many tokens it read from the cache, and how large the context was. */
12export type Refresh = { at: number; cacheRead: number; contextTokens: number };
13
14/** One of the plan's usage windows (`$.session.usage().rateLimits`); only the fill matters here. */
15export type PlanWindow = { percentUsed: number };
16
17/** What the session remembers across looks; it lives in `$.state`, since a reload restarts module variables. */
18export type Warmth = {
19  /** The run these facts are about (its `startedAt`): another run starts them over, so misses are counted per run. */
20  run?: string;
21  /** The last refresh, until a main-thread turn ends after a miss: that turn clears the miss. */
22  last?: Refresh;
23  /** The refreshes this run that found the cache lapsed. */
24  misses: number;
25  /** When the main thread's last turn ended. */
26  turnEnd?: number;
27};
28
29export type KeepWarmInput = {
30  /** The run record's `settings.keepWarm`; absent reads as on. */
31  enabled?: boolean;
32  /** A run this session started or follows is live (a paused run is live). */
33  live: boolean;
34  /** The later of the main thread's last turn end and the last refresh; absent is "just now". */
35  lastActivity?: number;
36  last?: Refresh;
37  /** The refreshes of this run that found the cache lapsed. */
38  misses?: number;
39  /** The plan's windows; none for an API key or a gateway. */
40  rateLimits?: PlanWindow[];
41  now: number;
42};
43
44export type KeepWarmVerdict = {
45  refresh: boolean;
46  /** `1h`: refreshing; `5m`: the cache is short-lived, so it is left to lapse; `off`: nothing to do. */
47  mode: "1h" | "5m" | "off";
48  /** When the next refresh is due, ms since the epoch; only in `1h` mode. */
49  nextAt?: number;
50  /** The row the band draws; absent when there is nothing to say. */
51  band?: string;
52};
53
54/** A refresh whose cache read was under half the context: the cache had lapsed. */
55export const missed = (last: Refresh): boolean => last.cacheRead < last.contextTokens / 2;
56
57/** The most misses a run puts up with: the second turns the refresh off for the run. */
58const MAX_MISSES = 2;
59
60const tokens = (n: number): string => (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
61
62/**
63 * Whether to refresh now, and the band's text. Overage (any window at 100%) or a refresh that
64 * found the cache lapsed mean a 5-minute cache: keeping it warm takes about 13 refreshes an hour
65 * (about 1.3x the input price), against one cold re-write at about 1.25x, so it costs more for
66 * any wait over an hour and is left alone. With no windows (an API key, a gateway) nothing is
67 * assumed: the first refresh's measured read decides.
68 */
69export const keepWarm = (input: KeepWarmInput): KeepWarmVerdict => {
70  const { now, last } = input;
71  if (input.enabled === false || !input.live || (input.misses ?? 0) >= MAX_MISSES) return { refresh: false, mode: "off" };
72  if ((input.rateLimits ?? []).some((w) => w.percentUsed >= 100) || (last !== undefined && missed(last))) {
73    return { refresh: false, mode: "5m", band: "cache 5m · not warmed (a cold restart costs less)" };
74  }
75  const lastActivity = input.lastActivity ?? now;
76  const nextAt = lastActivity + INTERVAL_MS;
77  if (now >= nextAt) return { refresh: true, mode: "1h", nextAt };
78  // "warm" said nothing (the refresh keeps it so): the countdown is the news, and after a refresh what it read.
79  const countdown = `cache refresh in ${Math.max(1, Math.ceil((nextAt - now) / 60000))}m`;
80  const band = last !== undefined && last.at >= lastActivity ? `${countdown} · last ${tokens(last.cacheRead)}` : countdown;
81  return { refresh: false, mode: "1h", nextAt, band };
82};
83
84/** The most recent thing that kept the cache warm: a main-thread turn, a refresh, or the run's start. */
85export const activity = (kept: Warmth, floor?: number): number | undefined => {
86  const times = [kept.turnEnd, kept.last?.at, floor].filter((t): t is number => typeof t === "number" && Number.isFinite(t));
87  return times.length === 0 ? undefined : Math.max(...times);
88};
89
90/**
91 * What a refresh found. `result` is `$.model.fork`'s: an answered one carries the request's usage;
92 * one that is not (`api-error`, `aborted`) is a miss, since nothing says the cache held.
93 */
94export const settle = (kept: Warmth, result: { isAnswered: boolean; usage?: { cache_read_input_tokens?: number } }, contextTokens: number, at: number): Warmth => {
95  const cacheRead = result.isAnswered ? Math.max(0, result.usage?.cache_read_input_tokens ?? 0) : 0;
96  const last: Refresh = { at, cacheRead, contextTokens: result.isAnswered ? contextTokens : Math.max(contextTokens, 1) };
97  return { ...kept, last, misses: kept.misses + (missed(last) ? 1 : 0) };
98};
99
100/** A main-thread turn ended: the cache was just used, and a miss before it is cleared (one more try at 55 minutes). */
101export const afterTurn = (kept: Warmth, at: number): Warmth => {
102  const { last, ...rest } = kept;
103  return { ...rest, turnEnd: at, ...(last !== undefined && !missed(last) ? { last } : {}) };
104};
105
106/**
107 * What a refresh writes back: its own facts, and a main-thread turn that ended while its request was out (`stored`,
108 * the state as it is now). Written as read before the request, that turn's end would be lost.
109 */
110export const withLaterTurn = (kept: Warmth, stored: Warmth): Warmth =>
111  stored.turnEnd !== undefined && stored.turnEnd > (kept.turnEnd ?? -Infinity) ? afterTurn(kept, stored.turnEnd) : kept;
112
113const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
114
115/** A stored value as `Warmth`; anything else reads as nothing remembered. */
116export const parseWarmth = (value: unknown): Warmth => {
117  if (typeof value !== "object" || value === null) return { misses: 0 };
118  const { run, last, misses, turnEnd } = value as Record<string, unknown>;
119  const l = typeof last === "object" && last !== null ? (last as Record<string, unknown>) : undefined;
120  return {
121    ...(typeof run === "string" ? { run } : {}),
122    misses: finite(misses) && misses > 0 ? Math.floor(misses) : 0,
123    ...(finite(turnEnd) ? { turnEnd } : {}),
124    ...(l && finite(l.at) && finite(l.cacheRead) && finite(l.contextTokens) ? { last: { at: l.at, cacheRead: l.cacheRead, contextTokens: l.contextTokens } } : {}),
125  };
126};
127
hooks/idle.ts 381 lines
1// The idle mark: the one row the mod draws in sand above the prompt (not in the status line) between runs, in a
2// project set up for sandcastle. Pure, and like run-state.ts it imports nothing: register.tsx
3// gathers the facts and this module decides the text. The input is one object on purpose - the
4// ready count, the project's hidden flag and a dismissal join it without a new signature.
5
6/** A project's cached ready-ticket read, one `$.store` entry shared by every session on the machine. */
7export type Entry = {
8  /** When `ids` were read, in ms since the epoch: the age of the count, kept through failed reads. */
9  at: number;
10  /** The ready ticket ids of the last good read. */
11  ids: string[];
12  /** Whether the latest read worked; a failure keeps `ids` and `at` and says so here. */
13  ok: boolean;
14  /**
15   * When the latest read ended, good or not: what `due` measures. Apart from `at` so that a
16   * tracker that cannot be reached is tried every ten minutes, not at every look.
17   */
18  tried: number;
19};
20
21/** What `sandcastle --version --json` prints (src/upgrading.ts's `versionFacts`), the part the mark reads. */
22export type VersionFacts = {
23  kit: { version: string; release: string; past: number };
24  /** The newest release tagged on the kit's remote and when the kit read it (ISO 8601); null when it is not known: the check is off, failed or found none. */
25  newestRelease: { release: string; checkedAt: string } | null;
26  /** Null outside a set-up project. */
27  project: { recorded: boolean; release: string | null; pendingNotes: string[] } | null;
28};
29
30/**
31 * A project's cached version read, one `$.store` entry beside the ready entry and shared by every
32 * session on the machine. A failed read keeps the last good `facts` and `at`, as the ready entry does.
33 */
34export type VersionEntry = {
35  /** When `facts` were read, in ms since the epoch. */
36  at: number;
37  /** The facts of the last good read; null before one. */
38  facts: VersionFacts | null;
39  /** Whether the latest read worked. */
40  ok: boolean;
41  /** When the latest read ended, good or not: what `due` measures. */
42  tried: number;
43};
44
45/**
46 * A person's choices for one project, one `$.store` entry beside the ready entry: machine-local,
47 * kept across a restart, never in the repository.
48 */
49export type Choice = {
50  /** `/sandcastle-mark hide`: no mark in this project until `show`. */
51  hidden: boolean;
52  /** `/sandcastle-mark dismiss`: the ready ids at that moment; absent when nothing is dismissed. */
53  dismissed?: string[];
54  /**
55   * `/sandcastle-mark dismiss`: the newest release tagged on the remote at that moment, when it was newer than the kit's
56   * own; absent when no release is dismissed. Kept apart from `dismissed`, so ending one leaves the other as it was.
57   */
58  dismissedRelease?: string;
59};
60
61/** What the line is decided from. */
62export type MarkInput = {
63  /** The project's `.sandcastle/config.ts` is a plain file: `sandcastle init` ran there. */
64  setUp: boolean;
65  /** The machine switch: false when the personal settings say `"idleMark": false`. */
66  idleMark: boolean;
67  /** The project's hidden flag (`/sandcastle-mark hide`). */
68  hidden?: boolean;
69  /** The ids of a dismissal (`/sandcastle-mark dismiss`); the count stays quiet while the ready set is within them. */
70  dismissed?: string[];
71  /** The release of a dismissal (`/sandcastle-mark dismiss`); `N out` stays quiet until a release newer than it is tagged. */
72  dismissedRelease?: string;
73  /** The cached read; none yet, or with no `now`, gives the bare mark. */
74  entry?: Entry;
75  /** The cached version read; none yet, or too old to show, and the mark carries no version. */
76  versionRead?: VersionEntry;
77  /** The time, ms since the epoch. */
78  now?: number;
79};
80
81/** A cached read is read again when it is this old. */
82export const READ_MS = 10 * 60 * 1000;
83/** A count older than this is not shown: the mark stands without one. */
84export const COUNT_MS = 60 * 60 * 1000;
85
86/** The ready ids of a read that is current - under `COUNT_MS` old - else none: what a count may be made of. */
87const shown = (entry: Entry | undefined, now: number | undefined): entry is Entry => entry !== undefined && now !== undefined && now - entry.at >= 0 && now - entry.at < COUNT_MS;
88const current = (entry: Entry | undefined, now: number | undefined): string[] => (shown(entry, now) ? entry.ids : []);
89
90/**
91 * Whether a dismissal has ended: the current ready set holds an id the dismissal does not. An id
92 * leaving the set ends nothing, and a count too old to show says nothing either way.
93 */
94export const dismissalEnded = (dismissed: string[], entry: Entry | undefined, now: number | undefined): boolean =>
95  current(entry, now).some((id) => !dismissed.includes(id));
96
97/**
98 * Whether a release dismissal has ended: the newest release the facts name is newer than the dismissed one.
99 * Facts that name none say nothing either way, as a count too old to show does for a ready dismissal.
100 */
101export const releaseDismissalEnded = (dismissedRelease: string, facts: VersionFacts | null): boolean => {
102  const out = facts?.newestRelease?.release;
103  return out !== undefined && newer(out, dismissedRelease);
104};
105
106/** The dismissed release while its dismissal holds, else undefined: what the report and the `dismiss` reply name. */
107export const heldRelease = (input: Pick<MarkInput, "dismissedRelease" | "versionRead" | "now">): string | undefined =>
108  input.dismissedRelease !== undefined && !releaseDismissalEnded(input.dismissedRelease, currentFacts(input.versionRead, input.now)) ? input.dismissedRelease : undefined;
109
110/** A tone of the mark's line: `name` the row's sand, `hint` the castle's bright sand in bold. */
111export type Tone = "name" | "hint";
112
113/** One coloured piece of the line. The pieces are drawn side by side with a space between them. */
114export type MarkPart = { text: string; tone: Tone };
115
116/** The idle mark's line: its coloured parts and the same line as plain text (the parts joined by a space). */
117export type Mark = { text: string; parts: MarkPart[] };
118
119const numbers = (release: string): number[] | undefined => (/^\d+\.\d+\.\d+$/.test(release) ? release.split(".").map(Number) : undefined);
120
121/** Whether release `a` is newer than `b`, part by part as numbers (`0.10.0` is newer than `0.9.0`); false for anything that is not `X.Y.Z`. */
122const newer = (a: string, b: string): boolean => {
123  const [x, y] = [numbers(a), numbers(b)];
124  if (!x || !y) return false;
125  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! > y[i]!;
126  return false;
127};
128
129/** The facts of a read that is current - under `COUNT_MS` old - else none: what a version may be shown from. */
130const currentFacts = (read: VersionEntry | undefined, now: number | undefined): VersionFacts | null =>
131  read !== undefined && now !== undefined && now - read.at >= 0 && now - read.at < COUNT_MS ? read.facts : null;
132
133/** The kit's release, with `+N` when the clone is N commits past its release's own tag: `0.16.0+3`. */
134const releaseLabel = (kit: VersionFacts["kit"]): string => `${kit.release}${kit.past > 0 ? `+${kit.past}` : ""}`;
135
136/**
137 * The line, or undefined to clear it. A count shows only while the last good read is under an
138 * hour old, so a tracker that cannot be reached keeps the number for a while and then goes quiet;
139 * the line never says why (`sandcastle queue` and the status view do). A dismissal takes the
140 * count off, never the mark; hiding takes both.
141 *
142 * With version facts the name carries the kit's release, and one hint may follow the count, the
143 * first of these that holds (bold, the call to action becomes `/sandcastle update`): `N out` when
144 * the newest release tagged on the kit's remote is newer than the kit's own release, else
145 * `update needed` when the project has Upgrading notes it has not had or no usable update record.
146 * A dismissed release (`dismissedRelease`) quiets `N out` until a newer one is tagged, and the
147 * line then falls to `update needed` as if no release were out: that hint has no dismissal.
148 * A project that is current says nothing: its recorded release is for the report.
149 */
150export const markText = (input: MarkInput): Mark | undefined => {
151  if (!input.setUp || !input.idleMark || input.hidden) return undefined;
152  const { entry, now, dismissed } = input;
153  const ids = current(entry, now);
154  const quiet = dismissed !== undefined && !dismissalEnded(dismissed, entry, now);
155  const count = ids.length > 0 && !quiet ? ids.length : 0;
156  const facts = currentFacts(input.versionRead, now);
157  const lead = `${facts ? `sandcastle ${releaseLabel(facts.kit)}` : "sandcastle"}${count ? ` · ${count} ready` : ""}`;
158  const project = facts?.project;
159  const parts: MarkPart[] = [];
160  const out = facts?.newestRelease?.release;
161  const outQuiet = out !== undefined && input.dismissedRelease !== undefined && !newer(out, input.dismissedRelease);
162  if (facts && out && !outQuiet && newer(out, facts.kit.release)) {
163    parts.push({ text: `${lead} ·`, tone: "name" }, { text: `${out} out`, tone: "hint" }, { text: "- /sandcastle update", tone: "name" });
164  } else if (project && (!project.recorded || project.pendingNotes.length > 0)) {
165    parts.push({ text: `${lead} ·`, tone: "name" }, { text: "update needed", tone: "hint" }, { text: "- /sandcastle update", tone: "name" });
166  } else parts.push({ text: count ? `${lead} - /sandcastle run` : lead, tone: "name" });
167  return { text: parts.map((p) => p.text).join(" "), parts };
168};
169
170/** What `/sandcastle-mark` takes. */
171export const MARK_USAGE = "Usage: /sandcastle-mark [dismiss|hide|show]";
172
173/** The command's argument, or undefined for one it does not know. Nothing is "no argument": the report. */
174export const markAction = (args: string): "dismiss" | "hide" | "show" | "report" | undefined => {
175  const word = args.trim().toLowerCase();
176  return word === "" ? "report" : word === "dismiss" || word === "hide" || word === "show" ? word : undefined;
177};
178
179/** The release a dismissal would quiet: the newest one on the remote, when the facts are current and it is newer than the kit's own. */
180const releaseOut = (read: VersionEntry | undefined, now: number | undefined): string | undefined => {
181  const facts = currentFacts(read, now);
182  const out = facts?.newestRelease?.release;
183  return facts && out !== undefined && newer(out, facts.kit.release) ? out : undefined;
184};
185
186/**
187 * The choice after `dismiss`, `hide` or `show`: the dismissal holds the ids of a count that is current, none otherwise,
188 * and the release `N out` names when there is one (else an earlier dismissed release stays). `show` clears both.
189 */
190export const choiceAfter = (
191  action: "dismiss" | "hide" | "show",
192  choice: Choice,
193  entry: Entry | undefined,
194  now: number | undefined,
195  versionRead?: VersionEntry,
196): Choice => {
197  if (action === "show") return { hidden: false };
198  if (action === "hide") return { ...choice, hidden: true };
199  const dismissedRelease = releaseOut(versionRead, now) ?? choice.dismissedRelease;
200  return { ...choice, dismissed: [...current(entry, now)], ...(dismissedRelease !== undefined ? { dismissedRelease } : {}) };
201};
202
203/** A stored value as a choice, or undefined when it is not one (the store is shared, so it is checked). */
204export const parseChoice = (value: unknown): Choice | undefined => {
205  if (typeof value !== "object" || value === null) return undefined;
206  const { hidden, dismissed, dismissedRelease } = value as Record<string, unknown>;
207  if (typeof hidden !== "boolean") return undefined;
208  if (dismissed !== undefined && (!Array.isArray(dismissed) || !dismissed.every((id) => typeof id === "string"))) return undefined;
209  // A release the comparison cannot read would quiet `N out` for good, so it is no choice at all.
210  if (dismissedRelease !== undefined && (typeof dismissedRelease !== "string" || !numbers(dismissedRelease))) return undefined;
211  return {
212    hidden,
213    ...(dismissed !== undefined ? { dismissed: dismissed as string[] } : {}),
214    ...(dismissedRelease !== undefined ? { dismissedRelease: dismissedRelease as string } : {}),
215  };
216};
217
218const ago = (ms: number): string => {
219  const min = Math.floor(Math.max(ms, 0) / 60000);
220  return min < 1 ? "under a minute ago" : min < 60 ? `${min} min ago` : `${Math.floor(min / 60)} h ${min % 60} min ago`;
221};
222
223/** The reply to a bare `/sandcastle-mark`: whether the mark is shown, and the cached count with its age. */
224export const markReport = (input: MarkInput): string => {
225  const { entry, now } = input;
226  const dismissed = input.dismissed !== undefined && !dismissalEnded(input.dismissed, entry, now);
227  const release = heldRelease(input);
228  const state = !input.setUp
229    ? "not shown: this project is not set up (no .sandcastle/config.ts)"
230    : !input.idleMark
231      ? `hidden on this machine ("idleMark": false in the personal settings)${input.hidden ? " and in this project" : ""}`
232      : input.hidden
233        ? "hidden in this project (/sandcastle-mark show brings it back)"
234        : dismissed || release
235          ? `shown${dismissed ? " without a count" : ""}: ${[
236              dismissed ? "dismissed until a new ticket becomes ready" : "",
237              release ? `release ${release} dismissed until a newer one is tagged` : "",
238            ]
239              .filter(Boolean)
240              .join(", and ")} (/sandcastle-mark show ends ${dismissed && release ? "both" : "it"})`
241          : "shown";
242  const count = !entry
243    ? "No count read yet."
244    : `${entry.ids.length} ready, read ${now === undefined ? "earlier" : ago(now - entry.at)}${entry.ok ? "" : " (the latest read failed)"}${shown(entry, now) ? "" : "; too old to show"}.`;
245  return `Idle mark: ${state}.\nCached count: ${count}\n${versionReport(input.versionRead, now)}`;
246};
247
248/** The report's version lines: the last facts held, whatever their age, or that none are. */
249const versionReport = (read: VersionEntry | undefined, now: number | undefined): string => {
250  const facts = read?.facts;
251  if (!read || !facts) return "Kit version: not read yet.";
252  const { kit, project, newestRelease } = facts;
253  const recorded = !project ? "this is not a set-up project" : !project.recorded ? "none (no usable update record on this machine)" : (project.release ?? "none named by the record");
254  const notes = !project || project.pendingNotes.length === 0 ? [" none held."] : ["", ...project.pendingNotes.map((n) => `  - ${n}`)];
255  return [
256    `Kit version: ${kit.version}, read ${now === undefined ? "earlier" : ago(now - read.at)}${read.ok ? "" : " (the latest read failed)"}${currentFacts(read, now) ? "" : "; too old to show"}.`,
257    `Project's recorded release: ${recorded}.`,
258    `Pending Upgrading notes:${notes.join("\n")}`,
259    `Newest release: ${newestRelease ? `${newestRelease.release}, checked ${now === undefined ? "earlier" : ago(now - Date.parse(newestRelease.checkedAt))}` : "not known (the check is off, the remote did not answer or it has no release tag)"}.`,
260  ].join("\n");
261};
262
263/**
264 * The ready ticket ids in `sandcastle queue --json`'s stdout - the queued tickets with no open
265 * blocker - or undefined for a read that is no list of tickets. Never an empty list for output
266 * that is not one: a failed read must not count as "nothing ready".
267 */
268export const readyIds = (stdout: string): string[] | undefined => {
269  let rows: unknown;
270  try {
271    rows = JSON.parse(stdout);
272  } catch {
273    return undefined;
274  }
275  if (!Array.isArray(rows)) return undefined;
276  const ids: string[] = [];
277  for (const row of rows) {
278    if (typeof row !== "object" || row === null || Array.isArray(row)) return undefined;
279    const { id, blockedOn } = row as Record<string, unknown>;
280    if ((typeof id !== "string" && typeof id !== "number") || String(id) === "" || !Array.isArray(blockedOn)) return undefined;
281    if (blockedOn.length === 0 && !ids.includes(String(id))) ids.push(String(id));
282  }
283  return ids;
284};
285
286/**
287 * What makes a read due ahead of its age: a run ended - the project's own, or one this session
288 * followed elsewhere, perhaps a second clone of it - or the sandcastle skill was used (it may just
289 * have labelled tickets). A session's start needs none: its first look applies
290 * the age rule at once, so an entry that is missing or old is read then.
291 */
292export type Trigger = "run-ended" | "skill";
293
294/** Whether to read the tracker now: no entry, one `READ_MS` old or more, or a trigger fired. */
295export const due = (entry: Pick<Entry, "tried"> | undefined, now: number, trigger?: Trigger): boolean => {
296  if (trigger !== undefined || entry === undefined) return true;
297  const age = now - entry.tried;
298  // An entry from the future is a clock that moved: read it again rather than trust it.
299  return age < 0 || age >= READ_MS;
300};
301
302/** The entry after a read: `ids` is the read's result, or undefined for a failed one. */
303export const afterRead = (prior: Entry | undefined, ids: string[] | undefined, now: number): Entry =>
304  ids !== undefined ? { at: now, ids, ok: true, tried: now } : { at: prior?.at ?? now, ids: prior?.ids ?? [], ok: false, tried: now };
305
306/** A stored value as an entry, or undefined when it is not one: a store is shared, so it is checked. */
307export const parseEntry = (value: unknown): Entry | undefined => {
308  if (typeof value !== "object" || value === null) return undefined;
309  const { at, ids, ok, tried } = value as Record<string, unknown>;
310  if (typeof at !== "number" || !Number.isFinite(at) || typeof tried !== "number" || !Number.isFinite(tried) || typeof ok !== "boolean") return undefined;
311  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) return undefined;
312  return { at, ids: ids as string[], ok, tried };
313};
314
315/** The entry after a version read: `facts` is the read's result, or undefined for a failed one. */
316export const afterVersionRead = (prior: VersionEntry | undefined, facts: VersionFacts | undefined, now: number): VersionEntry =>
317  facts !== undefined ? { at: now, facts, ok: true, tried: now } : { at: prior?.at ?? now, facts: prior?.facts ?? null, ok: false, tried: now };
318
319const nonEmpty = (value: unknown): value is string => typeof value === "string" && value !== "";
320
321/**
322 * The facts in `sandcastle --version --json`'s stdout, or undefined for output that is not them -
323 * a failed read keeps the last good facts, and one that parses to something else must not blank them.
324 */
325export const parseVersionFacts = (stdout: string): VersionFacts | undefined => {
326  let value: unknown;
327  try {
328    value = JSON.parse(stdout);
329  } catch {
330    return undefined;
331  }
332  if (typeof value !== "object" || value === null) return undefined;
333  const { kit, newestRelease, project } = value as Record<string, unknown>;
334  if (typeof kit !== "object" || kit === null) return undefined;
335  const { version, release, past } = kit as Record<string, unknown>;
336  if (!nonEmpty(version) || !nonEmpty(release) || typeof past !== "number" || !Number.isFinite(past)) return undefined;
337  let newest: VersionFacts["newestRelease"] = null;
338  if (newestRelease !== null && newestRelease !== undefined) {
339    if (typeof newestRelease !== "object") return undefined;
340    const { release: r, checkedAt } = newestRelease as Record<string, unknown>;
341    if (!nonEmpty(r) || !nonEmpty(checkedAt)) return undefined;
342    newest = { release: r, checkedAt };
343  }
344  if (project === null) return { kit: { version, release, past }, newestRelease: newest, project: null };
345  if (typeof project !== "object") return undefined;
346  const { recorded, release: recordedRelease, pendingNotes } = project as Record<string, unknown>;
347  if (typeof recorded !== "boolean" || (recordedRelease !== null && typeof recordedRelease !== "string")) return undefined;
348  if (!Array.isArray(pendingNotes) || !pendingNotes.every((n) => typeof n === "string")) return undefined;
349  return { kit: { version, release, past }, newestRelease: newest, project: { recorded, release: recordedRelease, pendingNotes: pendingNotes as string[] } };
350};
351
352/** A stored value as a version entry, or undefined when it is not one: a store is shared, so it is checked. */
353export const parseVersionEntry = (value: unknown): VersionEntry | undefined => {
354  if (typeof value !== "object" || value === null) return undefined;
355  const { at, facts, ok, tried } = value as Record<string, unknown>;
356  if (typeof at !== "number" || !Number.isFinite(at) || typeof tried !== "number" || !Number.isFinite(tried) || typeof ok !== "boolean") return undefined;
357  if (facts === null) return { at, facts: null, ok, tried };
358  const parsed = parseVersionFacts(JSON.stringify(facts));
359  return parsed ? { at, facts: parsed, ok, tried } : undefined;
360};
361
362/**
363 * Prints the personal machine settings, honouring `XDG_CONFIG_HOME` as the kit's `USER_CONFIG`
364 * does (src/sandbox.ts). `cat` only: BSD and GNU alike. A missing file prints nothing.
365 */
366export const SETTINGS_SCRIPT = ['cat -- "${XDG_CONFIG_HOME:-$HOME/.config}/sandcastle-kit/config.json" 2>/dev/null', "exit 0"].join("\n");
367
368/**
369 * The machine switch from the settings file's text. Off only for `"idleMark": false`: a file that
370 * is not JSON, or any other value, leaves the mark on - `sandcastle doctor` is where those are
371 * reported, and a typo never hides the mark silently the other way round.
372 */
373export const machineSwitch = (stdout: string): boolean => {
374  try {
375    const settings: unknown = JSON.parse(stdout);
376    return !(typeof settings === "object" && settings !== null && !Array.isArray(settings) && (settings as Record<string, unknown>).idleMark === false);
377  } catch {
378    return true;
379  }
380};
381
hooks/run-record.ts 401 lines
1// What a run record (.sandcastle/logs/run.json) holds and what the status view says about it:
2// the record's types, the closed set of ticket states, the derived states, and the tables from
3// ticket state to group and to word. Pure: it imports nothing, so the mod (which cannot import
4// the kit's source) and the kit's own tests can both read it. Terms are GLOSSARY.md's.
5
6/**
7 * Where one ticket of a run stands, as the run record holds it - every state src/run.ts
8 * writes. A phase (implement, review, gates ...) is one kind of ticket state; `requeued` is
9 * not one (it is a fact about a ticket's second attempt, `TicketRecord.requeued`). `paused` is a
10 * ticket parked at a juncture of a paused run: its sandbox is closed, its branch kept, and it
11 * resumes with the phase its note names.
12 */
13export const TICKET_STATES = [
14  "queued",
15  "blocked",
16  "setup",
17  "implement",
18  "resolve",
19  "review",
20  "cross-review",
21  "gates",
22  "repair",
23  "ready",
24  "landing",
25  "paused",
26  "merged",
27  "held",
28  "conflict",
29  "red",
30  "nochange",
31  "uncommitted",
32  "crashed",
33  "not landed",
34  "withdrawn",
35  "stopped",
36  "skipped",
37] as const;
38
39export type TicketState = (typeof TICKET_STATES)[number];
40
41/** Tells a ticket state from any other string: a record is a file in a repository, which may be a stranger's. */
42export const isTicketState = (s: unknown): s is TicketState => typeof s === "string" && (TICKET_STATES as readonly string[]).includes(s);
43
44/**
45 * A run record's tickets as read from a file, each one's state passed through the guard. A state
46 * outside the set (a record from an older kit, or edited by hand) is dropped, so the ticket
47 * falls to the "other" group and into no report section, never into one that asks for a person.
48 */
49export const readTickets = (record: unknown): Record<string, TicketRecord> => {
50  const tickets = (record as { tickets?: unknown } | null | undefined)?.tickets;
51  if (!tickets || typeof tickets !== "object" || Array.isArray(tickets)) return {};
52  return Object.fromEntries(
53    Object.entries(tickets as Record<string, unknown>).map(([id, t]) => {
54      const { state, ...rest } = (t && typeof t === "object" ? t : {}) as Record<string, unknown>;
55      return [id, (isTicketState(state) ? { ...rest, state } : rest) as TicketRecord];
56    }),
57  );
58};
59
60/**
61 * What a run says became of one ticket, as `.sandcastle/logs/outcomes.json` holds it beside the
62 * line: every reader (the status view, the report, the autonomy loop) decides on the kind, never
63 * on the line's words, so a new ending cannot read as "ready" for want of a prefix. `red` is red
64 * once merged with other tickets at landing; `gate red` is red in the ticket's own pipeline.
65 * `taken back` is a ticket a person marked for a human during the run; `green` is a branch gated
66 * green that this run has not (or, in a dry run, would have) landed.
67 */
68export const OUTCOME_KINDS = [
69  "green",
70  "merged",
71  "conflict",
72  "red",
73  "gate red",
74  "held",
75  "taken back",
76  "uncommitted",
77  "crashed",
78  "not landed",
79  "withdrawn",
80  "stopped",
81  "no change",
82] as const;
83
84export type OutcomeKind = (typeof OUTCOME_KINDS)[number];
85
86/** Tells an outcome kind from any other value: outcomes.json is a file in a repository, and an older run's entries carry none. */
87export const isOutcomeKind = (s: unknown): s is OutcomeKind => typeof s === "string" && (OUTCOME_KINDS as readonly string[]).includes(s);
88
89/** One ticket's outcome as a run writes it: the kind, the tickets it collided with, and the line a person reads. */
90export type Outcome = { kind: OutcomeKind; with?: string[]; text: string };
91
92/** One entry of outcomes.json as read: the run that wrote it, and no kind when an older kit did. */
93export type OutcomeEntry = Partial<Outcome> & { run?: string; at?: string };
94
95/**
96 * The states the status view works out for itself and no run record holds: a run that died
97 * (`stalled`, `orphaned`), a branch of an earlier run (`left over`), a branch of this run that
98 * waits for landing to decide it (`finished`), and `requeued`, the word it gives an older run's
99 * branch whose ticket was labelled again, and `later`, the word for a labelled ticket outside the live run.
100 */
101export const DERIVED_STATES = ["stalled", "orphaned", "left over", "finished", "requeued", "later"] as const;
102
103export type DerivedState = (typeof DERIVED_STATES)[number];
104
105/** What the status view sorts ticket states into, shared by every view so none disagrees about a ticket. */
106export type Group = "working" | "needs you" | "ready" | "queued" | "blocked" | "merged" | "other";
107
108/** The group each ticket state falls into. Keyed by the closed set: a missing or extra state fails the type check. */
109export const GROUPS: Record<TicketState, Group> = {
110  setup: "working",
111  implement: "working",
112  resolve: "working",
113  review: "working",
114  "cross-review": "working",
115  gates: "working",
116  repair: "working",
117  landing: "working",
118  red: "needs you",
119  conflict: "needs you",
120  held: "needs you",
121  uncommitted: "needs you",
122  crashed: "needs you",
123  "not landed": "needs you",
124  stopped: "needs you",
125  ready: "ready",
126  queued: "queued",
127  paused: "queued",
128  blocked: "blocked",
129  merged: "merged",
130  nochange: "other",
131  withdrawn: "other",
132  skipped: "other",
133};
134
135/** The status view's word for a ticket state, where it differs from the state's own name. */
136export const WORDS: Partial<Record<TicketState, string>> = { implement: "impl", "cross-review": "codex", red: "gate red", nochange: "no change" };
137
138/** One ticket of a run, as src/run.ts writes it. */
139export type TicketRecord = {
140  state?: TicketState;
141  /** Seconds since the epoch at which the state began. */
142  since?: number;
143  /** Seconds since the epoch at the ticket's first `setup`, kept through a requeue or a resume: TIME's start. */
144  started?: number;
145  /** Seconds since the epoch at the current attempt's `setup` (a requeued second attempt, a resume): the ETA's start. */
146  attemptStarted?: number;
147  order?: number;
148  note?: string | null;
149  title?: string;
150  commits?: number;
151  /** In and out as `tokenBrief` writes them (`3.1M in / 42k out`): the finished passes plus the one running, rewritten on the usage row's tick. */
152  tokens?: string;
153  /** Input tokens served from the cache, of the ticket's passes so far (the same passes as `tokens`): the status view shows its share of the input. Absent in an older record. */
154  cacheRead?: number;
155  /** Set when an agent pass of the ticket threw: `incomplete` - `tokens` is a floor, the pass may have spent more than its stream showed - or `unknown` - it threw before its stream showed any usage, so `tokens` is absent (never zero). Absent when no pass threw. */
156  tokensNote?: "incomplete" | "unknown";
157  /** The largest context one turn of the ticket's passes held (input + cache write + cache read tokens of one assistant message), by the pass that held it (`implement`, `review`, `repair`): the closing summary flags a pass over `PEAK_CONTEXT_WARN`. Absent in an older record and for a Codex pass. */
158  peakContext?: Record<string, number>;
159  minutes?: number;
160  /** Test ids a red gate named. */
161  failing?: string[];
162  /** Test ids that went red on one run of a gate and green on a later one (the ticket gate's re-runs), whatever became of the ticket. */
163  flaked?: string[];
164  /** The tests a repair pass judged flaky (its `<verdict>outside-branch</verdict>` line) when it committed nothing: ids of the gate run the repair was given, kept when the line names them, never the agent's own wording. The closing summary's likely-flaky lines read them. */
165  flaky?: string[];
166  /** Files a merge conflicted on, or protected paths a held branch changes. */
167  files?: string[];
168  /** The ticket's second attempt after a conflict (at landing, or found before its review or gates) or a red at landing ("requeued after conflict before review with #3"); null once that attempt is not going to run. */
169  requeued?: string | null;
170  /** Merged, but the tracker refused the close: the error, short. */
171  closeFailed?: string;
172  /** What the reviewer said no gate exercises; a merged ticket with one needs a person. */
173  ungated?: string;
174  /** A sentence a reviewer left in prose naming a gap it filed neither as a `<followup>` nor as an `<unmet>` line; a merged ticket with one needs a person. */
175  gap?: string;
176  /** Changelog lines the implementer and reviewer asked for (`changelog: true`), each starting Added:, Changed:, Fixed: or Upgrading:. */
177  changelog?: string[];
178  /** How many `<changelog>` tags were no changelog line (too long, a list, a commit sha) and were left out of `changelog`. */
179  changelogDropped?: number;
180  /** An agent answered `<changelog>none</changelog>` and no pass gave a line: the ticket needs no entry, so `report --changelog` does not list it as lacking a suggested line. */
181  changelogNone?: boolean;
182  /** Why each of those was dropped, in order ("too long (527 characters)", "spans list items", "holds a commit sha"); an older record has none. */
183  changelogDroppedWhy?: string[];
184  /** The acceptance criterion an agent knowingly left undone: merged, the ticket still open; a merged ticket with one needs a person. */
185  unmet?: string;
186  /** Paths the branch changed beyond its ticket's `Touches:` line. */
187  overrun?: string[];
188};
189
190/**
191 * A Claude Code session id as an environment variable or a record holds it, or undefined when
192 * the value is not one. The record is a file in a repository, so only a short id of letters,
193 * digits, `-` and `_` passes.
194 */
195export const sessionId = (value: unknown): string | undefined => (typeof value === "string" && /^[\w-]{1,100}$/.test(value) ? value : undefined);
196
197/** The estimate a turn printed at its start (`estimate` in `src/run.ts`): time and tokens as a median and a high figure, the slots it divided by and the tickets it priced. */
198export type RunEstimate = {
199  /** The run's time in milliseconds, base gates and verify included. */
200  ms: { mid: number; high: number };
201  tokensIn: { mid: number; high: number };
202  tokensOut: { mid: number; high: number };
203  slots: number;
204  tickets: number;
205};
206
207/**
208 * The run's settings as one turn's record holds them (GLOSSARY.md: run setting): the autonomy
209 * level, the turn this record is, the level's cap, the repair attempts, the concurrency (asked
210 * and effective), whether cross-review runs, and the usage guard. Each field is optional and a
211 * reader shows only what is there - an older kit's record has no group at all, level 1 has no cap
212 * (it asks after every turn), nor has a follow-on turn past the level's cap, and a record without the guard's fields shows nothing about it.
213 */
214export type RunSettings = {
215  /** The level, resolved once per run. */
216  autonomy?: 0 | 1 | 2 | 3 | "drain";
217  /** This record's turn, 1-based. */
218  turn?: number;
219  /** The most turns the level allows. */
220  cap?: number;
221  /** The repair attempts a ticket gets after a red gate; 0 is repair off. */
222  repair?: number;
223  /** The tickets the run takes at once, after the machine-wide sandbox cap. */
224  concurrency?: number;
225  /** The tickets at once the run asked for; the view shows it only when it differs from `concurrency`. */
226  asked?: number;
227  /** Whether cross-review runs, resolved once per run. */
228  crossReview?: boolean;
229  /** Cross-review's model: written only when it is on. */
230  crossReviewModel?: string;
231  /** Cross-review's effort: written only when it is on. */
232  crossReviewEffort?: string;
233  /** Whether the usage guard (`USAGE_CHECK=1`) was asked for. */
234  usageGuard?: boolean;
235  /** The guard's stop threshold in percent; only while it is on. */
236  usageStop?: number;
237  /**
238   * The guard's reading, a fact beside the setting and never a change to it: `unavailable` when it
239   * cannot get one (a 403 turns it off for the run, a rate limit or a missing OAuth token leaves it
240   * without one for now). The only settings field that may change during a turn.
241   */
242  usageReading?: "unavailable";
243  /** The plan usage in percent at which the run pauses itself (`USAGE_PAUSE`); only when it is on. */
244  usagePause?: number;
245  /** The machine-wide CPU pressure in percent at which the run holds each gate pass (`LOAD_PAUSE`); only when it is on. */
246  loadPause?: number;
247  /** The session that started the run keeps its prompt cache warm while the run is live; absent in records from older kits, read as true. */
248  keepWarm?: boolean;
249  /** True when the sandboxes spend `ANTHROPIC_API_KEY`, billing API credits; absent otherwise. */
250  apiKey?: boolean;
251  /** The dotted keys (`autonomy`, `implement.model`) whose value came from `.sandcastle/config.local.json`, not the environment or the committed config; the view marks the ones it draws. Absent when there are none. */
252  local?: string[];
253};
254
255/** One of a plan's usage windows: how much of it is spent (0 to 100) and when it resets (seconds since the epoch). */
256export type PlanWindow = { percent: number; resetsAt: number };
257
258/**
259 * One provider's plan usage, as a live run shows it (`usage` in the run record, read by the status view,
260 * the Herdr token and the closing summary), keyed by the provider that reports it. `windows` and `at` are
261 * absent until the first reading: the run is watching for one and none has come.
262 */
263export type PlanUsage = {
264  provider: "claude" | "codex";
265  /** The 5-hour and the weekly window: from a Claude agent's rate-limit event, or Codex's `rate_limits` (matched by their length, not their position). */
266  windows?: { fiveHour: PlanWindow; week: PlanWindow };
267  /** Seconds since the epoch at which the kit read the event: the reading's age is measured from it. */
268  at?: number;
269};
270
271/**
272 * Why a run is paused when no person asked for it: a plan window reached `USAGE_PAUSE` (or an agent hit the
273 * limit anyway), and the run resumes by itself at `resumesAt` - seconds since the epoch, a minute after the
274 * window's reset. `percent` is the window's usage when the run paused; `window` and `provider` say whose.
275 */
276export type UsagePaused = { cause: "usage"; provider: PlanUsage["provider"]; window: "fiveHour" | "week"; percent: number; resumesAt: number };
277
278/** The whole run record: the run's own fields and its tickets, by ticket id. Every field is optional - the file is read while the run is still filling it. */
279export type RunRecord = {
280  /** The project's name. */
281  orchestrator?: string;
282  pid?: number;
283  /** The Claude Code session that started the run (`CLAUDE_CODE_SESSION_ID`, nothing else of its environment); absent from a plain terminal, Codex or OpenCode. */
284  session?: string;
285  startedAt?: string;
286  /** Written on a clean exit; a pid that is gone without it is a run that was killed. */
287  finishedAt?: string;
288  exitCode?: number;
289  models?: string;
290  issues?: string[];
291  dryRun?: boolean;
292  /** `kit` is `kitVersion()`'s text (`0.11.0 +3 (1c4f46f)`), read once when the process started; an older record has none. */
293  versions?: { kit?: string; claude?: string; codex?: string };
294  /** Tickets held for another that is open: `on` names what each waits for. */
295  waiting?: { issue: string; on: string[] }[];
296  /** What the run line shows while the run is live. */
297  stage?: string;
298  concurrency?: number;
299  /**
300   * How loaded the run was, kept in the history line so the estimate prices a run from earlier runs of a similar load:
301   * the sandboxes it ran at once (its effective concurrency, after the machine-wide cap and its share) and its ticket
302   * count. An older kit's record has none, and the estimate counts that run as unknown.
303   */
304  load?: { concurrency: number; tickets: number };
305  /** Gate passes held for the machine's CPU pressure (`LOAD_PAUSE`): the run's running total across all its turns, and that it gave up holding; absent where the run is off or has held nothing yet. */
306  loadPause?: { heldMs: number; gaveUp?: true };
307  /**
308   * The estimate printed at the turn's start, kept so the history line can be set beside what the run took. Absent when
309   * none was printed (no history to price from). The figures are the line's, unrounded: milliseconds and tokens.
310   */
311  estimate?: RunEstimate;
312  /**
313   * Milliseconds the run spent with another run live in the pool while its share was below the slots it asked for
314   * (`share` under `demand`), summed as the run goes: the closing summary names it as a cause of a run that took far
315   * longer than its estimate. Absent until there is some.
316   */
317  sharedMs?: number;
318  /**
319   * Milliseconds in which at least one of the run's workers was waiting for a sandbox slot (the union, not the sum over
320   * workers), written as the run goes and at its end. Absent until there is some.
321   */
322  sandboxWaitMs?: number;
323  /**
324   * Milliseconds the run spent paused (a person's `sandcastle pause`, or a pause it took for its plan's usage), summed
325   * from each pause's `since` to its resume, its stop or the run's end, and written as each pause ends and at the
326   * run's end: the closing summary names it as a cause of a run that took far longer than its estimate. Absent at zero.
327   */
328  pausedMs?: number;
329  /** The run settings: what the status view's settings row shows. */
330  settings?: RunSettings;
331  /**
332   * Present while a person has paused the run (`sandcastle pause`): no agent pass starts, the
333   * passes in flight finish and green branches still land. `since` is seconds since the epoch;
334   * `finishing` the tickets still doing something (a pass, a gate run, a landing). Absent when the
335   * run is not paused: a paused run is live all the same, its process is running. A pause the run
336   * took for its plan's usage (`USAGE_PAUSE`) says so: `cause: "usage"`, the window and when it resumes.
337   */
338  paused?: { since: number; finishing: string[] } & Partial<UsagePaused>;
339  /**
340   * The plan's usage, one entry per provider the run shows, each its newest reading across the run's agent logs
341   * (`src/usage.ts`): Claude's while the run spends a subscription on a Claude model, Codex's while cross-review
342   * runs on a ChatGPT plan. An older kit wrote the one entry as an object, and readers still take that.
343   */
344  usage?: PlanUsage[] | PlanUsage;
345  /** Live values, not settings: the sandbox slots the run could use now, and its share of the machine pool (src/pool.ts), rewritten as either changes. */
346  demand?: number;
347  share?: number;
348  /** A person's cap on the run's share (`sandcastle cap`); absent when there is none. */
349  cap?: number;
350  /**
351   * Present (true) while the run waits for a sandbox slot that its share of the machine pool (or its cap) holds back, or
352   * the slot kept for landing does, not only a full pool: the status view's next-to-start rows say so. The wait is the
353   * run's, not a ticket's - a worker leases its slot before it takes a ticket - and an older kit wrote it as each waiting
354   * ticket's note. Kept for older views: `waitsFor` says which.
355   */
356  waitsForShare?: boolean;
357  /**
358   * What holds that wait back, present with `waitsForShare`: `share` (the run's share or cap: `waits for the run's
359   * share`) or `landing` (the last slot of the share is kept for a landing: `waits: slot kept to land`).
360   * An older kit's record has only `waitsForShare`, which the view reads as `share`.
361   */
362  waitsFor?: "share" | "landing";
363  typical?: unknown;
364  tokens?: string;
365  /** The same note for the run's `tokens`, set when any ticket's carries one (`incomplete`; `unknown` when no figure at all). */
366  tokensNote?: "incomplete" | "unknown";
367  /** Why the run stopped before the end of its queue. */
368  stopped?: string;
369  /** The stop's cause in a few words (`main moved while sandboxes ran`), beside `stopped`: the summary words its next step by it. */
370  stoppedWhat?: string;
371  /** The prompt-expansion error that crashed tickets alike, so the run started no more: a setup problem, which the summary words its next step by. */
372  setupProblem?: string;
373  /** Why the agents' follow-ups were not written to the tracker, once for the set: each one's `failed` carries the same text. */
374  followUpsWithheld?: string;
375  /** How a person ended the run: "sandcastle stop", "Ctrl-C", or the signal's name. Absent for a crash, a kill -9 and a run that ended by itself. */
376  stoppedBy?: string;
377  baseGates?: unknown;
378  /** Tests found red on the base mid-run, each once: a failure no branch caused, so none was repaired. */
379  baseRed?: string[];
380  /** Why a host merge check could not run for objects a partial clone lacks (`noteMissingObjects`): the closing summary says so, since those checks read the merge as clean. */
381  mergeUnchecked?: string;
382  /** Out-of-scope problems agents named in `<followup>` lines, recorded as each arrives: `id` is the ticket filed for triage, absent until it is filed (and for good in a dry run, or when filing `failed`, which a run that stopped on a `.git` change sets without trying). */
383  followUps?: { title: string; from: string; phase: string; id?: string; failed?: string }[];
384  /**
385   * The gates on the merged base. `image`: the tag they ran on, the run's own (built before any ticket landed).
386   * `failing`: the tests a red verify named, at most five (`failingMore`: it named others), read from the node:test, pytest, jest and similar output; absent when none were named.
387   * `dockerfiles`: the Dockerfiles the run's merges changed, which that image therefore lacks - absent when none.
388   * `gatedTree`: a red verify's tree is exactly one a fast-forward landing's ticket gates passed - the ticket's ref; the red is the sandbox's, not the merge's.
389   * `cleanTree`: the same for a landing merged and gated in a landing sandbox, a clean one - the red is a flaky or order-dependent test.
390   * `likelyLoad`: a red verify (run twice) whose failures are all test timeouts, or whose red gate ran several times its recorded time - the machine's load, not the merge or the sandbox.
391   * `skipped`: the verify did not run, as the green-base record already named the merged tip: `by` is whose gates proved it and `kind` where they ran.
392   * `notRun`: the verify could not open its sandbox (a worktree or container start that timed out): the error's line. `green` is false, so the run exits 1 and nothing is pushed on an ungated base.
393   */
394  verify?: { green: boolean; line: string; image?: string; failing?: string[]; failingMore?: boolean; dockerfiles?: string[]; gatedTree?: string; cleanTree?: string; likelyLoad?: boolean; skipped?: { commit: string; by?: string; kind?: string }; notRun?: string } | null;
395  keptWorktrees?: { issue: string; path: string }[];
396  /** Tracked files a gate rewrote and the kit put back, by path, once each. */
397  gateRewrites?: string[];
398  dryRunCheck?: string;
399  tickets?: Record<string, TicketRecord>;
400};
401
types/index.d.ts 23 lines
1/** What the band above the prompt draws from (run-state.ts, `Summary`); null while no run is live. */
2export type View = { name: string; stage: string; counts: number[]; tokens: string } | null;
3
4/** What the cache refresh remembers (keep-warm.ts's `Warmth`; this contract is self-contained, so it is written out). */
5export type Warmth = {
6  run?: string;
7  last?: { at: number; cacheRead: number; contextTokens: number };
8  misses: number;
9  turnEnd?: number;
10};
11
12declare module "claude-code" {
13  interface PluginState {
14    /**
15     * `castle`: the frame of the castle the band draws, an index into run-state.ts's `CASTLE_FRAMES`.
16     * `mark`: the idle mark's line the band draws between runs - the `parts` of idle.ts's `markText` - null for none.
17     * `warm`: the cache refresh's row under the castle (keep-warm.ts's `band`), null for none.
18     * `warmth`: what the refresh remembers across a reload (keep-warm.ts's `Warmth`).
19     */
20    sandcastle: { view: View; castle: number; mark: { text: string; tone: "name" | "hint" | "muted" }[] | null; warm: string | null; warmth: Warmth };
21  }
22}
23