@routinecrew/routinecode 2.31.87 → 2.31.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/bin/cli.sh +10 -0
  2. package/bin/prompt-vault.dat +1 -1
  3. package/bin/rc-login.js +5 -4
  4. package/bin/rc-savings.js +808 -0
  5. package/bin/rc-suggestions.js +100 -0
  6. package/bin/rc-team.js +1 -1
  7. package/hooks/hooks-config.json +9 -0
  8. package/hooks/lib/calibration.json +89 -0
  9. package/hooks/lib/card_gate.py +735 -0
  10. package/hooks/lib/cc-surface.json +1 -1
  11. package/hooks/lib/command_fix.py +209 -0
  12. package/hooks/lib/delegate_nudge.py +179 -0
  13. package/hooks/lib/deploy_suggest.py +312 -0
  14. package/hooks/lib/emit_raw.py +4 -0
  15. package/hooks/lib/knowledge_items.py +189 -19
  16. package/hooks/lib/knowledge_stock.py +604 -0
  17. package/hooks/lib/ops_guard.py +549 -0
  18. package/hooks/lib/prices.json +8 -0
  19. package/hooks/lib/route_ledger.py +622 -0
  20. package/hooks/lib/route_rules.json +88 -0
  21. package/hooks/lib/savings_emit.py +93 -0
  22. package/hooks/lib/secret_filter.py +11 -0
  23. package/hooks/lib/sync_manager.py +4 -1
  24. package/hooks/post-bash-verify.sh +14 -0
  25. package/hooks/post-edit-track.sh +9 -0
  26. package/hooks/pre-agent-spawn.mjs +1 -1
  27. package/hooks/pre-agent-spawn.sh +22 -2
  28. package/hooks/pre-bash-guard.sh +22 -0
  29. package/hooks/pre-bash-knowledge.sh +12 -2
  30. package/hooks/pre-edit-delegate.sh +15 -0
  31. package/hooks/pre-edit-guard.sh +10 -0
  32. package/hooks/pre-read-guard.sh +10 -0
  33. package/hooks/session-start.sh +6 -0
  34. package/hooks/stop-usage-metrics.sh +6 -0
  35. package/hooks/subagent-stop-usage.sh +36 -4
  36. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  37. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  38. package/package.json +1 -1
  39. package/plugin/.claude-plugin/plugin.json +1 -1
  40. package/plugin/agents/analyzer.md.sealed +1 -1
  41. package/plugin/agents/architect.md.sealed +1 -1
  42. package/plugin/agents/crawler.md.sealed +1 -1
  43. package/plugin/agents/explorer.md.sealed +1 -1
  44. package/plugin/agents/implementor-lite.md.sealed +1 -0
  45. package/plugin/agents/implementor.md.sealed +1 -1
  46. package/plugin/agents/looker.md.sealed +1 -1
  47. package/plugin/agents/ops-lite.md.sealed +1 -0
  48. package/plugin/agents/planner.md.sealed +1 -1
  49. package/plugin/agents/recorder.md.sealed +1 -1
  50. package/plugin/agents/reviewer.md.sealed +1 -1
  51. package/plugin/agents/runner-lite.md.sealed +1 -0
  52. package/plugin/agents/verifier.md.sealed +1 -1
  53. package/plugin/commands/analyze.md.sealed +1 -1
  54. package/plugin/commands/plan.md.sealed +1 -1
  55. package/plugin/commands/rc.md.sealed +1 -1
  56. package/plugin/commands/receipt.md.sealed +1 -1
  57. package/plugin/commands/recharge.md.sealed +1 -1
  58. package/plugin/commands/routines.md.sealed +1 -1
  59. package/plugin/commands/share.md.sealed +1 -1
  60. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -0,0 +1,808 @@
