sprag-cli 3.106.0 → 3.107.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.
@@ -36,9 +36,10 @@ import { userDataDir } from './paths.js';
36
36
  import { userLanguage } from './config.js';
37
37
  import { agentPhrase, agentPhraseEn, resolveAgentName, agentForRule, TIER_MODEL } from './agents.js';
38
38
  import { writeStateFile } from './state-file.js';
39
+ import { safeExcerpt } from './redact.js';
39
40
  import { signedUsd } from './money.js';
40
41
  import { implementationDelegationRule } from './implementation-delegation.js';
41
- import { routingEnabled, routingOffRatchetText } from './routing-switch.js';
42
+ import { routingEnabled, routingOffRatchetText, delegationGrade, normalizeDelegationGrade, gradeKeepsRule, relaxUntil, relaxClock } from './routing-switch.js';
42
43
 
43
44
  // Post-promotion delegated-category error rate above this flags the rule
44
45
  // for review (rule-health). Calibrated against local T0 avg error incidence.
@@ -154,7 +155,9 @@ export function composeRuleText(baseText, rule, lang = userLanguage()) {
154
155
  */
155
156
  const EXAMPLE_MAX = 30;
156
157
  function shortExample(text) {
157
- const one = String(text || '').replace(/\s+/g, ' ').trim();
158
+ // Masked first, because a registry written by an older version may still hold
159
+ // a raw prompt excerpt, and this is the point where it reaches ratchet-model.md.
160
+ const one = safeExcerpt(text, Infinity).trim();
158
161
  return one.length <= EXAMPLE_MAX ? one : `${one.slice(0, EXAMPLE_MAX - 1)}…`;
159
162
  }
160
163
 
@@ -235,7 +238,18 @@ export function ruleForProject(rules, tier, category, projectDir) {
235
238
  return promotedHere || firstGlobal;
236
239
  }
237
240
 
241
+ /** The registry keeps the user's own words as rule examples; secrets and personal data never go to disk. */
242
+ function maskExamples(data) {
243
+ for (const r of data?.rules || []) {
244
+ for (const key of ['example', 'exampleEn']) {
245
+ if (typeof r?.[key] === 'string' && r[key]) r[key] = safeExcerpt(r[key], 80);
246
+ }
247
+ }
248
+ return data;
249
+ }
250
+
238
251
  export function saveModelRules(data) {
252
+ maskExamples(data);
239
253
  writeStateFile(modelRulesPath(), JSON.stringify(data, null, 2) + '\n');
240
254
  }
241
255
 
@@ -274,11 +288,22 @@ export function removeModelRule(index1) {
274
288
  * to, or null for the global file, which may only name agents the user
275
289
  * directory holds (see agentExists). Left out, it is the current directory.
276
290
  */
277
- export function renderModelRatchet(rules, lang = userLanguage(), { root } = {}) {
291
+ export function renderModelRatchet(rules, lang = userLanguage(), { root, grade = delegationGrade(), relaxUntilMs = relaxUntil() } = {}) {
278
292
  const ko = lang === 'ko';
293
+ // The same T2 filter the prompt hook applies (routeMatch), so the file and
294
+ // the hook do not tell the model different things. At grade 'quality' a T2
295
+ // rule survives only for paste, read and translate.
296
+ rules = rules.filter((r) => gradeKeepsRule(grade, r));
297
+ // Only a relaxed window gets a line. The default behaviour is not described.
298
+ const relaxed = normalizeDelegationGrade(grade) === 'cost';
299
+ const clock = relaxed && typeof relaxUntilMs === 'number' ? relaxClock(relaxUntilMs) : null;
300
+ const relaxLine = !relaxed ? [] : lang === 'ko'
301
+ ? [`이번 한도 창${clock ? `(${clock}까지)` : ''}은 위임 범위를 넓혀 둔 상태입니다. 판단형 일도 원인 진단, 감사, 보안이 아니면 위임할 수 있습니다.`, '']
302
+ : [`This limit window${clock ? ` (until ${clock})` : ''} is widened for delegation. Judgement work may be delegated too unless it is root-cause diagnosis, an audit, or security.`, ''];
279
303
  const lines = ko ? [
280
304
  '# Model-Fitting Ratchet (sprag 자동 관리)',
281
305
  '',
306
+ ...relaxLine,
282
307
  '로그 기반 티어 위임 룰. 이 파일은 route-scan이 매 스캔마다 통째로 재생성하므로',
283
308
  '직접 수정하지 마세요 — 목록/제거: `sprag route-scan rules [rm <N>]`.',
284
309
  '',
@@ -314,6 +339,12 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
314
339
  '- 사용자만 아는 맥락(이미 반려된 후보, 앞서 정한 조건)은 위임 지시문에 적습니다.',
315
340
  ' 서브에이전트는 그 맥락을 볼 수 없어서 effort를 올려도 찾지 못합니다(실측: effort를',
316
341
  ' 바꿔 9회 돌렸고 9회 모두 반려된 후보를 다시 추천했습니다).',
342
+ '- 개선점이나 권고를 내는 검토, 감사, 원인 진단, 검색이 필요한 조사, 무엇이 "없다"고',
343
+ ' 단정해야 하는 조회, 출력을 보고 더 볼 곳을 정해야 하는 점검은 결론이 판단입니다.',
344
+ ' 이런 일은 위임하지 않고 메인이 맡습니다. 세션이 Sonnet이면 Opus(effort high)로',
345
+ ' 올립니다. effort xhigh는 권하지 않습니다(판단형 10건 실측에서 틀린 주장이 3개에서',
346
+ ' 11개로 늘었습니다). 메인 세션의 effort가 low나 medium이면 판단 부분을 Opus effort high',
347
+ ' 서브에이전트에 맡기고 사용자에게 /effort high를 한 줄로 알립니다.',
317
348
  '',
318
349
  '## 티어 판별 기준 (모든 룰에 공통 적용)',
319
350
  '',
@@ -357,6 +388,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
357
388
  ] : [
358
389
  '# Model-Fitting Ratchet (managed by sprag)',
359
390
  '',
391
+ ...relaxLine,
360
392
  'Log-derived tier delegation rules. route-scan regenerates this file in full',
361
393
  'on every scan — do not edit it by hand. List / remove with:',
362
394
  '`sprag route-scan rules [rm <N>]`.',
@@ -395,6 +427,15 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
395
427
  ' settled earlier) into the delegation prompt. The subagent cannot see it, and',
396
428
  ' no effort level makes up for that (measured: 9 runs across efforts, all 9',
397
429
  ' recommended the rejected candidate again).',
430
+ '- A review that ends in improvements or recommendations, an audit, a root-cause',
431
+ ' diagnosis, research that needs searching, a lookup that has to conclude that',
432
+ ' something does "not exist", and a check where the output decides where to',
433
+ ' look next all end in a judgement. Do not delegate them; the main model does',
434
+ ' them. If the session is on Sonnet, move up to Opus at effort high. Do not',
435
+ ' recommend effort xhigh (measured on 10 judgement jobs: wrong claims rose from',
436
+ ' 3 to 11). If the main session runs at effort low or medium, hand the part that',
437
+ ' needs judgement to an Opus subagent at effort high and tell the user about',
438
+ ' /effort high in one line.',
398
439
  '',
399
440
  '## Tier criteria (apply to every rule below)',
400
441
  '',
@@ -0,0 +1,239 @@
1
+ /**
2
+ * permission-secrets — secrets that "don't ask again" left in approval lists.
3
+ *
4
+ * Claude Code stores an approved command verbatim in permissions.allow of
5
+ * .claude/settings.local.json. A command that carried a password or token
6
+ * therefore keeps it on disk, and a project whose settings file is committed
7
+ * publishes it (Apiiro found 1,122 public GitHub files this way, 2026-11-05).
8
+ *
9
+ * This module reads the four settings files (home and project, shared and
10
+ * local), reports which approval entries hold something findSecrets flags, and
11
+ * removes allow/ask entries on request. It never prints a value: previews go
12
+ * through maskPreview. An entry is deleted, not rewritten, because a repaired
13
+ * command could permit a different command than the one the user approved.
14
+ * deny entries stay: they block, and a blocked secret-bearing command is harmless.
15
+ */
16
+
17
+ import {
18
+ readFileSync, writeFileSync, existsSync, mkdirSync, statSync, renameSync, realpathSync, rmSync, chmodSync,
19
+ } from 'node:fs';
20
+ import { join, dirname, basename } from 'node:path';
21
+ import { homedir } from 'node:os';
22
+ import { execFileSync } from 'node:child_process';
23
+ import { findSecrets, maskPreview } from './redact.js';
24
+ import { userDataDir } from './paths.js';
25
+ import { writeStateFile } from './state-file.js';
26
+ import { writePrivateFile } from './private-file.js';
27
+ import { debug } from './debug.js';
28
+
29
+ export const PERMISSION_LISTS = ['allow', 'ask', 'deny'];
30
+ const GIT_TIMEOUT_MS = 2000;
31
+ const STATE_FILE = 'secret-scan-state.json';
32
+
33
+ /** The settings files worth reading, home first. A file reached twice (cwd is the home directory) appears once. */
34
+ export function settingsTargets({ home = homedir(), root = null } = {}) {
35
+ const out = [];
36
+ const seen = new Set();
37
+ const add = (dir, name, scope) => {
38
+ const path = join(dir, '.claude', name);
39
+ let key = path;
40
+ try { key = realpathSync(path); } catch { /* not there: keep the plain path */ }
41
+ if (seen.has(key)) return;
42
+ seen.add(key);
43
+ out.push({ path, scope, name });
44
+ };
45
+ add(home, 'settings.json', 'home');
46
+ add(home, 'settings.local.json', 'home');
47
+ if (root) {
48
+ add(root, 'settings.json', 'project');
49
+ add(root, 'settings.local.json', 'project');
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function readJson(path) {
55
+ try {
56
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
57
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Entries of one settings file that hold something that looks like a secret.
65
+ * @returns {{ path: string, mtimeMs: number, entries: { list: string, index: number, kinds: string[], preview: string }[] } | null}
66
+ * null when the file is missing or unreadable; `entries` is empty for a clean file
67
+ */
68
+ export function scanSettingsFile(path) {
69
+ if (!existsSync(path)) return null;
70
+ const json = readJson(path);
71
+ if (!json) return null;
72
+ const perms = json.permissions;
73
+ const entries = [];
74
+ if (perms && typeof perms === 'object') {
75
+ for (const list of PERMISSION_LISTS) {
76
+ if (!Array.isArray(perms[list])) continue;
77
+ perms[list].forEach((item, i) => {
78
+ if (typeof item !== 'string') return;
79
+ const hits = findSecrets(item);
80
+ if (!hits.length) return;
81
+ entries.push({
82
+ list,
83
+ index: i + 1,
84
+ kinds: [...new Set(hits.map((h) => h.kind))],
85
+ preview: maskPreview(item, 100),
86
+ });
87
+ });
88
+ }
89
+ }
90
+ let mtimeMs = 0;
91
+ try { mtimeMs = statSync(path).mtimeMs; } catch { /* the entries are still valid */ }
92
+ return { path, mtimeMs, entries };
93
+ }
94
+
95
+ /** Run git without a shell. Returns the exit status, or null when git cannot answer (missing, timed out). */
96
+ function gitStatus(args, cwd) {
97
+ try {
98
+ execFileSync('git', args, { cwd, stdio: 'ignore', timeout: GIT_TIMEOUT_MS });
99
+ return 0;
100
+ } catch (e) {
101
+ return typeof e.status === 'number' ? e.status : null;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Whether git tracks `file` (a secret in a tracked file is one commit away from
107
+ * public, or already is) and whether it is ignored.
108
+ * @returns {{ tracked: boolean, ignored: boolean | null } | null} null when git is unavailable or the folder is no repository
109
+ */
110
+ export function gitState(file, { withIgnore = true } = {}) {
111
+ const cwd = dirname(file);
112
+ const tracked = gitStatus(['ls-files', '--error-unmatch', '--', basename(file)], cwd);
113
+ if (tracked === null || tracked > 1) return null; // 128: not a repository
114
+ let ignored = null;
115
+ if (withIgnore) {
116
+ const status = gitStatus(['check-ignore', '-q', '--', basename(file)], cwd);
117
+ ignored = status === 0 ? true : status === 1 ? false : null;
118
+ }
119
+ return { tracked: tracked === 0, ignored };
120
+ }
121
+
122
+ /**
123
+ * Scan every settings file for the given project.
124
+ * Project files with hits also get their git state; `withIgnore: false` skips the
125
+ * second git call (the session hook only needs to know whether a file is tracked).
126
+ */
127
+ export function scanPermissionSecrets({ home = homedir(), root = null, withIgnore = true } = {}) {
128
+ const results = [];
129
+ for (const target of settingsTargets({ home, root })) {
130
+ const scan = scanSettingsFile(target.path);
131
+ if (!scan) continue;
132
+ const git = target.scope === 'project' && scan.entries.length ? gitState(target.path, { withIgnore }) : null;
133
+ results.push({ ...target, ...scan, git });
134
+ }
135
+ return results;
136
+ }
137
+
138
+ /** Where `sprag secrets fix` keeps the original before it changes a file. */
139
+ export function backupPathFor(file, { dir = userDataDir(), now = new Date() } = {}) {
140
+ const folder = join(dir, 'backups', now.toISOString().replace(/[:.]/g, '-'));
141
+ mkdirSync(folder, { recursive: true });
142
+ let target = join(folder, basename(file));
143
+ // home and project both have a settings.local.json
144
+ for (let n = 2; existsSync(target); n += 1) target = join(folder, `${basename(file)}.${n}`);
145
+ return target;
146
+ }
147
+
148
+ /**
149
+ * Remove the flagged allow/ask entries from one settings file.
150
+ * The original is saved first (owner-only) and the rest of the JSON is kept as it was.
151
+ * @returns {{ removed: number, backup: string|null, error?: string }}
152
+ */
153
+ export function fixSettingsFile(path, { dir = userDataDir(), now = new Date() } = {}) {
154
+ const raw = readFileSync(path, 'utf8');
155
+ const json = JSON.parse(raw);
156
+ const perms = json?.permissions;
157
+ let removed = 0;
158
+ if (perms && typeof perms === 'object') {
159
+ for (const list of ['allow', 'ask']) {
160
+ if (!Array.isArray(perms[list])) continue;
161
+ const kept = perms[list].filter((item) => !(typeof item === 'string' && findSecrets(item).length > 0));
162
+ removed += perms[list].length - kept.length;
163
+ perms[list] = kept;
164
+ }
165
+ }
166
+ if (!removed) return { removed: 0, backup: null };
167
+
168
+ const backup = backupPathFor(path, { dir, now });
169
+ writePrivateFile(backup, raw);
170
+
171
+ // Same shape as installer.writeSettings (temp file + rename, mode kept, symlink followed),
172
+ // minus its .sprag-bak sidecar: that copy would put the secret right back beside the file.
173
+ let target = path;
174
+ let mode;
175
+ try { target = realpathSync(path); mode = statSync(target).mode & 0o777; } catch { /* write to the plain path */ }
176
+ const tmp = `${target}.sprag-tmp-${process.pid}`;
177
+ try {
178
+ writeFileSync(tmp, JSON.stringify(json, null, 2) + '\n', mode === undefined ? undefined : { mode });
179
+ if (mode !== undefined) { try { chmodSync(tmp, mode); } catch { /* mode is best effort */ } }
180
+ renameSync(tmp, target);
181
+ } catch (e) {
182
+ try { rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
183
+ return { removed: 0, backup, error: e.message };
184
+ }
185
+ return { removed, backup };
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Session start notice
190
+ // ---------------------------------------------------------------------------
191
+
192
+ const statePath = (dir) => join(dir, STATE_FILE);
193
+
194
+ function loadNoticeState(dir) {
195
+ try {
196
+ const parsed = JSON.parse(readFileSync(statePath(dir), 'utf8'));
197
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
198
+ } catch {
199
+ return {};
200
+ }
201
+ }
202
+
203
+ const shortPath = (p, home) => (p.startsWith(home) ? `~${p.slice(home.length)}` : p);
204
+
205
+ export function noticeLine({ file, n, tracked, lang }) {
206
+ if (lang === 'ko') {
207
+ return `✇ [sprag] ${file} 의 승인 목록 ${n}개 항목에 비밀 값으로 보이는 문자열이 있습니다${tracked ? '. 이 파일은 git이 추적하고 있어 커밋되면 공개될 수 있습니다' : ''}. 사용자에게 알리고 sprag secrets 로 확인한 뒤 sprag secrets fix 로 지우라고 안내하십시오.`;
208
+ }
209
+ return `✇ [sprag] ${n} entries in the permission list of ${file} look like they hold secrets${tracked ? ', and git tracks this file, so a commit would publish them' : ''}. Tell the user, and suggest sprag secrets to review them and sprag secrets fix to remove them.`;
210
+ }
211
+
212
+ /**
213
+ * The line(s) the session start hook shows when a settings file holds secrets, or null.
214
+ * A file is announced once per modification time: the same file at the same mtime
215
+ * stays quiet on later sessions, and editing it (adding an entry, or fixing it) re-arms the check.
216
+ * Cheap on purpose: four JSON reads, plus one `git ls-files` per project file that has hits.
217
+ */
218
+ export function secretsNotice({
219
+ home = homedir(), root = null, lang = 'en', dir = userDataDir(), enabled = true,
220
+ } = {}) {
221
+ if (!enabled) return null;
222
+ const state = loadNoticeState(dir);
223
+ const lines = [];
224
+ let changed = false;
225
+ for (const f of scanPermissionSecrets({ home, root, withIgnore: false })) {
226
+ if (!f.entries.length) {
227
+ if (state[f.path] !== undefined) { delete state[f.path]; changed = true; }
228
+ continue;
229
+ }
230
+ if (state[f.path] === f.mtimeMs) continue;
231
+ lines.push(noticeLine({ file: shortPath(f.path, home), n: f.entries.length, tracked: f.git?.tracked === true, lang }));
232
+ state[f.path] = f.mtimeMs;
233
+ changed = true;
234
+ }
235
+ if (changed) {
236
+ try { writeStateFile(statePath(dir), JSON.stringify(state) + '\n'); } catch (e) { debug('permission-secrets:state', e); }
237
+ }
238
+ return lines.length ? lines.join('\n') : null;
239
+ }
@@ -22,6 +22,7 @@ import { homedir } from 'node:os';
22
22
  import { dirname, join } from 'node:path';
23
23
  import { codexUserDir } from './agent.js';
24
24
  import { userLanguage } from './config.js';
25
+ import { writePrivateFile } from './private-file.js';
25
26
  import { routingEnabled, DELEGATION_PRESET_IDS } from './routing-switch.js';
26
27
  import {
27
28
  HARNESS_BLOCK_BEGIN,
@@ -102,7 +103,7 @@ export function migrateLegacyPresetRules({ agent = 'claude' } = {}) {
102
103
  return false;
103
104
  });
104
105
  if (!moved.length) return { file, moved: 0 };
105
- writeFileSync(`${file}.bak-preset-migration`, original);
106
+ writePrivateFile(`${file}.bak-preset-migration`, original);
106
107
  writeIfChanged(file, kept.join('\n'));
107
108
  const state = loadSeedState({ agent });
108
109
  const today = new Date().toISOString().slice(0, 10);
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Files that copy a user's settings or notes (the .bak and .sprag-bak
3
+ * backups) can hold what the original holds: a token in settings.json's env
4
+ * block, a pasted password in CLAUDE.md. A copy made with the default mode is
5
+ * readable by every account on the machine, so these helpers cut it to the
6
+ * owner. The content is never changed, because a backup exists to be restored.
7
+ */
8
+
9
+ import { chmodSync, writeFileSync } from 'node:fs';
10
+
11
+ /** chmod 0600; a failure (Windows, a filesystem without modes) is ignored. */
12
+ export function restrictFile(path) {
13
+ try { chmodSync(path, 0o600); } catch { /* best effort */ }
14
+ }
15
+
16
+ /** Write `data` to `path` readable by the owner only, replacing an older, wider-mode copy too. */
17
+ export function writePrivateFile(path, data) {
18
+ writeFileSync(path, data, { mode: 0o600 });
19
+ restrictFile(path);
20
+ }
package/src/redact.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * redact — the one place that masks secrets and personal data.
3
+ *
4
+ * Two callers need the same answer to "does this text hold a secret": the
5
+ * Enterprise prompt uploader (team-prompts.js, masks right before upload) and
6
+ * every place sprag writes a user's words into a local file (the rule examples
7
+ * in model-rules.json and ratchet-model.md, the candidates route-scan caches).
8
+ * Claude Code's "don't ask again" has stored approved commands, passwords
9
+ * included, in .claude/settings.local.json and pushed them to public GitHub
10
+ * (Apiiro, 2026-11-05), so a local file is not private just because it is
11
+ * local. permission-secrets.js reuses findSecrets for the approval lists.
12
+ *
13
+ * Every secret shape is one entry in SECRET_RULES, and findSecrets,
14
+ * redactSecrets and maskPreview all read that table, so they cannot disagree.
15
+ * Conservative on purpose: over-masking a look-alike is fine, leaving a real
16
+ * token is not. Prose such as "token budget is 8000" must stay untouched.
17
+ */
18
+
19
+ const REDACTED = '[redacted]';
20
+
21
+ const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gd;
22
+ // key block cut off by the end of the text (a prompt, or an 80-char excerpt)
23
+ const PRIVATE_KEY_CUT = /-----BEGIN [A-Z ]*PRIVATE KEY-----(?![\s\S]*-----END [A-Z ]*PRIVATE KEY-----)[\s\S]*$/gd;
24
+
25
+ const FLAG_NAME = '--[a-z0-9-]*?(?:password|passwd|passphrase|pwd|token|secret|api-?key)';
26
+ // A value that is only a word cannot be told from prose ("--token budget"): demand a digit or symbol and 6+ chars.
27
+ const looksLikeValue = (v) => {
28
+ const bare = v.replace(/^["']|["']$/g, '');
29
+ return bare.length >= 6 && /[^A-Za-z]/.test(bare) && !/^[$<{-]/.test(bare);
30
+ };
31
+ const notReference = (v) => !/^["']?[$<{-]/.test(v) && v !== REDACTED;
32
+
33
+ /** @type {{kind: string, re: RegExp, group?: number, ok?: (value: string, match: RegExpExecArray) => boolean}[]} */
34
+ const SECRET_RULES = [
35
+ { kind: 'private-key', re: PRIVATE_KEY_BLOCK },
36
+ { kind: 'private-key', re: PRIVATE_KEY_CUT },
37
+ { kind: 'anthropic-key', re: /\bsk-ant-[A-Za-z0-9_-]{16,}/gd },
38
+ { kind: 'api-key', re: /\bsk-[A-Za-z0-9_-]{20,}/gd },
39
+ { kind: 'github-token', re: /\bgh[pousr]_[A-Za-z0-9]{20,}/gd },
40
+ { kind: 'github-token', re: /\bgithub_pat_[A-Za-z0-9_]{20,}/gd },
41
+ { kind: 'gitlab-token', re: /\bglpat-[A-Za-z0-9_-]{20,}/gd },
42
+ { kind: 'aws-key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/gd },
43
+ { kind: 'slack-token', re: /\bxox[abpr]-[A-Za-z0-9-]{10,}/gd },
44
+ { kind: 'slack-token', re: /\bxapp-\d-[A-Za-z0-9-]{10,}/gd },
45
+ { kind: 'npm-token', re: /\bnpm_[A-Za-z0-9]{30,}/gd },
46
+ { kind: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{35}/gd },
47
+ { kind: 'google-refresh-token', re: /(?<![\w/])1\/\/[0-9A-Za-z_-]{40,}/gd },
48
+ { kind: 'google-access-token', re: /\bya29\.[A-Za-z0-9_-]{30,}/gd },
49
+ { kind: 'google-client-secret', re: /\bGOCSPX-[A-Za-z0-9_-]{20,}/gd },
50
+ { kind: 'stripe-key', re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/gd },
51
+ { kind: 'huggingface-token', re: /\bhf_[A-Za-z0-9]{30,}/gd },
52
+ { kind: 'pypi-token', re: /\bpypi-AgEI[A-Za-z0-9_-]{20,}/gd },
53
+ { kind: 'supabase-token', re: /\bsbp_[a-f0-9]{40}\b/gd },
54
+ { kind: 'sendgrid-key', re: /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/gd },
55
+ { kind: 'shopify-token', re: /\bshp(?:at|ss|ca|pa)_[a-f0-9]{32}\b/gd },
56
+ { kind: 'jwt', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/gd },
57
+ // Authorization headers
58
+ { kind: 'bearer', re: /\bBearer\s+([A-Za-z0-9._~+/=-]{16,})/gid, group: 1 },
59
+ { kind: 'basic-auth', re: /\bBasic\s+([A-Za-z0-9+/]{12,}={0,2})(?![\w+/])/gd, group: 1, ok: (v) => /[0-9+/=]/.test(v) },
60
+ // scheme://user:password@host (a $VAR or <placeholder> password is not a secret)
61
+ { kind: 'url-credentials', re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/?#'"]+:([^\s@/?#'"]+)@/gd, group: 1, ok: (v) => !/^[$<{]/.test(v) },
62
+ // curl -u user:password
63
+ { kind: 'basic-auth', re: /\bcurl\b[^\n|;&]*?\s(?:-u|--user)\s+['"]?[^\s:'"]+:([^\s'"]+)/gd, group: 1, ok: (v) => !/^[$<{]/.test(v) },
64
+ // --password=value, --api-key=value, --refresh-token=value
65
+ { kind: 'cli-flag', re: new RegExp(`(?<![\\w-])${FLAG_NAME}=("[^"\\n]*"|'[^'\\n]*'|[^\\s"']+)`, 'gid'), group: 1, ok: notReference },
66
+ // --password value (separated by space)
67
+ { kind: 'cli-flag', re: new RegExp(`(?<![\\w-])${FLAG_NAME}[ \\t]+("[^"\\n]*"|'[^'\\n]*'|[^\\s"']+)`, 'gid'), group: 1, ok: looksLikeValue },
68
+ // NAME_KEY=value, PGPASSWORD=value, apiToken = "value" (not --max-tokens=1024)
69
+ {
70
+ kind: 'env-assignment',
71
+ re: /(?<![\w-])[A-Za-z0-9_]*(?:KEY|TOKEN|PASSWORD|PASSWD|SECRET|CREDENTIALS?)[A-Za-z0-9_]*\s*=(?![=>])\s*("[^"\n]*"|'[^'\n]*'|[^\s"']+)/gid,
72
+ group: 1,
73
+ ok: (v) => notReference(v) && v.replace(/^["']|["']$/g, '') !== '',
74
+ },
75
+ ];
76
+
77
+ function* matchSpans(text) {
78
+ for (const { kind, re, group = 0, ok } of SECRET_RULES) {
79
+ re.lastIndex = 0;
80
+ let m;
81
+ while ((m = re.exec(text)) !== null) {
82
+ if (m[0] === '') { re.lastIndex += 1; continue; }
83
+ const idx = m.indices[group];
84
+ if (idx && (!ok || ok(m[group] ?? '', m))) yield { kind, start: idx[0], end: idx[1] };
85
+ }
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Where secrets sit in `text`: [{ kind, start, end }], sorted, overlaps merged
91
+ * (the first kind found wins). The value itself is never returned, so a caller
92
+ * can print or log the result without leaking it.
93
+ */
94
+ export function findSecrets(text) {
95
+ const s = String(text ?? '');
96
+ const spans = [...matchSpans(s)].sort((a, b) => a.start - b.start || b.end - a.end);
97
+ const merged = [];
98
+ for (const sp of spans) {
99
+ const last = merged[merged.length - 1];
100
+ if (last && sp.start <= last.end) { last.end = Math.max(last.end, sp.end); continue; }
101
+ merged.push({ ...sp });
102
+ }
103
+ return merged;
104
+ }
105
+
106
+ /** Replace obvious secrets with "[redacted]". Conservative: it may over-redact, never under-redact these shapes. */
107
+ export function redactSecrets(text) {
108
+ const s = String(text ?? '');
109
+ const spans = findSecrets(s);
110
+ if (!spans.length) return s;
111
+ let out = '';
112
+ let at = 0;
113
+ for (const { start, end } of spans) {
114
+ out += s.slice(at, start) + REDACTED;
115
+ at = end;
116
+ }
117
+ return out + s.slice(at);
118
+ }
119
+
120
+ /**
121
+ * A preview that is safe to print: secrets become "[redacted]", then the text
122
+ * is cut to `max` characters. Masking comes first so a cut never leaves half a token.
123
+ */
124
+ export function maskPreview(text, max = Infinity) {
125
+ const one = redactSecrets(text).replace(/\s+/g, ' ').trim();
126
+ return one.length <= max ? one : `${one.slice(0, Math.max(0, max - 1))}…`;
127
+ }
128
+
129
+ /** An example excerpt for a rule file: personal data and secrets masked first, then cut to `max` characters. */
130
+ export function safeExcerpt(text, max = 80) {
131
+ const masked = redactSecrets(redactPersonal(text)).replace(/\s+/g, ' ');
132
+ return masked.slice(0, max);
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Personal data (PII) redaction. Typed markers: [redacted:email] [redacted:phone] [redacted:rrn] [redacted:card].
137
+ // Tuned for coding prompts: a miss is acceptable, a mangled code snippet is not.
138
+ // ---------------------------------------------------------------------------
139
+
140
+ const MARK_EMAIL = '[redacted:email]';
141
+ const MARK_PHONE = '[redacted:phone]';
142
+ const MARK_RRN = '[redacted:rrn]';
143
+ const MARK_CARD = '[redacted:card]';
144
+
145
+ // local@a.b.tld: dotted domain, TLD of 2+ letters. `react@18.3.1` has no letter TLD; the `git@github.com` SSH remote user is skipped in the callback.
146
+ const EMAIL_RE = /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@([A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)\.[A-Za-z]{2,}(?![A-Za-z0-9-])/g;
147
+ // asset names such as logo@2x.png and a version with a prerelease tag such as react@18.3.1-beta.abc are not addresses
148
+ const looksLikeAssetOrVersion = (domain) => { const first = domain.split('.')[0]; return !/[A-Za-z]/.test(first) || /^\d+x$/i.test(first); };
149
+
150
+ const PHONE_RES = [
151
+ // mobile: 010 / 011 / 016 / 017 / 018 / 019, separators optional
152
+ /(?<![\w.])01[016789][-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
153
+ // international form of a mobile number: +82 10 ..., +82-10-..., +82 (0)10 ...
154
+ /(?<![\w])\+82[-. ]?(?:\(0\)[-. ]?)?10[-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
155
+ // landline and 070: area code only when joined by hyphens, so plain digit runs stay untouched
156
+ /(?<![\w-])0(?:[2-6][0-9]?|70)-\d{3,4}-\d{4}(?![\w-])/g,
157
+ ];
158
+
159
+ // YYMMDD-GXXXXXX, G is 1-8 (birth century and sex, foreigners 5-8); month and day are range-checked below
160
+ const RRN_RE = /(?<![\w-])(\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])[- ][1-8]\d{6}(?!\w)/g;
161
+
162
+ // grouped (4-4-4-4, 4-4-4-4-3, 4-6-5) or contiguous 15-16 digits
163
+ const CARD_RE = /(?<![\w-])(?:\d{4}([ -])\d{4}\1\d{4}\1\d{4}(?:\1\d{3})?|\d{4}([ -])\d{6}\2\d{5}|\d{15,16})(?![\w-])/g;
164
+ const CARD_IIN_RE = /^(?:4|5[1-5]|222[1-9]|22[3-9]\d|2[3-6]\d\d|27[01]\d|2720|3[457]|6011|65|9)/;
165
+
166
+ function luhnOk(digits) {
167
+ let sum = 0;
168
+ for (let i = digits.length - 1, dbl = false; i >= 0; i--, dbl = !dbl) {
169
+ let d = digits.charCodeAt(i) - 48;
170
+ if (dbl) { d *= 2; if (d > 9) d -= 9; }
171
+ sum += d;
172
+ }
173
+ return sum % 10 === 0;
174
+ }
175
+
176
+ /** Mask email addresses, Korean phone numbers, resident registration numbers and card numbers with typed markers. */
177
+ export function redactPersonal(text) {
178
+ let s = String(text ?? '');
179
+ s = s.replace(EMAIL_RE, (m, domain) => (/^git@/i.test(m) || looksLikeAssetOrVersion(domain) ? m : MARK_EMAIL));
180
+ s = s.replace(CARD_RE, (m) => {
181
+ const digits = m.replace(/\D/g, '');
182
+ if (digits.length < 13 || digits.length > 19 || !luhnOk(digits)) return m;
183
+ if (/^\d+$/.test(m) && !CARD_IIN_RE.test(digits)) return m; // contiguous digits need a real issuer prefix
184
+ return MARK_CARD;
185
+ });
186
+ s = s.replace(RRN_RE, MARK_RRN);
187
+ for (const re of PHONE_RES) s = s.replace(re, MARK_PHONE);
188
+ return s;
189
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The offer to widen delegation until the usage window resets.
3
+ *
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.
10
+ */
11
+
12
+ import { readFileSync, existsSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import { userDataDir } from './paths.js';
15
+ import { writeStateFile } from './state-file.js';
16
+
17
+ const FILE = 'relax-offer.json';
18
+ /** resetsAt values this close count as the same window (the reading jitters by seconds). */
19
+ const SAME_WINDOW_S = 600;
20
+ /** A window with no reset time is bucketed by this span instead. */
21
+ const FALLBACK_BUCKET_S = 5 * 60 * 60;
22
+
23
+ /** The window id used for the claim: its resetsAt, or a 5 hour bucket when the window has none. */
24
+ export function offerWindowId(resetsAt, nowMs = Date.now()) {
25
+ if (typeof resetsAt === 'number' && Number.isFinite(resetsAt) && resetsAt > 0) return resetsAt;
26
+ return Math.floor(nowMs / 1000 / FALLBACK_BUCKET_S) * FALLBACK_BUCKET_S;
27
+ }
28
+
29
+ /**
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.
33
+ *
34
+ * @param {number|null} resetsAt epoch seconds of the busiest window's reset
35
+ * @param {{dir?: string, nowMs?: number}} [opts]
36
+ */
37
+ export function claimRelaxOffer(resetsAt, { dir, nowMs = Date.now() } = {}) {
38
+ try {
39
+ const file = join(dir || userDataDir(), FILE);
40
+ const id = offerWindowId(resetsAt, nowMs);
41
+ let last = null;
42
+ try {
43
+ if (existsSync(file)) last = Number(JSON.parse(readFileSync(file, 'utf8'))?.resetsAt);
44
+ } 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');
47
+ return true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }