sprag-cli 3.96.0 → 3.97.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.
package/docs/TEAM.ko.md CHANGED
@@ -53,7 +53,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
53
53
 
54
54
  팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
55
55
 
56
- 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_rules_report`(위 위임 룰 요약), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다. LiteLLM 게이트웨이를 설정했다면 하루 동기화마다 게이트웨이의 `GET /user/info` 와 `GET /global/spend/logs` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. 비용을 계산하려고 `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` 아래의 Claude 데스크톱 앱 Cowork 기록을 로컬에서 읽습니다. 밖으로 나가는 것은 하루 합계뿐이며 작업 이름과 프롬프트는 보내지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
56
+ 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_rules_report`(위 위임 룰 요약), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다. LiteLLM 게이트웨이를 설정했다면 하루 동기화마다 게이트웨이의 `GET /user/info` 와 `GET /spend/logs/v2` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 요청 시각을 로컬 날짜(한국 PC는 한국시간)로 묶어 합산하고, `/spend/logs/v2` 가 없는 게이트웨이에서는 UTC 날짜로 묶인 `GET /global/spend/logs` 를 대신 씁니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. 비용을 계산하려고 `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` 아래의 Claude 데스크톱 앱 Cowork 기록을 로컬에서 읽습니다. 밖으로 나가는 것은 하루 합계뿐이며 작업 이름과 프롬프트는 보내지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
57
57
 
58
58
  ## CLI에서 팀 만들기
59
59
 
@@ -124,7 +124,7 @@ sprag team propose "커밋 전에 lint 실행" --scope ratchet
124
124
 
125
125
  Sprag 은 룰을 `~/.claude/ratchet-team.md`(Codex 는 `<CODEX_HOME>/ratchet-team.md`)에 씁니다. 조직 룰이 먼저, 팀 룰이 그다음이고, 모델 룰은 각각의 하위 절로 들어갑니다. 그 파일이 있는 동안 `~/.claude/CLAUDE.md` 의 전역 harness 블록에서 import 합니다. Sprag 이 파일을 통째로 다시 쓰므로 직접 고치지 마십시오. `sprag team rules` 는 받아 둔 룰을 `- [org · model] 내용`, `- [team · ratchet] 내용` 형태로 보여 줍니다. `sprag team leave` 는 멤버 키, 캐시, import 를 지웁니다.
126
126
 
127
- **추천 위임 룰.** 구성원이 올린 요약은 대시보드의 규칙 탭에 추천 위임 룰로 모입니다. 카테고리와 티어마다 한 건이며 이 룰을 쓰는 구성원 수, 위임 횟수, 실패율, 절감액이 붙습니다. 오너나 어드민이 그 탭에서 추천을 읽고 팀이나 조직 전체에 적용합니다. 적용된 룰은 문장과 함께 구조화된 기록(카테고리, 티어, 상한)을 달고 내려옵니다. 각 PC는 그 기록으로 모델 룰을 자기 환경에서 다시 그립니다. 에이전트 이름은 그 PC에 있는 것을 쓰고 언어는 자기 설정을 따르므로(Codex 파일은 영어로 남습니다) 한 PC에서 쓴 룰이 다른 PC에 없는 에이전트를 가리키는 일이 없습니다. 다시 그린 문장에는 예시가 없고 상한은 기록에 담긴 값입니다. 기록이 없는 룰은 서버가 보낸 문장 그대로 씁니다. `sprag team rules` 도 다시 그린 문장을 보여 줍니다.
127
+ **추천 위임 룰.** 구성원이 올린 요약은 대시보드의 규칙 탭에 추천 위임 룰로 모입니다. 카테고리와 티어마다 한 건이며 이 룰을 쓰는 구성원 수, 위임 횟수, 실패율, 절감액이 붙습니다. 추천을 펼치면 기여자 표가 나옵니다. 멤버(같은 좌석을 쓰는 PC는 한 명으로 셉니다)마다 팀, 위임 횟수, 실패율, 절감액, 시작일, 출처가 한 줄씩 담깁니다. 게시된 Sprag 프리셋에 이미 들어 있는 룰은 프리셋으로 모든 PC에 전달되므로 추천하지 않습니다. 추천 머리의 배지는 자체 학습한 멤버가 몇 명인지를 알려 줍니다. 오너나 어드민이 그 탭에서 추천을 읽고 팀이나 조직 전체에 적용합니다. 적용된 룰은 문장과 함께 구조화된 기록(카테고리, 티어, 상한)을 달고 내려옵니다. 각 PC는 그 기록으로 모델 룰을 자기 환경에서 다시 그립니다. 에이전트 이름은 그 PC에 있는 것을 쓰고 언어는 자기 설정을 따르므로(Codex 파일은 영어로 남습니다) 한 PC에서 쓴 룰이 다른 PC에 없는 에이전트를 가리키는 일이 없습니다. 다시 그린 문장에는 예시가 없고 상한은 기록에 담긴 값입니다. 기록이 없는 룰은 서버가 보낸 문장 그대로 씁니다. `sprag team rules` 도 다시 그린 문장을 보여 줍니다.
128
128
 
