sprag-cli 3.95.0 → 3.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -224,7 +224,7 @@ Usage:
224
224
  sprag brief --hook internal: the UserPromptSubmit hook entry point
225
225
  sprag brief --hook-tool internal: the PostToolUse hook entry point (delegation follow-up)
226
226
  sprag feedback "<msg>" file a bug report / feature request (no browser needed)
227
- sprag team create|join|status|sync|leave opt-in team layer: daily aggregates only (SPRAG_NO_TEAM_SYNC=1 turns it off)
227
+ sprag team create|join|status|sync|leave opt-in team layer: daily aggregates and a rule summary only (SPRAG_NO_TEAM_SYNC=1 turns it off)
228
228
  sprag upgrade install the latest release
229
229
  sprag --install-hook install cache-monitor PostToolUse hook
230
230
  sprag --uninstall-hook remove that hook
package/docs/TEAM.ko.md CHANGED
@@ -30,13 +30,30 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
30
30
  | 기기 ID | 위와 같은 무작위 구성원 ID입니다. 표시 이름을 바꿔도 참여할 때 함께 보내며, 같은 컴퓨터가 다시 참여하면 조직 안에서 기존 좌석을 그대로 쓰게 하는 데 씁니다 |
31
31
  | 운영체제 | OS 이름과 버전(예: macOS 26, Windows 11, Ubuntu 24.04)입니다. 참여한 직후 한 번 보내고, 바뀔 때만 다시 보냅니다. 호스트 이름, 사용자 이름, 경로처럼 컴퓨터를 이름으로 알아볼 수 있는 값은 보내지 않습니다 |
32
32
 
33
- 보내지 않는 것은 프롬프트, 대화 기록, 파일 경로, 프로젝트 이름, 룰 내용, API 키입니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 옵트인 프롬프트 업로드만 예외이며 "프롬프트 사용량 (엔터프라이즈)" 절에 적었습니다. 룰은 직접 `sprag team propose` 를 실행할 때만 밖으로 나갑니다.
33
+ 보내지 않는 것은 프롬프트, 대화 기록, 파일 경로, 프로젝트 이름, 룰 내용, 룰 예시, API 키입니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 옵트인 프롬프트 업로드만 예외이며 "프롬프트 사용량 (엔터프라이즈)" 절에 적었습니다. 룰 본문은 직접 `sprag team propose` 를 실행할 때만 밖으로 나갑니다.
34
+
35
+ ### 위임 룰 요약
36
+
37
+ 하루 단위 행과 별도로, 전체 동기화는 `sprag route-scan` 이 이 PC에 등록한 모델 위임 룰(`model-rules.json`)의 요약 한 벌을 올립니다. 직전에 보낸 요약과 다르거나 하루가 지났을 때 `member_rules_report` 로 올라갑니다. 꺼진 룰은 빠집니다. 여러 프로젝트에 같은 카테고리와 티어의 룰이 있으면 한 행으로 합치므로 행에는 프로젝트가 없습니다.
38
+
39
+ | 항목 | 의미 |
40
+ |---|---|
41
+ | 카테고리와 티어 | paste, translate, explore, read, check, run 중 하나와 T2, T1, T1H 중 하나 |
42
+ | 상태 | `active`, 합친 룰이 모두 검토 대상이면 `review` |
43
+ | 에피소드 | 기록에서 그 패턴이 나타난 횟수 |
44
+ | 위임 횟수와 실패율 | 룰이 받은 위임 실행 수와 그중 실패한 비율 |
45
+ | 기준선 실패율 | 세션 모델이 직접 같은 일을 했을 때의 실패 비율이며 모르면 null |
46
+ | 절감액(USD) | 룰이 위임한 실행이 아낀 금액 |
47
+ | 상한 | 룰이 지닌 도구 호출과 출력 토큰 상한 |
48
+ | 시작일 | 룰을 처음 등록한 날짜 |
49
+
50
+ 룰 본문, 예시, 프로젝트 경로는 PC에 남습니다. `sprag team status --show-payload` 가 올라갈 요약을 그대로 보여 줍니다. `member_rules_report` 가 없는 옛 서버는 오류 없이 건너뜁니다.
34
51
 
35
52
  하루 단위 집계 업로드는 마지막 성공 이후 5분에 한 번 이하로 실행됩니다. SessionStart 훅(그리고 작은 로컬 파일만 읽는 프롬프트 훅)이 띄운 분리된 자식 프로세스가 보냅니다. 네트워크가 끊기는 등 동기화가 실패하면 5분 주기 대신 15분, 30분, 60분 뒤에 다시 시도합니다(최대 60분 간격). 마지막으로 올린 날짜를 기억해 두었다가 그 전날부터 최대 30일 치를 다시 보내므로, 며칠 꺼져 있던 컴퓨터도 처음 성공하는 동기화에서 빠진 날을 따라잡습니다. 하루 단위 행은 덮어쓰기라 다시 보내도 안전합니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 프롬프트 업로드는 따로 30분 타이머로 움직입니다("프롬프트 사용량 (엔터프라이즈)" 절 참고). statusline 을 그리는 경로에서는 절대 실행되지 않습니다.
36
53
 
37
54
  팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
38
55
 
39
- 목적지는 `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_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 /global/spend/logs` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. 비용을 계산하려고 `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` 아래의 Claude 데스크톱 앱 Cowork 기록을 로컬에서 읽습니다. 밖으로 나가는 것은 하루 합계뿐이며 작업 이름과 프롬프트는 보내지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
40
57
 
41
58
  ## CLI에서 팀 만들기
42
59
 
@@ -107,13 +124,15 @@ sprag team propose "커밋 전에 lint 실행" --scope ratchet
107
124
 
108
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 를 지웁니다.
109
126
 
