sprag-cli 3.124.2 → 3.125.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/README.ko.md CHANGED
@@ -328,7 +328,7 @@ Pro 의 기능에 더해 다음을 제공합니다.
328
328
 
329
329
  ### 컴퓨터가 보내는 것
330
330
 
331
- Sprag 은 켜지 않으면 로컬에서만 동작합니다. `sprag team join <토큰>` 을 실행하거나(조직 전체는 `SPRAG_TEAM_TOKEN`) 하면 컴퓨터마다 하루에 한 행씩 올라갑니다. 내용은 지출, 절감액, 위임 실행 횟수, 모델 계열 비중입니다. 대화 기록, 파일 경로, 프로젝트 이름은 보내지 않습니다. 프롬프트도 Enterprise 조직이 수집 정책을 켜지 않는 한 보내지 않으며, `sprag team status --show-payload` 로 올라갈 내용을 그대로 볼 수 있습니다. 그 대신 팀 소유자는 대시보드에서 구성원별 합계를 보고, 모든 구성원에게 자동으로 적용될 래칫 룰을 승인할 수 있습니다.
331
+ Sprag 은 켜지 않으면 로컬에서만 동작합니다. `sprag team join <토큰>` 을 실행하거나(조직 전체는 `SPRAG_TEAM_TOKEN`) 하면 컴퓨터마다 하루에 한 행씩 올라갑니다. 내용은 지출, 절감액, 위임 실행 횟수, 모델 계열 비중입니다. 대화 기록, 파일 경로, 프로젝트 이름, sprag 자체의 오류 메시지는 보내지 않습니다. 프롬프트도 Enterprise 조직이 수집 정책을 켜지 않는 한 보내지 않으며, `sprag team status --show-payload` 로 올라갈 내용을 그대로 볼 수 있습니다. 그 대신 팀 소유자는 대시보드에서 구성원별 합계를 보고, 모든 구성원에게 자동으로 적용될 래칫 룰을 승인할 수 있습니다.
332
332
 
333
333
  `SPRAG_NO_TEAM_SYNC=1` 은 팀 관련 통신을 모두 끄고, `sprag team leave` 는 참여를 해제합니다.
334
334
 
package/README.md CHANGED
@@ -389,7 +389,7 @@ Prompt capture is off unless an organization owner or admin turns it on.
389
389
 
390
390
  ### What a machine sends
391
391
 
392
- Sprag stays local unless you opt in. With `sprag team join <token>` (or `SPRAG_TEAM_TOKEN` for a whole organization), each machine uploads one row per day: spend, savings, delegated-run count and model-family share. Transcripts, file paths and project names are never sent. Prompts are not sent either, unless an Enterprise organization turns on prompt capture, and `sprag team status --show-payload` prints exactly what would go up. In return the team owner sees per-member totals in a dashboard and can approve ratchet rules that every member picks up automatically.
392
+ Sprag stays local unless you opt in. With `sprag team join <token>` (or `SPRAG_TEAM_TOKEN` for a whole organization), each machine uploads one row per day: spend, savings, delegated-run count and model-family share. Transcripts, file paths, project names and sprag's own error messages are never sent. Prompts are not sent either, unless an Enterprise organization turns on prompt capture, and `sprag team status --show-payload` prints exactly what would go up. In return the team owner sees per-member totals in a dashboard and can approve ratchet rules that every member picks up automatically.
393
393
 
394
394
  `SPRAG_NO_TEAM_SYNC=1` turns all team traffic off, and `sprag team leave` removes the membership.
395
395
 
package/docs/DATA.ko.md CHANGED
@@ -24,7 +24,7 @@ Sprag 서버로 데이터를 올리는 경우만 플랜별로 정리했습니다
24
24
  - OS 이름과 버전, Sprag 버전, 표시 이름(기본값은 `member-3f9a2c71` 같은 무작위 ID)
25
25
  - 위임 룰 요약: 카테고리별 횟수, 실패율, 절감액 같은 숫자만
26
26
 
27
- **올리지 않는 것**: 프롬프트, 대화 기록, 코드, 파일 경로, 프로젝트 이름, 룰 본문, API 키, 호스트 이름
27
+ **올리지 않는 것**: 프롬프트, 대화 기록, 코드, 파일 경로, 프로젝트 이름, 룰 본문, API 키, 호스트 이름, 오류 메시지
28
28
 
29
29
  조직의 오너와 어드민은 구성원별 하루 합계만 볼 수 있습니다.
30
30
 
@@ -32,8 +32,8 @@ Sprag 서버로 데이터를 올리는 경우만 플랜별로 정리했습니다
32
32
 
33
33
  Pro 와 같은 집계를 올립니다. 조직 오너나 어드민이 팀별로 프롬프트 수집을 켠 경우에만 다음이 더해집니다.
34
34
 
35
- - 메인 세션에 직접 입력한 프롬프트의 본문(최대 20,000자), 입력 시각, 프로젝트 폴더 이름
36
- - API 키, 토큰, 비밀번호, 이메일, 전화번호, 주민등록번호, 카드번호는 업로드 전에 컴퓨터에서 `[redacted]` 로 가립니다
35
+ - 메인 세션에 직접 입력한 프롬프트의 본문(최대 20,000자), 입력 시각, 프로젝트 이름이 아닌 이 컴퓨터 전용 별칭(`p-` 뒤에 16진수 10자)
36
+ - API 키, 토큰, 비밀번호, 이메일, 전화번호, 주민등록번호, 카드번호는 `[redacted]`, 네트워크 주소는 `<host>`, URL은 `<url>`, 파일 경로는 `<path>` 로 모두 업로드 전에 컴퓨터에서 가립니다
37
37
  - 수집을 켜기 전에 쓴 기록은 올리지 않습니다
38
38
  - 어시스턴트 답변, 도구 출력, 파일 내용은 올리지 않습니다
39
39
 
package/docs/DATA.md CHANGED
@@ -24,7 +24,7 @@ Only computers that ran `sprag team join` or got `SPRAG_TEAM_TOKEN` from their o
24
24
  - OS name and version, Sprag version, display name (a random ID such as `member-3f9a2c71` by default)
25
25
  - delegation rule summary: numbers only, such as counts, failure rate and savings per category
26
26
 
27
- **Not uploaded**: prompts, conversations, code, file paths, project names, rule text, API keys, hostnames
27
+ **Not uploaded**: prompts, conversations, code, file paths, project names, rule text, API keys, hostnames, error messages
28
28
 
29
29
  Organization owners and admins see only each member's daily totals.
30
30
 
@@ -32,8 +32,8 @@ Organization owners and admins see only each member's daily totals.
32
32
 
33
33
  The same totals as Pro. Only when an organization owner or admin turns prompt capture on for a team, these are added:
34
34
 
35
- - the text of prompts typed in main sessions (up to 20,000 characters), the time, and the project folder name
36
- - API keys, tokens, passwords, emails, phone numbers, Korean resident registration numbers and card numbers are masked as `[redacted]` on your computer before upload
35
+ - the text of prompts typed in main sessions (up to 20,000 characters), the time, and a per-machine alias of the project (`p-` plus 10 hex characters), not its name
36
+ - API keys, tokens, passwords, emails, phone numbers, Korean resident registration numbers and card numbers are masked as `[redacted]`, network addresses as `<host>`, URLs as `<url>` and file paths as `<path>`, all on your computer before upload
37
37
  - nothing written before capture was turned on is uploaded
38
38
  - assistant replies, tool output and file contents are not uploaded
39
39
 
package/docs/TEAM.ko.md CHANGED
@@ -30,7 +30,7 @@ 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 자체의 오류 메시지입니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 옵트인 프롬프트 업로드만 예외이며 "프롬프트 사용량 (엔터프라이즈)" 절에 적었습니다. 룰 본문은 직접 `sprag team propose` 를 실행할 때만 밖으로 나갑니다.
34
34
 
35
35
  ### 위임 룰 요약
36
36
 
@@ -51,7 +51,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
51
51
 
52
52
  하루 단위 집계 업로드는 마지막 성공 이후 5분에 한 번 이하로 실행됩니다. SessionStart 훅(그리고 작은 로컬 파일만 읽는 프롬프트 훅)이 띄운 분리된 자식 프로세스가 보냅니다. 네트워크가 끊기는 등 동기화가 실패하면 5분 주기 대신 15분, 30분, 60분 뒤에 다시 시도합니다(최대 60분 간격). 마지막으로 올린 날짜를 기억해 두었다가 그 전날부터 최대 30일 치를 다시 보내므로, 며칠 꺼져 있던 컴퓨터도 처음 성공하는 동기화에서 빠진 날을 따라잡습니다. 하루 단위 행은 덮어쓰기라 다시 보내도 안전합니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 프롬프트 업로드는 따로 30분 타이머로 움직입니다("프롬프트 사용량 (엔터프라이즈)" 절 참고). statusline 을 그리는 경로에서는 절대 실행되지 않습니다.
53
53
 
54
- 팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
54
+ 팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1a2b3c4d 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1a2b3c4d 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
55
55
 
56
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
 
@@ -196,15 +196,15 @@ Free, 프로(좌석당 월 $5), 엔터프라이즈(좌석당 월 $10, 프롬프
196
196
 
197
197
  엔터프라이즈 조직의 오너와 어드민은 sprag.io/team 에서 프롬프트 탭을 씁니다. 사용자별 프롬프트 수, 글자 수, 평균 길이, 활동 일수, 마지막 프롬프트를 표로 보고, 사용자마다 프롬프트를 검색해 볼 수 있습니다. 프롬프트는 프롬프트 수집을 켠 엔터프라이즈 팀만 저장합니다. 프로 조직에는 잠금 화면이 나옵니다.
198
198
 
199
- **무엇을 수집하나.** 직접 입력한 프롬프트만 올라갑니다. 메인 Claude Code 세션(`~/.claude/projects/**/*.jsonl`)과 Codex 세션(`<CODEX_HOME 또는 ~/.codex>/sessions/**/*.jsonl`)이 대상입니다. 프롬프트마다 시각, 프로젝트 폴더 이름(경로의 마지막 부분이며 전체 경로는 아닙니다), 본문(최대 20,000자)이 올라갑니다. Claude 가 답하는 도중에 미리 입력해 둔 프롬프트도 대상이고, 프롬프트에 붙여 넣은 텍스트는 그 프롬프트와 함께 보냅니다. 어시스턴트 답변, 도구 출력, 파일 내용, 서브에이전트 기록, 슬래시 명령 래퍼, `!` 셸 명령과 그 출력, 백그라운드 작업 알림, 다른 에이전트가 보낸 메시지, 시스템 리마인더, 파일 경로는 수집하지 않습니다.
199
+ **무엇을 수집하나.** 직접 입력한 프롬프트만 올라갑니다. 메인 Claude Code 세션(`~/.claude/projects/**/*.jsonl`)과 Codex 세션(`<CODEX_HOME 또는 ~/.codex>/sessions/**/*.jsonl`)이 대상입니다. 프롬프트마다 시각, 프로젝트 별칭, 본문(최대 20,000자)이 올라갑니다. 별칭은 `p-` 뒤에 16진수 10자가 붙은 값으로, 이 컴퓨터에만 있는 비밀 키(`prompt-alias.key`)로 폴더 이름에서 계산합니다. 같은 프로젝트는 이 컴퓨터에서 늘 같은 별칭을 받고 폴더 이름 자체는 나가지 않습니다. Claude 가 답하는 도중에 미리 입력해 둔 프롬프트도 대상이고, 프롬프트에 붙여 넣은 텍스트는 그 프롬프트와 함께 보냅니다. 어시스턴트 답변, 도구 출력, 파일 내용, 서브에이전트 기록, 슬래시 명령 래퍼, `!` 셸 명령과 그 출력, 백그라운드 작업 알림, 다른 에이전트가 보낸 메시지, 시스템 리마인더, 파일 경로는 수집하지 않습니다.
200
200
 
201
- **비밀값과 개인정보 가림.** 가림 처리는 올리기 전에 이 컴퓨터에서 이루어집니다. 눈에 띄는 비밀값은 `[redacted]` 로 바꿉니다. API 키와 토큰(`sk-...`, `sk-ant-...`, `ghp_...`, `gho_...`, `github_pat_...`, `AKIA...`, `xox[abpr]-...`), `Bearer` 토큰, 개인 키 블록, `KEY=`, `TOKEN=`, `PASSWORD=`, `SECRET=` 형태의 대입이 대상입니다. 개인정보는 종류별 표지로 바꿉니다. 이메일 주소는 `[redacted:email]`, 한국 전화번호(휴대전화, `+82` 형태, 하이픈으로 이은 지역번호 유선전화. `1588-xxxx` 같은 대표번호는 그대로 둡니다)는 `[redacted:phone]`, 주민등록번호와 외국인등록번호(`YYMMDD-NNNNNNN`)는 `[redacted:rrn]`, Luhn 검사를 통과하는 카드번호는 `[redacted:card]` 로 바뀝니다. `git@github.com`, `react@18.3.1`, 13자리 타임스탬프처럼 모양만 비슷한 값은 건드리지 않습니다. 패턴 매칭이므로 흔한 형태만 잡을 뿐 보장하지는 않습니다. 이름, 주소, 자유 서술은 찾지 못하므로, 수집이 켜진 컴퓨터에서는 프롬프트에 비밀값이나 개인정보를 붙여 넣지 마십시오.
201
+ **비밀값과 개인정보 가림.** 가림 처리는 올리기 전에 이 컴퓨터에서 이루어집니다. 눈에 띄는 비밀값은 `[redacted]` 로 바꿉니다. API 키와 토큰(`sk-...`, `sk-ant-...`, `ghp_...`, `gho_...`, `github_pat_...`, `AKIA...`, `xox[abpr]-...`), `Bearer` 토큰, 개인 키 블록, `KEY=`, `TOKEN=`, `PASSWORD=`, `SECRET=` 형태의 대입이 대상입니다. 개인정보는 종류별 표지로 바꿉니다. 이메일 주소는 `[redacted:email]`, 한국 전화번호(휴대전화, `+82` 형태, 하이픈으로 이은 지역번호 유선전화. `1588-xxxx` 같은 대표번호는 그대로 둡니다)는 `[redacted:phone]`, 주민등록번호와 외국인등록번호(`YYMMDD-NNNNNNN`)는 `[redacted:rrn]`, Luhn 검사를 통과하는 카드번호는 `[redacted:card]` 로 바뀝니다. 네트워크 주소(IP 주소와 내부 호스트 이름)는 `<host>`, URL은 `<url>`(sprag, Anthropic, GitHub, npm, Supabase 주소는 그대로 둡니다), 홈 디렉터리를 포함한 절대 파일 경로는 `<path>` 로 바뀝니다. `git@github.com`, `react@18.3.1`, 13자리 타임스탬프처럼 모양만 비슷한 값은 건드리지 않습니다. 패턴 매칭이므로 흔한 형태만 잡을 뿐 보장하지는 않습니다. 이름, 주소, 자유 서술은 찾지 못하므로, 수집이 켜진 컴퓨터에서는 프롬프트에 비밀값이나 개인정보를 붙여 넣지 마십시오.
202
202
 
203
203
  **과거분은 올리지 않습니다.** 컴퓨터가 프롬프트 수집이 켜진 것을 처음 보면 기존 기록의 끝에 표시를 하고 그 뒤에 입력한 것만 올립니다. 정책이 이 컴퓨터에 닿기 전에 쓴 내용은 전혀 나가지 않고, 수집이 꺼진 동안 입력한 내용도 나중에 올라가지 않습니다. 그 뒤에 새로 생긴 기록 파일은 처음부터 읽습니다. 정책이 꺼지면 컴퓨터가 읽던 위치(`prompts-offsets.json`)를 지우므로, 다시 켜면 모든 파일의 끝에서 새로 시작합니다.
204
204
 
205
205
  **주기.** 프롬프트는 Claude Code 나 Codex 를 쓰는 동안 약 30분마다 올라가고, 하루 단위 집계는 5분마다 올라갑니다. 프롬프트를 제출할 때 작은 로컬 타이머를 확인하고, 30분이 지났으면 분리된 백그라운드 프로세스가 업로드를 시작합니다(훅 안에서는 네트워크 호출도 기록 파싱도 하지 않습니다). 세션을 시작할 때와 `sprag team sync --force` 를 실행할 때도 올라갑니다. 한 번에 최대 2,000건 또는 8MB까지 올리고 나머지는 다음 동기화로 넘어갑니다. 파일 경로는 보내지 않습니다. 파일은 경로 해시의 앞 16자로만 구분하고, 같은 조각을 다시 보내도 서버가 무시합니다.
206
206
 
207
- **확인하기.** `sprag team status` 는 "프롬프트 수집: 켜짐"과 마지막 프롬프트 업로드의 시각과 건수를 보여 줍니다. `sprag team status --show-payload` 는 올라갈 차례를 기다리는 프롬프트 수와 예시 하나(시각, 프로젝트, 앞 80자)를 더 보여 주며, 대기 중인 프롬프트의 전체 본문은 출력하지 않습니다.
207
+ **확인하기.** `sprag team status` 는 "프롬프트 수집: 켜짐"과 마지막 프롬프트 업로드의 시각과 건수를 보여 줍니다. `sprag team status --show-payload` 는 올라갈 차례를 기다리는 프롬프트 수와 예시 하나(시각, 프로젝트 별칭, 앞 80자)를 더 보여 주며, 대기 중인 프롬프트의 전체 본문은 출력하지 않습니다.
208
208
 
209
209
  **멈추는 방법.** 오너나 어드민에게 팀의 프롬프트 수집을 꺼 달라고 요청하면 다음 동기화부터 업로드가 멈추고 위치 파일이 지워집니다. 바로 모든 업로드를 멈추려면 `SPRAG_NO_TEAM_SYNC=1` 을 설정하거나 `sprag team leave` 를 실행합니다.
210
210
 
@@ -223,6 +223,7 @@ Free, 프로(좌석당 월 $5), 엔터프라이즈(좌석당 월 $10, 프롬프
223
223
  | `<사용자 데이터 디렉터리>/team-rules.json` | 마지막 동기화 때 받은 조직·팀 룰 |
224
224
  | `<사용자 데이터 디렉터리>/org-upgrade.json`, `org-upgrade.log` | 조직 최소 버전 업그레이드의 상태와 설치 출력 |
225
225
  | `<사용자 데이터 디렉터리>/prompts-offsets.json` | 프롬프트 업로더가 기록 파일마다 어디까지 읽었는지 적은 파일이며, 프롬프트 수집이 켜진 동안만 있습니다 |
226
+ | `<사용자 데이터 디렉터리>/prompt-alias.key` | 프로젝트 별칭을 만드는 비밀 키(권한 0600)이며 밖으로 올라가지 않습니다 |
226
227
  | `~/.claude/ratchet-team.md` | Claude Code 용 승인된 조직·팀 룰이며 `~/.claude/CLAUDE.md` 에서 import 합니다 |
227
228
  | `<CODEX_HOME>/ratchet-team.md` | Codex 용 같은 룰 |
228
229
  | `SPRAG_TEAM_TOKEN` | 초대 토큰이며, 다음 세션 시작 때 컴퓨터를 등록합니다 |
package/docs/TEAM.md CHANGED
@@ -30,7 +30,7 @@ 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, 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.
33
+ Not sent: prompts, transcripts, file paths, project names, rule text, rule examples, API keys, sprag's own error messages. 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
34
 
35
35
  ### Delegation rule summary
36
36
 
@@ -51,7 +51,7 @@ Rule text, examples and project paths stay on the machine. `sprag team status --
51
51
 
52
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.
53
53
 
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`.
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-1a2b3c4d 🦊 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-1a2b3c4d Fox #3 of 12`.
55
55
 
56
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
 
@@ -218,15 +218,15 @@ Free, Pro ($5 per seat per month) and Enterprise ($10 per seat per month, with p
218
218
 
219
219
  Owners and admins of an Enterprise organization get a Prompts tab on sprag.io/team: a per-user table of prompts, characters, average length, active days and last prompt, and a searchable prompt list per user. Prompts are stored only for Enterprise teams that have prompt capture switched on; Pro organizations see a locked state.
220
220
 
221
- **What is captured.** Only the prompts you typed yourself, from your main Claude Code sessions (`~/.claude/projects/**/*.jsonl`) and Codex sessions (`<CODEX_HOME or ~/.codex>/sessions/**/*.jsonl`). Each prompt goes up as its time, the project folder's name (the last part of the path, never the full path) and its text, cut at 20,000 characters. A prompt you type while Claude is still working (a queued prompt) counts too. Text you paste into a prompt goes up as part of it. Not captured: assistant replies, tool output, file contents, subagent transcripts, slash-command wrappers, `!` shell commands and their output, background-task notifications, messages from other agents, system reminders, or any file path.
221
+ **What is captured.** Only the prompts you typed yourself, from your main Claude Code sessions (`~/.claude/projects/**/*.jsonl`) and Codex sessions (`<CODEX_HOME or ~/.codex>/sessions/**/*.jsonl`). Each prompt goes up as its time, a project alias and its text, cut at 20,000 characters. A prompt you type while Claude is still working (a queued prompt) counts too. Text you paste into a prompt goes up as part of it. The alias is `p-` plus 10 hex characters computed from the folder name with a secret key that exists only on your machine (`prompt-alias.key`), so the same project always gets the same alias on your machine and the name itself is never sent. Not captured: assistant replies, tool output, file contents, subagent transcripts, slash-command wrappers, `!` shell commands and their output, background-task notifications, messages from other agents, system reminders, or any file path.
222
222
 
223
- **Redaction.** Masking happens on your machine, before anything is uploaded. Obvious secrets are replaced with `[redacted]`: API keys and tokens (`sk-...`, `sk-ant-...`, `ghp_...`, `gho_...`, `github_pat_...`, `AKIA...`, `xox[abpr]-...`), `Bearer` tokens, private key blocks, and `KEY=`, `TOKEN=`, `PASSWORD=` and `SECRET=` assignments. Personal data is masked with typed markers: email addresses as `[redacted:email]`, Korean phone numbers (mobile, `+82` and hyphenated landline forms; business numbers such as `1588-xxxx` are left alone) as `[redacted:phone]`, resident and foreigner registration numbers (`YYMMDD-NNNNNNN`) as `[redacted:rrn]`, and card numbers that pass the Luhn check as `[redacted:card]`. Things that only look similar stay as they are, for example `git@github.com`, `react@18.3.1` and 13-digit timestamps. This is pattern matching: it catches common forms only and is not a guarantee. Names, addresses and free-form text are not detected, so do not paste secrets or personal data into prompts on a machine with capture on.
223
+ **Redaction.** Masking happens on your machine, before anything is uploaded. Obvious secrets are replaced with `[redacted]`: API keys and tokens (`sk-...`, `sk-ant-...`, `ghp_...`, `gho_...`, `github_pat_...`, `AKIA...`, `xox[abpr]-...`), `Bearer` tokens, private key blocks, and `KEY=`, `TOKEN=`, `PASSWORD=` and `SECRET=` assignments. Personal data is masked with typed markers: email addresses as `[redacted:email]`, Korean phone numbers (mobile, `+82` and hyphenated landline forms; business numbers such as `1588-xxxx` are left alone) as `[redacted:phone]`, resident and foreigner registration numbers (`YYMMDD-NNNNNNN`) as `[redacted:rrn]`, and card numbers that pass the Luhn check as `[redacted:card]`. Network addresses (IP addresses, internal host names) become `<host>`, URLs become `<url>` (sprag, Anthropic, GitHub, npm and Supabase addresses stay), and absolute file paths, including your home directory, become `<path>`. Things that only look similar stay as they are, for example `git@github.com`, `react@18.3.1` and 13-digit timestamps. This is pattern matching: it catches common forms only and is not a guarantee. Names, addresses and free-form text are not detected, so do not paste secrets or personal data into prompts on a machine with capture on.
224
224
 
225
225
  **No backfill.** The first time a machine sees prompt capture on, it marks the end of every existing transcript and uploads only what you type after that. Nothing written before the policy reached your machine is sent, and what you type while capture is off is never sent later. Transcripts created afterwards are read from their start. When the policy turns off, the machine forgets its place (`prompts-offsets.json`), so switching it on again starts fresh at the end of every file.
226
226
 
227
227
  **Cadence.** Prompts are uploaded about every 30 minutes while Claude Code or Codex is in use; the daily aggregate goes up every 5 minutes. A prompt you submit checks a small local timer and, when 30 minutes have passed, starts a detached background upload (no network and no parsing happen in the hook itself). A session start and `sprag team sync --force` also upload. One run sends at most 2,000 prompts or 8 MB; the rest waits for the next sync. The file path is never sent; each file is identified by the first 16 characters of a hash of its path, and a repeated chunk is ignored by the server.
228
228
 
229
- **Check it.** `sprag team status` shows "Prompt capture: on" and the time and count of the last prompt upload. `sprag team status --show-payload` also shows how many prompts are waiting and one example (time, project, first 80 characters), never the full text of the pending prompts.
229
+ **Check it.** `sprag team status` shows "Prompt capture: on" and the time and count of the last prompt upload. `sprag team status --show-payload` also shows how many prompts are waiting and one example (time, project alias, first 80 characters), never the full text of the pending prompts.
230
230
 
231
231
  **How to stop.** Ask an owner or admin to switch prompt capture off for the team (the next sync stops the upload and clears the position file); set `SPRAG_NO_TEAM_SYNC=1` to stop every upload right away; or run `sprag team leave`.
232
232
 
@@ -245,6 +245,7 @@ Owners and admins of an Enterprise organization get a Prompts tab on sprag.io/te
245
245
  | `<user data dir>/team-rules.json` | Organization and team rules pulled at the last sync |
246
246
  | `<user data dir>/org-upgrade.json`, `org-upgrade.log` | State and install output of the organization minimum-version upgrade |
247
247
  | `<user data dir>/prompts-offsets.json` | Where the prompt uploader stopped in each transcript; exists only while prompt capture is on |
248
+ | `<user data dir>/prompt-alias.key` | Secret key (mode 0600) behind the project aliases; never uploaded |
248
249
  | `~/.claude/ratchet-team.md` | Approved organization and team rules for Claude Code, imported from `~/.claude/CLAUDE.md` |
249
250
  | `<CODEX_HOME>/ratchet-team.md` | The same rules for Codex |
250
251
  | `SPRAG_TEAM_TOKEN` | Invite token; enrolls the machine at the next session start |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.124.2",
3
+ "version": "3.125.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,6 @@ import {
23
23
  setDisplayName,
24
24
  } from '../team-sync.js';
25
25
  import { standingGuideLines } from '../team-standing.js';
26
- import { readDiag } from '../diag-log.js';
27
26
  import { envVar } from '../env.js';
28
27
 
29
28
  const T = {
@@ -41,7 +40,7 @@ const T = {
41
40
  ' propose <text> [--scope ratchet|model] propose a rule to the team',
42
41
  ' town [--no-open] open the read-only town in your browser (link valid 12 hours)',
43
42
  ].join('\n'),
44
- 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)\nError messages from sprag itself (to fix problems on your machine). Home paths, host names and secrets are masked.\nNo prompts, rule text, examples, file paths or transcripts are sent.',
43
+ 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, transcripts or error messages are sent.',
45
44
  rulesPayload: 'delegation rule summary (member_rules_report)',
46
45
  asName: (n) => `Display name: ${n}`,
47
46
  asDevice: (d) => `Machine ID: ${d} (lets the organization count this machine once if it joins again)`,
@@ -71,9 +70,6 @@ const T = {
71
70
  lastPrompts: (t, n) => `Last prompt upload: ${t} (${n} prompts)`,
72
71
  noPrompts: 'Last prompt upload: never',
73
72
  pendingPrompts: (n) => `Prompts waiting to upload: ${n}`,
74
- diagWaiting: (n, last) => `Diagnostics waiting to upload: ${n} (last upload: ${last})`,
75
- diagNever: 'never',
76
- diagPayload: 'diagnostics (diag_upload)',
77
73
  pendingExample: (e) => `Example (redacted): ${e.at} · ${e.project || '-'} · ${e.text}`,
78
74
  disabled: 'Team sync is disabled (SPRAG_NO_TEAM_SYNC=1).',
79
75
  skipped: (s) => `Skipped: ${s}`,
@@ -129,7 +125,7 @@ const T = {
129
125
  ' propose <내용> [--scope ratchet|model] 팀에 규칙 제안',
130
126
  ' town [--no-open] 읽기 전용 타운을 브라우저로 열기 (링크 12시간 유효)',
131
127
  ].join('\n'),
132
- willSend: '참여하면 집계만 올라갑니다. 로컬 날짜별로는 다음과 같습니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n위임 룰은 카테고리와 티어별 요약 한 벌이 올라갑니다.\n - 카테고리, 티어, 위임 횟수, 실패율, 절감액(USD)\nsprag 자체의 오류 메시지(이 기기의 문제를 고치는 데 씁니다). 홈 경로, 호스트 이름, 비밀 값은 가려서 보냅니다.\n프롬프트, 룰 본문, 예시, 파일 경로, 대화 기록은 보내지 않습니다.',
128
+ willSend: '참여하면 집계만 올라갑니다. 로컬 날짜별로는 다음과 같습니다.\n - 지출(USD)\n - 절감(USD)\n - 위임 실행 횟수\n - 모델 계열 비중\n위임 룰은 카테고리와 티어별 요약 한 벌이 올라갑니다.\n - 카테고리, 티어, 위임 횟수, 실패율, 절감액(USD)\n프롬프트, 룰 본문, 예시, 파일 경로, 대화 기록, 오류 메시지는 보내지 않습니다.',
133
129
  rulesPayload: '위임 룰 요약 (member_rules_report)',
134
130
  asName: (n) => `표시 이름: ${n}`,
135
131
  asDevice: (d) => `기기 ID: ${d} (다시 참여해도 조직이 이 PC를 한 좌석으로 셉니다)`,
@@ -159,9 +155,6 @@ const T = {
159
155
  lastPrompts: (t, n) => `마지막 프롬프트 업로드: ${t} (${n}건)`,
160
156
  noPrompts: '마지막 프롬프트 업로드: 아직 없음',
161
157
  pendingPrompts: (n) => `업로드 대기 중인 프롬프트: ${n}건`,
162
- diagWaiting: (n, last) => `업로드 대기 중인 진단 기록: ${n}건 (마지막 업로드: ${last})`,
163
- diagNever: '아직 없음',
164
- diagPayload: '진단 기록 (diag_upload)',
165
158
  pendingExample: (e) => `예시 (비밀값 가림): ${e.at} · ${e.project || '-'} · ${e.text}`,
166
159
  disabled: '팀 동기화가 꺼져 있습니다 (SPRAG_NO_TEAM_SYNC=1).',
167
160
  skipped: (s) => `건너뜀: ${s}`,
@@ -388,7 +381,6 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
388
381
  for (const l of standingGuideLines(st.standing, { lang: userLanguage(), org: st.orgName || st.teamName || null, team: st.teamName || null })) out(l);
389
382
  out(st.lastSyncAt ? m.lastSync(new Date(st.lastSyncAt).toLocaleString(), st.lastSyncRows || 0) : m.neverSynced);
390
383
  if (st.lastError) out(isOrgExpiredError(st.lastError) ? m.orgExpired : `${m.lastError}: ${st.lastError}`);
391
- out(m.diagWaiting(readDiag().length, st.lastDiagAt ? new Date(st.lastDiagAt).toLocaleString() : m.diagNever));
392
384
  if (orgMinVersion(st)) out(m.orgMin(orgMinVersion(st), version));
393
385
  {
394
386
  const up = readOrgUpgrade();
@@ -404,7 +396,6 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
404
396
  out(`device: ${JSON.stringify(st.deviceInfo || deviceInfo())}`);
405
397
  out(JSON.stringify(await aggregateDaily(), null, 2));
406
398
  out(`${m.rulesPayload}: ${JSON.stringify(ruleStatsSummary(), null, 2)}`);
407
- out(`${m.diagPayload}: ${JSON.stringify(readDiag(), null, 2)}`);
408
399
  if (st.promptCapture) {
409
400
  const pend = await pendingPrompts();
410
401
  out(m.pendingPrompts(pend.count));
package/src/diag-log.js CHANGED
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Why: a joined machine can show $0 spend, upload zero ledger rows or price
5
5
  * every Claude call as "unpriced", and the cause sits in a catch block that was
6
- * silent on purpose (see debug.js). The operator needs the error text from that
7
- * machine, so `debug()` also lands here and the team sync uploads the log to
8
- * `diag_upload`. Only error text goes up: never a prompt or a transcript.
6
+ * silent on purpose (see debug.js). The operator can read the error text on that
7
+ * machine, so `debug()` also lands here. The log is local only (mode 0600) and
8
+ * never leaves the machine: the team sync does not upload it.
9
9
  *
10
10
  * File: <userDataDir>/diag-log.json
11
11
  * { "version": 1, "entries": [ { scope, msg, count, first, last } ] }
@@ -32,7 +32,7 @@ import { dirname, join } from 'node:path';
32
32
  import { fileURLToPath, pathToFileURL } from 'node:url';
33
33
  import { envVar } from './env.js';
34
34
  import { userDataDir } from './paths.js';
35
- import { redactSecrets } from './redact.js';
35
+ import { redactSecrets, maskNetwork, FS_ROOT_RE } from './redact.js';
36
36
  import { writeStateFile } from './state-file.js';
37
37
 
38
38
  export const DIAG_VERSION = 1;
@@ -47,13 +47,13 @@ export const diagSrcDir = dirname(fileURLToPath(import.meta.url));
47
47
  const SRC_URL = pathToFileURL(diagSrcDir).href;
48
48
 
49
49
  const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/(?:[^\s/@?#]*@)?[^\s/?#]+/gi;
50
+
50
51
  const ARN_ACCOUNT_RE = /(arn:aws[\w-]*:[\w-]*:[\w-]*:)\d{12}(:)/g;
51
52
  const EMAIL_RE =/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
52
53
 
53
54
  // A file path after the start, a space, a quote, `(` or `=`. `<host>/path` is not
54
55
  // matched (the `>` before it), so a URL keeps its path.
55
56
  const PATH_RE = /(^|[\s'"(=])((?:~|[A-Za-z]:)?[\\/][^\s'"():,]+)/g;
56
- const FS_ROOT_RE = /^\/(?:Users|home|root|private|var|tmp|opt|usr|Volumes|mnt|media|srv|etc|Library|Applications|System|nix|snap|workspace|workspaces|data|app)(?:\/|$)/;
57
57
 
58
58
  /**
59
59
  * A path without the directories that could name a project: the last segment
@@ -86,6 +86,7 @@ export function sanitizeDiag(text, max = MAX_MSG) {
86
86
  if (home && home.length > 1) s = s.split(home).join('~');
87
87
  } catch { /* no home directory to mask */ }
88
88
  s = s.replace(URL_RE, '<host>');
89
+ s = maskNetwork(s);
89
90
  s = s.replace(PATH_RE, (_, lead, p) => lead + shortPath(p));
90
91
  s = s.replace(ARN_ACCOUNT_RE, '$1<acct>$2'); // a model id can be an ARN, and an ARN holds the AWS account id
91
92
  s = redactSecrets(s);
@@ -212,9 +213,9 @@ export function recordDiag(scope, err, { dir = userDataDir(), now = Date.now(),
212
213
  }
213
214
 
214
215
  /**
215
- * After a successful upload: take the sent counts off the log. The file is read
216
- * again first, so entries that arrived during the upload stay. An entry whose
217
- * count drops to zero or below is removed.
216
+ * Take the given counts off the local log. The file is read again first, so
217
+ * entries that arrived meanwhile stay. An entry whose count drops to zero or
218
+ * below is removed. Nothing in sprag sends the log anywhere.
218
219
  */
219
220
  export function ackDiag(sent, { dir = userDataDir() } = {}) {
220
221
  try {
@@ -231,5 +232,5 @@ export function ackDiag(sent, { dir = userDataDir() } = {}) {
231
232
  if (e.count - n > 0) kept.push({ ...e, count: e.count - n });
232
233
  }
233
234
  writeDiag(dir, kept);
234
- } catch { /* the next upload sends them again */ }
235
+ } catch { /* the entries stay in the local log */ }
235
236
  }
@@ -403,7 +403,7 @@ const TEAM_STANDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
403
403
  /**
404
404
  * Team chip: the member id, the organization and, once the server has told us,
405
405
  * the overall-score rank and the animal that member is in the team's virtual
406
- * office (`member-1e500474 amazon overall score #3 of 12 🦊 Fox`). Renders only
406
+ * office (`member-1a2b3c4d acmeco overall score #3 of 12 🦊 Fox`). Renders only
407
407
  * for a joined machine. A missing, unknown or day-old standing leaves just the
408
408
  * member label (and the organization, when known). The office page calls the
409
409
  * ranked figure the overall score (spend rank, delegation rank, prompt rank). Gray like the other identity chips; the emoji brings its own colour.
@@ -441,8 +441,8 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
441
441
  * percentages on the line are score percentiles (the gauge and the next
442
442
  * species' starting percentile); the two axes are ranks. Null for a machine
443
443
  * that has not joined; the chip above stands in on the single-line layouts.
444
- * icon: "👥 Pro · amazon · AWS-FSI · member-1e500474 | 🦊 여우 ▰▰▰▰▰▰▰▰▰▱▱▱ 75% → 🐆 치타 77% | 종합 3/12위 · 팀 1/4위 · 사용량 2/12위 · 위임률 5/12위"
445
- * text: "Pro · amazon · AWS-FSI · member-1e500474 | Fox 75% → Cheetah 77% | overall #3/12 · team #1/4 · spend #2/12 · delegation #5/12"
444
+ * icon: "👥 Pro · acmeco · DEV-OPS · member-1a2b3c4d | 🦊 여우 ▰▰▰▰▰▰▰▰▰▱▱▱ 75% → 🐆 치타 77% | 종합 3/12위 · 팀 1/4위 · 사용량 2/12위 · 위임률 5/12위"
445
+ * text: "Pro · acmeco · DEV-OPS · member-1a2b3c4d | Fox 75% → Cheetah 77% | overall #3/12 · team #1/4 · spend #2/12 · delegation #5/12"
446
446
  * Text mode draws no gauge, as the other gauges do not. An older server sends no
447
447
  * axis ranks, and the second group then holds the overall rank (and the team's).
448
448
  */
package/src/redact.js CHANGED
@@ -16,6 +16,8 @@
16
16
  * token is not. Prose such as "token budget is 8000" must stay untouched.
17
17
  */
18
18
 
19
+ import { homedir } from 'node:os';
20
+
19
21
  const REDACTED = '[redacted]';
20
22
 
21
23
  const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gd;
@@ -173,6 +175,95 @@ function luhnOk(digits) {
173
175
  return sum % 10 === 0;
174
176
  }
175
177
 
178
+ // ---------------------------------------------------------------------------
179
+ // Network addresses, URLs and file paths. Text that leaves the machine (diagnostics, Enterprise prompt capture)
180
+ // must not map a customer's internal network or directory layout.
181
+ // ---------------------------------------------------------------------------
182
+
183
+ // Network addresses without a scheme. A network error's cause names the proxy or
184
+ // host it could not reach ("connect ECONNREFUSED 10.20.30.40:3128", "getaddrinfo
185
+ // ENOTFOUND proxy.corp.local"), and that maps a customer's internal network. None
186
+ // of it leaves the machine: addresses, hosts after a network error code, hosts in
187
+ // a certificate mismatch and hosts under a private suffix all become `<host>`.
188
+ // sprag's own public endpoints stay, so a failing team sync is still readable.
189
+ const IPV4_RE = /(?<![\w.])(?:\d{1,3}\.){3}\d{1,3}(?::\d{1,5})?(?![\w.])/g;
190
+ const IPV6_BRACKET_RE = /\[[0-9a-f:.]*:[0-9a-f:.]*\](?::\d{1,5})?/gi;
191
+ const IPV6_FULL_RE = /(?<![\w:])(?:[0-9a-f]{1,4}:){3,7}[0-9a-f]{1,4}(?![\w:])/gi;
192
+ const IPV6_SHORT_RE = /(?<![\w:])(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4})*)?::(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4})*)?(?![\w:])/gi;
193
+ const NET_CODE_HOST_RE = /\b(getaddrinfo\s+[A-Z_]+|ENOTFOUND|EAI_AGAIN|EAI_NONAME|EAI_FAIL|ECONNREFUSED|ECONNRESET|ECONNABORTED|ETIMEDOUT|EHOSTUNREACH|EHOSTDOWN|ENETUNREACH|EPIPE)(\s+)([^\s,;)'"]+)/g;
194
+ const CERT_HOST_RE = /\b(Host|DNS|IP Address|servername)(:\s*)([^\s,;)'"]+)/g;
195
+ const ATTEMPTED_RE = /(attempted address(?:es)?:\s*)([^,;)]+)/gi;
196
+ // Only a host-shaped token: oauth-budget writes "fetch failed (TypeError)", an error name to keep.
197
+ const FETCH_HOST_RE = /(fetch failed \()((?:[a-z0-9-]+\.)+[a-z0-9-]+(?::\d{1,5})?|localhost(?::\d{1,5})?)(?=[,)])/gi;
198
+ const PRIVATE_HOST_RE = /(?<![\w.-])(?:[a-z0-9-]+\.)+(?:local|localdomain|internal|intranet|corp|lan|home\.arpa|private)(?::\d{1,5})?(?![\w-])/gi;
199
+ // sprag's own public endpoints: naming them reveals nothing about the customer.
200
+ // Only sprag's own endpoints and fixed public services. A wildcard such as *.supabase.co or github.com
201
+ // would let a customer's own project ref or `github.com/<org>/<repo>` through.
202
+ const PUBLIC_HOST_RE = /^(?:hiycfjwswtkixyoqkznm\.supabase\.co|(?:www\.)?sprag\.io|registry\.npmjs\.org|(?:www\.)?npmjs\.com|(?:api|docs|www)\.anthropic\.com|(?:docs\.)?claude\.com)(?::\d{1,5})?$/i;
203
+ const maskHost = (h) => (PUBLIC_HOST_RE.test(h) ? h : '<host>');
204
+
205
+ /** Every network address in `s` as `<host>`, sprag's public endpoints kept. */
206
+ export function maskNetwork(s) {
207
+ return String(s ?? '')
208
+ .replace(NET_CODE_HOST_RE, (_, code, sp, h) => code + sp + maskHost(h.replace(/[.:]+$/, '')))
209
+ .replace(CERT_HOST_RE, (_, k, sep, h) => k + sep + maskHost(h.replace(/\.$/, '')))
210
+ .replace(ATTEMPTED_RE, (_, lead) => `${lead}<host>`)
211
+ .replace(FETCH_HOST_RE, (_, lead, h) => lead + maskHost(h))
212
+ .replace(PRIVATE_HOST_RE, '<host>')
213
+ .replace(IPV6_BRACKET_RE, '<host>')
214
+ .replace(IPV4_RE, '<host>')
215
+ .replace(IPV6_FULL_RE, '<host>')
216
+ .replace(IPV6_SHORT_RE, (m) => (m === '::' ? m : '<host>'));
217
+ }
218
+
219
+ /** An absolute path starts under one of these: an API path such as `/rest/v1/rpc` names no directory and stays. */
220
+ export const FS_ROOT_RE = /^\/(?:Users|home|root|private|var|tmp|opt|usr|Volumes|mnt|media|srv|etc|Library|Applications|System|nix|snap|workspace|workspaces|data|app)(?:\/|$)/;
221
+
222
+ // A path after the start, whitespace, a quote, a bracket, `=` or `,`. `<url>/x` and `https://h/x` are not
223
+ // matched (the char before the slash is `>` or `:`), so a URL is left to maskUrls.
224
+ const ABS_PATH_RE = /(^|[\s'"`(\[{=,])((?:~|[A-Za-z]:)?[\\/][^\s'"`():,<>]+)/g;
225
+ const TRAILING_PUNCT_RE = /[.;!?]+$/;
226
+
227
+ /**
228
+ * Home directory -> `~`, then every absolute filesystem path (POSIX under a known root, `~/...`,
229
+ * Windows `C:\...`) -> `<path>`. URLs and API-looking paths stay.
230
+ */
231
+ export function redactPaths(text, { home } = {}) {
232
+ let s = String(text ?? '');
233
+ let h = home;
234
+ if (h === undefined) { try { h = homedir(); } catch { h = ''; } }
235
+ if (h && h.length > 1) {
236
+ const base = h.replace(/[\\/]+$/, '');
237
+ if (base.length > 1) s = s.replace(new RegExp(`${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-])`, 'g'), '~');
238
+ }
239
+ return s.replace(ABS_PATH_RE, (m, lead, p) => {
240
+ const root = p.startsWith('~') || /^[A-Za-z]:/.test(p);
241
+ if (!root && !FS_ROOT_RE.test(p)) return m;
242
+ const tail = TRAILING_PUNCT_RE.exec(p)?.[0] ?? '';
243
+ return `${lead}<path>${tail}`;
244
+ });
245
+ }
246
+
247
+ const ANY_URL_RE = /\b([a-z][a-z0-9+.-]*):\/\/([^\s/?#'"`<>]*)[^\s'"`<>]*/gi;
248
+
249
+ /** Every scheme://... URL whose host is not sprag's, Anthropic's, GitHub's, npm's or Supabase's -> `<url>`. */
250
+ export function maskUrls(text) {
251
+ return String(text ?? '').replace(ANY_URL_RE, (m, scheme, authority) => {
252
+ const tail = /[.,;:!?)\]}]+$/.exec(m)?.[0] ?? '';
253
+ const host = authority.slice(authority.lastIndexOf('@') + 1);
254
+ if (scheme.toLowerCase() !== 'file' && host && PUBLIC_HOST_RE.test(host.replace(/[.,;:!?)\]}]+$/, ''))) return m;
255
+ return `<url>${tail}`;
256
+ });
257
+ }
258
+
259
+ /**
260
+ * Text that may leave the machine in an Enterprise prompt upload: secrets, personal data, URLs, network
261
+ * addresses and file paths masked, in that order. Pattern matching only, not a guarantee.
262
+ */
263
+ export function redactUpload(text) {
264
+ return redactPaths(maskNetwork(maskUrls(redactPersonal(redactSecrets(text)))));
265
+ }
266
+
176
267
  /** Mask email addresses, Korean phone numbers, resident registration numbers and card numbers with typed markers. */
177
268
  export function redactPersonal(text) {
178
269
  let s = String(text ?? '');
@@ -6,10 +6,11 @@
6
6
  * What leaves the machine: the prompts the user typed in their own main
7
7
  * sessions (Claude Code transcripts and Codex sessions), including the ones
8
8
  * typed while the assistant was still working (queued), each as
9
- * { at, project (a directory basename), text }, with obvious secrets replaced
10
- * by "[redacted]" and personal data (email, Korean phone, resident registration
11
- * and card numbers) by "[redacted:email|phone|rrn|card]", all on this machine
12
- * before upload. Never sent: assistant replies, tool output, file contents,
9
+ * { at, project (a per-machine alias of the directory basename), text }, with
10
+ * obvious secrets replaced by "[redacted]", personal data (email, Korean phone,
11
+ * resident registration and card numbers) by "[redacted:email|phone|rrn|card]",
12
+ * network addresses by "<host>", URLs by "<url>" and absolute file paths by
13
+ * "<path>", all on this machine before upload (redactUpload). Never sent: assistant replies, tool output, file contents,
13
14
  * subagent transcripts, slash-command wrappers, system reminders, local paths,
14
15
  * background-task notifications, messages from other agents, and `!` shell
15
16
  * commands with their output.
@@ -26,15 +27,15 @@
26
27
  * 16 hex chars of sha256(path).
27
28
  */
28
29
 
29
- import { createHash } from 'node:crypto';
30
- import { openSync, readSync, closeSync, fstatSync, readdirSync, statSync, readFileSync, rmSync, existsSync } from 'node:fs';
30
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
31
+ import { openSync, readSync, closeSync, fstatSync, readdirSync, statSync, readFileSync, rmSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
31
32
  import { join } from 'node:path';
32
33
  import { claudeUserDir, userDataDir } from './paths.js';
33
34
  import { codexUserDir } from './agent.js';
34
35
  import { discoverCodexSessionFiles } from './codex/parser.js';
35
36
  import { writeStateFile } from './state-file.js';
36
37
  import { debug } from './debug.js';
37
- import { redactSecrets, redactPersonal } from './redact.js';
38
+ import { redactSecrets, redactPersonal, redactUpload } from './redact.js';
38
39
 
39
40
  export const MAX_RUN_PROMPTS = 2000;
40
41
  export const MAX_RUN_BYTES = 8 * 1024 * 1024;
@@ -54,6 +55,45 @@ export { redactSecrets, redactPersonal };
54
55
  // Prompt extraction
55
56
  // ---------------------------------------------------------------------------
56
57
 
58
+ /**
59
+ * The project as the server sees it: 'p-' + first 10 hex of HMAC-SHA256(key, name). The key is 32 random bytes
60
+ * created once at <userDataDir>/prompt-alias.key (mode 0600), never uploaded and never printed, so the same
61
+ * name maps to the same alias on this machine and a customer's project name cannot be read back or guessed
62
+ * from the alias. An empty name stays empty.
63
+ */
64
+ export const aliasKeyPath = (dir = userDataDir()) => join(dir, 'prompt-alias.key');
65
+ const aliasKeys = new Map(); // dir -> Buffer, read once per process
66
+
67
+ function aliasKey(dir) {
68
+ if (aliasKeys.has(dir)) return aliasKeys.get(dir);
69
+ const file = aliasKeyPath(dir);
70
+ const read = () => {
71
+ const hex = readFileSync(file, 'utf8').trim();
72
+ return /^[0-9a-f]{64}$/.test(hex) ? Buffer.from(hex, 'hex') : null;
73
+ };
74
+ let key = null; let existed = true;
75
+ try { key = read(); } catch { existed = false; /* not created yet */ }
76
+ if (!key) {
77
+ key = randomBytes(32);
78
+ try {
79
+ mkdirSync(dir, { recursive: true });
80
+ // 'wx' so two processes starting together cannot overwrite each other's key; a damaged file is replaced
81
+ writeFileSync(file, key.toString('hex') + '\n', { mode: 0o600, flag: existed ? 'w' : 'wx' });
82
+ } catch (e) {
83
+ if (e.code === 'EEXIST') { try { key = read() || key; } catch { /* keep the fresh key */ } }
84
+ else debug('team-prompts', e); // unwritable dir: the alias holds for this process only, the name is still never sent
85
+ }
86
+ }
87
+ aliasKeys.set(dir, key);
88
+ return key;
89
+ }
90
+
91
+ export function projectAlias(name, { dir = userDataDir() } = {}) {
92
+ const n = String(name ?? '');
93
+ if (!n) return '';
94
+ return 'p-' + createHmac('sha256', aliasKey(dir)).update(n).digest('hex').slice(0, 10);
95
+ }
96
+
57
97
  const basenameOf = (p) => {
58
98
  const s = String(p ?? '').replace(/[\\/]+$/, '');
59
99
  return s.slice(Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\')) + 1).slice(0, 80);
@@ -72,7 +112,7 @@ function cleanPrompt(raw) {
72
112
  if (MACHINE_RE.test(text)) return null;
73
113
  if (!text) return null;
74
114
  if (text.startsWith('[Request interrupted by user')) return null;
75
- return redactPersonal(redactSecrets(text)).slice(0, MAX_TEXT);
115
+ return redactUpload(text).slice(0, MAX_TEXT);
76
116
  }
77
117
 
78
118
  const textParts = (content) => (Array.isArray(content) ? content : [])
@@ -298,7 +338,7 @@ export async function uploadPrompts({
298
338
  try {
299
339
  r = await put({
300
340
  source: f.source, file_key: key, start_offset: c.start, end_offset: c.end,
301
- prompts: c.prompts.map((p) => ({ at: p.at, project: p.project, text: p.text })),
341
+ prompts: c.prompts.map((p) => ({ at: p.at, project: projectAlias(p.project, { dir }), text: p.text })),
302
342
  });
303
343
  } catch (e) {
304
344
  if (/prompt capture is off/.test(String(e.message))) { res.off = true; return res; }
@@ -339,7 +379,7 @@ export async function pendingPrompts({ dir = userDataDir(), claudeDir, codexDir
339
379
  count += c.prompts.length;
340
380
  if (!example && c.prompts.length) {
341
381
  const p = c.prompts[0];
342
- example = { at: p.at, project: p.project, text: p.text.slice(0, 80) };
382
+ example = { at: p.at, project: projectAlias(p.project, { dir }), text: p.text.slice(0, 80) };
343
383
  }
344
384
  }
345
385
  }
@@ -3,7 +3,7 @@
3
3
  * standing in the organization's virtual office, what moving up takes, and the
4
4
  * field guide of species to climb through.
5
5
  *
6
- * The statusline chip says `Pro member-1e500474 amazon 종합 점수 12명 중 3위
6
+ * The statusline chip says `Pro member-1a2b3c4d acmeco 종합 점수 12명 중 3위
7
7
  * 🦊 여우` and no more. This answers the questions that chip raises: how many
8
8
  * people stand ahead, whether the rank is earned by spending more tokens or by
9
9
  * using them better, which species is next and what the whole ladder looks
package/src/team-sync.js CHANGED
@@ -62,7 +62,7 @@ import { codexBudgetProvider } from './codex/budget.js';
62
62
  import { fetchGatewayDailySpend, gatewayDayValue, gatewayEnv } from './gateway-spend.js';
63
63
  import { withClaudeSettingsEnv, gatewayBase } from './gateway-auth.js';
64
64
  import { maybeRefreshGatewayModelMap, readGatewayModelMap } from './litellm-models.js';
65
- import { recordDiag, readDiag, ackDiag } from './diag-log.js';
65
+ import { recordDiag } from './diag-log.js';
66
66
 
67
67
  export const PROMPT_SYNC_INTERVAL_MS = 30 * 60 * 1000;
68
68
 
@@ -274,6 +274,25 @@ async function ledgerUpsert({ memberKey, rows, version, dir, fetch }) {
274
274
  }
275
275
  }
276
276
 
277
+ /**
278
+ * Node's fetch reports every network failure as a bare "fetch failed" and keeps
279
+ * the reason in `cause` (ENOTFOUND, ECONNREFUSED, UNABLE_TO_GET_ISSUER_CERT_LOCALLY...).
280
+ * Printing only e.message hid it, so a member behind a corporate proxy or a
281
+ * firewall saw "fetch failed" with nothing to act on. This names the step,
282
+ * the host and the cause code.
283
+ */
284
+ export function networkError(label, e, url) {
285
+ const c = e && e.cause;
286
+ const code = (c && (c.code || c.name)) || '';
287
+ const detail = c && c.message && c.message !== code ? c.message : '';
288
+ let host = '';
289
+ try { host = new URL(url).host; } catch { /* no usable url */ }
290
+ const parts = [host, [code, detail].filter(Boolean).join(': ')].filter(Boolean).join(', ');
291
+ const err = new Error(`${label}: fetch failed${parts ? ` (${parts})` : ''}`);
292
+ err.cause = c || e;
293
+ return err;
294
+ }
295
+
277
296
  export async function rpc(fn, params, {
278
297
  fetch = globalThis.fetch, timeoutMs = 8000, url = teamApiUrl(), key = teamAnonKey(),
279
298
  } = {}) {
@@ -296,6 +315,7 @@ export async function rpc(fn, params, {
296
315
  return body;
297
316
  } catch (e) {
298
317
  if (e && e.name === 'AbortError') throw new Error(`${fn}: timeout`);
318
+ if (e instanceof TypeError && /fetch failed/i.test(e.message)) throw networkError(fn, e, url);
299
319
  throw e;
300
320
  } finally {
301
321
  clearTimeout(timer);
@@ -326,6 +346,7 @@ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetc
326
346
  return data;
327
347
  } catch (e) {
328
348
  if (e && e.name === 'AbortError') throw new Error(`${label}: timeout`);
349
+ if (e instanceof TypeError && /fetch failed/i.test(e.message)) throw networkError(label, e, url);
329
350
  throw e;
330
351
  } finally {
331
352
  clearTimeout(timer);
@@ -931,47 +952,6 @@ async function reportRuleStats({ state, dir, fetch, now }) {
931
952
  }
932
953
  }
933
954
 
934
- export const DIAG_UPLOAD_INTERVAL_MS = 30 * 60 * 1000;
935
- const DIAG_UPLOAD_MAX = 100;
936
-
937
- /**
938
- * Upload the local diagnostics log (diag-log.js) to diag_upload: error text
939
- * only, newest 100 entries, at most once per DIAG_UPLOAD_INTERVAL_MS unless
940
- * `force`. Returns `{ diag, lastDiagAt }` after an upload, `{ lastDiagError }`
941
- * after a failed one, and null when nothing was due. A server without the
942
- * function (not migrated yet) is silent. It never throws, never fails the sync,
943
- * and does not call debug() on its own failure: that would put the upload error
944
- * into the log it is trying to send.
945
- */
946
- async function uploadDiag({ state, dir, fetch, version, now, force = false, env = process.env }) {
947
- try {
948
- if (envVar('NO_DIAG', env) === '1') return null;
949
- if (!force && Number.isFinite(state.lastDiagAt) && now - state.lastDiagAt >= 0 && now - state.lastDiagAt < DIAG_UPLOAD_INTERVAL_MS) return null;
950
- const entries = readDiag({ dir });
951
- if (!entries.length) return null;
952
- const sent = [...entries].sort((a, b) => (a.last < b.last ? 1 : a.last > b.last ? -1 : 0)).slice(0, DIAG_UPLOAD_MAX);
953
- try {
954
- const n = await rpc('diag_upload', { member_key: state.memberKey, entries: sent, sprag_version: version || '' }, { fetch });
955
- ackDiag(sent, { dir });
956
- return { diag: Number.isFinite(n) ? n : sent.length, lastDiagAt: now };
957
- } catch (e) {
958
- if (/Could not find the function|PGRST202/.test(String(e && e.message))) return null;
959
- return { lastDiagError: String((e && e.message) || e).slice(0, 200) };
960
- }
961
- } catch {
962
- return null;
963
- }
964
- }
965
-
966
- /** The team.json fields an uploadDiag result changes. */
967
- function withDiagMeta(state, d) {
968
- if (!d) return state;
969
- const next = { ...state };
970
- if (d.lastDiagAt) { next.lastDiagAt = d.lastDiagAt; delete next.lastDiagError; }
971
- if (d.lastDiagError) next.lastDiagError = d.lastDiagError;
972
- return next;
973
- }
974
-
975
955
  /**
976
956
  * `gatewayFetch` is the fetch the gateway calls use (the team server's `fetch`
977
957
  * is injected separately so tests can fake each side). `coworkSessions`, `codexSessions`,
@@ -1091,8 +1071,7 @@ export async function syncTeam({
1091
1071
  await ledgerUpsert({ memberKey: state.memberKey, rows, version, dir, fetch });
1092
1072
  const { r, rules } = await pullRules({ memberKey: state.memberKey, dir, fetch, now });
1093
1073
  const ruleStats = await reportRuleStats({ state, dir, fetch, now });
1094
- const diag = await uploadDiag({ state, dir, fetch, version, now, force, env });
1095
- const next = withRulesMeta(withDiagMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, diag), r, now);
1074
+ const next = withRulesMeta({ ...state, ...ruleStats, lastSyncAt: now, lastSyncAttemptAt: now, lastSyncRows: rows.length, ledgerSyncedThrough: dayKey(now) }, r, now);
1096
1075
  if (gatewayOk) next.gatewaySyncedThrough = dayKey(now);
1097
1076
  else if (gatewayDaily && gatewayDaily.error) next.lastGatewayError = gatewayDaily.error;
1098
1077
  if (gatewayOk || !hasGateway) delete next.lastGatewayError;
@@ -1113,11 +1092,6 @@ export async function syncTeam({
1113
1092
  try {
1114
1093
  saveTeamState({ ...state, lastSyncAttemptAt: now, syncFailures: (Number(state.syncFailures) || 0) + 1, lastError: e.message }, dir);
1115
1094
  } catch (e2) { debug('team-sync', e2); }
1116
- // The failure that just happened is exactly what the operator needs to see.
1117
- try {
1118
- const diag = await uploadDiag({ state, dir, fetch, version, now, force: true, env });
1119
- if (diag) saveTeamState(withDiagMeta(loadTeamState(dir), diag), dir);
1120
- } catch { /* best effort */ }
1121
1095
  return { error: e.message };
1122
1096
  }
1123
1097
  }