129
129
  ## 상태 확인, 전송 내용 확인, 나가기
130
130
 
package/docs/TEAM.md CHANGED
@@ -53,7 +53,7 @@ The daily aggregate upload runs at most once every 5 minutes after the last succ
53
53
 
54
54
  While this machine is joined, the statusline shows a `team` chip with your member id and your animal from the virtual office (Sprag Town), for example `member-1e500474 🦊 Fox #3 of 12`, with your overall rank among the ranked people of the organization. The animal comes from the standing the full sync fetches every 5 minutes and stores in `team.json`; if the server does not offer it yet, or the last fetch is more than a day old, only the member id is shown. Rendering the chip reads local files only. It sits just before the version chip, and `--segments team` shows it on its own. IntelliJ's terminal font has no animal emoji, so there (narrow mode) and in text mode the chip drops the emoji and keeps the name: `member-1e500474 Fox #3 of 12`.
55
55
 
56
- Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`), `member_rules_report` (the delegation rule summary above) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures). When a LiteLLM gateway is configured, each daily sync also calls the gateway's `GET /user/info` and `GET /global/spend/logs` with your own key to read the gateway's daily spend for you; nothing else is read and the key is never stored. Claude desktop Cowork transcripts under `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` are read locally to price them; only the daily sums leave the machine, and task names and prompts are not sent. `sprag team status --show-payload` prints the exact rows. `sprag team create` also calls `team_create` with your sign-in session.
56
+ Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`), `member_rules_report` (the delegation rule summary above) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures). When a LiteLLM gateway is configured, each daily sync also calls the gateway's `GET /user/info` and `GET /spend/logs/v2` (or `GET /global/spend/logs` on gateways without it) with your own key to read the gateway's daily spend for you, summed by your local day from each request's time; nothing else is read and the key is never stored. Claude desktop Cowork transcripts under `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` are read locally to price them; only the daily sums leave the machine, and task names and prompts are not sent. `sprag team status --show-payload` prints the exact rows. `sprag team create` also calls `team_create` with your sign-in session.
57
57
 
58
58
  ## Create a team from the CLI
59
59
 
@@ -124,7 +124,7 @@ sprag team propose "Run lint before every commit" --scope ratchet
124
124
 
125
125
  Sprag writes the rules to `~/.claude/ratchet-team.md` (Codex: `<CODEX_HOME>/ratchet-team.md`), organization rules first and then team rules, each with its model rules in a sub-section, and imports that file from the global harness block of `~/.claude/CLAUDE.md` for as long as the file exists. Do not edit the file by hand, because Sprag rewrites it. `sprag team rules` lists the cached rules as `- [org · model] text` or `- [team · ratchet] text`. `sprag team leave` removes the member key, the cache and the import.
126
126
 
127
- **Recommended delegation rules.** The summaries that members report are collected on the Rules tab of the dashboard as recommended delegation rules, one per category and tier: how many members run it, the delegation count, the failure rate and the savings. An owner or admin reads them there and applies a recommendation to the team or to the whole organization. The applied rule arrives with a structured record (category, tier and cap) next to its text. Each machine redraws a model rule from that record, with the agent names it has itself and in the language of its own settings (Codex files stay English), so a rule written on one machine never names an agent that another machine lacks. The redrawn sentence has no example, and the cap is the one in the record. A rule without a record is written as the server sent it. `sprag team rules` shows the redrawn sentence.
127
+ **Recommended delegation rules.** The summaries that members report are collected on the Rules tab of the dashboard as recommended delegation rules, one per category and tier: how many members run it, the delegation count, the failure rate and the savings. Opening a recommendation lists the contributors: for each member (machines that share a seat count once) the team, the delegation count, the failure rate, the savings, the start date and the origin. A rule that the published Sprag preset bundle already contains is not recommended, because the preset reaches every machine on its own; a badge on the recommendation says how many members learned it from their own route-scan. An owner or admin reads them there and applies a recommendation to the team or to the whole organization. The applied rule arrives with a structured record (category, tier and cap) next to its text. Each machine redraws a model rule from that record, with the agent names it has itself and in the language of its own settings (Codex files stay English), so a rule written on one machine never names an agent that another machine lacks. The redrawn sentence has no example, and the cap is the one in the record. A rule without a record is written as the server sent it. `sprag team rules` shows the redrawn sentence.
128
128
 
