sprag-cli 3.125.0 → 3.126.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.125.0",
3
+ "version": "3.126.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": {
@@ -14,7 +14,9 @@
14
14
  * brief --hook-tool — PostToolUse hook mode: counts the direct lookups of a
15
15
  * turn that carried a delegation hint and nudges once (src/route-follow.js),
16
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).
17
+ * a prompt that reads as an implementation request (src/impl-follow.js), and
18
+ * suggests once a ratchet rule for an error that keeps coming back, in this
19
+ * session or across sessions (src/ratchet-follow.js).
18
20
  */
19
21
 
20
22
  import { readStdinJson } from '../stdin-payload.js';
@@ -25,8 +27,8 @@ export async function run({ hasFlag }) {
25
27
  if (hasFlag('--hook-tool')) {
26
28
  // PostToolUse: a nudge is context for the model, so it goes out as
27
29
  // 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
+ // Three followers see the same payload (lookups after a hint, edits without
31
+ // a delegation, errors that recur); their notices go out as one context block.
30
32
  const payload = readStdinJson() || {};
31
33
  const notes = [];
32
34
  try {
@@ -39,6 +41,11 @@ export async function run({ hasFlag }) {
39
41
  const nudge = implFollowToolUse(payload);
40
42
  if (nudge) notes.push(nudge);
41
43
  } catch (e) { debug('brief:hook-tool-impl', e); }
44
+ try {
45
+ const { ratchetFollowToolUse } = await import('../ratchet-follow.js');
46
+ const nudge = await ratchetFollowToolUse(payload);
47
+ if (nudge) notes.push(nudge);
48
+ } catch (e) { debug('brief:hook-tool-ratchet', e); }
42
49
  if (notes.length) {
43
50
  console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: notes.join('\n\n') } }));
44
51
  }
