sprag-cli 3.106.1 → 3.107.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.
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Subcommand: secrets — secrets that "don't ask again" left in approval lists.
3
+ *
4
+ * sprag secrets list the settings entries that look like secrets (values are never printed)
5
+ * sprag secrets fix [--yes] delete the flagged allow/ask entries after saving the original
6
+ * sprag secrets off | on stop (or resume) the session start notice
7
+ *
8
+ * See src/permission-secrets.js for what is read and why an entry is deleted
9
+ * rather than repaired.
10
+ */
11
+
12
+ export async function run({ args, hasFlag }) {
13
+ const { userLanguage, loadConfig, saveConfig } = await import('../config.js');
14
+ const ko = userLanguage() === 'ko';
15
+ const ps = await import('../permission-secrets.js');
16
+ const { homedir } = await import('node:os');
17
+ const { findProjectRoot } = await import('../harness.js');
18
+ const sub = args[1];
19
+ const home = homedir();
20
+ const t = (koText, enText) => (ko ? koText : enText);
21
+ const shown = (p) => (p.startsWith(home) ? `~${p.slice(home.length)}` : p);
22
+
23
+ if (sub === 'off' || sub === 'on') {
24
+ const cfg = loadConfig();
25
+ if (sub === 'off') cfg.secretScan = false;
26
+ else delete cfg.secretScan;
27
+ saveConfig(cfg);
28
+ console.log(sub === 'off'
29
+ ? t('세션 시작 때 승인 목록의 비밀 값을 알리지 않습니다. 다시 켜기: sprag secrets on', 'The session start notice about secrets in approval lists is off. Turn it back on with: sprag secrets on')
30
+ : t('세션 시작 때 승인 목록의 비밀 값을 알립니다.', 'The session start notice about secrets in approval lists is on.'));
31
+ return;
32
+ }
33
+ if (sub !== undefined && sub !== 'fix') {
34
+ console.error(t('사용법: sprag secrets, sprag secrets fix [--yes], sprag secrets off, sprag secrets on', 'Usage: sprag secrets, sprag secrets fix [--yes], sprag secrets off, sprag secrets on'));
35
+ process.exit(1);
36
+ }
37
+
38
+ const root = findProjectRoot(process.cwd());
39
+ const found = ps.scanPermissionSecrets({ home, root }).filter((f) => f.entries.length);
40
+
41
+ if (sub === 'fix') {
42
+ if (!found.length) {
43
+ console.log(t('승인 목록에서 비밀 값으로 보이는 항목을 찾지 못했습니다.', 'No approval list entry looks like a secret.'));
44
+ return;
45
+ }
46
+ const removable = found.map((f) => ({ ...f, n: f.entries.filter((e) => e.list !== 'deny').length })).filter((f) => f.n > 0);
47
+ if (!removable.length) {
48
+ console.log(t('걸린 항목이 모두 deny 목록에 있어 지우지 않았습니다. deny 는 차단 규칙입니다.', 'Every flagged entry is in a deny list, so nothing was removed. deny entries block commands.'));
49
+ return;
50
+ }
51
+ printFindings(removable, { t, shown, ko });
52
+ if (!hasFlag('--yes')) {
53
+ const { canPrompt, confirm } = await import('../prompt.js');
54
+ if (!canPrompt()) {
55
+ console.log(t('대화형 터미널이 아니어서 아무것도 지우지 않았습니다. 지우려면 sprag secrets fix --yes 를 실행하십시오.',
56
+ 'This is not an interactive terminal, so nothing was removed. Run sprag secrets fix --yes to remove them.'));
57
+ return;
58
+ }
59
+ const ok = await confirm(t(`위 allow/ask 항목 ${removable.reduce((a, f) => a + f.n, 0)}개를 지울까요? 원본은 먼저 백업합니다.`,
60
+ `Remove these ${removable.reduce((a, f) => a + f.n, 0)} allow/ask entries? The original is backed up first.`), { defaultValue: false });
61
+ if (!ok) { console.log(t('취소했습니다.', 'Cancelled.')); return; }
62
+ }
63
+ const now = new Date();
64
+ let total = 0;
65
+ for (const f of removable) {
66
+ const r = ps.fixSettingsFile(f.path, { now });
67
+ if (r.error) {
68
+ console.error(t(`${shown(f.path)}: 쓰지 못했습니다 (${r.error}). 원본 백업: ${shown(r.backup)}`, `${shown(f.path)}: could not write (${r.error}). Backup: ${shown(r.backup)}`));
69
+ process.exitCode = 1;
70
+ continue;
71
+ }
72
+ total += r.removed;
73
+ console.log(t(`${shown(f.path)}: ${r.removed}개 지웠습니다. 원본 백업: ${shown(r.backup)} (소유자만 읽을 수 있음)`,
74
+ `${shown(f.path)}: removed ${r.removed}. Original saved to ${shown(r.backup)} (owner-only).`));
75
+ }
76
+ console.log(t(`총 ${total}개를 지웠습니다. 이미 노출됐을 수 있는 값은 발급처에서 회전하십시오.`,
77
+ `Removed ${total} in total. Rotate any value that may already have been exposed, at the service that issued it.`));
78
+ return;
79
+ }
80
+
81
+ if (!found.length) {
82
+ console.log(t('승인 목록에서 비밀 값으로 보이는 항목을 찾지 못했습니다.', 'No approval list entry looks like a secret.'));
83
+ return;
84
+ }
85
+ printFindings(found, { t, shown, ko });
86
+ console.log(t('지우려면: sprag secrets fix. 이미 노출됐을 수 있는 값은 발급처에서 회전하십시오.',
87
+ 'To remove them: sprag secrets fix. Rotate any value that may already have been exposed, at the service that issued it.'));
88
+ }
89
+
90
+ function printFindings(files, { t, shown }) {
91
+ for (const f of files) {
92
+ console.log(t(`${shown(f.path)}: 비밀 값으로 보이는 항목 ${f.entries.length}개`, `${shown(f.path)}: ${f.entries.length} entries look like secrets`));
93
+ for (const e of f.entries) {
94
+ console.log(` ${e.list} #${e.index} [${e.kinds.join(', ')}] ${e.preview}`);
95
+ }
96
+ if (f.git?.tracked) {
97
+ console.log(t(
98
+ ' 경고: 이 파일은 git이 추적하고 있습니다. 이미 커밋됐다면 값이 기록에 남아 있으니 파일을 고쳐도 소용없고, 발급처에서 값을 회전해야 합니다.',
99
+ ' Warning: git tracks this file. If it was ever committed, the value is in history, so editing the file is not enough: rotate it at the service that issued it.',
100
+ ));
101
+ } else if (f.git && f.git.ignored === false) {
102
+ console.log(t(' 이 파일은 git이 추적하지는 않지만 무시 목록에도 없어 다음 커밋에 들어갈 수 있습니다.', ' git does not track this file yet, but it is not ignored either, so the next commit can pick it up.'));
103
+ } else if (f.git?.ignored) {
104
+ console.log(t(' 이 파일은 git 무시 목록에 있습니다.', ' git ignores this file.'));
105
+ }
106
+ }
107
+ }
@@ -31,6 +31,7 @@ import { join, dirname } from 'node:path';
31
31
  import { homedir } from 'node:os';
