claude-doom-statusbar 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,7 +38,7 @@ npx claude-doom-statusbar install
38
38
  That writes the `statusLine`, the lifecycle hooks, and the preset into `~/.claude/settings.json` for you (merging into whatever's already there, with a one-level `.bak`). Restart Claude Code and the HUD is live.
39
39
 
40
40
  ```bash
41
- npx claude-doom-statusbar install --preset full # full | default | minimal (default: full)
41
+ npx claude-doom-statusbar install --preset full # full | standard | minimal (default: full)
42
42
  npx claude-doom-statusbar install --project # write ./.claude/settings.json instead of ~/.claude
43
43
  npx claude-doom-statusbar uninstall # remove everything the installer added
44
44
  ```
@@ -65,14 +65,18 @@ $env:FORCE_HYPERLINK = "1"; claude
65
65
 
66
66
  ## Presets
67
67
 
68
- `DOOMBAR_PRESET` picks the layout (defaults to `presets/default.toml`):
68
+ `DOOMBAR_PRESET` picks the layout (defaults to `presets/standard.toml`):
69
69
 
70
70
  - **`minimal`** — a couple of bars, blends into the terminal.
71
- - **`default`** — balanced HUD.
71
+ - **`standard`** — balanced HUD.
72
72
  - **`full`** — every box, the look in the screenshot above.
73
73
 
74
74
  A preset is TOML: a `[bar]` style block, a `[mugshot]` block, and a list of `[[segment]]` boxes. Each box lists metrics with a render type — `bar`, `number`, `text`, `spark`, `ammo`, `list`, `scroll`, or a `group`. Copy one and rearrange the boxes, swap icons, or change which metrics show.
75
75
 
76
+ ### Responsive width
77
+
78
+ As the terminal narrows, the HUD shrinks: bars contract and text columns shrink together, and whatever overflows scrolls (the marquee). When even the smallest layout no longer fits, the preset falls back to a smaller one via its `[bar].fallback` key — `full → standard → minimal`. Your chosen preset is the ceiling; widening the terminal recovers it. It's stateless — each refresh re-reads the terminal width (`COLUMNS`), so it follows live resizes.
79
+
76
80
  ## How it works
77
81
 
78
82
  - **`src/statusline.js`** is the statusLine command. Claude Code pipes session JSON on stdin; it maps that (plus git via shell, system metrics from Node built-ins, and the hook state file) to metric values, picks the mugshot sprite, and renders the preset.
package/bin/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // Port of install.py.
4
4
  //
5
5
  // claude-doom-statusbar install # install into ~/.claude/settings.json
6
- // claude-doom-statusbar install --preset full # pick a preset (full | default | minimal)
6
+ // claude-doom-statusbar install --preset full # pick a preset (full | standard | minimal)
7
7
  // claude-doom-statusbar install --project # install into ./.claude/settings.json instead
8
8
  // claude-doom-statusbar uninstall # remove everything this installer added
9
9
  //
@@ -29,8 +29,11 @@ const STATUSLINE_CMD = `node "${STATUSLINE}"`;
29
29
  const HOOK_CMD = `node "${HOOK}"`;
30
30
 
31
31
  // Lifecycle events the mugshot hook understands (face reactions, geiger, subagents,
32
- // tasks, permission mode). PreToolUse has no matcher -> fires for every tool.
32
+ // tasks, permission mode, git snapshots). PreToolUse has no matcher -> fires for every tool.
33
+ // SessionStart resets the journal and primes git so the HUD is populated from the first
34
+ // render. All entries are installed async (see install()) so they never block a tool.
33
35
  const HOOK_EVENTS = [
36
+ "SessionStart",
34
37
  "PreToolUse", "PostToolUse", "PostToolUseFailure", "PermissionDenied",
35
38
  "Stop", "SubagentStart", "SubagentStop", "TaskCreated", "TaskCompleted",
36
39
  ];
@@ -91,8 +94,9 @@ function install(cfg, preset) {
91
94
  for (const ev of HOOK_EVENTS) {
92
95
  const lst = (hooks[ev] ??= []);
93
96
  if (!lst.some(ours)) {
94
- // idempotent: don't double-add
95
- lst.push({ hooks: [{ type: "command", command: HOOK_CMD }] });
97
+ // idempotent: don't double-add. async:true keeps the hook off the blocking path —
98
+ // it only appends one journal line and returns; statusline folds it at render time.
99
+ lst.push({ hooks: [{ type: "command", command: HOOK_CMD, async: true }] });
96
100
  }
97
101
  }
98
102
  return notes;
@@ -124,7 +128,7 @@ function parseArgs(argv) {
124
128
  else if (a.startsWith("--preset=")) out.preset = a.slice("--preset=".length);
125
129
  else die(`! unknown argument: ${a}`);
126
130
  }
127
- if (out.cmd === "install" && !out.preset) die("! --preset needs a value (full | default | minimal)");
131
+ if (out.cmd === "install" && !out.preset) die("! --preset needs a value (full | standard | minimal)");
128
132
  return out;
129
133
  }
130
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-doom-statusbar",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "DOOM-inspired status bar for the Claude Code CLI — a mugshot that tracks session health, plus usage, model, project, system, and a live subagent list.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,7 +15,7 @@
15
15
  "scripts": {
16
16
  "statusline": "node src/statusline.js",
17
17
  "hook": "node src/hook.js",
18
- "test": "node test/installer.test.mjs && node test/smoke.test.mjs && node test/hook-tasks.test.mjs && node test/statusline-tasks.test.mjs && node test/render-scroll.test.mjs && node test/statusline-savings.test.mjs && node test/e2e-tasks.test.mjs",
18
+ "test": "node test/installer.test.mjs && node test/smoke.test.mjs && node test/hook-tasks.test.mjs && node test/statusline-tasks.test.mjs && node test/render-scroll.test.mjs && node test/statusline-savings.test.mjs && node test/e2e-tasks.test.mjs && node test/marquee.test.mjs && node test/layout.test.mjs && node test/resolve-preset.test.mjs && node test/preset-bands.test.mjs && node test/journal.test.mjs && node test/git-event.test.mjs",
19
19
  "preversion": "npm test",
20
20
  "postversion": "git push --follow-tags",
21
21
  "prepublishOnly": "npm test"
package/presets/full.toml CHANGED
@@ -4,6 +4,7 @@ border_style = "vertical"
4
4
  border_color = "term-bg" # seamless cuts through the panel
5
5
  box_background = "#1c2036"
6
6
  headers = true
7
+ fallback = "standard" # degrade to this preset when the terminal is too narrow
7
8
 
8
9
  [mugshot]
9
10
  background = "#000000"
@@ -66,6 +67,7 @@ metric = [
66
67
  [[segment]]
67
68
  type = "box"
68
69
  title = "AGENTS"
70
+ max_width = 22 # cap width so long agent labels marquee (scroll back and forth)
69
71
  metric = [
70
72
  { id = "act.subagents", render = "scroll", anchor = "top", icon = "👹" },
71
73
  ]
@@ -73,6 +75,7 @@ metric = [
73
75
  [[segment]]
74
76
  type = "box"
75
77
  title = "TASKS"
78
+ max_width = 22 # cap width so long task titles marquee (scroll back and forth)
76
79
  metric = [
77
80
  { id = "act.tasklist", render = "scroll", anchor = "boundary" },
78
81
  ]
@@ -1,19 +1,56 @@
1
- # minimal — blends into the terminal, smallest footprint
1
+ # minimal — MODEL, USAGE, mugshot, PROJECT, ACTIVITY
2
2
  [bar]
3
- border_style = "none"
4
- box_background = "term-bg"
5
- headers = false
3
+ border_style = "vertical"
4
+ border_color = "term-bg" # seamless cuts through the panel
5
+ box_background = "#1c2036"
6
+ headers = true
6
7
 
7
8
  [mugshot]
8
- background = "term-bg"
9
+ background = "#000000"
9
10
 
10
11
  [[segment]]
11
- type = "box"
12
+ type = "box"
13
+ title = "MODEL"
14
+ metric = [
15
+ { id = "model.name", render = "text", icon = "🤖", right = "model.effort" },
16
+ { id = "model.mode", render = "text" }, # 💭 thinking 🚀 fast
17
+ { id = "model.permission", render = "text" }, # 📋 plan / ⏩ auto (hidden on default)
18
+ { id = "model.style", render = "text", icon = "🎨" },
19
+ { id = "advisor.model", render = "text", icon = "🧙" },
20
+ ]
21
+
22
+ [[segment]]
23
+ type = "box"
24
+ title = "USAGE"
12
25
  metric = [
13
26
  { id = "context.hp", render = "bar", icon = "🧠", color = "threshold" },
14
- { id = "ratelimit.5h", render = "ammo", icon = "🕔" },
27
+ { id = "ratelimit.5h", render = "bar", icon = "🕔", color = "threshold", show_pct = false, suffix = "usage.reset5h" },
28
+ { id = "ratelimit.7d", render = "bar", icon = "📅", color = "threshold", show_pct = false, suffix = "usage.reset7d" },
29
+ { id = "sys.ram", render = "bar", icon = "💾", color = "threshold" },
15
30
  { id = "cost.total", render = "number", icon = "💰" },
16
31
  ]
17
32
 
18
33
  [[segment]]
19
34
  type = "mugshot"
35
+
36
+ [[segment]]
37
+ type = "box"
38
+ title = "PROJECT"
39
+ metric = [
40
+ { id = "session.name", render = "text", icon = "🎮" },
41
+ { id = "loc.cwd", render = "text", icon = "📁" },
42
+ { id = "git.branch", render = "text", icon = "🌿" },
43
+ { id = "git.work", render = "text" }, # ✎ files ⇅ pull/push
44
+ { id = "loc.churn", render = "text", icon = "📝" },
45
+ { id = "pr.state", render = "text", icon = "⇧ " },
46
+ ]
47
+
48
+ [[segment]]
49
+ type = "box"
50
+ title = "ACTIVITY"
51
+ metric = [
52
+ { id = "act.geiger", render = "spark", icon = "📟", spark_style = "octant", spark_max = 1 },
53
+ { id = "act.agents", render = "number", icon = "👹" },
54
+ { id = "act.tasks", render = "number", icon = "🎯" },
55
+ { id = "act.errors", render = "number", icon = "💢", color = "threshold" },
56
+ ]
@@ -0,0 +1,73 @@
1
+ # standard — full minus SAVE and SYS
2
+ [bar]
3
+ border_style = "vertical"
4
+ border_color = "term-bg" # seamless cuts through the panel
5
+ box_background = "#1c2036"
6
+ headers = true
7
+ fallback = "minimal" # degrade to this preset when the terminal is too narrow
8
+
9
+ [mugshot]
10
+ background = "#000000"
11
+
12
+ [[segment]]
13
+ type = "box"
14
+ title = "MODEL"
15
+ metric = [
16
+ { id = "model.name", render = "text", icon = "🤖", right = "model.effort" },
17
+ { id = "model.mode", render = "text" }, # 💭 thinking 🚀 fast
18
+ { id = "model.permission", render = "text" }, # 📋 plan / ⏩ auto (hidden on default)
19
+ { id = "model.style", render = "text", icon = "🎨" },
20
+ { id = "advisor.model", render = "text", icon = "🧙" },
21
+ ]
22
+
23
+ [[segment]]
24
+ type = "box"
25
+ title = "USAGE"
26
+ metric = [
27
+ { id = "context.hp", render = "bar", icon = "🧠", color = "threshold" },
28
+ { id = "ratelimit.5h", render = "bar", icon = "🕔", color = "threshold", show_pct = false, suffix = "usage.reset5h" },
29
+ { id = "ratelimit.7d", render = "bar", icon = "📅", color = "threshold", show_pct = false, suffix = "usage.reset7d" },
30
+ { id = "sys.ram", render = "bar", icon = "💾", color = "threshold" },
31
+ { id = "cost.total", render = "number", icon = "💰" },
32
+ ]
33
+
34
+ [[segment]]
35
+ type = "box"
36
+ title = "PROJECT"
37
+ metric = [
38
+ { id = "session.name", render = "text", icon = "🎮" },
39
+ { id = "loc.cwd", render = "text", icon = "📁" },
40
+ { id = "git.branch", render = "text", icon = "🌿" },
41
+ { id = "git.work", render = "text" }, # ✎ files ⇅ pull/push
42
+ { id = "loc.churn", render = "text", icon = "📝" },
43
+ { id = "pr.state", render = "text", icon = "⇧ " },
44
+ ]
45
+
46
+ [[segment]]
47
+ type = "mugshot"
48
+
49
+ [[segment]]
50
+ type = "box"
51
+ title = "ACTIVITY"
52
+ metric = [
53
+ { id = "act.geiger", render = "spark", icon = "📟", spark_style = "octant", spark_max = 1 },
54
+ { id = "act.agents", render = "number", icon = "👹" },
55
+ { id = "act.tasks", render = "number", icon = "🎯" },
56
+ { id = "act.errors", render = "number", icon = "💢", color = "threshold" },
57
+ ]
58
+
59
+ [[segment]]
60
+ type = "box"
61
+ title = "AGENTS"
62
+ max_width = 22 # cap width so long agent labels marquee (scroll back and forth)
63
+ metric = [
64
+ { id = "act.subagents", render = "scroll", anchor = "top", icon = "👹" },
65
+ ]
66
+
67
+ [[segment]]
68
+ type = "box"
69
+ title = "TASKS"
70
+ max_width = 22 # cap width so long task titles marquee (scroll back and forth)
71
+ metric = [
72
+ { id = "act.tasklist", render = "scroll", anchor = "boundary" },
73
+ ]
package/src/fold.js ADDED
@@ -0,0 +1,137 @@
1
+ // Shared, pure reducer for the DOOM HUD state. No I/O, no spawns.
2
+ //
3
+ // Two writers used to fight over one state file (hook did read-modify-write per event).
4
+ // Now hooks only APPEND raw events to a per-session journal, and statusline FOLDS that
5
+ // journal into a checkpoint at render time. This module is the fold — identical state
6
+ // shape as before (spans, squad, pending, tasks, tasks_ts, expr, ts, errors, mode, git),
7
+ // so every downstream consumer (activityValues, the tests) is unchanged.
8
+
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+
12
+ export const GEIGER_WINDOW = 30.0; // seconds of tool-run history kept for the sparkline
13
+ export const MAX_RUN = 300.0; // drop an unclosed span after this (assume the Post was lost)
14
+ export const TASK_LINGER = 10.0; // seconds the TASKS box lingers after all tasks settle
15
+
16
+ export const READ_TOOLS = new Set(["Read", "Grep", "Glob",
17
+ "ctx_read", "ctx_multi_read", "ctx_search", "ctx_semantic_search", "ctx_tree", "ctx_overview"]);
18
+ export const WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "Bash", "ctx_shell", "ctx_edit"]);
19
+
20
+ // Filesystem-safe session key, shared by hook + statusline so they agree on file names.
21
+ export const sidKey = (id) => String(id || "default").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 48);
22
+
23
+ // Checkpoint (statusline-owned folded state) + journal (hook-appended events) live next to
24
+ // each other so both processes derive the same pair from the session id. MUGSHOT_STATE
25
+ // overrides the checkpoint path (tests, custom setups); the journal hangs off it.
26
+ export function statePaths(sessionId) {
27
+ const base = process.env.MUGSHOT_STATE || path.join(os.tmpdir(), `mugshot_${sidKey(sessionId)}.json`);
28
+ return { checkpoint: base, journal: base + ".jsonl" };
29
+ }
30
+
31
+ export function base(tool) {
32
+ return tool.startsWith("mcp__") ? tool.split("__").pop() : tool;
33
+ }
34
+
35
+ // Task event subject: the exact key isn't documented, so try the likely ones.
36
+ export function taskTitle(ev) {
37
+ return ev.task_title || ev.task_subject || ev.subject || ev.title ||
38
+ (ev.tool_input && ev.tool_input.subject) || "task";
39
+ }
40
+
41
+ export function expression(name, tool) {
42
+ const b = base(tool);
43
+ if (["PostToolUseFailure", "StopFailure", "PermissionDenied"].includes(name)) return "ouch";
44
+ if (["Stop", "TaskCompleted"].includes(name)) return "evl";
45
+ if (name === "PostToolUse") {
46
+ if (READ_TOOLS.has(b)) return Math.floor((Date.now() / 1000) * 2) % 2 === 0 ? "tl" : "tr";
47
+ if (WRITE_TOOLS.has(b)) return "kill";
48
+ }
49
+ return null;
50
+ }
51
+
52
+ export function foldActivity(st, name, ev, now) {
53
+ st.spans ??= [];
54
+ st.squad ??= {};
55
+ st.pending ??= [];
56
+ st.tasks ??= {}; // keyed map: id -> { title, status, ts }
57
+ st.errors ??= 0;
58
+
59
+ const tool = base(ev.tool_name || "");
60
+ if (name === "PreToolUse") {
61
+ st.spans.push([now, null]); // open a run interval
62
+ if (tool === "Agent") {
63
+ const ti = ev.tool_input || {};
64
+ st.pending.push({ type: ti.subagent_type || "", desc: ti.description || "", ts: now });
65
+ st.pending = st.pending.filter((p) => now - p.ts < 60).slice(-16);
66
+ }
67
+ } else if (["PostToolUse", "PostToolUseFailure", "PermissionDenied"].includes(name)) {
68
+ for (let i = st.spans.length - 1; i >= 0; i--) { // close the most recent open one
69
+ if (st.spans[i][1] === null) { st.spans[i][1] = now; break; }
70
+ }
71
+ }
72
+
73
+ if (["PostToolUseFailure", "StopFailure", "PermissionDenied"].includes(name)) {
74
+ st.errors += 1;
75
+ } else if (name === "SubagentStart") {
76
+ const aid = String(ev.agent_id || now);
77
+ const atype = ev.agent_type || "agent";
78
+ let desc = "";
79
+ for (let i = 0; i < st.pending.length; i++) { // FIFO match the launch by agent type
80
+ if (st.pending[i].type === atype) { desc = st.pending[i].desc; st.pending.splice(i, 1); break; }
81
+ }
82
+ st.squad[aid] = { type: atype, start: now, desc };
83
+ } else if (name === "SubagentStop") {
84
+ delete st.squad[String(ev.agent_id || "")];
85
+ } else if (name === "TaskCreated") {
86
+ const id = String(ev.task_id ?? now);
87
+ st.tasks[id] = { title: taskTitle(ev), status: "pending", ts: now };
88
+ st.tasks_ts = now;
89
+ } else if (name === "TaskCompleted") {
90
+ const id = String(ev.task_id ?? "");
91
+ if (st.tasks[id]) st.tasks[id].status = "completed";
92
+ else st.tasks[id] = { title: taskTitle(ev), status: "completed", ts: now };
93
+ st.tasks_ts = now;
94
+ } else if (name === "PostToolUse" && (ev.tool_name === "TaskUpdate") && ev.tool_input) {
95
+ const id = String(ev.tool_input.taskId ?? "");
96
+ const s = ev.tool_input.status;
97
+ if (id && st.tasks[id] && ["pending", "in_progress", "completed", "deleted"].includes(s)) {
98
+ st.tasks[id].status = s;
99
+ st.tasks_ts = now;
100
+ }
101
+ }
102
+
103
+ const win = now - GEIGER_WINDOW; // prune: closed spans out of window, orphaned open spans
104
+ st.spans = st.spans.filter((s) => (s[1] === null ? s[0] >= now - MAX_RUN : s[1] >= win));
105
+ st.squad = Object.fromEntries(Object.entries(st.squad).filter(([, v]) => now - v.start < MAX_RUN));
106
+
107
+ const taskVals = Object.values(st.tasks || {});
108
+ const anyOpen = taskVals.some((t) => t.status === "pending" || t.status === "in_progress");
109
+ if (taskVals.length && !anyOpen && now - (st.tasks_ts || 0) > TASK_LINGER) st.tasks = {};
110
+ }
111
+
112
+ // One full event fold: activity + face expression + permission mode + git snapshot.
113
+ // This is exactly what hook.js's main() used to do per event — now applied at render time
114
+ // over the journal. A `git` event carries a precomputed snapshot in ev.git.
115
+ export function foldEvent(st, name, ev, now) {
116
+ foldActivity(st, name, ev, now);
117
+ const expr = expression(name, ev.tool_name || "");
118
+ if (expr) { st.expr = expr; st.ts = now; }
119
+ if (ev.permission_mode) st.mode = ev.permission_mode;
120
+ if (name === "git" && ev.git) st.git = ev.git; // { br, lr, st, cwd } or { cwd } when no repo
121
+ }
122
+
123
+ // Fold a batch of journal lines (each { name, ev, ts }) into st. Sort by ts first: async
124
+ // hooks give no append-order guarantee, so SubagentStop can land before its Start. Sorting
125
+ // the batch keeps open/close and create/consume in causal order (within the batch).
126
+ export function foldBatch(st, lines) {
127
+ const evs = [];
128
+ for (const ln of lines) {
129
+ if (!ln) continue;
130
+ let o; try { o = JSON.parse(ln); } catch { continue; } // torn/partial line -> skip
131
+ if (!o || typeof o.ts !== "number" || typeof o.name !== "string") continue;
132
+ evs.push(o);
133
+ }
134
+ evs.sort((a, b) => a.ts - b.ts);
135
+ for (const o of evs) foldEvent(st, o.name, o.ev || {}, o.ts);
136
+ return st;
137
+ }
package/src/hook.js CHANGED
@@ -1,112 +1,87 @@
1
1
  #!/usr/bin/env node
2
- // Claude Code hook: an event-bus for the DOOM HUD. Port of hooks/mugshot_hook.py.
3
- // Each invocation reads the shared state file, folds in the lifecycle event, and
4
- // writes it back atomically. The status line reads that state.
2
+ // Claude Code hook: an APPEND-ONLY event recorder for the DOOM HUD.
5
3
  //
6
- // State carries: face reaction {expr, ts}; activity spans[] [start,end] (geiger),
7
- // squad{} (running subagents), pending[] (Agent launch labels), tasks{} (id ->
8
- // {title,status,ts}), tasks_ts (last tasks mutation), errors, mode (permission mode). Always exits 0.
4
+ // Old design did read-modify-write on a shared state file per event; under async hooks that
5
+ // races (lost subagents/tasks). Now each invocation just APPENDS one slim line to a
6
+ // per-session journal append is atomic, so concurrent async hooks never clobber each
7
+ // other. statusline.js folds the journal into a checkpoint at render time (see fold.js).
9
8
  //
10
- // State file: $MUGSHOT_STATE, else <temp>/mugshot_<session_id>.json.
9
+ // Because the heavy work (folding, git) is off the blocking path, install these hooks with
10
+ // "async": true (see bin/cli.js). This hook never reads the journal and always exits 0.
11
+ //
12
+ // Extra job: git lives here now, not on the render hot path. On write-affecting events (and
13
+ // once per turn on Stop, and at SessionStart) we snapshot git into a `git` journal line,
14
+ // throttled by DOOMBAR_GIT_TTL. statusline no longer spawns git at all -> the Windows MSYS
15
+ // "bash flood" is gone by construction (git runs async, event-driven, rarely).
16
+ //
17
+ // Journal: <checkpoint>.jsonl where checkpoint is $MUGSHOT_STATE or <temp>/mugshot_<sid>.json.
11
18
 
12
- import { readFileSync, writeFileSync, renameSync } from "node:fs";
13
- import os from "node:os";
14
- import path from "node:path";
19
+ import { appendFileSync, writeFileSync, readFileSync } from "node:fs";
20
+ import { spawnSync } from "node:child_process";
15
21
  import { fileURLToPath } from "node:url";
16
-
17
- const GEIGER_WINDOW = 30.0; // seconds of tool-run history kept for the sparkline
18
- const MAX_RUN = 300.0; // drop an unclosed span after this (assume the Post was lost)
19
- const TASK_LINGER = 10.0; // seconds the TASKS box lingers after all tasks settle
20
-
21
- const READ_TOOLS = new Set(["Read", "Grep", "Glob",
22
- "ctx_read", "ctx_multi_read", "ctx_search", "ctx_semantic_search", "ctx_tree", "ctx_overview"]);
23
- const WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "Bash", "ctx_shell", "ctx_edit"]);
24
-
25
- function statePath(ev) {
26
- if (process.env.MUGSHOT_STATE) return process.env.MUGSHOT_STATE;
27
- const sid = String(ev.session_id || "default").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 48);
28
- return path.join(os.tmpdir(), `mugshot_${sid}.json`);
22
+ import path from "node:path";
23
+ import os from "node:os";
24
+ import { base, statePaths, sidKey, WRITE_TOOLS } from "./fold.js";
25
+
26
+ // Re-export the reducer so existing tests importing from hook.js keep working.
27
+ export { foldActivity, expression } from "./fold.js";
28
+
29
+ const GIT_TTL = Number.isFinite(Number(process.env.DOOMBAR_GIT_TTL))
30
+ ? Number(process.env.DOOMBAR_GIT_TTL)
31
+ : 4000; // ms; DOOMBAR_GIT_TTL=0 disables throttling (0 is a valid TTL)
32
+
33
+ // Project an event down to only the fields fold.js consumes. Keeps journal lines tiny and
34
+ // bounded — a raw Write/Edit event carries the whole file body in tool_input, which would
35
+ // bloat the journal and stress append atomicity. We never journal that.
36
+ function slim(ev) {
37
+ const ti = ev.tool_input || {};
38
+ const tn = ev.tool_name;
39
+ let tool_input;
40
+ if (tn === "TaskUpdate") tool_input = { taskId: ti.taskId, status: ti.status };
41
+ else if (tn === "Agent") tool_input = { subagent_type: ti.subagent_type, description: ti.description };
42
+ else if (ti.subject) tool_input = { subject: ti.subject };
43
+ return {
44
+ tool_name: tn,
45
+ tool_input,
46
+ agent_id: ev.agent_id,
47
+ agent_type: ev.agent_type,
48
+ task_id: ev.task_id,
49
+ task_title: ev.task_title, task_subject: ev.task_subject, subject: ev.subject, title: ev.title,
50
+ permission_mode: ev.permission_mode,
51
+ };
29
52
  }
