sprag-cli 3.110.0 → 3.112.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.
package/README.ko.md CHANGED
@@ -242,6 +242,7 @@ Codex에는 기본 훅과 `AGENTS.md` 하네스, 범위별 래칫 규칙, 한국
242
242
  | `sprag route-scan savings` | 라우팅 절감 원장 조회 |
243
243
  | `sprag routing on\|off` | 모델 위임(룰과 힌트와 후보 안내) 켜기와 끄기 |
244
244
  | `sprag routing relax [off]` | 가장 바쁜 사용량 창이 초기화될 때까지 위임 범위를 넓히거나(그 뒤에는 자동으로 돌아옵니다) 일찍 끝냅니다. `sprag routing status`에 `relax: off` 또는 `relax: until HH:MM`이 나옵니다 |
245
+ | `sprag routing impl on\|off` | 여러 파일 구현을 위임하라는 상기를 켜고 끕니다 |
245
246
  | `sprag secrets [fix]` | Claude Code 설정 파일의 승인 목록에서 비밀 값이 든 항목을 찾아 보여 주고(값은 출력하지 않습니다), `fix` 로 원본을 백업한 뒤 지웁니다. `sprag secrets off` 는 세션 시작 알림을 끕니다 |
246
247
  | `sprag harness check` | 🅷 하네스 점수 확인 |
247
248
  | `sprag doc2md <파일>` | 문서 한 건을 Markdown 으로 변환 |
package/README.md CHANGED
@@ -303,6 +303,7 @@ The ratchet presets, model-routing presets and delegation agents in `presets/` a
303
303
  | `sprag route-scan savings` | The routing-savings ledger |
304
304
  | `sprag routing on\|off` | Turn model delegation (rules, hints, candidates) on or off |
305
305
  | `sprag routing relax [off]` | Widen delegation until the busiest usage window resets (it switches back by itself), or end that early. `sprag routing status` shows `relax: off` or `relax: until HH:MM` |
306
+ | `sprag routing impl on\|off` | Turn the reminder to hand multi-file implementation to a worker on or off |
306
307
  | `sprag secrets [fix]` | List approval-list entries in Claude Code settings files that hold secrets (values are never shown), or remove them after backing up the original. `sprag secrets off` silences the session start notice |
307
308
  | `sprag harness check` | Current 🅷 harness score |
308
309
  | `sprag doc2md <file>` | Convert one document to Markdown |
package/bin/cli.js CHANGED
@@ -238,7 +238,7 @@ Usage:
238
238
  sprag cowork [sync|on|off|exclude <dir>|include <dir>] copy the ratchet rules into Cowork tab folders
239
239
  sprag korean on|off|status Korean writing guidance + write-time check
240
240
  sprag cohesion on|off|status English sentence-connection guidance
241
- sprag routing on|off|status|relax [off]|effort-hint on|off model delegation master switch (rules, hints, candidates); relax widens it until the usage window resets
241
+ sprag routing on|off|status|relax [off]|effort-hint on|off|impl on|off model delegation master switch (rules, hints, candidates); relax widens it until the usage window resets
242
242
  sprag doc2md on|off|<file> convert documents to Markdown before the model reads them
243
243
  sprag delegate on|off|status add bounds and context to Task/Agent delegation prompts
244
244
  sprag proof [--json] replayed delegation cases behind the tier rules (https://sprag.io/proof/)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.110.0",
3
+ "version": "3.112.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/brief.js CHANGED
@@ -14,7 +14,8 @@
14
14
  * transcript_path) and the "already briefed" markers are keyed by session_id.
15
15
  *
16
16
  * State: <stateDir>/brief-state.json
17
- * { sessions: { [session_id]: { ts, ctxTier, briefed: [signature] } } }
17
+ * { sessions: { [session_id]: { ts, ctxTier, startedAt, briefed: [signature] } } }
18
+ * startedAt caches the transcript's first timestamp for the session-age warning.
18
19
  * Sessions untouched for 7 days are pruned on every write.
19
20
  *
20
21
  * Division of labor with the SessionStart hook: SessionStart prints the
