sprag-cli 3.90.3 → 3.90.4

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.ko.md CHANGED
@@ -63,7 +63,7 @@ pnpm이나 bun처럼 패키지 관리자가 설치 스크립트를 건너뛰면,
63
63
  🧠 Cache hit 98.8% · ⏳ Cache expires 59:46 · 📦 Ctx 47% of 1M
64
64
  ```
65
65
 
66
- ![statusline 예시. 첫 줄은 라우팅 절감액, 둘째 줄은 문서 변환 절감액, 셋째 줄은 진단 칩입니다](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
66
+ ![statusline 예시. 첫 줄은 라우팅 절감액과 모델별 사용 비중, 둘째 줄은 문서 변환 절감액, 셋째 줄은 진단 칩입니다](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
67
67
 
68
68
  Sprag는 사용자가 고른 모델을 바꾸지 않습니다. 분석은 로컬 세션 기록만 읽으며,
69
69
  추가 모델 호출이나 API 키가 필요하지 않습니다. `sprag uninstall` 은 설치 때
package/README.md CHANGED
@@ -79,7 +79,7 @@ If your package manager skips install scripts (pnpm, bun), run `sprag install` o
79
79
  🧠 Cache hit 98.8% · ⏳ Cache expires 59:46 · 📦 Ctx 47% of 1M
80
80
  ```
81
81
 
