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.
package/src/installer.js CHANGED
@@ -1097,10 +1097,11 @@ export function removeDoc2mdHook() {
1097
1097
  // timeout is safe and catches a hung read fast. The size lives in that one
1098
1098
  // constant; quoting a number here is only ever a stale copy of it.
1099
1099
  //
1100
- // Installed by `delegate on`, removed by `delegate off`. Idempotent. Not part
1101
- // of `installAll()` — this feature rewrites tool input on every delegation,
1102
- // which is exactly the kind of silent-by-default behavior install.js's other
1103
- // opt-in features (doc2md, korean, cohesion) avoid shipping without being asked.
1100
+ // Installed by `sprag install` (on by default since v3.104.0) and by
1101
+ // `delegate on`, removed by `delegate off`. Idempotent. Kept out of
1102
+ // `installAll()` because install.js has to read the user's choice first: an
1103
+ // explicit `delegate off` must survive an upgrade, and the install prints what
1104
+ // the hook appends before the first delegation it rewrites.
1104
1105
  const DELEGATION_GUARD_HOOK_COMMAND = `${CLI} delegate --hook`;
1105
1106
  // Install, remove and the status readout all judge a command through
1106
1107
  // isDelegationGuardHookCommand() below, which compares whole tokens.
@@ -1327,17 +1328,17 @@ export function uninstallAll({ purge = false } = {}) {
1327
1328
  // The state directory stays so a reinstall keeps ledgers and preferences,
1328
1329
  // with one exception carved out just below.
1329
1330
  result.kept.push('state directory (savings ledgers, config, cache) — remove with --purge');
1330
- // delegate.enabled is not a preference, it is an assertion that a hook is
1331
- // registered — and the hooks were just removed above. `delegate on` goes
1332
- // out of its way to hold the invariant "flag on implies hook registered",
1333
- // installing first and leaving the flag alone when that fails; leaving the
1334
- // flag set here breaks the same invariant from the other side and makes
1335
- // status report `delegate: on, hook not registered` after a clean
1336
- // uninstall. Config it does not own is left untouched.
1331
+ // An explicit `delegate.enabled: true` is not a preference, it is an
1332
+ // assertion that a hook is registered, and the hooks were just removed
1333
+ // above. Dropping the key returns the guard to its default, so a later
1334
+ // reinstall registers it again the way a fresh install would. An explicit
1335
+ // `false` is the user's choice and is kept. Config it does not own is left
1336
+ // untouched.
1337
1337
  try {
1338
1338
  const cfg = loadConfig();
1339
- if (cfg?.delegate?.enabled) {
1340
- cfg.delegate = { ...cfg.delegate, enabled: false };
1339
+ if (cfg?.delegate?.enabled === true) {
1340
+ const { enabled: _dropped, ...rest } = cfg.delegate;
1341
+ cfg.delegate = rest;
1341
1342
  saveConfig(cfg);
1342
1343
  result.removed.push('delegate flag');
1343
1344
  }
@@ -42,6 +42,35 @@ export const SPECIES = {
42
42
  ghost: { emoji: '👻', en: 'Ghost', ko: '유령' },
43
43
  };
44
44
 
45
+ /**
46
+ * The species ladder, best first: the overall-score percentile a species starts
47
+ * at (`minSr`), its tier, and whether it also needs the delegation share at or
48
+ * above the company median (`needDlg`). `gt` marks a strict floor. Copied from
49
+ * GRADES in site/assets/scene/office-scene.js, and test/office-species.test.js
50
+ * pins the two, so `sprag team status` and the office page show one ladder.
51
+ * The chick is the idle row (no spend in the period) and has no floor.
52
+ */
53
+ const row = (key, minSr, tier, needDlg = false, gt = false) => ({ key, minSr, tier, needDlg, gt });
54
+ export const GRADES = [
55
+ row('dragon', 0.98, 'power', true), row('unicorn', 0.95, 'power', true), row('lion', 0.92, 'power', true),
56
+ row('tiger', 0.89, 'power', true), row('eagle', 0.85, 'power', true), row('wolf', 0.8, 'power', true),
57
+ row('cheetah', 0.77, 'active'), row('fox', 0.74, 'active'), row('owl', 0.71, 'active'), row('husky', 0.68, 'active'),
58
+ row('panda', 0.65, 'active'), row('koala', 0.62, 'active'), row('penguin', 0.58, 'active'), row('raccoon', 0.54, 'active'),
59
+ row('cat', 0.5, 'active'),
60
+ row('dog', 0.47, 'normal'), row('bear', 0.44, 'normal'), row('monkey', 0.41, 'normal'), row('deer', 0.38, 'normal'),
61
+ row('elephant', 0.35, 'normal'), row('pig', 0.32, 'normal'), row('sheep', 0.29, 'normal'), row('rabbit', 0.25, 'normal', false, true),
62
+ row('duck', 0.22, 'low'), row('hedgehog', 0.19, 'low'), row('squirrel', 0.16, 'low'), row('hamster', 0.12, 'low'),
63
+ row('frog', 0.08, 'low'), row('mouse', 0.04, 'low'), row('chick', -1, 'low'),
64
+ ];
65
+
66
+ /** Tier names as the office page shows them (`of.tier.<tier>` in site/team/index.html). */
67
+ export const TIER_NAMES = {
68
+ power: { en: 'AI power user', ko: 'AI 파워 유저' },
69
+ active: { en: 'Active', ko: '활발' },
70
+ normal: { en: 'Normal', ko: '보통' },
71
+ low: { en: 'Getting started', ko: '활용 장려 필요' },
72
+ };
73
+
45
74
  /**
46
75
  * `"<emoji> <name>"` for a grade key in the given language, or null for an unknown key.
47
76
  * `emoji: false` leaves just the name, for terminals whose font has no animal emoji (IntelliJ).
package/src/route-scan.js CHANGED
@@ -725,11 +725,14 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
725
725
  let unresolvedRuns = 0; // delegated runs dropped for an unpriceable model id
726
726
  const unresolvedModels = new Set();
727
727
  // Sonnet delegations the guard ran at high effort because the call passed
728
- // none (src/delegation-guard.js). Counted whether or not a rule covers the
729
- // run: the raise is sprag's own action, so its price is shown even where no
730
- // saving is claimed. The figure is what those runs cost on their own model,
731
- // priced the way the ledger prices `cost`; the savings already include it.
732
- const effortRaises = { count: 0, cost: 0, since: null };
728
+ // none (src/delegation-guard.js). Collected whether or not a rule covers the
729
+ // run: the raise is sprag's own action, so its cost is shown even where no
730
+ // saving is claimed. Each run becomes an event in the effort-raise ledger
731
+ // (src/effort-raise-ledger.js), which is read live with the routing reset
732
+ // mark, like the savings ledger. The cost is what the run cost on its own
733
+ // model, priced the way the ledger prices `cost`; the savings already
734
+ // include it.
735
+ const raiseEvents = [];
733
736
  // `sprag saved reset routing` zeroes the money, not the rule-health sample:
734
737
  // see tallyDelegatedRun. readResetMarks never throws (no file = no reset).
735
738
  const routingMark = readResetMarks(userDataDir()).routing;
@@ -773,15 +776,17 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
773
776
  for (const [sessionPath, index] of runIndexBySession) {
774
777
  // Every run of the session, not only those joined to a categorized episode
775
778
  // and past the tier gate: a sonnet run under a sonnet main session saves
776
- // nothing, yet the guard raised it all the same. The reset mark applies as
777
- // it does to savings (tallyDelegatedRun).
779
+ // nothing, yet the guard raised it all the same. The reset mark is not
780
+ // applied here: the ledger is evidence, and the mark applies when it is read
781
+ // (as savings-ledger does), so a reset zeroes the count without a rescan.
778
782
  for (const run of index.all) {
779
- if (!run.effortRaised || isBeforeReset(run.endedAt ?? run.startedAt, routingMark)) continue;
780
- effortRaises.count += 1;
781
- const cost = isRecognizedModelId(run.model) ? exactCost(runTotals(run), run.model, { at: runTime(run) }) : null;
782
- if (Number.isFinite(cost)) effortRaises.cost += cost;
783
- const at = run.startedAt ?? run.endedAt;
784
- if (Number.isFinite(at) && (effortRaises.since === null || at < effortRaises.since)) effortRaises.since = at;
783
+ if (!run.effortRaised) continue;
784
+ raiseEvents.push({
785
+ key: run.path,
786
+ ts: run.endedAt ?? run.startedAt ?? null,
787
+ cost: isRecognizedModelId(run.model) ? exactCost(runTotals(run), run.model, { at: runTime(run) }) : null,
788
+ model: run.model,
789
+ });
785
790
  }
786
791
  const used = new Set();
787
792
  const eps = all.filter((x) => x.sessionPath === sessionPath);
@@ -927,8 +932,6 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
927
932
  resolved: [...resolved],
928
933
  unresolvedRuns,
929
934
  unresolvedModels: [...unresolvedModels].slice(0, 5),
930
- // `since` is the earliest counted run (ms), so a reader can date the count.
931
- effortRaises: { ...effortRaises, cost: Math.round(effortRaises.cost * 100) / 100 },
932
935
  };
933
936
  try {
934
937
  const dir = stateDir();
@@ -1027,6 +1030,13 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
1027
1030
  } catch {
1028
1031
  // ledger write failure only delays the statusline totals, never the scan
1029
1032
  }
1033
+ // Its own try so a failure here never blocks the savings ledger above.
1034
+ try {
1035
+ const { recordEffortRaises } = await import('./effort-raise-ledger.js');
1036
+ recordEffortRaises(raiseEvents);
1037
+ } catch {
1038
+ // the effort-raise chip just stays stale until the next scan
1039
+ }
1030
1040
 
1031
1041
  return cache;
1032
1042
  }
@@ -77,7 +77,10 @@ async function readRunEffort(jsonlPath) {
77
77
  try { entry = JSON.parse(line); } catch { continue; }
78
78
  if (effort === null && typeof entry.effort === 'string' && entry.effort) effort = entry.effort;
79
79
  if (raised === null && entry.type === 'user' && entry.message) {
80
- raised = messageText(entry.message.content).includes(EFFORT_RAISE_MARKER);
80
+ // The guard appends the marker as the prompt's last line, so only a
81
+ // prompt that ends with it was raised. A prompt that merely quotes the
82
+ // line (a delegation about this very feature did) is not one.
83
+ raised = messageText(entry.message.content).trimEnd().endsWith(EFFORT_RAISE_MARKER);
81
84
  }
82
85
  if (raised !== null && effort !== null) break;
83
86
  }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * team-standing — the lines `sprag team status` prints about the member's
3
+ * standing in the organization's virtual office, what moving up takes, and the
4
+ * field guide of species to climb through.
5
+ *
6
+ * The statusline chip says `Pro member-1e500474 amazon 종합 점수 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
14
+ * (GRADES in office-species.js), and the six species from the wolf up also
15
+ * need the delegation share at or above the company median.
16
+ *
17
+ * The personal figures come from the server's member_standing (team-sync.js
18
+ * refreshStanding): `dlg`, `medianDlg`, `scorePct`, `spent`, `weights`, `idle`
19
+ * and `next` ({ grade, pass, needDlg }). An older server sends none of them;
20
+ * the block then names the next species from the ladder and says where the
21
+ * distance will come from. Pure: no I/O, so the tests pin every wording.
22
+ */
23
+
24
+ import { GRADES, TIER_NAMES, speciesLabel } from './office-species.js';
25
+
26
+ const pct = (v) => `${Math.round(Number(v) * 100)}%`;
27
+ const money = (v) => `$${Number(v).toFixed(2)}`;
28
+ const floorPct = (g) => Math.round(g.minSr * 100);
29
+ /** The species one row up the ladder, or null on the top row and for unknown keys. */
30
+ export function nextGradeUp(key) {
31
+ const i = GRADES.findIndex((g) => g.key === key);
32
+ return i > 0 ? GRADES[i - 1] : null;
33
+ }
34
+
35
+ /**
36
+ * @param {object|null|undefined} st team.json `standing`
37
+ * @param {{ lang?: 'ko'|'en', org?: string|null }} [opts]
38
+ * @returns {string[]} lines; empty when there is no standing on record
39
+ */
40
+ export function standingGuideLines(st, { lang = 'en', org = null, team = null } = {}) {
41
+ if (!st || typeof st !== 'object' || typeof st.grade !== 'string') return [];
42
+ const ko = lang === 'ko';
43
+ const label = (k) => speciesLabel(k, lang, { emoji: true }) || k;
44
+ const animal = label(st.grade);
45
+ const ranked = Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
46
+ const period = st.rangeFrom && st.rangeTo ? ` (${st.rangeFrom} ${ko ? '~' : 'to'} ${st.rangeTo})` : '';
47
+ const where = org ? `${org} ` : '';
48
+ const has = (v) => Number.isFinite(v);
49
+ // The rank within the team, when the team is a strict part of the ranked people.
50
+ const teamName = team || st.teamName || null;
51
+ const inTeam = ranked && Number.isInteger(st.teamRank) && Number.isInteger(st.teamRanked)
52
+ && st.teamRank >= 1 && st.teamRanked >= st.teamRank && st.teamRanked < st.ranked && teamName;
53
+ const teamPlace = inTeam ? (ko ? ` · ${teamName} 팀 ${st.teamRanked}명 중 ${st.teamRank}위` : ` · team ${teamName} #${st.teamRank} of ${st.teamRanked}`) : '';
54
+ const lines = [];
55
+
56
+ if (st.grade === 'ghost' || !ranked) {
57
+ lines.push(ko
58
+ ? `순위: ${where}${animal}${period}. 이 기간에 올라온 사용 기록이 없어 순위 밖입니다. 지출이 올라오면 아래 도감의 한 종이 됩니다.`
59
+ : `Standing: ${where}${animal}${period}. No usage uploaded in this period, so no rank yet; once spend comes in you become one of the species below.`);
60
+ lines.push(...fieldGuideLines(null, lang));
61
+ return lines;
62
+ }
63
+
64
+ lines.push(ko
65
+ ? `순위: ${where}종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace} · ${animal}${period}`
66
+ : `Standing: ${where}overall score #${st.rank} of ${st.ranked}${teamPlace} · ${animal}${period}`);
67
+
68
+ // Where that rank puts you: the people ahead, or the crown.
69
+ if (st.crown) {
70
+ lines.push(ko ? ' 이번 기간 회사 1위입니다 👑' : ' #1 in the company this period 👑');
71
+ } else if (st.rank === 1 && st.ranked === 1) {
72
+ lines.push(ko
73
+ ? ' 지금은 순위에 혼자 올라 있습니다. 동료가 참여하면 경쟁이 시작됩니다.'
74
+ : ' You are the only one in the standings so far; the race starts when a colleague joins.');
75
+ } else if (st.rank === 1) {
76
+ lines.push(ko ? ' 회사 1위입니다.' : ' #1 in the company.');
77
+ } else {
78
+ lines.push(ko
79
+ ? ` 앞에 ${st.rank - 1}명이 있습니다. 1위에 오르면 👑 왕관을 씁니다.`
80
+ : ` ${st.rank - 1} ahead of you; reach #1 and you wear the crown 👑.`);
81
+ }
82
+
83
+ // What the score is made of. The weights are the server's when it sent them;
84
+ // otherwise both known sets are stated.
85
+ const w = Array.isArray(st.weights) && st.weights.length >= 2 ? st.weights : null;
86
+ if (w) {
87
+ const parts = ko
88
+ ? [`기간 지출 순위 ${pct(w[0])}`, `위임 비율 순위 ${pct(w[1])}`, ...(w[2] > 0 ? [`프롬프트 수 순위 ${pct(w[2])}`] : [])]
89
+ : [`the spend rank (${pct(w[0])})`, `the delegation-share rank (${pct(w[1])})`, ...(w[2] > 0 ? [`the prompt-count rank (${pct(w[2])})`] : [])];
90
+ lines.push(ko
91
+ ? ` 종합 점수는 ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? '와 ' : ''}${parts[parts.length - 1]}를 더한 값입니다.`
92
+ : ` The overall score adds ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? ' and ' : ''}${parts[parts.length - 1]}.`);
93
+ } else {
94
+ lines.push(ko
95
+ ? ' 종합 점수는 기간 지출 순위 62.5%와 위임 비율 순위 37.5%를 더한 값입니다. 프롬프트 수집을 켠 Enterprise 조직은 50%, 30%, 20%로 프롬프트 수 순위까지 더합니다.'
96
+ : ' 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.');
97
+ }
98
+ lines.push(ko
99
+ ? ` 지출 순위는 토큰을 더 써야 오르고 위임 비율 순위는 같은 지출에서 싼 모델에 맡기는 몫을 늘려야 오릅니다. ${speciesLabel('wolf', 'ko', { emoji: false })} 이상 여섯 종은 위임 비율이 회사 중앙값 이상이어야 합니다.`
100
+ : ` 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.`);
101
+
102
+ // The caller's own figures, when the server sent them.
103
+ if (has(st.dlg) || has(st.spent) || has(st.scorePct)) {
104
+ const parts = [];
105
+ if (has(st.spent)) parts.push(ko ? `지출 ${money(st.spent)}` : `spent ${money(st.spent)}`);
106
+ if (has(st.dlg)) {
107
+ const med = has(st.medianDlg) ? (ko ? ` (회사 중앙값 ${pct(st.medianDlg)})` : ` (company median ${pct(st.medianDlg)})`) : '';
108
+ parts.push(ko ? `위임 비율 ${pct(st.dlg)}${med}` : `delegation share ${pct(st.dlg)}${med}`);
109
+ }
110
+ if (has(st.scorePct)) parts.push(ko ? `점수 백분위 ${pct(st.scorePct)}` : `score percentile ${pct(st.scorePct)}`);
111
+ lines.push(` ${ko ? '이 컴퓨터' : 'This machine'}: ${parts.join(' · ')}`);
112
+ }
113
+
114
+ // The next species up, as the office drawer says it, with the percentile it
115
+ // starts at; the ladder alone when the server sent no distance.
116
+ const next = st.next && typeof st.next === 'object' && typeof st.next.grade === 'string' ? st.next : null;
117
+ const up = nextGradeUp(st.grade);
118
+ const floorNote = (g) => (g && g.minSr >= 0
119
+ ? (ko
120
+ ? ` (백분위 ${has(st.scorePct) ? `지금 ${pct(st.scorePct)}, ` : ''}${floorPct(g)}%부터)`
121
+ : ` (percentile ${has(st.scorePct) ? `now ${pct(st.scorePct)}, ` : ''}${floorPct(g)}% and up)`)
122
+ : '');
123
+ if (next) {
124
+ const s = label(next.grade);
125
+ const x = Math.max(1, Number(next.pass) || 0);
126
+ const c = has(st.medianDlg) ? pct(st.medianDlg) : (ko ? '알 수 없음' : 'unknown');
127
+ let text;
128
+ if (next.needDlg && !(Number(next.pass) > 0)) {
129
+ text = ko ? `위임 비율을 회사 중앙값(${c}) 이상으로 올리면 ${s}` : `raise the delegation share to the company median (${c}) to become ${s}`;
130
+ } else if (next.needDlg) {
131
+ text = ko ? `${x}명을 더 앞지르고 위임 비율이 회사 중앙값(${c}) 이상이면 ${s}` : `pass ${x} more and reach the company median delegation share (${c}) to become ${s}`;
132
+ } else {
133
+ text = ko ? `${x}명을 더 앞지르면 ${s}` : `pass ${x} more to become ${s}`;
134
+ }
135
+ lines.push(` ${ko ? '다음 등급' : 'Next species'}: ${text}${floorNote(GRADES.find((g) => g.key === next.grade))}`);
136
+ } else if (st.idle === true || st.grade === 'chick') {
137
+ lines.push(ko ? ' 다음 등급: 이 기간에 지출이 생기면 순위에 오릅니다.' : ' Next species: spend in this period puts you in the standings.');
138
+ } else if (!up) {
139
+ lines.push(ko ? ' 다음 등급: 도감에서 가장 높은 종입니다.' : ' Next species: the top species in the field guide.');
140
+ } else {
141
+ // An older server: the ladder names the species, the distance is not known.
142
+ lines.push(ko
143
+ ? ` 다음 등급: ${label(up.key)}${floorNote(up)}. 몇 명을 더 앞질러야 하는지는 팀 서버가 갱신되면 나옵니다.`
144
+ : ` Next species: ${label(up.key)}${floorNote(up)}. How many people to pass appears once the team server is updated.`);
145
+ }
146
+
147
+ lines.push(...fieldGuideLines(st.grade, lang));
148
+ return lines;
149
+ }
150
+
151
+ /**
152
+ * The field guide: every species by tier, best first, with the percentile each
153
+ * one starts at and a marker on the caller's own. Shared by the ranked and the
154
+ * unranked block, so a newcomer sees what there is to climb.
155
+ */
156
+ export function fieldGuideLines(grade, lang = 'en') {
157
+ const ko = lang === 'ko';
158
+ const lines = [ko
159
+ ? '동물 도감: 종합 점수 백분위로 30종을 나눕니다. 종 옆 숫자는 그 종이 시작되는 백분위이고 ▶ 가 지금 등급입니다.'
160
+ : 'Field guide: 30 species by overall-score percentile. The number after a species is the percentile it starts at; ▶ marks yours.'];
161
+ for (const tier of ['power', 'active', 'normal', 'low']) {
162
+ const items = GRADES.filter((g) => g.tier === tier).map((g) => {
163
+ const mark = g.key === grade ? '▶ ' : '';
164
+ const floor = g.minSr >= 0 ? ` ${floorPct(g)}` : (ko ? ' (지출 없음)' : ' (no spend)');
165
+ return `${mark}${speciesLabel(g.key, lang, { emoji: true })}${floor}`;
166
+ });
167
+ const rule = tier === 'power'
168
+ ? (ko ? ' (위임 비율이 회사 중앙값 이상이어야 함)' : ' (needs a delegation share at or above the company median)')
169
+ : '';
170
+ lines.push(` ${TIER_NAMES[tier][lang]}${rule}: ${items.join(' · ')}`);
171
+ }
172
+ return lines;
173
+ }
package/src/team-sync.js CHANGED
@@ -108,9 +108,27 @@ async function refreshStanding({ memberKey, dir, fetch, now }) {
108
108
  if (!r || typeof r !== 'object' || typeof r.grade !== 'string') return;
109
109
  const cur = loadTeamState(dir);
110
110
  if (!isJoined(cur) || cur.memberKey !== memberKey) return;
111
+ const num = (v) => (Number.isFinite(v) ? v : null);
112
+ // What the rank is made of and what the next species takes (server migration
113
+ // 20261107000100). An older server sends none of it, and `sprag team status`
114
+ // then prints the formula alone.
115
+ const guide = {
116
+ dlg: num(r.dlg), medianDlg: num(r.median_dlg), scorePct: num(r.score_pct), spent: num(r.spent),
117
+ idle: typeof r.idle === 'boolean' ? r.idle : null,
118
+ hasPrompts: typeof r.has_prompts === 'boolean' ? r.has_prompts : null,
119
+ weights: Array.isArray(r.weights) && r.weights.every(Number.isFinite) ? r.weights : null,
120
+ next: r.next && typeof r.next === 'object' && typeof r.next.grade === 'string'
121
+ ? { grade: r.next.grade, pass: num(r.next.pass) ?? 0, needDlg: !!r.next.need_dlg }
122
+ : null,
123
+ rangeFrom: typeof r.range_from === 'string' ? r.range_from : null,
124
+ rangeTo: typeof r.range_to === 'string' ? r.range_to : null,
125
+ // The same score counted within the member's own team.
126
+ teamRank: num(r.team_rank), teamRanked: num(r.team_ranked),
127
+ teamName: typeof r.team_name === 'string' && r.team_name ? r.team_name : null,
128
+ };
111
129
  saveTeamState({
112
130
  ...cur,
113
- standing: { grade: r.grade, tier: r.tier ?? null, rank: Number.isFinite(r.rank) ? r.rank : null, ranked: Number.isFinite(r.ranked) ? r.ranked : null, crown: !!r.crown, fetchedAt: now },
131
+ standing: { grade: r.grade, tier: r.tier ?? null, rank: num(r.rank), ranked: num(r.ranked), crown: !!r.crown, fetchedAt: now, ...guide },
114
132
  }, dir);
115
133
  } catch (e) {
116
134
  debug('team-sync', e); // PGRST202 "Could not find the function": an older server, ignore
@@ -130,9 +148,19 @@ export function readTeamChip({ dir = userDataDir() } = {}) {
130
148
  const st = state.standing;
131
149
  return {
132
150
  label,
151
+ // The standing is ranked across the organization, so its name says whose standings these are.
152
+ org: String(state.orgName || state.teamName || '').trim() || null,
153
+ // The license the team runs under (`pro`, `enterprise`), which leads the chip.
154
+ plan: typeof state.plan === 'string' && state.plan.trim() ? state.plan.trim() : null,
155
+ // The team, for the rank within it.
156
+ team: String(state.teamName || '').trim() || null,
133
157
  lang: userLanguage(),
134
158
  standing: st && typeof st.grade === 'string'
135
- ? { grade: st.grade, rank: Number.isFinite(st.rank) ? st.rank : null, ranked: Number.isFinite(st.ranked) ? st.ranked : null, fetchedAt: Number(st.fetchedAt) || 0 }
159
+ ? {
160
+ grade: st.grade, rank: Number.isFinite(st.rank) ? st.rank : null, ranked: Number.isFinite(st.ranked) ? st.ranked : null,
161
+ teamRank: Number.isFinite(st.teamRank) ? st.teamRank : null, teamRanked: Number.isFinite(st.teamRanked) ? st.teamRanked : null,
162
+ fetchedAt: Number(st.fetchedAt) || 0,
163
+ }
136
164
  : null,
137
165
  };
138
166
  } catch (e) { debug('team-sync', e); return null; }