@sejuneoh/aitop 0.35.0 → 0.36.1

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.
@@ -76,6 +76,33 @@ export function tailStopReason(path) {
76
76
  return null;
77
77
  }
78
78
 
79
+ // 기록을 남긴 실행 방식 (entrypoint): 사람이 연 Claude Code 는 'cli', 다른 프로그램이 띄운 claude -p(SDK) 는 'sdk-cli' 다 (#286).
80
+ // 첫 줄부터 붙으므로 앞 HEAD_ENTRY_BYTES 만 본다. 모르면 null.
81
+ const HEAD_ENTRY_BYTES = 64 * 1024;
82
+ export function headEntrypoint(path) {
83
+ let text;
84
+ try {
85
+ const fd = openSync(path, 'r');
86
+ try {
87
+ const buf = Buffer.alloc(HEAD_ENTRY_BYTES);
88
+ text = buf.toString('utf8', 0, readSync(fd, buf, 0, buf.length, 0));
89
+ } finally {
90
+ closeSync(fd);
91
+ }
92
+ } catch (e) {
93
+ debugIo('claude', 'transcript head read failed', e, path);
94
+ return null;
95
+ }
96
+ for (const l of text.split('\n')) {
97
+ if (!l.includes('"entrypoint"')) continue;
98
+ try {
99
+ const x = JSON.parse(l);
100
+ if (typeof x.entrypoint === 'string') return x.entrypoint;
101
+ } catch {}
102
+ }
103
+ return null;
104
+ }
105
+
79
106
  // 프롬프트 캐시 수명. 공식 문서(https://platform.claude.com/docs/en/build-with-claude/prompt-caching) 기준:
80
107
  // 기본 5분, 1시간은 선택. 캐시를 쓰거나 읽을 때마다 수명이 새로 시작되고, 수명은 응답 끝이 아니라 그 요청이 시작된 때부터 잰다.
81
108
  // 요청 시작 시각은 기록에 없으므로 그 응답 바로 앞의 사용자 줄(지시·도구 결과) 시각으로 잡는다. 없으면 응답 줄 시각.
