sprag-cli 3.106.1 → 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.
@@ -38,13 +38,14 @@
38
38
  * A hint that fires on the wrong request costs more than one that stays quiet.
39
39
  */
40
40
 
41
- import { categorizeScored, ESCALATE_RE, EDIT_RE, worthDelegating } from './route-scan.js';
41
+ import { categorizeScored, ESCALATE_RE, JUDGE_RE, EDIT_RE, worthDelegating } from './route-scan.js';
42
+ import { delegationGrade, normalizeDelegationGrade, gradeKeepsRule } from './routing-switch.js';
42
43
  import { loadModelRules, budgetCapPhrase, ruleBudget } from './model-rules.js';
43
44
  import { sharedProjectRoots, realProjectRoot, scopeRank } from './shared-model-rules.js';
44
45
  import { agentPhrase, agentPhraseEn, resolveAgentName, agentForRule, TIER_MODEL } from './agents.js';
45
46
  import { userLanguage } from './config.js';
46
47
  import { aliasForRole, resolveModelAlias } from './model-alias.js';
47
- import { isRecognizedModelId, modelRank } from './cost.js';
48
+ import { isRecognizedModelId, modelRank, TIER_TARGET_RANK } from './cost.js';
48
49
  import { loadRecentSnapshot } from './caps-cache.js';
49
50
  import { getSessionModel } from './parser.js';
50
51
  import { labelForKey } from './window-labels.js';
