sprag-cli 3.88.0 → 3.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -208,6 +208,7 @@ Usage:
208
208
  sprag litellm-budget LiteLLM gateway key budget and spend
209
209
  sprag update-check is a newer version out?
210
210
  sprag brief --hook internal: the UserPromptSubmit hook entry point
211
+ sprag brief --hook-tool internal: the PostToolUse hook entry point (delegation follow-up)
211
212
  sprag feedback "<msg>" file a bug report / feature request (no browser needed)
212
213
  sprag team create|join|status|sync|leave opt-in team layer: daily aggregates only (SPRAG_NO_TEAM_SYNC=1 turns it off)
213
214
  sprag upgrade install the latest release
@@ -353,6 +354,8 @@ async function main() {
353
354
  // brief --hook — UserPromptSubmit hook mode: per-session, change-triggered
354
355
  // briefing of state the statusline can only chip (ctx tier crossings,
355
356
  // mid-session route/rule-health changes). Silent when nothing changed.
357
+ // brief --hook-tool — PostToolUse hook mode: one nudge when a hinted turn
358
+ // keeps looking things up instead of delegating.
356
359
  if (args[0] === 'brief') {
357
360
  return (await import('../src/commands/brief.js')).run({ hasFlag });
358
361
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.88.0",
3
+ "version": "3.89.1",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -6,7 +6,7 @@ import { userDataDir } from '../paths.js';
6
6
  import { writeViaTmp } from '../state-file.js';
7
7
  import { codexUserDir, codexProviderName } from '../agent.js';
8
8
  import { categorize, ESCALATE_RE, EDIT_RE } from '../route-scan.js';
9
- import { looksPasted } from '../route-inject.js';
9
+ import { looksPasted, isSystemPrompt, isOpinionQuestion } from '../route-inject.js';
10
10
  import { newRouteId, recordCodexDelegation } from './ledger.js';
11
11
  import { readCodexTailLines } from './parser.js';
12
12
  import { loadConfig } from '../config.js';
@@ -226,6 +226,9 @@ export function removeCodexModelRule(index, { dir = userDataDir() } = {}) {
226
226
  */
227
227
  export function codexPromptCategory(text) {
228
228
  const prompt = typeof text === 'string' ? text.trim() : '';
229
+ // Same two gates as the Claude Code hint (routeMatch): a harness message is
230
+ // not a request, and an opinion question is judgement rather than a lookup.
231
+ if (isSystemPrompt(prompt) || isOpinionQuestion(prompt)) return null;
229
232
  if (prompt.length < 8 || ESCALATE_RE.test(prompt) || EDIT_RE.test(prompt) || /\b(?:implement|modify|fix|delete|push|commit)\b/i.test(prompt)) return null;
230
233
  const category = categorize(prompt, null);
231
234
  if (!category || (category.id === 'paste' && !looksPasted(prompt))) return null;
@@ -12,7 +12,8 @@ import { writeViaTmp } from '../state-file.js';
12
12
  import { findProjectRoot } from '../harness.js';
13
13
  import { runCodexBrief } from './brief.js';
14
14
  import { codexDocumentTool, codexDocumentNote, convertCodexDocument, codexDocumentContext } from './doc2md.js';
15
- import { codexDelegationTool, codexRouteHint, codexDelegateEnabled } from './delegation.js';
15
+ import { codexDelegationTool, codexRouteHint, codexDelegateEnabled, codexPromptCategory } from './delegation.js';
16
+ import { startFollow, clearFollow, followToolUse } from '../route-follow.js';
16
17
  import { bindCodexSubagent, closeStaleCodexRoutes, unsettledCodexRoutes } from './ledger.js';
17
18
  import { seedOfferBlock } from '../seed-rules.js';
18
19
  import { readCodexRouteScan, openCodexCandidates, shouldRescanCodex } from './route-scan.js';
@@ -174,6 +175,9 @@ export async function codexHookOutput(event, payload, { cfg = loadConfig(), refr
174
175
  if (event === 'subagent-start' && !codexDelegateEnabled(cfg)) return null;
175
176
  if (event === 'subagent-start') {
176
177
  try { bindCodexSubagent(payload); } catch (e) { debug('codex:bind', e); }
178
+ // A child was spawned, so the parent's turn stops being counted for the
179
+ // follow-up nudge. `spawn_agent` is the tool name followToolUse treats as a delegation.
180
+ try { followToolUse({ session_id: payload.session_id, tool_name: 'spawn_agent' }, { cfg }); } catch (e) { debug('codex:follow-stop', e); }
177
181
  }
178
182
  const root = findProjectRoot(payload.cwd || process.cwd(), { agent: 'codex' });
179
183
  const parts = [];
@@ -237,9 +241,27 @@ export async function codexHookOutput(event, payload, { cfg = loadConfig(), refr
237
241
  // that no child claimed is closed, and children that did run get priced.
238
242
  try { closeStaleCodexRoutes(payload); } catch (e) { debug('codex:close-routes', e); }
239
243
  try { if (unsettledCodexRoutes() > 0) refreshLedger(); } catch (e) { debug('codex:ledger-refresh', e); }
244
+ let routeHint = null;
240
245
  try {
241
- parts.push(codexRouteHint(payload, { cfg, root: findProjectRoot(payload.cwd || process.cwd(), { agent: 'codex' }) }));
246
+ routeHint = codexRouteHint(payload, { cfg, root: findProjectRoot(payload.cwd || process.cwd(), { agent: 'codex' }) });
247
+ parts.push(routeHint);
242
248
  } catch (e) { debug('codex:route-hint', e); }
249
+ // A hinted turn is followed by PostToolUse, which nudges once if the
250
+ // parent keeps looking things up itself. An unhinted prompt clears the last turn's record.
251
+ try {
252
+ const category = routeHint ? codexPromptCategory(payload.prompt) : null;
253
+ if (routeHint && category) {
254
+ startFollow(payload.session_id, {
255
+ agent: 'codex',
256
+ category: category.id,
257
+ label: category.labelEn || category.id,
258
+ target: 'the child the routing hint named (spawn it with that model and route line)',
259
+ lang: 'en',
260
+ });
261
+ } else {
262
+ clearFollow(payload.session_id);
263
+ }
264
+ } catch (e) { debug('codex:route-follow', e); }
243
265
  }
244
266
  if (cfg?.codex?.brief !== false) {
245
267
  try {
@@ -262,12 +284,16 @@ export async function codexHookOutput(event, payload, { cfg = loadConfig(), refr
262
284
  return codexDelegationTool(payload, { cfg, root: findProjectRoot(payload.cwd || process.cwd(), { agent: 'codex' }) });
263
285
  }
264
286
  if (event === 'post-tool') {
265
- if (!koreanStyleEnabled(cfg) || cfg?.koreanStyle?.lint === 'off') return null;
266
- const result = lintCodexTool(payload, { scope: cfg?.koreanStyle?.lintScope === 'prose' ? 'prose' : 'all' });
267
- const text = typeof result === 'string' ? result : result ? lint.formatFindings(result.filePath, result.findings) : null;
268
- if (!text) return null;
269
- if (cfg?.koreanStyle?.lint === 'warn') return context('PostToolUse', text);
270
- return { decision: 'block', reason: text };
287
+ // The follow-up nudge runs whether or not the Korean style check is on, so
288
+ // it is computed first and merged with the check's result.
289
+ const nudge = followToolUse(payload, { cfg });
290
+ let text = null;
291
+ if (koreanStyleEnabled(cfg) && cfg?.koreanStyle?.lint !== 'off') {
292
+ const result = lintCodexTool(payload, { scope: cfg?.koreanStyle?.lintScope === 'prose' ? 'prose' : 'all' });
293
+ text = typeof result === 'string' ? result : result ? lint.formatFindings(result.filePath, result.findings) : null;
294
+ }
295
+ if (text && cfg?.koreanStyle?.lint !== 'warn') return { decision: 'block', reason: nudge ? `${text}\n\n${nudge}` : text };
296
+ return context('PostToolUse', [text, nudge].filter(Boolean).join('\n\n'));
271
297
  }
272
298
  throw new Error(`Unknown Codex hook event: ${event}`);
273
299
  }
@@ -11,14 +11,28 @@
11
11
  * brief --hook — UserPromptSubmit hook mode: per-session, change-triggered
12
12
  * briefing of state the statusline can only chip (ctx tier crossings,
13
13
  * mid-session route/rule-health changes). Silent when nothing changed.
14
+ * brief --hook-tool — PostToolUse hook mode: counts the direct lookups of a
15
+ * turn that carried a delegation hint and nudges once (src/route-follow.js).
14
16
  */
15
17
 
16
18
  import { readStdinJson } from '../stdin-payload.js';
17
19
  import { debug } from '../debug.js';
18
20
 
19
21
  export async function run({ hasFlag }) {
22
+ if (hasFlag('--hook-tool')) {
23
+ // PostToolUse: a nudge is context for the model, so it goes out as
24
+ // hookSpecificOutput; nothing is printed when there is nothing to say.
25
+ try {
26
+ const { followToolUse } = await import('../route-follow.js');
27
+ const nudge = followToolUse(readStdinJson() || {});
28
+ if (nudge) {
29
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: nudge } }));
30
+ }
31
+ } catch (e) { debug('brief:hook-tool', e); }
32
+ return;
33
+ }
20
34
  if (!hasFlag('--hook')) {
21
- console.error('Usage: sprag brief --hook (UserPromptSubmit hook mode)');
35
+ console.error('Usage: sprag brief --hook (UserPromptSubmit hook mode)\n sprag brief --hook-tool (PostToolUse hook mode)');
22
36
  process.exit(1);
23
37
  }
24
38
  const ctx = readStdinJson() || {};
@@ -39,7 +53,7 @@ export async function run({ hasFlag }) {
39
53
  // the match here removes both steps. Silent unless it is sure — see
40
54
  // src/route-inject.js.
41
55
  try {
42
- const { routeHint, routeMatch, matchCaps, sessionModelRank } = await import('../route-inject.js');
56
+ const { routeHint, routeMatch, matchCaps, sessionModelRank, hintTarget, hintLabel } = await import('../route-inject.js');
43
57
  // The payload names the session but not its model, so the rank comes from
44
58
  // the transcript: without it a Sonnet session is told to delegate to
45
59
  // Sonnet, which saves nothing.
@@ -54,6 +68,25 @@ export async function run({ hasFlag }) {
54
68
  const match = routeMatch(ctx.prompt, { sessionRank, root: ctx.cwd });
55
69
  const hint = routeHint(ctx.prompt, { sessionRank, root: ctx.cwd, match });
56
70
  if (hint) parts.push(hint);
71
+ // Remember that this turn carried a delegation hint, so the PostToolUse
72
+ // hook can nudge when the model looks things up itself instead. The
73
+ // unreachable-only notice tells the model NOT to delegate, so it starts
74
+ // no follow-up. A prompt without a hint clears the previous turn's record.
75
+ try {
76
+ const { startFollow, clearFollow } = await import('../route-follow.js');
77
+ const { userLanguage } = await import('../config.js');
78
+ if (hint && match && (match.t2 || match.t1 || match.t1h)) {
79
+ const lang = userLanguage();
80
+ startFollow(ctx.session_id, {
81
+ category: match.cat.id,
82
+ label: hintLabel(match, { lang }),
83
+ target: hintTarget(match, { lang, root: ctx.cwd }),
84
+ lang,
85
+ });
86
+ } else {
87
+ clearFollow(ctx.session_id);
88
+ }
89
+ } catch (e) { debug('brief:route-follow', e); /* never block a prompt */ }
57
90
  // The delegation guard repeats these caps to the subagent, so the limit it
58
91
  // works under is the one this hint states. A prompt with no match clears
59
92
  // the record of the turn before it.
@@ -10,6 +10,7 @@ import { signedUsd } from '../money.js';
10
10
  import { codexProviderName, codexModelName } from '../agent.js';
11
11
  import { loadSharedModelRules, sharedModelRulesForProject, SHARED_RULE_TIERS } from '../shared-model-rules.js';
12
12
  import { codexDelegationDiagnostics } from '../codex/delegation-diagnostics.js';
13
+ import { followStats } from '../route-follow.js';
13
14
 
14
15
  // Starts from the working directory, as the hooks do, so a project policy
15
16
  // stored under either agent's project root is counted.
@@ -137,11 +138,17 @@ export function run({ args, getArg, hasFlag, root }) {
137
138
  let events = [];
138
139
  try { events = Object.values(loadCodexLedger().events); } catch { /* No ledger yet: rules list without outcomes. */ }
139
140
  const inReview = new Set(codexRulesInReview({ rules, events, root: null }).map((x) => x.index));
141
+ // How hinted turns of each category ended (src/route-follow.js); the shared
142
+ // policies printed below are not per-category lines, so only these rules get it.
143
+ let follow = new Map();
144
+ try { follow = followStats({ days: 14, agent: 'codex' }); } catch { /* No event log yet. */ }
140
145
  rules.forEach((r, i) => {
141
146
  const h = codexRuleHealth(r, { events });
142
147
  const outcome = h.runs ? ` | measured x${h.runs}, err ${Math.round(h.rate * 100)}%, saved ${signedUsd(h.saved, 4)}` : '';
143
148
  const warn = inReview.has(i + 1) ? ` | rule-health: ${h.errs}/${h.runs} runs failed, narrow the condition or remove (delegate rules rm ${i + 1} --agent codex)` : '';
144
149
  console.log(`#${i + 1} ${r.category} | ${r.from} -> ${r.model} | ${r.scope}${r.targetRoot ? ` ${r.targetRoot}` : ''}${outcome}${warn}`);
150
+ const f = follow.get(r.category);
151
+ if (f && f.hints > 0) console.log(` hints x${f.hints} | delegated at once ${f.delegatedAtOnce} | nudged ${f.nudged} -> delegated ${f.delegatedAfterNudge} (last 14 days)`);
145
152
  });
146
153
  printShared(cfg, { details: true });
147
154
  return;
@@ -91,6 +91,7 @@ export async function run({ hasFlag }) {
91
91
  print('mod (desktop statusline, Claude Code 2.1.287+)', r.statuslineMod);
92
92
  if (r.statuslineMod.reason) console.log(` ${r.statuslineMod.reason}`);
93
93
  print('UserPromptSubmit hook (brief)', r.briefHook);
94
+ print('PostToolUse hook (delegation follow-up)', r.routeFollowHook);
94
95
  {
95
96
  let s = r.statusline;
96
97
  // A different statusline is already installed. Replacing it silently
@@ -154,6 +154,9 @@ export async function run({ args, hasFlag, numArg }) {
154
154
  const { modelRank } = await import('../cost.js');
155
155
  const sessionModel = aliasForRole('main');
156
156
  const sessionRank = sessionModel ? modelRank(sessionModel) : null;
157
+ // Read once: how the hinted turns of each category ended (src/route-follow.js).
158
+ let follow = new Map();
159
+ try { follow = (await import('../route-follow.js')).followStats({ days: 14, agent: 'claude' }); } catch (e) { debug('route-scan:follow-stats', e); }
157
160
  rules.forEach((r, i) => {
158
161
  const health = r.status === 'review'
159
162
  ? (lang === 'ko' ? ' ⚠ 에러율 초과 — 재검토 필요' : ' ⚠ error rate over threshold — needs review')
@@ -185,6 +188,12 @@ export async function run({ args, hasFlag, numArg }) {
185
188
  ? '실제 위임 기록이 아직 없습니다.'
186
189
  : 'measured delegations — (none yet)'));
187
190
  console.log(` ${measured}`);
191
+ const f = follow.get(r.category);
192
+ if (f && f.hints > 0) {
193
+ console.log(lang === 'ko'
194
+ ? ` 위임 힌트 ${f.hints}회 · 즉시 위임 ${f.delegatedAtOnce} · 재촉 ${f.nudged}회 → 위임 ${f.delegatedAfterNudge} (최근 14일)`
195
+ : ` hints ×${f.hints} · delegated at once ${f.delegatedAtOnce} · nudged ${f.nudged} → delegated ${f.delegatedAfterNudge} (last 14 days)`);
196
+ }
188
197
  // Same composer the md file uses, so what is listed here is exactly
189
198
  // what the model reads.
190
199
  console.log(` ${mr.composeRuleText(r.rule, r, lang)}`);
package/src/installer.js CHANGED
@@ -596,6 +596,56 @@ export function installDelegationHook() {
596
596
  return { path: file, action: 'created' };
597
597
  }
598
598
 
599
+ // PostToolUse hook behind the delegation follow-up (src/route-follow.js). After
600
+ // a prompt carried a delegation hint, it counts the model's direct lookups and
601
+ // nudges once at the second. The matcher lists what the counter reads: lookups,
602
+ // shell, edits, delegations, and MCP/web tools. Anything else never starts it.
603
+ //
604
+ // The same command also runs on PreToolUse for Task/Agent. PostToolUse for a
605
+ // delegation arrives only once the subagent has finished, and the subagent's
606
+ // own lookups in between would otherwise count toward the parent's turn and
607
+ // nudge a turn that did delegate. Stopping the count when the call starts closes
608
+ // that window without relying on a subagent marker in the payload.
609
+ const ROUTE_FOLLOW_HOOK_COMMAND = `${CLI} brief --hook-tool`;
610
+ const ROUTE_FOLLOW_MATCHER = 'Read|Grep|Glob|LS|Bash|Edit|Write|MultiEdit|NotebookEdit|Task|Agent|WebFetch|WebSearch|mcp__.*';
611
+ const ROUTE_FOLLOW_PRE_MATCHER = 'Task|Agent';
612
+
613
+ export function installRouteFollowHook() {
614
+ const dir = claudeUserDir();
615
+ const file = join(dir, 'settings.json');
616
+ mkdirSync(dir, { recursive: true });
617
+
618
+ const read = readSettings(file);
619
+ if (read.state === 'unusable') return { path: file, action: 'skipped', reason: read.reason };
620
+ const settings = read.settings;
621
+
622
+ const hooksProblem = ensureHooksObject(settings);
623
+ if (hooksProblem) return { path: file, action: 'skipped', reason: hooksProblem };
624
+ for (const event of ['PostToolUse', 'PreToolUse']) {
625
+ if (settings.hooks[event] !== undefined && !Array.isArray(settings.hooks[event])) {
626
+ return { path: file, action: 'skipped', reason: `hooks.${event} is not an array — fix settings.json manually` };
627
+ }
628
+ }
629
+ // Whole-token match: `brief --hook` (UserPromptSubmit) must not count as this hook.
630
+ const ours = (list) => list.some((m) =>
631
+ Array.isArray(m?.hooks) && m.hooks.some((h) => isOurSubcommand(h?.command, 'brief', '--hook-tool')),
632
+ );
633
+ let added = false;
634
+ for (const [event, matcher] of [['PostToolUse', ROUTE_FOLLOW_MATCHER], ['PreToolUse', ROUTE_FOLLOW_PRE_MATCHER]]) {
635
+ const list = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : [];
636
+ if (ours(list)) continue;
637
+ list.push({ matcher, hooks: [{ type: 'command', command: ROUTE_FOLLOW_HOOK_COMMAND, timeout: 5 }] });
638
+ settings.hooks[event] = list;
639
+ added = true;
640
+ }
641
+ if (!added) return { path: file, action: 'exists' };
642
+ {
643
+ const writeProblem = writeSettings(file, settings);
644
+ if (writeProblem) return { path: file, action: 'skipped', reason: writeProblem };
645
+ }
646
+ return { path: file, action: 'created' };
647
+ }
648
+
599
649
  const BRIEF_HOOK_COMMAND = `${CLI} brief --hook`;
600
650
 
601
651
  export function installBriefHook() {
@@ -1346,6 +1396,7 @@ export function installAll({ force = false } = {}) {
1346
1396
  delegationMeterMod: installDelegationMeterMod(),
1347
1397
  statuslineMod: installStatuslineMod(),
1348
1398
  briefHook: installBriefHook(),
1399
+ routeFollowHook: installRouteFollowHook(),
1349
1400
  cacheMonitorMigration: migrateLegacyCacheMonitorHook(),
1350
1401
  legacy: removeLegacyCommand(),
1351
1402
  };
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Follow-up after a delegation hint: one nudge when the model starts looking
3
+ * things up itself instead of delegating.
4
+ *
5
+ * Why this exists: the prompt hint (src/route-inject.js) says "delegate this".
6
+ * Measured over 14 days, 22 of 100 hinted turns delegated. 21 of the 23
7
+ * delegating turns delegated before any direct lookup; the 38 turns that did
8
+ * not delegate ran two or more direct lookups with no edit. Once the model has
9
+ * made its second lookup it is committed to doing the work itself, and the hint
10
+ * is two screens behind. So a PostToolUse hook counts the lookups of a hinted
11
+ * turn and, at the second one, says so once.
12
+ *
13
+ * What counts: read-only lookups (Read, Grep, Glob, LS, a shell command that
14
+ * changes nothing) as `c`, and MCP or web tools as `g`. What stops the count: a
15
+ * delegation, an edit, or a shell command that mutates something. Those turns
16
+ * are not "lookups instead of delegating" and the nudge would be noise.
17
+ *
18
+ * State is split over several small files per session instead of one JSON,
19
+ * because the PostToolUse hooks of parallel tool calls run at the same time.
20
+ * Each file has one writer role:
21
+ * <sid>.json written once by the prompt hook (startFollow)
22
+ * <sid>.calls one appended line per counted call (`c` or `g`); an append of
23
+ * a single short line is atomic enough that no count is lost
24
+ * <sid>.stop the counting for this turn is over
25
+ * <sid>.nudged created with the `wx` flag, so of several processes that all
26
+ * see "two lookups" exactly one wins and speaks
27
+ * All of it lives under <dir>/route-follow/. Events go to a separate JSONL
28
+ * (<dir>/route-follow-events.jsonl) so `route-scan rules` can show how often a
29
+ * hint, and the nudge after it, ended in a delegation.
30
+ *
31
+ * The module never throws into a hook: followToolUse swallows everything.
32
+ */
33
+
34
+ import {
35
+ mkdirSync, writeFileSync, appendFileSync, readFileSync, rmSync, existsSync, openSync, closeSync, statSync,
36
+ } from 'node:fs';
37
+ import { join } from 'node:path';
38
+ import { userDataDir } from './paths.js';
39
+ import { loadConfig } from './config.js';
40
+ import { writeStateFile } from './state-file.js';
41
+ import { debug } from './debug.js';
42
+
43
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
44
+ /** A hinted turn still running this long after its prompt is left over from a session that ended. */
45
+ const TURN_TTL_MS = 60 * 60 * 1000;
46
+ /** Lookups on the turn at which the nudge goes out. */
47
+ const NUDGE_AT = 2;
48
+ const EVENTS_FILE = 'route-follow-events.jsonl';
49
+ const EVENTS_MAX_BYTES = 2 * 1024 * 1024;
50
+ const EVENTS_KEEP_MS = 30 * 24 * 60 * 60 * 1000;
51
+ const DAY_MS = 24 * 60 * 60 * 1000;
52
+
53
+ const DELEGATE_TOOLS = new Set(['Task', 'Agent', 'spawn_agent']);
54
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
55
+ const SHELL_TOOLS = new Set(['Bash', 'exec_command', 'shell_command', 'shell']);
56
+ const LOOKUP_TOOLS = new Set(['Read', 'Grep', 'Glob', 'LS']);
57
+ const GENERAL_TOOLS = new Set(['WebFetch', 'WebSearch']);
58
+
59
+ /**
60
+ * A shell command that changes something: version control moves, installs,
61
+ * file operations, cluster or infrastructure writes, and any redirect to a file
62
+ * (`2>&1` and `> /dev/null` are not). Such a command means the turn is doing
63
+ * work, not looking around.
64
+ */
65
+ const MUTATING_BASH_RE = /\b(?:git\s+(?:commit|push|merge|rebase|reset|tag|checkout|switch|stash|cherry-pick|revert)|npm\s+(?:publish|version|install|i|uninstall)\b|rm\s|mv\s|cp\s|mkdir\s|touch\s|chmod\s|sed\s+-i|tee\s|kubectl\s+(?:apply|delete|edit|patch)|terraform\s+(?:apply|destroy))|(?:^|[^<>&0-9])>{1,2}\s*(?!&|\/dev\/null)\S/;
66
+
67
+ const baseDir = (dir) => dir || userDataDir();
68
+ const stateDir = (dir) => join(baseDir(dir), 'route-follow');
69
+ const eventsPath = (dir) => join(baseDir(dir), EVENTS_FILE);
70
+
71
+ function paths(sessionId, dir) {
72
+ const d = stateDir(dir);
73
+ return {
74
+ d,
75
+ json: join(d, `${sessionId}.json`),
76
+ calls: join(d, `${sessionId}.calls`),
77
+ stop: join(d, `${sessionId}.stop`),
78
+ nudged: join(d, `${sessionId}.nudged`),
79
+ };
80
+ }
81
+
82
+ const rmQuiet = (file) => {
83
+ try { rmSync(file, { force: true }); } catch (e) { debug('route-follow:rm', e); }
84
+ };
85
+
86
+ function logEvent(dir, entry) {
87
+ try {
88
+ const file = eventsPath(dir);
89
+ mkdirSync(baseDir(dir), { recursive: true });
90
+ appendFileSync(file, JSON.stringify(entry) + '\n');
91
+ } catch (e) { debug('route-follow:event', e); }
92
+ }
93
+
94
+ /** Keep the last 30 days once the log passes 2 MB; the log is only ever a measurement. */
95
+ function trimEvents(dir, now) {
96
+ try {
97
+ const file = eventsPath(dir);
98
+ if (statSync(file).size <= EVENTS_MAX_BYTES) return;
99
+ const kept = readFileSync(file, 'utf8').split('\n').filter((line) => {
100
+ if (!line) return false;
101
+ try { return now - JSON.parse(line).at <= EVENTS_KEEP_MS; } catch { return false; }
102
+ });
103
+ writeStateFile(file, kept.length ? kept.join('\n') + '\n' : '');
104
+ } catch (e) { if (e?.code !== 'ENOENT') debug('route-follow:trim', e); }
105
+ }
106
+
107
+ /**
108
+ * Record that this turn carried a delegation hint, and reset the counters left
109
+ * by the turn before it.
110
+ *
111
+ * @param {string} sessionId
112
+ * @param {{agent?: string, category: string, label: string, target: string, lang: string}} info
113
+ * @param {{now?: number, dir?: string}} [opts] `dir` replaces the user data dir (tests)
114
+ */
115
+ export function startFollow(sessionId, { agent = 'claude', category, label, target, lang } = {}, { now = Date.now(), dir } = {}) {
116
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
117
+ const p = paths(sessionId, dir);
118
+ mkdirSync(p.d, { recursive: true });
119
+ for (const f of [p.calls, p.stop, p.nudged]) rmQuiet(f);
120
+ const turn = String(now);
121
+ writeFileSync(p.json, JSON.stringify({ turn, ts: now, agent, category, label, target, lang }) + '\n');
122
+ trimEvents(dir, now);
123
+ logEvent(dir, { at: now, agent, sessionId, turn, category, event: 'hint' });
124
+ return true;
125
+ }
126
+
127
+ /** Forget the session's hinted turn: the prompt that just arrived has no hint. */
128
+ export function clearFollow(sessionId, { dir } = {}) {
129
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return false;
130
+ const p = paths(sessionId, dir);
131
+ for (const f of [p.json, p.calls, p.stop, p.nudged]) rmQuiet(f);
132
+ return true;
133
+ }
134
+
135
+ function commandOf(input) {
136
+ if (typeof input === 'string') return input;
137
+ const c = input?.command ?? input?.cmd;
138
+ return Array.isArray(c) ? c.join(' ') : typeof c === 'string' ? c : '';
139
+ }
140
+
141
+ /** @returns {'delegated'|'edited'|'mutated'|'c'|'g'|null} what the call means for the turn */
142
+ function classify(toolName, input) {
143
+ const tool = String(toolName || '').replace(/^(?:functions|tools)\./, '');
144
+ if (DELEGATE_TOOLS.has(tool)) return 'delegated';
145
+ if (EDIT_TOOLS.has(tool)) return 'edited';
146
+ if (SHELL_TOOLS.has(tool)) return MUTATING_BASH_RE.test(commandOf(input)) ? 'mutated' : 'c';
147
+ if (LOOKUP_TOOLS.has(tool)) return 'c';
148
+ if (tool.startsWith('mcp__') || GENERAL_TOOLS.has(tool)) return 'g';
149
+ return null;
150
+ }
151
+
152
+ function nudgeText(info, n, mcp) {
153
+ const { label, target } = info;
154
+ if (info.agent === 'codex') {
155
+ return `[Sprag model routing] This turn matched the approved routing hint for ${label}, but you have run ${n} lookups yourself instead of spawning. `
156
+ + `Hand the remaining lookups to ${target}, and summarize what you have already found in the task message. `
157
+ + 'If there is a reason to continue on the main agent (a design judgement, an edit, one or two lookups left), state it in one line and continue. '
158
+ + 'This notice is sent once per turn.';
159
+ }
160
+ if (info.lang === 'ko') {
161
+ return `[sprag] 이 턴은 위임 룰 "${label}" 에 해당하는데, 위임하지 않고 직접 조회를 ${n}회 했습니다. `
162
+ + (mcp
163
+ ? 'MCP·웹 도구가 필요한 조회이므로 남은 조회는 general-purpose(model: haiku) 에 넘기고, 지금까지 확인한 내용은 위임 프롬프트에 요약해 넣으십시오. '
164
+ : `남은 조회는 ${target} 에 넘기고, 지금까지 확인한 내용은 위임 프롬프트에 요약해 넣으십시오. `)
165
+ + '직접 처리해야 할 이유(설계 판단이 필요함, 수정이 필요함, 한두 번 더 조회하면 끝남)가 있으면 그 이유를 답변에 한 줄로 밝히고 계속하십시오. '
166
+ + '이 안내는 이번 턴에 한 번만 나갑니다.';
167
+ }
168
+ return `[sprag] This turn matches the delegation rule "${label}", but you have run ${n} lookups yourself instead of delegating. `
169
+ + (mcp
170
+ ? 'These lookups need MCP or web tools, so hand the remaining ones to general-purpose (model: haiku) and summarize what you have already found in the delegation prompt. '
171
+ : `Hand the remaining lookups to ${target} and summarize what you have already found in the delegation prompt. `)
172
+ + 'If there is a reason to continue directly (a design judgement, an edit, one or two lookups left), state it in one line in your reply and continue. '
173
+ + 'This notice is sent once per turn.';
174
+ }
175
+
176
+ /**
177
+ * PostToolUse entry: count the call and, on the second direct lookup of a
178
+ * hinted turn, return the nudge.
179
+ *
180
+ * @param {object} payload hook payload (`session_id`, `tool_name`, `tool_input`)
181
+ * @returns {string|null} the notice to add as context, or null
182
+ */
183
+ export function followToolUse(payload, { now = Date.now(), cfg = loadConfig(), dir } = {}) {
184
+ try {
185
+ if (cfg?.routeFollowUp === false) return null;
186
+ // A subagent's own tool calls reach this hook under the parent's session id,
187
+ // and PostToolUse for the Task call itself only fires once the subagent has
188
+ // finished. Counting the child's lookups would nudge the child. Claude Code
189
+ // marks those payloads with `agent_id`; a payload without the field is
190
+ // treated as the main agent's.
191
+ if (payload?.agent_id) return null;
192
+ const sessionId = payload?.session_id;
193
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null;
194
+ const p = paths(sessionId, dir);
195
+ let info;
196
+ try { info = JSON.parse(readFileSync(p.json, 'utf8')); } catch (e) { if (e?.code !== 'ENOENT') debug('route-follow:read', e); return null; }
197
+ if (!info || !Number.isFinite(info.ts) || now - info.ts > TURN_TTL_MS) return null;
198
+ if (existsSync(p.stop)) return null;
199
+
200
+ const kind = classify(payload.tool_name, payload.tool_input);
201
+ if (kind === null) return null;
202
+ // PreToolUse is registered for Task/Agent only, to stop the count before the
203
+ // subagent's own lookups can reach this hook (see installRouteFollowHook).
204
+ // Any other tool seen on PreToolUse is counted on its PostToolUse instead.
205
+ if (payload.hook_event_name === 'PreToolUse' && kind !== 'delegated') return null;
206
+ const event = { at: now, agent: info.agent, sessionId, turn: info.turn, category: info.category };
207
+ if (kind === 'delegated' || kind === 'edited' || kind === 'mutated') {
208
+ writeFileSync(p.stop, '');
209
+ logEvent(dir, kind === 'delegated'
210
+ ? { ...event, event: 'delegated', nudged: existsSync(p.nudged) }
211
+ : { ...event, event: kind });
212
+ return null;
213
+ }
214
+
215
+ appendFileSync(p.calls, `${kind}\n`);
216
+ const lines = readFileSync(p.calls, 'utf8').split('\n').filter(Boolean);
217
+ if (lines.length < NUDGE_AT) return null;
218
+ // Parallel hooks can all see the count here; only the process that creates
219
+ // the marker speaks.
220
+ try { closeSync(openSync(p.nudged, 'wx')); } catch (e) {
221
+ if (e?.code !== 'EEXIST') debug('route-follow:nudged', e);
222
+ return null;
223
+ }
224
+ logEvent(dir, { ...event, event: 'nudged' });
225
+ return nudgeText(info, lines.length, lines.includes('g'));
226
+ } catch (e) {
227
+ debug('route-follow:tool', e);
228
+ return null;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * How hinted turns ended, per category, over the last `days`.
234
+ *
235
+ * @returns {Map<string, {hints: number, delegatedAtOnce: number, nudged: number, delegatedAfterNudge: number}>}
236
+ */
237
+ export function followStats({ days = 14, now = Date.now(), agent = 'claude', dir } = {}) {
238
+ const turns = new Map();
239
+ let raw = '';
240
+ try { raw = readFileSync(eventsPath(dir), 'utf8'); } catch { return new Map(); }
241
+ const since = now - days * DAY_MS;
242
+ for (const line of raw.split('\n')) {
243
+ if (!line) continue;
244
+ let e;
245
+ try { e = JSON.parse(line); } catch { continue; }
246
+ if (!e || e.agent !== agent || !Number.isFinite(e.at) || e.at < since) continue;
247
+ const key = `${e.sessionId}\u0000${e.turn}`;
248
+ let t = turns.get(key);
249
+ if (!t) { t = { category: null, hint: false, nudged: false, delegated: null }; turns.set(key, t); }
250
+ if (e.event === 'hint') { t.hint = true; t.category = e.category; }
251
+ else if (e.event === 'nudged') t.nudged = true;
252
+ else if (e.event === 'delegated' && t.delegated === null) t.delegated = e.nudged ? 'after' : 'once';
253
+ }
254
+ const out = new Map();
255
+ for (const t of turns.values()) {
256
+ // A turn counts only when its hint is in the window; later events of a
257
+ // turn whose hint was cut off cannot be attributed to a category.
258
+ if (!t.hint || !t.category) continue;
259
+ const s = out.get(t.category) || { hints: 0, delegatedAtOnce: 0, nudged: 0, delegatedAfterNudge: 0 };
260
+ s.hints += 1;
261
+ if (t.nudged) s.nudged += 1;
262
+ if (t.delegated === 'once') s.delegatedAtOnce += 1;
263
+ else if (t.delegated === 'after') s.delegatedAfterNudge += 1;
264
+ out.set(t.category, s);
265
+ }
266
+ return out;
267
+ }
@@ -28,6 +28,13 @@
28
28
  * to hand a question about how the tool behaves to a command-running haiku.
29
29
  * Answering it takes the main model's knowledge, not a command. The read
30
30
  * category is exempt: explaining is what it is for.
31
+ * - the "prompt" is a message the harness wrote, not the user: a background
32
+ * task notification, a system reminder, a slash-command echo. Measured over
33
+ * 14 days, 25 of 67 `<task-notification>` messages carried a hint.
34
+ * - the text asks for an opinion ("…하는게 좋은가?", "…괜찮지 않을까 싶은데")
35
+ * and no request verb follows. Answering it is judgement, not a lookup. On
36
+ * a 28-day corpus the pattern removed 6 of 286 hints and none of the turns
37
+ * that actually delegated.
31
38
  * A hint that fires on the wrong request costs more than one that stays quiet.
32
39
  */
33
40
 
@@ -48,6 +55,33 @@ export function looksPasted(text) {
48
55
  return lines >= PASTE_MIN_LINES || LOG_SHAPE_RE.test(text);
49
56
  }
50
57
 
58
+ /**
59
+ * Messages the harness injects into the user turn. They arrive through the same
60
+ * hook as typed prompts but are not requests, so nothing here is routed. A
61
+ * `<pasted_content` wrapper is deliberately absent: that is the user's own text.
62
+ */
63
+ const SYSTEM_PROMPT_PREFIXES = [
64
+ '<task-notification>', '<system-reminder>', '<command-name>', '<command-message>', '<command-args>',
65
+ '<local-command-', '<bash-input>', '<bash-stdout>', '<bash-stderr>', '[Request interrupted',
66
+ ];
67
+
68
+ /** True for a message the harness wrote rather than the user (see SYSTEM_PROMPT_PREFIXES). */
69
+ export function isSystemPrompt(text) {
70
+ const t = String(text || '').trim();
71
+ return SYSTEM_PROMPT_PREFIXES.some((p) => t.startsWith(p));
72
+ }
73
+
74
+ /** Endings that ask what the model thinks ("좋은가", "괜찮지 않을까", "should we"). */
75
+ const OPINION_RE = /(?:좋은가|좋을까|좋겠지|좋지\s*않|낫겠|낫지\s*않|나을까|나을\s*듯|괜찮(?:을까|은가|겠|지\s*않)|어때|어떨까|어떤가|맞(?:을까|는\s*건가|는가)|아닐까|아닌가|싶은데|듯\s*한데|생각(?:해|이)|의견|\bshould\s+(?:we|i)\b|\bwhat do you think\b|\bis it (?:better|worth)\b)/i;
76
+ /** A request verb in the same text turns the opinion ending back into a task ("…아닐까 확인해줘"). */
77
+ const REQ_RE = /(?:해|봐|줘|찾아|알려|보여|돌려|만들어|올려|정리해)\s*(?:줘|주세요|줄래|봐|보자)|해줘|하자|해봐|부탁/;
78
+
79
+ /** True for a question that asks for an opinion and carries no request verb. */
80
+ export function isOpinionQuestion(text) {
81
+ const t = String(text || '');
82
+ return OPINION_RE.test(t) && !REQ_RE.test(t);
83
+ }
84
+
51
85
  /** Shortest text worth classifying; below this a prompt is an ack, not a task. */
52
86
  const MIN_LEN = 8;
53
87
 
@@ -152,6 +186,8 @@ export function unreachableTiers(env = process.env) {
152
186
  export function routeMatch(text, { rules, sessionRank = null, root, env = process.env } = {}) {
153
187
  const t = String(text || '').trim();
154
188
  if (t.length < MIN_LEN) return null;
189
+ // A task notification or command echo is not a request, whatever words it holds.
190
+ if (isSystemPrompt(t)) return null;
155
191
  // Judgement and irreversible work stay on the top tier. This check comes
156
192
  // before classification because such a request often looks like a light
157
193
  // "run" or "check" in its wording.
@@ -159,6 +195,9 @@ export function routeMatch(text, { rules, sessionRank = null, root, env = proces
159
195
  // Same for implementation work dressed as a run or a check: an edit is not
160
196
  // delegable, and with no tool calls yet only the wording can say so.
161
197
  if (EDIT_RE.test(t)) return null;
198
+ // "…하는게 좋은가?" asks what the model thinks. The answer is judgement, and a
199
+ // hint to hand it to a cheaper model is wrong however light the keywords look.
200
+ if (isOpinionQuestion(t)) return null;
162
201
 
163
202
  const scored = categorizeScored(t, null);
164
203
  if (!scored) return null;
@@ -237,23 +276,25 @@ function unreachableNotice(label, tiers, ko) {
237
276
  + `"Register a ${models} model in the Claude app settings to hand requests like this to a cheaper model."`;
238
277
  }
239
278
 
279
+ /** The label a hint names its rule by: the category's label in the user's language. */
280
+ export function hintLabel(match, { lang = userLanguage() } = {}) {
281
+ const { cat } = match;
282
+ return lang === 'ko' ? (cat.label || cat.id) : (cat.labelEn || cat.label || cat.id);
283
+ }
284
+
240
285
  /**
241
- * @param {string} text the prompt just submitted
242
- * @param {object} [opts] as routeMatch, plus:
286
+ * The delegation target a hint names ("the haiku agent", "model: sonnet when it
287
+ * spans …"), without the surrounding sentence. Split out of routeHint so the
288
+ * follow-up notice (src/route-follow.js) repeats exactly the words the hint used.
289
+ *
290
+ * @param {{t2?: object, t1?: object, t1h?: object}} match a routeMatch result with at least one tier
291
+ * @param {object} [opts]
243
292
  * @param {string} [opts.lang] 'ko' | 'en'
244
- * @param {string} [opts.root] project root used to look for a subagent's .md.
245
- * The hint names the agent when that file exists and only its model tier when
246
- * it does not, so a caller that needs a predictable phrase pins this.
247
- * @param {object|null} [opts.match] a routeMatch result the caller already has
248
- * @returns {string|null} the line to inject, or null to stay quiet
293
+ * @param {string} [opts.root] as routeHint
249
294
  */
250
- export function routeHint(text, { rules, lang = userLanguage(), root, sessionRank = null, match, env } = {}) {
251
- const found = match === undefined ? routeMatch(text, { rules, sessionRank, root, env }) : match;
252
- if (!found) return null;
253
- const { cat, t2, t1, t1h } = found;
295
+ export function hintTarget(match, { lang = userLanguage(), root } = {}) {
296
+ const { t2, t1, t1h } = match;
254
297
  const ko = lang === 'ko';
255
- const label = ko ? (cat.label || cat.id) : (cat.labelEn || cat.label || cat.id);
256
- if (!t2 && !t1 && !t1h && found.unreachable?.length) return unreachableNotice(label, found.unreachable, ko);
257
298
  // `root` is threaded through to agentPhrase, which names the subagent only
258
299
  // when its .md actually exists on this machine. A caller that pins it can
259
300
  // therefore get a deterministic phrase; a test that does not pin it reads
@@ -286,6 +327,28 @@ export function routeHint(text, { rules, lang = userLanguage(), root, sessionRan
286
327
  const only = picked[0];
287
328
  target = only.tier === 'T1H' ? tierPhrase(only) : phrase(nameOf(only));
288
329
  }
330
+ return target;
331
+ }
332
+
333
+ /**
334
+ * @param {string} text the prompt just submitted
335
+ * @param {object} [opts] as routeMatch, plus:
336
+ * @param {string} [opts.lang] 'ko' | 'en'
337
+ * @param {string} [opts.root] project root used to look for a subagent's .md.
338
+ * The hint names the agent when that file exists and only its model tier when
339
+ * it does not, so a caller that needs a predictable phrase pins this.
340
+ * @param {object|null} [opts.match] a routeMatch result the caller already has
341
+ * @returns {string|null} the line to inject, or null to stay quiet
342
+ */
343
+ export function routeHint(text, { rules, lang = userLanguage(), root, sessionRank = null, match, env } = {}) {
344
+ const found = match === undefined ? routeMatch(text, { rules, sessionRank, root, env }) : match;
345
+ if (!found) return null;
346
+ const { t2, t1, t1h } = found;
347
+ const ko = lang === 'ko';
348
+ const label = hintLabel(found, { lang });
349
+ if (!t2 && !t1 && !t1h && found.unreachable?.length) return unreachableNotice(label, found.unreachable, ko);
350
+ const target = hintTarget(found, { lang, root });
351
+ const picked = [t2, t1, t1h].filter(Boolean);
289
352
 
290
353
  const caps = picked.map((r) => budgetCapPhrase(r, lang));
291
354
  const capText = picked.length >= 2
@@ -30,7 +30,7 @@ export function withBaseStatusline(output, { input = '' } = {}) {
30
30
  try {
31
31
  const cmd = loadConfig().statuslineBase?.command;
32
32
  if (typeof cmd !== 'string' || !cmd.trim() || OURS.test(cmd)) return output;
33
- const opts = { input, encoding: 'utf8', timeout: 1500, env: { ...process.env, [NESTED]: '1' } };
33
+ const opts = { input, encoding: 'utf8', timeout: 1500, windowsHide: true, env: { ...process.env, [NESTED]: '1' } };
34
34
  const r = process.platform === 'win32'
35
35
  ? spawnSync(cmd, { ...opts, shell: true })
36
36
  : spawnSync('/bin/sh', ['-c', cmd], opts);