1
+ #!/usr/bin/env node
2
+ // `routinecode savings` — 순정 Opus 대비 절감 계산기 (설계 35 A10). zero-dep, ESM, 토큰 0.
3
+ //
4
+ // LLM·네트워크 호출이 없다(이 파일은 http/net/child_process 를 쓰지 않는다). 결정적 계산만 한다:
5
+ // 1) ~/.claude/projects/**/*.jsonl(서브에이전트 포함)에서 응답(message.id)당 1회 usage 를 읽는다.
6
+ // 마지막 처리 위치(파일별 바이트 오프셋)를 저장해 증분으로만 읽는다.
7
+ // 2) 단위(메인 세션 / 서브에이전트 카드)를 규칙으로 종류(bug|feature|multi|analysis|small|ops)에 분류한다.
8
+ // 카드는 route-ledger 의 CARD_KIND(kind_pre)를 우선, 없으면 도구 사용 패턴.
9
+ // 3) 순정 Opus 추정 = 내 기록 재생(서브에이전트 일을 메인에서 했다면: 메인 + 서브 토큰 Opus 가 + 재독 + 압축), 단순 1:1 비교(설계 35 A12).
10
+ // 재생 불가 세션만 실제 × ratio(kind). 같은 토큰을 Opus 단가로 친 값(설계 34 S2)이 항상 하한. 루틴코드 고정 부담·서버 비용은 넣지 않는다.
11
+ // 4) ~/.routinecode/savings.json 에 숫자만 쓴다(경로·세션 id·대화 원문 없음).
12
+ //
13
+ // routinecode savings [--json] [--no-update] 갱신 후 이번 주 표시 (--no-update: 저장된 값만)
14
+ // rc-savings.js --update --quiet [--budget-ms N] 훅용: 무음·시간 제한, 실패해도 종료코드 0
15
+ //
16
+ // 단가 표 = hooks/lib/prices.json, 배수표 = hooks/lib/calibration.json.
17
+
18
+ import {
19
+ closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, statSync,
20
+ unlinkSync, writeFileSync, appendFileSync,
21
+ } from 'node:fs';
22
+ import { homedir } from 'node:os';
23
+ import { basename, dirname, join } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { rcDir } from './rc-privacy.js';
26
+
27
+ const HERE = dirname(fileURLToPath(import.meta.url));
28
+ const KINDS = ['bug', 'feature', 'multi', 'analysis', 'small', 'ops'];
29
+ const KIND_KO = { bug: '버그', feature: '기능', multi: '여러 파일', analysis: '분석', small: '작은 수정', ops: '운영' };
30
+ const DAY = 86400;
31
+ const WINDOW_WEEKS = 9; // 현재 주 + 완료 8주(기준선은 최근 4주, 추이·누적은 전부)
32
+ const STATE_VERSION = 5;
33
+ const DEFAULT_SUMMARY_TOKENS = 20000; // 표식이 없을 때 요약 출력·재시작 맥락 기본값
34
+ const DEFAULT_COMPACT_WINDOW = 400000;
35
+ const MIN_LIVE_SAMPLES = 10; // 이 PC 표식이 이만큼 쌓이면 자기 값, 아니면 derived 값
36
+ const SOURCES = ['main', 'cc', 'routinecode', 'unknown'];
37
+ const SOURCE_KO = { main: '메인 대화', cc: 'Claude Code 기본 서브에이전트', routinecode: '루틴코드 서브에이전트', unknown: '출처 불명' };
38
+ const BINS = [['le10', '턴 10 이하', 10], ['mid', '턴 11~50', 50], ['long', '턴 51 이상', Infinity]];
39
+ const MAX_FILES_KEPT = 40; // 단위당 편집 파일 해시 상한(분류에 4개면 충분)
40
+
41
+ function readJson(p, fallback) {
42
+ try {
43
+ return JSON.parse(readFileSync(p, 'utf-8'));
44
+ } catch {
45
+ return fallback;
46
+ }
47
+ }
48
+
49
+ function writeJsonAtomic(p, obj) {
50
+ mkdirSync(dirname(p), { recursive: true });
51
+ const tmp = `${p}.${process.pid}.tmp`;
52
+ writeFileSync(tmp, JSON.stringify(obj));
53
+ renameSync(tmp, p);
54
+ }
55
+
56
+ export function loadPrices(path = join(HERE, '..', 'hooks', 'lib', 'prices.json')) {
57
+ return readJson(path, { per_1m: {} }).per_1m;
58
+ }
59
+
60
+ export function loadCalibration(path = join(HERE, '..', 'hooks', 'lib', 'calibration.json')) {
61
+ const c = readJson(path, null);
62
+ const kinds = {};
63
+ for (const k of KINDS) {
64
+ const r = (c && c.kinds && c.kinds[k]) || {};
65
+ const ratio = Math.max(1, Number(r.ratio) || 1);
66
+ kinds[k] = {
67
+ ratio,
68
+ low: Math.min(ratio, Math.max(1, Number(r.low) || 1)),
69
+ high: Math.max(ratio, Number(r.high) || ratio),
70
+ n: Number(r.n) || 0,
71
+ source: r.source === 'ab' ? 'ab' : 'estimate',
72
+ };
73
+ }
74
+ const rp = (c && c.replay) || {};
75
+ const correction = Math.max(0.01, Number(rp.correction) || 1);
76
+ const replay = {
77
+ correction,
78
+ low: Math.min(correction, Math.max(0.01, Number(rp.low) || correction)),
79
+ high: Math.max(correction, Number(rp.high) || correction),
80
+ n: Number(rp.n) || 0,
81
+ source: rp.source === 'ab' ? 'ab' : rp.source === 'replay-only' ? 'replay-only' : 'estimate',
82
+ };
83
+ const derived = (c && c.derived && typeof c.derived === 'object') ? c.derived : null;
84
+ return { derived, replay, version: (c && c.version) || 'none', model: (c && c.model) || null, measuredAt: (c && c.measuredAt) || null, kinds };
85
+ }
86
+
87
+ export function family(model) {
88
+ const m = model || '';
89
+ for (const k of ['opus', 'sonnet', 'haiku']) if (m.includes(k)) return k;
90
+ return null;
91
+ }
92
+
93
+ /** usage(Anthropic 형식)를 단가표로 환산(1M 토큰당 단가 → 사용량 단위). */
94
+ export function costOf(u, fam, prices) {
95
+ const p = fam && prices[fam];
96
+ if (!p || !u || typeof u !== 'object') return 0;
97
+ const n = (k) => Number(u[k]) || 0;
98
+ return (n('input_tokens') * p[0] + n('output_tokens') * p[1] + n('cache_read_input_tokens') * p[2]
99
+ + n('cache_creation_input_tokens') * p[3]) / 1e6;
100
+ }
101
+
102
+ /** 로컬 시각 월요일 00:00 (route-metrics.week_start 와 같다). 초 단위. */
103
+ export function weekStart(tSec) {
104
+ const d = new Date(tSec * 1000);
105
+ d.setHours(0, 0, 0, 0);
106
+ d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
107
+ return Math.floor(d.getTime() / 1000);
108
+ }
109
+
110
+ function weekLabel(ws) {
111
+ const d = new Date(ws * 1000);
112
+ const p = (n) => String(n).padStart(2, '0');
113
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
114
+ }
115
+
116
+ // ── 분류 (규칙 기반, LLM 없음) ──────────────────────────────────────────────
117
+
118
+ const BUG_RE = /(\bfix\b|\bbug\b|error|exception|crash|regress|fail|오류|버그|에러|고장|안\s?됨|안\s?돼|깨[짐졌]|실패|수정)/i;
119
+ const OPS_RE = /(\bssh |\brsync\b|\bscp\b|\bdocker |\bkubectl\b|\bsystemctl\b|\bnginx\b)/;
120
+ const LEDGER_KIND = { ops_read: 'ops', ops_proc: 'ops', run: 'ops', impl_large: 'multi', risk: 'multi', doc: 'small' };
121
+
122
+ export function newFeatures() {
123
+ return { edits: 0, files: [], reads: 0, ops: 0, bug: 0 };
124
+ }
125
+
126
+ /** features → kind. ledgerKind: route-ledger kind_pre/kind_post (카드일 때) */
127
+ export function classify(f, ledgerKind) {
128
+ if (ledgerKind && LEDGER_KIND[ledgerKind]) return LEDGER_KIND[ledgerKind];
129
+ const nfiles = f.files.length;
130
+ if (f.ops >= 3 && nfiles <= 2) return 'ops';
131
+ if (f.edits === 0) return f.reads > 0 ? 'analysis' : 'small';
132
+ if (nfiles >= 4) return 'multi';
133
+ if (f.bug) return 'bug';
134
+ if (nfiles <= 1 && f.edits <= 3) return 'small';
135
+ return 'feature';
136
+ }
137
+
138
+ function h32(s) {
139
+ let h = 2166136261;
140
+ for (let i = 0; i < s.length; i++) {
141
+ h ^= s.charCodeAt(i);
142
+ h = Math.imul(h, 16777619);
143
+ }
144
+ return h >>> 0;
145
+ }
146
+
147
+ function noteTools(f, content) {
148
+ if (!Array.isArray(content)) return;
149
+ for (const c of content) {
150
+ if (!c || c.type !== 'tool_use') continue;
151
+ const name = c.name || '';
152
+ const inp = c.input || {};
153
+ if (name === 'Edit' || name === 'Write' || name === 'NotebookEdit' || name === 'MultiEdit') {
154
+ f.edits++;
155
+ const fp = String(inp.file_path || inp.notebook_path || '');
156
+ const h = h32(fp);
157
+ if (fp && f.files.length < MAX_FILES_KEPT && !f.files.includes(h)) f.files.push(h);
158
+ } else if (name === 'Bash') {
159
+ if (OPS_RE.test(String(inp.command || ''))) f.ops++;
160
+ } else if (name === 'Read' || name === 'Grep' || name === 'Glob' || name.startsWith('mcp__')) {
161
+ f.reads++;
162
+ }
163
+ }
164
+ }
165
+
166
+ function firstText(msg) {
167
+ const c = msg && msg.content;
168
+ if (typeof c === 'string') return c;
169
+ if (Array.isArray(c)) {
170
+ for (const x of c) if (x && x.type === 'text' && typeof x.text === 'string') return x.text;
171
+ }
172
+ return '';
173
+ }
174
+
175
+ // ── 원장(CARD_KIND) ────────────────────────────────────────────────────────
176
+
177
+ export function loadLedgerKinds(ledgerPath) {
178
+ const byAgent = new Map(); // agent_id → { kind }
179
+ const openKind = new Map(); // card_id → kind_pre
180
+ let text = '';
181
+ try {
182
+ text = readFileSync(ledgerPath, 'utf-8');
183
+ } catch {
184
+ return byAgent;
185
+ }
186
+ const closes = [];
187
+ for (const line of text.split('\n')) {
188
+ if (!line) continue;
189
+ let d;
190
+ try {
191
+ d = JSON.parse(line);
192
+ } catch {
193
+ continue;
194
+ }
195
+ if (d.ev === 'card_open' && d.card_id && d.kind_pre) openKind.set(d.card_id, d.kind_pre);
196
+ else if (d.ev === 'card_close' && d.agent_id) closes.push(d);
197
+ }
198
+ for (const d of closes) byAgent.set(d.agent_id, { kind: openKind.get(d.card_id) || d.kind_post || null });
199
+ return byAgent;
200
+ }
201
+
202
+ // ── 증분 읽기 ──────────────────────────────────────────────────────────────
203
+
204
+ function listJsonl(root, sinceMs) {
205
+ const out = [];
206
+ const walk = (dir) => {
207
+ let ents;
208
+ try {
209
+ ents = readdirSync(dir, { withFileTypes: true });
210
+ } catch {
211
+ return;
212
+ }
213
+ for (const e of ents) {
214
+ const p = join(dir, e.name);
215
+ if (e.isDirectory()) walk(p);
216
+ else if (e.isFile() && e.name.endsWith('.jsonl')) {
217
+ try {
218
+ const st = statSync(p);
219
+ if (st.mtimeMs >= sinceMs) out.push({ p, size: st.size });
220
+ } catch { /* 사라진 파일 */ }
221
+ }
222
+ }
223
+ };
224
+ walk(root);
225
+ return out;
226
+ }
227
+
228
+ /** 서브에이전트 출처: 같은 이름 .meta.json 의 agentType(= Agent/Task 의 subagent_type)으로 규칙 분류. 못 읽으면 unknown. */
229
+ function sourceOf(p, sub) {
230
+ if (!sub) return 'main';
231
+ const t = readJson(`${p.slice(0, -'.jsonl'.length)}.meta.json`, {}).agentType;
232
+ if (typeof t !== 'string' || !t) return 'unknown';
233
+ return t.startsWith('routinecode:') ? 'routinecode' : 'cc';
234
+ }
235
+
236
+ function unitKeyOf(p) {
237
+ const sub = p.includes('/subagents/');
238
+ return { sub, parent: sub ? (/\/([^/]+)\/subagents\//.exec(p) || [])[1] || null : null, // 부모 세션 id = 'subagents' 바로 앞 폴더(workflows/wf_*/ 중첩 포함)
239
+ key: (sub ? 'sub:' : 'main:') + basename(p, '.jsonl'), agent: sub ? basename(p, '.jsonl').replace(/^agent-/, '') : null };
240
+ }
241
+
242
+ /** 한 파일의 새로 붙은 구간을 읽어 단위에 누적. 처리한 바이트 위치를 st.off 에 저장. */
243
+ function readFileIncremental(file, st, ctx) {
244
+ const fd = openSync(file.p, 'r');
245
+ try {
246
+ let pos = st.off || 0;
247
+ if (file.size < pos) pos = 0; // 잘렸거나 교체됨
248
+ const buf = Buffer.allocUnsafe(8 * 1024 * 1024);
249
+ let carry = Buffer.alloc(0);
250
+ let consumed = pos;
251
+ const uk = unitKeyOf(file.p);
252
+ let unit = ctx.units[uk.key];
253
+ const ensureUnit = () => {
254
+ if (!unit) unit = ctx.units[uk.key] = uk.sub
255
+ ? { s: 'sub', a: uk.agent, p: uk.parent, f: newFeatures(), w: {}, x: 0, t0: 0, t1: 0 }
256
+ : { s: 'main', a: null, f: newFeatures(), w: {}, t: [], cs: [], cb: [], cp: [] };
257
+ if (!unit.src || unit.src === 'unknown') unit.src = sourceOf(file.p, uk.sub);
258
+ return unit;
259
+ };
260
+ for (;;) {
261
+ const n = readSync(fd, buf, 0, buf.length, pos);
262
+ if (n <= 0) break;
263
+ pos += n;
264
+ const chunk = carry.length ? Buffer.concat([carry, buf.subarray(0, n)]) : Buffer.from(buf.subarray(0, n));
265
+ let start = 0;
266
+ for (;;) {
267
+ const nl = chunk.indexOf(10, start);
268
+ if (nl < 0) break;
269
+ const line = chunk.toString('utf-8', start, nl);
270
+ start = nl + 1;
271
+ if (line) processLine(line, ensureUnit, st, ctx);
272
+ }
273
+ consumed += start;
274
+ carry = chunk.subarray(start);
275
+ }
276
+ st.off = consumed;
277
+ } finally {
278
+ closeSync(fd);
279
+ }
280
+ }
281
+
282
+ function processLine(line, ensureUnit, st, ctx) {
283
+ if (line.includes('"subtype":"compact_boundary"')) {
284
+ // 압축 이벤트는 기록의 명시 표식만 인정한다. 다음 메인 응답의 맥락 = 압축 직후 크기
285
+ let d;
286
+ try {
287
+ d = JSON.parse(line);
288
+ } catch {
289
+ return;
290
+ }
291
+ const mts = Date.parse(d.timestamp || '') / 1000;
292
+ const u0 = ensureUnit();
293
+ if (u0.s === 'main' && d.type === 'system' && d.compactMetadata && mts >= ctx.minTs) {
294
+ u0.cb.push(mts);
295
+ const post = Number(d.compactMetadata.postTokens);
296
+ if (post > 0) u0.cp.push(mts, post); // 요약 본문 크기(출력 토큰)
297
+ st.pend = true;
298
+ }
299
+ return;
300
+ }
301
+ if (!line.includes('"type":"assistant"')) {
302
+ // 첫 요청 문장에서 버그 단어 여부만 본다(원문은 저장하지 않는다)
303
+ if ((st.ptxt || 0) >= 2 || !line.includes('"type":"user"') || line.includes('"tool_result"')) return;
304
+ let d;
305
+ try {
306
+ d = JSON.parse(line);
307
+ } catch {
308
+ return;
309
+ }
310
+ const t = firstText(d.message);
311
+ if (!t) return;
312
+ st.ptxt = (st.ptxt || 0) + 1;
313
+ if (BUG_RE.test(t.slice(0, 2000))) ensureUnit().f.bug = 1;
314
+ return;
315
+ }
316
+ let d;
317
+ try {
318
+ d = JSON.parse(line);
319
+ } catch {
320
+ return;
321
+ }
322
+ const m = d.message;
323
+ if (!m || !m.usage) return;
324
+ const u = ensureUnit();
325
+ const id = m.id;
326
+ if (id) {
327
+ if (st.lastId === id) return; // 같은 응답의 이어진 줄
328
+ st.lastId = id;
329
+ const key = String(id).replace(/^msg_/, '').slice(0, 12);
330
+ if (ctx.seen.has(key)) return; // 다른 파일(재개 세션)에서 이미 센 응답
331
+ ctx.seen.add(key);
332
+ ctx.newSeen.push(key);
333
+ }
334
+ noteTools(u.f, m.content);
335
+ const ts = Date.parse(d.timestamp || '') / 1000;
336
+ if (!ts || ts < ctx.minTs) return;
337
+ const fam = family(m.model);
338
+ if (!fam) return;
339
+ const us = m.usage;
340
+ if (u.s === 'sub') {
341
+ // 재생 계산용: 이 서브에이전트가 만든 내용 = 새로 읽은 입력(cache_creation) + 출력, 끝난 시각
342
+ u.x += (Number(us.cache_creation_input_tokens) || 0) + (Number(us.output_tokens) || 0);
343
+ if (!u.t0 || ts < u.t0) u.t0 = ts;
344
+ if (ts > u.t1) u.t1 = ts;
345
+ } else {
346
+ const cx = (Number(us.input_tokens) || 0) + (Number(us.cache_read_input_tokens) || 0) + (Number(us.cache_creation_input_tokens) || 0);
347
+ u.t.push(ts, cx);
348
+ if (st.pend) {
349
+ u.cs.push(ts, cx);
350
+ st.pend = false;
351
+ }
352
+ }
353
+ const ws = weekStart(ts);
354
+ const w = u.w[ws] || (u.w[ws] = { c: 0, o: 0, m: {} });
355
+ const cc = costOf(m.usage, fam, ctx.prices);
356
+ w.m[fam] = (w.m[fam] || 0) + cc;
357
+ w.c += cc;
358
+ w.o += costOf(m.usage, 'opus', ctx.prices);
359
+ }
360
+
361
+ function lockAcquire(p) {
362
+ try {
363
+ if (Date.now() - statSync(p).mtimeMs < 5 * 60 * 1000) return false;
364
+ } catch { /* 없음 */ }
365
+ try {
366
+ writeFileSync(p, String(process.pid));
367
+ return true;
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+
373
+ /**
374
+ * 증분 갱신. opts: {projects, ledger, dir, now(sec), budgetMs, prices, calibration}
375
+ * 반환: {status:'ok'|'busy'|'partial', files, bytes}
376
+ */
377
+ export function update(opts = {}) {
378
+ const dir = opts.dir || rcDir();
379
+ const projects = opts.projects || join(homedir(), '.claude', 'projects');
380
+ const now = opts.now || Math.floor(Date.now() / 1000);
381
+ const prices = opts.prices || loadPrices();
382
+ const lock = join(dir, 'savings.lock');
383
+ mkdirSync(dir, { recursive: true });
384
+ if (!lockAcquire(lock)) return { status: 'busy', files: 0 };
385
+ const t0 = Date.now();
386
+ try {
387
+ const statePath = join(dir, 'savings-state.json');
388
+ const seenPath = join(dir, 'savings-seen.txt');
389
+ const state = readJson(statePath, null);
390
+ const S = state && state.v === STATE_VERSION ? state : { v: STATE_VERSION, files: {}, units: {} };
391
+ const minTs = weekStart(now) - (WINDOW_WEEKS - 1) * 7 * DAY;
392
+ const seen = new Set();
393
+ if (S.files && !Object.keys(S.files).length && !Object.keys(S.units).length) writeFileSync(seenPath, '');
394
+ try {
395
+ for (const k of readFileSync(seenPath, 'utf-8').split('\n')) if (k) seen.add(k);
396
+ } catch { /* 첫 실행 */ }
397
+ const ctx = { units: S.units, seen, newSeen: [], prices, minTs };
398
+ const files = listJsonl(projects, minTs * 1000);
399
+ // 새로 붙은 바이트가 있는 파일만, 작은 것부터(시간 제한 안에 많이 끝내려고)
400
+ const todo = files.filter((f) => ((S.files[f.p] || {}).off || 0) !== f.size).sort((a, b) => a.size - b.size);
401
+ let done = 0;
402
+ let bytes = 0;
403
+ let partial = false;
404
+ for (const f of todo) {
405
+ if (opts.budgetMs && Date.now() - t0 > opts.budgetMs) {
406
+ partial = true;
407
+ break;
408
+ }
409
+ const st = S.files[f.p] || (S.files[f.p] = { off: 0 });
410
+ try {
411
+ readFileIncremental(f, st, ctx);
412
+ done++;
413
+ bytes += f.size;
414
+ } catch { /* 읽기 실패 파일은 다음 기회에 */ }
415
+ }
416
+ // 창 밖 주·사라진 파일 정리
417
+ for (const u of Object.values(S.units)) {
418
+ for (const k of Object.keys(u.w)) if (Number(k) < minTs) delete u.w[k];
419
+ if (u.t) {
420
+ let i = 0;
421
+ while (i < u.t.length && u.t[i] < minTs) i += 2;
422
+ if (i) u.t = u.t.slice(i);
423
+ let j = 0;
424
+ while (j < u.cs.length && u.cs[j] < minTs) j += 2;
425
+ if (j) u.cs = u.cs.slice(j);
426
+ u.cb = u.cb.filter((x) => x >= minTs);
427
+ let q = 0;
428
+ while (q < u.cp.length && u.cp[q] < minTs) q += 2;
429
+ if (q) u.cp = u.cp.slice(q);
430
+ }
431
+ }
432
+ for (const [k, u] of Object.entries(S.units)) if (!Object.keys(u.w).length) delete S.units[k];
433
+ const live = new Set(files.map((f) => f.p));
434
+ for (const p of Object.keys(S.files)) if (!live.has(p)) delete S.files[p];
435
+ if (ctx.newSeen.length) appendFileSync(seenPath, `${ctx.newSeen.join('\n')}\n`);
436
+ writeJsonAtomic(statePath, S);
437
+ const cal = opts.calibration || loadCalibration();
438
+ const ledger = loadLedgerKinds(opts.ledger || join(dir, 'knowledge', 'route-ledger.jsonl'));
439
+ const report = compute(S.units, ledger, cal, now, { limit: opts.limit });
440
+ report.partial = partial;
441
+ writeJsonAtomic(join(dir, 'savings.json'), report);
442
+ return { status: partial ? 'partial' : 'ok', files: done, bytes };
443
+ } finally {
444
+ try {
445
+ unlinkSync(lock);
446
+ } catch { /* 이미 없음 */ }
447
+ }
448
+ }
449
+
450
+ // ── 계산 ────────────────────────────────────────────────────────────────────
451
+
452
+ /** 압축 한도: 인자 > 환경변수 CLAUDE_CODE_AUTO_COMPACT_WINDOW > 400000 */
453
+ export function compactLimit(limit) {
454
+ return Number(limit) || Number(process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW) || DEFAULT_COMPACT_WINDOW;
455
+ }
456
+
457
+ const median = (xs) => {
458
+ xs.sort((a, b) => a - b);
459
+ const mid = xs.length >> 1;
460
+ return xs.length % 2 ? xs[mid] : Math.round((xs[mid - 1] + xs[mid]) / 2);
461
+ };
462
+
463
+ /**
464
+ * 압축 표식(compact_boundary)에서만 잰 두 값 — 서로 다른 것이다.
465
+ * out = compactMetadata.postTokens 중앙값: 압축이 만든 요약 본문 크기 → 출력 단가를 적용한다
466
+ * restart = 표식 직후 첫 메인 응답의 맥락(input+cache_read+cache_creation) 중앙값: 압축 뒤 재시작 맥락, 이후 턴 재독의 출발점(출력 아님)
467
+ * 표식이 없으면 둘 다 기본값.
468
+ */
469
+ export function summaryTokens(units) {
470
+ const rs = [];
471
+ const os = [];
472
+ let markers = 0;
473
+ for (const key of Object.keys(units).sort()) {
474
+ const u = units[key];
475
+ if (!u.cs) continue;
476
+ markers += (u.cb || []).length;
477
+ for (let k = 1; k < u.cs.length; k += 2) rs.push(u.cs[k]);
478
+ for (let k = 1; k < (u.cp || []).length; k += 2) os.push(u.cp[k]);
479
+ }
480
+ return {
481
+ restart: rs.length ? median(rs) : DEFAULT_SUMMARY_TOKENS,
482
+ out: os.length ? median(os) : DEFAULT_SUMMARY_TOKENS,
483
+ measured: rs.length > 0,
484
+ events: markers,
485
+ samples: rs.length,
486
+ outSamples: os.length,
487
+ };
488
+ }
489
+
490
+ /**
491
+ * 한 세션 재생(설계 35 A11): 서브에이전트 일을 메인 한 곳에서 했다고 다시 계산한 "추가분".
492
+ * 서브에이전트가 끝난 뒤 첫 메인 턴부터 그 내용(x 토큰)이 메인 맥락에 더해져 남은 턴마다 캐시 읽기 단가로 다시 읽힌다.
493
+ * 맥락(실제 + 추가분)이 한도를 넘는 턴에 압축 1회(그 시점 맥락 읽기 + 요약 출력) 후 추가분은 요약 기준으로 재시작한다.
494
+ * 반환: 주(ws) → {re: 재독, cp: 압축} (Opus 단가)
495
+ */
496
+ export function replaySession(main, subs, limit, restart, summaryOut, prices) {
497
+ const t = main.t || [];
498
+ const n = t.length / 2;
499
+ const adds = new Array(n).fill(0);
500
+ for (const sub of subs) {
501
+ if (!(sub.x > 0)) continue;
502
+ let e = 0;
503
+ while (e < n && t[2 * e] <= sub.t1) e++;
504
+ if (e < n) adds[e] += sub.x;
505
+ }
506
+ const cr = prices.opus[2];
507
+ const out = prices.opus[1];
508
+ const res = {};
509
+ let E = 0;
510
+ for (let j = 0; j < n; j++) {
511
+ E += adds[j];
512
+ const a = t[2 * j + 1];
513
+ const ws = weekStart(t[2 * j]);
514
+ const W = res[ws] || (res[ws] = { re: 0, cp: 0 });
515
+ if (E > 0 && a + E > limit) { // 추가분 때문에 넘는 경우만(실제 메인이 이미 한 압축은 실제 사용량에 있다)
516
+ W.cp += ((a + E) * cr + summaryOut * out) / 1e6; // 그 시점 맥락 읽기 + 요약 본문 출력
517
+ E = Math.max(0, restart - a); // 압축 뒤 재시작 맥락에서 이어간다
518
+ }
519
+ W.re += (E * cr) / 1e6;
520
+ }
521
+ return res;
522
+ }
523
+
524
+ /** 단위들 → 주별·종류별 합계와 이번 주 요약. 결정적(같은 입력 → 같은 출력). 재생 불가 서브에이전트만 종류별 배수. */
525
+ export function compute(units, ledgerKinds, cal, now, opts = {}) {
526
+ const prices = opts.prices || loadPrices();
527
+ const limit = compactLimit(opts.limit);
528
+ // 압축 직후 맥락: 인자 > 내 기록의 표식(10건 이상) > calibration.json derived(지난 기록으로 정한 값) > 기본값
529
+ const live = summaryTokens(units);
530
+ const dc = cal.derived && cal.derived.compaction;
531
+ const base0 = { measured: true, events: 0, samples: 0, outSamples: 0 };
532
+ const summ = opts.summary
533
+ ? { ...base0, restart: opts.summary, out: opts.summaryOut || opts.summary }
534
+ : live.samples >= MIN_LIVE_SAMPLES ? live
535
+ : dc && dc.samples > 0 && dc.restartTokens > 0
536
+ ? { restart: dc.restartTokens, out: dc.summaryOutTokens || DEFAULT_SUMMARY_TOKENS, measured: true, events: dc.markers || 0, samples: dc.samples, outSamples: dc.outSamples || 0, derived: true }
537
+ : live;
538
+ const keys = Object.keys(units).sort();
539
+ const subsOf = {};
540
+ for (const key of keys) {
541
+ const u = units[key];
542
+ if (u.s === 'sub' && u.p && units[`main:${u.p}`]) (subsOf[u.p] = subsOf[u.p] || []).push(u);
543
+ }
544
+ const rp = cal.replay;
545
+ const weeks = {};
546
+ const newWeek = () => ({ actual: 0, same: 0, est: 0, low: 0, high: 0, kinds: {}, src: {}, mainOwn: 0, subTok: 0, reread: 0, comp: 0, fbActual: 0, bins: {} });
547
+ const binOf = (turns) => BINS.find((b) => turns <= b[2])[0];
548
+ let nUnits = 0;
549
+ let nFallback = 0;
550
+ for (const key of keys) {
551
+ const u = units[key];
552
+ const lk = u.s === 'sub' && u.a && ledgerKinds.get(u.a) ? ledgerKinds.get(u.a).kind : null;
553
+ const kind = classify(u.f, lk);
554
+ const c = cal.kinds[kind];
555
+ const isMain = u.s === 'main';
556
+ const parentMain = !isMain && u.p ? units[`main:${u.p}`] : null;
557
+ const replayed = isMain || !!parentMain;
558
+ nUnits++;
559
+ if (!replayed) nFallback++;
560
+ const extra = isMain ? replaySession(u, subsOf[key.slice(5)] || [], limit, summ.restart, summ.out, prices) : {};
561
+ const turns = isMain ? (u.t || []).length / 2 : parentMain ? (parentMain.t || []).length / 2 : 0;
562
+ const bin = replayed && turns > 0 ? binOf(turns) : null;
563
+ const wsSet = new Set([...Object.keys(u.w), ...Object.keys(extra)]);
564
+ for (const ws of wsSet) {
565
+ const { c: act = 0, o: same = 0, m: byModel = {} } = u.w[ws] || {};
566
+ const ex = extra[ws] || { re: 0, cp: 0 };
567
+ if (!(act > 0) && !(ex.re > 0) && !(ex.cp > 0)) continue;
568
+ const W = weeks[ws] || (weeks[ws] = newWeek());
569
+ let est;
570
+ let low;
571
+ let high;
572
+ if (replayed) {
573
+ const base = same + ex.re + ex.cp;
574
+ est = Math.max(base * rp.correction, same);
575
+ low = Math.max(base * rp.low, same);
576
+ high = Math.max(base * rp.high, est);
577
+ if (isMain) W.mainOwn += same;
578
+ else W.subTok += same;
579
+ W.reread += ex.re;
580
+ W.comp += ex.cp;
581
+ } else {
582
+ est = Math.max(act * c.ratio, same);
583
+ low = Math.max(act * c.low, same);
584
+ high = Math.max(act * c.high, est);
585
+ W.fbActual += act;
586
+ }
587
+ W.actual += act;
588
+ W.same += same;
589
+ W.est += est;
590
+ W.low += low;
591
+ W.high += high;
592
+ if (bin) {
593
+ const B = W.bins[bin] || (W.bins[bin] = { sessions: 0, actual: 0, est: 0 });
594
+ B.actual += act;
595
+ B.est += est;
596
+ if (isMain) B.sessions += 1;
597
+ }
598
+ const src = SOURCES.includes(u.src) ? u.src : 'unknown';
599
+ const SS = W.src[src] || (W.src[src] = { actual: 0, models: {} });
600
+ SS.actual += act;
601
+ for (const [fam, v] of Object.entries(byModel)) SS.models[fam] = (SS.models[fam] || 0) + v;
602
+ const K = W.kinds[kind] || (W.kinds[kind] = { n: 0, actual: 0, est: 0 });
603
+ K.n += 1;
604
+ K.actual += act;
605
+ K.est += est;
606
+ }
607
+ }
608
+ const cur = weekStart(now);
609
+ const done = Object.keys(weeks).map(Number).filter((w) => w < cur && weeks[w].actual > 0).sort((a, b) => b - a).slice(0, 4);
610
+ const baseline = done.length ? done.reduce((s, w) => s + weeks[w].actual, 0) / done.length : 0;
611
+ const pct = (x, base) => (base > 0 ? Math.round((x / base) * 1000) / 10 : null);
612
+ const row = (ws) => {
613
+ const W = weeks[ws] || newWeek();
614
+ const base = baseline > 0 ? baseline : W.actual;
615
+ const sav = (den) => (den > 0 ? Math.round((1 - W.actual / den) * 1000) / 10 : 0);
616
+ return {
617
+ week: weekLabel(Number(ws)),
618
+ actualPct: pct(W.actual, base),
619
+ opusPct: pct(W.est, base),
620
+ opusLowPct: pct(W.low, base),
621
+ opusHighPct: pct(W.high, base),
622
+ sameTokenOpusPct: pct(W.same, base),
623
+ savingPct: sav(W.est),
624
+ savingLowPct: sav(W.low),
625
+ savingHighPct: sav(W.high),
626
+ multiple: W.actual > 0 ? Math.round((W.est / W.actual) * 100) / 100 : null,
627
+ replay: {
628
+ mainOwnPct: pct(W.mainOwn, base),
629
+ subTokensPct: pct(W.subTok, base),
630
+ rereadPct: pct(W.reread, base),
631
+ compactionPct: pct(W.comp, base),
632
+ fallbackActualPct: W.actual > 0 ? Math.round((W.fbActual / W.actual) * 1000) / 10 : null,
633
+ },
634
+ byLength: Object.fromEntries(BINS.filter((b) => W.bins[b[0]]).map((b) => [b[0], {
635
+ label: b[1], sessions: W.bins[b[0]].sessions, actualPct: pct(W.bins[b[0]].actual, base), opusPct: pct(W.bins[b[0]].est, base),
636
+ savingPct: W.bins[b[0]].est > 0 ? Math.round((1 - W.bins[b[0]].actual / W.bins[b[0]].est) * 1000) / 10 : null,
637
+ }])),
638
+ byOrigin: Object.fromEntries(SOURCES.filter((k) => W.src[k]).map((k) => [k, {
639
+ actualPct: pct(W.src[k].actual, base),
640
+ models: Object.fromEntries(Object.entries(W.src[k].models).sort().map(([f, v]) => [f, pct(v, base)])),
641
+ }])),
642
+ kinds: Object.fromEntries(KINDS.filter((k) => W.kinds[k]).map((k) => [k, {
643
+ n: W.kinds[k].n, actualPct: pct(W.kinds[k].actual, base), opusPct: pct(W.kinds[k].est, base),
644
+ }])),
645
+ };
646
+ };
647
+ // 화면 추이·누적(설계 35 A13): 데이터 있는 주만, 숫자만. 누적은 창 안 전체(순정 Opus=100 환산).
648
+ const liveWeeks = Object.keys(weeks).map(Number).filter((w) => weeks[w].actual > 0 && weeks[w].est > 0).sort((a, b) => a - b);
649
+ const sumA = liveWeeks.reduce((x, w) => x + weeks[w].actual, 0);
650
+ const sumE = liveWeeks.reduce((x, w) => x + weeks[w].est, 0);
651
+ const r1 = (x) => Math.round(x * 10) / 10;
652
+ const history = liveWeeks.slice(-8).map((w) => {
653
+ const base = baseline > 0 ? baseline : weeks[w].actual;
654
+ return { week: weekLabel(w), savingPct: r1((1 - weeks[w].actual / weeks[w].est) * 100), actualPct: pct(weeks[w].actual, base), opusPct: pct(weeks[w].est, base) };
655
+ });
656
+ // 최근 4주 합산(실제 합 ÷ 순정 합, 순정 Opus=100 환산) — 화면 큰 숫자(설계 35 A13)
657
+ const last4 = liveWeeks.slice(-4);
658
+ const a4 = last4.reduce((x, w) => x + weeks[w].actual, 0);
659
+ const e4 = last4.reduce((x, w) => x + weeks[w].est, 0);
660
+ const recent4 = e4 > 0 ? { weeks: last4.length, actualPct: r1((a4 / e4) * 100), opusPct: 100, savingPct: r1((1 - a4 / e4) * 100) } : null;
661
+ const cumulative = sumE > 0 ? { weeks: liveWeeks.length, actualPct: r1((sumA / sumE) * 100), opusPct: 100, savingPct: r1((1 - sumA / sumE) * 100) } : null;
662
+ const calibrated = rp.source === 'ab' && KINDS.every((k) => cal.kinds[k].source === 'ab');
663
+ return {
664
+ schema: 2,
665
+ generatedAt: new Date(now * 1000).toISOString(),
666
+ calibration: { version: cal.version, model: cal.model, measuredAt: cal.measuredAt, calibrated, replayOnly: rp.source === 'replay-only', replayCorrection: rp.correction, replaySource: rp.source },
667
+ replayParams: { compactWindow: limit, restartTokens: summ.restart, summaryOutTokens: summ.out, summaryMeasured: summ.measured, compactEvents: summ.events, restartSamples: summ.samples, summaryOutSamples: summ.outSamples, summaryDerived: !!summ.derived },
668
+ fallbackUnitPct: nUnits ? Math.round((nFallback / nUnits) * 1000) / 10 : 0,
669
+ baselineWeeks: done.length,
670
+ current: row(cur),
671
+ history,
672
+ cumulative,
673
+ recent4,
674
+ };
675
+ }
676
+
677
+ /**
678
+ * 지난 기록(창 안 전부)으로 계산기 매개변수를 정한다 → calibration.json 의 derived 블록.
679
+ * 압축 직후 맥락 중앙값(표식만), 서브 결과가 메인에 붙는 지연(서브 종료 → 다음 메인 턴), 부모 세션 연결률, 종류 분포.
680
+ */
681
+ export function derive(units, ledgerKinds, now) {
682
+ const comp = summaryTokens(units);
683
+ const lags = [];
684
+ let subs = 0;
685
+ let linked = 0;
686
+ const kinds = {};
687
+ for (const key of Object.keys(units).sort()) {
688
+ const u = units[key];
689
+ const lk = u.s === 'sub' && u.a && ledgerKinds.get(u.a) ? ledgerKinds.get(u.a).kind : null;
690
+ const k = classify(u.f, lk);
691
+ kinds[k] = (kinds[k] || 0) + 1;
692
+ if (u.s !== 'sub') continue;
693
+ subs++;
694
+ const main = u.p && units[`main:${u.p}`];
695
+ if (!main) continue;
696
+ linked++;
697
+ const t = main.t || [];
698
+ for (let j = 0; j < t.length; j += 2) {
699
+ if (t[j] > u.t1) {
700
+ lags.push(t[j] - u.t1);
701
+ break;
702
+ }
703
+ }
704
+ }
705
+ lags.sort((a, b) => a - b);
706
+ const q = (f) => (lags.length ? Math.round(lags[Math.min(lags.length - 1, Math.floor(lags.length * f))]) : null);
707
+ const to = weekStart(now) + 7 * DAY;
708
+ return {
709
+ period: { from: new Date((weekStart(now) - (WINDOW_WEEKS - 1) * 7 * DAY) * 1000).toISOString().slice(0, 10), to: new Date(to * 1000).toISOString().slice(0, 10), weeks: WINDOW_WEEKS },
710
+ compaction: { restartTokens: comp.measured ? comp.restart : null, summaryOutTokens: comp.outSamples ? comp.out : null, samples: comp.samples, outSamples: comp.outSamples, markers: comp.events },
711
+ resultLagSec: { median: q(0.5), p90: q(0.9), n: lags.length },
712
+ linkage: { subUnits: subs, linked, ratePct: subs ? Math.round((linked / subs) * 1000) / 10 : null },
713
+ kinds,
714
+ };
715
+ }
716
+
717
+ // ── 표시 ────────────────────────────────────────────────────────────────────
718
+
719
+ export function render(rep) {
720
+ const c = rep.current;
721
+ const L = [];
722
+ const est = rep.calibration.replayOnly ? ' — 실사용 기록 재생 계산' : rep.calibration.calibrated ? '' : ' (보정 전 추정)';
723
+ L.push(`이번 주(${c.week} 시작) 사용량${est}`);
724
+ L.push(' 루틴코드 고정 부담·서버 비용은 제외(1:1 비교)');
725
+ if (c.actualPct === null) {
726
+ L.push(' 집계된 사용량이 아직 없습니다.');
727
+ return L.join('\n');
728
+ }
729
+ const basis = rep.baselineWeeks > 0 ? `기준 = 직전 ${rep.baselineWeeks}주 평균 100%` : '기준 주가 아직 없어 이번 주 실제를 100%로 둡니다';
730
+ L.push(` 실제 ${c.actualPct}% · 순정 Opus 였다면 ${c.opusPct}%(${c.opusLowPct}~${c.opusHighPct}%) · 절감 ${c.savingPct}%(${c.savingLowPct}~${c.savingHighPct}%)`);
731
+ L.push(` 순정 Opus 대비 ${c.multiple}배 · 같은 토큰을 Opus 단가로 친 하한 ${c.sameTokenOpusPct}% · ${basis}`);
732
+ const ks = Object.keys(c.kinds);
733
+ if (ks.length) {
734
+ L.push(' 종류별(실제% → 순정 Opus%)');
735
+ for (const k of ks) L.push(` ${KIND_KO[k]} ${c.kinds[k].n}건 ${c.kinds[k].actualPct}% → ${c.kinds[k].opusPct}%`);
736
+ }
737
+ if (c.replay) {
738
+ const r = c.replay;
739
+ L.push(` 순정 Opus 재생(내 기록 기준) = 메인 ${r.mainOwnPct}% + 서브에이전트 토큰을 Opus 로 ${r.subTokensPct}% + 늘어난 맥락 재독 ${r.rereadPct}% + 압축 ${r.compactionPct}%`);
740
+ const p = rep.replayParams;
741
+ L.push(` 압축 한도 ${p.compactWindow} · 압축 뒤 재시작 맥락 ${p.restartTokens}토큰 · 요약 출력 ${p.summaryOutTokens}토큰(${p.summaryDerived ? '지난 기록으로 정한 값' : p.summaryMeasured ? `압축 표식 ${p.compactEvents}회, 재시작 ${p.restartSamples}건·요약 ${p.summaryOutSamples}건 중앙값` : '표식 없음 → 기본값'}) · 재생 불가(배수 대체) 사용량 ${r.fallbackActualPct}% · 세션 단위 ${rep.fallbackUnitPct}%`);
742
+ }
743
+ const bl = Object.values(c.byLength || {});
744
+ if (bl.length) {
745
+ L.push(' 세션 길이별 절감(메인 턴 수 기준, 서브에이전트 포함)');
746
+ for (const x of bl) L.push(` ${x.label} ${x.sessions}세션 실제 ${x.actualPct}% → 순정 Opus ${x.opusPct}% 절감 ${x.savingPct === null ? '-' : `${x.savingPct}%`}`);
747
+ }
748
+ const ss = Object.keys(c.byOrigin || {});
749
+ if (ss.length) {
750
+ L.push(' 출처별 실제 사용량(주간 %, 모델별)');
751
+ for (const k of ss) {
752
+ const ms = Object.entries(c.byOrigin[k].models).filter(([, v]) => v > 0).map(([f, v]) => `${f} ${v}%`).join(' · ');
753
+ L.push(` ${SOURCE_KO[k]} ${c.byOrigin[k].actualPct}%${ms ? ` (${ms})` : ''}`);
754
+ }
755
+ }
756
+ L.push(` 배수표 ${rep.calibration.version}${rep.calibration.replayOnly ? ' — 보정 계수 1.0(재생 값 그대로), 종류별 배수는 재생 불가 사용량에만' : est ? ' — 보수 추정값' : ''}. 계산은 이 PC 에서만, 숫자만 ~/.routinecode/savings.json 에 저장합니다.`);
757
+ return L.join('\n');
758
+ }
759
+
760
+ // ── CLI ─────────────────────────────────────────────────────────────────────
761
+
762
+ function main(argv) {
763
+ const has = (f) => argv.includes(f);
764
+ const arg = (f) => {
765
+ const i = argv.indexOf(f);
766
+ return i >= 0 ? argv[i + 1] : undefined;
767
+ };
768
+ const quiet = has('--quiet');
769
+ const dir = rcDir();
770
+ if (!has('--no-update')) {
771
+ if (!quiet && !existsSync(join(dir, 'savings-state.json'))) console.error('처음 한 번은 최근 5주 대화 기록을 읽느라 시간이 걸릴 수 있습니다...');
772
+ const r = update({
773
+ budgetMs: Number(arg('--budget-ms')) || 0, projects: arg('--projects'), ledger: arg('--ledger'),
774
+ now: arg('--now') ? Number(arg('--now')) : undefined,
775
+ calibration: arg('--calibration') ? loadCalibration(arg('--calibration')) : undefined,
776
+ });
777
+ if (quiet) return;
778
+ if (r.status === 'partial') console.error('시간 제한으로 일부만 처리했습니다. 다시 실행하면 이어서 계산합니다.');
779
+ }
780
+ if (has('--derive')) {
781
+ const st = readJson(join(dir, 'savings-state.json'), null);
782
+ if (!st || !st.units) throw new Error('상태가 없습니다(먼저 savings 를 한 번 실행).');
783
+ const calPath = arg('--write') || join(HERE, '..', 'hooks', 'lib', 'calibration.json');
784
+ const d = derive(st.units, loadLedgerKinds(arg('--ledger') || join(dir, 'knowledge', 'route-ledger.jsonl')), arg('--now') ? Number(arg('--now')) : Math.floor(Date.now() / 1000));
785
+ const cal = readJson(calPath, {});
786
+ cal.derived = d;
787
+ writeFileSync(calPath, `${JSON.stringify(cal, null, 2)}\n`);
788
+ console.log(JSON.stringify(d, null, 2));
789
+ return;
790
+ }
791
+ if (quiet) return;
792
+ const rep = readJson(join(dir, 'savings.json'), null);
793
+ if (!rep) {
794
+ console.error('savings.json 이 없습니다.');
795
+ process.exit(1);
796
+ }
797
+ console.log(has('--json') ? JSON.stringify(rep, null, 2) : render(rep));
798
+ }
799
+
800
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
801
+ try {
802
+ main(process.argv.slice(2));
803
+ } catch (e) {
804
+ if (process.argv.includes('--quiet')) process.exit(0);
805
+ console.error(`savings: ${e && e.message ? e.message : e}`);
806
+ process.exit(1);
807
+ }
808
+ }