harnessed 5.0.7 → 5.0.8

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/dist/cli.mjs CHANGED
@@ -40,7 +40,7 @@ var init_package = __esm({
40
40
  "package.json"() {
41
41
  package_default = {
42
42
  name: "harnessed",
43
- version: "5.0.7",
43
+ version: "5.0.8",
44
44
  description: "AI coding harness package manager + composition orchestrator",
45
45
  type: "module",
46
46
  license: "Apache-2.0",
@@ -5370,11 +5370,11 @@ function isComplete(output) {
5370
5370
  if (succeeded) return true;
5371
5371
  return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
5372
5372
  }
5373
- async function ralphLoopWrap(spawn9, maxIter) {
5373
+ async function ralphLoopWrap(spawn10, maxIter) {
5374
5374
  let last = "";
5375
5375
  let sessionId;
5376
5376
  for (let i = 0; i < maxIter; i++) {
5377
- last = await spawn9(sessionId, (id) => {
5377
+ last = await spawn10(sessionId, (id) => {
5378
5378
  sessionId = id;
5379
5379
  });
5380
5380
  if (isComplete(last)) return last;
@@ -8991,6 +8991,62 @@ function harnessedHookIdentity(raw) {
8991
8991
  }
8992
8992
  return null;
8993
8993
  }
8994
+ function commandScriptToken(raw) {
8995
+ const match = raw.match(/^\s*(?:node|bun)\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?:\s|$)/);
8996
+ return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;
8997
+ }
8998
+ function commandTransportSubcommand(raw) {
8999
+ const match = raw.match(/^\s*(?:"([^"]+)"|'([^']+)'|(\S+))\s+(\S+)/);
9000
+ const sub = match?.[4];
9001
+ return sub && COMPILED_HOOK_IDENTITIES.includes(sub) ? sub : null;
9002
+ }
9003
+ function escapeRegExp(value) {
9004
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9005
+ }
9006
+ function isTrustedScriptFile(path, rel, assetsRoot) {
9007
+ const normalized2 = path.replace(/\\/g, "/");
9008
+ const relNormalized = rel.replace(/\\/g, "/");
9009
+ if (normalized2 === relNormalized) return true;
9010
+ const root = assetsRoot.replace(/\\/g, "/").replace(/\/+$/, "");
9011
+ const resolved = `${root}/${relNormalized}`;
9012
+ if (pathKey(normalized2) === pathKey(resolved)) return true;
9013
+ const versioned = new RegExp(`^(.+/assets/)[^/]+(/${escapeRegExp(relNormalized)})$`);
9014
+ const candidate = pathKey(normalized2).match(versioned);
9015
+ const captured = pathKey(resolved).match(versioned);
9016
+ return candidate !== null && captured !== null && candidate[1] === captured[1] && candidate[2] === captured[2];
9017
+ }
9018
+ function referenceScriptToken(hookCommand) {
9019
+ const script = commandScriptToken(hookCommand);
9020
+ if (script) {
9021
+ const normalized2 = script.replace(/\\/g, "/");
9022
+ return ABSOLUTE_RE2.test(normalized2) ? null : normalized2;
9023
+ }
9024
+ const sub = commandTransportSubcommand(hookCommand);
9025
+ return sub ? `bin/harnessed-${sub}.mjs` : null;
9026
+ }
9027
+ function isRegistrationOf(recorded, reference, assetsRoot) {
9028
+ const script = commandScriptToken(recorded);
9029
+ if (script) return isTrustedScriptFile(script, reference, assetsRoot);
9030
+ const sub = commandTransportSubcommand(recorded);
9031
+ if (!sub) return false;
9032
+ if (`bin/harnessed-${sub}.mjs` !== reference) return false;
9033
+ return harnessedHookIdentity(recorded) === sub;
9034
+ }
9035
+ function harnessedHookRegistrations(hooks, hookCommand, deps) {
9036
+ const reference = referenceScriptToken(hookCommand);
9037
+ if (!reference) return [];
9038
+ const assetsRoot = (deps?.assetsRoot ?? getAssetsRoot)();
9039
+ const out = [];
9040
+ for (const [event, arr] of Object.entries(hooks)) {
9041
+ if (!Array.isArray(arr)) continue;
9042
+ for (const entry of arr) {
9043
+ for (const command of entryCommands(entry)) {
9044
+ if (isRegistrationOf(command, reference, assetsRoot)) out.push({ event, command });
9045
+ }
9046
+ }
9047
+ }
9048
+ return out;
9049
+ }
8994
9050
  function harnessedHookScriptPath(raw) {
8995
9051
  const qMjs = raw.match(new RegExp(`"([^"]*harnessed-(?:${ID_ALT})\\.mjs)"`)) ?? raw.match(new RegExp(`'([^']*harnessed-(?:${ID_ALT})\\.mjs)'`));
8996
9052
  if (qMjs?.[1]) return qMjs[1];
@@ -9116,19 +9172,23 @@ function checkStaleHooks(deps) {
9116
9172
  return { name: NAME, status: "pass", message: "no orphaned harnessed hooks" };
9117
9173
  }
9118
9174
  const list = stale.map((s) => `${s.event} \u2192 ${s.path}`).join("; ");
9175
+ const versioned = stale.filter((s) => VERSIONED_ASSETS_RE.test(s.path.replace(/\\/g, "/")));
9176
+ const orphaned = stale.filter((s) => !VERSIONED_ASSETS_RE.test(s.path.replace(/\\/g, "/")));
9177
+ const fix = versioned.length > 0 ? `run 'harnessed setup' (or 'harnessed update') to re-register the stale harnessed hook(s) to the current version, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}${orphaned.length > 0 ? " \u2014 entries whose package is gone can also be removed with 'harnessed uninstall'" : ""}` : `run 'harnessed uninstall' to strip them, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}`;
9119
9178
  return {
9120
9179
  name: NAME,
9121
9180
  status: "warn",
9122
9181
  message: `${stale.length} harnessed hook(s) point at a missing/unresolvable script \u2014 Claude Code errors MODULE_NOT_FOUND every prompt (${list})`,
9123
- fix: `run 'harnessed uninstall' to strip them, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}`
9182
+ fix
9124
9183
  };
9125
9184
  }
9126
- var NAME;
9185
+ var NAME, VERSIONED_ASSETS_RE;
9127
9186
  var init_check_stale_hooks = __esm({
9128
9187
  "src/cli/lib/check-stale-hooks.ts"() {
9129
9188
  init_harnessedHookTeardown();
9130
9189
  init_platform();
9131
9190
  NAME = "stale hooks";
9191
+ VERSIONED_ASSETS_RE = /\/assets\/[^/]+\//;
9132
9192
  }
9133
9193
  });
9134
9194
 
@@ -11485,11 +11545,11 @@ function resolveSpawnHost() {
11485
11545
  async function dispatchSpawn(def, opts, deps = {}) {
11486
11546
  const host = (deps.hostId ?? resolveSpawnHost)();
11487
11547
  if (host === "codex") {
11488
- const spawn10 = deps.codexExecSpawn ?? (await Promise.resolve().then(() => (init_codexExecSpawn(), codexExecSpawn_exports))).codexExecSpawn;
11489
- return spawn10(def, { expertName: opts.expertName });
11548
+ const spawn11 = deps.codexExecSpawn ?? (await Promise.resolve().then(() => (init_codexExecSpawn(), codexExecSpawn_exports))).codexExecSpawn;
11549
+ return spawn11(def, { expertName: opts.expertName });
11490
11550
  }
11491
- const spawn9 = deps.sdkSpawn ?? (await Promise.resolve().then(() => (init_sdkSpawn(), sdkSpawn_exports))).sdkSpawn;
11492
- return spawn9(def, opts);
11551
+ const spawn10 = deps.sdkSpawn ?? (await Promise.resolve().then(() => (init_sdkSpawn(), sdkSpawn_exports))).sdkSpawn;
11552
+ return spawn10(def, opts);
11493
11553
  }
11494
11554
  var init_spawnDispatch = __esm({
11495
11555
  "src/workflow/lib/spawnDispatch.ts"() {
@@ -13990,6 +14050,7 @@ var gc_exports = {};
13990
14050
  __export(gc_exports, {
13991
14051
  gcCompiledArtifacts: () => gcCompiledArtifacts,
13992
14052
  gcLedger: () => gcLedger,
14053
+ referencedAssetVersions: () => referencedAssetVersions,
13993
14054
  registerGc: () => registerGc
13994
14055
  });
13995
14056
  function byVersion(a, b) {
@@ -13999,16 +14060,54 @@ function byVersion(a, b) {
13999
14060
  if (c === "current") return 0;
14000
14061
  return a.localeCompare(b);
14001
14062
  }
14063
+ async function referencedAssetVersions(settingsPath) {
14064
+ const versions = /* @__PURE__ */ new Set();
14065
+ if (!settingsPath) return versions;
14066
+ let raw;
14067
+ try {
14068
+ raw = await readFile(settingsPath, "utf8");
14069
+ } catch {
14070
+ return versions;
14071
+ }
14072
+ let parsed;
14073
+ try {
14074
+ parsed = JSON.parse(raw);
14075
+ } catch {
14076
+ return versions;
14077
+ }
14078
+ const hooks = parsed.hooks;
14079
+ if (!hooks || typeof hooks !== "object") return versions;
14080
+ for (const arr of Object.values(hooks)) {
14081
+ if (!Array.isArray(arr)) continue;
14082
+ for (const entry of arr) {
14083
+ for (const command of entryCommands(entry)) {
14084
+ const match = command.replace(/\\/g, "/").match(REFERENCED_ASSETS_RE);
14085
+ if (match?.[1]) versions.add(match[1]);
14086
+ }
14087
+ }
14088
+ }
14089
+ return versions;
14090
+ }
14091
+ function hostSettingsPath() {
14092
+ try {
14093
+ return getSettingsPath();
14094
+ } catch {
14095
+ return null;
14096
+ }
14097
+ }
14002
14098
  async function gcCompiledArtifacts(opts) {
14003
14099
  const removed = [];
14004
14100
  const kept = [];
14005
14101
  const keep = new Set(opts.keepVersions);
14102
+ const referenced = await referencedAssetVersions(
14103
+ opts.settingsPath === void 0 ? hostSettingsPath() : opts.settingsPath
14104
+ );
14006
14105
  try {
14007
14106
  const assetsDir = join(opts.stateRoot, "assets");
14008
14107
  for (const e of await readdir(assetsDir, { withFileTypes: true })) {
14009
14108
  if (!e.isDirectory()) continue;
14010
14109
  const p8 = join(assetsDir, e.name);
14011
- if (keep.has(e.name)) {
14110
+ if (keep.has(e.name) || referenced.has(e.name)) {
14012
14111
  kept.push(p8);
14013
14112
  continue;
14014
14113
  }
@@ -14164,14 +14263,17 @@ ${t("gc.invalid_duration.fix")}`
14164
14263
  }
14165
14264
  });
14166
14265
  }
14167
- var DURATION_RE;
14266
+ var REFERENCED_ASSETS_RE, DURATION_RE;
14168
14267
  var init_gc = __esm({
14169
14268
  "src/cli/gc.ts"() {
14170
14269
  init_package();
14171
14270
  init_pruneSlots();
14172
14271
  init_i18n();
14173
14272
  init_backup();
14273
+ init_hookEntry();
14274
+ init_platform();
14174
14275
  init_version_check();
14276
+ REFERENCED_ASSETS_RE = /\/assets\/([^/]+)\/(?:bin|scripts)\/[^\s"']*\.mjs/;
14175
14277
  DURATION_RE = /^(\d+)([dhmw])$/;
14176
14278
  }
14177
14279
  });
@@ -15086,13 +15188,15 @@ async function prepareHookSettings(ctx, settingsPath) {
15086
15188
  }
15087
15189
  };
15088
15190
  }
15089
- const ours = arr.filter(
15090
- (entry) => entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker)
15191
+ const firstParty = new Set(
15192
+ harnessedHookRegistrations({ [install.hook_event]: arr }, install.hook_command, {
15193
+ assetsRoot: cmdDeps.assetsRoot
15194
+ }).map((registration) => registration.command)
15091
15195
  );
15196
+ const isOurs = (entry) => entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker) || entryCommands(entry).some((command) => firstParty.has(command));
15197
+ const ours = arr.filter(isOurs);
15092
15198
  const desired = ours.length === 1 && isDesiredHookEntry(ours[0] ?? {}, install.hook_matcher, resolvedCmd);
15093
- const others = arr.filter(
15094
- (entry) => !entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker)
15095
- );
15199
+ const others = arr.filter((entry) => !isOurs(entry));
15096
15200
  settings.hooks[install.hook_event] = [
15097
15201
  ...others,
15098
15202
  desiredHookEntry(install.hook_matcher, resolvedCmd)
@@ -15120,6 +15224,7 @@ var init_ccHookAdd2 = __esm({
15120
15224
  init_confirm();
15121
15225
  init_diff();
15122
15226
  init_err();
15227
+ init_harnessedHookTeardown();
15123
15228
  init_hookEntry();
15124
15229
  init_preflight();
15125
15230
  init_state2();
@@ -17286,6 +17391,56 @@ var init_componentPlan = __esm({
17286
17391
  init_verificationEnv();
17287
17392
  }
17288
17393
  });
17394
+ function isLockContention(error) {
17395
+ return error?.code === "ELOCKED";
17396
+ }
17397
+ function backoffDelay(attempt) {
17398
+ return Math.min(
17399
+ INSTALL_OWNERSHIP_LOCK_RETRIES.minTimeout * 2 ** attempt,
17400
+ INSTALL_OWNERSHIP_LOCK_RETRIES.maxTimeout
17401
+ );
17402
+ }
17403
+ async function acquireOwnershipLock(root) {
17404
+ for (let attempt = 0; ; attempt += 1) {
17405
+ try {
17406
+ return await lockfile.lock(root, {
17407
+ lockfilePath: join(root, ".ownership.lock"),
17408
+ realpath: false,
17409
+ stale: 10 * 60 * 1e3,
17410
+ // One attempt only — the loop below owns the backoff.
17411
+ retries: 0
17412
+ });
17413
+ } catch (error) {
17414
+ if (!isLockContention(error) || attempt >= INSTALL_OWNERSHIP_LOCK_RETRIES.retries) {
17415
+ throw error;
17416
+ }
17417
+ await sleep(backoffDelay(attempt));
17418
+ }
17419
+ }
17420
+ }
17421
+ async function withInstallOwnershipLock(context, work) {
17422
+ const root = context.platform.stateRoot;
17423
+ await mkdir(root, { recursive: true });
17424
+ const release = await acquireOwnershipLock(root);
17425
+ try {
17426
+ return await work();
17427
+ } finally {
17428
+ await release();
17429
+ }
17430
+ }
17431
+ var INSTALL_OWNERSHIP_LOCK_RETRIES, sleep;
17432
+ var init_installOwnershipLock = __esm({
17433
+ "src/installers/lib/installOwnershipLock.ts"() {
17434
+ INSTALL_OWNERSHIP_LOCK_RETRIES = {
17435
+ retries: 30,
17436
+ minTimeout: 250,
17437
+ maxTimeout: 4e3
17438
+ };
17439
+ sleep = (ms) => new Promise((resolve40) => {
17440
+ setTimeout(resolve40, ms);
17441
+ });
17442
+ }
17443
+ });
17289
17444
  async function mcpReadinessFailure(ctx, allowAbsent = false) {
17290
17445
  if (ctx.hostContext?.hostId !== "codex") return null;
17291
17446
  const servers = await listCodexMcpServerMetadata(ctx.hostContext);
@@ -17741,25 +17896,6 @@ ${newEntry}
17741
17896
  };
17742
17897
  }
17743
17898
  });
17744
- async function withInstallOwnershipLock(context, work) {
17745
- const root = context.platform.stateRoot;
17746
- await mkdir(root, { recursive: true });
17747
- const release = await lockfile.lock(root, {
17748
- lockfilePath: join(root, ".ownership.lock"),
17749
- realpath: false,
17750
- stale: 10 * 60 * 1e3,
17751
- retries: { retries: 5, minTimeout: 25, maxTimeout: 250 }
17752
- });
17753
- try {
17754
- return await work();
17755
- } finally {
17756
- await release();
17757
- }
17758
- }
17759
- var init_installOwnershipLock = __esm({
17760
- "src/installers/lib/installOwnershipLock.ts"() {
17761
- }
17762
- });
17763
17899
  function isDirectChild(root, target) {
17764
17900
  const rel = relative(root, target);
17765
17901
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) && dirname(target) === root;
@@ -19119,16 +19255,17 @@ async function runInstall(manifest, opts, hostContext) {
19119
19255
  });
19120
19256
  } catch (e) {
19121
19257
  const code2 = e.code;
19258
+ const contention = isLockContention(e);
19122
19259
  return {
19123
19260
  ok: false,
19124
19261
  phase: "spawn",
19125
19262
  error: {
19126
19263
  file: manifest.metadata.name,
19127
19264
  path: "/spec/install",
19128
- message: `installer threw unexpectedly${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)}`,
19265
+ message: contention ? `install lock contention${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)} \u2014 retryable, re-run to install this component` : `installer threw unexpectedly${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)}`,
19129
19266
  line: null,
19130
19267
  column: null,
19131
- keyword: "installer-exception"
19268
+ keyword: contention ? "lock-contention" : "installer-exception"
19132
19269
  }
19133
19270
  };
19134
19271
  }
@@ -19141,6 +19278,7 @@ var init_installers = __esm({
19141
19278
  init_ccPluginMarketplace2();
19142
19279
  init_gitCloneWithSetup2();
19143
19280
  init_componentPlan();
19281
+ init_installOwnershipLock();
19144
19282
  init_mcpHttpAdd2();
19145
19283
  init_mcpStdioAdd2();
19146
19284
  init_npmCli2();
@@ -20793,18 +20931,18 @@ function preparePackageUpdate(manager, target, context = {}) {
20793
20931
  const cwd = context.cwd ?? process.cwd();
20794
20932
  const executable = npmPath(env, cwd);
20795
20933
  const plan = (args) => {
20796
- const spawn9 = process.platform === "win32" ? planWindowsSpawn("npm", args, executable) : { command: executable, args, verbatim: false };
20797
- const command = spawn9.verbatim ? resolveWindowsBin("cmd.exe", env) : spawn9.command;
20934
+ const spawn10 = process.platform === "win32" ? planWindowsSpawn("npm", args, executable) : { command: executable, args, verbatim: false };
20935
+ const command = spawn10.verbatim ? resolveWindowsBin("cmd.exe", env) : spawn10.command;
20798
20936
  if (!command || !isAbsolute(command)) throw new Error("Selected npm launcher is unresolved");
20799
20937
  return {
20800
20938
  command,
20801
- args: spawn9.args,
20939
+ args: spawn10.args,
20802
20940
  options: {
20803
20941
  cwd,
20804
20942
  env,
20805
20943
  shell: false,
20806
20944
  windowsHide: true,
20807
- windowsVerbatimArguments: spawn9.verbatim
20945
+ windowsVerbatimArguments: spawn10.verbatim
20808
20946
  }
20809
20947
  };
20810
20948
  };
@@ -20950,6 +21088,11 @@ function assetNameFor(platform, arch) {
20950
21088
  function normalized(p8) {
20951
21089
  return p8.replace(/\\/g, "/");
20952
21090
  }
21091
+ function downloadFailureMessage(error, version, url) {
21092
+ const detail = error instanceof Error ? error.message : String(error);
21093
+ const target = version ? ` for release v${version}` : "";
21094
+ return `download failed${target}${url ? ` (tried ${url})` : ""}: ${detail} \u2014 if the network blocks GitHub, use the npm channel (\`npm i -g harnessed@latest\`) or a local build via \`HARNESSED_UPDATE_SOURCE_DIR=<dir> harnessed update\``;
21095
+ }
20953
21096
  async function sha256File(p8) {
20954
21097
  const buf = await readFile(p8);
20955
21098
  return createHash("sha256").update(buf).digest("hex");
@@ -20974,6 +21117,10 @@ async function runBinarySelfUpdate(deps, opts) {
20974
21117
  let targetVersion = null;
20975
21118
  let assetUrl = null;
20976
21119
  let shaUrl = null;
21120
+ let sigUrl = null;
21121
+ let assetFallbackUrl;
21122
+ let shaFallbackUrl;
21123
+ let sigFallbackUrl;
20977
21124
  let sourceAsset = null;
20978
21125
  let sourceSha = null;
20979
21126
  if (deps.sourceDir) {
@@ -21003,7 +21150,7 @@ async function runBinarySelfUpdate(deps, opts) {
21003
21150
  if (rel === null) {
21004
21151
  return {
21005
21152
  status: "error",
21006
- message: "could not reach GitHub releases to resolve the latest binary \u2014 check the network or use the npm channel (`npm i -g harnessed@latest`)"
21153
+ message: "could not reach GitHub releases to resolve the latest binary \u2014 check the network or use the npm channel (`npm i -g harnessed@latest`), or point `HARNESSED_UPDATE_SOURCE_DIR=<dir>` at a local build and re-run `harnessed update`"
21007
21154
  };
21008
21155
  }
21009
21156
  if ("error" in rel) {
@@ -21015,6 +21162,10 @@ async function runBinarySelfUpdate(deps, opts) {
21015
21162
  targetVersion = rel.version;
21016
21163
  assetUrl = rel.assetUrl;
21017
21164
  shaUrl = rel.shaUrl;
21165
+ sigUrl = rel.sigUrl ?? null;
21166
+ assetFallbackUrl = rel.assetFallbackUrl;
21167
+ shaFallbackUrl = rel.shaFallbackUrl;
21168
+ sigFallbackUrl = rel.sigFallbackUrl;
21018
21169
  if (opts.check) {
21019
21170
  return {
21020
21171
  status: "checked",
@@ -21047,15 +21198,15 @@ async function runBinarySelfUpdate(deps, opts) {
21047
21198
  if (deps.sourceDir && sourceAsset) {
21048
21199
  await copyFile(sourceAsset, tempPath);
21049
21200
  } else if (assetUrl) {
21050
- await deps.downloadTo(assetUrl, tempPath);
21201
+ await deps.downloadTo(assetUrl, tempPath, assetFallbackUrl);
21051
21202
  }
21052
21203
  } catch (e) {
21053
21204
  await unlink2(tempPath).catch(() => {
21054
21205
  });
21055
- return { status: "error", message: `download failed: ${e.message}` };
21206
+ return { status: "error", message: downloadFailureMessage(e, targetVersion, assetUrl) };
21056
21207
  }
21057
21208
  try {
21058
- const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "");
21209
+ const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "", shaFallbackUrl);
21059
21210
  const expected = parseShaText(shaText);
21060
21211
  if (!expected) throw new Error(`malformed .sha256 content`);
21061
21212
  const actual = await sha256File(tempPath);
@@ -21065,7 +21216,7 @@ async function runBinarySelfUpdate(deps, opts) {
21065
21216
  );
21066
21217
  }
21067
21218
  if (!deps.sourceDir) {
21068
- const sigText = await deps.fetchShaText(`${shaUrl ?? ""}.sig`).catch(() => {
21219
+ const sigText = await deps.fetchShaText(sigUrl ?? `${shaUrl ?? ""}.sig`, sigFallbackUrl).catch(() => {
21069
21220
  throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`);
21070
21221
  });
21071
21222
  if (!verifyShaSignature(shaText, sigText, deps.publicKeyPem)) {
@@ -21269,57 +21420,113 @@ async function runBinaryRollback(deps, opts) {
21269
21420
  });
21270
21421
  return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
21271
21422
  }
21272
- async function fetchWithTimeout(url, timeoutMs) {
21423
+ async function fetchWithTimeout(url, timeoutMs, net = {}, headers = {}) {
21273
21424
  await ensureProxyDispatcher();
21425
+ const doFetch = net.fetchImpl ?? fetch;
21274
21426
  const ac = new AbortController();
21275
21427
  const timer = setTimeout(() => ac.abort(), timeoutMs);
21276
21428
  try {
21277
- return await fetch(url, {
21429
+ return await doFetch(url, {
21278
21430
  signal: ac.signal,
21279
- headers: { "user-agent": `harnessed/${package_default.version}` }
21431
+ headers: { "user-agent": `harnessed/${package_default.version}`, ...headers },
21432
+ // GitHub's asset endpoint answers 302 → release-assets.githubusercontent.com
21433
+ // only when the Accept header asks for the raw bytes; without it the API
21434
+ // returns asset METADATA JSON instead of the file.
21435
+ redirect: "follow"
21280
21436
  });
21281
21437
  } finally {
21282
21438
  clearTimeout(timer);
21283
21439
  }
21284
21440
  }
21285
- async function resolveLatestRelease(platform = process.platform, arch = process.arch) {
21441
+ function isTransientNetworkError(error) {
21442
+ const code2 = error?.code;
21443
+ if (code2 && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "EAI_AGAIN"].includes(code2)) {
21444
+ return true;
21445
+ }
21446
+ const message = error instanceof Error ? error.message : String(error);
21447
+ return /socket connection was closed|ECONNRESET|ETIMEDOUT|network|terminated|fetch failed/i.test(
21448
+ message
21449
+ );
21450
+ }
21451
+ async function fetchAsset(url, fallbackUrl, timeoutMs, net, label) {
21452
+ const sleep2 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
21453
+ const attempts = [];
21454
+ let lastError;
21455
+ for (const candidate of [url, fallbackUrl].filter((u) => !!u)) {
21456
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
21457
+ try {
21458
+ const res = await fetchWithTimeout(candidate, timeoutMs, net, {
21459
+ accept: "application/octet-stream"
21460
+ });
21461
+ if (res.ok) return res;
21462
+ lastError = new Error(`HTTP ${res.status} downloading ${candidate}`);
21463
+ if (res.status < 500) break;
21464
+ } catch (error) {
21465
+ lastError = error;
21466
+ if (!isTransientNetworkError(error)) break;
21467
+ }
21468
+ attempts.push(candidate);
21469
+ if (attempt < DOWNLOAD_ATTEMPTS) await sleep2(250 * attempt);
21470
+ }
21471
+ }
21472
+ throw new Error(
21473
+ `${label} download failed (${attempts.length} attempt(s) over ${[url, fallbackUrl].filter(Boolean).join(", ")}): ${lastError instanceof Error ? lastError.message : String(lastError)}`
21474
+ );
21475
+ }
21476
+ async function resolveLatestRelease(platform = process.platform, arch = process.arch, net = {}) {
21286
21477
  try {
21287
- const res = await fetchWithTimeout(RELEASES_LATEST_URL, 1e4);
21478
+ const res = await fetchWithTimeout(RELEASES_LATEST_URL, 1e4, net);
21288
21479
  if (!res.ok) return null;
21289
21480
  const body = await res.json();
21290
21481
  const version = (body.tag_name ?? "").replace(/^v/, "");
21291
21482
  if (!/^\d+\.\d+\.\d+/.test(version)) return null;
21292
21483
  const asset = assetNameFor(platform, arch);
21293
- const found = body.assets?.find((a) => a.name === asset);
21294
- const sha = body.assets?.find((a) => a.name === `${asset}.sha256`);
21295
- if (!found?.browser_download_url) {
21484
+ const pick = (name) => body.assets?.find((a) => a.name === name);
21485
+ const found = pick(asset);
21486
+ const sha = pick(`${asset}.sha256`);
21487
+ const sig = pick(`${asset}.sha256.sig`);
21488
+ if (!found?.browser_download_url && !found?.url) {
21296
21489
  return { error: `asset ${asset} not found on release v${version}` };
21297
21490
  }
21298
- if (!sha?.browser_download_url) {
21491
+ if (!sha?.browser_download_url && !sha?.url) {
21299
21492
  return { error: `asset ${asset}.sha256 not found on release v${version}` };
21300
21493
  }
21301
- return { version, assetUrl: found.browser_download_url, shaUrl: sha.browser_download_url };
21494
+ const pair = (a) => {
21495
+ const api = a?.url;
21496
+ const browser = a?.browser_download_url;
21497
+ return api && browser ? { primary: api, fallback: browser } : { primary: api ?? browser ?? "", fallback: void 0 };
21498
+ };
21499
+ const assetPair = pair(found);
21500
+ const shaPair = pair(sha);
21501
+ const sigPair = pair(sig);
21502
+ return {
21503
+ version,
21504
+ assetUrl: assetPair.primary,
21505
+ shaUrl: shaPair.primary,
21506
+ sigUrl: sigPair.primary || void 0,
21507
+ assetFallbackUrl: assetPair.fallback,
21508
+ shaFallbackUrl: shaPair.fallback,
21509
+ sigFallbackUrl: sigPair.fallback
21510
+ };
21302
21511
  } catch {
21303
21512
  return null;
21304
21513
  }
21305
21514
  }
21306
- function realSelfUpdateDeps(context) {
21515
+ function realSelfUpdateDeps(context, net = {}) {
21307
21516
  return {
21308
21517
  execPath: process.execPath,
21309
21518
  platform: process.platform,
21310
21519
  arch: process.arch,
21311
21520
  currentVersion: package_default.version,
21312
21521
  sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
21313
- resolveRelease: () => resolveLatestRelease(),
21314
- downloadTo: async (url, dest) => {
21315
- const res = await fetchWithTimeout(url, 12e4);
21316
- if (!res.ok) throw new Error(`HTTP ${res.status} downloading ${url}`);
21522
+ resolveRelease: () => resolveLatestRelease(process.platform, process.arch, net),
21523
+ downloadTo: async (url, dest, fallbackUrl) => {
21524
+ const res = await fetchAsset(url, fallbackUrl, 12e4, net, "binary");
21317
21525
  const buf = Buffer.from(await res.arrayBuffer());
21318
21526
  await writeFile(dest, buf);
21319
21527
  },
21320
- fetchShaText: async (url) => {
21321
- const res = await fetchWithTimeout(url, 3e4);
21322
- if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${url}`);
21528
+ fetchShaText: async (url, fallbackUrl) => {
21529
+ const res = await fetchAsset(url, fallbackUrl, 3e4, net, "checksum");
21323
21530
  return res.text();
21324
21531
  },
21325
21532
  smoke: async (bin) => {
@@ -21350,7 +21557,7 @@ async function execDirWritable(execPath) {
21350
21557
  return false;
21351
21558
  }
21352
21559
  }
21353
- var OWNER_REPO, RELEASES_LATEST_URL;
21560
+ var OWNER_REPO, RELEASES_LATEST_URL, DOWNLOAD_ATTEMPTS;
21354
21561
  var init_selfUpdateBinary = __esm({
21355
21562
  "src/cli/lib/selfUpdateBinary.ts"() {
21356
21563
  init_package();
@@ -21360,6 +21567,7 @@ var init_selfUpdateBinary = __esm({
21360
21567
  init_version_check();
21361
21568
  OWNER_REPO = "easyinplay/harnessed";
21362
21569
  RELEASES_LATEST_URL = `https://api.github.com/repos/${OWNER_REPO}/releases/latest`;
21570
+ DOWNLOAD_ATTEMPTS = 3;
21363
21571
  }
21364
21572
  });
21365
21573
 
@@ -22540,6 +22748,29 @@ async function reminderEnabled(context) {
22540
22748
  return error.code === "ENOENT";
22541
22749
  }
22542
22750
  }
22751
+ async function hasFirstPartyRegistration(context, hookEvent, hookCommand) {
22752
+ let raw;
22753
+ try {
22754
+ raw = await readFile(join(context.nativeHome, "settings.json"), "utf8");
22755
+ } catch {
22756
+ return false;
22757
+ }
22758
+ let parsed;
22759
+ try {
22760
+ parsed = JSON.parse(raw);
22761
+ } catch {
22762
+ return false;
22763
+ }
22764
+ const hooks = parsed.hooks;
22765
+ if (!hooks || typeof hooks !== "object") return false;
22766
+ try {
22767
+ return harnessedHookRegistrations(hooks, hookCommand).some(
22768
+ (registration) => registration.event === hookEvent
22769
+ );
22770
+ } catch {
22771
+ return false;
22772
+ }
22773
+ }
22543
22774
  async function refreshOwnedUpdate(context) {
22544
22775
  const assets = getAssetsRoot();
22545
22776
  const results = [];
@@ -22591,17 +22822,26 @@ async function refreshOwnedUpdate(context) {
22591
22822
  if (!validated.ok || validated.manifest.metadata.name !== name || validated.manifest.metadata.upstream?.repository !== "https://github.com/easyinplay/harnessed.git" || validated.manifest.spec.install.method !== "cc-hook-add")
22592
22823
  throw new Error(`Invalid first-party hook: ${name}`);
22593
22824
  const plan = resolveComponentPlan(validated.manifest, context, "install");
22594
- if (name !== "update-reminder" && !await isAlreadyInstalled(
22595
- {
22596
- manifest: structuredClone(plan.manifest),
22597
- opts,
22598
- level: "L3",
22599
- cwd: context.neutralSpawnCwd ?? context.userHome,
22600
- hostContext: context
22601
- },
22602
- { honorUpdateFlag: false }
22603
- ))
22604
- continue;
22825
+ if (name !== "update-reminder") {
22826
+ const installed2 = await isAlreadyInstalled(
22827
+ {
22828
+ manifest: structuredClone(plan.manifest),
22829
+ opts,
22830
+ level: "L3",
22831
+ cwd: context.neutralSpawnCwd ?? context.userHome,
22832
+ hostContext: context
22833
+ },
22834
+ { honorUpdateFlag: false }
22835
+ );
22836
+ if (!installed2) {
22837
+ const registered = await hasFirstPartyRegistration(
22838
+ context,
22839
+ validated.manifest.spec.install.hook_event,
22840
+ validated.manifest.spec.install.hook_command
22841
+ );
22842
+ if (!registered) continue;
22843
+ }
22844
+ }
22605
22845
  const result = await runInstall(validated.manifest, opts, context);
22606
22846
  results.push(
22607
22847
  createUpdateComponent({
@@ -22633,6 +22873,7 @@ var init_refreshOwnedUpdate = __esm({
22633
22873
  init_i18n();
22634
22874
  init_installers();
22635
22875
  init_componentPlan();
22876
+ init_harnessedHookTeardown();
22636
22877
  init_idempotent();
22637
22878
  init_validate();
22638
22879
  init_assetsRoot();
@@ -25324,6 +25565,7 @@ function mergeStepBResults(first, next) {
25324
25565
  first.failed = first.failed.filter((entry) => !replaced.has(failureName(entry))).concat(next.failed);
25325
25566
  first.skipped = first.skipped.filter((entry) => !replaced.has(entry.name)).concat(skipped);
25326
25567
  first.keptExisting = (first.keptExisting ?? []).filter((entry) => !replaced.has(entry.name)).concat(next.keptExisting ?? []);
25568
+ first.failureKeywords = { ...first.failureKeywords, ...next.failureKeywords };
25327
25569
  first.componentTypes = { ...first.componentTypes, ...next.componentTypes };
25328
25570
  first.elapsedMs += next.elapsedMs;
25329
25571
  }
@@ -25834,17 +26076,31 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
25834
26076
  console.error(` [optional] ${failure.name}: ${failure.reason}`);
25835
26077
  }
25836
26078
  }
25837
- const failedCount = b.failed.length + optionalFailed + setupFailures.length;
26079
+ const lockContentionFailures = b.failed.filter(
26080
+ (failure) => b.failureKeywords?.[failure.split(": ", 1)[0] ?? failure] === "lock-contention"
26081
+ );
26082
+ const fatalBaseFailures = b.failed.length - lockContentionFailures.length;
26083
+ const failedCount = fatalBaseFailures + optionalFailed + setupFailures.length;
25838
26084
  if (failedCount > 0) {
25839
26085
  console.error(
25840
26086
  `
25841
26087
  ${failedCount} component(s) failed \u2014 see the notes above; re-run \`harnessed setup\` to retry, or run \`harnessed doctor\` for environment diagnostics.`
25842
26088
  );
25843
26089
  }
26090
+ if (lockContentionFailures.length > 0) {
26091
+ console.warn(
26092
+ `
26093
+ ${lockContentionFailures.length} component(s) hit install lock contention \u2014 re-run \`harnessed setup\` to finish them.`
26094
+ );
26095
+ }
25844
26096
  const configured = b.installed.length + b.alreadyInstalled.length + (b.keptExisting?.length ?? 0);
25845
26097
  if (failedCount > 0) {
25846
26098
  console.error(
25847
- `setup incomplete - ${skillsInstalled} workflow(s) installed; ${configured} base component(s) configured; ${failedCount} component(s) failed (${b.failed.length} base, ${optionalFailed} optional, ${setupFailures.length} setup).`
26099
+ `setup incomplete - ${skillsInstalled} workflow(s) installed; ${configured} base component(s) configured; ${failedCount} component(s) failed (${fatalBaseFailures} base, ${optionalFailed} optional, ${setupFailures.length} setup).`
26100
+ );
26101
+ } else if (lockContentionFailures.length > 0) {
26102
+ console.warn(
26103
+ `setup finished with ${lockContentionFailures.length} component(s) awaiting a re-run \u2014 ${configured} base component(s) configured.`
25848
26104
  );
25849
26105
  } else {
25850
26106
  console.log(
@@ -27229,6 +27485,99 @@ var init_uninstall = __esm({
27229
27485
  }
27230
27486
  });
27231
27487
 
27488
+ // src/cli/lib/ownedRefreshFlag.ts
27489
+ var ownedRefreshFlag_exports = {};
27490
+ __export(ownedRefreshFlag_exports, {
27491
+ OWNED_REFRESH_FLAG: () => OWNED_REFRESH_FLAG
27492
+ });
27493
+ var OWNED_REFRESH_FLAG;
27494
+ var init_ownedRefreshFlag = __esm({
27495
+ "src/cli/lib/ownedRefreshFlag.ts"() {
27496
+ OWNED_REFRESH_FLAG = "--internal-owned-refresh";
27497
+ }
27498
+ });
27499
+
27500
+ // src/cli/lib/ownedRefresh.ts
27501
+ var ownedRefresh_exports = {};
27502
+ __export(ownedRefresh_exports, {
27503
+ refreshOwnedState: () => refreshOwnedState,
27504
+ runOwnedRefreshEntry: () => runOwnedRefreshEntry,
27505
+ spawnOwnedRefresh: () => spawnOwnedRefresh
27506
+ });
27507
+ async function refreshOwnedState(context) {
27508
+ const { refreshOwnedUpdate: refreshOwnedUpdate2 } = await Promise.resolve().then(() => (init_refreshOwnedUpdate(), refreshOwnedUpdate_exports));
27509
+ const components = await refreshOwnedUpdate2(context);
27510
+ return {
27511
+ ok: !components.some((component2) => component2.status === "failed"),
27512
+ updated: components.filter((component2) => component2.status === "updated").map((c) => c.id),
27513
+ failed: components.filter((component2) => component2.status === "failed").map((c) => c.id)
27514
+ };
27515
+ }
27516
+ async function runOwnedRefreshEntry() {
27517
+ const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
27518
+ const context = captureHostInstallContext3();
27519
+ const outcome = await refreshOwnedState(context);
27520
+ if (outcome.ok) {
27521
+ console.log(
27522
+ `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`
27523
+ );
27524
+ return 0;
27525
+ }
27526
+ console.warn(
27527
+ `[harnessed] owned state refresh incomplete (${outcome.failed.join(", ")}) \u2014 run 'harnessed setup' to finish`
27528
+ );
27529
+ return 1;
27530
+ }
27531
+ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
27532
+ const spawnImpl = deps.spawn ?? spawn;
27533
+ return new Promise((resolve40) => {
27534
+ let child;
27535
+ try {
27536
+ child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
27537
+ env: withHostInstallEnv(process.env, context),
27538
+ // stdout is dropped on purpose: the handover's result is the exit code,
27539
+ // and the parent owns the user-facing line. Keeping the child's stdout
27540
+ // empty also means an abrupt child exit cannot truncate a half-written
27541
+ // summary. stderr stays inherited so a failed refresh explains itself.
27542
+ stdio: ["ignore", "ignore", "inherit"],
27543
+ windowsHide: true,
27544
+ shell: false
27545
+ });
27546
+ } catch (error) {
27547
+ resolve40({
27548
+ ok: false,
27549
+ exitCode: null,
27550
+ error: error instanceof Error ? error.message : String(error)
27551
+ });
27552
+ return;
27553
+ }
27554
+ const timer = setTimeout(() => {
27555
+ try {
27556
+ killProcessTree(child);
27557
+ } catch {
27558
+ }
27559
+ resolve40({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
27560
+ }, timeoutMs);
27561
+ child.on("error", (error) => {
27562
+ clearTimeout(timer);
27563
+ resolve40({ ok: false, exitCode: null, error: error.message });
27564
+ });
27565
+ child.on("close", (code2) => {
27566
+ clearTimeout(timer);
27567
+ resolve40({ ok: code2 === 0, exitCode: code2 });
27568
+ });
27569
+ });
27570
+ }
27571
+ var OWNED_REFRESH_TIMEOUT_MS;
27572
+ var init_ownedRefresh = __esm({
27573
+ "src/cli/lib/ownedRefresh.ts"() {
27574
+ init_killTree();
27575
+ init_runClaudeArgs();
27576
+ init_ownedRefreshFlag();
27577
+ OWNED_REFRESH_TIMEOUT_MS = 18e4;
27578
+ }
27579
+ });
27580
+
27232
27581
  // src/cli/lib/migration-report.ts
27233
27582
  var migration_report_exports = {};
27234
27583
  __export(migration_report_exports, {
@@ -27344,6 +27693,17 @@ async function runCompiledFlow(opts, context) {
27344
27693
  console.log(
27345
27694
  ` note: ${r.bakPath} left in place (running image / rollback net) \u2014 gc sweeps it later`
27346
27695
  );
27696
+ const { spawnOwnedRefresh: spawnOwnedRefresh2 } = await Promise.resolve().then(() => (init_ownedRefresh(), ownedRefresh_exports));
27697
+ const refresh = await spawnOwnedRefresh2(process.execPath, context);
27698
+ if (refresh.ok) {
27699
+ console.log(
27700
+ `[harnessed] refreshed workflow skills + hooks for ${r.to} (owned state re-synced).`
27701
+ );
27702
+ } else {
27703
+ console.warn(
27704
+ `[harnessed] could not refresh skills/hooks after the update (${refresh.error ?? `exit ${refresh.exitCode}`}) \u2014 run 'harnessed setup' to finish.`
27705
+ );
27706
+ }
27347
27707
  try {
27348
27708
  const { gcCompiledArtifacts: gcCompiledArtifacts2 } = await Promise.resolve().then(() => (init_gc(), gc_exports));
27349
27709
  await gcCompiledArtifacts2({
@@ -27628,6 +27988,11 @@ if (!updateInvocation) {
27628
27988
  );
27629
27989
  });
27630
27990
  }
27991
+ var { OWNED_REFRESH_FLAG: OWNED_REFRESH_FLAG2 } = await Promise.resolve().then(() => (init_ownedRefreshFlag(), ownedRefreshFlag_exports));
27992
+ if (entryArgs.length === 1 && entryArgs[0] === OWNED_REFRESH_FLAG2) {
27993
+ const { runOwnedRefreshEntry: runOwnedRefreshEntry2 } = await Promise.resolve().then(() => (init_ownedRefresh(), ownedRefresh_exports));
27994
+ process.exit(await runOwnedRefreshEntry2());
27995
+ }
27631
27996
  var program = new Command();
27632
27997
  if (wantsUpdateEnvelope2(process.argv)) program.exitOverride();
27633
27998
  program.name("harnessed").description("AI coding harness package manager + composition orchestrator").version(package_default.version).option("--lang <code>", "output language: en | zh (auto-detect from $LANG / Intl if absent)");