harnessed 4.32.19 → 4.32.21

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.
@@ -1,132 +1,143 @@
1
1
  #!/usr/bin/env node
2
+ // biome-ignore-all format: esbuild-generated (hook drift gate owns this file)
3
+ // biome-ignore-all lint: esbuild-generated
4
+ // biome-ignore-all assist/source/organizeImports: esbuild-generated
2
5
 
3
6
  // src/checkpoint/stopHookMain.ts
4
7
  import { createHash } from "node:crypto";
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { homedir } from "node:os";
7
- import { join } from "node:path";
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
8
11
 
9
12
  // src/checkpoint/modeBDetect.ts
10
- var TAIL_WINDOW = 200;
11
- var INVOKE_RE = /<invoke name="/g;
12
- var PARAM_RE = /<parameter name="/g;
13
+ var TAIL_WINDOW = 200
14
+ var INVOKE_RE = /<invoke name="/g
15
+ var PARAM_RE = /<parameter name="/g
13
16
  function stripCode(s) {
14
- return s.replace(/```[\s\S]*?```/g, "").replace(/`[^`]*`/g, "");
17
+ return s.replace(/```[\s\S]*?```/g, '').replace(/`[^`]*`/g, '')
15
18
  }
16
19
  function lastIndexOfRe(s, re) {
17
- let last = -1;
18
- re.lastIndex = 0;
19
- for (let m = re.exec(s); m !== null; m = re.exec(s)) last = m.index;
20
- return last;
20
+ let last = -1
21
+ re.lastIndex = 0
22
+ for (let m = re.exec(s); m !== null; m = re.exec(s)) last = m.index
23
+ return last
21
24
  }
