sprag-cli 3.129.0 → 3.130.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/docs/TEAM.ko.md CHANGED
@@ -169,7 +169,7 @@ https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드
169
169
 
170
170
  여러 팀을 한 번에 만들려면 "+ 새 팀"을 누르고 "여러 팀 한 번에 만들기"를 펼친 뒤 한 줄에 팀 이름을 하나씩 붙여 넣습니다. 한 번에 50개까지 만들 수 있습니다. 빈 줄과 조직에 이미 있는 이름, 목록에 두 번 나온 이름, 80자를 넘는 이름은 건너뛰고 따로 알려 줍니다. 만들다가 하나가 실패하면 그 이름에서 멈추고 아직 만들지 못한 이름은 다시 실행할 수 있도록 입력란에 남겨 둡니다. 팀 목록과 타운 탭의 "가입 명령어 내보내기"를 누르면 팀마다 한 줄씩 담긴 CSV를 받습니다. 열은 `team`, `team_id`, `invite_token`, `join_command`(`npm i -g sprag-cli@latest && sprag team join <토큰>`), `shell_profile`(`export SPRAG_TEAM_TOKEN=<토큰>`), `managed_settings`(관리형 설정 JSON)입니다. 일괄 생성이 끝나면 방금 만든 팀만 내보내는 버튼도 나옵니다. 이 파일에는 목록에 있는 모든 팀의 초대 토큰이 들어 있으므로 각 줄은 해당 팀에만 전달하고, 파일이 새어 나가면 그 팀의 토큰을 교체하십시오.
171
171
 
172
- 대시보드 맨 위의 기간 선택(7일, 30일, 90일, 이번 달, 지난 달, 직접 선택)이 멤버 표, 사용량 차트, 프롬프트 사용량 탭의 기간을 정합니다. 기본값은 최근 30일이고, 내 컴퓨터의 달력 날짜를 쓰며 종료일도 포함합니다. 최대 365일까지 고를 수 있습니다. 고른 기간은 주소(`?from=2026-10-01&to=2026-10-18`)에 남으므로 새로고침하거나 링크를 공유해도 같은 기간이 보입니다. sprag.io/ops/ 슈퍼유저 콘솔에도 같은 선택이 있어 조직 표, 조직 머리말, 조직의 프롬프트 사용량에 적용됩니다.
172
+ 대시보드 맨 위의 기간 선택(7일, 30일, 90일, 이번 달, 지난 달, 직접 선택)이 멤버 표, 사용량 차트, 프롬프트 사용량 탭의 기간을 정합니다. 기본값은 이번 달(1일부터 오늘까지)로 멤버 타운, statusline 순위와 같습니다. 내 컴퓨터의 달력 날짜를 쓰며 종료일도 포함합니다. 최대 365일까지 고를 수 있습니다. 고른 기간은 주소(`?from=2026-10-01&to=2026-10-18`)에 남으므로 새로고침하거나 링크를 공유해도 같은 기간이 보입니다. sprag.io/ops/ 슈퍼유저 콘솔에도 같은 선택이 있어 조직 표, 조직 머리말, 조직의 프롬프트 사용량에 적용됩니다.
173
173
 
174
174
  ### 좌석 현황
175
175
 
package/docs/TEAM.md CHANGED
@@ -150,7 +150,7 @@ sprag team town --no-open # prints the link only
150
150
 
151
151
  The command asks the team server for a link with `town_view_link` (it sends your member key and nothing else) and opens `https://sprag.io/town/#t=<token>`. The token is valid for 12 hours and the command prints the expiry in your local time. Asking for links too often is refused for a while ("too many town links"). The token sits in the part of the address after `#`, so the web server never receives it, and the page removes it from the address bar after reading it. When it expires, or after you leave the team, the page asks you to run the command again. `SPRAG_TOWN_URL` points the link at another page (for local tests).
152
152
 
153
- The page opens on this month (Asia/Seoul calendar month start to today). A period picker in the page head switches between this month, last month and the last 7, 30 or 90 days. The page sends the range to `town_view(p_token, p_from, p_to)`, which applies the same validation as the dashboard (both dates or neither, from not after to, at most 366 days), and the choice is kept for that tab only.
153
+ The page opens on this month (Asia/Seoul calendar month start to today). A period picker in the page head switches between this month, last month, the last 7, 30 or 90 days, and custom dates (a start and an end date, at most 365 days). The page sends the range to `town_view(p_token, p_from, p_to)`, which applies the same validation as the dashboard (both dates or neither, from not after to, at most 366 days), and the choice is kept for that tab only.
154
154
 
155
155
  What the town shows:
156
156
 
@@ -191,7 +191,7 @@ https://sprag.io/team/ is where a registered owner or admin signs in with an ema
191
191
 
192
192
  To create several teams at once, open "+ New team", then "Create several teams at once", and paste one team name per line (up to 50 per run). Blank lines, names already in the organization, names listed twice and names over 80 characters are skipped and listed. If one creation fails, the run stops there and the names not yet created stay in the box for another run. "Export join commands" (under the Teams list and on the Town tab) downloads a CSV with one row per team: `team`, `team_id`, `invite_token`, `join_command` (`npm i -g sprag-cli@latest && sprag team join <token>`), `shell_profile` (`export SPRAG_TEAM_TOKEN=<token>`) and `managed_settings` (the managed settings JSON). After a bulk run, a button exports only the teams it created. The file holds every listed team's invite token, so share each row only with that team, and rotate a team's token if the file leaks.
193
193
 
194
- A date range control at the top of the dashboard (7d, 30d, 90d, This month, Last month or Custom) sets the period for the members table, the Usage chart and the prompt usage tab. It defaults to the last 30 days, uses your local calendar days with the end date included, and allows 365 days at most. The choice is kept in the page address (`?from=2026-10-01&to=2026-10-18`), so a reload or a shared link shows the same period. The superuser console at /ops/ has the same control for the organization table, the organization header and its prompt usage.
194
+ A date range control at the top of the dashboard (7d, 30d, 90d, This month, Last month or Custom) sets the period for the members table, the Usage chart and the prompt usage tab. It defaults to this month (the 1st through today), the same period as the member town and the statusline standing, uses your local calendar days with the end date included, and allows 365 days at most. The choice is kept in the page address (`?from=2026-10-01&to=2026-10-18`), so a reload or a shared link shows the same period. The superuser console at /ops/ has the same control for the organization table, the organization header and its prompt usage.
195
195
 
196
196
  ### The seat roster
197
197
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.129.0",
3
+ "version": "3.130.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": {
@@ -109,12 +109,13 @@ export async function run({ hasFlag }) {
109
109
  const { getSessionModel } = await import('../parser.js');
110
110
  pressure = capPressure({ sessionModel: getSessionModel(ctx.transcript_path) });
111
111
  // High usage while delegation is not widened: the hint offers
112
- // `sprag routing relax` once per limit window instead of the plain
113
- // pressure line. Relaxed, or already offered for this window, the
114
- // plain line stays.
112
+ // `sprag routing relax` once per limit window and session instead of
113
+ // the plain pressure line. The offer rides on the model relaying it,
114
+ // so every session gets its own chance. Relaxed, or already offered
115
+ // to this session in this window, the plain line stays.
115
116
  if (pressure && (pressure.level === 'high' || pressure.level === 'critical') && (match.t2 || match.t1 || match.t1h) && !isRelaxed()) {
116
117
  const { claimRelaxOffer } = await import('../relax-offer.js');
117
- if (claimRelaxOffer(pressure.resetsAt)) pressure = { ...pressure, offer: true };
118
+ if (claimRelaxOffer(pressure.resetsAt, { session: ctx.session_id })) pressure = { ...pressure, offer: true };
118
119
  }
119
120
  } catch (e) { debug('brief:cap-pressure', e); }
120
121
  }
@@ -31,7 +31,7 @@ import { modelFamily } from '../savings-ledger.js';
31
31
  import { shareLegend } from '../model-share.js';
32
32
  import { STAR_URL } from '../star-note.js';
33
33
  import { GRADES, speciesLabel } from '../office-species.js';
34
- import { scorePctOf, nextOf, nextGradeUp, floorPct } from '../team-standing.js';
34
+ import { scorePctOf, nextOf, nextGradeUp, floorPct, rankMonthLabel } from '../team-standing.js';
35
35
  import { cellWidth } from '../cell-width.js';
36
36
 
37
37
  // The 8-color ANSI defaults (RED=31, GREEN=32, YELLOW=33…) read as garish
@@ -403,7 +403,9 @@ 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-1a2b3c4d acmeco overall score #3 of 12 🦊 Fox`). Renders only
406
+ * office (`member-1a2b3c4d acmeco overall score #3 of 12 🦊 Fox`; when the
407
+ * standing covers one calendar month the month leads the rank: `acmeco Nov
408
+ * overall score #3 of 12 🦊 Fox`, `acmeco 11월 종합 점수 12명 중 3위 🦊 여우`). Renders only
407
409
  * for a joined machine. A missing, unknown or day-old standing leaves just the
408
410
  * member label (and the organization, when known). The office page calls the
409
411
  * ranked figure the overall score (spend rank, delegation rank, prompt rank). Gray like the other identity chips; the emoji brings its own colour.
@@ -423,7 +425,9 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
423
425
  const inTeam = ranked && Number.isInteger(st.teamRank) && Number.isInteger(st.teamRanked)
424
426
  && st.teamRank >= 1 && st.teamRanked >= st.teamRank && st.teamRanked < st.ranked && typeof team.team === 'string' && team.team;
425
427
  const teamPlace = inTeam ? (team.lang === 'ko' ? `, ${team.team} 팀 ${st.teamRanked}명 중 ${st.teamRank}위` : `, team ${team.team} #${st.teamRank} of ${st.teamRanked}`) : '';
426
- const place = ranked ? (team.lang === 'ko' ? ` 종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace}` : ` overall score #${st.rank} of ${st.ranked}${teamPlace}`) : '';
428
+ const month = ranked ? rankMonthLabel(st, team.lang) : null;
429
+ const monthPre = month ? ` ${month}` : '';
430
+ const place = ranked ? (team.lang === 'ko' ? `${monthPre} 종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace}` : `${monthPre} overall score #${st.rank} of ${st.ranked}${teamPlace}`) : '';
427
431
  const org = typeof team.org === 'string' && team.org ? ` ${team.org}` : '';
428
432
  // The plan leads (`Pro`, `Enterprise`): the chip describes a licensed team, so
429
433
  // the license is the first thing it says, and the standing follows.
@@ -443,6 +447,8 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
443
447
  * that has not joined; the chip above stands in on the single-line layouts.
444
448
  * icon: "👥 Pro · acmeco · DEV-OPS · member-1a2b3c4d | 🦊 여우 ▰▰▰▰▰▰▰▰▰▱▱▱ 75% → 🐆 치타 77% | 종합 3/12위 · 팀 1/4위 · 사용량 2/12위 · 위임률 5/12위"
445
449
  * text: "Pro · acmeco · DEV-OPS · member-1a2b3c4d | Fox 75% → Cheetah 77% | overall #3/12 · team #1/4 · spend #2/12 · delegation #5/12"
450
+ * When the standing covers one calendar month, only the overall entry carries
451
+ * the month: "11월 종합 3/12위" / "Nov overall #3/12" (crown 👑 stays in front).
446
452
  * Text mode draws no gauge, as the other gauges do not. An older server sends no
