@trazum/cli 3.0.0 → 3.0.2

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 (109) hide show
  1. package/README.md +4 -1
  2. package/assets/trazum-statusline.sh +45 -0
  3. package/dist/base-cost.d.ts +173 -0
  4. package/dist/base-cost.d.ts.map +1 -0
  5. package/dist/base-cost.js +244 -0
  6. package/dist/base-cost.js.map +1 -0
  7. package/dist/bill-range.d.ts +118 -0
  8. package/dist/bill-range.d.ts.map +1 -0
  9. package/dist/bill-range.js +122 -0
  10. package/dist/bill-range.js.map +1 -0
  11. package/dist/command-help.d.ts +17 -0
  12. package/dist/command-help.d.ts.map +1 -0
  13. package/dist/command-help.js +69 -0
  14. package/dist/command-help.js.map +1 -0
  15. package/dist/filter.d.ts +7 -1
  16. package/dist/filter.d.ts.map +1 -1
  17. package/dist/filter.js +10 -18
  18. package/dist/filter.js.map +1 -1
  19. package/dist/gateway-metrics.d.ts +83 -0
  20. package/dist/gateway-metrics.d.ts.map +1 -0
  21. package/dist/gateway-metrics.js +181 -0
  22. package/dist/gateway-metrics.js.map +1 -0
  23. package/dist/gateway-server.d.ts +23 -5
  24. package/dist/gateway-server.d.ts.map +1 -1
  25. package/dist/gateway-server.js +26 -1
  26. package/dist/gateway-server.js.map +1 -1
  27. package/dist/gateway-spend.d.ts +11 -1
  28. package/dist/gateway-spend.d.ts.map +1 -1
  29. package/dist/gateway-spend.js +44 -32
  30. package/dist/gateway-spend.js.map +1 -1
  31. package/dist/git.d.ts +70 -0
  32. package/dist/git.d.ts.map +1 -1
  33. package/dist/git.js +145 -0
  34. package/dist/git.js.map +1 -1
  35. package/dist/i18n/en.d.ts.map +1 -1
  36. package/dist/i18n/en.js +358 -6
  37. package/dist/i18n/en.js.map +1 -1
  38. package/dist/i18n/es.d.ts +0 -1
  39. package/dist/i18n/es.d.ts.map +1 -1
  40. package/dist/i18n/es.js +456 -35
  41. package/dist/i18n/es.js.map +1 -1
  42. package/dist/i18n/types.d.ts +205 -0
  43. package/dist/i18n/types.d.ts.map +1 -1
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +942 -59
  46. package/dist/index.js.map +1 -1
  47. package/dist/loopback-guard.d.ts +37 -0
  48. package/dist/loopback-guard.d.ts.map +1 -0
  49. package/dist/loopback-guard.js +65 -0
  50. package/dist/loopback-guard.js.map +1 -0
  51. package/dist/markdown.d.ts +23 -0
  52. package/dist/markdown.d.ts.map +1 -1
  53. package/dist/markdown.js +105 -0
  54. package/dist/markdown.js.map +1 -1
  55. package/dist/plan-edits.d.ts +63 -0
  56. package/dist/plan-edits.d.ts.map +1 -0
  57. package/dist/plan-edits.js +96 -0
  58. package/dist/plan-edits.js.map +1 -0
  59. package/dist/proactive.d.ts +17 -2
  60. package/dist/proactive.d.ts.map +1 -1
  61. package/dist/proactive.js +16 -9
  62. package/dist/proactive.js.map +1 -1
  63. package/dist/receipt-send.d.ts +44 -0
  64. package/dist/receipt-send.d.ts.map +1 -0
  65. package/dist/receipt-send.js +71 -0
  66. package/dist/receipt-send.js.map +1 -0
  67. package/dist/serve.d.ts +7 -0
  68. package/dist/serve.d.ts.map +1 -1
  69. package/dist/serve.js +22 -1
  70. package/dist/serve.js.map +1 -1
  71. package/dist/session-guard.d.ts +210 -0
  72. package/dist/session-guard.d.ts.map +1 -0
  73. package/dist/session-guard.js +463 -0
  74. package/dist/session-guard.js.map +1 -0
  75. package/dist/task.d.ts +7 -1
  76. package/dist/task.d.ts.map +1 -1
  77. package/dist/task.js +7 -26
  78. package/dist/task.js.map +1 -1
  79. package/dist/waste.d.ts +25 -0
  80. package/dist/waste.d.ts.map +1 -0
  81. package/dist/waste.js +39 -0
  82. package/dist/waste.js.map +1 -0
  83. package/dist/zone.d.ts +27 -0
  84. package/dist/zone.d.ts.map +1 -0
  85. package/dist/zone.js +96 -0
  86. package/dist/zone.js.map +1 -0
  87. package/package.json +2 -2
  88. package/src/base-cost.ts +384 -0
  89. package/src/bill-range.ts +206 -0
  90. package/src/command-help.ts +65 -0
  91. package/src/filter.ts +11 -18
  92. package/src/gateway-metrics.ts +209 -0
  93. package/src/gateway-server.ts +43 -6
  94. package/src/gateway-spend.ts +45 -33
  95. package/src/git.ts +158 -0
  96. package/src/i18n/en.ts +424 -6
  97. package/src/i18n/es.ts +542 -35
  98. package/src/i18n/types.ts +208 -0
  99. package/src/index.ts +952 -58
  100. package/src/loopback-guard.ts +74 -0
  101. package/src/markdown.ts +117 -0
  102. package/src/plan-edits.ts +120 -0
  103. package/src/proactive.ts +22 -13
  104. package/src/receipt-send.ts +89 -0
  105. package/src/serve.ts +23 -1
  106. package/src/session-guard.ts +541 -0
  107. package/src/task.ts +8 -26
  108. package/src/waste.ts +42 -0
  109. package/src/zone.ts +95 -0
package/src/index.ts CHANGED
@@ -5,7 +5,7 @@ import { mkdir, mkdtemp, open, readdir, readFile, rm, stat, writeFile } from 'no
5
5
  import type { FileHandle } from 'node:fs/promises';
6
6
  import { cpus, homedir, tmpdir } from 'node:os';
7
7
  import { createInterface } from 'node:readline/promises';
8
- import { dirname, join, resolve as resolvePath } from 'node:path';
8
+ import { basename, dirname, join, resolve as resolvePath } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { createGunzip, gunzipSync } from 'node:zlib';
11
11
  import { Readable } from 'node:stream';
@@ -19,6 +19,8 @@ import {
19
19
  breaches,
20
20
  cacheableMinimum,
21
21
  analyzeCachePrefix,
22
+ analyzeSessionWaste,
23
+ sessionCwd,
22
24
  billFigures,
23
25
  billLevers,
24
26
  buildWeeklySummary,
@@ -151,6 +153,7 @@ import {
151
153
  positionAt,
152
154
  positionReport,
153
155
  PRICING_LAST_REVIEWED,
156
+ modelFrom,
154
157
  reviewedForModels,
155
158
  PROVIDER_REVIEWED,
156
159
  STALE_PRICING_DAYS,
@@ -175,10 +178,15 @@ import {
175
178
  isOffered,
176
179
  SOURCE_EXTENSIONS,
177
180
  suggestRewrites,
181
+ billOtlpInput,
182
+ toBillOtlpMetrics,
183
+ toPrometheusText,
178
184
  toOtlpMetrics,
179
185
  toPromptfoo,
180
186
  UNLABELLED,
181
187
  withExactTokenCounts,
188
+ overlayFromClaudeModelPricing,
189
+ partnerModelId,
182
190
  } from '@trazum/core';
183
191
  import { cacheDir, cacheStats, cachingProvider, clearCache } from './suggest-cache.js';
184
192
  import { OPTIONAL_COUNTERS } from './optional-counters.js';
@@ -190,6 +198,7 @@ import type {
190
198
  ProfileCsvShape,
191
199
  MeasuredUsage,
192
200
  PruneReport,
201
+ PlanAction,
193
202
  PlanDocument,
194
203
  StoredReport,
195
204
  VerifiedAction,
@@ -242,6 +251,7 @@ import {
242
251
  SAFE_FETCH_INIT,
243
252
  applyPricingOverlay,
244
253
  catalogueFromOverlay,
254
+ MAX_PRICING_BYTES,
245
255
  checkedEndpoint,
246
256
  openrouterOverlay,
247
257
  detectHost,
@@ -257,6 +267,9 @@ import type {
257
267
  } from '@trazum/core/node';
258
268
 
259
269
  import {
270
+ GitUnavailableError,
271
+ commitTimes,
272
+ rangeDelivery,
260
273
  contentAt,
261
274
  gitAvailable,
262
275
  namesByRevision,
@@ -266,6 +279,12 @@ import {
266
279
  runSelf,
267
280
  } from './git.js';
268
281
  import type { Revision } from './git.js';
282
+ import { billRange, perDelivery, projectLabelOfRoot, windowOf } from './bill-range.js';
283
+ import { canonicalZone, dayInZone, groupByDayInZone, nextDay, startOfDayInZone } from './zone.js';
284
+ import { currentFileDigests, planEditsFor } from './plan-edits.js';
285
+ import { baseGateFails, priceAgainstBase, readBothSides, volumeFor } from './base-cost.js';
286
+ import type { BaseCostReport } from './base-cost.js';
287
+ import type { EditSkip } from './plan-edits.js';
269
288
  import { fetchProviderUsage, findCredential } from './connect.js';
270
289
  import { STORE_DIR, appendRecords, readStore, rewriteStore } from './store-fs.js';
271
290
  import { WAIVER_LOG, appendWaiverUse, readWaiverLog } from './waiver-log.js';
@@ -276,6 +295,9 @@ import {
276
295
  buildGateway,
277
296
  listenGateway,
278
297
  } from './gateway-server.js';
298
+ import type { GatewayCount } from './gateway-server.js';
299
+ import { GatewayMetrics, buildMetricsServer } from './gateway-metrics.js';
300
+ import { priceGatewayUsage } from './gateway-spend.js';
279
301
  import {
280
302
  WATCH_STATE_VERSION,
281
303
  checkWebhook,
@@ -284,9 +306,13 @@ import {
284
306
  writeWatchState,
285
307
  } from './watch-run.js';
286
308
  import { notificationFor, sendNotification } from './watch-notify.js';
309
+ import { RECEIPT_KEY_ENV, checkReceiptTarget, sendReceipt } from './receipt-send.js';
287
310
  import { LOCALE_ENV_VARS, detectLocale, getCliMessages } from './i18n/index.js';
288
311
  import {
289
312
  MAX_SUMMARY_CHARS,
313
+ baseChangeText,
314
+ basePriceText,
315
+ baseSideText,
290
316
  fitWithin,
291
317
  renderBlameMarkdown,
292
318
  renderCheckMarkdown,
@@ -316,10 +342,23 @@ import {
316
342
  CRONTAB,
317
343
  inspectAll as inspectProactive,
318
344
  run as runProactive,
345
+ pathsFor,
346
+ readJsonObject,
319
347
  shown as shownPath,
320
348
  systemCrontab,
321
349
  } from './proactive.js';
322
350
  import type { Ctx as ProactiveCtx, Finding as ProactiveFinding, Item as ProactiveItem, ItemResult, ItemStatus } from './proactive.js';
351
+ import {
352
+ GuardWriteFailed,
353
+ applyGuardPlan,
354
+ check as checkSessionGuard,
355
+ guardState,
356
+ parseThresholds as parseGuardThresholds,
357
+ planGuard,
358
+ viewGuard,
359
+ } from './session-guard.js';
360
+ import { readSession, sizeOf } from './waste.js';
361
+ import { commandHelp } from './command-help.js';
323
362
  import { MAX_COLUMNS, Report, WINDOW, c, cErr, fitPath, sectionHeading, table, wrap } from './style.js';
324
363
  import type { Cell, TableColumn } from './style.js';
325
364
 
@@ -365,14 +404,25 @@ const VALUE_FLAGS = new Set([
365
404
  'against',
366
405
  'contract',
367
406
  'on-cannot-tell',
407
+ // `session-guard check|install`: the two dollar thresholds, which have no default.
408
+ 'warn',
409
+ 'stop',
410
+ // `waste`: a CLAUDE.md to size, the MCP servers the person says are loaded, and the fewest reads worth listing.
411
+ 'claude-md',
412
+ 'mcp-servers',
413
+ 'min-reads',
368
414
  'from-log',
369
415
  'min-usd',
370
416
  'payload',
371
417
  'keep',
372
418
  'interval',
373
419
  'webhook',
420
+ // `bill --receipt --send`: where the receipt is posted. The key is never a flag.
421
+ 'send',
374
422
  'port',
375
423
  'socket',
424
+ // `gateway`: the loopback port its counts are scraped from, off unless given.
425
+ 'metrics-port',
376
426
  // `route` takes a path here, and the flag is deliberately not `--prompt`:
377
427
  // everywhere else in this tool `--prompt` names a marked prompt *inside* a
378
428
  // source file, and reusing it for a path would be a trap laid for the reader.
@@ -391,6 +441,9 @@ const VALUE_FLAGS = new Set([
391
441
  'max-usd',
392
442
  'max-growth-usd',
393
443
  'max-cache-loss-usd',
444
+ // `check --base <ref>` and its gate (#785).
445
+ 'base',
446
+ 'max-monthly-increase-usd',
394
447
  'max-stale-hours',
395
448
  'measure',
396
449
  'workload',
@@ -406,6 +459,9 @@ const VALUE_FLAGS = new Set([
406
459
  'until',
407
460
  // `bill --by day|week|month`: the calendar unit the statement is split by.
408
461
  'by',
462
+ // `bill --agent <name>`: keep one coding agent. `bill --timezone <zone>`: cut days there (#826).
463
+ 'agent',
464
+ 'timezone',
409
465
  'export',
410
466
  'limit',
411
467
  'locale',
@@ -414,6 +470,10 @@ const VALUE_FLAGS = new Set([
414
470
  'html-out',
415
471
  'pdf-out',
416
472
  'otlp-out',
473
+ // `bill --prom-out <file>`: the bill in the Prometheus text format (#844).
474
+ 'prom-out',
475
+ // `bill --git-range <range>`: the commits whose span the statement sums.
476
+ 'git-range',
417
477
  'pricing',
418
478
  'prompt',
419
479
  'out',
@@ -424,6 +484,8 @@ const VALUE_FLAGS = new Set([
424
484
  'gpu-usd-hour',
425
485
  'tokens-per-second',
426
486
  'utilization',
487
+ // `model-pricing --reviewed <date>`: when the contracted rates were last checked (#856).
488
+ 'reviewed',
427
489
  'state',
428
490
  ]);
429
491
 
@@ -502,6 +564,12 @@ function localeFromArgv(argv: string[]): Locale {
502
564
  return detectLocale(flag);
503
565
  }
504
566
 
567
+ /** The arguments without `--locale <value>`, for a command whose own parser does not know it. */
568
+ function withoutLocale(args: string[]): string[] {
569
+ const index = args.indexOf('--locale');
570
+ return index === -1 ? args : [...args.slice(0, index), ...args.slice(index + 2)];
571
+ }
572
+
505
573
  function stringFlag(args: Args, name: string): string | undefined {
506
574
  const raw = args.flags.get(name);
507
575
  return typeof raw === 'string' ? raw : undefined;
@@ -847,10 +915,10 @@ const COMMAND_FLAGS: Record<string, string[]> = {
847
915
  'tokens-only', 'cost', 'prompt', 'suggest', 'apply-suggestions',
848
916
  'cache-suggestions', 'from-log', 'label', 'all-labels',
849
917
  ],
850
- check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from'],
918
+ check: ['max-tokens', 'level', 'exact-tokens', 'markdown-out', 'baseline', 'files-from', 'base', 'max-monthly-increase-usd'],
851
919
  baseline: ['model', 'calls', 'output-tokens', 'cache-hit-rate', 'batch', 'exact-tokens', 'out', 'o'],
852
920
  profile: ['json', 'pricing', 'pricing-live', 'against', 'what-if', 'markdown-out', 'html-out', 'pdf-out', 'csv-out', 'csv-shape', 'max-usd', 'max-growth-usd', 'max-cache-loss-usd', 'max-day-usd', 'max-session-usd', 'label', 'since', 'until', 'dry-run', 'markdown-summary', 'by-source', 'allow-empty'],
853
- plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live'],
921
+ plan: ['json', 'out', 'markdown-out', 'min-usd', 'pricing', 'pricing-live', 'edits', 'reorder'],
854
922
  verify: ['against', 'gate', 'json', 'markdown-out', 'pricing', 'pricing-live'],
855
923
  history: ['store', 'json', 'markdown-out'],
856
924
  connect: ['since', 'until', 'payload', 'store', 'json', 'out', 'markdown-out', 'pricing', 'pricing-live', 'dry-run'],
@@ -878,17 +946,18 @@ const COMMAND_FLAGS: Record<string, string[]> = {
878
946
  'from-anthropic': ['label', 'label-by-workspace', 'out', 'o'],
879
947
  'from-openai': ['label', 'label-by-project', 'out', 'o'],
880
948
  'from-openrouter': ['label', 'label-by-workspace', 'out', 'o'],
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'],
949
+ bill: ['label', 'label-from-project', 'out', 'o', 'stamp', 'receipt', 'send', 'table', 'pricing', 'pricing-live', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'otlp-out', 'prom-out', 'git-range', 'delivery', 'since', 'until', 'by', 'agent', 'timezone'],
882
950
  weekly: ['label', 'label-from-project', 'out', 'o', 'until', 'notify', 'pricing', 'pricing-live'],
883
951
  'from-helicone': ['out', 'o'],
884
952
  'from-langsmith': ['out', 'o'],
885
953
  switch: ['to', 'migration-usd', 'cases'],
886
954
  ownrate: ['gpu-usd-hour', 'tokens-per-second', 'utilization'],
955
+ 'model-pricing': ['reviewed', 'out', 'o'],
887
956
  pulse: ['json', 'max-stale-hours'],
888
957
  bench: ['workload', 'json', 'record', 'against', 'max-ratio'],
889
958
  write: ['answers', 'json', 'out', 'o', 'calls', 'avg-output'],
890
959
  feedback: [],
891
- gateway: ['on-cannot-tell', 'port', 'socket', 'log', 'pricing', 'pricing-live'],
960
+ gateway: ['on-cannot-tell', 'port', 'socket', 'metrics-port', 'log', 'pricing', 'pricing-live'],
892
961
  ladder: ['pricing', 'pricing-live', 'since', 'until', 'label'],
893
962
  experiment: ['a', 'b', 'min-outcomes', 'pricing', 'pricing-live'],
894
963
  quality: ['label', 'at', 'gate', 'pricing', 'pricing-live'],
@@ -901,6 +970,8 @@ const COMMAND_FLAGS: Record<string, string[]> = {
901
970
  blame: ['limit', 'model', 'calls', 'output-tokens', 'batch', 'prompt', 'markdown-out'],
902
971
  doctor: ['level', 'model', 'calls', 'output-tokens', 'batch', 'disable', 'prompt', 'otlp-out'],
903
972
  proactive: ['only', 'dry-run', 'yes', 'json'],
973
+ 'session-guard': ['warn', 'stop', 'on-cannot-tell', 'dry-run', 'yes'],
974
+ waste: ['claude-md', 'mcp-servers', 'min-reads', 'json'],
904
975
  };
905
976
 
906
977
  function rejectUnknownFlags(args: Args, t: CliMessages): void {
@@ -3462,10 +3533,11 @@ async function commandReconcile(args: Args, t: CliMessages): Promise<void> {
3462
3533
  function billingPeriod(
3463
3534
  args: Args,
3464
3535
  t: CliMessages,
3536
+ zone?: string,
3465
3537
  ): { sinceMs?: number; untilMs?: number; relative: boolean; words?: { since: string; until: string } } {
3466
3538
  const now = Date.now();
3467
- const since = parseWhen(args, 'since', false, t, now);
3468
- const until = parseWhen(args, 'until', true, t, now);
3539
+ const since = parseWhen(args, 'since', false, t, now, zone);
3540
+ const until = parseWhen(args, 'until', true, t, now, zone);
3469
3541
  if (since.ms !== undefined && until.ms !== undefined && since.ms >= until.ms) {
3470
3542
  throw new Error(t.profile.sinceAfterUntil());
3471
3543
  }
@@ -3489,13 +3561,17 @@ function refuseEmptyPeriod(
3489
3561
  period: ReturnType<typeof billingPeriod>,
3490
3562
  pricing: PricingCatalogue,
3491
3563
  t: CliMessages,
3564
+ zone?: string,
3492
3565
  ): void {
3493
3566
  if (period.words === undefined || report.total.calls > 0 || report.unpriced.calls > 0) return;
3494
3567
  const whole = profileUsage(text, { catalogue: pricing });
3495
3568
  if (whole.total.calls === 0 && whole.unpriced.calls === 0) return;
3496
3569
  if (whole.span === null) throw new Error(t.profile.windowNeedsClock());
3497
3570
  throw new Error(
3498
- `${t.bill.windowMatchesNothing(dayOf(whole.span.fromMs), dayOf(whole.span.toMs))}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`,
3571
+ `${t.bill.windowMatchesNothing(
3572
+ zone === undefined ? dayOf(whole.span.fromMs) : dayInZone(whole.span.fromMs, zone),
3573
+ zone === undefined ? dayOf(whole.span.toMs) : dayInZone(whole.span.toMs, zone),
3574
+ )}${period.relative ? ` ${t.profile.windowRelativeEmpty()}` : ''}`,
3499
3575
  );
3500
3576
  }
3501
3577
 
@@ -3625,6 +3701,10 @@ async function readUsageLogOnly(file: string, t: CliMessages, billPath: string =
3625
3701
  * a bill rather than usage, and pointed at `reconcile`.
3626
3702
  */
3627
3703
  async function commandBill(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
3704
+ /* A range of commits asks a different question and prints its own statement (#777). */
3705
+ const gitRange = stringFlag(args, 'git-range');
3706
+ if (gitRange !== undefined) return billGitRange(args, gitRange, pricing, t);
3707
+ if (args.flags.has('delivery')) throw new Error(t.bill.deliveryNeedsRange());
3628
3708
  /*
3629
3709
  The statement answers first (#758). What was read, file by file, is a
3630
3710
  note on the answer, and on a terminal it printed above it: five lines of
@@ -3726,6 +3806,8 @@ interface GatheredUsage {
3726
3806
  geminiCliFiles: number;
3727
3807
  codexEvidence: { source: string; basis: string; files: number; duplicates: number; missingModel: number; unsupported: number; unparseable: number };
3728
3808
  agentLines: Map<AgentId, string[]>;
3809
+ /** The records no coding agent's session folder produced: a log, a provider export, spans. */
3810
+ otherLines: string[];
3729
3811
  labelledByProject: number;
3730
3812
  }
3731
3813
 
@@ -3805,6 +3887,7 @@ async function gatherUsageLines(args: Args, t: CliMessages): Promise<GatheredUsa
3805
3887
  let geminiRemainder = 0;
3806
3888
  /* Each agent's own records, so a bill that read more than one can say which spent what. */
3807
3889
  const agentLines = new Map<AgentId, string[]>();
3890
+ const otherLines: string[] = [];
3808
3891
  const codexEvidence = { source: 'codex', basis: 'api-equivalent-telemetry', files: 0, duplicates: 0, missingModel: 0, unsupported: 0, unparseable: 0 };
3809
3892
  const lines: string[] = [];
3810
3893
  let sources = 0;
@@ -3930,7 +4013,11 @@ async function gatherUsageLines(args: Args, t: CliMessages): Promise<GatheredUsa
3930
4013
  case 'usage-log': {
3931
4014
  /* Already the shape every door reads: passed through line by line,
3932
4015
  and what does not parse is the receipt's own unread-lines gap. */
3933
- for (const line of text.split('\n')) if (line.trim() !== '') lines.push(line);
4016
+ for (const line of text.split('\n')) {
4017
+ if (line.trim() === '') continue;
4018
+ lines.push(line);
4019
+ otherLines.push(line);
4020
+ }
3934
4021
  break;
3935
4022
  }
3936
4023
  }
@@ -3939,6 +4026,8 @@ async function gatherUsageLines(args: Args, t: CliMessages): Promise<GatheredUsa
3939
4026
  const own = agentLines.get(shape) ?? [];
3940
4027
  for (const record of records) own.push(JSON.stringify(record));
3941
4028
  agentLines.set(shape, own);
4029
+ } else {
4030
+ for (const record of records) otherLines.push(JSON.stringify(record));
3942
4031
  }
3943
4032
  sources += 1;
3944
4033
  const count = shape === 'usage-log' ? null : records.length;
@@ -3983,24 +4072,203 @@ async function gatherUsageLines(args: Args, t: CliMessages): Promise<GatheredUsa
3983
4072
  if (geminiRemainder > 0) console.error(t.fromGeminiCli.remainder(geminiRemainder));
3984
4073
 
3985
4074
  if (sources === 0) throw new Error(t.bill.nothingRead());
3986
- return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject };
4075
+ return { lines, sources, fileCount: files.length, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, otherLines, labelledByProject };
4076
+ }
4077
+
4078
+ /**
4079
+ * `trazum bill --git-range <range>` (#777): what was recorded in this
4080
+ * repository's Claude Code sessions between the first and the last commit of
4081
+ * the range. The reasoning, and what the figure is not, is in `bill-range.ts`.
4082
+ *
4083
+ * Every flag that would set the period, the project or a file to write is
4084
+ * refused rather than ignored: a `--since` quietly overridden by the commits
4085
+ * would put a different period on the page than the one asked for.
4086
+ */
4087
+ async function billGitRange(args: Args, range: string, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
4088
+ for (const flag of ['since', 'until', 'label', 'by', 'agent', 'timezone', 'out', 'receipt', 'send', 'table', 'stamp', 'html-out', 'pdf-out', 'markdown-out', 'csv-out', 'csv-shape', 'otlp-out', 'prom-out']) {
4089
+ if (args.flags.has(flag)) throw new Error(t.bill.rangeConflict(`--${flag}`));
4090
+ }
4091
+ if (!boolFlag(args, 'label-from-project', true)) throw new Error(t.bill.rangeConflict('--no-label-from-project'));
4092
+
4093
+ const cwd = process.cwd();
4094
+ if (!gitAvailable(cwd)) throw new Error(t.bill.rangeNoGit());
4095
+ const root = repositoryRoot(cwd);
4096
+ if (root === null) throw new Error(t.bill.rangeNoRepository());
4097
+ let times;
4098
+ try {
4099
+ times = commitTimes(range, { cwd: root });
4100
+ } catch (error) {
4101
+ if (error instanceof GitUnavailableError) throw new Error(t.bill.rangeNoGit());
4102
+ throw error;
4103
+ }
4104
+ if (times === null) throw new Error(t.bill.rangeBad(range));
4105
+ const window = windowOf(times);
4106
+ if (window === null) throw new Error(t.bill.rangeEmpty(range));
4107
+
4108
+ const gathered = await gatherUsageLines(args, t);
4109
+ const claudeCodeLines = gathered.agentLines.get('claude-code') ?? [];
4110
+ const otherSources =
4111
+ (gathered.agentLines.get('codex')?.length ?? 0) + (gathered.agentLines.get('gemini-cli')?.length ?? 0) + gathered.otherLines.length;
4112
+ const project = projectLabelOfRoot(root);
4113
+ const answer = billRange({ claudeCodeLines, otherSources, project, window, catalogue: pricing });
4114
+ if (answer.projectRecords === 0) throw new Error(t.bill.rangeNoProject());
4115
+
4116
+ /* `--delivery`: what git shows landed in the same range, as counts (#825). */
4117
+ let delivery: ReturnType<typeof rangeDelivery> = null;
4118
+ if (boolFlag(args, 'delivery')) {
4119
+ try {
4120
+ delivery = rangeDelivery(range, { cwd: root });
4121
+ } catch (error) {
4122
+ if (error instanceof GitUnavailableError) throw new Error(t.bill.rangeNoGit());
4123
+ throw error;
4124
+ }
4125
+ }
4126
+
4127
+ const at = (ms: number): string => new Date(ms).toISOString().replace('.000Z', 'Z');
4128
+ const out: string[] = [
4129
+ '',
4130
+ t.bill.rangeHeading(range),
4131
+ '',
4132
+ t.bill.rangeWindow(at(window.fromMs), at(window.toMs), window.commits),
4133
+ answer.inside.sessions > 0
4134
+ ? t.bill.rangeInside(formatUsd(answer.inside.usd), answer.inside.calls, answer.inside.sessions)
4135
+ : t.bill.rangeNothingInside(),
4136
+ ];
4137
+ if (answer.straddling.length > 0) {
4138
+ out.push('', t.bill.rangeStraddleHeading(answer.straddling.length));
4139
+ for (const s of answer.straddling) {
4140
+ out.push(t.bill.rangeStraddleRow(s.session, at(s.firstMs), at(s.lastMs), formatUsd(s.insideUsd), s.insideCalls, formatUsd(s.outsideUsd), s.outsideCalls));
4141
+ }
4142
+ } else {
4143
+ out.push('', t.bill.rangeNoStraddle());
4144
+ }
4145
+ out.push('', t.bill.rangeMeaning());
4146
+ const left = answer.leftOut;
4147
+ out.push(t.bill.rangeLeftOut(answer.outsideCalls, left.otherProjects, left.otherSources, left.undated));
4148
+ if (answer.inside.unpricedCalls > 0) out.push(t.bill.rangeUnpriced(answer.inside.unpricedCalls));
4149
+ /* After everything the plain view prints, so the flag only adds lines at the end (#825). */
4150
+ if (delivery !== null) {
4151
+ out.push('', t.bill.rangeDelivered(delivery.commits, delivery.merges, delivery.pullRequests, delivery.days));
4152
+ if (answer.inside.sessions > 0) {
4153
+ const per = perDelivery(answer.inside.usd, delivery);
4154
+ const fmt = (usd: number | null): string | null => (usd === null ? null : formatUsd(usd));
4155
+ out.push(t.bill.rangeDividedBy(fmt(per.perCommit), fmt(per.perPullRequest), fmt(per.perDay)));
4156
+ } else {
4157
+ out.push(t.bill.rangeDividedNothing());
4158
+ }
4159
+ }
4160
+ out.push('');
4161
+ console.log(out.join('\n'));
4162
+ if (gathered.claudeCodeFiles > 0) console.error(t.bill.apiEquivalent());
4163
+ }
4164
+
4165
+ /** The ids `--agent` takes: the ones `bill` names each agent's records by. */
4166
+ const agentIds = (): AgentId[] => Object.keys(AGENT_NAMES) as AgentId[];
4167
+
4168
+ /**
4169
+ * `bill --agent <name>`, checked: an id (`claude-code`) or the name the bill
4170
+ * prints (`Claude Code`), in any case. An agent it does not know is refused by
4171
+ * name, with the ones it does, never read as "no records".
4172
+ */
4173
+ function agentFlagOf(args: Args, t: CliMessages): AgentId | undefined {
4174
+ const raw = stringFlag(args, 'agent');
4175
+ if (raw === undefined) return undefined;
4176
+ const wanted = raw.trim().toLowerCase();
4177
+ const found = agentIds().find((id) => id === wanted || AGENT_NAMES[id].toLowerCase() === wanted);
4178
+ if (found === undefined) throw new Error(t.bill.badAgent(raw, agentIds().join(', ')));
4179
+ return found;
4180
+ }
4181
+
4182
+ /**
4183
+ * `bill --timezone <zone>`, checked, and refused beside the outputs that cut
4184
+ * their days in UTC: those would print days that are not the ones the flag
4185
+ * asked for. The receipt and the statement are not among them. The receipt
4186
+ * holds instants and no day; the statement is the one that is cut.
4187
+ */
4188
+ function zoneFlagOf(args: Args, t: CliMessages, csvShape: ProfileCsvShape): string | undefined {
4189
+ const raw = stringFlag(args, 'timezone');
4190
+ if (raw === undefined) return undefined;
4191
+ const zone = canonicalZone(raw);
4192
+ if (zone === null) throw new Error(t.bill.badTimezone(raw));
4193
+ for (const flag of ['otlp-out', 'prom-out', 'markdown-out', 'html-out', 'pdf-out']) {
4194
+ if (args.flags.has(flag)) throw new Error(t.bill.timezoneConflict(`--${flag}`));
4195
+ }
4196
+ if (args.flags.has('csv-out') && csvShape !== 'slice') throw new Error(t.bill.timezoneConflict(`--csv-out --csv-shape ${csvShape}`));
4197
+ return zone;
3987
4198
  }
3988
4199
 
4200
+ /**
4201
+ * The priced, dated calls of a bill by day in `zone`: each day's records priced
4202
+ * through the same profile, window and catalogue as the whole, so the days add
4203
+ * up to what the UTC days would have.
4204
+ */
4205
+ function zonedSpendByDay(
4206
+ lines: readonly string[],
4207
+ zone: string,
4208
+ pricing: PricingCatalogue,
4209
+ period: ReturnType<typeof billingPeriod>,
4210
+ ): UsageProfileReport['spendByDay'] {
4211
+ const rows: UsageProfileReport['spendByDay'] = [];
4212
+ for (const [day, own] of [...groupByDayInZone(lines, zone)].sort(([a], [b]) => (a < b ? -1 : 1))) {
4213
+ const part = profileUsage(own.join('\n'), {
4214
+ catalogue: pricing,
4215
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
4216
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
4217
+ });
4218
+ const calls = part.spendByDay.reduce((sum, d) => sum + d.calls, 0);
4219
+ const usd = part.spendByDay.reduce((sum, d) => sum + d.usd, 0);
4220
+ if (calls > 0) rows.push({ day, calls, usd, topLabel: null, topLabelUsd: 0, byModel: [] });
4221
+ }
4222
+ return rows;
4223
+ }
4224
+
4225
+ /** `bill --send` could not deliver the receipt. 1 stays what every other failure exits with. */
4226
+ const BILL_SEND_FAILED = 3;
4227
+
3989
4228
  async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages): Promise<void> {
4229
+ /* `--send` posts the receipt, so it is refused without the flag that asks
4230
+ for the receipt, and its URL and key are judged before any file is read:
4231
+ a send that would be refused must not follow a bill that took a minute. */
4232
+ const sendRaw = stringFlag(args, 'send');
4233
+ let sendTarget: { url: URL; key: string | undefined } | null = null;
4234
+ if (sendRaw !== undefined) {
4235
+ if (!boolFlag(args, 'receipt')) throw new Error(t.bill.sendNeedsReceipt());
4236
+ const checked = checkReceiptTarget(sendRaw);
4237
+ if (!checked.ok) throw new Error(t.bill.badSendTarget(checked.reason, RECEIPT_KEY_ENV));
4238
+ sendTarget = { url: checked.url, key: checked.key };
4239
+ }
3990
4240
  /* Refused before any file is read: a bad shape found after the receipt
3991
4241
  printed would end a run that looked finished with an error. */
3992
4242
  const csvShape = csvShapeOf(args, t);
4243
+ /* `--agent` and `--timezone` are judged here too, for the same reason (#826). */
4244
+ const agent = agentFlagOf(args, t);
4245
+ const zone = zoneFlagOf(args, t, csvShape);
3993
4246
  /* "What did this month cost" is the question a Claude Code folder of a
3994
4247
  year's sessions answers worst without a period. */
3995
- const period = billingPeriod(args, t);
4248
+ const period = billingPeriod(args, t, zone);
3996
4249
  const byFlag = stringFlag(args, 'by');
3997
4250
  if (byFlag !== undefined && byFlag !== 'day' && byFlag !== 'week' && byFlag !== 'month') {
3998
4251
  throw new Error(t.bill.badBy(byFlag));
3999
4252
  }
4000
4253
  const by = byFlag as BillPeriodUnit | undefined;
4001
4254
 
4002
- const { lines, sources, fileCount, claudeCodeFiles, codexFiles, geminiCliFiles, codexEvidence, agentLines, labelledByProject } =
4003
- await gatherUsageLines(args, t);
4255
+ const gathered = await gatherUsageLines(args, t);
4256
+ const { sources, fileCount, claudeCodeFiles, geminiCliFiles, codexEvidence, labelledByProject } = gathered;
4257
+ /*
4258
+ `--agent` keeps one coding agent's records, the ones `bill` already tells
4259
+ apart by the folder or shape they were read from, and nothing else: a plain
4260
+ log or a provider export belongs to no agent and is left out, counted. What
4261
+ is left out is said on stderr, so a narrower bill never passes for a whole one.
4262
+ */
4263
+ const only = agent === undefined ? null : (gathered.agentLines.get(agent) ?? []);
4264
+ if (agent !== undefined && only !== null) {
4265
+ if (only.length === 0) throw new Error(t.bill.agentNoRecords(AGENT_NAMES[agent], agentIds().join(', ')));
4266
+ console.error(t.bill.agentOnly(AGENT_NAMES[agent], only.length, gathered.lines.length - only.length));
4267
+ }
4268
+ const lines = only ?? gathered.lines;
4269
+ const agentLines = agent === undefined || only === null ? gathered.agentLines : new Map<AgentId, string[]>([[agent, only]]);
4270
+ const otherLines = only === null ? gathered.otherLines : [];
4271
+ const codexFiles = agent === undefined || agent === 'codex' ? gathered.codexFiles : 0;
4004
4272
 
4005
4273
  const text = lines.join('\n');
4006
4274
  const report = profileUsage(text, {
@@ -4008,7 +4276,7 @@ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages):
4008
4276
  ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
4009
4277
  ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
4010
4278
  });
4011
- refuseEmptyPeriod(text, report, period, pricing, t);
4279
+ refuseEmptyPeriod(text, report, period, pricing, t, zone);
4012
4280
  const document = receiptFrom(report, pricing, boolFlag(args, 'stamp') ? { emittedAt: new Date() } : {});
4013
4281
  const billDocument = codexFiles === 0 ? document : {
4014
4282
  ...document,
@@ -4016,6 +4284,35 @@ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages):
4016
4284
  };
4017
4285
  const json = JSON.stringify(billDocument, null, 2);
4018
4286
 
4287
+ /*
4288
+ The bill as OTLP metrics, when asked for: a file and nothing sent, the way
4289
+ `doctor --otlp-out` does it. Priced here from the same records through the
4290
+ same `profileUsage`, split by day, project, model and agent; a day still
4291
+ being measured is counted in the payload's resource and not drawn as a
4292
+ point. See `toBillOtlpMetrics`.
4293
+ */
4294
+ const otlpPath = stringFlag(args, 'otlp-out');
4295
+ const promPath = stringFlag(args, 'prom-out');
4296
+ if (otlpPath !== undefined || promPath !== undefined) {
4297
+ // Built once for both: the Prometheus text is written from the OTLP payload, so the two cannot disagree.
4298
+ const payload = toBillOtlpMetrics(
4299
+ billOtlpInput(
4300
+ [
4301
+ { agent: null, lines: otherLines },
4302
+ ...[...agentLines.entries()].map(([agent, own]) => ({ agent: AGENT_NAMES[agent], lines: own })),
4303
+ ],
4304
+ {
4305
+ catalogue: pricing,
4306
+ ...(period.sinceMs !== undefined ? { sinceMs: period.sinceMs } : {}),
4307
+ ...(period.untilMs !== undefined ? { untilMs: period.untilMs } : {}),
4308
+ nowMs: Date.now(),
4309
+ },
4310
+ ),
4311
+ );
4312
+ if (otlpPath !== undefined && (await writeOtlp(args, () => payload))) console.error(t.report.reportWritten(otlpPath));
4313
+ if (promPath !== undefined && (await writeText(promPath, toPrometheusText(payload)))) console.error(t.report.reportWritten(promPath));
4314
+ }
4315
+
4019
4316
  /*
4020
4317
  A terminal gets a statement a person can read; a pipe gets the receipt.
4021
4318
  The receipt on a terminal was 60 lines of JSON before the first figure a
@@ -4033,6 +4330,23 @@ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages):
4033
4330
  } else if (!statement) {
4034
4331
  console.log(json);
4035
4332
  }
4333
+ /*
4334
+ The send comes after the receipt is written, so a refusal or an error
4335
+ leaves the file (or stdout) as it was, and the same `json` is what goes:
4336
+ the bytes of this run's receipt with the newline `--out` ends on, and no
4337
+ log line, path or prompt, which `sendReceipt` is not given.
4338
+ */
4339
+ if (sendTarget !== null) {
4340
+ const sent = await sendReceipt(sendTarget.url, sendTarget.key, `${json}\n`);
4341
+ const where = sendTarget.url.host;
4342
+ if (sent.ok) {
4343
+ console.error(t.bill.sendDelivered(where, String(sent.status)));
4344
+ } else {
4345
+ console.error(c.yellow(t.bill.sendFailed(where, sent.status === null ? null : String(sent.status))));
4346
+ if (sent.detail !== '') console.error(sent.detail);
4347
+ process.exitCode = BILL_SEND_FAILED;
4348
+ }
4349
+ }
4036
4350
  console.error(t.bill.sources(sources, fileCount));
4037
4351
  printReceiptSummary(document, t);
4038
4352
  const agentSessions = claudeCodeFiles + codexFiles + geminiCliFiles > 0;
@@ -4054,7 +4368,10 @@ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages):
4054
4368
  .filter((row) => row.calls > 0)
4055
4369
  .sort((a, b) => b.usd - a.usd);
4056
4370
  if (statement) {
4057
- printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by);
4371
+ const zoned = zone === undefined ? undefined : zonedSpendByDay(lines, zone, pricing, period);
4372
+ printBillStatement(report, labelledByProject > 0, t, period.words, agentSessions, byAgent.length > 1 ? byAgent : [], by, zone, zoned);
4373
+ } else if (zone !== undefined) {
4374
+ console.error(t.bill.zoneReceiptNote(zone));
4058
4375
  }
4059
4376
  await writeBillSideFiles(args, report, pricing, csvShape, t, period.words, agentSessions);
4060
4377
 
@@ -4080,6 +4397,23 @@ async function billBody(args: Args, pricing: PricingCatalogue, t: CliMessages):
4080
4397
  */
4081
4398
  const priceableAfterSlash = slugged.filter((model) => pricing.byId.has(model.slice(model.lastIndexOf('/') + 1)));
4082
4399
  if (priceableAfterSlash.length > 0) console.error(t.bill.prefixedKnown(priceableAfterSlash.join(', ')));
4400
+
4401
+ /*
4402
+ A Claude model as Bedrock or Vertex names it (#858). The platform sets its
4403
+ own price, so the call stays unpriced; what changes is that the reader is
4404
+ told what the id is, and the model inside when the catalogue knows it.
4405
+ */
4406
+ const partners = document.gaps.flatMap((gap) =>
4407
+ gap.kind === 'unpriced'
4408
+ ? gap.models.flatMap((id) => {
4409
+ const read = partnerModelId(id);
4410
+ if (read === undefined) return [];
4411
+ const known = pricing.byId.get(read.model);
4412
+ return [`${id} (${t.bill.partnerModel(read.platform, known?.id)})`];
4413
+ })
4414
+ : [],
4415
+ );
4416
+ if (partners.length > 0) console.error(t.bill.partnerUnpriced(partners.join('; ')));
4083
4417
  }
4084
4418
 
4085
4419
  /**
@@ -4219,8 +4553,12 @@ function printBillStatement(
4219
4553
  apiEquivalent = false,
4220
4554
  byAgent: { name: string; calls: number; usd: number }[] = [],
4221
4555
  by?: BillPeriodUnit,
4556
+ zone?: string,
4557
+ zoned?: UsageProfileReport['spendByDay'],
4222
4558
  ): void {
4223
4559
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
4560
+ /* The day an instant falls on: UTC, or the zone `--timezone` named (#826). */
4561
+ const dayAt = (ms: number): string => (zone === undefined ? dayOf(ms) : dayInZone(ms, zone));
4224
4562
  const pct = (share: number): string => `${(share * 100).toFixed(1)}%`;
4225
4563
  const total = report.total.totalUsd;
4226
4564
  const LIMIT = 12;
@@ -4281,7 +4619,7 @@ function printBillStatement(
4281
4619
  there are more than a screen holds: a month of days, twelve weeks.
4282
4620
  */
4283
4621
  const unit = by ?? 'month';
4284
- const { periods, undated } = spendByPeriod(report, unit);
4622
+ const { periods, undated } = spendByPeriod(zoned === undefined ? report : { spendByDay: zoned, total: report.total }, unit);
4285
4623
  if (periods.length >= (by === undefined ? 2 : 1)) {
4286
4624
  const keep = unit === 'day' ? 31 : LIMIT;
4287
4625
  const shown: Cell[][] = periods.slice(-keep).map(({ period, calls, usd }) => [period, n(calls), formatUsd(usd), ...shareCells(usd)]);
@@ -4298,13 +4636,16 @@ function printBillStatement(
4298
4636
  }
4299
4637
  const newest = periods[periods.length - 1]!;
4300
4638
  draw.text(unit === 'month' ? t.bill.monthHint(newest.firstDay, newest.lastDay) : t.bill.periodHint(newest.firstDay, newest.lastDay, unit), { tone: 'dim' });
4639
+ if (zone !== undefined) draw.text(t.bill.periodHintZone(zone), { tone: 'dim' });
4301
4640
  }
4302
4641
 
4303
4642
  // What qualifies the total: when the calls fell, and what it is not.
4304
4643
  draw.blank();
4305
4644
  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' });
4645
+ draw.text(t.profile.spanLine(dayAt(report.span.fromMs), dayAt(report.span.toMs), spanDays(report.span.fromMs, report.span.toMs)), { tone: 'dim' });
4307
4646
  }
4647
+ // Which calendar the days above are on, said whenever it is not UTC.
4648
+ if (zone !== undefined) draw.text(t.bill.zoneLine(zone), { tone: 'dim' });
4308
4649
  // The period asked for, as typed: the span above is when the calls in it fell.
4309
4650
  if (window !== undefined) draw.text(t.profile.windowLine(window.since, window.until), { tone: 'dim' });
4310
4651
  /*
@@ -4480,6 +4821,62 @@ async function commandSwitch(args: Args, pricing: PricingCatalogue, t: CliMessag
4480
4821
  );
4481
4822
  }
4482
4823
 
4824
+ /**
4825
+ * `trazum model-pricing` — the contracted rates an organisation already gave
4826
+ * Claude Code in its `modelPricing` managed setting, as a pricing overlay for
4827
+ * `--pricing` (#856). The conversion is `overlayFromClaudeModelPricing` in the
4828
+ * core; this reads the file, writes the overlay, and says on stderr what the
4829
+ * table could not say, model by model.
4830
+ */
4831
+ async function commandModelPricing(args: Args, t: CliMessages): Promise<void> {
4832
+ const file = args.positional[0];
4833
+ if (file === undefined) throw new Error(t.modelPricing.noFile());
4834
+ const reviewed = stringFlag(args, 'reviewed');
4835
+ if (reviewed === undefined) throw new Error(t.modelPricing.noReviewed());
4836
+
4837
+ /*
4838
+ One open file, measured and read through the same handle, as
4839
+ `readUsageLog` does: a stat by name and a read by name could see two
4840
+ different files. At most one byte past the ceiling is read, so a file
4841
+ that grew after the stat is refused rather than read whole.
4842
+ */
4843
+ const handle = await open(file, 'r').catch(() => undefined);
4844
+ if (handle === undefined) throw new Error(t.modelPricing.notFound(file));
4845
+ let raw: string;
4846
+ try {
4847
+ if (!(await handle.stat()).isFile()) throw new Error(t.modelPricing.notFound(file));
4848
+ // A settings file, not a dataset: the same ceiling as an overlay.
4849
+ const buffer = Buffer.alloc(MAX_PRICING_BYTES + 1);
4850
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
4851
+ if (bytesRead > MAX_PRICING_BYTES) throw new Error(t.modelPricing.tooLarge(file, MAX_PRICING_BYTES));
4852
+ raw = buffer.subarray(0, bytesRead).toString('utf8');
4853
+ } finally {
4854
+ await handle.close();
4855
+ }
4856
+ let document: unknown;
4857
+ try {
4858
+ document = JSON.parse(raw);
4859
+ } catch (error) {
4860
+ throw new Error(t.modelPricing.notJson(file, error instanceof Error ? error.message : String(error)));
4861
+ }
4862
+
4863
+ const result = overlayFromClaudeModelPricing(document, { reviewed, source: basename(file) });
4864
+ for (const skipped of result.skipped) console.error(` ${t.modelPricing.skipped(skipped.key, skipped.reason, skipped.detail)}`);
4865
+ const priced = Object.keys(result.overlay.models).length;
4866
+ if (priced === 0) throw new Error(t.modelPricing.empty());
4867
+
4868
+ const text = `${JSON.stringify(result.overlay, null, 2)}\n`;
4869
+ const out = stringFlag(args, 'out') ?? stringFlag(args, 'o');
4870
+ if (out !== undefined) await writeFile(out, text, 'utf8');
4871
+ else process.stdout.write(text);
4872
+
4873
+ console.error(t.modelPricing.summary(result.fromRows.length, result.fromMultiplier.length, result.multiplier));
4874
+ if (result.batchFromRatio.length > 0) console.error(` ${t.modelPricing.batch(result.batchFromRatio.length)}`);
4875
+ if (result.fastKept.length > 0) console.error(` ${t.modelPricing.fastKept(result.fastKept.join(', '))}`);
4876
+ if (result.usOnlyDropped.length > 0) console.error(` ${t.modelPricing.usOnly(result.usOnlyDropped.join(', '))}`);
4877
+ if (out !== undefined) console.error(t.modelPricing.written(out, priced));
4878
+ }
4879
+
4483
4880
  /**
4484
4881
  * `trazum ownrate` — the forty-second: a self-hosted model's $/MTok, derived
4485
4882
  * from the operator's own declared numbers, with the overlay snippet ready to
@@ -5900,6 +6297,16 @@ async function commandGateway(
5900
6297
  * would be the flattering direction.
5901
6298
  */
5902
6299
  let unmeasured = 0;
6300
+ /**
6301
+ * The scrape port, checked before anything listens: a typo here should not
6302
+ * leave a gateway running with no counts behind it.
6303
+ */
6304
+ const metricsRaw = stringFlag(args, 'metrics-port');
6305
+ const metricsPort = metricsRaw === undefined ? null : Number(metricsRaw);
6306
+ if (metricsPort !== null && (!Number.isInteger(metricsPort) || metricsPort < 0 || metricsPort > 65_535)) {
6307
+ throw new Error(t.gateway.badMetricsPort(String(metricsRaw)));
6308
+ }
6309
+ const metrics = metricsPort === null ? null : new GatewayMetrics(provider, Date.now());
5903
6310
  const server = buildGateway({
5904
6311
  liveBudget: true,
5905
6312
  provider,
@@ -5914,6 +6321,7 @@ async function commandGateway(
5914
6321
  standing: () => standing,
5915
6322
  record: (call) => {
5916
6323
  measured.calls += 1;
6324
+ metrics?.measured(call, priceGatewayUsage(pricing, call.model, call, Date.now()));
5917
6325
  console.error(
5918
6326
  c.dim(
5919
6327
  t.gateway.measured(
@@ -5928,11 +6336,13 @@ async function commandGateway(
5928
6336
  },
5929
6337
  unmeasured: (cause) => {
5930
6338
  unmeasured += 1;
6339
+ metrics?.unmeasured(cause);
5931
6340
  console.error(c.yellow(` ${t.gateway.unmeasured(cause, unmeasured)}`));
5932
6341
  },
5933
6342
  note: (line) => {
5934
6343
  console.error(c.yellow(` ${line}`));
5935
6344
  },
6345
+ ...(metrics === null ? {} : { count: (event: GatewayCount) => metrics.count(event) }),
5936
6346
  });
5937
6347
 
5938
6348
  const socket = stringFlag(args, 'socket');
@@ -5945,6 +6355,10 @@ async function commandGateway(
5945
6355
  const where = await listenGateway(server, socket !== undefined ? { socket } : { port });
5946
6356
  console.log(c.bold(t.gateway.listening(where, provider)));
5947
6357
  console.log(` ${c.dim(wrap(t.gateway.pointYourSdk(where), 74, ' '))}`);
6358
+ if (metrics !== null && metricsPort !== null) {
6359
+ const scrape = await listenGateway(buildMetricsServer(metrics), { port: metricsPort });
6360
+ console.log(` ${c.dim(wrap(t.gateway.metrics(scrape), 74, ' '))}`);
6361
+ }
5948
6362
  console.log(` ${c.dim(wrap(t.gateway.credential(), 74, ' '))}`);
5949
6363
  console.log(` ${c.dim(wrap(t.gateway.neverSubstitutes(), 74, ' '))}`);
5950
6364
  console.log(
@@ -7774,6 +8188,25 @@ async function commandCheck(
7774
8188
  // A flag beats the config, as everywhere else. -1 means "not given".
7775
8189
  const flagBudget = numberFlag(args, 'max-tokens', -1, t);
7776
8190
 
8191
+ /*
8192
+ `--base <ref>` (#785): each changed prompt's cost on that commit and
8193
+ here. Its gate needs it, and standard input has no base side; both are
8194
+ refused before anything is read.
8195
+ */
8196
+ const baseRef = stringFlag(args, 'base');
8197
+ const maxIncrease = args.flags.has('max-monthly-increase-usd')
8198
+ ? numberFlag(args, 'max-monthly-increase-usd', 0, t)
8199
+ : null;
8200
+ if (maxIncrease !== null && baseRef === undefined) throw new Error(t.againstBase.gateNeedsBase());
8201
+ const compare = async (
8202
+ kind: 'file' | 'directory' | 'list',
8203
+ on: string,
8204
+ listed?: readonly string[],
8205
+ ): Promise<BaseCostReport | null> =>
8206
+ baseRef === undefined
8207
+ ? null
8208
+ : againstBase(baseRef, kind, on, listed, maxIncrease, config, counter, pricing);
8209
+
7777
8210
  /**
7778
8211
  * `--files-from -` reads a file list from stdin — the shape
7779
8212
  * `git diff --name-only` already produces — so a pre-commit hook is one
@@ -7789,18 +8222,22 @@ async function commandCheck(
7789
8222
  .split('\n')
7790
8223
  .map((line) => line.trim())
7791
8224
  .filter((line) => line !== '');
7792
- await checkDirectory('.', args, flagBudget, config, counter, level, t, locale, pricing, listed);
8225
+ const base = await compare('list', '.', listed);
8226
+ await checkDirectory('.', args, flagBudget, config, counter, level, t, locale, pricing, listed, base);
7793
8227
  return;
7794
8228
  }
7795
8229
 
7796
8230
  const asDirectory = target !== undefined && target !== '-' ? await isDirectory(target) : false;
7797
8231
 
7798
8232
  if (asDirectory) {
7799
- await checkDirectory(target!, args, flagBudget, config, counter, level, t, locale, pricing);
8233
+ const base = await compare('directory', target!);
8234
+ await checkDirectory(target!, args, flagBudget, config, counter, level, t, locale, pricing, undefined, base);
7800
8235
  return;
7801
8236
  }
7802
8237
 
8238
+ if (baseRef !== undefined && (target === undefined || target === '-')) throw new Error(t.againstBase.noStdin());
7803
8239
  const prompt = await readInput(target, t, maxInputFlag(args, t));
8240
+ const base = target === undefined ? null : await compare('file', target);
7804
8241
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
7805
8242
 
7806
8243
  // A single file falls back to the config budget for its own path, so
@@ -7824,6 +8261,7 @@ async function commandCheck(
7824
8261
  t,
7825
8262
  locale,
7826
8263
  pricing,
8264
+ base,
7827
8265
  );
7828
8266
  return;
7829
8267
  }
@@ -7849,6 +8287,7 @@ async function commandCheck(
7849
8287
  tokenSource: counter.source,
7850
8288
  band: bandFor(prompt),
7851
8289
  truncated: false,
8290
+ ...(base === null ? {} : { againstBase: base }),
7852
8291
  t,
7853
8292
  }),
7854
8293
  );
@@ -7864,6 +8303,7 @@ async function commandCheck(
7864
8303
  optimizedTokens: verdict.optimizedTokens,
7865
8304
  wouldFitOptimized:
7866
8305
  verdict.optimizedTokens !== null ? verdict.optimizedTokens <= maxTokens : null,
8306
+ ...(base === null ? {} : { againstBase: base }),
7867
8307
  }),
7868
8308
  );
7869
8309
  } else if (ok) {
@@ -7882,8 +8322,106 @@ async function commandCheck(
7882
8322
  }
7883
8323
  draw.print((line) => console.error(line));
7884
8324
  }
8325
+ if (base !== null && !boolFlag(args, 'json')) printAgainstBase(base, t);
7885
8326
 
7886
8327
  if (!ok) process.exitCode = 1;
8328
+ if (base !== null && baseGateFails(base)) process.exitCode = 1;
8329
+ }
8330
+
8331
+ /**
8332
+ * Reads both sides and prices them: the CLI's half of `check --base` (#785).
8333
+ *
8334
+ * The model is the one `usage.model` names, or Trazum's default, and the
8335
+ * report says which. The volume comes from `volumes` through `labels`, and
8336
+ * from nowhere else.
8337
+ */
8338
+ async function againstBase(
8339
+ ref: string,
8340
+ kind: 'file' | 'directory' | 'list',
8341
+ target: string,
8342
+ listed: readonly string[] | undefined,
8343
+ maxIncreaseUsd: number | null,
8344
+ config: TrazumConfig,
8345
+ counter: Counter,
8346
+ pricing: PricingCatalogue,
8347
+ ): Promise<BaseCostReport> {
8348
+ const read = await readBothSides({
8349
+ ref,
8350
+ target,
8351
+ kind,
8352
+ ...(listed === undefined ? {} : { listed }),
8353
+ extensions: config.extensions ?? [...DEFAULT_EXTENSIONS, ...SOURCE_EXTENSIONS],
8354
+ ignore: config.ignore ?? [],
8355
+ });
8356
+ if (read.status === 'unavailable') {
8357
+ return {
8358
+ status: 'unavailable',
8359
+ ref,
8360
+ why: read.why,
8361
+ gate: maxIncreaseUsd === null ? null : { maxIncreaseUsd },
8362
+ };
8363
+ }
8364
+ const configured = config.usage?.model;
8365
+ return priceAgainstBase({
8366
+ ref,
8367
+ sha: read.sha,
8368
+ pairs: read.pairs,
8369
+ count: (text) => counter.count(text),
8370
+ model: modelFrom(pricing, configured ?? DEFAULT_USAGE.model),
8371
+ modelFrom: configured === undefined ? 'default' : 'config',
8372
+ pricing,
8373
+ volumeOf: (pair) => volumeFor(pair, config.labels ?? {}, config.volumes ?? {}),
8374
+ maxIncreaseUsd,
8375
+ });
8376
+ }
8377
+
8378
+ /** The base comparison in the terminal: the same figures as the Markdown, one prompt a row. */
8379
+ function printAgainstBase(report: BaseCostReport, t: CliMessages): void {
8380
+ const ab = t.againstBase;
8381
+ const n = (value: number): string => value.toLocaleString(t.numberLocale);
8382
+ const draw = new Report();
8383
+ draw.blank();
8384
+ if (report.status === 'unavailable') {
8385
+ draw.note('caution', ab.unavailable(report.why, report.ref));
8386
+ if (report.gate !== null) draw.text(ab.gateUnavailable(formatUsd(report.gate.maxIncreaseUsd)), { tone: 'error' });
8387
+ draw.print();
8388
+ return;
8389
+ }
8390
+ draw.heading(ab.heading(report.ref, report.sha.slice(0, 7)));
8391
+ if (report.gate !== null) {
8392
+ const change = formatSignedUsd(report.totals?.changeUsd ?? 0);
8393
+ const limit = formatUsd(report.gate.maxIncreaseUsd);
8394
+ draw.text(report.gate.breached ? ab.gateBreached(change, limit) : ab.gateWithin(change, limit), {
8395
+ tone: report.gate.breached ? 'error' : 'good',
8396
+ });
8397
+ }
8398
+ if (report.rows.length === 0) draw.text(ab.nothingChanged());
8399
+ for (const row of report.rows) {
8400
+ const tokens = `${row.base === null ? '–' : n(row.base.tokens)} → ${row.head === null ? '–' : n(row.head.tokens)}`;
8401
+ draw.blank();
8402
+ draw.text(row.id, { tone: 'bold' });
8403
+ draw.text(
8404
+ `${ab.columnTokens()}: ${tokens} · ${ab.columnCalls()}: ${row.callsPerMonth === null ? ab.notStated() : n(row.callsPerMonth)}`,
8405
+ { indent: ' ' },
8406
+ );
8407
+ draw.text(
8408
+ `${ab.columnBase()}: ${baseSideText(row.base, t)} · ${ab.columnHead()}: ${baseSideText(row.head, t)} · ${t.markdown.columnChange()}: ${baseChangeText(row, t)}`,
8409
+ { indent: ' ' },
8410
+ );
8411
+ draw.text(basePriceText(row, report.price, t), { indent: ' ', tone: 'dim' });
8412
+ }
8413
+ if (report.totals !== null) {
8414
+ draw.blank().text(
8415
+ ab.totals(formatUsd(report.totals.baseUsd), formatUsd(report.totals.headUsd), formatSignedUsd(report.totals.changeUsd)),
8416
+ );
8417
+ }
8418
+ draw.blank();
8419
+ if (report.gate !== null && report.perCallOnly > 0) draw.text(ab.gateNotJudged(report.perCallOnly), { tone: 'dim' });
8420
+ if (report.perCallOnly > 0) draw.text(ab.perCallNote(report.perCallOnly), { tone: 'dim' });
8421
+ if (report.unchanged > 0) draw.text(ab.unchanged(report.unchanged), { tone: 'dim' });
8422
+ if (report.modelFrom === 'default') draw.text(ab.modelDefault(report.price.displayName), { tone: 'dim' });
8423
+ draw.text(ab.inputOnly(), { tone: 'dim' });
8424
+ draw.print();
7887
8425
  }
7888
8426
 
7889
8427
  async function isDirectory(path: string): Promise<boolean> {
@@ -7929,15 +8467,29 @@ async function writeMarkdown(args: Args, render: () => string): Promise<void> {
7929
8467
  * full disk on a metrics runner must not turn a survey into a failure — the
7930
8468
  * survey is the thing somebody asked for, and the metrics are a copy of it.
7931
8469
  */
7932
- async function writeOtlp(args: Args, build: () => unknown): Promise<void> {
8470
+ /** Writes a text file, reporting and swallowing a failure, as `writeOtlp` does: the bill is what was asked for. */
8471
+ async function writeText(path: string, text: string): Promise<boolean> {
8472
+ try {
8473
+ await writeFile(path, text, 'utf8');
8474
+ return true;
8475
+ } catch (error) {
8476
+ const message = error instanceof Error ? error.message : String(error);
8477
+ console.error(c.yellow(`Could not write ${path}: ${message}`));
8478
+ return false;
8479
+ }
8480
+ }
8481
+
8482
+ async function writeOtlp(args: Args, build: () => unknown): Promise<boolean> {
7933
8483
  const path = stringFlag(args, 'otlp-out');
7934
- if (!path) return;
8484
+ if (!path) return false;
7935
8485
 
7936
8486
  try {
7937
8487
  await writeFile(path, `${JSON.stringify(build(), null, 2)}\n`, 'utf8');
8488
+ return true;
7938
8489
  } catch (error) {
7939
8490
  const message = error instanceof Error ? error.message : String(error);
7940
8491
  console.error(c.yellow(`Could not write ${path}: ${message}`));
8492
+ return false;
7941
8493
  }
7942
8494
  }
7943
8495
 
@@ -7972,6 +8524,7 @@ async function checkEmbedded(
7972
8524
  t: CliMessages,
7973
8525
  locale: Locale,
7974
8526
  pricing: PricingCatalogue,
8527
+ base: BaseCostReport | null = null,
7975
8528
  ): Promise<void> {
7976
8529
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
7977
8530
 
@@ -7998,6 +8551,7 @@ async function checkEmbedded(
7998
8551
  tokenSource: counter.source,
7999
8552
  band,
8000
8553
  truncated: false,
8554
+ ...(base === null ? {} : { againstBase: base }),
8001
8555
  t,
8002
8556
  }),
8003
8557
  );
@@ -8016,12 +8570,13 @@ async function checkEmbedded(
8016
8570
  ok: !isOverBudget(v),
8017
8571
  })),
8018
8572
  declined: extraction.declined,
8573
+ ...(base === null ? {} : { againstBase: base }),
8019
8574
  },
8020
8575
  null,
8021
8576
  2,
8022
8577
  ),
8023
8578
  );
8024
- if (!ok) process.exitCode = 1;
8579
+ if (!ok || (base !== null && baseGateFails(base))) process.exitCode = 1;
8025
8580
  return;
8026
8581
  }
8027
8582
 
@@ -8046,7 +8601,8 @@ async function checkEmbedded(
8046
8601
  }
8047
8602
 
8048
8603
  console.log();
8049
- if (!ok) process.exitCode = 1;
8604
+ if (base !== null) printAgainstBase(base, t);
8605
+ if (!ok || (base !== null && baseGateFails(base))) process.exitCode = 1;
8050
8606
  }
8051
8607
 
8052
8608
  /**
@@ -8099,6 +8655,7 @@ function parseWhen(
8099
8655
  endOfDay: boolean,
8100
8656
  t: CliMessages,
8101
8657
  now: number,
8658
+ zone?: string,
8102
8659
  ): { ms: number | undefined; relative: boolean } {
8103
8660
  const value = stringFlag(args, flag);
8104
8661
  if (value === undefined) return { ms: undefined, relative: false };
@@ -8114,6 +8671,10 @@ function parseWhen(
8114
8671
  if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
8115
8672
  const midnight = Date.parse(`${value}T00:00:00Z`);
8116
8673
  if (Number.isFinite(midnight)) {
8674
+ /* A bare day is a day of the zone asked for, `--timezone`, and of UTC otherwise (#826). */
8675
+ if (zone !== undefined) {
8676
+ return { ms: startOfDayInZone(endOfDay ? nextDay(value) : value, zone), relative: false };
8677
+ }
8117
8678
  return { ms: endOfDay ? midnight + 86_400_000 : midnight, relative: false };
8118
8679
  }
8119
8680
  }
@@ -9503,7 +10064,12 @@ async function commandVerify(
9503
10064
  const raw = texts.map((text) => (text.endsWith('\n') ? text : `${text}\n`)).join('');
9504
10065
  const report = profileUsage(raw, { catalogue: pricing });
9505
10066
 
9506
- const verification = verifyPlan(plan, report, { currentPricingLastReviewed: pricing.lastReviewed });
10067
+ // An edit is checked in the tree as well as in the log: the files it names
10068
+ // are hashed where they are now, and a file that is not there says so.
10069
+ const verification = verifyPlan(plan, report, {
10070
+ currentPricingLastReviewed: pricing.lastReviewed,
10071
+ files: await currentFileDigests(plan),
10072
+ });
9507
10073
  const gate = boolFlag(args, 'gate');
9508
10074
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
9509
10075
 
@@ -9532,6 +10098,17 @@ async function commandVerify(
9532
10098
  if (v.action.kind === 'fix-caching' && v.outcome !== 'cannot-tell') {
9533
10099
  rows.push(t.verify.cacheObserved(formatUsd(Number(v.observed.deltaUsd ?? 0)), v.outcome));
9534
10100
  }
10101
+ if (v.action.kind === 'edit-file' && v.observed.file === 'as-planned-from') {
10102
+ rows.push(t.verify.editNotMade(v.action.detail.edit?.path ?? ''));
10103
+ }
10104
+ if (v.action.kind === 'edit-file' && v.observed.file === 'edited' && v.outcome !== 'cannot-tell') {
10105
+ rows.push(
10106
+ t.verify.editObserved(
10107
+ n(Math.round(Number(v.observed.inputPerCallTokensBefore ?? 0))),
10108
+ n(Math.round(Number(v.observed.inputPerCallTokens ?? 0))),
10109
+ ),
10110
+ );
10111
+ }
9535
10112
  if (v.attribution?.calls !== undefined) {
9536
10113
  rows.push(
9537
10114
  t.verify.attribution(
@@ -11729,11 +12306,21 @@ function reportCacheVerdict(report: UsageProfileReport, t: CliMessages): void {
11729
12306
  */
11730
12307
  async function commandPlan(
11731
12308
  args: Args,
12309
+ config: TrazumConfig,
11732
12310
  pricing: PricingCatalogue,
11733
12311
  t: CliMessages,
11734
12312
  ): Promise<void> {
11735
12313
  const path = args.positional[0];
11736
12314
  if (path === undefined) throw new Error(t.plan.noTarget());
12315
+ /*
12316
+ `--edits` (#796): an edit to each prompt file the configuration maps a
12317
+ label to, made by the deterministic steps and recorded by hash. Refused
12318
+ before the log is read when it cannot do anything, rather than after.
12319
+ */
12320
+ const withEdits = boolFlag(args, 'edits');
12321
+ if (boolFlag(args, 'reorder') && !withEdits) throw new Error(t.plan.reorderNeedsEdits());
12322
+ const labelMap = config.labels ?? {};
12323
+ if (withEdits && Object.keys(labelMap).length === 0) throw new Error(t.plan.editsNeedLabels());
11737
12324
 
11738
12325
  const GZ = LOG_EXTENSIONS.map((ext) => `${ext}.gz`);
11739
12326
  const READABLE = [...LOG_EXTENSIONS, ...GZ];
@@ -11757,13 +12344,47 @@ async function commandPlan(
11757
12344
  if (report.total.calls === 0) throw new Error(t.plan.nothingPriced());
11758
12345
  const levers = billLevers(report, { catalogue: pricing });
11759
12346
  const plan = buildPlan(report, levers, pricing.lastReviewed);
12347
+ let editSkips: EditSkip[] = [];
12348
+ if (withEdits) {
12349
+ const planned = await planEditsFor({
12350
+ report,
12351
+ labels: labelMap,
12352
+ steps: boolFlag(args, 'reorder') ? ['reorder', 'trim'] : ['trim'],
12353
+ disabledRules: config.disable ?? [],
12354
+ pricing,
12355
+ });
12356
+ // Last, because they carry no money to rank by: the edit's figure is the
12357
+ // workload's measured bill, not a saving, and ranking it among savings
12358
+ // would be ranking it by a number it does not have.
12359
+ plan.actions.push(...planned.actions);
12360
+ editSkips = planned.skipped;
12361
+ }
11760
12362
 
12363
+ /*
12364
+ `--min-usd` is a floor on money, and an edit carries none, so it keeps
12365
+ every edit: one dropped for having no projected saving would have been
12366
+ dropped for being honest about it.
12367
+ */
11761
12368
  const minUsd = typeof args.flags.get('min-usd') === 'string' ? numberFlag(args, 'min-usd', 0, t) : 0;
11762
- const actions = plan.actions.filter((a) => (a.savingUsd ?? a.stakeUsd ?? 0) >= minUsd);
12369
+ const kept = (a: PlanAction): boolean => a.kind === 'edit-file' || (a.savingUsd ?? a.stakeUsd ?? 0) >= minUsd;
12370
+ const actions = plan.actions.filter(kept);
11763
12371
  const filtered = plan.actions.length - actions.length;
11764
12372
  const droppedUsd = plan.actions
11765
- .filter((a) => (a.savingUsd ?? a.stakeUsd ?? 0) < minUsd)
12373
+ .filter((a) => !kept(a))
11766
12374
  .reduce((sum, a) => sum + (a.savingUsd ?? a.stakeUsd ?? 0), 0);
12375
+ /** An edit's figure and change, in the order the reader needs them. */
12376
+ const editLines = (action: PlanAction): { money: string; rows: string[] } | null => {
12377
+ const edit = action.detail.edit;
12378
+ const base = action.detail.baseline;
12379
+ if (action.kind !== 'edit-file' || edit === undefined || base === undefined) return null;
12380
+ return {
12381
+ money: t.plan.editMeasured(formatUsd(base.usd), n(base.calls), n(Math.round(base.inputPerCallTokens))),
12382
+ rows: [
12383
+ t.plan.editChange(edit.path, edit.steps.includes('reorder'), n(edit.beforeTokens), n(edit.afterTokens)),
12384
+ t.plan.editCheck(),
12385
+ ],
12386
+ };
12387
+ };
11767
12388
 
11768
12389
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
11769
12390
  /**
@@ -11797,18 +12418,26 @@ async function commandPlan(
11797
12418
  }
11798
12419
  for (const action of actions) {
11799
12420
  const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
12421
+ const edit = editLines(action);
11800
12422
  const money =
11801
- action.savingUsd !== null
11802
- ? t.plan.projected(formatUsd(action.savingUsd))
11803
- : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
12423
+ edit !== null
12424
+ ? edit.money
12425
+ : action.savingUsd !== null
12426
+ ? t.plan.projected(formatUsd(action.savingUsd))
12427
+ : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
11804
12428
  lines.push('');
11805
12429
  lines.push(`### ${t.plan.action(action.kind, name, action.model)} — ${money}`);
12430
+ for (const row of edit?.rows ?? []) lines.push(`- ${row}`);
11806
12431
  if (action.detail.routeTo !== undefined) {
11807
12432
  lines.push(`- ${t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch')}`);
11808
12433
  }
11809
12434
  for (const assumption of action.assumes) lines.push(`- ${t.plan.assume(assumption)}`);
11810
12435
  if (action.check !== null) lines.push(`- ${t.plan.check(action.check)}`);
11811
12436
  }
12437
+ if (editSkips.length > 0) {
12438
+ lines.push('');
12439
+ for (const skip of editSkips) lines.push(`- _${t.plan.editSkipped(skip.why, skip.label, skip.path)}_`);
12440
+ }
11812
12441
  if (filtered > 0) {
11813
12442
  lines.push('');
11814
12443
  lines.push(`_${t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd))}_`);
@@ -11841,10 +12470,13 @@ async function commandPlan(
11841
12470
  if (plan.span === null) draw.text(t.plan.noClock(), { tone: 'dim' });
11842
12471
  for (const action of actions) {
11843
12472
  const name = action.label === UNLABELLED ? t.profile.unlabelled() : action.label;
12473
+ const edit = editLines(action);
11844
12474
  const money =
11845
- action.savingUsd !== null
11846
- ? t.plan.projected(formatUsd(action.savingUsd))
11847
- : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
12475
+ edit !== null
12476
+ ? edit.money
12477
+ : action.savingUsd !== null
12478
+ ? t.plan.projected(formatUsd(action.savingUsd))
12479
+ : t.plan.staked(formatUsd(action.stakeUsd ?? 0));
11848
12480
  draw.blank();
11849
12481
  // The action and its money on one line when the window holds them; the
11850
12482
  // money under the action when it does not, never split from its word.
@@ -11853,6 +12485,7 @@ async function commandPlan(
11853
12485
  if (draw.fits(whole)) draw.line(whole);
11854
12486
  else draw.text(title, { first: ` ${draw.markOf('point')} `, indent: ' ', tone: 'bold' }).text(money, { indent: ' ' });
11855
12487
  // The module's `wrap`, at the widths these lines always had on a pipe.
12488
+ for (const row of edit?.rows ?? []) draw.line(` ${c.dim(wrap(row, 72, ' '))}`);
11856
12489
  if (action.detail.routeTo !== undefined) {
11857
12490
  draw.line(` ${c.dim(wrap(t.plan.routeTo(action.detail.routeTo.displayName, action.kind === 'route+batch'), 1000, ' '))}`);
11858
12491
  }
@@ -11861,6 +12494,8 @@ async function commandPlan(
11861
12494
  }
11862
12495
  if (action.check !== null) draw.line(` ${c.dim(wrap(t.plan.check(action.check), 72, ' '))}`);
11863
12496
  }
12497
+ if (editSkips.length > 0) draw.blank();
12498
+ for (const skip of editSkips) draw.text(t.plan.editSkipped(skip.why, skip.label, skip.path), { tone: 'dim' });
11864
12499
  if (filtered > 0) draw.blank().text(t.plan.filtered(n(filtered), formatUsd(minUsd), formatUsd(droppedUsd)), { tone: 'dim' });
11865
12500
  if (plan.batchExcludedUsd > 0) draw.blank().text(t.plan.batchExcluded(formatUsd(plan.batchExcludedUsd)), { tone: 'dim' });
11866
12501
  draw.blank().text(t.plan.footer(), { tone: 'dim' });
@@ -13116,6 +13751,7 @@ async function checkDirectory(
13116
13751
  locale: Locale,
13117
13752
  pricing: PricingCatalogue,
13118
13753
  only?: readonly string[],
13754
+ base: BaseCostReport | null = null,
13119
13755
  ): Promise<void> {
13120
13756
  const n = (value: number): string => value.toLocaleString(t.numberLocale);
13121
13757
 
@@ -13235,6 +13871,7 @@ async function checkDirectory(
13235
13871
  path: baselineOutcome.path,
13236
13872
  }
13237
13873
  : undefined,
13874
+ ...(base === null ? {} : { againstBase: base }),
13238
13875
  t,
13239
13876
  }),
13240
13877
  );
@@ -13260,12 +13897,14 @@ async function checkDirectory(
13260
13897
  ? v.optimizedTokens <= v.maxTokens
13261
13898
  : null,
13262
13899
  })),
13900
+ ...(base === null ? {} : { againstBase: base }),
13263
13901
  },
13264
13902
  null,
13265
13903
  2,
13266
13904
  ),
13267
13905
  );
13268
13906
  if (failures.length > 0 || declined.length > 0) process.exitCode = 1;
13907
+ if (base !== null && baseGateFails(base)) process.exitCode = 1;
13269
13908
  return;
13270
13909
  }
13271
13910
 
@@ -13355,9 +13994,12 @@ async function checkDirectory(
13355
13994
  t,
13356
13995
  );
13357
13996
  }
13997
+ if (base !== null) printAgainstBase(base, t);
13358
13998
  console.log();
13359
13999
 
13360
14000
  if (bad) process.exitCode = 1;
14001
+ // A fourth verdict about the same run, and as independent as the others.
14002
+ if (base !== null && baseGateFails(base)) process.exitCode = 1;
13361
14003
  }
13362
14004
 
13363
14005
  /** Joins two path fragments for display and glob matching, always with `/`. */
@@ -14358,17 +15000,253 @@ function printRank(
14358
15000
  console.log(`${c.dim(t.rank.recoverableNote())}\n`);
14359
15001
  }
14360
15002
 
14361
- async function main(): Promise<void> {
14362
- const argv = process.argv.slice(2);
14363
- if (argv[0] === 'task') {
14364
- const { runTask } = await import('./task.js');
14365
- await runTask(argv.slice(1));
15003
+ /**
15004
+ * `trazum session-guard`: a Claude Code hook that warns, then stops a session,
15005
+ * at two dollar figures the person sets. The logic is in `session-guard.ts`;
15006
+ * this reads the flags and the machine once and says what happened.
15007
+ *
15008
+ * **It never loads the project's config or a pricing overlay.** `check` is the
15009
+ * hook Claude Code runs before every prompt and tool call, and a
15010
+ * `trazum.config.json` that fails to parse in whatever directory the session
15011
+ * is in must not decide whether a spending limit holds. It prices at the
15012
+ * bundled catalogue, dated, and reads only files already on this machine.
15013
+ */
15014
+ async function commandSessionGuard(args: Args, t: CliMessages): Promise<void> {
15015
+ const action = args.positional[0] ?? 'status';
15016
+ if (!['status', 'install', 'uninstall', 'check'].includes(action)) throw new Error(t.sessionGuard.unknownAction(action));
15017
+ for (const flag of ['pricing', 'pricing-live', 'config']) {
15018
+ if (args.flags.has(flag)) throw new Error(t.sessionGuard.refusedFlag(`--${flag}`));
15019
+ }
15020
+
15021
+ const parsed = parseGuardThresholds({
15022
+ warn: stringFlag(args, 'warn'),
15023
+ stop: stringFlag(args, 'stop'),
15024
+ policy: stringFlag(args, 'on-cannot-tell'),
15025
+ });
15026
+ const refusal = (given: ReturnType<typeof parseGuardThresholds>): string => {
15027
+ if (given.ok) return '';
15028
+ const r = given.refusal;
15029
+ switch (r.code) {
15030
+ case 'missing':
15031
+ return t.sessionGuard.refusedMissing(r.flags.join(', '));
15032
+ case 'notAmount':
15033
+ return t.sessionGuard.refusedAmount(r.flag, r.given);
15034
+ case 'badPolicy':
15035
+ return t.sessionGuard.refusedPolicy(r.given, r.allowed);
15036
+ case 'warnNotBelowStop':
15037
+ return t.sessionGuard.refusedWarnNotBelowStop();
15038
+ }
15039
+ };
15040
+
15041
+ if (action === 'check') {
15042
+ if (!parsed.ok) throw new Error(refusal(parsed));
15043
+ let stdin = '';
15044
+ if (process.stdin.isTTY !== true) {
15045
+ const chunks: Buffer[] = [];
15046
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
15047
+ stdin = Buffer.concat(chunks).toString('utf8');
15048
+ }
15049
+ const result = await checkSessionGuard(stdin, parsed.thresholds, {
15050
+ catalogue: BUNDLED_CATALOGUE,
15051
+ env: process.env,
15052
+ now: new Date(),
15053
+ t,
15054
+ });
15055
+ if (result.stdout !== '') process.stdout.write(`${result.stdout}\n`);
15056
+ if (result.stderr !== '') process.stderr.write(`${result.stderr}\n`);
15057
+ process.exitCode = result.code;
15058
+ return;
15059
+ }
15060
+
15061
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
15062
+ const entry = (() => {
15063
+ try {
15064
+ return realpathSync(process.argv[1] ?? '');
15065
+ } catch {
15066
+ return resolvePath(process.argv[1] ?? '');
15067
+ }
15068
+ })();
15069
+ const ctx: ProactiveCtx = {
15070
+ home,
15071
+ cwd: process.cwd(),
15072
+ platform: process.platform,
15073
+ execPath: process.execPath,
15074
+ entry,
15075
+ trazumBin: process.env.TRAZUM_BIN,
15076
+ // Not used: the guard writes the settings file and the record, never the crontab.
15077
+ crontab: { read: () => ({ kind: 'none' }), write: () => undefined },
15078
+ script: async () => '',
15079
+ catalogue: BUNDLED_CATALOGUE,
15080
+ };
15081
+ const settings = pathsFor(ctx).settings;
15082
+ const file = shownPath(ctx, settings);
15083
+
15084
+ if (action === 'status') {
15085
+ const read = await readJsonObject(ctx, settings, resolvePath(home));
15086
+ if (read.kind === 'refused') {
15087
+ console.log(t.proactive.reason[read.finding.code](read.finding.params));
15088
+ return;
15089
+ }
15090
+ const view = viewGuard(read.kind === 'ok' ? read.value : {});
15091
+ if (view.shape !== null) {
15092
+ console.log(t.sessionGuard.settingsShape(file, view.shape));
15093
+ return;
15094
+ }
15095
+ const state = guardState(view);
15096
+ const first = view.found.UserPromptSubmit ?? view.found.PreToolUse;
15097
+ if (state === 'off' || first === undefined) console.log(t.sessionGuard.statusOff(file));
15098
+ else {
15099
+ const line = t.sessionGuard.statusOn(file, formatUsd(first.warnUsd), formatUsd(first.stopUsd), first.policy);
15100
+ console.log(state === 'partial' ? t.sessionGuard.statusPartial(file) : line);
15101
+ }
15102
+ console.log(c.dim(t.sessionGuard.apiEquivalent()));
15103
+ return;
15104
+ }
15105
+
15106
+ if (action === 'install' && !parsed.ok) throw new Error(refusal(parsed));
15107
+ const plan = await planGuard(ctx, action as 'install' | 'uninstall', parsed.ok ? parsed.thresholds : null, t);
15108
+ if (plan.kind !== 'plan') {
15109
+ console[plan.kind === 'refused' ? 'error' : 'log'](plan.message);
15110
+ if (plan.kind === 'refused') process.exitCode = 1;
14366
15111
  return;
14367
15112
  }
14368
- // The stdin display filter has its own small grammar and no project config.
14369
- if (argv[0] === 'filter') {
14370
- const { runFilter } = await import('./filter.js');
14371
- await runFilter(argv.slice(1));
15113
+
15114
+ const yes = boolFlag(args, 'yes');
15115
+ const terminal = process.stdin.isTTY === true;
15116
+ const dryRun = boolFlag(args, 'dry-run') || (!yes && !terminal);
15117
+ const header = action === 'install' ? t.sessionGuard.wouldInstall() : t.sessionGuard.wouldUninstall();
15118
+ const show = (): void => {
15119
+ console.log(header);
15120
+ for (const change of plan.changes) {
15121
+ console.log(` ${shownPath(ctx, change.target)}`);
15122
+ for (const line of change.removed) console.log(` ${c.red(`- ${line}`)}`);
15123
+ for (const line of change.added) console.log(` ${c.green(`+ ${line}`)}`);
15124
+ }
15125
+ };
15126
+ if (dryRun) {
15127
+ show();
15128
+ console.log(!boolFlag(args, 'dry-run') ? t.sessionGuard.dryRunNoTerminal() : t.sessionGuard.dryRun());
15129
+ return;
15130
+ }
15131
+ if (!yes) {
15132
+ show();
15133
+ const reader = createInterface({ input: process.stdin, output: process.stderr });
15134
+ const answer = await reader
15135
+ .question(action === 'install' ? t.sessionGuard.askInstall(file) : t.sessionGuard.askUninstall(file))
15136
+ .finally(() => reader.close());
15137
+ if (!/^(y|yes|s|si|sí)$/i.test(answer.trim())) {
15138
+ console.log(t.sessionGuard.declined());
15139
+ return;
15140
+ }
15141
+ }
15142
+ try {
15143
+ await applyGuardPlan(ctx, plan, action as 'install' | 'uninstall');
15144
+ } catch (error) {
15145
+ if (!(error instanceof GuardWriteFailed)) throw error;
15146
+ console.error(t.sessionGuard.failed(t.proactive.reason[error.finding.code](error.finding.params)));
15147
+ process.exitCode = 1;
15148
+ return;
15149
+ }
15150
+ console.log(action === 'install' ? t.sessionGuard.didInstall(file) : t.sessionGuard.didUninstall(file));
15151
+ if (action === 'install') console.log(c.dim(t.sessionGuard.apiEquivalent()));
15152
+ }
15153
+
15154
+ /**
15155
+ * `trazum waste <transcript.jsonl>`: what a coding-agent session paid for twice,
15156
+ * or for nothing, priced at the bundled catalogue from the session's own counts.
15157
+ *
15158
+ * It recommends and changes nothing: no file is written, edited or opened for
15159
+ * writing. It reads the transcript and its subagents' transcripts, and the
15160
+ * *size* of one CLAUDE.md. Like `session-guard` it never loads the project's
15161
+ * config or a pricing overlay, so every figure is the bundled, dated catalogue's.
15162
+ */
15163
+ async function commandWaste(args: Args, t: CliMessages): Promise<void> {
15164
+ for (const flag of ['pricing', 'pricing-live', 'config']) {
15165
+ if (args.flags.has(flag)) throw new Error(t.waste.refusedFlag(`--${flag}`));
15166
+ }
15167
+ const target = args.positional[0];
15168
+ if (target === undefined) throw new Error(t.waste.noPath());
15169
+ const rawMin = stringFlag(args, 'min-reads');
15170
+ const minReads = rawMin === undefined ? 3 : Number(rawMin);
15171
+ if (!Number.isInteger(minReads) || minReads < 2) throw new Error(t.waste.minReadsBad(rawMin ?? ''));
15172
+
15173
+ const session = await readSession(resolvePath(target));
15174
+ if (!session.ok) throw new Error(session.cause === 'not-found' ? t.waste.notFound(target) : t.waste.unreadable(target));
15175
+
15176
+ const explicit = stringFlag(args, 'claude-md');
15177
+ const cwd = sessionCwd(session.texts[0] ?? '');
15178
+ const claudePath = explicit ?? (cwd === undefined ? undefined : join(cwd, 'CLAUDE.md'));
15179
+ const size = claudePath === undefined ? null : await sizeOf(claudePath);
15180
+ const servers = (stringFlag(args, 'mcp-servers') ?? '')
15181
+ .split(',')
15182
+ .map((name) => name.trim())
15183
+ .filter((name) => name !== '');
15184
+
15185
+ const report = analyzeSessionWaste(session.texts, {
15186
+ catalogue: BUNDLED_CATALOGUE,
15187
+ on: new Date(),
15188
+ minReads,
15189
+ mcpServers: servers,
15190
+ ...(size === null ? {} : { claudeMd: [size] }),
15191
+ });
15192
+
15193
+ if (boolFlag(args, 'json')) {
15194
+ console.log(JSON.stringify(report, null, 2));
15195
+ return;
15196
+ }
15197
+ if (report.cannotTell !== null) {
15198
+ console.log(t.waste.cannotTell());
15199
+ return;
15200
+ }
15201
+
15202
+ const w = t.waste;
15203
+ console.log(c.bold(w.heading(report.session.calls, report.session.threads)));
15204
+ console.log(c.dim(w.apiEquivalent(report.pricing.lastReviewed)));
15205
+ if (report.unpricedModels.length > 0) console.log(c.dim(w.unpriced(report.unpricedModels.join(', '))));
15206
+
15207
+ console.log(`\n${c.bold(w.readsHeading())}`);
15208
+ if (report.reads.findings.length === 0) console.log(w.readsNone(report.reads.minReads));
15209
+ for (const row of report.reads.findings) {
15210
+ console.log(` ${row.path}`);
15211
+ console.log(` ${w.readLine(row.reads, row.repeats, row.measured, row.tokens, row.usd === null ? null : formatUsd(row.usd))}`);
15212
+ }
15213
+ if (report.reads.omitted > 0) console.log(c.dim(w.readsOmitted(report.reads.omitted)));
15214
+ if (report.reads.usd !== null) console.log(w.readsTotal(formatUsd(report.reads.usd), report.reads.measured, report.reads.repeats));
15215
+ else if (report.reads.repeats > 0) console.log(w.readsUnmeasured(report.reads.repeats));
15216
+
15217
+ console.log(`\n${c.bold(w.mcpHeading())}`);
15218
+ if (report.mcp.source === 'none') console.log(w.mcpNoList());
15219
+ else {
15220
+ console.log(report.mcp.unused.length === 0 ? w.mcpAllCalled(report.mcp.loaded) : w.mcpSummary(report.mcp.loaded, report.mcp.called, report.mcp.source));
15221
+ for (const server of report.mcp.unused) console.log(` ${w.mcpUnused(server.server, server.tools)}`);
15222
+ if (report.mcp.unused.length > 0) console.log(c.dim(w.mcpNotPriced()));
15223
+ }
15224
+
15225
+ console.log(`\n${c.bold(w.claudeHeading())}`);
15226
+ if (report.claudeMd.findings.length === 0) console.log(w.claudeNone(claudePath ?? ''));
15227
+ for (const f of report.claudeMd.findings) {
15228
+ console.log(` ${f.path}`);
15229
+ console.log(` ${w.claudeLine(f.bytes, f.tokens, f.calls, formatUsd(f.usd), formatUsd(f.usdLow), formatUsd(f.usdHigh), report.claudeMd.bandPct)}`);
15230
+ }
15231
+
15232
+ console.log(`\n${c.dim(w.nothingChanged())}`);
15233
+ }
15234
+
15235
+ async function main(): Promise<void> {
15236
+ const argv = process.argv.slice(2);
15237
+ // `task` and the stdin display filter have grammars of their own and no
15238
+ // project config. They still speak the reader's language: `--locale` is
15239
+ // read and taken out before their parsers see it, which refused it (#871).
15240
+ if (argv[0] === 'task' || argv[0] === 'filter') {
15241
+ const messages = getCliMessages(localeFromArgv(argv)).taskFilter;
15242
+ const own = withoutLocale(argv.slice(1));
15243
+ if (argv[0] === 'task') {
15244
+ const { runTask } = await import('./task.js');
15245
+ await runTask(own, messages);
15246
+ } else {
15247
+ const { runFilter } = await import('./filter.js');
15248
+ await runFilter(own, messages);
15249
+ }
14372
15250
  return;
14373
15251
  }
14374
15252
  let locale = localeFromArgv(argv);
@@ -14410,25 +15288,35 @@ async function main(): Promise<void> {
14410
15288
  }
14411
15289
 
14412
15290
  if (boolFlag(args, 'help') || boolFlag(args, 'h') || !args.command) {
14413
- console.log(
14414
- t.help(
14415
- {
14416
- model: DEFAULT_USAGE.model,
14417
- callsPerMonth: DEFAULT_USAGE.callsPerMonth,
14418
- avgOutputTokens: DEFAULT_USAGE.avgOutputTokens,
14419
- cacheHitRate: DEFAULT_USAGE.cacheHitRate,
14420
- locales: LOCALES,
14421
- contracts: CONTRACT_NAMES,
14422
- },
14423
- c.bold,
14424
- ),
14425
- );
15291
+ const defaults = {
15292
+ model: DEFAULT_USAGE.model,
15293
+ callsPerMonth: DEFAULT_USAGE.callsPerMonth,
15294
+ avgOutputTokens: DEFAULT_USAGE.avgOutputTokens,
15295
+ cacheHitRate: DEFAULT_USAGE.cacheHitRate,
15296
+ locales: LOCALES,
15297
+ contracts: CONTRACT_NAMES,
15298
+ };
15299
+ const full = t.help(defaults, c.bold);
15300
+ // `trazum <command> --help` is that command's part of the help (#865); the whole help is `trazum --help`.
15301
+ const own = args.command ? commandHelp(full, t.help(defaults, (s) => s), args.command, t.commandHelpMore) : undefined;
15302
+ console.log(own ?? full);
14426
15303
  return;
14427
15304
  }
14428
15305
 
14429
15306
  rejectUnknownFlags(args, t);
14430
15307
  rejectExtraPositionals(args, t);
14431
15308
 
15309
+ // Before the config loads, for the reason `commandSessionGuard` gives.
15310
+ if (args.command === 'session-guard') {
15311
+ await commandSessionGuard(args, t);
15312
+ return;
15313
+ }
15314
+ // The same for `waste`: it prices at the bundled catalogue and reads a transcript, not a project's config.
15315
+ if (args.command === 'waste') {
15316
+ await commandWaste(args, t);
15317
+ return;
15318
+ }
15319
+
14432
15320
  // Loaded before dispatch so every command sees the same settings, and after
14433
15321
  // flag validation so a typo is reported before any file is touched. An
14434
15322
  // invalid config throws here rather than quietly reverting to defaults —
@@ -14499,7 +15387,7 @@ async function main(): Promise<void> {
14499
15387
  await commandProfile(args, config, configDir, pricing, t);
14500
15388
  break;
14501
15389
  case 'plan':
14502
- await commandPlan(args, pricing, t);
15390
+ await commandPlan(args, config, pricing, t);
14503
15391
  break;
14504
15392
  case 'verify':
14505
15393
  await commandVerify(args, pricing, t);
@@ -14621,6 +15509,9 @@ async function main(): Promise<void> {
14621
15509
  case 'ownrate':
14622
15510
  commandOwnrate(args, t);
14623
15511
  break;
15512
+ case 'model-pricing':
15513
+ await commandModelPricing(args, t);
15514
+ break;
14624
15515
  case 'pulse':
14625
15516
  await commandPulse(args, t);
14626
15517
  break;
@@ -14695,9 +15586,12 @@ function filesystemRefusal(error: unknown, t: CliMessages): string | null {
14695
15586
  }
14696
15587
 
14697
15588
  main().catch((error: unknown) => {
14698
- const t = getCliMessages(localeFromArgv(process.argv.slice(2)));
14699
- const message =
14700
- filesystemRefusal(error, t) ?? (error instanceof Error ? error.message : String(error));
15589
+ const argv = process.argv.slice(2);
15590
+ const t = getCliMessages(localeFromArgv(argv));
15591
+ const raised = error instanceof Error ? error.message : String(error);
15592
+ // `task`, `filter` and the core's task analysis raise in English (#871).
15593
+ const own = argv[0] === 'task' || argv[0] === 'filter' ? t.taskFilter.say(raised) : raised;
15594
+ const message = filesystemRefusal(error, t) ?? own;
14701
15595
  console.error(`\n${c.red(t.errors.errorLabel())}: ${message}\n`);
14702
15596
  process.exitCode = 1;
14703
15597
  });