22
25
  function detectModeB(content) {
23
- if (!Array.isArray(content) || content.length === 0) return false;
24
- if (content.some((b) => b && b.type === "tool_use")) return false;
25
- const text = content.filter((b) => b && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
26
- if (text.length === 0) return false;
27
- const stripped = stripCode(text);
28
- if (stripped.length === 0) return false;
29
- const invokeAt = lastIndexOfRe(stripped, INVOKE_RE);
30
- const paramAt = lastIndexOfRe(stripped, PARAM_RE);
31
- if (invokeAt < 0 || paramAt < 0) return false;
32
- const lastTag = Math.max(invokeAt, paramAt);
33
- return stripped.length - lastTag <= TAIL_WINDOW;
26
+ if (!Array.isArray(content) || content.length === 0) return false
27
+ if (content.some((b) => b && b.type === 'tool_use')) return false
28
+ const text = content
29
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
30
+ .map((b) => b.text)
31
+ .join('\n')
32
+ if (text.length === 0) return false
33
+ const stripped = stripCode(text)
34
+ if (stripped.length === 0) return false
35
+ const invokeAt = lastIndexOfRe(stripped, INVOKE_RE)
36
+ const paramAt = lastIndexOfRe(stripped, PARAM_RE)
37
+ if (invokeAt < 0 || paramAt < 0) return false
38
+ const lastTag = Math.max(invokeAt, paramAt)
39
+ return stripped.length - lastTag <= TAIL_WINDOW
34
40
  }
35
41
 
36
42
  // src/checkpoint/stopHookMain.ts
37
- var MAX_RETRIES = 2;
43
+ var MAX_RETRIES = 2
38
44
  function stateRoot() {
39
- const override = process.env.HARNESSED_ROOT_OVERRIDE;
40
- return override !== void 0 && override !== "" ? override : join(homedir(), ".claude", "harnessed");
45
+ const override = process.env.HARNESSED_ROOT_OVERRIDE
46
+ return override !== void 0 && override !== '' ? override : join(homedir(), '.claude', 'harnessed')
41
47
  }
42
48
  function messageSig(content) {
43
- const text = content.filter((b) => b && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
44
- return createHash("sha256").update(text).digest("hex").slice(0, 16);
49
+ const text = content
50
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
51
+ .map((b) => b.text)
52
+ .join('\n')
53
+ return createHash('sha256').update(text).digest('hex').slice(0, 16)
45
54
  }
46
55
  function lastAssistantContent(transcriptPath) {
47
56
  try {
48
- if (!transcriptPath || !existsSync(transcriptPath)) return null;
49
- const buf = readFileSync(transcriptPath);
50
- const slice = buf.length > 262144 ? buf.subarray(buf.length - 262144) : buf;
51
- const lines = slice.toString("utf8").split("\n");
57
+ if (!transcriptPath || !existsSync(transcriptPath)) return null
58
+ const buf = readFileSync(transcriptPath)
59
+ const slice = buf.length > 262144 ? buf.subarray(buf.length - 262144) : buf
60
+ const lines = slice.toString('utf8').split('\n')
52
61
  for (let i = lines.length - 1; i >= 0; i--) {
53
- const line = (lines[i] ?? "").trim();
54
- if (!line) continue;
55
- let obj;
62
+ const line = (lines[i] ?? '').trim()
63
+ if (!line) continue
64
+ let obj
56
65
  try {
57
- obj = JSON.parse(line);
66
+ obj = JSON.parse(line)
58
67
  } catch {
59
- continue;
68
+ continue
60
69
  }
61
- if (obj && obj.type === "assistant") {
62
- const content = obj.message?.content ?? obj.content;
63
- return Array.isArray(content) ? content : null;
70
+ if (obj && obj.type === 'assistant') {
71
+ const content = obj.message?.content ?? obj.content
72
+ return Array.isArray(content) ? content : null
64
73
  }
65
74
  }
66
- } catch {
67
- }
68
- return null;
75
+ } catch {}
76
+ return null
69
77
  }
70
78
  function retryStore(sessionId) {
71
- const id = createHash("sha256").update(String(sessionId ?? "nosession")).digest("hex").slice(0, 16);
72
- return join(stateRoot(), "stop-hook-retries", `${id}.json`);
79
+ const id = createHash('sha256')
80
+ .update(String(sessionId ?? 'nosession'))
81
+ .digest('hex')
82
+ .slice(0, 16)
83
+ return join(stateRoot(), 'stop-hook-retries', `${id}.json`)
73
84
  }
74
85
  function readRetry(path) {
75
86
  try {
76
- if (!existsSync(path)) return { sig: "", count: 0 };
77
- const j = JSON.parse(readFileSync(path, "utf8"));
78
- return { sig: typeof j.sig === "string" ? j.sig : "", count: Number(j.count) || 0 };
87
+ if (!existsSync(path)) return { sig: '', count: 0 }
88
+ const j = JSON.parse(readFileSync(path, 'utf8'))
89
+ return { sig: typeof j.sig === 'string' ? j.sig : '', count: Number(j.count) || 0 }
79
90
  } catch {
80
- return { sig: "", count: 0 };
91
+ return { sig: '', count: 0 }
81
92
  }
82
93
  }
83
94
  function writeRetry(path, sig, count) {
84
95
  try {
85
- mkdirSync(join(path, ".."), { recursive: true });
86
- writeFileSync(path, JSON.stringify({ sig, count }), "utf8");
87
- return true;
96
+ mkdirSync(join(path, '..'), { recursive: true })
97
+ writeFileSync(path, JSON.stringify({ sig, count }), 'utf8')
98
+ return true
88
99
  } catch {
89
- return false;
100
+ return false
90
101
  }
91
102
  }
92
103
  function readStdin() {
93
104
  return new Promise((resolve) => {
94
- let data = "";
95
- if (process.stdin.isTTY) return resolve("");
96
- process.stdin.setEncoding("utf8");
97
- process.stdin.on("data", (c) => {
98
- data += c;
99
- });
100
- process.stdin.on("end", () => resolve(data));
101
- process.stdin.on("error", () => resolve(data));
102
- setTimeout(() => resolve(data), 2e3).unref?.();
103
- });
105
+ let data = ''
106
+ if (process.stdin.isTTY) return resolve('')
107
+ process.stdin.setEncoding('utf8')
108
+ process.stdin.on('data', (c) => {
109
+ data += c
110
+ })
111
+ process.stdin.on('end', () => resolve(data))
112
+ process.stdin.on('error', () => resolve(data))
113
+ setTimeout(() => resolve(data), 2e3).unref?.()
114
+ })
104
115
  }