129
129
  ## Status, payload and leaving
130
130
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.96.0",
3
+ "version": "3.97.1",
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": {
@@ -9,8 +9,11 @@
9
9
  *
10
10
  * GET {base}/key/info the key's user_id (404 on custom-auth deployments)
11
11
  * GET {base}/user/info user_info.user_id as the fallback
12
+ * GET {base}/spend/logs/v2 one row per request with its startTime, paged,
13
+ * for this user since the first local day asked
12
14
  * GET {base}/global/spend/logs rows {date, spend, api_key, user}; the most
13
- * recent 30 days, every user the key may see
15
+ * recent 30 days, every user the key may see;
16
+ * the fallback when v2 is missing or too large
14
17
  *
15
18
  * Only rows whose `user` is this user id are summed: an admin key sees
16
19
  * everyone's rows and summing them all would report the whole company as one
@@ -21,9 +24,11 @@
21
24
  * a file (same rule as litellm-budget.js). Failures are returned as
22
25
  * `{ error }`, never thrown: the upload goes on with local figures.
23
26
  *
24
- * `date` is the gateway's calendar day (UTC on the deployments measured), so
25
- * a day can differ from the local day by up to a few hours of traffic; range
26
- * sums are unaffected.
27
+ * The request rows are summed by the local calendar day, the key every other
28
+ * figure in the daily row uses (Korean time on the machines measured). The
29
+ * daily tables behind /global/spend/logs and /user/daily/activity only keep
30
+ * the UTC date, so they cannot be regrouped: a request at 08:00 KST lands on
31
+ * the previous day there. That fallback result carries `dayBasis: 'utc'`.
27
32
  */
28
33
 
29
34
  import { createHash } from 'node:crypto';
