@sejuneoh/aitop 0.25.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
@@ -5,6 +5,8 @@
5
5
 
6
6
  **`top` for your AI coding agents.** A read-only terminal monitor that shows every Claude Code, Codex CLI and Antigravity CLI session on your machine in one live screen: what each one is doing, which ones are waiting for you, and how many tokens they used.
7
7
 
8
+ ![aitop showing Claude Code, Codex and Antigravity sessions (demo data)](https://raw.githubusercontent.com/SejuneOh/aitop/main/docs/demo.gif)
9
+
8
10
  - **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle
9
11
  - **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
10
12
  - **Tokens and cost** per session and for today / last 7 days, at public API list prices
@@ -29,8 +31,9 @@ aitop live screen
29
31
  aitop --all include sessions that ended in the last 24 hours
30
32
  aitop --json print a snapshot as JSON and exit
31
33
  aitop --doctor check which tools and logs aitop can see
32
- aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 $3.1/h)
34
+ aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
33
35
  aitop --report daily daily cost table and exit
36
+ aitop --report monthly monthly cost table (last 12 months) and exit
34
37
  aitop --help all options
35
38
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
36
39
  ```
@@ -41,15 +44,22 @@ In `--json`, `phase` stays the Korean status text in every language (as does `AI
41
44
 
42
45
  ### Daily report
43
46
 
44
- `aitop --report daily` prints tokens and cost (API list price, like the header) per day, newest first, with a total row, then exits. Columns are per tool by default or per model with `--by model`; `--days N` goes back up to 30 days, and `--json` gives the same numbers for scripts. The first run reads up to 30 days of logs, so it can take a while (progress shows on stderr); later runs use the cache.
47
+ `aitop --report daily` prints tokens and cost (API list price, like the header) per day, newest first, with a total row, then exits. Columns are per tool by default, per model with `--by model`, or per project with `--by project` (the last folder name of the working directory: Claude log `cwd`, Codex `turn_context.cwd`, agy workspace; Claude Code worktrees under `<repo>/.claude/worktrees/` count as the repo; `(unknown)` when missing; extra columns beyond the terminal width are merged into `(others)`, `--json` lists all with a `paths` map); `--days N` goes back up to 30 days, and `--json` gives the same numbers for scripts. The first run reads up to 30 days of logs, so it can take a while (progress shows on stderr); later runs use the cache.
45
48
 
46
49
  ```
47
50
  aitop --report daily --by model --days 14
51
+ aitop --report daily --by project --days 7
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
48
58
  ```
49
59
 
50
60
  ### tmux status line
51
61
 
52
- `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of Claude Code sessions waiting for you, 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. `--line=tmux` adds tmux colors, `NO_COLOR` turns them off.
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.
53
63
 
54
64
  ```tmux
55
65
  set -g status-right '#(aitop --line=tmux)'
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, --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,19 +147,27 @@ 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, formatReport, 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, 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
- const r = buildReport(got.books, { by: report.by, days: report.days, now });
165
+ // --by project 표는 터미널 폭(터미널이 아니면 COLUMNS 를 export 한 경우에만 그 폭, 아니면 열 8개)에 맞춰 열을 줄이고 나머지를 하나로 합친다 (--json 은 다 낸다).
166
+ const fit = report.by === 'project' && !args.has('--json');
167
+ const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
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 });
170
+ if (fit && cols) r = fitReport(r, cols);
163
171
  const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
164
172
  process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
165
173
  await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
@@ -195,6 +203,7 @@ const { arrange } = await import('../src/order.mjs');
195
203
  const { frameTimer } = await import('../src/frames.mjs');
196
204
  const { flushCache } = await import('../src/cache.mjs');
197
205
  const { toJson } = await import('../src/json.mjs');
206
+ const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
198
207
  const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
199
208
  const { createNotifier } = await import('../src/notify.mjs');
200
209
  const { onKey, fixFocus } = await import('../src/keys.mjs');
