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.
@@ -35,6 +35,10 @@ import { loadConfig, saveConfig } from './config.js';
35
35
  import { recentToolPaths } from './session-paths.js';
36
36
  import { routeCapsFor } from './route-caps.js';
37
37
  import { modelOf } from './agents.js';
38
+ import { routingEnabled, delegationGrade, normalizeDelegationGrade } from './routing-switch.js';
39
+ import { isJudgementDelegation, SAVING_GRADE_KINDS } from './judgement-prompt.js';
40
+ import { recordGradeAction } from './grade-counts.js';
41
+ import { userDataDir } from './paths.js';
38
42
 
39
43
  const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
40
44
 
@@ -266,11 +270,18 @@ export async function buildAppendix(payload, { cfg = loadConfig(), home = homedi
266
270
 
267
271
  /**
268
272
  * Decide whether to rewrite a Task/Agent call's prompt, and with what.
269
- * Returns `{ updatedInput }` or null — null on any reason not to touch the
273
+ * Returns `{ updatedInput }` or null. Null is any reason not to touch the
270
274
  * call, so the caller's contract stays "print nothing, let the tool run
271
275
  * exactly as given" for every one of them.
276
+ *
277
+ * The delegation grade (see gradeAction) can send a judgement delegation to
278
+ * Opus. It never stops a call, and it needs the guard on and routing on, like
279
+ * every other grade effect.
272
280
  */
273
- export async function decideForDelegation(payload, { cfg = loadConfig(), home = homedir(), routeCaps = routeCapsFor(payload?.session_id) } = {}) {
281
+ export async function decideForDelegation(payload, {
282
+ cfg = loadConfig(), home = homedir(), routeCaps = routeCapsFor(payload?.session_id),
283
+ countsDir = userDataDir(),
284
+ } = {}) {
274
285
  if (!delegateEnabled(cfg)) return null;
275
286
  if (payload?.tool_name !== 'Task' && payload?.tool_name !== 'Agent') return null;
276
287
 
@@ -282,9 +293,15 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
282
293
  // same tool_name, must not stack the appendix onto itself.
283
294
  if (prompt.includes(DELEGATION_MARKER)) return null;
284
295
 
285
- const raise = wantsEffortRaise(toolInput);
286
- const appendix = await buildAppendix(payload, { cfg, home, routeCaps });
287
- if (!appendix && !raise) return null;
296
+ const act = routingEnabled(cfg) ? gradeAction(toolInput, delegationGrade(cfg)) : null;
297
+ const modelRaise = act?.type === 'raise' && !prompt.includes(MODEL_RAISE_MARKER);
298
+
299
+ // The model raise wins over the effort raise: it sets the effort itself, and
300
+ // a second marker would count one run twice in the effort ledger.
301
+ const raise = !modelRaise && wantsEffortRaise(toolInput);
302
+ const seen = modelRaise ? { ...payload, tool_input: { ...toolInput, model: RAISED_MODEL } } : payload;
303
+ const appendix = await buildAppendix(seen, { cfg, home, routeCaps });
304
+ if (!appendix && !raise && !modelRaise) return null;
288
305
 
289
306
  const parts = [prompt];
290
307
  if (appendix) parts.push(appendix);
@@ -292,11 +309,63 @@ export async function decideForDelegation(payload, { cfg = loadConfig(), home =
292
309
  // what the subagent transcript keeps, so route-scan can later tell a raise
293
310
  // this hook made from an effort the caller chose (see src/route-scan.js).
294
311
  if (raise) parts.push(EFFORT_RAISE_MARKER);
312
+ if (modelRaise) parts.push(MODEL_RAISE_MARKER);
295
313
  const updatedInput = { ...toolInput, prompt: parts.join('\n\n') };
296
314
  if (raise) updatedInput.effort = RAISED_EFFORT;
315
+ if (modelRaise) {
316
+ updatedInput.model = RAISED_MODEL;
317
+ // A caller that already asked for more than high keeps it: the replay
318
+ // that set this grade found xhigh no better on judgement work, but
319
+ // lowering a level somebody chose on purpose is not this hook's call.
320
+ if (!HIGHER_THAN_RAISED.has(String(toolInput.effort || '').toLowerCase())) updatedInput.effort = RAISED_EFFORT;
321
+ recordGradeAction('raised', { dir: countsDir });
322
+ }
297
323
  return { updatedInput };
298
324
  }
299
325
 
326
+ /** Model a judgement delegation is raised to. Opus, not a higher effort on the cheaper model. */
327
+ export const RAISED_MODEL = 'opus';
328
+ const HIGHER_THAN_RAISED = new Set(['xhigh', 'max']);
329
+
330
+ /**
331
+ * Line appended to the prompt of a delegation whose model this hook raised.
332
+ * Like EFFORT_RAISE_MARKER, a later scan can grep subagent transcripts for it.
333
+ */
334
+ export const MODEL_RAISE_MARKER = '[sprag: raised to Opus for judgement work]';
335
+
336
+ /** Model family a call targets: the `model` argument wins over the agent's own pin. */
337
+ export function targetFamily(toolInput) {
338
+ const named = String(toolInput?.model || '');
339
+ for (const fam of ['opus', 'sonnet', 'haiku']) if (new RegExp(fam, 'i').test(named)) return fam;
340
+ if (named) return null; // some other model: no measurement says what it does with this work
341
+ return modelOf(String(toolInput?.subagent_type || '')) || null;
342
+ }
343
+
344
+ /**
345
+ * What the delegation grade does to a call, or null for nothing.
346
+ *
347
+ * Only a haiku or sonnet target is touched, and only when the prompt asks for
348
+ * work whose conclusion is a judgement (judgement-prompt.js). Opus targets,
349
+ * unknown models, and a call that names no model and no known agent (it runs
350
+ * on whatever the session runs on) pass.
351
+ *
352
+ * quality -> raise: same call, run on Opus at high effort
353
+ * cost -> raise, but only diagnosis and audit work; the rest passes
354
+ *
355
+ * Opus at high, never xhigh: on ten judgement cases the Opus high runs made 3
356
+ * wrong claims and xhigh made 11.
357
+ */
358
+ export function gradeAction(toolInput, grade) {
359
+ const fam = targetFamily(toolInput);
360
+ if (fam !== 'haiku' && fam !== 'sonnet') return null;
361
+ const { judgement, kind } = isJudgementDelegation(toolInput?.prompt);
362
+ if (!judgement) return null;
363
+ const g = normalizeDelegationGrade(grade) ?? 'quality';
364
+ if (g === 'quality') return { type: 'raise', kind };
365
+ if (SAVING_GRADE_KINDS.has(kind)) return { type: 'raise', kind };
366
+ return null;
367
+ }
368
+
300
369
  /**
301
370
  * True when the delegation prompt sets its own budget: the word budget (or
302
371
  * 예산) next to a number, or a tool-call count. The rules require an
package/src/doc2md.cjs CHANGED
@@ -125,6 +125,42 @@ function metaPathFor(cacheFile) {
125
125
  return cacheFile.replace(/\.md$/, '.meta.json');
126
126
  }
127
127
 
128
+ /** A converted copy keeps a document's whole text, so one nobody has touched for this long goes. */
129
+ const CACHE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
130
+
131
+ /**
132
+ * Delete cached conversions (the .md and its .meta.json) not modified for
133
+ * `maxAgeMs`, plus a .meta.json whose .md is gone and that is just as old.
134
+ * The caller decides how often this runs; a file that cannot be removed is skipped.
135
+ *
136
+ * @returns {number} how many conversions were removed
137
+ */
138
+ function pruneCache({ now = Date.now(), maxAgeMs = CACHE_MAX_AGE_MS } = {}) {
139
+ const dir = cacheDir();
140
+ let names;
141
+ try { names = fs.readdirSync(dir); } catch { return 0; }
142
+ const old = (file) => {
143
+ try {
144
+ const st = fs.lstatSync(file);
145
+ return st.isFile() && now - st.mtimeMs > maxAgeMs;
146
+ } catch { return false; }
147
+ };
148
+ let removed = 0;
149
+ for (const name of names) {
150
+ const file = path.join(dir, name);
151
+ if (name.endsWith('.md')) {
152
+ if (!old(file)) continue;
153
+ try { fs.rmSync(file, { force: true }); fs.rmSync(metaPathFor(file), { force: true }); removed += 1; } catch { /* skip it */ }
154
+ } else if (name.endsWith('.meta.json')) {
155
+ const md = file.replace(/\.meta\.json$/, '.md');
156
+ if (!fs.existsSync(md) && old(file)) {
157
+ try { fs.rmSync(file, { force: true }); } catch { /* skip it */ }
158
+ }
159
+ }
160
+ }
161
+ return removed;
162
+ }
163
+
128
164
  /** A cached conversion still matching the source's mtime and size, or null. */
129
165
  function readCache(filePath) {
130
166
  const cacheFile = cachePathFor(filePath);
@@ -1043,6 +1079,8 @@ module.exports = {
1043
1079
  interpreterParts,
1044
1080
  clearNotice,
1045
1081
  cacheDir,
1082
+ pruneCache,
1083
+ CACHE_MAX_AGE_MS,
1046
1084
  cachePathFor,
1047
1085
  metaPathFor,
1048
1086
  isTargetPath,
@@ -1217,6 +1217,25 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1217
1217
  ? `${c(GRAY)}${verbose ? `effort guard ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
1218
1218
  : null;
1219
1219
 
1220
+ // The delegation grade's own count (grade-counts.js): judgement delegations
1221
+ // the guard sent to Opus (`model↑N`). Same gray count chip as the effort
1222
+ // guard, same reset mark, hidden at zero. It always stays a chip: the guard
1223
+ // line above is about effort, and this one has no line of its own.
1224
+ // icon "🤖↑2" | text "model↑2" | verbose "model guard ×2"
1225
+ const gradeInfo = data.gradeActions;
1226
+ const modelUp = Number(gradeInfo && gradeInfo.raised) || 0;
1227
+ const modelUpSeg = modelUp > 0
1228
+ ? `${c(GRAY)}${verbose ? `model guard ×${modelUp}` : isIcon ? `${g.model}↑${modelUp}` : `model↑${modelUp}`}${c(RESET)}`
1229
+ : null;
1230
+ // The relax window, only while one is open: the default behaviour gets no
1231
+ // chip. data.relaxUntil is the deadline in epoch ms (null when closed).
1232
+ // text "relax →21:30" | verbose "relax until 21:30"
1233
+ const relaxMs = Number(data.relaxUntil);
1234
+ const relaxClockText = Number.isFinite(relaxMs) && relaxMs > Date.now() ? formatResetClock(relaxMs / 1000) : null;
1235
+ const gradeSeg = relaxClockText
1236
+ ? `${c(GRAY)}${verbose ? `relax until ${relaxClockText}` : `relax →${relaxClockText}`}${c(RESET)}`
1237
+ : null;
1238
+
1220
1239
  // Routing-savings headline line (multi-line layout). The lifetime sum from
1221
1240
  // the delegation ledger — the number the whole tool exists to grow, so it
1222
1241
  // gets line 1 to itself while the diagnostics move to line 2.
@@ -1287,8 +1306,10 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1287
1306
  // the dropped runs matter. The raise chip steps aside for its own line the
1288
1307
  // same way, and stays on line 2 while there is no line to carry it.
1289
1308
  chips: totalsLine
1290
- ? (totalsNum === 0 ? [unresolvedSeg, guardLine ? null : raisedSeg] : [guardLine ? null : raisedSeg])
1291
- : [delegateSeg, guardLine ? null : raisedSeg, delegateExtra],
1309
+ ? (totalsNum === 0
1310
+ ? [unresolvedSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg]
1311
+ : [guardLine ? null : raisedSeg, modelUpSeg, gradeSeg])
1312
+ : [delegateSeg, guardLine ? null : raisedSeg, modelUpSeg, gradeSeg, delegateExtra],
1292
1313
  headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
1293
1314
  guardLine,
1294
1315
  };
@@ -1426,6 +1447,8 @@ export const DEFAULT_SEGMENT_ORDER = [
1426
1447
  //
1427
1448
  // Lifetime, from the savings ledgers. Delegation stays ahead of the cache
1428
1449
  // figure: routing is what the tool is for, the cache number is a brag stat.
1450
+ // `delegated` also carries the guard chips (effort↑N, model↑N) and the
1451
+ // grade chip (C), so one name in `--segments` shows or hides all of them.
1429
1452
  'delegated', 'doc2md',
1430
1453
  // Same period as the routing counter, so it sits after the lifetime routing
1431
1454
  // figures but carries its own since date.
@@ -1591,7 +1614,7 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1591
1614
  * @param {boolean} [opts.verbose=false] - longer layout with labels
1592
1615
  * @param {boolean} [opts.timer=true] - show TTL countdown segment
1593
1616
  * @param {'text'|'icon'} [opts.mode='text'] - label style. 'icon' uses 🧠 ⏳ 💰 instead of word labels.
1594
- * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, ultra (ultracode on/off; live statusline only), hit, ttl, month, saved, delegated, doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1617
+ * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, ultra (ultracode on/off; live statusline only), hit, ttl, month, saved, delegated (Routing saved plus the effort↑N, model↑N and grade chips), doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1595
1618
  * @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line). It also ignores `columns`.
1596
1619
  * @param {number} [opts.columns=0] - terminal width in cells (Claude Code exports it as COLUMNS). When set, the chips wrap at chip boundaries instead of being truncated by the terminal; 0 keeps one unbounded line. A verbose layout that would need chips dropped is re-rendered once in the compact layout first.
1597
1620
  * @param {number} [opts.maxLines=3] - most chip lines when `columns` is set; lower-priority tail chips collapse into a `+N` chip beyond that. Counts the chip lines only: the headline lines above them wrap at their own `|` and `·` joints and are not included. Cap, usage, ctx, spike chips are never dropped.
@@ -0,0 +1,85 @@
1
+ /**
2
+ * grade-counts — how often the delegation grade acted on a call.
3
+ *
4
+ * The guard (delegation-guard.js) raises a judgement delegation to Opus under
5
+ * either grade. Each raise counts once here, and the statusline shows the
6
+ * number as `model↑N`.
7
+ *
8
+ * File: <userDataDir>/delegation-grade-counts.json
9
+ * { "version": 1, "raised": 3, "since": <ms> }
10
+ *
11
+ * An earlier version also counted held calls in a `blocked` field. That field
12
+ * is ignored on read and dropped on the next write, so an old file still loads.
13
+ *
14
+ * `since` is when the counting window opened: the first count after the last
15
+ * routing reset. The reset mark is the same one the effort-raise ledger and
16
+ * Routing saved read, so `sprag saved reset` zeroes all three together. The
17
+ * counts are not evidence the way a ledger is, so a reset restarts the file
18
+ * the next time it is written, and a read before that treats a window that
19
+ * opened before the mark as empty.
20
+ *
21
+ * The write happens inside a PreToolUse hook, so it is best effort: nothing
22
+ * throws, and two hooks racing can lose a count, which a display figure
23
+ * tolerates.
24
+ */
25
+
26
+ import { readFileSync } from 'node:fs';
27
+ import { join } from 'node:path';
28
+ import { userDataDir } from './paths.js';
29
+ import { writeStateFile } from './state-file.js';
30
+ import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
31
+
32
+ export const GRADE_COUNTS_VERSION = 1;
33
+
34
+ export function gradeCountsPath(dir = userDataDir()) {
35
+ return join(dir, 'delegation-grade-counts.json');
36
+ }
37
+
38
+ function readCounts(dir) {
39
+ try {
40
+ const data = JSON.parse(readFileSync(gradeCountsPath(dir), 'utf8'));
41
+ if (!data || data.version !== GRADE_COUNTS_VERSION) return null;
42
+ const n = (v) => (Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);
43
+ return { raised: n(data.raised), since: Number.isFinite(data.since) ? data.since : null };
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Count one action: 'raised' (sent to Opus). Returns the new counts, or null
51
+ * when nothing could be written.
52
+ */
53
+ export function recordGradeAction(action, { dir = userDataDir(), now = Date.now() } = {}) {
54
+ if (action !== 'raised') return null;
55
+ try {
56
+ const mark = readResetMarks(dir).routing;
57
+ let counts = readCounts(dir);
58
+ // A window that opened before the reset mark is the old count: start over.
59
+ if (!counts || counts.since === null || isBeforeReset(counts.since, mark)) {
60
+ counts = { raised: 0, since: now };
61
+ }
62
+ counts[action] += 1;
63
+ writeStateFile(gradeCountsPath(dir), JSON.stringify({ version: GRADE_COUNTS_VERSION, ...counts }) + '\n');
64
+ return counts;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * { raised, since } for the statusline, with `since` the routing reset
72
+ * mark (null when never reset), the same field the effort guard reads. Never
73
+ * throws; an unreadable file or a window older than the mark reads as zero.
74
+ */
75
+ export function gradeActionTotals(dir = userDataDir()) {
76
+ const since = readResetMarks(dir).routing;
77
+ const zero = { raised: 0, since };
78
+ try {
79
+ const counts = readCounts(dir);
80
+ if (!counts || counts.since === null || isBeforeReset(counts.since, since)) return zero;
81
+ return { raised: counts.raised, since };
82
+ } catch {
83
+ return zero;
84
+ }
85
+ }
package/src/harness.js CHANGED
@@ -26,6 +26,7 @@ import { routeWarningForStatusline } from './route-scan.js';
26
26
  import { ruleHealthWarningForStatusline, modelRatchetPathFor, renderModelRatchet } from './model-rules.js';
27
27
  import { compactWindowWarningForStatusline } from './compact-window.js';
28
28
  import { userLanguage } from './config.js';
29
+ import { writePrivateFile } from './private-file.js';
29
30
  import { routingEnabled, routingOffRatchetText } from './routing-switch.js';
30
31
  import { codexUserDir } from './agent.js';
31
32
  import { ratchetPresetEntries } from './presets-source.js';
@@ -241,7 +242,7 @@ export function harnessInit({ root = findProjectRoot(), force = false, scope = '
241
242
  if (force) {
242
243
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
243
244
  const bak = `${cmPath}.bak-${stamp}`;
244
- writeFileSync(bak, existing);
245
+ writePrivateFile(bak, existing);
245
246
  result.backedUp.push(bak);
246
247
  }
247
248
  writeFileSync(cmPath, next);
@@ -254,7 +255,7 @@ export function harnessInit({ root = findProjectRoot(), force = false, scope = '
254
255
  // via the BEGIN/END markers.
255
256
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15); // YYYYMMDDTHHMMSS
256
257
  const bak = `${cmPath}.bak-${stamp}`;
257
- writeFileSync(bak, existing);
258
+ writePrivateFile(bak, existing);
258
259
  const sep = existing.endsWith('\n') ? '\n' : '\n\n';
259
260
  writeFileSync(cmPath, existing + sep + block);
260
261
  result.backedUp.push(bak);
@@ -330,7 +331,7 @@ export function harnessUninit({ root = findProjectRoot(), purgeRatchet = false,
330
331
  } else if (beginIdx !== -1) {
331
332
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
332
333
  const bak = `${cmPath}.bak-${stamp}`;
333
- writeFileSync(bak, existing);
334
+ writePrivateFile(bak, existing);
334
335
  const re = new RegExp(
335
336
  `\\n*${escapeRe(HARNESS_BLOCK_BEGIN)}[\\s\\S]*?${escapeRe(HARNESS_BLOCK_END)}\\n?`,
336
337
  'm',
@@ -349,7 +350,7 @@ export function harnessUninit({ root = findProjectRoot(), purgeRatchet = false,
349
350
  if (purgeRatchet && existsSync(rmPath)) {
350
351
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
351
352
  const bak = `${rmPath}.bak-${stamp}`;
352
- writeFileSync(bak, readFileSync(rmPath, 'utf8'));
353
+ writePrivateFile(bak, readFileSync(rmPath, 'utf8'));
353
354
  result.backedUp.push(bak);
354
355
  // Replace with empty initial template rather than delete (preserves dir).
355
356
  writeFileSync(rmPath, harnessRatchetMdInitial());
@@ -554,7 +555,7 @@ export function harnessPrune({ root = findProjectRoot(), scope = 'project', agen
554
555
  });
555
556
  if (dryRun || doomed.length === 0) return { ok: true, path: rmPath, pruned: doomed, dryRun: true };
556
557
  const content = readFileSync(rmPath, 'utf8');
557
- writeFileSync(rmPath + '.bak', content);
558
+ writePrivateFile(rmPath + '.bak', content);
558
559
  const drop = new Set(doomed.map((r) => r.lineNo));
559
560
  const kept = content.split('\n').filter((_, i) => !drop.has(i));
560
561
  writeFileSync(rmPath, kept.join('\n'));
@@ -585,7 +586,7 @@ export function harnessRmRule(n, { root = findProjectRoot(), scope = 'project',
585
586
  return { ok: false, error: `No rule #${n} (have ${rules.length})`, rules };
586
587
  }
587
588
  const content = readFileSync(rmPath, 'utf8');
588
- writeFileSync(rmPath + '.bak', content);
589
+ writePrivateFile(rmPath + '.bak', content);
589
590
  const lines = content.split('\n');
590
591
  lines.splice(target.lineNo, 1);
591
592
  writeFileSync(rmPath, lines.join('\n'));
package/src/installer.js CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { writeFileSync, mkdirSync, existsSync, unlinkSync, readFileSync, rmSync, copyFileSync, renameSync, realpathSync, statSync } from 'node:fs';
17
17
  import { loadConfig, saveConfig } from './config.js';
18
+ import { restrictFile } from './private-file.js';
18
19
  import { CLI_NAME, LEGACY_CLI_NAME } from './cli-name.js';
19
20
  import { join, dirname, resolve } from 'node:path';
20
21
  import { homedir } from 'node:os';
@@ -163,6 +164,7 @@ export function writeSettings(file, settings) {
163
164
  target = realpathSync(file);
164
165
  mode = statSync(target).mode & 0o777;
165
166
  copyFileSync(target, `${target}.sprag-bak`);
167
+ restrictFile(`${target}.sprag-bak`);
166
168
  }
167
169
  const tmpPath = target === file ? tmp : `${target}.sprag-tmp-${process.pid}`;
168
170
  try {
@@ -0,0 +1,145 @@
1
+ /**
2
+ * judgement-prompt — does a subagent prompt ask for work whose conclusion is a
3
+ * judgement?
4
+ *
5
+ * The delegation grade (routing-switch.js) needs this at the moment the main
6
+ * model hands work to a haiku or sonnet subagent. Work whose answer is read off
7
+ * a command's output or a named file relays fine on a cheaper tier. Work whose
8
+ * answer is a judgement does not: a review that ends in priorities, an audit, a
9
+ * root-cause diagnosis, a web search for candidates, a lookup where "there is
10
+ * none" may be the answer, a check where the output decides what to open next.
11
+ * A cheaper model hands back a confident, wrong answer there and nothing
12
+ * announces it, so the guard sends that work to Opus (see delegation-guard.js).
13
+ *
14
+ * This is a regex and keyword pass, no model call: the hook runs on every
15
+ * Task/Agent call and has to stay in the milliseconds. Precision comes first.
16
+ * A false positive reroutes a delegation that was fine, a false
17
+ * negative only leaves today's behaviour in place.
18
+ *
19
+ * Left out on purpose: a prompt that names the pages to read and only copies
20
+ * facts off them ("Read https://... and quote ..."), which the rule set keeps
21
+ * as a delegable web read. A prompt that is nothing but a file path to an
22
+ * instruction sheet says nothing the pass can read, so it stays unflagged too.
23
+ *
24
+ * Measured 2026-11-08 against the lanes of the narrow-v3 assignment (54
25
+ * prompts, lane 'main' counted as judgement). Six 'main' prompts that are only
26
+ * a file path or a one-word reply say nothing a pass can read and were left
27
+ * out, which leaves 32 positives and 16 negatives:
28
+ *
29
+ * flagged not flagged
30
+ * main 25 7 recall 0.78 (25/32)
31
+ * other 1 15 precision 0.96 (25/26)
32
+ *
33
+ * The patterns were tuned on these same 54 prompts, so the figures are
34
+ * in-sample; with 16 negatives they are an order of magnitude, not a rate.
35
+ * The misses are mostly page reads whose questions end in "does the page say
36
+ * X": the assignment labels some 'main' and near-identical ones 'web', and no
37
+ * pattern separates the two. The one false positive is such a page read.
38
+ *
39
+ * Re-measured 2026-11-09 after a live session missed a review: paths now
40
+ * shrink to one token before matching (see judgementEvidence), which moved
41
+ * recall from 0.72 to 0.78, and the bare words "audit" and "읽기 전용 조사"
42
+ * left the audit pattern ("it feeds a security audit" and "read-only
43
+ * investigation" describe the purpose, not the job). Over the 240 prompts of
44
+ * the delegation-ledger snapshot the pass flags 52, about 22%. Both samples
45
+ * come from one user.
46
+ */
47
+
48
+ const MARKER = '<!-- sprag:delegation -->';
49
+
50
+ // Each kind is a list of regexes over the lowercased prompt, checked in this
51
+ // order so the kinds a stricter grade acts on come first. A prompt is a
52
+ // judgement when any pattern of any kind matches, unless a gate below applies.
53
+ const PATTERNS = {
54
+ diagnosis: [
55
+ /원인(?:을|이|은)? ?(?:진단|분석|찾|파악|조사|가 (?:뭐|무엇))|원인 진단|근본 ?원인|root[- ]?cause|\bdiagnos(?:e|es|is)\b|왜 (?:실패|느|안 ?되|안 ?돼|죽|멈|깨|오류|에러)|why (?:does|is|did|are|do|it|the)\b[^\n]{0,60}(?:fail|slow|crash|break|broken|not work|wrong|hang|stuck|0 impressions)|무엇이 문제|what(?:'s| is) (?:wrong|causing)|troubleshoot/,
56
+ ],
57
+ audit: [
58
+ /감사(?:해|하|를|\s|$)|\baudit (?:the|this|my|our|for|of|it)\b|security review|보안 (?:점검|검토|허점|감사)|허점|취약(?:점|성)[^\n]{0,12}(?:찾|점검|분석|있는지)|vulnerabilit[^\n]{0,20}(?:find|audit|review|look for)|문제(?:점|를|가)? ?(?:찾|발견)|find (?:the )?(?:problems|issues|bugs|gaps|weak)|훑어/,
59
+ ],
60
+ review: [
61
+ /개선점|개선 ?방안|권고|우선순위|improvements?\b|\brecommendations\b|\brecommend (?:which|the (?:best|top)|one|a (?:top|best))\b|prioriti[sz]|순위를 (?:매기|내)|상위 \d+\s*(?:개|건)[^\n]{0,30}(?:추천|고르|선정)|추천(?:해|까지|을)/,
62
+ /(?:검토|리뷰|review)(?:해|하여|해서|하십시오|하세요|를 해| the| this| my)?[^\n]{0,40}(?:개선|문제|결함|issues?|problems?|weakness|improve)/,
63
+ ],
64
+ search: [
65
+ // Looking for sources, candidates or cases on the web. The strong words say
66
+ // so on their own; a site name needs a research verb beside it, because
67
+ // "post it on Hacker News" is not a search.
68
+ /\bwebsearch\b|web search|웹 ?검색|검색으로|검색해|search the web|search for (?:candidates|packs|sources|alternatives|places|options|tools|articles|papers)|(?:web|market)[- ]research|research task|웹 조사|web only|웹으로 조사/,
69
+ /(?:reddit|레딧|hacker news|\bhn\b|itch\.io|github)[\s\S]{0,400}(?:조사|research|수집|모으|모은다|찾아|find\b|후보|candidates|evidence|what practitioners)|(?:조사|research|수집|모으|모은다|찾아|후보|candidates|evidence)[\s\S]{0,400}(?:reddit|레딧|hacker news)/,
70
+ ],
71
+ absence: [
72
+ /없다는 (?:결론|사실)|없다고 (?:단정|판단|보고)|없음을 (?:확인|단정)|(?:is|are) there any\b|does (?:it|the page|the doc|the docs|any page|this) (?:say|mention|describe)|any mention\b|if the page does not answer|read-only search\b/,
73
+ ],
74
+ conditional: [
75
+ /출력에 따라|결과에 따라|보고 (?:나서 )?(?:더 |어느 )|필요하면 (?:소스|코드|파일|로그)|depending on (?:what|the output|the result)|decide (?:which|what) to (?:open|read|look)|follow (?:the )?leads|(?:무엇|뭔)(?:인지)?(?:는|은)? 아직 모(?:른다|릅니다)|구현 (?:상태|여부)[^\n]{0,10}(?:조사|확인)|(?:막히면|실패하면|안 되면|if (?:it is blocked|that fails|blocked))[^\n]{0,80}(?:다음|대체|우회|fall ?back|시도|instead|try)/,
76
+ ],
77
+ };
78
+
79
+ /**
80
+ * A prompt that hands over a finished design to build. The wording ("the
81
+ * design is fixed", "implement the following") is how the main model briefs
82
+ * the implementation worker, and its text mentions audits, reviews and
83
+ * searches only as things the code does. Reading those as the task is the
84
+ * most common false positive in the ledger snapshot.
85
+ */
86
+ const IMPLEMENTATION_BRIEF = /구현 작업|설계(?:가|는|를)? (?:이미 )?확정|권장 모델|수정할 파일|수정 대상|(?:만들|작성할|생성할) 파일|완료 기준|leave (?:the )?changes uncommitted|do not git commit|커밋하지 마십시오|files to (?:create|add|change)|you are (?:extending|implementing)|^\s*(?:implement|extend)\b|implement the follow|(?:design|spec) is (?:fixed|final|settled)/;
87
+
88
+ /**
89
+ * A prompt that closes the web off and points at a file or pasted text to work
90
+ * from. Its mentions of Reddit or Hacker News name the content, not a search.
91
+ */
92
+ const SOURCE_IS_GIVEN = /파일 내용만으로|파일만으로|웹을 새로 조회하지|(?:do not|don't) (?:search|browse|fetch)[^\n]{0,20}(?:the )?web|only from the (?:file|text)/;
93
+
94
+ /** True when `re` matched at `m.index` inside a negation, "do not diagnose" or "원인 분석을 하지 말고". */
95
+ function negated(text, m) {
96
+ const before = text.slice(Math.max(0, m.index - 14), m.index);
97
+ const after = text.slice(m.index + m[0].length, m.index + m[0].length + 14);
98
+ return /(?:do not|don't|never|without|no)\s+$/.test(before) || /하지 (?:말|마|않)|금지|안 ?합니다/.test(after);
99
+ }
100
+
101
+ /**
102
+ * A prompt that names pages and asks for what they say. The gate looks for a
103
+ * URL, a read or fetch verb, and no search verb, so a prompt that goes looking
104
+ * for sources is not mistaken for a page read.
105
+ */
106
+ function isPageRead(text) {
107
+ if (!/https?:\/\//.test(text)) return false;
108
+ if (!/\b(?:read|fetch|open)\b|읽고|읽어|확인할 페이지/.test(text)) return false;
109
+ const bare = text.replace(/https?:\/\/\S+/g, ' ');
110
+ return !PATTERNS.search.some((re) => re.test(bare));
111
+ }
112
+
113
+ /**
114
+ * @param {string} prompt - the subagent prompt as the caller wrote it
115
+ * @returns {{ judgement: boolean, kind: 'review'|'audit'|'diagnosis'|'search'|'absence'|'conditional'|null }}
116
+ */
117
+ export function isJudgementDelegation(prompt) {
118
+ const { judgement, kind } = judgementEvidence(prompt);
119
+ return { judgement, kind };
120
+ }
121
+
122
+ /** Same answer plus the text that triggered it, for tests and for measuring false positives. */
123
+ export function judgementEvidence(prompt) {
124
+ if (typeof prompt !== 'string' || prompt === '') return { judgement: false, kind: null, match: null };
125
+ // The guard's own appendix is not part of what the caller asked for.
126
+ const cut = prompt.indexOf(MARKER);
127
+ // Paths shrink to one token first. The patterns keep their words within a
128
+ // short distance, and a real delegation names its directory in full: "review
129
+ // the file app.js in /private/tmp/…/project for security problems" put 70
130
+ // characters between the verb and its object and passed as not judgement in a
131
+ // live session, while the same prompt with a short path was caught.
132
+ const text = (cut === -1 ? prompt : prompt.slice(0, cut)).toLowerCase()
133
+ .replace(/(?:~|\.{0,2})?\/[^\s`'"()<>,;]+/g, '<path>');
134
+ if (IMPLEMENTATION_BRIEF.test(text) || SOURCE_IS_GIVEN.test(text) || isPageRead(text)) return { judgement: false, kind: null, match: null };
135
+ for (const [kind, res] of Object.entries(PATTERNS)) {
136
+ for (const re of res) {
137
+ const m = re.exec(text);
138
+ if (m && !negated(text, m)) return { judgement: true, kind, match: m[0].slice(0, 40) };
139
+ }
140
+ }
141
+ return { judgement: false, kind: null, match: null };
142
+ }
143
+
144
+ /** Kinds the 'cost' grade still raises: a wrong answer here costs the most and shows the least. */
145
+ export const SAVING_GRADE_KINDS = new Set(['diagnosis', 'audit']);
@@ -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
  '',