@@ -169,6 +170,49 @@ function ctxTierOf(pct) {
169
170
 
170
171
  const fmtK = (n) => `${Math.round(n / 1000)}k`;
171
172
 
173
+ // A session left open for days re-reads everything it ever loaded on every
174
+ // request, and each auto-compaction blurs the decisions made early on. Past a
175
+ // day the briefing asks the model to write a handoff and send the user to a
176
+ // new session, once per whole day of age.
177
+ export const SESSION_AGE_DAY_MS = 24 * 60 * 60 * 1000;
178
+ const HEAD_BYTES = 64 * 1024;
179
+
180
+ /**
181
+ * When THIS session started: the first `timestamp` in the transcript head.
182
+ * A resumed session keeps its original messages, so the age counts from the
183
+ * first request rather than from the resume. Falls back to the file's birth
184
+ * time; null when neither is readable.
185
+ */
186
+ export function sessionStartedAt(transcriptPath) {
187
+ let fd;
188
+ try {
189
+ fd = openSync(transcriptPath, 'r');
190
+ const buf = Buffer.alloc(HEAD_BYTES);
191
+ const n = readSync(fd, buf, 0, HEAD_BYTES, 0);
192
+ for (const m of buf.toString('utf8', 0, n).matchAll(/"timestamp"\s*:\s*"([^"]+)"/g)) {
193
+ const t = Date.parse(m[1]);
194
+ if (Number.isFinite(t)) return t;
195
+ }
196
+ } catch {
197
+ return null;
198
+ } finally {
199
+ if (fd !== undefined) try { closeSync(fd); } catch { /* already closed */ }
200
+ }
201
+ try {
202
+ const b = statSync(transcriptPath).birthtimeMs;
203
+ return b > 0 ? b : null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ const pad2 = (n) => String(n).padStart(2, '0');
210
+ const fmtLocal = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`; };
211
+
212
+ export function sessionAgeMessage(days, startedAt) {
213
+ return `이 세션을 시작한 지 ${days}일이 넘었습니다(시작 ${fmtLocal(startedAt)}). 오래 켜 둔 세션은 요청마다 그동안 쌓인 대화를 다시 읽어 비용이 커집니다. 자동 압축을 거칠 때마다 앞서 정한 내용도 흐려집니다. 사용자에게 이 사실을 알리고 지금 하던 일을 마무리한 뒤 \`sprag handoff\`로 핸드오프 파일을 만들어 빈 칸(한 일, 남은 일, 이어갈 지점, 주의할 점)을 채우십시오. 그다음 사용자에게 새 세션을 열어 "<만든 핸드오프 파일 경로> 핸드오프 이어서 해줘"라고 입력하라고 파일 경로를 넣은 문장 그대로 안내하십시오.`;
214
+ }
215
+
172
216
  /**
173
217
  * Called by the SessionStart hook after it prints the session-start snapshot:
174
218
  * records the signatures it actually briefed so runBrief suppresses exactly
@@ -233,6 +277,19 @@ export async function runBrief({ sessionId, transcriptPath, root = process.cwd()
233
277
  }
234
278
  }
235
279
 
280
+ // ── session age (per-session, once per whole day) ──
281
+ if (s.startedAt == null && transcriptPath) s.startedAt = sessionStartedAt(transcriptPath);
282
+ const ageDays = s.startedAt ? Math.floor((now - s.startedAt) / SESSION_AGE_DAY_MS) : 0;
283
+ if (ageDays >= 1) {
284
+ const sig = `age|${ageDays}`;
285
+ const briefed = new Set(s.briefed || []);
286
+ if (!briefed.has(sig)) {
287
+ briefed.add(sig);
288
+ s.briefed = [...briefed];
289
+ items.push(sessionAgeMessage(ageDays, s.startedAt));
290
+ }
291
+ }
292
+
236
293
  // ── mid-session route-scan / rule-health changes (global state, briefed
237
294
  // at most once per session per signature). Skipped while the routing
238
295
  // master switch is off. ──
@@ -12,7 +12,9 @@
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
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).
15
+ * turn that carried a delegation hint and nudges once (src/route-follow.js),
16
+ * and reminds once about delegating after two code files edited directly, and once on
17
+ * a prompt that reads as an implementation request (src/impl-follow.js).
16
18
  */
17
19
 
18
20
  import { readStdinJson } from '../stdin-payload.js';
@@ -23,13 +25,23 @@ export async function run({ hasFlag }) {
23
25
  if (hasFlag('--hook-tool')) {
24
26
  // PostToolUse: a nudge is context for the model, so it goes out as
25
27
  // hookSpecificOutput; nothing is printed when there is nothing to say.
28
+ // Two followers see the same payload (lookups after a hint, edits without
29
+ // a delegation); their notices go out as one context block.
30
+ const payload = readStdinJson() || {};
31
+ const notes = [];
26
32
  try {
27
33
  const { followToolUse } = await import('../route-follow.js');
28
- const nudge = followToolUse(readStdinJson() || {});
29
- if (nudge) {
30
- console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: nudge } }));
31
- }
34
+ const nudge = followToolUse(payload);
35
+ if (nudge) notes.push(nudge);
32
36
  } catch (e) { debug('brief:hook-tool', e); }