105
116
  async function main() {
106
- const raw = await readStdin();
107
- let payload;
117
+ const raw = await readStdin()
118
+ let payload
108
119
  try {
109
- payload = JSON.parse(raw);
120
+ payload = JSON.parse(raw)
110
121
  } catch {
111
- return;
122
+ return
112
123
  }
113
- if (payload.stop_hook_active === true) return;
114
- const content = lastAssistantContent(payload.transcript_path);
115
- if (!content || !detectModeB(content)) return;
116
- const sig = messageSig(content);
117
- const store = retryStore(payload.session_id);
118
- const prev = readRetry(store);
119
- const count = prev.sig === sig ? prev.count : 0;
120
- if (count >= MAX_RETRIES) return;
121
- const saved = writeRetry(store, sig, count + 1);
122
- if (!saved) return;
124
+ if (payload.stop_hook_active === true) return
125
+ const content = lastAssistantContent(payload.transcript_path)
126
+ if (!content || !detectModeB(content)) return
127
+ const sig = messageSig(content)
128
+ const store = retryStore(payload.session_id)
129
+ const prev = readRetry(store)
130
+ const count = prev.sig === sig ? prev.count : 0
131
+ if (count >= MAX_RETRIES) return
132
+ const saved = writeRetry(store, sig, count + 1)
133
+ if (!saved) return
123
134
  process.stdout.write(
124
135
  `${JSON.stringify({
125
- decision: "block",
126
- reason: "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 \u2014 content unchanged."
136
+ decision: 'block',
137
+ reason:
138
+ '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 \u2014 content unchanged.',
127
139
  })}
128
- `
129
- );
140
+ `,
141
+ )
130
142
  }
131
- main().catch(() => {
132
- });
143
+ main().catch(() => {})
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.32.19",
41
+ version: "4.32.21",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -4218,31 +4218,32 @@ async function checkMcpAvailability() {
4218
4218
  }
4219
4219
  if (missing.length === 0) {
4220
4220
  return {
4221
- name: "MCP servers (tavily/exa/chrome-devtools)",
4221
+ name: CHECK_NAME,
4222
4222
  status: "pass",
4223
- message: `all 3 installed: ${installed.join(", ")}`
4223
+ message: `installed: ${installed.join(", ")}`
4224
4224
  };
4225
4225
  }
4226
4226
  if (installed.length === 0) {
4227
4227
  return {
4228
- name: "MCP servers (tavily/exa/chrome-devtools)",
4228
+ name: CHECK_NAME,
4229
4229
  status: "warn",
4230
- message: "none of 3 target MCP servers registered in ~/.claude.json",
4231
- fix: "run `harnessed setup` to install via Step B (manifests/tools/{tavily,exa,chrome-devtools}-mcp.yaml)"
4230
+ message: `not registered in ~/.claude.json: ${missing.join(", ")}`,
4231
+ fix: "run `harnessed setup` to install via Step B (manifests/tools/tavily-mcp.yaml)"
4232
4232
  };
4233
4233
  }
4234
4234
  return {
4235
- name: "MCP servers (tavily/exa/chrome-devtools)",
4235
+ name: CHECK_NAME,
4236
4236
  status: "warn",
4237
- message: `${installed.length}/3 installed: ${installed.join(", ")}; missing: ${missing.join(", ")}`,
4237
+ message: `${installed.length}/${TARGET_SERVERS.length} installed: ${installed.join(", ")}; missing: ${missing.join(", ")}`,
4238
4238
  fix: "run `harnessed setup` to install missing MCPs via Step B"
4239
4239
  };
4240
4240
  }
4241
- var TARGET_SERVERS;
4241
+ var TARGET_SERVERS, CHECK_NAME;
4242
4242
  var init_check_mcp_availability = __esm({
4243
4243
  "src/cli/lib/check-mcp-availability.ts"() {
4244
4244
  init_readClaudeConfig();
4245
- TARGET_SERVERS = ["tavily-mcp", "exa-mcp", "chrome-devtools-mcp"];
4245
+ TARGET_SERVERS = ["tavily-mcp"];
4246
+ CHECK_NAME = "MCP servers (tavily)";
4246
4247
  }
4247
4248
  });
4248
4249
 
@@ -8684,6 +8685,7 @@ __export(selfUpdateBinary_exports, {
8684
8685
  execDirWritable: () => execDirWritable,
8685
8686
  realSelfUpdateDeps: () => realSelfUpdateDeps,
8686
8687
  resolveLatestRelease: () => resolveLatestRelease,
8688
+ runBinaryRollback: () => runBinaryRollback,
8687
8689
  runBinarySelfUpdate: () => runBinarySelfUpdate
8688
8690
  });
8689
8691
  function assetNameFor(platform, arch) {
@@ -8758,7 +8760,7 @@ async function runBinarySelfUpdate(deps, opts) {
8758
8760
  const steps = [
8759
8761
  deps.sourceDir ? `copy ${sourceAsset} \u2192 ${tempPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${tempPath}`,
8760
8762
  `verify sha256 against ${deps.sourceDir ? sourceSha : shaUrl ?? `${asset}.sha256`}`,
8761
- "verify the ed25519 signature (.sha256.sig) against the embedded release public key",
8763
+ ...deps.sourceDir ? [] : ["verify the ed25519 signature (.sha256.sig) against the embedded release public key"],
8762
8764
  ...deps.platform === "win32" ? [] : ["chmod 755 the downloaded binary"],
8763
8765
  "smoke: spawn `--version` on the new binary",
8764
8766
  `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
@@ -8789,15 +8791,15 @@ async function runBinarySelfUpdate(deps, opts) {
8789
8791
  `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`
8790
8792
  );
8791
8793
  }
8792
- const sigText = deps.sourceDir ? await readFile(`${sourceSha ?? ""}.sig`, "utf8").catch(() => {
8793
- throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`);
8794
- }) : await deps.fetchShaText(`${shaUrl ?? ""}.sig`).catch(() => {
8795
- throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`);
8796
- });
8797
- if (!verifyShaSignature(shaText, sigText, deps.publicKeyPem)) {
8798
- throw new Error(
8799
- `ed25519 signature over .sha256 did not verify \u2014 the release assets may be tampered`
8800
- );
8794
+ if (!deps.sourceDir) {
8795
+ const sigText = await deps.fetchShaText(`${shaUrl ?? ""}.sig`).catch(() => {
8796
+ throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`);
8797
+ });
8798
+ if (!verifyShaSignature(shaText, sigText, deps.publicKeyPem)) {
8799
+ throw new Error(
8800
+ `ed25519 signature over .sha256 did not verify \u2014 the release assets may be tampered`
8801
+ );
8802
+ }
8801
8803
  }
8802
8804
  } catch (e) {
8803
8805
  await unlink2(tempPath).catch(() => {
@@ -8877,6 +8879,109 @@ async function runBinarySelfUpdate(deps, opts) {
8877
8879
  backupDir
8878
8880
  };
8879
8881
  }
8882
+ async function runBinaryRollback(deps, opts) {
8883
+ const rename5 = deps.fsOps?.rename ?? rename;
8884
+ const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
8885
+ const unlink2 = deps.fsOps?.unlink ?? unlink;
8886
+ if (normalized(deps.execPath).includes("/node_modules/")) {
8887
+ return { status: "refused", reason: "binary lives under node_modules (npm-managed)" };
8888
+ }
8889
+ const asset = assetNameFor(deps.platform, deps.arch);
8890
+ const backupsRoot = join(deps.stateRoot(), "bin-backup");
8891
+ let versions = [];
8892
+ try {
8893
+ const entries = await readdir(backupsRoot, { withFileTypes: true });
8894
+ for (const e of entries) {
8895
+ if (!e.isDirectory()) continue;
8896
+ const has = await access(join(backupsRoot, e.name, asset)).then(
8897
+ () => true,
8898
+ () => false
8899
+ );
8900
+ if (has) versions.push(e.name);
8901
+ }
8902
+ } catch {
8903
+ versions = [];
8904
+ }
8905
+ if (versions.length === 0) {
8906
+ return {
8907
+ status: "error",
8908
+ message: `no rollback candidates \u2014 ${backupsRoot} holds no banked ${asset}`
8909
+ };
8910
+ }
8911
+ let target;
8912
+ if (opts.version) {
8913
+ if (!versions.includes(opts.version)) {
8914
+ return {
8915
+ status: "error",
8916
+ message: `no backup for version ${opts.version} \u2014 available: ${versions.sort().join(", ")}`
8917
+ };
8918
+ }
8919
+ target = opts.version;
8920
+ } else {
8921
+ target = versions.reduce((a, b) => compareVersions(a, b) === "behind" ? b : a);
8922
+ }
8923
+ const backupBin = join(backupsRoot, target, asset);
8924
+ const execDir = dirname(deps.execPath);
8925
+ const execBase = basename(deps.execPath);
8926
+ const ext = deps.platform === "win32" ? ".exe" : "";
8927
+ const tempPath = join(execDir, `.harnessed-rollback-${deps.pid}${ext}`);
8928
+ const bakPath = join(execDir, `${execBase}.bak-${deps.currentVersion}`);
8929
+ try {
8930
+ await copyFile(backupBin, tempPath);
8931
+ if (deps.platform !== "win32") await chmod(tempPath, 493);
8932
+ const out = (await deps.smoke(tempPath)).trim();
8933
+ if (!/^\d+\.\d+\.\d+/.test(out)) {
8934
+ throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`);
8935
+ }
8936
+ } catch (e) {
8937
+ await unlink2(tempPath).catch(() => {
8938
+ });
8939
+ return {
8940
+ status: "error",
8941
+ message: `rollback staging failed: ${e.message} \u2014 original binary untouched`
8942
+ };
8943
+ }
8944
+ try {
8945
+ await rename5(deps.execPath, bakPath);
8946
+ } catch (e) {
8947
+ await unlink2(tempPath).catch(() => {
8948
+ });
8949
+ return {
8950
+ status: "error",
8951
+ message: `could not move the current binary aside: ${e.message} \u2014 original untouched`
8952
+ };
8953
+ }
8954
+ try {
8955
+ await rename5(tempPath, deps.execPath);
8956
+ } catch (e) {
8957
+ try {
8958
+ await rename5(bakPath, deps.execPath);
8959
+ return {
8960
+ status: "error",
8961
+ message: `swap failed (${e.message}) \u2014 restored the previous binary`
8962
+ };
8963
+ } catch (rb) {
8964
+ return {
8965
+ status: "error",
8966
+ message: `CRITICAL: swap failed AND restore failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`
8967
+ };
8968
+ }
8969
+ }
8970
+ let copied = false;
8971
+ try {
8972
+ const dir = join(backupsRoot, deps.currentVersion);
8973
+ await mkdir(dir, { recursive: true });
8974
+ await copyFile$1(bakPath, join(dir, execBase));
8975
+ copied = true;
8976
+ } catch (e) {
8977
+ deps.log(
8978
+ `warning: could not bank the replaced binary (${e.message}) \u2014 keeping ${bakPath}`
8979
+ );
8980
+ }
8981
+ if (copied) await unlink2(bakPath).catch(() => {
8982
+ });
8983
+ return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
8984
+ }
8880
8985
  async function fetchWithTimeout(url, timeoutMs) {
8881
8986
  const ac = new AbortController();
8882
8987
  const timer = setTimeout(() => ac.abort(), timeoutMs);
@@ -12569,11 +12674,11 @@ function buildOrchestratorBody(name, prompt) {
12569
12674
  `Drive this exact sequence (it is the state machine \u2014 follow the file, don't improvise from memory):`,
12570
12675
  ``,
12571
12676
  ...autoDiscussStep,
12572
- `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --skip-sub clarify\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
12677
+ `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --skip-sub discuss\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
12573
12678
  `3. Bash: \`harnessed checkpoint start ${name} --plan '<the verbatim gates JSON from step 2>'\` \u2192 seeds the sub-progress ledger in \`current-workflow.json\` (fired subs \u2192 \`pending\`, skipped subs \u2192 \`skipped\` + reason). This makes \`harnessed status --recover\` able to tell you where you are after compaction.`,
12574
12679
  `4. If \`parallelism.escalate_to_teams === true\`: this stage needs multiple subagents to coordinate (SendMessage / shared contract). Read \`~/.claude/rules/agent-teams.md\`, then \`TeamCreate\` \u2192 \`Agent(name, team_name, ...)\` per fired sub (prompt from \`harnessed prompt <sub>\`) \u2192 coordinate via SendMessage \u2192 \`SendMessage shutdown_request\` + \`TeamDelete\`. Still checkpoint each sub (\`complete\` / \`fail\`) as below.`,
12575
12680
  `5. Otherwise, for each fired sub in \`order\` (serial subs sequentially, parallel subs concurrently via parallel Task calls):`,
12576
- ` - **If the fired entry has \`is_master: true\`** (it is itself a stage master, e.g. \`/auto\` firing \`plan\`/\`task\`/\`verify\`): do NOT prompt+spawn it directly \u2014 that would yield a vague dispatcher. RECURSE: run that master's orchestration \u2014 \`harnessed gates <sub> --task "<spec>" --skip-sub clarify\` \u2192 \`harnessed checkpoint start <sub> --plan '<that JSON>'\` \u2192 repeat this whole loop for ITS fired subs. Only leaf subs (no \`is_master\`) reach the spawn loop below.`,
12681
+ ` - **If the fired entry has \`is_master: true\`** (it is itself a stage master, e.g. \`/auto\` firing \`plan\`/\`task\`/\`verify\`): do NOT prompt+spawn it directly \u2014 that would yield a vague dispatcher. RECURSE: run that master's orchestration \u2014 \`harnessed gates <sub> --task "<spec>" --skip-sub discuss\` \u2192 \`harnessed checkpoint start <sub> --plan '<that JSON>'\` \u2192 repeat this whole loop for ITS fired subs. Only leaf subs (no \`is_master\`) reach the spawn loop below.`,
12577
12682
  ` - **Else (leaf sub)** \u2014 spawn it, then checkpoint the outcome:`,
12578
12683
  ...leafSpawnLoop,
12579
12684
  `6. After all fired subs are \`done\` (or recorded \`failed\`), Bash \`harnessed status --recover\` to confirm the ledger position (what's done, what's still pending, any evidence drift). Report a per-sub fired/skipped/done/failed summary to the user. ${name === "auto" ? "Then run the `retro` stage to capture lessons." : ""}`,
@@ -14084,7 +14189,27 @@ init_package();
14084
14189
  init_assetsRoot();
14085
14190
  init_harnessedRoot();
14086
14191
  async function runCompiledFlow(opts) {
14087
- const { realSelfUpdateDeps: realSelfUpdateDeps2, runBinarySelfUpdate: runBinarySelfUpdate2 } = await Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports));
14192
+ const { realSelfUpdateDeps: realSelfUpdateDeps2, runBinaryRollback: runBinaryRollback2, runBinarySelfUpdate: runBinarySelfUpdate2 } = await Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports));
14193
+ if (opts.rollback !== void 0 && opts.rollback !== false) {
14194
+ const r2 = await runBinaryRollback2(realSelfUpdateDeps2(), {
14195
+ version: typeof opts.rollback === "string" ? opts.rollback : void 0
14196
+ });
14197
+ switch (r2.status) {
14198
+ case "refused":
14199
+ console.warn(`[harnessed] rollback refused: ${r2.reason} \u2014 use npm to change versions`);
14200
+ process.exit(1);
14201
+ return true;
14202
+ case "error":
14203
+ console.warn(`[harnessed] rollback failed: ${r2.message}`);
14204
+ process.exit(1);
14205
+ return true;
14206
+ case "rolled-back":
14207
+ console.log(`[harnessed] rolled back ${r2.from} \u2192 ${r2.to} (from ${r2.backupUsed}).`);
14208
+ console.log("[harnessed] restart Claude Code so the restored version takes effect.");
14209
+ process.exit(0);
14210
+ return true;
14211
+ }
14212
+ }
14088
14213
  const r = await runBinarySelfUpdate2(realSelfUpdateDeps2(), {
14089
14214
  dryRun: opts.dryRun === true,
14090
14215
  check: opts.check === true
@@ -14156,7 +14281,10 @@ function changelogTop() {
14156
14281
  }
14157
14282
  }
14158
14283
  function registerUpdate(program2) {
14159
- program2.command("update").description("Update harnessed to the latest version (and, with --upstreams, the base plugins)").option("--check", "report installed/latest version without installing").option("--upstreams", "re-run the base manifests to upgrade upstream plugins").option("--all", "alias for --upstreams (self + upstreams)").option("--migration-report", "read-only inventory of stale harnessed state (deletes nothing)").option("--dry-run", "preview what the update would do without writing anything").action(async (opts) => {
14284
+ program2.command("update").description("Update harnessed to the latest version (and, with --upstreams, the base plugins)").option("--check", "report installed/latest version without installing").option("--upstreams", "re-run the base manifests to upgrade upstream plugins").option("--all", "alias for --upstreams (self + upstreams)").option("--migration-report", "read-only inventory of stale harnessed state (deletes nothing)").option("--dry-run", "preview what the update would do without writing anything").option(
14285
+ "--rollback [version]",
14286
+ "compiled binary only \u2014 restore a previous version from bin-backup/ (default: newest banked)"
14287
+ ).action(async (opts) => {
14160
14288
  if (opts.migrationReport === true) {
14161
14289
  const { collectMigrationReport: collectMigrationReport2 } = await Promise.resolve().then(() => (init_migration_report(), migration_report_exports));
14162
14290
  const items = collectMigrationReport2(process.cwd(), getHarnessedRoot());
@@ -14172,6 +14300,11 @@ function registerUpdate(program2) {
14172
14300
  if (isCompiledRuntime2()) {
14173
14301
  const handled = await runCompiledFlow(opts);
14174
14302
  if (handled) return;
14303
+ } else if (opts.rollback !== void 0 && opts.rollback !== false) {
14304
+ console.warn(
14305
+ "[harnessed] --rollback is compiled-binary only \u2014 on npm use `npm i -g harnessed@<version>`"
14306
+ );
14307
+ process.exit(1);
14175
14308
  }
14176
14309
  const { compareVersions: compareVersions2, fetchLatestVersion: fetchLatestVersion2 } = await Promise.resolve().then(() => (init_version_check(), version_check_exports));
14177
14310
  const latest = await fetchLatestVersion2();