82
- ![statusline example: routing savings on row 1, document conversion savings on row 2, diagnostics on row 3](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
82
+ ![statusline example: routing savings and the share of spend by model on row 1, document conversion savings on row 2, diagnostics on row 3](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
83
83
 
84
84
  Sprag never swaps the model you picked. Analysis reads your local session
85
85
  logs only, with no extra model calls and no API key. `sprag uninstall` removes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.90.3",
3
+ "version": "3.90.4",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -110,6 +110,10 @@ export function recordDelegationEvents(events) {
110
110
  const data = loadLedger();
111
111
  data.version = LEDGER_VERSION;
112
112
  let changed = false;
113
+ // Earliest moment whose figures this call changed. A rescan that reprices or
114
+ // finds a run from days ago changes a day the team sync already uploaded;
115
+ // changedSince tells it to reach back that far (see changedSinceForSync).
116
+ let earliest = Infinity;
113
117
  const keyOf = new Map(Object.keys(data.events).map((k) => [runIdentity(k), k]));
114
118
  for (const e of events) {
115
119
  if (!e || !e.key || typeof e.usd !== 'number' || !Number.isFinite(e.usd) || !Number.isFinite(e.ts)) continue;
@@ -126,6 +130,7 @@ export function recordDelegationEvents(events) {
126
130
  if (prev && prev.ts === e.ts && prev.usd === usd && prev.cost === cost
127
131
  && prev.basis === (e.basis || undefined) && prev.priceSource === (e.priceSource || undefined)
128
132
  && prev.baselineSource === (e.baselineSource || undefined)) continue;
133
+ earliest = Math.min(earliest, e.ts, Number.isFinite(prev?.ts) ? prev.ts : Infinity);
129
134
  if (prevKey !== e.key) delete data.events[prevKey];
130
135
  keyOf.set(id, e.key);
131
136
  data.events[e.key] = {
@@ -142,6 +147,10 @@ export function recordDelegationEvents(events) {
142
147
  changed = true;
143
148
  }
144
149
  if (!changed) return;
150
+ if (Number.isFinite(earliest)) {
151
+ data.changedSince = Math.min(Number.isFinite(data.changedSince) ? data.changedSince : Infinity, earliest);
152
+ data.changeSeq = (Number(data.changeSeq) || 0) + 1;
153
+ }
145
154
  try {
146
155
  writeStateFile(ledgerPath(), JSON.stringify(data) + '\n');
147
156
  } catch {
@@ -149,6 +158,44 @@ export function recordDelegationEvents(events) {
149
158
  }
150
159
  }
151
160
 
161
+ /**
162
+ * The ledger's pending change mark, for the team sync: `since` is the earliest
163
+ * event time a recordDelegationEvents call changed after the last upload, and
164
+ * `seq` identifies that state so the sync clears only what it uploaded.
165
+ * null when nothing changed.
166
+ */
167
+ export function changedSinceForSync() {
168
+ const data = loadLedger();
169
+ // Ledgers written before the mark existed may already hold repriced days
170
+ // (the v3 rescan) that went up with old figures. The first sync after the
171
+ // upgrade re-sends every event it can reach once; uploads are upserts.
172
+ if (data.changeTracking !== 1) {
173
+ const ts = Object.values(data.events).map((e) => e?.ts).filter(Number.isFinite);
174
+ const since = Math.min(...ts, Number.isFinite(data.changedSince) ? data.changedSince : Infinity);
175
+ return { since: Number.isFinite(since) ? since : Date.now(), seq: Number(data.changeSeq) || 0, initial: true };
176
+ }
177
+ return Number.isFinite(data.changedSince) ? { since: data.changedSince, seq: Number(data.changeSeq) || 0 } : null;
178
+ }
179
+
180
+ /**
181
+ * Clear the change mark once the team sync uploaded from its day onward. A
182
+ * scan that changed the ledger again in the meantime bumped `seq`; the mark is
183
+ * then kept, so the next sync covers that change too.
184
+ */
185
+ export function clearChangedSince(seq) {
186
+ const data = loadLedger();
187
+ if ((Number(data.changeSeq) || 0) !== seq) return false;
188
+ if (!Number.isFinite(data.changedSince) && data.changeTracking === 1) return false;
189
+ delete data.changedSince;
190
+ data.changeTracking = 1;
191
+ try {
192
+ writeStateFile(ledgerPath(), JSON.stringify(data) + '\n');
193
+ return true;
194
+ } catch {
195
+ return false;
196
+ }
197
+ }
198
+
152
199
  /**
153
200
  * Family name of a model id, with the version dropped: `claude-opus-5` and
154
201
  * `claude-opus-4-5-20251101-v1:0` both read as `opus`.
package/src/team-sync.js CHANGED
@@ -40,7 +40,7 @@ import { memberId, readMemberId } from './member-id.js';
40
40
  import { userLanguage } from './config.js';
41
41
  import { debug } from './debug.js';
42
42
  import { trustSystemCA } from './system-ca.js';
43
- import { loadLedger, modelFamily, roundUsd } from './savings-ledger.js';
43
+ import { loadLedger, modelFamily, roundUsd, changedSinceForSync, clearChangedSince } from './savings-ledger.js';
44
44
  import { sessionCost, pricedParts } from './claude-price.js';
45
45
  import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
46
46
  import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
@@ -172,8 +172,12 @@ export function teamSyncDue(state, now = Date.now()) {
172
172
  * reaches back to `gatewaySyncedThrough`, the last day whose gateway figure
173
173
  * went up: a sync whose gateway call failed uploaded local figures only, and
174
174
  * those days are sent again (as upserts) once the gateway answers.
175
+ *
176
+ * `changedSince` (ms) is the earliest event time the delegation ledger changed
177
+ * since the last upload, for instance a rescan repricing runs from last week.
178
+ * The window reaches back to that day too, still no further than 30 days.
175
179
  */
176
- export function ledgerWindow(state, now = Date.now(), { gateway = false } = {}) {
180
+ export function ledgerWindow(state, now = Date.now(), { gateway = false, changedSince = null } = {}) {
177
181
  const today = new Date(now);
178
182
  const earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate() - (LEDGER_WINDOW_DAYS - 1));
179
183
  let start = earliest;
@@ -184,6 +188,11 @@ export function ledgerWindow(state, now = Date.now(), { gateway = false } = {})
184
188
  const from = parsed.map((m) => new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]) - 1)).sort((a, b) => a - b)[0];
185
189
  if (from > earliest) start = from;
186
190
  }
191
+ if (Number.isFinite(changedSince)) {
192
+ const c = new Date(changedSince);
193
+ const changedDay = new Date(c.getFullYear(), c.getMonth(), c.getDate());
194
+ if (changedDay < start) start = changedDay < earliest ? earliest : changedDay;
195
+ }
187
196
  const startKey = dayKey(start.getTime());
188
197
  // aggregateDaily cuts by time, so ask for a little more and filter by day below
189
198
  const days = Math.ceil((now - start.getTime()) / 86400000) + 1;
@@ -848,7 +857,11 @@ export async function syncTeam({
848
857
  let gatewayDaily = null;
849
858
  if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
850
859
  const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
851
- const win = ledgerWindow(state, now, { gateway: hasGateway });
860
+ // Days the delegation ledger changed after they were uploaded (a rescan
861
+ // repriced them) go up again from the earliest one.
862
+ let change = null;
863
+ try { change = changedSinceForSync(); } catch (e) { debug('team-sync', e); }
864
+ const win = ledgerWindow(state, now, { gateway: hasGateway, changedSince: change?.since });
852
865
  let prices = codexPrices;
853
866
  if (prices === undefined) {
854
867
  const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });
@@ -867,6 +880,9 @@ export async function syncTeam({
867
880
  delete next.syncFailures;
868
881
  delete next.lastError;
869
882
  saveTeamState(next, dir);
883
+ if (change) {
884
+ try { clearChangedSince(change.seq); } catch (e) { debug('team-sync', e); }
885
+ }
870
886
  refreshTeamRatchetFiles({ dir });
871
887
  await refreshStanding({ memberKey: state.memberKey, dir, fetch, now });
872
888
  const prompts = await syncPrompts({ state: next, dir, fetch, now });