sprag-cli 3.131.0 β†’ 3.132.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.
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The warnings the sprag statusline is showing right now, for `sprag bar`.
3
+ *
4
+ * Two kinds, both read from files the statusline already writes:
5
+ * - cap: an account limit window at or past CAP_PRESSURE_CRITICAL, taken from
6
+ * the limits the snapshot already holds (the statusline's `🚨 7D 92%` chip).
7
+ * - issue: the `⚠ ...` chip in last-chip.json, with the advice registered for
8
+ * it in advice.js and the detail line of its newest history event. The
9
+ * context-size chip is left out (QUIET_CHIPS).
10
+ *
11
+ * last-chip.json keeps the last chip forever once every session has exited, so
12
+ * an issue only counts while some statusline has rendered in the last two
13
+ * minutes (statusline-last.json). Nothing here writes a file (readRecent makes
14
+ * sure the history folder exists, and only while an issue chip is active), and
15
+ * nothing throws.
16
+ */
17
+
18
+ import { userDataDir } from './paths.js';
19
+ import { userLanguage } from './config.js';
20
+ import { CAP_PRESSURE_CRITICAL } from './caps-cache.js';
21
+ import { readChipState, readRecent, detailKo } from './history.js';
22
+ import { newestRenderAt } from './statusline-guard.js';
23
+ import { findLatestWarning } from './commands/last.js';
24
+ import { ISSUE_MESSAGES, ISSUE_TIPS, CHIP_TO_CODES, CAP_TIPS } from './advice.js';
25
+
26
+ /**
27
+ * Chips the statusline shows that `sprag bar` does not raise as a warning. The
28
+ * context-size chip is on whenever any request of the last day passed 500k,
29
+ * which with 1M sessions is most days, and a mark that is always lit says
30
+ * nothing. Every row already carries its own context use. While this chip is
31
+ * the statusline's pick it also hides whatever lower-priority chip is under it,
32
+ * because the statusline records one chip at a time.
33
+ */
34
+ export const QUIET_CHIPS = new Set(['⚠ Ctx 500k+', '⚠ Ctx 200k+', '⚠ 1M ON']);
35
+
36
+ /** A chip older than this with no render since is a leftover of an exited session. */
37
+ const RENDER_FRESH_MS = 120_000;
38
+
39
+ function capItems(limits, lang) {
40
+ const ko = lang === 'ko';
41
+ const out = [];
42
+ for (const w of Array.isArray(limits?.windows) ? limits.windows : []) {
43
+ if (!w || !Number.isFinite(w.usedPct) || w.usedPct < CAP_PRESSURE_CRITICAL) continue;
44
+ const pct = Math.round(w.usedPct);
45
+ out.push({
46
+ kind: 'cap',
47
+ chip: `🚨 ${w.label} ${pct}%`,
48
+ level: 'critical',
49
+ since: null,
50
+ detail: null,
51
+ resetsAt: Number.isFinite(w.resetsAt) ? w.resetsAt : null,
52
+ advice: [{
53
+ code: 'CAP',
54
+ title: ko ? `${w.label} ν•œλ„λ₯Ό ${pct}% μΌμŠ΅λ‹ˆλ‹€` : `${w.label} limit is ${pct}% used`,
55
+ explain: null,
56
+ tip: CAP_TIPS[lang] ?? CAP_TIPS.en,
57
+ actions: [{ label: ko ? 'μ‹€ν–‰' : 'Run', commands: ['sprag handoff'] }],
58
+ }],
59
+ });
60
+ }
61
+ return out;
62
+ }
63
+
64
+ function adviceFor(code, lang) {
65
+ const msg = ISSUE_MESSAGES[code];
66
+ if (!msg) return null;
67
+ const pick = (en, ko) => (lang === 'ko' && ko ? ko : en);
68
+ const actions = typeof msg.actions === 'function' ? msg.actions() : msg.actions || [];
69
+ return {
70
+ code,
71
+ title: pick(msg.title, msg.titleKo),
72
+ explain: pick(msg.explain, msg.explainKo) ?? null,
73
+ tip: ISSUE_TIPS[code]?.[lang] ?? ISSUE_TIPS[code]?.en ?? null,
74
+ actions: actions.map((a) => ({
75
+ label: pick(a.label, a.labelKo),
76
+ commands: (a.commands ?? []).map((c, i) => pick(c, a.commandsKo?.[i])),
77
+ })),
78
+ };
79
+ }
80
+
81
+ function issueItem({ chipState, history, lang }) {
82
+ const chip = chipState.chip;
83
+ let event = null;
84
+ try { event = findLatestWarning(history(), CHIP_TO_CODES); } catch { event = null; }
85
+ if (event && event.chip !== chip) event = null;
86
+ const codes = [...(CHIP_TO_CODES[chip] ?? []), ...(event?.codes ?? [])].filter((c, i, all) => all.indexOf(c) === i);
87
+ const advice = [];
88
+ for (const code of codes) {
89
+ try {
90
+ const a = adviceFor(code, lang);
91
+ if (a) advice.push(a);
92
+ } catch { /* one broken entry must not hide the others */ }
93
+ }
94
+ const ts = Date.parse(chipState.ts);
95
+ let detail = event?.detail ?? null;
96
+ if (detail && lang === 'ko') detail = detailKo(detail);
97
+ return {
98
+ kind: 'issue',
99
+ chip,
100
+ level: 'warn',
101
+ since: Number.isFinite(ts) ? ts : null,
102
+ detail,
103
+ resetsAt: null,
104
+ advice,
105
+ };
106
+ }
107
+
108
+ /** @returns {object[]} rate-limit warnings first, then the issue chip; [] when none */
109
+ export function currentWarnings({
110
+ dataDir = userDataDir(),
111
+ now = Date.now(),
112
+ lang = userLanguage(),
113
+ limits = null,
114
+ chipState = readChipState(dataDir),
115
+ lastRenderAt = newestRenderAt({ dir: dataDir }),
116
+ history = () => readRecent(1),
117
+ quiet = QUIET_CHIPS,
118
+ } = {}) {
119
+ const out = [];
120
+ try { out.push(...capItems(limits, lang)); } catch { /* keep the issue chip */ }
121
+ try {
122
+ const chip = chipState?.chip;
123
+ if (typeof chip === 'string' && chip && !quiet.has(chip) && Number.isFinite(lastRenderAt) && now - lastRenderAt <= RENDER_FRESH_MS) {
124
+ out.push(issueItem({ chipState, history, lang }));
125
+ }
126
+ } catch { /* no issue item */ }
127
+ return out;
128
+ }
package/src/bar-app.js ADDED
@@ -0,0 +1,330 @@
1
+ /**
2
+ * The macOS menu bar app: where it lives, when it is compiled, and how it is
3
+ * started and stopped.
4
+ *
5
+ * The package ships the Swift source (mac/SpragBar.swift) and never a binary.
6
+ * The first session on a Mac with the Xcode command line tools compiles it
7
+ * once per sprag version into <dataDir>/bar/<version>/sprag-bar and starts it.
8
+ * `sprag bar off` turns the whole thing off, and `sprag bar on` brings it back.
9
+ *
10
+ * Every outside effect goes through an injectable dependency (run, spawn, kill,
11
+ * exists, clock, dataDir, version), so the tests start no process and touch no
12
+ * real folder. Every read of a state file tolerates a missing or corrupt file.
13
+ */
14
+
15
+ import * as childProcess from 'node:child_process';
16
+ import {
17
+ chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,
18
+ } from 'node:fs';
19
+ import { createRequire } from 'node:module';
20
+ import { createHash } from 'node:crypto';
21
+ import { basename, join } from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { CLI_ENTRY, DETACHED_CHILD_VAR, isDetachedChild, spawnDetachedCli } from './cli-entry.js';
24
+ import { loadConfig, saveConfig } from './config.js';
25
+ import { envVar } from './env.js';
26
+ import { userDataDir } from './paths.js';
27
+ import { writeStateFile } from './state-file.js';
28
+
29
+ export const BAR_SOURCE = fileURLToPath(new URL('../mac/SpragBar.swift', import.meta.url));
30
+
31
+ const PKG_VERSION = createRequire(import.meta.url)('../package.json').version;
32
+
33
+ /** A build lock older than this is a crashed build. */
34
+ export const LOCK_STALE_MS = 10 * 60 * 1000;
35
+ /** A failed build of this source is not retried at session start for this long. */
36
+ export const BUILD_RETRY_MS = 24 * 60 * 60 * 1000;
37
+ const BUILD_TIMEOUT_MS = 5 * 60 * 1000;
38
+ const ERROR_TAIL = 600;
39
+ const BINARY_NAME = 'sprag-bar';
40
+
41
+ /** The bar is on unless the user ran `sprag bar off`. */
42
+ export function barEnabled(cfg = loadConfig()) {
43
+ return cfg?.bar !== false;
44
+ }
45
+
46
+ /** Off stores `bar: false`; on removes the key so the default applies again. */
47
+ export function setBarEnabled(on) {
48
+ const cfg = loadConfig();
49
+ if (on) delete cfg.bar;
50
+ else cfg.bar = false;
51
+ saveConfig(cfg);
52
+ }
53
+
54
+ const buildIds = new Map();
55
+
56
+ /**
57
+ * What a compiled copy is keyed by: the first 12 hex digits of the source's
58
+ * hash, not the sprag version. sprag ships often and the app changes rarely, so
59
+ * keying by version would spend half a minute compiling and restart the app on
60
+ * every upgrade for nothing. An unreadable source falls back to the version.
61
+ */
62
+ export function barBuildId(source = BAR_SOURCE) {
63
+ if (!buildIds.has(source)) {
64
+ let id = PKG_VERSION;
65
+ try { id = createHash('sha256').update(readFileSync(source)).digest('hex').slice(0, 12); } catch { /* keep the version */ }
66
+ buildIds.set(source, id);
67
+ }
68
+ return buildIds.get(source);
69
+ }
70
+
71
+ /** `version` is the build id above; the name is kept because the app's pid file calls it that. */
72
+ export function barPaths({ dataDir = userDataDir(), version = barBuildId() } = {}) {
73
+ const dir = join(dataDir, 'bar');
74
+ return {
75
+ dataDir,
76
+ dir,
77
+ version,
78
+ binary: join(dir, version, BINARY_NAME),
79
+ pidFile: join(dataDir, 'bar-app.json'),
80
+ buildState: join(dataDir, 'bar-build.json'),
81
+ buildLock: join(dataDir, 'bar-build.lock'),
82
+ };
83
+ }
84
+
85
+ /** Run a command to completion. Never throws: a missing program is a non-zero status. */
86
+ function defaultRun(cmd, args, opts = {}) {
87
+ const r = childProcess.spawnSync(cmd, args, { encoding: 'utf8', windowsHide: true, ...opts });
88
+ return {
89
+ status: r.error ? (r.status ?? -1) : r.status,
90
+ stdout: r.stdout ?? '',
91
+ stderr: r.stderr ?? '',
92
+ error: r.error ?? null,
93
+ };
94
+ }
95
+
96
+ const runOf = (deps) => deps.run ?? defaultRun;
97
+ const existsOf = (deps) => deps.exists ?? existsSync;
98
+ const clockOf = (deps) => deps.clock ?? Date.now;
99
+ const killOf = (deps) => deps.kill ?? ((pid, signal) => process.kill(pid, signal));
100
+
101
+ function readJson(file) {
102
+ try {
103
+ const v = JSON.parse(readFileSync(file, 'utf8'));
104
+ return v && typeof v === 'object' ? v : null;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ /** The last build result, or null when none was recorded or the file is unreadable. */
111
+ export function readBuildState(deps = {}) {
112
+ return readJson(barPaths(deps).buildState);
113
+ }
114
+
115
+ function writeBuildState(paths, state) {
116
+ try { writeStateFile(paths.buildState, `${JSON.stringify(state)}\n`); } catch { /* the state only throttles retries */ }
117
+ }
118
+
119
+ /**
120
+ * The compiler, or null. `xcode-select -p` runs first and alone: when the
121
+ * command line tools are missing, a bare `swiftc` or `xcrun` pops up a system
122
+ * install dialog on the user's screen, so neither runs unless it succeeds.
123
+ */
124
+ export function findSwiftc(deps = {}) {
125
+ const run = runOf(deps);
126
+ const sel = run('xcode-select', ['-p']);
127
+ if (sel.error || sel.status !== 0) return null;
128
+ const found = run('xcrun', ['--find', 'swiftc']);
129
+ if (found.error || found.status !== 0) return null;
130
+ const path = String(found.stdout ?? '').trim();
131
+ return path && existsOf(deps)(path) ? path : null;
132
+ }
133
+
134
+ /** The running app, `{ pid, version }`, or null when the pid file is missing, unreadable or stale. */
135
+ export function barRunning(deps = {}) {
136
+ const info = readJson(barPaths(deps).pidFile);
137
+ const pid = info?.pid;
138
+ if (!Number.isInteger(pid) || pid <= 0) return null;
139
+ try {
140
+ killOf(deps)(pid, 0);
141
+ } catch {
142
+ return null;
143
+ }
144
+ return { pid, version: typeof info.version === 'string' ? info.version : null };
145
+ }
146
+
147
+ /** SIGTERM to the running app, only after `ps` confirms the pid is still a sprag-bar. True when a signal went out. */
148
+ export function stopBar(deps = {}) {
149
+ const running = barRunning(deps);
150
+ if (!running) return false;
151
+ const ps = runOf(deps)('ps', ['-p', String(running.pid), '-o', 'comm=']);
152
+ if (ps.error || ps.status !== 0) return false;
153
+ if (basename(String(ps.stdout ?? '').trim()) !== BINARY_NAME) return false;
154
+ try {
155
+ killOf(deps)(running.pid, 'SIGTERM');
156
+ return true;
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ /** Age of the build lock in ms, or null when there is none. */
163
+ function lockAge(paths, now) {
164
+ try {
165
+ return now - statSync(paths.buildLock).mtimeMs;
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ function takeLock(paths, now) {
172
+ mkdirSync(paths.dataDir, { recursive: true });
173
+ for (let attempt = 0; attempt < 2; attempt++) {
174
+ try {
175
+ writeFileSync(paths.buildLock, String(process.pid), { flag: 'wx' });
176
+ return true;
177
+ } catch (e) {
178
+ if (e?.code !== 'EEXIST') throw e;
179
+ const age = lockAge(paths, now);
180
+ if (age !== null && age < LOCK_STALE_MS) return false;
181
+ try { rmSync(paths.buildLock, { force: true }); } catch { /* the retake below fails and reports it */ }
182
+ }
183
+ }
184
+ return false;
185
+ }
186
+
187
+ function pruneOtherVersions(paths) {
188
+ try {
189
+ for (const entry of readdirSync(paths.dir, { withFileTypes: true })) {
190
+ if (entry.isDirectory() && entry.name !== paths.version) {
191
+ rmSync(join(paths.dir, entry.name), { recursive: true, force: true });
192
+ }
193
+ }
194
+ } catch { /* leftovers are only disk space */ }
195
+ }
196
+
197
+ /**
198
+ * Compile the Swift source for this version, in the foreground of this process.
199
+ * Returns `{ ok, ms, error }`, or `{ ok: false, skipped: 'building' }` when
200
+ * another build holds a fresh lock.
201
+ */
202
+ export function buildBar(deps = {}) {
203
+ const paths = barPaths(deps);
204
+ const clock = clockOf(deps);
205
+ const started = clock();
206
+ if (!takeLock(paths, started)) return { ok: false, skipped: 'building' };
207
+ try {
208
+ const swiftc = findSwiftc(deps);
209
+ if (!swiftc) {
210
+ writeBuildState(paths, { version: paths.version, ok: false, at: clock(), ms: 0, error: 'no-toolchain' });
211
+ return { ok: false, ms: 0, error: 'no-toolchain' };
212
+ }
213
+ const folder = join(paths.dir, paths.version);
214
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
215
+ const tmp = `${paths.binary}.tmp-${process.pid}`;
216
+ // The compiler inside the toolchain cannot find the SDK when run by its full path ("unable to load standard
217
+ // library"). /usr/bin/swiftc is the system's front door to the same compiler and sets the SDK up. Running it is
218
+ // safe here: findSwiftc has just confirmed developer tools are installed, so it cannot pop the install dialog.
219
+ const compiler = existsOf(deps)('/usr/bin/swiftc') ? '/usr/bin/swiftc' : swiftc;
220
+ const r = runOf(deps)(compiler, ['-O', '-swift-version', '5', deps.source ?? BAR_SOURCE, '-o', tmp], {
221
+ timeout: BUILD_TIMEOUT_MS, stdio: 'pipe', windowsHide: true, maxBuffer: 16 * 1024 * 1024,
222
+ });
223
+ let error = null;
224
+ if (r.error) error = r.error.code === 'ETIMEDOUT' ? 'timeout after 5 minutes' : String(r.error.message ?? r.error);
225
+ else if (r.status !== 0) error = String(r.stderr ?? '').trim().slice(-ERROR_TAIL) || `swiftc exited with status ${r.status}`;
226
+ if (!error) {
227
+ try {
228
+ renameSync(tmp, paths.binary);
229
+ chmodSync(paths.binary, 0o755);
230
+ } catch (e) {
231
+ error = String(e?.message ?? e).slice(-ERROR_TAIL);
232
+ }
233
+ }
234
+ if (error) {
235
+ try { rmSync(tmp, { force: true }); } catch { /* a stray temp file is only disk space */ }
236
+ error = error.slice(-ERROR_TAIL);
237
+ }
238
+ const ms = clock() - started;
239
+ writeBuildState(paths, { version: paths.version, ok: !error, at: clock(), ms, error });
240
+ if (!error) pruneOtherVersions(paths);
241
+ return { ok: !error, ms, error };
242
+ } finally {
243
+ try { rmSync(paths.buildLock, { force: true }); } catch { /* a stale lock expires by itself */ }
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The environment the app starts with: the caller's, minus what marks a Claude
249
+ * Code session. The app attributes processes to Claude sessions by those
250
+ * variables, so an app that inherited them would count itself as that
251
+ * session's own work, and later as a leftover of a session that has ended.
252
+ * The detached-child marker goes too, or the app's own `sprag` calls would
253
+ * refuse to start background work.
254
+ */
255
+ export function barChildEnv(env = process.env) {
256
+ const out = { ...env };
257
+ for (const key of Object.keys(out)) {
258
+ if (key.startsWith('CLAUDE_CODE_')) delete out[key];
259
+ }
260
+ for (const key of ['CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_EFFORT', 'AI_AGENT', DETACHED_CHILD_VAR]) {
261
+ delete out[key];
262
+ }
263
+ return out;
264
+ }
265
+
266
+ /** Start the compiled app detached from this process. The caller has checked the binary exists. */
267
+ export function launchBar(deps = {}) {
268
+ const paths = barPaths(deps);
269
+ const spawn = deps.spawn ?? childProcess.spawn;
270
+ const child = spawn(paths.binary, [
271
+ '--node', deps.execPath ?? process.execPath,
272
+ '--cli', deps.cliEntry ?? CLI_ENTRY,
273
+ '--data-dir', paths.dataDir,
274
+ '--version-tag', paths.version,
275
+ ], { detached: true, stdio: 'ignore', windowsHide: true, env: barChildEnv(deps.env ?? process.env) });
276
+ // A failed start (the binary vanished, no execute bit) must not become an unhandled error event.
277
+ if (typeof child.on === 'function') child.on('error', () => {});
278
+ child.unref();
279
+ }
280
+
281
+ /**
282
+ * Session start: make sure the app is running, building it first when needed.
283
+ * Returns why it did what it did and never throws. 'started', 'restarted' and
284
+ * 'running' mean the app is up; 'building' means a background build will start it.
285
+ */
286
+ export function ensureBar({ platform = process.platform, env = process.env, cfg, now = Date.now(), ...deps } = {}) {
287
+ try {
288
+ if (platform !== 'darwin') return 'not-mac';
289
+ if (isDetachedChild(env)) return 'child';
290
+ if (envVar('NO_BAR', env) === '1') return 'off';
291
+ if (!barEnabled(cfg)) return 'off';
292
+ const d = { ...deps, env };
293
+ const paths = barPaths(d);
294
+ let restart = false;
295
+ const running = barRunning(d);
296
+ if (running) {
297
+ if (running.version === paths.version) return 'running';
298
+ stopBar(d);
299
+ restart = true;
300
+ }
301
+ if (existsOf(d)(paths.binary)) {
302
+ launchBar(d);
303
+ return restart ? 'restarted' : 'started';
304
+ }
305
+ const state = readBuildState(d);
306
+ // A compile that failed is not retried for a day. A missing toolchain is looked for again every time:
307
+ // the check costs one short command, and installing the tools should bring the app at the next session.
308
+ if (state && state.version === paths.version && state.ok === false && state.error !== 'no-toolchain'
309
+ && Number.isFinite(state.at) && now - state.at < BUILD_RETRY_MS) return 'build-failed';
310
+ const age = lockAge(paths, now);
311
+ if (age !== null && age < LOCK_STALE_MS) return 'building';
312
+ if (!findSwiftc(d)) {
313
+ writeBuildState(paths, { version: paths.version, ok: false, at: now, ms: 0, error: 'no-toolchain' });
314
+ return 'no-toolchain';
315
+ }
316
+ (d.spawnCli ?? spawnDetachedCli)(['bar', 'build', '--then-launch'], { env });
317
+ return 'building';
318
+ } catch {
319
+ return 'error';
320
+ }
321
+ }
322
+
323
+ /** Uninstall: stop the app and delete everything this module wrote under the data directory. */
324
+ export function removeBarFiles(deps = {}) {
325
+ const paths = barPaths(deps);
326
+ try { stopBar(deps); } catch { /* the files go regardless */ }
327
+ for (const target of [paths.dir, paths.pidFile, paths.buildState, paths.buildLock]) {
328
+ try { rmSync(target, { recursive: true, force: true }); } catch { /* best effort */ }
329
+ }
330
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Every rule source a menu bar app lists, for `sprag bar --rules`.
3
+ *
4
+ * This file only reads. A rule is changed or removed through the command that
5
+ * already owns it, so each file keeps a single writer:
6
+ * global.rules[].index sprag harness rm <N> --global
7
+ * projects[].rules[] sprag harness rm <N>, run inside that project
8
+ * preset.pending[].id sprag seed accept <id> --global | sprag seed skip <id>
9
+ * preset.rules[].id sprag seed skip <id>
10
+ * model.rules[].index sprag route-scan rules rm <N>
11
+ * team.rules set by the team admin, read-only here
12
+ *
13
+ * Every source is read inside its own try/catch: a failing one gives its empty
14
+ * shape and never fails the command. Each parameter below is a reader (a
15
+ * function) whose default is the real one, so a test never touches the real
16
+ * home folder.
17
+ */
18
+
19
+ import { existsSync } from 'node:fs';
20
+ import os from 'node:os';
21
+ import { basename } from 'node:path';
22
+ import { userLanguage } from './config.js';
23
+ import { harnessListRules, findProjectRoot, RATCHET_TOKEN_BUDGET } from './harness.js';
24
+ import { readClaudeSessions } from './agent-activity.js';
25
+ import { claudeConfigDir } from './commands/panel.js';
26
+ import { defaultIsAlive } from './statusline-guard.js';
27
+ import { presetRatchetPath, acceptedGlobalPresets } from './preset-ratchet.js';
28
+ import { pendingSeeds } from './seed-rules.js';
29
+ import { loadModelRules } from './model-rules.js';
30
+ import { routingEnabled } from './routing-switch.js';
31
+ import { loadTeamState } from './team-sync.js';
32
+ import { isJoined, readTeamRulesCache, teamRuleText } from './team-ratchet.js';
33
+
34
+ const safe = (fn, fallback) => { try { return fn(); } catch { return fallback; } };
35
+
36
+ /** Project roots of the running Claude Code sessions. */
37
+ function runningRoots() {
38
+ const roots = new Set();
39
+ for (const file of readClaudeSessions(claudeConfigDir())) {
40
+ if (typeof file.cwd !== 'string' || !file.cwd || !defaultIsAlive(file.pid)) continue;
41
+ const root = safe(() => findProjectRoot(file.cwd), null);
42
+ if (root) roots.add(root);
43
+ }
44
+ return [...roots];
45
+ }
46
+
47
+ const EMPTY_FILE = () => ({ path: null, exists: false, bytes: 0, tokens: 0, rules: [] });
48
+
49
+ function ratchetFile(listRules, { root, scope }) {
50
+ return safe(() => {
51
+ const r = listRules({ root, scope });
52
+ const bytes = Number.isFinite(r.bytes) ? r.bytes : 0;
53
+ return {
54
+ path: r.path ?? null,
55
+ exists: r.path ? existsSync(r.path) : false,
56
+ bytes,
57
+ // The same 4 bytes per token the ratchet size check uses.
58
+ tokens: Math.round(bytes / 4),
59
+ rules: (r.rules ?? []).map(({ index, text, date, tags }) => ({ index, text, date: date ?? null, tags: tags ?? [] })),
60
+ };
61
+ }, EMPTY_FILE());
62
+ }
63
+
64
+ export function collectRules({
65
+ lang = userLanguage(),
66
+ roots = runningRoots,
67
+ listRules = harnessListRules,
68
+ presetPath = presetRatchetPath,
69
+ presets = acceptedGlobalPresets,
70
+ pending = pendingSeeds,
71
+ modelRules = () => loadModelRules().rules,
72
+ routing = routingEnabled,
73
+ teamState = loadTeamState,
74
+ teamCache = readTeamRulesCache,
75
+ } = {}) {
76
+ const home = os.homedir();
77
+
78
+ // A session started in the home folder has the global file as its project file.
79
+ const projects = safe(() => roots(), []).filter((root) => root !== home).map((root) => ({
80
+ root, name: basename(root), ...ratchetFile(listRules, { root, scope: 'project' }),
81
+ })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.root < b.root ? -1 : a.root > b.root ? 1 : 0));
82
+
83
+ const preset = {
84
+ path: safe(() => presetPath() ?? null, null),
85
+ rules: safe(() => presets({ lang }).map((p) => ({ id: p.id, text: p.text })), []),
86
+ pending: safe(() => pending({ lang, root: home })
87
+ .filter((s) => s.kind === 'ratchet')
88
+ .map((s) => ({ id: s.id, text: s.ruleText })), []),
89
+ };
90
+
91
+ const model = {
92
+ enabled: safe(() => !!routing(), false),
93
+ // index is the 1-based position `sprag route-scan rules` prints and `rules rm <N>` takes.
94
+ rules: safe(() => modelRules().map((r, i) => ({
95
+ index: i + 1,
96
+ scope: r.scope ?? null,
97
+ root: r.targetRoot ?? null,
98
+ label: lang === 'ko' ? r.label : (r.labelEn ?? r.label),
99
+ tier: r.tier ?? null,
100
+ status: r.status ?? null,
101
+ text: r.rule ?? '',
102
+ example: r.example ?? null,
103
+ count: r.count ?? null,
104
+ savedUsd: r.savedUsd ?? null,
105
+ })), []),
106
+ };
107
+
108
+ const team = {
109
+ joined: safe(() => isJoined(teamState()), false),
110
+ rules: safe(() => {
111
+ const cache = teamCache();
112
+ const removed = new Set(Array.isArray(cache?.removed) ? cache.removed : []);
113
+ const textOf = (r) => teamRuleText(r, { lang });
114
+ const found = (Array.isArray(cache?.rules) ? cache.rules : [])
115
+ .filter((r) => r && textOf(r) && !removed.has(r.id));
116
+ return [...found.filter((r) => r.level === 'org'), ...found.filter((r) => r.level !== 'org')].map((r) => ({
117
+ id: r.id ?? null,
118
+ level: r.level === 'org' ? 'org' : 'team',
119
+ scope: r.scope === 'model' ? 'model' : 'ratchet',
120
+ text: textOf(r).replace(/\s*\n\s*/g, ' '),
121
+ }));
122
+ }, []),
123
+ };
124
+
125
+ return {
126
+ budgetTokens: RATCHET_TOKEN_BUDGET,
127
+ global: ratchetFile(listRules, { root: home, scope: 'global' }),
128
+ projects,
129
+ preset,
130
+ model,
131
+ team,
132
+ };
133
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The settings a menu bar app shows, for `sprag bar --settings`.
3
+ *
4
+ * This file only reads. A change goes through the command that already owns the
5
+ * setting, so each stored value keeps a single writer:
6
+ * routing.enabled sprag routing on | off
7
+ * routing.relaxed sprag routing relax | relax off
8
+ * statusline.compact sprag mode compact=0..3
9
+ * statusline.labels sprag mode icon | narrow | text
10
+ * statusline.timer sprag mode timer | no-timer
11
+ * language sprag mode lang=en | lang=ko
12
+ * team.displayName sprag team name "<name>"
13
+ * compactWindow.value sprag compact-window set --global --all-models --value <n>
14
+ * compactWindow.warn sprag compact-window on | off
15
+ */
16
+
17
+ import { loadConfig, statuslineDefaults, userLanguage } from './config.js';
18
+ import { routingEnabled, isRelaxed, relaxUntil } from './routing-switch.js';
19
+ import { loadTeamState, isJoined } from './team-sync.js';
20
+ import { compactWindowStatus, compactWindowWarningEnabled } from './compact-window.js';
21
+ import { latestLiveWindow, latestLiveModel } from './ctx-window-cache.js';
22
+
23
+ /** The compact window status of the folder the command runs in, or null when any reader fails. */
24
+ function readCompact() {
25
+ try {
26
+ const guard = (fn) => { try { return fn(); } catch { return null; } };
27
+ return compactWindowStatus({ root: process.cwd(), liveWindow: guard(latestLiveWindow), liveModel: guard(latestLiveModel) });
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
34
+
35
+ /** Never throws: every reader below falls back to its default on a missing or broken file. */
36
+ export function collectSettings({
37
+ cfg = loadConfig(),
38
+ statusline = statuslineDefaults(),
39
+ language = userLanguage(),
40
+ team = loadTeamState(),
41
+ now = Date.now(),
42
+ compact = readCompact(),
43
+ } = {}) {
44
+ const relaxed = isRelaxed(cfg, now);
45
+ const joined = isJoined(team);
46
+ return {
47
+ routing: {
48
+ enabled: routingEnabled(cfg),
49
+ relaxed,
50
+ // Epoch ms while delegation is widened; a deadline already past reads as not relaxed.
51
+ relaxUntil: relaxed ? relaxUntil(cfg) : null,
52
+ },
53
+ statusline: {
54
+ compact: statusline.compactLevel,
55
+ labels: statusline.labels,
56
+ timer: statusline.timer,
57
+ },
58
+ language,
59
+ team: {
60
+ joined,
61
+ teamName: joined ? text(team.teamName) : null,
62
+ displayName: joined ? text(team.displayName) : null,
63
+ },
64
+ compactWindow: compact ? {
65
+ is1m: compact.is1m,
66
+ value: compact.window ?? null,
67
+ auto: compact.windowAuto,
68
+ source: compact.windowSource ?? null,
69
+ modelKey: compact.windowModelKey ?? null,
70
+ ok: compact.ok,
71
+ reason: compact.reason,
72
+ recommended: compact.recommended,
73
+ min: compact.recommendedMin,
74
+ max: compact.recommendedMax,
75
+ warn: compactWindowWarningEnabled(cfg),
76
+ } : null,
77
+ };
78
+ }