@@ -233,11 +234,15 @@ export function unreachableTiers(env = process.env) {
233
234
  * model filters nothing.
234
235
  * @param {object} [opts.env] environment to read tier aliases from (see
235
236
  * unreachableTiers)
237
+ * @param {string} [opts.grade] delegation grade (routing-switch.js), 'quality'
238
+ * unless a relax window is open. 'cost' gates on ESCALATE_RE alone; 'quality' also
239
+ * gates on JUDGE_RE and drops the T2 rules of every category but paste,
240
+ * read and translate.
236
241
  * @returns {{cat: object, t2: object|undefined, t1: object|undefined, unreachable?: string[]}|null}
237
242
  * `unreachable` is set, with neither t2 nor t1, when every matching tier is
238
243
  * one this session cannot reach
239
244
  */
240
- export function routeMatch(text, { rules, sessionRank = null, root, env = process.env } = {}) {
245
+ export function routeMatch(text, { rules, sessionRank = null, root, env = process.env, grade = delegationGrade() } = {}) {
241
246
  const t = String(text || '').trim();
242
247
  if (t.length < MIN_LEN) return null;
243
248
  // A task notification or command echo is not a request, whatever words it holds.
@@ -246,6 +251,9 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
246
251
  // before classification because such a request often looks like a light
247
252
  // "run" or "check" in its wording.
248
253
  if (ESCALATE_RE.test(t)) return null;
254
+ // At grade 'quality' the gate is wider: audits, recommendations, absence
255
+ // checks and research end in a judgement as well (JUDGE_RE).
256
+ if (isQualityGrade(grade) && JUDGE_RE.test(t)) return null;
249
257
  // Same for implementation work dressed as a run or a check: an edit is not
250
258
  // delegable, and with no tool calls yet only the wording can say so.
251
259
  if (EDIT_RE.test(t)) return null;
@@ -277,7 +285,7 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
277
285
  const roots = root ? sharedProjectRoots(root) : [];
278
286
  const inScope = (r) => r.scope !== 'project' ||
279
287
  (typeof r.targetRoot === 'string' && roots.includes(realProjectRoot(r.targetRoot)));
280
- const matched = all.filter((r) => r && r.category === cat.id && inScope(r));
288
+ const matched = all.filter((r) => r && r.category === cat.id && inScope(r) && gradeKeepsRule(grade, r));
281
289
  if (!matched.length) return null;
282
290
  // A rule only saves anything when its target tier is cheaper than the model
283
291
  // reading the hint. A T1 rule states "delegate to model: sonnet", which in a
@@ -304,6 +312,117 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
304
312
  return t2 || t1 || t1h ? { cat, t2, t1, t1h } : null;
305
313
  }
306
314
 
315
+ /** True for 'quality'; an unknown grade reads as the default. */
316
+ function isQualityGrade(grade) {
317
+ return (normalizeDelegationGrade(grade) ?? 'quality') === 'quality';
318
+ }
319
+
320
+ /**
321
+ * ESCALATE_RE terms that name an action rather than a question: store
322
+ * submission, deploy, release, merge, production access, a go-ahead. They keep
323
+ * the delegation quiet (an irreversible step stays on the main model) but
324
+ * "this request ends in a judgement" would be wrong for "배포해줘".
325
+ */
326
+ const ACTION_RE = new RegExp(
327
+ /운영\s*(?:db|디비|데이터베이스|서버|환경)|프로덕션|\bprod(?:uction)?\s*(?:db|database|server|env)|승인\s*(?:할게|했어|했으니|했습니다|합니다|해줄게|완료)|\bapproved?\b|제출|배포|출시|퍼블리시|릴리[스즈](?!\s*노트)|(?<!나)머지|submit|deploy|release|publish|merge/.source, 'gi');
328
+
329
+ /**
330
+ * Why a request is kept off the delegation path, for the grades that gate on
331
+ * judgement. routeMatch returns null for all of these; this says which gate it
332
+ * was so the caller can recommend a stronger model instead of staying silent.
333
+ *
334
+ * @returns {{judgement: true, kind: 'escalate'|'judge'|'action', cat: null}|null}
335
+ * 'escalate' is a design, diagnosis or comparison word (ESCALATE_RE), 'judge'
336
+ * an audit, recommendation, absence check or research (JUDGE_RE, only below
337
+ * grade 'quality'), 'action' an irreversible step with no judgement word.
338
+ */
339
+ export function judgementMatch(text, { grade = delegationGrade() } = {}) {
340
+ const t = String(text || '').trim();
341
+ if (t.length < MIN_LEN || isSystemPrompt(t)) return null;
342
+ if (ESCALATE_RE.test(t)) {
343
+ const kind = ESCALATE_RE.test(t.replace(ACTION_RE, ' ')) ? 'escalate' : 'action';
344
+ return { judgement: true, kind, cat: null };
345
+ }
346
+ if (isQualityGrade(grade) && JUDGE_RE.test(t)) return { judgement: true, kind: 'judge', cat: null };
347
+ return null;
348
+ }
349
+
350
+ /**
351
+ * What grade 'cost' still sends up: diagnosis, audit and security asks. The
352
+ * other judgement words stay quiet there because that grade is the relax window, where
353
+ * the user chose to spend less.
354
+ */
355
+ const COST_UP_RE = /원인\s*(?:분석|파악|확인|규명|조사)|원인을?\s*찾|root cause|버그|취약|vulnerabilit|보안\s*(?:점검|검토|감사|리뷰|이슈)|security (?:review|audit)|감사\s*(?:해\s*(?:줘|봐|주|보|라|볼)|좀|를\s*(?:해|돌|진행)|하자|요청|부탁)|\baudit(?!\s*(?:log|trail))/i;
356
+
357
+ /** Price rank of Opus: a session at or above it needs no recommendation to move up. */
358
+ const OPUS_RANK = TIER_TARGET_RANK.T1H;
359
+
360
+ /**
361
+ * The line that recommends Opus at effort high for a request that ends in a
362
+ * judgement, or null when none applies.
363
+ *
364
+ * Measured in the validation Lab (r8) on ten jobs whose result is a judgement:
365
+ * Sonnet at high reached the same conclusion as the reference 1 time, Opus at
366
+ * high 5 times, Opus at xhigh 6 times with 11 wrong claims against 3. So the
367
+ * line names high and never xhigh.
368
+ *
369
+ * Silent when the session already runs Opus or better, and when the session
370
+ * model is unknown (a guess could tell an Opus session to switch to itself).
371
+ * Grade 'quality' speaks for every judgement request; 'cost'
372
+ * only for diagnosis, audit and security (COST_UP_RE).
373
+ *
374
+ * @param {string} text the prompt just submitted
375
+ * @param {object} [opts]
376
+ * @param {number|null} [opts.sessionRank] see sessionModelRank
377
+ * @param {string} [opts.grade] delegation grade
378
+ * @param {string} [opts.lang] 'ko' | 'en'
379
+ * @param {object|null} [opts.judgement] a judgementMatch result the caller already has
380
+ */
381
+ export function escalationNotice(text, { sessionRank = null, grade = delegationGrade(), lang = userLanguage(), judgement } = {}) {
382
+ if (sessionRank === null || sessionRank >= OPUS_RANK) return null;
383
+ const j = judgement === undefined ? judgementMatch(text, { grade }) : judgement;
384
+ if (!j || j.kind === 'action') return null;
385
+ if (!isQualityGrade(grade) && !COST_UP_RE.test(String(text || ''))) return null;
386
+ return lang === 'ko'
387
+ ? '✇ [sprag] 이 요청은 판단이 결론인 일입니다. Sonnet보다 Opus(effort high)가 맡도록 권합니다. '
388
+ + 'Opus 서브에이전트(t1h-worker)로 넘기거나 /model opus로 바꾸십시오. '
389
+ + '근거는 판단형 10건에서 Sonnet high가 같은 결론 1건, Opus high가 5건이었던 측정입니다(sprag.io/proof).'
390
+ : '✇ [sprag] This request ends in a judgement. sprag recommends Opus at effort high over Sonnet: '
391
+ + 'hand it to an Opus subagent (t1h-worker) or switch with /model opus. '
392
+ + 'On 10 judgement jobs Sonnet high reached the same conclusion once and Opus high five times (sprag.io/proof).';
393
+ }
394
+
395
+ /**
396
+ * The line for a main session at effort low or medium that gets a request
397
+ * ending in a judgement. A hook cannot change the session's effort, so the line
398
+ * has the model hand the judgement part to an Opus subagent at effort high and
399
+ * tell the user about /effort high in one line. Null when no line applies.
400
+ *
401
+ * Same request gate as escalationNotice: a judgement request that is not an
402
+ * irreversible action, and at grade 'cost' only diagnosis, audit and security.
403
+ *
404
+ * @param {string} text the prompt just submitted
405
+ * @param {object} [opts]
406
+ * @param {string|null} [opts.sessionEffort] the level the statusline recorded (readSessionEffort)
407
+ * @param {string} [opts.grade] delegation grade
408
+ * @param {string} [opts.lang] 'ko' | 'en'
409
+ * @param {object|null} [opts.judgement] a judgementMatch result the caller already has
410
+ */
411
+ export function effortNotice(text, { sessionEffort = null, grade = delegationGrade(), lang = userLanguage(), judgement } = {}) {
412
+ const level = typeof sessionEffort === 'string' ? sessionEffort.trim().toLowerCase() : '';
413
+ if (level !== 'low' && level !== 'medium') return null;
414
+ const j = judgement === undefined ? judgementMatch(text, { grade }) : judgement;
415
+ if (!j || j.kind === 'action') return null;
416
+ if (!isQualityGrade(grade) && !COST_UP_RE.test(String(text || ''))) return null;
417
+ return lang === 'ko'
418
+ ? `✇ [sprag] 이 요청은 판단이 결론인 일인데 지금 세션의 effort가 ${level}입니다. `
419
+ + '판단이 필요한 부분은 Opus effort high 서브에이전트(t1h-worker)에 맡기고, '
420
+ + '답 끝에 "/effort high로 올리면 메인도 같은 수준으로 답합니다"를 한 줄 덧붙이십시오.'
421
+ : `✇ [sprag] This request ends in a judgement and the session runs at effort ${level}. `
422
+ + 'Hand the part that needs judgement to an Opus subagent at effort high (t1h-worker), '
423
+ + 'and end your answer with one line: "Raise the main session with /effort high to get the same level here."';
424
+ }
425
+
307
426
  /** The budgets a match states, by tier: what the delegation guard repeats to the subagent. */
308
427
  export function matchCaps(match) {
309
428
  if (!match) return null;
@@ -398,6 +517,9 @@ export function pressureLine(pressure, { lang = userLanguage() } = {}) {
398
517
  const label = labelForKey(pressure.key).short;
399
518
  const pct = Math.round(pressure.pct);
400
519
  const ko = lang === 'ko';
520
+ // The caller sets `offer` once per limit window when delegation is not
521
+ // relaxed (claimRelaxOffer). The offer stands in for the usual line.
522
+ if (pressure.offer) return relaxOfferLine(label, pct, lang);
401
523
  if (pressure.level === 'critical') {
402
524
  return ko
403
525
  ? `한도 위험: ${label} ${pct}%. 여러 단계 작업도 위임 대상으로 보고, 메인 모델을 바꾸는 것(/model)도 사용자에게 제안하십시오.`
@@ -408,6 +530,13 @@ export function pressureLine(pressure, { lang = userLanguage() } = {}) {
408
530
  : `Usage limit pressure: ${label} ${pct}%. When in doubt, delegate.`;
409
531
  }
410
532
 
533
+ /** The one-time offer to widen delegation until the limit window resets. */
534
+ export function relaxOfferLine(label, pct, lang = userLanguage()) {
535
+ return lang === 'ko'
536
+ ? `✇ [sprag] ${label} 사용량이 ${pct}%입니다. 이번 한도 창이 끝날 때까지 위임 범위를 넓히면 사용량을 아낄 수 있습니다. 사용자에게 한 줄로 물어보고, 동의하면 sprag routing relax 를 실행하십시오. 창이 초기화되면 자동으로 원래대로 돌아옵니다.`
537
+ : `✇ [sprag] ${label} usage is at ${pct}%. Widening delegation until this limit window resets would save usage. Ask the user in one line, and if they agree run sprag routing relax. It switches back by itself when the window resets.`;
538
+ }
539
+
411
540
  /**
412
541
  * @param {string} text the prompt just submitted
413
542
  * @param {object} [opts] as routeMatch, plus:
package/src/route-scan.js CHANGED
@@ -34,6 +34,7 @@ import { modelRuleBaseText } from './model-rules.js';
34
34
  import { RULE_CATEGORY_LABELS } from './rule-categories.js';
35
35
  import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
36
36
  import { agentForRule } from './agents.js';
37
+ import { safeExcerpt } from './redact.js';
37
38
 
38
39
  // ── Tier bands (docs/TIER_CRITERIA.md §3) ────────────────────────────────
39
40
  // T2 (haiku): finished in few calls, tiny output, near-zero mutation, no
@@ -82,6 +83,28 @@ export const MIN_DELEGABLE_OUT = 100;
82
83
  // out: "승인된 룰" is a product noun in sprag's own ratchet flow.
83
84
  export const ESCALATE_RE = /운영\s*(?:db|디비|데이터베이스|서버|환경)|프로덕션|\bprod(?:uction)?\s*(?:db|database|server|env)|승인\s*(?:할게|했어|했으니|했습니다|합니다|해줄게|완료)|\bapproved?\b|설계|아키텍처|리팩토링|원인\s*(?:분석|파악|확인|규명|조사)|원인을?\s*찾|버그|개선할|개선점|개선\s*(?:사항|방안)|검토해보|검수|코드\s*리뷰|리뷰\s*해|취약|보안\s*(?:점검|검토|감사|리뷰|이슈)|비교|왜(?=[\s?]|$)|이유|제출|배포|출시|퍼블리시|릴리[스즈](?!\s*노트)|(?<!나)머지|analyze|compare|evaluate|architect|refactor|submit|deploy|release|publish|merge|root cause|code review|security (?:review|audit)|vulnerabilit/i;
84
85
 
86
+ // Requests that end in a judgement but that ESCALATE_RE does not list: audits,
87
+ // recommendations, rankings, "is there none / is there any" absence checks,
88
+ // and research that needs searching. In the validation Lab (r8) the answer to
89
+ // ten such jobs was a judgement, and Sonnet at effort high reached the same
90
+ // conclusion as Opus in 1 of 10 against 5 of 10 for Opus at high. Request-shaped
91
+ // forms only: "감사합니다" is thanks and "audit log", "추천 위임 룰" (a product
92
+ // noun) and "<name>-research-summary.md" (a file name) are not requests.
93
+ //
94
+ // Measured 2026-11-08 on 1,351 distinct local prompts (type=user, text only,
95
+ // harness messages and sidechains removed, last 90 days): JUDGE_RE matches 351,
96
+ // of which ESCALATE_RE already gated 343, so it newly gates 8 (6 distinct
97
+ // texts, three of them repeats of one eval prompt). The first draft gated 23;
98
+ // the 15 it lost were file names holding "research" (<name>-research-summary.md,
99
+ // 6), "할 수 없는지" read as absence (1), a code-lookup question "is there a
100
+ // function that …" (5, one prompt) and "조사해" in the
101
+ // sense of reading a git stash (3, one prompt). All 8 that remain are a
102
+ // research or absence-check request (precision 8/8; 6/6 distinct), but the sample
103
+ // is small, so the figure says "no false positive seen", not "none exist".
104
+ // The pattern was not asked to catch "있는지" alone: "실행되고 있는지" and the
105
+ // like are ordinary checks, so only "없는지", "있는지 없는지" and "존재하는지" count.
106
+ export const JUDGE_RE = /감사\s*(?:해\s*(?:줘|봐|주|보|라|볼)|좀|를\s*(?:해|돌|진행)|하자|요청|부탁)|\baudit(?!\s*(?:log|trail))|추천\s*(?:해\s*(?:줘|주|봐|달)|좀|부탁)|추천해|\brecommend(?!ation\s*(?:letter|engine))|우선\s*순위|순위\s*(?:를|을)\s*(?:매기|매겨|정해|정하)|\bprioriti[sz]e|(?<![수순]\s*)없는지|있는지\s*없는지|존재하는지|조사\s*해\s*(?:보|줘|주|봐|달|라)|조사\s*(?:좀|부탁)|리서치|(?<![\w./-])research(?![\w./-])|\bfind\s+(?:me\s+)?(?:alternatives?|options|candidates)|\bis there (?:any|an?)\b(?!\s+(?:exported\s+|existing\s+)?(?:function|file|method|class|module|variable|constant|test|script|helper|field|key|line))[^?\n]{0,60}\b(?:that|which)\b/i;
107
+
85
108
  // Implementation asks phrased around a run/check verb ("설치와 동시에 설정되도록
86
109
  // 하자", "피드백 확인해주고 아이콘도 만들자"). Editing is not delegable, and at
87
110
  // prompt time there is no tool mix to reveal it, so the wording has to. Offline
@@ -707,7 +730,8 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
707
730
  const usable = ep.text.length > 10;
708
731
  if ((!g.example && (usable || !g.exampleUsable))
709
732
  || (usable && (!g.exampleUsable || ep.text.length < g.example.length))) {
710
- g.example = ep.text.slice(0, 80).replace(/\s+/g, ' ');
733
+ // Mask before cutting so a token cut in half at char 80 cannot slip through.
734
+ g.example = safeExcerpt(ep.text, 80);
711
735
  g.exampleUsable = usable;
712
736
  }
713
737
  groups.set(key, g);
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { loadConfig, saveConfig } from './config.js';
12
+ import { formatResetClock } from './format-time.js';
12
13
 
13
14
  export function routingEnabled(cfg = loadConfig()) {
14
15
  try {
@@ -18,12 +19,116 @@ export function routingEnabled(cfg = loadConfig()) {
18
19
  }
19
20
  }
20
21
 
22
+ /**
23
+ * Whether the prompt hook may tell a low or medium effort session to hand its
24
+ * judgement work to an Opus subagent (effortNotice). Only an explicit `false`
25
+ * in `effortHint` is off; routing off silences it too.
26
+ */
27
+ export function effortHintEnabled(cfg = loadConfig()) {
28
+ try {
29
+ return routingEnabled(cfg) && cfg?.effortHint !== false;
30
+ } catch {
31
+ return true;
32
+ }
33
+ }
34
+
35
+ export function setEffortHint(on) {
36
+ const cfg = loadConfig();
37
+ cfg.effortHint = on !== false;
38
+ pruneExpiredRelax(cfg);
39
+ saveConfig(cfg);
40
+ }
41
+
21
42
  export function setRoutingEnabled(on) {
22
43
  const cfg = loadConfig();
23
44
  cfg.routing = on !== false;
45
+ pruneExpiredRelax(cfg);
24
46
  saveConfig(cfg);
25
47
  }
26
48
 
49
+ /**
50
+ * How far delegation goes while routing is on. 'quality' hands off only work
51
+ * whose answer comes straight from tool output and sends judgement work up to
52
+ * Opus; 'cost' hands off as much as the rules allow. Routing off still wins
53
+ * over any grade.
54
+ *
55
+ * The grade is not a setting. It is 'quality' unless a relax window is open:
56
+ * `relaxUntil` in config.json holds an epoch-ms deadline, and until then the
57
+ * grade reads 'cost'. `sprag routing relax` opens the window up to the reset
58
+ * of the busiest usage window, and once the deadline passes the grade goes
59
+ * back to 'quality' by itself, with no write needed.
60
+ */
61
+ export const DELEGATION_GRADES = ['quality', 'cost'];
62
+ export const DEFAULT_DELEGATION_GRADE = 'quality';
63
+
64
+ /** A grade name; null for anything else. */
65
+ export function normalizeDelegationGrade(value) {
66
+ return DELEGATION_GRADES.includes(value) ? value : null;
67
+ }
68
+
69
+ /** The stored relax deadline in epoch ms, or null when none is stored. It may already be past. */
70
+ export function relaxUntil(cfg = loadConfig()) {
71
+ try {
72
+ const v = cfg?.relaxUntil;
73
+ return typeof v === 'number' && Number.isFinite(v) ? v : null;
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** True while the relax deadline is still ahead of `now`. */
80
+ export function isRelaxed(cfg = loadConfig(), now = Date.now()) {
81
+ const until = relaxUntil(cfg);
82
+ return until !== null && until > now;
83
+ }
84
+
85
+ export function delegationGrade(cfg = loadConfig(), now = Date.now()) {
86
+ try {
87
+ return isRelaxed(cfg, now) ? 'cost' : DEFAULT_DELEGATION_GRADE;
88
+ } catch {
89
+ return DEFAULT_DELEGATION_GRADE;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Stores the relax deadline (epoch ms), or clears it with null. A deadline
95
+ * that has passed is dropped from the config on any write that goes through
96
+ * here or through the other setters in this file.
97
+ */
98
+ export function setRelaxUntil(ms) {
99
+ const cfg = loadConfig();
100
+ if (typeof ms === 'number' && Number.isFinite(ms)) cfg.relaxUntil = ms;
101
+ else delete cfg.relaxUntil;
102
+ saveConfig(cfg);
103
+ }
104
+
105
+ /** Drops an expired relaxUntil from a config object about to be saved. */
106
+ function pruneExpiredRelax(cfg) {
107
+ const until = relaxUntil(cfg);
108
+ if (until !== null && until <= Date.now()) delete cfg.relaxUntil;
109
+ else if (cfg && 'relaxUntil' in cfg && until === null) delete cfg.relaxUntil;
110
+ }
111
+
112
+ /** The deadline as the user reads it: HH:MM, with the weekday ahead of it when it is not today. */
113
+ export function relaxClock(ms, now = new Date()) {
114
+ return formatResetClock(ms / 1000, now);
115
+ }
116
+
117
+ /**
118
+ * At grade 'quality' a T2 (haiku) rule survives only for the categories whose
119
+ * answer is copied out of text the model is handed: pasted logs, reading and
120
+ * translating. A lookup, check or command run goes to T1 or stays on the main
121
+ * model, because a lookup that stops early is wrong without saying so. T1 and
122
+ * T1H rules are untouched, and so is grade 'cost'.
123
+ */
124
+ export const QUALITY_T2_CATEGORIES = new Set(['paste', 'read', 'translate']);
125
+
126
+ /** False when this grade drops the rule (see QUALITY_T2_CATEGORIES). */
127
+ export function gradeKeepsRule(grade, rule) {
128
+ if ((normalizeDelegationGrade(grade) ?? DEFAULT_DELEGATION_GRADE) !== 'quality') return true;
129
+ return rule?.tier !== 'T2' || QUALITY_T2_CATEGORIES.has(rule.category);
130
+ }
131
+
27
132
  // Preset ratchet rules (presets/ratchet-rules.json) whose text tells the model
28
133
  // to delegate: fix-f558f9 sends simple lookups and commands to T2 agents and
29
134
  // fix-777a15 sends multi-file implementation to the T1 worker. The other
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The effort level each session runs at, as the statusline last saw it.
3
+ *
4
+ * Claude Code puts `effort.level` into the statusline payload, but the
5
+ * UserPromptSubmit payload does not carry it. The statusline therefore writes
6
+ * the level to <userDataDir>/session-effort/<sessionId>, and the prompt hook
7
+ * reads it back (effortNotice in src/route-inject.js).
8
+ *
9
+ * The statusline renders every few seconds, so an unchanged level is not
10
+ * written again. Files untouched for 7 days are removed, checked on roughly one
11
+ * write in PRUNE_EVERY. Every failure is swallowed: this is a hint input.
12
+ */
13
+
14
+ import { readFileSync, readdirSync, statSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { userDataDir } from './paths.js';
17
+ import { debug } from './debug.js';
18
+
19
+ export const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
20
+ const PRUNE_MS = 7 * 24 * 60 * 60 * 1000;
21
+ const PRUNE_EVERY = 100;
22
+
23
+ export const sessionEffortDir = (dir) => join(dir || userDataDir(), 'session-effort');
24
+
25
+ /** Removes level files older than 7 days. */
26
+ export function pruneSessionEffort({ dir, now = Date.now() } = {}) {
27
+ try {
28
+ const d = sessionEffortDir(dir);
29
+ for (const name of readdirSync(d)) {
30
+ try {
31
+ if (now - statSync(join(d, name)).mtimeMs > PRUNE_MS) rmSync(join(d, name), { force: true });
32
+ } catch { /* gone already */ }
33
+ }
34
+ } catch (e) { if (e?.code !== 'ENOENT') debug('session-effort:prune', e); }
35
+ }
36
+
37
+ /**
38
+ * Record the level for a session. Returns true when a file was written; false
39
+ * for a malformed id, an empty level, an unchanged level, or a failure.
40
+ *
41
+ * @param {{dir?: string, now?: number, random?: () => number}} [opts] `dir` replaces the user data dir (tests)
42
+ */
43
+ export function recordSessionEffort(sessionId, level, { dir, now = Date.now(), random = Math.random } = {}) {
44
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
45
+ if (typeof level !== 'string' || level === '') return false;
46
+ try {
47
+ const file = join(sessionEffortDir(dir), sessionId);
48
+ let prev = null;
49
+ try { prev = readFileSync(file, 'utf8').trim(); } catch { /* first write */ }
50
+ if (prev === level) return false;
51
+ mkdirSync(sessionEffortDir(dir), { recursive: true });
52
+ // Not writeStateFile: that treats a file that is not JSON as corrupt and keeps a copy.
53
+ writeFileSync(file, level + '\n');
54
+ if (random() < 1 / PRUNE_EVERY) pruneSessionEffort({ dir, now });
55
+ return true;
56
+ } catch (e) {
57
+ debug('session-effort:record', e);
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /** The recorded level for a session, or null. */
63
+ export function readSessionEffort(sessionId, { dir } = {}) {
64
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null;
65
+ try {
66
+ const v = readFileSync(join(sessionEffortDir(dir), sessionId), 'utf8').trim();
67
+ return v === '' ? null : v;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
@@ -34,6 +34,7 @@ import { codexUserDir } from './agent.js';
34
34
  import { discoverCodexSessionFiles } from './codex/parser.js';
35
35
  import { writeStateFile } from './state-file.js';
36
36
  import { debug } from './debug.js';
37
+ import { redactSecrets, redactPersonal } from './redact.js';
37
38
 
38
39
  export const MAX_RUN_PROMPTS = 2000;
39
40
  export const MAX_RUN_BYTES = 8 * 1024 * 1024;
@@ -45,89 +46,9 @@ const READ_WINDOW_MAX = 256 * 1024 * 1024;
45
46
 
46
47
  export const promptOffsetsPath = (dir = userDataDir()) => join(dir, 'prompts-offsets.json');
47
48
 
48
- // ---------------------------------------------------------------------------
49
- // Redaction
50
- // ---------------------------------------------------------------------------
51
-
52
- const REDACTED = '[redacted]';
53
- const SECRET_PATTERNS = [
54
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
55
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*$/g, // key block cut off by the end of the prompt
56
- /\bsk-ant-[A-Za-z0-9_-]{16,}/g,
57
- /\bsk-[A-Za-z0-9_-]{20,}/g,
58
- /\bgh[pousr]_[A-Za-z0-9]{20,}/g,
59
- /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
60
- /\bAKIA[0-9A-Z]{16}\b/g,
61
- /\bxox[abpr]-[A-Za-z0-9-]{10,}/g,
62
- ];
63
-
64
- /** Replace obvious secrets with "[redacted]". Conservative: it may over-redact, never under-redact these shapes. */
65
- export function redactSecrets(text) {
66
- let s = String(text ?? '');
67
- for (const re of SECRET_PATTERNS) s = s.replace(re, REDACTED);
68
- s = s.replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{16,}/gi, `$1${REDACTED}`);
69
- s = s.replace(
70
- /\b([A-Za-z0-9_]*(?:KEY|TOKEN|PASSWORD|PASSWD|SECRET)[A-Za-z0-9_]*)(\s*=\s*)("[^"\n]*"|'[^'\n]*'|[^\s"']+)/gi,
71
- (m, name, eq, val) => (val === REDACTED ? m : `${name}${eq}${REDACTED}`),
72
- );
73
- return s;
74
- }
75
-
76
- // ---------------------------------------------------------------------------
77
- // Personal data (PII) redaction. Typed markers: [redacted:email] [redacted:phone] [redacted:rrn] [redacted:card].
78
- // Tuned for coding prompts: a miss is acceptable, a mangled code snippet is not.
79
- // ---------------------------------------------------------------------------
80
-
81
- const MARK_EMAIL = '[redacted:email]';
82
- const MARK_PHONE = '[redacted:phone]';
83
- const MARK_RRN = '[redacted:rrn]';
84
- const MARK_CARD = '[redacted:card]';
85
-
86
- // 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.
87
- 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;
88
- // 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
89
- const looksLikeAssetOrVersion = (domain) => { const first = domain.split('.')[0]; return !/[A-Za-z]/.test(first) || /^\d+x$/i.test(first); };
90
-
91
- const PHONE_RES = [
92
- // mobile: 010 / 011 / 016 / 017 / 018 / 019, separators optional
93
- /(?<![\w.])01[016789][-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
94
- // international form of a mobile number: +82 10 ..., +82-10-..., +82 (0)10 ...
95
- /(?<![\w])\+82[-. ]?(?:\(0\)[-. ]?)?10[-. ]?\d{3,4}[-. ]?\d{4}(?!\w)/g,
96
- // landline and 070: area code only when joined by hyphens, so plain digit runs stay untouched
97
- /(?<![\w-])0(?:[2-6][0-9]?|70)-\d{3,4}-\d{4}(?![\w-])/g,
98
- ];
99
-
100
- // YYMMDD-GXXXXXX, G is 1-8 (birth century and sex, foreigners 5-8); month and day are range-checked below
101
- 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;
102
-
103
- // grouped (4-4-4-4, 4-4-4-4-3, 4-6-5) or contiguous 15-16 digits
104
- 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;
105
- 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)/;
106
-
107
- function luhnOk(digits) {
108
- let sum = 0;
109
- for (let i = digits.length - 1, dbl = false; i >= 0; i--, dbl = !dbl) {
110
- let d = digits.charCodeAt(i) - 48;
111
- if (dbl) { d *= 2; if (d > 9) d -= 9; }
112
- sum += d;
113
- }
114
- return sum % 10 === 0;
115
- }
116
-
117
- /** Mask email addresses, Korean phone numbers, resident registration numbers and card numbers with typed markers. */
118
- export function redactPersonal(text) {
119
- let s = String(text ?? '');
120
- s = s.replace(EMAIL_RE, (m, domain) => (/^git@/i.test(m) || looksLikeAssetOrVersion(domain) ? m : MARK_EMAIL));
121
- s = s.replace(CARD_RE, (m) => {
122
- const digits = m.replace(/\D/g, '');
123
- if (digits.length < 13 || digits.length > 19 || !luhnOk(digits)) return m;
124
- if (/^\d+$/.test(m) && !CARD_IIN_RE.test(digits)) return m; // contiguous digits need a real issuer prefix
125
- return MARK_CARD;
126
- });
127
- s = s.replace(RRN_RE, MARK_RRN);
128
- for (const re of PHONE_RES) s = s.replace(re, MARK_PHONE);
129
- return s;
130
- }
49
+ // Redaction lives in redact.js (shared with the rule examples); re-exported so
50
+ // existing importers keep working.
51
+ export { redactSecrets, redactPersonal };
131
52
 
132
53
  // ---------------------------------------------------------------------------
133
54
  // Prompt extraction