127
+ **추천 위임 룰.** 구성원이 올린 요약은 대시보드의 규칙 탭에 추천 위임 룰로 모입니다. 카테고리와 티어마다 한 건이며 이 룰을 쓰는 구성원 수, 위임 횟수, 실패율, 절감액이 붙습니다. 오너나 어드민이 그 탭에서 추천을 읽고 팀이나 조직 전체에 적용합니다. 적용된 룰은 문장과 함께 구조화된 기록(카테고리, 티어, 상한)을 달고 내려옵니다. 각 PC는 그 기록으로 모델 룰을 자기 환경에서 다시 그립니다. 에이전트 이름은 그 PC에 있는 것을 쓰고 언어는 자기 설정을 따르므로(Codex 파일은 영어로 남습니다) 한 PC에서 쓴 룰이 다른 PC에 없는 에이전트를 가리키는 일이 없습니다. 다시 그린 문장에는 예시가 없고 상한은 기록에 담긴 값입니다. 기록이 없는 룰은 서버가 보낸 문장 그대로 씁니다. `sprag team rules` 도 다시 그린 문장을 보여 줍니다.
128
+
110
129
  ## 상태 확인, 전송 내용 확인, 나가기
111
130
 
112
131
  | 명령 | 설명 |
113
132
  |---|---|
114
133
  | `sprag team join [토큰] [--name <이름>] [--yes]` | 팀에 참여 |
115
134
  | `sprag team name [<이름>]` | 대시보드에 나오는 표시 이름 보기 또는 바꾸기 |
116
- | `sprag team status [--show-payload]` | 팀, 플랜, 프롬프트 수집 설정, 표시 이름, 마지막 동기화를 보여 줍니다. `--show-payload` 를 붙이면 보내는 기기 정보와 올라갈 하루 단위 행도 그대로 출력합니다 |
135
+ | `sprag team status [--show-payload]` | 팀, 플랜, 프롬프트 수집 설정, 표시 이름, 마지막 동기화를 보여 줍니다. `--show-payload` 를 붙이면 보내는 기기 정보와 올라갈 하루 단위 행, 위임 룰 요약도 그대로 출력합니다 |
117
136
  | `sprag team sync [--force] [--rules-only]` | 지금 업로드하고 룰을 받습니다. `--force` 는 5분 간격을 무시하고, `--rules-only` 는 조직·팀 룰만 받고 아무것도 올리지 않습니다 |
118
137
  | `sprag team rules` | 받아 둔 조직·팀 룰 보기 |
119
138
  | `sprag team propose "<내용>" [--scope ratchet\|model]` | 팀에 룰 제안 |
@@ -192,7 +211,7 @@ Free, 프로(좌석당 월 $5), 엔터프라이즈(좌석당 월 $10, 프롬프
192
211
  - 오너와 어드민은 구성원별 하루 합계를 봅니다. 엔터프라이즈 조직에서 팀이 프롬프트 수집을 켠 경우를 빼면 세션이나 프롬프트는 보지 못합니다.
193
212
  - 구성원은 `sprag team status --show-payload` 로 같은 내용을 직접 볼 수 있습니다.
194
213
  - 프롬프트 수집은 엔터프라이즈 정책이며, 오너나 어드민이 대시보드에서 켤 수 있습니다. 구성원은 `sprag team status` 에서 설정 상태를 확인합니다. 수집이 켜져 있으면 CLI 가 정책이 이 컴퓨터에 닿은 뒤 입력한 프롬프트를 올립니다("프롬프트 사용량 (엔터프라이즈)" 절 참고).
195
- - 룰 내용은 `sprag team propose` 를 통해서만 밖으로 나갑니다.
214
+ - 룰 내용은 `sprag team propose` 를 통해서만 밖으로 나갑니다. 위임 룰 요약에는 카테고리와 티어별 숫자만 있고 본문이나 경로는 없습니다.
196
215
 
197
216
  ## 파일과 환경 변수
198
217
 
package/docs/TEAM.md CHANGED
@@ -30,13 +30,30 @@ After you join, Sprag uploads one row per local calendar day:
30
30
  | Machine ID | the same random member ID, sent at join even when you choose another display name, so that a machine joining again reuses its seat in the organization instead of taking a second one |
31
31
  | Operating system | OS name and version (for example macOS 26, Windows 11, Ubuntu 24.04); sent once after joining and again only if it changes. Nothing that identifies the machine by name: no hostname, no user name, no path |
32
32
 
33
- Not sent: prompts, transcripts, file paths, project names, rule text, API keys. The one exception is the opt-in prompt upload of an Enterprise team with prompt capture on, described under "Prompt usage (Enterprise)". A rule leaves your machine only when you run `sprag team propose` yourself.
33
+ Not sent: prompts, transcripts, file paths, project names, rule text, rule examples, API keys. The one exception is the opt-in prompt upload of an Enterprise team with prompt capture on, described under "Prompt usage (Enterprise)". A rule's text leaves your machine only when you run `sprag team propose` yourself.
34
+
35
+ ### Delegation rule summary
36
+
37
+ Besides the daily rows, a full sync reports one summary of the model-fitting rules that `sprag route-scan` registered on this machine (the file `model-rules.json`). It goes up through `member_rules_report` when it differs from the last one sent or a day has passed. Rules that are off are left out. Rules of one category and tier from several projects are folded into one row, so a row has no project in it.
38
+
39
+ | Field | Meaning |
40
+ |---|---|
41
+ | Category and tier | one of paste, translate, explore, read, check, run, and one of T2, T1, T1H |
42
+ | Status | `active`, or `review` when every folded rule is flagged for review |
43
+ | Episodes | how often the pattern was seen in the logs |
44
+ | Delegations and failure rate | how many delegated runs the rule got and the share that failed |
45
+ | Baseline failure rate | the share of failures when the session model did such work itself, null when unknown |
46
+ | Savings (USD) | what the rule's delegated runs saved |
47
+ | Cap | the tool-call and output-token cap the rule carries |
48
+ | Since | the date the rule was first registered |
49
+
50
+ Rule text, examples and project paths stay on the machine. `sprag team status --show-payload` prints the exact summary. An older server without `member_rules_report` is skipped without an error.
34
51
 
35
52
  The daily aggregate upload runs at most once every 5 minutes after the last successful one, from a detached child process that the SessionStart hook (and the prompt hook, which only reads a small local file) spawns. If a sync fails, for example because the network is down, it is retried after 15, then 30, then 60 minutes (60 at most) instead of every 5 minutes. The CLI remembers the last day it uploaded and re-sends from the day before it, up to 30 days, so a machine that was offline for days catches up on its first successful sync. Re-sending a day is safe because each day is an upsert. The prompt upload of an Enterprise team with capture on has its own 30-minute timer (see "Prompt usage (Enterprise)"). It never runs on the statusline path.
36
53
 
37
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`.
38
55
 
39
- 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`) 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 /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.
40
57
 
41
58
  ## Create a team from the CLI
42
59
 
@@ -107,13 +124,15 @@ sprag team propose "Run lint before every commit" --scope ratchet
107
124
 
108
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.
109
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.
128
+
110
129
  ## Status, payload and leaving
111
130
 
112
131
  | Command | What it does |
113
132
  |---|---|
114
133
  | `sprag team join [token] [--name <n>] [--yes]` | Join a team |
115
134
  | `sprag team name [<n>]` | Show or change your display name on the dashboard |
116
- | `sprag team status [--show-payload]` | Team, plan, prompt-capture flag, display name, last sync. `--show-payload` also prints the device info and the exact daily rows that would be uploaded |
135
+ | `sprag team status [--show-payload]` | Team, plan, prompt-capture flag, display name, last sync. `--show-payload` also prints the device info, the exact daily rows and the delegation rule summary that would be uploaded |
117
136
  | `sprag team sync [--force] [--rules-only]` | Upload now and pull rules. `--force` ignores the 5-minute interval; `--rules-only` pulls the organization and team rules and uploads nothing |
118
137
  | `sprag team rules` | Show the cached organization and team rules |
119
138
  | `sprag team propose "<text>" [--scope ratchet\|model]` | Propose a rule to the team |
@@ -193,7 +212,7 @@ Owners and admins of an Enterprise organization get a Prompts tab on sprag.io/te
193
212
  - Owners and admins see per-member daily totals, not sessions or prompts, unless the organization is on Enterprise and the team has prompt capture switched on.
194
213
  - A member sees the same payload with `sprag team status --show-payload`.
195
214
  - Prompt capture is an Enterprise policy that an owner or admin can switch on in the dashboard. Members see its state in `sprag team status`. When capture is on, the CLI uploads the prompts you type after the policy reached your machine (see "Prompt usage (Enterprise)").
196
- - Rule text leaves your machine only through `sprag team propose`.
215
+ - Rule text leaves your machine only through `sprag team propose`. The delegation rule summary carries numbers per category and tier, never text or paths.
197
216
 
198
217
  ## Files and environment variables
199
218
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.95.0",
3
+ "version": "3.96.0",
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": {
@@ -2,7 +2,7 @@
2
2
  * team — `sprag team <create|join|name|leave|status|sync|rules|propose>`.
3
3
  *
4
4
  * The opt-in team layer. `join` shows exactly what will be uploaded (daily
5
- * aggregates only) and asks before enrolling. `sync --background` is what the
5
+ * aggregates and a delegation rule summary) and asks before enrolling. `sync --background` is what the
6
6
  * SessionStart hook's detached child runs: auto-join from SPRAG_TEAM_TOKEN,
7
7
  * then upload and pull, printing nothing. All network access goes through
8
8
  * rpc() in src/team-sync.js. Exit codes: 0 ok, 1 error, 2 usage.
@@ -13,6 +13,8 @@ import { readFileSync } from 'node:fs';
13
13
  import { userLanguage } from '../config.js';
14
14
  import { pendingPrompts } from '../team-prompts.js';
15
15
  import { memberId } from '../member-id.js';
16
+ import { teamRuleText } from '../team-ratchet.js';
17
+ import { ruleStatsSummary } from '../team-rule-stats.js';
16
18
  import { orgMinVersion, readOrgUpgrade, orgUpgradeInFlight } from '../org-upgrade.js';
