harnessed 4.29.0 → 4.31.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/bin/harnessed-stop-hook.mjs +180 -0
- package/dist/cli.mjs +1232 -642
- package/dist/cli.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/schemas/index.mjs +3 -1
- package/dist/schemas/index.mjs.map +1 -1
- package/manifests/optional/stop-hook-recover.yaml +53 -0
- package/package.json +1 -1
- package/schemas/manifest.v1.schema.json +8 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 4.30.0 (issue #6) — Stop hook: auto-recover silent "mode-B" tool-call
|
|
3
|
+
// corruption. Claude Code sometimes mis-samples the tool-open delimiter into a
|
|
4
|
+
// garbage word (count/court/…), so the whole <invoke>…</invoke> block is emitted
|
|
5
|
+
// as PLAIN TEXT — no tool runs, no error, the turn just ends and the model gets
|
|
6
|
+
// no failure signal. The Stop hook fires at turn end; on detecting the mode-B
|
|
7
|
+
// signature it returns {"decision":"block","reason":…} to hand the model one
|
|
8
|
+
// fresh turn to re-emit the call as a real tool_use — no user "retry" needed.
|
|
9
|
+
//
|
|
10
|
+
// Self-contained plain JS (no project imports) — must stay equivalent to
|
|
11
|
+
// src/checkpoint/modeBDetect.ts detectModeB; the parity test in
|
|
12
|
+
// tests/checkpoint/stopHook.test.ts runs this file and cross-checks. Fail-soft:
|
|
13
|
+
// ANY error or non-match exits 0 with no output (a Stop hook must never wedge a
|
|
14
|
+
// normal turn end).
|
|
15
|
+
//
|
|
16
|
+
// stdin payload (CC Stop hook): {session_id, transcript_path, stop_hook_active,
|
|
17
|
+
// hook_event_name, cwd, …}. Loop guard: stop_hook_active + a per-(session,
|
|
18
|
+
// message-signature) retry cap of MAX_RETRIES persisted under the state root.
|
|
19
|
+
import { createHash } from 'node:crypto'
|
|
20
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
21
|
+
import { homedir } from 'node:os'
|
|
22
|
+
import { join } from 'node:path'
|
|
23
|
+
|
|
24
|
+
const MAX_RETRIES = 2
|
|
25
|
+
const TAIL_WINDOW = 200
|
|
26
|
+
|
|
27
|
+
function stateRoot() {
|
|
28
|
+
const override = process.env.HARNESSED_ROOT_OVERRIDE
|
|
29
|
+
return override !== undefined && override !== ''
|
|
30
|
+
? override
|
|
31
|
+
: join(homedir(), '.claude', 'harnessed')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function stripCode(s) {
|
|
35
|
+
return s.replace(/```[\s\S]*?```/g, '').replace(/`[^`]*`/g, '')
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lastIndexOfRe(s, reSrc) {
|
|
39
|
+
const re = new RegExp(reSrc, 'g')
|
|
40
|
+
let last = -1
|
|
41
|
+
for (let m = re.exec(s); m !== null; m = re.exec(s)) last = m.index
|
|
42
|
+
return last
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Mirror of src/checkpoint/modeBDetect.ts detectModeB.
|
|
46
|
+
function detectModeB(content) {
|
|
47
|
+
if (!Array.isArray(content) || content.length === 0) return false
|
|
48
|
+
if (content.some((b) => b && b.type === 'tool_use')) return false
|
|
49
|
+
const text = content
|
|
50
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
51
|
+
.map((b) => b.text)
|
|
52
|
+
.join('\n')
|
|
53
|
+
if (text.length === 0) return false
|
|
54
|
+
const stripped = stripCode(text)
|
|
55
|
+
if (stripped.length === 0) return false
|
|
56
|
+
const invokeAt = lastIndexOfRe(stripped, '<invoke name="')
|
|
57
|
+
const paramAt = lastIndexOfRe(stripped, '<parameter name="')
|
|
58
|
+
if (invokeAt < 0 || paramAt < 0) return false
|
|
59
|
+
const lastTag = Math.max(invokeAt, paramAt)
|
|
60
|
+
return stripped.length - lastTag <= TAIL_WINDOW
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The signature of the corrupted message (its joined text), for the retry cap. */
|
|
64
|
+
function messageSig(content) {
|
|
65
|
+
const text = content
|
|
66
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
67
|
+
.map((b) => b.text)
|
|
68
|
+
.join('\n')
|
|
69
|
+
return createHash('sha256').update(text).digest('hex').slice(0, 16)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Read the LAST assistant message's content blocks from a transcript JSONL.
|
|
73
|
+
* Streams from the file tail (transcripts run to 100k+ lines) — read the last
|
|
74
|
+
* ~256KB, split to lines, scan bottom-up for the last {type:'assistant'} entry.
|
|
75
|
+
* Returns null on any failure (fail-soft). */
|
|
76
|
+
function lastAssistantContent(transcriptPath) {
|
|
77
|
+
try {
|
|
78
|
+
if (!transcriptPath || !existsSync(transcriptPath)) return null
|
|
79
|
+
const buf = readFileSync(transcriptPath)
|
|
80
|
+
const slice = buf.length > 262144 ? buf.subarray(buf.length - 262144) : buf
|
|
81
|
+
const lines = slice.toString('utf8').split('\n')
|
|
82
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
83
|
+
const line = lines[i].trim()
|
|
84
|
+
if (!line) continue
|
|
85
|
+
let obj
|
|
86
|
+
try {
|
|
87
|
+
obj = JSON.parse(line)
|
|
88
|
+
} catch {
|
|
89
|
+
continue // partial first line from the tail slice, or non-JSON
|
|
90
|
+
}
|
|
91
|
+
// CC transcript rows: {type:'assistant', message:{role, content:[…]}}
|
|
92
|
+
if (obj && obj.type === 'assistant') {
|
|
93
|
+
const content = obj.message?.content ?? obj.content
|
|
94
|
+
return Array.isArray(content) ? content : null
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
// fall through
|
|
99
|
+
}
|
|
100
|
+
return null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function retryStore(sessionId) {
|
|
104
|
+
const id = createHash('sha256')
|
|
105
|
+
.update(String(sessionId ?? 'nosession'))
|
|
106
|
+
.digest('hex')
|
|
107
|
+
.slice(0, 16)
|
|
108
|
+
return join(stateRoot(), 'stop-hook-retries', `${id}.json`)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function readRetry(path) {
|
|
112
|
+
try {
|
|
113
|
+
if (!existsSync(path)) return { sig: '', count: 0 }
|
|
114
|
+
const j = JSON.parse(readFileSync(path, 'utf8'))
|
|
115
|
+
return { sig: typeof j.sig === 'string' ? j.sig : '', count: Number(j.count) || 0 }
|
|
116
|
+
} catch {
|
|
117
|
+
return { sig: '', count: 0 }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function writeRetry(path, sig, count) {
|
|
122
|
+
try {
|
|
123
|
+
mkdirSync(join(path, '..'), { recursive: true })
|
|
124
|
+
writeFileSync(path, JSON.stringify({ sig, count }), 'utf8')
|
|
125
|
+
return true
|
|
126
|
+
} catch {
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function readStdin() {
|
|
132
|
+
return new Promise((resolve) => {
|
|
133
|
+
let data = ''
|
|
134
|
+
if (process.stdin.isTTY) return resolve('')
|
|
135
|
+
process.stdin.setEncoding('utf8')
|
|
136
|
+
process.stdin.on('data', (c) => {
|
|
137
|
+
data += c
|
|
138
|
+
})
|
|
139
|
+
process.stdin.on('end', () => resolve(data))
|
|
140
|
+
process.stdin.on('error', () => resolve(data))
|
|
141
|
+
setTimeout(() => resolve(data), 2000).unref?.()
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function main() {
|
|
146
|
+
const raw = await readStdin()
|
|
147
|
+
let payload
|
|
148
|
+
try {
|
|
149
|
+
payload = JSON.parse(raw)
|
|
150
|
+
} catch {
|
|
151
|
+
return // no payload → nothing to do
|
|
152
|
+
}
|
|
153
|
+
// Loop guard 1: the runtime flags a stop that was already re-issued by a hook.
|
|
154
|
+
if (payload.stop_hook_active === true) return
|
|
155
|
+
|
|
156
|
+
const content = lastAssistantContent(payload.transcript_path)
|
|
157
|
+
if (!content || !detectModeB(content)) return
|
|
158
|
+
|
|
159
|
+
// Loop guard 2: per-(session, message signature) retry cap. Only honor the cap
|
|
160
|
+
// when the increment persists — else count would freeze and never recover.
|
|
161
|
+
const sig = messageSig(content)
|
|
162
|
+
const store = retryStore(payload.session_id)
|
|
163
|
+
const prev = readRetry(store)
|
|
164
|
+
const count = prev.sig === sig ? prev.count : 0
|
|
165
|
+
if (count >= MAX_RETRIES) return // give up — avoid an infinite corrupt loop
|
|
166
|
+
const saved = writeRetry(store, sig, count + 1)
|
|
167
|
+
if (!saved) return // could not record → do not block (fail-soft, no loop risk)
|
|
168
|
+
|
|
169
|
+
process.stdout.write(
|
|
170
|
+
`${JSON.stringify({
|
|
171
|
+
decision: 'block',
|
|
172
|
+
reason:
|
|
173
|
+
'MODE-B tool corruption detected: your previous message emitted a tool call as plain text (the opening delimiter was mis-sampled to a garbage word). Re-emit that exact same tool call now as a real tool call — content unchanged.',
|
|
174
|
+
})}\n`,
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
main().catch(() => {
|
|
179
|
+
// fail-soft — a Stop hook must never wedge a normal turn end
|
|
180
|
+
})
|