sprag-cli 3.103.0 → 3.104.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.
@@ -98,8 +98,8 @@ export async function run({ args, hasFlag }) {
98
98
  setDelegateEnabled(true);
99
99
  console.log(`✓ PreToolUse hook ${res.action} (${res.path})`);
100
100
  console.log(lang === 'ko'
101
- ? '다음 서브에이전트 위임부터 프롬프트에 상한과 필요한 경우 한국어 지침, 최근에 읽은 경로가 덧붙습니다.'
102
- : 'From the next delegation, prompts get bounds, Korean guidance when it applies, and already-touched paths appended.');
101
+ ? '다음 서브에이전트 위임부터 프롬프트에 상한과 필요한 경우 한국어 지침, 최근에 읽은 경로가 덧붙습니다. effort 없이 Sonnet에 보낸 위임은 high로 올립니다.'
102
+ : 'From the next delegation, prompts get bounds, Korean guidance when it applies, and already-touched paths appended. A Sonnet delegation sent without an effort runs at high.');
103
103
  return;
104
104
  }
105
105
 
@@ -116,26 +116,29 @@ export async function run({ args, hasFlag }) {
116
116
  }
117
117
 
118
118
  // status (default)
119
- const { delegateEnabled, BOUNDS_PATH } = await import('../delegation-guard.js');
119
+ const { delegateEnabled, delegateDecided, BOUNDS_PATH } = await import('../delegation-guard.js');
120
120
  const { koreanStyleEnabled } = await import('../korean-style.js');
121
121
  const enabled = delegateEnabled();
122
+ const byDefault = enabled && !delegateDecided();
122
123
  const { registered: hookOn, reason } = await hookState();
123
124
  if (lang === 'ko') {
124
- console.log(`delegate: ${enabled ? 'on' : 'off'}, hook ${hookOn ? '등록됨' : '미등록'}`);
125
+ console.log(`delegate: ${enabled ? 'on' : 'off'}${byDefault ? ' (기본값)' : ''}, hook ${hookOn ? '등록됨' : '미등록'}`);
125
126
  if (reason) console.log(` settings.json: ${reason}`);
126
127
  console.log(`bounds 파일: ${BOUNDS_PATH}`);
127
128
  console.log(koreanStyleEnabled()
128
- ? 'korean 지침이 켜져 있어, 한글이 들어간 위임 프롬프트에는 같은 지침이 함께 붙습니다.'
129
- : 'korean 지침이 꺼져 있어, 위임 프롬프트에는 상한과 경로 안내만 붙습니다.');
130
- console.log('켜기: sprag delegate on');
129
+ ? 'korean 지침이 켜져 있어서 한글이 들어간 위임 프롬프트에는 같은 지침이 함께 붙습니다.'
130
+ : 'korean 지침이 꺼져 있어서 위임 프롬프트에는 상한과 경로 안내만 붙습니다.');
131
+ if (enabled && !hookOn) console.log('훅을 등록하려면: sprag delegate on');
132
+ console.log(enabled ? '끄기: sprag delegate off' : '켜기: sprag delegate on');
131
133
  } else {
132
- console.log(`delegate: ${enabled ? 'on' : 'off'}, hook ${hookOn ? 'registered' : 'not registered'}`);
134
+ console.log(`delegate: ${enabled ? 'on' : 'off'}${byDefault ? ' (default)' : ''}, hook ${hookOn ? 'registered' : 'not registered'}`);
133
135
  if (reason) console.log(` settings.json: ${reason}`);
134
136
  console.log(`bounds file: ${BOUNDS_PATH}`);
135
137
  console.log(koreanStyleEnabled()
136
138
  ? 'Korean guidance is on, so a delegation prompt containing Hangul also gets that guidance appended.'
137
139
  : 'Korean guidance is off, so delegation prompts only get bounds and touched-path notes appended.');
138
- console.log('Enable with: sprag delegate on');
140
+ if (enabled && !hookOn) console.log('Register the hook with: sprag delegate on');
141
+ console.log(enabled ? 'Disable with: sprag delegate off' : 'Enable with: sprag delegate on');
139
142
  }
140
143
  }
141
144
 
@@ -367,6 +367,46 @@ export async function run({ hasFlag }) {
367
367
  debug('install:doc2md', e); // optional feature; never fail install
368
368
  }
369
369
 
370
+ // Delegation guard, on by default since v3.104.0. It rewrites every
371
+ // Task/Agent prompt, so the install says what it appends before the first
372
+ // delegation it touches; that notice is what makes a default-on rewrite
373
+ // acceptable. An explicit `delegate off` is kept across upgrades. The
374
+ // Korean section inside it still follows `korean on|off` above.
375
+ try {
376
+ const dg = await import('../delegation-guard.js');
377
+ if (envVar('NO_DELEGATE') === '1') {
378
+ console.log('');
379
+ console.log(lang === 'ko'
380
+ ? ' delegate: SPRAG_NO_DELEGATE=1 이므로 건너뜁니다 (나중에 `delegate on`).'
381
+ : ' delegate: skipped (SPRAG_NO_DELEGATE=1) — run `delegate on` later.');
382
+ } else if (!dg.delegateEnabled()) {
383
+ console.log('');
384
+ console.log(lang === 'ko'
385
+ ? ' delegate: 기존 설정 유지, 위임 가드 꺼짐 (켜려면 `sprag delegate on`)'
386
+ : ' delegate: keeping your setting, delegation guard off (turn on with `sprag delegate on`)');
387
+ } else {
388
+ const { installDelegationGuardHook } = await import('../installer.js');
389
+ const res = installDelegationGuardHook();
390
+ console.log('');
391
+ console.log(res.action === 'skipped'
392
+ ? ` delegate: ${res.reason}`
393
+ : ` delegate: PreToolUse hook ${res.action} (${res.path})`);
394
+ if (res.action !== 'skipped' && res.action !== 'exists') {
395
+ console.log(lang === 'ko'
396
+ ? ' 서브에이전트 위임 프롬프트에 룰이 정한 상한과 이미 읽은 경로를 덧붙입니다.'
397
+ : ' appends the rule\'s caps and already-read paths to every subagent delegation prompt.');
398
+ console.log(lang === 'ko'
399
+ ? ' effort 없이 Sonnet에 보낸 위임은 high로 올립니다(실측: 여러 파일 조회 medium 0/3, high 2/3). 상태줄 🔬 Effort saved 가 그 위임이 낸 절감이고 횟수는 그 뒤에 붙습니다.'
400
+ : ' a Sonnet delegation sent without an effort runs at high (measured: multi-file lookup 0/3 at medium, 2/3 at high). The statusline shows what those runs saved as 🔬 Effort saved, with the count beside it.');
401
+ console.log(lang === 'ko'
402
+ ? ' 근거: https://sprag.io/proof/ 끄기: sprag delegate off'
403
+ : ' evidence: https://sprag.io/proof/ turn off: sprag delegate off');
404
+ }
405
+ }
406
+ } catch (e) {
407
+ debug('install:delegate', e); // optional feature; never fail install
408
+ }
409
+
370
410
  // Starter rules. The asking itself belongs to the first session — a
371
411
  // postinstall cannot hold a conversation, and a prompt here would be
