sprag-cli 3.109.1 → 3.111.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 +3 -0
- package/README.md +3 -0
- package/bin/cli.js +15 -1
- package/package.json +1 -1
- package/src/commands/brief.js +28 -5
- package/src/commands/panel.js +232 -0
- package/src/commands/routing.js +18 -2
- package/src/impl-follow.js +266 -0
- package/src/installer.js +24 -1
- package/src/model-rules.js +4 -2
- package/src/route-follow.js +1 -1
- package/src/route-inject.js +14 -0
- package/src/routing-switch.js +20 -0
package/README.ko.md
CHANGED
|
@@ -190,6 +190,8 @@ LLMRouterBench(Findings of ACL 2026)에서 오프라인으로 측정했습니다
|
|
|
190
190
|
|
|
191
191
|
JetBrains IDE 내장 터미널에서는 이모지 대신 한 칸 글리프로 표시합니다(`◉ Cache hit 98.8% · ◧ Ctx 47% of 1M`). IDE 기본 폰트에 이모지 글리프가 없어서, 이모지를 그대로 두면 `Cache expires 4:545` 처럼 이전 프레임 문자가 화면에 남습니다. 모드 종류와 `sprag mode narrow` · `mode icon-force` 사용법은 [statusline 문서의 라벨 모드](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.ko.md#라벨-모드)에 있습니다.
|
|
192
192
|
|
|
193
|
+
Agent SDK로 Claude Code를 실행하는 호스트(T3 Code 등)는 `statusLine` 명령을 실행하지 않아서 이 줄이 보이지 않습니다. 그 호스트의 내장 터미널에서 `sprag panel` 을 실행하면 해당 프로젝트의 가장 최근 세션을 따라가는 실시간 사본이 뜹니다(`--once` 는 한 프레임만 출력합니다). Orca는 Claude Code를 실제 터미널에서 실행하므로 기본 statusline이 그대로 보이고 패널이 필요하지 않습니다. Orca가 자기 statusLine을 먼저 넣어 두었다면 `sprag install` 이 그 명령을 sprag 아래에서 계속 실행해 Orca의 사용량 표시도 유지합니다.
|
|
194
|
+
|
|
193
195
|
## 같은 프롬프트를 저가 등급에 돌리면
|
|
194
196
|
|
|
195
197
|
벤치마크는 공개 데이터를 씁니다. 이 절은 같은 질문을 제 작업에 던진 결과입니다. 이 저장소의 실제 세션에서 질문 여덟 개를 골라 두 등급에 보내고, 실행 전에 적어 둔 정답과 맞춰 봤습니다(2026-09-17, 원자료 `video/out/measure2.json`).
|
|
@@ -240,6 +242,7 @@ Codex에는 기본 훅과 `AGENTS.md` 하네스, 범위별 래칫 규칙, 한국
|
|
|
240
242
|
| `sprag route-scan savings` | 라우팅 절감 원장 조회 |
|
|
241
243
|
| `sprag routing on\|off` | 모델 위임(룰과 힌트와 후보 안내) 켜기와 끄기 |
|
|
242
244
|
| `sprag routing relax [off]` | 가장 바쁜 사용량 창이 초기화될 때까지 위임 범위를 넓히거나(그 뒤에는 자동으로 돌아옵니다) 일찍 끝냅니다. `sprag routing status`에 `relax: off` 또는 `relax: until HH:MM`이 나옵니다 |
|
|
245
|
+
| `sprag routing impl on\|off` | 여러 파일 구현을 위임하라는 상기를 켜고 끕니다 |
|
|
243
246
|
| `sprag secrets [fix]` | Claude Code 설정 파일의 승인 목록에서 비밀 값이 든 항목을 찾아 보여 주고(값은 출력하지 않습니다), `fix` 로 원본을 백업한 뒤 지웁니다. `sprag secrets off` 는 세션 시작 알림을 끕니다 |
|
|
244
247
|
| `sprag harness check` | 🅷 하네스 점수 확인 |
|
|
245
248
|
| `sprag doc2md <파일>` | 문서 한 건을 Markdown 으로 변환 |
|
package/README.md
CHANGED
|
@@ -239,6 +239,8 @@ When something is wrong the warning chip leads the line: `🚨 5H/7D NN%`, `⚠
|
|
|
239
239
|
|
|
240
240
|
Inside a JetBrains IDE terminal the chips render as single-cell glyphs instead of emoji (`◉ Cache hit 98.8% · ◧ Ctx 47% of 1M`). The IDE's default font has no emoji glyphs, so emoji leave characters from the previous frame on screen, like `Cache expires 4:545`. [Label modes](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.md#label-modes) covers the detail, plus `sprag mode narrow` and `mode icon-force`.
|
|
241
241
|
|
|
242
|
+
Hosts that run Claude Code through the Agent SDK, such as T3 Code, never run the `statusLine` command, so the line does not appear there. Run `sprag panel` in the host's integrated terminal to get a live copy that follows the newest session of that project (`--once` prints a single frame). Orca runs Claude Code in a real terminal, so the normal statusline shows there and needs no panel. When Orca wrote its own statusLine first, `sprag install` keeps it running underneath sprag's, which keeps Orca's usage display fed.
|
|
243
|
+
|
|
242
244
|
## The cheap tier on the same prompts
|
|
243
245
|
|
|
244
246
|
The benchmark uses public data. This asks the same question of my own work: eight
|
|
@@ -301,6 +303,7 @@ The ratchet presets, model-routing presets and delegation agents in `presets/` a
|
|
|
301
303
|
| `sprag route-scan savings` | The routing-savings ledger |
|
|
302
304
|
| `sprag routing on\|off` | Turn model delegation (rules, hints, candidates) on or off |
|
|
303
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 |
|
|
304
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 |
|
|
305
308
|
| `sprag harness check` | Current 🅷 harness score |
|
|
306
309
|
| `sprag doc2md <file>` | Convert one document to Markdown |
|
package/bin/cli.js
CHANGED
|
@@ -134,6 +134,7 @@ const KNOWN_SUBCOMMANDS = new Set([
|
|
|
134
134
|
'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
|
|
135
135
|
'doc2md', 'delegate', 'proof', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
|
|
136
136
|
'seed', 'litellm-budget', 'oauth-budget', 'profile-map', 'feedback', 'saved', 'cowork', 'team', 'presets', 'routing', 'secrets',
|
|
137
|
+
'panel',
|
|
137
138
|
]);
|
|
138
139
|
|
|
139
140
|
// Flags each entry path reads, collected from the hasFlag/getArg/numArg calls in
|
|
@@ -156,6 +157,11 @@ const FLAG_SPECS = {
|
|
|
156
157
|
// --yes and --no-input are the explicit spelling of "do not ask", and
|
|
157
158
|
// uninstall never asks, so they are accepted as no-ops.
|
|
158
159
|
uninstall: { value: [], bool: ['--purge', '--yes', '--no-input', '--help', '-h'] },
|
|
160
|
+
// The Claude-side panel. The Codex panel is routed away before any spec applies.
|
|
161
|
+
panel: {
|
|
162
|
+
value: ['--project', '--session', '--interval'],
|
|
163
|
+
bool: ['--once', '--no-color', '--icon', '--verbose', '--single-line', '--help', '-h'],
|
|
164
|
+
},
|
|
159
165
|
};
|
|
160
166
|
|
|
161
167
|
/** Which spec applies to this invocation, or null for a subcommand that parses its own arguments. */
|
|
@@ -232,7 +238,7 @@ Usage:
|
|
|
232
238
|
sprag cowork [sync|on|off|exclude <dir>|include <dir>] copy the ratchet rules into Cowork tab folders
|
|
233
239
|
sprag korean on|off|status Korean writing guidance + write-time check
|
|
234
240
|
sprag cohesion on|off|status English sentence-connection guidance
|
|
235
|
-
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
|
|
236
242
|
sprag doc2md on|off|<file> convert documents to Markdown before the model reads them
|
|
237
243
|
sprag delegate on|off|status add bounds and context to Task/Agent delegation prompts
|
|
238
244
|
sprag proof [--json] replayed delegation cases behind the tier rules (https://sprag.io/proof/)
|
|
@@ -248,6 +254,8 @@ Usage:
|
|
|
248
254
|
sprag upgrade install the latest release
|
|
249
255
|
sprag --install-hook install cache-monitor PostToolUse hook
|
|
250
256
|
sprag --uninstall-hook remove that hook
|
|
257
|
+
sprag panel live statusline in a terminal pane, for hosts that do not draw it (T3 Code, Agent SDK)
|
|
258
|
+
--once / --interval <sec> / --project <dir> / --session <id> / --no-color
|
|
251
259
|
sprag --statusline one-line output for Claude Code statusline
|
|
252
260
|
--verbose / --no-color / --icon / --no-timer / --single-line
|
|
253
261
|
--columns N fit lines to N cells (default: $COLUMNS, which Claude Code sets, else 120)
|
|
@@ -306,6 +314,12 @@ async function main() {
|
|
|
306
314
|
}
|
|
307
315
|
}
|
|
308
316
|
|
|
317
|
+
// Subcommand: panel — live statusline for hosts that never run the statusLine
|
|
318
|
+
// command (T3 Code and other Agent SDK hosts). The Codex panel is handled above.
|
|
319
|
+
if (args[0] === 'panel') {
|
|
320
|
+
return (await import('../src/commands/panel.js')).run({ getArg, hasFlag });
|
|
321
|
+
}
|
|
322
|
+
|
|
309
323
|
// Subcommand: last — print the most recent warning + how to handle it.
|
|
310
324
|
// Designed for the auto-trigger skill so the user immediately sees
|
|
311
325
|
// "what just fired and how to fix it" without having to read the whole
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.111.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/commands/brief.js
CHANGED
|
@@ -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(
|
|
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
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subcommand: panel (Claude Code side) -- a live copy of the statusline in a
|
|
3
|
+
* terminal pane.
|
|
4
|
+
*
|
|
5
|
+
* Hosts that run Claude Code headless through the Agent SDK `query()` (T3 Code)
|
|
6
|
+
* never execute settings.json `statusLine.command`, so the statusline is
|
|
7
|
+
* invisible there. Those hosts do ship a terminal whose cwd is the thread's
|
|
8
|
+
* project, so `sprag panel` finds the newest transcript for that project and
|
|
9
|
+
* re-renders the real `sprag --statusline` against it every few seconds.
|
|
10
|
+
*
|
|
11
|
+
* `sprag panel --agent codex` is a different panel and never reaches this file.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { execFile } from 'node:child_process';
|
|
15
|
+
import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
16
|
+
import { basename, join } from 'node:path';
|
|
17
|
+
import { claudeUserDir } from '../paths.js';
|
|
18
|
+
import { CLI_ENTRY } from '../cli-entry.js';
|
|
19
|
+
|
|
20
|
+
const RENDER_TIMEOUT_MS = 4000;
|
|
21
|
+
const DEFAULT_INTERVAL_S = 5;
|
|
22
|
+
const MIN_INTERVAL_S = 1;
|
|
23
|
+
const PASSTHROUGH_FLAGS = ['--no-color', '--icon', '--verbose', '--single-line'];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Where Claude Code keeps its config. paths.js claudeUserDir() ignores
|
|
27
|
+
* CLAUDE_CONFIG_DIR, but a host that sets it (Cowork, T3 profiles) writes its
|
|
28
|
+
* transcripts there, so the panel has to look there first.
|
|
29
|
+
*/
|
|
30
|
+
export function claudeConfigDir(env = process.env) {
|
|
31
|
+
return env.CLAUDE_CONFIG_DIR || claudeUserDir();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Claude Code names a project's transcript directory after its cwd, every non-alphanumeric char turned into '-'. */
|
|
35
|
+
export function encodeProjectDir(cwd) {
|
|
36
|
+
return String(cwd).replace(/[^A-Za-z0-9]/g, '-');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The transcript directory for `cwd`. The realpath is tried as well because the
|
|
41
|
+
* terminal may report /tmp while Claude Code recorded /private/tmp (macOS). When
|
|
42
|
+
* neither exists the directory for the given cwd is returned so callers see "no
|
|
43
|
+
* session yet" rather than an error.
|
|
44
|
+
*/
|
|
45
|
+
export function projectTranscriptDir(cwd, { claudeDir = claudeConfigDir() } = {}) {
|
|
46
|
+
const candidates = [cwd];
|
|
47
|
+
try {
|
|
48
|
+
const real = realpathSync(cwd);
|
|
49
|
+
if (real !== cwd) candidates.push(real);
|
|
50
|
+
} catch { /* cwd may not exist (yet) */ }
|
|
51
|
+
const dirs = candidates.map((c) => join(claudeDir, 'projects', encodeProjectDir(c)));
|
|
52
|
+
return dirs.find((d) => existsSync(d)) || dirs[0];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The session to show: `session` when pinned, otherwise the newest *.jsonl by
|
|
57
|
+
* mtime. Only files directly in the directory count; subdirectories hold
|
|
58
|
+
* subagent transcripts, which must not displace the main session.
|
|
59
|
+
*
|
|
60
|
+
* @returns {{ sessionId: string, transcriptPath: string | null } | null}
|
|
61
|
+
*/
|
|
62
|
+
export function latestSession(cwd, { claudeDir = claudeConfigDir(), session } = {}) {
|
|
63
|
+
const dir = projectTranscriptDir(cwd, { claudeDir });
|
|
64
|
+
if (session) {
|
|
65
|
+
const file = join(dir, `${session}.jsonl`);
|
|
66
|
+
return { sessionId: session, transcriptPath: existsSync(file) ? file : null };
|
|
67
|
+
}
|
|
68
|
+
let best = null;
|
|
69
|
+
let entries;
|
|
70
|
+
try {
|
|
71
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
for (const e of entries) {
|
|
76
|
+
if (!e.isFile() || !e.name.endsWith('.jsonl')) continue;
|
|
77
|
+
const path = join(dir, e.name);
|
|
78
|
+
let mtime;
|
|
79
|
+
try { mtime = statSync(path).mtimeMs; } catch { continue; }
|
|
80
|
+
if (!best || mtime > best.mtime) best = { mtime, path };
|
|
81
|
+
}
|
|
82
|
+
if (!best) return null;
|
|
83
|
+
return { sessionId: basename(best.path, '.jsonl'), transcriptPath: best.path };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The stdin JSON for one statusline render. Only what the panel knows: an
|
|
88
|
+
* absent field means "no data" to the statusline, a 0 means 0%, so rate limits,
|
|
89
|
+
* model and context are never invented here.
|
|
90
|
+
*/
|
|
91
|
+
export function panelPayload({ cwd, session }) {
|
|
92
|
+
const payload = { cwd, workspace: { current_dir: cwd, project_dir: cwd } };
|
|
93
|
+
if (session) {
|
|
94
|
+
payload.session_id = session.sessionId;
|
|
95
|
+
if (session.transcriptPath) payload.transcript_path = session.transcriptPath;
|
|
96
|
+
}
|
|
97
|
+
return payload;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The argv of the child that renders one frame. CLI_ENTRY, never process.argv[1]: under the test runner that is the test file and forks without end. */
|
|
101
|
+
export function renderArgs({ cols, passthrough = [], cliEntry = CLI_ENTRY }) {
|
|
102
|
+
return [cliEntry, '--statusline', '--columns', String(cols), ...passthrough];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Default spawner: run `cmd args` with `input` on stdin, never throw. */
|
|
106
|
+
export function defaultSpawner(cmd, args, { input, timeout, cwd }) {
|
|
107
|
+
return new Promise((resolve) => {
|
|
108
|
+
let child;
|
|
109
|
+
try {
|
|
110
|
+
child = execFile(cmd, args, { timeout, windowsHide: true, cwd, maxBuffer: 1024 * 1024 },
|
|
111
|
+
(err, stdout) => resolve({ ok: !err, stdout: String(stdout || '') }));
|
|
112
|
+
} catch {
|
|
113
|
+
resolve({ ok: false, stdout: '' });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
child.stdin.on('error', () => { /* the child exited before reading; the callback reports it */ });
|
|
117
|
+
child.stdin.end(input);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** One rendered frame, or null when the render failed or timed out (the caller keeps the last frame). */
|
|
122
|
+
export async function renderFrame({
|
|
123
|
+
payload, cols, passthrough = [], spawner = defaultSpawner, execPath = process.execPath,
|
|
124
|
+
cliEntry = CLI_ENTRY, timeoutMs = RENDER_TIMEOUT_MS, cwd,
|
|
125
|
+
}) {
|
|
126
|
+
const res = await spawner(execPath, renderArgs({ cols, passthrough, cliEntry }), {
|
|
127
|
+
input: JSON.stringify(payload), timeout: timeoutMs, cwd,
|
|
128
|
+
});
|
|
129
|
+
if (!res || !res.ok) return null;
|
|
130
|
+
const text = String(res.stdout).replace(/\s+$/, '');
|
|
131
|
+
return text === '' ? null : text;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Repaint only when the frame text changed; a redraw every tick makes the pane flicker. */
|
|
135
|
+
export function createScreen(write) {
|
|
136
|
+
let last = null;
|
|
137
|
+
return {
|
|
138
|
+
draw(frame) {
|
|
139
|
+
if (frame === last) return false;
|
|
140
|
+
last = frame;
|
|
141
|
+
write(`\x1b[H\x1b[2J${frame}\n`);
|
|
142
|
+
return true;
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export const waitingHint = (cwd) => `sprag panel: waiting for a Claude Code session in ${cwd}`;
|
|
148
|
+
|
|
149
|
+
function passthroughOf(hasFlag) {
|
|
150
|
+
return PASSTHROUGH_FLAGS.filter((f) => hasFlag(f));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @param {object} p
|
|
155
|
+
* @param {(name: string) => string | undefined} p.getArg
|
|
156
|
+
* @param {(name: string) => boolean} p.hasFlag
|
|
157
|
+
* @param {object} [p.deps] injection points for tests
|
|
158
|
+
*/
|
|
159
|
+
export async function run({ getArg, hasFlag, deps = {} }) {
|
|
160
|
+
const {
|
|
161
|
+
spawner = defaultSpawner,
|
|
162
|
+
stdout = process.stdout,
|
|
163
|
+
stderr = process.stderr,
|
|
164
|
+
env = process.env,
|
|
165
|
+
setTimeoutFn = setTimeout,
|
|
166
|
+
onStop,
|
|
167
|
+
} = deps;
|
|
168
|
+
const write = (s) => stdout.write(s);
|
|
169
|
+
const cwd = getArg('--project') || process.cwd();
|
|
170
|
+
const pinned = getArg('--session') || undefined;
|
|
171
|
+
const claudeDir = claudeConfigDir(env);
|
|
172
|
+
const passthrough = passthroughOf(hasFlag);
|
|
173
|
+
const cols = () => stdout.columns || 120;
|
|
174
|
+
const renderCwd = existsSync(cwd) ? cwd : undefined;
|
|
175
|
+
|
|
176
|
+
const intervalRaw = getArg('--interval');
|
|
177
|
+
let intervalS = DEFAULT_INTERVAL_S;
|
|
178
|
+
if (intervalRaw !== undefined) {
|
|
179
|
+
const n = Number(intervalRaw);
|
|
180
|
+
if (!Number.isFinite(n)) throw new Error(`--interval expects a number, got "${intervalRaw}"`);
|
|
181
|
+
intervalS = Math.max(MIN_INTERVAL_S, n);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const frameFor = async () => {
|
|
185
|
+
const session = latestSession(cwd, { claudeDir, session: pinned });
|
|
186
|
+
const frame = await renderFrame({
|
|
187
|
+
payload: panelPayload({ cwd, session }), cols: cols(), passthrough, spawner, cwd: renderCwd,
|
|
188
|
+
});
|
|
189
|
+
return { session, frame };
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
if (hasFlag('--once') || !stdout.isTTY) {
|
|
193
|
+
const { session, frame } = await frameFor();
|
|
194
|
+
if (frame !== null) write(`${frame}\n`);
|
|
195
|
+
if (!session) stderr.write(`${waitingHint(cwd)}\n`);
|
|
196
|
+
else if (frame === null) process.exitCode = 1;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const screen = createScreen(write);
|
|
201
|
+
let lastFrame = null;
|
|
202
|
+
let stopped = false;
|
|
203
|
+
let timer = null;
|
|
204
|
+
const stop = () => {
|
|
205
|
+
if (stopped) return;
|
|
206
|
+
stopped = true;
|
|
207
|
+
if (timer) clearTimeout(timer);
|
|
208
|
+
write('\x1b[?25h');
|
|
209
|
+
if (onStop) onStop(); else process.exit(0);
|
|
210
|
+
};
|
|
211
|
+
process.once('SIGINT', stop);
|
|
212
|
+
process.once('SIGTERM', stop);
|
|
213
|
+
write('\x1b[?25l');
|
|
214
|
+
|
|
215
|
+
// The next tick is scheduled only after this one finishes, so a slow render
|
|
216
|
+
// can never stack a second child on top of the first.
|
|
217
|
+
const tick = async () => {
|
|
218
|
+
try {
|
|
219
|
+
const { session, frame } = await frameFor();
|
|
220
|
+
if (frame !== null) lastFrame = frame;
|
|
221
|
+
if (lastFrame !== null) {
|
|
222
|
+
screen.draw(session ? lastFrame : `${lastFrame}\n${waitingHint(cwd)}`);
|
|
223
|
+
} else if (!session) {
|
|
224
|
+
screen.draw(waitingHint(cwd));
|
|
225
|
+
}
|
|
226
|
+
} catch { /* keep the last frame on screen */ }
|
|
227
|
+
if (!stopped) {
|
|
228
|
+
timer = setTimeoutFn(tick, intervalS * 1000);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
await tick();
|
|
232
|
+
}
|
package/src/commands/routing.js
CHANGED
|
@@ -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
|
+
}
|
package/src/installer.js
CHANGED
|
@@ -416,10 +416,28 @@ function detectStatuslineWrapper(command) {
|
|
|
416
416
|
return { script, name, deprecatedFallback: body.includes(`${LEGACY_CLI}@latest`) };
|
|
417
417
|
}
|
|
418
418
|
|
|
419
|
+
/**
|
|
420
|
+
* Whether a statusLine command is the one Orca installs for itself.
|
|
421
|
+
*
|
|
422
|
+
* Orca (stablyai/orca) runs Claude Code in a real terminal and, when the slot is
|
|
423
|
+
* empty, writes a statusLine that runs `~/.orca/agent-hooks/claude-statusline.sh`
|
|
424
|
+
* (`.cmd` on Windows) inside a shell wrapper. That script prints nothing: it only
|
|
425
|
+
* forwards the payload's rate limits to the Orca app. Left in place it blanks the
|
|
426
|
+
* statusline, and Orca never replaces a statusLine it did not write, so whichever
|
|
427
|
+
* tool installs first keeps the slot. Treating it as someone's own statusline made
|
|
428
|
+
* a machine that had Orca first skip ours on every install, with nothing drawn in
|
|
429
|
+
* any terminal.
|
|
430
|
+
*/
|
|
431
|
+
export function isOrcaStatusline(command) {
|
|
432
|
+
return typeof command === 'string' && /\.orca[\\/]agent-hooks[\\/]claude-statusline\b/.test(command);
|
|
433
|
+
}
|
|
434
|
+
|
|
419
435
|
// Registers/repairs the Claude Code statusLine entry in ~/.claude/settings.json.
|
|
420
436
|
// - No statusLine yet: insert ours with refreshInterval:STATUSLINE_REFRESH_INTERVAL.
|
|
421
437
|
// - statusLine already points at sprag: ensure that refreshInterval
|
|
422
438
|
// (this is the bit that makes the TTL countdown tick every second while idle).
|
|
439
|
+
// - statusLine is Orca's usage feed: merge without asking. It draws nothing, and
|
|
440
|
+
// running it as the base keeps Orca's rate-limit display fed.
|
|
423
441
|
// - statusLine points at a different command: leave it alone unless --force,
|
|
424
442
|
// or `merge`, which keeps their command running underneath ours (the original
|
|
425
443
|
// object is saved as config `statuslineBase` so uninstall can restore it).
|
|
@@ -460,6 +478,8 @@ export function installStatusline({ force = false, merge = false } = {}) {
|
|
|
460
478
|
return { path: file, action: 'updated', reason: `set refreshInterval=${STATUSLINE_REFRESH_INTERVAL}` };
|
|
461
479
|
}
|
|
462
480
|
|
|
481
|
+
if (!force && isOrcaStatusline(cur.command)) merge = true;
|
|
482
|
+
|
|
463
483
|
if (!force && !merge) {
|
|
464
484
|
// `conflict` lets the interactive install distinguish "someone else's
|
|
465
485
|
// statusline is here" (worth asking about) from other skip reasons
|
|
@@ -498,7 +518,10 @@ export function installStatusline({ force = false, merge = false } = {}) {
|
|
|
498
518
|
if (merge) {
|
|
499
519
|
cfg.statuslineBase = base;
|
|
500
520
|
saveConfig(cfg);
|
|
501
|
-
|
|
521
|
+
const reason = isOrcaStatusline(base.command)
|
|
522
|
+
? "merged with Orca's statusLine, which keeps running underneath"
|
|
523
|
+
: 'merged with previous statusLine';
|
|
524
|
+
return { path: file, action: 'updated', reason, merged: true };
|
|
502
525
|
}
|
|
503
526
|
// Replace means the old one is gone for good; a stale base would resurrect it
|
|
504
527
|
// (or keep running it) later.
|
package/src/model-rules.js
CHANGED
|
@@ -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.',
|
package/src/route-follow.js
CHANGED
|
@@ -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 });
|
package/src/route-inject.js
CHANGED
|
@@ -140,6 +140,20 @@ export function looksLikeContextOrSpec(text) {
|
|
|
140
140
|
|| (t.length > SPEC_LEN && !looksPasted(t));
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
+
/**
|
|
144
|
+
* True when a prompt reads as a request to write or change code: an edit ask
|
|
145
|
+
* (EDIT_RE, EDIT_MORE_RE) or a written spec (long and not a paste), minus
|
|
146
|
+
* outward actions and open web research. routeMatch never hints for such a
|
|
147
|
+
* request, so src/impl-follow.js uses this to remind about the implementation
|
|
148
|
+
* split at prompt time. Harness-written messages and acks are not requests.
|
|
149
|
+
*/
|
|
150
|
+
export function looksLikeImplementation(text) {
|
|
151
|
+
const t = String(text || '').trim();
|
|
152
|
+
if (t.length < MIN_LEN || isSystemPrompt(t)) return false;
|
|
153
|
+
if (OUTWARD_RE.test(t) || OPEN_RESEARCH_RE.test(t)) return false;
|
|
154
|
+
return EDIT_RE.test(t) || EDIT_MORE_RE.test(t) || (t.length > SPEC_LEN && !looksPasted(t));
|
|
155
|
+
}
|
|
156
|
+
|
|
143
157
|
/**
|
|
144
158
|
* A question that asks for an explanation ("어떻게 쓰이는거지?", "뭐야", "how
|
|
145
159
|
* does it work"). "왜" is not here: ESCALATE_RE already routes it to the top
|
package/src/routing-switch.js
CHANGED
|
@@ -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;
|