harnessed 4.32.18 → 4.32.20

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
@@ -11,7 +11,7 @@ import { Ajv } from 'ajv';
11
11
  import * as ajvFormatsNs from 'ajv-formats';
12
12
  import { execFileSync, spawnSync, spawn, execSync, exec, execFile } from 'child_process';
13
13
  import { pathToFileURL, fileURLToPath } from 'url';
14
- import { createHash } from 'crypto';
14
+ import { createHash, verify, createPublicKey } from 'crypto';
15
15
  import { promisify } from 'util';
16
16
  import { Parser } from 'expr-eval';
17
17
  import * as p from '@clack/prompts';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.32.18",
41
+ version: "4.32.20",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -8657,6 +8657,24 @@ var init_auto_install = __esm({
8657
8657
  init_doctor_registry();
8658
8658
  }
8659
8659
  });
8660
+ function verifyShaSignature(shaText, sigBase64, publicKeyPem = HARNESSED_RELEASE_PUBKEY_PEM) {
8661
+ try {
8662
+ const sig = Buffer.from(sigBase64.trim(), "base64");
8663
+ if (sig.length === 0) return false;
8664
+ return verify(null, Buffer.from(shaText, "utf8"), createPublicKey(publicKeyPem), sig);
8665
+ } catch {
8666
+ return false;
8667
+ }
8668
+ }
8669
+ var HARNESSED_RELEASE_PUBKEY_PEM;
8670
+ var init_updateSignature = __esm({
8671
+ "src/cli/lib/updateSignature.ts"() {
8672
+ HARNESSED_RELEASE_PUBKEY_PEM = `-----BEGIN PUBLIC KEY-----
8673
+ MCowBQYDK2VwAyEAgCsfkZ+uCRNIBSHGfiOzp+TCSwQqOVJW1tsCW/beF4g=
8674
+ -----END PUBLIC KEY-----
8675
+ `;
8676
+ }
8677
+ });
8660
8678
 
8661
8679
  // src/cli/lib/selfUpdateBinary.ts
8662
8680
  var selfUpdateBinary_exports = {};
@@ -8666,6 +8684,7 @@ __export(selfUpdateBinary_exports, {
8666
8684
  execDirWritable: () => execDirWritable,
8667
8685
  realSelfUpdateDeps: () => realSelfUpdateDeps,
8668
8686
  resolveLatestRelease: () => resolveLatestRelease,
8687
+ runBinaryRollback: () => runBinaryRollback,
8669
8688
  runBinarySelfUpdate: () => runBinarySelfUpdate
8670
8689
  });
8671
8690
  function assetNameFor(platform, arch) {
@@ -8740,6 +8759,7 @@ async function runBinarySelfUpdate(deps, opts) {
8740
8759
  const steps = [
8741
8760
  deps.sourceDir ? `copy ${sourceAsset} \u2192 ${tempPath} (local source dir \u2014 rehearsal seam)` : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${tempPath}`,
8742
8761
  `verify sha256 against ${deps.sourceDir ? sourceSha : shaUrl ?? `${asset}.sha256`}`,
8762
+ ...deps.sourceDir ? [] : ["verify the ed25519 signature (.sha256.sig) against the embedded release public key"],
8743
8763
  ...deps.platform === "win32" ? [] : ["chmod 755 the downloaded binary"],
8744
8764
  "smoke: spawn `--version` on the new binary",
8745
8765
  `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
@@ -8770,6 +8790,16 @@ async function runBinarySelfUpdate(deps, opts) {
8770
8790
  `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`
8771
8791
  );
8772
8792
  }
8793
+ if (!deps.sourceDir) {
8794
+ const sigText = 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
+ );
8801
+ }
8802
+ }
8773
8803
  } catch (e) {
8774
8804
  await unlink2(tempPath).catch(() => {
8775
8805
  });
@@ -8848,6 +8878,109 @@ async function runBinarySelfUpdate(deps, opts) {
8848
8878
  backupDir
8849
8879
  };
8850
8880
  }