372
412
  // answered by whoever happens to be at the terminal for a set of rules
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Subcommand: proof — list the replayed delegation cases that back the tier
3
+ * rules, from the summary shipped inside the package.
4
+ *
5
+ * sprag proof # counts and one row per case
6
+ * sprag proof --json # the summary JSON as is
7
+ *
8
+ * The summary is evals/summary.json, generated by scripts/evals/build.mjs. It is
9
+ * located from this module, not from the working directory or process.argv[1].
10
+ */
11
+ import { readFileSync } from 'node:fs';
12
+ import { join, dirname } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { userLanguage } from '../config.js';
15
+
16
+ const SUMMARY_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'evals', 'summary.json');
17
+ const PROOF_URL = 'https://sprag.io/proof/';
18
+
19
+ const VERDICT = {
20
+ en: { ok: 'relayable', partial: 'partial', fail: 'missed' },
21
+ ko: { ok: '그대로 전달', partial: '부분', fail: '놓침' },
22
+ };
23
+
24
+ function loadSummary(path) {
25
+ try {
26
+ return JSON.parse(readFileSync(path, 'utf8'));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ function pad(text, width) {
33
+ const s = String(text);
34
+ return s + ' '.repeat(Math.max(0, width - displayWidth(s)));
35
+ }
36
+
37
+ // Hangul and other wide characters take two terminal columns.
38
+ function displayWidth(s) {
39
+ let w = 0;
40
+ for (const ch of s) w += /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿＀-⦆]/.test(ch) ? 2 : 1;
41
+ return w;
42
+ }
43
+
44
+ export function formatProof(summary, lang) {
45
+ const ko = lang === 'ko';
46
+ const lines = [];
47
+ lines.push(
48
+ ko
49
+ ? `재생한 위임 사례 ${summary.cases}건, 실행 ${summary.runs}회, 라운드 ${summary.rounds.length}개 (최근 ${summary.latest})`
50
+ : `${summary.cases} replayed delegations, ${summary.runs} runs, ${summary.rounds.length} rounds (latest ${summary.latest})`,
51
+ );
52
+ lines.push('');
53
+ const head = ko ? ['사례', '추천 설정', '판정', 'Opus 대비'] : ['Case', 'Setup', 'Verdict', 'vs Opus'];
54
+ const rows = summary.items.map((it) => [
55
+ it.title[lang] || it.title.en,
56
+ it.recommendedLabel || it.recommended,
57
+ VERDICT[lang][it.recommendedVerdict] || it.recommendedVerdict,
58
+ it.savingsPct > 0 ? `-${it.savingsPct.toFixed(1)}%` : `+${Math.abs(it.savingsPct).toFixed(1)}%`,
59
+ ]);
60
+ const widths = head.map((h, i) => Math.max(displayWidth(h), ...rows.map((r) => displayWidth(r[i]))));
61
+ const row = (cells) => cells.map((c, i) => pad(c, widths[i])).join(' ').trimEnd();
62
+ lines.push(row(head));
63
+ for (const r of rows) lines.push(row(r));
64
+ lines.push('');
65
+ lines.push(ko ? `모든 실행 기록: ${PROOF_URL}` : `Every run: ${PROOF_URL}`);
66
+ return lines.join('\n');
67
+ }
68
+
69
+ export async function run({ args = [], hasFlag, summaryPath = SUMMARY_PATH } = {}) {
70
+ const summary = loadSummary(summaryPath);
71
+ if (!summary) {
72
+ console.log(`No replayed-delegation summary in this install. See ${PROOF_URL}`);
73
+ return;
74
+ }
75
+ if (hasFlag?.('--json') || args.includes('--json')) {
76
+ console.log(JSON.stringify(summary, null, 2));
77
+ return;
78
+ }
79
+ console.log(formatProof(summary, userLanguage()));
80
+ }
@@ -72,24 +72,31 @@ async function refreshRuleSavings(ko, rescan) {
72
72
 
73
73
  /**
74
74
  * Sonnet delegations the guard ran at high effort because the call passed none
75
- * (src/delegation-guard.js), from the last route-scan. The statusline shows only
76
- * the count; the cost is said here, along with the fact that the saving above
77
- * already paid for it. Silent when nothing was raised or the scan is unreadable.
75
+ * (src/delegation-guard.js), from the effort-raise ledger (`totals` is
76
+ * effortRaiseTotals, read with the same routing reset mark as the line above
77
+ * it). The statusline shows the count and the saving those runs kept; the cost
78
+ * is said here. Silent when nothing was raised.
78
79
  */
79
- function printEffortRaises({ ko, money, readScan }) {
80
- let r;
81
- try {
82
- r = readScan()?.effortRaises;
83
- } catch (e) {
84
- debug('saved:effort-raises', e);
85
- return;
86
- }
87
- const count = Number(r?.count) || 0;
80
+ function printEffortRaises({ ko, money, totals, since }) {
81
+ const count = Number(totals?.count) || 0;
88
82
  if (count <= 0) return;
89
- const cost = money(Number(r.cost) || 0);
90
- console.log(ko
91
- ? `effort 상향: ${count}회 · 실행 비용 ${cost} (effort 없이 Sonnet에 보낸 위임을 high로 올렸습니다. 절감액에는 이미 반영돼 있습니다)`
92
- : `Effort raised: ${count} runs · run cost ${cost} (sonnet delegations sent without an effort were run at high; the saving above is already net of it)`);
83
+ const cost = money(Number(totals.cost) || 0);
84
+ const keptRuns = Number(totals.keptRuns) || 0;
85
+ const missing = Number(totals.costMissing) || 0;
86
+ const unpriced = missing > 0 ? ` +${missing} unpriced` : '';
87
+ // The same shape as the routing line above it: the saving first, then what it
88
+ // is made of. A raise no rule routed has no saving to show and is counted apart.
89
+ const kept = keptRuns > 0 ? money(Number(totals.kept) || 0) : (ko ? '측정 없음' : 'none measured');
90
+ const unmatched = count - keptRuns;
91
+ if (ko) {
92
+ const runs = `상향 ${count}회${unmatched > 0 && keptRuns > 0 ? ` (룰 없는 ${unmatched}회는 절감 미측정)` : ''}`;
93
+ console.log(`effort 절감: ${kept} · ${runs} · 실행 비용 ${cost}${unpriced} (${since})`);
94
+ console.log(' effort 없이 Sonnet에 보낸 위임을 high로 올린 횟수와 그 위임이 낸 라우팅 절감입니다. 이 절감은 위 라우팅 절감에 이미 들어 있습니다.');
95
+ } else {
96
+ const runs = `${count} raised${unmatched > 0 && keptRuns > 0 ? ` (${unmatched} with no rule, saving not measured)` : ''}`;
97
+ console.log(`Effort saved: ${kept} · ${runs} · run cost ${cost}${unpriced} (${since})`);
98
+ console.log(' Sonnet delegations sent without an effort ran at high; the saving is what those runs saved by routing and is already inside the routing figure above.');
99
+ }
93
100
  }
94
101
 
95
102
  const FAMILY_NAMES = { opus: 'Opus', sonnet: 'Sonnet', haiku: 'Haiku', fable: 'Fable', mythos: 'Mythos' };
@@ -140,7 +147,7 @@ async function printModelShare({ ko, dir, money }) {
140
147
  }
141
148
  }
142
149
 
143
- export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan, readScan: readScanArg }) {
150
+ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan }) {
144
151
  const { userLanguage } = await import('../config.js');
145
152
  const { userDataDir } = await import('../paths.js');
146
153
  const { readResetMarks, resetSaved, undoReset } = await import('../saved-reset.cjs');
@@ -172,14 +179,14 @@ export async function run({ args, hasFlag, agent = 'claude', dir: dirArg, rescan
172
179
 
173
180
  if (sub === undefined) {
174
181
  const marks = readResetMarks(dir);
175
- const readScan = readScanArg || (await import('../route-scan.js')).readRouteScan;
182
+ const { effortRaiseTotals } = await import('../effort-raise-ledger.js');
176
183
  for (const s of scopes) {
177
184
  const t = await currentTotals(s, dir);
178
185
  const since = marks[s] === null
179
186
  ? (ko ? '초기화한 적 없음' : 'not reset')
180
187
  : (ko ? `${fmtTime(marks[s])} 이후` : `since ${fmtTime(marks[s])}`);
181
188
  console.log(`${label(s)}: ${fmtTotal(t)} (${since})`);
182
- if (s === 'routing') printEffortRaises({ ko, money, readScan });
189
+ if (s === 'routing') printEffortRaises({ ko, money, totals: effortRaiseTotals(Date.now(), dir), since });
183
190
  }
184
191
  if (agent !== 'codex') {
185
192
  console.log(ko
@@ -21,6 +21,7 @@ import {
21
21
  teamRulesCachePath, teamSyncDisabled, requestSignInCode, verifySignInCode, createTeam, isSeatLimitError, isOrgExpiredError,
22
22
  setDisplayName,
23
23
  } from '../team-sync.js';
24
+ import { standingGuideLines } from '../team-standing.js';
24
25
 
25
26
  const T = {
26
27
  en: {
@@ -30,7 +31,7 @@ const T = {
30
31
  ' join [token] [--name <n>] [--yes] join a team (token or SPRAG_TEAM_TOKEN)',
31
32
  ' name [<n>] show or change your display name',
32
33
  ' leave leave the team and stop uploading',
33
- ' status [--show-payload] membership, last sync, what is sent (daily aggregates and rule summary)',
34
+ ' status [--show-payload] membership, standing and what the next species takes, last sync, what is sent (daily aggregates and rule summary)',
34
35
  ' sync [--force] [--rules-only] upload aggregates, prompts (Enterprise capture) and pull rules now',
35
36
  ' (--rules-only: pull organization and team rules only, upload nothing)',
36
37
  ' rules show cached organization and team rules',
@@ -105,7 +106,7 @@ const T = {
105
106
  ' join [토큰] [--name <이름>] [--yes] 팀에 참여 (토큰 또는 SPRAG_TEAM_TOKEN)',
106
107
  ' name [<이름>] 표시 이름 보기 또는 바꾸기',
107
108
  ' leave 팀에서 나가고 업로드 중단',
108
- ' status [--show-payload] 참여 상태, 마지막 동기화, 보내는 내용(하루 집계와 룰 요약)',
109
+ ' status [--show-payload] 참여 상태, 순위와 다음 등급까지의 거리, 마지막 동기화, 보내는 내용(하루 집계와 룰 요약)',
109
110
  ' sync [--force] [--rules-only] 지금 집계를 올리고 규칙을 받기',
110
111
  ' (--rules-only: 조직·팀 규칙만 받고 아무것도 올리지 않음)',
111
112
  ' rules 받아 둔 조직·팀 규칙 보기',
@@ -328,6 +329,9 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
328
329
  }
329
330
  out(`${m.name}: ${st.displayName}`);
330
331
  if (MACHINE_NAME_RE.test(String(st.displayName || ''))) out(` ${m.nameHint}`);
332
+ // The standing behind the statusline chip, and what moving up takes
333
+ // (src/team-standing.js). Nothing until the first sync has fetched one.
334
+ for (const l of standingGuideLines(st.standing, { lang: userLanguage(), org: st.orgName || st.teamName || null, team: st.teamName || null })) out(l);
331
335
  out(st.lastSyncAt ? m.lastSync(new Date(st.lastSyncAt).toLocaleString(), st.lastSyncRows || 0) : m.neverSynced);
332
336
  if (st.lastError) out(isOrgExpiredError(st.lastError) ? m.orgExpired : `${m.lastError}: ${st.lastError}`);
333
337
  if (orgMinVersion(st)) out(m.orgMin(orgMinVersion(st), version));
@@ -15,9 +15,16 @@
15
15
  * tends to explore until its own context runs out rather than until the task
16
16
  * is answered, which is the tool-call-cap section below.
17
17
  *
18
- * Opt-in via `sprag delegate on` — like doc2md and korean-style, a feature
19
- * that rewrites tool input silently has to be something the user asked for,
20
- * not something that ships on by default.
18
+ * On by default since v3.104.0; `sprag delegate off` turns it off and the
19
+ * choice survives upgrades. It started as opt-in (2026-09-21) on the principle
20
+ * that a hook rewriting tool input silently should be asked for. Two things
21
+ * changed that. The replay of 2026-11-07 measured what the guard prevents:
22
+ * a multi-file lookup sent to sonnet without an effort argument ran at medium
23
+ * and was relayable in 0 of 3 runs, against 2 of 3 at high. And the rewrite is
24
+ * no longer silent: `sprag install` says what it appends before the first
25
+ * delegation, and the statusline counts every effort raise (`🔬↑N`). The one
26
+ * expensive section, the Korean style guidance (~7k tokens), still follows its
27
+ * own opt-in through koreanStyleEnabled().
21
28
  */
22
29
 
23
30
  import { readFileSync, existsSync } from 'node:fs';
@@ -41,9 +48,18 @@ const DELEGATION_MARKER = '<!-- sprag:delegation -->';
41
48
  /** The rules file the ratchet section points at. One place, two readers. */
42
49
  const ratchetPath = (home = homedir()) => join(home, '.claude', 'ratchet.md');
43
50
 
44
- /** Whether the delegation guard is on. Off unless the user asked. */
51
+ /**
52
+ * Whether the delegation guard is on. On unless the user turned it off: only
53
+ * an explicit `false` disables it, so a config written before the default
54
+ * changed (no `delegate` key at all) reads as on.
55
+ */
45
56
  export function delegateEnabled(cfg = loadConfig()) {
46
- return cfg?.delegate?.enabled === true;
57
+ return cfg?.delegate?.enabled !== false;
58
+ }
59
+
60
+ /** Whether the user has set the guard either way, as opposed to the default. */
61
+ export function delegateDecided(cfg = loadConfig()) {
62
+ return typeof cfg?.delegate?.enabled === 'boolean';
47
63
  }
48
64
 
49
65
  export function setDelegateEnabled(enabled) {
@@ -130,6 +146,7 @@ export async function buildAppendix(payload, { cfg = loadConfig(), home = homedi
130
146
  const isHaiku = /haiku/i.test(modelHint);
131
147
  const isOpus = /opus/i.test(modelHint);
132
148
 
149
+ const prompt = payload?.tool_input?.prompt;
133
150
  const bounds = boundsText();
134
151
  if (bounds) {
135
152
  // Haiku delegations get a tighter leash (8 tool calls / 1,500 output
@@ -142,11 +159,18 @@ export async function buildAppendix(payload, { cfg = loadConfig(), home = homedi
142
159
  const matched = routeCaps?.[isHaiku ? 'T2' : isOpus ? 'T1H' : 'T1'];
143
160
  const calls = Number.isFinite(matched?.calls) && matched.calls > 0 ? matched.calls : fallback.calls;
144
161
  const out = Number.isFinite(matched?.out) && matched.out > 0 ? matched.out : fallback.out;
145
- const capLine = `Cap for this delegation: ${calls} tool calls, ${out.toLocaleString('en-US')} output tokens.`;
162
+ // A caller that states its own budget has sized the work, and an
163
+ // implementation hand-off sized at 90 calls cannot finish inside a lookup
164
+ // rule's 6,100 output tokens. Before this the appended cap won: a t1-worker
165
+ // given "about 90 tool calls" stopped after 7 calls at the rule's cap
166
+ // (2026-11-07), because the bounds told it to obey the cap whatever the
167
+ // prompt said. The caller's number now replaces the default.
168
+ const capLine = statesOwnBudget(prompt)
169
+ ? 'Cap for this delegation: the budget stated in your prompt above. It replaces the default cap.'
170
+ : `Cap for this delegation: ${calls} tool calls, ${out.toLocaleString('en-US')} output tokens.`;
146
171
  sections.push(['## Bounds and output shape', bounds, capLine].join('\n\n'));
147
172
  }
148
173
 
149
- const prompt = payload?.tool_input?.prompt;
150
174
  // koreanStyleInjection() runs to ~8k characters. Appending it to every
151
175
  // delegation regardless of language would multiply that cost by the number
152
176
  // of delegations in a session; gating it on the prompt actually containing
@@ -273,6 +297,17 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
273
297
  return { updatedInput };
274
298
  }
275
299
 
300
+ /**
301
+ * True when the delegation prompt sets its own budget: the word budget (or
302
+ * 예산) next to a number, or a tool-call count. The rules require an
303
+ * implementation hand-off to state one, so this is the signal that the caller
304
+ * sized the work itself.
305
+ */
306
+ export function statesOwnBudget(prompt) {
307
+ if (typeof prompt !== 'string') return false;
308
+ return /\bbudget\b[^\n]{0,40}\d|예산[^\n]{0,40}\d|\b\d+\s*tool calls?\b|도구 호출\s*\d+\s*회/i.test(prompt);
309
+ }
310
+
276
311
  /** Effort a sonnet delegation runs at when the call passed none. */
277
312
  export const RAISED_EFFORT = 'high';
278
313
 
@@ -0,0 +1,117 @@
1
+ /**
2
+ * effort-raise-ledger — one event per subagent run the delegation guard raised
3
+ * to high effort (the run's first prompt ends with EFFORT_RAISE_MARKER).
4
+ *
5
+ * The count used to live in the route-scan cache, so it covered only the scan
6
+ * window and went stale after `sprag saved reset routing` until the next scan.
7
+ * Routing saved is a ledger read live with the reset mark; this one is read the
8
+ * same way, so both zero out together.
9
+ *
10
+ * File: <userDataDir>/effort-raise-ledger.json
11
+ * { "version": 1, "events": { "<run transcript path>": { "ts", "cost"?, "model"? } } }
12
+ *
13
+ * Keyed by the run's transcript path and upserted by run identity, like the
14
+ * delegation ledger, so overlapping scans and renamed project folders never
15
+ * count a run twice. The ledger is evidence: the reset mark is applied when the
16
+ * totals are read, not when events are recorded.
17
+ *
18
+ * `kept` joins each raised run to its delegation-ledger event (priced live) and
19
+ * sums the routing saving those runs produced. It is a subset of Routing saved,
20
+ * never added to it.
21
+ *
22
+ * Best-effort like every other state file here: nothing throws, and an
23
+ * unreadable or wrong-version file reads as empty.
24
+ */
25
+
26
+ import { readFileSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+ import { userDataDir } from './paths.js';
29
+ import { writeStateFile } from './state-file.js';
30
+ import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
31
+ import { loadLedger, runIdentity, roundUsd } from './savings-ledger.js';
32
+
33
+ export const EFFORT_RAISE_LEDGER_VERSION = 1;
34
+
35
+ export function effortRaiseLedgerPath(dir = userDataDir()) {
36
+ return join(dir, 'effort-raise-ledger.json');
37
+ }
38
+
39
+ export function loadEffortRaiseLedger(dir = userDataDir()) {
40
+ try {
41
+ const data = JSON.parse(readFileSync(effortRaiseLedgerPath(dir), 'utf8'));
42
+ if (!data || data.version !== EFFORT_RAISE_LEDGER_VERSION
43
+ || typeof data.events !== 'object' || data.events === null || Array.isArray(data.events)) {
44
+ return { version: EFFORT_RAISE_LEDGER_VERSION, events: {} };
45
+ }
46
+ return data;
47
+ } catch {
48
+ return { version: EFFORT_RAISE_LEDGER_VERSION, events: {} };
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Upsert raise events: [{ key, ts, cost?, model? }]. `key` is the run's
54
+ * transcript path. Entries without a key or a finite ts are skipped, and the
55
+ * file is written only when something changed.
56
+ */
57
+ export function recordEffortRaises(events, dir = userDataDir()) {
58
+ try {
59
+ if (!Array.isArray(events) || events.length === 0) return;
60
+ const data = loadEffortRaiseLedger(dir);
61
+ let changed = false;
62
+ const keyOf = new Map(Object.keys(data.events).map((k) => [runIdentity(k), k]));
63
+ for (const e of events) {
64
+ if (!e || !e.key || !Number.isFinite(e.ts)) continue;
65
+ const id = runIdentity(e.key);
66
+ const prevKey = keyOf.get(id) ?? e.key;
67
+ const prev = data.events[prevKey];
68
+ const cost = Number.isFinite(e.cost) ? roundUsd(e.cost) : undefined;
69
+ const model = typeof e.model === 'string' && e.model ? e.model : undefined;
70
+ if (prev && prevKey === e.key && prev.ts === e.ts && prev.cost === cost && prev.model === model) continue;
71
+ if (prevKey !== e.key) delete data.events[prevKey];
72
+ keyOf.set(id, e.key);
73
+ data.events[e.key] = {
74
+ ts: e.ts,
75
+ ...(cost !== undefined ? { cost } : {}),
76
+ ...(model !== undefined ? { model } : {}),
77
+ };
78
+ changed = true;
79
+ }
80
+ if (!changed) return;
81
+ writeStateFile(effortRaiseLedgerPath(dir), JSON.stringify(data) + '\n');
82
+ } catch {
83
+ // totals just stay stale until the next successful scan
84
+ }
85
+ }
86
+
87
+ /**
88
+ * { count, cost, costMissing, kept, keptRuns, since } over the events after the
89
+ * `routing` reset mark. `cost` is what the raised runs cost, `kept` the routing
90
+ * saving the same runs produced (their delegation-ledger `usd`), over the
91
+ * `keptRuns` runs that have one. Never throws.
92
+ */
93
+ export function effortRaiseTotals(now = Date.now(), dir = userDataDir()) { // eslint-disable-line no-unused-vars
94
+ const since = readResetMarks(dir).routing;
95
+ const zero = { count: 0, cost: 0, costMissing: 0, kept: 0, keptRuns: 0, since };
96
+ try {
97
+ const delegated = new Map();
98
+ for (const [key, e] of Object.entries(loadLedger().events)) delegated.set(runIdentity(key), e);
99
+ const totals = { ...zero };
100
+ for (const [key, e] of Object.entries(loadEffortRaiseLedger(dir).events)) {
101
+ if (!e || isBeforeReset(e.ts, since)) continue;
102
+ totals.count += 1;
103
+ if (Number.isFinite(e.cost)) totals.cost += e.cost;
104
+ else totals.costMissing += 1;
105
+ const usd = Number(delegated.get(runIdentity(key))?.usd);
106
+ if (Number.isFinite(usd)) {
107
+ totals.kept += usd;
108
+ totals.keptRuns += 1;
109
+ }
110
+ }
111
+ totals.cost = Math.round(totals.cost * 100) / 100;
112
+ totals.kept = Math.round(totals.kept * 100) / 100;
113
+ return totals;
114
+ } catch {
115
+ return zero;
116
+ }
117
+ }
@@ -399,10 +399,12 @@ function buildVersionSeg(version, update, c, isIcon, verbose, g) {
399
399
  const TEAM_STANDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
400
400
 
401
401
  /**
402
- * Team chip: the member id and, once the server has told us, the animal that
403
- * member is in the team's virtual office and the rank (`member-1e500474 🦊 Fox #3 of 12`). Renders only
402
+ * Team chip: the member id, the organization and, once the server has told us,
403
+ * the overall-score rank and the animal that member is in the team's virtual
404
+ * office (`member-1e500474 amazon overall score #3 of 12 🦊 Fox`). Renders only
404
405
  * for a joined machine. A missing, unknown or day-old standing leaves just the
405
- * member label. Gray like the other identity chips; the emoji brings its own colour.
406
+ * member label (and the organization, when known). The office page calls the
407
+ * ranked figure the overall score (spend rank, delegation rank, prompt rank). Gray like the other identity chips; the emoji brings its own colour.
406
408
  * The emoji draws only in icon mode: narrow (the IntelliJ default, whose font has
407
409
  * no animal emoji) and text keep the animal's name and the rank.
408
410
  */
@@ -413,8 +415,18 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
413
415
  const animal = fresh ? speciesLabel(st.grade, team.lang, { emoji: mode === 'icon' }) : null;
414
416
  // The rank among the ranked people, the same standing the office drawer shows; a ghost has none.
415
417
  const ranked = animal && Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
416
- const place = ranked ? (team.lang === 'ko' ? ` ${st.ranked}명 중 ${st.rank}위` : ` #${st.rank} of ${st.ranked}`) : '';
417
- return `${c(GRAY)}${team.label}${animal ? ` ${animal}${place}` : ''}${c(RESET)}`;
418
+ // The rank within the person's own team rides behind the organization rank,
419
+ // only when the team is a strict part of the ranked people: in a one-team
420
+ // organization the two are the same number.
421
+ const inTeam = ranked && Number.isInteger(st.teamRank) && Number.isInteger(st.teamRanked)
422
+ && st.teamRank >= 1 && st.teamRanked >= st.teamRank && st.teamRanked < st.ranked && typeof team.team === 'string' && team.team;
423
+ const teamPlace = inTeam ? (team.lang === 'ko' ? `, ${team.team} 팀 ${st.teamRanked}명 중 ${st.teamRank}위` : `, team ${team.team} #${st.teamRank} of ${st.teamRanked}`) : '';
424
+ const place = ranked ? (team.lang === 'ko' ? ` 종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace}` : ` overall score #${st.rank} of ${st.ranked}${teamPlace}`) : '';
425
+ const org = typeof team.org === 'string' && team.org ? ` ${team.org}` : '';
426
+ // The plan leads (`Pro`, `Enterprise`): the chip describes a licensed team, so
427
+ // the license is the first thing it says, and the standing follows.
428
+ const plan = typeof team.plan === 'string' && team.plan ? `${team.plan[0].toUpperCase()}${team.plan.slice(1)} ` : '';
429
+ return `${c(GRAY)}${plan}${team.label}${org}${animal ? `${place} ${animal}` : ''}${c(RESET)}`;
418
430
  }
419
431
 
420
432
  /**
@@ -1147,13 +1159,29 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1147
1159
  const delegateExtra = savingsChip && delegationSaved === 0 ? unresolvedSeg : null;
1148
1160
 
1149
1161
  // Sonnet delegations the guard ran at high effort because the call passed
1150
- // none. Gray, since it is a cost and not a saving: the savings beside it are
1151
- // already net of it, and `sprag saved` prints what the runs cost.
1152
- // icon: "🔬↑3" | text: "effort↑3" | verbose: "effort raised ×3"
1153
- const raised = Number(data.effortRaises && data.effortRaises.count) || 0;
1154
- const raisedSeg = raised > 0
1155
- ? `${c(GRAY)}${verbose ? `effort raised ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
1156
- : null;
1162
+ // none, in the shape of the other two savings: "Effort saved" is the routing
1163
+ // saving those raised runs produced (a part of Routing saved, never added to
1164
+ // it), and the raise count rides as the breakdown. A raise with no measured
1165
+ // saving (no registered rule routed the run) keeps the gray count chip, as a
1166
+ // bare document count does for Doc2md. `sprag saved` prints what the runs cost.
1167
+ // icon: "🔬 $12.4" verbose: "🔬 Effort saved $12.4 · 3 raised"
1168
+ // text: "Effort saved $12.4"
1169
+ // no saving measured: icon "🔬↑3" | text "effort↑3" | verbose "effort raised ×3"
1170
+ const raisedInfo = data.effortRaises;
1171
+ const raised = Number(raisedInfo && raisedInfo.count) || 0;
1172
+ const keptUsd = Number(raisedInfo && raisedInfo.kept) || 0;
1173
+ const keptRuns = Number(raisedInfo && raisedInfo.keptRuns) || 0;
1174
+ const hasKept = raised > 0 && keptRuns > 0 && keptUsd !== 0;
1175
+ const keptTone = keptUsd < 0 ? RED : GREEN;
1176
+ const raisedSince = formatSince(raisedInfo && raisedInfo.since);
1177
+ const effortLabel = isIcon ? (verbose ? `${g.effort} Effort saved` : g.effort) : 'Effort saved';
1178
+ let raisedSeg = null;
1179
+ if (hasKept) {
1180
+ raisedSeg = `${c(keptTone)}${effortLabel}${c(RESET)} ${formatMoney(keptUsd)}${sinceInline(raisedSince)}`
1181
+ + (verbose ? ` ${c(GRAY)}· ${raised} raised${c(RESET)}` : '');
1182
+ } else if (raised > 0) {
1183
+ raisedSeg = `${c(GRAY)}${verbose ? `effort raised ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`;
1184
+ }
1157
1185
 
1158
1186
  // Routing-savings headline line (multi-line layout). The lifetime sum from
1159
1187
  // the delegation ledger — the number the whole tool exists to grow, so it
@@ -1198,16 +1226,38 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1198
1226
  (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
1199
1227
  }
1200
1228
 
1229
+ // The Effort saved line (multi-line layout), under the savings lines and in
1230
+ // their anatomy: the figure, the same reset mark as Routing saved, then the
1231
+ // breakdown, where the raise count sits as `medium→high ×N $X` (Claude
1232
+ // Code's default effort to the one the guard set). Raises that no rule
1233
+ // routed have no saving to show and are counted as `no rule ×N (n/a)`, as
1234
+ // Doc2md counts a format with no baseline. Built only beside a Routing saved
1235
+ // line and only with a measured saving; a bare count stays a chip.
1236
+ // icon: "🔬 Effort saved $12.4 since 11/1 | medium→high ×2 $12.4 · no rule ×1 (n/a)"
1237
+ // text: "Effort saved $12.4 since 11/1 | medium→high ×2 $12.4 · no rule ×1 (n/a)"
1238
+ let raisedLine = null;
1239
+ if (totalsLine && hasKept) {
1240
+ const head = isIcon ? `${g.effort} Effort saved` : 'Effort saved';
1241
+ const parts = [`${c(GRAY)}medium→high ×${keptRuns} ${formatMoney(keptUsd)}${c(RESET)}`];
1242
+ if (raised > keptRuns) parts.push(`${c(GRAY)}no rule ×${raised - keptRuns} ${verbose ? '(no saving measured)' : '(n/a)'}${c(RESET)}`);
1243
+ raisedLine =
1244
+ `${c(keptTone)}${c(BOLD)}${head}${c(RESET)} ` +
1245
+ `${c(keptTone)}${formatMoney(keptUsd)}${c(RESET)}` +
1246
+ sinceWord(raisedSince) +
1247
+ ` ${c(GRAY)}|${c(RESET)} ${parts.join(` ${c(GRAY)}·${c(RESET)} `)}`;
1248
+ }
1249
+
1201
1250
  return {
1202
1251
  // Dropped when the same story already owns a headline line above, which
1203
1252
  // would otherwise repeat it on line 2. The unresolved-runs chip survives the
1204
1253
  // headline when that headline is a dated zero, since a zero is exactly when
1205
- // the dropped runs matter.
1206
- // The raise count is not part of that story, so it stays on line 2 either way.
1254
+ // the dropped runs matter. The raise chip steps aside for its own line the
1255
+ // same way, and stays on line 2 while there is no line to carry it.
1207
1256
  chips: totalsLine
1208
- ? (totalsNum === 0 ? [unresolvedSeg, raisedSeg] : [raisedSeg])
1257
+ ? (totalsNum === 0 ? [unresolvedSeg, raisedLine ? null : raisedSeg] : [raisedLine ? null : raisedSeg])
1209
1258
  : [delegateSeg, raisedSeg, delegateExtra],
1210
1259
  headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
1260
+ raisedHeadline: raisedLine ? { usd: keptUsd, line: raisedLine } : null,
1211
1261
  };
1212
1262
  }
1213
1263
 
@@ -1490,6 +1540,9 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v)
1490
1540
  if (delegated.headline && want('delegated')) headlines.push(delegated.headline);
1491
1541
  if (doc2md.headline && want('doc2md')) headlines.push(doc2md.headline);
1492
1542
  headlines.sort((a, b) => b.usd - a.usd);
1543
+ // The effort-raise line closes the savings lines rather than competing with
1544
+ // them: its figure is a part of Routing saved, not a saver of its own.
1545
+ if (delegated.raisedHeadline && want('delegated')) headlines.push(delegated.raisedHeadline);
1493
1546
  const rows = columns
1494
1547
  ? headlines.flatMap((h) => wrapHeadline(h.line, availWidth(columns), c))
1495
1548
  : headlines.map((h) => h.line);