LeanCTX Context Gateway cockpit: inspect recorded context activity and evidence, explore local knowledge, view colored ctx_patch diffs and highlighted…

A Claude Code mod (Community tier) that makes lean-ctx part of Claude Code itself instead of something the model has to be talked into using. Requires Claude Code 2.1.287+; tested with 2.1.287.
lean-ctx setup and lean-ctx update set the mod up wherever Claude Code 2.1.287+ is installed, and say so in their report. By hand:
lean-ctx claude-mod install
lean-ctx claude-mod status
lean-ctx claude-mod uninstall # stays removed: setup/update will not reinstall it
The lean-ctx binary carries the mod and installs it from a local marketplace in its data dir — nothing is downloaded, and the mod's version is the engine's version, so every lean-ctx update rolls it forward. It becomes active in new Claude Code sessions, or after /reload-plugins. The mod runs inside Claude Code with your permissions, so removing it is respected as a standing decision: uninstall leaves a marker (<data dir>/claude-mod.declined) that keeps setup and update from installing it again, until lean-ctx claude-mod install lifts it.
Measured on 569 Claude Code sessions (30 days): ~19 % of all model requests were waiting — 7,551 status polls for 1,030 background jobs plus 1,770 sleep calls — and every extra request re-reads the whole context (median 149k tokens). The mod removes those requests instead of compressing around them.
hooks/cockpit.tsx, interactive sessions only). A docked sidebar in the product's own terms: SELECT (tokens kept out of Claude's context, share of the raw tool output, files, commands, cached re-reads), CONTROL (secrets redacted, commands and paths blocked, injections flagged; context window and prompt cache), PROVE (both hash chains re-verified by lean-ctx value every 5 minutes), TIMELINE (the session's running total) and RECENT (the last tool calls). A pulse line above the prompt while Claude works, brighter while a lean-ctx tool runs; a short card when a turn ends and when a milestone is crossed. The numbers are those of the lean-ctx session serving this conversation (matched by process tree), the same ones lean-ctx statusline shows below the prompt; the band above the prompt repeats none of them. /cockpit reopens the sidebar; /cockpit off closes it and keeps it closed in new sessions (the proof re-verification stops with it), /cockpit on brings it back. The choice is the mod's Open the LeanCTX cockpit sidebar option in /config. /cockpit pulse off hides the pulse line and /cockpit cards off the turn and milestone cards (with the milestone notification and the summary on the "done in" line), now and in new sessions; on brings each back, and both are also options in /config. The spinner always stays. LeanCTX colours from leanctx.com.hooks/render.tsx). ctx_patch evidence goes through Claude Code's diff renderer (gutters, +/- colouring, syntax highlighting); ctx_read (lines, anchored, full/raw, several files) is drawn as highlighted code numbered from the real line, anchor hashes hidden on screen; ctx_search hits show a dim path:line, the highlighted line and the enclosing symbol. Display only — Claude receives every result byte-for-byte, and anything not recognised (signatures, map, errors, running calls) is drawn as usual. Turn it off with the color_output setting. The idea came from community member Kirill Naumenko's leanctx-colored; with both installed, whichever runs first draws the row, never both.ctx_shell(run_in_background=true) jobs in Claude Code's process (state from ctx_shell's structuredContent, then its JSON text, then the [background:…] header) and starts one new turn when they finish — including failed jobs, which MCP reports as error results — with the job id, exit status and recovery handle. Bare sleep N waits are answered while a job is watched. Verified live: the model started a job, ended its turn, and was woken by the mod with Job … finished · exit 0 (no polls). Each wake shows as a "Prompt from the lean-ctx plugin" row; Claude Code keeps plugin prompts in the transcript and offers no hidden variant. Wakes are therefore rare: jobs finishing together share one, a job that finishes while a turn runs or an earlier wake waits for its turn is held and dropped if the model reads it there, and only what is left wakes once afterwards. The Wake Claude when a lean-ctx background job finishes option (wake_on_job_finish) turns watching off; Claude then checks jobs itself.Bash stdout (≥ 2,000 chars) is compressed by lean-ctx's command-aware engine via the internal ctx_shape tool — the same patterns, secret redaction and output filters as ctx_shell, ending lossy results with a recovery handle. stderr, small output, images, background launches and commands with LEAN_CTX_RAW=1 / lean-ctx raw stay byte-for-byte; any failure keeps the native result. Turn it off with the shape_native_output setting.ctx_read, ctx_search, ctx_shell, ctx_compose, ctx_callgraph, ctx_session (setting front_loaded_tools) and defers every other lean-ctx tool — including the shell alias — behind ToolSearch, with descriptions byte-identical. Verified by capturing the real /v1/messages request: exactly the configured six keep their schema.SessionStart and UserPromptSubmit attachments, including matching lean-ctx blocks when Claude joins several hooks' text. Exact leading signatures keep engine and plugin attachments, other hooks' output, and unrelated security or policy reminders intact. The MCP server instructions and live lean-ctx skill remain the guidance channel. Set keep_hook_context to true to keep the hook context; its default is false. /leanctx reports how many attachments and characters the mod removed.lean-ctx skill with what is true in this session (wake, front-loaded tools, shaping), so it never contradicts the mod./compact … instructions are kept. The first prompt afterwards carries the lean-ctx session state (task, decisions, findings) once, capped at ~500 tokens. Subagent compactions are untouched./leanctx. This session's requests, input/output/cache tokens, ToolSearch-only requests, lean-ctx calls, answered sleeps, wakes and shaped Bash outputs, and dropped hook attachments/characters — from Claude Code's own turn.step usage and hook text, not estimates.It keeps nothing after the session, sends no telemetry, sets no gateway policy and stays inert when no lean-ctx MCP server is connected.
A mod runs inside Claude Code with your permissions. This one only calls the mods API methods the validator lists below; it reaches lean-ctx through Claude Code's own MCP connection ($.mcp.call), never through a shell or the network. ctx_shape is an internal host hook: never advertised to agents; the mod reaches it through the listed ctx_call, because $.mcp.call only calls listed tools.
The sources are canonical in rust/src/templates/claude_mod/ (embedded in the binary); this directory is the development workspace, regenerated with cargo run --example gen_rules --features dev-tools and drift-checked in CI. Edit the templates, regenerate, then:
claude --plugin-dir ./integrations/claude-code-mod # one session, hot reload
claude plugin validate --strict integrations/claude-code-mod
claude plugin validate --strict integrations/claude-code-mod/.claude-plugin/plugin.json
claude plugin test integrations/claude-code-mod
tsc -p integrations/claude-code-mod/tsconfig.json
tsc needs the version-matched declarations in .claude-plugin/types/ (git-ignored), which Claude Code writes the first time it loads the mod with --plugin-dir. The validator reports:
❯ ./register.ts hooks: tool.describe{tool=/"^mcp__lean[-_]ctx__[A-Za-z0-9_-]+$"/}, skill.prompt{skill=lean-ctx}, prompt.attachment, session.start, tool.call, session.compact, prompt.submit, turn.step, command.run{command=leanctx}
❯ ./register.ts calls: $.clock.every (via startWatcher), $.command.register (via ensureMeterCommand), $.mcp.call (via pollWatchedJobs, shapeBash), $.prompt.submit (via submitWake)hooks/register.ts 963 lines1// SPDX-License-Identifier: Apache-2.0
2import type {
3 EngineInterface,
4 McpToolResult,
5 Register,
6 Timer,
7 ToolCallResult,
8 TurnStepResult,
9} from "claude-code";
10
11import { registerCockpit } from "./cockpit";
12import { registerResultRendering } from "./render";
13
14const DEFAULT_FRONT_LOADED_TOOLS = [
15 "ctx_read",
16 "ctx_search",
17 "ctx_shell",
18 "ctx_compose",
19 "ctx_callgraph",
20 "ctx_session",
21];
22// Every tool of the lean-ctx server, not only `ctx_*`: the `shell` alias of
23// ctx_shell would otherwise stay front-loaded under `alwaysLoad`.
24const LEAN_CTX_TOOL_PATTERN = /^mcp__lean[-_]ctx__[A-Za-z0-9_-]+$/;
25const LEAN_CTX_TOOL_NAME = /^mcp__(lean[-_]ctx)__([A-Za-z0-9_-]+)$/;
26const SHELL_TOOLS = new Set(["ctx_shell", "shell"]);
27const WATCH_CONTEXT =
28 "This background job is being watched; you will be woken automatically on completion, so do not poll or sleep.";
29const WATCH_INTERVAL_MS = 2_000;
30// A submitted wake normally starts its turn within seconds; after this many
31// watcher ticks' worth it is treated as gone, so held jobs never stay stuck.
32const WAKE_IN_FLIGHT_MAX_MS = 60_000;
33// Consecutive unreadable status checks before a job is handed back to the
34// model's own polling; one transient MCP hiccup must not drop the watch.
35const MAX_STATUS_MISSES = 5;
36const MAX_TAIL_LINES = 20;
37const MAX_TAIL_LINE_CHARS = 300;
38// Native Bash stdout below this is kept byte-for-byte: the shaping gain cannot
39// pay for the extra hop, and short output is usually exactly what was asked.
40const SHAPE_MIN_CHARS = 2_000;
41// Commands that explicitly ask for exact bytes are never shaped.
42const RAW_INTENT = /\bLEAN_CTX_(?:RAW|DISABLED)=1\b|\blean-ctx\s+raw\b/;
43// Upper bound for the session state injected after a compaction (~500 tokens).
44const MAX_RESUME_CHARS = 2_000;
45type LeanCtxHookTextEnd = { end: string; continues?: readonly string[] };
46type LeanCtxHookTextSignature = { start: string; ends: readonly LeanCtxHookTextEnd[] };
47// Exact leading signatures emitted by observe.rs. Keep these stable and update
48// the cross-language drift test there whenever an authored hook text changes.
49const LEAN_CTX_HOOK_TEXT_SIGNATURES: readonly LeanCtxHookTextSignature[] = [
50 {
51 start: "lean-ctx active: ALWAYS use ctx_* MCP tools instead of native equivalents.",
52 ends: [
53 { end: "Exclusive tools: ctx_compose, ctx_callgraph, ctx_knowledge, ctx_session." },
54 ],
55 },
56 {
57 start: "CRITICAL: ALWAYS use lean-ctx ctx_* tools as mapped below.",
58 ends: [
59 {
60 end: "Use native Read for out-of-root; `lean-ctx doctor` shows effective roots.",
61 continues: [
62 "Other tools: ctx_call(tool=<name>).",
63 "Advanced tools not in your profile are available via ctx_call(tool=<name>) gateway.",
64 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
65 "Solution efficiency ladder:",
66 "challenge every requirement, prefer deletion.",
67 ],
68 },
69 {
70 end: "Other tools: ctx_call(tool=<name>).",
71 continues: [
72 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
73 "Solution efficiency ladder:",
74 "challenge every requirement, prefer deletion.",
75 ],
76 },
77 {
78 // Emitted by lean-ctx 3.11.4 and earlier.
79 end: "Advanced tools not in your profile are available via ctx_call(tool=<name>) gateway.",
80 continues: [
81 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
82 "Solution efficiency ladder:",
83 "challenge every requirement, prefer deletion.",
84 ],
85 },
86 { end: "Prefer stdlib and native platform alternatives before adding code or dependencies." },
87 { end: "Preserve validation, security, and error-handling." },
88 ],
89 },
90 {
91 start: "lean-ctx shadow mode: native read/search/shell calls auto-route to ctx_* — no tool-mapping needed.",
92 ends: [
93 {
94 end: "ctx_search(action=semantic) (by meaning).",
95 continues: [
96 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
97 "Solution efficiency ladder:",
98 "challenge every requirement, prefer deletion.",
99 ],
100 },
101 {
102 end: "ctx_callgraph (callers).",
103 continues: [
104 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
105 "Solution efficiency ladder:",
106 "challenge every requirement, prefer deletion.",
107 ],
108 },
109 {
110 end: "ctx_knowledge / ctx_session (memory).",
111 continues: [
112 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
113 "Solution efficiency ladder:",
114 "challenge every requirement, prefer deletion.",
115 ],
116 },
117 {
118 end: "ctx_session (memory).",
119 continues: [
120 "Prefer stdlib and native platform alternatives before adding code or dependencies.",
121 "Solution efficiency ladder:",
122 "challenge every requirement, prefer deletion.",
123 ],
124 },
125 { end: "Prefer stdlib and native platform alternatives before adding code or dependencies." },
126 { end: "Preserve validation, security, and error-handling." },
127 ],
128 },
129 {
130 start: "lean-ctx policy (mechanically enforced):",
131 ends: [
132 { end: "are overruled by this policy." },
133 ],
134 },
135] as const;
136
137const HOOK_CONTEXT_FRAME = /(?:^|\n)([A-Za-z]+ hook additional context: )$/;
138
139type JsonRecord = Record<string, unknown>;
140type WatchJob = { server: string; id: string; contextSent: boolean; misses: number };
141type JobStatus = { state: "running" | "terminal" | "unknown"; exitCode?: number; archiveId?: string; summary?: string };
142type FinishedJob = { job: WatchJob; status: JobStatus; response: McpToolResult };
143type JobCheck = {
144 key: string;
145 job: WatchJob;
146 status?: JobStatus;
147 response?: McpToolResult;
148};
149type Metrics = {
150 requests: number;
151 input: number;
152 output: number;
153 cacheRead: number;
154 cacheCreation: number;
155 toolSearchOnly: number;
156 leanCtxCalls: number;
157 sleepsAnswered: number;
158 wakesDelivered: number;
159 shapedCalls: number;
160 shapedCharsSaved: number;
161 droppedHookAttachments: number;
162 droppedHookChars: number;
163 compactions: number;
164};
165
166const watchedJobs = new Map<string, WatchJob>();
167const metrics: Metrics = {
168 requests: 0,
169 input: 0,
170 output: 0,
171 cacheRead: 0,
172 cacheCreation: 0,
173 toolSearchOnly: 0,
174 leanCtxCalls: 0,
175 sleepsAnswered: 0,
176 wakesDelivered: 0,
177 shapedCalls: 0,
178 shapedCharsSaved: 0,
179 droppedHookAttachments: 0,
180 droppedHookChars: 0,
181 compactions: 0,
182};
183let watcher: Timer | undefined;
184let watcherTickInProgress = false;
185// True between a main-loop `turn.start` and its `turn.complete`. A wake
186// submitted then is only delivered after the turn, by which time the model
187// may have read the job itself — so finished jobs wait in `pendingWakes`.
188let mainTurnActive = false;
189const pendingWakes = new Map<string, FinishedJob>();
190// Watcher ticks since the last wake was submitted, until its turn starts. Jobs
191// that finish meanwhile are held too: every wake is a visible prompt row and a
192// turn, and in that turn the model often reads the other jobs itself, which
193// drops them.
194let wakeInFlightTicks: number | undefined;
195
196function isWakeInFlight(): boolean {
197 return wakeInFlightTicks !== undefined && wakeInFlightTicks * WATCH_INTERVAL_MS < WAKE_IN_FLIGHT_MAX_MS;
198}
199let leanCtxSeen = false;
200// The lean-ctx MCP server name as this session spells it (`lean-ctx`/`lean_ctx`).
201let leanServer: string | undefined;
202let commandAttempted = false;
203let commandRegistered = false;
204// Set by a main-loop compaction; the next prompt carries the lean-ctx session state once.
205let resumePending = false;
206
207export const register: Register = (on, options) => {
208 // The cockpit: sidebar, pulse line, turn and milestone overlays (cockpit.tsx).
209 // Held wakes go out on the next watcher tick after the turn (≤ 2 s); the
210 // watcher keeps running while any are held.
211 registerCockpit(
212 on,
213 {
214 onTurnStart: () => {
215 mainTurnActive = true;
216 wakeInFlightTicks = undefined;
217 },
218 onMainTurnComplete: () => {
219 mainTurnActive = false;
220 },
221 },
222 {
223 panel: asRecord(options).cockpit_panel !== false,
224 pulse: asRecord(options).cockpit_pulse_line !== false,
225 cards: asRecord(options).cockpit_turn_cards !== false,
226 },
227 );
228 // ctx_patch / ctx_read / ctx_search results drawn as diffs and code
229 // (render.tsx). Display only: the model receives every result unchanged.
230 if (asRecord(options).color_output !== false) registerResultRendering(on);
231 const frontLoaded = getFrontLoadedTools(options);
232 const shapeNative = asRecord(options).shape_native_output !== false;
233 const keepHookContext = asRecord(options).keep_hook_context === true;
234 // Off: background jobs are not watched and the model checks them itself.
235 const wakeOnFinish = asRecord(options).wake_on_job_finish !== false;
236
237 on("tool.describe", { tool: LEAN_CTX_TOOL_PATTERN }, async ($, event) => {
238 const match = getLeanCtxTool(event.tool);
239 if (!match) return { description: event.description, isDeferred: event.isDeferred };
240
241 leanCtxSeen = true;
242 leanServer = match.server;
243 await ensureMeterCommand($);
244 return {
245 description: event.description,
246 isDeferred: !frontLoaded.has(match.tool),
247 };
248 });
249
250 // Live skill (concept K5): the shipped SKILL.md is static; this prefixes it
251 // with what is true in *this* session, so the guidance never contradicts the
252 // mod (e.g. "no need to poll") or the configured tool surface. Byte-stable
253 // for a given configuration, so it never churns the prompt cache.
254 on("skill.prompt", { skill: "lean-ctx" }, async ($, event, next) => {
255 const base = await next(event);
256 return { text: `${liveSkillHeader(frontLoaded, shapeNative, wakeOnFinish)}\n\n${base.text}` };
257 });
258
259 // The MCP instructions and live skill carry the durable guidance. Drop only
260 // exact lean-ctx SessionStart/UserPromptSubmit hook blocks; other authors and
261 // other hook events pass through unchanged. No agentId check keeps this
262 // channel diet active in both the main loop and subagents.
263 on("prompt.attachment", async ($, event, next) => {
264 if (
265 keepHookContext ||
266 event.origin.kind !== "hook" ||
267 (event.origin.event !== "SessionStart" && event.origin.event !== "UserPromptSubmit")
268 ) {
269 return next(event);
270 }
271 const stripped = stripLeanCtxHookText(event.text);
272 if (stripped.removedChars === 0) return next(event);
273 metrics.droppedHookAttachments += 1;
274 metrics.droppedHookChars += stripped.removedChars;
275 return { text: stripped.text || null };
276 });
277
278 on("session.start", async ($, event, next) => {
279 resetSessionState();
280 // Detect lean-ctx up front so `/leanctx` exists before the first model
281 // request (tool.describe only fires once a request renders the tools).
282 // A server still connecting is picked up later by the tool hooks.
283 if (!leanCtxSeen) {
284 try {
285 const match = (await $.tool.list())
286 .map((tool) => getLeanCtxTool(tool.name))
287 .find((found) => found !== undefined);
288 if (match) {
289 leanCtxSeen = true;
290 leanServer = match.server;
291 }
292 } catch {
293 // Listing is best-effort; the tool hooks still detect lean-ctx.
294 }
295 }
296 if (leanCtxSeen) await ensureMeterCommand($);
297 return next(event);
298 });
299
300 on("tool.call", async ($, event, next) => {
301 const fields = event as unknown as JsonRecord;
302 const tool = typeof fields.tool === "string" ? fields.tool : "";
303 const leanCtxTool = getLeanCtxTool(tool);
304
305 if (!leanCtxTool) {
306 if (tool === "Bash" && watchedJobs.size > 0 && isSleepWait(readString(fields, "command"))) {
307 metrics.sleepsAnswered += 1;
308 return { result: sleepAnswer() };
309 }
310 if (tool === "Bash" && shapeNative) {
311 return shapeBash($, readString(fields, "command"), await next(event));
312 }
313 return next(event);
314 }
315
316 leanCtxSeen = true;
317 leanServer = leanCtxTool.server;
318 metrics.leanCtxCalls += 1;
319 await ensureMeterCommand($);
320
321 if (
322 SHELL_TOOLS.has(leanCtxTool.tool) &&
323 watchedJobs.size > 0 &&
324 isSleepWait(readString(fields, "command"))
325 ) {
326 metrics.sleepsAnswered += 1;
327 return { result: sleepAnswer() };
328 }
329
330 if (SHELL_TOOLS.has(leanCtxTool.tool) && fields.run_in_background && wakeOnFinish) {
331 const result = await next(event);
332 const jobId = extractJobId(result);
333 if (!jobId) return result;
334
335 const key = watchKey(leanCtxTool.server, jobId);
336 const job = watchedJobs.get(key) ?? { server: leanCtxTool.server, id: jobId, contextSent: false, misses: 0 };
337 watchedJobs.set(key, job);
338 if (!startWatcher($)) {
339 watchedJobs.delete(key);
340 stopWatcherWhenIdle();
341 return result;
342 }
343 return addWatchContext(result, job);
344 }
345
346 const backgroundAction = readString(fields, "background_action");
347 if (SHELL_TOOLS.has(leanCtxTool.tool) && (backgroundAction === "status" || backgroundAction === "cancel")) {
348 const jobId = readString(fields, "job_id");
349 const key = jobId ? watchKey(leanCtxTool.server, jobId) : undefined;
350 const job = key ? watchedJobs.get(key) : undefined;
351 const result = await next(event);
352 if (!key || !jobId || (!job && !pendingWakes.has(key))) return result;
353 // The model has now seen this job's terminal state itself: stop
354 // watching it and drop a wake the watcher already held for it, or the
355 // same result arrives again and costs a whole extra turn.
356 if (toolCallJobStatus(result, jobId).state === "terminal") {
357 if (job && watchedJobs.get(key) === job) watchedJobs.delete(key);
358 pendingWakes.delete(key);
359 stopWatcherWhenIdle();
360 return result;
361 }
362 return job ? addWatchContext(result, job) : result;
363 }
364
365 return next(event);
366 });
367
368 // K8 compaction coordination: before the main conversation is compacted,
369 // lean-ctx persists its session state and the summarizer is told what lean-ctx
370 // still depends on; afterwards the next prompt carries that state once.
371 // Subagent compactions and every failure pass through untouched.
372 on("session.compact", async ($, event, next) => {
373 if (!leanServer || event.agentId) return next(event);
374 const server = leanServer;
375 try {
376 await $.mcp.call(server, "ctx_session", { action: "save" });
377 } catch {
378 // Saving is best-effort; compaction proceeds regardless.
379 }
380 const instructions = [event.instructions, compactionInstructions()].filter(Boolean).join("\n\n");
381 const result = await next({ ...event, instructions });
382 if (!result.skip) {
383 metrics.compactions += 1;
384 resumePending = true;
385 }
386 return result;
387 });
388
389 on("prompt.submit", async ($, event, next) => {
390 if (!resumePending || !leanServer) return next(event);
391 resumePending = false;
392 const state = await sessionState($, leanServer);
393 return state ? next({ ...event, context: [...(event.context ?? []), state] }) : next(event);
394 });
395
396 on("turn.step", async function* ($, event, next) {
397 const result = yield* next(event);
398 if (leanCtxSeen) recordRequest(result);
399 return result;
400 });
401
402 on("command.run", { command: "leanctx" }, async ($, event, next) => {
403 return commandRegistered ? { text: formatMetrics() } : next(event);
404 });
405};
406
407// Shape, don't redirect (concept K2): the native Bash call already ran; its
408// stdout goes through lean-ctx's command-aware compressor (`ctx_shape`, which
409// also applies lean-ctx's secret redaction and output filters) instead of
410// denying the call and forcing a round trip to ctx_shell. Lossy results end
411// with a recovery handle. stderr is kept verbatim. Fail-open everywhere: any
412// refusal on the way (workflow, role, budget) comes back as an error.
413// ctx_shape is not listed, and `$.mcp.call` only reaches listed tools (Claude
414// Code 2.1.296+), so the call goes through the listed `ctx_call` (#2089).
415async function shapeBash(
416 $: EngineInterface,
417 command: string | undefined,
418 result: ToolCallResult,
419): Promise<ToolCallResult> {
420 if (!leanServer || !command || RAW_INTENT.test(command)) return result;
421 if ("deny" in result || result.isError) return result;
422 const record = asRecord(result.result);
423 const stdout = typeof record.stdout === "string" ? record.stdout : "";
424 if (
425 stdout.length < SHAPE_MIN_CHARS ||
426 record.isImage ||
427 record.backgroundTaskId ||
428 record.persistedOutputPath
429 ) {
430 return result;
431 }
432 try {
433 // A non-error result without a special-exit interpretation exited 0, so the
434 // engine takes its success path (folds build/test noise); otherwise it gets
435 // no exit code and keeps the unknown-outcome guard.
436 const exitCode = record.returnCodeInterpretation ? {} : { exit_code: 0 };
437 const shaped = await $.mcp.call(leanServer, "ctx_call", {
438 name: "ctx_shape",
439 arguments: { tool: "Bash", command, output: stdout, ...exitCode },
440 });
441 if (shaped.isError) return result;
442 const text = mcpText(shaped);
443 if (!text || text.length >= stdout.length) return result;
444 metrics.shapedCalls += 1;
445 metrics.shapedCharsSaved += stdout.length - text.length;
446 return { result: { ...record, stdout: text }, context: result.context } as ToolCallResult;
447 } catch {
448 return result;
449 }
450}
451
452// What the compaction summary must keep for lean-ctx to stay usable: ids of
453// jobs that will still wake the model, and recovery handles of compressed
454// output the ongoing work refers to. Deterministic for a given watch set.
455function compactionInstructions(): string {
456 const ids = [...watchedJobs.values()].map((job) => job.id).sort();
457 const lines = [
458 "lean-ctx: keep, verbatim, any lean-ctx recovery handles the ongoing work still relies on (ctx_expand ids and `full original at …` paths).",
459 ];
460 if (ids.length > 0) {
461 lines.push(
462 `lean-ctx: background job(s) ${ids.join(", ")} are still running and will report when done — keep their ids and do not plan to poll them.`,
463 );
464 }
465 return lines.join("\n");
466}
467
468// The lean-ctx session state (task, decisions, findings) for the first prompt
469// after a compaction, bounded so it can never crowd out the conversation.
470async function sessionState($: EngineInterface, server: string): Promise<string | undefined> {
471 try {
472 const response = await $.mcp.call(server, "ctx_session", { action: "status" });
473 if (response.isError) return undefined;
474 const text = mcpText(response).trim();
475 if (!text) return undefined;
476 const bounded = text.length <= MAX_RESUME_CHARS ? text : `${text.slice(0, MAX_RESUME_CHARS)}…`;
477 return `lean-ctx session state, restored after compaction:\n${bounded}`;
478 } catch {
479 return undefined;
480 }
481}
482
483function liveSkillHeader(frontLoaded: Set<string>, shapeNative: boolean, wakeOnFinish: boolean): string {
484 const front = [...frontLoaded].sort().join(", ");
485 return [
486 "## Live in this session (lean-ctx Claude Code mod)",
487 wakeOnFinish
488 ? "- Background jobs (`ctx_shell(run_in_background=true)` or Bash `run_in_background`) wake you when they finish: start them, then continue other work or end the turn. Never `sleep` or poll their status."
489 : "- Bash `run_in_background` jobs wake you when they finish. `ctx_shell(run_in_background=true)` jobs do not: check one with `ctx_shell(background_action=\"status\", job_id=…)` once you need its result.",
490 `- In your tool list: ${front}. Other lean-ctx tools load with one ToolSearch \`select:\` or run via \`ctx_call\`.`,
491 shapeNative
492 ? "- Native Bash output is compressed automatically (a recovery handle ends any lossy result); there is no need to route commands through ctx_shell just for compression."
493 : "- Native Bash output is passed through unchanged in this session.",
494 ].join("\n");
495}
496
497function getFrontLoadedTools(options: unknown): Set<string> {
498 const configured = asRecord(options).front_loaded_tools;
499 if (!Array.isArray(configured)) return new Set(DEFAULT_FRONT_LOADED_TOOLS);
500 return new Set(configured.filter((value): value is string => typeof value === "string"));
501}
502
503function getLeanCtxTool(name: string): { server: string; tool: string } | undefined {
504 const match = LEAN_CTX_TOOL_NAME.exec(name);
505 if (!match?.[1] || !match[2]) return undefined;
506 return { server: match[1], tool: match[2] };
507}
508
509function readString(record: JsonRecord, key: string): string | undefined {
510 return typeof record[key] === "string" ? (record[key] as string) : undefined;
511}
512
513function isSleepWait(command: string | undefined): boolean {
514 return !!command &&
515 /^\s*sleep\s+\d+(?:\.\d+)?(?:\s*&&\s*(?=[^;\n]*(?:\bstatus\b|\btail\b))[^;\n]*)?\s*$/i.test(command);
516}
517
518function sleepAnswer(): string {
519 const ids = [...watchedJobs.values()].map((job) => job.id).sort();
520 return `No need to wait: background job(s) ${ids.join(", ")} are watched and you will be woken automatically; end the turn or continue other work.`;
521}
522
523function watchKey(server: string, id: string): string {
524 return `${server}\u0000${id}`;
525}
526
527function addWatchContext(result: ToolCallResult, job: WatchJob): ToolCallResult {
528 if (job.contextSent || "deny" in result) return result;
529 job.contextSent = true;
530 const context = [...(result.context ?? [])];
531 if (!context.includes(WATCH_CONTEXT)) context.push(WATCH_CONTEXT);
532 return { ...result, context };
533}
534
535function extractJobId(result: ToolCallResult): string | undefined {
536 if ("deny" in result) return undefined;
537 return readString(readShellFields(result.result, result.text), "jobId");
538}
539
540// ctx_shell reports background state as MCP `structuredContent`
541// (`{ jobId, state, exitCode?, archiveId?, summary }`, or `{ jobId, errorCode }`
542// for an expired id — rust/src/server/tool_trait.rs). Hosts often render
543// only that object as the text block, so a JSON text block is the second
544// source; the `[background:…]` text header is the last resort.
545function readShellFields(raw: unknown, extraText?: string): JsonRecord {
546 const body = asRecord(raw);
547 const structured = asRecord(body.structuredContent);
548 if (readString(structured, "jobId") || readString(structured, "job_id")) return normalize(structured);
549
550 const texts = [
551 ...(Array.isArray(body.content)
552 ? body.content.map((block) => asRecord(block).text).filter((t): t is string => typeof t === "string")
553 : []),
554 ...(extraText ? [extraText] : []),
555 ];
556 for (const text of texts) {
557 const trimmed = text.trim();
558 if (!trimmed.startsWith("{")) continue;
559 try {
560 const parsed = asRecord(JSON.parse(trimmed));
561 if (readString(parsed, "jobId") || readString(parsed, "job_id")) return normalize(parsed);
562 } catch {
563 // Not a JSON block; try the next source.
564 }
565 }
566
567 const joined = texts.join("\n");
568 const header = /\[(?:auto-)?background:([A-Za-z0-9_-]+)\s*(running|started|completed|failed|cancelled|canceled|not found)?(?:,\s*exit\s+(-?\d+))?/i.exec(joined);
569 if (!header) return {};
570 const word = header[2]?.toLowerCase();
571 return {
572 jobId: header[1],
573 state: word === "started" ? "running" : word === "not found" ? "expired" : word,
574 exitCode: header[3] === undefined ? undefined : Number(header[3]),
575 text: joined,
576 };
577}
578
579function normalize(fields: JsonRecord): JsonRecord {
580 return {
581 jobId: readString(fields, "jobId") ?? readString(fields, "job_id"),
582 state: readString(fields, "errorCode") ? "expired" : readString(fields, "state"),
583 exitCode: getNumber(fields, ["exitCode", "exit_code"]),
584 archiveId: readString(fields, "archiveId") ?? readString(fields, "archive_id"),
585 summary: readString(fields, "summary"),
586 };
587}
588
589function getNumber(record: JsonRecord, keys: string[]): number | undefined {
590 for (const key of keys) {
591 const value = record[key];
592 if (typeof value === "number" && Number.isFinite(value)) return value;
593 }
594 return undefined;
595}
596
597function startWatcher($: EngineInterface): boolean {
598 if (watcher) return true;
599 try {
600 watcher = $.clock.every(WATCH_INTERVAL_MS, () => {
601 void pollWatchedJobs($);
602 });
603 return true;
604 } catch {
605 watcher = undefined;
606 return false;
607 }
608}
609
610function stopWatcherWhenIdle(): void {
611 if (watchedJobs.size > 0 || pendingWakes.size > 0 || !watcher) return;
612 try {
613 watcher.cancel();
614 } catch {
615 // Cancellation failure must not affect the model's tool flow.
616 }
617 watcher = undefined;
618}
619
620// Deliver the held wakes of jobs the model has not read itself, as one wake.
621function flushPendingWakes($: EngineInterface): void {
622 if (mainTurnActive || isWakeInFlight() || pendingWakes.size === 0) return;
623 const finished = [...pendingWakes.values()];
624 pendingWakes.clear();
625 stopWatcherWhenIdle();
626 submitWake($, formatWakeSummary(finished));
627}
628
629async function pollWatchedJobs($: EngineInterface): Promise<void> {
630 if (wakeInFlightTicks !== undefined) wakeInFlightTicks += 1;
631 // The tick doubles as the fallback flush once no turn runs.
632 flushPendingWakes($);
633 if (watcherTickInProgress || watchedJobs.size === 0) return;
634 watcherTickInProgress = true;
635 const snapshot = [...watchedJobs.entries()];
636
637 try {
638 const checks = await Promise.all(
639 snapshot.map(async ([key, job]): Promise<JobCheck> => {
640 try {
641 const response = await $.mcp.call(job.server, "ctx_shell", {
642 background_action: "status",
643 job_id: job.id,
644 });
645 // A finished job with a non-zero exit is an MCP error result too;
646 // only the parsed state decides, never `isError`.
647 return { key, job, response, status: inspectJobStatus(response, job.id) };
648 } catch {
649 return { key, job, status: { state: "unknown" } };
650 }
651 }),
652 );
653
654 const finished: FinishedJob[] = [];
655 const lost: WatchJob[] = [];
656 for (const check of checks) {
657 if (watchedJobs.get(check.key) !== check.job) continue;
658 if (!check.status || check.status.state === "running") {
659 check.job.misses = 0;
660 continue;
661 }
662 if (check.status.state === "unknown") {
663 check.job.misses += 1;
664 if (check.job.misses >= MAX_STATUS_MISSES) {
665 watchedJobs.delete(check.key);
666 lost.push(check.job);
667 }
668 continue;
669 }
670 watchedJobs.delete(check.key);
671 if (!check.response) continue;
672 const done = { job: check.job, status: check.status, response: check.response };
673 // Mid-turn, or while an earlier wake waits for its turn, hold the wake:
674 // the model may still read this job itself.
675 if (mainTurnActive || isWakeInFlight()) pendingWakes.set(check.key, done);
676 else finished.push(done);
677 }
678 stopWatcherWhenIdle();
679 const text = [
680 finished.length > 0 ? formatWakeSummary(finished) : "",
681 lost.length > 0 ? formatLostNotice(lost) : "",
682 ].filter(Boolean).join("\n\n");
683 if (text) submitWake($, text);
684 } catch {
685 // The watcher can no longer read job state: hand every watched job back
686 // to the model explicitly — it was told it would be woken, so a silent
687 // drop would leave it waiting forever.
688 const lost = [...watchedJobs.values()];
689 watchedJobs.clear();
690 stopWatcherWhenIdle();
691 if (lost.length > 0) submitWake($, formatLostNotice(lost));
692 } finally {
693 watcherTickInProgress = false;
694 }
695}
696
697function formatLostNotice(lost: WatchJob[]): string {
698 const ids = lost.map((job) => job.id).sort();
699 return `lean-ctx can no longer watch background job(s) ${ids.join(", ")}: check each once with ctx_shell(background_action="status", job_id=…) when you need its result.`;
700}
701
702function inspectJobStatus(response: McpToolResult, jobId: string): JobStatus {
703 return jobStatus(readShellFields(response), jobId);
704}
705
706// The model's own ctx_shell call reaches `tool.call` as the host's result
707// wrapper (`{ result, text }`), not as the raw MCP response the watcher polls.
708function toolCallJobStatus(result: ToolCallResult, jobId: string): JobStatus {
709 if ("deny" in result) return { state: "unknown" };
710 return jobStatus(readShellFields(result.result, result.text), jobId);
711}
712
713function jobStatus(fields: JsonRecord, jobId: string): JobStatus {
714 if (fields.jobId !== undefined && fields.jobId !== jobId) return { state: "unknown" };
715 const state = readString(fields, "state")?.toLowerCase();
716 if (state === "running") return { state: "running" };
717 if (state === "completed" || state === "failed" || state === "cancelled" || state === "canceled" || state === "expired") {
718 return {
719 state: "terminal",
720 exitCode: getNumber(fields, ["exitCode"]),
721 archiveId: readString(fields, "archiveId"),
722 summary: readString(fields, "summary"),
723 };
724 }
725 return { state: "unknown" };
726}
727
728function mcpText(response: McpToolResult): string {
729 return response.content
730 .map((block) => (block.type === "text" ? block.text : ""))
731 .filter(Boolean)
732 .join("\n");
733}
734
735type LeanCtxHookTextBlock = { start: number; end: number };
736
737function stripLeanCtxHookText(text: string): { text: string; removedChars: number } {
738 let remaining = text;
739 let removedChars = 0;
740 while (true) {
741 const block = LEAN_CTX_HOOK_TEXT_SIGNATURES
742 .map((signature) => findLeanCtxHookTextBlock(remaining, signature))
743 .find((candidate) => candidate !== undefined);
744 if (!block) break;
745 const next = removeJoinedTextBlock(remaining, block);
746 if (next === remaining) break;
747 removedChars += remaining.length - next.length;
748 remaining = next;
749 }
750 return { text: remaining, removedChars };
751}
752
753function findLeanCtxHookTextBlock(
754 text: string,
755 signature: LeanCtxHookTextSignature,
756): LeanCtxHookTextBlock | undefined {
757 let start = text.indexOf(signature.start);
758 while (start !== -1) {
759 // Claude Code frames hook context as "<Event> hook additional context: "
760 // on the same line; the frame goes with the block it introduces.
761 const frame = start === 0 || text[start - 1] === "\n" ? "" : HOOK_CONTEXT_FRAME.exec(text.slice(0, start))?.[1];
762 if (frame !== undefined) {
763 const end = findLeanCtxHookTextEnd(text, start, signature);
764 if (end !== undefined) return { start: start - frame.length, end };
765 }
766 start = text.indexOf(signature.start, start + 1);
767 }
768 return undefined;
769}
770
771function findLeanCtxHookTextEnd(
772 text: string,
773 start: number,
774 signature: LeanCtxHookTextSignature,
775): number | undefined {
776 let lineStart = start;
777 while (lineStart <= text.length) {
778 const end = lineEnd(text, lineStart);
779 const line = text.slice(lineStart, end);
780 const ending = signature.ends.find((marker) => line.endsWith(marker.end));
781 if (ending) {
782 const nextLine = nextNonEmptyLineStart(text, end);
783 const next = text.slice(nextLine, lineEnd(text, nextLine));
784 if (!ending.continues?.some((marker) => next.startsWith(marker))) return end;
785 lineStart = nextLine;
786 continue;
787 }
788 if (end === text.length) break;
789 lineStart = text.startsWith("\r\n", end) ? end + 2 : end + 1;
790 }
791}
792
793function nextNonEmptyLineStart(text: string, end: number): number {
794 let next = end;
795 while (next < text.length) {
796 if (text.startsWith("\r\n", next)) next += 2;
797 else if (text[next] === "\n") next += 1;
798 else break;
799 if (text.slice(next, lineEnd(text, next)) !== "") break;
800 }
801 return next;
802}
803
804function lineEnd(text: string, from: number): number {
805 const newline = text.indexOf("\n", from);
806 if (newline === -1) return text.length;
807 return newline > from && text[newline - 1] === "\r" ? newline - 1 : newline;
808}
809
810function removeJoinedTextBlock(text: string, block: LeanCtxHookTextBlock): string {
811 let before = text.slice(0, block.start);
812 let after = text.slice(block.end);
813 if (before.endsWith("\r\n")) before = before.slice(0, -2);
814 else if (before.endsWith("\n")) before = before.slice(0, -1);
815 else if (after.startsWith("\r\n")) after = after.slice(2);
816 else if (after.startsWith("\n")) after = after.slice(1);
817 return `${before}${after}`;
818}
819
820function submitWake($: EngineInterface, text: string): void {
821 wakeInFlightTicks = 0;
822 // A wake that never got through holds nothing back.
823 const failed = () => {
824 wakeInFlightTicks = undefined;
825 };
826 try {
827 void $.prompt
828 .submit({ text })
829 .then(() => {
830 metrics.wakesDelivered += 1;
831 })
832 .catch(() => {
833 // A failed wake leaves native status polling available.
834 failed();
835 });
836 } catch {
837 // A failed wake leaves native status polling available.
838 failed();
839 }
840}
841
842function formatWakeSummary(finished: FinishedJob[]): string {
843 const ordered = [...finished].sort((a, b) =>
844 a.job.id < b.job.id ? -1 : a.job.id > b.job.id ? 1 : a.job.server < b.job.server ? -1 : 1,
845 );
846 const sections = ordered.map(({ job, status, response }) => {
847 const handle = recoveryHandle(response, status.archiveId);
848 const lines = tailLines(response, job.id);
849 const body = handle
850 ? `Full output: ${handle}`
851 : status.summary || lines.join("\n") || "No output captured.";
852 const exit = status.exitCode === undefined ? "unknown" : status.exitCode;
853 return `Job ${job.id} finished · exit ${exit}\n${body}`;
854 });
855 return `Watched background job(s) finished:\n${sections.join("\n\n")}`;
856}
857
858function recoveryHandle(response: McpToolResult, archiveId?: string): string | undefined {
859 if (archiveId) return `ctx_expand id=${archiveId}`;
860 const structured = asRecord(response.structuredContent);
861 const direct =
862 readString(structured, "recovery_handle") ??
863 readString(structured, "recoveryHandle") ??
864 readString(structured, "tee_path") ??
865 readString(structured, "teePath");
866 if (direct) return direct;
867
868 const match = /(?:full output at|full output:)\s+([^\]\n]*?)(?:\s+—|\]|$)/i.exec(mcpText(response));
869 return match?.[1]?.trim();
870}
871
872function tailLines(response: McpToolResult, jobId: string): string[] {
873 const escapedId = jobId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
874 const statusLine = new RegExp(`^\\[background:${escapedId}(?:\\s|\\])`, "i");
875 return mcpText(response)
876 .split(/\r?\n/)
877 // Status headers and the structured JSON echo are metadata, not output.
878 .filter((line) => {
879 const trimmed = line.trim();
880 return trimmed.length > 0 && !statusLine.test(trimmed) && !trimmed.startsWith("{");
881 })
882 .slice(-MAX_TAIL_LINES)
883 .map((line) => (line.length <= MAX_TAIL_LINE_CHARS ? line : `${line.slice(0, MAX_TAIL_LINE_CHARS)}…`));
884}
885
886function recordRequest(result: TurnStepResult): void {
887 metrics.requests += 1;
888 if (result.usage) {
889 metrics.input += nonNegative(result.usage.input_tokens);
890 metrics.output += nonNegative(result.usage.output_tokens);
891 metrics.cacheRead += nonNegative(result.usage.cache_read_input_tokens);
892 metrics.cacheCreation += nonNegative(result.usage.cache_creation_input_tokens);
893 }
894 if (
895 result.toolUses.length > 0 &&
896 result.toolUses.every((use) => /(?:^|[_-])tool[_-]?search$/i.test(use.name))
897 ) {
898 metrics.toolSearchOnly += 1;
899 }
900}
901
902function formatMetrics(): string {
903 return [
904 `Requests ${metrics.requests}`,
905 `input ${metrics.input}`,
906 `output ${metrics.output}`,
907 `cache read ${metrics.cacheRead}`,
908 `cache creation ${metrics.cacheCreation}`,
909 `ToolSearch-only ${metrics.toolSearchOnly}`,
910 `lean-ctx calls ${metrics.leanCtxCalls}`,
911 `sleeps answered ${metrics.sleepsAnswered}`,
912 `wakes delivered ${metrics.wakesDelivered}`,
913 `Bash outputs shaped ${metrics.shapedCalls} (−${metrics.shapedCharsSaved} chars)`,
914 `hook attachments dropped ${metrics.droppedHookAttachments} (−${metrics.droppedHookChars} chars)`,
915 `compactions ${metrics.compactions}`,
916 ].join(" · ");
917}
918
919function nonNegative(value: number): number {
920 return Number.isFinite(value) && value > 0 ? value : 0;
921}
922
923async function ensureMeterCommand($: EngineInterface): Promise<void> {
924 if (commandAttempted) return;
925 commandAttempted = true;
926 try {
927 const command = await $.command.register({
928 name: "leanctx",
929 description: "Show per-session Claude Code request and lean-ctx usage.",
930 });
931 commandRegistered = command.command === "leanctx";
932 } catch {
933 // The name may already be taken; keep all other mod behavior fail-open.
934 }
935}
936
937function resetSessionState(): void {
938 metrics.requests = 0;
939 metrics.input = 0;
940 metrics.output = 0;
941 metrics.cacheRead = 0;
942 metrics.cacheCreation = 0;
943 metrics.toolSearchOnly = 0;
944 metrics.leanCtxCalls = 0;
945 metrics.sleepsAnswered = 0;
946 metrics.wakesDelivered = 0;
947 metrics.shapedCalls = 0;
948 metrics.shapedCharsSaved = 0;
949 metrics.droppedHookAttachments = 0;
950 metrics.droppedHookChars = 0;
951 metrics.compactions = 0;
952 resumePending = false;
953 wakeInFlightTicks = undefined;
954 watchedJobs.clear();
955 stopWatcherWhenIdle();
956}
957
958function asRecord(value: unknown): JsonRecord {
959 return value !== null && typeof value === "object" && !Array.isArray(value)
960 ? (value as JsonRecord)
961 : {};
962}
963hooks/cockpit.tsx 1532 lines1// SPDX-License-Identifier: Apache-2.0
2import { atom, read, update } from 'claude-code'
3import type { Elements, EngineInterface, On, RenderChildren } from 'claude-code'
4
5import type { Board, Depth, FeedItem, Frame, Overlay, Proof, SourceStat, TurnStat, ValueSnap } from '../types'
6
7// The LeanCTX cockpit, in the product's own terms: a Context Gateway between
8// Claude and the sources it reads. It shows what Claude saw and how deep, the
9// two checks before the handoff (may it be read? may it be delivered?), the
10// tokens kept out, and the receipts behind them. A handoff line runs above the
11// prompt while Claude works; short cards mark turns and milestones. lean-ctx's
12// status line below the prompt keeps the one-line totals.
13
14const PANE = 'leanctx-cockpit'
15const DOCK_COLUMNS = 62
16// lean-ctx writes a session's snapshot at most once a second.
17const REFRESH_AFTER_TOOL_MS = 1_300
18const REFRESH_MS = 15_000
19// `lean-ctx value` re-verifies both hash chains end to end (~8 s): rarely, in the background.
20const PROVE_FIRST_MS = 4_000
21const PROVE_MS = 5 * 60_000
22const PROVE_TIMEOUT_MS = 120_000
23const FRAME_MS = 70
24const COUNT_EASE = 0.16
25const TURN_OVERLAY_MS = 6_500
26const MILESTONE_OVERLAY_MS = 8_000
27// A call travels the handoff line: into the gate, then on to Claude.
28const PACKET_IN_MS = 700
29const PACKET_OUT_MS = 1_600
30// Same freshness window as lean-ctx's own status line.
31const ACTIVE_MS = 12 * 3_600_000
32const TURNS_KEPT = 60
33const HISTORY_KEPT = 480
34// The saving curve: three rows of eighth blocks (24 levels) and an axis line.
35const CURVE_ROWS = 3
36const FEED_KEPT = 30
37const FEED_SHOWN = 5
38const SOURCES_KEPT = 200
39const TOKEN_MILESTONES = [10e3, 25e3, 50e3, 100e3, 250e3, 500e3, 1e6, 2.5e6, 5e6, 10e6, 25e6]
40const SOURCE_MILESTONES = [25, 100, 250, 1000]
41const LEAN_CTX_TOOL = /^mcp__lean[-_]ctx__/
42
43// Keys are versioned by name: $.state outlives reloads, older shapes stay behind.
44const board = atom({ plugin: 'lean-ctx', key: 'gateway' } as const, {
45 milestone: 0,
46 turns: [],
47 isWorking: false,
48 leanRunning: 0,
49 feed: [],
50 sources: {},
51 turnSeen: { sources: 0, governed: 0, structure: 0 },
52 celebrated: [],
53} as Board)
54const frame = atom({ plugin: 'lean-ctx', key: 'clock' } as const, { tick: 0 } as Frame)
55
56// ── LeanCTX brand: leanctx.com premium-tokens.css (dark theme) ─────────────
57const CANVAS = 0x111626
58const PANEL = 0x1b2034
59const FOREGROUND = 0xf1f3ff
60const SECONDARY = 0xafb8d0
61const HAIRLINE = 0x353e5a
62const SIGNATURE = 0x668cff
63const BLUE_FIELD = 0x31416c
64// Derived within the family for light and motion; status colours only where earned.
65const ICE = 0xc9d6ff
66const VIOLET = 0xa08cff
67const AMBER = 0xf5b84b
68const DANGER = 0xff6b81
69const OK = 0x7ee0b5
70const DEFAULT_BG = 0x01000000
71const BRAND_SWEEP = [BLUE_FIELD, SIGNATURE, ICE, VIOLET, SIGNATURE, BLUE_FIELD]
72const DATA = [BLUE_FIELD, SIGNATURE, ICE]
73const hex = (c: number) => `#${c.toString(16).padStart(6, '0')}`
74
75// Each read depth keeps its colour everywhere: mix bar, legend, receipts.
76const DEPTHS: readonly Depth[] = ['structure', 'passage', 'full', 'search', 'command']
77const DEPTH_COLOR: Record<Depth, number> = {
78 structure: SIGNATURE,
79 passage: ICE,
80 full: VIOLET,
81 search: 0x7fc8ff,
82 command: 0x8fa9ff,
83}
84
85function mix(a: number, b: number, t: number): number {
86 const k = Math.min(1, Math.max(0, t))
87 const ch = (s: number) => {
88 const x = (a >> s) & 255
89 const y = (b >> s) & 255
90 return Math.round(x + (y - x) * k) << s
91 }
92 return ch(16) | ch(8) | ch(0)
93}
94
95function ramp(stops: readonly number[], t: number): number {
96 const u = Math.min(1, Math.max(0, t)) * (stops.length - 1)
97 const i = Math.min(stops.length - 2, Math.floor(u))
98 return mix(stops[i] ?? 0, stops[i + 1] ?? 0, u - i)
99}
100const cycle = (stops: readonly number[], t: number) => ramp(stops, ((t % 1) + 1) % 1)
101
102// Budgets stay brand blue and warm only under real pressure.
103const pressure = (frac: number) =>
104 frac < 0.7 ? SIGNATURE : frac < 0.9 ? mix(SIGNATURE, AMBER, (frac - 0.7) / 0.2) : mix(AMBER, DANGER, (frac - 0.9) / 0.1)
105
106// ── raster cells ───────────────────────────────────────────────────────────
107const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
108
109function toBase64(bytes: Uint8Array): string {
110 let out = ''
111 for (let i = 0; i < bytes.length; i += 3) {
112 const a = bytes[i] ?? 0
113 const b = bytes[i + 1]
114 const c = bytes[i + 2]
115 const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0)
116 out += B64.charAt((n >> 18) & 63) + B64.charAt((n >> 12) & 63)
117 out += b === undefined ? '=' : B64.charAt((n >> 6) & 63)
118 out += c === undefined ? '=' : B64.charAt(n & 63)
119 }
120 return out
121}
122
123class Grid {
124 private readonly view: DataView
125 private readonly bytes: Uint8Array
126 constructor(
127 readonly cols: number,
128 readonly rows: number,
129 ) {
130 this.bytes = new Uint8Array(cols * rows * 12)
131 this.view = new DataView(this.bytes.buffer)
132 for (let i = 0; i < cols * rows; i++) this.put(i, 0x20, DEFAULT_BG, DEFAULT_BG)
133 }
134 private put(i: number, ch: number, fg: number, bg: number) {
135 this.view.setUint32(i * 12, ch, true)
136 this.view.setUint32(i * 12 + 4, fg, true)
137 this.view.setUint32(i * 12 + 8, bg, true)
138 }
139 set(x: number, y: number, ch: string, fg: number, bg = DEFAULT_BG) {
140 if (x < 0 || y < 0 || x >= this.cols || y >= this.rows) return
141 this.put(y * this.cols + x, ch.charCodeAt(0), fg, bg)
142 }
143 encode(): string {
144 return toBase64(this.bytes)
145 }
146}
147
148// The handoff line: sources on the left, Claude on the right, the gateway ◆ in
149// between. While Claude works the line breathes in brand colours; every call
150// travels it as a light — governed calls pass through the gate, direct calls
151// (Claude's own tools) run past it dimmed, failures turn red.
152function handoffCells(cols: number, tick: number, feed: readonly FeedItem[], now: number, isWorking: boolean): string {
153 const g = new Grid(cols, 1)
154 const gate = Math.floor(cols * 0.5)
155 const breath = (Math.sin(tick * 0.09) + 1) / 2
156 for (let x = 0; x < cols; x++) {
157 const base = isWorking
158 ? mix(HAIRLINE, cycle(BRAND_SWEEP, x / cols / 1.6 - tick * 0.004), 0.3 + breath * 0.3)
159 : HAIRLINE
160 g.set(x, 0, '─', base)
161 }
162 const gatePulse = isWorking ? (Math.sin(tick * 0.25) + 1) / 2 : 0
163 const draw = (x: number, color: number, isHead: boolean) => {
164 const at = Math.round(x)
165 g.set(at, 0, isHead ? '●' : '━', color)
166 if (isHead) {
167 g.set(at - 1, 0, '━', mix(color, HAIRLINE, 0.35))
168 g.set(at - 2, 0, '─', mix(color, HAIRLINE, 0.65))
169 }
170 }
171 for (const item of feed) {
172 const color = item.isError ? DANGER : item.governed ? ICE : SECONDARY
173 if (item.ms === undefined) {
174 const age = now - item.startedAt
175 // Direct calls never enter the gate: they cross the whole line.
176 if (!item.governed) {
177 if (age < PACKET_IN_MS + PACKET_OUT_MS) draw(((age / (PACKET_IN_MS + PACKET_OUT_MS)) % 1) * (cols - 1), color, true)
178 } else if (age < PACKET_IN_MS) draw((age / PACKET_IN_MS) * gate, color, true)
179 continue
180 }
181 const age = now - (item.startedAt + item.ms)
182 if (age < 0 || age > PACKET_OUT_MS) continue
183 const from = item.governed ? gate : (age / PACKET_OUT_MS) * gate
184 draw(from + ((cols - 1 - from) * age) / PACKET_OUT_MS, color, true)
185 }
186 const waiting = feed.some(f => f.governed && f.ms === undefined && now - f.startedAt >= PACKET_IN_MS)
187 g.set(gate, 0, '◆', waiting ? mix(SIGNATURE, FOREGROUND, gatePulse) : isWorking ? mix(SIGNATURE, ICE, gatePulse * 0.6) : BLUE_FIELD)
188 return g.encode()
189}
190
191// A light that sweeps once across the band as a turn card opens.
192function sweepCells(cols: number, progress: number, tick: number): string {
193 const g = new Grid(cols, 1)
194 const head = progress * (cols + 12) - 6
195 for (let x = 0; x < cols; x++) {
196 const near = Math.max(0, 1 - Math.abs(x - head) / 8)
197 const base = cycle(BRAND_SWEEP, x / cols / 1.5 - tick * 0.01)
198 g.set(x, 0, '━', mix(mix(HAIRLINE, base, 0.75), FOREGROUND, near))
199 }
200 return g.encode()
201}
202
203// Twinkling field for milestones: deterministic per cell, phased by the tick.
204function sparkleCells(cols: number, tick: number, seed: number): string {
205 const g = new Grid(cols, 1)
206 const glyphs = ['·', '✧', '✦', '✧', '·']
207 for (let x = 0; x < cols; x++) {
208 const h = Math.sin((x + 1) * 12.9898 + seed * 78.233) * 43758.5453
209 const r = h - Math.floor(h)
210 if (r < 0.55) continue
211 const phase = (Math.sin(tick * 0.35 + r * 40) + 1) / 2
212 g.set(x, 0, glyphs[Math.floor(phase * (glyphs.length - 1) + 0.5)] ?? '·', mix(BLUE_FIELD, r > 0.8 ? ICE : SIGNATURE, phase))
213 }
214 return g.encode()
215}
216
217// 4×7 display figures, folded into half blocks: four terminal rows.
218const FONT: Record<string, readonly string[]> = {
219 '0': ['.##.', '#..#', '#..#', '#..#', '#..#', '#..#', '.##.'],
220 '1': ['.#..', '##..', '.#..', '.#..', '.#..', '.#..', '###.'],
221 '2': ['.##.', '#..#', '...#', '..#.', '.#..', '#...', '####'],
222 '3': ['###.', '...#', '...#', '.##.', '...#', '...#', '###.'],
223 '4': ['#..#', '#..#', '#..#', '####', '...#', '...#', '...#'],
224 '5': ['####', '#...', '###.', '...#', '...#', '#..#', '.##.'],
225 '6': ['.##.', '#...', '#...', '###.', '#..#', '#..#', '.##.'],
226 '7': ['####', '...#', '..#.', '..#.', '.#..', '.#..', '.#..'],
227 '8': ['.##.', '#..#', '#..#', '.##.', '#..#', '#..#', '.##.'],
228 '9': ['.##.', '#..#', '#..#', '.###', '...#', '...#', '.##.'],
229 '.': ['.', '.', '.', '.', '.', '.', '#'],
230 K: ['#..#', '#.#.', '##..', '#...', '##..', '#.#.', '#..#'],
231 M: ['#...#', '##.##', '#.#.#', '#...#', '#...#', '#...#', '#...#'],
232 B: ['###.', '#..#', '#..#', '###.', '#..#', '#..#', '###.'],
233}
234const FIGURE_ROWS = 4
235const figureWidth = (text: string) => [...text].reduce((w, ch) => w + (FONT[ch]?.[0]?.length ?? 0) + 1, -1)
236
237// A display figure: a slow brand sweep runs across it; brighter while it counts.
238function figureCells(text: string, cols: number, phase: number, lift: number): string {
239 const g = new Grid(cols, FIGURE_ROWS)
240 const width = Math.max(8, figureWidth(text))
241 let x0 = 0
242 for (const ch of text) {
243 const glyph = FONT[ch]
244 if (!glyph) continue
245 const w = glyph[0]?.length ?? 0
246 for (let x = 0; x < w; x++) {
247 const color = mix(cycle(BRAND_SWEEP, (x0 + x) / width / 2.2 - phase), FOREGROUND, lift)
248 for (let r = 0; r < FIGURE_ROWS; r++) {
249 const top = glyph[r * 2]?.charAt(x) === '#'
250 const bottom = glyph[r * 2 + 1]?.charAt(x) === '#'
251 const cell = top && bottom ? '█' : top ? '▀' : bottom ? '▄' : ''
252 if (cell) g.set(x0 + x, r, cell, color)
253 }
254 }
255 x0 += w + 1
256 }
257 return g.encode()
258}
259
260const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
261
262// Meter: fractional blocks on a dim track, a gradient along the fill.
263function meterCells(cols: number, frac: number, color: (t: number) => number): string {
264 const g = new Grid(cols, 1)
265 const filled = Math.min(1, Math.max(0, frac)) * cols
266 const full = Math.floor(filled)
267 const part = Math.floor((filled - full) * 8)
268 for (let x = 0; x < cols; x++) {
269 const c = color(x / Math.max(1, cols - 1))
270 if (x < full) g.set(x, 0, '█', c)
271 else if (x === full && part > 0) g.set(x, 0, EIGHTHS[part] ?? '▏', c, PANEL)
272 else g.set(x, 0, '█', PANEL)
273 }
274 return g.encode()
275}
276
277// The depth mix: one bar, a segment per read depth in its colour.
278function mixCells(cols: number, counts: Record<Depth, number>): string {
279 const g = new Grid(cols, 1)
280 const total = DEPTHS.reduce((n, d) => n + counts[d], 0)
281 if (total === 0) {
282 for (let x = 0; x < cols; x++) g.set(x, 0, '█', PANEL)
283 return g.encode()
284 }
285 let x = 0
286 DEPTHS.forEach((d, i) => {
287 const isLast = i === DEPTHS.length - 1
288 const width = isLast ? cols - x : Math.round((counts[d] / total) * cols)
289 for (let k = 0; k < width && x < cols; k++, x++) g.set(x, 0, '█', DEPTH_COLOR[d])
290 })
291 return g.encode()
292}
293
294const LEVELS = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
295
296export type CurvePoint = { at: number; saved: number; raw?: number }
297
298// The value a running total held at time `t`: the last sample at or before it.
299function stepAt(points: readonly CurvePoint[], t: number, pick: (p: CurvePoint) => number | undefined): number {
300 let value = 0
301 for (const p of points) {
302 if (p.at > t) break
303 value = pick(p) ?? value
304 }
305 return value
306}
307
308// The saving curve, true to time: x runs from the session's first sample to
309// now, y from zero to the largest total, so a column is a slice of wall time
310// and a height is a token count. The raw total sits behind as a dim envelope;
311// "kept out" fills in front of it, rising from blue field to ice, so the gap
312// between them is what Claude still received. Columns in which lean-ctx kept
313// tokens out are lit; the newest one breathes while Claude works.
314export function curveCells(cols: number, rows: number, points: readonly CurvePoint[], now: number, pulse: number): string {
315 const g = new Grid(cols, rows)
316 const start = points[0]?.at ?? now
317 const span = Math.max(60_000, now - start)
318 const timeAt = (x: number) => start + ((x + 1) / cols) * span
319 const saved = Array.from({ length: cols }, (_, x) => stepAt(points, timeAt(x), p => p.saved))
320 const raw = Array.from({ length: cols }, (_, x) => Math.max(saved[x] ?? 0, stepAt(points, timeAt(x), p => p.raw)))
321 const top = Math.max(1, ...raw, ...saved)
322 const steps = rows * 8
323 const eighths = (v: number) => (v <= 0 ? 0 : Math.max(1, Math.round((v / top) * steps)))
324 const envelope = mix(PANEL, BLUE_FIELD, 0.7)
325 for (let x = 0; x < cols; x++) {
326 const keptH = eighths(saved[x] ?? 0)
327 const rawH = eighths(raw[x] ?? 0)
328 const gained = (saved[x] ?? 0) > (x > 0 ? (saved[x - 1] ?? 0) : 0)
329 const isLast = x === cols - 1
330 for (let r = 0; r < rows; r++) {
331 const y = rows - 1 - r
332 const kept = Math.min(8, Math.max(0, keptH - r * 8))
333 const behind = Math.min(8, Math.max(0, rawH - r * 8))
334 if (kept === 0 && behind === 0) {
335 if (r === 0) g.set(x, y, '▁', HAIRLINE)
336 continue
337 }
338 let color = ramp(DATA, (r * 8 + kept) / steps)
339 if (gained && r * 8 + kept >= keptH) color = mix(color, ICE, 0.55)
340 if (isLast) color = mix(color, FOREGROUND, 0.25 + pulse * 0.55)
341 // A partial "kept" block sits on the raw envelope only where raw fills
342 // the whole cell; a cell cannot show two partial heights, and drawing
343 // the envelope there would overstate raw.
344 const bg = behind >= 8 ? envelope : DEFAULT_BG
345 if (kept === 0) g.set(x, y, LEVELS[behind - 1] ?? '█', envelope)
346 else g.set(x, y, LEVELS[kept - 1] ?? '█', color, kept < 8 ? bg : DEFAULT_BG)
347 }
348 }
349 return g.encode()
350}
351
352// What a stretch of the curve adds: the gain over the last `windowMs`.
353export function recentGain(points: readonly CurvePoint[], now: number, windowMs: number): number {
354 const latest = points.at(-1)?.saved ?? 0
355 return Math.max(0, latest - stepAt(points, now - windowMs, p => p.saved))
356}
357
358// ── formatting (lean-ctx's own style: 49.1K, 1.2M) ─────────────────────────
359function compact(n: number): string {
360 const a = Math.abs(n)
361 const f = (v: number, s: string) => `${v >= 100 ? v.toFixed(0) : v.toFixed(1)}${s}`
362 if (a >= 1e9) return f(n / 1e9, 'B')
363 if (a >= 1e6) return f(n / 1e6, 'M')
364 if (a >= 1e3) return f(n / 1e3, 'K')
365 return Math.round(n).toString()
366}
367const grouped = (n: number) => Math.round(n).toLocaleString('en-US')
368const pct = (n: number | undefined) => (n === undefined ? '—' : `${Math.round(n)}%`)
369const dur = (ms: number) => (ms < 1000 ? `${ms}ms` : ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms / 60_000)}m`)
370// The engine's own turn-duration style: 3s, 1m 4s.
371function clock(ms: number): string {
372 const s = Math.max(0, Math.round(ms / 1000))
373 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`
374}
375function ago(ms: number): string {
376 const s = Math.max(0, Math.round(ms / 1000))
377 return s < 60 ? `${s}s ago` : s < 3600 ? `${Math.round(s / 60)}m ago` : `${Math.round(s / 3600)}h ago`
378}
379function span(ms: number): string {
380 const m = Math.max(0, Math.round(ms / 60_000))
381 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
382}
383const plural = (n: number, one: string, many: string) => `${compact(n)} ${n === 1 ? one : many}`
384
385function shortTool(tool: string): string {
386 return /^mcp__.+?__(.+)$/.exec(tool)?.[1] ?? tool
387}
388
389function tail(path: string): string {
390 return path.split('/').filter(Boolean).at(-1) ?? path
391}
392
393type Rec = Record<string, unknown>
394const isRec = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
395const num = (r: Rec, k: string) => (typeof r[k] === 'number' ? (r[k] as number) : 0)
396const str = (r: Rec, k: string) => (typeof r[k] === 'string' ? (r[k] as string) : undefined)
397
398function describe(args: Rec): string {
399 for (const key of ['path', 'file_path', 'command', 'pattern', 'query', 'task', 'symbol', 'url', 'description', 'prompt']) {
400 const v = args[key]
401 if (typeof v !== 'string' || v.length === 0) continue
402 const line = v.split('\n')[0] ?? ''
403 return key.endsWith('path') ? tail(line) : line.slice(0, 80)
404 }
405 const paths = args['paths']
406 if (Array.isArray(paths) && typeof paths[0] === 'string') return `${tail(paths[0])} +${paths.length - 1}`
407 return ''
408}
409
410// The read depth a call brought a source to Claude at, or none for calls that
411// bring no source (edits, sessions, agents). `ctx_read` modes map onto the
412// website's depths: structure (map, signatures), a passage (lines, reference,
413// task, compressed modes), or the whole file.
414function depthOf(tool: string, args: Rec): Depth | undefined {
415 const t = shortTool(tool)
416 if (/^(ctx_read|ctx_multi_read|Read)$/.test(t)) {
417 const mode = str(args, 'mode') ?? ''
418 if (/^(map|signatures)$/.test(mode)) return 'structure'
419 if (/^(lines|reference|task|aggressive|entropy|diff)/.test(mode)) return 'passage'
420 return 'full'
421 }
422 if (/search|grep|glob|tree|compose|callgraph|graph|semantic/i.test(t)) return 'search'
423 if (/shell|bash|execute/i.test(t)) return 'command'
424 return undefined
425}
426
427const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
428
429// ── lean-ctx value snapshots ───────────────────────────────────────────────
430function parseSnap(text: string): ValueSnap | undefined {
431 const r: unknown = JSON.parse(text)
432 if (!isRec(r)) return undefined
433 const sessionId = str(r, 'session_id')
434 const projectRoot = str(r, 'project_root')
435 if (!sessionId || !projectRoot) return undefined
436 const sec = isRec(r['security']) ? r['security'] : {}
437 return {
438 sessionId,
439 projectRoot,
440 hostPid: typeof r['host_pid'] === 'number' ? (r['host_pid'] as number) : undefined,
441 startedAt: str(r, 'started_at'),
442 updatedAt: str(r, 'updated_at'),
443 toolCalls: num(r, 'tool_calls'),
444 tokensInput: num(r, 'tokens_input'),
445 tokensSaved: num(r, 'tokens_saved'),
446 cacheHits: num(r, 'cache_hits'),
447 filesRead: num(r, 'files_read'),
448 commandsRun: num(r, 'commands_run'),
449 secretsRedacted: num(sec, 'secrets_redacted'),
450 shellBlocked: num(sec, 'shell_blocked'),
451 pathBlocked: num(sec, 'path_blocked'),
452 injectionFlagged: num(sec, 'injection_flagged'),
453 }
454}
455
456// One spelling per path: Windows hands out backslashes, either drive-letter
457// case and sometimes the `\\?\` verbatim prefix (#2077).
458const normPath = (p: string) => {
459 const s = p.replace(/^\\\\\?\\/, '').replace(/\\/g, '/').replace(/\/+$/, '')
460 return /^[a-z]:(\/|$)/i.test(s) ? s.toLowerCase() : s
461}
462const inProject = (cwd: string, root: string) => {
463 const [c, r] = [normPath(cwd), normPath(root)]
464 return c === r || c.startsWith(`${r}/`)
465}
466const newest = (snaps: ValueSnap[]) => [...snaps].sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))[0]
467
468const countersOf = (s: ValueSnap | undefined) => ({
469 sessionId: s?.sessionId,
470 saved: s?.tokensSaved ?? 0,
471 calls: s?.toolCalls ?? 0,
472 files: s?.filesRead ?? 0,
473 commands: s?.commandsRun ?? 0,
474})
475
476// ── module state (a reload starts it over; what drawing reads lives in $.state) ──
477let valueDir: string | undefined
478let cwd: string | undefined
479let refreshing = false
480let refreshAgain = false
481let pendingRefresh: { cancel: () => void } | undefined
482let frames: { cancel: () => void } | undefined
483let isWorking = false
484let overlayUntil = 0
485let packetsUntil = 0
486let proving = false
487// The token figure counts toward the session total.
488let shown = -1
489let target = 0
490
491// $.state outlives reloads: fill in anything an older build left out.
492async function readBoard($: EngineInterface): Promise<Board> {
493 const b: Partial<Board> = (await read($, board)) ?? {}
494 return {
495 ...b,
496 milestone: typeof b.milestone === 'number' ? b.milestone : 0,
497 turns: Array.isArray(b.turns) ? b.turns : [],
498 isWorking: b.isWorking === true,
499 leanRunning: typeof b.leanRunning === 'number' ? Math.max(0, b.leanRunning) : 0,
500 feed: Array.isArray(b.feed) ? b.feed : [],
501 sources: isRec(b.sources) ? (b.sources as Record<string, SourceStat>) : {},
502 turnSeen: isRec(b.turnSeen) ? b.turnSeen : { sources: 0, governed: 0, structure: 0 },
503 celebrated: Array.isArray(b.celebrated) ? b.celebrated : [],
504 }
505}
506
507// Our ancestors, nearest first, as lean-ctx sees them from the process that
508// runs it: the agent is among them, whether hooks run in it or in a worker.
509// lean-ctx walks the tree natively; `ps` and `sh` are missing on Windows (#2077).
510let chain: number[] | undefined
511
512// The data directory lean-ctx reports itself, so XDG and custom homes hold,
513// and the ancestors whose sessions serve this conversation.
514async function locate($: EngineInterface): Promise<{ dir: string; cwd: string; hosts: number[] }> {
515 if (!valueDir || !chain) {
516 const { exitCode, stdout } = await $.process.run(['lean-ctx', 'prompt-segment', '--json'], { timeoutMs: 15_000 })
517 if (exitCode !== 0) throw new Error('lean-ctx prompt-segment failed')
518 const parsed: unknown = JSON.parse(stdout)
519 const watch = isRec(parsed) ? str(parsed, 'watch') : undefined
520 if (!watch) throw new Error('lean-ctx reports no value directory')
521 const hosts = isRec(parsed) && Array.isArray(parsed['hosts']) ? parsed['hosts'] : []
522 valueDir = watch.replace(/[\\/]projects[\\/]?$/, '')
523 chain = hosts.filter((h): h is number => typeof h === 'number')
524 }
525 cwd ??= await $.session.cwd()
526 return { dir: valueDir, cwd, hosts: chain }
527}
528
529function scheduleRefresh($: EngineInterface) {
530 if (pendingRefresh) return
531 pendingRefresh = $.clock.after(REFRESH_AFTER_TOOL_MS, () => {
532 pendingRefresh = undefined
533 void refresh($).catch(() => {})
534 })
535}
536
537// A gateway first worth a moment, celebrated once per conversation.
538function gatewayFirst(prev: ValueSnap | undefined, snap: ValueSnap, sources: number, done: string[]): { key: string; title: string; detail: string } | undefined {
539 const firsts = [
540 {
541 key: 'first-secret',
542 hit: snap.secretsRedacted > 0 && (prev?.secretsRedacted ?? 0) === 0,
543 title: 'FIRST SECRET KEPT OUT OF CLAUDE’S CONTEXT',
544 detail: 'Redacted before the handoff · see lean-ctx value',
545 },
546 {
547 key: 'first-block',
548 hit: snap.shellBlocked + snap.pathBlocked > 0 && (prev ? prev.shellBlocked + prev.pathBlocked : 0) === 0,
549 title: 'FIRST READ STOPPED AT THE GATE',
550 detail: 'A command or path outside your rules was blocked',
551 },
552 ...SOURCE_MILESTONES.map(n => ({
553 key: `sources-${n}`,
554 hit: sources >= n,
555 title: `${grouped(n)} SOURCES THROUGH THE GATEWAY`,
556 detail: 'Each one selected, checked and recorded',
557 })),
558 ]
559 return firsts.find(f => f.hit && !done.includes(f.key))
560}
561
562// Reads the snapshot of the lean-ctx session serving this conversation (the
563// same one lean-ctx's status line shows), keeps its history, raises milestones.
564async function refresh($: EngineInterface) {
565 if (refreshing) {
566 refreshAgain = true
567 return
568 }
569 refreshing = true
570 try {
571 // Claude's side (window, cost) rides along: refresh only runs from timers.
572 await refreshUsage($)
573 const where = await locate($)
574 const sessions = `${where.dir}/sessions`
575 const now = Date.now()
576 const entries = (await $.fs.list(sessions)).filter(
577 e => e.kind === 'file' && e.name.endsWith('.json') && now - e.mtimeMs < ACTIVE_MS,
578 )
579 const snaps: ValueSnap[] = []
580 for (const e of entries) {
581 try {
582 const s = parseSnap(await $.fs.read(`${sessions}/${e.name}`))
583 if (s && inProject(where.cwd, s.projectRoot)) snaps.push(s)
584 } catch {
585 // a snapshot mid-write or gone: skip it this round
586 }
587 }
588 // Nearest ancestor first: the session whose server recorded it as `host_pid`.
589 let snap: ValueSnap | undefined
590 for (const host of where.hosts) {
591 snap = newest(snaps.filter(s => s.hostPid === host))
592 if (snap) break
593 }
594 if (!snap) {
595 chain = undefined // a reconnect starts a new server: look again next time
596 return
597 }
598
599 const b = await readBoard($)
600 const at = Date.now()
601 const governedSources = Object.values(b.sources).filter(s => s.governed).length
602 // The first look only records where the session stands; later crossings celebrate.
603 const isLive = b.milestone > 0 || b.turns.length > 0 || b.snap !== undefined
604 const reached = TOKEN_MILESTONES.filter(m => m <= snap.tokensSaved).pop() ?? 0
605 const first = isLive && b.snap?.sessionId === snap.sessionId ? gatewayFirst(b.snap, snap, governedSources, b.celebrated) : undefined
606 let celebration: Overlay | undefined
607 if (first) {
608 celebration = { kind: 'milestone', title: first.title, detail: first.detail, at }
609 } else if (reached > b.milestone && isLive) {
610 celebration = {
611 kind: 'milestone',
612 title: `${compact(reached)} TOKENS KEPT OUT OF CONTEXT`,
613 detail: 'Selected, not sent · numbers from lean-ctx value',
614 at,
615 }
616 }
617 await update($, board, x => {
618 const same = x.history?.sessionId === snap.sessionId ? x.history.points : []
619 const last = same.at(-1)
620 // A point per change, and one a minute while flat, so time stays honest.
621 const isNew =
622 !last || last.saved !== snap.tokensSaved || last.raw !== snap.tokensInput || at - last.at >= 60_000
623 const points = isNew ? [...same, { at, saved: snap.tokensSaved, raw: snap.tokensInput }].slice(-HISTORY_KEPT) : same
624 return {
625 ...x,
626 snap,
627 history: { sessionId: snap.sessionId, points },
628 milestone: Math.max(x.milestone ?? 0, reached),
629 celebrated: first ? [...(Array.isArray(x.celebrated) ? x.celebrated : []), first.key] : x.celebrated,
630 overlay: celebration ?? x.overlay,
631 }
632 })
633 if (shown < 0) shown = 0
634 target = snap.tokensSaved
635 if (celebration && cardsEnabled) {
636 overlayUntil = at + MILESTONE_OVERLAY_MS
637 const title = celebration.kind === 'milestone' ? celebration.title : ''
638 $.ui.toast(`★ LeanCTX · ${title.toLowerCase()}`, { timeoutMs: 6000 })
639 }
640 if (celebration || shown !== target) startFrames($)
641 } catch {
642 // the cockpit is cosmetic; lean-ctx's status line still carries the numbers
643 } finally {
644 refreshing = false
645 if (refreshAgain) {
646 refreshAgain = false
647 scheduleRefresh($)
648 }
649 }
650}
651
652// Prove: re-derive the evidence from both hash chains, the way `lean-ctx value` does.
653async function prove($: EngineInterface) {
654 if (proving) return
655 proving = true
656 const before = (await readBoard($)).proof
657 await update($, board, x => ({ ...x, proof: { ...(x.proof ?? {}), isRunning: true } }))
658 try {
659 const b = await readBoard($)
660 const argv = ['lean-ctx', 'value', '--json', ...(b.snap ? ['--session', b.snap.sessionId] : [])]
661 const { stdout } = await $.process.run(argv, { timeoutMs: PROVE_TIMEOUT_MS })
662 const r: unknown = JSON.parse(stdout)
663 if (!isRec(r)) throw new Error('lean-ctx value returned no report')
664 const ledger = isRec(r['ledger']) ? r['ledger'] : {}
665 const audit = isRec(r['audit']) ? r['audit'] : {}
666 const evidence = isRec(r['ledger_evidence']) ? r['ledger_evidence'] : {}
667 const proof: Proof = {
668 isRunning: false,
669 checkedAt: Date.now(),
670 ledgerEntries: num(ledger, 'entries'),
671 ledgerIntact: ledger['intact'] === true,
672 auditEntries: num(audit, 'entries'),
673 auditIntact: audit['intact'] === true,
674 sessionEntries: num(evidence, 'entries'),
675 }
676 await update($, board, x => ({ ...x, proof }))
677 } catch (err) {
678 const message = err instanceof Error ? err.message : String(err)
679 await update($, board, x => ({ ...x, proof: { ...(before ?? {}), isRunning: false, error: message } }))
680 } finally {
681 proving = false
682 }
683}
684
685async function refreshUsage($: EngineInterface) {
686 try {
687 const u = await $.session.usage()
688 await update($, board, x => ({
689 ...x,
690 contextPct: u.context.percent,
691 contextTokens: u.context.tokens,
692 window: u.context.window,
693 costUsd: u.cost?.usd ?? x.costUsd,
694 }))
695 } catch {
696 // usage is cosmetic; never disturb the session for it
697 }
698}
699
700// The turn just ended: sum up what lean-ctx did and what Claude saw. Runs from a
701// `$.clock.after` timer (scheduled by the `turn.complete` hook) once lean-ctx's
702// last write is in: work that outlives a hook's dispatch must not hang off the
703// hook itself. Without a snapshot the card still shows, with the turn alone.
704async function finishTurn($: EngineInterface, durationMs: number) {
705 await refresh($).catch(() => {})
706 const b = await readBoard($)
707 const now = countersOf(b.snap)
708 // A turn that spans a session change (a reconnect) counts from the new
709 // session's start, never as the difference of two sessions' counters.
710 const start =
711 b.turnStart && b.turnStart.sessionId === now.sessionId
712 ? b.turnStart
713 : { sessionId: now.sessionId, saved: 0, calls: 0, files: 0, commands: 0 }
714 const turn: TurnStat = {
715 n: b.turns.length + 1,
716 durationMs,
717 saved: Math.max(0, now.saved - start.saved),
718 calls: Math.max(0, now.calls - start.calls),
719 files: Math.max(0, now.files - start.files),
720 commands: Math.max(0, now.commands - start.commands),
721 sources: b.turnSeen.sources,
722 governed: b.turnSeen.governed,
723 structure: b.turnSeen.structure,
724 at: Date.now(),
725 }
726 await update($, board, x => {
727 // A milestone on show keeps the band; the turn card does not cut it short.
728 const isMilestoneShowing = x.overlay?.kind === 'milestone' && Date.now() - x.overlay.at < MILESTONE_OVERLAY_MS
729 const overlay: Overlay | undefined = isMilestoneShowing ? x.overlay : { kind: 'turn', turn, at: Date.now() }
730 const turns = [...(Array.isArray(x.turns) ? x.turns : []), turn].slice(-TURNS_KEPT)
731 return { ...x, turns, overlay }
732 })
733 if (cardsEnabled) overlayUntil = Math.max(overlayUntil, Date.now() + TURN_OVERLAY_MS)
734 startFrames($)
735}
736
737// Tool calls as the conversation records them: an assistant row's `tool_use`
738// blocks start calls (with the source and depth they bring), a `tool_result`
739// ends one. Reading rows keeps the cockpit off the tool chain the rest of the
740// mod shapes.
741async function observeRow($: EngineInterface, row: Rec) {
742 const message = isRec(row['message']) ? row['message'] : {}
743 const blocks = (Array.isArray(message['content']) ? message['content'] : []).filter(isRec)
744 const now = Date.now()
745 const started: FeedItem[] = []
746 const ended = new Map<string, boolean>()
747 for (const block of blocks) {
748 if (block['type'] === 'tool_use' && typeof block['id'] === 'string' && typeof block['name'] === 'string') {
749 const input = isRec(block['input']) ? block['input'] : {}
750 started.push({
751 id: block['id'],
752 tool: block['name'],
753 label: describe(input),
754 isSubagent: typeof row['agentId'] === 'string',
755 startedAt: now,
756 depth: depthOf(block['name'], input),
757 governed: LEAN_CTX_TOOL.test(block['name']),
758 })
759 } else if (block['type'] === 'tool_result' && typeof block['tool_use_id'] === 'string') {
760 ended.set(block['tool_use_id'], block['is_error'] === true)
761 }
762 }
763 if (started.length === 0 && ended.size === 0) return
764 await update($, board, x => {
765 const feed = [...(Array.isArray(x.feed) ? x.feed : []), ...started].slice(-FEED_KEPT)
766 let running = (x.leanRunning ?? 0) + started.filter(f => f.governed).length
767 const done = feed.map(f => {
768 const isError = ended.get(f.id)
769 if (isError === undefined || f.ms !== undefined) return f
770 if (f.governed) running -= 1
771 return { ...f, ms: now - f.startedAt, isError }
772 })
773 // Sources Claude saw: one entry per path / pattern / command, deepest read kept.
774 const sources = { ...(isRec(x.sources) ? (x.sources as Record<string, SourceStat>) : {}) }
775 const seen = isRec(x.turnSeen) ? { ...x.turnSeen } : { sources: 0, governed: 0, structure: 0 }
776 for (const f of started) {
777 if (!f.depth || !f.label) continue
778 const key = `${f.depth === 'command' ? 'cmd' : 'src'}:${f.label}`
779 const prev = sources[key]
780 sources[key] = { label: f.label, depth: f.depth, governed: f.governed || (prev?.governed ?? false), n: (prev?.n ?? 0) + 1, last: now }
781 seen.sources += 1
782 if (f.governed) seen.governed += 1
783 if (f.depth === 'structure') seen.structure += 1
784 }
785 const kept = Object.entries(sources)
786 .sort(([, a], [, b]) => b.last - a.last)
787 .slice(0, SOURCES_KEPT)
788 return { ...x, feed: done, leanRunning: Math.max(0, running), sources: Object.fromEntries(kept), turnSeen: seen }
789 })
790 // Keep the handoff line moving while calls travel it.
791 packetsUntil = now + PACKET_IN_MS + PACKET_OUT_MS
792 startFrames($)
793 if (ended.size > 0) scheduleRefresh($)
794}
795
796// One frame clock for every effect; it runs only while something moves.
797function startFrames($: EngineInterface) {
798 if (frames) return
799 frames = $.clock.every(FRAME_MS, () => {
800 if (shown >= 0 && shown !== target) {
801 const gap = target - shown
802 const step = Math.sign(gap) * Math.max(1, Math.abs(gap) * COUNT_EASE)
803 shown = Math.abs(step) >= Math.abs(gap) ? target : Math.round(shown + step)
804 }
805 const now = Date.now()
806 if (!isWorking && !proving && shown === target && now > overlayUntil && now > packetsUntil) {
807 frames?.cancel()
808 frames = undefined
809 }
810 void update($, frame, f => ({ tick: (f?.tick ?? 0) + 1 })).catch(() => {})
811 })
812}
813
814// Whether the sidebar opens with a session: the `cockpit_panel` option, then
815// `/cockpit on|off` (#2057). The pulse line, spinner and turn rows stay either way.
816let panelEnabled = true
817// The band above the prompt while Claude works (`cockpit_pulse_line`) and the
818// turn and milestone cards there (`cockpit_turn_cards`), each `/cockpit pulse|cards
819// on|off`. The sidebar keeps the same turns and milestones; the spinner stays.
820let pulseEnabled = true
821let cardsEnabled = true
822// The proof clock re-verifies receipts only the sidebar shows (~8 s of work).
823let proofClock: { cancel: () => void } | undefined
824
825function startProofClock($: EngineInterface) {
826 if (proofClock) return
827 $.clock.after(PROVE_FIRST_MS, () => void prove($).catch(() => {}))
828 proofClock = $.clock.every(PROVE_MS, () => void prove($).catch(() => {}))
829}
830
831function stopProofClock() {
832 proofClock?.cancel()
833 proofClock = undefined
834}
835
836// Registers /cockpit, opens the sidebar unless it is turned off, and starts
837// the refresh clock (and, with the sidebar, the proof clock).
838async function cockpitStart($: EngineInterface): Promise<void> {
839 await $.command.register({
840 name: 'cockpit',
841 description: 'Open the LeanCTX cockpit; on/off keeps the sidebar open or closed, pulse/cards on|off the lines above the prompt',
842 argumentHint: '[on|off|pulse on|pulse off|cards on|cards off]',
843 immediate: true,
844 })
845 $.ui.status(undefined)
846 // Work that outlives this hook runs from timers, never off the hook itself.
847 $.clock.after(300, () => void refresh($).catch(() => {}))
848 $.clock.every(REFRESH_MS, () => void refresh($).catch(() => {}))
849 if (!panelEnabled) return
850 // Fire-and-forget, and never an unhandled rejection: a surface that draws
851 // no panes (or none yet) simply leaves the sidebar closed.
852 $.ui.open({ id: PANE, title: 'LeanCTX', columns: DOCK_COLUMNS }).catch(() => {})
853 startProofClock($)
854}
855
856// Stores a choice in the mod's option `option` (`cockpit_panel`, …) so new
857// sessions keep it; `false` when the setting could not be written.
858async function persistChoice($: EngineInterface, option: string, on: boolean): Promise<boolean> {
859 try {
860 const row = (await $.config.list()).find(r => r.key.endsWith(`.${option}`))
861 if (!row) return false
862 const { deny } = await $.config.set({ key: row.key, value: on })
863 return deny === undefined
864 } catch {
865 return false
866 }
867}
868
869const COCKPIT_USAGE =
870 'Usage: /cockpit opens the sidebar · /cockpit on|off keeps it open or closed in new sessions · ' +
871 '/cockpit pulse on|off the line above the prompt while Claude works · /cockpit cards on|off the turn and milestone cards.'
872
873// `/cockpit pulse|cards on|off`: shows or hides one of the lines above the
874// prompt, now and in new sessions.
875async function runSurfaceCommand($: EngineInterface, surface: 'pulse' | 'cards', on: boolean): Promise<string> {
876 const [option, name] =
877 surface === 'pulse' ? ['cockpit_pulse_line', 'pulse line'] : ['cockpit_turn_cards', 'turn and milestone cards']
878 if (surface === 'pulse') pulseEnabled = on
879 else cardsEnabled = on
880 // Redraw now, so a card or band on show goes away (or a hidden one returns).
881 startFrames($)
882 const kept = await persistChoice($, option, on)
883 const state = on ? 'on' : 'off'
884 const back = on ? '' : ` /cockpit ${surface} on brings it back.`
885 return kept
886 ? `LeanCTX ${name} ${state}, now and in new sessions.${back}`
887 : `LeanCTX ${name} ${state} for this session (the setting could not be saved; /config → lean-ctx).`
888}
889
890// `/cockpit [on|off]`: no argument opens the sidebar now; on/off also decides
891// whether it opens in new sessions. `pulse|cards on|off` go to runSurfaceCommand.
892async function runCockpitCommand($: EngineInterface, args: string): Promise<string> {
893 const words = args.trim().toLowerCase().split(/\s+/).filter(Boolean)
894 const [head, value] = words
895 if (head === 'pulse' || head === 'cards') {
896 if (words.length !== 2 || (value !== 'on' && value !== 'off')) return COCKPIT_USAGE
897 return runSurfaceCommand($, head, value === 'on')
898 }
899 const choice = words.join(' ')
900 if (choice === 'off') {
901 panelEnabled = false
902 stopProofClock()
903 await $.ui.close({ id: PANE }).catch(() => {})
904 const kept = await persistChoice($, 'cockpit_panel', false)
905 return kept
906 ? 'LeanCTX cockpit sidebar off: closed now and in new sessions. /cockpit on brings it back.'
907 : 'LeanCTX cockpit sidebar closed for this session (the setting could not be saved; /config → lean-ctx).'
908 }
909 if (choice !== '' && choice !== 'on') return COCKPIT_USAGE
910 const kept = choice === 'on' ? await persistChoice($, 'cockpit_panel', true) : true
911 if (choice === 'on') panelEnabled = true
912 const { isPlaced } = await $.ui.open({ id: PANE, title: 'LeanCTX', columns: DOCK_COLUMNS })
913 $.clock.after(0, () => void refresh($).catch(() => {}))
914 $.clock.after(0, () => void prove($).catch(() => {}))
915 if (panelEnabled) startProofClock($)
916 const opened = isPlaced ? 'LeanCTX cockpit opened.' : 'LeanCTX cockpit is waiting for room (fullscreen, ~110+ columns).'
917 if (choice !== 'on') return opened
918 return kept ? `${opened} It opens in new sessions again.` : `${opened} (The setting could not be saved; /config → lean-ctx.)`
919}
920
921// ── drawing helpers ────────────────────────────────────────────────────────
922type Ui = Elements['terminal']
923
924// Text with a soft light travelling through it (Charm-style shimmer).
925function shimmer(ui: Ui, text: string, tick: number, base: number, light: number, bold = false) {
926 const { Text } = ui
927 const head = (tick * 0.9) % (text.length + 14)
928 return (
929 <Text bold={bold}>
930 {[...text].map((ch, i) => (
931 <Text color={hex(mix(base, light, Math.max(0, 1 - Math.abs(i - head + 7) / 5)))}>{ch}</Text>
932 ))}
933 </Text>
934 )
935}
936
937// A pill: a short label on a filled ground, the way Lip Gloss badges sit.
938function pill(ui: Ui, text: string, fg: number, bg: number, bold = false) {
939 const { Text } = ui
940 return (
941 <Text color={hex(fg)} backgroundColor={hex(bg)} bold={bold}>
942 {` ${text} `}
943 </Text>
944 )
945}
946
947type Part = { node: RenderChildren; rows: number }
948const GAP: Part = { node: '', rows: 1 }
949
950// A panel, btop-style: the title sits in the top border (╭─┐TITLE┌──── meta ─╮),
951// a blank row of air inside top and bottom, and a blank row before the next.
952function panel(ui: Ui, width: number, title: string, meta: string, parts: Part[]) {
953 const { Box, Text } = ui
954 const inner = width - 4
955 const line = hex(HAIRLINE)
956 const metaText = meta ? ` ${meta} ` : ''
957 const fill = Math.max(1, width - 6 - title.length - metaText.length - 1)
958 const side = (rows: number) => <Text color={line}>{Array.from({ length: rows }, () => '│').join('\n')}</Text>
959 return (
960 <Box flexDirection="column" marginTop={1}>
961 <Text>
962 <Text color={line}>╭─┐</Text>
963 <Text bold color={hex(SIGNATURE)}>
964 {title}
965 </Text>
966 <Text color={line}>┌{'─'.repeat(fill)}</Text>
967 <Text color={hex(SECONDARY)}>{metaText}</Text>
968 <Text color={line}>─╮</Text>
969 </Text>
970 {[GAP, ...parts, GAP].map(p => (
971 <Box>
972 {side(p.rows)}
973 <Box width={inner + 2} paddingX={1} flexDirection="column">
974 {p.node === '' ? <Text> </Text> : p.node}
975 </Box>
976 {side(p.rows)}
977 </Box>
978 ))}
979 <Text color={line}>╰{'─'.repeat(width - 2)}╯</Text>
980 </Box>
981 )
982}
983
984// The handoff line with its two ends named: SOURCES ──◆── CLAUDE.
985function handoff(ui: Ui, key: string, cols: number, b: Board, tick: number, now: number) {
986 const { Box, Text, Raster } = ui
987 const lane = Math.max(8, cols - 16)
988 const ends = hex(b.isWorking ? SECONDARY : HAIRLINE)
989 return (
990 <Box>
991 <Text color={ends}>sources </Text>
992 <Raster key={key} columns={lane} rows={1} cells={handoffCells(lane, tick, b.feed, now, b.isWorking)} />
993 <Text color={ends}> claude</Text>
994 </Box>
995 )
996}
997
998// ── the cockpit ────────────────────────────────────────────────────────────
999// The mod's other parts that follow main-loop turns. A plugin registers one
1000// hook per event, and the cockpit owns `turn.start` / `turn.complete`.
1001export type TurnObserver = {
1002 onTurnStart?: () => void
1003 onMainTurnComplete?: () => void
1004}
1005
1006export function registerCockpit(
1007 on: On,
1008 turns: TurnObserver = {},
1009 options: { panel?: boolean; pulse?: boolean; cards?: boolean } = {},
1010): void {
1011 panelEnabled = options.panel !== false
1012 pulseEnabled = options.pulse !== false
1013 cardsEnabled = options.cards !== false
1014 // A matcher, because the mod's own `session.start` hook has none (one per
1015 // event and plugin); headless runs (`claude -p`) get no cockpit at all.
1016 on('session.start', { isInteractive: true }, async ($, e, next) => {
1017 try {
1018 await cockpitStart($)
1019 } catch {
1020 // the cockpit is cosmetic; the session starts regardless
1021 }
1022 return next(e)
1023 })
1024
1025 on('command.run', { command: 'cockpit' }, async ($, e) => ({ text: await runCockpitCommand($, e.args) }))
1026
1027 on('turn.start', async ($, e, next) => {
1028 turns.onTurnStart?.()
1029 try {
1030 isWorking = true
1031 const b = await readBoard($)
1032 await update($, board, x => ({
1033 ...x,
1034 isWorking: true,
1035 leanRunning: 0,
1036 turnStart: countersOf(b.snap),
1037 turnSeen: { sources: 0, governed: 0, structure: 0 },
1038 }))
1039 startFrames($)
1040 } catch {
1041 // the cockpit is cosmetic
1042 }
1043 return next(e)
1044 })
1045
1046 on('turn.complete', async ($, e, next) => {
1047 if (e.agentId) return next(e)
1048 turns.onMainTurnComplete?.()
1049 isWorking = false
1050 const usage = 'usage' in e ? e.usage : undefined
1051 await update($, board, x => {
1052 let cacheHitPct = x.cacheHitPct
1053 if (usage) {
1054 const total = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
1055 if (total > 0) cacheHitPct = (usage.cache_read_input_tokens / total) * 100
1056 }
1057 return { ...x, isWorking: false, leanRunning: 0, cacheHitPct }
1058 })
1059 if (!e.isAborted) {
1060 const durationMs = e.durationMs
1061 $.clock.after(REFRESH_AFTER_TOOL_MS, () => void finishTurn($, durationMs).catch(() => {}))
1062 }
1063 return next(e)
1064 })
1065
1066 // The row is stored first and handed back unchanged; the cockpit only reads it.
1067 on('session.append', async ($, e, next) => {
1068 const stored = await next(e)
1069 try {
1070 await observeRow($, e as unknown as Rec)
1071 } catch {
1072 // the cockpit is cosmetic
1073 }
1074 return stored
1075 })
1076
1077 // ── above the prompt: the handoff line while working; a card when a turn ends or a milestone falls
1078 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1079 if (e.props.hasSurvey || e.surface !== 'terminal') return next(e)
1080 // Read the frame before any early return: a hidden band stays subscribed,
1081 // so `/cockpit pulse|cards on` shows it again at once.
1082 const f = await read($, frame)
1083 const b = await readBoard($)
1084 const tick = f?.tick ?? 0
1085 const now = Date.now()
1086 const o = b.overlay
1087 const ui = $.ui.resolve(e)
1088 const { Box, Text, Raster } = ui
1089 const cols = Math.max(24, e.props.bodyColumns)
1090
1091 if (cardsEnabled && o?.kind === 'milestone' && now - o.at < MILESTONE_OVERLAY_MS && typeof o.title === 'string') {
1092 const title = `★ ${o.title} ★`
1093 return (
1094 <Box flexDirection="column">
1095 <Raster key="spark-a" columns={cols} rows={1} cells={sparkleCells(cols, tick, 1)} />
1096 <Box justifyContent="center">{shimmer(ui, title, tick, SIGNATURE, FOREGROUND, true)}</Box>
1097 <Box justifyContent="center">
1098 <Text color={hex(SECONDARY)}>LeanCTX · {o.detail}</Text>
1099 </Box>
1100 <Raster key="spark-b" columns={cols} rows={1} cells={sparkleCells(cols, tick + 7, 2)} />
1101 </Box>
1102 )
1103 }
1104
1105 if (cardsEnabled && o?.kind === 'turn' && now - o.at < TURN_OVERLAY_MS && !b.isWorking) {
1106 const t = o.turn
1107 const gap = <Text> </Text>
1108 return (
1109 <Box flexDirection="column">
1110 <Raster key="sweep" columns={cols} rows={1} cells={sweepCells(cols, Math.min(1, (now - o.at) / 900), tick)} />
1111 <Box>
1112 <Text bold color={hex(OK)}>
1113 ✓{' '}
1114 </Text>
1115 <Text bold color={hex(FOREGROUND)}>
1116 Turn {t.n}
1117 </Text>
1118 <Text color={hex(SECONDARY)}> · {clock(t.durationMs)} </Text>
1119 {t.sources > 0 ? pill(ui, `Claude saw ${plural(t.sources, 'source', 'sources')}`, CANVAS, SIGNATURE, true) : null}
1120 {t.sources > 0 && t.structure > 0 ? gap : null}
1121 {t.sources > 0 && t.structure > 0 ? pill(ui, `${t.structure} as structure`, FOREGROUND, PANEL) : null}
1122 {t.saved > 0 ? gap : null}
1123 {t.saved > 0 ? pill(ui, `▲ ${compact(t.saved)} tokens kept out`, FOREGROUND, BLUE_FIELD, true) : null}
1124 {t.sources === 0 && t.saved === 0 ? pill(ui, plural(t.calls, 'lean-ctx call', 'lean-ctx calls'), FOREGROUND, PANEL) : null}
1125 </Box>
1126 </Box>
1127 )
1128 }
1129
1130 // The handoff line sits on top; the rest of the chain still renders (#2142).
1131 if (pulseEnabled && b.isWorking) {
1132 const below = await next(e)
1133 return (
1134 <Box flexDirection="column">
1135 {handoff(ui, 'band-handoff', cols, b, tick, now)}
1136 {below}
1137 </Box>
1138 )
1139 }
1140 return next(e)
1141 })
1142
1143 // ── the spinner row: brand spinner, shimmering words, the turn's live gateway work
1144 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
1145 if (e.surface !== 'terminal') return next(e)
1146 const f = await read($, frame)
1147 const b = await readBoard($)
1148 const ui = $.ui.resolve(e)
1149 const { Box, Text } = ui
1150 const tick = f?.tick ?? 0
1151 const words = `${e.props.message ?? e.props.word}${e.props.suffix}`
1152 const start = b.turnStart
1153 const gained = start && b.snap && start.sessionId === b.snap.sessionId ? Math.max(0, b.snap.tokensSaved - start.saved) : 0
1154 const seen = b.turnSeen.sources
1155 return (
1156 <Box>
1157 <Text bold color={hex(cycle(BRAND_SWEEP, tick / 30))}>
1158 {SPINNER[tick % SPINNER.length]}{' '}
1159 </Text>
1160 {shimmer(ui, words, tick, SECONDARY, ICE)}
1161 {seen > 0 || gained > 0 ? <Text> </Text> : null}
1162 {seen > 0 ? pill(ui, `◆ ${plural(seen, 'source', 'sources')}`, FOREGROUND, PANEL) : null}
1163 {seen > 0 && gained > 0 ? <Text> </Text> : null}
1164 {gained > 0 ? pill(ui, `▲ ${compact(gained)} kept out`, FOREGROUND, BLUE_FIELD) : null}
1165 </Box>
1166 )
1167 })
1168
1169 // ── the "done in" row: keep the engine's words, add what passed the gateway that turn
1170 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
1171 if (e.surface !== 'terminal') return next(e)
1172 // Subscribed to the frame either way, so `/cockpit cards on` redraws it.
1173 await read($, frame)
1174 if (!cardsEnabled) return next(e)
1175 const b = await readBoard($)
1176 const turn = b.turns.find(t => Math.abs(t.durationMs - e.props.durationMs) < 1_000)
1177 if (!turn || (turn.saved === 0 && turn.calls === 0 && (turn.sources ?? 0) === 0)) return next(e)
1178 const { Box, Text } = $.ui.resolve(e)
1179 return (
1180 <Box>
1181 <Text color={hex(SECONDARY)}>
1182 ✻ {e.props.word} for {clock(e.props.durationMs)}
1183 </Text>
1184 <Text color={hex(HAIRLINE)}> │ </Text>
1185 <Text bold color={hex(SIGNATURE)}>
1186 ◆ LeanCTX
1187 </Text>
1188 <Text color={hex(SECONDARY)}>
1189 {(turn.sources ?? 0) > 0 ? ` Claude saw ${plural(turn.sources, 'source', 'sources')}` : ''}
1190 {turn.saved > 0 ? (
1191 <Text>
1192 {(turn.sources ?? 0) > 0 ? ' ·' : ''} <Text bold color={hex(FOREGROUND)}>{compact(turn.saved)}</Text> tokens kept out
1193 </Text>
1194 ) : null}
1195 </Text>
1196 </Box>
1197 )
1198 })
1199
1200 // ── the docked sidebar: what Claude saw, tokens, the two checks, receiptshooks/render.tsx 297 lines1// SPDX-License-Identifier: Apache-2.0
2//
3// Draws lean-ctx results the way Claude Code draws its own: ctx_patch evidence
4// through the engine's diff renderer, ctx_read code and ctx_search hits
5// syntax-highlighted with line numbers. Display only — the model receives
6// every result byte-for-byte. Anything this file does not recognise (map and
7// signatures views, errors, running calls) falls through to the engine.
8//
9// The formats read here are lean-ctx's own output contract: the ```diff fence
10// of ctx_patch, the `name NL` header with ` N| ` or `N:hash|` rows of
11// ctx_read, and `path:line text` hits of ctx_search.
12import type { Elements as SurfaceElements, On, RenderElement } from "claude-code";
13
14const TOOLS = [
15 "mcp__lean-ctx__ctx_patch",
16 "mcp__lean-ctx__ctx_read",
17 "mcp__lean-ctx__ctx_search",
18 "mcp__lean_ctx__ctx_patch",
19 "mcp__lean_ctx__ctx_read",
20 "mcp__lean_ctx__ctx_search",
21] as const;
22type LeanTool = (typeof TOOLS)[number];
23
24/** One block under the call row. */
25type Block =
26 | { kind: "note"; text: string }
27 | { kind: "code"; source: string; path?: string; startLine?: number }
28 | { kind: "diff"; source: string; path?: string }
29 | { kind: "hit"; location: string; path: string; line: string; symbol?: string };
30
31/** What a result turns into: the call row's one-line summary and the blocks. */
32type Drawing = { summary: string; blocks: Block[] };
33
34// The engine caps one Code drawing; past it a result stays plain.
35const MAX_CODE_CHARS = 100_000;
36const DIFF_FENCE = /^```diff[ \t]*\n([\s\S]*?)\n?^```[ \t]*$/gm;
37const NEW_FILE = /^\+\+\+ (?:b\/)?(\S+)/m;
38const READ_HEADER = /^(\S+) \d+L\b/;
39const LINES_ROW = /^ *(\d+)\| ?(.*)$/;
40const ANCHOR_ROW = /^(\d+):[0-9a-f]{2,8}\|(.*)$/;
41const SEARCH_HIT = /^([^\s:]+):(\d+) (.*)$/;
42const SYMBOL_SUFFIX = / ∈(\S+@L\d+)$/;
43
44export function registerResultRendering(on: On): void {
45 on(
46 "ui.render",
47 {
48 component: "ToolUse",
49 props: { tool: TOOLS, isRunning: false, isErrored: false, isInterrupted: false },
50 },
51 async ($, event, next) => {
52 const props = event.props;
53 const drawing = drawingFor(props.tool, props.tool_use_id, props.output, props.input);
54 if (!drawing) return next(event);
55 // The engine keeps the call row; only its result text shrinks to the summary.
56 const row = await next({
57 ...event,
58 props: { ...props, output: [{ type: "text", text: drawing.summary }] },
59 });
60 const els = $.ui.resolve(event);
61 return (
62 <els.Box flexDirection="column">
63 {row}
64 <els.Box flexDirection="column" paddingLeft={5}>
65 {drawBlocks(els, drawing.blocks)}
66 </els.Box>
67 </els.Box>
68 );
69 },
70 );
71
72 on(
73 "ui.render",
74 { component: "ToolResult", props: { tool: TOOLS, isErrored: false } },
75 async ($, event, next) => {
76 const props = event.props;
77 // A standalone result has no call input: headerless full reads stay plain.
78 const drawing = drawingFor(props.tool, `result:${props.tool_use_id}`, props.output, undefined);
79 if (!drawing) return next(event);
80 const els = $.ui.resolve(event);
81 return (
82 <els.Box flexDirection="column">
83 <els.Text dimColor>{drawing.summary}</els.Text>
84 {drawBlocks(els, drawing.blocks)}
85 </els.Box>
86 );
87 },
88 );
89}
90
91// ── Parsing (pure, exported for tests) ──────────────────────────────────────
92
93export function resultText(output: unknown): string {
94 if (typeof output === "string") return output;
95 if (Array.isArray(output)) {
96 return output
97 .map((part) => (part && typeof part === "object" && "text" in part ? String(part.text) : ""))
98 .filter((text) => text.length > 0)
99 .join("\n");
100 }
101 if (output && typeof output === "object" && "content" in output) {
102 return resultText((output as { content: unknown }).content);
103 }
104 return "";
105}
106
107/** ctx_patch: every ```diff fence becomes a diff block; the `✓` line is the summary. */
108export function drawPatch(text: string): Drawing | null {
109 const blocks: Block[] = [];
110 let summary = "";
111 let cursor = 0;
112 const pushNotes = (chunk: string) => {
113 for (const line of chunk.split("\n")) {
114 if (!summary && line.startsWith("✓")) summary = line;
115 else if (line.trim()) blocks.push({ kind: "note", text: line });
116 }
117 };
118 for (const match of text.matchAll(DIFF_FENCE)) {
119 pushNotes(text.slice(cursor, match.index));
120 const source = match[1] ?? "";
121 if (source.length > MAX_CODE_CHARS) return null;
122 blocks.push({ kind: "diff", source, path: NEW_FILE.exec(source)?.[1] });
123 cursor = (match.index ?? 0) + match[0].length;
124 }
125 if (cursor === 0) return null;
126 pushNotes(text.slice(cursor));
127 return { summary: summary || "✓ patched", blocks: mergeNotes(blocks) };
128}
129
130/** ctx_read: numbered views (lines, anchored) of one or several files; full/raw with input. */
131export function drawRead(text: string, input: unknown): Drawing | null {
132 const args = (input ?? {}) as { path?: unknown; paths?: unknown; mode?: unknown; raw?: unknown };
133 const body = text.replace(/\n+$/, "");
134 const files = body.split("\n---\n");
135 if (files.length > 1) {
136 const last = files[files.length - 1] ?? "";
137 if (!/^Read \d+ files?\b/.test(last)) return null;
138 const blocks: Block[] = [];
139 for (const file of files.slice(0, -1)) {
140 const numbered = numberedBlocks(file, undefined);
141 if (!numbered) return null;
142 blocks.push({ kind: "note", text: numbered.header }, ...numbered.blocks);
143 }
144 return { summary: last.split("\n")[0] ?? last, blocks };
145 }
146 const path = typeof args.path === "string" ? args.path : undefined;
147 const numbered = numberedBlocks(body, path);
148 if (numbered) return { summary: numbered.header, blocks: numbered.blocks };
149 const verbatim = args.raw === true || args.mode === "full" || args.mode === "raw";
150 if (!verbatim || !path || body.length > MAX_CODE_CHARS) return null;
151 const { code, trailer } = splitTrailer(body);
152 // One line is more likely an error than a file.
153 if (code.split("\n").filter((line) => line.trim()).length < 2) return null;
154 const blocks: Block[] = [{ kind: "code", source: code, path, startLine: 1 }];
155 if (trailer) blocks.push({ kind: "note", text: trailer });
156 return { summary: `${baseName(path)} ${code.split("\n").length}L`, blocks };
157}
158
159/** ctx_search: `path:line text` hits; everything else is a note. */
160export function drawSearch(text: string): Drawing | null {
161 const [summary = "", ...lines] = text.replace(/\n+$/, "").split("\n");
162 const blocks: Block[] = [];
163 for (const line of lines) {
164 const hit = SEARCH_HIT.exec(line);
165 if (!hit) {
166 if (line.trim()) blocks.push({ kind: "note", text: line });
167 continue;
168 }
169 const [, path = "", lineNo = "", rest = ""] = hit;
170 const symbol = SYMBOL_SUFFIX.exec(rest);
171 blocks.push({
172 kind: "hit",
173 location: `${path}:${lineNo}`,
174 path,
175 line: (symbol ? rest.slice(0, symbol.index) : rest).replace(/\t/g, " ").trimEnd(),
176 symbol: symbol?.[1],
177 });
178 }
179 if (!blocks.some((block) => block.kind === "hit")) return null;
180 return { summary, blocks: mergeNotes(blocks) };
181}
182
183function numberedBlocks(
184 text: string,
185 path: string | undefined,
186): { header: string; blocks: Block[] } | null {
187 const [header = "", ...rows] = text.split("\n");
188 const named = READ_HEADER.exec(header);
189 if (!named) return null;
190 const rowPattern = ANCHOR_ROW.test(rows[0] ?? "") ? ANCHOR_ROW : LINES_ROW;
191 const filePath = path ?? named[1];
192 const blocks: Block[] = [];
193 let run: string[] = [];
194 let first = 0;
195 let previous = 0;
196 let index = 0;
197 const flush = () => {
198 if (run.length) blocks.push({ kind: "code", source: run.join("\n"), path: filePath, startLine: first });
199 run = [];
200 };
201 for (; index < rows.length; index++) {
202 const row = rowPattern.exec(rows[index] ?? "");
203 if (!row) break;
204 const lineNo = Number(row[1]);
205 // `lines:1-5,20-30` leaves gaps: each contiguous run numbers itself.
206 if (run.length && lineNo !== previous + 1) flush();
207 if (!run.length) first = lineNo;
208 run.push(row[2] ?? "");
209 previous = lineNo;
210 }
211 flush();
212 if (!blocks.length) return null;
213 const tail = rows.slice(index).join("\n").trim();
214 if (tail) blocks.push({ kind: "note", text: tail });
215 return { header, blocks };
216}
217
218/** Trailing `[lean-ctx …]` / `[… truncated …]` service lines are not code. */
219function splitTrailer(text: string): { code: string; trailer: string } {
220 const lines = text.split("\n");
221 let end = lines.length;
222 while (end > 0 && /^\[(?:lean-ctx|…)/.test(lines[end - 1] ?? "")) end--;
223 return { code: lines.slice(0, end).join("\n"), trailer: lines.slice(end).join("\n") };
224}
225
226function mergeNotes(blocks: Block[]): Block[] {
227 const merged: Block[] = [];
228 for (const block of blocks) {
229 const last = merged[merged.length - 1];
230 if (block.kind === "note" && last?.kind === "note") last.text += `\n${block.text}`;
231 else merged.push({ ...block });
232 }
233 return merged;
234}
235
236function baseName(path: string): string {
237 return path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
238}
239
240// ── Drawing ─────────────────────────────────────────────────────────────────
241
242// Tool rows draw on every surface; these three elements exist on all of them.
243type Elements = Pick<SurfaceElements[keyof SurfaceElements], "Box" | "Text" | "Code">;
244
245// Finished results never change, but rows redraw on scroll and resize.
246const CACHE_LIMIT = 200;
247const drawings = new Map<string, { text: string; drawing: Drawing | null }>();
248
249function drawingFor(tool: LeanTool, key: string, output: unknown, input: unknown): Drawing | null {
250 const text = resultText(output);
251 const cached = drawings.get(key);
252 if (cached && cached.text === text) return cached.drawing;
253 const name = tool.slice(tool.lastIndexOf("__") + 2);
254 const drawing =
255 name === "ctx_patch" ? drawPatch(text) : name === "ctx_read" ? drawRead(text, input) : drawSearch(text);
256 if (drawings.size >= CACHE_LIMIT) {
257 const oldest = drawings.keys().next();
258 if (!oldest.done) drawings.delete(oldest.value);
259 }
260 drawings.set(key, { text, drawing });
261 return drawing;
262}
263
264function drawBlocks(els: Elements, blocks: Block[]): RenderElement[] {
265 return blocks.map((block, index) => {
266 const key = `b${index}`;
267 switch (block.kind) {
268 case "note":
269 return (
270 <els.Text key={key} dimColor>
271 {block.text}
272 </els.Text>
273 );
274 case "diff":
275 return <els.Code key={key} source={block.source} path={block.path} format="diff" />;
276 case "code":
277 return <els.Code key={key} source={block.source} path={block.path} startLine={block.startLine} />;
278 case "hit":
279 return (
280 <els.Box key={key} flexDirection="row">
281 <els.Box flexShrink={0}>
282 <els.Text dimColor>{`${block.location} `}</els.Text>
283 </els.Box>
284 <els.Box flexShrink={1}>
285 <els.Code source={block.line} path={block.path} wrap="truncate-end" />
286 </els.Box>
287 {block.symbol ? (
288 <els.Box flexShrink={0}>
289 <els.Text dimColor>{` ∈ ${block.symbol}`}</els.Text>
290 </els.Box>
291 ) : null}
292 </els.Box>
293 );
294 }
295 });
296}
297types/index.d.ts 110 lines1// SPDX-License-Identifier: Apache-2.0
2/** One lean-ctx session's value snapshot (`<data>/value/sessions/<id>.json`). */
3export type ValueSnap = {
4 sessionId: string
5 projectRoot: string
6 /** The agent process that started that server, when lean-ctx records it. */
7 hostPid?: number
8 startedAt?: string
9 updatedAt?: string
10 toolCalls: number
11 tokensInput: number
12 tokensSaved: number
13 cacheHits: number
14 filesRead: number
15 commandsRun: number
16 secretsRedacted: number
17 shellBlocked: number
18 pathBlocked: number
19 injectionFlagged: number
20}
21
22/** `lean-ctx value --json`: both hash chains re-verified end to end. */
23export type Proof = {
24 isRunning: boolean
25 checkedAt?: number
26 ledgerEntries?: number
27 ledgerIntact?: boolean
28 auditEntries?: number
29 auditIntact?: boolean
30 /** Ledger entries recorded for this lean-ctx session. */
31 sessionEntries?: number
32 error?: string
33}
34
35/** What lean-ctx did during one finished main-loop turn. */
36export type TurnStat = {
37 n: number
38 durationMs: number
39 saved: number
40 calls: number
41 files: number
42 commands: number
43 /** Sources Claude saw this turn, how many through the gateway, how many as structure. */
44 sources: number
45 governed: number
46 structure: number
47 at: number
48}
49
50export type Overlay =
51 | { kind: 'turn'; turn: TurnStat; at: number }
52 /** A crossing worth a moment: a token amount, or a gateway first (title, detail). */
53 | { kind: 'milestone'; title: string; detail: string; at: number }
54
55/** How deep a source reached Claude: the read depth the website's flow names. */
56export type Depth = 'structure' | 'passage' | 'full' | 'search' | 'command'
57
58export type FeedItem = {
59 id: string
60 tool: string
61 label: string
62 isSubagent: boolean
63 startedAt: number
64 ms?: number
65 isError?: boolean
66 /** Set when the call brought a source to Claude. */
67 depth?: Depth
68 /** Through lean-ctx (the gateway) rather than one of Claude's own tools. */
69 governed: boolean
70}
71
72/** One source Claude saw this conversation, by path, pattern or command. */
73export type SourceStat = { label: string; depth: Depth; governed: boolean; n: number; last: number }
74
75export type Board = {
76 snap?: ValueSnap
77 milestone: number
78 turns: TurnStat[]
79 overlay?: Overlay
80 /** The counters as the running turn started. */
81 turnStart?: { sessionId?: string; saved: number; calls: number; files: number; commands: number }
82 isWorking: boolean
83 /** lean-ctx tool calls in flight right now. */
84 leanRunning: number
85 proof?: Proof
86 /** The session's running total over time; reset when the session changes. */
87 history?: { sessionId: string; points: { at: number; saved: number; raw?: number }[] }
88 feed: FeedItem[]
89 /** Sources Claude saw this conversation, keyed by path / pattern / command. */
90 sources: Record<string, SourceStat>
91 /** Sources seen since the running turn started. */
92 turnSeen: { sources: number; governed: number; structure: number }
93 /** Gateway milestones already celebrated (first secret kept out, …). */
94 celebrated: string[]
95 contextPct?: number
96 contextTokens?: number
97 window?: number
98 cacheHitPct?: number
99 costUsd?: number
100}
101
102/** The animation clock: one tick per frame while anything moves. */
103export type Frame = { tick: number }
104
105declare module 'claude-code' {
106 interface PluginState {
107 'lean-ctx': { gateway: Board; clock: Frame }
108 }
109}
110