@promptctl/cc-candybar 1.41.0 → 1.41.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.41.0",
3
+ "version": "1.41.1",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -91,9 +91,9 @@
91
91
  "mobx": "^6.15.0"
92
92
  },
93
93
  "optionalDependencies": {
94
- "@promptctl/cc-candybar-darwin-arm64": "1.41.0",
95
- "@promptctl/cc-candybar-darwin-x64": "1.41.0",
96
- "@promptctl/cc-candybar-linux-x64": "1.41.0",
97
- "@promptctl/cc-candybar-linux-arm64": "1.41.0"
94
+ "@promptctl/cc-candybar-darwin-arm64": "1.41.1",
95
+ "@promptctl/cc-candybar-darwin-x64": "1.41.1",
96
+ "@promptctl/cc-candybar-linux-x64": "1.41.1",
97
+ "@promptctl/cc-candybar-linux-arm64": "1.41.1"
98
98
  }
99
99
  }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import net from "node:net";
3
3
  import path from "node:path";
4
4
  import { launchDetachedSync } from "../proc/launch";
5
+ import { heapCapMb } from "./limits";
5
6
  import process from "node:process";
6
7
  import {
7
8
  socketPath,
@@ -656,9 +657,11 @@ function sleep(ms: number): Promise<void> {
656
657
 
657
658
  // ─── Default spawn implementation ───────────────────────────────────────────
658
659
  //
659
- // Cap V8 old-generation at 400 MB so GC fires before RSS hits the 512 MB hard
660
- // limit. The Rust client mirrors this in rust-client/src/main.rs
661
- // (spawn_daemon_detached) — keep the two in sync when changing this value.
660
+ // [LAW:one-source-of-truth] The V8 old-space cap is derived from the daemon's
661
+ // RSS budget (limits.ts: heapCapMb), never a literal here — the cap must sit
662
+ // ABOVE the RSS backstop so the graceful path fires first, and only one owner
663
+ // of the budget can keep that order true. The Rust client derives the same
664
+ // value the same way (rust-client/src/launch.rs).
662
665
  //
663
666
  // [LAW:single-enforcer] Routes through src/proc/launch so daemon-spawn shows
664
667
  // up in subprocess metering (category "daemon-spawn"). The launch primitive
@@ -674,7 +677,7 @@ function spawnDaemonDetachedReal(): boolean {
674
677
  // discarded the Promise and unconditionally returned true.
675
678
  const result = launchDetachedSync({
676
679
  bin: node,
677
- args: ["--max-old-space-size=400", script, "daemon"],
680
+ args: [`--max-old-space-size=${heapCapMb(process.env)}`, script, "daemon"],
678
681
  category: "daemon-spawn",
679
682
  });
680
683
  return result.ok;
@@ -8,10 +8,66 @@ import { dlog, type DaemonLogger } from "./log";
8
8
  // Only the RSS trigger remains — idle and age limits were removed because they
9
9
  // interrupted active sessions. The RSS limit is a true anomaly backstop; normal
10
10
  // operation should never approach it now that transcript parsing is pruned.
11
- const DEFAULT_RSS_LIMIT =
12
- (parseInt(process.env["CC_CANDYBAR_RSS_LIMIT_MB"] ?? "", 10) || 512) *
13
- 1024 *
14
- 1024;
11
+ //
12
+ // [LAW:one-source-of-truth] The daemon's memory budget is ONE number, read from
13
+ // ONE place. Two limits derive from it and their ORDER is the whole point:
14
+ //
15
+ // RSS backstop (this module) — graceful: heap snapshot, logged shutdown,
16
+ // clean restart on the next tick.
17
+ // V8 old-space cap (spawners) — hard: V8 aborts with SIGABRT below every JS
18
+ // handler, so no log line, no snapshot, and
19
+ // the next daemon finds only a stale socket.
20
+ //
21
+ // The cap sits at HEAP_CAP_OVER_RSS × the backstop, a margin wide enough that
22
+ // the graceful path fires first under any growth the 60 s poll can see (a
23
+ // burst that doubles RSS inside one poll window can still reach the hard cap).
24
+ // Before this the two were unrelated literals (400 MB heap in
25
+ // each spawner, 512 MB RSS here): a cold daemon seeding a large transcript tree
26
+ // for a dozen sessions blew the heap in seconds, aborted silently, and crash-
27
+ // looped on every render tick while the backstop — a 60 s poll — never got a
28
+ // turn. Raising the env override raises BOTH, because both spawners derive the
29
+ // cap through heapCapMb below. The Rust client mirrors RSS_LIMIT_ENV,
30
+ // DEFAULT_RSS_LIMIT_MB, and HEAP_CAP_OVER_RSS as literals
31
+ // (rust-client/src/launch.rs); scripts/check-protocol.mjs fails the build on
32
+ // drift.
33
+ export const RSS_LIMIT_ENV = "CC_CANDYBAR_RSS_LIMIT_MB";
34
+ export const DEFAULT_RSS_LIMIT_MB = 2048;
35
+ export const HEAP_CAP_OVER_RSS = 2;
36
+
37
+ // [LAW:parse-dont-validate] Absent → default; a positive integer → that; present
38
+ // but malformed → throw. Only an operator ever sets this variable, so garbage
39
+ // is an operator error, and `|| default` would silently run at a budget they
40
+ // did not ask for. [LAW:no-silent-failure]
41
+ //
42
+ // [LAW:one-source-of-truth] The grammar is ONE rule both runtimes apply
43
+ // verbatim — ASCII digits only, > 0, within the safe-integer range —
44
+ // so the spawner and the daemon it spawns accept and reject the same values
45
+ // (rust-client/src/launch.rs heap_cap_mb). A grammar that differed by so much
46
+ // as a leading `+` would let a client spawn a daemon that refuses to boot.
47
+ export function rssLimitMb(env: NodeJS.ProcessEnv): number {
48
+ const raw = env[RSS_LIMIT_ENV];
49
+ if (raw === undefined) return DEFAULT_RSS_LIMIT_MB;
50
+ const mb = /^\d+$/.test(raw) ? Number(raw) : NaN;
51
+ if (!Number.isSafeInteger(mb) || mb <= 0) {
52
+ throw new Error(
53
+ `${RSS_LIMIT_ENV} must be a positive integer (MB), got ${JSON.stringify(raw)}`,
54
+ );
55
+ }
56
+ return mb;
57
+ }
58
+
59
+ // The `--max-old-space-size` value a spawner hands node for the daemon.
60
+ export function heapCapMb(env: NodeJS.ProcessEnv): number {
61
+ return rssLimitMb(env) * HEAP_CAP_OVER_RSS;
62
+ }
63
+
64
+ const BYTES_PER_MB = 1024 * 1024;
65
+
66
+ // The budget in the unit `process.memoryUsage().rss` reports.
67
+ export function rssLimitBytes(env: NodeJS.ProcessEnv): number {
68
+ return rssLimitMb(env) * BYTES_PER_MB;
69
+ }
70
+
15
71
  const DEFAULT_CHECK_INTERVAL = 60 * 1000;
16
72
  const HEAP_SNAPSHOT_KEEP = 3;
17
73
 
@@ -42,7 +98,7 @@ export interface LimitsHandle {
42
98
  }
43
99
 
44
100
  export function makeLimits(deps: LimitsDeps): LimitsHandle {
45
- const rssLimit = deps.rssLimitBytes ?? DEFAULT_RSS_LIMIT;
101
+ const rssLimit = deps.rssLimitBytes ?? DEFAULT_RSS_LIMIT_MB * BYTES_PER_MB;
46
102
  const keep = deps.snapshotsKeep ?? HEAP_SNAPSHOT_KEEP;
47
103
  let triggered = false;
48
104
 
package/src/daemon/log.ts CHANGED
@@ -2,35 +2,34 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { logPath } from "./paths";
4
4
 
5
- const MAX_BYTES = 5 * 1024 * 1024;
5
+ export const MAX_BYTES = 5 * 1024 * 1024;
6
6
  const KEEP_GENERATIONS = 3;
7
7
 
8
- let stream: fs.WriteStream | null = null;
9
- let bytesWritten = 0;
8
+ // [LAW:no-ambient-temporal-coupling] Every line is a synchronous append, so a
9
+ // line is on disk the moment the call returns — including the death line each
10
+ // shutdown path writes last, which an async stream dropped whenever
11
+ // `process.exit` outran its flush. The daemon writes a handful of short lines
12
+ // per second; a sync append is microseconds. No stream means nothing to flush,
13
+ // nothing to close, and no window in which a late writer can reopen a sink
14
+ // that nobody waits for. [LAW:polishing-by-subtraction]
15
+ let bytesWritten: number | null = null;
10
16
 
11
- function ensureStream(): fs.WriteStream {
12
- if (stream) return stream;
13
- const filePath = logPath();
17
+ // Pre-load size once so rotation triggers correctly across daemon restarts.
18
+ function currentBytes(filePath: string): number {
19
+ if (bytesWritten !== null) return bytesWritten;
14
20
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
15
- // Pre-load size so rotation triggers correctly across daemon restarts.
16
21
  try {
17
22
  bytesWritten = fs.statSync(filePath).size;
18
23
  } catch {
19
24
  bytesWritten = 0;
20
25
  }
21
- stream = fs.createWriteStream(filePath, { flags: "a" });
22
- return stream;
26
+ return bytesWritten;
23
27
  }
24
28
 
25
29
  // Self-rotation: when daemon.log exceeds MAX_BYTES, shift .1→.2, .2→.3, drop
26
30
  // the oldest, and start fresh. Daemon-internal so we don't depend on any
27
31
  // external rotator. Cheap because rotation only runs at the rollover boundary.
28
- function rotate(): void {
29
- const filePath = logPath();
30
- if (stream) {
31
- stream.end();
32
- stream = null;
33
- }
32
+ function rotate(filePath: string): void {
34
33
  for (let i = KEEP_GENERATIONS - 1; i >= 1; i--) {
35
34
  const src = `${filePath}.${i}`;
36
35
  const dst = `${filePath}.${i + 1}`;
@@ -44,26 +43,39 @@ function rotate(): void {
44
43
  bytesWritten = 0;
45
44
  }
46
45
 
46
+ export type LogLevel = "info" | "warn" | "error";
47
+
47
48
  // [LAW:locality-or-seam] The logging capability daemon components depend on.
48
49
  // `dlog` is the daemon's implementation (writes to daemon.log); consumers that
49
50
  // inject a different impl (a quiet default in tests) take this shape.
50
- export type DaemonLogger = (
51
- level: "info" | "warn" | "error",
52
- msg: string,
53
- ) => void;
51
+ export type DaemonLogger = (level: LogLevel, msg: string) => void;
54
52
 
55
- export function dlog(level: "info" | "warn" | "error", msg: string): void {
53
+ export function dlog(level: LogLevel, msg: string): void {
56
54
  const line = `${new Date().toISOString()} [${level}] ${msg}\n`;
57
- const buf = Buffer.from(line, "utf8");
58
- const s = ensureStream();
59
- s.write(buf);
60
- bytesWritten += buf.length;
61
- if (bytesWritten >= MAX_BYTES) rotate();
62
- }
63
-
64
- export function closeLog(): void {
65
- if (stream) {
66
- stream.end();
67
- stream = null;
55
+ try {
56
+ // [LAW:single-enforcer] Path resolution reaches os.homedir(); it lives
57
+ // inside the one boundary that makes dlog total.
58
+ const filePath = logPath();
59
+ const before = currentBytes(filePath);
60
+ fs.appendFileSync(filePath, line);
61
+ bytesWritten = before + Buffer.byteLength(line, "utf8");
62
+ if (bytesWritten >= MAX_BYTES) rotate(filePath);
63
+ } catch (e) {
64
+ // [LAW:no-silent-failure] exception: the failure IS the log sink, so it
65
+ // cannot be reported through the log sink. A throw here would escape the
66
+ // crash handlers that call dlog first (uncaughtException → dlog →
67
+ // shutdown), taking the clean-death path down with it. stderr carries the
68
+ // line and the reason — the terminal when the daemon runs by hand, and
69
+ // /dev/null under a detached spawn; the daemon keeps serving either way.
70
+ // Nulling the counter re-runs the lazy init on the next call, so a state
71
+ // dir removed out from under the daemon is recreated for the next line.
72
+ bytesWritten = null;
73
+ try {
74
+ process.stderr.write(
75
+ `${line}cc-candybar: daemon.log unwritable: ${(e as Error).message}\n`,
76
+ );
77
+ } catch {
78
+ // stderr was the last channel.
79
+ }
68
80
  }
69
81
  }
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import net from "node:net";
3
+ import v8 from "node:v8";
3
4
  import process from "node:process";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { parseArgs } from "node:util";
@@ -33,7 +34,7 @@ import {
33
34
  releaseRegistration,
34
35
  readRegistryEntry,
35
36
  } from "./fork-bomb-breaker";
36
- import { dlog, closeLog } from "./log";
37
+ import { dlog } from "./log";
37
38
  import {
38
39
  PROTOCOL_VERSION,
39
40
  encodeFrame,
@@ -46,7 +47,12 @@ import { SessionUsageStore } from "./cache/session-usage-store";
46
47
  import { RenderCache } from "./cache/render";
47
48
  import { WatcherRegistry } from "./cache/watchers";
48
49
  import { RuntimeStats } from "./stats";
49
- import { makeLimits, realLimitsDeps, type LimitsHandle } from "./limits";
50
+ import {
51
+ makeLimits,
52
+ realLimitsDeps,
53
+ rssLimitBytes,
54
+ type LimitsHandle,
55
+ } from "./limits";
50
56
  import { armParentWatchdog, anchorFromEnv, pidAlive } from "./parent-watchdog";
51
57
  import { resetSpawnBackoff } from "./acquire";
52
58
  import { SessionState } from "./session-state";
@@ -154,6 +160,9 @@ let myStartTime: string | null = null;
154
160
  // waiting for the next boot's stale-sweep.
155
161
  let breakerRegistryPath: string | null = null;
156
162
 
163
+ // The parsed memory budget (bytes); set first thing in runDaemon.
164
+ let budgetBytes = 0;
165
+
157
166
  export function runDaemon(): void {
158
167
  // Catch-alls log + exit so the supervisor (the next client) can restart us.
159
168
  // [LAW:no-defensive-null-guards] These are *trust boundaries* — we are
@@ -179,6 +188,23 @@ export function runDaemon(): void {
179
188
  });
180
189
  }
181
190
 
191
+ // [LAW:effects-at-boundaries] The memory budget is parsed here, before any
192
+ // resource is committed — a malformed override is refused before the breaker
193
+ // registers us, before the bind, before the lease, and before a `daemon up`
194
+ // line could claim a boot that is about to die. Parsed once, threaded into
195
+ // armLimits and the boot line.
196
+ // [LAW:single-enforcer] Refused through the same death funnel as every other
197
+ // boot failure. A synchronous throw here is NOT uncaught — it lands in
198
+ // index.ts's catch, whose stderr the detached spawn discards — so the one
199
+ // line that says why the daemon never came up would go nowhere.
200
+ try {
201
+ budgetBytes = rssLimitBytes(process.env);
202
+ } catch (err) {
203
+ dlog("error", `refusing to boot: ${(err as Error).message}`);
204
+ shutdown(1);
205
+ return;
206
+ }
207
+
182
208
  // [LAW:single-enforcer] The fork-bomb circuit breaker runs FIRST among the
183
209
  // resource-committing steps (no dir created, no socket touched, no session
184
210
  // state loaded) — the whole point of a load-independent backstop is that it
@@ -375,7 +401,12 @@ function onListening(sockPath: string): void {
375
401
  }
376
402
  dlog(
377
403
  "info",
378
- `daemon up: pid=${process.pid} v=${PROTOCOL_VERSION} sock=${sockPath}`,
404
+ // [FRAMING:representation] Report the heap cap V8 actually applied (the
405
+ // territory), not the flag the spawner meant to pass (the map) — the one
406
+ // question a silent SIGABRT crash-loop leaves open is "which cap was live".
407
+ `daemon up: pid=${process.pid} v=${PROTOCOL_VERSION} sock=${sockPath} ` +
408
+ `heapCap=${Math.round(v8.getHeapStatistics().heap_size_limit / 1048576)}MB ` +
409
+ `rssLimit=${Math.round(budgetBytes / 1048576)}MB`,
379
410
  );
380
411
  // [LAW:single-enforcer] This bind is the one process-wide fact that answers
381
412
  // "did an outage just end" — see resetSpawnBackoff's doc comment in
@@ -458,7 +489,9 @@ function armBinaryWatch(): void {
458
489
  let limits: LimitsHandle | null = null;
459
490
  function armLimits(): void {
460
491
  limits = makeLimits(
461
- realLimitsDeps(stats.startedAt.getTime(), (code) => shutdown(code)),
492
+ realLimitsDeps(stats.startedAt.getTime(), (code) => shutdown(code), {
493
+ rssLimitBytes: budgetBytes,
494
+ }),
462
495
  );
463
496
  limits.arm();
464
497
  }
@@ -569,7 +602,8 @@ function shutdown(code: number): void {
569
602
  (p) => fs.unlinkSync(p),
570
603
  );
571
604
  }
572
- closeLog();
605
+ // Every dlog above was a synchronous append (log.ts), so the death line is
606
+ // already on disk; nothing to flush before exit.
573
607
  process.exit(code);
574
608
  }
575
609