harnessed 4.29.0 → 4.30.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.
@@ -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
+ })
package/dist/cli.mjs CHANGED
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.29.0",
41
+ version: "4.30.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -1177,7 +1177,9 @@ var init_ccHookAdd = __esm({
1177
1177
  Type.Literal("SessionStart"),
1178
1178
  Type.Literal("UserPromptSubmit"),
1179
1179
  Type.Literal("PreToolUse"),
1180
- Type.Literal("PostToolUse")
1180
+ Type.Literal("PostToolUse"),
1181
+ // 4.30.0 (issue #6) — Stop hook for mode-B tool-call corruption auto-recovery.
1182
+ Type.Literal("Stop")
1181
1183
  ]);
1182
1184
  CcHookAdd = Type.Object(
1183
1185
  {
@@ -6754,9 +6756,10 @@ function stripQuotes(token) {
6754
6756
  return { bare: token, quoted: false };
6755
6757
  }
6756
6758
  function resolveHookCommand(raw, deps) {
6757
- if (deps.compiledExecPath && hookScriptMarker(raw) === INJECT_IDENTITY) {
6759
+ const marker = deps.compiledExecPath ? hookScriptMarker(raw) : null;
6760
+ if (deps.compiledExecPath && marker && COMPILED_HOOK_IDENTITIES.includes(marker)) {
6758
6761
  const exe = deps.compiledExecPath();
6759
- if (exe) return `"${exe.replace(/\\/g, "/")}" ${INJECT_IDENTITY}`;
6762
+ if (exe) return `"${exe.replace(/\\/g, "/")}" ${marker}`;
6760
6763
  }
6761
6764
  let root = null;
6762
6765
  const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
@@ -6776,12 +6779,14 @@ function hookScriptMarker(raw) {
6776
6779
  if (isRelativeFileToken(bare2)) {
6777
6780
  const seg = bare2.split(/[\\/]/);
6778
6781
  const base = seg[seg.length - 1] ?? null;
6779
- if (base?.includes(INJECT_IDENTITY)) return INJECT_IDENTITY;
6782
+ const id = COMPILED_HOOK_IDENTITIES.find((k) => base?.includes(k));
6783
+ if (id) return id;
6780
6784
  return base;
6781
6785
  }
6782
6786
  }
6783
6787
  for (const token of raw.split(/\s+/)) {
6784
- if (stripQuotes(token).bare === INJECT_IDENTITY) return INJECT_IDENTITY;
6788
+ const { bare: bare2 } = stripQuotes(token);
6789
+ if (COMPILED_HOOK_IDENTITIES.includes(bare2)) return bare2;
6785
6790
  }
6786
6791
  return null;
6787
6792
  }
@@ -6829,10 +6834,10 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
6829
6834
  const matching = arr.filter((e) => entryMatchesRegistration(e, raw, resolved, marker));
6830
6835
  return matching.length === 1 && isDesiredHookEntry(matching[0] ?? {}, matcher, resolved);
6831
6836
  }
6832
- var INJECT_IDENTITY, ABSOLUTE_RE;
6837
+ var COMPILED_HOOK_IDENTITIES, ABSOLUTE_RE;
6833
6838
  var init_hookEntry = __esm({
6834
6839
  "src/installers/lib/hookEntry.ts"() {
6835
- INJECT_IDENTITY = "inject-state";
6840
+ COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook"];
6836
6841
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
6837
6842
  }
6838
6843
  });
@@ -12536,6 +12541,19 @@ ${b.failed.length} component(s) failed \u2014 see the notes in the tables above;
12536
12541
  });
12537
12542
  }
12538
12543
 
12544
+ // src/cli/stopHookCmd.ts
12545
+ init_assetsRoot();
12546
+ function registerStopHook(program2) {
12547
+ program2.command("stop-hook").description("(internal) Stop hook \u2014 auto-recovers mode-B tool-call corruption (issue #6)").action(async () => {
12548
+ try {
12549
+ const mjs = join(getAssetsRoot(), "bin", "harnessed-stop-hook.mjs");
12550
+ if (!existsSync(mjs)) return;
12551
+ await import(pathToFileURL(mjs).href);
12552
+ } catch {
12553
+ }
12554
+ });
12555
+ }
12556
+
12539
12557
  // src/cli/uninstall.ts
12540
12558
  init_i18n();
12541
12559
  init_harnessedRoot();
@@ -13258,6 +13276,7 @@ registerUpdate(program);
13258
13276
  registerReleasePreflight(program);
13259
13277
  registerRetro(program);
13260
13278
  registerInjectState(program);
13279
+ registerStopHook(program);
13261
13280
  var bare = parseBareInvocation(process.argv.slice(2));
13262
13281
  if (bare.here) {
13263
13282
  void runHere({ json: bare.json });