@sejuneoh/aitop 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,7 @@ aitop --json print a snapshot as JSON and exit
33
33
  aitop --doctor check which tools and logs aitop can see
34
34
  aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
35
35
  aitop --report daily daily cost table and exit
36
+ aitop --report monthly monthly cost table (last 12 months) and exit
36
37
  aitop --help all options
37
38
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
38
39
  ```
@@ -50,6 +51,12 @@ aitop --report daily --by model --days 14
50
51
  aitop --report daily --by project --days 7
51
52
  ```
52
53
 
54
+ `aitop --report monthly [--by tool|model|project] [--months N] [--json]` prints the same per month, newest first, for up to 12 months. Past days are folded into `monthly.json` in the cache folder (`~/.cache/aitop`, outside the versioned cache) about two days later, so monthly totals survive cache rebuilds and Claude Code deleting old transcripts. The first run reads up to a year of remaining logs once. `*` marks this month, `~` a month only partly counted (for example before the oldest remaining Claude log), and `no data` a month with neither logs nor archive (unknown, not zero). The archive keeps token counts per type, so costs are recomputed when the price table changes. In `--json`, rows have `month`, `current` and `status` (`complete`, `partial` or `missing`).
55
+
56
+ ```
57
+ aitop --report monthly --by model --months 6
58
+ ```
59
+
53
60
  ### tmux status line
54
61
 