37
+ try {
38
+ const { implFollowToolUse } = await import('../impl-follow.js');
39
+ const nudge = implFollowToolUse(payload);
40
+ if (nudge) notes.push(nudge);
41
+ } catch (e) { debug('brief:hook-tool-impl', e); }
42
+ if (notes.length) {
43
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: notes.join('\n\n') } }));
44
+ }
33
45
  return;
34
46
  }
35
47
  if (!hasFlag('--hook')) {
@@ -134,6 +146,17 @@ export async function run({ hasFlag }) {
134
146
  }
135
147
  } catch (e) { debug('brief:effort-notice', e); }
136
148
  }
149
+ // An implementation request gets no delegation hint (routeMatch is null for
150
+ // an edit ask), so it gets the implementation split reminder instead, once
151
+ // until the next delegation (src/impl-follow.js). Only when no hint went out
152
+ // this turn.
153
+ if (!hint) {
154
+ try {
155
+ const { implementationReminder } = await import('../impl-follow.js');
156
+ const reminder = implementationReminder(ctx.prompt, { sessionId: ctx.session_id, sessionRank });
157
+ if (reminder) parts.push(reminder);
158
+ } catch (e) { debug('brief:impl-reminder', e); }
159
+ }
137
160
  // Remember that this turn carried a delegation hint, so the PostToolUse
138
161
  // hook can nudge when the model looks things up itself instead. The
139
162
  // unreachable-only notice tells the model NOT to delegate, so it starts
@@ -5,6 +5,7 @@
5
5
  * sprag routing on|off # turn every delegation path on or off
6
6
  * sprag routing relax [off] # widen delegation until the busiest usage window resets, or end that early
7
7
  * sprag routing effort-hint on|off # the effort line for low/medium sessions on judgement requests
8
+ * sprag routing impl on|off # the reminder to hand multi-file implementation to a worker
8
9
  *
9
10
  * Off removes the delegation rules from ratchet-model.md and the preset
10
11
  * ratchet, the per-prompt route hint, and the route-scan candidate and