447
453
  * axis ranks, and the second group then holds the overall rank (and the team's).
448
454
  */
@@ -497,7 +503,8 @@ function buildTeamLine(team, c, isIcon, g, mode = 'icon', now = Date.now(), colo
497
503
  && st.teamRank >= 1 && st.teamRanked >= st.teamRank && st.teamRanked < st.ranked;
498
504
  const has = (v) => Number.isFinite(v);
499
505
  const rk = (koName, enName, r, n) => (ko ? `${koName} ${r}/${n}위` : `${enName} #${r}/${n}`);
500
- const ranks = [`${st.crown && emoji ? '👑 ' : ''}${rk('종합', 'overall', st.rank, st.ranked)}`];
506
+ const month = rankMonthLabel(st, team.lang);
507
+ const ranks = [`${st.crown && emoji ? '👑 ' : ''}${rk(month ? `${month} 종합` : '종합', month ? `${month} overall` : 'overall', st.rank, st.ranked)}`];
501
508
  if (inTeam) ranks.push(rk('팀', 'team', st.teamRank, st.teamRanked));
502
509
  if (has(st.spendRank)) ranks.push(rk('사용량', 'spend', st.spendRank, st.ranked));
503
510
  if (has(st.dlgRank)) ranks.push(rk('위임률', 'delegation', st.dlgRank, st.ranked));
@@ -2,11 +2,13 @@
2
2
  * The offer to widen delegation until the usage window resets.
3
3
  *
4
4
  * When a window runs high the prompt hook tells the model to ask the user once
5
- * whether to run `sprag routing relax`. "Once" is counted per limit window, not
6
- * per session: a new session in the same window has already been offered, and
7
- * the window resetting is what makes a new offer possible. The last window
8
- * offered, identified by its resetsAt (epoch seconds), is kept in a small file
9
- * under the user data directory.
5
+ * whether to run `sprag routing relax`. "Once" is counted per limit window and
6
+ * per session: the offer goes through the model as a context line, and a
7
+ * session that never relays it must not silence every other session for the
8
+ * rest of the window. The window resetting is what makes a new offer possible
9
+ * for a session that was already offered. The last window offered, identified
10
+ * by its resetsAt (epoch seconds), and the sessions offered in it are kept in a
11
+ * small file under the user data directory.
10
12
  */
11
13
 
12
14
  import { readFileSync, existsSync } from 'node:fs';
@@ -19,6 +21,8 @@ const FILE = 'relax-offer.json';
19
21
  const SAME_WINDOW_S = 600;
20
22
  /** A window with no reset time is bucketed by this span instead. */
21
23
  const FALLBACK_BUCKET_S = 5 * 60 * 60;
24
+ /** Sessions remembered per window; the oldest ids drop first. */
25
+ const MAX_SESSIONS = 50;
22
26
 
23
27
  /** The window id used for the claim: its resetsAt, or a 5 hour bucket when the window has none. */
24
28
  export function offerWindowId(resetsAt, nowMs = Date.now()) {
@@ -27,23 +31,38 @@ export function offerWindowId(resetsAt, nowMs = Date.now()) {
27
31
  }
28
32
 
29
33
  /**
30
- * True the first time a window is offered, false after. Never throws: when the
31
- * state file cannot be written the offer is skipped, so a failing disk cannot
32
- * turn it into a line on every prompt.
34
+ * True the first time a (window, session) pair is offered, false after. A call
35
+ * without a session id counts under one shared key, which keeps the old
36
+ * once-per-window behaviour for it. Never throws: when the state file cannot be
37
+ * written the offer is skipped, so a failing disk cannot turn it into a line on
38
+ * every prompt.
39
+ *
40
+ * The file holds { resetsAt, sessions: [ids], offeredAt }. A file in the older
41
+ * shape { resetsAt, offeredAt } reads as the same window with no sessions.
33
42
  *
34
43
  * @param {number|null} resetsAt epoch seconds of the busiest window's reset
35
- * @param {{dir?: string, nowMs?: number}} [opts]
44
+ * @param {{dir?: string, nowMs?: number, session?: string}} [opts]
36
45
  */
37
- export function claimRelaxOffer(resetsAt, { dir, nowMs = Date.now() } = {}) {
46
+ export function claimRelaxOffer(resetsAt, { dir, nowMs = Date.now(), session } = {}) {
38
47
  try {
39
48
  const file = join(dir || userDataDir(), FILE);
40
49
  const id = offerWindowId(resetsAt, nowMs);
41
- let last = null;
50
+ const key = typeof session === 'string' ? session : '';
51
+ let last = NaN;
52
+ let sessions = [];
42
53
  try {
43
- if (existsSync(file)) last = Number(JSON.parse(readFileSync(file, 'utf8'))?.resetsAt);
54
+ if (existsSync(file)) {
55
+ const saved = JSON.parse(readFileSync(file, 'utf8'));
56
+ last = Number(saved?.resetsAt);
57
+ if (Array.isArray(saved?.sessions)) sessions = saved.sessions.filter((s) => typeof s === 'string');
58
+ }
44
59
  } catch { /* unreadable reads as never offered */ }
45
- if (Number.isFinite(last) && Math.abs(last - id) <= SAME_WINDOW_S) return false;
46
- writeStateFile(file, JSON.stringify({ resetsAt: id, offeredAt: nowMs }) + '\n');
60
+ const sameWindow = Number.isFinite(last) && Math.abs(last - id) <= SAME_WINDOW_S;
61
+ if (sameWindow && sessions.includes(key)) return false;
62
+ // A new window starts a fresh list; the same window keeps its resetsAt so
63
+ // the jitter allowance does not creep forward with every session.
64
+ const kept = sameWindow ? [...sessions, key].slice(-MAX_SESSIONS) : [key];
65
+ writeStateFile(file, JSON.stringify({ resetsAt: sameWindow ? last : id, sessions: kept, offeredAt: nowMs }) + '\n');
47
66
  return true;
48
67
  } catch {
49
68
  return false;
@@ -13,12 +13,21 @@
13
13
  * type, so the two sides meet on that pair. The oldest entry for the pair wins:
14
14
  * two delegations of one type in a row start in the order they were sent.
15
15
  *
16
- * The file is shared state between short-lived hook processes. Nothing here
17
- * takes a lock; a lost update costs one subagent its appendix, and the hook
18
- * paths must never fail a delegation, so every function swallows its errors.
16
+ * Several Agent calls in one response start several hook processes at once, so
17
+ * the queue needs no lock: each entry is its own file in
18
+ * `<dir>/subagent-context/`, written as a temp file and renamed into place, and
19
+ * a take claims an entry by creating `<entry>.claim` with the exclusive flag
20
+ * ('wx'), which only one process can win. Claiming by renaming the entry away
21
+ * delivered one entry twice on Windows CI (2026-11-15), while an exclusive
22
+ * create is atomic on every platform. The claim file stays until the TTL prune,
23
+ * so a process that read the entry before it was deleted still loses. An entry
24
+ * is therefore delivered at most once, and one process's write cannot drop
25
+ * another's entry. The hook paths must never fail a delegation, so every
26
+ * function swallows its errors.
19
27
  */
20
28
 
21
- import { readFileSync, mkdirSync } from 'node:fs';
29
+ import { readFileSync, readdirSync, mkdirSync, openSync, closeSync, unlinkSync } from 'node:fs';
30
+ import { randomBytes } from 'node:crypto';
22
31
  import { join } from 'node:path';
23
32
  import { userDataDir } from './paths.js';
24
33
  import { writeViaTmp } from './state-file.js';
@@ -28,38 +37,53 @@ export const SUBAGENT_CONTEXT_TTL_MS = 120_000;
28
37
  /** Newest entries kept. A burst of parallel delegations stays well under this. */
29
38
  export const SUBAGENT_CONTEXT_MAX = 20;
30
39
 
31
- const FILE_NAME = 'subagent-context.json';
40
+ const DIR_NAME = 'subagent-context';
41
+ /** The single-file queue an older version kept; nothing reads it any more. */
42
+ const OLD_FILE_NAME = 'subagent-context.json';
43
+ const ENTRY_NAME = /^(\d{15})-\d+-[0-9a-f]{8}\.json$/;
44
+ const CLAIM_MARK = '.claim';
32
45
 
33
- const queueFile = (dir) => join(dir, FILE_NAME);
46
+ const queueDir = (dir) => join(dir, DIR_NAME);
47
+ const rand = () => randomBytes(4).toString('hex');
48
+ const rmQuiet = (file) => { try { unlinkSync(file); } catch { /* already gone */ } };
34
49
 
35
- /** The entries still worth delivering, oldest first. Unreadable or malformed means empty. */
36
- function readEntries(dir, now) {
37
- let raw;
38
- try {
39
- raw = readFileSync(queueFile(dir), 'utf8');
40
- } catch {
41
- return [];
42
- }
43
- let parsed;
44
- try {
45
- parsed = JSON.parse(raw);
46
- } catch {
47
- return [];
50
+ /** The `at` encoded in a queue file name (entry, temp or claim file), or null when the name does not parse. */
51
+ function nameAt(name) {
52
+ const m = /^(\d{15})-/.exec(name);
53
+ return m ? Number(m[1]) : null;
54
+ }
55
+
56
+ const expired = (name, now) => {
57
+ const at = nameAt(name);
58
+ return at === null || now - at > SUBAGENT_CONTEXT_TTL_MS;
59
+ };
60
+
61
+ const list = (dir) => {
62
+ try { return readdirSync(queueDir(dir)); } catch { return []; }
63
+ };
64
+
65
+ /**
66
+ * Delete expired files (a name that does not parse counts as expired, claim
67
+ * files included), then the oldest entries beyond the cap.
68
+ */
69
+ function prune(dir, now) {
70
+ const base = queueDir(dir);
71
+ const live = [];
72
+ for (const name of list(dir).sort()) {
73
+ if (expired(name, now)) rmQuiet(join(base, name));
74
+ else if (ENTRY_NAME.test(name)) live.push(name);
48
75
  }
49
- const list = Array.isArray(parsed?.entries) ? parsed.entries : [];
50
- return list
51
- .filter((e) => e && typeof e === 'object'
52
- && typeof e.session === 'string' && typeof e.type === 'string'
53
- && typeof e.text === 'string' && Number.isFinite(e.at)
54
- && now - e.at <= SUBAGENT_CONTEXT_TTL_MS)
55
- .sort((a, b) => a.at - b.at)
56
- .slice(-SUBAGENT_CONTEXT_MAX);
76
+ for (const name of live.slice(0, Math.max(0, live.length - SUBAGENT_CONTEXT_MAX))) rmQuiet(join(base, name));
57
77
  }
58
78
 
59
- function writeEntries(dir, entries) {
60
- mkdirSync(dir, { recursive: true });
61
- const file = queueFile(dir);
62
- writeViaTmp(`${file}.${process.pid}.tmp`, file, JSON.stringify({ entries }) + '\n');
79
+ /** An entry file's parsed body, or null when it is unreadable or malformed. */
80
+ function readEntry(file) {
81
+ try {
82
+ const e = JSON.parse(readFileSync(file, 'utf8'));
83
+ if (e && typeof e === 'object' && typeof e.session === 'string' && typeof e.type === 'string'
84
+ && typeof e.text === 'string' && Number.isFinite(e.at)) return e;
85
+ } catch { /* unreadable reads as no entry */ }
86
+ return null;
63
87
  }
64
88
 
65
89
  /**
@@ -70,10 +94,16 @@ export function enqueueSubagentContext(entry, { dir = userDataDir(), now = Date.
70
94
  try {
71
95
  if (!entry || typeof entry.session !== 'string' || !entry.session
72
96
  || typeof entry.type !== 'string' || typeof entry.text !== 'string' || !entry.text) return false;
73
- const at = Number.isFinite(entry.at) ? entry.at : now;
74
- const entries = readEntries(dir, now);
75
- entries.push({ session: entry.session, type: entry.type, at, text: entry.text });
76
- writeEntries(dir, entries.sort((a, b) => a.at - b.at).slice(-SUBAGENT_CONTEXT_MAX));
97
+ const at = Number.isFinite(entry.at) && entry.at >= 0 ? Math.floor(entry.at) : now;
98
+ const base = queueDir(dir);
99
+ mkdirSync(base, { recursive: true });
100
+ const name = `${String(at).padStart(15, '0')}-${process.pid}-${rand()}.json`;
101
+ const body = JSON.stringify({ session: entry.session, type: entry.type, at, text: entry.text }) + '\n';
102
+ // The temp name keeps the `at` prefix, so prune treats it like any file of
103
+ // this time and never deletes a write that is still in flight.
104
+ writeViaTmp(join(base, `${name}.tmp`), join(base, name), body);
105
+ prune(dir, now);
106
+ rmQuiet(join(dir, OLD_FILE_NAME));
77
107
  return true;
78
108
  } catch {
79
109
  return false;
@@ -83,20 +113,29 @@ export function enqueueSubagentContext(entry, { dir = userDataDir(), now = Date.
83
113
  /**
84
114
  * Remove and return the oldest live entry for this session and agent type, or
85
115
  * null. Nothing is written when there is no match, so a resumed subagent (which
86
- * never had an entry) costs one read.
116
+ * never had an entry) costs one directory read.
87
117
  */
88
118
  export function takeSubagentContext({ session, type }, { dir = userDataDir(), now = Date.now() } = {}) {
89
119
  try {
90
120
  if (typeof session !== 'string' || !session || typeof type !== 'string' || !type) return null;
91
- const entries = readEntries(dir, now);
92
- const i = entries.findIndex((e) => e.session === session && e.type === type);
93
- if (i < 0) return null;
94
- const [entry] = entries.splice(i, 1);
95
- // A failed write still delivers: the subagent getting its appendix matters
96
- // more than the rare double delivery a stale entry could cause later (the
97
- // TTL ends that within two minutes).
98
- try { writeEntries(dir, entries); } catch { /* deliver anyway */ }
99
- return entry;
121
+ const base = queueDir(dir);
122
+ for (const name of list(dir).sort()) {
123
+ if (!ENTRY_NAME.test(name)) continue;
124
+ const file = join(base, name);
125
+ if (expired(name, now)) { rmQuiet(file); continue; }
126
+ const entry = readEntry(file);
127
+ if (!entry || entry.session !== session || entry.type !== type) continue;
128
+ // The exclusive create is the claim: of two processes after the same
129
+ // entry, one gets EEXIST and moves on to the next candidate. The claim
130
+ // file is left for the prune, so a late reader of this entry loses too.
131
+ try { closeSync(openSync(`${file}${CLAIM_MARK}`, 'wx')); } catch { continue; }
132
+ const mine = readEntry(file);
133
+ // Gone between the read and the claim: an old process deleted it. Not ours.
134
+ if (!mine) continue;
135
+ rmQuiet(file);
136
+ return mine;
137
+ }
138
+ return null;
100
139
  } catch {
101
140
  return null;
102
141
  }
@@ -3,14 +3,16 @@
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-1a2b3c4d acmeco 종합 점수 12명 중 3위
7
- * 🦊 여우` and no more. This answers the questions that chip raises: how many
8
- * people stand ahead, whether the rank is earned by spending more tokens or by
9
- * using them better, which species is next and what the whole ladder looks
10
- * like. The score adds the spend rank and the delegation-share rank (and the
11
- * prompt-count rank where prompt capture is on), so the spend rank rises with
12
- * more tokens and the delegation rank rises by handing a larger share of the
13
- * same spend to cheaper models. The species follow the score's percentile
6
+ * The statusline chip says `Pro member-1a2b3c4d acmeco 11월 종합 점수 12명 중
7
+ * 3위 🦊 여우` and no more (the standing covers the current calendar month, so
8
+ * the month leads the rank). This answers the questions that chip raises: how
9
+ * many people stand ahead, whether the rank is earned by spending more tokens
10
+ * or by using them better, which species is next and what the whole ladder
11
+ * looks like. The score adds the spend rank and the delegation-share rank (and
12
+ * the prompt-count rank where prompt capture is on), so the spend rank rises
13
+ * with more tokens and the delegation rank rises with the share of savings
14
+ * that delegation brings, counted since the machine joined (saved ÷ (spend +
15
+ * saved)). The species follow the score's percentile
14
16
  * (GRADES in office-species.js), and the six species from the wolf up also
15
17
  * need the delegation share at or above the company median.
16
18
  *
@@ -95,6 +97,30 @@ export function nextOf(st, sr = scorePctOf(st)) {
95
97
  return { grade: up.key, pass: Math.max(0, Math.ceil((up.minSr - sr) / span * (st.ranked - 1) - 1e-6)), needDlg: up.needDlg && !dlgOk };
96
98
  }
97
99
 
100
+ const MONTHS_EN = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
101
+
102
+ /**
103
+ * The month the standing covers when its period is one calendar month so far:
104
+ * `rangeFrom` is the 1st of a month and `rangeTo` a valid date in that same
105
+ * year and month. Korean `11월`, English `Nov` (a fixed table, no locale
106
+ * dependency). Null for any other period (a rolling window such as
107
+ * 2026-10-09..2026-11-07), a missing field or an impossible month.
108
+ * @param {{ rangeFrom?: string|null, rangeTo?: string|null }|null|undefined} st
109
+ * @param {'ko'|'en'} [lang]
110
+ * @returns {string|null}
111
+ */
112
+ export function rankMonthLabel(st, lang = 'en') {
113
+ if (!st || typeof st !== 'object') return null;
114
+ const from = typeof st.rangeFrom === 'string' ? /^(\d{4})-(\d{2})-01$/.exec(st.rangeFrom) : null;
115
+ const to = typeof st.rangeTo === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(st.rangeTo) : null;
116
+ if (!from || !to) return null;
117
+ const month = Number(from[2]);
118
+ if (month < 1 || month > 12 || from[1] !== to[1] || from[2] !== to[2]) return null;
119
+ const day = Number(to[3]);
120
+ if (day < 1 || day > new Date(Date.UTC(Number(to[1]), month, 0)).getUTCDate()) return null;
121
+ return lang === 'ko' ? `${month}월` : MONTHS_EN[month - 1];
122
+ }
123
+
98
124
  /**
99
125
  * @param {object|null|undefined} st team.json `standing`
100
126
  * @param {{ lang?: 'ko'|'en', org?: string|null }} [opts]
@@ -124,9 +150,10 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
124
150
  return lines;
125
151
  }
126
152
 
153
+ const month = rankMonthLabel(st, lang);
127
154
  lines.push(ko
128
- ? `순위: ${where}종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace} · ${animal}${period}`
129
- : `Standing: ${where}overall score #${st.rank} of ${st.ranked}${teamPlace} · ${animal}${period}`);
155
+ ? `순위: ${where}${month ? `${month} ` : ''}종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace} · ${animal}${period}`
156
+ : `Standing: ${where}${month ? `${month} ` : ''}overall score #${st.rank} of ${st.ranked}${teamPlace} · ${animal}${period}`);
130
157
 
131
158
  // Where that rank puts you: the people ahead, or the crown.
132
159
  if (st.crown) {
@@ -159,8 +186,8 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
159
186
  : ' The overall score adds the spend rank (62.5%) and the delegation-share rank (37.5%). An Enterprise organization with prompt capture on uses 50%, 30% and 20%, with the prompt-count rank as the third.');
160
187
  }
161
188
  lines.push(ko
162
- ? ` 지출 순위는 토큰을 더 써야 오르고 위임 비율 순위는 같은 지출에서 싼 모델에 맡기는 몫을 늘려야 오릅니다. ${speciesLabel('wolf', 'ko', { emoji: false })} 이상 여섯 종은 위임 비율이 회사 중앙값 이상이어야 합니다.`
163
- : ` The spend rank rises with more tokens; the delegation rank rises by handing a larger share of the same spend to cheaper models. The six species from ${speciesLabel('wolf', 'en', { emoji: false })} up also need a delegation share at or above the company median.`);
189
+ ? ` 지출 순위는 토큰을 더 써야 오르고 위임 비율 순위는 위임이 낸 절감의 몫이 커져야 오릅니다. 이 몫은 설치한 뒤부터 센 절감액 ÷ (지출 + 절감액)입니다. ${speciesLabel('wolf', 'ko', { emoji: false })} 이상 여섯 종은 위임 비율이 회사 중앙값 이상이어야 합니다.`
190
+ : ` The spend rank rises with more tokens; the delegation rank rises with the share of savings that delegation brings, counted since this machine joined (saved ÷ (spend + saved)). The six species from ${speciesLabel('wolf', 'en', { emoji: false })} up also need a delegation share at or above the company median.`);
164
191
 
165
192
  // The caller's own figures, when the server sent them.
166
193
  if (has(st.dlg) || has(st.spent) || has(st.scorePct)) {