@@ -156,8 +156,11 @@ export async function run({ args, hasFlag }) {
156
156
  const n = parseInt(raw, 10);
157
157
  const analyzer = await import('../harness-analyzer.cjs');
158
158
  const a = analyzer.default || analyzer;
159
+ // The tool hook's candidate file wins when it has any; the analyzer
160
+ // state is the fallback.
161
+ const hookList = a.readCandidates()?.candidates;
159
162
  const state = a.readState();
160
- const list = (state && state.ratchetCandidates) || [];
163
+ const list = Array.isArray(hookList) && hookList.length ? hookList : (state && state.ratchetCandidates) || [];
161
164
  const cand = list.find((c) => c.id === n);
162
165
  if (!cand) {
163
166
  console.error(`No ratchet candidate #${n} in state. Run \`harness analyze\` or wait for the hook to populate it.`);
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * Three signals (precedence: ratchet? > no-evidence > PEV-skip):
6
6
  *
7
- * 1. Ratchet candidate — same is_error tool_use_result appears 2+ times in
8
- * the last 30 turns. Suggests the user codify a rule so it doesn't repeat.
7
+ * 1. Ratchet candidate — same is_error tool_use_result (grouped by
8
+ * normalizeError) appears 2+ times in the last 30 turns. Suggests the user codify a rule so it doesn't repeat.
9
9
  *
10
10
  * 2. Evidence rate — fraction of recent assistant messages that ship proof
11
11
  * (code blocks, tool_use_result, "test"/"output"/"diff"/"screenshot"
@@ -29,6 +29,7 @@ const os = require('node:os');
29
29
 
30
30
  const STATE_DIR = stateDir();
31
31
  const STATE_PATH = path.join(STATE_DIR, 'harness-state.json');
32
+ const CANDIDATES_PATH = path.join(STATE_DIR, 'ratchet-candidates.json');
32
33
 
33
34
  const RECENT_TURNS = 15; // PEV / evidence window (assistant turns)
34
35
  const RATCHET_TURNS = 30; // ratchet-candidate window
@@ -74,6 +75,81 @@ function readJsonl(file) {
74
75
  return out;
75
76
  }
76
77
 
78
+ /**
79
+ * The entries in the last `maxBytes` of a transcript. Every signal here looks
80
+ * at the recent end of the session only, and the tool hook calls this on each
81
+ * tool use, so the cost has to stay flat while the transcript grows (a long
82
+ * session reaches tens of megabytes). The first line of the slice is dropped
83
+ * when the read started mid-file, because it is cut.
84
+ */
85
+ function readTailEntries(file, maxBytes) {
86
+ const limit = maxBytes > 0 ? maxBytes : 1024 * 1024;
87
+ let raw = '';
88
+ let cut = false;
89
+ let fd = null;
90
+ try {
91
+ fd = fs.openSync(file, 'r');
92
+ const size = fs.fstatSync(fd).size;
93
+ const start = Math.max(0, size - limit);
94
+ const buf = Buffer.alloc(size - start);
95
+ let read = 0;
96
+ while (read < buf.length) {
97
+ const n = fs.readSync(fd, buf, read, buf.length - read, start + read);
98
+ if (n <= 0) break;
99
+ read += n;
100
+ }
101
+ raw = buf.toString('utf8', 0, read);
102
+ cut = start > 0;
103
+ } catch {
104
+ return [];
105
+ } finally {
106
+ if (fd !== null) { try { fs.closeSync(fd); } catch { /* already closed */ } }
107
+ }
108
+ const lines = raw.split('\n');
109
+ if (cut) lines.shift();
110
+ const out = [];
111
+ for (const line of lines) {
112
+ if (!line.trim()) continue;
113
+ try {
114
+ out.push(JSON.parse(line));
115
+ } catch {
116
+ // ignore corrupt line
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * The conversation itself: user and assistant messages in order, one entry per
124
+ * message.
125
+ *
126
+ * A transcript is more than that. Claude Code writes hook results, API request
127
+ * records, mode and title changes between the messages, and stores each content
128
+ * block of one assistant message (thinking, text, tool_use) as its own line.
129
+ * Reading the raw lines as turns broke two signals: the tool result was no
130
+ * longer the entry right after its tool call (a hook record sat between them),
131
+ * so no assistant message ever counted as showing its work, and a window of 15
132
+ * "assistant turns" covered a handful of real ones. Subagent lines kept in the
133
+ * parent transcript (`isSidechain`) are not this session's conversation.
134
+ */
135
+ function conversation(entries) {
136
+ const out = [];
137
+ for (const e of entries) {
138
+ if (!e || !e.message || e.isSidechain === true) continue;
139
+ if (e.type !== 'user' && e.type !== 'assistant') continue;
140
+ const prev = out[out.length - 1];
141
+ const id = e.message.id;
142
+ if (e.type === 'assistant' && id && prev && prev.type === 'assistant' && prev.message.id === id
143
+ && Array.isArray(prev.message.content) && Array.isArray(e.message.content)) {
144
+ prev.message = { ...prev.message, content: prev.message.content.concat(e.message.content) };
145
+ prev.timestamp = e.timestamp || prev.timestamp;
146
+ continue;
147
+ }
148
+ out.push({ type: e.type, timestamp: e.timestamp, message: e.message });
149
+ }
150
+ return out;
151
+ }
152
+
77
153
  /**
78
154
  * Pull the text payload out of an assistant message, regardless of whether
79
155
  * Claude Code stored it as a string, a content-block array, or a mix.
@@ -127,7 +203,28 @@ function looksLikePlanSignal(text, toolUses) {
127
203
  return planWords.some((w) => lower.includes(w));
128
204
  }
129
205
 
130
- function errorSignature(toolResult) {
206
+ // A tool call the user turned down comes back as an error result too. Two of
207
+ // those in a row are the user's decision, twice, and no rule would have
208
+ // prevented them. In 14 days of transcripts on one machine these were the most
209
+ // common "repeated error" (9 of 51 sessions that had one). An interrupted call
210
+ // is the same kind of result.
211
+ const USER_DECISION_RE = /^(?:<tool_use_error>\s*)?(?:The user doesn't want to (?:proceed|take this action)|\[Request interrupted by user|\[Tool call interrupted|Permission (?:for this action|to use \S+) (?:was|has been) denied|Claude requested permissions? to|The user (?:rejected|denied|declined))/i;
212
+
213
+ /**
214
+ * The grouping key of an error text: volatile parts (paths, hashes, numbers)
215
+ * are replaced so two runs of the same failure land in one group.
216
+ */
217
+ function normalizeError(text) {
218
+ return String(text)
219
+ .replace(/^<tool_use_error>\s*/i, '')
220
+ .replace(/(?:[A-Za-z]:)?(?:\/[\w.@~+-]+){2,}\/?/g, '<path>')
221
+ .replace(/\b[0-9a-f]{7,}\b/gi, '<id>')
222
+ .replace(/\d+/g, '#')
223
+ .slice(0, 60);
224
+ }
225
+
226
+ /** `{ key, pattern }` of an is_error tool_result, or null when it is not a signal. */
227
+ function errorInfo(toolResult) {
131
228
  if (!toolResult || toolResult.is_error !== true) return null;
132
229
  const c = toolResult.content;
133
230
  let txt = '';
@@ -137,39 +234,45 @@ function errorSignature(toolResult) {
137
234
  }
138
235
  txt = txt.replace(/\s+/g, ' ').trim();
139
236
  if (!txt) return null;
140
- // First 80 chars is enough to dedupe most repeated errors without overfitting
141
- // to volatile bits like timestamps or pids.
142
- return txt.slice(0, 80);
237
+ if (USER_DECISION_RE.test(txt)) return null;
238
+ const key = normalizeError(txt);
239
+ // A bare exit status says nothing about what failed; "Exit code 1" alone
240
+ // would group every failed command in the session.
241
+ if (key.replace(/^Exit code #/, '').trim().length < 12) return null;
242
+ return { key, pattern: txt.slice(0, 80) };
143
243
  }
144
244
 
145
245
  /**
146
- * Walk the last `RATCHET_TURNS` turns and surface error signatures that
147
- * appear 2+ times. Returns the top candidate (or null).
246
+ * The error groups in the last `RATCHET_TURNS` messages of the conversation:
247
+ * `{ key, pattern, count, lastAt }`, `pattern` being the first original text
248
+ * seen (80 chars). Takes raw transcript entries.
148
249
  */
149
- function findRatchetCandidates(entries) {
150
- const counts = new Map();
151
- const recent = entries.slice(-RATCHET_TURNS);
250
+ function recentErrors(rawEntries) {
251
+ const groups = new Map();
252
+ const recent = conversation(rawEntries).slice(-RATCHET_TURNS);
152
253
  for (const e of recent) {
153
- const msg = e && e.message;
154
- if (!msg) continue;
155
- for (const tr of toolResultsIn(msg)) {
156
- const sig = errorSignature(tr);
157
- if (!sig) continue;
158
- const cur = counts.get(sig) || { count: 0, lastAt: e.timestamp };
254
+ for (const tr of toolResultsIn(e.message)) {
255
+ const info = errorInfo(tr);
256
+ if (!info) continue;
257
+ const cur = groups.get(info.key) || { key: info.key, pattern: info.pattern, count: 0, lastAt: e.timestamp };
159
258
  cur.count += 1;
160
259
  cur.lastAt = e.timestamp || cur.lastAt;
161
- counts.set(sig, cur);
260
+ groups.set(info.key, cur);
162
261
  }
163
262
  }
164
- const list = [];
165
- for (const [sig, info] of counts.entries()) {
166
- if (info.count < 2) continue;
167
- list.push({ pattern: sig, count: info.count, lastAt: info.lastAt });
168
- }
263
+ return [...groups.values()];
264
+ }
265
+
266
+ /**
267
+ * Error groups that appear 2+ times in the last `RATCHET_TURNS` messages.
268
+ * Takes raw transcript entries.
269
+ */
270
+ function findRatchetCandidates(rawEntries) {
271
+ const list = recentErrors(rawEntries).filter((g) => g.count >= 2);
169
272
  // Top 5 by count, ID assigned in rank order so `harness promote 1` always
170
273
  // targets the most-repeated error — stable even as new candidates appear.
171
274
  list.sort((a, b) => b.count - a.count);
172
- return list.slice(0, 5).map((c, i) => ({ id: i + 1, ...c }));
275
+ return list.slice(0, 5).map((g, i) => ({ id: i + 1, pattern: g.pattern, count: g.count, lastAt: g.lastAt, key: g.key }));
173
276
  }
174
277
 
175
278
  /**
@@ -220,11 +323,15 @@ function analyzeTranscript(transcriptPath, opts) {
220
323
  opts = opts || {};
221
324
  // The hook has already parsed the transcript for its own totals; reading a
222
325
  // 65MB session a second time per tool call is the one avoidable cost here.
223
- const entries = Array.isArray(opts.entries) ? opts.entries : readJsonl(transcriptPath);
224
- if (entries.length === 0) return null;
326
+ // The tool hook has no parsed transcript at hand and passes `tailBytes`.
327
+ const raw = Array.isArray(opts.entries) ? opts.entries
328
+ : opts.tailBytes ? readTailEntries(transcriptPath, opts.tailBytes)
329
+ : readJsonl(transcriptPath);
330
+ if (raw.length === 0) return null;
331
+ const entries = conversation(raw);
225
332
  const evidenceRate = computeEvidenceRate(entries);
226
333
  const pevSkip = computePevSkip(entries);
227
- const ratchetCandidates = findRatchetCandidates(entries);
334
+ const ratchetCandidates = findRatchetCandidates(raw);
228
335
  return {
229
336
  sessionId: opts.sessionId || null,
230
337
  cwd: opts.cwd || null,
@@ -238,15 +345,14 @@ function analyzeTranscript(transcriptPath, opts) {
238
345
  };
239
346
  }
240
347
 
241
- function writeState(state) {
242
- if (!state) return;
348
+ function writeJsonAtomic(dir, file, obj) {
243
349
  try {
244
- if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
245
- // tmp + rename so the statusline never reads a half-written state file.
246
- const tmp = STATE_PATH + '.' + process.pid + '.tmp';
350
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
351
+ // tmp + rename so the statusline never reads a half-written file.
352
+ const tmp = file + '.' + process.pid + '.tmp';
247
353
  try {
248
- fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n');
249
- fs.renameSync(tmp, STATE_PATH);
354
+ fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n');
355
+ fs.renameSync(tmp, file);
250
356
  } catch (e) {
251
357
  // A failed write or rename must not leave the temp file behind.
252
358
  try { fs.rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
@@ -257,6 +363,33 @@ function writeState(state) {
257
363
  }
258
364
  }
259
365
 
366
+ function writeState(state) {
367
+ if (!state) return;
368
+ writeJsonAtomic(STATE_DIR, STATE_PATH, state);
369
+ }
370
+
371
+ /**
372
+ * The ratchet candidates the tool hook found, kept apart from the state file:
373
+ * the state file is the analyzer's (evidence, PEV), this one is the follower's.
374
+ * `dir` replaces the state dir (tests).
375
+ */
376
+ function candidatesFile(dir) {
377
+ return dir ? path.join(dir, 'ratchet-candidates.json') : CANDIDATES_PATH;
378
+ }
379
+
380
+ function writeCandidates(obj, dir) {
381
+ if (!obj) return;
382
+ writeJsonAtomic(dir || STATE_DIR, candidatesFile(dir), obj);
383
+ }
384
+
385
+ function readCandidates(dir) {
386
+ try {
387
+ return JSON.parse(fs.readFileSync(candidatesFile(dir), 'utf8'));
388
+ } catch {
389
+ return null;
390
+ }
391
+ }
392
+
260
393
  function readState() {
261
394
  try {
262
395
  if (!fs.existsSync(STATE_PATH)) return null;
@@ -268,8 +401,16 @@ function readState() {
268
401
 
269
402
  module.exports = {
270
403
  analyzeTranscript,
404
+ readTailEntries,
405
+ conversation,
406
+ normalizeError,
407
+ recentErrors,
408
+ findRatchetCandidates,
271
409
  writeState,
272
410
  readState,
411
+ readCandidates,
412
+ writeCandidates,
273
413
  STATE_PATH,
414
+ CANDIDATES_PATH,
274
415
  EVIDENCE_THRESHOLD,
275
416
  };
package/src/harness.js CHANGED
@@ -41,6 +41,14 @@ function readHarnessState() {
41
41
  }
42
42
  }
43
43
 
44
+ function readHarnessCandidates() {
45
+ try {
46
+ return require('./harness-analyzer.cjs').readCandidates();
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
44
52
  /**
45
53
  * Walk up from `start` looking for a project root marker (CLAUDE.md, .git,
46
54
  * or package.json). Falls back to `start` itself so harness commands always
@@ -626,12 +634,26 @@ export function harnessStatusForStatusline(cfg, { root, liveWindow = null, liveM
626
634
  const WARNING_TTL_MS = 30 * 60 * 1000;
627
635
  const state = readHarnessState();
628
636
  const warnings = [];
637
+ // The tool hook's candidate file (src/ratchet-follow.js) comes first: it also
638
+ // sees errors that recur across sessions. The analyzer state's own
639
+ // candidate is the fallback, and the chip is added once either way.
640
+ let ratchetChip = false;
641
+ try {
642
+ const cand = readHarnessCandidates();
643
+ const ts = cand && cand.timestamp ? Date.parse(cand.timestamp) : NaN;
644
+ const first = cand && Array.isArray(cand.candidates) ? cand.candidates[0] : null;
645
+ if (first && first.count >= 2 && Number.isFinite(ts) && Date.now() - ts <= WARNING_TTL_MS
646
+ && cand.cwd && findProjectRoot(cand.cwd) === projectRoot) {
647
+ warnings.push(`ratchet? #${first.id || 1}`);
648
+ ratchetChip = true;
649
+ }
650
+ } catch { /* candidate file unreadable — fall back to the state */ }
629
651
  if (state) {
630
652
  const ts = state.timestamp ? Date.parse(state.timestamp) : NaN;
631
653
  const fresh = Number.isFinite(ts) && Date.now() - ts <= WARNING_TTL_MS;
632
654
  const matches = !!state.cwd && findProjectRoot(state.cwd) === projectRoot;
633
655
  if (fresh && matches) {
634
- if (state.ratchetCandidate && state.ratchetCandidate.count >= 2) {
656
+ if (!ratchetChip && state.ratchetCandidate && state.ratchetCandidate.count >= 2) {
635
657
  const id = state.ratchetCandidate.id || 1;
636
658
  warnings.push(`ratchet? #${id}`);
637
659
  }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Ratchet candidates from the PostToolUse hook: spot an error that keeps coming
3
+ * back, record it for the statusline chip, and tell the model once to ask the
4
+ * user whether to turn it into a ratchet rule.
5
+ *
6
+ * Why this exists: the `ratchet? #N` chip and the "register this mistake as a
7
+ * rule" suggestion almost never appeared. Three causes. The detector in
8
+ * src/harness-analyzer.cjs was only called from the `--hook-run` hook, which
9
+ * `sprag install` does not register. A candidate only ever reached the
10
+ * statusline, never the model's context. And the detector looked for the same
11
+ * error twice inside the last 30 lines of one session, which misses the errors
12
+ * that recur across sessions. Measured over 30 days and 1043 sessions: 30 error
13
+ * shapes recurred in two or more sessions, while a repeat inside a single session
14
+ * happened in only 6 sessions over 14 days.
15
+ *
16
+ * So this follower runs on `sprag brief --hook-tool` (installed by default), next
17
+ * to route-follow.js and impl-follow.js. It keeps a small ledger of error shapes
18
+ * (`<base>/ratchet-seen.json`) that holds only hashes and times, never error
19
+ * text, so a shape seen in another session counts toward the same candidate.
20
+ *
21
+ * Files under the data dir (`dir` replaces it in tests):
22
+ * ratchet-seen.json { v: 1, sigs: { "<h12>": { s: [session hash x8], first, last, nudged? } } }
23
+ * ratchet-candidates.json written through harness-analyzer.cjs, read by the statusline and `harness promote N`
24
+ * route-follow/<sid>.ratchet-<h12> `wx` marker, so of several parallel hook
25
+ * processes exactly one speaks
26
+ * Events go to route-follow-events.jsonl as `ratchet-nudged` (no error text).
27
+ *
28
+ * Switches: `harness.enabled: false` silences everything, `ratchetFollowUp: false`
29
+ * in config.json keeps the candidate file but drops the notice. A clean tool
30
+ * call ends before any file is read or written. The module never throws into a
31
+ * hook.
32
+ */
33
+
34
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, openSync, closeSync } from 'node:fs';
35
+ import { join } from 'node:path';
36
+ import { createHash } from 'node:crypto';
37
+ import { createRequire } from 'node:module';
38
+ import { userDataDir } from './paths.js';
39
+ import { loadConfig, userLanguage } from './config.js';
40
+ import { logEvent } from './route-follow.js';
41
+ import { CLI_NAME } from './cli-name.js';
42
+ import { debug } from './debug.js';
43
+
44
+ const require = createRequire(import.meta.url);
45
+
46
+ const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
47
+ const TAIL_BYTES = 1024 * 1024;
48
+ const LEDGER_TTL_MS = 30 * 24 * 60 * 60 * 1000;
49
+ const LEDGER_MAX = 400;
50
+ const SESSIONS_KEPT = 8;
51
+ const MAX_CANDIDATES = 5;
52
+
53
+ const sha1 = (s, n) => createHash('sha1').update(String(s)).digest('hex').slice(0, n);
54
+
55
+ function readLedger(file) {
56
+ try {
57
+ const l = JSON.parse(readFileSync(file, 'utf8'));
58
+ if (l && l.v === 1 && l.sigs && typeof l.sigs === 'object') return l;
59
+ } catch (e) {
60
+ if (e?.code !== 'ENOENT') debug('ratchet-follow:ledger-read', e);
61
+ }
62
+ return { v: 1, sigs: {} };
63
+ }
64
+
65
+ function writeLedger(file, ledger, now) {
66
+ const sigs = ledger.sigs;
67
+ for (const k of Object.keys(sigs)) {
68
+ if (!(now - (sigs[k].last || 0) <= LEDGER_TTL_MS)) delete sigs[k];
69
+ }
70
+ const keys = Object.keys(sigs);
71
+ if (keys.length > LEDGER_MAX) {
72
+ keys.sort((a, b) => (sigs[a].last || 0) - (sigs[b].last || 0));
73
+ for (const k of keys.slice(0, keys.length - LEDGER_MAX)) delete sigs[k];
74
+ }
75
+ const tmp = `${file}.${process.pid}.tmp`;
76
+ try {
77
+ writeFileSync(tmp, JSON.stringify(ledger) + '\n');
78
+ renameSync(tmp, file);
79
+ } catch (e) {
80
+ try { rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
81
+ throw e;
82
+ }
83
+ }
84
+
85
+ function noticeText({ count, sessions, pattern, lang }) {
86
+ if (lang === 'ko') {
87
+ const where = sessions < 2 ? `이 세션에서 ${count}번` : `최근 30일 동안 세션 ${sessions}개에서`;
88
+ return `✇ [sprag] 같은 오류가 ${where} 발생했습니다: "${pattern}". `
89
+ + '지금 하던 작업을 마친 뒤 답변 끝에서 이 실수를 래칫 룰로 등록할지 사용자에게 한 번 물으십시오. '
90
+ + '물을 때는 "조건 → 행동" 한 줄로 쓴 룰 초안을 보여 주고 등록 범위(global 또는 project)도 함께 묻습니다. '
91
+ + `사용자가 승인하면 \`${CLI_NAME} harness promote "<룰>" --global\` 또는 \`--project\` 로 등록합니다. `
92
+ + '같은 내용을 다루는 룰이 이미 있으면 새로 묻지 말고 그 룰을 따르지 못한 이유를 밝히십시오. '
93
+ + '환경 문제나 일회성 오타라서 룰로 막을 수 없는 오류라면 묻지 말고 그 이유를 한 줄로 밝히십시오. '
94
+ + '이 오류는 다시 안내하지 않습니다.';
95
+ }
96
+ const where = sessions < 2 ? `${count} times in this session` : `in ${sessions} sessions over the last 30 days`;
97
+ return `✇ [sprag] The same error has now come up ${where}: "${pattern}". `
98
+ + 'When the current task is done, ask the user once, at the end of your reply, whether to register this mistake as a ratchet rule. '
99
+ + 'Show a one-line draft in the form "condition → action" and ask for the scope (global or project) in the same question. '
100
+ + `On approval, register it with \`${CLI_NAME} harness promote "<rule>" --global\` or \`--project\`. `
101
+ + 'If a rule already covers it, do not ask again; say why that rule was not followed. '
102
+ + 'If no rule could have prevented it (an environment problem, a one-off typo), do not ask; say why in one line instead. '
103
+ + 'This notice does not repeat for this error.';
104
+ }
105
+
106
+ /**
107
+ * PostToolUse entry: update the ledger, write the candidate file, and return
108
+ * the notice the first time a candidate crosses the threshold.
109
+ *
110
+ * @param {object} payload hook payload (`session_id`, `transcript_path`, `cwd`, `hook_event_name`, `agent_id`)
111
+ * @param {{now?: number, cfg?: object, dir?: string, lang?: string, harnessReady?: boolean}} [opts]
112
+ * `dir` replaces the user data dir (tests); `harnessReady` replaces the check
113
+ * that the project's CLAUDE.md carries the harness block
114
+ * @returns {Promise<string|null>} the notice to add as context, or null
115
+ */
116
+ export async function ratchetFollowToolUse(payload, { now = Date.now(), cfg = loadConfig(), dir, lang, harnessReady } = {}) {
117
+ try {
118
+ if (cfg?.harness?.enabled === false) return null;
119
+ if (payload?.agent_id) return null;
120
+ if (payload?.hook_event_name && payload.hook_event_name !== 'PostToolUse') return null;
121
+ const sessionId = payload?.session_id;
122
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null;
123
+ if (typeof payload.transcript_path !== 'string') return null;
124
+
125
+ const analyzer = require('./harness-analyzer.cjs');
126
+ const errors = analyzer.recentErrors(analyzer.readTailEntries(payload.transcript_path, TAIL_BYTES));
127
+ if (errors.length === 0) return null;
128
+
129
+ const base = dir || userDataDir();
130
+ const ledgerFile = join(base, 'ratchet-seen.json');
131
+ const ledger = readLedger(ledgerFile);
132
+ const sh = sha1(sessionId, 8);
133
+ let changed = false;
134
+ const rows = errors.map((e) => {
135
+ const h12 = sha1(e.key, 12);
136
+ let entry = ledger.sigs[h12];
137
+ if (!entry) {
138
+ entry = { s: [], first: now, last: now };
139
+ ledger.sigs[h12] = entry;
140
+ changed = true;
141
+ }
142
+ if (!entry.s.includes(sh)) {
143
+ entry.s = entry.s.concat(sh).slice(-SESSIONS_KEPT);
144
+ entry.last = now;
145
+ changed = true;
146
+ }
147
+ return { e, h12, entry };
148
+ });
149
+ if (changed) {
150
+ mkdirSync(base, { recursive: true });
151
+ writeLedger(ledgerFile, ledger, now);
152
+ }
153
+
154
+ const ranked = rows
155
+ .map(({ e, h12, entry }) => ({ pattern: e.pattern, count: Math.max(e.count, entry.s.length), sessions: entry.s.length, lastAt: e.lastAt, key: h12 }))
156
+ .filter((c) => c.count >= 2)
157
+ .sort((a, b) => b.count - a.count)
158
+ .slice(0, MAX_CANDIDATES);
159
+ const candidates = ranked.map((c, i) => ({ id: i + 1, ...c }));
160
+ if (candidates.length === 0) return null;
161
+
162
+ analyzer.writeCandidates({
163
+ sessionId,
164
+ cwd: payload.cwd || null,
165
+ timestamp: new Date(now).toISOString(),
166
+ candidates,
167
+ }, dir);
168
+
169
+ if (cfg?.ratchetFollowUp === false) return null;
170
+ let ready = harnessReady;
171
+ if (typeof ready !== 'boolean') {
172
+ const { harnessStatus, findProjectRoot } = await import('./harness.js');
173
+ ready = !!harnessStatus(findProjectRoot(payload.cwd || process.cwd())).hasBlock;
174
+ }
175
+ if (!ready) return null;
176
+
177
+ const pick = candidates.find((c) => !ledger.sigs[c.key]?.nudged);
178
+ if (!pick) return null;
179
+ const markerDir = join(base, 'route-follow');
180
+ mkdirSync(markerDir, { recursive: true });
181
+ try { closeSync(openSync(join(markerDir, `${sessionId}.ratchet-${pick.key}`), 'wx')); } catch (e) {
182
+ if (e?.code !== 'EEXIST') debug('ratchet-follow:marker', e);
183
+ return null;
184
+ }
185
+ ledger.sigs[pick.key].nudged = now;
186
+ writeLedger(ledgerFile, ledger, now);
187
+ logEvent(dir, { at: now, agent: 'claude', sessionId, event: 'ratchet-nudged', count: pick.count, sessions: pick.sessions });
188
+ return noticeText({ count: pick.count, sessions: pick.sessions, pattern: pick.pattern, lang: lang || userLanguage() });
189
+ } catch (e) {
190
+ debug('ratchet-follow:tool', e);
191
+ return null;
192
+ }
193
+ }