32
32
  import { execFileSync } from 'node:child_process';
33
33
  import { debug } from './debug.js';
34
+ import { writePrivateFile } from './private-file.js';
34
35
  import { isNewer } from './update-check.js';
35
36
 
36
37
  // First Claude Code release that reads `modelSettings[<model>].autoCompactWindow`.
@@ -366,7 +367,7 @@ export function setAutoCompactWindow({ root = process.cwd(), scope = 'global', v
366
367
 
367
368
  if (existsSync(path)) {
368
369
  backup = `${path}.bak`;
369
- writeFileSync(backup, readFileSync(path, 'utf8'));
370
+ writePrivateFile(backup, readFileSync(path, 'utf8'));
370
371
  } else {
371
372
  mkdirSync(dirname(path), { recursive: true });
372
373
  }
@@ -35,6 +35,10 @@ import { loadConfig, saveConfig } from './config.js';
35
35
  import { recentToolPaths } from './session-paths.js';
36
36
  import { routeCapsFor } from './route-caps.js';
37
37
  import { modelOf } from './agents.js';
38
+ import { routingEnabled, delegationGrade, normalizeDelegationGrade } from './routing-switch.js';
39
+ import { isJudgementDelegation, SAVING_GRADE_KINDS } from './judgement-prompt.js';
40
+ import { recordGradeAction } from './grade-counts.js';
41
+ import { userDataDir } from './paths.js';
38
42
 
39
43
  const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
40
44
 
@@ -266,11 +270,18 @@ export async function buildAppendix(payload, { cfg = loadConfig(), home = homedi
266
270
 
267
271
  /**
268
272
  * Decide whether to rewrite a Task/Agent call's prompt, and with what.
269
- * Returns `{ updatedInput }` or null — null on any reason not to touch the
273
+ * Returns `{ updatedInput }` or null. Null is any reason not to touch the
270
274
  * call, so the caller's contract stays "print nothing, let the tool run
271
275
  * exactly as given" for every one of them.
276
+ *
277
+ * The delegation grade (see gradeAction) can send a judgement delegation to
278
+ * Opus. It never stops a call, and it needs the guard on and routing on, like
279
+ * every other grade effect.
272
280
  */
273
- export async function decideForDelegation(payload, { cfg = loadConfig(), home = homedir(), routeCaps = routeCapsFor(payload?.session_id) } = {}) {
281
+ export async function decideForDelegation(payload, {
282
+ cfg = loadConfig(), home = homedir(), routeCaps = routeCapsFor(payload?.session_id),
283
+ countsDir = userDataDir(),
284
+ } = {}) {
274
285
  if (!delegateEnabled(cfg)) return null;
275
286
  if (payload?.tool_name !== 'Task' && payload?.tool_name !== 'Agent') return null;
276
287
 
@@ -282,9 +293,15 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
282
293
  // same tool_name, must not stack the appendix onto itself.
283
294
  if (prompt.includes(DELEGATION_MARKER)) return null;
284
295
 
285
- const raise = wantsEffortRaise(toolInput);
286
- const appendix = await buildAppendix(payload, { cfg, home, routeCaps });
287
- if (!appendix && !raise) return null;
296
+ const act = routingEnabled(cfg) ? gradeAction(toolInput, delegationGrade(cfg)) : null;
297
+ const modelRaise = act?.type === 'raise' && !prompt.includes(MODEL_RAISE_MARKER);
298
+
299
+ // The model raise wins over the effort raise: it sets the effort itself, and
300
+ // a second marker would count one run twice in the effort ledger.
301
+ const raise = !modelRaise && wantsEffortRaise(toolInput);
302
+ const seen = modelRaise ? { ...payload, tool_input: { ...toolInput, model: RAISED_MODEL } } : payload;
303
+ const appendix = await buildAppendix(seen, { cfg, home, routeCaps });
304
+ if (!appendix && !raise && !modelRaise) return null;
288
305
 
289
306
  const parts = [prompt];
290
307
  if (appendix) parts.push(appendix);
@@ -292,11 +309,63 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
292
309
  // what the subagent transcript keeps, so route-scan can later tell a raise
293
310
  // this hook made from an effort the caller chose (see src/route-scan.js).
294
311
  if (raise) parts.push(EFFORT_RAISE_MARKER);
312
+ if (modelRaise) parts.push(MODEL_RAISE_MARKER);
295
313
  const updatedInput = { ...toolInput, prompt: parts.join('\n\n') };
296
314
  if (raise) updatedInput.effort = RAISED_EFFORT;
315
+ if (modelRaise) {
316
+ updatedInput.model = RAISED_MODEL;
317
+ // A caller that already asked for more than high keeps it: the replay
318
+ // that set this grade found xhigh no better on judgement work, but
319
+ // lowering a level somebody chose on purpose is not this hook's call.
320
+ if (!HIGHER_THAN_RAISED.has(String(toolInput.effort || '').toLowerCase())) updatedInput.effort = RAISED_EFFORT;
321
+ recordGradeAction('raised', { dir: countsDir });
322
+ }
297
323
  return { updatedInput };
298
324
  }
299
325
 
326
+ /** Model a judgement delegation is raised to. Opus, not a higher effort on the cheaper model. */
327
+ export const RAISED_MODEL = 'opus';
328
+ const HIGHER_THAN_RAISED = new Set(['xhigh', 'max']);
329
+
330
+ /**
331
+ * Line appended to the prompt of a delegation whose model this hook raised.
332
+ * Like EFFORT_RAISE_MARKER, a later scan can grep subagent transcripts for it.
333
+ */
334
+ export const MODEL_RAISE_MARKER = '[sprag: raised to Opus for judgement work]';
335
+
336
+ /** Model family a call targets: the `model` argument wins over the agent's own pin. */
337
+ export function targetFamily(toolInput) {
338
+ const named = String(toolInput?.model || '');
339
+ for (const fam of ['opus', 'sonnet', 'haiku']) if (new RegExp(fam, 'i').test(named)) return fam;
340
+ if (named) return null; // some other model: no measurement says what it does with this work
341
+ return modelOf(String(toolInput?.subagent_type || '')) || null;
342
+ }
343
+
344
+ /**
345
+ * What the delegation grade does to a call, or null for nothing.
346
+ *
347
+ * Only a haiku or sonnet target is touched, and only when the prompt asks for
348
+ * work whose conclusion is a judgement (judgement-prompt.js). Opus targets,
349
+ * unknown models, and a call that names no model and no known agent (it runs
350
+ * on whatever the session runs on) pass.
351
+ *
352
+ * quality -> raise: same call, run on Opus at high effort
353
+ * cost -> raise, but only diagnosis and audit work; the rest passes
354
+ *
355
+ * Opus at high, never xhigh: on ten judgement cases the Opus high runs made 3
356
+ * wrong claims and xhigh made 11.
357
+ */
358
+ export function gradeAction(toolInput, grade) {
359
+ const fam = targetFamily(toolInput);
360
+ if (fam !== 'haiku' && fam !== 'sonnet') return null;
361
+ const { judgement, kind } = isJudgementDelegation(toolInput?.prompt);
362
+ if (!judgement) return null;
363
+ const g = normalizeDelegationGrade(grade) ?? 'quality';
364
+ if (g === 'quality') return { type: 'raise', kind };
365
+ if (SAVING_GRADE_KINDS.has(kind)) return { type: 'raise', kind };
366
+ return null;
367
+ }
368
+
300
369
  /**
301
370
  * True when the delegation prompt sets its own budget: the word budget (or
302
371
  * 예산) next to a number, or a tool-call count. The rules require an
package/src/doc2md.cjs CHANGED
@@ -125,6 +125,42 @@ function metaPathFor(cacheFile) {
125
125
  return cacheFile.replace(/\.md$/, '.meta.json');
126
126
  }
127
127
 
128
+ /** A converted copy keeps a document's whole text, so one nobody has touched for this long goes. */
129
+ const CACHE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
130
+
131
+ /**
132
+ * Delete cached conversions (the .md and its .meta.json) not modified for
133
+ * `maxAgeMs`, plus a .meta.json whose .md is gone and that is just as old.
134
+ * The caller decides how often this runs; a file that cannot be removed is skipped.
135
+ *
136
+ * @returns {number} how many conversions were removed
137
+ */
138
+ function pruneCache({ now = Date.now(), maxAgeMs = CACHE_MAX_AGE_MS } = {}) {
139
+ const dir = cacheDir();
140
+ let names;
141
+ try { names = fs.readdirSync(dir); } catch { return 0; }
142
+ const old = (file) => {
143
+ try {
144
+ const st = fs.lstatSync(file);
145
+ return st.isFile() && now - st.mtimeMs > maxAgeMs;
146
+ } catch { return false; }
147
+ };
148
+ let removed = 0;
149
+ for (const name of names) {
150
+ const file = path.join(dir, name);
151
+ if (name.endsWith('.md')) {
152
+ if (!old(file)) continue;
153
+ try { fs.rmSync(file, { force: true }); fs.rmSync(metaPathFor(file), { force: true }); removed += 1; } catch { /* skip it */ }
154
+ } else if (name.endsWith('.meta.json')) {
155
+ const md = file.replace(/\.meta\.json$/, '.md');
156
+ if (!fs.existsSync(md) && old(file)) {
157
+ try { fs.rmSync(file, { force: true }); } catch { /* skip it */ }
158
+ }
159
+ }
160
+ }
161
+ return removed;
162
+ }
163
+
128
164
  /** A cached conversion still matching the source's mtime and size, or null. */
129
165
  function readCache(filePath) {
130
166
  const cacheFile = cachePathFor(filePath);
@@ -1043,6 +1079,8 @@ module.exports = {
1043
1079
  interpreterParts,
1044
1080
  clearNotice,
1045
1081
  cacheDir,
1082
+ pruneCache,
1083
+ CACHE_MAX_AGE_MS,
1046
1084
  cachePathFor,
1047
1085
  metaPathFor,
1048
1086
  isTargetPath,
@@ -607,6 +607,28 @@ function buildSessionDelegationSeg(sd, c, isIcon, verbose, g) {
607
607
  return `${c(CYAN)}${label} ${total}${c(RESET)}${split}${spent}`;
608
608
  }
609
609
 
610
+ /**
611
+ * Subagents running right now: `⏳ 서브에이전트 2개 실행 중 (sonnet 1, opus 1)`
612
+ * (English: `⏳ 2 subagents running (sonnet 1, opus 1)`). It leads the first
613
+ * line and exists only while something is running, so its appearance is the
614
+ * signal. The session chip further down counts every run the session started;
615
+ * this one answers "is anything working for me at this moment". The model split
616
+ * covers the runs whose model could be read, and is left off when none could.
617
+ * Icon modes draw the hourglass; text mode and the narrow set use words alone.
618
+ */
619
+ function buildRunningSeg(rs, c, isIcon, g) {
620
+ const n = Number(rs && rs.count);
621
+ if (!Number.isFinite(n) || n <= 0) return null;
622
+ const ko = rs.lang === 'ko';
623
+ const words = ko ? `서브에이전트 ${n}개 실행 중` : `${n} ${n === 1 ? 'subagent' : 'subagents'} running`;
624
+ const glyph = isIcon && g.running ? `${g.running} ` : '';
625
+ const families = Array.isArray(rs.families)
626
+ ? rs.families.filter((f) => f && Number(f.runs) > 0).map((f) => `${f.family} ${f.runs}`)
627
+ : [];
628
+ const split = families.length ? ` ${c(GRAY)}(${families.join(', ')})${c(RESET)}` : '';
629
+ return `${c(BOLD)}${c(CYAN)}${glyph}${words}${c(RESET)}${split}`;
630
+ }
631
+
610
632
  /**
611
633
  * Cap-warn chip builder — shared by the full report and the no-session
612
634
  * fallback line. At 90%+ the user wants to know "when can I send again", so
@@ -643,6 +665,54 @@ const HEADLINE_INDENT = ' ';
643
665
 
644
666
  const availWidth = (columns) => Math.max(20, columns - STATUSLINE_MARGIN);
645
667
 
668
+ /** Width assumed for the statusline when neither `--columns` nor COLUMNS says. */
669
+ export const DEFAULT_COLUMNS = 120;
670
+ /** Model pairs the routing headline keeps when it has to shorten itself. */
671
+ const HEADLINE_PAIRS_SHORT = 2;
672
+
673
+ /**
674
+ * A headline split at its joints: sections joined by a gray `|`, items by a
675
+ * gray `·`. Each piece carries the separator that precedes it.
676
+ */
677
+ function splitHeadline(line, c) {
678
+ const bar = ` ${c(GRAY)}|${c(RESET)} `;
679
+ const dot = ` ${c(GRAY)}·${c(RESET)} `;
680
+ const pieces = [];
681
+ line.split(bar).forEach((section, i) => {
682
+ section.split(dot).forEach((text, j) => pieces.push({ text, sep: j ? dot : i ? bar : '' }));
683
+ });
684
+ return pieces;
685
+ }
686
+
687
+ /**
688
+ * One headline on one row. A headline that is too wide gives up its tail items,
689
+ * lowest priority first (they are listed biggest first), and ends in `…`; it is
690
+ * not wrapped onto more rows. The routing headline tries its short form (top
691
+ * pairs plus `+N`) before anything is cut. The first piece always stays.
692
+ *
693
+ * @param {{ line: string, short?: string|null }} h
694
+ * @param {number} avail cells available for the row
695
+ * @param {(v: string) => string} c
696
+ * @param {string} [lead] text that will sit in front of the row (width only)
697
+ */
698
+ function fitHeadline(h, avail, c, lead = '') {
699
+ const room = avail - cellWidth(lead);
700
+ if (cellWidth(h.line) <= room) return h.line;
701
+ const body = h.short && cellWidth(h.short) <= room ? h.short : (h.short || h.line);
702
+ if (cellWidth(body) <= room) return body;
703
+ const marker = ` ${c(GRAY)}…${c(RESET)}`;
704
+ const markerW = 2;
705
+ const kept = [];
706
+ let used = 0;
707
+ for (const { text, sep } of splitHeadline(body, c)) {
708
+ const w = cellWidth(text) + (kept.length ? cellWidth(sep) : 0);
709
+ if (kept.length && used + w + markerW > room) break;
710
+ used += w;
711
+ kept.push(kept.length ? sep + text : text);
712
+ }
713
+ return kept.join('') + marker;
714
+ }
715
+
646
716
  /**
647
717
  * Wrap one headline line to `avail` cells. A headline is sections joined by a
648
718
  * gray `|`, and a section is items joined by a gray `·` (see buildDelegatedSeg
@@ -653,12 +723,7 @@ const availWidth = (columns) => Math.max(20, columns - STATUSLINE_MARGIN);
653
723
  */
654
724
  function wrapHeadline(line, avail, c) {
655
725
  if (cellWidth(line) <= avail) return [line];
656
- const bar = ` ${c(GRAY)}|${c(RESET)} `;
657
- const dot = ` ${c(GRAY)}·${c(RESET)} `;
658
- const pieces = [];
659
- line.split(bar).forEach((section, i) => {
660
- section.split(dot).forEach((text, j) => pieces.push({ text, sep: j ? dot : i ? bar : '' }));
661
- });
726
+ const pieces = splitHeadline(line, c);
662
727
  const rows = [];
663
728
  let row = '';
664
729
  let used = 0;
@@ -1217,6 +1282,25 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1217
1282
  ? `${c(GRAY)}${verbose ? `effort guard ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
1218
1283
  : null;
1219
1284
 
1285
+ // The delegation grade's own count (grade-counts.js): judgement delegations
1286
+ // the guard sent to Opus (`model↑N`). Same gray count chip as the effort
1287
+ // guard, same reset mark, hidden at zero. It always stays a chip: the guard
1288
+ // line above is about effort, and this one has no line of its own.
1289
+ // icon "🤖↑2" | text "model↑2" | verbose "model guard ×2"
1290
+ const gradeInfo = data.gradeActions;
1291
+ const modelUp = Number(gradeInfo && gradeInfo.raised) || 0;
1292
+ const modelUpSeg = modelUp > 0
1293
+ ? `${c(GRAY)}${verbose ? `model guard ×${modelUp}` : isIcon ? `${g.model}↑${modelUp}` : `model↑${modelUp}`}${c(RESET)}`
1294
+ : null;
1295
+ // The relax window, only while one is open: the default behaviour gets no
1296
+ // chip. data.relaxUntil is the deadline in epoch ms (null when closed).
1297
+ // text "relax →21:30" | verbose "relax until 21:30"
1298
+ const relaxMs = Number(data.relaxUntil);
1299
+ const relaxClockText = Number.isFinite(relaxMs) && relaxMs > Date.now() ? formatResetClock(relaxMs / 1000) : null;
1300
+ const gradeSeg = relaxClockText
1301
+ ? `${c(GRAY)}${verbose ? `relax until ${relaxClockText}` : `relax →${relaxClockText}`}${c(RESET)}`
1302
+ : null;
1303
+
1220
1304
  // Routing-savings headline line (multi-line layout). The lifetime sum from
1221
1305
  // the delegation ledger — the number the whole tool exists to grow, so it
1222
1306
  // gets line 1 to itself while the diagnostics move to line 2.
@@ -1229,6 +1313,7 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1229
1313
  // icon: "🔀 Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1230
1314
  // text: "Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1231
1315
  let totalsLine = null;
1316
+ let totalsShort = null;
1232
1317
  const totalsNum = Number(totals && totals.total);
1233
1318
  // A zero total gets its line only when a reset mark explains it; see the
1234
1319
  // note above `routingSince`.
@@ -1253,11 +1338,22 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1253
1338
  .join(` ${c(GRAY)}·${c(RESET)} `);
1254
1339
  // A net loss must not read as a win, and a zero is neither.
1255
1340
  const tone = totalsNum < 0 ? RED : totalsNum > 0 ? GREEN : GRAY;
1256
- totalsLine =
1341
+ const compose = (text) =>
1257
1342
  `${c(tone)}${c(BOLD)}${head}${c(RESET)} ` +
1258
1343
  `${c(tone)}${formatMoney(totalsNum)}${c(RESET)}` +
1259
1344
  sinceWord(routingSince) + scanTag +
1260
- (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
1345
+ (text ? ` ${c(GRAY)}|${c(RESET)} ${text}` : '');
1346
+ totalsLine = compose(pairText);
1347
+ // The short form for a line that is too wide: the two biggest moves (the
1348
+ // ledger lists them biggest first) and the count of the rest. The full list
1349
+ // stays the default whenever it fits, and a user who named `delegated` in
1350
+ // `--segments` always gets it (see buildHeadlines).
1351
+ if (pairs.length > HEADLINE_PAIRS_SHORT) {
1352
+ const top = pairs.slice(0, HEADLINE_PAIRS_SHORT)
1353
+ .map((p) => `${c(GRAY)}${p.from}→${p.to} ×${p.runs} ${formatMoney(p.usd)}${c(RESET)}`)
1354
+ .join(` ${c(GRAY)}·${c(RESET)} `);
1355
+ totalsShort = compose(`${top} ${c(GRAY)}·${c(RESET)} ${c(GRAY)}+${pairs.length - HEADLINE_PAIRS_SHORT}${c(RESET)}`);
1356
+ }
1261
1357
  }
1262
1358
 
1263
1359
  // The effort guard line (multi-line layout): the top line of the statusline,
@@ -1287,9 +1383,11 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1287
1383
  // the dropped runs matter. The raise chip steps aside for its own line the
1288
1384
  // same way, and stays on line 2 while there is no line to carry it.
1289
1385
  chips: totalsLine
1290
- ? (totalsNum === 0 ? [unresolvedSeg, guardLine ? null : raisedSeg] : [guardLine ? null : raisedSeg])
1291
- : [delegateSeg, guardLine ? null : raisedSeg, delegateExtra],
1292
- headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
1386
+ ? (totalsNum === 0
1387
+ ? [unresolvedSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg]
1388
+ : [guardLine ? null : raisedSeg, modelUpSeg, gradeSeg])
1389
+ : [delegateSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg, delegateExtra],
1390
+ headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine, short: totalsShort } : null,
1293
1391
  guardLine,
1294
1392
  };
1295
1393
  }
@@ -1426,6 +1524,8 @@ export const DEFAULT_SEGMENT_ORDER = [
1426
1524
  //
1427
1525
  // Lifetime, from the savings ledgers. Delegation stays ahead of the cache
1428
1526
  // figure: routing is what the tool is for, the cache number is a brag stat.
1527
+ // `delegated` also carries the guard chips (effort↑N, model↑N) and the
1528
+ // grade chip (C), so one name in `--segments` shows or hides all of them.
1429
1529
  'delegated', 'doc2md',
1430
1530
  // Same period as the routing counter, so it sits after the lifetime routing
1431
1531
  // figures but carries its own since date.
@@ -1564,7 +1664,7 @@ function arrangeSegments(order, s) {
1564
1664
  /**
1565
1665
  * The headline lines that sit above the chips, as one string of `line\n` pairs.
1566
1666
  */
1567
- function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v, teamLine = null) {
1667
+ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v, teamLine = null, { trim = false, lead = null } = {}) {
1568
1668
  // Each savings source that earned real money gets a headline line, ordered
1569
1669
  // biggest saver first — the top line is the one the eye lands on, so it
1570
1670
  // goes to whichever habit is actually paying for the tool. The diagnostics
@@ -1578,9 +1678,18 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1578
1678
  if (delegated.guardLine && want('delegated')) headlines.unshift({ usd: 0, line: delegated.guardLine });
1579
1679
  // The team line comes last: identity and standing, after the money.
1580
1680
  if (teamLine && want('team')) headlines.push(teamLine);
1681
+ // The running-subagents chip leads the first row. It is joined before the
1682
+ // row is fitted so its width counts, and it is never the part that is cut.
1683
+ const join = lead && headlines.length ? `${lead}${CHIP_SEP}` : '';
1581
1684
  const rows = columns
1582
- ? headlines.flatMap((h) => wrapHeadline(h.line, availWidth(columns), c))
1583
- : headlines.map((h) => h.line);
1685
+ ? headlines.flatMap((h, i) => {
1686
+ const prefix = i === 0 ? join : '';
1687
+ // `trim` is the default layout: one row per headline, tail given up with
1688
+ // `…`. A user who picked the segments gets every item, wrapped instead.
1689
+ if (trim) return [prefix + fitHeadline(h, availWidth(columns), c, prefix)];
1690
+ return wrapHeadline(prefix + h.line, availWidth(columns), c);
1691
+ })
1692
+ : headlines.map((h, i) => (i === 0 ? join : '') + h.line);
1584
1693
  return rows.map((row) => row + eol + '\n').join('');
1585
1694
  }
1586
1695
 
@@ -1591,7 +1700,7 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1591
1700
  * @param {boolean} [opts.verbose=false] - longer layout with labels
1592
1701
  * @param {boolean} [opts.timer=true] - show TTL countdown segment
1593
1702
  * @param {'text'|'icon'} [opts.mode='text'] - label style. 'icon' uses 🧠 ⏳ 💰 instead of word labels.
1594
- * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, ultra (ultracode on/off; live statusline only), hit, ttl, month, saved, delegated, doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1703
+ * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, ultra (ultracode on/off; live statusline only), hit, ttl, month, saved, delegated (Routing saved plus the effort↑N, model↑N and grade chips), doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1595
1704
  * @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`.
1596
1705
  * @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.
1597
1706
  * @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.
@@ -1685,17 +1794,36 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1685
1794
  const order = resolveSegmentOrder(segments, caps, updateAvailable);
1686
1795
  const segs = arrangeSegments(order, built);
1687
1796
 
1797
+ // Leads the first line, ahead of every segment. A caller's `--segments` list
1798
+ // is a filter, so the chip needs a name in it too: `running`, or the
1799
+ // subagent names it belongs with.
1800
+ const runningSeg = !allow || ['running', 'subagents', 'delegated'].some((n) => allow.has(n))
1801
+ ? buildRunningSeg(data.runningSubagents, c, isIcon, g)
1802
+ : null;
1803
+ // Items the user picked are never given up for width: only the default layout
1804
+ // trims a headline to one row with `…`; an explicit list wraps instead.
1805
+ const trim = !allow;
1806
+
1688
1807
  // Trailing erase-to-end-of-line so any leftover characters from a previous
1689
1808
  // (longer) statusline render don't bleed into ours. \x1b[K is the standard
1690
1809
  // "erase from cursor to EOL" CSI. Only emitted when color (i.e. ANSI) is
1691
1810
  // allowed — --no-color/NO_COLOR consumers expect escape-free output.
1692
1811
  const eol = color ? '\x1b[K' : '';
1693
- if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol, 0, c, teamLine) + segs.join(' · ') + eol;
1694
- const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c, teamLine);
1812
+ // With a headline row the chip joins that row; without one it is the first chip.
1813
+ const hasHeadline = !!((delegated.headline && want('delegated')) || (delegated.guardLine && want('delegated'))
1814
+ || (doc2md.headline && want('doc2md')) || (teamLine && want('team')));
1815
+ const lead = runningSeg && hasHeadline ? runningSeg : null;
1816
+ if (runningSeg && !lead) segs.unshift(runningSeg);
1817
+ if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol, 0, c, teamLine, { lead }) + segs.join(' · ') + eol;
1818
+ const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c, teamLine, { trim, lead });
1695
1819
 
1696
1820
  // The chips that stop the work: layoutChips drops from the tail when the
1697
1821
  // terminal is narrow, and these must survive that.
1698
1822
  const protectedSegs = new Set([built.capWarn, built.spike, built.ctx, ...built.usage.map((u) => u.seg)].filter(Boolean));
1823
+ // The running chip, and everything the user named in `--segments`, is kept
1824
+ // whatever the width: the chip budget gives up the default tail instead.
1825
+ if (runningSeg && !lead) protectedSegs.add(runningSeg);
1826
+ if (allow) for (const seg of segs) protectedSegs.add(seg);
1699
1827
  const fitted = fitChips(segs, { columns, maxLines, eol, protectedSegs, color });
1700
1828
  // Verbose labels are the first thing to give up: if they only fit by dropping
1701
1829
  // chips, the compact layout (same chips, shorter text) may keep all of them.
package/src/glyphs.js CHANGED
@@ -58,6 +58,10 @@ const ICON = {
58
58
  doc: '📄',
59
59
  hit: '🧠',
60
60
  ttl: '⏳',
61
+ // Subagents running right now (the statusline's leading chip). The same hourglass
62
+ // as the cache timer: both say "time is passing", and the words beside it tell
63
+ // them apart.
64
+ running: '⏳',
61
65
  month: '💵',
62
66
  // Team: the people this machine is ranked among. U+1F465, East Asian Width W.
63
67
  team: '👥',
@@ -92,6 +96,7 @@ const NARROW = {
92
96
  doc: '≣', // stacked lines: a page of text
93
97
  hit: '◉', // bullseye: a cache hit
94
98
  ttl: '◔', // a partly elapsed dial
99
+ running: '', // no second font-verified dial; the chip's words lead it
95
100
  month: '∑', // a running total
96
101
  team: '', // no glyph verified in the font yet; the team line's own words lead it
97
102
  ctx: '◧', // a box filling up
@@ -0,0 +1,85 @@
1
+ /**
2
+ * grade-counts — how often the delegation grade acted on a call.
3
+ *
4
+ * The guard (delegation-guard.js) raises a judgement delegation to Opus under
5
+ * either grade. Each raise counts once here, and the statusline shows the
6
+ * number as `model↑N`.
7
+ *
8
+ * File: <userDataDir>/delegation-grade-counts.json
9
+ * { "version": 1, "raised": 3, "since": <ms> }
10
+ *
11
+ * An earlier version also counted held calls in a `blocked` field. That field
12
+ * is ignored on read and dropped on the next write, so an old file still loads.
13
+ *
14
+ * `since` is when the counting window opened: the first count after the last
15
+ * routing reset. The reset mark is the same one the effort-raise ledger and
16
+ * Routing saved read, so `sprag saved reset` zeroes all three together. The
17
+ * counts are not evidence the way a ledger is, so a reset restarts the file
18
+ * the next time it is written, and a read before that treats a window that
19
+ * opened before the mark as empty.
20
+ *
21
+ * The write happens inside a PreToolUse hook, so it is best effort: nothing
22
+ * throws, and two hooks racing can lose a count, which a display figure
23
+ * tolerates.
24
+ */
25
+
26
+ import { readFileSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+ import { userDataDir } from './paths.js';
29
+ import { writeStateFile } from './state-file.js';
30
+ import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
31
+
32
+ export const GRADE_COUNTS_VERSION = 1;
33
+
34
+ export function gradeCountsPath(dir = userDataDir()) {
35
+ return join(dir, 'delegation-grade-counts.json');
36
+ }
37
+
38
+ function readCounts(dir) {
39
+ try {
40
+ const data = JSON.parse(readFileSync(gradeCountsPath(dir), 'utf8'));
41
+ if (!data || data.version !== GRADE_COUNTS_VERSION) return null;
42
+ const n = (v) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);
43
+ return { raised: n(data.raised), since: Number.isFinite(data.since) ? data.since : null };
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Count one action: 'raised' (sent to Opus). Returns the new counts, or null
51
+ * when nothing could be written.
52
+ */
53
+ export function recordGradeAction(action, { dir = userDataDir(), now = Date.now() } = {}) {
54
+ if (action !== 'raised') return null;
55
+ try {
56
+ const mark = readResetMarks(dir).routing;
57
+ let counts = readCounts(dir);
58
+ // A window that opened before the reset mark is the old count: start over.
59
+ if (!counts || counts.since === null || isBeforeReset(counts.since, mark)) {
60
+ counts = { raised: 0, since: now };
61
+ }
62
+ counts[action] += 1;
63
+ writeStateFile(gradeCountsPath(dir), JSON.stringify({ version: GRADE_COUNTS_VERSION, ...counts }) + '\n');
64
+ return counts;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * { raised, since } for the statusline, with `since` the routing reset
72
+ * mark (null when never reset), the same field the effort guard reads. Never
73
+ * throws; an unreadable file or a window older than the mark reads as zero.
74
+ */
75
+ export function gradeActionTotals(dir = userDataDir()) {
76
+ const since = readResetMarks(dir).routing;
77
+ const zero = { raised: 0, since };
78
+ try {
79
+ const counts = readCounts(dir);
80
+ if (!counts || counts.since === null || isBeforeReset(counts.since, since)) return zero;
81
+ return { raised: counts.raised, since };
82
+ } catch {
83
+ return zero;
84
+ }
85
+ }