@sejuneoh/aitop 0.25.0 → 0.26.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,7 +31,7 @@ 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
34
36
  aitop --help all options
35
37
  aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
@@ -41,15 +43,16 @@ In `--json`, `phase` stays the Korean status text in every language (as does `AI
41
43
 
42
44
  ### Daily report
43
45
 
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.
46
+ `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
47
 
46
48
  ```
47
49
  aitop --report daily --by model --days 14
50
+ aitop --report daily --by project --days 7
48
51
  ```
49
52
 
50
53
  ### tmux status line
51
54
 
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.
55
+ `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
56
 
54
57
  ```tmux
55
58
  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, --by tool|model|project, --days <N> 은 reportOption 이 꺼낸다.
45
45
  const report = reportOption(line.rest);
46
46
  if (report.error) {
47
47
  process.stderr.write(`aitop: ${report.error}\n`);
@@ -149,17 +149,21 @@ if (line.mode) {
149
149
  // --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
150
150
  // 처음 실행은 30일치 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
151
151
  if (report.kind) {
152
- const { buildReport, collectReport, formatReport, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
152
+ const { buildReport, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
153
153
  const { flushCache } = await import('../src/cache.mjs');
154
154
  if (report.capped) process.stderr.write(`aitop: ${t('report.capped', { n: MAX_DAYS })}\n`);
155
155
  const progress = progressWriter();
156
156
  const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
157
157
  const now = Date.now();
158
- const got = await collectReport({ days: report.days, maxMs, now, onProgress: progress.update });
158
+ const got = await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
159
159
  progress.done();
160
160
  flushCache();
161
161
  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 });
162
+ // --by project 표는 터미널 폭(터미널이 아니면 COLUMNS 를 export 한 경우에만 그 폭, 아니면 열 8개)에 맞춰 열을 줄이고 나머지를 하나로 합친다 (--json 은 다 낸다).
163
+ const fit = report.by === 'project' && !args.has('--json');
164
+ 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 });
166
+ if (fit && cols) r = fitReport(r, cols);
163
167
  const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
164
168
  process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
165
169
  await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
@@ -195,6 +199,7 @@ const { arrange } = await import('../src/order.mjs');
195
199
  const { frameTimer } = await import('../src/frames.mjs');
196
200
  const { flushCache } = await import('../src/cache.mjs');
197
201
  const { toJson } = await import('../src/json.mjs');
202
+ const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
198
203
  const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
199
204
  const { createNotifier } = await import('../src/notify.mjs');
200
205
  const { onKey, fixFocus } = await import('../src/keys.mjs');
@@ -271,6 +276,8 @@ function select(id) {
271
276
  if (once) {
272
277
  refresh();
273
278
  flushCache();
279
+ // --line 이 작업 중 수를 낼 수 있게 요약을 남긴다 (summary.mjs).
280
+ writeSummary(summarize(view.data.sessions));
274
281
  const size = (v) => (Number(v) > 0 ? Math.floor(Number(v)) : 0);
275
282
  const W = process.stdout.columns || size(process.env.COLUMNS) || 140;
276
283
  const H = process.stdout.rows || size(process.env.LINES) || 40;
@@ -398,8 +405,11 @@ stdin.on('data', (key) => {
398
405
  });
399
406
 
400
407
  let lastFlush = 0;
408
+ // --line 용 요약. 시작 때 기록을 다 읽기 전(ready 전)에는 수가 덜 잡혔을 수 있어 쓰지 않는다.
409
+ const writeSummaryThrottled = createSummaryWriter();
401
410
  function tick() {
402
411
  const shown = refresh({ throttle: true });
412
+ if (loading.ready && view.data) writeSummaryThrottled(view.data.sessions);
403
413
  const more = lastMore;
404
414
  if (more ? Date.now() - lastFlush > LOADING_FLUSH_MS : Date.now() - lastFlush > 15_000) {
405
415
  flushCache();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cache.mjs CHANGED
@@ -11,6 +11,7 @@ import { debug, debugIo } from './log.mjs';
11
11
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
12
12
  const VERSION = 14;
13
13
  const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
14
+ export const CACHE_ROOT = ROOT;
14
15
  const NAME = `v${VERSION}-${PRICE_TAG}`;
15
16
  const DIR = join(ROOT, NAME);
16
17
  export const CACHE_DIR = DIR;
@@ -24,7 +25,8 @@ function removeOldDirs() {
24
25
  cleaned = true;
25
26
  try {
26
27
  for (const d of readdirSync(ROOT)) {
27
- if (d === NAME) continue;
28
+ // summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
29
+ if (d === NAME || d === 'summary.json') continue;
28
30
  const p = join(ROOT, d);
29
31
  // 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
30
32
  const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
package/src/i18n.mjs CHANGED
@@ -61,12 +61,14 @@ 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
+ 프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
70
72
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
71
73
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
72
74
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
@@ -101,12 +103,14 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
101
103
  aitop live screen
102
104
  aitop --once print the current state once and exit
103
105
  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)
106
+ 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
107
  --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
108
+ Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
109
+ show only when the live screen, --once or --json left a summary in the last minute
107
110
  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
111
+ aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
112
+ (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
+ A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
110
114
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
111
115
  aitop --bell ring the terminal bell when a session starts waiting for you
112
116
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
@@ -193,8 +197,8 @@ export const STRINGS = {
193
197
  'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
194
198
  'opt.reportMissing': '--report 값이 없습니다 (daily)',
195
199
  'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
196
- 'opt.byMissing': '--by 값이 없습니다 (tool 또는 model)',
197
- 'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool 또는 model)',
200
+ 'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
201
+ 'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
198
202
  'opt.daysMissing': '--days 값이 없습니다 (일 수)',
199
203
  'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
200
204
  'opt.reportOnly': '--by, --days 는 --report 와 함께 쓴다',
@@ -203,6 +207,9 @@ export const STRINGS = {
203
207
  'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
204
208
  'report.by.tool': '도구별',
205
209
  'report.by.model': '모델별',
210
+ 'report.by.project': '프로젝트별',
211
+ 'report.unknown': '(모름)',
212
+ 'report.others': '(그 외)',
206
213
  'report.date': '날짜',
207
214
  'report.total': '합계',
208
215
  'report.empty': '이 기간에 기록된 사용량이 없습니다',
@@ -412,7 +419,7 @@ export const STRINGS = {
412
419
  'hopt.showRequests': '응답 대기 요청 전체를 상세·--json 에',
413
420
  'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
414
421
  'hopt.debug': '디버그 로그를 남긴다',
415
- 'hopt.line': '오늘 비용·대기 수·시간당 지출 한 줄 (tmux 상태줄용)',
422
+ 'hopt.line': '오늘 비용·대기·작업 중 수·시간당 지출 한 줄 (tmux 상태줄용)',
416
423
  'hopt.printConfig': '설정 값과 출처, 설정 파일 위치',
417
424
  'hopt.ambiguous': '·→─● 를 2칸으로 그리는 터미널용 (1칸 기호로)',
418
425
  'set.budget': '예산 {v}',
@@ -536,8 +543,8 @@ export const STRINGS = {
536
543
  'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
537
544
  'opt.reportMissing': '--report needs a value (daily)',
538
545
  '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)',
546
+ 'opt.byMissing': '--by needs a value (tool, model or project)',
547
+ 'opt.byBad': 'bad --by value {value} (tool, model or project)',
541
548
  'opt.daysMissing': '--days needs a value (number of days)',
542
549
  'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
543
550
  'opt.reportOnly': '--by and --days only work with --report',
@@ -545,6 +552,9 @@ export const STRINGS = {
545
552
  'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
546
553
  'report.by.tool': 'by tool',
547
554
  'report.by.model': 'by model',
555
+ 'report.by.project': 'by project',
556
+ 'report.unknown': '(unknown)',
557
+ 'report.others': '(others)',
548
558
  'report.date': 'Date',
549
559
  'report.total': 'Total',
550
560
  'report.empty': 'No usage recorded in this period',
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
  }
package/src/report.mjs CHANGED
@@ -3,12 +3,18 @@
3
3
  // 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
4
4
  // 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
5
5
  import { t } from './i18n.mjs';
6
- import { fmtTokens, pad, stripControl, width } from './text.mjs';
6
+ import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
7
7
  import { money } from './line.mjs';
8
8
  import { KEEP_DAYS, lastDays } from './sources/common.mjs';
9
+ import { projectLabels } from './sources/projects.mjs';
9
10
 
10
11
  export const KINDS = ['daily'];
11
- export const BY = ['tool', 'model'];
12
+ export const BY = ['tool', 'model', 'project'];
13
+ // --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
14
+ export const UNKNOWN = '(unknown)';
15
+ export const OTHERS = '(others)';
16
+ // 표 머리글 한 칸의 최대 폭 (긴 프로젝트·모델 이름은 줄인다).
17
+ const HEAD_MAX = 24;
12
18
  export const MAX_DAYS = KEEP_DAYS;
13
19
  export const DEFAULT_DAYS = KEEP_DAYS;
14
20
  // 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
@@ -20,7 +26,7 @@ const PROGRESS_AFTER_MS = 400;
20
26
  const FLUSH_MS = 3000;
21
27
  const TOOLS = ['claude', 'codex', 'agy'];
22
28
 
23
- // --report <kind>, --report=<kind>, --by <tool|model>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
29
+ // --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
24
30
  // kind 는 --report 를 주지 않았으면 null. --by·--days 는 --report 와 함께일 때만 받는다. capped: --days 를 30으로 줄였는지.
25
31
  export function reportOption(argv) {
26
32
  let kind = null;
@@ -67,21 +73,29 @@ const add = (a, tokens, cost, unpriced) => {
67
73
  if (unpriced) a.unpriced = true;
68
74
  };
69
75
 
70
- // books: collectDaily 의 [{ tool, days }]. 최근 days 일의 날짜 줄(오늘부터 거꾸로)과 열(도구 또는 모델), 합계를 만든다.
71
- // 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
76
+ // 폭을 모를 때(파이프) --by project 표의 열 수 상한.
77
+ export const PIPE_COLUMNS = 8;
78
+
79
+ // books: collectDaily 의 [{ tool, days }] (--by project 면 project 도). 최근 days 일의 날짜 줄(오늘부터 거꾸로)과
80
+ // 열(도구, 모델 또는 프로젝트), 합계를 만든다. 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
81
+ // maxColumns: 열이 이보다 많으면 앞의 maxColumns-1 개만 두고 나머지를 OTHERS 로 합친다 (--by project 표만).
72
82
  // unpriced: 가격표에 없는 모델이 끼어 비용이 실제보다 적게 잡혔을 수 있는지.
73
- export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now() } = {}) {
83
+ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now(), maxColumns = Infinity } = {}) {
74
84
  const dates = lastDays(days, now);
85
+ // 프로젝트 경로 → 짧은 이름. paths 는 거꾸로 (--json 에 이름별 경로를 둔다).
86
+ const labels = by === 'project' ? projectLabels(new Set(books.map((b) => b.project).filter(Boolean))) : new Map();
87
+ const paths = {};
75
88
  const rows = dates.map((date) => ({ date, tokens: 0, cost: 0, unpriced: false, items: {} }));
76
89
  const at = new Map(rows.map((r) => [r.date, r]));
77
90
  const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
78
91
  let unpriced = false;
79
- for (const { tool, days: book } of books) {
92
+ for (const { tool, project, days: book } of books) {
80
93
  for (const [date, d] of Object.entries(book ?? {})) {
81
94
  const row = at.get(date);
82
95
  if (!row) continue;
83
96
  if (d.unknown) unpriced = true;
84
- const parts = by === 'model' ? Object.entries(d.models ?? {}) : [[tool, d]];
97
+ const parts = by === 'model' ? Object.entries(d.models ?? {}) : by === 'project' ? [[labels.get(project) ?? UNKNOWN, d]] : [[tool, d]];
98
+ if (by === 'project' && project) paths[labels.get(project)] = project;
85
99
  for (const [name, x] of parts) {
86
100
  add((row.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
87
101
  add((total.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
@@ -95,7 +109,46 @@ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Dat
95
109
  .filter(([, x]) => x.tokens > 0 || x.cost > 0)
96
110
  .sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
97
111
  .map(([name]) => name);
98
- return { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
112
+ 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 };
114
+ if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
115
+ return out;
116
+ }
117
+
118
+ // 표 r 을 열 keep 개 + OTHERS 로 접은 복사본 (r 은 그대로).
119
+ function folded(r, keep) {
120
+ const copy = (o) => ({ ...o, items: { ...o.items } });
121
+ const out = { ...r, columns: [...r.columns], rows: r.rows.map(copy), total: copy(r.total) };
122
+ foldOthers(out.columns, keep, [...out.rows, out.total]);
123
+ if (r.paths) out.paths = Object.fromEntries(Object.entries(r.paths).filter(([c]) => out.columns.includes(c)));
124
+ return out;
125
+ }
126
+
127
+ // 표 줄이 터미널 폭 cols 안에 들어가도록, 실제 칸 폭(머리글과 값 중 긴 쪽)을 재어 들어가는 만큼만 열을 남기고 나머지를 OTHERS 로 접는다.
128
+ // 한 열도 안 들어가면 열 1개 + OTHERS 로 낸다.
129
+ export function fitReport(r, cols) {
130
+ // 열이 1개 이하면 접어도 좁아지지 않는다 (빈 OTHERS 만 붙는다).
131
+ if (!(cols > 0) || r.columns.length <= 1 || tableWidth(r) <= cols) return r;
132
+ for (let keep = r.columns.length - 1; keep >= 1; keep--) {
133
+ const f = folded(r, keep);
134
+ if (tableWidth(f) <= cols) return f;
135
+ }
136
+ return folded(r, 1);
137
+ }
138
+
139
+ // 앞의 keep 개 뒤 열들을 OTHERS 한 열로 합친다 (columns 와 각 줄의 items 를 고친다).
140
+ function foldOthers(columns, keep, lines) {
141
+ const rest = columns.splice(keep);
142
+ columns.push(OTHERS);
143
+ for (const o of lines) {
144
+ let sum = null;
145
+ for (const c of rest) {
146
+ const x = o.items[c];
147
+ delete o.items[c];
148
+ if (x) add((sum ??= zero()), x.tokens, x.cost, x.unpriced);
149
+ }
150
+ if (sum) o.items[OTHERS] = sum;
151
+ }
99
152
  }
100
153
 
101
154
  // --json 모양: 키는 영어, 값은 숫자만 (날짜·이름은 문자열). partial: 시간 상한 때문에 덜 읽었는지.
@@ -113,6 +166,7 @@ export function reportJson(r, version, { partial = false } = {}) {
113
166
  partial,
114
167
  unpriced: r.unpriced,
115
168
  columns: r.columns,
169
+ ...(r.paths ? { paths: r.paths } : {}),
116
170
  rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
117
171
  total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
118
172
  };
@@ -121,15 +175,28 @@ export function reportJson(r, version, { partial = false } = {}) {
121
175
  // 칸 하나: '1.2M $3.40'. 토큰이 없으면 '-'. 가격표에 없는 모델이 끼었으면 화면 헤더처럼 비용 뒤에 ? 를 붙인다 ('$12.30?').
122
176
  const cell = (x) => (x && (x.tokens > 0 || x.cost > 0) ? `${fmtTokens(Math.round(x.tokens))} ${money(x.cost)}${x.unpriced ? '?' : ''}` : '-');
123
177
 
124
- // 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다. 도구 이름과 모델 이름은 그대로 쓴다.
125
- export function formatReport(r, { partial = false } = {}) {
126
- // 모델 이름은 기록에서 온 글이라 제어문자를 지운다.
127
- const head = [t('report.date'), ...r.columns.map((c) => stripControl(c)), t('report.total')];
178
+ // 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다. 도구·모델·프로젝트 이름은 그대로 쓴다.
179
+ const colName = (c) => (c === UNKNOWN ? t('report.unknown') : c === OTHERS ? t('report.others') : truncate(stripControl(c), HEAD_MAX));
180
+ // 표의 머리글·날짜 줄·합계 줄 글과 칸 폭 w.
181
+ function table(r) {
182
+ // 모델·프로젝트 이름은 기록에서 온 글이라 제어문자를 지운다.
183
+ const head = [t('report.date'), ...r.columns.map(colName), t('report.total')];
128
184
  const line = (label, o) => [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)];
129
185
  const body = r.rows.map((x) => line(x.date, x));
130
186
  const foot = line(t('report.total'), r.total);
131
187
  const all = [head, ...body, foot];
132
188
  const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
189
+ return { head, body, foot, w };
190
+ }
191
+
192
+ // 표 한 줄의 폭 (칸 사이는 두 칸).
193
+ const tableWidth = (r) => {
194
+ const { w } = table(r);
195
+ return w.reduce((a, n) => a + n, 0) + 2 * (w.length - 1);
196
+ };
197
+
198
+ export function formatReport(r, { partial = false } = {}) {
199
+ const { head, body, foot, w } = table(r);
133
200
  const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
134
201
  const rule = w.map((n) => '-'.repeat(n)).join(' ');
135
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)];
@@ -141,23 +208,26 @@ export function formatReport(r, { partial = false } = {}) {
141
208
 
142
209
  // 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
143
210
  // 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
144
- export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), onProgress = () => {} } = {}) {
211
+ // by 가 'project' 면 장부마다 project(작업 폴더)를 붙인다.
212
+ export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {} } = {}) {
145
213
  const { createBudget } = await import('./tail.mjs');
146
214
  const { collectDaily } = await import('./sources/claude-ledger.mjs');
147
215
  const { flushCache } = await import('./cache.mjs');
216
+ const { attachProjects } = await import('./sources/projects.mjs');
217
+ const done = (books, partial) => ({ books: by === 'project' ? attachProjects(books) : books, partial });
148
218
  const start = Date.now();
149
219
  let lastFlush = start;
150
220
  for (;;) {
151
221
  const budget = createBudget(Infinity, STEP_MS);
152
222
  const r = collectDaily({ budget, now, days });
153
223
  const spent = Date.now() - start;
154
- if (!budget.exhausted) return { books: r.books, partial: false };
224
+ if (!budget.exhausted) return done(r.books, false);
155
225
  onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
156
226
  if (Date.now() - lastFlush > FLUSH_MS) {
157
227
  flushCache();
158
228
  lastFlush = Date.now();
159
229
  }
160
- if (spent >= maxMs) return { books: r.books, partial: true };
230
+ if (spent >= maxMs) return done(r.books, true);
161
231
  // 다른 일(신호 처리 등)이 돌 틈을 준다.
162
232
  await new Promise((resolve) => setImmediate(resolve));
163
233
  }
@@ -134,7 +134,7 @@ const books = new Map();
134
134
  // 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size).
135
135
  // node:sqlite 를 못 쓰는 Node 에서는 비어 있다 (agy 는 프로세스만 보인다).
136
136
  export function collectAgyLedger({ budget, days = DAYS } = {}) {
137
- const out = { days: [], slots: [], pending: 0, size: 0 };
137
+ const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
138
138
  if (!loadSqlite() || !existsSync(join(AGY_ROOT, 'conversations'))) return out;
139
139
  const files = recentFiles(days);
140
140
  const keep = new Set(files);
@@ -147,6 +147,7 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
147
147
  out.size += size;
148
148
  if (!b.complete) out.pending += size;
149
149
  out.days.push(b.days);
150
+ out.paths.push(p);
150
151
  out.slots.push(b.slots);
151
152
  }
152
153
  return out;
@@ -147,12 +147,13 @@ function gather({ budget, now, days = DAYS }) {
147
147
  ['agy', collectAgyLedger({ budget, now, days })],
148
148
  ['codex', collectCodexLedger({ budget, days })],
149
149
  ];
150
- const books = [...trackers.values()].map((t) => ({ tool: 'claude', days: t.days }));
150
+ // path: 리포트 --by project 가 기록 파일에서 프로젝트를 찾을 때 쓴다 (projects.mjs).
151
+ const books = [...trackers.entries()].map(([path, t]) => ({ tool: 'claude', path, days: t.days }));
151
152
  const slots = [...trackers.values()].map((t) => t.slots);
152
153
  for (const [tool, o] of others) {
153
154
  pending += o.pending;
154
155
  size += o.size;
155
- books.push(...o.days.map((d) => ({ tool, days: d })));
156
+ books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d })));
156
157
  slots.push(...o.slots);
157
158
  }
158
159
  return { books, slots, pending, size };
@@ -123,7 +123,7 @@ const books = new Map();
123
123
  // 기록마다 날짜별 합계(days)와 5분 칸(slots), 아직 읽지 않은 크기(pending)·전체 크기(size).
124
124
  // days: 최근 며칠 안에 바뀐 기록을 볼지 (평소 7일, 리포트는 더 길게).
125
125
  export function collectCodexLedger({ budget, days = DAYS } = {}) {
126
- const out = { days: [], slots: [], pending: 0, size: 0 };
126
+ const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
127
127
  const files = recentFiles(days);
128
128
  const keep = new Set(files);
129
129
  for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
@@ -134,6 +134,7 @@ export function collectCodexLedger({ budget, days = DAYS } = {}) {
134
134
  out.pending += b.pending;
135
135
  out.size += b.tail.size;
136
136
  out.days.push(b.days);
137
+ out.paths.push(p);
137
138
  out.slots.push(b.slots);
138
139
  }
139
140
  return out;
@@ -0,0 +1,179 @@
1
+ // 기간 리포트 --by project 용: 기록 파일 하나가 어느 프로젝트(작업 폴더)의 것인지 찾는다.
2
+ // Claude 는 기록 앞부분 줄의 cwd (없으면 projects/ 아래 폴더 이름), Codex 는 turn_context.cwd (없으면 session_meta.cwd),
3
+ // agy 는 conversation_summaries.db 의 workspace_uris (서브에이전트는 부모 대화의 것) 를 쓴다. 못 찾으면 null.
4
+ // agy 기록은 immutable 로 열어 -wal 에만 있는 막 생긴 대화는 아직 안 보이므로, 그 대화는 (unknown) 으로 나올 수 있다.
5
+ // 장부 캐시 모양은 그대로 두고, 리포트를 낼 때만 파일 앞부분을 조금 읽는다.
6
+ import { openSync, readSync, closeSync, statSync } from 'node:fs';
7
+ import { basename, join, relative, sep } from 'node:path';
8
+ import { homedir } from 'node:os';
9
+ import { AGY_ROOT, cwdOf } from './antigravity.mjs';
10
+ import { openReadOnly } from '../sqlite.mjs';
11
+ import { debugIo } from '../log.mjs';
12
+
13
+ const HOME = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
14
+ const PROJECTS = join(HOME, 'projects');
15
+ // 앞부분에서 cwd 를 찾을 때 읽는 최대 크기. Codex 의 첫 줄(session_meta)은 지침 글이 들어 있어 길 수 있다.
16
+ const HEAD_BYTES = 256 * 1024;
17
+ const heads = new Map();
18
+ // 앞부분을 읽는 버퍼. scanHead 는 동기 함수라 하나를 돌려 쓴다.
19
+ const BUF = Buffer.allocUnsafe(HEAD_BYTES);
20
+
21
+ // 파일 앞부분의 완성된 줄을 차례로 pick 에 넘긴다. pick 이 true 를 돌려주면 멈춘다.
22
+ // 대개 첫 몇 줄에 있으므로 CHUNK 씩 읽고, 찾으면 더 읽지 않는다.
23
+ const CHUNK = 16 * 1024;
24
+ function scanHead(path, pick) {
25
+ let fd;
26
+ try {
27
+ fd = openSync(path, 'r');
28
+ const buf = BUF;
29
+ let len = 0;
30
+ let done = 0;
31
+ while (len < HEAD_BYTES) {
32
+ const n = readSync(fd, buf, len, Math.min(CHUNK, HEAD_BYTES - len), len);
33
+ if (n <= 0) break;
34
+ len += n;
35
+ const end = buf.lastIndexOf(10, len - 1);
36
+ if (end < done) continue;
37
+ for (const line of buf.toString('utf8', done, end).split('\n')) {
38
+ let x;
39
+ try {
40
+ x = JSON.parse(line);
41
+ } catch {
42
+ continue;
43
+ }
44
+ if (pick(x)) return;
45
+ }
46
+ done = end + 1;
47
+ }
48
+ } catch (e) {
49
+ debugIo('report', 'log head read failed', e, path);
50
+ } finally {
51
+ if (fd != null) closeSync(fd);
52
+ }
53
+ }
54
+
55
+ // 같은 파일(inode)이면 다시 읽지 않는다.
56
+ function memo(path, find) {
57
+ let ino = null;
58
+ try {
59
+ ino = statSync(path).ino;
60
+ } catch {}
61
+ const c = heads.get(path);
62
+ if (c && c.ino === ino) return c.cwd;
63
+ const cwd = find();
64
+ heads.set(path, { ino, cwd });
65
+ return cwd;
66
+ }
67
+
68
+ // Claude 기록 앞부분 줄의 cwd. 없으면 null.
69
+ export function claudeProject(path) {
70
+ return memo(path, () => {
71
+ let cwd = null;
72
+ scanHead(path, (x) => typeof x?.cwd === 'string' && x.cwd && (cwd = x.cwd));
73
+ return cwd;
74
+ });
75
+ }
76
+
77
+ // Claude 가 projects/ 아래 폴더 이름을 만드는 방식: 영문·숫자 밖의 글자를 - 로 바꾼다.
78
+ export const encodeFolder = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, '-');
79
+
80
+ // cwd 를 못 찾았을 때 쓰는 projects/ 바로 아래 폴더 이름. 작업 트리 꼴(--claude-worktrees-<이름>)이면 그 부분을 뗀다.
81
+ export function claudeFolder(path, root = PROJECTS) {
82
+ const rel = relative(root, path);
83
+ const dir = rel.split(sep)[0];
84
+ if (!dir || rel.startsWith('..') || dir === rel) return null;
85
+ return dir.replace(/--claude-worktrees-.*$/, '') || dir;
86
+ }
87
+
88
+ export function codexProject(path) {
89
+ return memo(path, () => {
90
+ let meta = null;
91
+ let turn = null;
92
+ scanHead(path, (x) => {
93
+ const p = x?.payload;
94
+ if (x?.type === 'session_meta' && typeof p?.cwd === 'string') meta ??= p.cwd;
95
+ if (x?.type === 'turn_context' && typeof p?.cwd === 'string') turn = p.cwd;
96
+ return turn != null;
97
+ });
98
+ return turn || meta || null;
99
+ });
100
+ }
101
+
102
+ // 대화 id → 작업 폴더. 서브에이전트는 작업 폴더가 비어 있으면 부모를 따라 올라간다. 리포트 한 번에 한 번만 읽는다.
103
+ export function agyWorkspaces(root = AGY_ROOT) {
104
+ const out = new Map();
105
+ let db;
106
+ try {
107
+ db = openReadOnly(join(root, 'conversation_summaries.db'));
108
+ if (!db) return out;
109
+ const rows = db.prepare('select conversation_id id, parent_conversation_id parent, workspace_uris ws from conversation_summaries').all();
110
+ const byId = new Map(rows.map((r) => [r.id, r]));
111
+ for (const r of rows) {
112
+ let cur = r;
113
+ let cwd = cwdOf(cur.ws);
114
+ for (let i = 0; !cwd && cur?.parent && i < 10; i++) {
115
+ cur = byId.get(cur.parent);
116
+ cwd = cur ? cwdOf(cur.ws) : null;
117
+ }
118
+ out.set(r.id, cwd);
119
+ }
120
+ } catch (e) {
121
+ debugIo('report', 'agy workspaces read failed', e);
122
+ } finally {
123
+ db?.close();
124
+ }
125
+ return out;
126
+ }
127
+
128
+ // Claude Code 가 만든 작업 트리(<저장소>/.claude/worktrees/<이름>) 는 저장소 하나로 본다.
129
+ // 에이전트마다 작업 트리가 생겨 그대로 두면 열이 수십 개로 갈라진다.
130
+ export function projectRoot(cwd) {
131
+ if (!cwd) return null;
132
+ const m = /^(.+?)[\\/]\.claude[\\/]worktrees[\\/][^\\/]+(?:[\\/].*)?$/.exec(cwd);
133
+ return m ? m[1] : cwd;
134
+ }
135
+
136
+ // books: collectDaily 의 [{ tool, path, days }]. 각 장부에 project(작업 폴더 경로 또는 null)를 붙여 돌려준다.
137
+ // Claude 기록에서 cwd 를 못 찾으면 폴더 이름을 쓰되, 같은 폴더 이름이 되는 경로를 다른 기록에서 찾았으면 그 경로로 묶는다.
138
+ export function attachProjects(books, root = PROJECTS) {
139
+ let agy = null;
140
+ const folder = new Map();
141
+ const out = books.map((b) => {
142
+ let project = null;
143
+ let fallback = null;
144
+ if (b.path) {
145
+ if (b.tool === 'claude') {
146
+ project = claudeProject(b.path);
147
+ if (!project) fallback = claudeFolder(b.path, root);
148
+ } else if (b.tool === 'codex') project = codexProject(b.path);
149
+ else if (b.tool === 'agy') project = (agy ??= agyWorkspaces()).get(basename(b.path, '.db')) ?? null;
150
+ }
151
+ project = projectRoot(project);
152
+ // 한 폴더 이름에 서로 다른 경로가 둘 이상 모이면(/a/b-c 와 /a/b/c, 한글 이름 등) 어느 쪽인지 모르니 묶지 않는다 (false).
153
+ if (project) {
154
+ const k = encodeFolder(project);
155
+ const had = folder.get(k);
156
+ folder.set(k, had === undefined || had === project ? project : false);
157
+ }
158
+ return { ...b, project: project ?? fallback, fallback: Boolean(fallback) };
159
+ });
160
+ return out.map(({ fallback, ...b }) => (fallback ? { ...b, project: folder.get(b.project) || b.project } : b));
161
+ }
162
+
163
+ // 작업 폴더 경로들 → 짧은 이름. 마지막 폴더 이름을 쓰고, 이름이 겹치면 겹치지 않을 때까지 앞 폴더를 붙인다 (dev/aitop).
164
+ export function projectLabels(paths) {
165
+ const segs = new Map();
166
+ for (const p of paths) segs.set(p, String(p).split(/[\\/]+/).filter(Boolean));
167
+ const out = new Map();
168
+ let todo = [...segs.keys()];
169
+ for (let n = 1; todo.length; n++) {
170
+ const name = (p) => segs.get(p).slice(-n).join('/') || p;
171
+ const count = new Map();
172
+ for (const p of segs.keys()) if (!out.has(p)) count.set(name(p), (count.get(name(p)) ?? 0) + 1);
173
+ // 모든 경로가 다 쓰였는데도 겹치면(같은 경로를 다르게 쓴 것) 전체 경로를 쓴다.
174
+ const last = todo.every((p) => segs.get(p).length <= n);
175
+ for (const p of todo) if (count.get(name(p)) === 1 || last) out.set(p, last && count.get(name(p)) > 1 ? p : name(p));
176
+ todo = todo.filter((p) => !out.has(p));
177
+ }
178
+ return out;
179
+ }
@@ -0,0 +1,80 @@
1
+ // --line 용 작은 요약 파일. 실시간 화면·--once·--json 이 세션을 다 모은 뒤 작업 중·응답 대기 수를 적고,
2
+ // --line 은 이 파일만 읽어 작업 중 수를 낸다 (세션 기록·프로세스 목록을 다시 읽지 않게).
3
+ // 가격·캐시 형식과 무관하므로 버전 폴더가 아니라 캐시 루트에 두고, 파일 안의 v 로 형식을 가른다.
4
+ // 그래야 다른 버전의 aitop 화면이 쓴 요약도 --line 이 읽는다.
5
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { CACHE_ROOT } from './cache.mjs';
8
+ import { debugIo } from './log.mjs';
9
+
10
+ const V = 1;
11
+ export const SUMMARY_FILE = join(CACHE_ROOT, 'summary.json');
12
+ // 이보다 오래된 요약은 버린다. 화면은 수가 그대로여도 HEARTBEAT_MS 마다 다시 쓰므로 두 번 넘게 놓쳐야 버려진다.
13
+ // 화면을 끄면 마지막 수가 1분 안에 사라진다 (tmux 기본 갱신 15초로 네 번 안).
14
+ export const STALE_MS = 60_000;
15
+ // 수가 바뀌었을 때도 이 간격보다 자주 쓰지 않는다.
16
+ export const MIN_WRITE_MS = 5_000;
17
+ // 수가 그대로여도 이 간격마다 시각을 새로 적는다.
18
+ export const HEARTBEAT_MS = 20_000;
19
+ // 시계가 조금 어긋난 것은 봐준다. 이보다 미래 시각이면 잘못된 파일로 본다.
20
+ const SKEW_MS = 5_000;
21
+
22
+ const nat = (x) => Number.isInteger(x) && x >= 0;
23
+
24
+ // 세션 목록에서 요약 값을 뽑는다. 화면 헤더(ui/table.mjs)와 같은 기준이다.
25
+ export function summarize(sessions, now = Date.now()) {
26
+ const live = sessions.filter((s) => s.live);
27
+ const waiting = live.filter((s) => s.status === 'waiting');
28
+ return {
29
+ v: V,
30
+ at: now,
31
+ running: live.filter((s) => s.status === 'busy' || s.status === 'shell').length,
32
+ waiting: waiting.length,
33
+ // Claude 대기 수는 --line 이 세션 파일에서 바로 세므로, 그 밖의 도구 몫(지금은 Antigravity 만 대기 상태가 있다)을 따로 적는다.
34
+ waitingOther: waiting.filter((s) => s.tool !== 'claude').length,
35
+ };
36
+ }
37
+
38
+ // 여러 aitop 이 함께 써도 섞이지 않게 pid 별 임시 파일에 쓰고 rename 한다 (마지막에 쓴 쪽이 남는다).
39
+ export function writeSummary(summary, file = SUMMARY_FILE) {
40
+ const tmp = `${file}.${process.pid}.tmp`;
41
+ try {
42
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
43
+ writeFileSync(tmp, JSON.stringify(summary), { mode: 0o600 });
44
+ renameSync(tmp, file);
45
+ return true;
46
+ } catch (e) {
47
+ debugIo('summary', 'summary write failed', e);
48
+ try {
49
+ rmSync(tmp, { force: true });
50
+ } catch {}
51
+ return false;
52
+ }
53
+ }
54
+
55
+ // 새 요약이면 값, 없거나 깨졌거나 오래됐으면 null.
56
+ export function readSummary({ file = SUMMARY_FILE, now = Date.now(), staleMs = STALE_MS } = {}) {
57
+ let s;
58
+ try {
59
+ s = JSON.parse(readFileSync(file, 'utf8'));
60
+ } catch {
61
+ return null;
62
+ }
63
+ if (s?.v !== V || !Number.isFinite(s.at) || ![s.running, s.waiting, s.waitingOther].every(nat)) return null;
64
+ if (now - s.at > staleMs || s.at - now > SKEW_MS) return null;
65
+ return s;
66
+ }
67
+
68
+ // 실시간 화면용: 수가 바뀌면 지난번 쓴 뒤 minMs 가 지났을 때, 그대로면 heartbeatMs 마다 쓴다.
69
+ export function createSummaryWriter({ file = SUMMARY_FILE, minMs = MIN_WRITE_MS, heartbeatMs = HEARTBEAT_MS, write = writeSummary } = {}) {
70
+ let last = null;
71
+ return (sessions, now = Date.now()) => {
72
+ const s = summarize(sessions, now);
73
+ const since = last ? now - last.at : Infinity;
74
+ const changed = !last || s.running !== last.running || s.waiting !== last.waiting || s.waitingOther !== last.waitingOther;
75
+ if (since < (changed ? minMs : heartbeatMs)) return false;
76
+ if (!write(s, file)) return false;
77
+ last = s;
78
+ return true;
79
+ };
80
+ }