@@ -15,7 +16,7 @@ export async function run({ args }) {
15
16
  const sub = args[1];
16
17
  const { userLanguage } = await import('../config.js');
17
18
  const ko = userLanguage() === 'ko';
18
- const { routingEnabled, setRoutingEnabled, isRelaxed, relaxUntil, setRelaxUntil, relaxClock, effortHintEnabled, setEffortHint } = await import('../routing-switch.js');
19
+ const { routingEnabled, setRoutingEnabled, isRelaxed, relaxUntil, setRelaxUntil, relaxClock, effortHintEnabled, setEffortHint, implementationFollowUpEnabled, setImplementationFollowUp } = await import('../routing-switch.js');
19
20
 
20
21
  // The reset of the busiest usage window in the statusline snapshot, in epoch
21
22
  // ms; five hours from now when the snapshot is missing, stale or has no reset.
@@ -106,6 +107,20 @@ export async function run({ args }) {
106
107
  return;
107
108
  }
108
109
 
110
+ if (sub === 'impl') {
111
+ const want = args[2];
112
+ if (want !== 'on' && want !== 'off') {
113
+ console.error('Usage: sprag routing impl on|off');
114
+ process.exitCode = 2;
115
+ return;
116
+ }
117
+ setImplementationFollowUp(want === 'on');
118
+ console.log(want === 'on'
119
+ ? (ko ? '✓ 구현 분업 상기를 켰습니다. 구현 요청과 파일 두 개 직접 수정 때 한 번씩 안내합니다.' : '✓ Implementation reminder is on. It speaks once on an implementation request and once after two files edited directly.')
120
+ : (ko ? '✓ 구현 분업 상기를 껐습니다.' : '✓ Implementation reminder is off.'));
121
+ return;
122
+ }
123
+
109
124
  if (sub === undefined || sub === 'status') {
110
125
  const on = routingEnabled();
111
126
  const n = await rules().catch(() => 0);
@@ -114,6 +129,7 @@ export async function run({ args }) {
114
129
  console.log(`routing: ${on ? 'on' : 'off'}`);
115
130
  console.log(isRelaxed() ? `relax: until ${relaxClock(relaxUntil())}` : 'relax: off');
116
131
  console.log(`effort hint: ${effortHintEnabled() ? 'on' : 'off'}`);
132
+ console.log(ko ? `구현 분업 상기: ${implementationFollowUpEnabled() ? '켜짐' : '꺼짐'}` : `Implementation reminder: ${implementationFollowUpEnabled() ? 'on' : 'off'}`);
117
133
  console.log(ko ? `등록된 룰: ${n}건` : `registered rules: ${n}`);
118
134
  console.log(`delegate agents: ${agentsOn ? 'on' : 'off'}`);
119
135
  console.log(ko
@@ -122,6 +138,6 @@ export async function run({ args }) {
122
138
  return;
123
139
  }
124
140
 
125
- console.log('Usage: sprag routing on|off|status|relax [off]|effort-hint on|off');
141
+ console.log('Usage: sprag routing on|off|status|relax [off]|effort-hint on|off|impl on|off');
126
142
  process.exitCode = 1;
127
143
  }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Reminders about the implementation split: one at prompt time (the main one)
3
+ * and one after two directly edited files.
4
+ *
5
+ * Why this exists: the implementation split clause of the model rules (the main
6
+ * model settles the design, a Sonnet worker writes the code) is static text, and
7
+ * the model often misses it. evals/impl-delegation-rate.mjs on one machine since
8
+ * 10-10: 87 turns delegated the implementation, 43 edited three or more code
9
+ * files directly (issue #17 was an 8-file, 380-line one). The prompt hook cannot
10
+ * give a delegation hint for an implementation request (the EDIT_RE gate in
11
+ * src/route-inject.js is intentional and stays).
12
+ *
13
+ * Why two moments: the edit-count reminder at the third file came too late.
14
+ * Median share of a direct turn's edit text still to come: 85% after the 1st
15
+ * code file, 52% after the 2nd, 18% after the 3rd. So the main device is implementationReminder, which speaks on the
16
+ * prompt itself (looksLikeImplementation in src/route-inject.js), and the
17
+ * PostToolUse count was moved from three files to two.
18
+ *
19
+ * What counts at PostToolUse: Edit, Write, MultiEdit and NotebookEdit, distinct
20
+ * paths only. Memory and settings (anything under /.claude/), scratch paths
21
+ * (os.tmpdir(), /tmp, /var/folders) and documents (.md, .mdx, .markdown, .txt,
22
+ * .rst, .adoc) are not implementation. Codex is out of scope (apply_patch is
23
+ * ignored). A streak whose last edit is older than two hours is stale and starts
24
+ * over.
25
+ *
26
+ * What counts as a delegation (seen on either PreToolUse or PostToolUse): a
27
+ * spawn_agent call, or a Task or Agent call that hands work to an implementer:
28
+ * no subagent_type (general-purpose), t1-worker, t1h-worker, general-purpose,
29
+ * claude, or a name ending in builder or worker. Lookup agents (Explore, t2-*,
30
+ * web-fetch, cavecrew-investigator and the like) are not a delegation of the
31
+ * implementation: they change no state. A delegation clears the edit list and
32
+ * the markers, so both reminders arm again.
33
+ *
34
+ * Both reminders are skipped when the session model is not above the Sonnet tier
35
+ * (worthDelegating('T1', rank) is false): delegating from Sonnet saves nothing.
36
+ *
37
+ * State lives under <dir>/route-follow/ next to route-follow.js's files:
38
+ * <sid>.edits one line per edit, "<ts>\t<path>", appended
39
+ * <sid>.impl-nudged created with the `wx` flag, so of several parallel hook
40
+ * processes exactly one speaks; removed by a delegation
41
+ * <sid>.impl-reminded the same for the prompt-time reminder
42
+ * Events go to the same route-follow-events.jsonl. followStats() only counts
43
+ * turns that have a `hint` event and reads the event names `hint`, `nudged` and
44
+ * `delegated`, so the `impl-nudged`, `impl-reminded` and `impl-delegated` lines
45
+ * never change its numbers.
46
+ *
47
+ * Switch: `implementationFollowUp: false` in config.json (sprag routing impl off).
48
+ * The module never throws into a hook.
49
+ */
50
+
51
+ import { mkdirSync, appendFileSync, readFileSync, rmSync, openSync, closeSync } from 'node:fs';
52
+ import { basename, join } from 'node:path';
53
+ import { tmpdir } from 'node:os';
54
+ import { userDataDir } from './paths.js';
55
+ import { loadConfig, userLanguage } from './config.js';
56
+ import { routingEnabled } from './routing-switch.js';
57
+ import { logEvent } from './route-follow.js';
58
+ import { sessionModelRank, looksLikeImplementation } from './route-inject.js';
59
+ import { worthDelegating } from './route-scan.js';
60
+ import { resolveAgentName } from './agents.js';
61
+ import { debug } from './debug.js';
62
+
63
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
64
+ /** Distinct edited files at which the PostToolUse reminder goes out. */
65
+ const NUDGE_FILES = 2;
66
+ /** An edit streak whose last edit is older than this is left over from earlier work. */
67
+ const STREAK_TTL_MS = 2 * 60 * 60 * 1000;
68
+
69
+ const DELEGATE_TOOLS = new Set(['Task', 'Agent', 'spawn_agent']);
70
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
71
+ const EXCLUDED_PREFIXES = ['/tmp/', '/private/tmp/', '/var/folders/', '/private/var/folders/'];
72
+ const DOC_EXT_RE = /\.(md|mdx|markdown|txt|rst|adoc)$/i;
73
+ /** Subagent types that carry implementation work (no type means general-purpose). */
74
+ const IMPL_AGENTS = new Set(['t1-worker', 't1h-worker', 'general-purpose', 'claude']);
75
+ const IMPL_AGENT_RE = /(?:^|[:-])(?:builder|worker)$/;
76
+
77
+ const baseDir = (dir) => dir || userDataDir();
78
+
79
+ function paths(sessionId, dir) {
80
+ const d = join(baseDir(dir), 'route-follow');
81
+ return {
82
+ d,
83
+ edits: join(d, `${sessionId}.edits`),
84
+ nudged: join(d, `${sessionId}.impl-nudged`),
85
+ reminded: join(d, `${sessionId}.impl-reminded`),
86
+ };
87
+ }
88
+
89
+ const rmQuiet = (file) => {
90
+ try { rmSync(file, { force: true }); } catch (e) { debug('impl-follow:rm', e); }
91
+ };
92
+
93
+ function hasMarker(file) {
94
+ try { readFileSync(file); return true; } catch (e) {
95
+ if (e?.code !== 'ENOENT') debug('impl-follow:marker', e);
96
+ return false;
97
+ }
98
+ }
99
+
100
+ export function excludedPath(file) {
101
+ // Windows paths arrive with backslashes; compare with forward slashes only.
102
+ const f = file.replace(/\\/g, '/');
103
+ if (f.includes('/.claude/')) return true;
104
+ if (DOC_EXT_RE.test(f)) return true;
105
+ const tmp = (tmpdir() || '').replace(/\\/g, '/');
106
+ if (tmp && (f === tmp || f.startsWith(tmp.endsWith('/') ? tmp : `${tmp}/`))) return true;
107
+ return EXCLUDED_PREFIXES.some((p) => f.startsWith(p));
108
+ }
109
+
110
+ /** True when this tool call hands implementation work to another agent. */
111
+ export function countsAsDelegation(tool, input) {
112
+ if (tool === 'spawn_agent') return true;
113
+ const type = typeof input?.subagent_type === 'string' ? input.subagent_type.trim() : '';
114
+ if (!type) return true;
115
+ return IMPL_AGENTS.has(type) || IMPL_AGENT_RE.test(type);
116
+ }
117
+
118
+ function readEdits(file) {
119
+ let raw = '';
120
+ try { raw = readFileSync(file, 'utf8'); } catch (e) { if (e?.code !== 'ENOENT') debug('impl-follow:read', e); }
121
+ const out = [];
122
+ for (const line of raw.split('\n')) {
123
+ if (!line) continue;
124
+ const i = line.indexOf('\t');
125
+ if (i < 0) continue;
126
+ out.push({ ts: Number(line.slice(0, i)), path: line.slice(i + 1) });
127
+ }
128
+ return out;
129
+ }
130
+
131
+ function nudgeText({ n, files, target, lang }) {
132
+ const names = files.map((f) => basename(f));
133
+ const shown = names.slice(0, 3).join(', ');
134
+ const more = names.length - 3;
135
+ if (lang === 'ko') {
136
+ const list = more > 0 ? `${shown} 외 ${more}개` : shown;
137
+ return `✇ [sprag] 위임 없이 파일 ${n}개를 직접 고쳤습니다(${list}). `
138
+ + `남은 구현이 여러 파일에 걸치면 구현 분업 조항대로 설계와 수정할 파일, 완료 기준, 테스트 명령을 정리해 ${target}에 넘기십시오. `
139
+ + '남은 변경이 이미 읽은 파일의 약 50줄 이하이거나 설계를 아직 정하지 못했다면 그 이유를 답변에 한 줄로 밝히고 계속하십시오. '
140
+ + '이 안내는 다음 위임 전까지 다시 나가지 않습니다.';
141
+ }
142
+ const list = more > 0 ? `${shown} and ${more} more` : shown;
143
+ return `✇ [sprag] You have edited ${n} files yourself without delegating (${list}). `
144
+ + 'If the remaining implementation spans several files, follow the implementation split: write down the design, files to change, completion criteria and test commands, '
145
+ + `and hand it to ${target}. `
146
+ + 'If what remains is roughly 50 lines in files already read, or the design is not settled yet, say so in one line in your reply and continue. '
147
+ + 'This notice does not repeat until the next delegation.';
148
+ }
149
+
150
+ function reminderText({ target, lang }) {
151
+ if (lang === 'ko') {
152
+ return '✇ [sprag] 구현 요청으로 보입니다. 여러 파일을 고치는 구현이면 구현 분업 조항대로 설계를 먼저 정하고 '
153
+ + `코드 작성은 ${target}에 넘기십시오. 이미 읽은 파일의 약 50줄 이하 변경이면 직접 처리합니다. `
154
+ + '이 안내는 다음 위임 전까지 다시 나가지 않습니다.';
155
+ }
156
+ return '✇ [sprag] This looks like an implementation request. If it spans several files, follow the implementation split: '
157
+ + `settle the design first and hand the code writing to ${target}. `
158
+ + 'Changes of roughly 50 lines in files already read stay on the main model. '
159
+ + 'This notice does not repeat until the next delegation.';
160
+ }
161
+
162
+ /**
163
+ * UserPromptSubmit entry: one reminder per session (until the next delegation)
164
+ * for a prompt that reads as an implementation request.
165
+ *
166
+ * @param {string} text the user's prompt
167
+ * @param {{sessionId?: string, sessionRank?: number|null, cfg?: object, dir?: string, lang?: string, now?: number}} [opts]
168
+ * @returns {string|null} the notice to add as context, or null
169
+ */
170
+ export function implementationReminder(text, { sessionId, sessionRank = null, cfg = loadConfig(), dir, lang, now = Date.now() } = {}) {
171
+ try {
172
+ if (!routingEnabled(cfg)) return null;
173
+ if (cfg?.implementationFollowUp === false) return null;
174
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null;
175
+ if (!looksLikeImplementation(text)) return null;
176
+ if (sessionRank !== null && !worthDelegating('T1', sessionRank)) return null;
177
+
178
+ const p = paths(sessionId, dir);
179
+ mkdirSync(p.d, { recursive: true });
180
+ try { closeSync(openSync(p.reminded, 'wx')); } catch (e) {
181
+ if (e?.code !== 'EEXIST') debug('impl-follow:reminded', e);
182
+ return null;
183
+ }
184
+ logEvent(dir, { at: now, agent: 'claude', sessionId, event: 'impl-reminded' });
185
+ const target = resolveAgentName('sonnet', null) || 'general-purpose (model: sonnet)';
186
+ return reminderText({ target, lang: lang || userLanguage() });
187
+ } catch (e) {
188
+ debug('impl-follow:reminder', e);
189
+ return null;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * PostToolUse entry: record the edit and, at the second distinct file edited
195
+ * without a delegation, return the reminder.
196
+ *
197
+ * @param {object} payload hook payload (`session_id`, `tool_name`, `tool_input`, `hook_event_name`)
198
+ * @param {{now?: number, cfg?: object, dir?: string, rank?: number|null, lang?: string}} [opts]
199
+ * `dir` replaces the user data dir (tests); `rank` replaces the session model
200
+ * rank read from the transcript; `lang` replaces userLanguage()
201
+ * @returns {string|null} the notice to add as context, or null
202
+ */
203
+ export function implFollowToolUse(payload, { now = Date.now(), cfg = loadConfig(), dir, rank, lang } = {}) {
204
+ try {
205
+ if (!routingEnabled(cfg)) return null;
206
+ if (cfg?.implementationFollowUp === false) return null;
207
+ // A subagent's own edits reach this hook under the parent's session id; the
208
+ // worker doing the delegated edits must not be told to delegate.
209
+ if (payload?.agent_id) return null;
210
+ const sessionId = payload?.session_id;
211
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null;
212
+
213
+ const tool = String(payload.tool_name || '').replace(/^(?:functions|tools)\./, '');
214
+ const p = paths(sessionId, dir);
215
+
216
+ if (DELEGATE_TOOLS.has(tool)) {
217
+ // A lookup agent (Explore, t2-*, web-fetch ...) delegates no implementation:
218
+ // leave every record as it is.
219
+ if (!countsAsDelegation(tool, payload.tool_input)) return null;
220
+ rmQuiet(p.edits);
221
+ const afterNudge = hasMarker(p.nudged);
222
+ const afterReminder = hasMarker(p.reminded);
223
+ rmQuiet(p.nudged);
224
+ rmQuiet(p.reminded);
225
+ if (afterNudge || afterReminder) {
226
+ logEvent(dir, { at: now, agent: 'claude', sessionId, event: 'impl-delegated', afterNudge, afterReminder });
227
+ }
228
+ return null;
229
+ }
230
+
231
+ if (!EDIT_TOOLS.has(tool)) return null;
232
+ if (payload.hook_event_name === 'PreToolUse') return null;
233
+ const input = payload.tool_input;
234
+ const file = input?.file_path ?? input?.notebook_path;
235
+ if (typeof file !== 'string' || !file || excludedPath(file)) return null;
236
+
237
+ mkdirSync(p.d, { recursive: true });
238
+ let edits = readEdits(p.edits);
239
+ const last = edits[edits.length - 1];
240
+ if (last && Number.isFinite(last.ts) && now - last.ts > STREAK_TTL_MS) {
241
+ rmQuiet(p.edits);
242
+ rmQuiet(p.nudged);
243
+ edits = [];
244
+ }
245
+ appendFileSync(p.edits, `${now}\t${file}\n`);
246
+ edits.push({ ts: now, path: file });
247
+ const files = [...new Set(edits.map((e) => e.path))];
248
+ if (files.length < NUDGE_FILES) return null;
249
+
250
+ const sessionRank = rank === undefined ? sessionModelRank({ transcriptPath: payload.transcript_path }) : rank;
251
+ if (sessionRank !== null && !worthDelegating('T1', sessionRank)) return null;
252
+
253
+ // Parallel hooks can all see the count here; only the process that creates
254
+ // the marker speaks.
255
+ try { closeSync(openSync(p.nudged, 'wx')); } catch (e) {
256
+ if (e?.code !== 'EEXIST') debug('impl-follow:nudged', e);
257
+ return null;
258
+ }
259
+ logEvent(dir, { at: now, agent: 'claude', sessionId, event: 'impl-nudged', files: files.length });
260
+ const target = resolveAgentName('sonnet', null) || 'general-purpose (model: sonnet)';
261
+ return nudgeText({ n: files.length, files, target, lang: lang || userLanguage() });
262
+ } catch (e) {
263
+ debug('impl-follow:tool', e);
264
+ return null;
265
+ }
266
+ }
@@ -329,7 +329,8 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root, grade =
329
329
  '- 세션 모델이 위임 목표와 같은 급이거나 그보다 낮으면 위임하지 않습니다.',
330
330
  ' 절감이 발생하지 않기 때문입니다.',
331
331
  '- 설계 판단이나 되돌릴 수 없는 작업(배포·릴리스·머지·제출)이 섞여 있으면',
332
- ' 위임하지 않습니다.',
332
+ ' 위임하지 않습니다. 메인이 설계를 확정한 뒤 구현만 넘기는 구현 분업은',
333
+ ' 예외입니다.',
333
334
  '- 웹에서 뉴스나 대안, 후보를 찾는 열린 조사는 위임하지 않습니다. 하위 모델이',
334
335
  ' 몇 번 검색하고 멈춰도 무엇을 빠뜨렸는지 드러나지 않기 때문입니다. 조사를',
335
336
  ' 위임한 결과를 전달할 때는 어디까지 찾았는지 먼저 확인합니다. 사용자가 그래도',
@@ -418,7 +419,8 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root, grade =
418
419
  '- Skip delegation when the session model is already at or below the target',
419
420
  ' tier: there is nothing to save.',
420
421
  '- Skip it when the request mixes in design judgement or irreversible work',
421
- ' (deploy, release, merge, submission).',
422
+ ' (deploy, release, merge, submission). The implementation split, where the main',
423
+ ' model settles the design and hands over only the code, is the exception.',
422
424
  '- Do not delegate open research on the web (news, alternatives, candidates):',
423
425
  ' a cheaper model stops after a few searches and nothing shows what it missed.',
424
426
  ' Before relaying any delegated research, check how far it actually searched.',
@@ -87,7 +87,7 @@ const rmQuiet = (file) => {
87
87
  try { rmSync(file, { force: true }); } catch (e) { debug('route-follow:rm', e); }
88
88
  };
89
89
 
90
- function logEvent(dir, entry) {
90
+ export function logEvent(dir, entry) {
91
91
  try {
92
92
  const file = eventsPath(dir);
93
93
  mkdirSync(baseDir(dir), { recursive: true });
@@ -78,6 +78,27 @@ export function isSystemPrompt(text) {
78
78
  return SYSTEM_PROMPT_PREFIXES.some((p) => t.startsWith(p));
79
79
  }
80
80
 
81
+ /**
82
+ * A paragraph that opens with a short bracketed label ("[운영 규칙] …",
83
+ * "[리마인더] …") is a standing instruction a wrapper adds to every message,
84
+ * such as a Slack bot's prompt suffix.
85
+ */
86
+ const STANDING_PARA_RE = /^\[[^\]\n]{1,24}\][ \t]/;
87
+
88
+ /**
89
+ * The user's request without the standing-instruction paragraphs a wrapper puts
90
+ * before or after it. A 130-character "[운영 규칙]" suffix on every Slack message
91
+ * made each prompt read as a long spec: over 260 such prompts the delegation hint
92
+ * fired 0 times instead of 24, and the implementation reminder 236 times instead
93
+ * of 21. A prompt that is nothing but such a paragraph is kept as it is.
94
+ */
95
+ export function stripStandingInstructions(text) {
96
+ const paras = String(text || '').trim().split(/\n[ \t]*\n/);
97
+ while (paras.length > 1 && STANDING_PARA_RE.test(paras[paras.length - 1].trim())) paras.pop();
98
+ while (paras.length > 1 && STANDING_PARA_RE.test(paras[0].trim())) paras.shift();
99
+ return paras.join('\n\n').trim();
100
+ }
101
+
81
102
  /** Endings that ask what the model thinks ("좋은가", "괜찮지 않을까", "should we"). */
82
103
  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;
83
104
  /** A request verb in the same text turns the opinion ending back into a task ("…아닐까 확인해줘"). */
@@ -140,6 +161,20 @@ export function looksLikeContextOrSpec(text) {
140
161
  || (t.length > SPEC_LEN && !looksPasted(t));
141
162
  }
142
163
 
164
+ /**
165
+ * True when a prompt reads as a request to write or change code: an edit ask
166
+ * (EDIT_RE, EDIT_MORE_RE) or a written spec (long and not a paste), minus
167
+ * outward actions and open web research. routeMatch never hints for such a
168
+ * request, so src/impl-follow.js uses this to remind about the implementation
169
+ * split at prompt time. Harness-written messages and acks are not requests.
170
+ */
171
+ export function looksLikeImplementation(text) {
172
+ const t = stripStandingInstructions(text);
173
+ if (t.length < MIN_LEN || isSystemPrompt(t)) return false;
174
+ if (OUTWARD_RE.test(t) || OPEN_RESEARCH_RE.test(t)) return false;
175
+ return EDIT_RE.test(t) || EDIT_MORE_RE.test(t) || (t.length > SPEC_LEN && !looksPasted(t));
176
+ }
177
+
143
178
  /**
144
179
  * A question that asks for an explanation ("어떻게 쓰이는거지?", "뭐야", "how
145
180
  * does it work"). "왜" is not here: ESCALATE_RE already routes it to the top
@@ -243,7 +278,7 @@ export function unreachableTiers(env = process.env) {
243
278
  * one this session cannot reach
244
279
  */
245
280
  export function routeMatch(text, { rules, sessionRank = null, root, env = process.env, grade = delegationGrade() } = {}) {
246
- const t = String(text || '').trim();
281
+ const t = stripStandingInstructions(text);
247
282
  if (t.length < MIN_LEN) return null;
248
283
  // A task notification or command echo is not a request, whatever words it holds.
249
284
  if (isSystemPrompt(t)) return null;
@@ -337,7 +372,7 @@ const ACTION_RE = new RegExp(
337
372
  * grade 'quality'), 'action' an irreversible step with no judgement word.
338
373
  */
339
374
  export function judgementMatch(text, { grade = delegationGrade() } = {}) {
340
- const t = String(text || '').trim();
375
+ const t = stripStandingInstructions(text);
341
376
  if (t.length < MIN_LEN || isSystemPrompt(t)) return null;
342
377
  if (ESCALATE_RE.test(t)) {
343
378
  const kind = ESCALATE_RE.test(t.replace(ACTION_RE, ' ')) ? 'escalate' : 'action';
@@ -39,6 +39,26 @@ export function setEffortHint(on) {
39
39
  saveConfig(cfg);
40
40
  }
41
41
 
42
+ /**
43
+ * Whether the implementation-split reminders (prompt time and after two edited
44
+ * files, src/impl-follow.js) may speak. Only an explicit `false` in
45
+ * `implementationFollowUp` is off; routing off silences them too.
46
+ */
47
+ export function implementationFollowUpEnabled(cfg = loadConfig()) {
48
+ try {
49
+ return routingEnabled(cfg) && cfg?.implementationFollowUp !== false;
50
+ } catch {
51
+ return true;
52
+ }
53
+ }
54
+
55
+ export function setImplementationFollowUp(on) {
56
+ const cfg = loadConfig();
57
+ cfg.implementationFollowUp = on !== false;
58
+ pruneExpiredRelax(cfg);
59
+ saveConfig(cfg);
60
+ }
61
+
42
62
  export function setRoutingEnabled(on) {
43
63
  const cfg = loadConfig();
44
64
  cfg.routing = on !== false;