@@ -158,6 +185,8 @@ export class ClaudeTracker {
158
185
  // 사용자가 /rename 으로 붙인 이름. 기록의 마지막 custom-title 이 이긴다.
159
186
  this.customTitle = null;
160
187
  this.branch = null;
188
+ // 실행 방식 (headEntrypoint). 기록의 첫 값을 쓴다.
189
+ this.entrypoint = null;
161
190
 
162
191
  const c = loadCache(path);
163
192
  if (c) {
@@ -171,6 +200,12 @@ export class ClaudeTracker {
171
200
  this.customTitle = tailCustomTitle(path) ?? null;
172
201
  markDirty(path, () => this.snapshot());
173
202
  }
203
+ // 실행 방식도 같은 방식으로 한 번만 채운다 (캐시 버전은 그대로, 기록 앞부분만 읽는다).
204
+ if ('entrypoint' in c) this.entrypoint = c.entrypoint;
205
+ else {
206
+ this.entrypoint = headEntrypoint(path);
207
+ markDirty(path, () => this.snapshot());
208
+ }
174
209
  // 멈춘 이유도 같은 방식으로 한 번만 채운다 (캐시 버전은 그대로).
175
210
  if (!('stopReason' in c)) {
176
211
  this.stopReason = tailStopReason(path);
@@ -257,6 +292,7 @@ export class ClaudeTracker {
257
292
  title: this.title,
258
293
  customTitle: this.customTitle,
259
294
  branch: this.branch,
295
+ entrypoint: this.entrypoint,
260
296
  events: this.events,
261
297
  lastTool: this.lastTool,
262
298
  lastKind: this.lastKind,
@@ -301,6 +337,7 @@ export class ClaudeTracker {
301
337
  if (x.type === 'ai-title' && x.aiTitle) this.title = x.aiTitle;
302
338
  if (x.type === 'custom-title') this.customTitle = sessionName(x.customTitle);
303
339
  if (x.gitBranch) this.branch = x.gitBranch;
340
+ if (typeof x.entrypoint === 'string') this.entrypoint ??= x.entrypoint;
304
341
  if (this.firstAt == null && x.timestamp) this.firstAt = parseTs(x.timestamp);
305
342
  if (x.isMeta) return;
306
343
 
@@ -1,12 +1,13 @@
1
1
  // Claude Code: ~/.claude/sessions/<pid>.json 으로 살아 있는 세션을 찾고,
2
2
  // ~/.claude/projects/*/<sessionId>.jsonl 대화 기록에서 진행 단계·토큰·비용을 읽는다.
3
3
  // 설정 폴더가 여럿이면(dirs.mjs) 모두 보고, 같은 세션 id 는 하나로 합친다.
4
- import { readdirSync, readFileSync, existsSync, statSync, openSync, readSync, closeSync } from 'node:fs';
5
- import { loadCache } from '../cache.mjs';
4
+ import { readdirSync, readFileSync, existsSync, statSync, openSync, readSync, closeSync, writeFileSync, mkdirSync } from 'node:fs';
5
+ import { CACHE_ROOT, PARENTS_FILE, loadCache } from '../cache.mjs';
6
+ import { renameSync } from '../rename.mjs';
6
7
  import { contextWindow } from '../pricing.mjs';
7
- import { join, basename } from 'node:path';
8
- import { isSessionAlive } from '../procs.mjs';
9
- import { ClaudeTracker, tailCustomTitle, tailStopReason } from './claude-tracker.mjs';
8
+ import { join, basename, dirname } from 'node:path';
9
+ import { isSessionAlive, parentPid } from '../procs.mjs';
10
+ import { ClaudeTracker, headEntrypoint, tailCustomTitle, tailStopReason } from './claude-tracker.mjs';
10
11
  import { emptyTokens, isLongTool, mergeActivity, MEMBER_FADE_MS, sessionName } from './common.mjs';
11
12
  import { mergeFiles } from './files.mjs';
12
13
  import { debug, debugIo } from '../log.mjs';
@@ -230,6 +231,11 @@ function toolStartOf(status, phase, t) {
230
231
  const DISCOVER_TTL_MS = 10_000;
231
232
  const HEAD_BYTES = 256 * 1024;
232
233
  let discovered = { at: 0, list: [] };
234
+ // 테스트용: 다음 갱신에서 기록 목록을 다시 훑게 한다 (기본 보기의 하위 실행 후보 runFiles 도).
235
+ export const _resetDiscover = () => {
236
+ discovered = { at: 0, list: [] };
237
+ runFiles = { at: 0, key: '', list: [] };
238
+ };
233
239
  const heads = new Map();
234
240
 
235
241
  function recentTranscripts() {
@@ -270,7 +276,7 @@ function recentTranscripts() {
270
276
  function readHead(path, mtime) {
271
277
  const cached = heads.get(path);
272
278
  if (cached && cached.mtime === mtime) return cached;
273
- const head = { mtime, cwd: null, title: null, customTitle: null, branch: null, startedAt: null };
279
+ const head = { mtime, cwd: null, title: null, customTitle: null, branch: null, startedAt: null, entrypoint: null };
274
280
  let headCustom;
275
281
  try {
276
282
  const fd = openSync(path, 'r');
@@ -288,6 +294,7 @@ function readHead(path, mtime) {
288
294
  }
289
295
  head.cwd ??= x.cwd ?? null;
290
296
  head.branch ??= x.gitBranch ?? null;
297
+ if (typeof x.entrypoint === 'string') head.entrypoint ??= x.entrypoint;
291
298
  if (x.timestamp) head.startedAt ??= Date.parse(x.timestamp) || null;
292
299
  if (x.type === 'ai-title' && x.aiTitle) head.title = x.aiTitle;
293
300
  if (x.type === 'custom-title') headCustom = sessionName(x.customTitle);
@@ -324,35 +331,44 @@ function endedFromTranscripts(known, selectedId, budget) {
324
331
  if (known.has(f.sessionId)) continue;
325
332
  const head = readHead(f.path, f.mtime);
326
333
  const want = eager || f.sessionId === selectedId || trackers.has(f.path) || hasCache(f.path, f.mtime);
327
- const t = want ? tracker(trackers, f.path, budget) : null;
328
- const { sub } = t ? readMembers(f.path, t, budget) : { sub: emptySub() };
329
- out.push({
330
- tool: 'claude',
331
- id: f.sessionId,
332
- pid: null,
333
- kind: '-',
334
- name: (t ? t.customTitle : head.customTitle) ?? t?.title ?? head.title ?? `${basename(head.cwd ?? '')} · ${f.sessionId.slice(0, 8)}`,
335
- customName: (t ? t.customTitle : head.customTitle) ?? null,
336
- cwd: head.cwd,
337
- project: basename(head.cwd ?? ''),
338
- branch: t?.branch ?? head.branch,
339
- model: t?.model ?? null,
340
- live: false,
341
- lazy: !t,
342
- status: 'ended',
343
- phase: { kind: 'ended' },
344
- waitingFor: null,
345
- now: '',
346
- startedAt: head.startedAt,
347
- updatedAt: f.mtime,
348
- ...sessionTotals(t, sub),
349
- events: t?.events ?? [],
350
- members: [],
351
- });
334
+ out.push(endedSession(f, head, want ? tracker(trackers, f.path, budget) : null, budget));
352
335
  }
353
336
  return out;
354
337
  }
355
338
 
339
+ // 끝난 세션 한 줄. t 가 없으면(본문을 아직 읽지 않음) 숫자는 비우고 lazy 로 둔다.
340
+ // 기록 경로(f)는 endedSrc 에 따로 둔다: claude -p 실행을 부모에 붙일 때 그 기록을 마저 읽는 데 쓴다 (attachRuns).
341
+ const endedSrc = new WeakMap();
342
+ function endedSession(f, head, t, budget) {
343
+ const { sub } = t ? readMembers(f.path, t, budget) : { sub: emptySub() };
344
+ const s = {
345
+ tool: 'claude',
346
+ id: f.sessionId,
347
+ pid: null,
348
+ kind: '-',
349
+ name: (t ? t.customTitle : head.customTitle) ?? t?.title ?? head.title ?? `${basename(head.cwd ?? '')} · ${f.sessionId.slice(0, 8)}`,
350
+ customName: (t ? t.customTitle : head.customTitle) ?? null,
351
+ cwd: head.cwd,
352
+ project: basename(head.cwd ?? ''),
353
+ branch: t?.branch ?? head.branch,
354
+ model: t?.model ?? null,
355
+ entrypoint: t?.entrypoint ?? head.entrypoint ?? null,
356
+ live: false,
357
+ lazy: !t,
358
+ status: 'ended',
359
+ phase: { kind: 'ended' },
360
+ waitingFor: null,
361
+ now: '',
362
+ startedAt: head.startedAt,
363
+ updatedAt: f.mtime,
364
+ ...sessionTotals(t, sub),
365
+ events: t?.events ?? [],
366
+ members: [],
367
+ };
368
+ endedSrc.set(s, f);
369
+ return s;
370
+ }
371
+
356
372
  // sessions 폴더 목록은 폴더 수정 시각이 그대로면 재사용한다 (#135).
357
373
  // 수정 시각은 틱(수 ms)이나 초 단위로 거칠어, 읽기 직전·직후의 변경이 같은 시각으로 남을 수 있다.
358
374
  // 그래서 수정된 지 RACY_MS 안에 읽은 결과는 믿지 않고 다음 갱신에 다시 읽는다 (git 의 racy 검사와 같다).
@@ -397,7 +413,7 @@ function sessionFile(path) {
397
413
  }
398
414
  // 미리 띄워 둔 대기 프로세스(claude bg-spare)는 아직 세션이 아니다. 작업을 맡으면 spare 가 빠진 파일로 다시 쓰인다.
399
415
  if (!c.entry?.sessionId || c.entry.spare) return null;
400
- if (!c.dead && !isSessionAlive(c.entry.pid, c.entry.procStart)) c.dead = true;
416
+ if (!c.dead && !isSessionAlive(c.entry.pid, c.entry.procStart, c.entry.updatedAt ?? c.entry.startedAt)) c.dead = true;
401
417
  return { ...c.entry, alive: !c.dead };
402
418
  }
403
419
 
@@ -430,7 +446,7 @@ function sessionEntries() {
430
446
  }
431
447
  ok = true;
432
448
  for (const f of prev.files) keep.add(f);
433
- for (const x of prev.entries) all.push(x.alive && !isSessionAlive(x.pid, x.procStart) ? { ...x, alive: false } : x);
449
+ for (const x of prev.entries) all.push(x.alive && !isSessionAlive(x.pid, x.procStart, x.updatedAt ?? x.startedAt) ? { ...x, alive: false } : x);
434
450
  continue;
435
451
  }
436
452
  ok = true;
@@ -498,6 +514,8 @@ export function claudeLineCounts({ deadline = Infinity } = {}) {
498
514
  for (const e of entries) {
499
515
  if (!e.waitingFor) continue;
500
516
  const transcript = find(e.sessionId);
517
+ // claude -p(sdk-cli) 실행은 사람이 답할 수 없으므로 응답 대기로 세지 않는다 (화면 callsYou 와 같은 규칙). 기록 앞부분만 본다.
518
+ if ((e.entrypoint ?? (transcript ? headEntrypoint(transcript) : null)) === SDK_ENTRY) continue;
501
519
  const custom = transcript ? tailCustomTitle(transcript) : undefined;
502
520
  const since = [e.statusUpdatedAt, e.updatedAt, e.startedAt].find(Number.isFinite) ?? null;
503
521
  waiting.push({ tool: 'claude', name: givenName(e, custom) ?? (isAutoName(e) ? basename(e.cwd ?? '') : String(e.name)), since });
@@ -543,6 +561,8 @@ export function collectClaude({ showEnded, budget, selectedId }) {
543
561
  project: basename(e.cwd ?? ''),
544
562
  branch: t?.branch,
545
563
  model: t?.model,
564
+ // 실행 방식: 'cli'(사람이 연 것), 'sdk-cli'(다른 프로그램이 띄운 claude -p) 등. 기록에서 읽고, 모르면 null (#286).
565
+ entrypoint: t?.entrypoint ?? e.entrypoint ?? null,
546
566
  live: e.alive,
547
567
  status,
548
568
  // Claude Code 가 상태를 남기지 않아 기록 수정 시각으로 추측한 경우
@@ -565,7 +585,259 @@ export function collectClaude({ showEnded, budget, selectedId }) {
565
585
  members: status === 'ended' ? [] : members,
566
586
  });
567
587
  }
588
+ // 끝난 claude -p 하위 실행은 --all 이 아니어도 읽어 부모 합계에 넣는다 (endedRuns). 부모 비용이 보기 방식과 상관없이 같게 한다.
589
+ const extra = showEnded ? [] : endedRuns(out, budget);
568
590
  if (showEnded) out.push(...endedFromTranscripts(new Set(out.map((s) => s.id)), selectedId, budget));
591
+ const shown = attachRuns([...out, ...extra], budget);
569
592
  prune();
593
+ // 부모에 붙지 못한 끝난 하위 실행은 기본 보기에 내지 않는다 (예전처럼 --all 에서만 보인다).
594
+ const hidden = new Set(extra);
595
+ return hidden.size ? shown.filter((s) => !hidden.has(s)) : shown;
596
+ }
597
+
598
+ // ---- claude -p(sdk-cli) 실행을 부모 세션 아래로 (#286) ----
599
+ // 다른 프로그램이 claude -p 로 띄운 실행은 따로 세션 파일·기록을 만들고, 어디에도 부모 세션 id 를 적지 않는다.
600
+ // 그래서 두 가지로 짐작한다.
601
+ // 1. 살아 있으면: 그 프로세스의 부모 pid 를 PARENT_DEPTH 단계까지 따라 올라가 다른 Claude 세션 pid 를 만나면 그 세션.
602
+ // (Claude 세션 → bash → claude -p 처럼 쉘을 거쳐 뜬다.) 부모 pid 는 procs.mjs parentPid 가 이미 얻는 정보로만 얻는다.
603
+ // 2. 그래도 못 찾았거나 끝난 실행이면: 작업 폴더가 <설정 폴더>/jobs/<id>/ 아래인 경우 id 가 <id> 로 시작하는 세션.
604
+ // Claude Code 백그라운드 작업은 jobs/<자기 세션 id 앞 8자>/tmp 를 작업 폴더로 쓴다.
605
+ // 붙은 실행은 서브에이전트처럼 팀원 행이 되고 토큰·비용은 부모 합계에 더한다 (부모가 끝났으면 서브에이전트처럼 행 없이 합계만).
606
+ // 날짜별 장부(헤더 오늘·7일)는 기록 파일 단위로 따로 세므로 여기서 옮겨도 두 번 세지 않는다.
607
+ // 부모를 못 찾은 sdk-cli 실행(cron 등)은 최상위에 두고 auto 를 켠다. 사람이 답할 수 없는 실행이라 응답 대기로 부르지 않는다 (attention.mjs callsYou).
608
+ // sdk-cli 만 대상이다: 사람이 연 Claude Code(cli)나 그 밖의 앱은 사람이 직접 보고 답하는 세션이라 따로 둔다.
609
+ export const SDK_ENTRY = 'sdk-cli';
610
+ const PARENT_DEPTH = 8;
611
+ let ppidOf = parentPid;
612
+ export function _setParentPid(fn) {
613
+ const prev = ppidOf;
614
+ ppidOf = fn ?? parentPid;
615
+ return prev;
616
+ }
617
+
618
+ // 작업 폴더가 Claude 백그라운드 작업 폴더(<설정 폴더>/jobs/<id>/…)면 <id>, 아니면 null.
619
+ // 설정 폴더 안의 jobs 와, 설정 폴더 위 홈의 .claude/jobs 를 모두 본다 (CLAUDE_CONFIG_DIR 를 바꾼 경우).
620
+ export function jobIdOf(cwd, homes = claudeDirs()) {
621
+ if (!cwd) return null;
622
+ const norm = (p) => String(p).replace(/\\/g, '/').replace(/\/+$/, '');
623
+ const c = norm(cwd);
624
+ for (const h of homes) {
625
+ for (const jobs of [join(h, 'jobs'), join(dirname(h), '.claude', 'jobs')]) {
626
+ const j = norm(jobs) + '/';
627
+ if (!c.startsWith(j)) continue;
628
+ const id = c.slice(j.length).split('/')[0];
629
+ // 짧은 조각은 여러 세션에 맞으므로 4자 이상만 쓴다.
630
+ if (id && id.length >= 4) return id.toLowerCase();
631
+ }
632
+ }
633
+ return null;
634
+ }
635
+
636
+ // 실행 중에 부모 pid 로 알아낸 부모 { 실행 id: { parentId, at } }. 끝나면 부모 pid 를 알 길이 없으므로 기억해 두고,
637
+ // aitop 을 다시 켜도 쓰게 캐시 폴더의 작은 파일에 남긴다. PARENTS_KEEP_MS(끝난 세션 범위와 같은 24시간)가 지나면 잊는다.
638
+ // 파일은 버전 폴더 밖(CACHE_ROOT, summary.json 과 같은 곳)에 두어 캐시 형식이 바뀌어도 남는다 (cache.mjs removeOldDirs 가 건너뛴다).
639
+ const PARENTS_KEEP_MS = ENDED_WINDOW_MS;
640
+ let parents = null;
641
+ const parentsFile = () => join(CACHE_ROOT, PARENTS_FILE);
642
+ const fresh = (v, now = Date.now()) => Boolean(v?.parentId) && Number.isFinite(v.at) && now - v.at < PARENTS_KEEP_MS;
643
+
644
+ function readParentsFile() {
645
+ try {
646
+ return Object.entries(JSON.parse(readFileSync(parentsFile(), 'utf8')) ?? {});
647
+ } catch (e) {
648
+ if (e.code !== 'ENOENT') debugIo('claude', 'sdk parents read failed', e);
649
+ return [];
650
+ }
651
+ }
652
+
653
+ function knownParents() {
654
+ if (parents) return parents;
655
+ parents = new Map(readParentsFile().filter(([, v]) => fresh(v)));
656
+ return parents;
657
+ }
658
+
659
+ function rememberParent(id, parentId) {
660
+ const m = knownParents();
661
+ if (m.get(id)?.parentId === parentId) return;
662
+ m.set(id, { parentId, at: Date.now() });
663
+ // 실시간 화면과 --line 등 여러 aitop 이 같이 쓸 수 있으므로, 쓰기 직전에 파일을 다시 읽어 합친다 (같은 id 는 더 최근 것).
664
+ // 24시간 지난 것만 버린다. 임시 파일 이름에 pid 를 붙여 서로의 임시 파일을 덮지 않고, rename 으로 한 번에 바꾼다.
665
+ const now = Date.now();
666
+ for (const [k, v] of readParentsFile()) if (fresh(v, now) && !(m.get(k)?.at >= v.at)) m.set(k, v);
667
+ for (const [k, v] of m) if (!fresh(v, now)) m.delete(k);
668
+ try {
669
+ mkdirSync(CACHE_ROOT, { recursive: true, mode: 0o700 });
670
+ const f = parentsFile();
671
+ const tmp = `${f}.${process.pid}.tmp`;
672
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(m)), { mode: 0o600 });
673
+ renameSync(tmp, f);
674
+ } catch (e) {
675
+ debugIo('claude', 'sdk parents write failed', e);
676
+ }
677
+ }
678
+
679
+ export function _forgetParents() {
680
+ parents = null;
681
+ }
682
+
683
+ // 기본 보기(--all 아님)에서 지금 목록에 있는 세션의 끝난 claude -p 하위 실행. 모든 기록을 훑지 않고 두 곳만 본다:
684
+ // 1. 기록 폴더 이름이 -jobs-<목록 세션 id 앞 8자> 를 담은 폴더 (작업 폴더가 jobs/<id>/… 이면 Claude Code 가 그 경로로 폴더 이름을 짓는다).
685
+ // 2. 기억된 부모(knownParents)가 목록에 있는 실행의 기록 (findTranscript, 경로는 기억된다).
686
+ // 범위는 끝난 세션 목록과 같은 24시간 안에 바뀐 기록이고, 찾은 경로는 DISCOVER_TTL_MS 동안 다시 쓴다.
687
+ // 그다음 기록 앞부분(readHead, 수정 시각별로 기억)으로 sdk-cli 인지 확인하고, 본문은 화면 읽기 한도(budget) 안에서 이어 읽어 캐시에 남긴다.
688
+ // 부모가 24시간 넘게 살아 있으면 그보다 오래 전에 끝난 하위 실행은 합계에서 빠진다 (README).
689
+ let runFiles = { at: 0, key: '', list: [] };
690
+
691
+ function runCandidates(list) {
692
+ const key = list.map((s) => s.id).sort().join(',');
693
+ if (runFiles.key === key && Date.now() - runFiles.at < DISCOVER_TTL_MS) return runFiles.list;
694
+ const ids = new Set(list.map((s) => s.id));
695
+ const prefixes = new Set(list.map((s) => s.id.slice(0, 8).toLowerCase()));
696
+ const found = [];
697
+ const add = (path, sessionId) => {
698
+ if (ids.has(sessionId)) return;
699
+ try {
700
+ const mtime = statSync(path).mtimeMs;
701
+ if (Date.now() - mtime < ENDED_WINDOW_MS) found.push({ key: sessionId, sessionId, path, mtime });
702
+ } catch {}
703
+ };
704
+ const listing = projectDirs();
705
+ for (const [root, dirs] of listing) {
706
+ for (const dir of dirs ?? []) {
707
+ const job = /-jobs-([0-9a-z]{4,})/i.exec(dir)?.[1]?.toLowerCase();
708
+ if (!job || !prefixes.has(job.slice(0, 8))) continue;
709
+ let names = [];
710
+ try {
711
+ names = readdirSync(join(root, dir));
712
+ } catch (e) {
713
+ debugIo('claude', 'project folder read failed', e, dir);
714
+ }
715
+ for (const n of names) if (n.endsWith('.jsonl')) add(join(root, dir, n), n.slice(0, -'.jsonl'.length));
716
+ }
717
+ }
718
+ for (const [child, v] of knownParents()) {
719
+ if (!ids.has(v.parentId) || found.some((f) => f.sessionId === child)) continue;
720
+ const path = findTranscript(child, listing);
721
+ if (path) add(path, child);
722
+ }
723
+ runFiles = { at: Date.now(), key, list: dedupeBy(found) };
724
+ return runFiles.list;
725
+ }
726
+
727
+ function endedRuns(list, budget) {
728
+ if (!list.some((s) => s.live)) return [];
729
+ const out = [];
730
+ for (const f of runCandidates(list)) {
731
+ const head = readHead(f.path, f.mtime);
732
+ if (head.entrypoint !== SDK_ENTRY) continue;
733
+ out.push(endedSession(f, head, tracker(trackers, f.path, budget), budget));
734
+ }
570
735
  return out;
571
736
  }
737
+
738
+ function findParent(s, byPid, list) {
739
+ const known = knownParents().get(s.id)?.parentId;
740
+ const remembered = known ? list.find((x) => x.id === known && x !== s) : null;
741
+ if (remembered) return remembered;
742
+ if (s.live && Number.isInteger(s.pid)) {
743
+ let p = ppidOf(s.pid);
744
+ for (let i = 0; i < PARENT_DEPTH && Number.isInteger(p) && p > 1; i++) {
745
+ const hit = byPid.get(p);
746
+ if (hit && hit !== s) {
747
+ rememberParent(s.id, hit.id);
748
+ return hit;
749
+ }
750
+ p = ppidOf(p);
751
+ }
752
+ }
753
+ const job = jobIdOf(s.cwd);
754
+ if (!job) return null;
755
+ const cands = list.filter((x) => x !== s && x.id.toLowerCase().startsWith(job));
756
+ // 살아 있는 쪽, 그다음 최근에 바뀐 쪽.
757
+ cands.sort((a, b) => Number(b.live) - Number(a.live) || (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
758
+ return cands[0] ?? null;
759
+ }
760
+
761
+ const TOKEN_KEYS = Object.keys(emptyTokens());
762
+
763
+ // 붙은 실행의 합계를 부모에 더한다 (sessionTotals 가 서브에이전트를 더하는 것과 같은 칸). 부모 숫자를 아직 모르면(null) 그대로 둔다.
764
+ function absorb(root, c) {
765
+ const tk = (root.tokens = { ...root.tokens });
766
+ for (const k of TOKEN_KEYS) tk[k] = (tk[k] ?? 0) + (c.tokens?.[k] ?? 0);
767
+ tk.sub = (tk.sub ?? 0) + (c.tokens?.total ?? 0);
768
+ // 그 실행이 띄운 서브에이전트도 함께 센다 (토큰은 이미 c.tokens 에 들어 있다).
769
+ tk.subCount = (tk.subCount ?? 0) + 1 + (c.tokens?.subCount ?? 0);
770
+ if (root.cost != null && c.cost != null) root.cost += c.cost;
771
+ if (root.costNoCache != null && c.costNoCache != null) root.costNoCache += c.costNoCache;
772
+ root.costUnknown ||= Boolean(c.costUnknown);
773
+ root.loading ||= Boolean(c.loading);
774
+ root.activity = mergeActivity([root.activity, c.activity]);
775
+ }
776
+
777
+ // 팀원 행 모양 (readMembers 와 같은 칸). sdk: true 면 화면이 이름 앞에 -p 를 붙인다.
778
+ function runMember(c, parentId) {
779
+ const done = !c.live;
780
+ const started = Boolean(c.model || c.tokens?.total > 0);
781
+ return {
782
+ id: c.id,
783
+ sdk: true,
784
+ entrypoint: c.entrypoint,
785
+ parentId,
786
+ name: 'claude -p',
787
+ model: c.model ?? null,
788
+ task: c.name ?? '',
789
+ status: done ? 'done' : 'busy',
790
+ started,
791
+ phase: done ? { kind: 'done' } : !started ? { kind: 'idle', msg: 'starting' } : c.phase,
792
+ now: c.now,
793
+ tokens: c.tokens?.total ?? 0,
794
+ cost: c.cost,
795
+ costNoCache: c.costNoCache,
796
+ costUnknown: c.costUnknown,
797
+ loading: Boolean(c.loading),
798
+ startedAt: c.startedAt,
799
+ lastActivityAt: c.updatedAt ?? null,
800
+ longStep: false,
801
+ };
802
+ }
803
+
804
+ function attachRuns(list, budget) {
805
+ if (!list.some((s) => s.entrypoint === SDK_ENTRY)) return list;
806
+ const byPid = new Map(list.filter((s) => s.live && Number.isInteger(s.pid)).map((s) => [s.pid, s]));
807
+ const parent = new Map();
808
+ for (const s of list) {
809
+ if (s.entrypoint !== SDK_ENTRY) continue;
810
+ const p = findParent(s, byPid, list);
811
+ if (p) parent.set(s, p);
812
+ }
813
+ // 부모도 붙은 실행이면 맨 위 세션까지 올라간다 (고리는 끊는다).
814
+ const rootOf = (s) => {
815
+ const path = new Set([s]);
816
+ let r = parent.get(s);
817
+ while (r && parent.has(r) && !path.has(r)) {
818
+ path.add(r);
819
+ r = parent.get(r);
820
+ }
821
+ return r && !path.has(r) ? r : null;
822
+ };
823
+ const gone = new Set();
824
+ const now = Date.now();
825
+ for (const s of list) {
826
+ if (!parent.has(s)) continue;
827
+ const root = rootOf(s);
828
+ // 살아 있는 실행은 끝난 부모 아래로 숨기지 않는다.
829
+ if (!root || (s.live && !root.live)) continue;
830
+ let c = s;
831
+ // 부모 숫자는 읽었는데 끝난 실행은 아직 안 읽었으면 마저 읽어 합계가 덜 차지 않게 한다 (선택해서 읽을 길이 없어진다).
832
+ const src = endedSrc.get(s);
833
+ if (s.lazy && !root.lazy && src) c = endedSession(src, heads.get(src.path) ?? readHead(src.path, src.mtime), tracker(trackers, src.path, budget), budget);
834
+ absorb(root, c);
835
+ gone.add(s);
836
+ const m = runMember(c, root.id);
837
+ if (root.status !== 'ended' && !(m.status === 'done' && now - (c.updatedAt ?? 0) > MEMBER_FADE_MS)) {
838
+ root.members = [...root.members, m].sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0));
839
+ }
840
+ }
841
+ for (const s of list) if (s.entrypoint === SDK_ENTRY && !gone.has(s)) s.auto = true;
842
+ return gone.size ? list.filter((s) => !gone.has(s)) : list;
843
+ }
@@ -17,7 +17,7 @@ import { codexHomes, codexSessionRoots, dedupeBy, homeOf } from './dirs.mjs';
17
17
  const MAX_TURNS = 50;
18
18
 
19
19
  const RECENT_MS = 24 * 3600 * 1000;
20
- // 프로세스 목록을 못 얻는 OS(지금은 Windows)에서는 이 시간 안에 바뀐 기록을 실행 중으로 본다.
20
+ // 프로세스 목록을 못 얻을 때(Windows 에서 PowerShell CIM 이 실패할 때 등)는 이 시간 안에 바뀐 기록을 실행 중으로 본다.
21
21
  // codex 는 답할 때마다 기록에 쓰므로, 답을 읽고 다음 지시를 쓰는 동안(대개 몇 분)은 남고 닫은 세션은 곧 빠진다.
22
22
  // Claude 팀원의 MEMBER_STALE_MS(15분)보다 짧게 둔다. 실제 프로세스가 없으니 끝난 세션이 오래 남는 쪽이 더 헷갈린다.
23
23
  export const NO_PROC_LIVE_MS = 10 * 60_000;
@@ -361,10 +361,48 @@ export function codexIndexName(path, id) {
361
361
 
362
362
  export const _test = { newState, applyLine, phaseOf, toolStartOf, snapshot, readIndex, indexName };
363
363
 
364
- export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses }) {
364
+ // 작업 폴더를 모르는 프로세스(Windows, cwdUnknown)와 rollout 을 시작 시각으로 짝짓는다. 돌려주는 값은 경로 → pid.
365
+ // files 는 최근에 바뀐 순서, sessionStartOf(path) 는 세션이 시작한 시각(ms), startOf(pid) 는 프로세스가 뜬 시각.
366
+ // 1) 프로세스 기준: 늦게 뜬 프로세스부터, 그 프로세스가 뜬 뒤 시작한 세션 중 가장 최근에 기록된 것을 준다.
367
+ // codex 안에서 /new 로 새 세션을 열면 예전 세션은 조용해지고 새 세션이 기록되므로, 지금 쓰는 세션이 숨지 않는다.
368
+ // 알려진 한계: 시각만으로는 다른 터미널에서 방금 끝난 세션과 구별할 수 없어, 오래 쉬는 세션 대신 그 세션이 잠시
369
+ // 실행 중으로 보일 수 있다. 쉬던 세션이 다시 기록하면 바로잡힌다 (지금 쓰는 세션이 숨는 쪽이 더 나빠서 이렇게 고른다).
370
+ // 2) 남은 프로세스(이어 연 세션)에는 최근에 바뀐 파일부터, 파일이 쓰이기 전에 뜬 프로세스 중 가장 늦게 뜬 것을 준다.
371
+ // 어느 쪽이든 프로세스가 뜨기 전에 마지막으로 쓰인 파일은 받지 않는다.
372
+ export function pairByStart(pids, files, sessionStartOf, startOf) {
373
+ const out = new Map();
374
+ const left = pids.map((pid) => ({ pid, since: startOf(pid) }));
375
+ const order = left.filter((p) => p.since !== null).sort((a, b) => b.since - a.since);
376
+ for (const p of order) {
377
+ // files 는 최근에 바뀐 순서라 처음 맞는 것이 가장 최근에 기록된 세션이다.
378
+ const best = files.find((f) => {
379
+ if (out.has(f.path) || f.mtime < p.since) return false;
380
+ const s = sessionStartOf(f.path);
381
+ return Number.isFinite(s) && s >= p.since;
382
+ });
383
+ if (best) {
384
+ out.set(best.path, p.pid);
385
+ left.splice(left.indexOf(p), 1);
386
+ }
387
+ }
388
+ for (const f of files) {
389
+ if (!left.length) break;
390
+ if (out.has(f.path)) continue;
391
+ let j = -1;
392
+ for (let i = 0; i < left.length; i++) {
393
+ const since = left[i].since;
394
+ if (since !== null && f.mtime < since) continue;
395
+ if (j < 0 || (since ?? -Infinity) > (left[j].since ?? -Infinity)) j = i;
396
+ }
397
+ if (j >= 0) out.set(f.path, left.splice(j, 1)[0].pid);
398
+ }
399
+ return out;
400
+ }
401
+
402
+ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses, procsOf = () => findProcesses(isCodex) }) {
365
403
  // 프로세스를 못 세면 숨기지 않고 최근에 바뀐 기록으로 판정한다 (pid 는 null).
366
404
  const blind = !canList();
367
- const procs = blind ? [] : findProcesses(isCodex);
405
+ const procs = blind ? [] : procsOf();
368
406
  if (!procs.length && !showEnded && !blind) return [];
369
407
 
370
408
  const fresh = (f) => Date.now() - f.mtime <= NO_PROC_LIVE_MS;
@@ -401,7 +439,11 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
401
439
  // 남은 프로세스는 같은 폴더에서 돌고 있는 수만큼, 가장 최근에 바뀐 세션 파일을 '실행 중'으로 본다.
402
440
  // 시작 시각을 아는 프로세스에는 시작한 뒤에 쓰인 파일만 준다. 새 codex 에 방금 끝난 세션이 붙지 않게 한다.
403
441
  const slots = new Map();
404
- for (const p of rest) slots.set(p.cwd, [...(slots.get(p.cwd) ?? []), p.pid]);
442
+ const anyCwd = [];
443
+ for (const p of rest) {
444
+ if (p.cwdUnknown) anyCwd.push(p.pid);
445
+ else slots.set(p.cwd, [...(slots.get(p.cwd) ?? []), p.pid]);
446
+ }
405
447
  for (const f of files) {
406
448
  if (liveByPath.has(f.path)) continue;
407
449
  const free = slots.get(states.get(f.path).cwd);
@@ -411,6 +453,11 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
411
453
  }) ?? -1;
412
454
  if (i >= 0) liveByPath.set(f.path, free.splice(i, 1)[0]);
413
455
  }
456
+ // 작업 폴더를 모르는 프로세스(Windows)는 폴더와 상관없이 시작 시각으로만 짝짓는다 (pairByStart).
457
+ if (anyCwd.length) {
458
+ const free = files.filter((f) => !liveByPath.has(f.path));
459
+ for (const [path, pid] of pairByStart(anyCwd, free, (p) => states.get(p)?.startedAt, startOf)) liveByPath.set(path, pid);
460
+ }
414
461
 
415
462
  const alive = new Set(procs.map((p) => p.pid));
416
463
  for (const pid of foundByPid.keys()) if (!alive.has(pid)) foundByPid.delete(pid);
package/src/summary.mjs CHANGED
@@ -2,10 +2,12 @@
2
2
  // --line 은 이 파일만 읽어 작업 중 수를 낸다 (세션 기록·프로세스 목록을 다시 읽지 않게).
3
3
  // 가격·캐시 형식과 무관하므로 버전 폴더가 아니라 캐시 루트에 두고, 파일 안의 v 로 형식을 가른다.
4
4
  // 그래야 다른 버전의 aitop 화면이 쓴 요약도 --line 이 읽는다.
5
- import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
5
+ import { readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
6
+ import { renameSync } from './rename.mjs';
6
7
  import { dirname, join } from 'node:path';
7
8
  import { CACHE_ROOT } from './cache.mjs';
8
9
  import { debugIo } from './log.mjs';
10
+ import { callsYou } from './attention.mjs';
9
11
 
10
12
  const V = 1;
11
13
  export const SUMMARY_FILE = join(CACHE_ROOT, 'summary.json');
@@ -43,7 +45,7 @@ const sinceKey = (t) => t ?? Number.MAX_SAFE_INTEGER;
43
45
  // 세션 목록에서 요약 값을 뽑는다. 화면 헤더(ui/table.mjs)와 같은 기준이다.
44
46
  export function summarize(sessions, now = Date.now()) {
45
47
  const live = sessions.filter((s) => s.live);
46
- const waiting = live.filter((s) => s.status === 'waiting');
48
+ const waiting = live.filter(callsYou);
47
49
  return {
48
50
  v: V,
49
51
  at: now,
package/src/ui/chrome.mjs CHANGED
@@ -46,10 +46,12 @@ const LEGEND_IDS = [
46
46
  ['legend.toolKey', 'legend.tool'],
47
47
  ['legend.elapsedKey', 'legend.elapsed'],
48
48
  ['legend.stalledKey', 'legend.stalled'],
49
+ ['member.sdk', 'legend.sdk'],
50
+ ['session.auto', 'legend.auto'],
49
51
  ];
50
52
 
51
53
  // 지금 언어의 상태 기호·열 설명. 제목 줄은 설명이 null 이다. {g} 는 팀원 경과 시간 표시(glyphs().elapsed)로 바꾼다.
52
- export const legend = () => LEGEND_IDS.map(([k, d]) => [/^(help|legend)\./.test(k) ? t(k, { g: glyphs().elapsed }) : k, d ? t(d) : d]);
54
+ export const legend = () => LEGEND_IDS.map(([k, d]) => [/^(help|legend|member|session)\./.test(k) ? t(k, { g: glyphs().elapsed }) : k, d ? t(d) : d]);
53
55
 
54
56
  // 도움말 줄 목록: 지금 화면의 키 → (표에 검색어가 걸려 있으면) 그 키 → (상세 패널이 열려 있으면) 상세 패널 키 → 어디서나 쓰는 키 → 다른 화면 한 줄씩 → 옵션 → 상태 기호·열.
55
57
  // 넓으면(100칸 이상) 키는 왼쪽, 옵션·기호·열은 오른쪽 칸에 둔다.
package/src/ui/table.mjs CHANGED
@@ -9,7 +9,7 @@ import { NOW, SPIN, cacheState, clock, toolElapsed, costOf, gauge, glyph, levelB
9
9
  import { glyphs } from './glyphs.mjs';
10
10
  import { phaseText, t } from '../i18n.mjs';
11
11
  import { NO_FOLDER } from '../order.mjs';
12
- import { isStopped } from '../attention.mjs';
12
+ import { callsYou, isStopped } from '../attention.mjs';
13
13
 
14
14
  // 검색어가 세션 이름·폴더·모델 중 하나에 들어 있으면 남긴다 (대소문자 무시).
15
15
  export function filterSessions(sessions, query) {
@@ -65,7 +65,7 @@ export function header(view, W) {
65
65
  const live = sessions.filter((s) => s.live);
66
66
  const count = (pred) => live.filter(pred).length;
67
67
  const working = count((s) => ['busy', 'shell'].includes(s.status));
68
- const waiting = count((s) => s.status === 'waiting');
68
+ const waiting = count(callsYou);
69
69
  const unseen = count((s) => s.unseen);
70
70
  // 오류로 멈춘 세션은 status 가 idle 이라도 대기에서 빼고 따로 센다 (#262).
71
71
  const stopped = count(isStopped);
@@ -351,7 +351,10 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
351
351
  // 좁아도 고정 표시는 남기고 이름 칸을 먼저 줄인다 (이름 칸이 2칸 이하면 기호만).
352
352
  const mark = glyphs().pin;
353
353
  const pin = pinned ? [{ t: c.name >= width(mark) + 2 ? `${mark} ` : mark, fg: ended ? PALETTE.ended : PALETTE.brand, bold: true }] : [];
354
- segs.push(...pin, { t: pad(s.name ?? '', c.name - segsWidth(pin)) + ' ', fg: ended ? PALETTE.ended : PALETTE.text, bold: selected });
354
+ // 부모 세션을 못 찾은 claude -p 실행(cron 등)은 이름 앞에 '자동'(auto) 글자를 흐리게 붙인다. 색이 없어도 글자로 구분된다 (#286).
355
+ const autoMark = t('session.auto');
356
+ const auto = s.auto && c.name - segsWidth(pin) >= width(autoMark) + 4 ? [{ t: `${autoMark} `, fg: PALETTE.info, italic: true }] : [];
357
+ segs.push(...pin, ...auto, { t: pad(s.name ?? '', c.name - segsWidth(pin) - segsWidth(auto)) + ' ', fg: ended ? PALETTE.ended : PALETTE.text, bold: selected });
355
358
  if (c.showProject) segs.push({ t: pad(s.project ?? '', c.project) + ' ', fg: ended ? PALETTE.ended : PALETTE.muted });
356
359
  segs.push(
357
360
  ...statusCell(status, cacheState(s) ?? toolElapsed(s), c.status, { fg: pc, bold: s.status === 'waiting' }, briefStatus(s)),
@@ -420,8 +423,9 @@ export function memberRow(m, last, c, W, frame, parentModel, costMode = 'api', p
420
423
  // 같은 타입의 팀원이 여럿이어도 구분되도록, 하는 일(description)을 앞에 두고 타입은 흐리게 붙인다.
421
424
  // 팀원 행은 PROJECT 칸이 비므로 그 자리까지 하는 일 글을 이어 쓴다. general-purpose 타입은 정보가 없어 붙이지 않는다.
422
425
  const nameW = c.name - 2 + (c.showProject ? c.project + 1 : 0);
423
- const suffix = m.task && m.name !== 'general-purpose' ? ` · ${m.name}` : '';
424
- const label = truncate(m.task || m.name, nameW);
426
+ // 이 세션이 띄운 claude -p 실행(m.sdk)은 이름 앞에 -p 를 붙여 서브에이전트와 글자로 구분한다 (#286). 타입 덧붙임은 없다.
427
+ const suffix = m.task && m.name !== 'general-purpose' && !m.sdk ? ` · ${m.name}` : '';
428
+ const label = truncate((m.sdk ? `${t('member.sdk')} ` : '') + (m.task || m.name), nameW);
425
429
  const showSuffix = suffix && nameW - width(label) >= width(suffix);
426
430
  const started = m.started !== false;
427
431
  const sameModel = parentModel && shortModel(m.model) === shortModel(parentModel);