17
19
  import {
18
20
  loadTeamState, deviceInfo, isJoined, joinTeam, leaveTeam, syncTeam, autoJoin, aggregateDaily, rpc,
@@ -28,13 +30,14 @@ const T = {
28
30
  ' join [token] [--name <n>] [--yes] join a team (token or SPRAG_TEAM_TOKEN)',
29
31
  ' name [<n>] show or change your display name',
30
32
  ' leave leave the team and stop uploading',
31
- ' status [--show-payload] membership, last sync, what is sent',
33
+ ' status [--show-payload] membership, last sync, what is sent (daily aggregates and rule summary)',
32
34
  ' sync [--force] [--rules-only] upload aggregates, prompts (Enterprise capture) and pull rules now',
33
35
  ' (--rules-only: pull organization and team rules only, upload nothing)',
34
36
  ' rules show cached organization and team rules',
35
37
  ' propose <text> [--scope ratchet|model] propose a rule to the team',
36
38
  ].join('\n'),
37
- willSend: 'Joining uploads daily aggregates only, per local day:\n - spend (USD)\n - savings (USD)\n - delegation run counts\n - model-family share\nNo prompts, file paths or transcripts are sent.',
39
+ willSend: 'Joining uploads aggregates only. Per local day:\n - spend (USD)\n - savings (USD)\n - delegation run counts\n - model-family share\nAnd one summary of your delegation rules, per category and tier:\n - category, tier, delegation count, failure rate, savings (USD)\nNo prompts, rule text, examples, file paths or transcripts are sent.',
40
+ rulesPayload: 'delegation rule summary (member_rules_report)',
38
41
  asName: (n) => `Display name: ${n}`,
39
42
  asDevice: (d) => `Machine ID: ${d} (lets the organization count this machine once if it joins again)`,
40
43
  ask: 'Join? [y/N] ',
@@ -102,13 +105,14 @@ const T = {
102
105
  ' join [토큰] [--name <이름>] [--yes] 팀에 참여 (토큰 또는 SPRAG_TEAM_TOKEN)',
103
106
  ' name [<이름>] 표시 이름 보기 또는 바꾸기',
104
107
  ' leave 팀에서 나가고 업로드 중단',
105
- ' status [--show-payload] 참여 상태, 마지막 동기화, 보내는 내용',
108
+ ' status [--show-payload] 참여 상태, 마지막 동기화, 보내는 내용(하루 집계와 룰 요약)',
106
109
  ' sync [--force] [--rules-only] 지금 집계를 올리고 규칙을 받기',
107
110
  ' (--rules-only: 조직·팀 규칙만 받고 아무것도 올리지 않음)',
108
111
  ' rules 받아 둔 조직·팀 규칙 보기',
109
112
  ' propose <내용> [--scope ratchet|model] 팀에 규칙 제안',
110
113
  ].join('\n'),
111
- willSend: '참여하면 로컬 날짜별 하루 단위 집계만 올라갑니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n프롬프트, 파일 경로, 대화 기록은 보내지 않습니다.',
114
+ willSend: '참여하면 집계만 올라갑니다. 로컬 날짜별로는 다음과 같습니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n위임 룰은 카테고리와 티어별 요약 한 벌이 올라갑니다.\n - 카테고리, 티어, 위임 횟수, 실패율, 절감액(USD)\n프롬프트, 룰 본문, 예시, 파일 경로, 대화 기록은 보내지 않습니다.',
115
+ rulesPayload: '위임 룰 요약 (member_rules_report)',
112
116
  asName: (n) => `표시 이름: ${n}`,
113
117
  asDevice: (d) => `기기 ID: ${d} (다시 참여해도 조직이 이 컴퓨터를 한 좌석으로 셉니다)`,
114
118
  ask: '참여할까요? [y/N] ',
@@ -175,14 +179,15 @@ const T = {
175
179
  * `sprag team rules` lines: `- [org · model] text`, organization rules first.
176
180
  * Rows without a level (older servers) are team rules. Removed ids are skipped.
177
181
  */
178
- export function formatRuleLines(cache) {
182
+ export function formatRuleLines(cache, { lang = userLanguage() } = {}) {
179
183
  const removed = new Set(Array.isArray(cache?.removed) ? cache.removed : []);
184
+ const textOf = (r) => teamRuleText(r, { lang });
180
185
  const rules = (Array.isArray(cache?.rules) ? cache.rules : [])
181
- .filter((r) => r && typeof r.text === 'string' && r.text.trim() && !removed.has(r.id));
186
+ .filter((r) => r && textOf(r) && !removed.has(r.id));
182
187
  const org = rules.filter((r) => r.level === 'org');
183
188
  const team = rules.filter((r) => r.level !== 'org');
184
189
  return [...org, ...team].map((r) =>
185
- `- [${r.level === 'org' ? 'org' : 'team'} · ${r.scope === 'model' ? 'model' : 'ratchet'}] ${r.text.trim().replace(/\s*\n\s*/g, ' ')}`);
190
+ `- [${r.level === 'org' ? 'org' : 'team'} · ${r.scope === 'model' ? 'model' : 'ratchet'}] ${textOf(r).replace(/\s*\n\s*/g, ' ')}`);
186
191
  }
187
192
 
188
193
  function prompt(question) {
@@ -339,6 +344,7 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
339
344
  if (hasFlag('--show-payload')) {
340
345
  out(`device: ${JSON.stringify(st.deviceInfo || deviceInfo())}`);
341
346
  out(JSON.stringify(await aggregateDaily(), null, 2));
347
+ out(`${m.rulesPayload}: ${JSON.stringify(ruleStatsSummary(), null, 2)}`);
342
348
  if (st.promptCapture) {
343
349
  const pend = await pendingPrompts();
344
350
  out(m.pendingPrompts(pend.count));
@@ -170,21 +170,26 @@ function t1Target(root, ko, g) {
170
170
  }
171
171
 
172
172
  export function modelRuleBaseText(g, lang = userLanguage(), { root } = {}) {
173
+ // A rule redrawn from a structured record (the team layer) has no example:
174
+ // the parenthesis is left out rather than printed empty.
175
+ const hasExample = !!(String(g.example || '').trim() || String(g.exampleEn || '').trim());
173
176
  if (lang === 'ko') {
177
+ const eg = hasExample ? `(예: "${shortExample(g.example)}")` : '';
174
178
  if (g.tier === 'T1H') {
175
- return `"${g.label}" 고난도 구현 요청(예: "${shortExample(g.example)}")은 Fable·Mythos 세션에 한해 ${t1Target(root, true, g) ?? `model: ${TIER_MODEL.T1H}`}에 위임`;
179
+ return `"${g.label}" 고난도 구현 요청${eg}은 Fable·Mythos 세션에 한해 ${t1Target(root, true, g) ?? `model: ${TIER_MODEL.T1H}`}에 위임`;
176
180
  }
177
181
  return g.tier === 'T2'
178
- ? `"${g.label}" 단순 요청(예: "${shortExample(g.example)}")은 ${agentPhrase(targetName(g), { root })}에 위임`
179
- : `"${g.label}" 중간 난도 요청(예: "${shortExample(g.example)}")은 ${t1Target(root, true, g) ?? `model: ${TIER_MODEL.T1}`}에 위임`;
182
+ ? `"${g.label}" 단순 요청${eg}은 ${agentPhrase(targetName(g), { root })}에 위임`
183
+ : `"${g.label}" 중간 난도 요청${eg}은 ${t1Target(root, true, g) ?? `model: ${TIER_MODEL.T1}`}에 위임`;
180
184
  }
181
185
  const example = g.exampleEn || g.example;
186
+ const eg = hasExample ? ` (e.g. "${shortExample(example)}")` : '';
182
187
  if (g.tier === 'T1H') {
183
- return `Heavy "${g.labelEn}" implementation requests (e.g. "${shortExample(example)}") go to ${t1Target(root, false, g) ?? `a model: ${TIER_MODEL.T1H} subagent`}, in Fable/Mythos sessions only`;
188
+ return `Heavy "${g.labelEn}" implementation requests${eg} go to ${t1Target(root, false, g) ?? `a model: ${TIER_MODEL.T1H} subagent`}, in Fable/Mythos sessions only`;
184
189
  }
185
190
  return g.tier === 'T2'
186
- ? `Simple "${g.labelEn}" requests (e.g. "${shortExample(example)}") go to ${agentPhraseEn(targetName(g), { root })}`
187
- : `Moderate "${g.labelEn}" requests (e.g. "${shortExample(example)}") go to ${t1Target(root, false, g) ?? `a model: ${TIER_MODEL.T1} subagent`}`;
191
+ ? `Simple "${g.labelEn}" requests${eg} go to ${agentPhraseEn(targetName(g), { root })}`
192
+ : `Moderate "${g.labelEn}" requests${eg} go to ${t1Target(root, false, g) ?? `a model: ${TIER_MODEL.T1} subagent`}`;
188
193
  }
189
194
 
190
195
  // See the note in route-scan.js — paths.js is the only place that resolves
package/src/route-scan.js CHANGED
@@ -30,6 +30,7 @@ import { modelRank, isRecognizedModelId, TIER_TARGET_RANK, tierForRank } from '.
30
30
  import { sessionCost } from './claude-price.js';
31
31
  import { learnProfileMapping, resetModelAliasCache } from './model-alias.js';
32
32
  import { modelRuleBaseText } from './model-rules.js';
33
+ import { RULE_CATEGORY_LABELS } from './rule-categories.js';
33
34
  import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
34
35
  import { agentForRule } from './agents.js';
35
36
 
@@ -121,40 +122,28 @@ export const RESCAN_AFTER_DELEGATION_MS = 30 * 1000;
121
122
  const PASTE_MIN_LEN = 400;
122
123
  const CATEGORIES = [
123
124
  {
124
- id: 'paste',
125
- label: '붙여넣은 화면·로그 질문',
126
- labelEn: 'questions about pasted screens/logs',
125
+ ...RULE_CATEGORY_LABELS.paste,
127
126
  kw: null, // matched by length, see categorize()
128
127
  },
129
128
  {
130
- id: 'translate',
131
- label: '배치 번역·정형 텍스트 변환',
132
- labelEn: 'batch translation / mechanical text transforms',
129
+ ...RULE_CATEGORY_LABELS.translate,
133
130
  kw: [[/번역|translate/i, 2], [/변환해|표로 정리|포맷팅/i, 1]],
134
131
  },
135
132
  {
136
- id: 'explore',
137
- label: '탐색·조회 (파일/값 찾기)',
138
- labelEn: 'lookup (finding files/values)',
133
+ ...RULE_CATEGORY_LABELS.explore,
139
134
  kw: [[/\bgrep\b|검색|\bsearch|\bfind\b/i, 2], [/찾아|어디|위치|목록|살펴/i, 1],
140
135
  [/정의(?:돼|되어)\s*있|어느\s*파일|어떤\s*파일에|\bwhich\s+file\b|\bwhere\s+(?:is|are)\b[^?\n]*\bdefined\b/i, 1]],
141
136
  },
142
137
  {
143
- id: 'read',
144
- label: '읽기·요약·설명',
145
- labelEn: 'reading / summarizing / explaining',
138
+ ...RULE_CATEGORY_LABELS.read,
146
139
  kw: [[/요약|summar|explain/i, 2], [/읽어|설명|정리해|보여줘|알려줘|뭐야|\bwhat\b/i, 1]],
147
140
  },
148
141
  {
149
- id: 'check',
150
- label: '상태 확인·검증',
151
- labelEn: 'status checks / verification',
142
+ ...RULE_CATEGORY_LABELS.check,
152
143
  kw: [[/확인|검증|\bverif|점검/i, 2], [/맞아\?|되나|됐나|됐어|되는지|괜찮|체크|\bcheck\b|\bstatus\b/i, 1]],
153
144
  },
154
145
  {
155
- id: 'run',
156
- label: '명령 실행 (빌드·테스트·git)',
157
- labelEn: 'running commands (build/test/git)',
146
+ ...RULE_CATEGORY_LABELS.run,
158
147
  kw: [[/\bgit |\bcommit(?:s|ted)?\b|\bpush(?:ed|es)?\b|\bnpm |\bpip3? |빌드해|빌드 돌/i, 2], [/실행|돌려|\brun\b|\bbuild\b|빌드|테스트|설치/i, 1]],
159
148
  },
160
149
  ];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * rule-categories — the request categories and tiers a model-fitting rule can
3
+ * name, with the labels the rule sentence quotes.
4
+ *
5
+ * route-scan classifies requests into these categories (it adds the keyword
6
+ * tables), shared-model-rules validates against them, and the team layer
7
+ * (team-rule-stats, team-ratchet) uses them to check and redraw a rule that
8
+ * arrives as a structured record. The module imports nothing, so any of them
9
+ * can use it without closing an import cycle.
10
+ */
11
+
12
+ export const RULE_TIERS = Object.freeze(['T2', 'T1', 'T1H']);
13
+
14
+ // The Korean labels moved here unchanged from route-scan.js. Stored rules, the
15
+ // rendered ratchet files and the tests quote them byte for byte, so the middle
16
+ // dots stay as they were (an existing fixed expression, not new prose).
17
+ export const RULE_CATEGORY_LABELS = Object.freeze({
18
+ paste: Object.freeze({ id: 'paste', label: '붙여넣은 화면·로그 질문', labelEn: 'questions about pasted screens/logs' }),
19
+ translate: Object.freeze({ id: 'translate', label: '배치 번역·정형 텍스트 변환', labelEn: 'batch translation / mechanical text transforms' }),
20
+ explore: Object.freeze({ id: 'explore', label: '탐색·조회 (파일/값 찾기)', labelEn: 'lookup (finding files/values)' }),
21
+ read: Object.freeze({ id: 'read', label: '읽기·요약·설명', labelEn: 'reading / summarizing / explaining' }),
22
+ check: Object.freeze({ id: 'check', label: '상태 확인·검증', labelEn: 'status checks / verification' }),
23
+ run: Object.freeze({ id: 'run', label: '명령 실행 (빌드·테스트·git)', labelEn: 'running commands (build/test/git)' }),
24
+ });
25
+
26
+ export const RULE_CATEGORY_IDS = Object.freeze(Object.keys(RULE_CATEGORY_LABELS));
27
+
28
+ export const isRuleTier = (v) => typeof v === 'string' && RULE_TIERS.includes(v);
29
+ export const isRuleCategory = (v) => typeof v === 'string' && Object.hasOwn(RULE_CATEGORY_LABELS, v);
@@ -2,9 +2,10 @@ import { realpathSync } from 'node:fs';
2
2
  import { isAbsolute, resolve } from 'node:path';
3
3
  import { loadModelRules, ruleBudget } from './model-rules.js';
4
4
  import { findProjectRoot } from './harness.js';
5
+ import { RULE_TIERS, RULE_CATEGORY_IDS } from './rule-categories.js';
5
6
 
6
- export const SHARED_RULE_TIERS = ['T2', 'T1', 'T1H'];
7
- const CATEGORIES = new Set(['paste', 'translate', 'explore', 'read', 'check', 'run']);
7
+ export const SHARED_RULE_TIERS = [...RULE_TIERS];
8
+ const CATEGORIES = new Set(RULE_CATEGORY_IDS);
8
9
 
9
10
  /** A root as a real path, so a symlinked checkout or macOS /var names one directory once. */
10
11
  export function realProjectRoot(path) {
@@ -18,6 +18,8 @@ import { homedir } from 'node:os';
18
18
  import { dirname, join } from 'node:path';
19
19
  import { codexUserDir } from './agent.js';
20
20
  import { userLanguage } from './config.js';
21
+ import { modelRuleBaseText, composeRuleText, ruleBudget } from './model-rules.js';
22
+ import { RULE_CATEGORY_LABELS, isRuleCategory, isRuleTier } from './rule-categories.js';
21
23
  import { debug } from './debug.js';
22
24
  import {
23
25
  HARNESS_BLOCK_BEGIN,
@@ -119,10 +121,44 @@ export function teamRatchetPath({ agent = 'claude' } = {}) {
119
121
  : join(homedir(), '.claude', 'ratchet-team.md');
120
122
  }
121
123
 
124
+ const posInt = (v) => (Number.isSafeInteger(v) && v > 0 ? v : null);
125
+
126
+ /** The structured recommendation of a model rule row, or null when absent or not a known category and tier. */
127
+ function validRec(r) {
128
+ const rec = r && r.scope === 'model' ? r.rec : null;
129
+ return rec && typeof rec === 'object' && isRuleCategory(rec.category) && isRuleTier(rec.tier) ? rec : null;
130
+ }
131
+
132
+ /**
133
+ * The sentence a team rule row is written as on this machine. A model rule that
134
+ * carries a valid `rec` is drawn locally (the agent named is the one this
135
+ * machine has, the cap comes from the record, there is no example). Any other
136
+ * row keeps the server's `text`. Returns '' for a row with neither.
137
+ * Korean only for lang 'ko' on Claude; Codex files stay English.
138
+ */
139
+ export function teamRuleText(r, { lang = 'en', agent = 'claude' } = {}) {
140
+ const rec = validRec(r);
141
+ if (rec) {
142
+ const ko = lang === 'ko' && agent !== 'codex';
143
+ const l = ko ? 'ko' : 'en';
144
+ const { label, labelEn } = RULE_CATEGORY_LABELS[rec.category];
145
+ const calls = posInt(rec.calls);
146
+ const out = posInt(rec.out);
147
+ // Both caps missing: the tier's own default. One missing: its default fills in.
148
+ const base = ruleBudget({ tier: rec.tier });
149
+ const budget = calls === null && out === null ? base : { calls, out: out ?? base.out };
150
+ // root null: this file is global, so it names only agents the user directory holds.
151
+ const text = modelRuleBaseText({ tier: rec.tier, category: rec.category, label, labelEn, example: '' }, l, { root: null });
152
+ return composeRuleText(text, { tier: rec.tier, budget }, l);
153
+ }
154
+ return typeof r?.text === 'string' ? r.text.trim() : '';
155
+ }
156
+
122
157
  export function renderTeamRatchet(cache, { lang = 'en', agent = 'claude' } = {}) {
123
158
  if (!cache || !Array.isArray(cache.rules)) return null;
124
159
  const removed = new Set(Array.isArray(cache.removed) ? cache.removed : []);
125
- const live = cache.rules.filter((r) => r && typeof r.text === 'string' && r.text.trim() && !removed.has(r.id));
160
+ const textOf = (r) => teamRuleText(r, { lang, agent });
161
+ const live = cache.rules.filter((r) => r && textOf(r) && !removed.has(r.id));
126
162
  if (!live.length) return null;
127
163
  // Rows from servers older than the org layer carry no level: they are team rules.
128
164
  const org = live.filter((r) => r.level === 'org');
@@ -140,7 +176,7 @@ export function renderTeamRatchet(cache, { lang = 'en', agent = 'claude' } = {})
140
176
  const H = ko
141
177
  ? { org: '조직 룰', orgModel: '조직 모델 룰', team: '팀 룰', teamModel: '팀 모델 룰' }
142
178
  : { org: 'Organization rules', orgModel: 'Organization model rules', team: 'Team rules', teamModel: 'Team model rules' };
143
- const line = (r) => `- ${r.text.trim().replace(/\s*\n\s*/g, ' ')}`;
179
+ const line = (r) => `- ${textOf(r).replace(/\s*\n\s*/g, ' ')}`;
144
180
  const section = (rows, title, modelTitle) => {
145
181
  if (!rows.length) return '';
146
182
  const plain = rows.filter((r) => !isModel(r));
@@ -271,6 +307,6 @@ export function autoJoinNoticeBlock(dir = userDataDir(), lang = userLanguage())
271
307
  try { writeStateFile(file, `${JSON.stringify({ ...state, autoJoinNoticePending: false }, null, 2)}\n`); }
272
308
  catch (e) { debug('team-ratchet:notice-clear', e); }
273
309
  return lang === 'ko'
274
- ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude·Codex·게이트웨이), 위임 비용, 절감, 위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
275
- : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates only (spend across Claude, Codex and the gateway, delegation cost, savings, delegation counts). See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
310
+ ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude, Codex, 게이트웨이), 위임 비용, 절감, 위임 횟수)와 위임 룰 요약(카테고리, 티어, 위임 횟수, 실패율, 절감액)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
311
+ : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates (spend across Claude, Codex and the gateway, delegation cost, savings, delegation counts) and a delegation rule summary (category, tier, delegation count, failure rate, savings) only. See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
276
312
  }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * team-rule-stats — the per-category summary of this machine's model-fitting
3
+ * rules that a team member uploads (RPC member_rules_report).
4
+ *
5
+ * The registry (model-rules.json) holds project paths, the user's prompt
6
+ * excerpts and rule sentences. None of that may leave the machine, so the
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
10
+ * and checks that no path or example text survives into the JSON.
11
+ *
12
+ * Rules of one (category, tier) from different projects fold into one row;
13
+ * the server rejects a report that names the same pair twice.
14
+ */
15
+
16
+ import { loadModelRules, ruleBudget } from './model-rules.js';
17
+ import { RULE_CATEGORY_IDS, RULE_TIERS, isRuleCategory, isRuleTier } from './rule-categories.js';
18
+
19
+ export const RULE_STATS_MAX = 24;
20
+ export const RULE_STAT_KEYS = Object.freeze([
21
+ 'category', 'tier', 'status', 'episodes', 'delegated', 'delegated_err',
22
+ 'saved_usd', 'baseline_err', 'budget_calls', 'budget_out', 'since',
23
+ ]);
24
+
25
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
26
+ const num = (v) => (Number.isFinite(v) ? v : 0);
27
+ const posInt = (v) => (Number.isSafeInteger(v) && v > 0 ? v : null);
28
+ const round = (v, places) => { const k = 10 ** places; return Math.round(v * k) / k; };
29
+ const rate = (v) => (Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : null);
30
+
31
+ /** Weighted mean of [value, weight] pairs; null when no pair has weight. */
32
+ function weighted(pairs) {
33
+ let sum = 0;
34
+ let weight = 0;
35
+ for (const [value, w] of pairs) {
36
+ if (value === null || !(w > 0)) continue;
37
+ sum += value * w;
38
+ weight += w;
39
+ }
40
+ return weight > 0 ? round(sum / weight, 4) : null;
41
+ }
42
+
43
+ /** The most common budget among the rules; the first one wins a tie. */
44
+ function commonBudget(rules) {
45
+ const tally = new Map();
46
+ for (const r of rules) {
47
+ const b = ruleBudget(r) || {};
48
+ const calls = posInt(b.calls);
49
+ const out = posInt(b.out);
50
+ const key = `${calls}|${out}`;
51
+ const hit = tally.get(key);
52
+ if (hit) hit.n += 1; else tally.set(key, { calls, out, n: 1 });
53
+ }
54
+ let best = null;
55
+ for (const v of tally.values()) if (!best || v.n > best.n) best = v;
56
+ return best || { calls: null, out: null };
57
+ }
58
+
59
+ /**
60
+ * Fold registry rules into the upload rows. Pure: takes the rule array,
61
+ * returns a new array of allowlisted rows ordered by category, then tier.
62
+ */
63
+ export function summarizeModelRules(rules) {
64
+ const groups = new Map();
65
+ for (const r of Array.isArray(rules) ? rules : []) {
66
+ if (!r || (r.status !== 'active' && r.status !== 'review')) continue;
67
+ if (!isRuleCategory(r.category) || !isRuleTier(r.tier)) continue;
68
+ const key = `${r.category}|${r.tier}`;
69
+ if (!groups.has(key)) groups.set(key, []);
70
+ groups.get(key).push(r);
71
+ }
72
+ const rows = [];
73
+ for (const category of RULE_CATEGORY_IDS) {
74
+ for (const tier of RULE_TIERS) {
75
+ const list = groups.get(`${category}|${tier}`);
76
+ if (!list) continue;
77
+ const delegated = list.reduce((n, r) => n + Math.max(0, Math.trunc(num(r.delegatedRuns))), 0);
78
+ const dates = list.map((r) => String(r.promotedAt || '').slice(0, 10)).filter((d) => DATE_RE.test(d)).sort();
79
+ const budget = commonBudget(list);
80
+ rows.push({
81
+ category,
82
+ tier,
83
+ status: list.some((r) => r.status === 'active') ? 'active' : 'review',
84
+ episodes: list.reduce((n, r) => n + Math.max(0, Math.trunc(num(r.count))), 0),
85
+ delegated,
86
+ delegated_err: delegated > 0 ? weighted(list.map((r) => [rate(r.delegatedErrRate), Math.max(0, num(r.delegatedRuns))])) : null,
87
+ saved_usd: round(list.reduce((n, r) => n + num(r.savedUsd), 0), 2),
88
+ baseline_err: weighted(list.map((r) => [rate(r.baselineErrRate), Math.max(0, num(r.baselineSample))])),
89
+ budget_calls: budget.calls,
90
+ budget_out: budget.out,
91
+ since: dates[0] || null,
92
+ });
93
+ }
94
+ }
95
+ return rows.slice(0, RULE_STATS_MAX);
96
+ }
97
+
98
+ /** The summary for this machine's registry (read-only; no network). */
99
+ export function ruleStatsSummary({ dir } = {}) {
100
+ return summarizeModelRules(loadModelRules(dir ? { dir } : {}).rules);
101
+ }
package/src/team-sync.js CHANGED
@@ -25,6 +25,11 @@
25
25
  * files right away, so a new session picks the rules up without waiting for
26
26
  * the next session-start render.
27
27
  *
28
+ * A full sync also reports a per-category summary of the machine's model
29
+ * delegation rules (category, tier, counts, rates, savings; see
30
+ * team-rule-stats.js), when it changed or a day has passed. Rule text,
31
+ * examples and project paths stay local.
32
+ *
28
33
  * Opt out of all network traffic with SPRAG_NO_TEAM_SYNC=1.
29
34
  */
30
35
 
@@ -32,6 +37,7 @@ import { envVar } from './env.js';
32
37
  import { readFileSync, existsSync, rmSync, chmodSync } from 'node:fs';
33
38
  import { execFileSync } from 'node:child_process';
34
39
  import { join } from 'node:path';
40
+ import { createHash } from 'node:crypto';
35
41
  import { release as osRelease } from 'node:os';
36
42
  import { createRequire } from 'node:module';
37
43
  import { userDataDir } from './paths.js';
@@ -43,6 +49,7 @@ import { trustSystemCA } from './system-ca.js';
43
49
  import { loadLedger, modelFamily, roundUsd, changedSinceForSync, clearChangedSince } from './savings-ledger.js';
44
50
  import { sessionCost, pricedParts } from './claude-price.js';
45
51
  import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
52
+ import { ruleStatsSummary } from './team-rule-stats.js';
46
53
  import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
47
54
  import { parseMinVersion } from './org-upgrade.js';
48
55
  import { codexUserDir } from './agent.js';
@@ -772,6 +779,40 @@ export function refreshTeamRatchetFiles({ dir = userDataDir() } = {}) {
772
779
  return out;
773
780
  }
774
781
 
782
+ export const RULE_STATS_RESEND_MS = 24 * 60 * 60 * 1000;
783
+ const RULE_STATS_RETRY_MS = 60 * 60 * 1000;
784
+
785
+ /**
786
+ * Report the delegation-rule summary (member_rules_report) when it differs from
787
+ * what was last sent or the last report is a day old. Returns the team.json
788
+ * fields to merge into the sync's state, or null for "nothing to change".
789
+ * Fails soft: a failure (an older server answers "Could not find the function")
790
+ * never fails the sync, and is retried after an hour at the earliest.
791
+ */
792
+ async function reportRuleStats({ state, dir, fetch, now }) {
793
+ try {
794
+ const rows = ruleStatsSummary({ dir });
795
+ // Never reported and nothing to report: no call at all.
796
+ if (!rows.length && !state.ruleStatsSent) return null;
797
+ const hash = createHash('sha256').update(JSON.stringify(rows)).digest('hex').slice(0, 32);
798
+ const age = now - Number(state.ruleStatsAt);
799
+ const fresh = Number.isFinite(age) && age >= 0 && age < RULE_STATS_RESEND_MS;
800
+ if (hash === state.ruleStatsSent && (fresh || !rows.length)) return null;
801
+ const tried = now - Number(state.ruleStatsTriedAt);
802
+ if (Number.isFinite(tried) && tried >= 0 && tried < RULE_STATS_RETRY_MS) return null;
803
+ try {
804
+ await rpc('member_rules_report', { member_key: state.memberKey, rules: rows }, { fetch });
805
+ } catch (e) {
806
+ debug('team-sync:rule-stats', e);
807
+ return { ruleStatsTriedAt: now };
808
+ }
809
+ return { ruleStatsSent: hash, ruleStatsAt: now, ruleStatsTriedAt: undefined };
810
+ } catch (e) {
811
+ debug('team-sync:rule-stats', e);
812
+ return null;
813
+ }
814
+ }
815
+
775
816
  /**
776
817
  * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
777
818
  * is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
@@ -873,7 +914,8 @@ export async function syncTeam({
873
914
  .filter((r) => r.day >= win.startKey).slice(-MAX_ROWS);
874
915
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
875
916
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
876
- const next = withRulesMeta({ ...state, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
917
+ const ruleStats = await reportRuleStats({ state, dir, fetch, now });
918
+ const next = withRulesMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
877
919
  if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
878
920
  else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
879
921
  if (gatewayOk || !hasGateway) delete next.lastGatewayError;
@@ -952,6 +994,6 @@ export function autoJoinNotice(state, lang = 'en') {
952
994
  state.autoJoinNoticePending = false;
953
995
  const name = state.teamName || '';
954
996
  return lang === 'ko'
955
- ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude·Codex·게이트웨이), 위임 비용, 절감, 위임 횟수)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
956
- : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates only (spend across Claude, Codex and the gateway, delegation cost, savings, delegation counts). See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
997
+ ? `Sprag: 이 PC는 SPRAG_TEAM_TOKEN 으로 팀 "${name}" 에 자동 참여됐습니다. 보내는 것은 하루 단위 집계(지출(Claude, Codex, 게이트웨이), 위임 비용, 절감, 위임 횟수)와 위임 룰 요약(카테고리, 티어, 위임 횟수, 실패율, 절감액)뿐입니다. \`sprag team status --show-payload\` 로 내용을 확인하고 \`sprag team leave\` 로 멈출 수 있습니다.`
998
+ : `Sprag: this machine was enrolled in team "${name}" through SPRAG_TEAM_TOKEN. It sends daily aggregates (spend across Claude, Codex and the gateway, delegation cost, savings, delegation counts) and a delegation rule summary (category, tier, delegation count, failure rate, savings) only. See what is sent with \`sprag team status --show-payload\`; stop with \`sprag team leave\`.`;
957
999
  }