30
53
 
31
- function base(tool) {
32
- return tool.startsWith("mcp__") ? tool.split("__").pop() : tool;
54
+ function gitCmd(cwd, ...args) {
55
+ try {
56
+ const r = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", timeout: 1000 });
57
+ return r.status === 0 ? r.stdout.trim() : null;
58
+ } catch { return null; }
33
59
  }
34
60
 
35
- // Task event subject: the exact key isn't documented, so try the likely ones.
36
- function taskTitle(ev) {
37
- return ev.task_title || ev.task_subject || ev.subject || ev.title ||
38
- (ev.tool_input && ev.tool_input.subject) || "task";
61
+ function gitSnapshot(cwd) {
62
+ return {
63
+ cwd,
64
+ br: gitCmd(cwd, "branch", "--show-current"),
65
+ lr: gitCmd(cwd, "rev-list", "--count", "--left-right", "@{u}...HEAD"),
66
+ st: gitCmd(cwd, "status", "--porcelain"),
67
+ };
39
68
  }
40
69
 
41
- export function expression(name, tool) {
42
- const b = base(tool);
43
- if (["PostToolUseFailure", "StopFailure", "PermissionDenied"].includes(name)) return "ouch";
44
- if (["Stop", "TaskCompleted"].includes(name)) return "evl";
45
- if (name === "PostToolUse") {
46
- if (READ_TOOLS.has(b)) return Math.floor((Date.now() / 1000) * 2) % 2 === 0 ? "tl" : "tr";
47
- if (WRITE_TOOLS.has(b)) return "kill";
48
- }
49
- return null;
70
+ // Best-effort per-session throttle (not a lock): a tiny marker holds the last git ts + cwd.
71
+ // Worst case under a race is a redundant concurrent git spawn — harmless and rare.
72
+ function gitMarkerPath(sid) {
73
+ return path.join(os.tmpdir(), `mugshot_git_${sidKey(sid)}.json`);
50
74
  }
51
75
 
52
- export function foldActivity(st, name, ev, now) {
53
- st.spans ??= [];
54
- st.squad ??= {};
55
- st.pending ??= [];
56
- st.tasks ??= {}; // keyed map: id -> { title, status, ts }
57
- st.errors ??= 0;
58
-
59
- const tool = base(ev.tool_name || "");
60
- if (name === "PreToolUse") {
61
- st.spans.push([now, null]); // open a run interval
62
- if (tool === "Agent") {
63
- const ti = ev.tool_input || {};
64
- st.pending.push({ type: ti.subagent_type || "", desc: ti.description || "", ts: now });
65
- st.pending = st.pending.filter((p) => now - p.ts < 60).slice(-16);
66
- }
67
- } else if (["PostToolUse", "PostToolUseFailure", "PermissionDenied"].includes(name)) {
68
- for (let i = st.spans.length - 1; i >= 0; i--) { // close the most recent open one
69
- if (st.spans[i][1] === null) { st.spans[i][1] = now; break; }
70
- }
71
- }
72
-
73
- if (["PostToolUseFailure", "StopFailure", "PermissionDenied"].includes(name)) {
74
- st.errors += 1;
75
- } else if (name === "SubagentStart") {
76
- const aid = String(ev.agent_id || now);
77
- const atype = ev.agent_type || "agent";
78
- let desc = "";
79
- for (let i = 0; i < st.pending.length; i++) { // FIFO match the launch by agent type
80
- if (st.pending[i].type === atype) { desc = st.pending[i].desc; st.pending.splice(i, 1); break; }
81
- }
82
- st.squad[aid] = { type: atype, start: now, desc };
83
- } else if (name === "SubagentStop") {
84
- delete st.squad[String(ev.agent_id || "")];
85
- } else if (name === "TaskCreated") {
86
- const id = String(ev.task_id ?? now);
87
- st.tasks[id] = { title: taskTitle(ev), status: "pending", ts: now };
88
- st.tasks_ts = now;
89
- } else if (name === "TaskCompleted") {
90
- const id = String(ev.task_id ?? "");
91
- if (st.tasks[id]) st.tasks[id].status = "completed";
92
- else st.tasks[id] = { title: taskTitle(ev), status: "completed", ts: now };
93
- st.tasks_ts = now;
94
- } else if (name === "PostToolUse" && (ev.tool_name === "TaskUpdate") && ev.tool_input) {
95
- const id = String(ev.tool_input.taskId ?? "");
96
- const s = ev.tool_input.status;
97
- if (id && st.tasks[id] && ["pending", "in_progress", "completed", "deleted"].includes(s)) {
98
- st.tasks[id].status = s;
99
- st.tasks_ts = now;
100
- }
101
- }
102
-
103
- const win = now - GEIGER_WINDOW; // prune: closed spans out of window, orphaned open spans
104
- st.spans = st.spans.filter((s) => (s[1] === null ? s[0] >= now - MAX_RUN : s[1] >= win));
105
- st.squad = Object.fromEntries(Object.entries(st.squad).filter(([, v]) => now - v.start < MAX_RUN));
106
-
107
- const taskVals = Object.values(st.tasks || {});
108
- const anyOpen = taskVals.some((t) => t.status === "pending" || t.status === "in_progress");
109
- if (taskVals.length && !anyOpen && now - (st.tasks_ts || 0) > TASK_LINGER) st.tasks = {};
76
+ function shouldSnapshotGit(name, ev, nowMs, sid) {
77
+ if (name !== "SessionStart" && name !== "Stop" &&
78
+ !(name === "PostToolUse" && WRITE_TOOLS.has(base(ev.tool_name || "")))) return false;
79
+ if (name === "SessionStart") return true; // always prime at start
80
+ let m = {};
81
+ try { m = JSON.parse(readFileSync(gitMarkerPath(sid), "utf8")); } catch { /* none */ }
82
+ const cwd = ev.cwd || (ev.workspace || {}).current_dir;
83
+ if (m.cwd !== cwd) return true; // cwd changed -> refresh regardless of TTL
84
+ return nowMs - (m.ts || 0) >= GIT_TTL;
110
85
  }
111
86
 
112
87
  function main() {
@@ -114,19 +89,31 @@ function main() {
114
89
  let ev = {};
115
90
  try { ev = JSON.parse(readFileSync(0, "utf8")); } catch { ev = {}; }
116
91
  const name = ev.hook_event_name || "";
117
- const now = Date.now() / 1000;
118
- const p = statePath(ev);
119
-
120
- let st = {};
121
- try { st = JSON.parse(readFileSync(p, "utf8")); } catch { st = {}; }
122
-
123
- foldActivity(st, name, ev, now);
124
- const expr = expression(name, ev.tool_name || "");
125
- if (expr) { st.expr = expr; st.ts = now; }
126
- if (ev.permission_mode) st.mode = ev.permission_mode;
92
+ const now = Date.now() / 1000; // seconds, matches fold's time base
93
+ const nowMs = Date.now();
94
+ const sid = ev.session_id || "default";
95
+ const { journal } = statePaths(sid);
96
+
97
+ // SessionStart resets the journal so each session starts clean (hygiene; sid is already
98
+ // per-session). At this instant no other hook is appending, so truncation is race-free.
99
+ if (name === "SessionStart") {
100
+ try { writeFileSync(journal, ""); } catch { /* ignore */ }
101
+ }
127
102
 
128
- const tmp = `${p}.${process.pid}.tmp`;
129
- try { writeFileSync(tmp, JSON.stringify(st)); renameSync(tmp, p); } catch { /* never block */ }
103
+ // Append the slim event line (atomic). foldEvent ignores names it doesn't know.
104
+ try {
105
+ appendFileSync(journal, JSON.stringify({ name, ev: slim(ev), ts: now }) + "\n", { flag: "a" });
106
+ } catch { /* never block a tool */ }
107
+
108
+ // Git snapshot on write-affecting events / per-turn Stop / session start, throttled.
109
+ const cwd = ev.cwd || (ev.workspace || {}).current_dir;
110
+ if (cwd && shouldSnapshotGit(name, ev, nowMs, sid)) {
111
+ const snap = gitSnapshot(cwd);
112
+ try {
113
+ appendFileSync(journal, JSON.stringify({ name: "git", ev: { git: snap }, ts: now }) + "\n", { flag: "a" });
114
+ } catch { /* ignore */ }
115
+ try { writeFileSync(gitMarkerPath(sid), JSON.stringify({ ts: nowMs, cwd })); } catch { /* ignore */ }
116
+ }
130
117
  } catch { /* swallow everything: a hook must never block a tool */ }
131
118
  process.exit(0);
132
119
  }
package/src/render.js CHANGED
@@ -203,7 +203,20 @@ function barMeta(entry) {
203
203
  return [lw, 0, entry.render || "text"];
204
204
  }
205
205
 
206
- export function metricFixedWidth(entry) {
206
+ // Display width of a plain text run, capped at `textCap` columns — but only when
207
+ // it is marquee-safe. Values carrying ANSI/OSC escapes (coloured text, hyperlinks)
208
+ // can't be column-sliced without corrupting the escape, so they keep full width
209
+ // (a hard floor): their box shrinks less, which is what trips the preset fallback.
210
+ const TEXTCAP_MAX = 24; // upper bound — matches statusline's clip(…, 24)
211
+ const TEXTCAP_MIN = 10; // lower bound — the readable floor before falling back
212
+ const ESC_RE = /\x1b/;
213
+ function capLen(s, textCap) {
214
+ const str = String(s);
215
+ const w = vlen(str);
216
+ return ESC_RE.test(str) ? w : Math.min(w, textCap);
217
+ }
218
+
219
+ export function metricFixedWidth(entry, textCap = TEXTCAP_MAX) {
207
220
  const icon = entry.icon || "";
208
221
  const lw = vlen(icon ? icon + " " : "");
209
222
  const r = entry.render || "text";
@@ -211,7 +224,7 @@ export function metricFixedWidth(entry) {
211
224
  const rextra = rid && rid in VALUES ? 1 + vlen(String(VALUES[rid])) : 0;
212
225
  if ("group" in entry) {
213
226
  const sep = entry.sep ?? " ";
214
- return lw + vlen(entry.group.filter((i) => i in VALUES).map((i) => String(VALUES[i])).join(sep)) + rextra;
227
+ return lw + capLen(entry.group.filter((i) => i in VALUES).map((i) => String(VALUES[i])).join(sep), textCap) + rextra;
215
228
  }
216
229
  if (r === "spark") return lw + Math.floor(((VALUES[entry.id] || []).length + 1) / 2);
217
230
  if (r === "ammo") return lw + 5 + vlen(" " + (entry.id in VALUES ? VALUES[entry.id] : 0) + "%");
@@ -220,21 +233,27 @@ export function metricFixedWidth(entry) {
220
233
  if (items.length === 0) return lw;
221
234
  return Math.max(...items.map((it) =>
222
235
  Array.isArray(it) && it.length === 2
223
- ? lw + vlen(String(it[0])) + 1 + vlen(String(it[1]))
224
- : lw + vlen(String(it))));
236
+ ? lw + capLen(it[0], textCap) + 1 + vlen(String(it[1]))
237
+ : lw + capLen(it, textCap)));
225
238
  }
226
239
  if (r === "scroll") {
227
240
  const items = VALUES[entry.id] || [];
228
241
  if (items.length === 0) return lw;
229
242
  return Math.max(...items.map((it) => {
230
243
  if (Array.isArray(it) && it.length === 2)
231
- return lw + vlen(String(it[0])) + 1 + vlen(String(it[1]));
244
+ return lw + capLen(it[0], textCap) + 1 + vlen(String(it[1]));
232
245
  // object {mark, text}
233
- return lw + vlen(String(it.mark || "")) + 1 + vlen(String(it.text || ""));
246
+ return lw + vlen(String(it.mark || "")) + 1 + capLen(it.text || "", textCap);
234
247
  }));
235
248
  }
236
249
  if (r === "bar") return null;
237
- return lw + vlen(String(entry.id in VALUES ? VALUES[entry.id] : "?")) + rextra;
250
+ return lw + capLen(entry.id in VALUES ? VALUES[entry.id] : "?", textCap) + rextra;
251
+ }
252
+
253
+ // The coupled text cap for a given bar-cell count: cells 14 -> cap 24, cells 4 ->
254
+ // cap 10, linearly in between. One scale drives bars and text together (approach A).
255
+ export function textCapFor(cells) {
256
+ return Math.round(TEXTCAP_MIN + (cells - 4) / (14 - 4) * (TEXTCAP_MAX - TEXTCAP_MIN));
238
257
  }
239
258
 
240
259
  export function scrollWindow(n, h, anchor, boundary) {
@@ -246,16 +265,63 @@ export function scrollWindow(n, h, anchor, boundary) {
246
265
  return { start, up: start, down: n - start - h };
247
266
  }
248
267
 
268
+ // --- horizontal marquee (the "car radio" scroll) ----------------------------
269
+ // Long text that won't fit its column budget glides left until its tail shows,
270
+ // pauses, then glides back to the start and pauses again — ping-pong, driven by
271
+ // the same per-refresh `tick` as the mugshot/geiger. Pure function of `tick`
272
+ // (no Date in here) so renders stay deterministic and testable.
273
+ const MARQUEE_STEP = 1; // display columns advanced per tick
274
+ const MARQUEE_DWELL = 3; // ticks held at each end before reversing
275
+
276
+ // Triangular offset wave 0..span..0 with a dwell at both extremes.
277
+ function marqueeOffset(span, tick) {
278
+ if (span <= 0) return 0;
279
+ const sweep = Math.ceil(span / MARQUEE_STEP);
280
+ const cycle = 2 * (MARQUEE_DWELL + sweep);
281
+ let t = ((tick % cycle) + cycle) % cycle;
282
+ if (t < MARQUEE_DWELL) return 0; // hold at start
283
+ t -= MARQUEE_DWELL;
284
+ if (t < sweep) return Math.min(span, t * MARQUEE_STEP); // glide forward 0->span
285
+ t -= sweep;
286
+ if (t < MARQUEE_DWELL) return span; // hold at end
287
+ t -= MARQUEE_DWELL;
288
+ return Math.max(0, span - t * MARQUEE_STEP); // glide back span->0
289
+ }
290
+
291
+ // Take a `width`-wide display window starting `off` columns in, never splitting a
292
+ // 2-col glyph; the result is always exactly `width` columns (padded with spaces).
293
+ function sliceCols(text, off, width) {
294
+ let col = 0, taken = 0, out = "";
295
+ for (const ch of [...String(text)]) {
296
+ const cw = vlen(ch);
297
+ if (col < off) { col += cw; continue; } // still left of the window
298
+ if (taken + cw > width) break; // glyph would overflow the window
299
+ out += ch; taken += cw; col += cw;
300
+ }
301
+ if (taken < width) out += " ".repeat(width - taken);
302
+ return out;
303
+ }
304
+
305
+ // Fit `text` into exactly `width` display columns. Fits -> left-aligned + padded.
306
+ // Overflows -> ping-pong marquee window for the current `tick`.
307
+ export function marquee(text, width, tick = 0) {
308
+ text = String(text);
309
+ if (width <= 0) return "";
310
+ const tw = vlen(text);
311
+ if (tw <= width) return text + " ".repeat(width - tw);
312
+ return sliceCols(text, marqueeOffset(tw - width, tick), width);
313
+ }
314
+
249
315
  function available(entry) {
250
316
  if ("group" in entry) return entry.group.some((i) => i in VALUES);
251
317
  if (entry.render === "list") return true;
252
318
  return entry.id in VALUES;
253
319
  }
254
320
 
255
- function boxWidth(box, cells) {
321
+ function boxWidth(box, cells, textCap = TEXTCAP_MAX) {
256
322
  const widths = [vlen(box.title || "")];
257
323
  for (const m of box.metric) {
258
- let fw = metricFixedWidth(m);
324
+ let fw = metricFixedWidth(m, textCap);
259
325
  if (fw === null) {
260
326
  const [lw, sw] = barMeta(m);
261
327
  fw = lw + cells + sw;
@@ -280,17 +346,15 @@ function hpRow(thresholds = HP_THRESHOLDS) {
280
346
  return thresholds.filter((t) => headroom < t).length;
281
347
  }
282
348
 
283
- export function buildBar(cfg, target, spriteFor) {
349
+ // Width-relevant layout context shared by buildBar (render) and planLayout (fit
350
+ // test). Filters unavailable metrics, computes the row count, and loads the mugshot
351
+ // art so its width counts toward the layout. spriteFor defaults to the idle face;
352
+ // the exact sprite never changes the mugshot's column width.
353
+ function layoutContext(cfg, spriteFor) {
284
354
  if (!spriteFor) spriteFor = (hp) => `STFST${hp}1`;
285
-
286
355
  const bar = cfg.bar || {};
287
356
  const style = bar.border_style ?? "vertical";
288
357
  const headers = (bar.headers ?? true) && style !== "frame";
289
- const boxRgb = rgbOf(bar.box_background ?? "term-bg");
290
- const bcol = bar.border_color ?? "term-fg";
291
- const mugRgb = rgbOf((cfg.mugshot || {}).background ?? "#000000");
292
-
293
- // availability: drop metrics whose value is absent; collapse empty boxes.
294
358
  const segs = [];
295
359
  for (const s of cfg.segment) {
296
360
  if (s.type === "mugshot") { segs.push(s); continue; }
@@ -301,35 +365,79 @@ export function buildBar(cfg, target, spriteFor) {
301
365
  const rowcount = (b) => b.metric.reduce((n, m) =>
302
366
  n + (m.render === "list" ? (VALUES[m.id] || []).length : (m.render === "scroll" ? 0 : 1)), 0);
303
367
  const dataRows = boxes.length ? Math.max(...boxes.map(rowcount)) : 0;
304
- const headersExtra = headers ? 1 : 0;
305
- const totalRows = Math.max(dataRows + headersExtra, 4); // 4 = mugshot floor
306
-
368
+ const totalRows = Math.max(dataRows + (headers ? 1 : 0), 4); // 4 = mugshot floor
307
369
  const hp = hpRow();
308
370
  const face = loadFace(spriteFor(hp), totalRows);
309
371
  const faceW = Math.max(...face.map((r) => r.length));
372
+ return { bar, style, headers, segs, totalRows, hp, face, faceW };
373
+ }
310
374
 
311
- const colWidths = (cells) => {
312
- const ws = [];
313
- let mug = null;
314
- segs.forEach((s, i) => {
315
- if (s.type === "mugshot") { ws.push(faceW + 2); mug = i; }
316
- else ws.push(boxWidth(s, cells) + 2);
317
- });
318
- return [ws, mug];
319
- };
320
-
321
- const balancedWidth = (cells) => {
322
- const [ws, mug] = colWidths(cells);
323
- if (mug === null) return ws.reduce((a, b) => a + b, 0) + (ws.length - 1);
324
- const left = ws.slice(0, mug).reduce((a, b) => a + b, 0) + mug;
325
- const right = ws.slice(mug + 1).reduce((a, b) => a + b, 0) + (ws.length - 1 - mug);
326
- return 2 * Math.max(left, right) + ws[mug];
327
- };
328
-
329
- let cells = 4;
375
+ function colWidthsOf(segs, faceW, cells, textCap) {
376
+ const ws = [];
377
+ let mug = null;
378
+ segs.forEach((s, i) => {
379
+ if (s.type === "mugshot") { ws.push(faceW + 2); mug = i; }
380
+ else ws.push(boxWidth(s, cells, textCap) + 2);
381
+ });
382
+ return [ws, mug];
383
+ }
384
+
385
+ function balancedWidthOf(segs, faceW, cells, textCap) {
386
+ const [ws, mug] = colWidthsOf(segs, faceW, cells, textCap);
387
+ if (mug === null) return ws.reduce((a, b) => a + b, 0) + (ws.length - 1);
388
+ const left = ws.slice(0, mug).reduce((a, b) => a + b, 0) + mug;
389
+ const right = ws.slice(mug + 1).reduce((a, b) => a + b, 0) + (ws.length - 1 - mug);
390
+ return 2 * Math.max(left, right) + ws[mug];
391
+ }
392
+
393
+ // Largest lockstep scale (bars 14->4, text 24->10) whose balanced layout fits
394
+ // `target`. Returns the minimum scale with fits=false when nothing fits — the
395
+ // caller (statusline) reads `fits` to decide whether to fall back to a smaller
396
+ // preset. Pure: no filesystem, deterministic for a given cfg + VALUES.
397
+ export function planLayout(cfg, target, spriteFor) {
398
+ const { segs, faceW } = layoutContext(cfg, spriteFor);
330
399
  for (let c = 14; c >= 4; c--) {
331
- if (balancedWidth(c) <= target) { cells = c; break; }
400
+ const textCap = textCapFor(c);
401
+ const width = balancedWidthOf(segs, faceW, c, textCap);
402
+ if (width <= target) return { cells: c, textCap, width, fits: true };
332
403
  }
404
+ const textCap = textCapFor(4);
405
+ return { cells: 4, textCap, width: balancedWidthOf(segs, faceW, 4, textCap), fits: false };
406
+ }
407
+
408
+ // Walk the per-preset fallback chain from `chosenCfg` (the ceiling) downward and
409
+ // return the first preset whose layout fits `target`; if none fit, return the last
410
+ // (smallest) one reached. `loadByName(name) -> cfg | null` loads a sibling preset;
411
+ // returning null (missing/unreadable) ends the chain. Stateless: ceiling + recovery
412
+ // fall out of re-deriving from `target` each call. Guards against fallback cycles.
413
+ export function resolvePreset(chosenCfg, target, loadByName, spriteFor) {
414
+ let cfg = chosenCfg, last = chosenCfg;
415
+ const seen = new Set();
416
+ while (cfg) {
417
+ last = cfg;
418
+ // Fit-test with the SAME sprite buildBar will render, so the mugshot column
419
+ // width matches: plan.fits then implies the rendered layout actually fits.
420
+ if (planLayout(cfg, target, spriteFor).fits) return cfg;
421
+ const next = cfg.bar && cfg.bar.fallback;
422
+ if (!next || seen.has(next)) break; // terminus or cycle
423
+ seen.add(next);
424
+ const loaded = loadByName(next);
425
+ if (!loaded) break; // missing/unreadable fallback
426
+ cfg = loaded;
427
+ }
428
+ return last; // nothing fit -> smallest reached
429
+ }
430
+
431
+ export function buildBar(cfg, target, spriteFor, tick = 0) {
432
+ if (!spriteFor) spriteFor = (hp) => `STFST${hp}1`;
433
+
434
+ const { style, headers, segs, totalRows, hp, face, faceW } = layoutContext(cfg, spriteFor);
435
+ const bar = cfg.bar || {};
436
+ const boxRgb = rgbOf(bar.box_background ?? "term-bg");
437
+ const bcol = bar.border_color ?? "term-fg";
438
+ const mugRgb = rgbOf((cfg.mugshot || {}).background ?? "#000000");
439
+
440
+ const { cells, textCap } = planLayout(cfg, target, spriteFor);
333
441
 
334
442
  const columns = [];
335
443
  let mugIdx = null;
@@ -339,7 +447,7 @@ export function buildBar(cfg, target, spriteFor) {
339
447
  columns.push(Array.from({ length: totalRows }, (_, r) => faceCell(face[r], faceW, mugRgb)));
340
448
  continue;
341
449
  }
342
- const w = boxWidth(s, cells);
450
+ const w = boxWidth(s, cells, textCap);
343
451
  const col = [];
344
452
  if (headers) {
345
453
  const t = s.title || "";
@@ -354,12 +462,12 @@ export function buildBar(cfg, target, spriteFor) {
354
462
  for (const item of VALUES[m.id] || []) {
355
463
  let body;
356
464
  if (Array.isArray(item) && item.length === 2) {
357
- const left = lbl + f(TEXT) + String(item[0]);
358
465
  const right = f(TEXT) + String(item[1]);
359
- body = left + " ".repeat(Math.max(0, w - vlen(left) - vlen(right))) + right;
466
+ const budget = Math.max(0, w - vlen(lbl) - vlen(String(item[1])) - 1); // 1 = min gap
467
+ const left = lbl + f(TEXT) + marquee(String(item[0]), budget, tick);
468
+ body = left + " ".repeat(Math.max(0, w - vlen(left) - vlen(String(item[1])))) + right;
360
469
  } else {
361
- body = lbl + f(TEXT) + String(item);
362
- body += " ".repeat(Math.max(0, w - vlen(body)));
470
+ body = lbl + f(TEXT) + marquee(String(item), Math.max(0, w - vlen(lbl)), tick);
363
471
  }
364
472
  col.push(bgsgrBox(boxRgb) + " " + body + " " + RESET);
365
473
  }
@@ -384,20 +492,16 @@ export function buildBar(cfg, target, spriteFor) {
384
492
  const right = f(TEXT) + String(item[1]) + (marker ? f(TEXT) + tail : "");
385
493
  const rightW = vlen(String(item[1])) + tailW;
386
494
  const labelMax = Math.max(0, w - vlen(lbl) - rightW - 1); // 1 = min gap
387
- let label = String(item[0]);
388
- if (vlen(label) > labelMax) label = [...label].slice(0, Math.max(0, labelMax - 1)).join("") + "…";
389
- const left = lbl + f(TEXT) + label;
495
+ const left = lbl + f(TEXT) + marquee(String(item[0]), labelMax, tick);
390
496
  const room = Math.max(0, w - vlen(left) - rightW);
391
497
  body = left + " ".repeat(room) + right;
392
498
  } else { // {mark, markRgb, text} (tasks)
393
499
  const markCol = item.markRgb ? f(item.markRgb) : f(TEXT);
394
500
  const m = String(item.mark);
395
501
  const mPad = m + (vlen(m) < 2 ? " " : ""); // normalize mark to 2 cols so text aligns
396
- let text = String(item.text);
397
502
  const head = markCol + mPad + " " + f(TEXT);
398
- const max = w - vlen(mPad) - 1 - tailW; // reserve gap + marker on the right
399
- if (vlen(text) > max) text = [...text].slice(0, Math.max(0, max - 1)).join("") + "…";
400
- body = head + text;
503
+ const max = Math.max(0, w - vlen(mPad) - 1 - tailW); // reserve gap + marker on the right
504
+ body = head + marquee(String(item.text), max, tick);
401
505
  body += " ".repeat(Math.max(0, w - tailW - vlen(body)));
402
506
  if (tail) body += f(TEXT) + tail;
403
507
  }
@@ -408,6 +512,21 @@ export function buildBar(cfg, target, spriteFor) {
408
512
  let body = renderValue(m, m.render === "bar" ? cells : 0, boxRgb);
409
513
  const rid = m.right;
410
514
  const rhs = rid && rid in VALUES ? f(TEXT) + String(VALUES[rid]) : "";
515
+ // Plain text/number that overflows its column budget -> marquee. Skipped when
516
+ // the value carries ANSI/OSC escapes (colours, hyperlinks): those can't be
517
+ // sliced by column without corrupting the escape sequence.
518
+ const r = m.render || "text";
519
+ if ((r === "text" || r === "number") && !("group" in m) && m.id in VALUES) {
520
+ const raw = String(VALUES[m.id]);
521
+ const lbl = m.icon ? m.icon + " " : "";
522
+ const budget = w - vlen(lbl) - vlen(rhs);
523
+ if (!/[\x1b]/.test(raw) && budget > 0 && vlen(raw) > budget) {
524
+ let col;
525
+ if (m.color === "threshold") col = threshold(parseInt(raw.replace(/\D/g, "") || "0", 10));
526
+ else col = m.color ? rgbOf(m.color) : TEXT;
527
+ body = lbl + f(col) + marquee(raw, budget, tick);
528
+ }
529
+ }
411
530
  body += " ".repeat(Math.max(0, w - vlen(body) - vlen(rhs))) + rhs;
412
531
  col.push(bgsgrBox(boxRgb) + " " + body + " " + RESET);
413
532
  }
@@ -456,11 +575,12 @@ function main() {
456
575
  p = path.isAbsolute(arg) ? arg : path.join(process.cwd(), arg);
457
576
  try { readFileSync(p); } catch { p = path.join(REPO, "presets", path.basename(arg)); }
458
577
  } else {
459
- p = path.join(REPO, "presets", "default.toml");
578
+ p = path.join(REPO, "presets", "standard.toml");
460
579
  }
461
580
  const target = process.argv[3] ? parseInt(process.argv[3], 10) : 100;
581
+ const tick = process.argv[4] ? parseInt(process.argv[4], 10) : 0; // marquee phase for previews
462
582
  const cfg = parseToml(readFileSync(p, "utf8"));
463
- const res = buildBar(cfg, target);
583
+ const res = buildBar(cfg, target, undefined, tick);
464
584
  const out = ["", ` preset: ${path.basename(p)} style=${res.style} headers=${res.headers} bar=${res.cells}`, ""];
465
585
  out.push(...res.lines, "");
466
586
  process.stdout.write(out.join("\n") + "\n");
package/src/statusline.js CHANGED
@@ -7,18 +7,18 @@
7
7
  // settings.json:
8
8
  // "statusLine": { "type": "command",
9
9
  // "command": "node /abs/path/src/statusline.js", "refreshInterval": 1 }
10
- // Config: $DOOMBAR_PRESET (default presets/default.toml) State: $MUGSHOT_STATE
10
+ // Config: $DOOMBAR_PRESET (default presets/standard.toml) State: $MUGSHOT_STATE
11
11
 
12
12
  import {
13
- readFileSync, writeFileSync, openSync, fstatSync, readSync, closeSync, statfsSync, statSync,
13
+ readFileSync, writeFileSync, renameSync, openSync, fstatSync, readSync, closeSync, statfsSync, statSync,
14
14
  } from "node:fs";
15
15
  import os from "node:os";
16
16
  import path from "node:path";
17
17
  import { fileURLToPath, pathToFileURL } from "node:url";
18
- import { spawnSync } from "node:child_process";
19
18
  import { parse as parseToml } from "smol-toml";
20
19
  import { pyround, sgrFg } from "./ansi.js";
21
- import { buildBar, setValues, OK, TEXT, CRIT } from "./render.js";
20
+ import { buildBar, setValues, resolvePreset, OK, TEXT, CRIT } from "./render.js";
21
+ import { foldBatch, statePaths } from "./fold.js";
22
22
 
23
23
  const HERE = path.dirname(fileURLToPath(import.meta.url));
24
24
  const REPO = path.dirname(HERE);
@@ -32,14 +32,9 @@ const GEIGER_BINS = 14;
32
32
 
33
33
  const has = (o, k) => Object.prototype.hasOwnProperty.call(o || {}, k);
34
34
 
35
- function git(cwd, ...args) {
36
- try {
37
- const r = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8", timeout: 1000 });
38
- return r.status === 0 ? r.stdout.trim() : null;
39
- } catch {
40
- return null;
41
- }
42
- }
35
+ // git is no longer spawned here. The async hook snapshots it into the journal (see hook.js
36
+ // + fold.js); buildValues reads the folded snapshot from state.git. This keeps the render
37
+ // hot path spawn-free the Windows MSYS "bash flood" cannot happen by construction.
43
38
 
44
39
  // Clip a display label to at most `n` code points, ending with … when truncated,
45
40
  // so an oversized repo or branch name can't blow up the PROJECT box width.
@@ -111,7 +106,7 @@ function godFlash(data, advTs, now) {
111
106
 
112
107
  const f = sgrFg;
113
108
 
114
- export function buildValues(data) {
109
+ export function buildValues(data, git) {
115
110
  const v = {};
116
111
  const cw = data.context_window || {};
117
112
  if ("used_percentage" in cw) v["context.hp"] = pyround(cw.used_percentage);
@@ -156,14 +151,13 @@ export function buildValues(data) {
156
151
  if (cwd) {
157
152
  const name = clip(path.basename(cwd.replace(/[/\\]+$/, "")) || cwd, 24);
158
153
  try { v["loc.cwd"] = _link(name, pathToFileURL(cwd).href); } catch { v["loc.cwd"] = name; }
159
- const br = git(cwd, "branch", "--show-current");
154
+ // git fields come from the folded snapshot the async hook wrote, not a live spawn.
155
+ const { br = null, lr = null, st = null } = git || {};
160
156
  if (br) { const brLbl = clip(br, 24); v["git.branch"] = repoUrl ? _link(brLbl, `${repoUrl}/tree/${br}`) : brLbl; }
161
- const lr = git(cwd, "rev-list", "--count", "--left-right", "@{u}...HEAD");
162
157
  if (lr && lr.includes("\t")) {
163
158
  const [behind, ahead] = lr.split("\t");
164
159
  v["git.behind"] = `↓${behind}`; v["git.ahead"] = `↑${ahead}`;
165
160
  }
166
- const st = git(cwd, "status", "--porcelain");
167
161
  if (st !== null) v["git.status"] = String(st.split("\n").filter((l) => l.trim()).length);
168
162
  // Merge changed-file count + pull/push onto one line (icons baked in, like model.mode):
169
163
  // "✎ <files> ⇅ ↓<behind> ↑<ahead>" — files first, then pull/push.
@@ -189,14 +183,54 @@ function _pick(bucket) {
189
183
  return x % 3;
190
184
  }
191
185
 
192
- function statePath(data) {
193
- if (process.env.MUGSHOT_STATE) return process.env.MUGSHOT_STATE;
194
- const sid = String(data.session_id || "default").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 48);
195
- return path.join(TMP, `mugshot_${sid}.json`);
196
- }
186
+ // Fold the per-session journal into the checkpoint and return the folded state.
187
+ //
188
+ // Read cost is O(events since last render): we read only journal bytes past the stored
189
+ // offset, so a multi-hour session never re-reads old events. Invariant: checkpoint.state
190
+ // always equals fold(journal[0..offset]); state + offset are persisted together atomically,
191
+ // so the reducer's push/increment ops never double-count across renders.
192
+ export function loadState(data) {
193
+ const { checkpoint, journal } = statePaths(data.session_id);
197
194
 
198
- function readState(data) {
199
- try { return JSON.parse(readFileSync(statePath(data), "utf8")); } catch { return {}; }
195
+ let size = -1;
196
+ try { size = statSync(journal).size; } catch { /* no journal yet */ }
197
+
198
+ let raw = null;
199
+ try { raw = readFileSync(checkpoint, "utf8"); } catch { /* no checkpoint */ }
200
+ let st;
201
+ if (raw === null) {
202
+ st = { offset: 0 }; // no checkpoint -> recompute from journal start
203
+ } else {
204
+ try { st = JSON.parse(raw); } catch { st = null; }
205
+ if (!st || typeof st !== "object") st = { offset: 0 }; // corrupt -> full recompute (journal has full history)
206
+ else if (typeof st.offset !== "number") st.offset = Math.max(0, size); // externally-supplied state is current
207
+ }
208
+
209
+ if (size < 0) return st; // no journal -> state stands as-is
210
+ if (st.offset > size) st = { offset: 0 }; // journal truncated/reset -> recompute from 0
211
+
212
+ if (size > st.offset) {
213
+ let chunk = "";
214
+ try {
215
+ const fd = openSync(journal, "r");
216
+ const buf = Buffer.alloc(size - st.offset);
217
+ readSync(fd, buf, 0, buf.length, st.offset);
218
+ closeSync(fd);
219
+ chunk = buf.toString("utf8");
220
+ } catch { chunk = ""; }
221
+ const lastNl = chunk.lastIndexOf("\n"); // consume complete lines only; keep any partial tail
222
+ if (lastNl >= 0) {
223
+ foldBatch(st, chunk.slice(0, lastNl).split("\n"));
224
+ st.offset += Buffer.byteLength(chunk.slice(0, lastNl + 1), "utf8");
225
+ }
226
+ }
227
+
228
+ try { // persist state + offset together, atomically
229
+ const tmp = `${checkpoint}.${process.pid}.tmp`;
230
+ writeFileSync(tmp, JSON.stringify(st));
231
+ renameSync(tmp, checkpoint);
232
+ } catch { /* ignore: next render retries */ }
233
+ return st;
200
234
  }
201
235
 
202
236
  function ramPercent() {
@@ -366,7 +400,9 @@ export function activityValues(st, now) {
366
400
  const squad = st.squad || {};
367
401
  v["act.agents"] = String(Object.keys(squad).length);
368
402
  const agents = Object.values(squad).sort((a, b) => a.start - b.start);
369
- v["act.subagents"] = agents.map((a) => [clip(a.desc || a.type || "agent", 24), _dur(now - a.start)]);
403
+ // Clip generously (not 24): the box caps width and the label marquees, so a long
404
+ // agent description should stay long enough to be worth scrolling through.
405
+ v["act.subagents"] = agents.map((a) => [clip(a.desc || a.type || "agent", 60), _dur(now - a.start)]);
370
406
 
371
407
  const tasks = st.tasks && typeof st.tasks === "object" ? Object.values(st.tasks) : [];
372
408
  const live = tasks.filter((t) => t.status !== "deleted");
@@ -377,7 +413,7 @@ export function activityValues(st, now) {
377
413
  .sort((a, b) => (TASK_ORDER[a.status] - TASK_ORDER[b.status]) || (a.ts - b.ts));
378
414
  v["act.tasklist"] = ordered.map((t) => {
379
415
  const [mark, markRgb] = TASK_MARK[t.status] || ["🎯", null];
380
- return { mark, markRgb, text: clip(t.title, 24) };
416
+ return { mark, markRgb, text: clip(t.title, 60) }; // generous clip: box width caps it, title marquees
381
417
  });
382
418
 
383
419
  if ("errors" in st) v["act.errors"] = String(st.errors);
@@ -388,13 +424,13 @@ function main() {
388
424
  let data = {};
389
425
  try { data = JSON.parse(readFileSync(0, "utf8")); } catch { data = {}; }
390
426
 
391
- const preset = process.env.DOOMBAR_PRESET || path.join(REPO, "presets", "default.toml");
427
+ const preset = process.env.DOOMBAR_PRESET || path.join(REPO, "presets", "standard.toml");
392
428
  const cfg = parseToml(readFileSync(preset, "utf8"));
393
429
 
394
430
  const now = Date.now() / 1000;
395
- const st = readState(data);
431
+ const st = loadState(data);
396
432
  const cwd = data.cwd || (data.workspace || {}).current_dir;
397
- const values = { ...buildValues(data), ...activityValues(st, now), ...sysValues(cwd), ...statsValues(data, cwd) };
433
+ const values = { ...buildValues(data, st.git), ...activityValues(st, now), ...sysValues(cwd), ...statsValues(data, cwd) };
398
434
  const [advModel, advTs] = advisorInfo(data.transcript_path || "");
399
435
  if (advModel) values["advisor.model"] = advModel;
400
436
  const god_until = godFlash(data, advTs, now);
@@ -425,7 +461,17 @@ function main() {
425
461
  };
426
462
 
427
463
  const target = parseInt(process.env.COLUMNS || "100", 10);
428
- const res = buildBar(cfg, target, spriteFor);
464
+ const tick = Math.floor(now); // one marquee step per refresh (~1s); pure fn of time
465
+ // Pick the preset that fits the terminal: the chosen preset is the ceiling; if it
466
+ // (at its minimum scale) overflows COLUMNS, fall back down its [bar].fallback chain.
467
+ // Sibling presets resolve relative to the chosen preset's directory.
468
+ const presetDir = path.dirname(preset);
469
+ const loadByName = (name) => {
470
+ try { return parseToml(readFileSync(path.join(presetDir, `${name}.toml`), "utf8")); }
471
+ catch { return null; }
472
+ };
473
+ const selected = resolvePreset(cfg, target, loadByName, spriteFor);
474
+ const res = buildBar(selected, target, spriteFor, tick);
429
475
  process.stdout.write(res.lines.join("\n") + "\n");
430
476
  }
431
477
 
@@ -1,38 +0,0 @@
1
- # default — balanced (the live-mockup look)
2
- [bar]
3
- border_style = "vertical"
4
- border_color = "term-fg"
5
- box_background = "term-bg"
6
- headers = true
7
-
8
- [mugshot]
9
- background = "#000000"
10
-
11
- [[segment]]
12
- type = "box"
13
- title = "USAGE"
14
- metric = [
15
- { id = "context.hp", render = "bar", icon = "🧠", color = "threshold" },
16
- { id = "ratelimit.5h", render = "bar", icon = "🕔", color = "threshold" },
17
- { id = "ratelimit.7d", render = "bar", icon = "📅", color = "threshold" },
18
- ]
19
-
20
- [[segment]]
21
- type = "box"
22
- title = "SAVE"
23
- metric = [
24
- { id = "save.leanctx", render = "text", icon = "🪶" },
25
- { id = "save.lingua", render = "text", icon = "📜" },
26
- ]
27
-
28
- [[segment]]
29
- type = "mugshot"
30
-
31
- [[segment]]
32
- type = "box"
33
- title = "GIT"
34
- metric = [
35
- { id = "git.branch", render = "text", icon = "🌿" },
36
- { group = ["git.behind", "git.ahead"], render = "number", sep = " ", icon = "⇅" },
37
- { id = "cost.total", render = "number", icon = "💰" },
38
- ]