@@ -271,6 +280,8 @@ function select(id) {
271
280
  if (once) {
272
281
  refresh();
273
282
  flushCache();
283
+ // --line 이 작업 중 수를 낼 수 있게 요약을 남긴다 (summary.mjs).
284
+ writeSummary(summarize(view.data.sessions));
274
285
  const size = (v) => (Number(v) > 0 ? Math.floor(Number(v)) : 0);
275
286
  const W = process.stdout.columns || size(process.env.COLUMNS) || 140;
276
287
  const H = process.stdout.rows || size(process.env.LINES) || 40;
@@ -398,8 +409,11 @@ stdin.on('data', (key) => {
398
409
  });
399
410
 
400
411
  let lastFlush = 0;
412
+ // --line 용 요약. 시작 때 기록을 다 읽기 전(ready 전)에는 수가 덜 잡혔을 수 있어 쓰지 않는다.
413
+ const writeSummaryThrottled = createSummaryWriter();
401
414
  function tick() {
402
415
  const shown = refresh({ throttle: true });
416
+ if (loading.ready && view.data) writeSummaryThrottled(view.data.sessions);
403
417
  const more = lastMore;
404
418
  if (more ? Date.now() - lastFlush > LOADING_FLUSH_MS : Date.now() - lastFlush > 15_000) {
405
419
  flushCache();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.25.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,8 +9,10 @@ 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');
15
+ export const CACHE_ROOT = ROOT;
14
16
  const NAME = `v${VERSION}-${PRICE_TAG}`;
15
17
  const DIR = join(ROOT, NAME);
16
18
  export const CACHE_DIR = DIR;
@@ -24,7 +26,9 @@ function removeOldDirs() {
24
26
  cleaned = true;
25
27
  try {
26
28
  for (const d of readdirSync(ROOT)) {
27
- if (d === NAME) continue;
29
+ // summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
30
+ // monthly.json(월별 보관함, monthly.mjs)과 깨져서 옆으로 옮긴 monthly.json.bad-* 도 사용자 기록이라 지우지 않는다.
31
+ if (d === NAME || d === 'summary.json' || d === 'monthly.json' || d.startsWith('monthly.json.bad-')) continue;
28
32
  const p = join(ROOT, d);
29
33
  // 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
30
34
  const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
package/src/i18n.mjs CHANGED
@@ -61,12 +61,16 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
61
61
  aitop 실시간 화면
62
62
  aitop --once 현재 상태를 한 번 출력하고 끝낸다
63
63
  aitop --all 종료된 세션(24시간 이내)도 함께 본다
64
- aitop --line 오늘 비용·응답 대기 수·시간당 지출을 한 줄로 내고 끝낸다 (tmux 상태줄용, 예: $54.13/$50 wait 2 $3.1/h)
64
+ aitop --line 오늘 비용·응답 대기 수·작업 중 수·시간당 지출을 한 줄로 내고 끝낸다 (tmux 상태줄용, 예: $54.13/$50 wait 2 run 3 $3.1/h)
65
65
  --line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 뺀다)
66
- 장부 캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 응답 대기 수는 Claude Code 세션만 센다
66
+ 캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 작업 중 수와 Antigravity 의 대기 수는
67
+ 1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
67
68
  aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
68
- aitop --report daily [--by tool|model] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
69
- 도구별 또는 모델별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
69
+ aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
70
+ 도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
71
+ 프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
72
+ aitop --report monthly [--by tool|model|project] [--months N] [--json] 최근 N달(기본·최대 12)의 달별 표. 지난 날은 캐시 폴더의
73
+ monthly.json 에 달별로 남겨 기록이 지워져도 남는다. 처음 실행은 1년치 기록을 한 번 읽는다. * 이번 달, ~ 일부만 센 달
70
74
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
71
75
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
72
76
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
@@ -101,12 +105,17 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
101
105
  aitop live screen
102
106
  aitop --once print the current state once and exit
103
107
  aitop --all also show sessions that ended in the last 24 hours
104
- aitop --line print today's cost, waiting count and spend per hour on one line and exit (for tmux, e.g. $54.13/$50 wait 2 $3.1/h)
108
+ aitop --line print today's cost, waiting count, running count and spend per hour on one line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
105
109
  --line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end)
106
- Reads only the cache. With no cache it prints ... after 1.5 seconds. The waiting count covers Claude Code sessions only
110
+ Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
111
+ show only when the live screen, --once or --json left a summary in the last minute
107
112
  aitop --json print the session list and usage totals as JSON once (works with --all)
108
- aitop --report daily [--by tool|model] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
109
- (default and max 30) by tool or by model, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
113
+ aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
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
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
110
119
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
111
120
  aitop --bell ring the terminal bell when a session starts waiting for you
112
121
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
@@ -191,18 +200,25 @@ export const STRINGS = {
191
200
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
192
201
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
193
202
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
194
- 'opt.reportMissing': '--report 값이 없습니다 (daily)',
195
- 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
196
- 'opt.byMissing': '--by 값이 없습니다 (tool 또는 model)',
197
- 'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool 또는 model)',
203
+ 'opt.reportMissing': '--report 값이 없습니다 (daily 또는 monthly)',
204
+ 'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily 또는 monthly)',
205
+ 'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
206
+ 'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
198
207
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
199
208
  'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
200
- '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 와 함께 쓴다',
201
214
 
202
215
  // 기간 리포트 (--report daily). 도구·모델 이름은 번역하지 않는다.
203
216
  'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
204
217
  'report.by.tool': '도구별',
205
218
  'report.by.model': '모델별',
219
+ 'report.by.project': '프로젝트별',
220
+ 'report.unknown': '(모름)',
221
+ 'report.others': '(그 외)',
206
222
  'report.date': '날짜',
207
223
  'report.total': '합계',
208
224
  'report.empty': '이 기간에 기록된 사용량이 없습니다',
@@ -210,6 +226,13 @@ export const STRINGS = {
210
226
  'report.partial': '시간 상한 안에 기록을 다 읽지 못해 일부만 셌습니다. 다시 실행하면 이어 읽습니다',
211
227
  'report.progress': '사용량 장부 읽는 중 {pct}% ({s}초)',
212
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 이 아니라 모름)',
213
236
 
214
237
  'cfg.notFile': '설정 파일이 일반 파일이 아니라 읽지 않습니다',
215
238
  'cfg.tooBig': '설정 파일이 {kb}KB 를 넘어 읽지 않습니다',
@@ -412,7 +435,7 @@ export const STRINGS = {
412
435
  'hopt.showRequests': '응답 대기 요청 전체를 상세·--json 에',
413
436
  'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
414
437
  'hopt.debug': '디버그 로그를 남긴다',
415
- 'hopt.line': '오늘 비용·대기 수·시간당 지출 한 줄 (tmux 상태줄용)',
438
+ 'hopt.line': '오늘 비용·대기·작업 중 수·시간당 지출 한 줄 (tmux 상태줄용)',
416
439
  'hopt.printConfig': '설정 값과 출처, 설정 파일 위치',
417
440
  'hopt.ambiguous': '·→─● 를 2칸으로 그리는 터미널용 (1칸 기호로)',
418
441
  'set.budget': '예산 {v}',
@@ -534,17 +557,24 @@ export const STRINGS = {
534
557
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
535
558
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
536
559
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
537
- 'opt.reportMissing': '--report needs a value (daily)',
538
- 'opt.reportBad': 'bad --report value {value} (daily)',
539
- 'opt.byMissing': '--by needs a value (tool or model)',
540
- 'opt.byBad': 'bad --by value {value} (tool or model)',
560
+ 'opt.reportMissing': '--report needs a value (daily or monthly)',
561
+ 'opt.reportBad': 'bad --report value {value} (daily or monthly)',
562
+ 'opt.byMissing': '--by needs a value (tool, model or project)',
563
+ 'opt.byBad': 'bad --by value {value} (tool, model or project)',
541
564
  'opt.daysMissing': '--days needs a value (number of days)',
542
565
  'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
543
- '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',
544
571
 
545
572
  'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
546
573
  'report.by.tool': 'by tool',
547
574
  'report.by.model': 'by model',
575
+ 'report.by.project': 'by project',
576
+ 'report.unknown': '(unknown)',
577
+ 'report.others': '(others)',
548
578
  'report.date': 'Date',
549
579
  'report.total': 'Total',
550
580
  'report.empty': 'No usage recorded in this period',
@@ -552,6 +582,13 @@ export const STRINGS = {
552
582
  'report.partial': 'Could not read all logs within the time limit, so this is partial. Run again to continue',
553
583
  'report.progress': 'Reading usage logs {pct}% ({s}s)',
554
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)',
555
592
 
556
593
  'cfg.notFile': 'config file is not a regular file, not reading it',
557
594
  'cfg.tooBig': 'config file is over {kb}KB, not reading it',
package/src/line.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 $3.1/h
1
+ // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 run 3 $3.1/h
2
2
  // 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
3
3
  // 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
4
4
  // 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
@@ -12,7 +12,8 @@ export const CAP_MS = 1500;
12
12
  export const PENDING = '...';
13
13
 
14
14
  // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
15
- const COLOURS = { normal: { waiting: 'colour214', money: 'colour154' }, colorBlind: { waiting: 'colour226', money: 'colour75' } };
15
+ // 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
16
+ const COLOURS = { normal: { waiting: 'colour214', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', money: 'colour75', running: 'colour250' } };
16
17
 
17
18
  // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
18
19
  export function lineOption(argv) {
@@ -50,29 +51,40 @@ const rate = (x) => (x >= 100 ? `$${x.toFixed(0)}` : x >= 1 ? `$${x.toFixed(1)}`
50
51
  // 표시하면 0 으로 보이는 값은 0 으로 본다.
51
52
  const zero = (x) => !(Number(x) >= 0.005);
52
53
 
53
- // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수), perHour(최근 1시간 지출).
54
+ // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
55
+ // running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
54
56
  // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
55
57
  // width 를 넘으면 뒤 항목부터 뺀다. mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다.
56
- export function formatLine({ today = 0, budgetDay = null, waiting = 0, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
58
+ export function formatLine({ today = 0, budgetDay = null, waiting = 0, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
57
59
  const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
58
60
  const parts = [];
59
61
  const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
60
62
  if (!zero(today) || hasBudget) parts.push({ text: `${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`, fg: c.money });
61
63
  if (waiting > 0) parts.push({ text: `wait ${waiting}`, fg: c.waiting });
64
+ if (running > 0) parts.push({ text: `run ${running}`, fg: c.running });
62
65
  if (!zero(perHour)) parts.push({ text: `${rate(perHour)}/h`, fg: c.money });
63
66
  while (parts.length && parts.map((p) => p.text).join(' ').length > width) parts.pop();
64
67
  const styled = mode === 'tmux' && !noColor;
65
68
  return parts.map((p) => (styled ? `#[fg=${p.fg}]${p.text}#[default]` : p.text)).join(' ');
66
69
  }
67
70
 
68
- // 장부 캐시와 새로 붙은 줄만 읽어 값을 모은다 (세션 화면용 기록 전체·프로세스 목록은 읽지 않는다).
71
+ // 요약 파일(summary.mjs)에서 작업 중 수와 응답 대기 수를 고른다. claudeWaiting 은 세션 파일에서 지금 센 Claude 대기 수.
72
+ // 대기는 Claude 몫을 늘 지금 값으로 쓰고(요약은 최대 1분 늦다), 다른 도구 몫(지금은 Antigravity)만 요약에서 더한다. 요약이 없으면 Claude 몫만.
73
+ // 작업 중은 요약에만 있으므로 요약이 없거나 오래됐으면 null (줄에서 뺀다).
74
+ export function pickCounts(summary, claudeWaiting) {
75
+ if (!summary) return { waiting: claudeWaiting, running: null };
76
+ return { waiting: claudeWaiting + summary.waitingOther, running: summary.running };
77
+ }
78
+
79
+ // 장부 캐시와 새로 붙은 줄, 요약 파일만 읽어 값을 모은다 (세션 화면용 기록 전체·프로세스 목록은 읽지 않는다).
69
80
  // 시간 상한 안에 다 읽지 못했거나 아직 집계 중이면 null. 읽은 만큼은 aitop 캐시에 남아 다음 실행이 이어 읽는다.
70
81
  export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
71
82
  const { createBudget } = await import('./tail.mjs');
72
83
  const { collectLedger } = await import('./sources/claude-ledger.mjs');
73
84
  const { claudeWaitingCount } = await import('./sources/claude.mjs');
85
+ const { readSummary } = await import('./summary.mjs');
74
86
  const budget = createBudget(Infinity, capMs);
75
87
  const usage = collectLedger({ budget, now });
76
88
  if (budget.exhausted || usage.loading != null) return null;
77
- return { today: usage.today.cost, waiting: claudeWaitingCount(), perHour: usage.lastHour.cost };
89
+ return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaitingCount()), perHour: usage.lastHour.cost };
78
90
  }
@@ -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
+ }