@@ -42,8 +47,12 @@ export function gatewayEnv(env = process.env) {
42
47
 
43
48
  export const GATEWAY_SPEND_TIMEOUT_MS = 15000;
44
49
  export const GATEWAY_SPEND_DAYS = 30;
50
+ export const GATEWAY_LOG_PAGE_SIZE = 1000;
51
+ /** 60 pages of 1,000 requests; past that the UTC daily totals are cheaper. */
52
+ export const GATEWAY_LOG_MAX_PAGES = 60;
45
53
 
46
54
  const DAY_RE = /^\d{4}-\d{2}-\d{2}/;
55
+ const KEY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
47
56
 
48
57
  /** Local calendar day, same key as team-sync.js and stats.js. */
49
58
  function dayKey(ms) {
@@ -78,6 +87,34 @@ export function sumSpendRows(rows, userId) {
78
87
  return { days, earliest };
79
88
  }
80
89
 
90
+ /**
91
+ * Epoch ms of a spend log's startTime. The column is a timestamp without a
92
+ * zone holding UTC, so a value without an offset is read as UTC.
93
+ */
94
+ export function logStartMs(v) {
95
+ const s = String(v ?? '').trim();
96
+ if (!s) return NaN;
97
+ return Date.parse(/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s.replace(' ', 'T')}Z`);
98
+ }
99
+
100
+ /** Sum `/spend/logs/v2` request rows for one user by local calendar day. */
101
+ export function sumLogRows(rows, userId) {
102
+ const days = new Map();
103
+ for (const r of rows) {
104
+ if (!r || typeof r !== 'object') continue;
105
+ if (String(r.user ?? '') !== String(userId)) continue;
106
+ const usd = Number(r.spend);
107
+ const ms = logStartMs(r.startTime);
108
+ if (!Number.isFinite(usd) || !Number.isFinite(ms)) continue;
109
+ const day = dayKey(ms);
110
+ days.set(day, (days.get(day) || 0) + usd);
111
+ }
112
+ return days;
113
+ }
114
+
115
+ /** UTC "YYYY-MM-DD HH:MM:SS", the form /spend/logs/v2 reads its window in. */
116
+ const utcStamp = (ms) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ');
117
+
81
118
  /**
82
119
  * The gateway figure for one local day: a number inside the covered range (0
83
120
  * when the gateway has no row for it), null outside it or without a result.
@@ -89,21 +126,48 @@ export function gatewayDayValue(result, day) {
89
126
  }
90
127
 
91
128
  /**
92
- * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, userId: string, userHash: string }>}
129
+ * @param {object} [opts]
130
+ * @param {string} [opts.from] first local day (YYYY-MM-DD) the caller needs;
131
+ * request logs are read from there, never further back than 30 days
132
+ * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, dayBasis: 'local' | 'utc', userId: string, userHash: string }>}
93
133
  * null when no gateway is configured or the user id cannot be learned.
94
134
  */
95
- export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS } = {}) {
135
+ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS, from = null } = {}) {
96
136
  const g = gatewayEnv(env);
97
137
  if (!g) return null;
98
138
  const { base, key } = g;
99
139
  const ctl = new AbortController();
100
140
  const timer = setTimeout(() => ctl.abort(), timeoutMs);
141
+ // The request logs get half the time, so a slow or huge log still leaves
142
+ // room for the daily totals.
143
+ const logCtl = new AbortController();
144
+ const logTimer = setTimeout(() => logCtl.abort(), Math.floor(timeoutMs / 2));
145
+ const stopLogs = () => logCtl.abort();
146
+ ctl.signal.addEventListener('abort', stopLogs);
101
147
  const headers = { accept: 'application/json', authorization: `Bearer ${key}` };
102
- const getJson = async (path) => {
103
- const res = await fetchImpl(`${base}${path}`, { signal: ctl.signal, headers, redirect: 'error' });
104
- if (!res.ok) throw new Error(`LiteLLM ${path} responded ${res.status}`);
148
+ const getJson = async (path, signal = ctl.signal) => {
149
+ const res = await fetchImpl(`${base}${path}`, { signal, headers, redirect: 'error' });
150
+ if (!res.ok) throw new Error(`LiteLLM ${path.split('?')[0]} responded ${res.status}`);
105
151
  return res.json();
106
152
  };
153
+ // Request rows summed by local day, or null when the log is over the page
154
+ // cap. Oldest first, so requests made while paging only add to the end.
155
+ const logDays = async (userId, fromKey) => {
156
+ const m = KEY_RE.exec(fromKey);
157
+ const startMs = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime();
158
+ const days = new Map();
159
+ for (let page = 1; page <= GATEWAY_LOG_MAX_PAGES; page++) {
160
+ const q = new URLSearchParams({
161
+ user_id: userId, start_date: utcStamp(startMs), end_date: utcStamp(now),
162
+ page: String(page), page_size: String(GATEWAY_LOG_PAGE_SIZE), sort_by: 'startTime', sort_order: 'asc',
163
+ });
164
+ const body = await getJson(`/spend/logs/v2?${q}`, logCtl.signal);
165
+ if (!body || !Array.isArray(body.data)) throw new Error('LiteLLM /spend/logs/v2 sent no data array');
166
+ for (const [day, usd] of sumLogRows(body.data, userId)) days.set(day, (days.get(day) || 0) + usd);
167
+ if (body.data.length < GATEWAY_LOG_PAGE_SIZE) return days;
168
+ }
169
+ return null;
170
+ };
107
171
  try {
108
172
  // Same order as pickBudgetSource: the key's own user id first, then the
109
173
  // user record. /key/info is 404 on custom-auth deployments; that is fine.
@@ -119,19 +183,32 @@ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = gl
119
183
  if (typeof id === 'string' && id) userId = id;
120
184
  }
121
185
  if (!userId) return null;
122
- const rows = await getJson('/global/spend/logs');
123
- const { days, earliest } = sumSpendRows(rows, userId);
124
186
  const coveredTo = dayKey(now);
125
187
  const windowStart = dayKey(now - (GATEWAY_SPEND_DAYS - 1) * 86400000);
188
+ const userHash = gatewayUserHash(base, userId);
189
+ const logFrom = KEY_RE.test(String(from || '')) && from > windowStart && from <= coveredTo ? from : windowStart;
190
+ let local = null;
191
+ try {
192
+ local = await logDays(userId, logFrom);
193
+ } catch (e) {
194
+ // The whole budget is spent: the daily totals would time out as well.
195
+ if (ctl.signal.aborted) throw e;
196
+ debug('gateway-spend:logs-v2', e);
197
+ }
198
+ if (local) return { days: local, coveredFrom: logFrom, coveredTo, dayBasis: 'local', userId, userHash };
199
+ const rows = await getJson('/global/spend/logs');
200
+ const { days, earliest } = sumSpendRows(rows, userId);
126
201
  // The response is the gateway's recent-30-day window. A day inside it with
127
202
  // no row is a day with no spend; the earliest row only widens the window
128
203
  // when the gateway sent more than 30 days.
129
204
  const coveredFrom = earliest && earliest < windowStart ? earliest : windowStart;
130
- return { days, coveredFrom, coveredTo, userId, userHash: gatewayUserHash(base, userId) };
205
+ return { days, coveredFrom, coveredTo, dayBasis: 'utc', userId, userHash };
131
206
  } catch (e) {
132
207
  debug('gateway-spend', e);
133
208
  return { error: e && e.name === 'AbortError' ? 'timeout' : String((e && e.message) || e) };
134
209
  } finally {
135
210
  clearTimeout(timer);
211
+ clearTimeout(logTimer);
212
+ ctl.signal.removeEventListener('abort', stopLogs);
136
213
  }
137
214
  }
@@ -5,8 +5,8 @@
5
5
  * The registry (model-rules.json) holds project paths, the user's prompt
6
6
  * excerpts and rule sentences. None of that may leave the machine, so the
7
7
  * summary is built from an allowlist: each output row is a new object whose
8
- * keys are RULE_STAT_KEYS, filled only from numbers, the two enumerations
9
- * (category, tier) and one date. test/team-rule-stats.test.js pins the key set
8
+ * keys are RULE_STAT_KEYS, filled only from numbers, the enumerations
9
+ * (category, tier, status, origin) and one date. test/team-rule-stats.test.js pins the key set
10
10
  * and checks that no path or example text survives into the JSON.
11
11
  *
12
12
  * Rules of one (category, tier) from different projects fold into one row;
@@ -19,7 +19,7 @@ import { RULE_CATEGORY_IDS, RULE_TIERS, isRuleCategory, isRuleTier } from './rul
19
19
  export const RULE_STATS_MAX = 24;
20
20
  export const RULE_STAT_KEYS = Object.freeze([
21
21
  'category', 'tier', 'status', 'episodes', 'delegated', 'delegated_err',
22
- 'saved_usd', 'baseline_err', 'budget_calls', 'budget_out', 'since',
22
+ 'saved_usd', 'baseline_err', 'budget_calls', 'budget_out', 'since', 'origin',
23
23
  ]);
24
24
 
25
25
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -40,6 +40,19 @@ function weighted(pairs) {
40
40
  return weight > 0 ? round(sum / weight, 4) : null;
41
41
  }
42
42
 
43
+ /**
44
+ * Where the folded rules came from, as one of three fixed words. A Sprag preset the
45
+ * user accepted is marked `origin: 'preset'` and signed `<tier>|<category>|preset`
46
+ * (src/seed-rules.js); every other rule was promoted from this machine's own
47
+ * route-scan candidates. 'both' means the row folds rules of the two kinds.
48
+ */
49
+ const isPresetRule = (r) => r.origin === 'preset' || (typeof r.signature === 'string' && r.signature.endsWith('|preset'));
50
+ function ruleOrigin(rules) {
51
+ const presets = rules.filter(isPresetRule).length;
52
+ if (presets === 0) return 'scan';
53
+ return presets === rules.length ? 'preset' : 'both';
54
+ }
55
+
43
56
  /** The most common budget among the rules; the first one wins a tie. */
44
57
  function commonBudget(rules) {
45
58
  const tally = new Map();
@@ -89,6 +102,7 @@ export function summarizeModelRules(rules) {
89
102
  budget_calls: budget.calls,
90
103
  budget_out: budget.out,
91
104
  since: dates[0] || null,
105
+ origin: ruleOrigin(list),
92
106
  });
93
107
  }
94
108
  }
package/src/team-sync.js CHANGED
@@ -895,14 +895,15 @@ export async function syncTeam({
895
895
  // price Claude the same way and both see the gateway figure.
896
896
  env = withClaudeSettingsEnv(env);
897
897
  const hasGateway = !!gatewayEnv(env);
898
- let gatewayDaily = null;
899
- if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
900
- const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
901
898
  // Days the delegation ledger changed after they were uploaded (a rescan
902
899
  // repriced them) go up again from the earliest one.
903
900
  let change = null;
904
901
  try { change = changedSinceForSync(); } catch (e) { debug('team-sync', e); }
905
902
  const win = ledgerWindow(state, now, { gateway: hasGateway, changedSince: change?.since });
903
+ // The gateway's request log is read only from the first day going up.
904
+ let gatewayDaily = null;
905
+ if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now, from: win.startKey });
906
+ const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
906
907
  let prices = codexPrices;
907
908
  if (prices === undefined) {
908
909
  const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });