@trazum/cli 2.7.12 → 3.0.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.
Files changed (47) hide show
  1. package/README.md +4 -2
  2. package/assets/trazum-statusline.sh +131 -0
  3. package/dist/git.d.ts +38 -0
  4. package/dist/git.d.ts.map +1 -1
  5. package/dist/git.js +54 -0
  6. package/dist/git.js.map +1 -1
  7. package/dist/i18n/en.d.ts.map +1 -1
  8. package/dist/i18n/en.js +170 -3
  9. package/dist/i18n/en.js.map +1 -1
  10. package/dist/i18n/es.d.ts.map +1 -1
  11. package/dist/i18n/es.js +174 -3
  12. package/dist/i18n/es.js.map +1 -1
  13. package/dist/i18n/types.d.ts +84 -0
  14. package/dist/i18n/types.d.ts.map +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +670 -262
  17. package/dist/index.js.map +1 -1
  18. package/dist/proactive.d.ts +344 -0
  19. package/dist/proactive.d.ts.map +1 -0
  20. package/dist/proactive.js +1079 -0
  21. package/dist/proactive.js.map +1 -0
  22. package/dist/style.d.ts +305 -26
  23. package/dist/style.d.ts.map +1 -1
  24. package/dist/style.js +449 -47
  25. package/dist/style.js.map +1 -1
  26. package/dist/watch-notify.d.ts +82 -0
  27. package/dist/watch-notify.d.ts.map +1 -0
  28. package/dist/watch-notify.js +118 -0
  29. package/dist/watch-notify.js.map +1 -0
  30. package/dist/watch-run.d.ts +7 -0
  31. package/dist/watch-run.d.ts.map +1 -1
  32. package/dist/watch-run.js.map +1 -1
  33. package/dist/weekly.d.ts +32 -0
  34. package/dist/weekly.d.ts.map +1 -0
  35. package/dist/weekly.js +119 -0
  36. package/dist/weekly.js.map +1 -0
  37. package/package.json +3 -2
  38. package/src/git.ts +77 -0
  39. package/src/i18n/en.ts +198 -3
  40. package/src/i18n/es.ts +202 -3
  41. package/src/i18n/types.ts +130 -0
  42. package/src/index.ts +715 -302
  43. package/src/proactive.ts +1319 -0
  44. package/src/style.ts +502 -54
  45. package/src/watch-notify.ts +152 -0
  46. package/src/watch-run.ts +7 -0
  47. package/src/weekly.ts +133 -0
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from 'node:crypto';
3
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
3
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
4
4
  import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import type { FileHandle } from 'node:fs/promises';
6
6
  import { cpus, homedir, tmpdir } from 'node:os';
@@ -19,7 +19,9 @@ import {
19
19
  breaches,
20
20
  cacheableMinimum,
21
21
  analyzeCachePrefix,
22
+ billFigures,
22
23
  billLevers,
24
+ buildWeeklySummary,
23
25
  bucketedCacheEconomics,
24
26
  bucketedProfile,
25
27
  buildHistory,
@@ -94,7 +96,6 @@ import {
94
96
  getMessages,
95
97
  getModel,
96
98
  hasMarker,
97
- listModels,
98
99
  LOCALES,
99
100
  MAX_BASELINE_BYTES,
100
101
  matchGlob,
@@ -156,6 +157,7 @@ import {
156
157
  profilePrompt,
157
158
  profileToCsv,
158
159
  profileUsage,
160
+ weekWindows,
159
161
  promptId,
160
162
  providerFromEnv,
161
163
  pruneExamples,
@@ -169,7 +171,6 @@ import {
169
171
  RULES,
170
172
  sharedPrefixes,
171
173
  sharesOf,
172
- spendByMonth,
173
174
  spendByPeriod,
174
175
  isOffered,
175
176
  SOURCE_EXTENSIONS,
@@ -183,7 +184,6 @@ import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cac
183
184
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
184
185
  import { dayOf, formatGap, median, spanDays } from './time.js';
185
186
  import type {
186
- BucketedReport,
187
187
  EvalReport,
188
188
  FleetSource,
189
189
  HistoryRun,
@@ -222,6 +222,7 @@ import type {
222
222
  FailurePolicy,
223
223
  GatewayStanding,
224
224
  UsageProfileReport,
225
+ WeekWindow,
225
226
  BillPeriodUnit,
226
227
  WaiverUse,
227
228
  InitDecline,
@@ -282,6 +283,7 @@ import {
282
283
  readWatchState,
283
284
  writeWatchState,
284
285
  } from './watch-run.js';
286
+ import { notificationFor, sendNotification } from './watch-notify.js';
285
287
  import { LOCALE_ENV_VARS, detectLocale, getCliMessages } from './i18n/index.js';
286
288
  import {
287
289
  MAX_SUMMARY_CHARS,
@@ -306,8 +308,20 @@ import type { CliMessages } from './i18n/index.js';
306
308
  // proportion bar and the heading rule — the 1.75 style module. The guard in
307
309
  // style.test.js holds the contract: stripped colour output is byte-identical
308
310
  // to plain output, and a pipe stays plain.
309
- import { bar, c, sectionHeading, table } from './style.js';
310
- import type { TableColumn } from './style.js';
311
+ import { runCrontab } from './git.js';
312
+ import { checkedWeekly } from './weekly.js';
313
+ import {
314
+ ITEMS as PROACTIVE_ITEMS,
315
+ BACKUP_SUFFIX,
316
+ CRONTAB,
317
+ inspectAll as inspectProactive,
318
+ run as runProactive,
319
+ shown as shownPath,
320
+ systemCrontab,
321
+ } from './proactive.js';
322
+ import type { Ctx as ProactiveCtx, Finding as ProactiveFinding, Item as ProactiveItem, ItemResult, ItemStatus } from './proactive.js';
323
+ import { MAX_COLUMNS, Report, WINDOW, c, cErr, fitPath, sectionHeading, table, wrap } from './style.js';
324
+ import type { Cell, TableColumn } from './style.js';
311
325
 
312
326
  // --------------------------------------------------------------------------
313
327
  // Argument parsing
@@ -328,6 +342,7 @@ interface Args {
328
342
  }
329
343
 
330
344
  const VALUE_FLAGS = new Set([
345
+ 'only',
331
346
  'id', 'type', 'criterion', 'outcome', 'assessor', 'policy', 'claude-code', 'codex', 'instructions',
332
347
  'recovery-dir',
333
348
  'answers',
@@ -840,7 +855,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
840
855
  history: ['store', 'json', 'markdown-out'],
841
856
  connect: ['since', 'until', 'payload', 'store', 'json', 'out', 'markdown-out', 'pricing', 'pricing-live', 'dry-run'],
842
857
  store: ['prune', 'keep', 'json', 'pricing', 'pricing-live', 'dry-run'],
843
- watch: ['once', 'interval', 'since', 'payload', 'webhook', 'json', 'pricing', 'pricing-live'],
858
+ watch: ['once', 'interval', 'since', 'payload', 'sessions', 'notify', 'webhook', 'json', 'pricing', 'pricing-live'],
844
859
  serve: ['port', 'socket', 'log', 'pricing', 'pricing-live'],
845
860
  route: ['prompt-file', 'cases', 'label', 'concurrency', 'json', 'yes', 'pricing', 'pricing-live'],
846
861
  eval: ['cases', 'level', 'concurrency', 'export', 'out', 'o', 'model'],
@@ -864,6 +879,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
864
879
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
865
880
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
866
881
  bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'since', 'until', 'by'],
882
+ weekly: ['label', 'label-from-project', 'out', 'o', 'until', 'notify', 'pricing', 'pricing-live'],
867
883
  'from-helicone': ['out', 'o'],
868
884
  'from-langsmith': ['out', 'o'],
869
885
  switch: ['to', 'migration-usd', 'cases'],
@@ -884,6 +900,7 @@ const COMMAND_FLAGS: Record<string, string[]> = {
884
900
  rules: ['measure', 'level', 'json'],
885
901
  blame: ['limit', 'model', 'calls', 'output-tokens', 'batch', 'prompt', 'markdown-out'],
886
902
  doctor: ['level', 'model', 'calls', 'output-tokens', 'batch', 'disable', 'prompt', 'otlp-out'],
903
+ proactive: ['only', 'dry-run', 'yes', 'json'],
887
904
  };
888
905
 
889
906
  function rejectUnknownFlags(args: Args, t: CliMessages): void {
@@ -1040,7 +1057,7 @@ function biggestLever(
1040
1057
  result: OptimizationResult,
1041
1058
  tokensOnly: boolean,
1042
1059
  t: CliMessages,
1043
- ): { line: string } | null {
1060
+ ): { line: string; amount: string } | null {
1044
1061
  /**
1045
1062
  * One guard, and it is the only thing deciding.
1046
1063
  *
@@ -1055,6 +1072,7 @@ function biggestLever(
1055
1072
 
1056
1073
  const ruleSaving = result.savings.monthlySavingsUsd;
1057
1074
  return {
1075
+ amount: formatUsd(best.estimatedMonthlyUsd),
1058
1076
  line: t.report.biggestLeverDetail(
1059
1077
  best.title,
1060
1078
  formatUsd(best.estimatedMonthlyUsd),
@@ -1110,21 +1128,24 @@ function printReport(
1110
1128
  *
1111
1129
  * So the answer to "what should I do about this prompt" goes at the top, and
1112
1130
  * the token count follows as the detail it is.
1131
+ *
1132
+ * Drawn as every report's headline is (#758): the question as a heading, the
1133
+ * answer under it with its figure marked. With no lever worth money, the
1134
+ * question is the token count, and the reduction is the marked figure.
1113
1135
  */
1114
1136
  const best = biggestLever(result, tokensOnly, t);
1137
+ const draw = new Report();
1138
+ const reduction = `-${result.reductionPct.toFixed(1)}%`;
1115
1139
  if (best) {
1116
- console.log();
1117
- console.log(c.bold(t.report.biggestLever()));
1118
- console.log(` ${c.dim(wrap(best.line, 74, ' '))}`);
1140
+ draw.blank().headline(t.report.biggestLever(), best.line, best.amount);
1141
+ draw.blank().title(t.report.inputTokens());
1142
+ } else {
1143
+ draw.blank().heading(t.report.inputTokens());
1119
1144
  }
1120
-
1121
- console.log();
1122
- console.log(c.bold(t.report.inputTokens()));
1123
- console.log(
1124
- ` ${n(result.tokensBefore)} → ${c.green(n(result.tokensAfter))} ${c.bold(
1125
- `-${result.reductionPct.toFixed(1)}%`,
1126
- )}${sourceNote}`,
1145
+ draw.line(
1146
+ ` ${n(result.tokensBefore)} → ${c.green(n(result.tokensAfter))} ${best ? c.bold(reduction) : c.mark(reduction)}${sourceNote}`,
1127
1147
  );
1148
+ draw.print();
1128
1149
 
1129
1150
  // Before the rules, because the rearrangement is the bigger change and the
1130
1151
  // one the reader has to make a judgement about.
@@ -1169,7 +1190,7 @@ function printReport(
1169
1190
  console.log(` ${c.dim(t.report.reorderDeclinedMore(reorder.declined.length - SHOWN))}`);
1170
1191
  }
1171
1192
  }
1172
- if (reorder.moved.length > 0) console.log(` ${c.yellow(t.report.reorderReview())}`);
1193
+ if (reorder.moved.length > 0) new Report().note('caution', t.report.reorderReview()).print();
1173
1194
  }
1174
1195
 
1175
1196
  if (result.rules.length > 0) {
@@ -1192,9 +1213,7 @@ function printReport(
1192
1213
  */
1193
1214
  const promptLanguage = detectTextLanguage(result.original);
1194
1215
  if (promptLanguage !== null && dictionaryStanding(promptLanguage)?.standing === 'unreviewed') {
1195
- console.log(
1196
- c.yellow(t.report.dictionaryAppliedUnreviewed(t.languages[promptLanguage] ?? promptLanguage)),
1197
- );
1216
+ new Report().note('caution', t.report.dictionaryAppliedUnreviewed(t.languages[promptLanguage] ?? promptLanguage)).print();
1198
1217
  }
1199
1218
  for (const rule of result.rules) {
1200
1219
  const tag =
@@ -1220,18 +1239,18 @@ function printReport(
1220
1239
  }
1221
1240
  } else {
1222
1241
  console.log();
1223
- console.log(c.dim(t.report.nothingToTrim()));
1242
+ const draw = new Report();
1243
+ draw.text(t.report.nothingToTrim(), { tone: 'dim' });
1224
1244
  // Which languages the dictionaries actually cover. Only here, because this
1225
1245
  // is the one branch where silence reads as "your prompt is already clean".
1226
- console.log(c.dim(t.report.dictionaryCoverage(languageNames(PHRASE_LANGUAGES, t))));
1246
+ draw.text(t.report.dictionaryCoverage(languageNames(PHRASE_LANGUAGES, t)), { tone: 'dim' });
1227
1247
  // And which of them nobody here reads. Naming the seven and stopping there
1228
1248
  // reads as seven equal dictionaries; five of them have never been agreed by
1229
1249
  // a speaker of the language, and a reader deciding whether to trust an
1230
1250
  // empty result deserves the difference.
1231
1251
  const unreviewed = languagesWithStanding(PHRASE_LANGUAGES, 'unreviewed');
1232
- if (unreviewed.length > 0) {
1233
- console.log(c.dim(t.report.dictionaryUnreviewed(languageNames(unreviewed, t))));
1234
- }
1252
+ if (unreviewed.length > 0) draw.text(t.report.dictionaryUnreviewed(languageNames(unreviewed, t)), { tone: 'dim' });
1253
+ draw.print();
1235
1254
  }
1236
1255
 
1237
1256
  if (result.llm) {
@@ -1249,7 +1268,7 @@ function printReport(
1249
1268
  )}`,
1250
1269
  );
1251
1270
  } else {
1252
- console.log(` ${c.yellow(t.report.llmRejected(result.llm.rejectedReason ?? ''))}`);
1271
+ new Report().note('caution', t.report.llmRejected(result.llm.rejectedReason ?? '')).print();
1253
1272
  }
1254
1273
  }
1255
1274
 
@@ -1305,7 +1324,7 @@ function printReport(
1305
1324
  : c.dim('·');
1306
1325
  const amount = amountOf(advisory);
1307
1326
  const column = width > 0 ? `${c.green(amount.padStart(width))} ` : '';
1308
- console.log(` ${marker} ${column}${c.bold(advisory.title)}`);
1327
+ console.log(` ${marker} ${column}${c.bold(wrap(advisory.title, 78 - gutter.length, gutter))}`);
1309
1328
  console.log(`${gutter}${c.dim(wrap(advisory.detail, 78 - gutter.length, gutter))}`);
1310
1329
  }
1311
1330
 
@@ -1314,7 +1333,7 @@ function printReport(
1314
1333
  }
1315
1334
 
1316
1335
  printSuggestions(suggestions, t, n);
1317
- printRest(result, showDiff, t, examplesReview, n);
1336
+ printRest(result, showDiff, t, examplesReview);
1318
1337
 
1319
1338
  /**
1320
1339
  * Where the money actually is, said at the front door.
@@ -1400,9 +1419,7 @@ function printMoney(
1400
1419
  ...result.pricingSource.addedModels,
1401
1420
  ];
1402
1421
  if (touched.length > 0) {
1403
- console.log(
1404
- ` ${c.yellow(t.report.pricingOverlaid(touched.join(', '), result.pricingSource.lastReviewed))}`,
1405
- );
1422
+ new Report().note('caution', t.report.pricingOverlaid(touched.join(', '), result.pricingSource.lastReviewed)).print();
1406
1423
  }
1407
1424
  const periodOnly = measured !== null && measured.scaled === null;
1408
1425
  console.log(
@@ -1451,15 +1468,10 @@ function printTokensOnly(
1451
1468
  const model = getModel(result.usage.model);
1452
1469
  const saved = result.tokensBefore - result.tokensAfter;
1453
1470
 
1454
- console.log();
1455
- console.log(sectionHeading(t.report.tokensOnlyHeading(host.displayName)));
1456
- console.log(
1457
- ` ${prefersTokenReport(host)
1458
- ? t.report.tokensOnlyWhy(host.displayName)
1459
- : t.report.tokensOnlyAsked()}`,
1460
- );
1461
- console.log();
1462
- console.log(` ${c.green(t.report.tokensSaved(n(saved)))}`);
1471
+ const draw = new Report();
1472
+ draw.blank().heading(t.report.tokensOnlyHeading(host.displayName));
1473
+ draw.text(prefersTokenReport(host) ? t.report.tokensOnlyWhy(host.displayName) : t.report.tokensOnlyAsked());
1474
+ draw.blank().text(t.report.tokensSaved(n(saved)), { tone: 'good' });
1463
1475
 
1464
1476
  /**
1465
1477
  * Share of the window, which is what a saved token is actually worth here.
@@ -1484,16 +1496,16 @@ function printTokensOnly(
1484
1496
  */
1485
1497
  const unchanged = before === after;
1486
1498
  const negligible = after === '0.0%';
1487
- console.log(
1488
- ` ${c.dim(
1489
- !unchanged
1490
- ? t.report.windowUse(before, after, model.displayName, n(model.contextWindow))
1491
- : negligible
1492
- ? t.report.windowNegligible(n(result.tokensAfter), model.displayName, n(model.contextWindow))
1493
- : t.report.windowUnmoved(after, model.displayName, n(model.contextWindow)),
1494
- )}`,
1499
+ draw.text(
1500
+ !unchanged
1501
+ ? t.report.windowUse(before, after, model.displayName, n(model.contextWindow))
1502
+ : negligible
1503
+ ? t.report.windowNegligible(n(result.tokensAfter), model.displayName, n(model.contextWindow))
1504
+ : t.report.windowUnmoved(after, model.displayName, n(model.contextWindow)),
1505
+ { tone: 'dim' },
1495
1506
  );
1496
- console.log(` ${c.dim(namedScenario ? t.report.tokensOnlyAskedFor() : t.report.tokensOnlyCost())}`);
1507
+ draw.text(namedScenario ? t.report.tokensOnlyAskedFor() : t.report.tokensOnlyCost(), { tone: 'dim' });
1508
+ draw.print();
1497
1509
  }
1498
1510
 
1499
1511
  /**
@@ -1562,7 +1574,6 @@ function printRest(
1562
1574
  showDiff: boolean,
1563
1575
  t: CliMessages,
1564
1576
  examplesReview: ExampleReview | null,
1565
- n: (v: number) => string,
1566
1577
  ): void {
1567
1578
  if (examplesReview && examplesReview.groups.length > 0) {
1568
1579
  console.log();
@@ -1600,23 +1611,6 @@ function truncate(text: string, max: number): string {
1600
1611
  return clean.length <= max ? clean : `${clean.slice(0, max - 1)}\u2026`;
1601
1612
  }
1602
1613
 
1603
- /** Wraps a paragraph to a given width. */
1604
- function wrap(text: string, width: number, indent: string): string {
1605
- const words = text.split(/\s+/);
1606
- const lines: string[] = [];
1607
- let line = '';
1608
- for (const word of words) {
1609
- if (line.length + word.length + 1 > width) {
1610
- lines.push(line);
1611
- line = word;
1612
- } else {
1613
- line = line ? `${line} ${word}` : word;
1614
- }
1615
- }
1616
- if (line) lines.push(line);
1617
- return lines.join(`\n${indent}`);
1618
- }
1619
-
1620
1614
  // --------------------------------------------------------------------------
1621
1615
  // Subcommands
1622
1616
  // --------------------------------------------------------------------------
@@ -3631,18 +3625,111 @@ async function readUsageLogOnly(file: string, t: CliMessages, billPath: string =
3631
3625
  * a bill rather than usage, and pointed at `reconcile`.
3632
3626
  */
3633
3627
  async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3634
- /* Refused before any file is read: a bad shape found after the receipt
3635
- printed would end a run that looked finished with an error. */
3636
- const csvShape = csvShapeOf(args, t);
3637
- /* "What did this month cost" is the question a Claude Code folder of a
3638
- year's sessions answers worst without a period. */
3639
- const period = billingPeriod(args, t);
3640
- const byFlag = stringFlag(args, 'by');
3641
- if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3642
- throw new Error(t.bill.badBy(byFlag));
3628
+ /*
3629
+ The statement answers first (#758). What was read, file by file, is a
3630
+ note on the answer, and on a terminal it printed above it: five lines of
3631
+ file names before the total. So when the statement is what stdout gets,
3632
+ those lines are held and written to stderr after it, in the order they
3633
+ came, and on the way out of an error too. A pipe that reads the receipt
3634
+ gets them as it always did, as they happen.
3635
+ */
3636
+ const statement = !boolFlag(args, 'receipt') && boolFlag(args, 'table', process.stdout.isTTY === true);
3637
+ if (!statement) return billBody(args, pricing, t);
3638
+ const held: unknown[][] = [];
3639
+ const write = console.error;
3640
+ console.error = (...line: unknown[]) => {
3641
+ held.push(line);
3642
+ };
3643
+ try {
3644
+ await billBody(args, pricing, t);
3645
+ } finally {
3646
+ console.error = write;
3647
+ // Notes on the answer, not the answer: dimmed on a terminal, below the
3648
+ // statement's own notes, and wrapped to the window when there is one. A
3649
+ // line of its own lines, or a pipe, gets the bytes as they came.
3650
+ for (const line of held) {
3651
+ const [only] = line;
3652
+ if (line.length === 1 && typeof only === 'string') {
3653
+ const text = WINDOW && !only.includes('\n') ? wrap(only, MAX_COLUMNS, '') : only;
3654
+ console.error(text.split('\n').map((part) => cErr.dim(part)).join('\n'));
3655
+ } else console.error(...line);
3656
+ }
3657
+ }
3658
+ }
3659
+
3660
+ /**
3661
+ * `trazum weekly [<file|dir>...]`: the week in Markdown, for somebody to read
3662
+ * in an issue (#757).
3663
+ *
3664
+ * It reads what `bill` reads, prices the seven days before `--until` and the
3665
+ * seven before those with the same catalogue, and writes the bill, what moved
3666
+ * and the three changes `plan` ranks first. It writes a file or stdout and
3667
+ * nothing else: it holds no GitHub token and makes no call. Where the summary
3668
+ * is posted is the Action's business, and the Action's inputs are the owner's
3669
+ * word for where.
3670
+ *
3671
+ * Every dollar amount and percentage in the finished text is read back against
3672
+ * the two weeks' bills. A summary with one that is in neither is refused and
3673
+ * nothing is written: the number would be read, believed and not re-added.
3674
+ */
3675
+ async function commandWeekly(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3676
+ const now = Date.now();
3677
+ const until = parseWhen(args, 'until', true, t, now);
3678
+ const windows = weekWindows(until.ms ?? now);
3679
+ const { lines } = await gatherUsageLines(args, t);
3680
+ const text = lines.join('\n');
3681
+ const profileWeek = (week: WeekWindow): UsageProfileReport =>
3682
+ profileUsage(text, { catalogue: pricing, sinceMs: week.sinceMs, untilMs: week.untilMs });
3683
+ const current = profileWeek(windows.current);
3684
+ const previous = profileWeek(windows.previous);
3685
+ const plan = buildPlan(current, billLevers(current, { catalogue: pricing }), pricing.lastReviewed);
3686
+
3687
+ const { markdown, headline } = checkedWeekly(
3688
+ buildWeeklySummary(current, previous, plan, windows),
3689
+ billFigures(current, previous, plan),
3690
+ t,
3691
+ );
3692
+
3693
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
3694
+ if (out !== undefined) {
3695
+ await writeFile(out, markdown, 'utf8');
3696
+ console.error(t.weekly.wrote(out));
3697
+ } else {
3698
+ process.stdout.write(markdown);
3643
3699
  }
3644
- const by = byFlag as BillPeriodUnit | undefined;
3645
3700
 
3701
+ /*
3702
+ The person at the machine, once the summary is safely written: the same
3703
+ notifier `watch --notify` uses, carrying one sentence of figures that went
3704
+ through the same check as the file. Off unless asked for; where the
3705
+ platform has no notifier it is said and the file stands.
3706
+ */
3707
+ if (boolFlag(args, 'notify')) {
3708
+ const sent = sendNotification(notificationFor([headline]));
3709
+ if (sent.outcome === 'unavailable') console.error(c.yellow(t.weekly.notifyUnavailable(sent.command)));
3710
+ if (sent.outcome === 'failed') console.error(c.yellow(t.weekly.notifyFailed(sent.command, sent.error)));
3711
+ }
3712
+ }
3713
+
3714
+ /**
3715
+ * What `bill` and `weekly` read: every path given, or every coding agent's own
3716
+ * sessions when none is, converted in memory to the one record shape the
3717
+ * profile reads. Everything said about a file is said here, once, so the two
3718
+ * commands refuse and report the same way.
3719
+ */
3720
+ interface GatheredUsage {
3721
+ lines: string[];
3722
+ sources: number;
3723
+ fileCount: number;
3724
+ claudeCodeFiles: number;
3725
+ codexFiles: number;
3726
+ geminiCliFiles: number;
3727
+ codexEvidence: { source: string; basis: string; files: number; duplicates: number; missingModel: number; unsupported: number; unparseable: number };
3728
+ agentLines: Map<AgentId, string[]>;
3729
+ labelledByProject: number;
3730
+ }
3731
+
3732
+ async function gatherUsageLines(args: Args, t: CliMessages): Promise<GatheredUsage> {
3646
3733
  /*
3647
3734
  No path is the most common first run, and it used to be a refusal: the
3648
3735
  person had to know where Claude Code keeps its sessions before the one
@@ -3896,6 +3983,24 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3896
3983
  if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3897
3984
 
3898
3985
  if (sources === 0) throw new Error(t.bill.nothingRead());
3986
+ return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject };
3987
+ }
3988
+
3989
+ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3990
+ /* Refused before any file is read: a bad shape found after the receipt
3991
+ printed would end a run that looked finished with an error. */
3992
+ const csvShape = csvShapeOf(args, t);
3993
+ /* "What did this month cost" is the question a Claude Code folder of a
3994
+ year's sessions answers worst without a period. */
3995
+ const period = billingPeriod(args, t);
3996
+ const byFlag = stringFlag(args, 'by');
3997
+ if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3998
+ throw new Error(t.bill.badBy(byFlag));
3999
+ }
4000
+ const by = byFlag as BillPeriodUnit | undefined;
4001
+
4002
+ const { lines, sources, fileCount, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject } =
4003
+ await gatherUsageLines(args, t);
3899
4004
 
3900
4005
  const text = lines.join('\n');
3901
4006
  const report = profileUsage(text, {
@@ -3928,7 +4033,7 @@ async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages
3928
4033
  } else if (!statement) {
3929
4034
  console.log(json);
3930
4035
  }
3931
- console.error(t.bill.sources(sources, files.length));
4036
+ console.error(t.bill.sources(sources, fileCount));
3932
4037
  printReceiptSummary(document, t);
3933
4038
  const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
3934
4039
  /*
@@ -4119,12 +4224,13 @@ function printBillStatement(
4119
4224
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
4120
4225
  const total = report.total.totalUsd;
4121
4226
  const LIMIT = 12;
4122
- const rowsOf = (entries: { name: string; calls: number; usd: number }[]): string[][] => {
4123
- const shown = entries.slice(0, LIMIT).map(({ name, calls, usd }) => {
4124
- const share = total > 0 ? usd / total : 0;
4125
- return [name, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
4126
- });
4127
- if (entries.length > LIMIT) shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '']);
4227
+ const shareCells = (usd: number): Cell[] => {
4228
+ const share = total > 0 ? usd / total : 0;
4229
+ return [{ bar: share }, pct(share)];
4230
+ };
4231
+ const rowsOf = (entries: { name: string; calls: number; usd: number }[]): Cell[][] => {
4232
+ const shown: Cell[][] = entries.slice(0, LIMIT).map(({ name, calls, usd }) => [name, n(calls), formatUsd(usd), ...shareCells(usd)]);
4233
+ if (entries.length > LIMIT) shown.push([c.dim(t.bill.moreRows(entries.length - LIMIT)), '', '', '', '']);
4128
4234
  return shown;
4129
4235
  };
4130
4236
  const columns = (first: string): TableColumn[] => [
@@ -4132,48 +4238,35 @@ function printBillStatement(
4132
4238
  { header: t.bill.colCalls(), align: 'right' },
4133
4239
  { header: 'USD', align: 'right' },
4134
4240
  { header: t.bill.colShare(), align: 'left' },
4241
+ { header: '', align: 'right' },
4135
4242
  ];
4136
4243
 
4137
- console.log();
4138
- console.log(sectionHeading(t.bill.statementHeading()));
4139
- console.log(` ${c.bold(t.bill.statementTotal(formatUsd(total), report.total.calls))}`);
4140
- if (report.span !== null) {
4141
- const span = t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs));
4142
- console.log(c.dim(` ${wrap(span, 74, ' ')}`));
4143
- }
4144
- // The period asked for, as typed: the span above is when the calls in it fell.
4145
- if (window !== undefined) console.log(c.dim(` ${wrap(t.profile.windowLine(window.since, window.until), 74, ' ')}`));
4146
4244
  /*
4147
- "Your bill" over Claude Code transcripts is the API's list price for the
4148
- work. On a Pro or Max plan the plan is what was paid, and a statement that
4149
- did not say so would hand somebody a figure they never owed.
4245
+ The question and its answer first: the total, marked. Then the
4246
+ breakdown, by agent, project, model and period. Then what qualifies the
4247
+ total, and what to do next. A reader who stops after the total has it.
4150
4248
  */
4151
- if (apiEquivalent) console.log(` ${c.yellow(wrap(t.bill.apiEquivalent(), 74, ' '))}`);
4249
+ const draw = new Report();
4250
+ const totalUsd = formatUsd(total);
4251
+ draw.blank().headline(t.bill.statementHeading(), t.bill.statementTotal(totalUsd, report.total.calls), totalUsd);
4152
4252
 
4153
4253
  // Which agent spent what, first: it is the split a person running more than one asks for.
4154
- if (byAgent.length > 1) {
4155
- console.log();
4156
- for (const line of table(columns(t.bill.colAgent()), rowsOf(byAgent))) console.log(line);
4157
- }
4254
+ if (byAgent.length > 1) draw.blank().table(columns(t.bill.colAgent()), rowsOf(byAgent));
4158
4255
 
4159
4256
  const labelled = report.byLabel.filter((row) => row.label !== UNLABELLED);
4160
4257
  if (labelled.length > 0) {
4161
- console.log();
4162
4258
  const entries = report.byLabel.map((row) => ({
4163
4259
  name: row.label === UNLABELLED ? t.profile.unlabelled() : row.label,
4164
4260
  calls: row.breakdown.calls,
4165
4261
  usd: row.breakdown.totalUsd,
4166
4262
  }));
4167
- for (const line of table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries))) {
4168
- console.log(line);
4169
- }
4263
+ draw.blank().table(columns(byProject ? t.bill.colProject() : t.bill.colWorkload()), rowsOf(entries));
4170
4264
  }
4171
4265
 
4172
4266
  const priced = report.byModel.filter((row) => !report.unpricedModels.includes(row.model));
4173
4267
  if (priced.length > 0) {
4174
- console.log();
4175
4268
  const entries = priced.map((row) => ({ name: row.model, calls: row.breakdown.calls, usd: row.breakdown.totalUsd }));
4176
- for (const line of table(columns(t.bill.colModel()), rowsOf(entries))) console.log(line);
4269
+ draw.blank().table(columns(t.bill.colModel()), rowsOf(entries));
4177
4270
  }
4178
4271
 
4179
4272
  /*
@@ -4191,38 +4284,46 @@ function printBillStatement(
4191
4284
  const { periods, undated } = spendByPeriod(report, unit);
4192
4285
  if (periods.length >= (by === undefined ? 2 : 1)) {
4193
4286
  const keep = unit === 'day' ? 31 : LIMIT;
4194
- const shown = periods.slice(-keep).map(({ period, calls, usd }) => {
4195
- const share = total > 0 ? usd / total : 0;
4196
- return [period, n(calls), formatUsd(usd), `${bar(share)} ${pct(share)}`];
4197
- });
4287
+ const shown: Cell[][] = periods.slice(-keep).map(({ period, calls, usd }) => [period, n(calls), formatUsd(usd), ...shareCells(usd)]);
4198
4288
  if (periods.length > keep) {
4199
4289
  const earlier = periods.length - keep;
4200
- shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '']);
4290
+ shown.unshift([c.dim(unit === 'month' ? t.bill.earlierMonths(earlier) : t.bill.earlierPeriods(earlier, unit)), '', '', '', '']);
4201
4291
  }
4202
- console.log();
4203
- for (const line of table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown)) console.log(line);
4292
+ draw.blank().table(columns(unit === 'month' ? t.bill.colMonth() : t.bill.colPeriod(unit)), shown);
4204
4293
  if (undated.calls > 0) {
4205
4294
  const sentence = unit === 'month'
4206
4295
  ? t.bill.monthsUndated(undated.calls, formatUsd(undated.usd))
4207
4296
  : t.bill.periodsUndated(undated.calls, formatUsd(undated.usd), unit);
4208
- console.log(c.dim(` ${wrap(sentence, 74, ' ')}`));
4297
+ draw.text(sentence, { tone: 'dim' });
4209
4298
  }
4210
4299
  const newest = periods[periods.length - 1]!;
4211
- console.log(c.dim(` ${unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit)}`));
4300
+ draw.text(unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit), { tone: 'dim' });
4212
4301
  }
4213
4302
 
4214
- console.log();
4303
+ // What qualifies the total: when the calls fell, and what it is not.
4304
+ draw.blank();
4305
+ if (report.span !== null) {
4306
+ draw.text(t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)), { tone: 'dim' });
4307
+ }
4308
+ // The period asked for, as typed: the span above is when the calls in it fell.
4309
+ if (window !== undefined) draw.text(t.profile.windowLine(window.since, window.until), { tone: 'dim' });
4310
+ /*
4311
+ "Your bill" over Claude Code transcripts is the API's list price for the
4312
+ work. On a Pro or Max plan the plan is what was paid, and a statement that
4313
+ did not say so would hand somebody a figure they never owed.
4314
+ */
4315
+ if (apiEquivalent) draw.note('caution', t.bill.apiEquivalent());
4215
4316
  if (report.unpricedModels.length > 0) {
4216
- console.log(` ${wrap(t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls), 74, ' ')}`);
4317
+ draw.note('caution', t.bill.statementUnpriced(report.unpricedModels.join(', '), report.unpriced.calls));
4217
4318
  }
4218
4319
  const ceiling = tierCeilingLine(report, t);
4219
- if (ceiling !== null) console.log(` ${wrap(ceiling, 74, ' ')}`);
4220
- if (report.skippedLines.length > 0) console.log(` ${t.bill.statementUnread(report.skippedLines.length)}`);
4320
+ if (ceiling !== null) draw.note('caution', ceiling);
4321
+ if (report.skippedLines.length > 0) draw.note('caution', t.bill.statementUnread(report.skippedLines.length));
4221
4322
  if (report.timeWindow !== null && report.timeWindow.undatedExcluded > 0) {
4222
- console.log(` ${c.yellow(wrap(t.receipt.undatedExcluded(report.timeWindow.undatedExcluded), 74, ' '))}`);
4323
+ draw.note('caution', t.receipt.undatedExcluded(report.timeWindow.undatedExcluded));
4223
4324
  }
4224
- console.log(c.dim(` ${wrap(t.bill.statementNext(), 74, ' ')}`));
4225
- console.log();
4325
+ draw.blank().text(t.bill.statementNext(), { tone: 'dim' }).blank();
4326
+ draw.print();
4226
4327
  }
4227
4328
 
4228
4329
  /**
@@ -4427,7 +4528,6 @@ function commandOwnrate(args: Args, t: CliMessages): void {
4427
4528
  outputPerMTok: Number(usdPerMTok.toFixed(4)),
4428
4529
  contextWindow: 32768,
4429
4530
  cacheMinTokens: null,
4430
- tier: 'unknown',
4431
4531
  capability: 'unknown',
4432
4532
  },
4433
4533
  },
@@ -6540,7 +6640,6 @@ async function commandOwners(
6540
6640
  */
6541
6641
  async function commandCommitment(
6542
6642
  args: Args,
6543
- config: TrazumConfig,
6544
6643
  pricing: PricingCatalogue,
6545
6644
  t: CliMessages,
6546
6645
  ): Promise<void> {
@@ -7215,7 +7314,7 @@ async function commandOptimize(
7215
7314
  ? t.report.allLabelsRowPeriod(formatUsd(row.savingUsd))
7216
7315
  : t.report.allLabelsRow(formatUsd(row.savingUsd));
7217
7316
  console.log(
7218
- ` ${row.savingUsd > 0 ? c.green('→') : c.dim('·')} ${c.bold(row.label)} ${saving} ${c.dim(`${row.path} · ${n(row.tokensBefore)} → ${n(row.tokensAfter)} tokens · ${formatUsd(row.spentUsd)} measured`)}`,
7317
+ ` ${row.savingUsd > 0 ? c.accent('→') : c.dim('·')} ${c.bold(row.label)} ${saving} ${c.dim(`${row.path} · ${n(row.tokensBefore)} → ${n(row.tokensAfter)} tokens · ${formatUsd(row.spentUsd)} measured`)}`,
7219
7318
  );
7220
7319
  }
7221
7320
  if (rows.length > 0) {
@@ -7770,16 +7869,18 @@ async function commandCheck(
7770
7869
  } else if (ok) {
7771
7870
  console.log(`${c.green(t.check.okLabel())} ${t.check.ok(n(verdict.tokens), n(maxTokens))}`);
7772
7871
  } else {
7773
- console.error(
7774
- `${c.red(t.check.failedLabel())} ${t.check.failed(n(verdict.tokens), n(maxTokens))}`,
7775
- );
7872
+ // The verdict first, in a word and its colour; then what would make it fit.
7873
+ const draw = new Report();
7874
+ draw.text(t.check.failed(n(verdict.tokens), n(maxTokens)), { first: `${c.red(t.check.failedLabel())} `, indent: '' });
7776
7875
  if (verdict.optimizedTokens !== null) {
7777
- console.error(
7876
+ draw.text(
7778
7877
  verdict.optimizedTokens <= maxTokens
7779
7878
  ? t.check.wouldFit(level, n(verdict.optimizedTokens))
7780
7879
  : t.check.stillTooBig(n(verdict.optimizedTokens)),
7880
+ { indent: '' },
7781
7881
  );
7782
7882
  }
7883
+ draw.print((line) => console.error(line));
7783
7884
  }
7784
7885
 
7785
7886
  if (!ok) process.exitCode = 1;
@@ -8116,6 +8217,198 @@ async function commandServe(
8116
8217
  }
8117
8218
  }
8118
8219
 
8220
+ /**
8221
+ * `trazum proactive`: the three places Trazum can speak first, turned on and
8222
+ * off from one command. The logic and the one function that writes live in
8223
+ * `proactive.ts`; this reads the machine once, asks, and says what happened.
8224
+ *
8225
+ * **A separate command and not a mode of `init`**, because the two edit
8226
+ * different things for different reasons. `init` proposes a config for one
8227
+ * repository and has `--dry-run` and `--yes` meaning "the config"; this edits
8228
+ * files in a home directory and the project's MCP config. Two jobs under one
8229
+ * name would have made `init --dry-run` ambiguous about which it printed.
8230
+ */
8231
+ async function commandProactive(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
8232
+ const action = args.positional[0] ?? 'status';
8233
+ if (action !== 'status' && action !== 'on' && action !== 'off') throw new Error(t.proactive.unknownAction(action));
8234
+
8235
+ let items: readonly ProactiveItem[] = PROACTIVE_ITEMS;
8236
+ const only = stringFlag(args, 'only');
8237
+ if (only !== undefined) {
8238
+ const named = only.split(',').map((name) => name.trim()).filter(Boolean);
8239
+ const unknown = named.find((name) => !(PROACTIVE_ITEMS as readonly string[]).includes(name));
8240
+ if (unknown !== undefined || named.length === 0) {
8241
+ throw new Error(t.proactive.unknownItem(unknown ?? '', PROACTIVE_ITEMS.join(', ')));
8242
+ }
8243
+ items = PROACTIVE_ITEMS.filter((item) => named.includes(item));
8244
+ }
8245
+
8246
+ /*
8247
+ The home directory is read from the environment here and nowhere else, once,
8248
+ and everything in proactive.ts takes it as a parameter. HOME first, as the
8249
+ shell does, then USERPROFILE for Windows, then what the operating system says.
8250
+ */
8251
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
8252
+ const entry = (() => {
8253
+ try {
8254
+ return realpathSync(process.argv[1] ?? '');
8255
+ } catch {
8256
+ return resolvePath(process.argv[1] ?? '');
8257
+ }
8258
+ })();
8259
+ const ctx: ProactiveCtx = {
8260
+ home,
8261
+ cwd: process.cwd(),
8262
+ platform: process.platform,
8263
+ execPath: process.execPath,
8264
+ entry,
8265
+ trazumBin: process.env.TRAZUM_BIN,
8266
+ crontab: systemCrontab(runCrontab),
8267
+ script: () => readFile(fileURLToPath(new URL('../assets/trazum-statusline.sh', import.meta.url)), 'utf8'),
8268
+ catalogue: pricing,
8269
+ };
8270
+
8271
+ const asJson = boolFlag(args, 'json');
8272
+ const terminal = process.stdin.isTTY === true;
8273
+ const yes = boolFlag(args, 'yes');
8274
+ const dryRun = action === 'status' || boolFlag(args, 'dry-run') || (!yes && !terminal);
8275
+ const forcedDryRun = action !== 'status' && !boolFlag(args, 'dry-run') && !yes && !terminal;
8276
+
8277
+ const name = (item: ProactiveItem): string => t.proactive.item[item];
8278
+ const reason = (finding: ProactiveFinding): string => t.proactive.reason[finding.code](finding.params);
8279
+ const place = (target: string): string => (target === CRONTAB ? t.proactive.crontab() : shownPath(ctx, target));
8280
+
8281
+ /** One file and the lines that go and that come, as they would be read in it. */
8282
+ const printChange = (change: { target: string; added: string[]; removed: string[] }, say: (line: string) => void = console.log): void => {
8283
+ say(` ${place(change.target)}`);
8284
+ for (const line of change.removed) say(` ${c.red(`- ${line}`)}`);
8285
+ for (const line of change.added) say(` ${c.green(`+ ${line}`)}`);
8286
+ };
8287
+
8288
+ const prompt: { reader: ReturnType<typeof createInterface> | null } = { reader: null };
8289
+ /** The items whose lines were printed before their question, so they are not printed twice. */
8290
+ const shownBeforeAsking = new Set<ProactiveItem>();
8291
+ const decide = async (item: ProactiveItem, changes: { target: string; added: string[]; removed: string[] }[]): Promise<boolean> => {
8292
+ if (yes) return true;
8293
+ /*
8294
+ Every file and every line, and then the question. A yes to "write the
8295
+ status line?" with the lines printed afterwards is a yes to something
8296
+ nobody had read: the first version asked first, and its changelog entry
8297
+ said the opposite.
8298
+ */
8299
+ // With --json the standard output is the document, so the lines go beside the question.
8300
+ const say = asJson ? console.error : console.log;
8301
+ say('');
8302
+ say(` ${c.bold((action === 'off' ? t.proactive.wouldTurnOff : t.proactive.wouldTurnOn)(name(item)))}`);
8303
+ for (const change of changes) printChange(change, say);
8304
+ shownBeforeAsking.add(item);
8305
+ prompt.reader ??= createInterface({ input: process.stdin, output: process.stderr });
8306
+ const files = [...new Set(changes.map((change) => place(change.target)))].join(', ');
8307
+ const answer = await prompt.reader.question(action === 'off' ? t.proactive.askOff(name(item), files) : t.proactive.askOn(name(item), files));
8308
+ return /^(y|yes|s|si|sí)$/i.test(answer.trim());
8309
+ };
8310
+
8311
+ let outcome: { before: ItemStatus[]; results: ItemResult[]; after: ItemStatus[] };
8312
+ try {
8313
+ if (action === 'status') {
8314
+ const inspected = await inspectProactive(ctx);
8315
+ const statuses = PROACTIVE_ITEMS.map((item) => inspected.items[item].status);
8316
+ outcome = { before: statuses, results: [], after: statuses };
8317
+ } else {
8318
+ outcome = await runProactive(ctx, { action, items, dryRun, decide });
8319
+ }
8320
+ } finally {
8321
+ prompt.reader?.close();
8322
+ }
8323
+
8324
+ const shownStatuses = (list: ItemStatus[]): ItemStatus[] => list.filter((status) => items.includes(status.item));
8325
+ if (asJson) {
8326
+ const document = {
8327
+ schemaVersion: 1,
8328
+ action,
8329
+ dryRun,
8330
+ home: ctx.home,
8331
+ project: ctx.cwd,
8332
+ items: shownStatuses(outcome.after).map((status) => ({
8333
+ item: status.item,
8334
+ state: status.verdict,
8335
+ reason: status.code,
8336
+ detail: reason(status),
8337
+ files: status.files,
8338
+ notes: status.notes.map((note) => ({ reason: note.code, detail: reason(note) })),
8339
+ })),
8340
+ changes: outcome.results.map((result) => ({
8341
+ item: result.item,
8342
+ outcome: result.outcome,
8343
+ error: result.error === null ? null : { reason: result.error.code, detail: reason(result.error) },
8344
+ files: result.changes.map((change) => ({ file: change.target, added: change.added, removed: change.removed })),
8345
+ })),
8346
+ };
8347
+ console.log(JSON.stringify(document, null, 2));
8348
+ if (outcome.results.some((result) => result.outcome === 'failed')) process.exitCode = 1;
8349
+ return;
8350
+ }
8351
+
8352
+ const verdictPaint = (status: ItemStatus, text: string): string =>
8353
+ status.verdict === 'on' ? c.green(text) : status.verdict === 'off' ? text : status.verdict === 'could-not-tell' ? c.red(text) : c.yellow(text);
8354
+ /*
8355
+ The question is the heading and the rows are its answer, one item a line:
8356
+ the name, its state in a word, and why (#758). The state's colour repeats
8357
+ the word; the reason hangs under itself, inside the window.
8358
+ */
8359
+ const draw = new Report();
8360
+ const block = (list: ItemStatus[]): void => {
8361
+ const width = Math.max(...items.map((item) => name(item).length));
8362
+ const verdictWidth = Math.max(...Object.values(t.proactive.verdict).map((word) => word.length));
8363
+ const hang = ' '.repeat(width + verdictWidth + 6);
8364
+ // The module's `wrap`: the layout a pipe always had, and inside the window when there is one.
8365
+ const said = (finding: ProactiveFinding): string => c.dim(wrap(reason(finding), 76 - width - verdictWidth, hang).trimStart());
8366
+ for (const status of shownStatuses(list)) {
8367
+ draw.line(` ${name(status.item).padEnd(width)} ${verdictPaint(status, t.proactive.verdict[status.verdict].padEnd(verdictWidth))} ${said(status)}`);
8368
+ for (const note of status.notes) draw.line(` ${' '.repeat(width + verdictWidth + 4)}${said(note)}`);
8369
+ }
8370
+ };
8371
+
8372
+ draw.blank().heading(t.proactive.heading());
8373
+ block(outcome.before);
8374
+ if (action === 'status') {
8375
+ draw.print();
8376
+ return;
8377
+ }
8378
+
8379
+ let anyChange = false;
8380
+ for (const result of outcome.results) {
8381
+ if (result.outcome === 'nothing') {
8382
+ draw.blank().text(t.proactive.nothingToChange(name(result.item)), { tone: 'dim' });
8383
+ continue;
8384
+ }
8385
+ anyChange = true;
8386
+ const done = result.outcome === 'written';
8387
+ const header = action === 'off'
8388
+ ? (done ? t.proactive.didTurnOff : t.proactive.wouldTurnOff)(name(result.item))
8389
+ : (done ? t.proactive.didTurnOn : t.proactive.wouldTurnOn)(name(result.item));
8390
+ draw.blank().text(header, { tone: 'bold' });
8391
+ // Asked about in a terminal, an item's lines are already above its question.
8392
+ // The lines a file gains or loses are its content: drawn as they are.
8393
+ if (!shownBeforeAsking.has(result.item)) for (const change of result.changes) printChange(change, (line) => draw.line(line));
8394
+ if (result.outcome === 'declined') draw.text(t.proactive.declined(name(result.item)));
8395
+ if (result.outcome === 'failed' && result.error !== null) {
8396
+ draw.note('error', t.proactive.failed(name(result.item), reason(result.error)), { tone: 'error' });
8397
+ }
8398
+ }
8399
+ // The module's `wrap` at the widths these always had, so a pipe gets the same lines.
8400
+ if (action === 'on' && anyChange) draw.blank().line(` ${c.dim(wrap(t.proactive.backupNote(BACKUP_SUFFIX), 74, ' ').trimStart())}`);
8401
+ if (dryRun && anyChange) {
8402
+ draw.blank().line(` ${wrap(forcedDryRun ? t.proactive.dryRunNoTerminal() : t.proactive.dryRunAsked(), 74, ' ').trimStart()}`);
8403
+ }
8404
+ if (outcome.results.some((result) => result.outcome === 'written')) {
8405
+ draw.blank();
8406
+ block(outcome.after);
8407
+ }
8408
+ draw.print();
8409
+ if (outcome.results.some((result) => result.outcome === 'failed')) process.exitCode = 1;
8410
+ }
8411
+
8119
8412
  /**
8120
8413
  * `trazum watch` — the afternoon it happened, said that afternoon.
8121
8414
  *
@@ -8167,6 +8460,16 @@ async function commandWatch(
8167
8460
  webhook = checked.url;
8168
8461
  }
8169
8462
 
8463
+ /*
8464
+ One source to a cycle. `--sessions` is the sessions `bill` reads with no
8465
+ path, so the command that needs no setup can alert; refused beside
8466
+ `--payload` before anything is read, because a cycle that quietly picked
8467
+ one of two would be watching the other's silence.
8468
+ */
8469
+ const sessions = boolFlag(args, 'sessions');
8470
+ if (sessions && stringFlag(args, 'payload') !== undefined) throw new Error(t.watch.sessionsAndPayload());
8471
+ const notify = boolFlag(args, 'notify');
8472
+
8170
8473
  const intervalRaw = stringFlag(args, 'interval');
8171
8474
  const once = boolFlag(args, 'once') || intervalRaw === undefined;
8172
8475
  let intervalMs = 0;
@@ -8182,38 +8485,59 @@ async function commandWatch(
8182
8485
  }
8183
8486
 
8184
8487
  const cycle = async (): Promise<number> => {
8185
- const state = await readWatchState(root);
8488
+ /*
8489
+ What was reported about one source says nothing about the other's
8490
+ figures: a crossing kept quiet because the store had already said it
8491
+ must not keep quiet one that only the sessions show. A state the other
8492
+ source wrote is a first cycle for this one, and writing over it below is
8493
+ what keeps the two from reading each other's record.
8494
+ */
8495
+ const prior = await readWatchState(root);
8496
+ const state = prior !== null && (prior.source === 'sessions') !== sessions ? null : prior;
8186
8497
  const nowMs = Date.now();
8187
8498
 
8188
8499
  /**
8189
- * Where the measurements come from: a saved payload when one is named
8190
- * (which is how this is tested and how an air-gapped run works), and the
8191
- * store otherwise. A cycle that found nothing to measure says so — a
8192
- * watcher over nothing is a green light nobody earned.
8500
+ * Where the measurements come from: the sessions on this machine when
8501
+ * `--sessions` is given, a saved payload when one is named (which is how
8502
+ * this is tested and how an air-gapped run works), and the store
8503
+ * otherwise. A cycle that found nothing to measure says so — a watcher
8504
+ * over nothing is a green light nobody earned.
8193
8505
  */
8194
8506
  const payloadPath = stringFlag(args, 'payload');
8195
- let pull;
8196
- if (payloadPath !== undefined) {
8197
- pull = normalizeAnthropicUsage(JSON.parse(await readFile(payloadPath, 'utf8')));
8507
+ let report: WatchedReport;
8508
+ let cacheDeltaUsd: number | undefined;
8509
+ let sessionFolders: string[] = [];
8510
+ if (sessions) {
8511
+ const measured = await watchedSessions(pricing, t);
8512
+ report = measured.report;
8513
+ cacheDeltaUsd = measured.cacheDeltaUsd;
8514
+ sessionFolders = measured.folders;
8198
8515
  } else {
8199
- const { resolved } = await readStore(root);
8200
- if (resolved.records.length === 0) throw new Error(t.watch.nothingToWatch(STORE_DIR));
8201
- pull = {
8202
- provider: 'store',
8203
- granularity: 'bucketed' as const,
8204
- buckets: bucketsFromRecords(resolved.records),
8205
- window: null,
8206
- gaps: [],
8207
- unavailable: [],
8208
- };
8209
- }
8516
+ let pull;
8517
+ if (payloadPath !== undefined) {
8518
+ pull = normalizeAnthropicUsage(JSON.parse(await readFile(payloadPath, 'utf8')));
8519
+ } else {
8520
+ const { resolved } = await readStore(root);
8521
+ if (resolved.records.length === 0) throw new Error(t.watch.nothingToWatch(STORE_DIR));
8522
+ pull = {
8523
+ provider: 'store',
8524
+ granularity: 'bucketed' as const,
8525
+ buckets: bucketsFromRecords(resolved.records),
8526
+ window: null,
8527
+ gaps: [],
8528
+ unavailable: [],
8529
+ };
8530
+ }
8210
8531
 
8211
- const report = bucketedProfile(pull, { catalogue: pricing });
8212
- const cache = bucketedCacheEconomics(report);
8532
+ const bucketed = bucketedProfile(pull, { catalogue: pricing });
8533
+ const cache = bucketedCacheEconomics(bucketed);
8534
+ report = bucketed;
8535
+ cacheDeltaUsd = cache.verdict === 'no-cache' ? undefined : cache.deltaUsd;
8536
+ }
8213
8537
  const result = evaluateWatch({
8214
8538
  report,
8215
8539
  thresholds,
8216
- cacheDeltaUsd: cache.verdict === 'no-cache' ? undefined : cache.deltaUsd,
8540
+ cacheDeltaUsd,
8217
8541
  nowMs,
8218
8542
  lastCoveredToMs: state?.lastCoveredToMs ?? undefined,
8219
8543
  alreadyFired: new Set(Object.keys(state?.fired ?? {})),
@@ -8222,6 +8546,7 @@ async function commandWatch(
8222
8546
  if (asJson) {
8223
8547
  console.log(JSON.stringify({ schemaVersion: 1, firedAtMs: nowMs, ...result }, null, 2));
8224
8548
  } else {
8549
+ for (const line of sessionFolders) console.log(c.dim(line));
8225
8550
  if (result.gap !== null) {
8226
8551
  console.log(c.yellow(wrap(t.watch.gap(day(result.gap.fromMs), day(result.gap.toMs)), 76, ' ')));
8227
8552
  }
@@ -8297,6 +8622,27 @@ async function commandWatch(
8297
8622
  }
8298
8623
  }
8299
8624
 
8625
+ /*
8626
+ The person at the machine, for what is new this cycle and nothing else:
8627
+ a crossing already reported is `suppressed`, and a notification about it
8628
+ would be the second one. The text is the sentence the terminal printed,
8629
+ built from the same figures, and `notificationFor` takes nothing but
8630
+ sentences, so a prompt, a path or a project name has no way in.
8631
+ */
8632
+ if (notify && result.crossings.length > 0) {
8633
+ const sent = sendNotification(
8634
+ notificationFor(
8635
+ result.crossings.map((crossing) =>
8636
+ t.watch.crossed(crossing.gate, formatUsd(crossing.measuredUsd), formatUsd(crossing.limitUsd), crossing.day),
8637
+ ),
8638
+ ),
8639
+ );
8640
+ // Said on stderr so a `--json` reader's stdout stays the document, and
8641
+ // swallowed for the reason the webhook's failure is.
8642
+ if (sent.outcome === 'unavailable') console.error(c.yellow(t.watch.notifyUnavailable(sent.command)));
8643
+ if (sent.outcome === 'failed') console.error(c.yellow(t.watch.notifyFailed(sent.command, sent.error)));
8644
+ }
8645
+
8300
8646
  const fired = { ...(state?.fired ?? {}) };
8301
8647
  for (const crossing of result.crossings) fired[firedKey(crossing.gate, crossing.day)] = nowMs;
8302
8648
  await writeWatchState(root, {
@@ -8304,6 +8650,7 @@ async function commandWatch(
8304
8650
  lastCycleMs: nowMs,
8305
8651
  lastCoveredToMs: report.span?.toMs ?? state?.lastCoveredToMs ?? null,
8306
8652
  fired,
8653
+ ...(sessions ? { source: 'sessions' as const } : {}),
8307
8654
  });
8308
8655
 
8309
8656
  return result.crossings.length + result.suppressed.length;
@@ -8323,6 +8670,66 @@ async function commandWatch(
8323
8670
  }
8324
8671
  }
8325
8672
 
8673
+ /** What a gate is judged against: a connected report has it, and so do the sessions. */
8674
+ type WatchedReport = Parameters<typeof evaluateWatch>[0]['report'];
8675
+
8676
+ /**
8677
+ * What `trazum watch --sessions` judges: the sessions Claude Code, Codex and
8678
+ * Gemini CLI keep on this machine, read the way `bill` reads them with no
8679
+ * path and priced the way `bill` prices them.
8680
+ *
8681
+ * The folders are `agentSessionFolders`, the walk is `bill`'s, the converters
8682
+ * are the ones `from-claude-code`, `from-codex` and `from-gemini-cli` use, and
8683
+ * the money is `profileUsage`'s, so a total here is the total `bill` prints for
8684
+ * the same folders. Only those three agents' files: a file no agent claims is
8685
+ * not this command's to guess at, and `bill` is where it gets named.
8686
+ *
8687
+ * What comes back is the part of a report a gate is judged against, with no
8688
+ * prompt text in it: the records the converters make carry counts and a model,
8689
+ * and the folders named are the agents' own, never a project.
8690
+ */
8691
+ async function watchedSessions(
8692
+ pricing: PricingCatalogue,
8693
+ t: CliMessages,
8694
+ ): Promise<{ report: WatchedReport; cacheDeltaUsd: number | undefined; folders: string[] }> {
8695
+ const { found, tried } = await agentSessionFolders(process.env);
8696
+ if (found.length === 0) throw new Error(t.bill.noPath(tried.join(', ')));
8697
+ const lines: string[] = [];
8698
+ for (const { path } of found) {
8699
+ const entries = await readdir(path, { recursive: true, withFileTypes: true });
8700
+ const files = entries
8701
+ .filter((entry) => entry.isFile() && isUsageLogName(entry.name))
8702
+ .map((entry) => join(entry.parentPath, entry.name))
8703
+ .sort();
8704
+ for (const file of files) {
8705
+ const text = await readUsageLog(file, t);
8706
+ const [shape, ...others] = usageShapesOf(text);
8707
+ if (shape === undefined || others.length > 0) continue;
8708
+ const records =
8709
+ shape === 'claude-code'
8710
+ ? claudeCodeRecords(text, {}).records
8711
+ : shape === 'codex'
8712
+ ? codexRecords(text, {}).records
8713
+ : shape === 'gemini-cli'
8714
+ ? geminiCliRecords(text, {}).records
8715
+ : [];
8716
+ for (const record of records) lines.push(JSON.stringify(record));
8717
+ }
8718
+ }
8719
+ const profile = profileUsage(lines.join('\n'), { catalogue: pricing });
8720
+ if (profile.total.calls === 0) throw new Error(t.watch.noSessionUsage());
8721
+ const cache = cacheEconomics(profile.total);
8722
+ return {
8723
+ report: {
8724
+ span: profile.span === null ? null : { fromMs: profile.span.fromMs, toMs: profile.span.toMs },
8725
+ total: { totalUsd: profile.total.totalUsd },
8726
+ byDay: profile.spendByDay.map((entry) => ({ day: entry.day, usd: entry.usd, calls: entry.calls })),
8727
+ },
8728
+ cacheDeltaUsd: cache.verdict === 'not-attempted' || cache.verdict === 'unpriced' ? undefined : cache.deltaUsd,
8729
+ folders: found.map(({ agent, path }) => t.watch.readingSessions(AGENT_NAMES[agent], path)),
8730
+ };
8731
+ }
8732
+
8326
8733
  /**
8327
8734
  * `trazum store` — what is kept, and what a prune would take.
8328
8735
  *
@@ -9259,7 +9666,7 @@ async function profileBySource(
9259
9666
  unmatchedFiles: unmatched,
9260
9667
  },
9261
9668
  },
9262
- (key, value) => (value instanceof Map ? undefined : value),
9669
+ (_key, value) => (value instanceof Map ? undefined : value),
9263
9670
  2,
9264
9671
  ),
9265
9672
  );
@@ -9403,7 +9810,7 @@ async function runProfileGates(context: {
9403
9810
  pricing: PricingCatalogue;
9404
9811
  t: CliMessages;
9405
9812
  }): Promise<{ failed: boolean; verdicts: string[] }> {
9406
- const { args, config, configDir, report, previous, againstDelta, windowed, now, pricing, t } =
9813
+ const { args, config, configDir, report, previous, againstDelta, windowed, pricing, t } =
9407
9814
  context;
9408
9815
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
9409
9816
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
@@ -9875,7 +10282,7 @@ async function writeProfileSideFiles(context: {
9875
10282
  t: CliMessages;
9876
10283
  }): Promise<void> {
9877
10284
  const {
9878
- args, path, report, previous, pressures, labelDrivers, modelDrivers, againstOverlap,
10285
+ args, report, previous, pressures, labelDrivers, modelDrivers, againstOverlap,
9879
10286
  whatIf, pricingStale, windowed, gates, pricing, t,
9880
10287
  } = context;
9881
10288
  /**
@@ -10244,9 +10651,8 @@ function reportAgainstPrevious(context: {
10244
10651
  now: number;
10245
10652
  t: CliMessages;
10246
10653
  }): void {
10247
- const { report, previous, againstOverlap, labelDrivers, modelDrivers, gates, now, t } =
10654
+ const { report, previous, againstOverlap, labelDrivers, modelDrivers, t } =
10248
10655
  context;
10249
- const n = (value: number): string => value.toLocaleString(t.numberLocale);
10250
10656
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
10251
10657
  /**
10252
10658
  * This bill against the previous one — how spend actually gets out of hand.
@@ -10524,26 +10930,24 @@ function reportContextPressure(
10524
10930
  * prediction of *when*: a straight line through two points is a guess
10525
10931
  * wearing arithmetic's clothes.
10526
10932
  */
10527
- {
10528
- if (pressures.length > 0) {
10933
+ if (pressures.length > 0) {
10934
+ console.log();
10935
+ console.log(sectionHeading(t.profile.pressureHeading()));
10936
+ for (const row of pressures.slice(0, 3)) {
10937
+ const label = row.label === UNLABELLED ? t.profile.unlabelled() : row.label;
10938
+ const line = t.profile.pressureLine(
10939
+ label,
10940
+ row.modelName,
10941
+ n(row.maxCallInputTokens),
10942
+ n(row.contextWindow),
10943
+ pct(row.share),
10944
+ );
10529
10945
  console.log();
10530
- console.log(sectionHeading(t.profile.pressureHeading()));
10531
- for (const row of pressures.slice(0, 3)) {
10532
- const label = row.label === UNLABELLED ? t.profile.unlabelled() : row.label;
10533
- const line = t.profile.pressureLine(
10534
- label,
10535
- row.modelName,
10536
- n(row.maxCallInputTokens),
10537
- n(row.contextWindow),
10538
- pct(row.share),
10539
- );
10540
- console.log();
10541
- if (row.share >= 0.85) {
10542
- console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
10543
- console.log(` ${c.dim(wrap(t.profile.pressureAdvice(), 74, ' '))}`);
10544
- } else {
10545
- console.log(` ${c.dim(wrap(line, 74, ' '))}`);
10546
- }
10946
+ if (row.share >= 0.85) {
10947
+ console.log(` ${c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
10948
+ console.log(` ${c.dim(wrap(t.profile.pressureAdvice(), 74, ' '))}`);
10949
+ } else {
10950
+ console.log(` ${c.dim(wrap(line, 74, ' '))}`);
10547
10951
  }
10548
10952
  }
10549
10953
  }
@@ -10737,11 +11141,9 @@ function reportConversationHistory(report: UsageProfileReport, t: CliMessages):
10737
11141
  */
10738
11142
  function reportWhatIf(
10739
11143
  whatIf: ReturnType<typeof repriceProfile>,
10740
- report: UsageProfileReport,
10741
11144
  t: CliMessages,
10742
11145
  ): void {
10743
11146
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
10744
- const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
10745
11147
  /**
10746
11148
  * `--what-if <model>`: these exact calls, at another model's rates.
10747
11149
  *
@@ -10771,7 +11173,7 @@ function reportWhatIf(
10771
11173
  formatUsd(whatIf.targetUsd),
10772
11174
  formatUsd(Math.abs(whatIf.deltaUsd)),
10773
11175
  );
10774
- console.log(` ${cheaper ? c.green('→') : c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
11176
+ console.log(` ${cheaper ? c.accent('→') : c.yellow('!')} ${c.bold(wrap(line, 74, ' '))}`);
10775
11177
  console.log(
10776
11178
  ` ${c.dim(wrap(cheaper ? t.profile.whatIfCheaper() : t.profile.whatIfDearer(), 74, ' '))}`,
10777
11179
  );
@@ -10850,7 +11252,6 @@ function reportLevers(
10850
11252
  pricing: PricingCatalogue,
10851
11253
  t: CliMessages,
10852
11254
  ): void {
10853
- const n = (value: number): string => value.toLocaleString(t.numberLocale);
10854
11255
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
10855
11256
  /**
10856
11257
  * The section this command is for, and the answer to the fairest complaint the
@@ -10901,7 +11302,7 @@ function reportLevers(
10901
11302
  * than the bill it came from, in the flattering direction.
10902
11303
  */
10903
11304
  console.log(
10904
- ` ${c.green('→')} ${c.bold(wrap(t.profile.leverSlice(label, slice.modelName, formatUsd(slice.combinedUsd), pct(slice.shareOfBill)), 74, ' '))}`,
11305
+ ` ${c.accent('→')} ${c.bold(wrap(t.profile.leverSlice(label, slice.modelName, formatUsd(slice.combinedUsd), pct(slice.shareOfBill)), 74, ' '))}`,
10905
11306
  );
10906
11307
  console.log(` ${c.dim(t.profile.leverCalls(t.profile.calls(slice.calls), formatUsd(slice.spentUsd)))}`);
10907
11308
  if (slice.route) {
@@ -11426,42 +11827,45 @@ async function commandPlan(
11426
11827
  return;
11427
11828
  }
11428
11829
 
11429
- console.log(sectionHeading(t.plan.heading(n(actions.length), formatUsd(plan.totalUsd))));
11430
- console.log(
11431
- ` ${wrap(t.plan.totals(formatUsd(stamped.projectedSavingUsd), formatUsd(stamped.measuredStakeUsd)), 74, ' ')}`,
11830
+ /*
11831
+ The question and its answer first: what the plan would save, marked.
11832
+ Then the actions, then what was left out and how to read it (#758).
11833
+ */
11834
+ const draw = new Report();
11835
+ const projected = formatUsd(stamped.projectedSavingUsd);
11836
+ draw.headline(
11837
+ t.plan.heading(n(actions.length), formatUsd(plan.totalUsd)),
11838
+ t.plan.totals(projected, formatUsd(stamped.measuredStakeUsd)),
11839
+ projected,
11432
11840
  );
11433
- if (plan.span === null) {
11434
- console.log(` ${c.dim(wrap(t.plan.noClock(), 74, ' '))}`);
11435
- }
11841
+ if (plan.span === null) draw.text(t.plan.noClock(), { tone: 'dim' });
11436
11842
  for (const action of actions) {
11437
11843
  const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
11438
11844
  const money =
11439
11845
  action.savingUsd !== null
11440
11846
  ? t.plan.projected(formatUsd(action.savingUsd))
11441
11847
  : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
11442
- console.log();
11443
- console.log(` ${c.green('→')} ${c.bold(t.plan.action(action.kind, name, action.model))} ${money}`);
11848
+ draw.blank();
11849
+ // The action and its money on one line when the window holds them; the
11850
+ // money under the action when it does not, never split from its word.
11851
+ const title = t.plan.action(action.kind, name, action.model);
11852
+ const whole = ` ${draw.markOf('point')} ${c.bold(title)} ${money}`;
11853
+ if (draw.fits(whole)) draw.line(whole);
11854
+ else draw.text(title, { first: ` ${draw.markOf('point')} `, indent: ' ', tone: 'bold' }).text(money, { indent: ' ' });
11855
+ // The module's `wrap`, at the widths these lines always had on a pipe.
11444
11856
  if (action.detail.routeTo !== undefined) {
11445
- console.log(` ${c.dim(t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch'))}`);
11857
+ draw.line(` ${c.dim(wrap(t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch'), 1000, ' '))}`);
11446
11858
  }
11447
11859
  for (const assumption of action.assumes) {
11448
- console.log(` ${c.yellow('?')} ${c.dim(wrap(t.plan.assume(assumption), 72, ' '))}`);
11860
+ draw.line(` ${draw.markOf('question')} ${c.dim(wrap(t.plan.assume(assumption), 72, ' '))}`);
11449
11861
  }
11450
- if (action.check !== null) {
11451
- console.log(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
11452
- }
11453
- }
11454
- if (filtered > 0) {
11455
- console.log();
11456
- console.log(` ${c.dim(wrap(t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd)), 74, ' '))}`);
11457
- }
11458
- if (plan.batchExcludedUsd > 0) {
11459
- console.log();
11460
- console.log(` ${c.dim(wrap(t.plan.batchExcluded(formatUsd(plan.batchExcludedUsd)), 74, ' '))}`);
11862
+ if (action.check !== null) draw.line(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
11461
11863
  }
11462
- console.log();
11463
- console.log(` ${c.dim(wrap(t.plan.footer(), 74, ' '))}`);
11464
- if (outPath !== undefined) console.log(c.dim(wrap(t.plan.wrote(outPath), 74, '')));
11864
+ if (filtered > 0) draw.blank().text(t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd)), { tone: 'dim' });
11865
+ if (plan.batchExcludedUsd > 0) draw.blank().text(t.plan.batchExcluded(formatUsd(plan.batchExcludedUsd)), { tone: 'dim' });
11866
+ draw.blank().text(t.plan.footer(), { tone: 'dim' });
11867
+ if (outPath !== undefined) draw.text(t.plan.wrote(outPath), { indent: '', tone: 'dim' });
11868
+ draw.print();
11465
11869
  }
11466
11870
 
11467
11871
  async function commandProfile(
@@ -11903,7 +12307,7 @@ async function commandProfile(
11903
12307
  if (report.total.calls === 0) {
11904
12308
  console.log();
11905
12309
  console.log(c.dim(report.unpriced.calls === 0 ? t.profile.empty() : t.profile.nothingPriced()));
11906
- reportProfileGaps(report, t, n, pricingStale);
12310
+ reportProfileGaps(report, t, pricingStale);
11907
12311
  return;
11908
12312
  }
11909
12313
 
@@ -11915,9 +12319,46 @@ async function commandProfile(
11915
12319
  [t.profile.partOutput(), report.total.outputUsd, shares.output, report.total.outputTokens],
11916
12320
  ];
11917
12321
 
11918
- console.log();
11919
- console.log(sectionHeading(t.profile.heading()));
11920
- console.log(` ${t.profile.spent(t.profile.calls(report.total.calls), formatUsd(report.total.totalUsd))}`);
12322
+ /*
12323
+ The question and its answer first: what this log cost, the total marked.
12324
+ Then where it went, part by part. Then what qualifies the total: the
12325
+ period, the files, a doubled line, the window (#758).
12326
+ */
12327
+ const draw = new Report();
12328
+ const totalUsd = formatUsd(report.total.totalUsd);
12329
+ draw.blank().headline(t.profile.heading(), t.profile.spent(t.profile.calls(report.total.calls), totalUsd), totalUsd);
12330
+ draw.blank();
12331
+ // Every part, including the zero ones. A row missing because it was zero reads
12332
+ // as a row somebody forgot, and "you are not caching at all" is a finding.
12333
+ const partRows: { share: number; text: string }[] = parts.map(([name, usd, share, tokens]) => ({
12334
+ share,
12335
+ text: t.profile.part(name, formatUsd(usd), pct(share), n(tokens)),
12336
+ }));
12337
+ // Billed per search, so it counts searches where the rows above count tokens.
12338
+ if (report.total.webSearchRequests > 0) {
12339
+ partRows.push({
12340
+ share: shares.webSearch,
12341
+ text: t.profile.partSearches(t.profile.partWebSearch(), formatUsd(report.total.webSearchUsd), pct(shares.webSearch), report.total.webSearchRequests),
12342
+ });
12343
+ }
12344
+ draw.shares(partRows);
12345
+
12346
+ /**
12347
+ * The line the command exists for: which part of the bill to argue with.
12348
+ *
12349
+ * When output is both the biggest part and over half, the two sentences say the
12350
+ * same thing and the second says more — so only the second prints. Reporting a
12351
+ * fact twice in adjacent lines reads as a bug, and it was one.
12352
+ */
12353
+ const [biggestName, , biggestShare] = parts.reduce((a, b) => (b[1] > a[1] ? b : a));
12354
+ const outputDominates = shares.output > 0.5;
12355
+ draw.blank();
12356
+ if (outputDominates) {
12357
+ draw.text(t.profile.outputDominates(pct(shares.output)), { tone: 'bold' });
12358
+ } else {
12359
+ draw.text(t.profile.biggestPart(biggestName, pct(biggestShare)), { tone: 'bold' });
12360
+ }
12361
+
11921
12362
  /**
11922
12363
  * The period, when the log carries a clock — stated, never extrapolated. A
11923
12364
  * span makes the reader's own monthly arithmetic valid; a per-month figure
@@ -11932,15 +12373,11 @@ async function commandProfile(
11932
12373
  report.span.calls < totalParsed
11933
12374
  ? ` ${t.profile.spanPartial(n(report.span.calls), n(totalParsed))}`
11934
12375
  : '';
11935
- console.log(
11936
- ` ${c.dim(wrap(`${t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs))}${partial}`, 74, ' '))}`,
11937
- );
12376
+ draw.text(`${t.profile.spanLine(dayOf(report.span.fromMs), dayOf(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs))}${partial}`, { tone: 'dim' });
11938
12377
  }
11939
12378
  // How many files this report covers, when it covers more than one: a total
11940
12379
  // over "the logs" that silently skipped one is wrong by an unknown amount.
11941
- if (logFiles.length > 1) {
11942
- console.log(` ${c.dim(wrap(t.profile.readFiles(logFiles.length, path), 74, ' '))}`);
11943
- }
12380
+ if (logFiles.length > 1) draw.text(t.profile.readFiles(logFiles.length, path), { tone: 'dim' });
11944
12381
 
11945
12382
  /**
11946
12383
  * A doubled bill, said before anything is believed.
@@ -11953,9 +12390,7 @@ async function commandProfile(
11953
12390
  * double export or a genuinely busy millisecond is the reader's to know.
11954
12391
  */
11955
12392
  if (report.duplicateLines.count > 0) {
11956
- console.log(
11957
- ` ${c.yellow('!')} ${c.dim(wrap(t.profile.duplicateLines(report.duplicateLines.count, formatUsd(report.duplicateLines.usd)), 74, ' '))}`,
11958
- );
12393
+ draw.note('caution', t.profile.duplicateLines(report.duplicateLines.count, formatUsd(report.duplicateLines.usd)), { tone: 'dim' });
11959
12394
  }
11960
12395
 
11961
12396
  /**
@@ -11966,46 +12401,13 @@ async function commandProfile(
11966
12401
  * figures are a floor on the period, and only this line says so.
11967
12402
  */
11968
12403
  if (report.timeWindow !== null) {
11969
- console.log(
11970
- ` ${c.dim(wrap(t.profile.windowLine(stringFlag(args, 'since') ?? '—', stringFlag(args, 'until') ?? '—'), 74, ' '))}`,
11971
- );
11972
- if (relativeWindow) {
11973
- console.log(` ${c.dim(wrap(t.profile.windowRelative(), 74, ' '))}`);
11974
- }
12404
+ draw.text(t.profile.windowLine(stringFlag(args, 'since') ?? '—', stringFlag(args, 'until') ?? '—'), { tone: 'dim' });
12405
+ if (relativeWindow) draw.text(t.profile.windowRelative(), { tone: 'dim' });
11975
12406
  if (report.timeWindow.undatedExcluded > 0) {
11976
- console.log(
11977
- ` ${c.yellow(wrap(t.profile.windowUndated(report.timeWindow.undatedExcluded), 74, ' '))}`,
11978
- );
12407
+ draw.note('caution', t.profile.windowUndated(report.timeWindow.undatedExcluded));
11979
12408
  }
11980
12409
  }
11981
- console.log();
11982
- // Every part, including the zero ones. A row missing because it was zero reads
11983
- // as a row somebody forgot, and "you are not caching at all" is a finding.
11984
- for (const [name, usd, share, tokens] of parts) {
11985
- console.log(` ${bar(share)} ${t.profile.part(name, formatUsd(usd), pct(share), n(tokens))}`);
11986
- }
11987
- // Billed per search, so it counts searches where the rows above count tokens.
11988
- if (report.total.webSearchRequests > 0) {
11989
- console.log(
11990
- ` ${bar(shares.webSearch)} ${t.profile.partSearches(t.profile.partWebSearch(), formatUsd(report.total.webSearchUsd), pct(shares.webSearch), report.total.webSearchRequests)}`,
11991
- );
11992
- }
11993
-
11994
- /**
11995
- * The line the command exists for: which part of the bill to argue with.
11996
- *
11997
- * When output is both the biggest part and over half, the two sentences say the
11998
- * same thing and the second says more — so only the second prints. Reporting a
11999
- * fact twice in adjacent lines reads as a bug, and it was one.
12000
- */
12001
- const [biggestName, , biggestShare] = parts.reduce((a, b) => (b[1] > a[1] ? b : a));
12002
- const outputDominates = shares.output > 0.5;
12003
- console.log();
12004
- if (outputDominates) {
12005
- console.log(` ${c.bold(wrap(t.profile.outputDominates(pct(shares.output)), 74, ' '))}`);
12006
- } else {
12007
- console.log(` ${c.bold(t.profile.biggestPart(biggestName, pct(biggestShare)))}`);
12008
- }
12410
+ draw.print();
12009
12411
 
12010
12412
  /**
12011
12413
  * The most expensive day, with a suspect attached.
@@ -12026,9 +12428,10 @@ async function commandProfile(
12026
12428
  peak.topLabel !== null && report.byLabel.length > 1
12027
12429
  ? ` ${t.profile.dayPeakLabel(peak.topLabel === UNLABELLED ? t.profile.unlabelled() : peak.topLabel, formatUsd(peak.topLabelUsd))}`
12028
12430
  : '';
12431
+ // Loud past twice the median: the mark says so, a pipe included.
12029
12432
  const loud = peak.usd > 2 * medianUsd;
12030
- const text = wrap(`${line}${labelClause}`, 74, ' ');
12031
- console.log(` ${loud ? c.yellow(text) : c.dim(text)}`);
12433
+ if (loud) new Report().note('caution', `${line}${labelClause}`).print();
12434
+ else new Report().text(`${line}${labelClause}`, { tone: 'dim' }).print();
12032
12435
  }
12033
12436
  }
12034
12437
 
@@ -12074,7 +12477,7 @@ async function commandProfile(
12074
12477
 
12075
12478
  reportLevers(report, pricing, t);
12076
12479
 
12077
- reportWhatIf(whatIf, report, t);
12480
+ reportWhatIf(whatIf, t);
12078
12481
 
12079
12482
  reportConversationHistory(report, t);
12080
12483
 
@@ -12097,17 +12500,21 @@ async function commandProfile(
12097
12500
  [t.profile.byModelHeading(), report.byModel.map((r) => [r.model, r.breakdown] as const)],
12098
12501
  ] as const) {
12099
12502
  if (rows.length <= 1) continue; // One row is the total again, said twice.
12100
- console.log();
12101
- console.log(sectionHeading(heading));
12102
- for (const [name, breakdown] of rows) {
12103
- const share = report.total.totalUsd > 0 ? breakdown.totalUsd / report.total.totalUsd : 0;
12104
- console.log(` ${bar(share)} ${t.profile.row(name, formatUsd(breakdown.totalUsd), pct(share), t.profile.calls(breakdown.calls))}`);
12105
- }
12503
+ new Report()
12504
+ .blank()
12505
+ .heading(heading)
12506
+ .shares(
12507
+ rows.map(([name, breakdown]) => {
12508
+ const share = report.total.totalUsd > 0 ? breakdown.totalUsd / report.total.totalUsd : 0;
12509
+ return { share, text: t.profile.row(name, formatUsd(breakdown.totalUsd), pct(share), t.profile.calls(breakdown.calls)) };
12510
+ }),
12511
+ )
12512
+ .print();
12106
12513
  }
12107
12514
 
12108
12515
  reportOutcomesAndCoverage(report, config, t);
12109
12516
 
12110
- reportProfileGaps(report, t, n, pricingStale);
12517
+ reportProfileGaps(report, t, pricingStale);
12111
12518
 
12112
12519
  gates = await runProfileGates({
12113
12520
  args, config, configDir, report, previous, againstDelta, windowed, now, pricing, t,
@@ -12129,7 +12536,6 @@ async function commandProfile(
12129
12536
  function reportProfileGaps(
12130
12537
  report: ReturnType<typeof profileUsage>,
12131
12538
  t: CliMessages,
12132
- n: (value: number) => string,
12133
12539
  stalePricing: { date: string; days: number } | null = null,
12134
12540
  ): void {
12135
12541
  /**
@@ -12728,7 +13134,7 @@ async function checkDirectory(
12728
13134
  only = checkable;
12729
13135
  }
12730
13136
 
12731
- const { verdicts, declined, truncated, extensions, band } = await scanPrompts(
13137
+ const { verdicts, declined, truncated, band } = await scanPrompts(
12732
13138
  root,
12733
13139
  args,
12734
13140
  flagBudget,
@@ -12873,19 +13279,33 @@ async function checkDirectory(
12873
13279
  ...verdicts.map((v) => (v.maxTokens === null ? 0 : n(v.maxTokens).length)),
12874
13280
  );
12875
13281
 
12876
- console.log();
12877
- console.log(sectionHeading(t.check.directoryHeading(root, verdicts.length)));
12878
- console.log();
13282
+ /*
13283
+ The question and its answer first (#758): how many prompts, and whether
13284
+ they fit, in the colour of the verdict and in words that say it without
13285
+ one. Then the prompts, one a line; then what could not be read.
13286
+ */
13287
+ const summary = t.check.directorySummary(failures.length, verdicts.length);
13288
+ // Three independent verdicts about one run: a busted budget, an unreadable
13289
+ // marker, and drift past the baseline. Any of them failing fails the build —
13290
+ // an && here would let a breach ride out on a green budget.
13291
+ // The summary sentence counts budgets, so its colour follows budgets. `bad`
13292
+ // is the run's verdict and folds in the baseline: three independent findings
13293
+ // about one run, and any of them failing fails the build. An && here would let
13294
+ // a breach ride out on a green budget.
13295
+ const budgetBad = failures.length > 0 || declined.length > 0;
13296
+ const bad = budgetBad || (baselineOutcome?.breached.length ?? 0) > 0;
13297
+ const draw = new Report();
13298
+ draw.blank().heading(t.check.directoryHeading(root, verdicts.length));
13299
+ draw.text(summary, { tone: budgetBad ? 'error' : 'good' });
13300
+ draw.blank();
12879
13301
 
12880
13302
  for (const verdict of verdicts) {
12881
13303
  const tokens = n(verdict.tokens).padStart(tokenWidth);
12882
13304
 
12883
13305
  if (verdict.maxTokens === null) {
12884
13306
  // Blanks where " / <budget>" would be, so the path column does not shift.
12885
- console.log(
12886
- ` ${c.dim('—'.padEnd(labelWidth))}${tokens}${' '.repeat(3 + budgetWidth)} ` +
12887
- `${verdict.path} ${c.dim(t.check.noBudget())}`,
12888
- );
13307
+ const lead = ` ${c.dim('—'.padEnd(labelWidth))}${tokens}${' '.repeat(3 + budgetWidth)} `;
13308
+ draw.line(`${lead}${fitPath(`${verdict.path} ${t.check.noBudget()}`, draw.room(lead))}`);
12889
13309
  continue;
12890
13310
  }
12891
13311
 
@@ -12893,15 +13313,15 @@ async function checkDirectory(
12893
13313
  const plain = over ? t.check.failedLabel() : t.check.okLabel();
12894
13314
  const label = (over ? c.red(plain) : c.green(plain)) + ' '.repeat(labelWidth - plain.length);
12895
13315
  const budget = n(verdict.maxTokens).padEnd(budgetWidth);
12896
- console.log(` ${label}${tokens} / ${budget} ${verdict.path}`);
13316
+ const lead = ` ${label}${tokens} / ${budget} `;
13317
+ draw.line(`${lead}${fitPath(verdict.path, draw.room(lead))}`);
12897
13318
 
12898
13319
  if (over && verdict.optimizedTokens !== null) {
12899
- console.log(
12900
- ` ${' '.repeat(labelWidth)}${c.dim(
12901
- verdict.optimizedTokens <= verdict.maxTokens
12902
- ? t.check.wouldFit(level, n(verdict.optimizedTokens))
12903
- : t.check.stillTooBig(n(verdict.optimizedTokens)),
12904
- )}`,
13320
+ draw.text(
13321
+ verdict.optimizedTokens <= verdict.maxTokens
13322
+ ? t.check.wouldFit(level, n(verdict.optimizedTokens))
13323
+ : t.check.stillTooBig(n(verdict.optimizedTokens)),
13324
+ { indent: ` ${' '.repeat(labelWidth)}`, tone: 'dim' },
12905
13325
  );
12906
13326
  }
12907
13327
  }
@@ -12911,26 +13331,13 @@ async function checkDirectory(
12911
13331
  // green summary alongside would be the same lie as "0 failures" from a run
12912
13332
  // that measured nothing.
12913
13333
  if (declined.length > 0) {
12914
- console.log();
12915
- console.log(c.red(t.check.declinedHeading(declined.length)));
13334
+ draw.blank().line(c.red(t.check.declinedHeading(declined.length)));
12916
13335
  for (const entry of declined) {
12917
- console.log(` ${c.dim(`${entry.path} ${t.check.declinedAt(entry.line, entry.detail)}`)}`);
13336
+ draw.text(`${entry.path} ${t.check.declinedAt(entry.line, entry.detail)}`, { tone: 'dim' });
12918
13337
  }
12919
13338
  }
12920
-
12921
- console.log();
12922
- const summary = t.check.directorySummary(failures.length, verdicts.length);
12923
- // Three independent verdicts about one run: a busted budget, an unreadable
12924
- // marker, and drift past the baseline. Any of them failing fails the build —
12925
- // an && here would let a breach ride out on a green budget.
12926
- // The summary sentence counts budgets, so its colour follows budgets. `bad`
12927
- // is the run's verdict and folds in the baseline: three independent findings
12928
- // about one run, and any of them failing fails the build. An && here would let
12929
- // a breach ride out on a green budget.
12930
- const budgetBad = failures.length > 0 || declined.length > 0;
12931
- const bad = budgetBad || (baselineOutcome?.breached.length ?? 0) > 0;
12932
- console.log(` ${budgetBad ? c.red(summary) : c.green(summary)}`);
12933
- if (truncated) console.log(` ${c.yellow(t.check.walkTruncated())}`);
13339
+ if (truncated) draw.blank().note('caution', t.check.walkTruncated());
13340
+ draw.print();
12934
13341
 
12935
13342
  // After the per-file summary, because the two answer different questions and
12936
13343
  // the wider one reads last: budgets are about files, the baseline is about the
@@ -13044,7 +13451,7 @@ async function commandPrune(args: Args, t: CliMessages): Promise<void> {
13044
13451
  */
13045
13452
  const needed = contribution.verdict === 'diverges';
13046
13453
  const unknown = contribution.verdict === 'inconclusive';
13047
- const mark = unknown ? c.yellow('?') : needed ? c.dim('·') : c.green('→');
13454
+ const mark = unknown ? c.yellow('?') : needed ? c.dim('·') : c.accent('→');
13048
13455
  const label = unknown
13049
13456
  ? t.prune.verdictUnknown()
13050
13457
  : needed
@@ -14131,7 +14538,7 @@ async function main(): Promise<void> {
14131
14538
  await commandReport(args, config, pricing, t);
14132
14539
  break;
14133
14540
  case 'commitment':
14134
- await commandCommitment(args, config, pricing, t);
14541
+ await commandCommitment(args, pricing, t);
14135
14542
  break;
14136
14543
  case 'owners':
14137
14544
  await commandOwners(args, config, pricing, t);
@@ -14202,6 +14609,9 @@ async function main(): Promise<void> {
14202
14609
  case 'bill':
14203
14610
  await commandBill(args, pricing, t);
14204
14611
  break;
14612
+ case 'weekly':
14613
+ await commandWeekly(args, pricing, t);
14614
+ break;
14205
14615
  case 'from-helicone':
14206
14616
  await commandFromHelicone(args, t);
14207
14617
  break;
@@ -14223,6 +14633,9 @@ async function main(): Promise<void> {
14223
14633
  case 'init':
14224
14634
  await commandInit(args, config, pricing, t);
14225
14635
  break;
14636
+ case 'proactive':
14637
+ await commandProactive(args, pricing, t);
14638
+ break;
14226
14639
  case 'where':
14227
14640
  await commandWhere(args, config, pricing, t);
14228
14641
  break;