sprag-cli 3.133.0 → 3.135.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/bin/cli.js CHANGED
@@ -1163,6 +1163,9 @@ async function main() {
1163
1163
  // This session's subagent runs, matched to the session Claude Code is
1164
1164
  // drawing for by the transcript path / session id in its payload.
1165
1165
  let sessionDelegation;
1166
+ // How many times this session's conversation was compacted, from the same
1167
+ // parsed sessions; null when the session is not among them.
1168
+ let sessionCompactionCount = null;
1166
1169
  let runningNow = null;
1167
1170
  // Delegation-rule counts, read only when `--segments` names `rules`: the
1168
1171
  // chip is opt-in, so nothing else would look at them.
@@ -1178,6 +1181,15 @@ async function main() {
1178
1181
  } catch (e) {
1179
1182
  debug('statusline-data:session-delegation', e);
1180
1183
  }
1184
+ try {
1185
+ const { sessionCompactions } = await import('../src/statusline-data.js');
1186
+ sessionCompactionCount = sessionCompactions(sessions, {
1187
+ transcriptPath: extractTranscriptPath(stdinJson),
1188
+ sessionId: extractSessionId(stdinJson),
1189
+ });
1190
+ } catch (e) {
1191
+ debug('statusline-data:compactions', e);
1192
+ }
1181
1193
  // Subagents working right now, from the session's subagent transcripts: one
1182
1194
  // readdir and a stat per file, never a parse of a whole transcript.
1183
1195
  try {
@@ -1241,6 +1253,7 @@ async function main() {
1241
1253
  relaxUntil: isStatusline ? relaxUntilNow : undefined,
1242
1254
  delegationLevel: isStatusline ? delegationLevel : undefined,
1243
1255
  sessionDelegation,
1256
+ compactions: isStatusline ? sessionCompactionCount : undefined,
1244
1257
  runningSubagents: runningNow,
1245
1258
  ruleStats,
1246
1259
  ttlBucket,
@@ -34,6 +34,7 @@ struct Session: Decodable, Identifiable {
34
34
  let state: String?; let stateSince: Double?; let tools: [String]; let subagents: Int
35
35
  let cpu: Double?; let rssMb: Double?; let procs: Int?
36
36
  let cpuPct: Double?; let model: String?; let modelName: String?; let effort: String?; let context: Ctx?; let usage: SUsage?
37
+ let compactions: Int? // times the conversation was compacted; optional so a snapshot from an older sprag still decodes
37
38
  var id: Int { pid }
38
39
  }
39
40
  struct Totals: Decodable { let sessions: Int; let busy: Int; let subagents: Int; let cpu: Double?; let rssMb: Double?; let procs: Int?; let costUsd: Double? }
@@ -1677,6 +1678,10 @@ struct SessionRow: View {
1677
1678
  Text("컨텍스트").foregroundColor(.secondary)
1678
1679
  if let p = c.pct { Bar(value: p / 100, tint: p >= 80 ? .orange : agentTint(s.agent)).frame(width: 54); Text("\(Int(p))%").monospacedDigit() } else { Text(tokText(c.tokens)).monospacedDigit() }
1679
1680
  }
1681
+ // The panel's own scale: secondary, then the orange of a filling context, then the red of a danger pill.
1682
+ if let n = s.compactions, n >= 1 {
1683
+ Text("압축 \(n)").font(.system(size: 10.5, weight: .medium)).monospacedDigit().foregroundColor(n >= 3 ? .red : n == 2 ? .orange : .secondary).fixedSize().help(compactionTip(n))
1684
+ }
1680
1685
  Spacer(minLength: 0)
1681
1686
  }.font(.system(size: 11.5)).lineLimit(1)
1682
1687
  }
@@ -2239,6 +2244,8 @@ struct Fact: View {
2239
2244
  }
2240
2245
  }
2241
2246
  func tokenLine(_ u: SUsage) -> String { "입력 \(tokText(u.tokens.input)), 캐시 읽기 \(tokText(u.tokens.cacheRead)), 캐시 쓰기 \(tokText(u.tokens.cacheWrite)), 출력 \(tokText(u.tokens.output))" }
2247
+ /** The tooltip of the compaction mark: each pass replaces the earlier conversation with a summary. */
2248
+ func compactionTip(_ n: Int) -> String { "이 세션에서 대화가 \(n)번 압축됐습니다. 압축될 때마다 앞에서 정한 내용이 요약으로 줄어듭니다" }
2242
2249
  func contextLine(_ c: Ctx) -> String { c.pct.map { "\(Int($0))% (\(tokText(c.tokens))" + (c.window.map { " / \(tokText($0)))" } ?? ")") } ?? tokText(c.tokens) }
2243
2250
  /** One session in full, opened by clicking its row. */