8881
+ async function runBinaryRollback(deps, opts) {
8882
+ const rename5 = deps.fsOps?.rename ?? rename;
8883
+ const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
8884
+ const unlink2 = deps.fsOps?.unlink ?? unlink;
8885
+ if (normalized(deps.execPath).includes("/node_modules/")) {
8886
+ return { status: "refused", reason: "binary lives under node_modules (npm-managed)" };
8887
+ }
8888
+ const asset = assetNameFor(deps.platform, deps.arch);
8889
+ const backupsRoot = join(deps.stateRoot(), "bin-backup");
8890
+ let versions = [];
8891
+ try {
8892
+ const entries = await readdir(backupsRoot, { withFileTypes: true });
8893
+ for (const e of entries) {
8894
+ if (!e.isDirectory()) continue;
8895
+ const has = await access(join(backupsRoot, e.name, asset)).then(
8896
+ () => true,
8897
+ () => false
8898
+ );
8899
+ if (has) versions.push(e.name);
8900
+ }
8901
+ } catch {
8902
+ versions = [];
8903
+ }
8904
+ if (versions.length === 0) {
8905
+ return {
8906
+ status: "error",
8907
+ message: `no rollback candidates \u2014 ${backupsRoot} holds no banked ${asset}`
8908
+ };
8909
+ }
8910
+ let target;
8911
+ if (opts.version) {
8912
+ if (!versions.includes(opts.version)) {
8913
+ return {
8914
+ status: "error",
8915
+ message: `no backup for version ${opts.version} \u2014 available: ${versions.sort().join(", ")}`
8916
+ };
8917
+ }
8918
+ target = opts.version;
8919
+ } else {
8920
+ target = versions.reduce((a, b) => compareVersions(a, b) === "behind" ? b : a);
8921
+ }
8922
+ const backupBin = join(backupsRoot, target, asset);
8923
+ const execDir = dirname(deps.execPath);
8924
+ const execBase = basename(deps.execPath);
8925
+ const ext = deps.platform === "win32" ? ".exe" : "";
8926
+ const tempPath = join(execDir, `.harnessed-rollback-${deps.pid}${ext}`);
8927
+ const bakPath = join(execDir, `${execBase}.bak-${deps.currentVersion}`);
8928
+ try {
8929
+ await copyFile(backupBin, tempPath);
8930
+ if (deps.platform !== "win32") await chmod(tempPath, 493);
8931
+ const out = (await deps.smoke(tempPath)).trim();
8932
+ if (!/^\d+\.\d+\.\d+/.test(out)) {
8933
+ throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`);
8934
+ }
8935
+ } catch (e) {
8936
+ await unlink2(tempPath).catch(() => {
8937
+ });
8938
+ return {
8939
+ status: "error",
8940
+ message: `rollback staging failed: ${e.message} \u2014 original binary untouched`
8941
+ };
8942
+ }
8943
+ try {
8944
+ await rename5(deps.execPath, bakPath);
8945
+ } catch (e) {
8946
+ await unlink2(tempPath).catch(() => {
8947
+ });
8948
+ return {
8949
+ status: "error",
8950
+ message: `could not move the current binary aside: ${e.message} \u2014 original untouched`
8951
+ };
8952
+ }
8953
+ try {
8954
+ await rename5(tempPath, deps.execPath);
8955
+ } catch (e) {
8956
+ try {
8957
+ await rename5(bakPath, deps.execPath);
8958
+ return {
8959
+ status: "error",
8960
+ message: `swap failed (${e.message}) \u2014 restored the previous binary`
8961
+ };
8962
+ } catch (rb) {
8963
+ return {
8964
+ status: "error",
8965
+ message: `CRITICAL: swap failed AND restore failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`
8966
+ };
8967
+ }
8968
+ }
8969
+ let copied = false;
8970
+ try {
8971
+ const dir = join(backupsRoot, deps.currentVersion);
8972
+ await mkdir(dir, { recursive: true });
8973
+ await copyFile$1(bakPath, join(dir, execBase));
8974
+ copied = true;
8975
+ } catch (e) {
8976
+ deps.log(
8977
+ `warning: could not bank the replaced binary (${e.message}) \u2014 keeping ${bakPath}`
8978
+ );
8979
+ }
8980
+ if (copied) await unlink2(bakPath).catch(() => {
8981
+ });
8982
+ return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
8983
+ }
8851
8984
  async function fetchWithTimeout(url, timeoutMs) {
8852
8985
  const ac = new AbortController();
8853
8986
  const timer = setTimeout(() => ac.abort(), timeoutMs);
@@ -8933,6 +9066,7 @@ var init_selfUpdateBinary = __esm({
8933
9066
  "src/cli/lib/selfUpdateBinary.ts"() {
8934
9067
  init_package();
8935
9068
  init_platform();
9069
+ init_updateSignature();
8936
9070
  init_version_check();
8937
9071
  OWNER_REPO = "easyinplay/harnessed";
8938
9072
  RELEASES_LATEST_URL = `https://api.github.com/repos/${OWNER_REPO}/releases/latest`;
@@ -12539,11 +12673,11 @@ function buildOrchestratorBody(name, prompt) {
12539
12673
  `Drive this exact sequence (it is the state machine \u2014 follow the file, don't improvise from memory):`,
12540
12674
  ``,
12541
12675
  ...autoDiscussStep,
12542
- `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)." : ""}`,
12676
+ `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)." : ""}`,
12543
12677
  `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.`,
12544
12678
  `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.`,
12545
12679
  `5. Otherwise, for each fired sub in \`order\` (serial subs sequentially, parallel subs concurrently via parallel Task calls):`,
12546
- ` - **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.`,
12680
+ ` - **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.`,
12547
12681
  ` - **Else (leaf sub)** \u2014 spawn it, then checkpoint the outcome:`,
12548
12682
  ...leafSpawnLoop,
12549
12683
  `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." : ""}`,
@@ -14054,7 +14188,27 @@ init_package();
14054
14188
  init_assetsRoot();
14055
14189
  init_harnessedRoot();
14056
14190
  async function runCompiledFlow(opts) {
14057
- const { realSelfUpdateDeps: realSelfUpdateDeps2, runBinarySelfUpdate: runBinarySelfUpdate2 } = await Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports));
14191
+ const { realSelfUpdateDeps: realSelfUpdateDeps2, runBinaryRollback: runBinaryRollback2, runBinarySelfUpdate: runBinarySelfUpdate2 } = await Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports));
14192
+ if (opts.rollback !== void 0 && opts.rollback !== false) {
14193
+ const r2 = await runBinaryRollback2(realSelfUpdateDeps2(), {
14194
+ version: typeof opts.rollback === "string" ? opts.rollback : void 0
14195
+ });
14196
+ switch (r2.status) {
14197
+ case "refused":
14198
+ console.warn(`[harnessed] rollback refused: ${r2.reason} \u2014 use npm to change versions`);
14199
+ process.exit(1);
14200
+ return true;
14201
+ case "error":
14202
+ console.warn(`[harnessed] rollback failed: ${r2.message}`);
14203
+ process.exit(1);
14204
+ return true;
14205
+ case "rolled-back":
14206
+ console.log(`[harnessed] rolled back ${r2.from} \u2192 ${r2.to} (from ${r2.backupUsed}).`);
14207
+ console.log("[harnessed] restart Claude Code so the restored version takes effect.");
14208
+ process.exit(0);
14209
+ return true;
14210
+ }
14211
+ }
14058
14212
  const r = await runBinarySelfUpdate2(realSelfUpdateDeps2(), {
14059
14213
  dryRun: opts.dryRun === true,
14060
14214
  check: opts.check === true
@@ -14126,7 +14280,10 @@ function changelogTop() {
14126
14280
  }
14127
14281
  }
14128
14282
  function registerUpdate(program2) {
14129
- 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) => {
14283
+ 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(
14284
+ "--rollback [version]",
14285
+ "compiled binary only \u2014 restore a previous version from bin-backup/ (default: newest banked)"
14286
+ ).action(async (opts) => {
14130
14287
  if (opts.migrationReport === true) {
14131
14288
  const { collectMigrationReport: collectMigrationReport2 } = await Promise.resolve().then(() => (init_migration_report(), migration_report_exports));
14132
14289
  const items = collectMigrationReport2(process.cwd(), getHarnessedRoot());
@@ -14142,6 +14299,11 @@ function registerUpdate(program2) {
14142
14299
  if (isCompiledRuntime2()) {
14143
14300
  const handled = await runCompiledFlow(opts);
14144
14301
  if (handled) return;
14302
+ } else if (opts.rollback !== void 0 && opts.rollback !== false) {
14303
+ console.warn(
14304
+ "[harnessed] --rollback is compiled-binary only \u2014 on npm use `npm i -g harnessed@<version>`"
14305
+ );
14306
+ process.exit(1);
14145
14307
  }
14146
14308
  const { compareVersions: compareVersions2, fetchLatestVersion: fetchLatestVersion2 } = await Promise.resolve().then(() => (init_version_check(), version_check_exports));
14147
14309
  const latest = await fetchLatestVersion2();