55
62
  `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of sessions waiting for you (`wait 2`, Claude Code counted live), the number of sessions running (`run 3`), and spend over the last hour. Items that are 0 are left out, and `--line-width N` (default 40) drops items from the end. It reads only aitop's cache, so it is fast once `aitop` has run before; with no cache yet it prints `...` after about 1.5 seconds. The running count (and waiting Antigravity sessions) come from a small summary that the live screen, `--once` and `--json` write to the cache; when no summary is newer than 60 seconds, `run` is left out rather than shown wrong. `--line=tmux` adds tmux colors, `NO_COLOR` turns them off.
package/bin/aitop.mjs CHANGED
@@ -41,7 +41,7 @@ if (line.error) {
41
41
  process.stderr.write(`aitop: ${line.error}\n`);
42
42
  process.exit(2);
43
43
  }
44
- // --report daily, --by tool|model|project, --days <N> 은 reportOption 이 꺼낸다.
44
+ // --report daily|monthly, --by tool|model|project, --days <N>, --months <N> 은 reportOption 이 꺼낸다.
45
45
  const report = reportOption(line.rest);
46
46
  if (report.error) {
47
47
  process.stderr.write(`aitop: ${report.error}\n`);
@@ -147,22 +147,26 @@ if (line.mode) {
147
147
  }
148
148
 
149
149
  // --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
150
- // 처음 실행은 30일치 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
150
+ // --report monthly 는 월별 보관함(monthly.mjs)과 장부를 합친다.
151
+ // 처음 실행은 30일치(monthly 는 1년치) 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
151
152
  if (report.kind) {
152
- const { buildReport, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
153
+ const { buildMonthly, buildReport, collectMonthly, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS, MAX_MONTHS } = await import('../src/report.mjs');
153
154
  const { flushCache } = await import('../src/cache.mjs');
154
- if (report.capped) process.stderr.write(`aitop: ${t('report.capped', { n: MAX_DAYS })}\n`);
155
+ const monthly = report.kind === 'monthly';
156
+ if (report.capped) process.stderr.write(`aitop: ${monthly ? t('report.cappedMonths', { n: MAX_MONTHS }) : t('report.capped', { n: MAX_DAYS })}\n`);
155
157
  const progress = progressWriter();
156
158
  const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
157
159
  const now = Date.now();
158
- const got = await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
160
+ // monthly: 보관함(monthly.json)과 장부를 합친다. 처음이면 1년치 기록을 한 번 읽어 보관함을 채운다.
161
+ const got = monthly ? await collectMonthly({ maxMs, now, onProgress: progress.update }) : await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
159
162
  progress.done();
160
163
  flushCache();
161
164
  if (got.partial && args.has('--json')) process.stderr.write(`aitop: ${t('report.partial')}\n`);
162
165
  // --by project 표는 터미널 폭(터미널이 아니면 COLUMNS 를 export 한 경우에만 그 폭, 아니면 열 8개)에 맞춰 열을 줄이고 나머지를 하나로 합친다 (--json 은 다 낸다).
163
166
  const fit = report.by === 'project' && !args.has('--json');
164
167
  const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
165
- let r = buildReport(got.books, { by: report.by, days: report.days, now, maxColumns: fit && !cols ? PIPE_COLUMNS : Infinity });
168
+ const maxColumns = fit && !cols ? PIPE_COLUMNS : Infinity;
169
+ let r = monthly ? buildMonthly(got.books, got.archive, { by: report.by, months: report.months, now, viewLo: got.viewLo, liveLo: got.liveLo, partial: got.partial, maxColumns }) : buildReport(got.books, { by: report.by, days: report.days, now, maxColumns });
166
170
  if (fit && cols) r = fitReport(r, cols);
167
171
  const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
168
172
  process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cache.mjs CHANGED
@@ -9,6 +9,7 @@ import { debug, debugIo } from './log.mjs';
9
9
 
10
10
  // 캐시 형식이 바뀌면 VERSION 을, 가격표가 바뀌면 PRICE_TAG 가 폴더 이름을 바꿔서 예전 캐시를 버린다.
11
11
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
12
+ // 장부(ledger)만 형식이 바뀔 때는 VERSION 대신 장부의 kind 이름을 바꿔 장부만 다시 센다 (세션 화면 캐시는 그대로).
12
13
  const VERSION = 14;
13
14
  const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
14
15
  export const CACHE_ROOT = ROOT;
@@ -26,7 +27,8 @@ function removeOldDirs() {
26
27
  try {
27
28
  for (const d of readdirSync(ROOT)) {
28
29
  // summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
29
- if (d === NAME || d === 'summary.json') continue;
30
+ // monthly.json(월별 보관함, monthly.mjs)과 깨져서 옆으로 옮긴 monthly.json.bad-* 도 사용자 기록이라 지우지 않는다.
31
+ if (d === NAME || d === 'summary.json' || d === 'monthly.json' || d.startsWith('monthly.json.bad-')) continue;
30
32
  const p = join(ROOT, d);
31
33
  // 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
32
34
  const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
package/src/i18n.mjs CHANGED
@@ -69,6 +69,8 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
69
69
  aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
70
70
  도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
71
71
  프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
72
+ aitop --report monthly [--by tool|model|project] [--months N] [--json] 최근 N달(기본·최대 12)의 달별 표. 지난 날은 캐시 폴더의
73
+ monthly.json 에 달별로 남겨 기록이 지워져도 남는다. 처음 실행은 1년치 기록을 한 번 읽는다. * 이번 달, ~ 일부만 센 달
72
74
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
73
75
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
74
76
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
@@ -111,6 +113,9 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
111
113
  aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
112
114
  (default and max 30) by tool, model or project, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
113
115
  A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
116
+ aitop --report monthly [--by tool|model|project] [--months N] [--json] the same per month for the last N months (default and max 12).
117
+ Past days are kept per month in monthly.json in the cache folder, so they survive log cleanup. The first run reads up to a year of logs once.
118
+ * marks this month, ~ a month only partly counted
114
119
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
115
120
  aitop --bell ring the terminal bell when a session starts waiting for you
116
121
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
@@ -195,13 +200,17 @@ export const STRINGS = {
195
200
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
196
201
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
197
202
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
198
- 'opt.reportMissing': '--report 값이 없습니다 (daily)',
199
- 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
203
+ 'opt.reportMissing': '--report 값이 없습니다 (daily 또는 monthly)',
204
+ 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily 또는 monthly)',
200
205
  'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
201
206
  'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
202
207
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
203
208
  'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
204
- 'opt.reportOnly': '--by, --days 는 --report 와 함께 쓴다',
209
+ 'opt.monthsMissing': '--months 값이 없습니다 (달 수)',
210
+ 'opt.monthsBad': '--months 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
211
+ 'opt.daysDaily': '--days 는 --report daily 와 함께 쓴다 (monthly 는 --months)',
212
+ 'opt.monthsMonthly': '--months 는 --report monthly 와 함께 쓴다 (daily 는 --days)',
213
+ 'opt.reportOnly': '--by, --days, --months 는 --report 와 함께 쓴다',
205
214
 
206
215
  // 기간 리포트 (--report daily). 도구·모델 이름은 번역하지 않는다.
207
216
  'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
@@ -217,6 +226,13 @@ export const STRINGS = {
217
226
  'report.partial': '시간 상한 안에 기록을 다 읽지 못해 일부만 셌습니다. 다시 실행하면 이어 읽습니다',
218
227
  'report.progress': '사용량 장부 읽는 중 {pct}% ({s}초)',
219
228
  'report.capped': '--days 는 장부가 남기는 {n}일까지만 볼 수 있어 {n}일로 줄입니다',
229
+ 'report.cappedMonths': '--months 는 보관함이 남기는 {n}달까지만 볼 수 있어 {n}달로 줄입니다',
230
+ 'report.titleMonthly': '달별 사용량 · 최근 {n}달 ({from} ~ {to}) · {by} · API 정가 환산',
231
+ 'report.month': '달',
232
+ 'report.missing': '기록 없음',
233
+ 'report.noteCurrent': '* 이번 달 (아직 진행 중)',
234
+ 'report.notePartial': '~ 일부 날만 셌습니다 (그 전 기록이 지워졌거나 보관함이 비어 있던 때)',
235
+ 'report.noteMissing': '기록 없음: 남은 기록도 보관함도 없는 달입니다 (0 이 아니라 모름)',
220
236
 
221
237
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
222
238
  'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
@@ -541,13 +557,17 @@ export const STRINGS = {
541
557
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
542
558
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
543
559
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
544
- 'opt.reportMissing': '--report needs a value (daily)',
545
- 'opt.reportBad': 'bad --report value {value} (daily)',
560
+ 'opt.reportMissing': '--report needs a value (daily or monthly)',
561
+ 'opt.reportBad': 'bad --report value {value} (daily or monthly)',
546
562
  'opt.byMissing': '--by needs a value (tool, model or project)',
547
563
  'opt.byBad': 'bad --by value {value} (tool, model or project)',
548
564
  'opt.daysMissing': '--days needs a value (number of days)',
549
565
  'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
550
- 'opt.reportOnly': '--by and --days only work with --report',
566
+ 'opt.monthsMissing': '--months needs a value (number of months)',
567
+ 'opt.monthsBad': 'bad --months value {value} (a whole number above 0)',
568
+ 'opt.daysDaily': '--days only works with --report daily (use --months for monthly)',
569
+ 'opt.monthsMonthly': '--months only works with --report monthly (use --days for daily)',
570
+ 'opt.reportOnly': '--by, --days and --months only work with --report',
551
571
 
552
572
  'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
553
573
  'report.by.tool': 'by tool',
@@ -562,6 +582,13 @@ export const STRINGS = {
562
582
  'report.partial': 'Could not read all logs within the time limit, so this is partial. Run again to continue',
563
583
  'report.progress': 'Reading usage logs {pct}% ({s}s)',
564
584
  'report.capped': '--days is limited to the {n} days the ledger keeps, using {n}',
585
+ 'report.cappedMonths': '--months is limited to the {n} months the archive keeps, using {n}',
586
+ 'report.titleMonthly': 'Monthly usage, last {n} months ({from} to {to}), {by}, API list price',
587
+ 'report.month': 'Month',
588
+ 'report.missing': 'no data',
589
+ 'report.noteCurrent': '* this month (still in progress)',
590
+ 'report.notePartial': '~ only some days were counted (older logs were deleted or the archive was empty then)',
591
+ 'report.noteMissing': 'no data: neither logs nor the archive cover this month (unknown, not zero)',
565
592
 
566
593
  'cfg.notFile': 'config file is not a regular file, not reading it',
567
594
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
@@ -0,0 +1,273 @@
1
+ // 월별 보관함 (--report monthly, #164). 장부(캐시)는 버전·가격표가 바뀌면 통째로 버려지고, 원본 기록도 도구가 오래되면 지운다.
2
+ // 그래서 지난 날의 합계를 캐시 루트의 monthly.json 에 달(YYYY-MM)별로 접어 12개월 남긴다 (버전 폴더 밖, summary.json 과 같은 자리).
3
+ //
4
+ // 한 번만 세기: since~through 의 날은 모두 보관함에 접혀 있다. 리포트는 through 까지는 보관함에서, through 다음 날부터는
5
+ // 살아 있는 장부에서 센다. 장부를 처음부터 다시 세도(버전·가격 변경) through 이전 날은 보관함 값만 쓰므로 두 번 더해지지 않는다.
6
+ // 접을 때는 [lo, hi] 를 빠짐없이 읽은 장부만 받고, 이미 [since, through] 에 든 날은 건너뛴다.
7
+ // 새 범위가 [since, through] 와 이어지지 않으면(사이가 빈다) 접지 않는다 (1년치를 다시 읽은 때만 빈 날을 holes 에 적고 접는다).
8
+ // from: 이 날부터는 빠짐없이 셌다 (그 앞은 기록이 지워졌을 수 있어 '일부' 로 보인다). holes 의 날도 '일부' 다.
9
+ //
10
+ // 여러 aitop 이 함께 써도 파일 하나에는 늘 "since~through 의 합" 만 들어 있다: 쓰기 전에 다시 읽어 rev 가 바뀌었으면 쓰지 않고
11
+ // (다음 기회에 다시 접는다), pid 별 임시 파일에 쓴 뒤 rename 한다.
12
+ //
13
+ // 값마다 사용량 벡터(입력·출력·캐시 읽기·캐시 쓰기 5분·1시간, fast 모드는 따로)를 남겨, 가격표가 바뀌면 지금 가격으로 다시 계산한다.
14
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
15
+ import { dirname, join } from 'node:path';
16
+ import { CACHE_ROOT } from './cache.mjs';
17
+ import { PRICE_TAG, vecCost } from './pricing.mjs';
18
+ import { dayKey } from './sources/common.mjs';
19
+ import { debug, debugIo } from './log.mjs';
20
+
21
+ export const V = 1;
22
+ export const ARCHIVE_FILE = join(CACHE_ROOT, 'monthly.json');
23
+ // 남기는 달 수 (이번 달 포함).
24
+ export const KEEP_MONTHS = 12;
25
+ // 갱신이 실패한 agy 기록 때문에 접기가 이만큼 넘게 밀리면, 그 기록을 빼고 접고 그 날들을 '일부' 로 적는다.
26
+ export const STALE_MAX_DAYS = 7;
27
+ // 오늘·어제는 아직 늦게 쓰이는 줄(자정을 넘긴 응답, agy 의 늦은 기록)이 있을 수 있어 그제까지만 접는다.
28
+ export const LAG_DAYS = 2;
29
+
30
+ const DAY = /^\d{4}-\d\d-\d\d$/;
31
+ const MONTH = /^\d{4}-\d\d$/;
32
+
33
+ // 날짜 키 산술 (로컬 정오 기준이라 서머타임에도 하루씩 움직인다).
34
+ const atNoon = (key) => {
35
+ const [y, m, d] = key.split('-').map(Number);
36
+ return new Date(y, m - 1, d, 12);
37
+ };
38
+ export const addDays = (key, n) => {
39
+ const d = atNoon(key);
40
+ d.setDate(d.getDate() + n);
41
+ return dayKey(d.getTime());
42
+ };
43
+ export const monthOf = (key) => key.slice(0, 7);
44
+
45
+ // 이번 달부터 거꾸로 n 달 (YYYY-MM).
46
+ export function lastMonths(n, now = Date.now()) {
47
+ const d = new Date(now);
48
+ const out = [];
49
+ for (let i = 0; i < n; i++) {
50
+ const x = new Date(d.getFullYear(), d.getMonth() - i, 1, 12);
51
+ out.push(dayKey(x.getTime()).slice(0, 7));
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // 보관함이 남기는 가장 오래된 날 (12개월 전 달의 1일).
57
+ export const keepFrom = (now = Date.now()) => `${lastMonths(KEEP_MONTHS, now).at(-1)}-01`;
58
+ // 접을 수 있는 가장 최근 날.
59
+ export const foldHi = (now = Date.now()) => dayKey(now - LAG_DAYS * 86400_000);
60
+ // 그 달의 마지막 날.
61
+ export const monthEnd = (month) => {
62
+ const [y, m] = month.split('-').map(Number);
63
+ return dayKey(new Date(y, m, 0, 12).getTime());
64
+ };
65
+
66
+ export const emptyArchive = () => ({ v: V, rev: 0, price: PRICE_TAG, since: null, from: null, through: null, backfilled: null, holes: [], months: {} });
67
+
68
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
69
+ const isVec = (x) => Array.isArray(x) && x.every(isNum);
70
+ const validEntry = (e) => e && typeof e.t === 'string' && typeof e.m === 'string' && (e.p == null || typeof e.p === 'string') && isNum(e.n) && isNum(e.c) && (e.u == null || isVec(e.u)) && (e.f == null || isVec(e.f));
71
+ function valid(a) {
72
+ if (!a || typeof a !== 'object' || !Number.isInteger(a.rev)) return false;
73
+ for (const k of ['since', 'from', 'through', 'backfilled']) if (a[k] != null && !(typeof a[k] === 'string' && DAY.test(a[k]))) return false;
74
+ if ((a.since == null) !== (a.through == null) || (a.from == null) !== (a.through == null)) return false;
75
+ // holes: [첫날, 끝날] 또는 [첫날, 끝날, 빠진 도구]. 남는 칸은 무시한다.
76
+ if (!Array.isArray(a.holes) || !a.holes.every((h) => Array.isArray(h) && h.length >= 2 && DAY.test(h[0]) && DAY.test(h[1]))) return false;
77
+ if (!a.months || typeof a.months !== 'object') return false;
78
+ return Object.entries(a.months).every(([k, list]) => MONTH.test(k) && Array.isArray(list) && list.every(validEntry));
79
+ }
80
+
81
+ // 가격표가 바뀌었으면 벡터로 지금 가격을 다시 매긴다. 가격표에서 모델이 사라졌으면 예전 비용을 그대로 둔다.
82
+ function reprice(a) {
83
+ if (a.price === PRICE_TAG) return a;
84
+ for (const [month, list] of Object.entries(a.months)) {
85
+ const at = Date.parse(`${month}-15T12:00:00Z`);
86
+ for (const e of list) {
87
+ if (!e.u && !e.f) continue;
88
+ const c = vecCost(e.t, e.m, e.u, e.f, at);
89
+ if (c == null) continue;
90
+ e.c = c;
91
+ delete e.x;
92
+ }
93
+ }
94
+ a.price = PRICE_TAG;
95
+ return a;
96
+ }
97
+
98
+ // { archive, state }. state: ok, missing(없음), corrupt(깨짐, 옆으로 옮기고 빈 보관함), newer(더 새 형식: 읽지도 쓰지도 않는다, archive null).
99
+ export function readArchive(file = ARCHIVE_FILE) {
100
+ let raw;
101
+ try {
102
+ raw = readFileSync(file, 'utf8');
103
+ } catch (e) {
104
+ if (e.code !== 'ENOENT') debugIo('monthly', 'archive read failed', e);
105
+ return { archive: emptyArchive(), state: 'missing' };
106
+ }
107
+ let a = null;
108
+ try {
109
+ a = JSON.parse(raw);
110
+ } catch {}
111
+ if (a && Number.isInteger(a.v) && a.v > V) return { archive: null, state: 'newer' };
112
+ if (a?.v === V && valid(a)) return { archive: reprice(a), state: 'ok' };
113
+ // 지우지 않고 옆으로 옮겨 둔다 (사용자 기록이라 손으로 살릴 수 있게).
114
+ try {
115
+ renameSync(file, `${file}.bad-${Date.now()}`);
116
+ } catch (e) {
117
+ debugIo('monthly', 'archive move aside failed', e);
118
+ }
119
+ return { archive: emptyArchive(), state: 'corrupt' };
120
+ }
121
+
122
+ // 지금 파일의 rev (없으면 0, 읽을 수 없으면 null).
123
+ function revOf(file) {
124
+ try {
125
+ const a = JSON.parse(readFileSync(file, 'utf8'));
126
+ return a?.v === V && Number.isInteger(a.rev) ? a.rev : null;
127
+ } catch (e) {
128
+ return e.code === 'ENOENT' ? 0 : null;
129
+ }
130
+ }
131
+
132
+ // 읽은 뒤(rev = base) 아무도 쓰지 않았을 때만 쓴다. 썼으면 true.
133
+ export function writeArchive(a, base, file = ARCHIVE_FILE) {
134
+ if (revOf(file) !== base) return false;
135
+ const tmp = `${file}.${process.pid}.tmp`;
136
+ try {
137
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
138
+ writeFileSync(tmp, JSON.stringify({ ...a, v: V, rev: base + 1, price: PRICE_TAG }), { mode: 0o600 });
139
+ // 임시 파일을 쓰는 사이에 다른 쪽이 썼으면 버린다. 이 확인과 rename 사이에 다른 쪽이 rename 하면 그쪽 접기가
140
+ // 덮여 사라질 수 있다 (lost update). 그래도 남는 파일은 이쪽의 since~through 합이라 두 번 세지 않고, 사라진 날은
141
+ // 아직 장부 창 안(그제 근처)이라 다음 접기 때 다시 접힌다.
142
+ if (revOf(file) !== base) {
143
+ rmSync(tmp, { force: true });
144
+ return false;
145
+ }
146
+ renameSync(tmp, file);
147
+ a.rev = base + 1;
148
+ return true;
149
+ } catch (e) {
150
+ debugIo('monthly', 'archive write failed', e);
151
+ try {
152
+ rmSync(tmp, { force: true });
153
+ } catch {}
154
+ return false;
155
+ }
156
+ }
157
+
158
+ // books 의 날짜별 장부를 [lo, hi] 안의 날만 보관함 a 에 접는다 (a 를 고친다). books: [{ tool, project, days }].
159
+ // 부르는 쪽은 [lo, hi] 의 날을 빠짐없이 읽은 장부만 넘긴다. 이미 [since, through] 에 든 날은 건너뛴다.
160
+ // complete: 이 날부터는 원본 기록이 다 남아 있다 (기본 lo). 1년치를 다시 읽을 때 Claude 기록이 지워진 앞쪽을 가른다.
161
+ // gap: 사이가 비면 'hole'(빈 날을 holes 에 적고 접는다) 또는 'refuse'(접지 않는다).
162
+ // 돌려주는 값: 'folded', 'none'(더 접을 날 없음), 'gap'.
163
+ // extraHoles: 이번에 접는 날 중 일부만 센 범위 (staleCut 이 뺀 agy 기록 등).
164
+ export function foldInto(a, books, { lo, hi, complete = lo, now = Date.now(), gap = 'refuse', extraHoles = [] }) {
165
+ const keep = keepFrom(now);
166
+ if (lo < keep) lo = keep;
167
+ if (complete < lo) complete = lo;
168
+ if (hi < lo) return 'none';
169
+ const holes = [];
170
+ // 이번에 새로 접는 범위 (이미 접은 [since, through] 밖).
171
+ const fresh = a.through == null ? [[lo, hi]] : [[lo, addDays(a.since, -1)], [addDays(a.through, 1), hi]];
172
+ if (a.through != null) {
173
+ if (lo >= a.since && hi <= a.through) return 'none';
174
+ const after = addDays(a.through, 1);
175
+ if (hi < addDays(a.since, -1) || (lo > after && gap !== 'hole')) return 'gap';
176
+ // 빈 날, 그리고 원본 기록이 덜 남은 앞쪽과 원래 빠짐없던 날 사이는 '일부' 다.
177
+ const end = lo > complete ? lo : complete;
178
+ if (end > after) holes.push([after, addDays(end, -1)]);
179
+ }
180
+ const has = (d) => a.through != null && d >= a.since && d <= a.through;
181
+ const index = new Map();
182
+ const slot = (month, t, m, p) => {
183
+ const key = `${month}\t${t}\t${m}\t${p ?? ''}`;
184
+ let e = index.get(key);
185
+ if (!e) {
186
+ const list = (a.months[month] ??= []);
187
+ e = list.find((x) => x.t === t && x.m === m && (x.p ?? null) === (p ?? null));
188
+ if (!e) list.push((e = { t, m, p: p ?? null, n: 0, c: 0 }));
189
+ index.set(key, e);
190
+ }
191
+ return e;
192
+ };
193
+ for (const { tool, project, days } of books)
194
+ for (const [d, day] of Object.entries(days ?? {})) {
195
+ if (d < lo || d > hi || has(d)) continue;
196
+ const models = day.models && Object.keys(day.models).length ? day.models : { unknown: { tokens: day.tokens, cost: day.cost, unknown: day.unknown } };
197
+ for (const [model, x] of Object.entries(models)) {
198
+ if (!(x.tokens > 0) && !(x.cost > 0)) continue;
199
+ const e = slot(monthOf(d), tool, model, project);
200
+ e.n += x.tokens;
201
+ e.c += x.cost;
202
+ if (x.unknown) e.x = 1;
203
+ for (const k of ['u', 'f']) if (x[k]) e[k] = (e[k] ?? [0, 0, 0, 0, 0]).map((v, i) => v + (x[k][i] ?? 0));
204
+ }
205
+ }
206
+ if (a.through == null) {
207
+ a.since = lo;
208
+ a.from = complete;
209
+ a.through = hi;
210
+ } else {
211
+ // 앞으로 넓혔으면 from 도 앞당긴다 (complete 가 원래 from 보다 늦으면 그 사이는 위에서 holes 로 적었다).
212
+ if (lo < a.since && complete < a.from) a.from = complete;
213
+ if (lo < a.since) a.since = lo;
214
+ if (hi > a.through) a.through = hi;
215
+ }
216
+ // 이번에 새로 접은 날만 적는다 (이미 접은 날에 겹쳐 쌓이지 않게).
217
+ for (const [x, y, tool] of extraHoles)
218
+ for (const [p, q] of fresh) {
219
+ const from = x > p ? x : p;
220
+ const to = y < q ? y : q;
221
+ if (from <= to) holes.push(tool ? [from, to, tool] : [from, to]);
222
+ }
223
+ a.holes.push(...holes.filter(([x, y]) => x <= y));
224
+ // 12개월보다 오래된 달은 버린다.
225
+ const keepMonth = monthOf(keep);
226
+ for (const k of Object.keys(a.months)) if (k < keepMonth) delete a.months[k];
227
+ a.holes = a.holes.filter(([, to]) => to >= keep);
228
+ if (a.since < keep) a.since = keep;
229
+ if (a.from < keep) a.from = keep;
230
+ if (a.from > a.through) a.from = addDays(a.through, 1);
231
+ return 'folded';
232
+ }
233
+
234
+ // 갱신이 실패한 agy 기록(book.staleFrom)이 있을 때 접을 범위. 그 기록이 쓰였을 수 있는 첫날 전날까지만 접는다.
235
+ // 그렇게 STALE_MAX_DAYS 넘게 밀리면, 그 기록은 staleFrom 앞의 날(마지막으로 다 읽은 정상 값)만 남겨 hi 까지 접고
236
+ // 빠졌을 수 있는 범위를 holes 로 남긴다 (Claude·Codex 몫이 지워지기 전에).
237
+ export function staleCut(books, hi) {
238
+ const stale = books.filter((b) => b.staleFrom && b.staleFrom <= hi);
239
+ if (!stale.length) return { books, hi, holes: [] };
240
+ const first = stale.reduce((x, b) => (b.staleFrom < x ? b.staleFrom : x), hi);
241
+ const cut = addDays(first, -1);
242
+ if (cut >= addDays(hi, -STALE_MAX_DAYS)) {
243
+ debug('monthly', 'fold held back: an agy log failed to update', null, `${first}`);
244
+ return { books, hi: cut, holes: [] };
245
+ }
246
+ debug('monthly', 'fold skipped failing agy logs, days marked partial', null, `${first}`);
247
+ const trim = (b) => ({ ...b, days: Object.fromEntries(Object.entries(b.days ?? {}).filter(([k]) => k < b.staleFrom)) });
248
+ return { books: books.map((b) => (stale.includes(b) ? trim(b) : b)), hi, holes: [[first, hi, 'agy']] };
249
+ }
250
+
251
+ // 읽고, 접고, 쓴다. attach: 장부에 project 를 붙이는 함수 (projects.mjs attachProjects).
252
+ // 돌려주는 값: 'folded', 'none', 'gap', 'newer', 'busy'(다른 aitop 이 먼저 썼다), 'error'.
253
+ export function foldArchive(books, { lo, hi, complete = lo, now = Date.now(), gap = 'refuse', backfilled = false, attach = (b) => b, file = ARCHIVE_FILE } = {}) {
254
+ const { archive: a, state } = readArchive(file);
255
+ if (state === 'newer') return 'newer';
256
+ const cut = staleCut(books, hi);
257
+ books = cut.books;
258
+ hi = cut.hi;
259
+ // 접을 날이 없으면 프로젝트를 찾지도 않는다 (평소 화면은 대개 여기서 끝난다).
260
+ if (a.through != null && lo >= a.since && hi <= a.through && !backfilled) return 'none';
261
+ const base = a.rev;
262
+ let r;
263
+ try {
264
+ r = foldInto(a, attach(books), { lo, hi, complete, now, gap, extraHoles: cut.holes });
265
+ } catch (e) {
266
+ debugIo('monthly', 'archive fold failed', e);
267
+ return 'error';
268
+ }
269
+ if (r === 'gap') return r;
270
+ if (backfilled) a.backfilled = dayKey(now);
271
+ else if (r === 'none') return r;
272
+ return writeArchive(a, base, file) ? r : 'busy';
273
+ }
package/src/pricing.mjs CHANGED
@@ -79,17 +79,46 @@ function priceOf(model) {
79
79
  return lookup(PRICES, model);
80
80
  }
81
81
 
82
+ // 사용량 벡터: [입력(캐시 제외), 출력, 캐시 읽기, 캐시 쓰기 5분, 캐시 쓰기 1시간]. 월별 보관함(monthly.mjs)이
83
+ // 이 벡터를 남겨 두었다가 가격표가 바뀌면 지금 가격으로 다시 계산한다.
84
+ export const VEC = 5;
85
+ export const zeroVec = () => [0, 0, 0, 0, 0];
86
+
87
+ // Claude usage 한 건의 벡터.
88
+ export function claudeVec(u) {
89
+ if (!u) return zeroVec();
90
+ const write1h = u.cache_creation?.ephemeral_1h_input_tokens ?? 0;
91
+ const write5m = u.cache_creation ? (u.cache_creation.ephemeral_5m_input_tokens ?? 0) : (u.cache_creation_input_tokens ?? 0);
92
+ return [u.input_tokens ?? 0, u.output_tokens ?? 0, u.cache_read_input_tokens ?? 0, write5m, write1h];
93
+ }
94
+
95
+ // Claude 벡터 하나의 비용 (m: fast 배수).
96
+ function claudeVecCost(p, v, m) {
97
+ const input = p.input * m;
98
+ const base = v[0] * input + v[1] * p.output * m;
99
+ const cache = v[2] * (p.cacheRead ?? p.input * 0.1) * m + v[3] * input * 1.25 + v[4] * input * 2;
100
+ return { total: (base + cache) / 1e6, noCache: base / 1e6 };
101
+ }
102
+
82
103
  // Claude 메시지 usage 한 건의 환산 비용. total 은 캐시 포함, noCache 는 입력·출력만. 가격표에 없는 모델이면 null.
83
104
  export function claudeCost(model, u) {
84
105
  const p = priceOf(model);
85
106
  if (!p || !u) return null;
86
- const m = u.speed === 'fast' && p.fast ? p.fast : 1;
87
- const input = p.input * m;
88
- const write1h = u.cache_creation?.ephemeral_1h_input_tokens ?? 0;
89
- const write5m = u.cache_creation ? (u.cache_creation.ephemeral_5m_input_tokens ?? 0) : (u.cache_creation_input_tokens ?? 0);
90
- const base = (u.input_tokens ?? 0) * input + (u.output_tokens ?? 0) * p.output * m;
91
- const cache = (u.cache_read_input_tokens ?? 0) * (p.cacheRead ?? p.input * 0.1) * m + write5m * input * 1.25 + write1h * input * 2;
92
- return { total: (base + cache) / 1e6, noCache: base / 1e6 };
107
+ return claudeVecCost(p, claudeVec(u), u.speed === 'fast' && p.fast ? p.fast : 1);
108
+ }
109
+
110
+ // 보관된 벡터(v: 보통, f: fast 모드)를 지금 가격표로 환산한 비용(USD). 가격표에 없는 모델이면 null.
111
+ // agy(Gemini)는 날짜별 가격이라 at(그 달 가운데) 시각의 가격을 쓴다.
112
+ export function vecCost(tool, model, v, f, at = Date.now()) {
113
+ const u = v ?? zeroVec();
114
+ if (tool === 'claude') {
115
+ const p = priceOf(model);
116
+ if (!p) return null;
117
+ return claudeVecCost(p, u, 1).total + (f ? claudeVecCost(p, f, p.fast ?? 1).total : 0);
118
+ }
119
+ const p = tool === 'codex' ? openaiPrice(model) : tool === 'agy' ? geminiPrice(model, at) : null;
120
+ if (!p) return null;
121
+ return (u[0] * p.input + u[1] * p.output + u[2] * (p.cacheRead ?? 0)) / 1e6;
93
122
  }
94
123
 
95
124
  // Codex(OpenAI) API 정가 기준 환산 비용 (USD / 100만 토큰). Claude 와 같이 "API 로 썼다면" 기준이다.
package/src/report.mjs CHANGED
@@ -2,13 +2,15 @@
2
2
  // 값은 날짜별 사용량 장부(claude-ledger.mjs 의 collectDaily)에서 오고, 비용은 화면 헤더와 같은 API 정가 환산이다.
3
3
  // 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
4
4
  // 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
5
+ // --report monthly: 최근 N달(기본·최대 12)의 달별 표. 지난 날은 월별 보관함(monthly.mjs), 접기 전의 날은 장부에서 센다.
5
6
  import { t } from './i18n.mjs';
6
7
  import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
7
8
  import { money } from './line.mjs';
8
9
  import { KEEP_DAYS, lastDays } from './sources/common.mjs';
9
10
  import { projectLabels } from './sources/projects.mjs';
11
+ import { KEEP_MONTHS, lastMonths, monthOf, monthEnd } from './monthly.mjs';
10
12
 
11
- export const KINDS = ['daily'];
13
+ export const KINDS = ['daily', 'monthly'];
12
14
  export const BY = ['tool', 'model', 'project'];
13
15
  // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
14
16
  export const UNKNOWN = '(unknown)';
@@ -17,6 +19,8 @@ export const OTHERS = '(others)';
17
19
  const HEAD_MAX = 24;
18
20
  export const MAX_DAYS = KEEP_DAYS;
19
21
  export const DEFAULT_DAYS = KEEP_DAYS;
22
+ export const MAX_MONTHS = KEEP_MONTHS;
23
+ export const DEFAULT_MONTHS = KEEP_MONTHS;
20
24
  // 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
21
25
  export const MAX_MS = 120_000;
22
26
  // 한 번에 읽는 시간. 이만큼마다 진행률을 고치고 캐시를 저장한다.
@@ -26,19 +30,22 @@ const PROGRESS_AFTER_MS = 400;
26
30
  const FLUSH_MS = 3000;
27
31
  const TOOLS = ['claude', 'codex', 'agy'];
28
32
 
29
- // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
30
- // kind 는 --report 를 주지 않았으면 null. --by·--days 는 --report 와 함께일 때만 받는다. capped: --days 를 30으로 줄였는지.
33
+ // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --months <N> (= 꼴도) 를 꺼낸다.
34
+ // kind 는 --report 를 주지 않았으면 null. --by·--days·--months 는 --report 와 함께일 때만 받는다.
35
+ // --days 는 daily, --months 는 monthly 와만 쓴다. capped: --days 를 30으로(--months 를 12로) 줄였는지.
31
36
  export function reportOption(argv) {
32
37
  let kind = null;
33
38
  let by = 'tool';
34
39
  let days = DEFAULT_DAYS;
40
+ let months = DEFAULT_MONTHS;
35
41
  let capped = false;
42
+ let gave = null;
36
43
  let error = null;
37
44
  let extra = false;
38
45
  const rest = [];
39
46
  for (let i = 0; i < argv.length; i++) {
40
47
  const a = argv[i];
41
- const m = /^--(report|by|days)(?:=(.*))?$/.exec(a);
48
+ const m = /^--(report|by|days|months)(?:=(.*))?$/.exec(a);
42
49
  if (!m) {
43
50
  rest.push(a);
44
51
  continue;
@@ -54,15 +61,19 @@ export function reportOption(argv) {
54
61
  else error ??= raw === '' ? t('opt.byMissing') : t('opt.byBad', { value: JSON.stringify(raw) });
55
62
  } else {
56
63
  extra = true;
64
+ gave = name;
65
+ const max = name === 'days' ? MAX_DAYS : MAX_MONTHS;
57
66
  const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
58
67
  if (n > 0) {
59
- capped = n > MAX_DAYS;
60
- days = Math.min(n, MAX_DAYS);
61
- } else error ??= raw === '' ? t('opt.daysMissing') : t('opt.daysBad', { value: JSON.stringify(raw) });
68
+ capped = n > max;
69
+ if (name === 'days') days = Math.min(n, max);
70
+ else months = Math.min(n, max);
71
+ } else error ??= raw === '' ? t(`opt.${name}Missing`) : t(`opt.${name}Bad`, { value: JSON.stringify(raw) });
62
72
  }
63
73
  }
64
74
  if (!error && extra && !kind) error = t('opt.reportOnly');
65
- return { kind, by, days, capped, rest, error };
75
+ if (!error && gave && kind && (gave === 'days') !== (kind === 'daily')) error = t(gave === 'days' ? 'opt.daysDaily' : 'opt.monthsMonthly');
76
+ return { kind, by, days, months, capped, rest, error };
66
77
  }
67
78
 
68
79
  const zero = () => ({ tokens: 0, cost: 0, unpriced: false });
@@ -104,13 +115,81 @@ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Dat
104
115
  add(total, d.tokens, d.cost, d.unknown);
105
116
  }
106
117
  }
118
+ const columns = columnsOf(total, rows, by, maxColumns);
119
+ const out = { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
120
+ if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
121
+ return out;
122
+ }
123
+
124
+ // 열: 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순). 토큰이 하나도 없는 열은 빼고, maxColumns 를 넘으면 OTHERS 로 접는다.
125
+ function columnsOf(total, rows, by, maxColumns) {
107
126
  const rank = (name) => (by === 'tool' ? TOOLS.indexOf(name) : 0);
108
127
  const columns = Object.entries(total.items)
109
128
  .filter(([, x]) => x.tokens > 0 || x.cost > 0)
110
129
  .sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
111
130
  .map(([name]) => name);
112
131
  if (columns.length > maxColumns) foldOthers(columns, Math.max(1, maxColumns - 1), [...rows, total]);
113
- const out = { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
132
+ return columns;
133
+ }
134
+
135
+ const nextDay = (key) => {
136
+ const [y, m, d] = key.split('-').map(Number);
137
+ return lastDays(1, new Date(y, m - 1, d + 1, 12).getTime())[0];
138
+ };
139
+
140
+ // 월별 표. archive: 월별 보관함(없으면 null), books: 장부 [{ tool, project, days }].
141
+ // 보관함은 through 까지의 날을, 장부는 viewLo(다 읽은 창의 첫날) 이후이면서 through 다음 날부터를 센다 (한 날은 한쪽에서만).
142
+ // liveLo: 장부 쪽에서 원본 기록이 빠짐없이 남은 첫날 (기본 viewLo).
143
+ // 달마다 status: complete(빠짐없이 셌다), partial(일부 날만 셌다), missing(센 날도 값도 없다: 0 이 아니라 모름). current: 이번 달.
144
+ // partial: 장부를 시간 상한 때문에 덜 읽었으면, 장부 쪽 날은 센 날로 치지 않는다 (그 달은 complete 가 되지 않는다).
145
+ export function buildMonthly(books, archive, { by = 'tool', months = DEFAULT_MONTHS, now = Date.now(), viewLo, liveLo, partial = false, maxColumns = Infinity } = {}) {
146
+ const keys = lastMonths(months, now);
147
+ const shown = new Set(keys);
148
+ const today = lastDays(1, now)[0];
149
+ const through = archive?.through ?? null;
150
+ const from = archive?.from ?? null;
151
+ const holes = archive?.holes ?? [];
152
+ viewLo ??= lastDays(KEEP_DAYS, now).at(-1);
153
+ liveLo ??= viewLo;
154
+ const parts = [];
155
+ for (const k of keys) for (const e of archive?.months?.[k] ?? []) parts.push({ month: k, tool: e.t, model: e.m, project: e.p ?? null, tokens: e.n, cost: e.c, unknown: Boolean(e.x) });
156
+ for (const { tool, project, days } of books)
157
+ for (const [d, day] of Object.entries(days ?? {})) {
158
+ if (d < viewLo || d > today || (through && d <= through) || !shown.has(monthOf(d))) continue;
159
+ const models = day.models && Object.keys(day.models).length ? day.models : { unknown: day };
160
+ for (const [model, x] of Object.entries(models)) parts.push({ month: monthOf(d), tool, model, project: project ?? null, tokens: x.tokens, cost: x.cost, unknown: Boolean(x.unknown) });
161
+ }
162
+ const labels = by === 'project' ? projectLabels(new Set(parts.map((p) => p.project).filter(Boolean))) : new Map();
163
+ const paths = {};
164
+ // 센 날인지: 보관함 [from, through] (빈 날 제외) 또는 장부 [liveLo, 오늘].
165
+ const counted = (d) => (!partial && d >= liveLo) || (through && d >= from && d <= through && !holes.some(([a, b]) => d >= a && d <= b));
166
+ const rows = keys.map((month) => {
167
+ let all = 0;
168
+ let got = 0;
169
+ for (let d = `${month}-01`, end = monthEnd(month); d <= end && d <= today; d = nextDay(d)) {
170
+ all++;
171
+ if (counted(d)) got++;
172
+ }
173
+ return { date: month, month, current: month === keys[0], status: got === 0 ? 'missing' : got < all ? 'partial' : 'complete', tokens: 0, cost: 0, unpriced: false, items: {} };
174
+ });
175
+ const at = new Map(rows.map((r) => [r.month, r]));
176
+ const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
177
+ let unpriced = false;
178
+ for (const p of parts) {
179
+ if (!(p.tokens > 0) && !(p.cost > 0)) continue;
180
+ const row = at.get(p.month);
181
+ const name = by === 'model' ? p.model : by === 'project' ? (labels.get(p.project) ?? UNKNOWN) : p.tool;
182
+ if (by === 'project' && p.project) paths[labels.get(p.project)] = p.project;
183
+ if (p.unknown) unpriced = true;
184
+ for (const o of [row, total]) {
185
+ add((o.items[name] ??= zero()), p.tokens, p.cost, p.unknown);
186
+ add(o, p.tokens, p.cost, p.unknown);
187
+ }
188
+ }
189
+ // 센 날이 없어도 값이 있으면(예: Claude 기록은 지워졌지만 Codex 기록은 남은 달) '일부' 로 값을 보인다.
190
+ for (const r of rows) if (r.status === 'missing' && (r.tokens > 0 || r.cost > 0)) r.status = 'partial';
191
+ const columns = columnsOf(total, rows, by, maxColumns);
192
+ const out = { report: 'monthly', by, months, from: keys.at(-1), to: keys[0], columns, rows, total, unpriced };
114
193
  if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
115
194
  return out;
116
195
  }
@@ -155,11 +234,13 @@ function foldOthers(columns, keep, lines) {
155
234
  // 칸마다 unpriced(가격표에 없는 모델이 끼었는지)를 참·거짓으로 둔다. 화면의 ? 와 같은 뜻이다.
156
235
  export function reportJson(r, version, { partial = false } = {}) {
157
236
  const items = (o) => Object.fromEntries(r.columns.map((c) => [c, { tokens: o.items[c]?.tokens ?? 0, cost: o.items[c]?.cost ?? 0, unpriced: Boolean(o.items[c]?.unpriced) }]));
237
+ const monthly = r.report === 'monthly';
238
+ const row = (x) => (monthly ? { month: x.month, current: x.current, status: x.status } : { date: x.date });
158
239
  return {
159
240
  version,
160
241
  report: r.report,
161
242
  by: r.by,
162
- days: r.days,
243
+ ...(monthly ? { months: r.months } : { days: r.days }),
163
244
  from: r.from,
164
245
  to: r.to,
165
246
  basis: 'api',
@@ -167,7 +248,7 @@ export function reportJson(r, version, { partial = false } = {}) {
167
248
  unpriced: r.unpriced,
168
249
  columns: r.columns,
169
250
  ...(r.paths ? { paths: r.paths } : {}),
170
- rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
251
+ rows: r.rows.map((x) => ({ ...row(x), tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
171
252
  total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
172
253
  };
173
254
  }
@@ -180,9 +261,11 @@ const colName = (c) => (c === UNKNOWN ? t('report.unknown') : c === OTHERS ? t('
180
261
  // 표의 머리글·날짜 줄·합계 줄 글과 칸 폭 w.
181
262
  function table(r) {
182
263
  // 모델·프로젝트 이름은 기록에서 온 글이라 제어문자를 지운다.
183
- const head = [t('report.date'), ...r.columns.map(colName), t('report.total')];
184
- const line = (label, o) => [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)];
185
- const body = r.rows.map((x) => line(x.date, x));
264
+ const head = [t(r.report === 'monthly' ? 'report.month' : 'report.date'), ...r.columns.map(colName), t('report.total')];
265
+ const line = (label, o) => (o.status === 'missing' ? [label, ...r.columns.map(() => ''), t('report.missing')] : [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)]);
266
+ // 달 표시: 이번 달 *, 일부만 센 달 ~.
267
+ const mark = (x) => (x.month ? `${x.month}${x.current ? ' *' : ''}${x.status === 'partial' ? ' ~' : ''}` : x.date);
268
+ const body = r.rows.map((x) => line(mark(x), x));
186
269
  const foot = line(t('report.total'), r.total);
187
270
  const all = [head, ...body, foot];
188
271
  const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
@@ -199,8 +282,17 @@ export function formatReport(r, { partial = false } = {}) {
199
282
  const { head, body, foot, w } = table(r);
200
283
  const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
201
284
  const rule = w.map((n) => '-'.repeat(n)).join(' ');
202
- const out = [t('report.title', { n: r.days, by: t(`report.by.${r.by}`), from: r.from, to: r.to }), '', fmt(head), rule, ...body.map(fmt), rule, fmt(foot)];
285
+ const monthly = r.report === 'monthly';
286
+ const title = monthly ? t('report.titleMonthly', { n: r.months, by: t(`report.by.${r.by}`), from: r.from, to: r.to }) : t('report.title', { n: r.days, by: t(`report.by.${r.by}`), from: r.from, to: r.to });
287
+ const out = [title, '', fmt(head), rule, ...body.map(fmt), rule, fmt(foot)];
203
288
  if (!r.columns.length) out.push('', t('report.empty'));
289
+ if (monthly) {
290
+ const notes = [];
291
+ if (r.rows.some((x) => x.current)) notes.push(t('report.noteCurrent'));
292
+ if (r.rows.some((x) => x.status === 'partial')) notes.push(t('report.notePartial'));
293
+ if (r.rows.some((x) => x.status === 'missing')) notes.push(t('report.noteMissing'));
294
+ if (notes.length) out.push('', ...notes);
295
+ }
204
296
  if (r.unpriced) out.push('', t('report.unpriced'));
205
297
  if (partial) out.push('', t('report.partial'));
206
298
  return out.join('\n');
@@ -209,19 +301,26 @@ export function formatReport(r, { partial = false } = {}) {
209
301
  // 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
210
302
  // 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
211
303
  // by 가 'project' 면 장부마다 project(작업 폴더)를 붙인다.
212
- export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {} } = {}) {
304
+ // span: 주면 days 대신 최근 span 일(상한 없음) 안에 바뀐 기록을 읽는다 (월별 리포트). 이때는 접지 않는다 (collectMonthly 가 접는다).
305
+ // stepMs: 한 번에 읽는 시간 (테스트가 시간 상한을 흉내 낼 때 줄인다).
306
+ export async function collectReport({ days = DEFAULT_DAYS, span = null, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {}, stepMs = STEP_MS } = {}) {
213
307
  const { createBudget } = await import('./tail.mjs');
214
- const { collectDaily } = await import('./sources/claude-ledger.mjs');
308
+ const { collectDaily, collectSpan } = await import('./sources/claude-ledger.mjs');
215
309
  const { flushCache } = await import('./cache.mjs');
216
310
  const { attachProjects } = await import('./sources/projects.mjs');
217
311
  const done = (books, partial) => ({ books: by === 'project' ? attachProjects(books) : books, partial });
218
312
  const start = Date.now();
219
313
  let lastFlush = start;
220
314
  for (;;) {
221
- const budget = createBudget(Infinity, STEP_MS);
222
- const r = collectDaily({ budget, now, days });
315
+ const budget = createBudget(Infinity, stepMs);
316
+ const r = span ? collectSpan({ budget, now, days: span }) : collectDaily({ budget, now, days });
223
317
  const spent = Date.now() - start;
224
- if (!budget.exhausted) return done(r.books, false);
318
+ // 다 읽었으면 지난 날을 월별 보관함에 접는다 (화면을 띄우지 않고 리포트만 쓰는 사용자도 보관함이 이어지게).
319
+ if (!budget.exhausted) {
320
+ const out = done(r.books, false);
321
+ if (!span) await foldDaily(out.books, now, days, by === 'project');
322
+ return out;
323
+ }
225
324
  onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
226
325
  if (Date.now() - lastFlush > FLUSH_MS) {
227
326
  flushCache();
@@ -233,6 +332,42 @@ export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now =
233
332
  }
234
333
  }
235
334
 
335
+ // --report daily 가 다 읽은 장부(최근 days 일)를 보관함에 접는다. 접을 날이 없으면 파일만 읽고 끝난다.
336
+ async function foldDaily(books, now, days, attached) {
337
+ const { foldArchive, foldHi } = await import('./monthly.mjs');
338
+ const { attachProjects } = await import('./sources/projects.mjs');
339
+ foldArchive(books, { lo: lastDays(Math.max(7, Math.min(KEEP_DAYS, days)), now).at(-1), hi: foldHi(now), now, attach: attached ? (b) => b : attachProjects });
340
+ }
341
+
342
+ // --report monthly 용 장부 읽기와 접기. 보관함을 아직 1년치로 채운 적이 없거나(backfilled) 마지막으로 접은 날이 30일 창보다 오래됐으면,
343
+ // 12개월 전 달 1일부터 바뀐 기록을 모두 읽어(시간 상한·진행률은 daily 와 같다) 한 번 채운다. 아니면 30일 창만 읽는다.
344
+ // 다 읽었을 때만 접는다. 돌려주는 값: { books, archive, viewLo, liveLo, partial, state } (buildMonthly 참고).
345
+ export async function collectMonthly({ maxMs = MAX_MS, now = Date.now(), onProgress = () => {}, stepMs = STEP_MS } = {}) {
346
+ const m = await import('./monthly.mjs');
347
+ const { archive, state } = m.readArchive();
348
+ const lo30 = lastDays(KEEP_DAYS, now).at(-1);
349
+ const backfill = Boolean(archive) && (!archive.backfilled || archive.through == null || archive.through < m.addDays(lo30, -1));
350
+ const lo = backfill ? m.keepFrom(now) : lo30;
351
+ const [y, mo, d] = lo.split('-').map(Number);
352
+ const span = Math.ceil((now - new Date(y, mo - 1, d).getTime()) / 86400_000) + 1;
353
+ const got = await collectReport({ span, maxMs, now, by: 'project', onProgress, stepMs });
354
+ // 30일 창만 읽을 때도, 보관함이 아는 '빠짐없는 첫날(from)' 보다 앞은 일부로 둔다 (지워진 기록은 창 안에서도 돌아오지 않는다).
355
+ let liveLo = !backfill && archive?.from > lo ? archive.from : lo;
356
+ if (backfill) {
357
+ // Claude Code 는 수정 시각이 오래된 기록부터 지운다 (cleanupPeriodDays, 기본 30일). 남은 Claude 기록 중 가장 오래된
358
+ // 수정 시각이 든 날까지는 지워진 기록이 있었을 수 있어 '일부' 로 두고, 그다음 날부터 빠짐없다고 본다.
359
+ // (오래 이어 쓴 기록 하나에 옛날 날짜가 있어도 경계는 수정 시각이다.) Codex·agy 는 기록을 지우지 않는다.
360
+ const { oldestClaudeMtime } = await import('./sources/claude-ledger.mjs');
361
+ const oldest = oldestClaudeMtime();
362
+ const next = oldest == null ? lo : m.addDays(lastDays(1, oldest)[0], 1);
363
+ liveLo = next > lo ? next : lo;
364
+ }
365
+ if (!got.partial && archive) m.foldArchive(got.books, { lo, hi: m.foldHi(now), complete: liveLo, now, gap: backfill ? 'hole' : 'refuse', backfilled: backfill });
366
+ // 다른 aitop 이 먼저 썼을 수도 있으니 다시 읽는다 (그 경우도 파일 안은 늘 from~through 의 합이다).
367
+ const after = archive ? m.readArchive().archive : null;
368
+ return { books: got.books, archive: after, viewLo: lo, liveLo, partial: got.partial, state };
369
+ }
370
+
236
371
  // stderr 진행률. 터미널일 때만, 처음 PROGRESS_AFTER_MS 가 지난 뒤부터 같은 줄을 고쳐 쓴다. done() 은 그 줄을 지운다.
237
372
  export function progressWriter(stream = process.stderr) {
238
373
  let shown = false;
@@ -7,16 +7,17 @@ import { join } from 'node:path';
7
7
  import { AGY_ROOT, readCalls, sigOf, maxIdx } from './antigravity.mjs';
8
8
  import { openReadOnly, loadSqlite } from '../sqlite.mjs';
9
9
  import { loadCache, markDirty } from '../cache.mjs';
10
- import { dayKey, lastDays, addSlot, addModel, KEEP_DAYS } from './common.mjs';
10
+ import { dayKey, addSlot, addModel, recentDays } from './common.mjs';
11
11
  import { debugIo } from '../log.mjs';
12
12
 
13
- const KIND = 'agy-ledger';
13
+ // 2: 사용량 벡터, 날짜 400일 보관 (#164).
14
+ const KIND = 'agy-ledger2';
14
15
  const DAYS = 7;
15
16
  const LIST_TTL_MS = 30_000;
16
17
 
17
18
  const outOf = (budget) => budget.left <= 0 || (budget.read > 0 && Date.now() >= (budget.deadline ?? Infinity));
18
19
  // 하루 합계 안의 모델별 몫도 따로 복사해, 읽다가 버릴 때 원래 장부가 바뀌지 않게 한다.
19
- const copyDays = (days) => Object.fromEntries(Object.entries(days).map(([k, v]) => [k, v.models ? { ...v, models: Object.fromEntries(Object.entries(v.models).map(([m, x]) => [m, { ...x }])) } : { ...v }]));
20
+ const copyDays = (days) => Object.fromEntries(Object.entries(days).map(([k, v]) => [k, v.models ? { ...v, models: Object.fromEntries(Object.entries(v.models).map(([m, x]) => [m, { ...x, ...(x.u ? { u: [...x.u] } : {}), ...(x.f ? { f: [...x.f] } : {}) }])) } : { ...v }]));
20
21
 
21
22
  export class AgyBook {
22
23
  constructor(path) {
@@ -29,16 +30,39 @@ export class AgyBook {
29
30
  this.slots = {};
30
31
  // 한 번이라도 끝까지 읽었는지. 처음 읽는 동안만 '집계 중' 진행률에 들어간다.
31
32
  this.complete = false;
33
+ // 마지막 갱신이 실패했는지 (열지 못함, 읽는 중 agy 가 씀, 예외). 캐시에서 불러온 값이 낡았을 수 있어
34
+ // 월별 보관함은 이 기록이 쓰였을 수 있는 날(staleFrom 부터)을 접지 않는다 (monthly.mjs staleCut).
35
+ this.stale = false;
36
+ // 실패한 때의 sig. 파일이 바뀌기 전까지는 매 갱신마다 다시 열지 않는다.
37
+ this.failSig = null;
38
+ // 마지막으로 끝까지 읽었을 때의 파일 수정 시각 (그 뒤에 쓴 호출만 빠졌을 수 있다).
39
+ this.okAt = null;
32
40
  const c = loadCache(path, KIND);
33
41
  if (c) {
34
42
  this.idx = c.idx ?? -1;
35
43
  this.model = c.model ?? null;
36
44
  this.days = c.days ?? {};
37
45
  this.slots = c.slots ?? {};
46
+ this.okAt = c.okAt ?? null;
38
47
  this.complete = true;
39
48
  }
40
49
  }
41
50
 
51
+ // 빠졌을 수 있는 첫날. 끝까지 읽은 적이 있으면 그때의 날, 없으면 파일이 생긴 날, 그것도 모르면 맨 처음부터.
52
+ get staleFrom() {
53
+ if (this.okAt != null) return dayKey(this.okAt);
54
+ try {
55
+ const born = statSync(this.path).birthtimeMs;
56
+ if (born > 0) return dayKey(born);
57
+ } catch {}
58
+ return '0000-00-00';
59
+ }
60
+
61
+ fail(sig) {
62
+ this.stale = true;
63
+ this.failSig = sig;
64
+ }
65
+
42
66
  get size() {
43
67
  try {
44
68
  return statSync(this.path).size;
@@ -49,7 +73,7 @@ export class AgyBook {
49
73
 
50
74
  update(budget) {
51
75
  const sig = sigOf(this.path);
52
- if (sig === null || sig === this.sig) return;
76
+ if (sig === null || sig === this.sig || sig === this.failSig) return;
53
77
  if (outOf(budget)) {
54
78
  budget.exhausted = true;
55
79
  return;
@@ -60,8 +84,12 @@ export class AgyBook {
60
84
  let db;
61
85
  let result = null;
62
86
  try {
87
+ opens++;
63
88
  db = openReadOnly(this.path);
64
- if (!db) return;
89
+ if (!db) {
90
+ this.fail(sig);
91
+ return;
92
+ }
65
93
  const has = db.prepare("select 1 from sqlite_master where type = 'table' and name = 'gen_metadata'").get();
66
94
  const last = has ? maxIdx(db, 'gen_metadata') : -1;
67
95
  // 마지막 줄 번호가 줄었으면 기록이 새로 쓰인 것이니 처음부터 다시 센다.
@@ -73,7 +101,7 @@ export class AgyBook {
73
101
  day.tokens += tokens;
74
102
  day.cost += cost?.total ?? 0;
75
103
  day.costNoCache += cost?.noCache ?? 0;
76
- addModel(day, model, tokens, cost?.total ?? 0, !cost && tokens > 0);
104
+ addModel(day, model, tokens, cost?.total ?? 0, !cost && tokens > 0, [u.input, u.output, u.cacheRead, u.cacheWrite, 0]);
77
105
  if (!cost && tokens > 0) day.unknown = true;
78
106
  addSlot(n.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost && tokens > 0);
79
107
  })
@@ -86,21 +114,27 @@ export class AgyBook {
86
114
  } finally {
87
115
  db?.close();
88
116
  }
89
- if (!result) return;
117
+ if (!result) {
118
+ this.fail(sig);
119
+ return;
120
+ }
90
121
  const changed = n.idx !== this.idx;
91
122
  Object.assign(this, n);
92
123
  if (result === 'done') {
93
124
  this.sig = sig;
94
125
  this.complete = true;
126
+ this.stale = false;
127
+ this.failSig = null;
128
+ this.okAt = mtime;
95
129
  }
96
130
  if (result === 'exhausted') budget.exhausted = true;
131
+ // 덜 쓰인 줄(torn)에서 멈췄으면 그 뒤가 빠졌을 수 있다. 파일이 바뀌면(마저 쓰이면) 다시 읽는다.
132
+ if (result === 'torn') this.fail(sig);
97
133
  if (changed) markDirty(this.path, () => this.snapshot(), KIND);
98
134
  }
99
135
 
100
136
  snapshot() {
101
- const keep = new Set(lastDays(KEEP_DAYS));
102
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
103
- return { offset: 0, idx: this.idx, model: this.model, days, slots: this.slots };
137
+ return { offset: 0, idx: this.idx, model: this.model, days: recentDays(this.days), slots: this.slots, okAt: this.okAt };
104
138
  }
105
139
  }
106
140
 
@@ -131,10 +165,11 @@ function recentFiles(days = DAYS) {
131
165
 
132
166
  const books = new Map();
133
167
 
134
- // 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size).
168
+ // 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size),
169
+ // 기록마다 마지막 갱신이 실패했으면 빠졌을 수 있는 첫날(stale, 아니면 null).
135
170
  // node:sqlite 를 못 쓰는 Node 에서는 비어 있다 (agy 는 프로세스만 보인다).
136
171
  export function collectAgyLedger({ budget, days = DAYS } = {}) {
137
- const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
172
+ const out = { days: [], slots: [], paths: [], stale: [], pending: 0, size: 0 };
138
173
  if (!loadSqlite() || !existsSync(join(AGY_ROOT, 'conversations'))) return out;
139
174
  const files = recentFiles(days);
140
175
  const keep = new Set(files);
@@ -146,6 +181,8 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
146
181
  const size = b.size;
147
182
  out.size += size;
148
183
  if (!b.complete) out.pending += size;
184
+ // 실패한 기록은 빠졌을 수 있는 첫날, 아니면 null.
185
+ out.stale.push(b.stale ? b.staleFrom : null);
149
186
  out.days.push(b.days);
150
187
  out.paths.push(p);
151
188
  out.slots.push(b.slots);
@@ -153,4 +190,6 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
153
190
  return out;
154
191
  }
155
192
 
156
- export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()) };
193
+ // 테스트용: 기록을 연 횟수.
194
+ let opens = 0;
195
+ export const _test = { reset: () => ((listed = { at: 0, files: [], days: 0 }), books.clear()), opens: () => opens };
@@ -7,17 +7,20 @@ import { join } from 'node:path';
7
7
  import { homedir } from 'node:os';
8
8
  import { JsonlTail } from '../tail.mjs';
9
9
  import { loadCache, markDirty } from '../cache.mjs';
10
- import { claudeCost } from '../pricing.mjs';
11
- import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, KEEP_DAYS } from './common.mjs';
10
+ import { claudeCost, claudeVec } from '../pricing.mjs';
11
+ import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, recentDays, KEEP_DAYS } from './common.mjs';
12
12
  import { collectAgyLedger } from './agy-ledger.mjs';
13
13
  import { collectCodexLedger } from './codex-ledger.mjs';
14
14
  import { debugIo } from '../log.mjs';
15
+ import { foldArchive, foldHi } from '../monthly.mjs';
16
+ import { attachProjects } from './projects.mjs';
15
17
 
16
18
  export { dayKey };
17
19
 
18
20
  const HOME = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
19
21
  const PROJECTS = join(HOME, 'projects');
20
- const KIND = 'ledger';
22
+ // 2: 모델 몫에 사용량 벡터(u, f), 날짜 400일 보관 (#164). 이름을 바꾸면 장부만 다시 센다.
23
+ const KIND = 'ledger2';
21
24
  const DAYS = 7;
22
25
  const LIST_TTL_MS = 30_000;
23
26
  const RECENT_IDS = 64;
@@ -55,9 +58,7 @@ export class UsageTracker {
55
58
  }
56
59
 
57
60
  snapshot() {
58
- const keep = new Set(lastDays(KEEP_DAYS));
59
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
60
- return { offset: this.tail.lineOffset, days, slots: this.slots, recent: [...this.recent] };
61
+ return { offset: this.tail.lineOffset, days: recentDays(this.days), slots: this.slots, recent: [...this.recent] };
61
62
  }
62
63
 
63
64
  // 같은 message.id 가 여러 줄로 반복되므로 직전 값과의 차이만, 그 줄의 날짜와 5분 칸에 더한다.
@@ -77,7 +78,9 @@ export class UsageTracker {
77
78
  const dTokens = tokensOf(u) - tokensOf(prev?.u);
78
79
  day.tokens += dTokens;
79
80
  day.cost += dCost;
80
- addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0);
81
+ const vec = claudeVec(u);
82
+ const was = claudeVec(prev?.u);
83
+ addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0, vec.map((x, i) => x - was[i]), u.speed === 'fast');
81
84
  day.costNoCache = (day.costNoCache ?? 0) + (cost?.noCache ?? 0) - (prev?.costNoCache ?? 0);
82
85
  if (unknown) day.unknown = true;
83
86
  addSlot(this.slots, at, dCost, dNoCache, unknown);
@@ -153,7 +156,7 @@ function gather({ budget, now, days = DAYS }) {
153
156
  for (const [tool, o] of others) {
154
157
  pending += o.pending;
155
158
  size += o.size;
156
- books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d })));
159
+ books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d, ...(o.stale?.[i] ? { staleFrom: o.stale[i] } : {}) })));
157
160
  slots.push(...o.slots);
158
161
  }
159
162
  return { books, slots, pending, size };
@@ -162,14 +165,61 @@ function gather({ budget, now, days = DAYS }) {
162
165
  // 기간 리포트용: 최근 days 일(최대 KEEP_DAYS) 안에 바뀐 기록의 날짜별·모델별 장부.
163
166
  // 평소 화면(collectLedger)은 7일 안에 바뀐 기록만 보므로, 이 함수를 부를 때만 더 오래된 기록을 읽는다.
164
167
  export function collectDaily({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
165
- const { books, pending, size } = gather({ budget, now, days: Math.max(DAYS, Math.min(KEEP_DAYS, days)) });
168
+ return collectSpan({ budget, now, days: Math.min(KEEP_DAYS, days) });
169
+ }
170
+
171
+ // 최근 days 일(상한 없음) 안에 바뀐 기록의 장부. 월별 리포트가 보관함을 처음 채울 때 1년치까지 넓혀 읽는다.
172
+ export function collectSpan({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
173
+ const { books, pending, size } = gather({ budget, now, days: Math.max(DAYS, days) });
166
174
  return { books, pending, size };
167
175
  }
168
176
 
177
+ // 남은 Claude 기록 중 가장 오래된 수정 시각(ms, 없으면 null). Claude Code 는 수정 시각이 오래된 기록부터 지우므로,
178
+ // 이 시각이 든 날까지는 지워진 기록이 있었을 수 있다 (월별 리포트가 '일부' 를 가를 때 쓴다).
179
+ export function oldestClaudeMtime() {
180
+ let oldest = null;
181
+ const see = (p) => {
182
+ try {
183
+ const m = statSync(p).mtimeMs;
184
+ if (oldest == null || m < oldest) oldest = m;
185
+ } catch {}
186
+ };
187
+ let dirs = [];
188
+ try {
189
+ dirs = readdirSync(PROJECTS);
190
+ } catch {}
191
+ for (const dir of dirs) {
192
+ let names = [];
193
+ try {
194
+ names = readdirSync(join(PROJECTS, dir));
195
+ } catch {
196
+ continue;
197
+ }
198
+ for (const n of names) if (n.endsWith('.jsonl')) see(join(PROJECTS, dir, n));
199
+ }
200
+ return oldest;
201
+ }
202
+
203
+ // 평소 화면이 하루 한 번 지난 날을 월별 보관함(monthly.mjs)에 접는다. 7일 안에 바뀐 기록을 다 읽었을 때만
204
+ // (한도 소진 없음, 남은 바이트 없음. 갱신이 실패한 agy 기록이 있으면 monthly.mjs foldArchive 가 그 날들을 미룬다):
205
+ // 어떤 날 D 에 쓴 기록은 D 이후에 바뀌었으니, 7일 창 안의 날(lo~그제)은 이 장부에 빠짐없이 들어 있다.
206
+ // 이미 접었으면 보관함 파일만 읽고 끝난다. 실패(다른 aitop 이 먼저 씀 등)면 10분 뒤 다시 해 본다.
207
+ let folded = { hi: null, retry: 0 };
208
+ const FOLD_RETRY_MS = 10 * 60_000;
209
+ function foldLedger(books, now) {
210
+ const hi = foldHi(now);
211
+ if (folded.hi === hi || now < folded.retry) return;
212
+ const r = foldArchive(books, { lo: lastDays(DAYS, now).at(-1), hi, now, attach: attachProjects });
213
+ if (r === 'busy' || r === 'error') folded = { hi: null, retry: now + FOLD_RETRY_MS };
214
+ else folded = { hi, retry: 0 };
215
+ }
216
+
169
217
  // 오늘·최근 7일·최근 1시간 합계 (Claude + agy + Codex). 아직 다 읽지 못했으면 loading 에 진행률(0~1).
170
- export function collectLedger({ budget, now = Date.now() } = {}) {
218
+ // fold: 지난 날을 월별 보관함에 접을지 (평소 켠다).
219
+ export function collectLedger({ budget, now = Date.now(), fold = true } = {}) {
171
220
  const g = gather({ budget, now });
172
221
  const { pending, size } = g;
222
+ if (fold && !budget?.exhausted && !pending) foldLedger(g.books, now);
173
223
  const books = g.books.map((b) => b.days);
174
224
  const slots = g.slots;
175
225
  const sum = (keys) => {
@@ -200,4 +250,4 @@ export function collectLedger({ budget, now = Date.now() } = {}) {
200
250
  };
201
251
  }
202
252
 
203
- export const _test = { lastDays };
253
+ export const _test = { lastDays, resetFold: () => (folded = { hi: null, retry: 0 }) };
@@ -7,14 +7,14 @@ import { join } from 'node:path';
7
7
  import { JsonlTail } from '../tail.mjs';
8
8
  import { loadCache, markDirty } from '../cache.mjs';
9
9
  import { codexCost } from '../pricing.mjs';
10
- import { dayDirs } from './codex.mjs';
11
- import { dayKey, lastDays, addSlot, addModel, KEEP_DAYS } from './common.mjs';
10
+ import { allDayDirs } from './codex.mjs';
11
+ import { dayKey, addSlot, addModel, recentDays } from './common.mjs';
12
12
  import { debugIo } from '../log.mjs';
13
13
 
14
- const KIND = 'codex-ledger';
14
+ // 2: 사용량 벡터, 날짜 400일 보관 (#164).
15
+ const KIND = 'codex-ledger2';
15
16
  const DAYS = 7;
16
17
  const LIST_TTL_MS = 30_000;
17
- const SCAN_DAYS = 30;
18
18
 
19
19
  // total_token_usage 를 codexCost 가 받는 모양으로 바꾼다 (input 은 캐시 제외).
20
20
  export function tokensOf(t) {
@@ -62,9 +62,7 @@ export class CodexBook {
62
62
  }
63
63
 
64
64
  snapshot() {
65
- const keep = new Set(lastDays(KEEP_DAYS));
66
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
67
- return { offset: this.tail.lineOffset, model: this.model, last: this.last, days, slots: this.slots };
65
+ return { offset: this.tail.lineOffset, model: this.model, last: this.last, days: recentDays(this.days), slots: this.slots };
68
66
  }
69
67
 
70
68
  apply(x) {
@@ -85,7 +83,7 @@ export class CodexBook {
85
83
  day.tokens += tokens;
86
84
  day.cost += cost?.total ?? 0;
87
85
  day.costNoCache += cost?.noCache ?? 0;
88
- addModel(day, this.model, tokens, cost?.total ?? 0, !cost);
86
+ addModel(day, this.model, tokens, cost?.total ?? 0, !cost, [d.input, d.output, d.cacheRead, 0, 0]);
89
87
  if (!cost) day.unknown = true;
90
88
  addSlot(this.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost);
91
89
  }
@@ -93,13 +91,13 @@ export class CodexBook {
93
91
 
94
92
  let listed = { at: 0, files: [], days: 0 };
95
93
 
96
- // 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로, 30일치 폴더에서 7일 안에 바뀐 기록을 고른다.
97
- // 7일보다 오래된 줄은 날짜 키로 걸러진다. 리포트처럼 days 를 늘리면 폴더도 그만큼 더 거슬러 본다 (30일 리포트면 53일치).
94
+ // 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로, 모든 날짜 폴더에서 days 일 안에 바뀐 기록을 고른다.
95
+ // 오래전에 시작해 최근까지 이어 쓴 세션도 빠지지 않아야 월별 보관함에 빠짐없이 접힌다 (목록은 30초 동안 다시 쓴다).
98
96
  function recentFiles(days = DAYS) {
99
97
  if (listed.days === days && Date.now() - listed.at < LIST_TTL_MS) return listed.files;
100
98
  const cutoff = Date.now() - days * 86400_000;
101
99
  const files = [];
102
- for (const dir of dayDirs(SCAN_DAYS + days - DAYS)) {
100
+ for (const dir of allDayDirs()) {
103
101
  let names = [];
104
102
  try {
105
103
  names = readdirSync(dir);
@@ -30,6 +30,20 @@ export function dayDirs(days = 7) {
30
30
  return dirs;
31
31
  }
32
32
 
33
+ // 남아 있는 날짜 폴더 전부 (sessions/YYYY/MM/DD). 장부는 시작한 날과 상관없이 최근에 바뀐 기록을 모두 봐야 해서 이것을 쓴다.
34
+ export function allDayDirs() {
35
+ const dirs = [];
36
+ const sub = (p) => {
37
+ try {
38
+ return readdirSync(p).filter((n) => /^\d+$/.test(n)).map((n) => join(p, n));
39
+ } catch {
40
+ return [];
41
+ }
42
+ };
43
+ for (const y of sub(ROOT)) for (const m of sub(y)) dirs.push(...sub(m));
44
+ return dirs;
45
+ }
46
+
33
47
  // 날짜 폴더를 매초 다시 훑지 않도록 파일 이름 목록만 잠깐 재사용한다. 수정 시각은 매번 확인한다.
34
48
  const LIST_TTL_MS = 5000;
35
49
  let listed = { at: 0, paths: [] };
@@ -27,17 +27,32 @@ export function lastDays(n, now = Date.now()) {
27
27
  return keys;
28
28
  }
29
29
 
30
- // 장부가 날짜별로 남기는 일수. 기간 리포트(--report)가 볼 수 있는 가장 긴 기간이기도 하다.
31
- // 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 30일치 날짜 합계는 캐시에 남겨 리포트가 다시 읽지 않게 한다.
30
+ // 날짜별 리포트(--report daily)가 볼 수 있는 가장 긴 기간. 리포트는 30일 안에 바뀐 기록을 읽는다.
31
+ // 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 날짜 합계는 캐시에 남겨(STORE_DAYS) 리포트가 다시 읽지 않게 한다.
32
32
  export const KEEP_DAYS = 30;
33
33
 
34
- // 하루 합계(day)에 모델별 몫 { tokens, cost } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
34
+ // 캐시에 날짜별 합계를 남기는 일수. 월별 보관함(monthly.mjs)이 12개월치를 처음 채울 때 다시 읽지 않게 1년 넘게 남긴다.
35
+ // 기록 하나에는 그 기록이 쓰인 날만 있어 길게 남겨도 캐시가 거의 커지지 않는다.
36
+ export const STORE_DAYS = 400;
37
+
38
+ // 날짜별 합계 중 최근 n 일(키 비교) 것만 남긴 복사본.
39
+ export function recentDays(days, n = STORE_DAYS, now = Date.now()) {
40
+ const from = dayKey(now - (n - 1) * 86400_000);
41
+ return Object.fromEntries(Object.entries(days).filter(([k]) => k >= from));
42
+ }
43
+
44
+ // 하루 합계(day)에 모델별 몫 { tokens, cost, u } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
35
45
  // unknown: 가격표에 없는 모델이라 비용을 0 으로 셌을 때. 그 모델 몫에 unknown 을 남겨 리포트가 ? 를 붙인다.
36
- export function addModel(day, model, tokens, cost, unknown = false) {
46
+ // vec: 사용량 벡터(pricing.mjs VEC). fast 면 f 에 따로 더한다 (Claude fast 모드는 단가가 다르다).
47
+ export function addModel(day, model, tokens, cost, unknown = false, vec = null, fast = false) {
37
48
  const m = ((day.models ??= {})[String(model || 'unknown')] ??= { tokens: 0, cost: 0 });
38
49
  m.tokens += tokens;
39
50
  m.cost += cost;
40
51
  if (unknown) m.unknown = true;
52
+ if (vec) {
53
+ const to = fast ? (m.f ??= [0, 0, 0, 0, 0]) : (m.u ??= [0, 0, 0, 0, 0]);
54
+ for (let i = 0; i < to.length; i++) to[i] += vec[i] ?? 0;
55
+ }
41
56
  }
42
57
 
43
58
  // 지출 속도용 짧은 구간 장부. 비용을 5분 칸(키 = 칸 시작 시각 ms)에 모으고, 그 장부에서 가장 새 칸부터