2244
2251
  struct SessionView: View {
@@ -2256,6 +2263,7 @@ struct SessionView: View {
2256
2263
  Divider().padding(.vertical, 2)
2257
2264
  Fact(label: "모델", value: [s.modelName ?? s.model ?? "알 수 없음", s.effort.map { "effort \($0)" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
2258
2265
  if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
2266
+ if let n = s.compactions, n >= 1 { Fact(label: "압축", value: "\(n)번") }
2259
2267
  if let u = s.usage {
2260
2268
  Fact(label: "토큰", value: tokenLine(u))
2261
2269
  Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
@@ -2463,10 +2471,16 @@ struct SessionTile: View {
2463
2471
  var phase: Phase = .active
2464
2472
  var work: [(name: String, w: Work)] = []
2465
2473
  var subs = 0, subsActive = 0 // sessions this one started, and how many of them are working
2466
- func mini<V: View>(_ label: String, _ value: String, @ViewBuilder _ plot: () -> V) -> some View {
2474
+ func mini<V: View>(_ label: String, _ value: String, compactions: Int? = nil, @ViewBuilder _ plot: () -> V) -> some View {
2467
2475
  VStack(alignment: .leading, spacing: 3) {
2468
2476
  Text(label).font(.system(size: 10)).foregroundColor(pal.text2)
2469
- Text(value).font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).minimumScaleFactor(0.7)
2477
+ HStack(alignment: .firstTextBaseline, spacing: 5) {
2478
+ Text(value).font(.system(size: 15, weight: .semibold)).foregroundColor(pal.text).lineLimit(1).minimumScaleFactor(0.7)
2479
+ // The same scale as the context meter: muted text, then the palette's warning, then its critical colour.
2480
+ if let n = compactions, n >= 1 {
2481
+ Text("압축 \(n)").font(.system(size: 10, weight: .medium)).monospacedDigit().foregroundColor(severity(Double(n), pal.text2, pal, warnAt: 2, critAt: 3).color).lineLimit(1).fixedSize().help(compactionTip(n))
2482
+ }
2483
+ }
2470
2484
  plot().frame(height: 22)
2471
2485
  }.frame(maxWidth: .infinity, alignment: .leading)
2472
2486
  }
@@ -2495,10 +2509,10 @@ struct SessionTile: View {
2495
2509
  HStack(alignment: .top, spacing: 12) {
2496
2510
  if let c = s.context, let p = c.pct {
2497
2511
  let sv = severity(p, tint, pal, warnAt: 80, critAt: 95)
2498
- mini("컨텍스트", "\(Int(p))%") {
2512
+ mini("컨텍스트", "\(Int(p))%", compactions: s.compactions) {
2499
2513
  HStack(spacing: 5) { Meter(value: p / 100, fill: sv.color); if let sym = sv.symbol { Image(systemName: sym).font(.system(size: 10)).foregroundColor(sv.color) } }.frame(maxHeight: .infinity, alignment: .center)
2500
2514
  }
2501
- } else { mini("컨텍스트", s.context.map { tokText($0.tokens) } ?? "-") { Color.clear } }
2515
+ } else { mini("컨텍스트", s.context.map { tokText($0.tokens) } ?? "-", compactions: s.compactions) { Color.clear } }
2502
2516
  // Each bar is this session's share of the whole machine, the same scale on every tile. The session's own trend is in its detail.
2503
2517
  mini("CPU", s.cpu == nil ? "-" : pct1(cpu)) { Meter(value: cpu / 100, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 전체 CPU에서 이 세션이 쓰는 몫입니다") }
2504
2518
  mini("메모리", s.rssMb == nil ? "-" : memText(mem)) { Meter(value: mem / RAM_MB, fill: tint).frame(maxHeight: .infinity, alignment: .center).help("막대는 기기 메모리 \(Int((RAM_MB / 1024).rounded())) GB에서 이 세션이 쓰는 몫입니다") }
@@ -2711,6 +2725,7 @@ struct DashboardView: View {
2711
2725
  Text(activity(s, now: snap.at)).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)
2712
2726
  Divider().padding(.vertical, 2)
2713
2727
  if let c = s.context { Fact(label: "컨텍스트", value: contextLine(c)) }
2728
+ if let n = s.compactions, n >= 1 { Fact(label: "압축", value: "\(n)번") }
2714
2729
  if let u = s.usage {
2715
2730
  Fact(label: "토큰", value: tokenLine(u))
2716
2731
  Fact(label: "비용", value: [u.costUsd.map { String(format: "$%.2f (정가 환산)", $0) } ?? "가격표 없음", u.requests.map { "요청 \(Int($0))회" } ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))
@@ -3331,13 +3346,32 @@ struct PanelView: View {
3331
3346
 
3332
3347
  // ---------- the menu bar item and its window ----------
3333
3348
  final class FloatPanel: NSPanel { override var canBecomeKey: Bool { true } }
3334
- func dockIcon() -> NSImage {
3335
- NSImage(size: NSSize(width: 512, height: 512), flipped: false) { r in
3336
- NSColor(red: 0.10, green: 0.10, blue: 0.098, alpha: 1).setFill()
3337
- NSBezierPath(roundedRect: r.insetBy(dx: 44, dy: 44), xRadius: 96, yRadius: 96).fill()
3338
- let glyph = NSAttributedString(string: "✇", attributes: [.font: NSFont.systemFont(ofSize: 280, weight: .bold), .foregroundColor: NSColor(red: 0.85, green: 0.35, blue: 0.15, alpha: 1)])
3339
- let size = glyph.size()
3340
- glyph.draw(at: NSPoint(x: r.midX - size.width / 2, y: r.midY - size.height / 2))
3349
+ /**
3350
+ * The Dock icon while the dashboard is open: the member's town animal, white on a coral rounded square, the same
3351
+ * species that runs in the menu bar. It is one still frame, redrawn only when the grade changes; a running Dock icon
3352
+ * would spend CPU and pull the eye away from the dashboard. Drawn on the macOS icon grid (an 824 square in 1024).
3353
+ */
3354
+ func dockIcon(_ grade: String?) -> NSImage {
3355
+ let sp = runnerSpecies(grade)
3356
+ // a frame that reads as that animal at rest in motion: wings up for fliers, mid-leap for the frog, a stride otherwise
3357
+ let frame = sp.fly > 0 || sp.x.contains("wings") ? 2 : sp.kind == 4 ? 2 : sp.kind == 7 ? 0 : sp.kind == 5 || sp.kind == 6 ? 1 : 7
3358
+ let still = runner(sp, frame: frame, idle: false)
3359
+ return NSImage(size: NSSize(width: 512, height: 512), flipped: false) { r in
3360
+ let k = r.width / 1024
3361
+ let body = NSRect(x: 100 * k, y: 100 * k, width: 824 * k, height: 824 * k)
3362
+ let shape = NSBezierPath(roundedRect: body, xRadius: 185 * k, yRadius: 185 * k)
3363
+ let top = NSColor(srgbRed: 0.941, green: 0.573, blue: 0.416, alpha: 1), bottom = NSColor(srgbRed: 0.788, green: 0.341, blue: 0.235, alpha: 1)
3364
+ NSGraphicsContext.saveGraphicsState()
3365
+ let sh = NSShadow(); sh.shadowColor = NSColor.black.withAlphaComponent(0.28); sh.shadowBlurRadius = 22 * k; sh.shadowOffset = NSSize(width: 0, height: -10 * k); sh.set()
3366
+ top.setFill(); shape.fill()
3367
+ NSGraphicsContext.restoreGraphicsState()
3368
+ NSGradient(starting: top, ending: bottom)?.draw(in: shape, angle: -90)
3369
+ // a soft shadow on the ground under the animal
3370
+ NSColor(srgbRed: 0.478, green: 0.180, blue: 0.118, alpha: 0.35).setFill()
3371
+ NSBezierPath(ovalIn: NSRect(x: 262 * k, y: 262 * k, width: 500 * k, height: 44 * k)).fill()
3372
+ let w = 700 * k, h = w * still.size.height / still.size.width
3373
+ let white = NSImage(size: still.size, flipped: false) { rr in still.draw(in: rr); NSColor.white.set(); rr.fill(using: .sourceAtop); return true }
3374
+ white.draw(in: NSRect(x: r.midX - w / 2 + 10 * k, y: 250 * k, width: w, height: h))
3341
3375
  return true
3342
3376
  }
3343
3377
  }
@@ -3392,7 +3426,7 @@ final class App: NSObject {
3392
3426
  // A menu bar app has no Dock icon, so a dashboard that slipped behind other windows could only be found through the
3393
3427
  // menu bar again. While the window is open the app is a regular one: Dock icon, app switcher, and a click on either brings it back.
3394
3428
  NSApp.setActivationPolicy(.regular)
3395
- NSApp.applicationIconImage = dockIcon()
3429
+ dockGrade = model.snap?.animal?.grade; NSApp.applicationIconImage = dockIcon(dockGrade)
3396
3430
  if NSApp.mainMenu == nil { NSApp.mainMenu = dashboardMenu() }
3397
3431
  NSApp.activate(ignoringOtherApps: true)
3398
3432
  if dash?.isMiniaturized == true { dash?.deminiaturize(nil) }
@@ -3448,7 +3482,11 @@ final class App: NSObject {
3448
3482
  b.attributedTitle = out
3449
3483
  b.toolTip = model.sysCpu != nil ? String(format: "기기 전체 CPU %.0f%%, 그중 AI 세션 %.0f%%. 세션 %d개 실행 중", (model.sysCpu ?? 0) * 100, model.share(nil), s.totals.sessions) : "작업 중인 세션 수 / 실행 중인 세션 수"
3450
3484
  }
3485
+ var dockGrade: String? = nil // the grade the Dock icon was drawn for
3451
3486
  func animate() {
3487
+ if NSApp.activationPolicy() == .regular, model.snap?.animal?.grade != dockGrade {
3488
+ dockGrade = model.snap?.animal?.grade; NSApp.applicationIconImage = dockIcon(dockGrade)
3489
+ }
3452
3490
  // RunCat's rule, on the same thing RunCat measures: the whole machine. A runner that strolls while the machine is
3453
3491
  // flat out, because the agent sessions' own share happens to be small, reads as wrong.
3454
3492
  let load = min(100, max(0, (model.sysCpu ?? 0) * 100))
@@ -3724,6 +3762,8 @@ func dashboardTest(_ prefix: String) {
3724
3762
  DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) {
3725
3763
  let m = main.model
3726
3764
  print("DASHBOARD window \(main.dash.map { "\(Int($0.frame.width))x\(Int($0.frame.height)) visible \($0.isVisible)" } ?? "none") | panel closed \(!main.isOpen) | asked for detail \(m.wantDetail) | sessions \(m.snap?.sessions.count ?? 0) with detail \(m.snap?.sessions.filter { $0.detail != nil }.count ?? 0)")
3765
+ if let icon = NSApp.applicationIconImage { png(icon, "\(prefix)-dock.png") }
3766
+ print("DOCK icon drawn for grade \(main.dockGrade ?? "none") (species \(runnerSpecies(main.dockGrade).id))")
3727
3767
  print("DOCK regular app while the dashboard is open: \(NSApp.activationPolicy() == .regular) | icon set \(NSApp.applicationIconImage != nil) | menu \(NSApp.mainMenu != nil) | reopen handler \(NSApp.delegate is App)")
3728
3768
  print("STARTED BY " + (m.parentSession.isEmpty ? "none" : m.parentSession.map { c, up in "\(m.snap?.sessions.first { $0.pid == c }?.name ?? "\(c)") <- \(m.snap?.sessions.first { $0.pid == up }?.name ?? "\(up)")" }.sorted().joined(separator: " | ")))
3729
3769
  print("PHASE " + (m.snap?.sessions ?? []).map { s in "\(s.name ?? s.agent) \(m.phase(s)) [" + m.working(s, max: 3).map { "\($0.name) cpu \(pct1($0.w.cpu * 100)) gpu \(pct1($0.w.gpu * 100)) \(memText($0.w.mem))" }.joined(separator: "; ") + "]" }.joined(separator: " | "))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.133.0",
3
+ "version": "3.135.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -279,6 +279,7 @@ function claudeRow(file, { claudeDir, dataDir, now, table, env, getCache, detail
279
279
  effort,
280
280
  context: usage.context,
281
281
  usage: usage.usage,
282
+ compactions: usage.compactions,
282
283
  cpu: table ? 0 : null,
283
284
  cpuPct: null,
284
285
  rssMb: table ? 0 : null,
@@ -175,15 +175,19 @@ export function claudeUsage({ cache, transcript, sessionId, env, now }) {
175
175
  }
176
176
 
177
177
  /**
178
- * Model, context and usage of one Claude session. `cache` is the loaded
179
- * session-cache.json, shared by every row of one snapshot.
178
+ * Model, context, usage and compaction count of one Claude session. `cache` is
179
+ * the loaded session-cache.json, shared by every row of one snapshot.
180
+ *
181
+ * `compactions` is how many times this transcript's conversation was compacted,
182
+ * from its own cache entry (a subagent's are not added), and null when the
183
+ * transcript has no entry yet.
180
184
  *
181
185
  * @returns {{ model: string|null, modelName: string|null,
182
186
  * context: { tokens: number, window: number|null, pct: number|null }|null,
183
- * usage: object|null }}
187
+ * usage: object|null, compactions: number|null }}
184
188
  */
185
189
  export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env, now }) {
186
- const detail = { model: null, modelName: null, context: null, usage: null };
190
+ const detail = { model: null, modelName: null, context: null, usage: null, compactions: null };
187
191
  try {
188
192
  const ctxPath = join(dataDir, 'ctx-window.json');
189
193
  const tail = readTail(transcript);
@@ -199,6 +203,8 @@ export function claudeSessionDetail({ sessionId, transcript, dataDir, cache, env
199
203
  detail.context = { tokens, window, pct: window ? Math.round(tokens / window * 100) : null };
200
204
  }
201
205
  detail.usage = claudeUsage({ cache, transcript, sessionId, env, now });
206
+ const own = typeof transcript === 'string' ? peekCached(cache, transcript) : null;
207
+ if (own) detail.compactions = own.compactions;
202
208
  } catch { /* keep whatever was read */ }
203
209
  return detail;
204
210
  }
@@ -1145,6 +1145,22 @@ function buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g) {
1145
1145
  return ctxSeg;
1146
1146
  }
1147
1147
 
1148
+ /**
1149
+ * How many times this session's conversation was compacted: `Compacted 3×`.
1150
+ * Each compaction replaces the earlier conversation with a summary, so what was
1151
+ * decided early gets blurrier with every pass, and the tone darkens with the
1152
+ * count: gray at 1, yellow at 2, red from 3. Nothing at 0. It sits right after
1153
+ * the context chip because it is the history of that same fill level.
1154
+ */
1155
+ function buildCompactionsSeg(count, c, isIcon, verbose, g) {
1156
+ if (!Number.isInteger(count) || count < 1) return null;
1157
+ const tone = count >= 3 ? RED : count === 2 ? YELLOW : GRAY;
1158
+ const words = `Compacted ${count}×`;
1159
+ let text = words;
1160
+ if (isIcon && g.compactions) text = verbose ? `${g.compactions} ${words}` : `${g.compactions} ${count}×`;
1161
+ return `${c(tone)}${text}${c(RESET)}`;
1162
+ }
1163
+
1148
1164
  /** The warning chip the analyzer raised for this window, if any. */
1149
1165
  function buildSpikeSeg(spikeChip, c) {
1150
1166
  // Spike chip — one word only, keeps the statusline single-line.
@@ -1610,6 +1626,8 @@ function buildDoc2mdSeg(doc2md, singleLine, c, isIcon, verbose, g) {
1610
1626
  export const DEFAULT_SEGMENT_ORDER = [
1611
1627
  'cap-warn', 'spike',
1612
1628
  'usage', 'ctx',
1629
+ // Right after the context chip: how many times that context was compacted.
1630
+ 'compactions',
1613
1631
  'ttl',
1614
1632
  'model', 'effort', 'ultra',
1615
1633
  // Grouped by the timeframe each figure covers, because mixing them was the
@@ -1677,6 +1695,7 @@ function segmentsNamed(name, s, usageByKey) {
1677
1695
  case 'ttl': return [s.ttl];
1678
1696
  case 'month': return [s.month];
1679
1697
  case 'ctx': return [s.ctx];
1698
+ case 'compactions': return [s.compactions];
1680
1699
  case 'saved': return [s.saved];
1681
1700
  case 'period': return [s.period];
1682
1701
  // Every rate-limit window, in payload order.
@@ -1701,7 +1720,9 @@ function normalizeCompactLevel(level) {
1701
1720
  // Names kept in the default order at compact level 2 and 3. `usage` stands for
1702
1721
  // every rate-limit window; `version` joins only while an upgrade is available.
1703
1722
  const COMPACT_KEEP_3 = ['cap-warn', 'spike', 'usage', 'ctx', 'ttl'];
1704
- const COMPACT_KEEP_2 = [...COMPACT_KEEP_3, 'model', 'effort', 'ultra', 'delegated'];
1723
+ // `compactions` stays at level 2 but not 3: it is a health signal about the
1724
+ // session, not a chip that stops the work.
1725
+ const COMPACT_KEEP_2 = [...COMPACT_KEEP_3, 'compactions', 'model', 'effort', 'ultra', 'delegated'];
1705
1726
 
1706
1727
  /** The default-order names a compact level keeps, or null when it keeps all. */
1707
1728
  function compactKeepNames(level, updateAvailable) {
@@ -1826,7 +1847,7 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1826
1847
  * @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line). It also ignores `columns`.
1827
1848
  * @param {number} [opts.columns=0] - terminal width in cells (Claude Code exports it as COLUMNS). When set, the chips wrap at chip boundaries instead of being truncated by the terminal; 0 keeps one unbounded line. A verbose layout that would need chips dropped is re-rendered once in the compact layout first.
1828
1849
  * @param {number} [opts.maxLines=3] - most chip lines when `columns` is set; lower-priority tail chips collapse into a `+N` chip beyond that. Counts the chip lines only: the headline lines above them wrap at their own `|` and `·` joints and are not included. Cap, usage, ctx, spike chips are never dropped.
1829
- * @param {number} [opts.compactLevel=0] - 0 keeps `verbose` as given, 1 forces short labels, 2 adds folded headline lines (chips instead), the default chip set cut to cap-warn, spike, usage, ctx, ttl, model, effort, ultra, delegated (plus version while an upgrade is available) and at most 2 chip lines, 3 keeps cap-warn, spike, usage, ctx, ttl on one line. An explicit `segments` list is never filtered by the level.
1850
+ * @param {number} [opts.compactLevel=0] - 0 keeps `verbose` as given, 1 forces short labels, 2 adds folded headline lines (chips instead), the default chip set cut to cap-warn, spike, usage, ctx, compactions, ttl, model, effort, ultra, delegated (plus version while an upgrade is available) and at most 2 chip lines, 3 keeps cap-warn, spike, usage, ctx, ttl on one line. An explicit `segments` list is never filtered by the level.
1830
1851
  */
1831
1852
  export function formatReport(data, { color = true, verbose: verboseOpt = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines: maxLinesOpt = 3, compactLevel = 0 } = {}) {
1832
1853
  // Compact level: 1+ means short labels, 2+ folds the headline lines and trims
@@ -1885,6 +1906,7 @@ export function formatReport(data, { color = true, verbose: verboseOpt = false,
1885
1906
  spike: buildSpikeSeg(spikeChip, c),
1886
1907
  usage: buildUsageSegs(caps, capWarn, c, isIcon, verbose, g, color, mode),
1887
1908
  ctx: buildCtxSeg(ctxLive, contextWindow, c, isIcon, verbose, g),
1909
+ compactions: buildCompactionsSeg(data.compactions, c, isIcon, verbose, g),
1888
1910
  ttl: buildTtlSeg({ ttl, ttlBucket: data.ttlBucket, lastActivity }, timer, c, isIcon, verbose, g),
1889
1911
  // Model, then the effort that qualifies it: the same model answers
1890
1912
  // differently at `low` and at `max`, and the pair is one glance.
package/src/glyphs.js CHANGED
@@ -66,6 +66,10 @@ const ICON = {
66
66
  // Team: the people this machine is ranked among. U+1F465, East Asian Width W.
67
67
  team: '👥',
68
68
  ctx: '📦',
69
+ // Compactions: the conversation swept into a summary. U+1F9F9, East Asian Width
70
+ // W. The literal compression emoji 🗜 (U+1F5DC) is width N and would shift the
71
+ // line, for the reason given at `effort`.
72
+ compactions: '🧹',
69
73
  saved: '💰',
70
74
  used: '📊',
71
75
  reset: '🔄',
@@ -100,6 +104,7 @@ const NARROW = {
100
104
  month: '∑', // a running total
101
105
  team: '', // no glyph verified in the font yet; the team line's own words lead it
102
106
  ctx: '◧', // a box filling up
107
+ compactions: '', // no font-verified glyph; the chip's word leads it
103
108
  saved: '✓',
104
109
  used: '◩', // a split square: what the spend is made of
105
110
  reset: '↩', // the window turning over
@@ -48,7 +48,7 @@ export const SPECIES = {
48
48
  * above the company median (`needDlg`). `gt` marks a strict floor. Copied from
49
49
  * GRADES in site/assets/scene/office-scene.js, and test/office-species.test.js
50
50
  * pins the two, so `sprag team status` and the office page show one ladder.
51
- * The chick is the idle row (no spend in the period) and has no floor.
51
+ * The chick is the last row and has no floor. A person with no usage in the period is not ranked and shows as a ghost, so the chick is for someone who used little.
52
52
  */
53
53
  const row = (key, minSr, tier, needDlg = false, gt = false) => ({ key, minSr, tier, needDlg, gt });
54
54
  export const GRADES = [
package/src/parser.js CHANGED
@@ -69,6 +69,9 @@ function newParseState(track) {
69
69
  firstTimestamp: null,
70
70
  lastTimestamp: null,
71
71
  gatewayObserved: false,
72
+ // Times Claude Code compacted this conversation. A whole-session figure like
73
+ // gatewayObserved: it is not windowed and it travels with the request store.
74
+ compactions: 0,
72
75
  };
73
76
  }
74
77
 
@@ -122,6 +125,12 @@ function consumeLine(st, line) {
122
125
  st.sessionId = entry.sessionId;
123
126
  }
124
127
 
128
+ // Decided on the parsed fields, not on a substring: transcripts quote the
129
+ // marker inside message text, and other subtypes (microcompact_boundary) are
130
+ // not a compaction of the conversation. Counted before the usage return
131
+ // below, because a boundary line carries no message.usage.
132
+ if (entry.type === 'system' && entry.subtype === 'compact_boundary') st.compactions++;
133
+
125
134
  const msg = entry.message;
126
135
  if (!msg?.usage || !msg.id) return;
127
136
 
@@ -174,7 +183,7 @@ function snapshotStore(st, offset, filePath) {
174
183
  }
175
184
  return {
176
185
  offset, tailHash, sessionId: st.sessionId, firstTs: st.firstTimestamp, lastTs: st.lastTimestamp,
177
- gatewayObserved: !!st.gatewayObserved, reqs,
186
+ gatewayObserved: !!st.gatewayObserved, compactions: st.compactions, reqs,
178
187
  };
179
188
  }
180
189
 
@@ -183,6 +192,7 @@ function restoreState(st, stored) {
183
192
  st.firstTimestamp = stored.firstTs ?? null;
184
193
  st.lastTimestamp = stored.lastTs ?? null;
185
194
  st.gatewayObserved = !!stored.gatewayObserved;
195
+ st.compactions = Number.isInteger(stored.compactions) && stored.compactions >= 0 ? stored.compactions : 0;
186
196
  for (const row of stored.reqs) {
187
197
  if (!Array.isArray(row) || row.length < 9) throw new Error('malformed request row');
188
198
  const [id, ts, rawModel, input, cacheCreation, cacheRead, e5m, e1h, output] = row;
@@ -326,6 +336,7 @@ export async function parseSessionFile(filePath, { store = true, minBytes } = {}
326
336
  ...(modelTotals ? { modelTotals } : {}),
327
337
  ...(dayTotals ? { dayTotals } : {}),
328
338
  gatewayObserved: st.gatewayObserved,
339
+ compactions: st.compactions,
329
340
  };
330
341
  }
331
342
 
@@ -680,6 +691,7 @@ function trimToCutoff(session, cutoffMs) {
680
691
  ...(modelTotals ? { modelTotals } : {}),
681
692
  ...(dayTotals ? { dayTotals } : {}),
682
693
  gatewayObserved: session.gatewayObserved,
694
+ compactions: session.compactions,
683
695
  };
684
696
  }
685
697
 
@@ -24,7 +24,10 @@ import { writeViaTmp } from './state-file.js';
24
24
  import { envVar } from './env.js';
25
25
  import { debug } from './debug.js';
26
26
 
27
- export const STORE_VERSION = 1;
27
+ // 2: stores carry `compactions`, the count of compact_boundary lines before the
28
+ // offset. A v1 store has no count for the bytes it already consumed, so resuming
29
+ // from it would undercount; readStore discards it and the file is read whole once.
30
+ export const STORE_VERSION = 2;
28
31
  /** Transcripts smaller than this are cheap to parse whole and get no store. */
29
32
  export const STORE_MIN_BYTES = 4 * 1024 * 1024;
30
33
  /** How many bytes before the offset are hashed to prove the prefix is unchanged. */
@@ -45,7 +45,10 @@ const CACHE_PATH = join(userDataDir(), 'session-cache.json');
45
45
  // day and model), so cost can use each day's price row (#15). A v5 entry lacks
46
46
  // it, so a session crossing a price change would be priced at one day's rate
47
47
  // until its transcript changed.
48
- const CACHE_VERSION = 6;
48
+ // 7: sessions carry `compactions`, the number of times Claude Code compacted the
49
+ // conversation. A v6 entry lacks it, so a cached session would show no count
50
+ // until its transcript changed.
51
+ const CACHE_VERSION = 7;
49
52
  // Entries for transcripts this old are pruned on write. Keeps the file
50
53
  // bounded without an existence check per entry (which would cost the syscalls
51
54
  // the cache exists to avoid).
@@ -63,6 +66,7 @@ const PRUNE_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
63
66
  * @property {string} model
64
67
  * @property {Record<string, object>} [modelTotals] totals per model, present only when more than one model spent tokens
65
68
  * @property {Record<string, Record<string, object>>} [dayTotals] totals per UTC day and model, present only when the requests span more than one UTC day
69
+ * @property {number} compactions times the conversation was compacted (compact_boundary lines), 0 when never
66
70
  * @property {string} [projectDir]
67
71
  */
68
72
 
@@ -79,6 +83,7 @@ function serialize(session) {
79
83
  ...(session.modelTotals ? { modelTotals: session.modelTotals } : {}),
80
84
  ...(session.dayTotals ? { dayTotals: session.dayTotals } : {}),
81
85
  gatewayObserved: !!session.gatewayObserved,
86
+ compactions: Number.isInteger(session.compactions) && session.compactions >= 0 ? session.compactions : 0,
82
87
  };
83
88
  }
84
89
 
@@ -96,6 +101,7 @@ function deserialize(stored, filePath, projectDir) {
96
101
  ...(stored.modelTotals && typeof stored.modelTotals === 'object' ? { modelTotals: stored.modelTotals } : {}),
97
102
  ...(stored.dayTotals && typeof stored.dayTotals === 'object' ? { dayTotals: stored.dayTotals } : {}),
98
103
  gatewayObserved: !!stored.gatewayObserved,
104
+ compactions: Number.isInteger(stored.compactions) && stored.compactions >= 0 ? stored.compactions : 0,
99
105
  };
100
106
  }
101
107
 
@@ -2,9 +2,9 @@
2
2
  * Statusline data helpers that need more than a number from the payload.
3
3
  *
4
4
  * bin/cli.js assembles the report data inline and cannot be imported (it runs
5
- * on load), so the two derivations below live here where a test can reach them.
6
- * Both read only what the render has already loaded or one small JSON file the
7
- * statusline reads anyway; neither scans a transcript.
5
+ * on load), so the derivations below live here where a test can reach them.
6
+ * They read only what the render has already loaded or one small JSON file the
7
+ * statusline reads anyway; none scans a transcript.
8
8
  */
9
9
 
10
10
  import { resolve } from 'node:path';
@@ -17,6 +17,29 @@ const FAMILY_MAX = 14;
17
17
 
18
18
  const shortFamily = (name) => (name.length > FAMILY_MAX ? `${name.slice(0, FAMILY_MAX - 1)}…` : name);
19
19
 
20
+ /**
21
+ * The loaded session the statusline is drawing for. Matched by transcript path
22
+ * first, then by session id, because Claude Code reports both and either can be
23
+ * absent or spelled differently (a symlinked home).
24
+ */
25
+ function findSession(sessions, transcriptPath, sessionId) {
26
+ if (!Array.isArray(sessions) || (!transcriptPath && !sessionId)) return null;
27
+ let hit = null;
28
+ if (transcriptPath) {
29
+ const want = resolve(transcriptPath);
30
+ hit = sessions.find((s) => s && s.filePath && resolve(s.filePath) === want) || null;
31
+ }
32
+ if (!hit && sessionId) {
33
+ // A resumed conversation can leave more than one file under one id; the
34
+ // most recently active is the one still being written.
35
+ const end = (s) => (s.endTime ? new Date(s.endTime).getTime() || 0 : 0);
36
+ hit = sessions
37
+ .filter((s) => s && s.sessionId === sessionId)
38
+ .sort((a, b) => end(b) - end(a))[0] || null;
39
+ }
40
+ return hit;
41
+ }
42
+
20
43
  /**
21
44
  * The subagent runs of the session the statusline is drawing for.
22
45
  *
@@ -44,20 +67,7 @@ const shortFamily = (name) => (name.length > FAMILY_MAX ? `${name.slice(0, FAMIL
44
67
  * null when the session cannot be found or ran no subagents
45
68
  */
46
69
  export function sessionSubagentSummary(sessions, { transcriptPath = null, sessionId = null, env = process.env } = {}) {
47
- if (!Array.isArray(sessions) || (!transcriptPath && !sessionId)) return null;
48
- let hit = null;
49
- if (transcriptPath) {
50
- const want = resolve(transcriptPath);
51
- hit = sessions.find((s) => s && s.filePath && resolve(s.filePath) === want) || null;
52
- }
53
- if (!hit && sessionId) {
54
- // A resumed conversation can leave more than one file under one id; the
55
- // most recently active is the one still being written.
56
- const end = (s) => (s.endTime ? new Date(s.endTime).getTime() || 0 : 0);
57
- hit = sessions
58
- .filter((s) => s && s.sessionId === sessionId)
59
- .sort((a, b) => end(b) - end(a))[0] || null;
60
- }
70
+ const hit = findSession(sessions, transcriptPath, sessionId);
61
71
  const runs = hit && Array.isArray(hit.subagentRuns) ? hit.subagentRuns : [];
62
72
  if (runs.length === 0) return null;
63
73
  const byFamily = new Map();
@@ -74,6 +84,21 @@ export function sessionSubagentSummary(sessions, { transcriptPath = null, sessio
74
84
  return { total: runs.length, families, usd: cost.actual, unpriced: cost.unpriced };
75
85
  }
76
86
 
87
+ /**
88
+ * How many times the conversation of the session the statusline is drawing for
89
+ * was compacted, as the parser counted its compact_boundary lines. The figure is
90
+ * that transcript's own: a subagent's compactions are not added to it.
91
+ *
92
+ * @param {Array} sessions parseAllSessions result
93
+ * @param {{ transcriptPath?: string|null, sessionId?: string|null }} [ids]
94
+ * @returns {number|null} null when the session is not among those loaded
95
+ */
96
+ export function sessionCompactions(sessions, { transcriptPath = null, sessionId = null } = {}) {
97
+ const hit = findSession(sessions, transcriptPath, sessionId);
98
+ if (!hit) return null;
99
+ return Number.isInteger(hit.compactions) && hit.compactions >= 0 ? hit.compactions : 0;
100
+ }
101
+
77
102
  /**
78
103
  * How many delegation rules apply in this project, and how many of those are
79
104
  * flagged for review.