@hasna/hooks 0.12.23 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/index.js CHANGED
@@ -1371,6 +1371,8 @@ var init_manifest = __esm(() => {
1371
1371
  script_kind: z.enum(["inline", "file"]).optional(),
1372
1372
  args: z.array(z.string()).optional(),
1373
1373
  nativeTargetDispatch: z.boolean().optional(),
1374
+ requires_final_message: z.boolean().optional(),
1375
+ requires_block: z.boolean().optional(),
1374
1376
  timeout_ms: z.number().int().positive().optional(),
1375
1377
  env: z.record(z.string(), z.string()).optional()
1376
1378
  });
@@ -1452,6 +1454,8 @@ function resolveHookMeta(name) {
1452
1454
  matcher: "",
1453
1455
  tags: ["custom"],
1454
1456
  nativeTargetDispatch: manifest.nativeTargetDispatch,
1457
+ requiresFinalMessage: manifest.requires_final_message,
1458
+ requiresBlock: manifest.requires_block,
1455
1459
  timeoutSeconds: manifest.timeout_ms === undefined ? undefined : Math.ceil(manifest.timeout_ms / 1000)
1456
1460
  };
1457
1461
  }
@@ -1966,6 +1970,305 @@ function mementosRunEnvironment(env, value) {
1966
1970
  };
1967
1971
  }
1968
1972
 
1973
+ // src/lib/targets.ts
1974
+ import { homedir as homedir5 } from "os";
1975
+ import { dirname as dirname6, join as join8, resolve as resolve4 } from "path";
1976
+ function isTargetName(value) {
1977
+ return typeof value === "string" && TARGET_NAMES.includes(value);
1978
+ }
1979
+ function isInstallTargetName(value) {
1980
+ return typeof value === "string" && INSTALL_TARGET_NAMES.includes(value);
1981
+ }
1982
+ function getTargetCapabilities(target, options = {}) {
1983
+ if (!isTargetName(target))
1984
+ return;
1985
+ const definition = DEFINITIONS[target];
1986
+ const resolved = {
1987
+ scope: options.scope ?? "global",
1988
+ home: options.home ?? homedir5(),
1989
+ cwd: options.cwd ?? process.cwd(),
1990
+ env: options.env ?? process.env,
1991
+ hook: options.hook
1992
+ };
1993
+ return {
1994
+ install: definition.install,
1995
+ run: definition.run,
1996
+ stopEvent: definition.stopEvent,
1997
+ canBlock: definition.canBlock,
1998
+ deliversFinalMessage: definition.deliversFinalMessage,
1999
+ configPath: definition.path(resolved)
2000
+ };
2001
+ }
2002
+ function musePluginRoot(options = {}) {
2003
+ return dirname6(getTargetCapabilities("muse", { ...options, hook: "bundle" }).configPath);
2004
+ }
2005
+ function targetInstallNote(target) {
2006
+ return isTargetName(target) ? DEFINITIONS[target].installNote : undefined;
2007
+ }
2008
+ function runTargetHelp() {
2009
+ return TARGET_NAMES.join(", ");
2010
+ }
2011
+ function runTargetRefusal(target) {
2012
+ const capabilities = getTargetCapabilities(target);
2013
+ if (!capabilities) {
2014
+ return `Refused: '${target}' is not a run target. Supported run targets: ${runTargetHelp()}.`;
2015
+ }
2016
+ if (!capabilities.run) {
2017
+ return `Refused: '${target}' has no hook payload shape (run: false). Supported run targets: ${runTargetHelp()}.`;
2018
+ }
2019
+ return;
2020
+ }
2021
+ function blockingInstallTargets() {
2022
+ return INSTALL_TARGET_NAMES.filter((name) => DEFINITIONS[name].canBlock);
2023
+ }
2024
+ function installCapabilityRefusal(hook, target, requirement, options = {}) {
2025
+ const definition = isTargetName(target) ? DEFINITIONS[target] : undefined;
2026
+ if (!definition) {
2027
+ return `Refused: Unknown target '${target}'. Known targets: ${runTargetHelp()}.`;
2028
+ }
2029
+ const capabilities = getTargetCapabilities(target, options);
2030
+ if (requirement.requiresBlock && !capabilities.canBlock) {
2031
+ const others = [];
2032
+ if (!capabilities.install)
2033
+ others.push("no generic install path (install: false)");
2034
+ if (requirement.requiresFinalMessage && !capabilities.deliversFinalMessage)
2035
+ others.push("no final assistant message (deliversFinalMessage: false)");
2036
+ if (requirement.events.includes("Stop") && capabilities.stopEvent === null)
2037
+ others.push("no turn-end event (stopEvent: null)");
2038
+ const also = others.length === 0 ? "" : ` It also has ${others.join(" and ")}.`;
2039
+ return `Refused: '${hook}' declares requires_block, and target '${target}' cannot hold the turn (canBlock: false) \u2014 ${definition.blockNote ?? "a block verdict is ignored there"}.${also} ` + `Unblock it by installing on a target that can block (${blockingInstallTargets().join(", ")}), or by clearing requires_block in the hook's manifest.`;
2040
+ }
2041
+ if (requirement.requiresFinalMessage && !capabilities.deliversFinalMessage) {
2042
+ const others = [];
2043
+ if (!capabilities.install)
2044
+ others.push("no generic install path (install: false)");
2045
+ if (requirement.requiresBlock && !capabilities.canBlock)
2046
+ others.push("no turn-holding verdict (canBlock: false)");
2047
+ if (requirement.events.includes("Stop") && capabilities.stopEvent === null)
2048
+ others.push("no turn-end event (stopEvent: null)");
2049
+ const also = others.length === 0 ? "" : ` It also has ${others.join(" and ")}.`;
2050
+ return `Refused: '${hook}' declares requires_final_message, and target '${target}' does not deliver the assistant's final message (deliversFinalMessage: false) \u2014 ${definition.finalMessageNote ?? "its payload carries no assistant text"}.${also} ` + `Unblock it by installing on a target that delivers the message (${INSTALL_TARGET_NAMES.filter((name) => DEFINITIONS[name].deliversFinalMessage).join(", ")}), or by clearing requires_final_message in the hook's manifest.`;
2051
+ }
2052
+ if (!capabilities.install) {
2053
+ return `Refused: Hooks has no generic install path for target '${target}' (install: false). ${definition.stopEventSubstitute ?? `Supported install targets: ${INSTALL_TARGET_NAMES.join(", ")}.`}`;
2054
+ }
2055
+ if (requirement.events.includes("Stop") && capabilities.stopEvent === null) {
2056
+ return `Refused: '${hook}' runs on the Stop event, and target '${target}' has no turn-end event (stopEvent: null), so nothing would ever run it. ${definition.stopEventSubstitute ?? ""}`.trim();
2057
+ }
2058
+ return;
2059
+ }
2060
+ function shapeTargetInput(target, stdin) {
2061
+ if (target !== "muse" || !stdin)
2062
+ return stdin;
2063
+ try {
2064
+ const payload = JSON.parse(stdin);
2065
+ const message = payload?.last_assistant_message;
2066
+ if (typeof message !== "string")
2067
+ return stdin;
2068
+ try {
2069
+ const parsed = JSON.parse(message);
2070
+ if (parsed !== null && (typeof parsed === "object" || typeof parsed === "string" || typeof parsed === "number")) {
2071
+ return JSON.stringify({ ...payload, last_assistant_message: typeof parsed === "string" ? parsed : JSON.stringify(parsed) });
2072
+ }
2073
+ } catch {}
2074
+ return stdin;
2075
+ } catch {
2076
+ return stdin;
2077
+ }
2078
+ }
2079
+ function shapeTargetOutput(target, output) {
2080
+ if (target !== "kimi")
2081
+ return output;
2082
+ let verdict;
2083
+ try {
2084
+ const parsed = JSON.parse(output.stdout);
2085
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2086
+ return output;
2087
+ verdict = parsed;
2088
+ } catch {
2089
+ return output;
2090
+ }
2091
+ if (verdict.decision !== "block")
2092
+ return output;
2093
+ const reason = typeof verdict.reason === "string" && verdict.reason.trim() ? verdict.reason.trim() : "Blocked by hook.";
2094
+ return { stdout: "", stderr: reason.endsWith(`
2095
+ `) ? reason : `${reason}
2096
+ `, exitCode: 2 };
2097
+ }
2098
+ var TARGET_NAMES, INSTALL_TARGET_NAMES, settingsJson = (dir) => (o) => o.scope === "project" ? join8(resolve4(o.cwd), dir, "settings.json") : join8(o.home, dir, "settings.json"), DEFINITIONS;
2099
+ var init_targets = __esm(() => {
2100
+ TARGET_NAMES = [
2101
+ "claude",
2102
+ "codex",
2103
+ "gemini",
2104
+ "codewith",
2105
+ "qwen",
2106
+ "muse",
2107
+ "kimi",
2108
+ "pi",
2109
+ "cursor",
2110
+ "opencode",
2111
+ "sumi"
2112
+ ];
2113
+ INSTALL_TARGET_NAMES = [
2114
+ "claude",
2115
+ "codex",
2116
+ "gemini",
2117
+ "codewith",
2118
+ "qwen",
2119
+ "muse",
2120
+ "kimi",
2121
+ "pi",
2122
+ "cursor"
2123
+ ];
2124
+ DEFINITIONS = {
2125
+ claude: {
2126
+ install: true,
2127
+ run: true,
2128
+ stopEvent: "Stop",
2129
+ canBlock: true,
2130
+ deliversFinalMessage: true,
2131
+ finalMessageField: "last_assistant_message",
2132
+ path: settingsJson(".claude")
2133
+ },
2134
+ codex: {
2135
+ install: true,
2136
+ run: true,
2137
+ stopEvent: "Stop",
2138
+ canBlock: true,
2139
+ deliversFinalMessage: true,
2140
+ finalMessageField: "last_assistant_message",
2141
+ path: (o) => o.scope === "project" ? join8(resolve4(o.cwd), ".codex", "hooks.json") : join8(o.home, ".codex", "hooks.json")
2142
+ },
2143
+ gemini: {
2144
+ install: true,
2145
+ run: true,
2146
+ stopEvent: "AfterAgent",
2147
+ canBlock: true,
2148
+ deliversFinalMessage: true,
2149
+ finalMessageField: "prompt_response",
2150
+ path: settingsJson(".gemini")
2151
+ },
2152
+ codewith: {
2153
+ install: true,
2154
+ run: true,
2155
+ stopEvent: "Stop",
2156
+ canBlock: true,
2157
+ deliversFinalMessage: true,
2158
+ finalMessageField: "last_assistant_message",
2159
+ path: (o) => o.scope === "project" ? join8(resolve4(o.cwd), ".codewith", "config.toml") : join8(o.home, ".codewith", "config.toml")
2160
+ },
2161
+ qwen: {
2162
+ install: true,
2163
+ run: true,
2164
+ stopEvent: "Stop",
2165
+ canBlock: true,
2166
+ deliversFinalMessage: true,
2167
+ finalMessageField: "last_assistant_message",
2168
+ path: settingsJson(".qwen")
2169
+ },
2170
+ muse: {
2171
+ install: true,
2172
+ run: true,
2173
+ stopEvent: "Stop",
2174
+ canBlock: true,
2175
+ deliversFinalMessage: true,
2176
+ finalMessageField: "last_assistant_message",
2177
+ installNote: "Muse receives the final message as a quoted JSON string; `hooks run --target muse` parses it once before the hook sees it.",
2178
+ path: (o) => join8(o.home, ".hasna", "hooks", "muse-plugins", o.hook ?? "")
2179
+ },
2180
+ kimi: {
2181
+ install: true,
2182
+ run: true,
2183
+ stopEvent: "Stop",
2184
+ canBlock: true,
2185
+ deliversFinalMessage: false,
2186
+ finalMessageNote: "Kimi's Stop payload carries only hook_event_name, session_id, cwd, client_type, session_title and stop_hook_active",
2187
+ path: (o) => join8(o.home, ".kimi-code", "config.toml")
2188
+ },
2189
+ pi: {
2190
+ install: true,
2191
+ run: true,
2192
+ stopEvent: "turn_end",
2193
+ canBlock: true,
2194
+ deliversFinalMessage: false,
2195
+ finalMessageNote: "the pi-hooks bridge sends only hook_event_name, session_id, cwd and stop_hook_active (transcript_path is declared but never populated)",
2196
+ installNote: "Pi runs hooks through the hasna-pi-hooks bridge: the config points at a Hooks profile, so registration is not by itself proof that a turn was held.",
2197
+ path: (o) => join8(o.home, ".pi", "agent", "state", "hasna-pi-hooks.config.json")
2198
+ },
2199
+ cursor: {
2200
+ install: true,
2201
+ run: true,
2202
+ stopEvent: "stop",
2203
+ canBlock: false,
2204
+ deliversFinalMessage: false,
2205
+ finalMessageNote: "Cursor's stop hook carries no assistant text",
2206
+ blockNote: "a block verdict is ignored, and only followup_message continues a turn (loop_limit 5)",
2207
+ installNote: "Cursor's stop hook cannot block the turn: a block verdict is ignored, and only followup_message continues a turn (loop_limit 5). The registration alone does not hold anything.",
2208
+ path: (o) => o.scope === "project" ? join8(resolve4(o.cwd), ".cursor", "hooks.json") : join8(o.home, ".cursor", "hooks.json")
2209
+ },
2210
+ opencode: {
2211
+ install: false,
2212
+ run: true,
2213
+ stopEvent: null,
2214
+ canBlock: false,
2215
+ deliversFinalMessage: false,
2216
+ blockNote: "opencode has no turn-end event to hold: session.prompt schedules a new agent-loop run instead of continuing the current turn",
2217
+ stopEventSubstitute: "opencode has only the session.idle bus event, which is observe-only and cannot hold the turn; `hooks install stop-review --target opencode` registers the managed observe-and-re-prompt plugin",
2218
+ path: (o) => {
2219
+ const xdg = o.env.XDG_CONFIG_HOME;
2220
+ const base = xdg && xdg.startsWith("/") ? xdg : join8(o.home, ".config");
2221
+ return join8(resolve4(base), "opencode", "opencode.json");
2222
+ }
2223
+ },
2224
+ sumi: {
2225
+ install: false,
2226
+ run: true,
2227
+ stopEvent: "Stop",
2228
+ canBlock: true,
2229
+ deliversFinalMessage: true,
2230
+ finalMessageField: "last_assistant_message",
2231
+ stopEventSubstitute: "Sumi stop review is registered through the managed path: `hooks install stop-review --target sumi`",
2232
+ path: (o) => join8(o.home, ".sumi", "plugins")
2233
+ }
2234
+ };
2235
+ });
2236
+
2237
+ // src/lib/native-target.ts
2238
+ var exports_native_target = {};
2239
+ __export(exports_native_target, {
2240
+ nativeTargetCommandSuffix: () => nativeTargetCommandSuffix,
2241
+ nativeTargetArgs: () => nativeTargetArgs,
2242
+ isHookRunTarget: () => isHookRunTarget,
2243
+ HOOK_RUN_TARGETS: () => HOOK_RUN_TARGETS
2244
+ });
2245
+ function isHookRunTarget(value) {
2246
+ return typeof value === "string" && HOOK_RUN_TARGETS.includes(value);
2247
+ }
2248
+ function nativeTargetArgs(dispatch, target, args = []) {
2249
+ if (target !== undefined && !isHookRunTarget(target))
2250
+ throw new Error(`Invalid --target; expected one of ${HOOK_RUN_TARGETS.join(", ")}`);
2251
+ if (!dispatch)
2252
+ return [...args];
2253
+ if (!isHookRunTarget(target))
2254
+ throw new Error("This hook requires --target from its native registration");
2255
+ if (args.some((arg) => arg === "--harness" || arg.startsWith("--harness=")))
2256
+ throw new Error("nativeTargetDispatch owns the --harness argument; remove it from manifest args");
2257
+ return [...args, "--harness", target];
2258
+ }
2259
+ function nativeTargetCommandSuffix(dispatch, target) {
2260
+ if (!dispatch)
2261
+ return "";
2262
+ if (!isHookRunTarget(target))
2263
+ throw new Error("Native registration requires a supported target");
2264
+ return ` --target ${target}`;
2265
+ }
2266
+ var HOOK_RUN_TARGETS;
2267
+ var init_native_target = __esm(() => {
2268
+ init_targets();
2269
+ HOOK_RUN_TARGETS = TARGET_NAMES;
2270
+ });
2271
+
1969
2272
  // src/lib/registration.ts
1970
2273
  function registrationName(command) {
1971
2274
  if (typeof command !== "string")
@@ -2082,7 +2385,8 @@ var init_registration = __esm(() => {
2082
2385
  init_native_safety();
2083
2386
  init_native_readiness_command();
2084
2387
  init_resolve();
2085
- REGISTRATION_COMMAND_RE = /^(?:hooks run ([\w-]+)(?:\s+--profile\s+[\w-]+)?(?:\s+--target\s+(?:claude|codex|gemini|codewith|sumi|opencode))?|hook-([\w-]+))$/;
2388
+ init_native_target();
2389
+ REGISTRATION_COMMAND_RE = new RegExp(`^(?:hooks run ([\\w-]+)(?:\\s+--profile\\s+[\\w-]+)?(?:\\s+--target\\s+(?:${HOOK_RUN_TARGETS.join("|")}))?|hook-([\\w-]+))$`);
2086
2390
  });
2087
2391
 
2088
2392
  // src/db/schema.ts
@@ -2280,8 +2584,8 @@ var init_migrations = __esm(() => {
2280
2584
 
2281
2585
  // src/db/legacy-import.ts
2282
2586
  import { existsSync as existsSync6, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "fs";
2283
- import { join as join8 } from "path";
2284
- import { homedir as homedir5 } from "os";
2587
+ import { join as join9 } from "path";
2588
+ import { homedir as homedir6 } from "os";
2285
2589
  function ensureMetaTable(db) {
2286
2590
  db.exec(`
2287
2591
  CREATE TABLE IF NOT EXISTS _meta (
@@ -2355,25 +2659,25 @@ function importErrorsLog(db, filePath) {
2355
2659
  } catch {}
2356
2660
  return count;
2357
2661
  }
2358
- function runLegacyImport(db, homeDir = homedir5()) {
2662
+ function runLegacyImport(db, homeDir = homedir6()) {
2359
2663
  try {
2360
2664
  if (isAlreadyDone(db))
2361
2665
  return;
2362
2666
  let total = 0;
2363
- const claudeProjectsDir = join8(homeDir, ".claude", "projects");
2667
+ const claudeProjectsDir = join9(homeDir, ".claude", "projects");
2364
2668
  if (existsSync6(claudeProjectsDir)) {
2365
2669
  try {
2366
2670
  const projectDirs = readdirSync2(claudeProjectsDir);
2367
2671
  for (const dir of projectDirs) {
2368
- const projectDir = join8(claudeProjectsDir, dir);
2672
+ const projectDir = join9(claudeProjectsDir, dir);
2369
2673
  try {
2370
2674
  const files = readdirSync2(projectDir);
2371
2675
  for (const file of files) {
2372
2676
  if (file.match(/^session-log-\d{4}-\d{2}-\d{2}\.jsonl$/)) {
2373
- total += importJsonlFile(db, join8(projectDir, file));
2677
+ total += importJsonlFile(db, join9(projectDir, file));
2374
2678
  }
2375
2679
  if (file === "errors.log") {
2376
- total += importErrorsLog(db, join8(projectDir, file));
2680
+ total += importErrorsLog(db, join9(projectDir, file));
2377
2681
  }
2378
2682
  }
2379
2683
  } catch {}
@@ -2421,7 +2725,7 @@ __export(exports_db, {
2421
2725
  });
2422
2726
  import { Database } from "bun:sqlite";
2423
2727
  import { existsSync as existsSync7, mkdirSync as mkdirSync2, cpSync } from "fs";
2424
- import { join as join9 } from "path";
2728
+ import { join as join10 } from "path";
2425
2729
  function refuseLocalStore(message) {
2426
2730
  localStoreRefusal = message;
2427
2731
  }
@@ -2436,7 +2740,7 @@ function localStoreRefusalMessage() {
2436
2740
  }
2437
2741
  function resolveDataDir() {
2438
2742
  const effective = getEffectiveDataRoot();
2439
- const oldDir = join9(getHomeDir(), ".hooks");
2743
+ const oldDir = join10(getHomeDir(), ".hooks");
2440
2744
  if (!existsSync7(effective) && existsSync7(oldDir)) {
2441
2745
  mkdirSync2(effective, { recursive: true });
2442
2746
  cpSync(oldDir, effective, { recursive: true });
@@ -2448,7 +2752,7 @@ function getDbPath() {
2448
2752
  if (explicitDb)
2449
2753
  return explicitDb;
2450
2754
  const dataDir2 = resolveDataDir();
2451
- return join9(dataDir2, "hooks.db");
2755
+ return join10(dataDir2, "hooks.db");
2452
2756
  }
2453
2757
  function ensureDir(dbPath) {
2454
2758
  const dir = dbPath.substring(0, dbPath.lastIndexOf("/"));
@@ -2567,7 +2871,7 @@ __export(exports_store, {
2567
2871
  });
2568
2872
  import { createHash as createHash5 } from "crypto";
2569
2873
  import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2, renameSync, lstatSync as lstatSync4 } from "fs";
2570
- import { join as join10 } from "path";
2874
+ import { join as join11 } from "path";
2571
2875
  import { readFile } from "fs/promises";
2572
2876
  import { randomBytes } from "crypto";
2573
2877
  function sha256Of(input) {
@@ -2671,13 +2975,13 @@ function getPinnedHook(name) {
2671
2975
  return readLock().hooks[name];
2672
2976
  }
2673
2977
  function registryManagedMarker(name) {
2674
- return join10(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
2978
+ return join11(getHooksDataDir(), "registry-managed", sha256Of(name) + ".json");
2675
2979
  }
2676
2980
  function markRegistryManaged(name) {
2677
2981
  const path = registryManagedMarker(name);
2678
2982
  const content = JSON.stringify({ schema: 1, name }) + `
2679
2983
  `;
2680
- mkdirSync3(join10(getHooksDataDir(), "registry-managed"), { recursive: true, mode: 448 });
2984
+ mkdirSync3(join11(getHooksDataDir(), "registry-managed"), { recursive: true, mode: 448 });
2681
2985
  try {
2682
2986
  writeFileSync2(path, content, { flag: "wx", mode: 384 });
2683
2987
  } catch (error) {
@@ -2822,7 +3126,7 @@ var init_store = __esm(() => {
2822
3126
 
2823
3127
  // src/lib/codex-settings.ts
2824
3128
  import { closeSync as closeSync4, existsSync as existsSync9, lstatSync as lstatSync5, mkdirSync as mkdirSync4, openSync as openSync4, readFileSync as readFileSync6, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
2825
- import { dirname as dirname6 } from "path";
3129
+ import { dirname as dirname7 } from "path";
2826
3130
  import { createHash as createHash6, randomUUID } from "crypto";
2827
3131
  function current(path) {
2828
3132
  try {
@@ -2880,7 +3184,7 @@ function writeCodexSettings(path, settings, expectedSha256, beforeWrite) {
2880
3184
  ` });
2881
3185
  }
2882
3186
  function writeHookSettingsPreimage(path, settings, before, beforeWrite) {
2883
- mkdirSync4(dirname6(path), { recursive: true, mode: 448 });
3187
+ mkdirSync4(dirname7(path), { recursive: true, mode: 448 });
2884
3188
  const lock = `${path}.hooks-write.lock`;
2885
3189
  let fd;
2886
3190
  try {
@@ -2913,8 +3217,8 @@ var init_codex_settings = __esm(() => {
2913
3217
 
2914
3218
  // ../../node_modules/.bun/@hasna+skills@0.10.78+a00d3064559565bb/node_modules/@hasna/skills/dist/index.js
2915
3219
  import { existsSync as existsSync10 } from "fs";
2916
- import { homedir as homedir6 } from "os";
2917
- import { join as join11, resolve as resolve4 } from "path";
3220
+ import { homedir as homedir7 } from "os";
3221
+ import { join as join12, resolve as resolve5 } from "path";
2918
3222
  import { homedir as pathsResolverHomedir2 } from "os";
2919
3223
  import { join as pathsResolverJoin2 } from "path";
2920
3224
  import { createHash as createHash7 } from "crypto";
@@ -2924,7 +3228,7 @@ import { createHash as createHash32 } from "crypto";
2924
3228
  import { createHash as createHash22 } from "crypto";
2925
3229
  import { closeSync as closeSync22, constants as constants22, fstatSync as fstatSync22, lstatSync as lstatSync42, openSync as openSync22, readSync as readSync2 } from "fs";
2926
3230
  import { basename as basename2, dirname as dirname32, isAbsolute as isAbsolute22, resolve as resolve22 } from "path";
2927
- import { basename as basename5, isAbsolute as isAbsolute5, join as join72, resolve as resolve5, sep as sep3 } from "path";
3231
+ import { basename as basename5, isAbsolute as isAbsolute5, join as join72, resolve as resolve52, sep as sep3 } from "path";
2928
3232
  import { createHash as createHash42 } from "crypto";
2929
3233
  import { basename as basename3, dirname as dirname42, isAbsolute as isAbsolute32, resolve as resolve32 } from "path";
2930
3234
  import { createHash as createHash52 } from "crypto";
@@ -2938,13 +3242,13 @@ import { dirname as dirname62, isAbsolute as isAbsolute6, join as join82, resolv
2938
3242
  import { lstatSync as lstatSync6, readFileSync as readFileSync62, opendirSync } from "fs";
2939
3243
  import { createHash as createHash62 } from "crypto";
2940
3244
  import { lstatSync as lstatSync7, opendirSync as opendirSync2 } from "fs";
2941
- import { dirname as dirname7, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
3245
+ import { dirname as dirname72, isAbsolute as isAbsolute7, join as join92, resolve as resolve7 } from "path";
2942
3246
  import { createHash as createHash72 } from "crypto";
2943
3247
  import { closeSync as closeSync42, constants as constants4, fstatSync as fstatSync4, lstatSync as lstatSync8, openSync as openSync42, readSync as readSync3 } from "fs";
2944
3248
  import { dirname as dirname8, isAbsolute as isAbsolute8, resolve as resolve8 } from "path";
2945
3249
  import { createHash as createHash11, randomUUID as randomUUID2 } from "crypto";
2946
3250
  import { constants as constants6, closeSync as closeSync6, fchmodSync, fstatSync as fstatSync6, fsyncSync as fsyncSync2, linkSync as linkSync2, lstatSync as lstatSync10, mkdirSync as mkdirSync42, openSync as openSync6, opendirSync as opendirSync3, readSync as readSync5, renameSync as renameSync22, rmdirSync, rmSync, unlinkSync as unlinkSync2, writeSync } from "fs";
2947
- import { dirname as dirname10, isAbsolute as isAbsolute10, join as join12, parse as parse4, resolve as resolve10 } from "path";
3251
+ import { dirname as dirname10, isAbsolute as isAbsolute10, join as join122, parse as parse4, resolve as resolve10 } from "path";
2948
3252
  import { createHash as createHash10 } from "crypto";
2949
3253
  import { createHash as createHash12 } from "crypto";
2950
3254
  import { createHash as createHash13 } from "crypto";
@@ -3038,10 +3342,10 @@ function dataDir2(options) {
3038
3342
  return pathsResolverJoin2(pathsResolverDataBaseDir(options), appSegment);
3039
3343
  }
3040
3344
  function effectiveHome() {
3041
- return process.env["HOME"] || process.env["USERPROFILE"] || homedir6() || "/tmp";
3345
+ return process.env["HOME"] || process.env["USERPROFILE"] || homedir7() || "/tmp";
3042
3346
  }
3043
3347
  function legacyDataRoot() {
3044
- return join11(effectiveHome(), ".hasna", "skills");
3348
+ return join12(effectiveHome(), ".hasna", "skills");
3045
3349
  }
3046
3350
  function resolverDataRoot(home = effectiveHome(), env) {
3047
3351
  return dataDir2({ app: "skills", home, env });
@@ -3050,13 +3354,13 @@ function adoptResolverDataRoot2(resolved, env = process.env) {
3050
3354
  const dataOverride = env.HASNA_DATA_HOME;
3051
3355
  if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
3052
3356
  return true;
3053
- return existsSync10(join11(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join11(resolved, GLOBAL_CONFIG_FILENAME));
3357
+ return existsSync10(join12(resolved, DEFAULT_SQLITE_FILENAME)) || existsSync10(join12(resolved, GLOBAL_CONFIG_FILENAME));
3054
3358
  }
3055
3359
  function exactDataRoot() {
3056
3360
  for (const key of [DATA_DIR_ENV, HASNA_SKILLS_HOME_ENV, SKILLS_HOME_ENV]) {
3057
3361
  const dir = process.env[key]?.trim();
3058
3362
  if (dir)
3059
- return resolve4(dir);
3363
+ return resolve5(dir);
3060
3364
  }
3061
3365
  return;
3062
3366
  }
@@ -3065,7 +3369,7 @@ function getDataRoot() {
3065
3369
  if (exact)
3066
3370
  return exact;
3067
3371
  const resolved = resolverDataRoot();
3068
- return adoptResolverDataRoot2(resolved) ? resolve4(resolved) : resolve4(legacyDataRoot());
3372
+ return adoptResolverDataRoot2(resolved) ? resolve5(resolved) : resolve5(legacyDataRoot());
3069
3373
  }
3070
3374
  function getDataDirReadOnly() {
3071
3375
  return getDataRoot();
@@ -3984,7 +4288,7 @@ function assertAgentPolicyCollections(policy) {
3984
4288
  text(control.pluginId, 1024);
3985
4289
  text(control.namespace, 64);
3986
4290
  text(control.pluginParent);
3987
- requireBound(isAbsolute5(control.pluginParent) && resolve5(control.pluginParent) === control.pluginParent && /^[a-f0-9]{64}$/.test(control.manifestSha256));
4291
+ requireBound(isAbsolute5(control.pluginParent) && resolve52(control.pluginParent) === control.pluginParent && /^[a-f0-9]{64}$/.test(control.manifestSha256));
3988
4292
  if (control.remotePluginId !== undefined)
3989
4293
  requireBound(typeof control.remotePluginId === "string" && /^[A-Za-z0-9_~-]{1,1024}$/.test(control.remotePluginId));
3990
4294
  if (control.skillsOnly !== undefined)
@@ -4002,7 +4306,7 @@ function assertAgentPolicyCollections(policy) {
4002
4306
  text(control.pluginId, 1024);
4003
4307
  text(control.namespace, 64);
4004
4308
  text(control.pluginParent);
4005
- requireBound(!ids.has(control.pluginId) && isAbsolute5(control.pluginParent) && resolve5(control.pluginParent) === control.pluginParent && ["local", "git", "npm"].includes(control.sourceType) && typeof control.sourceSha256 === "string" && /^[a-f0-9]{64}$/.test(control.sourceSha256));
4309
+ requireBound(!ids.has(control.pluginId) && isAbsolute5(control.pluginParent) && resolve52(control.pluginParent) === control.pluginParent && ["local", "git", "npm"].includes(control.sourceType) && typeof control.sourceSha256 === "string" && /^[a-f0-9]{64}$/.test(control.sourceSha256));
4006
4310
  ids.add(control.pluginId);
4007
4311
  }
4008
4312
  }
@@ -4011,7 +4315,7 @@ function assertAgentPolicyCollections(policy) {
4011
4315
  requireBound(agent === "gemini" && object2(executable) && Object.keys(executable).length === 3 && executable.command === "gemini");
4012
4316
  for (const path of [executable.path, executable.target]) {
4013
4317
  text(path);
4014
- requireBound(!/[\x00-\x1f\x7f-\x9f\u200e\u200f\u202a-\u202e\u2066-\u2069]/.test(path) && isAbsolute5(path) && resolve5(path) === path);
4318
+ requireBound(!/[\x00-\x1f\x7f-\x9f\u200e\u200f\u202a-\u202e\u2066-\u2069]/.test(path) && isAbsolute5(path) && resolve52(path) === path);
4015
4319
  }
4016
4320
  }
4017
4321
  if (bridge.disabledBuiltins !== undefined)
@@ -4039,11 +4343,11 @@ function assertAgentPolicyCollections(policy) {
4039
4343
  requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && Object.keys(proof).every((key) => ["roots", "parents", "directories"].includes(key)) && roots.length + parents2.length > 0 && new Set(roots).size === roots.length && new Set(parents2).size === parents2.length);
4040
4344
  for (const root of roots) {
4041
4345
  text(root);
4042
- requireBound(isAbsolute5(root) && resolve5(root) === root);
4346
+ requireBound(isAbsolute5(root) && resolve52(root) === root);
4043
4347
  }
4044
4348
  for (const parent of parents2) {
4045
4349
  text(parent);
4046
- requireBound(isAbsolute5(parent) && resolve5(parent) === parent);
4350
+ requireBound(isAbsolute5(parent) && resolve52(parent) === parent);
4047
4351
  }
4048
4352
  for (const directory of array(proof.directories, AGENT_POLICY_LIMITS.discoveryDirectories)) {
4049
4353
  requireBound(object2(directory));
@@ -4063,7 +4367,7 @@ function assertAgentPolicyCollections(policy) {
4063
4367
  text(input.namespace, 64);
4064
4368
  text(input.pluginParent);
4065
4369
  text(input.sourceRoot);
4066
- requireBound(!ids.has(input.pluginId) && [input.pluginParent, input.sourceRoot].every((path) => isAbsolute5(path) && resolve5(path) === path) && typeof input.sourceSha256 === "string" && /^[a-f0-9]{64}$/.test(input.sourceSha256));
4370
+ requireBound(!ids.has(input.pluginId) && [input.pluginParent, input.sourceRoot].every((path) => isAbsolute5(path) && resolve52(path) === path) && typeof input.sourceSha256 === "string" && /^[a-f0-9]{64}$/.test(input.sourceSha256));
4067
4371
  ids.add(input.pluginId);
4068
4372
  }
4069
4373
  if (proof.directories !== undefined)
@@ -4077,14 +4381,14 @@ function assertAgentPolicyCollections(policy) {
4077
4381
  const proof = record(value.codexSemanticCache, 9), witness = record(proof.witness, 7);
4078
4382
  requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && [8, 9].includes(Object.keys(proof).length) && Object.keys(proof).every((key) => ["schema", "configPath", "hookRootAlias", "witness", "appOnlyParents", "previousPolicySha256", "supersededSources", "supersededDirectories", "reviewedHookParents"].includes(key)) && proof.schema === "hasna.codex-semantic-cache-discovery.v1" && typeof proof.previousPolicySha256 === "string" && /^[a-f0-9]{64}$/.test(proof.previousPolicySha256) && [6, 7].includes(Object.keys(witness).length) && Object.keys(witness).every((key) => ["schema", "cacheRoot", "controls", "appOnlyParents", "skills", "sha256", "hookParents"].includes(key)) && witness.schema === "hasna.codex-semantic-cache-witness.v1" && typeof witness.sha256 === "string" && /^[a-f0-9]{64}$/.test(witness.sha256));
4079
4383
  text(proof.configPath);
4080
- requireBound(isAbsolute5(proof.configPath) && resolve5(proof.configPath) === proof.configPath && basename5(proof.configPath) === "config.toml");
4384
+ requireBound(isAbsolute5(proof.configPath) && resolve52(proof.configPath) === proof.configPath && basename5(proof.configPath) === "config.toml");
4081
4385
  text(witness.cacheRoot);
4082
- requireBound(isAbsolute5(witness.cacheRoot) && resolve5(witness.cacheRoot) === witness.cacheRoot);
4386
+ requireBound(isAbsolute5(witness.cacheRoot) && resolve52(witness.cacheRoot) === witness.cacheRoot);
4083
4387
  if (proof.hookRootAlias !== null) {
4084
4388
  requireBound(object2(proof.hookRootAlias) && Object.keys(proof.hookRootAlias).length === 2);
4085
4389
  for (const key of ["alias", "target"]) {
4086
4390
  text(proof.hookRootAlias[key]);
4087
- requireBound(isAbsolute5(proof.hookRootAlias[key]) && resolve5(proof.hookRootAlias[key]) === proof.hookRootAlias[key]);
4391
+ requireBound(isAbsolute5(proof.hookRootAlias[key]) && resolve52(proof.hookRootAlias[key]) === proof.hookRootAlias[key]);
4088
4392
  }
4089
4393
  }
4090
4394
  const parents2 = array(proof.appOnlyParents, 4096);
@@ -4092,7 +4396,7 @@ function assertAgentPolicyCollections(policy) {
4092
4396
  requireBound(object2(parent) && Object.keys(parent).length === 5 && parent.role === "app-only");
4093
4397
  for (const key of ["pluginId", "namespace", "pluginParent", "remotePluginId"])
4094
4398
  text(parent[key]);
4095
- requireBound(isAbsolute5(parent.pluginParent) && resolve5(parent.pluginParent) === parent.pluginParent);
4399
+ requireBound(isAbsolute5(parent.pluginParent) && resolve52(parent.pluginParent) === parent.pluginParent);
4096
4400
  }
4097
4401
  if (proof.reviewedHookParents !== undefined)
4098
4402
  for (const parent of array(proof.reviewedHookParents, 4096)) {
@@ -4104,9 +4408,9 @@ function assertAgentPolicyCollections(policy) {
4104
4408
  text(parent.remotePluginId);
4105
4409
  else {
4106
4410
  text(parent.marketplaceSourcePath);
4107
- requireBound(typeof parent.marketplaceSha256 === "string" && /^[a-f0-9]{64}$/.test(parent.marketplaceSha256) && isAbsolute5(parent.marketplaceSourcePath) && resolve5(parent.marketplaceSourcePath) === parent.marketplaceSourcePath && basename5(parent.marketplaceSourcePath) === "marketplace.json");
4411
+ requireBound(typeof parent.marketplaceSha256 === "string" && /^[a-f0-9]{64}$/.test(parent.marketplaceSha256) && isAbsolute5(parent.marketplaceSourcePath) && resolve52(parent.marketplaceSourcePath) === parent.marketplaceSourcePath && basename5(parent.marketplaceSourcePath) === "marketplace.json");
4108
4412
  }
4109
- requireBound(isAbsolute5(parent.pluginParent) && resolve5(parent.pluginParent) === parent.pluginParent);
4413
+ requireBound(isAbsolute5(parent.pluginParent) && resolve52(parent.pluginParent) === parent.pluginParent);
4110
4414
  }
4111
4415
  for (const row of [...array(witness.controls, 4096), ...array(witness.appOnlyParents, 4096)]) {
4112
4416
  requireBound(object2(row));
@@ -4126,9 +4430,9 @@ function assertAgentPolicyCollections(policy) {
4126
4430
  text(row.remotePluginId);
4127
4431
  else {
4128
4432
  text(row.marketplaceSourcePath);
4129
- requireBound(typeof row.marketplaceSha256 === "string" && /^[a-f0-9]{64}$/.test(row.marketplaceSha256) && isAbsolute5(row.marketplaceSourcePath) && resolve5(row.marketplaceSourcePath) === row.marketplaceSourcePath && basename5(row.marketplaceSourcePath) === "marketplace.json");
4433
+ requireBound(typeof row.marketplaceSha256 === "string" && /^[a-f0-9]{64}$/.test(row.marketplaceSha256) && isAbsolute5(row.marketplaceSourcePath) && resolve52(row.marketplaceSourcePath) === row.marketplaceSourcePath && basename5(row.marketplaceSourcePath) === "marketplace.json");
4130
4434
  }
4131
- requireBound(isAbsolute5(row.pluginParent) && resolve5(row.pluginParent) === row.pluginParent);
4435
+ requireBound(isAbsolute5(row.pluginParent) && resolve52(row.pluginParent) === row.pluginParent);
4132
4436
  for (const key of ["manifestSha256", "hooksSha256"])
4133
4437
  requireBound(typeof row[key] === "string" && /^[a-f0-9]{64}$/.test(row[key]));
4134
4438
  if (row.installation === "remote-receipt")
@@ -4165,13 +4469,13 @@ function assertAgentPolicyCollections(policy) {
4165
4469
  if (source.hashMode === CLAUDE_ORPHAN_MARKER_MODE)
4166
4470
  requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && isClaudePluginCacheOrphanMarker(source.path) && source.managedPlugins === undefined && source.reviewArtifact === undefined);
4167
4471
  if (source.hashMode === "executable-v1")
4168
- requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && value.sources.some((row) => row.hashMode === "codex-settings-v6") && isAbsolute5(source.path) && resolve5(source.path) === source.path);
4472
+ requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && value.sources.some((row) => row.hashMode === "codex-settings-v6") && isAbsolute5(source.path) && resolve52(source.path) === source.path);
4169
4473
  if (source.hashMode === "codex-settings-v6") {
4170
4474
  const seen = new Set;
4171
4475
  for (const hook of array(source.hookSources, AGENT_POLICY_LIMITS.discoverySources)) {
4172
4476
  requireBound(object2(hook) && Object.keys(hook).length === 2 && Object.keys(hook).every((key) => ["path", "sha256"].includes(key)));
4173
4477
  text(hook.path);
4174
- requireBound(isAbsolute5(hook.path) && resolve5(hook.path) === hook.path && !seen.has(hook.path));
4478
+ requireBound(isAbsolute5(hook.path) && resolve52(hook.path) === hook.path && !seen.has(hook.path));
4175
4479
  seen.add(hook.path);
4176
4480
  requireBound(hook.sha256 === null || typeof hook.sha256 === "string" && /^[a-f0-9]{64}$/.test(hook.sha256));
4177
4481
  requireBound(value.sources.some((row) => row.path === hook.path && row.sha256 === hook.sha256 && [undefined, "bytes"].includes(row.hashMode) && row.format === undefined && row.fields === undefined));
@@ -4179,15 +4483,15 @@ function assertAgentPolicyCollections(policy) {
4179
4483
  } else
4180
4484
  requireBound(source.hookSources === undefined);
4181
4485
  if (source.hashMode === "claude-plugin-manifest-v1")
4182
- requireBound(agent === "claude" && value.agent === "claude" && ["automatic", "reviewed"].includes(value.method) && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve5(source.path) === source.path && source.path.endsWith(join72(sep3, ".claude-plugin", "plugin.json")) && source.managedPlugins === undefined);
4486
+ requireBound(agent === "claude" && value.agent === "claude" && ["automatic", "reviewed"].includes(value.method) && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve52(source.path) === source.path && source.path.endsWith(join72(sep3, ".claude-plugin", "plugin.json")) && source.managedPlugins === undefined);
4183
4487
  if (source.hashMode === "sumi-settings-v1")
4184
- requireBound(agent === "sumi" && value.agent === "sumi" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve5(source.path) === source.path && basename5(source.path) === "sumi.json");
4488
+ requireBound(agent === "sumi" && value.agent === "sumi" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve52(source.path) === source.path && basename5(source.path) === "sumi.json");
4185
4489
  if (source.hashMode === "codex-settings-v1" || source.hashMode === "codex-settings-v2" || (source.hashMode === "codex-settings-v3" || source.hashMode === "codex-settings-v4" || source.hashMode === "codex-settings-v5" || source.hashMode === "codex-settings-v6"))
4186
- requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve5(source.path) === source.path && basename5(source.path) === "config.toml");
4490
+ requireBound(agent === "codex" && value.agent === "codex" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve52(source.path) === source.path && basename5(source.path) === "config.toml");
4187
4491
  if (source.hashMode === "claude-settings-v1" || source.hashMode === "claude-settings-v2" || (source.hashMode === "claude-settings-v3" || source.hashMode === "claude-settings-v4"))
4188
- requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve5(source.path) === source.path && basename5(source.path) === "settings.json");
4492
+ requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve52(source.path) === source.path && basename5(source.path) === "settings.json");
4189
4493
  if (source.hashMode === "claude-marketplace-registry" || source.hashMode === "claude-marketplace-registry-v2")
4190
- requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve5(source.path) === source.path && basename5(source.path) === "known_marketplaces.json");
4494
+ requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && !/[\x00-\x1f\x7f]/.test(source.path) && isAbsolute5(source.path) && resolve52(source.path) === source.path && basename5(source.path) === "known_marketplaces.json");
4191
4495
  if (source.hashMode === "claude-marketplace-entry-v1")
4192
4496
  requireBound(agent === "claude" && value.agent === "claude" && value.method === "reviewed" && claudeMarketplaceEntrySourceValid(source));
4193
4497
  if (source.hashMode === "claude-plugin-registry") {
@@ -4206,7 +4510,7 @@ function assertAgentPolicyCollections(policy) {
4206
4510
  requireBound(agent === "codex" && value.method === "reviewed" && source.hashMode === "bytes" && object2(artifact) && Object.keys(artifact).length === 6 && Object.keys(artifact).every((key) => ["version", "kind", "storeRoot", "originalPath", "sha256", "catalogSha256"].includes(key)) && artifact.version === 1 && artifact.kind === "codex-native-catalog" && artifact.sha256 === source.sha256 && /^[a-f0-9]{64}$/.test(artifact.catalogSha256));
4207
4511
  for (const path of [artifact.storeRoot, artifact.originalPath]) {
4208
4512
  text(path);
4209
- requireBound(isAbsolute5(path) && resolve5(path) === path);
4513
+ requireBound(isAbsolute5(path) && resolve52(path) === path);
4210
4514
  }
4211
4515
  requireBound(source.path === join72(artifact.storeRoot, "agent-discovery", "artifacts", artifact.sha256, "catalog.json"));
4212
4516
  }
@@ -4416,9 +4720,9 @@ function need3(value, message) {
4416
4720
  }
4417
4721
  function safe2(path) {
4418
4722
  need3(typeof path === "string" && path.length <= AGENT_POLICY_LIMITS.pathCharacters && isAbsolute7(path) && resolve7(path) === path && !path.includes("\x00"), "Expected a canonical absolute discovery directory path");
4419
- for (let cursor = path;; cursor = dirname7(cursor)) {
4723
+ for (let cursor = path;; cursor = dirname72(cursor)) {
4420
4724
  need3(!lstatSync7(cursor, { throwIfNoEntry: false })?.isSymbolicLink(), "Refusing symlink native discovery directory");
4421
- if (dirname7(cursor) === cursor)
4725
+ if (dirname72(cursor) === cursor)
4422
4726
  break;
4423
4727
  }
4424
4728
  }
@@ -4868,7 +5172,7 @@ function ancestors(path, create = false) {
4868
5172
  let current2 = filesystemRoot;
4869
5173
  for (const segment of ["", ...parent.slice(filesystemRoot.length).split("/").filter(Boolean)]) {
4870
5174
  if (segment)
4871
- current2 = join12(current2, segment);
5175
+ current2 = join122(current2, segment);
4872
5176
  let currentStat = stat(current2);
4873
5177
  if (!currentStat && create) {
4874
5178
  try {
@@ -4976,7 +5280,7 @@ function snapshotPluginTree(root, options = {}) {
4976
5280
  pluginNeed(++visited <= PLUGIN_PROJECTION_LIMITS.files * 50, "Plugin tree membership exceeds its limit");
4977
5281
  const path = relative32 ? `${relative32}/${name}` : name;
4978
5282
  pluginNeed(new TextEncoder().encode(path).byteLength <= 100 && !/[\\:\x00-\x1f\x7f]/u.test(path), "Plugin entry path exceeds its limit or is unsafe");
4979
- const absolute2 = join12(directory, name), entryStat = stat(absolute2);
5283
+ const absolute2 = join122(directory, name), entryStat = stat(absolute2);
4980
5284
  pluginNeed(entryStat, "Plugin tree member disappeared");
4981
5285
  if (relative32 === "" && name === ".orphaned_at" && (options.nativeRuntime === "claude-2.1.274" || options.nativeRuntime === "claude-2.1.276")) {
4982
5286
  const bytes2 = readBytes(absolute2, 32, "native-pin");
@@ -4993,7 +5297,7 @@ function snapshotPluginTree(root, options = {}) {
4993
5297
  directories.push({ path: absolute2, stat: entryStat, names: pins });
4994
5298
  for (const pin3 of pins) {
4995
5299
  pluginNeed(/^[1-9][0-9]{0,9}$/.test(pin3) && Number(pin3) <= 2147483647, "Unrecognized native plugin pin name");
4996
- const pinPath = join12(absolute2, pin3), pinStat = stat(pinPath);
5300
+ const pinPath = join122(absolute2, pin3), pinStat = stat(pinPath);
4997
5301
  pluginNeed(pinStat, "Native plugin pin disappeared");
4998
5302
  const bytes2 = readBytes(pinPath, 4096, "native-pin");
4999
5303
  let value;
@@ -40505,7 +40809,7 @@ CREATE TABLE IF NOT EXISTS skills_sync_cursors (
40505
40809
  // src/lib/claude-skills-coordination.ts
40506
40810
  import { createHash as createHash8 } from "crypto";
40507
40811
  import { existsSync as existsSync11, lstatSync as lstatSync9 } from "fs";
40508
- import { homedir as homedir7 } from "os";
40812
+ import { homedir as homedir8 } from "os";
40509
40813
  import { join as join17, resolve as resolve9 } from "path";
40510
40814
  function claudeSkillsUsage(before, home) {
40511
40815
  const evidence = [], events3 = [];
@@ -40536,7 +40840,7 @@ function skillsPolicyLocations(dataDir3) {
40536
40840
  const state = (path) => existsSync11(path) ? "present" : "absent";
40537
40841
  if (dataDir3 !== undefined)
40538
40842
  return [`${join17(resolve9(dataDir3), "agent-policy.json")} (explicit data directory, absent)`];
40539
- const env = process.env, home = env.HOME || env.USERPROFILE || homedir7() || "/tmp", searched = [];
40843
+ const env = process.env, home = env.HOME || env.USERPROFILE || homedir8() || "/tmp", searched = [];
40540
40844
  let selected = false;
40541
40845
  for (const key2 of ["HASNA_SKILLS_DIR", "HASNA_SKILLS_HOME", "SKILLS_HOME"]) {
40542
40846
  const value = env[key2]?.trim();
@@ -40604,38 +40908,803 @@ var init_claude_skills_coordination = __esm(() => {
40604
40908
  SKILLS_HOOK_COMMAND = /(?:^|\s)hook user-prompt --agent (?:claude|codex|gemini)(?:\s|$)/;
40605
40909
  });
40606
40910
 
40607
- // src/lib/native-target.ts
40608
- var exports_native_target = {};
40609
- __export(exports_native_target, {
40610
- nativeTargetCommandSuffix: () => nativeTargetCommandSuffix,
40611
- nativeTargetArgs: () => nativeTargetArgs,
40612
- isHookRunTarget: () => isHookRunTarget,
40613
- HOOK_RUN_TARGETS: () => HOOK_RUN_TARGETS
40911
+ // src/lib/profiles.ts
40912
+ import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync7, readdirSync as readdirSync4, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
40913
+ import { join as join20 } from "path";
40914
+ function getProfilesDir() {
40915
+ const newDir = join20(getEffectiveDataRoot(), "profiles");
40916
+ const oldDir = join20(getHomeDir(), ".hooks", "profiles");
40917
+ if (!existsSync12(newDir) && existsSync12(oldDir)) {
40918
+ mkdirSync6(newDir, { recursive: true });
40919
+ cpSync2(oldDir, newDir, { recursive: true });
40920
+ }
40921
+ return newDir;
40922
+ }
40923
+ function ensureProfilesDir() {
40924
+ const dir = getProfilesDir();
40925
+ if (!existsSync12(dir)) {
40926
+ mkdirSync6(dir, { recursive: true });
40927
+ }
40928
+ }
40929
+ function profilePath(id) {
40930
+ return join20(getProfilesDir(), `${id}.json`);
40931
+ }
40932
+ function shortUuid() {
40933
+ return crypto.randomUUID().slice(0, 8);
40934
+ }
40935
+ function createProfile(input2) {
40936
+ ensureProfilesDir();
40937
+ const id = shortUuid();
40938
+ const now = new Date().toISOString();
40939
+ const profile = {
40940
+ agent_id: id,
40941
+ agent_type: input2.agent_type,
40942
+ created_at: now,
40943
+ last_seen_at: now,
40944
+ preferences: {}
40945
+ };
40946
+ if (input2.name) {
40947
+ profile.name = input2.name;
40948
+ }
40949
+ writeFileSync7(profilePath(id), JSON.stringify(profile, null, 2) + `
40950
+ `);
40951
+ return profile;
40952
+ }
40953
+ function getProfile(id) {
40954
+ const path = profilePath(id);
40955
+ try {
40956
+ if (!existsSync12(path))
40957
+ return null;
40958
+ return JSON.parse(readFileSync7(path, "utf-8"));
40959
+ } catch {
40960
+ return null;
40961
+ }
40962
+ }
40963
+ function listProfiles() {
40964
+ const dir = getProfilesDir();
40965
+ if (!existsSync12(dir))
40966
+ return [];
40967
+ try {
40968
+ const files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
40969
+ const profiles = [];
40970
+ for (const file2 of files) {
40971
+ try {
40972
+ const content = readFileSync7(join20(dir, file2), "utf-8");
40973
+ profiles.push(JSON.parse(content));
40974
+ } catch {}
40975
+ }
40976
+ return profiles.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
40977
+ } catch {
40978
+ return [];
40979
+ }
40980
+ }
40981
+ function updateProfile(id, data) {
40982
+ const profile = getProfile(id);
40983
+ if (!profile)
40984
+ return null;
40985
+ if (data.name !== undefined)
40986
+ profile.name = data.name;
40987
+ if (data.preferences !== undefined)
40988
+ profile.preferences = data.preferences;
40989
+ writeFileSync7(profilePath(id), JSON.stringify(profile, null, 2) + `
40990
+ `);
40991
+ return profile;
40992
+ }
40993
+ function touchProfile(id) {
40994
+ const profile = getProfile(id);
40995
+ if (!profile)
40996
+ return;
40997
+ profile.last_seen_at = new Date().toISOString();
40998
+ writeFileSync7(profilePath(id), JSON.stringify(profile, null, 2) + `
40999
+ `);
41000
+ }
41001
+ function exportProfiles() {
41002
+ return listProfiles();
41003
+ }
41004
+ function importProfiles(profiles) {
41005
+ ensureProfilesDir();
41006
+ let imported = 0;
41007
+ let skipped = 0;
41008
+ for (const profile of profiles) {
41009
+ if (!profile.agent_id || !profile.agent_type) {
41010
+ skipped++;
41011
+ continue;
41012
+ }
41013
+ const path = profilePath(profile.agent_id);
41014
+ if (existsSync12(path)) {
41015
+ skipped++;
41016
+ continue;
41017
+ }
41018
+ writeFileSync7(path, JSON.stringify(profile, null, 2) + `
41019
+ `);
41020
+ imported++;
41021
+ }
41022
+ return { imported, skipped };
41023
+ }
41024
+ var init_profiles = __esm(() => {
41025
+ init_app_home();
40614
41026
  });
40615
- function isHookRunTarget(value) {
40616
- return typeof value === "string" && HOOK_RUN_TARGETS.includes(value);
41027
+
41028
+ // src/lib/target-adapters.ts
41029
+ import { spawnSync } from "child_process";
41030
+ import { chmodSync as chmodSync2, existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync8, readdirSync as readdirSync8, rmdirSync as rmdirSync2, statSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9, renameSync as renameSync5 } from "fs";
41031
+ import { tmpdir } from "os";
41032
+ import { basename as basename9, dirname as dirname9, join as join22 } from "path";
41033
+ import { randomUUID as randomUUID5 } from "crypto";
41034
+ function isAdapterTarget(value) {
41035
+ return typeof value === "string" && ADAPTER_TARGETS.includes(value);
40617
41036
  }
40618
- function nativeTargetArgs(dispatch, target, args = []) {
40619
- if (target !== undefined && !isHookRunTarget(target))
40620
- throw new Error("Invalid --target; expected claude, codex, gemini, codewith, sumi, or opencode");
40621
- if (!dispatch)
40622
- return [...args];
40623
- if (!isHookRunTarget(target))
40624
- throw new Error("This hook requires --target from its native registration");
40625
- if (args.some((arg) => arg === "--harness" || arg.startsWith("--harness=")))
40626
- throw new Error("nativeTargetDispatch owns the --harness argument; remove it from manifest args");
40627
- return [...args, "--harness", target];
41037
+ function hookFromCommand(command) {
41038
+ return command.trim().match(HOOK_COMMAND_RE)?.[1];
40628
41039
  }
40629
- function nativeTargetCommandSuffix(dispatch, target) {
40630
- if (!dispatch)
40631
- return "";
40632
- if (!isHookRunTarget(target))
40633
- throw new Error("Native registration requires a supported target");
40634
- return ` --target ${target}`;
41040
+ function homeOf(options) {
41041
+ return options.home ?? process.env.HOME ?? process.env.USERPROFILE ?? "";
40635
41042
  }
40636
- var HOOK_RUN_TARGETS;
40637
- var init_native_target = __esm(() => {
40638
- HOOK_RUN_TARGETS = ["claude", "codex", "gemini", "codewith", "sumi", "opencode"];
41043
+ function adapterStorePath(target, options, hook) {
41044
+ return adapterPath(target, options, hook);
41045
+ }
41046
+ function adapterPath(target, options, hook) {
41047
+ const capabilities = getTargetCapabilities(target, {
41048
+ scope: options.scope,
41049
+ home: homeOf(options),
41050
+ cwd: options.cwd ?? process.cwd(),
41051
+ env: options.env ?? process.env,
41052
+ ...hook ? { hook } : {}
41053
+ });
41054
+ if (!capabilities)
41055
+ throw new Error(`No capability record for target '${target}'`);
41056
+ return capabilities.configPath;
41057
+ }
41058
+ function redactedDiagnostic(text3) {
41059
+ const line = (text3.split(`
41060
+ `).find((entry) => entry.trim()) ?? "").trim();
41061
+ return line.slice(0, 300).replace(/[A-Za-z0-9_\-]{24,}/g, "<redacted>");
41062
+ }
41063
+ function redactedCode(value) {
41064
+ return typeof value === "string" && value.length <= 64 && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/.test(value) ? value : "<redacted>";
41065
+ }
41066
+ function messageOf(error61) {
41067
+ return error61 instanceof Error ? error61.message : String(error61);
41068
+ }
41069
+ function readJsonObject(path) {
41070
+ let text3;
41071
+ try {
41072
+ text3 = readFileSync8(path, "utf-8");
41073
+ } catch (error61) {
41074
+ if (error61?.code === "ENOENT")
41075
+ return { status: "absent" };
41076
+ return { status: "unreadable", kind: "file", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
41077
+ }
41078
+ try {
41079
+ const value = JSON.parse(text3);
41080
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
41081
+ return { status: "unreadable", kind: "content", reason: `${path} is not a JSON object` };
41082
+ }
41083
+ return { status: "verified", value };
41084
+ } catch (error61) {
41085
+ return { status: "unreadable", kind: "content", reason: `${path} is not valid JSON (${redactedDiagnostic(messageOf(error61))})` };
41086
+ }
41087
+ }
41088
+ function writeText(path, content) {
41089
+ const dir = dirname9(path);
41090
+ mkdirSync10(dir, { recursive: true });
41091
+ const temp = join22(dir, `.${basename9(path)}.${randomUUID5()}.tmp`);
41092
+ try {
41093
+ writeFileSync9(temp, content);
41094
+ if (existsSync13(path))
41095
+ chmodSync2(temp, statSync(path).mode & 4095);
41096
+ renameSync5(temp, path);
41097
+ } catch (error61) {
41098
+ try {
41099
+ if (existsSync13(temp))
41100
+ unlinkSync3(temp);
41101
+ } catch {}
41102
+ throw error61;
41103
+ }
41104
+ }
41105
+ function tomlString(value) {
41106
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
41107
+ }
41108
+ function tomlStringValue(raw) {
41109
+ return raw.replace(/\\"/g, '"').replace(/\\\\/g, "\\");
41110
+ }
41111
+ function splitToml(text3) {
41112
+ const preamble = [];
41113
+ const chunks = [];
41114
+ let current2 = null;
41115
+ for (const line of text3.split(`
41116
+ `)) {
41117
+ if (TOML_HEADER_RE.test(line)) {
41118
+ if (current2)
41119
+ chunks.push(current2);
41120
+ current2 = { header: line.trim(), lines: [line] };
41121
+ } else if (current2) {
41122
+ current2.lines.push(line);
41123
+ } else {
41124
+ preamble.push(line);
41125
+ }
41126
+ }
41127
+ if (current2)
41128
+ chunks.push(current2);
41129
+ return { preamble, chunks };
41130
+ }
41131
+ function chunkCommand(chunk) {
41132
+ const text3 = chunk.lines.join(`
41133
+ `);
41134
+ const basic = text3.match(/^\s*command\s*=\s*"((?:[^"\\]|\\.)*)"/m);
41135
+ if (basic)
41136
+ return tomlStringValue(basic[1]);
41137
+ const literal2 = text3.match(/^\s*command\s*=\s*'([^']*)'/m);
41138
+ return literal2 ? literal2[1] : undefined;
41139
+ }
41140
+ function isKimiHookChunk(chunk) {
41141
+ return KIMI_HOOK_HEADER_RE.test(chunk.header);
41142
+ }
41143
+ function kimiRegistrations(text3) {
41144
+ const out = [];
41145
+ for (const chunk of splitToml(text3).chunks) {
41146
+ if (!isKimiHookChunk(chunk))
41147
+ continue;
41148
+ const command = chunkCommand(chunk);
41149
+ const hook = command ? hookFromCommand(command) : undefined;
41150
+ if (command && hook)
41151
+ out.push({ hook, command });
41152
+ }
41153
+ return out;
41154
+ }
41155
+ function kimiBlock(command, timeoutSeconds) {
41156
+ return [
41157
+ "[[hooks]]",
41158
+ 'event = "Stop"',
41159
+ `command = ${tomlString(command)}`,
41160
+ `timeout = ${Math.max(1, Math.min(600, timeoutSeconds))}`
41161
+ ].join(`
41162
+ `);
41163
+ }
41164
+ function removeKimiChunk(text3, hook) {
41165
+ const { preamble, chunks } = splitToml(text3);
41166
+ const kept = [...preamble];
41167
+ let removed = false;
41168
+ for (const chunk of chunks) {
41169
+ const command = isKimiHookChunk(chunk) ? chunkCommand(chunk) : undefined;
41170
+ if (command && hookFromCommand(command) === hook) {
41171
+ removed = true;
41172
+ while (kept.length > 0 && kept[kept.length - 1].trim() === "")
41173
+ kept.pop();
41174
+ continue;
41175
+ }
41176
+ if (TOML_HEADER_RE.test(chunk.header) && kept.length > 0 && kept[kept.length - 1].trim() !== "") {
41177
+ kept.push("");
41178
+ }
41179
+ kept.push(...chunk.lines);
41180
+ }
41181
+ return { text: kept.join(`
41182
+ `), removed };
41183
+ }
41184
+ function installKimi(hook, command, options, timeoutSeconds) {
41185
+ const path = adapterPath("kimi", options);
41186
+ const read3 = readTextState(path);
41187
+ if (read3.status === "unreadable") {
41188
+ return { ok: false, configPath: path, error: `Refused: ${read3.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` };
41189
+ }
41190
+ const existing = read3.status === "verified" ? read3.text : "";
41191
+ if (kimiRegistrations(existing).some((entry) => entry.hook === hook)) {
41192
+ return { ok: true, configPath: path, note: "already registered; nothing was written" };
41193
+ }
41194
+ const next = existing.trim() === "" ? `${kimiBlock(command, timeoutSeconds)}
41195
+ ` : `${existing.trimEnd()}
41196
+
41197
+ ${kimiBlock(command, timeoutSeconds)}
41198
+ `;
41199
+ const candidate = join22(tmpdir(), `hooks-kimi-config-${randomUUID5()}.toml`);
41200
+ writeFileSync9(candidate, next);
41201
+ let validationNote;
41202
+ try {
41203
+ const result = (options.run ?? defaultRunner)("kimi", ["doctor", "config", candidate]);
41204
+ if (result.notFound) {
41205
+ validationNote = "kimi is not installed here, so `kimi doctor config` did not validate the entry";
41206
+ } else if (result.status !== 0) {
41207
+ const detail = redactedDiagnostic(result.stderr) || redactedDiagnostic(result.stdout) || `exit ${result.status}`;
41208
+ return { ok: false, configPath: path, error: `Refused: \`kimi doctor config\` rejected the candidate config (${detail}). Nothing was written to ${path}.` };
41209
+ } else {
41210
+ validationNote = "validated with `kimi doctor config`";
41211
+ }
41212
+ } finally {
41213
+ try {
41214
+ if (existsSync13(candidate))
41215
+ unlinkSync3(candidate);
41216
+ } catch {}
41217
+ }
41218
+ writeText(path, next);
41219
+ return {
41220
+ ok: true,
41221
+ configPath: path,
41222
+ note: `Kimi blocks with exit 2 + stderr once per turn; ${validationNote}.`
41223
+ };
41224
+ }
41225
+ function piPointerPath(options) {
41226
+ return adapterPath("pi", options);
41227
+ }
41228
+ function readPiPointer(options) {
41229
+ return readJsonObject(piPointerPath(options));
41230
+ }
41231
+ function piProfile(options, pointer) {
41232
+ const state = pointer === undefined ? readPiPointer(options) : undefined;
41233
+ const config2 = pointer ?? (state?.status === "verified" ? state.value : undefined);
41234
+ if (typeof config2?.profile === "string") {
41235
+ const pointed = getProfile(config2.profile);
41236
+ if (pointed)
41237
+ return pointed;
41238
+ }
41239
+ return listProfiles().find((profile) => profile.agent_type === "custom" && profile.name === "pi");
41240
+ }
41241
+ function piCommands(profile) {
41242
+ const stored = profile?.preferences?.[PI_PREFERENCE_KEY];
41243
+ const hooks = stored?.hooks;
41244
+ return Array.isArray(hooks) ? hooks.filter((entry) => typeof entry === "string") : [];
41245
+ }
41246
+ function writePiCommands(profileId, commands) {
41247
+ const profile = getProfile(profileId);
41248
+ if (!profile)
41249
+ return;
41250
+ updateProfile(profileId, {
41251
+ preferences: {
41252
+ ...profile.preferences,
41253
+ [PI_PREFERENCE_KEY]: { hooks: commands, updated_at: new Date().toISOString() }
41254
+ }
41255
+ });
41256
+ }
41257
+ function installPi(hook, command, options) {
41258
+ const path = piPointerPath(options);
41259
+ const pointerRead = readPiPointer(options);
41260
+ if (pointerRead.status === "unreadable") {
41261
+ return { ok: false, configPath: path, error: `Refused: ${pointerRead.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` };
41262
+ }
41263
+ const profile = piProfile(options) ?? createProfile({ agent_type: "custom", name: "pi" });
41264
+ const commands = piCommands(profile);
41265
+ if (commands.some((entry) => hookFromCommand(entry) === hook)) {
41266
+ return { ok: true, configPath: path, note: "already registered; nothing was written" };
41267
+ }
41268
+ const pointer = pointerRead.status === "verified" ? pointerRead.value : {};
41269
+ writeText(path, `${JSON.stringify({ ...pointer, profile: profile.agent_id }, null, 2)}
41270
+ `);
41271
+ writePiCommands(profile.agent_id, [...commands, command]);
41272
+ return {
41273
+ ok: true,
41274
+ configPath: path,
41275
+ note: `registered through Hooks profile ${profile.agent_id}, which the hasna-pi-hooks bridge reads`
41276
+ };
41277
+ }
41278
+ function readCursorFile(path) {
41279
+ return readJsonObject(path);
41280
+ }
41281
+ function cursorRegistrations(config2) {
41282
+ const out = [];
41283
+ const hooks = config2?.hooks;
41284
+ if (!hooks || typeof hooks !== "object")
41285
+ return out;
41286
+ for (const key2 of Object.keys(hooks)) {
41287
+ const entries = hooks[key2];
41288
+ if (!Array.isArray(entries))
41289
+ continue;
41290
+ for (const entry of entries) {
41291
+ const command = typeof entry?.command === "string" ? entry.command : undefined;
41292
+ const hook = command ? hookFromCommand(command) : undefined;
41293
+ if (command && hook)
41294
+ out.push({ hook, command });
41295
+ }
41296
+ }
41297
+ return out;
41298
+ }
41299
+ function installCursor(hook, command, options, timeoutSeconds) {
41300
+ const path = adapterPath("cursor", options);
41301
+ const read3 = readCursorFile(path);
41302
+ if (read3.status === "unreadable") {
41303
+ return {
41304
+ ok: false,
41305
+ configPath: path,
41306
+ error: read3.kind === "file" ? `Refused: ${read3.reason}, so Hooks wrote nothing. Repair the file or move it aside, then retry.` : `Refused: ${path} is not a JSON object, so Hooks wrote nothing. Repair the file or move it aside, then retry.`
41307
+ };
41308
+ }
41309
+ const config2 = read3.status === "verified" ? read3.value : undefined;
41310
+ if (cursorRegistrations(config2).some((entry) => entry.hook === hook)) {
41311
+ return { ok: true, configPath: path, note: "already registered; nothing was written" };
41312
+ }
41313
+ const next = config2 ?? {};
41314
+ const hooks = next.hooks && typeof next.hooks === "object" ? { ...next.hooks } : {};
41315
+ const stop = Array.isArray(hooks.stop) ? [...hooks.stop] : [];
41316
+ stop.push({ command, timeout: Math.max(1, Math.min(600, timeoutSeconds)) });
41317
+ hooks.stop = stop;
41318
+ writeText(path, `${JSON.stringify({ version: 1, ...next, hooks }, null, 2)}
41319
+ `);
41320
+ return { ok: true, configPath: path };
41321
+ }
41322
+ function splitArgv(command) {
41323
+ return command.trim().split(/\s+/).filter(Boolean);
41324
+ }
41325
+ function hookFromMuseCommand(command) {
41326
+ if (!Array.isArray(command))
41327
+ return;
41328
+ const joined = command.filter((part) => typeof part === "string").join(" ");
41329
+ const match = joined.match(/(?:^|\s)\S*hooks run ([\w-]+)(?:\s|$)/);
41330
+ return match?.[1];
41331
+ }
41332
+ function museManifest(hook, command, options, timeoutSeconds) {
41333
+ return {
41334
+ name: `hasna-hook-${hook}`,
41335
+ version: options.version ?? "0.0.0",
41336
+ description: options.description ?? `Hasna hook ${hook}`,
41337
+ schemaVersion: 1,
41338
+ compat: { source: "native", manifestDir: ".muse-plugin" },
41339
+ capabilities: {
41340
+ hooks: [{
41341
+ id: `hasna-${hook}-stop`,
41342
+ event: "Stop",
41343
+ command: splitArgv(command),
41344
+ timeoutMs: timeoutSeconds * 1000,
41345
+ statusMessage: `Running Hasna hook ${hook}`
41346
+ }]
41347
+ }
41348
+ };
41349
+ }
41350
+ function museDiagnostic(outcome) {
41351
+ try {
41352
+ const parsed = JSON.parse(outcome.stdout);
41353
+ const message = parsed?.error?.message;
41354
+ if (typeof message === "string" && message.trim()) {
41355
+ const code2 = parsed.error?.code === undefined ? "" : `${redactedCode(parsed.error.code)}: `;
41356
+ return `${code2}${redactedDiagnostic(message)}`;
41357
+ }
41358
+ } catch {}
41359
+ return redactedDiagnostic(outcome.stderr) || redactedDiagnostic(outcome.stdout) || `exit ${outcome.status}`;
41360
+ }
41361
+ function removeMuseBundle(bundle) {
41362
+ const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
41363
+ try {
41364
+ if (existsSync13(manifestPath))
41365
+ unlinkSync3(manifestPath);
41366
+ } catch {}
41367
+ for (const dir of [join22(bundle, ".muse-plugin"), bundle]) {
41368
+ try {
41369
+ if (existsSync13(dir))
41370
+ rmdirSync2(dir);
41371
+ } catch {}
41372
+ }
41373
+ }
41374
+ function museBundles(options) {
41375
+ const root = musePluginRoot({ home: homeOf(options), env: options.env ?? process.env });
41376
+ if (!existsSync13(root))
41377
+ return [];
41378
+ const out = [];
41379
+ for (const entry of readdirSync8(root)) {
41380
+ const manifestPath = join22(root, entry, ".muse-plugin", "plugin.json");
41381
+ if (!existsSync13(manifestPath))
41382
+ continue;
41383
+ try {
41384
+ const manifest = JSON.parse(readFileSync8(manifestPath, "utf-8"));
41385
+ for (const capability of manifest.capabilities?.hooks ?? []) {
41386
+ const command = Array.isArray(capability.command) ? capability.command.join(" ") : "";
41387
+ const hook = hookFromCommand(command) ?? hookFromMuseCommand(capability.command);
41388
+ if (hook)
41389
+ out.push({ hook, command });
41390
+ }
41391
+ } catch {}
41392
+ }
41393
+ return out;
41394
+ }
41395
+ function museOwnFiles(options) {
41396
+ const home = homeOf(options);
41397
+ const env = options.env ?? process.env;
41398
+ const configBase = env.XDG_CONFIG_HOME?.startsWith("/") ? env.XDG_CONFIG_HOME : join22(home, ".config");
41399
+ const dataBase = env.XDG_DATA_HOME?.startsWith("/") ? env.XDG_DATA_HOME : join22(home, ".local", "share");
41400
+ const searched = [join22(configBase, "muse", "settings.json"), join22(dataBase, "muse")];
41401
+ const found = searched.filter((path) => existsSync13(path));
41402
+ return { present: found.length > 0, found, searched };
41403
+ }
41404
+ function readMuseState(options, runner = options.run ?? defaultRunner) {
41405
+ const source = "`muse plugins list --json`";
41406
+ const bundleRoot = musePluginRoot({ home: homeOf(options), env: options.env ?? process.env });
41407
+ const unverified = (reason2) => ({ status: "unverified", registrations: [], inactive: [], source, reason: reason2 });
41408
+ const result = runner("muse", ["plugins", "list", "--json"]);
41409
+ if (result.notFound) {
41410
+ const muse = museOwnFiles(options);
41411
+ if (muse.present) {
41412
+ return unverified(`Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so ${source} cannot say what Muse carries \u2014 ` + `a plugin Muse registered may still run, and a bundle under ${bundleRoot} is a file Hooks wrote, not proof either way`);
41413
+ }
41414
+ return {
41415
+ ...unverified(`Muse is not installed here: neither its store (${muse.searched.join(" or ")}) nor the \`muse\` command exists, so it carries no registration`),
41416
+ absent: true
41417
+ };
41418
+ }
41419
+ if (result.status !== 0) {
41420
+ return unverified(`${source} failed (${museDiagnostic(result)})`);
41421
+ }
41422
+ let parsed;
41423
+ try {
41424
+ parsed = JSON.parse(result.stdout);
41425
+ } catch {
41426
+ return unverified(`${source} did not return JSON`);
41427
+ }
41428
+ const entries = parsed?.plugins;
41429
+ if (!Array.isArray(entries))
41430
+ return unverified(`${source} returned no plugin list`);
41431
+ const registrations = [];
41432
+ const inactive = [];
41433
+ for (const entry of entries) {
41434
+ const hooks = entry?.plugin?.capabilities?.hooks;
41435
+ if (!Array.isArray(hooks))
41436
+ continue;
41437
+ const enabled = entry?.record?.enabled === true;
41438
+ for (const capability of hooks) {
41439
+ const command = Array.isArray(capability?.command) ? capability.command.filter((part) => typeof part === "string").join(" ") : "";
41440
+ const hook = hookFromMuseCommand(capability?.command);
41441
+ if (!hook)
41442
+ continue;
41443
+ if (enabled) {
41444
+ registrations.push({ hook, command });
41445
+ } else if (!inactive.includes(hook)) {
41446
+ inactive.push(hook);
41447
+ }
41448
+ }
41449
+ }
41450
+ return { status: "verified", registrations, inactive, source };
41451
+ }
41452
+ function installMuse(hook, command, options, timeoutSeconds) {
41453
+ const runner = options.run ?? defaultRunner;
41454
+ const bundle = adapterPath("muse", options, hook);
41455
+ const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
41456
+ const existedBefore = existsSync13(manifestPath);
41457
+ const manifest = museManifest(hook, command, options, timeoutSeconds);
41458
+ writeText(manifestPath, `${JSON.stringify(manifest, null, 2)}
41459
+ `);
41460
+ const installCommand = `muse plugins install ${bundle} --scope user`;
41461
+ const approveCommand = `muse plugins approve ${manifest.name}`;
41462
+ const cleanup = () => {
41463
+ if (!existedBefore)
41464
+ removeMuseBundle(bundle);
41465
+ };
41466
+ const left = existedBefore ? ` The existing bundle at ${bundle} was left as it was.` : " The bundle was removed again, so nothing is left half-written.";
41467
+ const validated = runner("muse", ["plugins", "validate", bundle, "--json"]);
41468
+ if (validated.notFound) {
41469
+ cleanup();
41470
+ const muse = museOwnFiles(options);
41471
+ return {
41472
+ ok: false,
41473
+ configPath: bundle,
41474
+ error: muse.present ? `Refused: Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so \`muse plugins validate\` could not check the bundle.${left} Run it where the Muse command is available: \`${installCommand}\` then \`${approveCommand}\`.` : `Refused: Muse is not installed here, so \`muse plugins validate\` could not check the bundle.${left} On a station with Muse run \`${installCommand}\` then \`${approveCommand}\`.`
41475
+ };
41476
+ }
41477
+ if (validated.status !== 0) {
41478
+ cleanup();
41479
+ return {
41480
+ ok: false,
41481
+ configPath: bundle,
41482
+ error: `Refused: Muse rejected the plugin manifest (${museDiagnostic(validated)}).${left} Nothing was registered.`
41483
+ };
41484
+ }
41485
+ const installed = runner("muse", ["plugins", "install", bundle, "--scope", "user"]);
41486
+ if (installed.notFound) {
41487
+ cleanup();
41488
+ return {
41489
+ ok: false,
41490
+ configPath: bundle,
41491
+ error: `Refused: Muse disappeared between validation and install, so the plugin was not registered.${left} On a station with Muse run \`${installCommand}\` then \`${approveCommand}\`.`
41492
+ };
41493
+ }
41494
+ if (installed.status !== 0) {
41495
+ cleanup();
41496
+ return {
41497
+ ok: false,
41498
+ configPath: bundle,
41499
+ error: `Refused: \`${installCommand}\` failed (${museDiagnostic(installed)}).${left}`
41500
+ };
41501
+ }
41502
+ const approved = runner("muse", ["plugins", "approve", manifest.name]);
41503
+ if (approved.status !== 0) {
41504
+ const detail = museDiagnostic(approved);
41505
+ return {
41506
+ ok: false,
41507
+ configPath: bundle,
41508
+ error: `Refused: the plugin installed but Muse did not approve it (${detail}); an unapproved plugin does not run. Run \`${approveCommand}\` and retry.`
41509
+ };
41510
+ }
41511
+ return { ok: true, configPath: bundle, note: `installed at user scope and approved as ${manifest.name}` };
41512
+ }
41513
+ function readTextState(path) {
41514
+ try {
41515
+ return { status: "verified", text: readFileSync8(path, "utf-8") };
41516
+ } catch (error61) {
41517
+ if (error61?.code === "ENOENT")
41518
+ return { status: "absent" };
41519
+ return { status: "unreadable", reason: `cannot read ${path} (${redactedDiagnostic(messageOf(error61))})` };
41520
+ }
41521
+ }
41522
+ function readKimiState(options) {
41523
+ const read3 = readTextState(adapterPath("kimi", options));
41524
+ if (read3.status === "unreadable")
41525
+ return { status: "unverified", registrations: [], reason: read3.reason };
41526
+ if (read3.status === "absent")
41527
+ return { status: "verified", registrations: [] };
41528
+ return { status: "verified", registrations: kimiRegistrations(read3.text) };
41529
+ }
41530
+ function readPiState(options) {
41531
+ const read3 = readPiPointer(options);
41532
+ if (read3.status === "unreadable")
41533
+ return { status: "unverified", registrations: [], reason: read3.reason };
41534
+ const profile = piProfile(options, read3.status === "verified" ? read3.value : {});
41535
+ const registrations = piCommands(profile).flatMap((command) => {
41536
+ const hook = hookFromCommand(command);
41537
+ return hook ? [{ hook, command }] : [];
41538
+ });
41539
+ return { status: "verified", registrations };
41540
+ }
41541
+ function readCursorState(options) {
41542
+ const read3 = readCursorFile(adapterPath("cursor", options));
41543
+ if (read3.status === "unreadable")
41544
+ return { status: "unverified", registrations: [], reason: read3.reason };
41545
+ if (read3.status === "absent")
41546
+ return { status: "verified", registrations: [] };
41547
+ return { status: "verified", registrations: cursorRegistrations(read3.value) };
41548
+ }
41549
+ function readAdapterState(target, options, runner) {
41550
+ try {
41551
+ if (target === "kimi")
41552
+ return readKimiState(options);
41553
+ if (target === "pi")
41554
+ return readPiState(options);
41555
+ if (target === "cursor")
41556
+ return readCursorState(options);
41557
+ return readMuseState(options, runner ?? options.run ?? defaultRunner);
41558
+ } catch (error61) {
41559
+ return {
41560
+ status: "unverified",
41561
+ registrations: [],
41562
+ reason: `${target}: cannot read its registration state (${redactedDiagnostic(messageOf(error61))})`
41563
+ };
41564
+ }
41565
+ }
41566
+ function readAdapterRegistrations(target, options) {
41567
+ if (target === "muse") {
41568
+ try {
41569
+ return museBundles(options);
41570
+ } catch {
41571
+ return [];
41572
+ }
41573
+ }
41574
+ return readAdapterState(target, options).registrations;
41575
+ }
41576
+ function adapterStateCarries(state, hook) {
41577
+ if (state.registrations.some((entry) => entry.hook === hook))
41578
+ return true;
41579
+ const inactive = state.inactive;
41580
+ return Array.isArray(inactive) && inactive.includes(hook);
41581
+ }
41582
+ function installInAdapter(target, hook, command, options, timeoutSeconds = 10) {
41583
+ try {
41584
+ if (target === "kimi")
41585
+ return installKimi(hook, command, options, timeoutSeconds);
41586
+ if (target === "pi")
41587
+ return installPi(hook, command, options);
41588
+ if (target === "cursor")
41589
+ return installCursor(hook, command, options, timeoutSeconds);
41590
+ return installMuse(hook, command, options, timeoutSeconds);
41591
+ } catch (error61) {
41592
+ return { ok: false, configPath: "", error: `Refused: ${target}: the install did not complete (${redactedDiagnostic(messageOf(error61))})` };
41593
+ }
41594
+ }
41595
+ function removeFromAdapter(target, hook, options) {
41596
+ try {
41597
+ if (target === "kimi") {
41598
+ const path = adapterPath("kimi", options);
41599
+ const existing = readTextState(path);
41600
+ if (existing.status === "unreadable") {
41601
+ return { removed: false, reason: `${existing.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
41602
+ }
41603
+ const { text: text3, removed } = removeKimiChunk(existing.status === "verified" ? existing.text : "", hook);
41604
+ if (!removed)
41605
+ return { removed: false, reason: `no '${hook}' entry in ${path}` };
41606
+ writeText(path, text3.endsWith(`
41607
+ `) ? text3 : `${text3}
41608
+ `);
41609
+ return { removed: true };
41610
+ }
41611
+ if (target === "pi") {
41612
+ const pointer = readPiPointer(options);
41613
+ if (pointer.status === "unreadable") {
41614
+ return { removed: false, reason: `${pointer.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
41615
+ }
41616
+ const profile = piProfile(options);
41617
+ if (!profile)
41618
+ return { removed: false, reason: `no Hooks profile is registered for Pi; nothing to remove` };
41619
+ const commands = piCommands(profile);
41620
+ const kept = commands.filter((command) => hookFromCommand(command) !== hook);
41621
+ if (kept.length === commands.length)
41622
+ return { removed: false, reason: `no '${hook}' entry in profile ${profile.agent_id}` };
41623
+ writePiCommands(profile.agent_id, kept);
41624
+ return { removed: true };
41625
+ }
41626
+ if (target === "cursor") {
41627
+ const path = adapterPath("cursor", options);
41628
+ const read3 = readCursorFile(path);
41629
+ if (read3.status === "unreadable") {
41630
+ return { removed: false, reason: `${read3.reason}, so Hooks cannot tell whether '${hook}' is registered; nothing was removed` };
41631
+ }
41632
+ const config2 = read3.status === "verified" ? read3.value : undefined;
41633
+ if (!config2?.hooks)
41634
+ return { removed: false, reason: `no '${hook}' entry in ${path}` };
41635
+ let removed = false;
41636
+ const hooks = {};
41637
+ for (const key2 of Object.keys(config2.hooks)) {
41638
+ const entries = config2.hooks[key2];
41639
+ if (!Array.isArray(entries)) {
41640
+ hooks[key2] = entries;
41641
+ continue;
41642
+ }
41643
+ const kept = entries.filter((entry) => {
41644
+ if (typeof entry?.command !== "string" || hookFromCommand(entry.command) !== hook)
41645
+ return true;
41646
+ removed = true;
41647
+ return false;
41648
+ });
41649
+ if (kept.length > 0)
41650
+ hooks[key2] = kept;
41651
+ }
41652
+ if (!removed)
41653
+ return { removed: false, reason: `no '${hook}' entry in ${path}` };
41654
+ const next = { ...config2, hooks };
41655
+ if (Object.keys(hooks).length === 0)
41656
+ delete next.hooks;
41657
+ writeText(path, `${JSON.stringify(next, null, 2)}
41658
+ `);
41659
+ return { removed: true };
41660
+ }
41661
+ const bundle = adapterPath("muse", options, hook);
41662
+ const manifestPath = join22(bundle, ".muse-plugin", "plugin.json");
41663
+ const hadBundle = existsSync13(manifestPath);
41664
+ const bundleNote = hadBundle ? `the bundle at ${bundle} was left in place` : `no bundle was present at ${bundle}`;
41665
+ const pluginId2 = `hasna-hook-${hook}`;
41666
+ const result = (options.run ?? defaultRunner)("muse", ["plugins", "remove", pluginId2, "--json"]);
41667
+ if (result.notFound) {
41668
+ const muse = museOwnFiles(options);
41669
+ return {
41670
+ removed: false,
41671
+ reason: muse.present ? `Refused: Muse's own store is here (${muse.found.join(", ")}), but the \`muse\` command is not on PATH, so '${hook}' cannot be unregistered from it and may still run; ${bundleNote}. Run \`muse plugins remove ${pluginId2}\` where the Muse command is available.` : `Refused: Muse is not installed here, so '${hook}' cannot be unregistered from Muse's own store; ${bundleNote}. Run \`muse plugins remove ${pluginId2}\` on a station with Muse.`
41672
+ };
41673
+ }
41674
+ const refusal3 = result.status === 0 ? undefined : museDiagnostic(result);
41675
+ const alreadyGone = refusal3 !== undefined && /unknown-plugin|not installed/i.test(refusal3);
41676
+ if (refusal3 !== undefined && !alreadyGone) {
41677
+ return {
41678
+ removed: false,
41679
+ reason: `Refused: \`muse plugins remove ${pluginId2}\` failed (${refusal3}); ${bundleNote}.`
41680
+ };
41681
+ }
41682
+ removeMuseBundle(bundle);
41683
+ return {
41684
+ removed: true,
41685
+ bundleRemoved: hadBundle,
41686
+ reason: alreadyGone ? `Muse did not carry ${pluginId2}; ${hadBundle ? `the bundle at ${bundle} was removed` : `no bundle was present at ${bundle}`}` : hadBundle ? `unregistered ${pluginId2} from Muse and removed ${bundle}` : `unregistered ${pluginId2} from Muse; no bundle was present at ${bundle}`
41687
+ };
41688
+ } catch (error61) {
41689
+ return { removed: false, reason: `${target}: the removal failed (${redactedDiagnostic(messageOf(error61))}); nothing was removed` };
41690
+ }
41691
+ }
41692
+ var ADAPTER_TARGETS, defaultRunner = (command, args) => {
41693
+ const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 4 * 1024 * 1024 });
41694
+ return {
41695
+ status: result.status ?? 1,
41696
+ stdout: result.stdout ?? "",
41697
+ stderr: result.stderr ?? "",
41698
+ notFound: result.error?.code === "ENOENT"
41699
+ };
41700
+ }, HOOK_COMMAND_RE, TOML_HEADER_RE, KIMI_HOOK_HEADER_RE, PI_PREFERENCE_KEY = "hasna-pi-hooks";
41701
+ var init_target_adapters = __esm(() => {
41702
+ init_profiles();
41703
+ init_targets();
41704
+ ADAPTER_TARGETS = ["muse", "kimi", "pi", "cursor"];
41705
+ HOOK_COMMAND_RE = /^hooks run ([\w-]+)(?:\s|$)/;
41706
+ TOML_HEADER_RE = /^\s*\[\[?[^\]]/;
41707
+ KIMI_HOOK_HEADER_RE = /^\s*\[\[hooks\]\]\s*$/;
40639
41708
  });
40640
41709
 
40641
41710
  // src/lib/installer.ts
@@ -40645,6 +41714,7 @@ __export(exports_installer, {
40645
41714
  uninstallHook: () => uninstallHook,
40646
41715
  scanStaleRegistrations: () => scanStaleRegistrations,
40647
41716
  removeHook: () => removeHook,
41717
+ removeFailureMessage: () => removeFailureMessage,
40648
41718
  removeCodewithHookEntry: () => removeCodewithHookEntry,
40649
41719
  pruneStaleRegistrations: () => pruneStaleRegistrations,
40650
41720
  previewNativeSafetyRegistration: () => previewNativeSafetyRegistration,
@@ -40661,11 +41731,12 @@ __export(exports_installer, {
40661
41731
  getInstalledHooks: () => getInstalledHooks,
40662
41732
  getHookPath: () => getHookPath,
40663
41733
  detectRewriteConflict: () => detectRewriteConflict,
40664
- buildCodewithTomlFragment: () => buildCodewithTomlFragment
41734
+ buildCodewithTomlFragment: () => buildCodewithTomlFragment,
41735
+ adapterOptions: () => adapterOptions
40665
41736
  });
40666
- import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync as readdirSync4, realpathSync as realpathSync7, rmdirSync as rmdirSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync7 } from "fs";
40667
- import { join as join20, dirname as dirname9, basename as basename9, resolve as resolve28 } from "path";
40668
- import { homedir as homedir8 } from "os";
41737
+ import { existsSync as existsSync14, mkdirSync as mkdirSync12, readFileSync as readFileSync13, readdirSync as readdirSync12, realpathSync as realpathSync7, rmdirSync as rmdirSync4, unlinkSync as unlinkSync6, writeFileSync as writeFileSync10 } from "fs";
41738
+ import { join as join24, dirname as dirname16, basename as basename12, resolve as resolve28 } from "path";
41739
+ import { homedir as homedir9 } from "os";
40669
41740
  import { fileURLToPath as fileURLToPath3 } from "url";
40670
41741
  function normalizeHookName(name) {
40671
41742
  return name.startsWith("hook-") ? name : `hook-${name}`;
@@ -40683,15 +41754,6 @@ function removeHookEntriesByName(entries, hookName) {
40683
41754
  return kept.length === entry.hooks.length ? [entry] : kept.length ? [{ ...entry, hooks: kept }] : [];
40684
41755
  });
40685
41756
  }
40686
- function getTargetSettingsDir(target) {
40687
- if (target === "codex")
40688
- return ".codex";
40689
- if (target === "codewith")
40690
- return ".codewith";
40691
- if (target === "gemini")
40692
- return ".gemini";
40693
- return ".claude";
40694
- }
40695
41757
  function getGlobalSettingsPathOverride(target) {
40696
41758
  if (target === "codex")
40697
41759
  return process.env.HASNA_HOOKS_CODEX_SETTINGS_PATH ?? (process.env.CODEX_HOME ? resolve28(process.env.CODEX_HOME, "hooks.json") : undefined);
@@ -40699,34 +41761,38 @@ function getGlobalSettingsPathOverride(target) {
40699
41761
  return process.env.HASNA_HOOKS_CLAUDE_SETTINGS_PATH ?? (process.env.CLAUDE_CONFIG_DIR ? resolve28(process.env.CLAUDE_CONFIG_DIR, "settings.json") : undefined);
40700
41762
  if (target === "gemini")
40701
41763
  return process.env.HASNA_HOOKS_GEMINI_SETTINGS_PATH;
41764
+ if (target === "qwen")
41765
+ return process.env.HASNA_HOOKS_QWEN_SETTINGS_PATH;
41766
+ if (target === "codewith")
41767
+ return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH;
40702
41768
  return;
40703
41769
  }
41770
+ function capabilityOptions(scope, hook) {
41771
+ return { scope, home: homedir9(), cwd: process.cwd(), env: process.env, ...hook ? { hook } : {} };
41772
+ }
41773
+ function adapterOptions(scope, home, run) {
41774
+ return { scope, home: home ?? process.env.HOME ?? homedir9(), cwd: process.cwd(), env: process.env, ...run ? { run } : {} };
41775
+ }
40704
41776
  function getSettingsPath(scope = "global", target = "claude", codewithConfigPath) {
40705
41777
  if (target === "codewith" && codewithConfigPath)
40706
41778
  return codewithConfigPath;
40707
- if (target === "codewith" && scope === "global" && process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH) {
40708
- return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH;
40709
- }
40710
41779
  const globalOverride = scope === "global" ? getGlobalSettingsPathOverride(target) : undefined;
40711
41780
  if (globalOverride)
40712
41781
  return globalOverride;
40713
- const dir = getTargetSettingsDir(target);
40714
- if (target === "codex")
40715
- return join20(scope === "project" ? process.cwd() : homedir8(), dir, "hooks.json");
40716
- if (scope === "project") {
40717
- return target === "codewith" ? join20(process.cwd(), dir, "config.toml") : join20(process.cwd(), dir, "settings.json");
40718
- }
40719
- return target === "codewith" ? join20(homedir8(), dir, "config.toml") : join20(homedir8(), dir, "settings.json");
41782
+ const capabilities = getTargetCapabilities(target, capabilityOptions(scope));
41783
+ if (capabilities)
41784
+ return capabilities.configPath;
41785
+ return join24(homedir9(), ".claude", "settings.json");
40720
41786
  }
40721
41787
  function getHookPath(name) {
40722
41788
  const shortName = shortHookName(name);
40723
41789
  const resolved = resolveHookDir(shortName);
40724
41790
  if (resolved)
40725
41791
  return resolved;
40726
- return join20(HOOKS_DIR, normalizeHookName(shortName));
41792
+ return join24(HOOKS_DIR, normalizeHookName(shortName));
40727
41793
  }
40728
41794
  function hookExists(name) {
40729
- return existsSync12(getHookPath(name));
41795
+ return existsSync14(getHookPath(name));
40730
41796
  }
40731
41797
  function readSettings(scope = "global", target = "claude") {
40732
41798
  const path = getSettingsPath(scope, target);
@@ -40734,8 +41800,8 @@ function readSettings(scope = "global", target = "claude") {
40734
41800
  return readCodexSettings(path);
40735
41801
  let reason2 = "cannot be read";
40736
41802
  try {
40737
- if (existsSync12(path)) {
40738
- const text3 = readFileSync7(path, "utf-8");
41803
+ if (existsSync14(path)) {
41804
+ const text3 = readFileSync13(path, "utf-8");
40739
41805
  reason2 = "is not valid JSON";
40740
41806
  const value = JSON.parse(text3);
40741
41807
  reason2 = "does not hold a JSON object";
@@ -40751,7 +41817,7 @@ function readSettings(scope = "global", target = "claude") {
40751
41817
  console.warn("[hooks] Cannot read hook settings; repair the selected file before installation.");
40752
41818
  }
40753
41819
  const empty = {};
40754
- if (!existsSync12(path))
41820
+ if (!existsSync14(path))
40755
41821
  settingsPreimages.set(empty, { path, text: null });
40756
41822
  else
40757
41823
  unreadableSettings.set(empty, { path, reason: reason2 });
@@ -40759,23 +41825,23 @@ function readSettings(scope = "global", target = "claude") {
40759
41825
  }
40760
41826
  function unreadableSettingsRefusal(settings, path) {
40761
41827
  const captured = settingsPreimages.get(settings);
40762
- if (captured?.path === path && captured.text !== null || !existsSync12(path))
41828
+ if (captured?.path === path && captured.text !== null || !existsSync14(path))
40763
41829
  return;
40764
41830
  const failed = unreadableSettings.get(settings);
40765
41831
  const reason2 = captured?.path === path ? "was created after Hooks read the settings" : failed?.path === path ? failed.reason : "was not read as a settings object";
40766
41832
  return new ClaudeSettingsRefusal("settings_unreadable", `${path} ${reason2}, so Hooks wrote nothing. Repair the file or move it aside, then retry.`);
40767
41833
  }
40768
41834
  function settingsIdentity(path) {
40769
- if (existsSync12(path))
41835
+ if (existsSync14(path))
40770
41836
  return realpathSync7(path);
40771
- return existsSync12(dirname9(path)) ? join20(realpathSync7(dirname9(path)), basename9(path)) : resolve28(path);
41837
+ return existsSync14(dirname16(path)) ? join24(realpathSync7(dirname16(path)), basename12(path)) : resolve28(path);
40772
41838
  }
40773
41839
  function coordinatesWithSkills(path, target) {
40774
- return target === "claude" && settingsIdentity(path) === settingsIdentity(join20(homedir8(), ".claude/settings.json"));
41840
+ return target === "claude" && settingsIdentity(path) === settingsIdentity(join24(homedir9(), ".claude/settings.json"));
40775
41841
  }
40776
41842
  function planClaudeSettingsWrite(before, after, scope = "global") {
40777
41843
  if (coordinatesWithSkills(getSettingsPath(scope, "claude"), "claude"))
40778
- planCoordinatedClaudeSettings(before, after, { home: homedir8() });
41844
+ planCoordinatedClaudeSettings(before, after, { home: homedir9() });
40779
41845
  }
40780
41846
  function writerRefusal(error61) {
40781
41847
  return { error: error61 instanceof Error ? error61.message : "Unknown error", ...error61 instanceof ClaudeSettingsRefusal ? { code: error61.code } : {} };
@@ -40797,21 +41863,21 @@ function writeSettings(settings, scope = "global", target = "claude", expectedSe
40797
41863
  const before = settingsPreimages.get(settings);
40798
41864
  if (!before || before.path !== path)
40799
41865
  throw new Error("Claude settings require a valid captured preimage before installation.");
40800
- const current2 = existsSync12(path) ? readFileSync7(path, "utf8") : null;
41866
+ const current2 = existsSync14(path) ? readFileSync13(path, "utf8") : null;
40801
41867
  if (current2 !== before.text)
40802
41868
  throw new Error("Claude settings changed during installation; no settings were written.");
40803
41869
  if (coordinateClaudeSettings(before.text, JSON.stringify(settings, null, 2) + `
40804
- `, { home: homedir8() }, beforeWrite))
41870
+ `, { home: homedir9() }, beforeWrite))
40805
41871
  return;
40806
41872
  }
40807
41873
  if (expectedSettingsSha256 !== undefined)
40808
41874
  return writeHookSettingsPreimage(path, settings, captured.text, beforeWrite);
40809
41875
  beforeWrite?.();
40810
- const dir = dirname9(path);
40811
- if (!existsSync12(dir)) {
40812
- mkdirSync6(dir, { recursive: true });
41876
+ const dir = dirname16(path);
41877
+ if (!existsSync14(dir)) {
41878
+ mkdirSync12(dir, { recursive: true });
40813
41879
  }
40814
- writeFileSync7(path, JSON.stringify(settings, null, 2) + `
41880
+ writeFileSync10(path, JSON.stringify(settings, null, 2) + `
40815
41881
  `);
40816
41882
  }
40817
41883
  function getTargetEventName(internalEvent, target) {
@@ -40820,7 +41886,7 @@ function getTargetEventName(internalEvent, target) {
40820
41886
  function isEventSupported(internalEvent, target) {
40821
41887
  return getTargetEventName(internalEvent, target) !== null;
40822
41888
  }
40823
- function tomlString(value) {
41889
+ function tomlString2(value) {
40824
41890
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
40825
41891
  }
40826
41892
  function codewithMatcher(matcher) {
@@ -40894,8 +41960,8 @@ function buildCodewithTomlFragment(name, profile, mementos) {
40894
41960
  `[[hooks.${eventKey}]]`
40895
41961
  ];
40896
41962
  if (matcher)
40897
- lines.push(`matcher = ${tomlString(matcher)}`);
40898
- lines.push("", `[[hooks.${eventKey}.hooks]]`, `type = "command"`, `command = ${tomlString(command)}`, `timeout = ${codewithTimeout(shortName)}`, `statusMessage = ${tomlString(codewithStatusMessage(shortName))}`);
41963
+ lines.push(`matcher = ${tomlString2(matcher)}`);
41964
+ lines.push("", `[[hooks.${eventKey}.hooks]]`, `type = "command"`, `command = ${tomlString2(command)}`, `timeout = ${codewithTimeout(shortName)}`, `statusMessage = ${tomlString2(codewithStatusMessage(shortName))}`);
40899
41965
  fragments.push(lines.join(`
40900
41966
  `));
40901
41967
  }
@@ -40907,21 +41973,21 @@ function buildCodewithTomlFragment(name, profile, mementos) {
40907
41973
  function readCodewithConfig(scope, configPath) {
40908
41974
  const path = getSettingsPath(scope, "codewith", configPath);
40909
41975
  try {
40910
- return existsSync12(path) ? readFileSync7(path, "utf-8") : "";
41976
+ return existsSync14(path) ? readFileSync13(path, "utf-8") : "";
40911
41977
  } catch {
40912
41978
  return "";
40913
41979
  }
40914
41980
  }
40915
41981
  function appendCodewithFragment(fragment, scope, configPath) {
40916
41982
  const path = getSettingsPath(scope, "codewith", configPath);
40917
- const dir = dirname9(path);
40918
- if (!existsSync12(dir))
40919
- mkdirSync6(dir, { recursive: true });
40920
- const existing = existsSync12(path) ? readFileSync7(path, "utf-8") : "";
41983
+ const dir = dirname16(path);
41984
+ if (!existsSync14(dir))
41985
+ mkdirSync12(dir, { recursive: true });
41986
+ const existing = existsSync14(path) ? readFileSync13(path, "utf-8") : "";
40921
41987
  const sep10 = existing.trim() ? `
40922
41988
 
40923
41989
  ` : "";
40924
- writeFileSync7(path, `${existing.replace(/\s*$/, "")}${sep10}${fragment}`);
41990
+ writeFileSync10(path, `${existing.replace(/\s*$/, "")}${sep10}${fragment}`);
40925
41991
  return path;
40926
41992
  }
40927
41993
  function detectConflict(name, scope, target) {
@@ -40964,14 +42030,59 @@ function detectRewriteConflict(name, scope, target, lookup = getHook) {
40964
42030
  }
40965
42031
  return;
40966
42032
  }
42033
+ function installForAdapter(shortName, scope, overwrite, target, events3, timeoutSeconds, profile, mementos) {
42034
+ const stopEvent = getTargetCapabilities(target, capabilityOptions(scope, shortName))?.stopEvent ?? "turn-end";
42035
+ const unsupported = events3.filter((event) => event !== "Stop");
42036
+ if (events3.length === 0 || unsupported.length > 0) {
42037
+ return {
42038
+ hook: shortName,
42039
+ success: false,
42040
+ scope,
42041
+ target,
42042
+ error: `Refused: '${shortName}' runs on ${events3.length > 0 ? events3.join(", ") : "no event"}, and target '${target}' only has the ${stopEvent} turn-end event. Install it on claude, codex, gemini, codewith or qwen; a harness config is never given an event it does not carry.`
42043
+ };
42044
+ }
42045
+ const options = adapterOptions(scope);
42046
+ const registered = readAdapterRegistrations(target, options).some((entry) => entry.hook === shortName);
42047
+ if (registered && !overwrite) {
42048
+ return { hook: shortName, success: false, error: "Already installed. Use --overwrite to replace.", scope, target };
42049
+ }
42050
+ if (registered)
42051
+ removeFromAdapter(target, shortName, options);
42052
+ const conflict = detectConflict(shortName, scope, target);
42053
+ const command = (profile ? `hooks run ${shortName} --profile ${profile}` : `hooks run ${shortName}`) + ` --target ${target}` + mementosCommandSuffix(mementos);
42054
+ const outcome = installInAdapter(target, shortName, command, options, timeoutSeconds);
42055
+ if (!outcome.ok) {
42056
+ return { hook: shortName, success: false, error: outcome.error, scope, target, ...outcome.configPath ? { configPath: outcome.configPath } : {} };
42057
+ }
42058
+ const note = [outcome.note, targetInstallNote(target)].filter(Boolean).join(" ");
42059
+ return {
42060
+ hook: shortName,
42061
+ success: true,
42062
+ scope,
42063
+ target,
42064
+ applied: true,
42065
+ conflict,
42066
+ configPath: outcome.configPath,
42067
+ ...note ? { note } : {}
42068
+ };
42069
+ }
40967
42070
  function installForTarget(name, scope, overwrite, target, profile, codewithMode = "fragment", codewithConfigPath, mementos, expectedSettingsSha256, beforeWrite) {
40968
42071
  const shortName = shortHookName(name);
40969
- if (isNativeSafetyName(shortName) && (profile || target === "gemini" || target === "codewith" && codewithMode === "write")) {
42072
+ if (isNativeSafetyName(shortName) && (profile || target === "gemini" || isAdapterTarget(target) || target === "codewith" && codewithMode === "write")) {
40970
42073
  return { hook: shortName, success: false, error: "Bundled native safety guards support Claude/Codex and managed Codewith fragments, without registry profiles.", target };
40971
42074
  }
40972
42075
  if (!isNativeSafetyName(shortName) && !hookExists(shortName)) {
40973
42076
  return { hook: shortName, success: false, error: `Hook '${shortName}' not found`, target };
40974
42077
  }
42078
+ const meta3 = isNativeSafetyName(shortName) ? getHook(shortName) : resolveHookMeta(shortName);
42079
+ const events3 = meta3 ? getHookEvents(meta3) : [];
42080
+ const capabilityRefusal = installCapabilityRefusal(shortName, target, { events: events3, requiresFinalMessage: meta3?.requiresFinalMessage === true, requiresBlock: meta3?.requiresBlock === true }, capabilityOptions(scope, shortName));
42081
+ if (capabilityRefusal)
42082
+ return { hook: shortName, success: false, error: capabilityRefusal, scope, target };
42083
+ if (isAdapterTarget(target)) {
42084
+ return installForAdapter(shortName, scope, overwrite, target, events3, meta3?.timeoutSeconds ?? 10, profile, mementos);
42085
+ }
40975
42086
  if (target === "codewith") {
40976
42087
  try {
40977
42088
  const fragment = buildCodewithTomlFragment(shortName, profile, mementos);
@@ -41022,7 +42133,8 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
41022
42133
  }
41023
42134
  }
41024
42135
  try {
41025
- const registered = getRegisteredHooksForTarget(scope, target);
42136
+ const settingsTarget = target;
42137
+ const registered = getRegisteredHooksForTarget(scope, settingsTarget);
41026
42138
  if (registered.includes(shortName) && !overwrite) {
41027
42139
  return { hook: shortName, success: false, error: "Already installed. Use --overwrite to replace.", scope, target };
41028
42140
  }
@@ -41031,7 +42143,7 @@ function installForTarget(name, scope, overwrite, target, profile, codewithMode
41031
42143
  if (rewriteConflict) {
41032
42144
  return { hook: shortName, success: false, error: `Refused: ${rewriteConflict}`, scope, target };
41033
42145
  }
41034
- registerHook(shortName, scope, target, profile, mementos, (settings, selectedScope, selectedTarget) => writeSettings(settings, selectedScope, selectedTarget, expectedSettingsSha256, beforeWrite));
42146
+ registerHook(shortName, scope, settingsTarget, profile, mementos, (settings, selectedScope, selectedTarget) => writeSettings(settings, selectedScope, selectedTarget, expectedSettingsSha256, beforeWrite));
41035
42147
  return {
41036
42148
  hook: shortName,
41037
42149
  success: true,
@@ -41255,6 +42367,9 @@ function installHooks(names, options = {}) {
41255
42367
  return names.map((name) => installHook(name, options));
41256
42368
  }
41257
42369
  function getRegisteredHooksForTarget(scope = "global", target = "claude") {
42370
+ if (isAdapterTarget(target)) {
42371
+ return [...new Set(readAdapterRegistrations(target, adapterOptions(scope)).map((entry) => entry.hook))];
42372
+ }
41258
42373
  if (target === "codewith") {
41259
42374
  const config2 = readCodewithConfig(scope);
41260
42375
  const registered2 = [];
@@ -41293,20 +42408,37 @@ function getRegisteredHooksForTarget(scope = "global", target = "claude") {
41293
42408
  function getRegisteredHooks(scope = "global") {
41294
42409
  return getRegisteredHooksForTarget(scope, "claude");
41295
42410
  }
41296
- function removeHook(name, scope = "global", target = "claude") {
42411
+ function removeHook(name, scope = "global", target = "claude", options = {}) {
41297
42412
  const shortName = shortHookName(name);
41298
42413
  if (target === "all") {
41299
- const claudeRemoved = removeHookForTarget(shortName, scope, "claude");
41300
- const geminiRemoved = removeHookForTarget(shortName, scope, "gemini");
41301
- const codexRemoved = removeHookForTarget(shortName, scope, "codex");
41302
- return claudeRemoved || geminiRemoved || codexRemoved;
42414
+ let removedAny = false;
42415
+ for (const candidate of ALL_REMOVABLE_TARGETS) {
42416
+ if (removeHookForTarget(shortName, scope, candidate, options.run))
42417
+ removedAny = true;
42418
+ }
42419
+ return removedAny;
41303
42420
  }
41304
42421
  if (target === "codewith") {
41305
42422
  return false;
41306
42423
  }
41307
- return removeHookForTarget(shortName, scope, target);
42424
+ if (isAdapterTarget(target)) {
42425
+ return removeFromAdapter(target, shortName, adapterOptions(scope, undefined, options.run)).removed;
42426
+ }
42427
+ if (target === "opencode" || target === "sumi") {
42428
+ return false;
42429
+ }
42430
+ return removeHookForTarget(shortName, scope, target, options.run);
41308
42431
  }
41309
- function removeHookForTarget(name, scope, target) {
42432
+ function removeHookForTarget(name, scope, target, run) {
42433
+ if (isAdapterTarget(target)) {
42434
+ const options = adapterOptions(scope, undefined, run);
42435
+ const state = readAdapterState(target, options);
42436
+ if (state.status !== "verified")
42437
+ return false;
42438
+ if (!adapterStateCarries(state, name))
42439
+ return false;
42440
+ return removeFromAdapter(target, name, options).removed;
42441
+ }
41310
42442
  const registered = getRegisteredHooksForTarget(scope, target);
41311
42443
  if (!registered.includes(name)) {
41312
42444
  return false;
@@ -41316,9 +42448,9 @@ function removeHookForTarget(name, scope, target) {
41316
42448
  }
41317
42449
  function readSettingsAt(path) {
41318
42450
  try {
41319
- if (!existsSync12(path))
42451
+ if (!existsSync14(path))
41320
42452
  return;
41321
- const raw = readFileSync7(path, "utf-8");
42453
+ const raw = readFileSync13(path, "utf-8");
41322
42454
  const settings = JSON.parse(raw);
41323
42455
  settingsPreimages.set(settings, { path, text: raw });
41324
42456
  return { raw, settings };
@@ -41354,7 +42486,7 @@ function pruneStaleRegistrations(scope = "global") {
41354
42486
  staleCommandsByEvent.set(finding.event, commands);
41355
42487
  }
41356
42488
  const settings = target === "codex" ? readCodexSettings(path) : parsed.settings;
41357
- if (target === "codex" && readFileSync7(path, "utf8") !== parsed.raw)
42489
+ if (target === "codex" && readFileSync13(path, "utf8") !== parsed.raw)
41358
42490
  throw new Error("Codex settings changed before pruning; retry.");
41359
42491
  for (const [eventKey, commands] of staleCommandsByEvent) {
41360
42492
  const entries = settings.hooks?.[eventKey];
@@ -41380,11 +42512,18 @@ function pruneStaleRegistrations(scope = "global") {
41380
42512
  if (settings.hooks && Object.keys(settings.hooks).length === 0)
41381
42513
  delete settings.hooks;
41382
42514
  const backupPath = `${path}.bak`;
41383
- writeSettings(settings, scope, target, undefined, () => writeFileSync7(backupPath, parsed.raw));
42515
+ writeSettings(settings, scope, target, undefined, () => writeFileSync10(backupPath, parsed.raw));
41384
42516
  results2.push({ file: path, removed: stale, backupPath });
41385
42517
  }
41386
42518
  return results2;
41387
42519
  }
42520
+ function removeFailureMessage(result, hook, suggestions = []) {
42521
+ const notFound = `Hook '${result.name}' not found`;
42522
+ if (result.error && result.error !== notFound)
42523
+ return `\u2717 ${result.error}`;
42524
+ const hint = suggestions.length ? ` \u2014 did you mean: ${suggestions.join(", ")}?` : "";
42525
+ return `\u2717 Hook '${hook}' not found${hint}`;
42526
+ }
41388
42527
  function removeCodewithHookEntry(configText, name) {
41389
42528
  const sections = configText.split(/\n\s*\n/);
41390
42529
  const commandRe = /^command\s*=\s*"([^"\n]+)"$/;
@@ -41441,70 +42580,149 @@ function codewithHasHookEntryInText(configText, name) {
41441
42580
  }
41442
42581
  function codewithHasHookEntry(name, scope = "global") {
41443
42582
  const path = getSettingsPath(scope, "codewith");
41444
- if (!existsSync12(path))
42583
+ if (!existsSync14(path))
41445
42584
  return false;
41446
42585
  try {
41447
- return codewithHasHookEntryInText(readFileSync7(path, "utf-8"), name);
42586
+ return codewithHasHookEntryInText(readFileSync13(path, "utf-8"), name);
41448
42587
  } catch {
41449
42588
  return false;
41450
42589
  }
41451
42590
  }
41452
42591
  function removeStoreDirFailClosed(dir) {
41453
- const entries = readdirSync4(dir, { withFileTypes: true });
42592
+ const entries = readdirSync12(dir, { withFileTypes: true });
41454
42593
  for (const entry of entries) {
41455
42594
  if (entry.isDirectory()) {
41456
- removeStoreDirFailClosed(join20(dir, entry.name));
42595
+ removeStoreDirFailClosed(join24(dir, entry.name));
41457
42596
  }
41458
42597
  }
41459
42598
  for (const entry of entries) {
41460
42599
  if (!entry.isDirectory()) {
41461
- unlinkSync3(join20(dir, entry.name));
42600
+ unlinkSync6(join24(dir, entry.name));
41462
42601
  }
41463
42602
  }
41464
- rmdirSync2(dir);
42603
+ rmdirSync4(dir);
41465
42604
  }
41466
- function uninstallHook(name, scope = "global", target = "claude") {
42605
+ function uninstallHook(name, scope = "global", target = "claude", options = {}) {
41467
42606
  const shortName = shortHookName(name);
42607
+ const adapterOptionsFor = (s) => adapterOptions(s, undefined, options.run);
41468
42608
  const custom2 = readCustomManifest(shortName);
41469
42609
  const bundledMeta = custom2 ? undefined : getHook(shortName);
41470
- const existsInTarget = (t) => getRegisteredHooksForTarget("global", t).includes(shortName) || getRegisteredHooksForTarget("project", t).includes(shortName);
41471
- const registeredClaudeOrGemini = target === "all" ? JSON_SETTINGS_TARGETS.some(existsInTarget) : false;
41472
- const registeredGlobal = registeredClaudeOrGemini || getRegisteredHooksForTarget("global", target === "all" ? "claude" : target).includes(shortName);
41473
- const registeredProject = registeredClaudeOrGemini || getRegisteredHooksForTarget("project", target === "all" ? "claude" : target).includes(shortName);
42610
+ const configuredTargets = target === "all" ? ALL_REMOVABLE_TARGETS : [target];
42611
+ const adapterStates = new Map;
42612
+ const unreadable = [];
42613
+ const notes = [];
42614
+ const withNotes = (result) => notes.length > 0 ? { ...result, notes } : result;
42615
+ const adapterStateFor = (t, s) => {
42616
+ const key2 = `${s}:${t}`;
42617
+ const cached2 = adapterStates.get(key2);
42618
+ if (cached2)
42619
+ return cached2;
42620
+ const state = isAdapterTarget(t) ? readAdapterState(t, adapterOptionsFor(s)) : { status: "verified", registrations: [] };
42621
+ adapterStates.set(key2, state);
42622
+ return state;
42623
+ };
42624
+ const forgetAdapterState = (t, s) => {
42625
+ adapterStates.delete(`${s}:${t}`);
42626
+ };
42627
+ const isRegistered = (s, t) => {
42628
+ if (!isAdapterTarget(t))
42629
+ return getRegisteredHooksForTarget(s, t).includes(shortName);
42630
+ const state = adapterStateFor(t, s);
42631
+ if (state.status === "unverified") {
42632
+ if (state.absent && target === "all") {
42633
+ const note = `${t}: skipped, ${state.reason}`;
42634
+ if (!notes.includes(note))
42635
+ notes.push(note);
42636
+ return false;
42637
+ }
42638
+ const reason2 = `${t} (${s} scope): its config could not be read \u2014 ${state.reason}`;
42639
+ if (!unreadable.includes(reason2))
42640
+ unreadable.push(reason2);
42641
+ return false;
42642
+ }
42643
+ return adapterStateCarries(state, shortName);
42644
+ };
42645
+ const registeredGlobal = configuredTargets.some((t) => isRegistered("global", t));
42646
+ const registeredProject = configuredTargets.some((t) => isRegistered("project", t));
41474
42647
  const codewithOnly = (target === "codewith" || target === "all") && codewithHasHookEntry(shortName, scope);
41475
- if (!custom2 && !bundledMeta && !registeredGlobal && !registeredProject && !codewithOnly) {
41476
- return { name: shortName, removed: false, source: null, settingsScopes: [], storeDirRemoved: false, pinRemoved: false, dbRecordRemoved: false, registrationsRemaining: [], error: `Hook '${shortName}' not found` };
42648
+ if (!custom2 && !bundledMeta && !registeredGlobal && !registeredProject && !codewithOnly && unreadable.length === 0) {
42649
+ return withNotes({ name: shortName, removed: false, source: null, settingsScopes: [], storeDirRemoved: false, pinRemoved: false, dbRecordRemoved: false, registrationsRemaining: [], error: `Hook '${shortName}' not found` });
41477
42650
  }
41478
- const writableTargets = target === "all" ? JSON_SETTINGS_TARGETS : target === "codewith" ? [] : [target];
42651
+ const writableTargets = target === "all" ? ALL_REMOVABLE_TARGETS : target === "codewith" ? [] : [target];
41479
42652
  const scopes = [];
42653
+ const registrationsRemaining = [];
42654
+ const notRemoved = [];
42655
+ const attemptedStores = new Set;
41480
42656
  for (const s of ["global", "project"]) {
41481
42657
  for (const t of writableTargets) {
41482
- if (getRegisteredHooksForTarget(s, t).includes(shortName)) {
42658
+ if (!isRegistered(s, t))
42659
+ continue;
42660
+ if (isAdapterTarget(t)) {
42661
+ const storePath = adapterStorePath(t, adapterOptionsFor(s), shortName);
42662
+ if (attemptedStores.has(storePath))
42663
+ continue;
42664
+ attemptedStores.add(storePath);
42665
+ const before = adapterStateFor(t, s);
42666
+ const disabledInStore = t === "muse" && adapterStateCarries(before, shortName) && !before.registrations.some((entry) => entry.hook === shortName);
42667
+ const outcome = removeFromAdapter(t, shortName, adapterOptionsFor(s));
42668
+ forgetAdapterState(t, s);
42669
+ if (!outcome.removed) {
42670
+ if (!registrationsRemaining.includes(t))
42671
+ registrationsRemaining.push(t);
42672
+ const reason2 = `${t} (${s} scope): ${outcome.reason ?? "the adapter refused the removal"}`;
42673
+ if (!notRemoved.includes(reason2))
42674
+ notRemoved.push(reason2);
42675
+ continue;
42676
+ }
42677
+ if (disabledInStore) {
42678
+ const bundleClause = outcome.bundleRemoved === undefined ? "the plugin was removed from Muse" : outcome.bundleRemoved ? `the plugin and its bundle at ${storePath} were removed` : `the plugin was removed from Muse; no bundle was present at ${storePath}`;
42679
+ const note = `${t} (${s} scope): '${shortName}' is in Muse's store but is not enabled now, and Hooks cannot tell whether it ran; ${bundleClause}.`;
42680
+ if (!notes.includes(note))
42681
+ notes.push(note);
42682
+ } else if (outcome.reason) {
42683
+ const note = `${t} (${s} scope): ${outcome.reason}`;
42684
+ if (!notes.includes(note))
42685
+ notes.push(note);
42686
+ }
42687
+ } else {
41483
42688
  unregisterHook(shortName, s, t);
41484
- if (!scopes.includes(s))
41485
- scopes.push(s);
41486
42689
  }
42690
+ if (!scopes.includes(s))
42691
+ scopes.push(s);
41487
42692
  }
41488
42693
  }
41489
- const registrationsRemaining = [];
41490
42694
  if (target === "codewith" || target === "all") {
41491
42695
  const codewithPath = getSettingsPath(scope, "codewith");
41492
- if (existsSync12(codewithPath)) {
41493
- const before = readFileSync7(codewithPath, "utf-8");
42696
+ if (existsSync14(codewithPath)) {
42697
+ const before = readFileSync13(codewithPath, "utf-8");
41494
42698
  const after = removeCodewithHookEntry(before, shortName);
41495
42699
  if (after.removed) {
41496
- writeFileSync7(codewithPath, after.text, "utf-8");
42700
+ writeFileSync10(codewithPath, after.text, "utf-8");
41497
42701
  }
41498
42702
  if (codewithHasHookEntryInText(after.removed ? after.text : before, shortName)) {
41499
42703
  registrationsRemaining.push("codewith");
41500
42704
  }
41501
42705
  }
41502
42706
  }
42707
+ const blockers = [...unreadable, ...notRemoved];
42708
+ if (blockers.length > 0) {
42709
+ return withNotes({
42710
+ name: shortName,
42711
+ removed: false,
42712
+ source: custom2 ? "custom" : bundledMeta ? "bundled" : "registered-only",
42713
+ settingsScopes: scopes,
42714
+ storeDirRemoved: false,
42715
+ pinRemoved: false,
42716
+ dbRecordRemoved: false,
42717
+ registrationsRemaining,
42718
+ error: `Hook '${shortName}' was not fully uninstalled: ${blockers.join("; ")}. Its store, pin and DB record were preserved because that registration could still run; fix the named cause and retry.`
42719
+ });
42720
+ }
41503
42721
  if (custom2) {
41504
42722
  try {
41505
42723
  removeStoreDirFailClosed(customHookDir(shortName));
41506
42724
  } catch {
41507
- return {
42725
+ return withNotes({
41508
42726
  name: shortName,
41509
42727
  removed: false,
41510
42728
  source: "custom",
@@ -41514,11 +42732,11 @@ function uninstallHook(name, scope = "global", target = "claude") {
41514
42732
  dbRecordRemoved: false,
41515
42733
  registrationsRemaining,
41516
42734
  error: `Hook '${shortName}' store directory could not be removed; trust records preserved (no fail-open)`
41517
- };
42735
+ });
41518
42736
  }
41519
42737
  }
41520
42738
  const { removedPin, removedRecord } = removeHookFromStore(shortName);
41521
- return {
42739
+ return withNotes({
41522
42740
  name: shortName,
41523
42741
  removed: true,
41524
42742
  source: custom2 ? "custom" : bundledMeta ? "bundled" : "registered-only",
@@ -41527,9 +42745,9 @@ function uninstallHook(name, scope = "global", target = "claude") {
41527
42745
  pinRemoved: removedPin,
41528
42746
  dbRecordRemoved: removedRecord,
41529
42747
  registrationsRemaining
41530
- };
42748
+ });
41531
42749
  }
41532
- var __dirname2, HOOKS_DIR, EVENT_MAP, settingsPreimages, unreadableSettings, getInstalledHooks, JSON_SETTINGS_TARGETS;
42750
+ var __dirname2, HOOKS_DIR, CLAUDE_EVENT_MAP, EVENT_MAP, settingsPreimages, unreadableSettings, getInstalledHooks, JSON_SETTINGS_TARGETS, ALL_REMOVABLE_TARGETS;
41533
42751
  var init_installer = __esm(() => {
41534
42752
  init_registry();
41535
42753
  init_native_readiness();
@@ -41542,19 +42760,23 @@ var init_installer = __esm(() => {
41542
42760
  init_native_readiness_command();
41543
42761
  init_claude_skills_coordination();
41544
42762
  init_native_target();
41545
- __dirname2 = dirname9(fileURLToPath3(import.meta.url));
41546
- HOOKS_DIR = existsSync12(join20(__dirname2, "..", "..", "hooks", "hook-gitguard")) ? join20(__dirname2, "..", "..", "hooks") : join20(__dirname2, "..", "hooks");
42763
+ init_targets();
42764
+ init_target_adapters();
42765
+ __dirname2 = dirname16(fileURLToPath3(import.meta.url));
42766
+ HOOKS_DIR = existsSync14(join24(__dirname2, "..", "..", "hooks", "hook-gitguard")) ? join24(__dirname2, "..", "..", "hooks") : join24(__dirname2, "..", "hooks");
42767
+ CLAUDE_EVENT_MAP = {
42768
+ PreToolUse: "PreToolUse",
42769
+ PostToolUse: "PostToolUse",
42770
+ Stop: "Stop",
42771
+ Notification: "Notification",
42772
+ SessionStart: "SessionStart",
42773
+ SessionEnd: "SessionEnd",
42774
+ UserPromptSubmit: "UserPromptSubmit",
42775
+ SubagentStart: null
42776
+ };
41547
42777
  EVENT_MAP = {
41548
- claude: {
41549
- PreToolUse: "PreToolUse",
41550
- PostToolUse: "PostToolUse",
41551
- Stop: "Stop",
41552
- Notification: "Notification",
41553
- SessionStart: "SessionStart",
41554
- SessionEnd: "SessionEnd",
41555
- UserPromptSubmit: "UserPromptSubmit",
41556
- SubagentStart: null
41557
- },
42778
+ claude: CLAUDE_EVENT_MAP,
42779
+ qwen: CLAUDE_EVENT_MAP,
41558
42780
  gemini: {
41559
42781
  PreToolUse: "BeforeTool",
41560
42782
  PostToolUse: "AfterTool",
@@ -41589,21 +42811,22 @@ var init_installer = __esm(() => {
41589
42811
  settingsPreimages = new WeakMap;
41590
42812
  unreadableSettings = new WeakMap;
41591
42813
  getInstalledHooks = getRegisteredHooks;
41592
- JSON_SETTINGS_TARGETS = ["claude", "gemini", "codex"];
42814
+ JSON_SETTINGS_TARGETS = ["claude", "gemini", "codex", "qwen"];
42815
+ ALL_REMOVABLE_TARGETS = [...JSON_SETTINGS_TARGETS, ...ADAPTER_TARGETS];
41593
42816
  });
41594
42817
 
41595
42818
  // src/native-safety.ts
41596
42819
  import { execFile } from "child_process";
41597
- import { createHash as createHash9, randomUUID as randomUUID5 } from "crypto";
41598
- import { closeSync as closeSync5, constants as constants5, existsSync as existsSync13, fstatSync as fstatSync5, fsyncSync, linkSync, lstatSync as lstatSync16, mkdirSync as mkdirSync10, openSync as openSync5, readFileSync as readFileSync8, realpathSync as realpathSync11, renameSync as renameSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync9 } from "fs";
41599
- import { homedir as homedir9 } from "os";
41600
- import { dirname as dirname16, isAbsolute as isAbsolute9, join as join22, resolve as resolve30 } from "path";
42820
+ import { createHash as createHash9, randomUUID as randomUUID7 } from "crypto";
42821
+ import { closeSync as closeSync5, constants as constants5, existsSync as existsSync15, fstatSync as fstatSync5, fsyncSync, linkSync, lstatSync as lstatSync16, mkdirSync as mkdirSync13, openSync as openSync5, readFileSync as readFileSync18, realpathSync as realpathSync11, renameSync as renameSync7, unlinkSync as unlinkSync8, writeFileSync as writeFileSync11 } from "fs";
42822
+ import { homedir as homedir10 } from "os";
42823
+ import { dirname as dirname23, isAbsolute as isAbsolute9, join as join32, resolve as resolve30 } from "path";
41601
42824
  function safeDirectory(path) {
41602
- for (let cursor = path;; cursor = dirname16(cursor)) {
42825
+ for (let cursor = path;; cursor = dirname23(cursor)) {
41603
42826
  const stat2 = lstatSync16(cursor);
41604
42827
  if (!stat2.isDirectory() || !owner2(stat2.uid) || stat2.mode & 18)
41605
42828
  throw new NativeSafetyError("binding_invalid");
41606
- if (dirname16(cursor) === cursor)
42829
+ if (dirname23(cursor) === cursor)
41607
42830
  return;
41608
42831
  }
41609
42832
  }
@@ -41614,13 +42837,13 @@ function canonicalHome(home) {
41614
42837
  return resolve30(home);
41615
42838
  }
41616
42839
  function readOwned(path) {
41617
- safeDirectory(dirname16(path));
42840
+ safeDirectory(dirname23(path));
41618
42841
  const fd = openSync5(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
41619
42842
  try {
41620
42843
  const stat2 = fstatSync5(fd);
41621
42844
  if (!stat2.isFile() || !owner2(stat2.uid) || stat2.mode & 63 || stat2.size > 32768)
41622
42845
  throw new NativeSafetyError("binding_invalid");
41623
- const value = readFileSync8(fd, "utf8");
42846
+ const value = readFileSync18(fd, "utf8");
41624
42847
  if (Buffer.byteLength(value) > 32768)
41625
42848
  throw new NativeSafetyError("binding_invalid");
41626
42849
  return value;
@@ -41656,10 +42879,10 @@ function nativeSafetyRecordText(command) {
41656
42879
  return JSON.stringify(record6) + `
41657
42880
  `;
41658
42881
  }
41659
- function readNativeSafetyRegistration(home = homedir9()) {
42882
+ function readNativeSafetyRegistration(home = homedir10()) {
41660
42883
  try {
41661
42884
  home = canonicalHome(home);
41662
- const path = join22(home, ".hasna/hooks/native", filename), text3 = readOwned(path);
42885
+ const path = join32(home, ".hasna/hooks/native", filename), text3 = readOwned(path);
41663
42886
  return { record: parseSumiRecord(text3, home), sha256: hash(text3), path, text: text3 };
41664
42887
  } catch (error61) {
41665
42888
  if (error61 instanceof NativeSafetyError)
@@ -41667,9 +42890,9 @@ function readNativeSafetyRegistration(home = homedir9()) {
41667
42890
  throw new NativeSafetyError(error61?.code === "ENOENT" ? "binding_missing" : "binding_invalid");
41668
42891
  }
41669
42892
  }
41670
- function nativeSafetyBindingIntegrityReason(home = homedir9()) {
42893
+ function nativeSafetyBindingIntegrityReason(home = homedir10()) {
41671
42894
  try {
41672
- const path = join22(canonicalHome(home), ".hasna/hooks/native", filename);
42895
+ const path = join32(canonicalHome(home), ".hasna/hooks/native", filename);
41673
42896
  const stat2 = lstatSync16(path);
41674
42897
  if (!stat2.isFile())
41675
42898
  return "the saved binding is not a regular file";
@@ -41685,20 +42908,20 @@ function nativeSafetyBindingIntegrityReason(home = homedir9()) {
41685
42908
  }
41686
42909
  }
41687
42910
  function registerNativeSafety(options = {}) {
41688
- const home = canonicalHome(options.home ?? homedir9());
42911
+ const home = canonicalHome(options.home ?? homedir10());
41689
42912
  const text3 = nativeSafetyRecordText(options.command ?? installedSumiNativeSafetyCommand());
41690
42913
  parseSumiRecord(text3, home);
41691
- for (const dir of [join22(home, ".hasna"), join22(home, ".hasna/hooks"), join22(home, ".hasna/hooks/native")]) {
42914
+ for (const dir of [join32(home, ".hasna"), join32(home, ".hasna/hooks"), join32(home, ".hasna/hooks/native")]) {
41692
42915
  try {
41693
- mkdirSync10(dir, { mode: 448 });
41694
- syncDirectory(dirname16(dir));
42916
+ mkdirSync13(dir, { mode: 448 });
42917
+ syncDirectory(dirname23(dir));
41695
42918
  } catch (error61) {
41696
42919
  if (error61.code !== "EEXIST")
41697
42920
  throw error61;
41698
42921
  }
41699
42922
  safeDirectory(dir);
41700
42923
  }
41701
- const directory3 = join22(home, ".hasna/hooks/native"), path = join22(directory3, filename), lock = path + ".lock";
42924
+ const directory3 = join32(home, ".hasna/hooks/native"), path = join32(directory3, filename), lock = path + ".lock";
41702
42925
  let lockFD;
41703
42926
  try {
41704
42927
  lockFD = openSync5(lock, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY, 384);
@@ -41707,9 +42930,9 @@ function registerNativeSafety(options = {}) {
41707
42930
  }
41708
42931
  const lockIdentity = fstatSync5(lockFD);
41709
42932
  let temporaryIdentity;
41710
- const temporary = join22(directory3, `.${filename}.${randomUUID5()}`);
42933
+ const temporary = join32(directory3, `.${filename}.${randomUUID7()}`);
41711
42934
  try {
41712
- writeFileSync9(lockFD, JSON.stringify({ pid: process.pid, expectedSHA256: options.expectedSHA256 ?? "absent" }));
42935
+ writeFileSync11(lockFD, JSON.stringify({ pid: process.pid, expectedSHA256: options.expectedSHA256 ?? "absent" }));
41713
42936
  fsyncSync(lockFD);
41714
42937
  syncDirectory(directory3);
41715
42938
  let before;
@@ -41725,7 +42948,7 @@ function registerNativeSafety(options = {}) {
41725
42948
  throw new NativeSafetyError("binding_changed");
41726
42949
  if (before) {
41727
42950
  const backup = path + ".before-" + before.sha256;
41728
- if (existsSync13(backup)) {
42951
+ if (existsSync15(backup)) {
41729
42952
  if (hash(readOwned(backup)) !== before.sha256)
41730
42953
  throw new NativeSafetyError("binding_changed");
41731
42954
  } else {
@@ -41734,7 +42957,7 @@ function registerNativeSafety(options = {}) {
41734
42957
  throw new NativeSafetyError("binding_changed");
41735
42958
  const fd2 = openSync5(backup, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY, 384);
41736
42959
  try {
41737
- writeFileSync9(fd2, original);
42960
+ writeFileSync11(fd2, original);
41738
42961
  fsyncSync(fd2);
41739
42962
  } finally {
41740
42963
  closeSync5(fd2);
@@ -41745,7 +42968,7 @@ function registerNativeSafety(options = {}) {
41745
42968
  const fd = openSync5(temporary, constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY, 384);
41746
42969
  try {
41747
42970
  temporaryIdentity = fstatSync5(fd);
41748
- writeFileSync9(fd, text3);
42971
+ writeFileSync11(fd, text3);
41749
42972
  fsyncSync(fd);
41750
42973
  } finally {
41751
42974
  closeSync5(fd);
@@ -41754,11 +42977,11 @@ function registerNativeSafety(options = {}) {
41754
42977
  if (hash(readOwned(path)) !== before.sha256)
41755
42978
  throw new NativeSafetyError("binding_changed");
41756
42979
  options.beforeWrite?.();
41757
- renameSync5(temporary, path);
42980
+ renameSync7(temporary, path);
41758
42981
  } else {
41759
42982
  options.beforeWrite?.();
41760
42983
  linkSync(temporary, path);
41761
- unlinkSync6(temporary);
42984
+ unlinkSync8(temporary);
41762
42985
  }
41763
42986
  syncDirectory(directory3);
41764
42987
  const after = readNativeSafetyRegistration(home);
@@ -41769,11 +42992,11 @@ function registerNativeSafety(options = {}) {
41769
42992
  closeSync5(lockFD);
41770
42993
  const currentTemporary = lstatSync16(temporary, { throwIfNoEntry: false });
41771
42994
  if (temporaryIdentity && currentTemporary?.dev === temporaryIdentity.dev && currentTemporary.ino === temporaryIdentity.ino)
41772
- unlinkSync6(temporary);
42995
+ unlinkSync8(temporary);
41773
42996
  const currentLock = lstatSync16(lock, { throwIfNoEntry: false });
41774
42997
  if (currentLock?.dev !== lockIdentity.dev || currentLock.ino !== lockIdentity.ino)
41775
42998
  throw new NativeSafetyError("binding_changed");
41776
- unlinkSync6(lock);
42999
+ unlinkSync8(lock);
41777
43000
  syncDirectory(directory3);
41778
43001
  }
41779
43002
  }
@@ -41831,7 +43054,7 @@ async function evaluateRecord(event, record6, signal, executionAgent) {
41831
43054
  } catch {}
41832
43055
  throw new NativeSafetyError("guard_failed");
41833
43056
  }
41834
- async function verifyNativeSafetyCommand(command, home = homedir9(), guard = "trash-guard") {
43057
+ async function verifyNativeSafetyCommand(command, home = homedir10(), guard = "trash-guard") {
41835
43058
  if (guard !== "trash-guard" && guard !== "workspace-repos-guard")
41836
43059
  throw new NativeSafetyError("input_invalid");
41837
43060
  home = canonicalHome(home);
@@ -41839,7 +43062,7 @@ async function verifyNativeSafetyCommand(command, home = homedir9(), guard = "tr
41839
43062
  const binding = nativeSafetyCommandBinding(command);
41840
43063
  if (binding?.name !== guard || binding.home !== home)
41841
43064
  throw new NativeSafetyError("binding_invalid");
41842
- const root = join22(home, ".hasna", "repos", "clones"), probe2 = join22(root, ".hasna-workspace-repos-verification-only");
43065
+ const root = join32(home, ".hasna", "repos", "clones"), probe2 = join32(root, ".hasna-workspace-repos-verification-only");
41843
43066
  const verdict2 = await evaluateRecord({
41844
43067
  hook_event_name: "PreToolUse",
41845
43068
  tool_name: "Bash",
@@ -41855,7 +43078,7 @@ async function verifyNativeSafetyCommand(command, home = homedir9(), guard = "tr
41855
43078
  if (verdict.decision !== "rewrite")
41856
43079
  throw new NativeSafetyError("guard_failed", verdict.decision === "deny" ? verdict.reason.slice(0, 512) : undefined);
41857
43080
  }
41858
- async function verifyNativeSafetyRegistration(home = homedir9()) {
43081
+ async function verifyNativeSafetyRegistration(home = homedir10()) {
41859
43082
  const before = readNativeSafetyRegistration(home);
41860
43083
  await verifyNativeSafetyCommand(before.record.command, home);
41861
43084
  const after = readNativeSafetyRegistration(home);
@@ -41863,7 +43086,7 @@ async function verifyNativeSafetyRegistration(home = homedir9()) {
41863
43086
  throw new NativeSafetyError("binding_changed");
41864
43087
  return { path: before.path, sha256: before.sha256 };
41865
43088
  }
41866
- async function verifyNativeSafetyExecutionRegistration(home = homedir9()) {
43089
+ async function verifyNativeSafetyExecutionRegistration(home = homedir10()) {
41867
43090
  const before = readNativeSafetyRegistration(home);
41868
43091
  const verdict = await evaluateNativeSafetyForExecution({
41869
43092
  hook_event_name: "PreToolUse",
@@ -41901,10 +43124,10 @@ __export(exports_native_safety_registration, {
41901
43124
  applyNativeReadinessRegistration: () => applyNativeReadinessRegistration,
41902
43125
  NativeRegistrationError: () => NativeRegistrationError
41903
43126
  });
41904
- import { createHash as createHash18, randomUUID as randomUUID7 } from "crypto";
41905
- import { constants as constants9, closeSync as closeSync8, fstatSync as fstatSync8, fsyncSync as fsyncSync5, lstatSync as lstatSync18, mkdirSync as mkdirSync12, openSync as openSync8, readFileSync as readFileSync13, realpathSync as realpathSync14, writeFileSync as writeFileSync10 } from "fs";
41906
- import { basename as basename12, dirname as dirname23, isAbsolute as isAbsolute14, join as join24, relative as relative2, resolve as resolve31 } from "path";
41907
- import { homedir as homedir10 } from "os";
43127
+ import { createHash as createHash18, randomUUID as randomUUID8 } from "crypto";
43128
+ import { constants as constants9, closeSync as closeSync8, fstatSync as fstatSync8, fsyncSync as fsyncSync5, lstatSync as lstatSync18, mkdirSync as mkdirSync14, openSync as openSync8, readFileSync as readFileSync20, realpathSync as realpathSync14, writeFileSync as writeFileSync12 } from "fs";
43129
+ import { basename as basename16, dirname as dirname27, isAbsolute as isAbsolute14, join as join34, relative as relative2, resolve as resolve31 } from "path";
43130
+ import { homedir as homedir11 } from "os";
41908
43131
  function canonical9(value) {
41909
43132
  if (Array.isArray(value))
41910
43133
  return "[" + value.map(canonical9).join(",") + "]";
@@ -41913,10 +43136,10 @@ function canonical9(value) {
41913
43136
  return JSON.stringify(value);
41914
43137
  }
41915
43138
  function safeDirectory2(path) {
41916
- for (let p = path;; p = dirname23(p)) {
43139
+ for (let p = path;; p = dirname27(p)) {
41917
43140
  const s = lstatSync18(p);
41918
43141
  need11(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "settings_unsafe");
41919
- if (dirname23(p) === p)
43142
+ if (dirname27(p) === p)
41920
43143
  return;
41921
43144
  }
41922
43145
  }
@@ -41934,14 +43157,14 @@ function read3(path) {
41934
43157
  if (missing2.code !== "ENOENT")
41935
43158
  throw missing2;
41936
43159
  }
41937
- let ancestor = dirname23(path);
41938
- const suffix = [basename12(path)];
43160
+ let ancestor = dirname27(path);
43161
+ const suffix = [basename16(path)];
41939
43162
  for (;; ) {
41940
43163
  try {
41941
- resolved = join24(realpathSync14(ancestor), ...suffix);
43164
+ resolved = join34(realpathSync14(ancestor), ...suffix);
41942
43165
  break;
41943
43166
  } catch (missing2) {
41944
- if (missing2.code !== "ENOENT" || dirname23(ancestor) === ancestor || suffix.length >= 64)
43167
+ if (missing2.code !== "ENOENT" || dirname27(ancestor) === ancestor || suffix.length >= 64)
41945
43168
  throw new NativeRegistrationError("settings_unsafe");
41946
43169
  try {
41947
43170
  lstatSync18(ancestor);
@@ -41950,14 +43173,14 @@ function read3(path) {
41950
43173
  if (absent.code !== "ENOENT")
41951
43174
  throw absent;
41952
43175
  }
41953
- suffix.unshift(basename12(ancestor));
41954
- ancestor = dirname23(ancestor);
43176
+ suffix.unshift(basename16(ancestor));
43177
+ ancestor = dirname27(ancestor);
41955
43178
  }
41956
43179
  }
41957
43180
  safeDirectory2(realpathSync14(ancestor));
41958
43181
  return { resolved, raw: null, sha256: "absent" };
41959
43182
  }
41960
- safeDirectory2(dirname23(resolved));
43183
+ safeDirectory2(dirname27(resolved));
41961
43184
  let fd;
41962
43185
  try {
41963
43186
  fd = openSync8(resolved, constants9.O_RDONLY | constants9.O_NOFOLLOW | constants9.O_NONBLOCK);
@@ -41969,7 +43192,7 @@ function read3(path) {
41969
43192
  try {
41970
43193
  const s = fstatSync8(fd);
41971
43194
  need11(s.isFile() && s.uid === process.getuid?.() && !(s.mode & 18) && s.nlink === 1 && s.size <= 1048576, "settings_unsafe");
41972
- const bytes = readFileSync13(fd);
43195
+ const bytes = readFileSync20(fd);
41973
43196
  need11(bytes.length <= 1048576, "settings_unsafe");
41974
43197
  const raw = bytes.toString("utf8");
41975
43198
  need11(Buffer.from(raw).equals(bytes), "settings_invalid");
@@ -42045,7 +43268,7 @@ function validateSettings(raw) {
42045
43268
  function inspect(options) {
42046
43269
  need11(options?.target === "codex" || options?.target === "claude", "input_invalid");
42047
43270
  need11(options.readiness ? options.guard === "trash-guard" : isNativeSafetyName(options.guard), "input_invalid");
42048
- const home = realpathSync14(homedir10()), path = getSettingsPath("global", options.target);
43271
+ const home = realpathSync14(homedir11()), path = getSettingsPath("global", options.target);
42049
43272
  need11(isAbsolute14(path) && resolve31(path) === path, "input_invalid");
42050
43273
  const nativeHome = options.target === "codex" ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR;
42051
43274
  if (nativeHome !== undefined) {
@@ -42094,12 +43317,12 @@ function syncDirectory2(path) {
42094
43317
  function exclusive(path, bytes) {
42095
43318
  const fd = openSync8(path, constants9.O_CREAT | constants9.O_EXCL | constants9.O_WRONLY | constants9.O_NOFOLLOW, 384);
42096
43319
  try {
42097
- writeFileSync10(fd, bytes);
43320
+ writeFileSync12(fd, bytes);
42098
43321
  fsyncSync5(fd);
42099
43322
  } finally {
42100
43323
  closeSync8(fd);
42101
43324
  }
42102
- syncDirectory2(dirname23(path));
43325
+ syncDirectory2(dirname27(path));
42103
43326
  }
42104
43327
  function refusalOf(error61) {
42105
43328
  const code2 = error61?.code;
@@ -42107,7 +43330,7 @@ function refusalOf(error61) {
42107
43330
  }
42108
43331
  function refuseApply(directory3, operationId, planDigest, refusal3) {
42109
43332
  try {
42110
- exclusive(join24(directory3, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest, refusal: refusal3 }) + `
43333
+ exclusive(join34(directory3, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest, refusal: refusal3 }) + `
42111
43334
  `);
42112
43335
  } catch {
42113
43336
  throw new NativeRegistrationError("apply_outcome_uncertain", operationId);
@@ -42148,13 +43371,13 @@ async function applyRegistration(options, dependencies = {}) {
42148
43371
  need11(before.plan.planDigest === plan.planDigest, "settings_changed");
42149
43372
  if (plan.action === "unchanged")
42150
43373
  return { ok: true, changed: false, ...plan };
42151
- const operationId = randomUUID7();
43374
+ const operationId = randomUUID8();
42152
43375
  let directory3 = before.home;
42153
43376
  for (const part of [".hasna", "hooks", "native", selected.readiness ? "trash-readiness-registration" : selected.guard === "trash-guard" ? "trash-registration" : selected.guard + "-registration", operationId]) {
42154
- directory3 = join24(directory3, part);
43377
+ directory3 = join34(directory3, part);
42155
43378
  try {
42156
- mkdirSync12(directory3, { mode: 448 });
42157
- syncDirectory2(dirname23(directory3));
43379
+ mkdirSync14(directory3, { mode: 448 });
43380
+ syncDirectory2(dirname27(directory3));
42158
43381
  } catch (error61) {
42159
43382
  if (error61.code !== "EEXIST")
42160
43383
  throw new NativeRegistrationError("settings_unsafe");
@@ -42162,8 +43385,8 @@ async function applyRegistration(options, dependencies = {}) {
42162
43385
  safeDirectory2(directory3);
42163
43386
  }
42164
43387
  if (before.before.raw !== null)
42165
- exclusive(join24(directory3, "settings.before"), before.before.raw);
42166
- exclusive(join24(directory3, "intent.json"), JSON.stringify({ operationId, plan }) + `
43388
+ exclusive(join34(directory3, "settings.before"), before.before.raw);
43389
+ exclusive(join34(directory3, "intent.json"), JSON.stringify({ operationId, plan }) + `
42167
43390
  `);
42168
43391
  let writeMayHaveStarted = false;
42169
43392
  const beforeWrite = () => {
@@ -42192,7 +43415,7 @@ async function applyRegistration(options, dependencies = {}) {
42192
43415
  ...selected.readiness ? { readinessRunnerVerified: true } : {},
42193
43416
  nativeAdoptionVerified: false
42194
43417
  };
42195
- exclusive(join24(directory3, "receipt.json"), JSON.stringify(receipt) + `
43418
+ exclusive(join34(directory3, "receipt.json"), JSON.stringify(receipt) + `
42196
43419
  `);
42197
43420
  return receipt;
42198
43421
  } catch (error61) {
@@ -42204,7 +43427,7 @@ async function applyRegistration(options, dependencies = {}) {
42204
43427
  function inspectSumi(dependencies) {
42205
43428
  let home, command;
42206
43429
  try {
42207
- home = realpathSync14(dependencies.home ?? homedir10());
43430
+ home = realpathSync14(dependencies.home ?? homedir11());
42208
43431
  } catch {
42209
43432
  throw new NativeRegistrationError("settings_unsafe");
42210
43433
  }
@@ -42215,10 +43438,10 @@ function inspectSumi(dependencies) {
42215
43438
  }
42216
43439
  const binding = nativeSafetyCommandBinding(command);
42217
43440
  need11(binding?.name === "trash-guard" && binding.home === home && isPreviousNativeSafetyCommand(command), "input_invalid");
42218
- const directory3 = join24(home, ".hasna", "hooks", "native"), path = join24(directory3, "sumi-trash-guard.json");
43441
+ const directory3 = join34(home, ".hasna", "hooks", "native"), path = join34(directory3, "sumi-trash-guard.json");
42219
43442
  let existing = directory3;
42220
43443
  while (!lstatSync18(existing, { throwIfNoEntry: false }))
42221
- existing = dirname23(existing);
43444
+ existing = dirname27(existing);
42222
43445
  safeDirectory2(existing);
42223
43446
  let before;
42224
43447
  try {
@@ -42261,13 +43484,13 @@ async function applySumiRegistration(expectedPlanDigest, dependencies) {
42261
43484
  return { ok: true, changed: false, ...plan };
42262
43485
  const current2 = inspectSumi(dependencies);
42263
43486
  need11(current2.plan.planDigest === plan.planDigest, "settings_changed");
42264
- const operationId = randomUUID7();
43487
+ const operationId = randomUUID8();
42265
43488
  let directory3 = current2.home;
42266
43489
  for (const part of [".hasna", "hooks", "native", "trash-readiness-registration", operationId]) {
42267
- directory3 = join24(directory3, part);
43490
+ directory3 = join34(directory3, part);
42268
43491
  try {
42269
- mkdirSync12(directory3, { mode: 448 });
42270
- syncDirectory2(dirname23(directory3));
43492
+ mkdirSync14(directory3, { mode: 448 });
43493
+ syncDirectory2(dirname27(directory3));
42271
43494
  } catch (error61) {
42272
43495
  if (error61.code !== "EEXIST")
42273
43496
  throw new NativeRegistrationError("settings_unsafe");
@@ -42275,8 +43498,8 @@ async function applySumiRegistration(expectedPlanDigest, dependencies) {
42275
43498
  safeDirectory2(directory3);
42276
43499
  }
42277
43500
  if (current2.before)
42278
- exclusive(join24(directory3, "settings.before"), current2.before.text);
42279
- exclusive(join24(directory3, "intent.json"), JSON.stringify({ operationId, plan }) + `
43501
+ exclusive(join34(directory3, "settings.before"), current2.before.text);
43502
+ exclusive(join34(directory3, "intent.json"), JSON.stringify({ operationId, plan }) + `
42280
43503
  `);
42281
43504
  let writeMayHaveStarted = false;
42282
43505
  try {
@@ -42304,7 +43527,7 @@ async function applySumiRegistration(expectedPlanDigest, dependencies) {
42304
43527
  ...current2.before ? { backup: plan.settingsPath + ".before-" + plan.beforeSHA256 } : {},
42305
43528
  nativeAdoptionVerified: false
42306
43529
  };
42307
- exclusive(join24(directory3, "receipt.json"), JSON.stringify(receipt) + `
43530
+ exclusive(join34(directory3, "receipt.json"), JSON.stringify(receipt) + `
42308
43531
  `);
42309
43532
  return receipt;
42310
43533
  } catch (error61) {
@@ -42385,9 +43608,9 @@ var init_native_child_env = __esm(() => {
42385
43608
  // src/lib/codex-safety-check.ts
42386
43609
  import { spawn as spawn3, execFile as execFile2 } from "child_process";
42387
43610
  import { createHash as createHash25 } from "crypto";
42388
- import { constants as constants21, openSync as openSync15, closeSync as closeSync15, fstatSync as fstatSync15, lstatSync as lstatSync29, readFileSync as readFileSync20, realpathSync as realpathSync17 } from "fs";
42389
- import { homedir as homedir12 } from "os";
42390
- import { dirname as dirname29, isAbsolute as isAbsolute29, resolve as resolve35 } from "path";
43611
+ import { constants as constants21, openSync as openSync15, closeSync as closeSync15, fstatSync as fstatSync15, lstatSync as lstatSync29, readFileSync as readFileSync22, realpathSync as realpathSync17 } from "fs";
43612
+ import { homedir as homedir13 } from "os";
43613
+ import { dirname as dirname30, isAbsolute as isAbsolute29, resolve as resolve35 } from "path";
42391
43614
  import { promisify } from "util";
42392
43615
  function need14(condition, code2) {
42393
43616
  if (!condition)
@@ -42411,17 +43634,17 @@ function executable2(command) {
42411
43634
  need14(found, "native_unavailable");
42412
43635
  try {
42413
43636
  const path = realpathSync17(found);
42414
- for (let parent = dirname29(path);; parent = dirname29(parent)) {
43637
+ for (let parent = dirname30(path);; parent = dirname30(parent)) {
42415
43638
  const stat2 = lstatSync29(parent);
42416
43639
  need14(stat2.isDirectory() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18), "native_unsafe_executable");
42417
- if (parent === dirname29(parent))
43640
+ if (parent === dirname30(parent))
42418
43641
  break;
42419
43642
  }
42420
43643
  const fd = openSync15(path, constants21.O_RDONLY | constants21.O_NOFOLLOW | constants21.O_NONBLOCK);
42421
43644
  try {
42422
43645
  const stat2 = fstatSync15(fd);
42423
43646
  need14(stat2.isFile() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18) && !!(stat2.mode & 64) && stat2.size <= CODEX_EXECUTABLE_MAX_BYTES, "native_unsafe_executable");
42424
- const bytes = readFileSync20(fd);
43647
+ const bytes = readFileSync22(fd);
42425
43648
  need14(bytes.length <= CODEX_EXECUTABLE_MAX_BYTES, "native_unavailable");
42426
43649
  need14(nativeHeader(bytes), "native_executable_required");
42427
43650
  return { path, sha256: digest4(bytes) };
@@ -42556,9 +43779,9 @@ function supportedDiscoveryWarnings(hooks, warnings) {
42556
43779
  const sources = new Set(hooks.map((hook) => JSON.stringify([hook?.source, hook?.sourcePath])));
42557
43780
  for (const hook of hooks) {
42558
43781
  const path = hook?.sourcePath;
42559
- if (typeof path !== "string" || path.length > 4096 || !isAbsolute29(path) || path !== resolve35(dirname29(path), "hooks.json") || !["user", "project"].includes(hook.source))
43782
+ if (typeof path !== "string" || path.length > 4096 || !isAbsolute29(path) || path !== resolve35(dirname30(path), "hooks.json") || !["user", "project"].includes(hook.source))
42560
43783
  continue;
42561
- const toml = resolve35(dirname29(path), "config.toml");
43784
+ const toml = resolve35(dirname30(path), "config.toml");
42562
43785
  if (sources.has(JSON.stringify([hook.source, toml]))) {
42563
43786
  allowed.add(`loading hooks from both ${path} and ${toml}; prefer a single representation for this layer`);
42564
43787
  }
@@ -42625,7 +43848,7 @@ async function readCodexSafety(rpc, home, cwd, options = {}) {
42625
43848
  return { guard: selectCodexSafety(hooks, configuration, home, cwd, enabled, options.requireReady ?? true, options.readiness ?? false, options.guard ?? "trash-guard"), discovery: hooks, configuration };
42626
43849
  }
42627
43850
  async function verifyCodexNativeSafety(options = {}, dependencies = {}) {
42628
- const home = realpathSync17(options.home ?? homedir12()), cwd = realpathSync17(options.cwd ?? process.cwd());
43851
+ const home = realpathSync17(options.home ?? homedir13()), cwd = realpathSync17(options.cwd ?? process.cwd());
42629
43852
  need14(isAbsolute29(home) && isAbsolute29(cwd), "native_unavailable");
42630
43853
  const rpc = await (dependencies.connect ?? connectCodexSafety)({ ...options, home });
42631
43854
  try {
@@ -42684,10 +43907,10 @@ __export(exports_codex_safety_trust, {
42684
43907
  applyCodexReadinessTrust: () => applyCodexReadinessTrust,
42685
43908
  CodexTrustError: () => CodexTrustError
42686
43909
  });
42687
- import { createHash as createHash31, randomUUID as randomUUID8 } from "crypto";
42688
- import { constants as constants23, closeSync as closeSync20, fsyncSync as fsyncSync8, fstatSync as fstatSync20, lstatSync as lstatSync33, mkdirSync as mkdirSync13, openSync as openSync20, readFileSync as readFileSync21, realpathSync as realpathSync18, writeFileSync as writeFileSync11 } from "fs";
42689
- import { dirname as dirname30, isAbsolute as isAbsolute31, join as join34, relative as relative7 } from "path";
42690
- import { homedir as homedir13 } from "os";
43910
+ import { createHash as createHash31, randomUUID as randomUUID9 } from "crypto";
43911
+ import { constants as constants23, closeSync as closeSync20, fsyncSync as fsyncSync8, fstatSync as fstatSync20, lstatSync as lstatSync33, mkdirSync as mkdirSync15, openSync as openSync20, readFileSync as readFileSync23, realpathSync as realpathSync18, writeFileSync as writeFileSync13 } from "fs";
43912
+ import { dirname as dirname31, isAbsolute as isAbsolute31, join as join39, relative as relative7 } from "path";
43913
+ import { homedir as homedir14 } from "os";
42691
43914
  function need15(value, code2 = "native_changed") {
42692
43915
  if (!value)
42693
43916
  throw new CodexTrustError(code2);
@@ -42723,20 +43946,20 @@ function mergedConfiguration(value) {
42723
43946
  return canonical11(copy);
42724
43947
  }
42725
43948
  function safeDirectory3(path) {
42726
- for (let p = path;; p = dirname30(p)) {
43949
+ for (let p = path;; p = dirname31(p)) {
42727
43950
  const s = lstatSync33(p);
42728
43951
  need15(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "preimage_unsafe");
42729
- if (dirname30(p) === p)
43952
+ if (dirname31(p) === p)
42730
43953
  return;
42731
43954
  }
42732
43955
  }
42733
43956
  function readPrivate(path) {
42734
- safeDirectory3(dirname30(path));
43957
+ safeDirectory3(dirname31(path));
42735
43958
  const fd = openSync20(path, constants23.O_RDONLY | constants23.O_NOFOLLOW | constants23.O_NONBLOCK);
42736
43959
  try {
42737
43960
  const s = fstatSync20(fd);
42738
43961
  need15(s.isFile() && s.uid === process.getuid?.() && !(s.mode & 63) && s.size <= 4194304, "preimage_unsafe");
42739
- const bytes = readFileSync21(fd);
43962
+ const bytes = readFileSync23(fd);
42740
43963
  need15(bytes.length <= 4194304, "preimage_unsafe");
42741
43964
  return bytes;
42742
43965
  } finally {
@@ -42754,12 +43977,12 @@ function syncDirectory3(path) {
42754
43977
  function exclusive2(path, bytes) {
42755
43978
  const fd = openSync20(path, constants23.O_CREAT | constants23.O_EXCL | constants23.O_WRONLY | constants23.O_NOFOLLOW, 384);
42756
43979
  try {
42757
- writeFileSync11(fd, bytes);
43980
+ writeFileSync13(fd, bytes);
42758
43981
  fsyncSync8(fd);
42759
43982
  } finally {
42760
43983
  closeSync20(fd);
42761
43984
  }
42762
- syncDirectory3(dirname30(path));
43985
+ syncDirectory3(dirname31(path));
42763
43986
  }
42764
43987
  async function inspect2(rpc, home, cwd, readiness = false, selected = "trash-guard") {
42765
43988
  const observed = await readCodexSafety(rpc, home, cwd, { includeLayers: true, requireReady: false, readiness, guard: selected });
@@ -42797,7 +44020,7 @@ async function inspect2(rpc, home, cwd, readiness = false, selected = "trash-gua
42797
44020
  }
42798
44021
  async function context2(options, dependencies) {
42799
44022
  need15(options.readiness ? options.guard === undefined : options.guard === undefined || isNativeSafetyName(options.guard), "input_invalid");
42800
- const home = realpathSync18(options.home ?? homedir13()), cwd = realpathSync18(options.cwd ?? process.cwd());
44023
+ const home = realpathSync18(options.home ?? homedir14()), cwd = realpathSync18(options.cwd ?? process.cwd());
42801
44024
  need15(isAbsolute31(home) && isAbsolute31(cwd), "input_invalid");
42802
44025
  return { home, cwd, rpc: await (dependencies.connect ?? connectCodexSafety)({ ...options, home }) };
42803
44026
  }
@@ -42840,21 +44063,21 @@ async function applyTrust(options, dependencies = {}) {
42840
44063
  const expectedGuard = expectedDiscovery.data[0].hooks.find((h) => h.key === before.guard.key);
42841
44064
  expectedGuard.enabled = true;
42842
44065
  expectedGuard.trustStatus = "trusted";
42843
- operationId = randomUUID8();
44066
+ operationId = randomUUID9();
42844
44067
  let directory3 = home;
42845
44068
  for (const part of [".hasna", "hooks", "native", selected.readiness ? "codex-readiness-trust" : (selected.guard ?? "trash-guard") === "trash-guard" ? "codex-trash-trust" : "codex-" + selected.guard + "-trust", operationId]) {
42846
- directory3 = join34(directory3, part);
44069
+ directory3 = join39(directory3, part);
42847
44070
  try {
42848
- mkdirSync13(directory3, { mode: 448 });
42849
- syncDirectory3(dirname30(directory3));
44071
+ mkdirSync15(directory3, { mode: 448 });
44072
+ syncDirectory3(dirname31(directory3));
42850
44073
  } catch (error61) {
42851
44074
  if (error61.code !== "EEXIST")
42852
44075
  throw error61;
42853
44076
  }
42854
44077
  safeDirectory3(directory3);
42855
44078
  }
42856
- exclusive2(join34(directory3, "config.before"), before.before);
42857
- exclusive2(join34(directory3, "intent.json"), JSON.stringify({ operationId, plan: before.plan, configSHA256: sha10(before.before) }) + `
44079
+ exclusive2(join39(directory3, "config.before"), before.before);
44080
+ exclusive2(join39(directory3, "intent.json"), JSON.stringify({ operationId, plan: before.plan, configSHA256: sha10(before.before) }) + `
42858
44081
  `);
42859
44082
  journal = directory3;
42860
44083
  need15(sha10(readPrivate(before.canonicalPath)) === sha10(before.before));
@@ -42882,7 +44105,7 @@ async function applyTrust(options, dependencies = {}) {
42882
44105
  nativeAdoptionVerified: false,
42883
44106
  unrelatedConfigurationPreserved: true
42884
44107
  };
42885
- exclusive2(join34(directory3, "receipt.json"), JSON.stringify(receipt) + `
44108
+ exclusive2(join39(directory3, "receipt.json"), JSON.stringify(receipt) + `
42886
44109
  `);
42887
44110
  return receipt;
42888
44111
  } catch (error61) {
@@ -42895,7 +44118,7 @@ async function applyTrust(options, dependencies = {}) {
42895
44118
  if (!journal)
42896
44119
  throw new CodexTrustError("trust_refused", undefined, refusal3);
42897
44120
  try {
42898
- exclusive2(join34(journal, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest: selected.expectedPlanDigest, refusal: refusal3 }) + `
44121
+ exclusive2(join39(journal, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, planDigest: selected.expectedPlanDigest, refusal: refusal3 }) + `
42899
44122
  `);
42900
44123
  } catch {
42901
44124
  throw new CodexTrustError("trust_outcome_uncertain", operationId);
@@ -46405,9 +47628,9 @@ var require_cli_spinners = __commonJS((exports, module) => {
46405
47628
  });
46406
47629
 
46407
47630
  // hooks/hook-trash-guard/src/binary.ts
46408
- import { dirname as dirname31, isAbsolute as isAbsolute33, join as join39, resolve as resolve37 } from "path";
46409
- import { accessSync as accessSync3, closeSync as closeSync23, constants as constants24, fstatSync as fstatSync23, lstatSync as lstatSync35, openSync as openSync23, readFileSync as readFileSync22, readlinkSync, readSync as readSync4, realpathSync as realpathSync19, statSync } from "fs";
46410
- import { spawnSync } from "child_process";
47631
+ import { dirname as dirname33, isAbsolute as isAbsolute33, join as join42, resolve as resolve37 } from "path";
47632
+ import { accessSync as accessSync3, closeSync as closeSync23, constants as constants24, fstatSync as fstatSync23, lstatSync as lstatSync35, openSync as openSync23, readFileSync as readFileSync24, readlinkSync, readSync as readSync4, realpathSync as realpathSync19, statSync as statSync2 } from "fs";
47633
+ import { spawnSync as spawnSync4 } from "child_process";
46411
47634
  function trustedOwner(uid2) {
46412
47635
  return uid2 === 0 || uid2 === process.getuid?.();
46413
47636
  }
@@ -46424,10 +47647,10 @@ function safeExecutableFile(path, systemBinAlias = false) {
46424
47647
  if (!part || part === ".")
46425
47648
  continue;
46426
47649
  if (part === "..") {
46427
- parent = dirname31(parent);
47650
+ parent = dirname33(parent);
46428
47651
  continue;
46429
47652
  }
46430
- const next = join39(parent, part), info2 = lstatSync35(next);
47653
+ const next = join42(parent, part), info2 = lstatSync35(next);
46431
47654
  if (systemBinAlias && next === "/bin" && info2.isSymbolicLink() && info2.uid === 0) {
46432
47655
  const target = realpathSync19(next);
46433
47656
  if (!safeBinaryDirectory(target))
@@ -46439,7 +47662,7 @@ function safeExecutableFile(path, systemBinAlias = false) {
46439
47662
  return false;
46440
47663
  parent = next;
46441
47664
  }
46442
- const candidate = join39(parent, name), info = lstatSync35(candidate);
47665
+ const candidate = join42(parent, name), info = lstatSync35(candidate);
46443
47666
  if (!trustedOwner(info.uid))
46444
47667
  return false;
46445
47668
  if (info.isSymbolicLink()) {
@@ -46454,7 +47677,7 @@ function safeExecutableFile(path, systemBinAlias = false) {
46454
47677
  function safeInterpreterSearchDirectory(path) {
46455
47678
  if (!isAbsolute33(path) || resolve37(path) !== (path.replace(/\/+$/, "") || "/"))
46456
47679
  return false;
46457
- for (let cursor = resolve37(path);; cursor = dirname31(cursor)) {
47680
+ for (let cursor = resolve37(path);; cursor = dirname33(cursor)) {
46458
47681
  try {
46459
47682
  lstatSync35(cursor);
46460
47683
  return safeBinaryDirectory(cursor);
@@ -46462,7 +47685,7 @@ function safeInterpreterSearchDirectory(path) {
46462
47685
  if (error61.code !== "ENOENT")
46463
47686
  return false;
46464
47687
  }
46465
- if (dirname31(cursor) === cursor)
47688
+ if (dirname33(cursor) === cursor)
46466
47689
  return false;
46467
47690
  }
46468
47691
  }
@@ -46488,7 +47711,7 @@ function safeScriptInterpreter(executable3, pathValue) {
46488
47711
  return false;
46489
47712
  const interpreter = resolve37(dir, "bun");
46490
47713
  try {
46491
- if (!statSync(interpreter).isFile())
47714
+ if (!statSync2(interpreter).isFile())
46492
47715
  continue;
46493
47716
  accessSync3(interpreter, constants24.X_OK);
46494
47717
  } catch {
@@ -46504,7 +47727,7 @@ function safeBinaryDirectory(path) {
46504
47727
  const info = lstatSync35(current2);
46505
47728
  if (!info.isDirectory() || !trustedOwner(info.uid) || (info.mode & 18) !== 0)
46506
47729
  return false;
46507
- const parent = dirname31(current2);
47730
+ const parent = dirname33(current2);
46508
47731
  if (parent === current2)
46509
47732
  return true;
46510
47733
  current2 = parent;
@@ -46523,13 +47746,13 @@ function inspectTrashBinary(env = process.env) {
46523
47746
  continue;
46524
47747
  const candidate = resolve37(dir, "trash");
46525
47748
  try {
46526
- const stat2 = statSync(candidate);
47749
+ const stat2 = statSync2(candidate);
46527
47750
  if (!stat2.isFile() || !trustedOwner(stat2.uid) || (stat2.mode & 73) === 0 || (stat2.mode & 18) !== 0) {
46528
47751
  reject("unsafe_executable");
46529
47752
  continue;
46530
47753
  }
46531
47754
  const executable3 = realpathSync19(candidate);
46532
- if (!safeBinaryDirectory(resolve37(dir)) || !safeBinaryDirectory(dirname31(executable3))) {
47755
+ if (!safeBinaryDirectory(resolve37(dir)) || !safeBinaryDirectory(dirname33(executable3))) {
46533
47756
  reject("unsafe_directory");
46534
47757
  continue;
46535
47758
  }
@@ -46537,14 +47760,14 @@ function inspectTrashBinary(env = process.env) {
46537
47760
  reject("unsafe_directory");
46538
47761
  continue;
46539
47762
  }
46540
- const packageRoot = resolve37(dirname31(executable3), "../..");
46541
- const manifestPath = join39(packageRoot, "package.json");
46542
- const manifestStat = statSync(manifestPath);
47763
+ const packageRoot = resolve37(dirname33(executable3), "../..");
47764
+ const manifestPath = join42(packageRoot, "package.json");
47765
+ const manifestStat = statSync2(manifestPath);
46543
47766
  if (!manifestStat.isFile() || !trustedOwner(manifestStat.uid) || manifestStat.size > 16384 || (manifestStat.mode & 18) !== 0 || lstatSync35(manifestPath).isSymbolicLink()) {
46544
47767
  reject("unsafe_manifest");
46545
47768
  continue;
46546
47769
  }
46547
- const manifest = JSON.parse(readFileSync22(manifestPath, "utf8"));
47770
+ const manifest = JSON.parse(readFileSync24(manifestPath, "utf8"));
46548
47771
  if (manifest.name !== "@hasna/trash" || typeof manifest.version !== "string" || typeof manifest.bin?.trash !== "string" || realpathSync19(resolve37(packageRoot, manifest.bin.trash)) !== executable3) {
46549
47772
  reject("unrecognized_package");
46550
47773
  continue;
@@ -46563,7 +47786,7 @@ function inspectTrashBinary(env = process.env) {
46563
47786
  reject("identity_failed");
46564
47787
  break;
46565
47788
  }
46566
- const probe2 = spawnSync(candidate, ["--identity"], {
47789
+ const probe2 = spawnSync4(candidate, ["--identity"], {
46567
47790
  encoding: "utf8",
46568
47791
  timeout: remaining,
46569
47792
  maxBuffer: 2048,
@@ -46585,16 +47808,16 @@ function inspectTrashBinary(env = process.env) {
46585
47808
  var init_binary = () => {};
46586
47809
 
46587
47810
  // src/lib/sumi-binding.ts
46588
- import { homedir as homedir15 } from "os";
46589
- import { join as join41, sep as sep10 } from "path";
47811
+ import { homedir as homedir16 } from "os";
47812
+ import { join as join43, sep as sep10 } from "path";
46590
47813
  function failure(code2, reason2) {
46591
47814
  return { ok: false, target: "sumi", code: code2, ...reason2 ? { reason: reason2.slice(0, 300) } : {} };
46592
47815
  }
46593
47816
  function nativeSafetyBindingDurable(worker, home) {
46594
- return !(worker.startsWith(join41(home, ".bun") + sep10) || worker.includes(`${sep10}node_modules${sep10}.bun${sep10}`));
47817
+ return !(worker.startsWith(join43(home, ".bun") + sep10) || worker.includes(`${sep10}node_modules${sep10}.bun${sep10}`));
46595
47818
  }
46596
47819
  async function provisionSumiSafetyBinding(options = {}) {
46597
- const home = options.home ?? homedir15();
47820
+ const home = options.home ?? homedir16();
46598
47821
  let desired;
46599
47822
  try {
46600
47823
  desired = options.command ?? installedSumiNativeSafetyCommand();
@@ -46717,123 +47940,18 @@ var init_redact = __esm(() => {
46717
47940
  ];
46718
47941
  });
46719
47942
 
46720
- // src/lib/profiles.ts
46721
- import { existsSync as existsSync15, mkdirSync as mkdirSync14, readFileSync as readFileSync23, writeFileSync as writeFileSync12, readdirSync as readdirSync8, rmSync as rmSync3, cpSync as cpSync2 } from "fs";
46722
- import { join as join42 } from "path";
46723
- function getProfilesDir() {
46724
- const newDir = join42(getEffectiveDataRoot(), "profiles");
46725
- const oldDir = join42(getHomeDir(), ".hooks", "profiles");
46726
- if (!existsSync15(newDir) && existsSync15(oldDir)) {
46727
- mkdirSync14(newDir, { recursive: true });
46728
- cpSync2(oldDir, newDir, { recursive: true });
46729
- }
46730
- return newDir;
46731
- }
46732
- function ensureProfilesDir() {
46733
- const dir = getProfilesDir();
46734
- if (!existsSync15(dir)) {
46735
- mkdirSync14(dir, { recursive: true });
46736
- }
46737
- }
46738
- function profilePath(id) {
46739
- return join42(getProfilesDir(), `${id}.json`);
46740
- }
46741
- function shortUuid() {
46742
- return crypto.randomUUID().slice(0, 8);
46743
- }
46744
- function createProfile(input2) {
46745
- ensureProfilesDir();
46746
- const id = shortUuid();
46747
- const now2 = new Date().toISOString();
46748
- const profile = {
46749
- agent_id: id,
46750
- agent_type: input2.agent_type,
46751
- created_at: now2,
46752
- last_seen_at: now2,
46753
- preferences: {}
46754
- };
46755
- if (input2.name) {
46756
- profile.name = input2.name;
46757
- }
46758
- writeFileSync12(profilePath(id), JSON.stringify(profile, null, 2) + `
46759
- `);
46760
- return profile;
46761
- }
46762
- function getProfile(id) {
46763
- const path = profilePath(id);
46764
- try {
46765
- if (!existsSync15(path))
46766
- return null;
46767
- return JSON.parse(readFileSync23(path, "utf-8"));
46768
- } catch {
46769
- return null;
46770
- }
46771
- }
46772
- function listProfiles() {
46773
- const dir = getProfilesDir();
46774
- if (!existsSync15(dir))
46775
- return [];
46776
- try {
46777
- const files = readdirSync8(dir).filter((f) => f.endsWith(".json"));
46778
- const profiles = [];
46779
- for (const file2 of files) {
46780
- try {
46781
- const content = readFileSync23(join42(dir, file2), "utf-8");
46782
- profiles.push(JSON.parse(content));
46783
- } catch {}
46784
- }
46785
- return profiles.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
46786
- } catch {
46787
- return [];
46788
- }
46789
- }
46790
- function touchProfile(id) {
46791
- const profile = getProfile(id);
46792
- if (!profile)
46793
- return;
46794
- profile.last_seen_at = new Date().toISOString();
46795
- writeFileSync12(profilePath(id), JSON.stringify(profile, null, 2) + `
46796
- `);
46797
- }
46798
- function exportProfiles() {
46799
- return listProfiles();
46800
- }
46801
- function importProfiles(profiles) {
46802
- ensureProfilesDir();
46803
- let imported = 0;
46804
- let skipped = 0;
46805
- for (const profile of profiles) {
46806
- if (!profile.agent_id || !profile.agent_type) {
46807
- skipped++;
46808
- continue;
46809
- }
46810
- const path = profilePath(profile.agent_id);
46811
- if (existsSync15(path)) {
46812
- skipped++;
46813
- continue;
46814
- }
46815
- writeFileSync12(path, JSON.stringify(profile, null, 2) + `
46816
- `);
46817
- imported++;
46818
- }
46819
- return { imported, skipped };
46820
- }
46821
- var init_profiles = __esm(() => {
46822
- init_app_home();
46823
- });
46824
-
46825
47943
  // ../contracts/dist/client/transport.js
46826
47944
  import { isIP as isIP2 } from "net";
46827
- import { spawnSync as spawnSync4 } from "child_process";
46828
- import { closeSync as closeSync24, fstatSync as fstatSync24, openSync as openSync24, readFileSync as readFileSync24 } from "fs";
47945
+ import { spawnSync as spawnSync6 } from "child_process";
47946
+ import { closeSync as closeSync24, fstatSync as fstatSync24, openSync as openSync24, readFileSync as readFileSync25 } from "fs";
46829
47947
  import { O_NOFOLLOW as O_NOFOLLOW2, O_NONBLOCK as O_NONBLOCK2, O_RDONLY as O_RDONLY2 } from "constants";
46830
47948
  import { hostname as osHostname } from "os";
46831
47949
  import { isAbsolute as isAbsolute35, join as join212 } from "path";
46832
47950
  import { createRequire as createRequire2 } from "module";
46833
47951
  import { fileURLToPath as fileURLToPath22 } from "url";
46834
- import { closeSync as closeSync25, fstatSync as fstatSync25, lstatSync as lstatSync36, openSync as openSync25, readFileSync as readFileSync25, realpathSync as realpathSync20, statSync as statSync2 } from "fs";
47952
+ import { closeSync as closeSync25, fstatSync as fstatSync25, lstatSync as lstatSync36, openSync as openSync25, readFileSync as readFileSync27, realpathSync as realpathSync20, statSync as statSync3 } from "fs";
46835
47953
  import { O_NOFOLLOW, O_NONBLOCK, O_RDONLY } from "constants";
46836
- import { basename as basename16, dirname as dirname33, join as join43, relative as relative11, sep as sep16 } from "path";
47954
+ import { basename as basename18, dirname as dirname35, join as join44, relative as relative11, sep as sep16 } from "path";
46837
47955
  import { fileURLToPath as fileURLToPath4, pathToFileURL } from "url";
46838
47956
  function envToken2(name) {
46839
47957
  return name.toUpperCase().replace(/-/g, "_");
@@ -46908,13 +48026,13 @@ function o(e2, r2, t2) {
46908
48026
  }
46909
48027
  function entryPoint(directory3) {
46910
48028
  const root = realpathSync20(directory3);
46911
- const fd = openSync25(join43(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
48029
+ const fd = openSync25(join44(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
46912
48030
  let pkg;
46913
48031
  try {
46914
48032
  const stat2 = fstatSync25(fd);
46915
48033
  if (!stat2.isFile() || stat2.size > MAX_PACKAGE_BYTES2)
46916
48034
  throw new Error("Invalid Secrets package metadata");
46917
- pkg = JSON.parse(readFileSync25(fd, "utf8"));
48035
+ pkg = JSON.parse(readFileSync27(fd, "utf8"));
46918
48036
  } finally {
46919
48037
  closeSync25(fd);
46920
48038
  }
@@ -46928,18 +48046,18 @@ function entryPoint(directory3) {
46928
48046
  if (/[\\%?#\0]/.test(target) || parts.some((part) => !part || part === "." || part === ".." || part === "node_modules")) {
46929
48047
  throw new Error("Invalid Secrets import export");
46930
48048
  }
46931
- const file2 = realpathSync20(join43(root, ...parts));
48049
+ const file2 = realpathSync20(join44(root, ...parts));
46932
48050
  const within = relative11(root, file2);
46933
- if (!within || within === ".." || within.startsWith(`..${sep16}`) || !statSync2(file2).isFile()) {
48051
+ if (!within || within === ".." || within.startsWith(`..${sep16}`) || !statSync3(file2).isFile()) {
46934
48052
  throw new Error("Secrets import export escapes its package or is not a file");
46935
48053
  }
46936
48054
  return pathToFileURL(file2).href;
46937
48055
  }
46938
48056
  function resolveInstalledSecrets(parentUrl) {
46939
- let directory3 = dirname33(fileURLToPath4(parentUrl));
48057
+ let directory3 = dirname35(fileURLToPath4(parentUrl));
46940
48058
  for (;; ) {
46941
- if (basename16(directory3) !== "node_modules") {
46942
- const candidate = join43(directory3, "node_modules", PACKAGE);
48059
+ if (basename18(directory3) !== "node_modules") {
48060
+ const candidate = join44(directory3, "node_modules", PACKAGE);
46943
48061
  let absent = false;
46944
48062
  try {
46945
48063
  lstatSync36(candidate);
@@ -46951,7 +48069,7 @@ function resolveInstalledSecrets(parentUrl) {
46951
48069
  if (!absent)
46952
48070
  return entryPoint(candidate);
46953
48071
  }
46954
- const parent = dirname33(directory3);
48072
+ const parent = dirname35(directory3);
46955
48073
  if (parent === directory3)
46956
48074
  throw new Error("Secrets SDK is not installed for this consumer");
46957
48075
  directory3 = parent;
@@ -47061,7 +48179,7 @@ function readAppConfigFile(path) {
47061
48179
  unsafe("the file is not owned by the current user");
47062
48180
  if (before.size > MAX_CREDENTIAL_FILE_BYTES2)
47063
48181
  unsafe("the file exceeds the size limit");
47064
- const bytes = readFileSync24(fd);
48182
+ const bytes = readFileSync25(fd);
47065
48183
  const after = fstatSync24(fd);
47066
48184
  if (!configFileReadsCoherent(before, after)) {
47067
48185
  unsafe("the file changed while being read");
@@ -47194,7 +48312,7 @@ function isAmbientEnvironment(env) {
47194
48312
  return env === process.env || env[AMBIENT_ENVIRONMENT2] === true;
47195
48313
  }
47196
48314
  function defaultKeychainRunner(argv) {
47197
- const result = spawnSync4(KEYCHAIN_SECURITY_BIN, [...argv], {
48315
+ const result = spawnSync6(KEYCHAIN_SECURITY_BIN, [...argv], {
47198
48316
  encoding: "utf8",
47199
48317
  stdio: ["ignore", "pipe", "pipe"],
47200
48318
  timeout: KEYCHAIN_SPAWN_TIMEOUT_MS
@@ -48197,9 +49315,9 @@ var init_stop_review_context = __esm(() => {
48197
49315
  });
48198
49316
 
48199
49317
  // src/lib/hook-env.ts
48200
- import { dirname as dirname35, isAbsolute as isAbsolute36 } from "path";
48201
- import { existsSync as existsSync16, realpathSync as realpathSync21, statSync as statSync3 } from "fs";
48202
- import { tmpdir } from "os";
49318
+ import { dirname as dirname36, isAbsolute as isAbsolute36 } from "path";
49319
+ import { existsSync as existsSync17, realpathSync as realpathSync21, statSync as statSync5 } from "fs";
49320
+ import { tmpdir as tmpdir2 } from "os";
48203
49321
  function isDeniedEnvName(name) {
48204
49322
  const upper = name.toUpperCase();
48205
49323
  if (DENY_PREFIXES.some((prefix3) => upper.startsWith(prefix3)))
@@ -48233,22 +49351,22 @@ function isUnsafePathEntry(entry, home) {
48233
49351
  }
48234
49352
  };
48235
49353
  const resolved = canonical10(entry);
48236
- for (const root of [home, tmpdir(), "/tmp", "/var/tmp"].filter((value) => Boolean(value))) {
49354
+ for (const root of [home, tmpdir2(), "/tmp", "/var/tmp"].filter((value) => Boolean(value))) {
48237
49355
  const blocked = canonical10(root);
48238
49356
  if (resolved === blocked || resolved.startsWith(blocked + "/"))
48239
49357
  return true;
48240
49358
  }
48241
49359
  try {
48242
- if ((statSync3(entry).mode & 2) !== 0)
49360
+ if ((statSync5(entry).mode & 2) !== 0)
48243
49361
  return true;
48244
49362
  } catch {}
48245
49363
  return false;
48246
49364
  }
48247
49365
  function sanitizeHookPath(pathValue, home) {
48248
49366
  const baseline = PATH_BASELINE.slice();
48249
- if (process.platform === "darwin" && existsSync16("/opt/homebrew/bin"))
49367
+ if (process.platform === "darwin" && existsSync17("/opt/homebrew/bin"))
48250
49368
  baseline.push("/opt/homebrew/bin");
48251
- const bunDir = dirname35(process.execPath);
49369
+ const bunDir = dirname36(process.execPath);
48252
49370
  const seen = new Set;
48253
49371
  const out = [];
48254
49372
  for (const dir of baseline) {
@@ -48381,10 +49499,10 @@ __export(exports_run, {
48381
49499
  BUN_ISOLATION_FLAGS: () => BUN_ISOLATION_FLAGS
48382
49500
  });
48383
49501
  import { randomBytes as randomBytes2 } from "crypto";
48384
- import { rmSync as rmSync5, writeFileSync as writeFileSync13 } from "fs";
48385
- import { basename as basename18, dirname as dirname36, isAbsolute as isAbsolute37, join as join44 } from "path";
49502
+ import { rmSync as rmSync5, writeFileSync as writeFileSync14 } from "fs";
49503
+ import { basename as basename19, dirname as dirname37, isAbsolute as isAbsolute37, join as join45 } from "path";
48386
49504
  function extensionOf(scriptPath) {
48387
- const base = basename18(scriptPath);
49505
+ const base = basename19(scriptPath);
48388
49506
  const dot = base.lastIndexOf(".");
48389
49507
  return dot > 0 ? base.slice(dot + 1) : "ts";
48390
49508
  }
@@ -48396,9 +49514,9 @@ function shebangInterpreter(firstLine) {
48396
49514
  return null;
48397
49515
  const parts = rest.split(/\s+/);
48398
49516
  if (parts[0] === "env" || parts[0] === "/usr/bin/env") {
48399
- return parts[1] && parts[1] !== "-S" ? basename18(parts[1]) : parts[2] ? basename18(parts[2]) : null;
49517
+ return parts[1] && parts[1] !== "-S" ? basename19(parts[1]) : parts[2] ? basename19(parts[2]) : null;
48400
49518
  }
48401
- return basename18(parts[0]);
49519
+ return basename19(parts[0]);
48402
49520
  }
48403
49521
  function interpreterFor(name, scriptPath, content) {
48404
49522
  const ext = extensionOf(scriptPath);
@@ -48451,9 +49569,9 @@ async function readPipeWithDeadline(stream, deadlineMs) {
48451
49569
  return chunks.join("");
48452
49570
  }
48453
49571
  async function executeVerifiedScript(options) {
48454
- const scriptDir = dirname36(options.scriptPath);
49572
+ const scriptDir = dirname37(options.scriptPath);
48455
49573
  const interpreter = interpreterFor(options.name, options.scriptPath, options.content);
48456
- const tempPath = join44(scriptDir, `.hooks-verified-${randomBytes2(12).toString("hex")}.${interpreter.tempExt}`);
49574
+ const tempPath = join45(scriptDir, `.hooks-verified-${randomBytes2(12).toString("hex")}.${interpreter.tempExt}`);
48457
49575
  let proc = null;
48458
49576
  let timedOut = false;
48459
49577
  const timeoutTimer = options.timeout ? setTimeout(() => {
@@ -48461,7 +49579,7 @@ async function executeVerifiedScript(options) {
48461
49579
  killGroup(proc, { leaderAlive: proc !== null && proc.exitCode === null });
48462
49580
  }, options.timeout) : null;
48463
49581
  try {
48464
- writeFileSync13(tempPath, options.content, { flag: "wx", mode: 384 });
49582
+ writeFileSync14(tempPath, options.content, { flag: "wx", mode: 384 });
48465
49583
  proc = Bun.spawn([...interpreter.command, isAbsolute37(tempPath) ? tempPath : `./${tempPath}`, ...options.args ?? []], {
48466
49584
  stdin: new Response(options.stdin),
48467
49585
  stdout: "pipe",
@@ -48542,9 +49660,9 @@ var init_run = __esm(() => {
48542
49660
  // src/lib/sumi-stop-plugin.ts
48543
49661
  import { spawn as spawn5 } from "child_process";
48544
49662
  import { createHash as createHash33 } from "crypto";
48545
- import { closeSync as closeSync26, constants as constants25, fstatSync as fstatSync26, lstatSync as lstatSync37, openSync as openSync26, readFileSync as readFileSync27, realpathSync as realpathSync23 } from "fs";
48546
- import { homedir as homedir16 } from "os";
48547
- import { dirname as dirname37, isAbsolute as isAbsolute38, normalize as normalize4 } from "path";
49663
+ import { closeSync as closeSync26, constants as constants25, fstatSync as fstatSync26, lstatSync as lstatSync37, openSync as openSync26, readFileSync as readFileSync29, realpathSync as realpathSync23 } from "fs";
49664
+ import { homedir as homedir17 } from "os";
49665
+ import { dirname as dirname38, isAbsolute as isAbsolute38, normalize as normalize4 } from "path";
48548
49666
  function isSumiStopReviewEnvelope(v) {
48549
49667
  if (!record6(v) || !keys3(v, ["schema", "sessionId", "turnId", "inputRevision", "capturedAt", "lastUserPrompt", "lastAssistantMessage", "runtime"], ["goal", "goalAvailability"]) || v.schema !== "hooks.stop-review.v1" || !identifier4(v.sessionId) || !identifier4(v.turnId) || !identifier4(v.inputRevision) || typeof v.capturedAt !== "string" || !Number.isFinite(Date.parse(v.capturedAt)) || !text3(v.lastUserPrompt) || !text3(v.lastAssistantMessage) || !record6(v.runtime))
48550
49668
  return false;
@@ -48599,18 +49717,18 @@ function verifySumiStopReviewCommand(command, expected) {
48599
49717
  if (!pathForm(command) || !digest6(expected) || realpathSync23(command) !== command)
48600
49718
  return false;
48601
49719
  const owners = [0, process.getuid?.()];
48602
- for (let path = dirname37(command);; path = dirname37(path)) {
49720
+ for (let path = dirname38(command);; path = dirname38(path)) {
48603
49721
  const stat2 = lstatSync37(path);
48604
49722
  if (!stat2.isDirectory() || !owners.includes(stat2.uid) || (stat2.mode & 18) !== 0)
48605
49723
  return false;
48606
- if (path === dirname37(path))
49724
+ if (path === dirname38(path))
48607
49725
  break;
48608
49726
  }
48609
49727
  fd = openSync26(command, constants25.O_RDONLY | constants25.O_NOFOLLOW | constants25.O_NONBLOCK);
48610
49728
  const before = fstatSync26(fd);
48611
49729
  if (!before.isFile() || !owners.includes(before.uid) || (before.mode & 18) !== 0 || (before.mode & 64) === 0 || before.size < 1 || before.size > 268435456)
48612
49730
  return false;
48613
- const bytes = readFileSync27(fd), after = fstatSync26(fd), target = lstatSync37(command);
49731
+ const bytes = readFileSync29(fd), after = fstatSync26(fd), target = lstatSync37(command);
48614
49732
  return bytes.length === before.size && before.size === after.size && before.ino === after.ino && before.mtimeMs === after.mtimeMs && before.mode === after.mode && target.isFile() && target.ino === before.ino && target.dev === before.dev && target.size === before.size && target.mtimeMs === before.mtimeMs && realpathSync23(command) === command && createHash33("sha256").update(bytes).digest("hex") === expected;
48615
49733
  } catch {
48616
49734
  return false;
@@ -48640,7 +49758,7 @@ async function requestParentStopReview(envelope, harness, pins, dependencies = {
48640
49758
  const input2 = JSON.stringify(envelope) + `
48641
49759
  `;
48642
49760
  {
48643
- const home = source.HOME || source.USERPROFILE || homedir16();
49761
+ const home = source.HOME || source.USERPROFILE || homedir17();
48644
49762
  if (!pathForm(home))
48645
49763
  throw new Error(`${harness}_stop_review_invalid_home`);
48646
49764
  const context3 = projectStopReviewClientContext(source);
@@ -48841,25 +49959,25 @@ __export(exports_opencode_stop_install, {
48841
49959
  applyOpenCodeStopInstall: () => applyOpenCodeStopInstall,
48842
49960
  OpenCodeStopInstallError: () => OpenCodeStopInstallError
48843
49961
  });
48844
- import { createHash as createHash35, randomUUID as randomUUID10 } from "crypto";
49962
+ import { createHash as createHash35, randomUUID as randomUUID11 } from "crypto";
48845
49963
  import {
48846
49964
  closeSync as closeSync27,
48847
49965
  constants as constants26,
48848
- existsSync as existsSync17,
49966
+ existsSync as existsSync18,
48849
49967
  fstatSync as fstatSync27,
48850
49968
  fsyncSync as fsyncSync10,
48851
49969
  linkSync as linkSync4,
48852
49970
  lstatSync as lstatSync38,
48853
- mkdirSync as mkdirSync15,
49971
+ mkdirSync as mkdirSync16,
48854
49972
  openSync as openSync27,
48855
- readFileSync as readFileSync28,
49973
+ readFileSync as readFileSync30,
48856
49974
  realpathSync as realpathSync25,
48857
- renameSync as renameSync7,
48858
- unlinkSync as unlinkSync8,
48859
- writeFileSync as writeFileSync14
49975
+ renameSync as renameSync8,
49976
+ unlinkSync as unlinkSync9,
49977
+ writeFileSync as writeFileSync15
48860
49978
  } from "fs";
48861
- import { homedir as homedir17 } from "os";
48862
- import { dirname as dirname38, isAbsolute as isAbsolute39, join as join45, resolve as resolve38 } from "path";
49979
+ import { homedir as homedir18 } from "os";
49980
+ import { dirname as dirname39, isAbsolute as isAbsolute39, join as join46, resolve as resolve38 } from "path";
48863
49981
  import { fileURLToPath as fileURLToPath5, pathToFileURL as pathToFileURL2 } from "url";
48864
49982
  function openCodeConfigPath(options) {
48865
49983
  const env = options.env ?? process.env;
@@ -48867,22 +49985,22 @@ function openCodeConfigPath(options) {
48867
49985
  const cwd = options.cwd ?? process.cwd();
48868
49986
  if (!isAbsolute39(cwd))
48869
49987
  throw new OpenCodeStopInstallError("input_invalid");
48870
- return join45(resolve38(cwd), "opencode.json");
49988
+ return join46(resolve38(cwd), "opencode.json");
48871
49989
  }
48872
49990
  const xdg = env.XDG_CONFIG_HOME;
48873
- const base = xdg && isAbsolute39(xdg) ? xdg : join45(options.home ?? homedir17(), ".config");
48874
- return join45(resolve38(base), "opencode", "opencode.json");
49991
+ const base = xdg && isAbsolute39(xdg) ? xdg : join46(options.home ?? homedir18(), ".config");
49992
+ return join46(resolve38(base), "opencode", "opencode.json");
48875
49993
  }
48876
49994
  function installedOpenCodeStopPins(options = {}) {
48877
- const home = realpathSync25(options.home ?? homedir17());
49995
+ const home = realpathSync25(options.home ?? homedir18());
48878
49996
  const find = (candidates, name) => {
48879
- const found = candidates.find((candidate) => existsSync17(candidate));
49997
+ const found = candidates.find((candidate) => existsSync18(candidate));
48880
49998
  if (!found)
48881
49999
  throw new OpenCodeStopInstallError("plugin_missing", `${name} is not built; build or reinstall @hasna/hooks`);
48882
50000
  return realpathSync25(found);
48883
50001
  };
48884
- const plugin = options.plugin ?? find([join45(import.meta.dir, "../../dist/opencode-stop-plugin.js"), join45(import.meta.dir, "../dist/opencode-stop-plugin.js")], "dist/opencode-stop-plugin.js");
48885
- const hooksCommand = options.hooksCommand ?? find([join45(import.meta.dir, "../../bin/index.js"), join45(import.meta.dir, "index.js")], "bin/index.js");
50002
+ const plugin = options.plugin ?? find([join46(import.meta.dir, "../../dist/opencode-stop-plugin.js"), join46(import.meta.dir, "../dist/opencode-stop-plugin.js")], "dist/opencode-stop-plugin.js");
50003
+ const hooksCommand = options.hooksCommand ?? find([join46(import.meta.dir, "../../bin/index.js"), join46(import.meta.dir, "index.js")], "bin/index.js");
48886
50004
  const runtimeCommand = options.runtimeCommand ?? realpathSync25(process.execPath);
48887
50005
  for (const file2 of [plugin, hooksCommand]) {
48888
50006
  if (!nativeSafetyBindingDurable(file2, home))
@@ -48912,24 +50030,24 @@ function openCodeStopEntry(pins) {
48912
50030
  return [pathToFileURL2(pins.plugin).href, options];
48913
50031
  }
48914
50032
  function safeAncestry(path) {
48915
- for (let cursor = path;; cursor = dirname38(cursor)) {
50033
+ for (let cursor = path;; cursor = dirname39(cursor)) {
48916
50034
  const stat2 = lstatSync38(cursor, { throwIfNoEntry: false });
48917
50035
  if (!stat2) {
48918
- if (dirname38(cursor) === cursor)
50036
+ if (dirname39(cursor) === cursor)
48919
50037
  throw new OpenCodeStopInstallError("config_unsafe");
48920
50038
  continue;
48921
50039
  }
48922
50040
  if (!stat2.isDirectory() || !owner3(stat2.uid) || stat2.mode & 18) {
48923
50041
  throw new OpenCodeStopInstallError("config_unsafe", `${cursor} is not an owner-controlled directory that only its owner can write`);
48924
50042
  }
48925
- if (dirname38(cursor) === cursor)
50043
+ if (dirname39(cursor) === cursor)
48926
50044
  return;
48927
50045
  }
48928
50046
  }
48929
50047
  function readConfig(path) {
48930
50048
  if (!isAbsolute39(path))
48931
50049
  throw new OpenCodeStopInstallError("input_invalid");
48932
- safeAncestry(dirname38(path));
50050
+ safeAncestry(dirname39(path));
48933
50051
  let fd;
48934
50052
  try {
48935
50053
  fd = openSync27(path, constants26.O_RDONLY | constants26.O_NOFOLLOW | constants26.O_NONBLOCK);
@@ -48944,7 +50062,7 @@ function readConfig(path) {
48944
50062
  throw new OpenCodeStopInstallError("config_unsafe", `${path} is writable by group or others or not owned by this user`);
48945
50063
  if (stat2.size > MAX_CONFIG_BYTES)
48946
50064
  throw new OpenCodeStopInstallError("config_invalid", "config exceeds its size bound");
48947
- const text4 = readFileSync28(fd, "utf8");
50065
+ const text4 = readFileSync30(fd, "utf8");
48948
50066
  let config2;
48949
50067
  try {
48950
50068
  config2 = JSON.parse(text4);
@@ -48962,7 +50080,7 @@ function readConfig(path) {
48962
50080
  }
48963
50081
  function siblingConflict(path) {
48964
50082
  for (const name of SIBLINGS) {
48965
- const sibling = join45(dirname38(path), name);
50083
+ const sibling = join46(dirname39(path), name);
48966
50084
  let fd;
48967
50085
  try {
48968
50086
  fd = openSync27(sibling, constants26.O_RDONLY | constants26.O_NOFOLLOW | constants26.O_NONBLOCK);
@@ -48977,7 +50095,7 @@ function siblingConflict(path) {
48977
50095
  throw new OpenCodeStopInstallError("config_unsafe");
48978
50096
  if (stat2.size > MAX_CONFIG_BYTES)
48979
50097
  throw new OpenCodeStopInstallError("config_invalid", "sibling config exceeds its size bound");
48980
- const text4 = readFileSync28(fd, "utf8");
50098
+ const text4 = readFileSync30(fd, "utf8");
48981
50099
  const after = fstatSync27(fd);
48982
50100
  if (Buffer.byteLength(text4) > MAX_CONFIG_BYTES || stat2.size !== after.size || stat2.mtimeMs !== after.mtimeMs) {
48983
50101
  throw new OpenCodeStopInstallError("config_changed");
@@ -49037,9 +50155,9 @@ function applyOpenCodeStopInstall(options) {
49037
50155
  throw new OpenCodeStopInstallError("config_precondition_required", `pass --expected-config-sha256 ${first.plan.currentSha256}`);
49038
50156
  if (options.expectedSha256 !== first.plan.currentSha256)
49039
50157
  throw new OpenCodeStopInstallError("config_changed");
49040
- const directory3 = dirname38(options.path);
49041
- if (!existsSync17(directory3))
49042
- mkdirSync15(directory3, { recursive: true, mode: 448 });
50158
+ const directory3 = dirname39(options.path);
50159
+ if (!existsSync18(directory3))
50160
+ mkdirSync16(directory3, { recursive: true, mode: 448 });
49043
50161
  safeAncestry(directory3);
49044
50162
  const lock = options.path + ".hasna-hooks.lock";
49045
50163
  let lockFD;
@@ -49049,10 +50167,10 @@ function applyOpenCodeStopInstall(options) {
49049
50167
  throw new OpenCodeStopInstallError("config_busy");
49050
50168
  }
49051
50169
  const lockIdentity = fstatSync27(lockFD);
49052
- const temporary = join45(directory3, `.opencode.json.${randomUUID10()}`);
50170
+ const temporary = join46(directory3, `.opencode.json.${randomUUID11()}`);
49053
50171
  let temporaryIdentity;
49054
50172
  try {
49055
- writeFileSync14(lockFD, JSON.stringify({ pid: process.pid, expectedSha256: options.expectedSha256 }));
50173
+ writeFileSync15(lockFD, JSON.stringify({ pid: process.pid, expectedSha256: options.expectedSha256 }));
49056
50174
  fsyncSync10(lockFD);
49057
50175
  const state = readConfig(options.path);
49058
50176
  if (state.sha256 !== options.expectedSha256)
@@ -49060,25 +50178,25 @@ function applyOpenCodeStopInstall(options) {
49060
50178
  const next = plan(state, options.pins);
49061
50179
  if (state.text !== undefined) {
49062
50180
  const backup = `${options.path}.before-${state.sha256}`;
49063
- if (existsSync17(backup)) {
49064
- if (hash5(readFileSync28(backup)) !== state.sha256)
50181
+ if (existsSync18(backup)) {
50182
+ if (hash5(readFileSync30(backup)) !== state.sha256)
49065
50183
  throw new OpenCodeStopInstallError("config_changed", "a different preserved original already exists");
49066
50184
  } else {
49067
50185
  const fd2 = openSync27(backup, constants26.O_CREAT | constants26.O_EXCL | constants26.O_WRONLY, 384);
49068
50186
  try {
49069
- writeFileSync14(fd2, state.text);
50187
+ writeFileSync15(fd2, state.text);
49070
50188
  fsyncSync10(fd2);
49071
50189
  } finally {
49072
50190
  closeSync27(fd2);
49073
50191
  }
49074
- if (hash5(readFileSync28(backup)) !== state.sha256)
50192
+ if (hash5(readFileSync30(backup)) !== state.sha256)
49075
50193
  throw new OpenCodeStopInstallError("config_changed", "preserved original did not read back");
49076
50194
  }
49077
50195
  }
49078
50196
  const fd = openSync27(temporary, constants26.O_CREAT | constants26.O_EXCL | constants26.O_WRONLY, state.mode);
49079
50197
  try {
49080
50198
  temporaryIdentity = fstatSync27(fd);
49081
- writeFileSync14(fd, next.text);
50199
+ writeFileSync15(fd, next.text);
49082
50200
  fsyncSync10(fd);
49083
50201
  } finally {
49084
50202
  closeSync27(fd);
@@ -49086,10 +50204,10 @@ function applyOpenCodeStopInstall(options) {
49086
50204
  if (readConfig(options.path).sha256 !== state.sha256)
49087
50205
  throw new OpenCodeStopInstallError("config_changed");
49088
50206
  if (state.text !== undefined)
49089
- renameSync7(temporary, options.path);
50207
+ renameSync8(temporary, options.path);
49090
50208
  else {
49091
50209
  linkSync4(temporary, options.path);
49092
- unlinkSync8(temporary);
50210
+ unlinkSync9(temporary);
49093
50211
  }
49094
50212
  syncDirectory4(directory3);
49095
50213
  const after = readConfig(options.path);
@@ -49106,10 +50224,10 @@ function applyOpenCodeStopInstall(options) {
49106
50224
  closeSync27(lockFD);
49107
50225
  const currentTemporary = lstatSync38(temporary, { throwIfNoEntry: false });
49108
50226
  if (temporaryIdentity && currentTemporary?.dev === temporaryIdentity.dev && currentTemporary.ino === temporaryIdentity.ino)
49109
- unlinkSync8(temporary);
50227
+ unlinkSync9(temporary);
49110
50228
  const currentLock = lstatSync38(lock, { throwIfNoEntry: false });
49111
50229
  if (currentLock?.dev === lockIdentity.dev && currentLock.ino === lockIdentity.ino)
49112
- unlinkSync8(lock);
50230
+ unlinkSync9(lock);
49113
50231
  }
49114
50232
  }
49115
50233
  function entryVerified(entry) {
@@ -49131,7 +50249,7 @@ function verifyOpenCodeStopInstall(options) {
49131
50249
  throw new OpenCodeStopInstallError(owned.length ? "config_conflict" : "entry_missing");
49132
50250
  if (!entryVerified(owned[0]))
49133
50251
  throw new OpenCodeStopInstallError("pins_drifted", "a pinned file changed or is no longer eligible; run the install again");
49134
- const home = realpathSync25(options.home ?? homedir17());
50252
+ const home = realpathSync25(options.home ?? homedir18());
49135
50253
  const pins = owned[0][1];
49136
50254
  return {
49137
50255
  ok: true,
@@ -49173,13 +50291,13 @@ __export(exports_sumi_stop_install, {
49173
50291
  applySumiStopInstall: () => applySumiStopInstall,
49174
50292
  SumiStopInstallError: () => SumiStopInstallError
49175
50293
  });
49176
- import { createHash as createHash37, randomUUID as randomUUID11 } from "crypto";
49177
- import { closeSync as closeSync28, constants as constants27, existsSync as existsSync18, fstatSync as fstatSync28, fsyncSync as fsyncSync11, linkSync as linkSync6, lstatSync as lstatSync39, mkdirSync as mkdirSync16, openSync as openSync28, readFileSync as readFileSync29, realpathSync as realpathSync26, renameSync as renameSync8, unlinkSync as unlinkSync9, writeFileSync as writeFileSync15 } from "fs";
49178
- import { homedir as homedir18 } from "os";
49179
- import { basename as basename19, dirname as dirname39, isAbsolute as isAbsolute40, join as join46, resolve as resolve39 } from "path";
50294
+ import { createHash as createHash37, randomUUID as randomUUID12 } from "crypto";
50295
+ import { closeSync as closeSync28, constants as constants27, existsSync as existsSync19, fstatSync as fstatSync28, fsyncSync as fsyncSync11, linkSync as linkSync6, lstatSync as lstatSync39, mkdirSync as mkdirSync17, openSync as openSync28, readFileSync as readFileSync31, realpathSync as realpathSync26, renameSync as renameSync9, unlinkSync as unlinkSync10, writeFileSync as writeFileSync16 } from "fs";
50296
+ import { homedir as homedir19 } from "os";
50297
+ import { basename as basename20, dirname as dirname40, isAbsolute as isAbsolute40, join as join47, resolve as resolve39 } from "path";
49180
50298
  function sumiConfigRoot(options) {
49181
50299
  const env = options.env ?? process.env;
49182
- const home = options.home ?? env.SUMI_TEST_HOME ?? homedir18();
50300
+ const home = options.home ?? env.SUMI_TEST_HOME ?? homedir19();
49183
50301
  const selected = (value) => value?.trim() ? value : undefined;
49184
50302
  const expand = (value) => resolve39(value === "~" ? home : value.startsWith("~/") || value.startsWith("~\\") ? resolve39(home, value.slice(2)) : value);
49185
50303
  if (env.SUMI_CONFIG_DIR !== undefined) {
@@ -49189,10 +50307,10 @@ function sumiConfigRoot(options) {
49189
50307
  }
49190
50308
  const xdg = selected(env.XDG_CONFIG_HOME);
49191
50309
  if (xdg)
49192
- return join46(expand(xdg), "sumi");
50310
+ return join47(expand(xdg), "sumi");
49193
50311
  const custom2 = selected(env.SUMI_HOME);
49194
50312
  if (custom2)
49195
- return join46(expand(custom2), "config");
50313
+ return join47(expand(custom2), "config");
49196
50314
  const canonical10 = resolve39(home, ".hasna-internal/sumi", "config");
49197
50315
  const legacy = resolve39(home, ".config/sumi");
49198
50316
  const current2 = lstatSync39(canonical10, { throwIfNoEntry: false });
@@ -49208,24 +50326,24 @@ function sumiStopPluginPath(options) {
49208
50326
  const disabled = env.SUMI_CONFIG_PROJECT_DISABLE ?? env.SUMI_DISABLE_PROJECT_CONFIG;
49209
50327
  if (disabled === "1" || disabled?.toLowerCase() === "true")
49210
50328
  throw new SumiStopInstallError("project_config_disabled");
49211
- const globalRoot = dirname39(dirname39(sumiStopPluginPath({ ...options, scope: "global" })));
50329
+ const globalRoot = dirname40(dirname40(sumiStopPluginPath({ ...options, scope: "global" })));
49212
50330
  const cwd = options.cwd ?? process.cwd();
49213
- if (existsSync18(cwd) && realpathSync26(cwd) === globalRoot)
50331
+ if (existsSync19(cwd) && realpathSync26(cwd) === globalRoot)
49214
50332
  throw new SumiStopInstallError("project_config_disabled", "Sumi does not discover project config from its global config directory");
49215
50333
  }
49216
- const directory3 = options.scope === "project" ? join46(options.cwd ?? process.cwd(), ".sumi") : sumiConfigRoot(options);
50334
+ const directory3 = options.scope === "project" ? join47(options.cwd ?? process.cwd(), ".sumi") : sumiConfigRoot(options);
49217
50335
  if (!isAbsolute40(directory3))
49218
50336
  throw new SumiStopInstallError("input_invalid", "Sumi config paths must be absolute");
49219
50337
  let ancestor = resolve39(directory3);
49220
50338
  const missing2 = [];
49221
- while (!existsSync18(ancestor)) {
49222
- missing2.unshift(basename19(ancestor));
49223
- ancestor = dirname39(ancestor);
50339
+ while (!existsSync19(ancestor)) {
50340
+ missing2.unshift(basename20(ancestor));
50341
+ ancestor = dirname40(ancestor);
49224
50342
  }
49225
- return join46(realpathSync26(ancestor), ...missing2, "plugins", `${NAME2}.js`);
50343
+ return join47(realpathSync26(ancestor), ...missing2, "plugins", `${NAME2}.js`);
49226
50344
  }
49227
50345
  function installedSumiStopPins(options = {}) {
49228
- const candidate = options.plugin ?? [join46(import.meta.dir, "../../dist/sumi-stop-plugin.js"), join46(import.meta.dir, "../dist/sumi-stop-plugin.js")].find(existsSync18);
50346
+ const candidate = options.plugin ?? [join47(import.meta.dir, "../../dist/sumi-stop-plugin.js"), join47(import.meta.dir, "../dist/sumi-stop-plugin.js")].find(existsSync19);
49229
50347
  if (!candidate)
49230
50348
  throw new SumiStopInstallError("plugin_missing", "build or reinstall @hasna/hooks");
49231
50349
  try {
@@ -49271,18 +50389,18 @@ export default createSumiStopReviewPlugin(pins);
49271
50389
  `;
49272
50390
  }
49273
50391
  function safeAncestry2(path) {
49274
- for (let cursor = path;; cursor = dirname39(cursor)) {
50392
+ for (let cursor = path;; cursor = dirname40(cursor)) {
49275
50393
  const stat2 = lstatSync39(cursor, { throwIfNoEntry: false });
49276
50394
  if (stat2 && (!stat2.isDirectory() || !owner4(stat2.uid) || stat2.mode & 18))
49277
50395
  throw new SumiStopInstallError("config_unsafe");
49278
- if (dirname39(cursor) === cursor)
50396
+ if (dirname40(cursor) === cursor)
49279
50397
  return;
49280
50398
  }
49281
50399
  }
49282
50400
  function readState(path) {
49283
50401
  if (!isAbsolute40(path) || !path.endsWith(`/plugins/${NAME2}.js`))
49284
50402
  throw new SumiStopInstallError("input_invalid");
49285
- safeAncestry2(dirname39(path));
50403
+ safeAncestry2(dirname40(path));
49286
50404
  let fd;
49287
50405
  try {
49288
50406
  fd = openSync28(path, constants27.O_RDONLY | constants27.O_NOFOLLOW | constants27.O_NONBLOCK);
@@ -49295,7 +50413,7 @@ function readState(path) {
49295
50413
  const stat2 = fstatSync28(fd);
49296
50414
  if (!stat2.isFile() || !owner4(stat2.uid) || stat2.mode & 18 || stat2.size > MAX_BYTES)
49297
50415
  throw new SumiStopInstallError("config_unsafe");
49298
- const text4 = readFileSync29(fd, "utf8");
50416
+ const text4 = readFileSync31(fd, "utf8");
49299
50417
  if (Buffer.byteLength(text4) > MAX_BYTES)
49300
50418
  throw new SumiStopInstallError("config_unsafe");
49301
50419
  return { path, text: text4, sha256: hash7(text4), mode: stat2.mode & 511 };
@@ -49320,11 +50438,11 @@ function storedPins(state) {
49320
50438
  }
49321
50439
  }
49322
50440
  function conflicts(path) {
49323
- const root = dirname39(dirname39(path));
50441
+ const root = dirname40(dirname40(path));
49324
50442
  for (const dir of ["plugin", "plugins"]) {
49325
- safeAncestry2(join46(root, dir));
50443
+ safeAncestry2(join47(root, dir));
49326
50444
  for (const suffix of ["", ".js", ".ts"]) {
49327
- const other = join46(root, dir, NAME2 + suffix);
50445
+ const other = join47(root, dir, NAME2 + suffix);
49328
50446
  if (other !== path && lstatSync39(other, { throwIfNoEntry: false }))
49329
50447
  throw new SumiStopInstallError("config_conflict", "a second native wrapper path exists");
49330
50448
  }
@@ -49367,9 +50485,9 @@ function applySumiStopInstall(options) {
49367
50485
  throw new SumiStopInstallError("config_precondition_required", `pass --expected-config-sha256 ${first.plan.currentSha256}`);
49368
50486
  if (options.expectedSha256 !== first.plan.currentSha256)
49369
50487
  throw new SumiStopInstallError("config_changed");
49370
- const directory3 = dirname39(options.path);
49371
- if (!existsSync18(directory3))
49372
- mkdirSync16(directory3, { recursive: true, mode: 448 });
50488
+ const directory3 = dirname40(options.path);
50489
+ if (!existsSync19(directory3))
50490
+ mkdirSync17(directory3, { recursive: true, mode: 448 });
49373
50491
  safeAncestry2(directory3);
49374
50492
  const lock = options.path + ".hasna-hooks.lock";
49375
50493
  let lockFD;
@@ -49379,10 +50497,10 @@ function applySumiStopInstall(options) {
49379
50497
  throw new SumiStopInstallError("config_busy");
49380
50498
  }
49381
50499
  const lockIdentity = fstatSync28(lockFD);
49382
- const temporary = join46(directory3, `.hasna-hooks-stop-review.${randomUUID11()}.tmp`);
50500
+ const temporary = join47(directory3, `.hasna-hooks-stop-review.${randomUUID12()}.tmp`);
49383
50501
  let temporaryIdentity;
49384
50502
  try {
49385
- writeFileSync15(lockFD, JSON.stringify({ pid: process.pid, expectedSha256: options.expectedSha256 }));
50503
+ writeFileSync16(lockFD, JSON.stringify({ pid: process.pid, expectedSha256: options.expectedSha256 }));
49386
50504
  fsyncSync11(lockFD);
49387
50505
  const state = readState(options.path);
49388
50506
  if (state.sha256 !== options.expectedSha256)
@@ -49390,13 +50508,13 @@ function applySumiStopInstall(options) {
49390
50508
  const next = plan2(state, options.pins);
49391
50509
  if (state.text !== undefined) {
49392
50510
  const backup = `${options.path}.before-${state.sha256}`;
49393
- if (existsSync18(backup)) {
50511
+ if (existsSync19(backup)) {
49394
50512
  if (pinEligibleFile(backup, MAX_BYTES) !== state.sha256)
49395
50513
  throw new SumiStopInstallError("config_changed", "a different preserved original already exists");
49396
50514
  } else {
49397
50515
  const fd2 = openSync28(backup, constants27.O_CREAT | constants27.O_EXCL | constants27.O_WRONLY, 384);
49398
50516
  try {
49399
- writeFileSync15(fd2, state.text);
50517
+ writeFileSync16(fd2, state.text);
49400
50518
  fsyncSync11(fd2);
49401
50519
  } finally {
49402
50520
  closeSync28(fd2);
@@ -49408,7 +50526,7 @@ function applySumiStopInstall(options) {
49408
50526
  const fd = openSync28(temporary, constants27.O_CREAT | constants27.O_EXCL | constants27.O_WRONLY, state.mode);
49409
50527
  try {
49410
50528
  temporaryIdentity = fstatSync28(fd);
49411
- writeFileSync15(fd, next.text);
50529
+ writeFileSync16(fd, next.text);
49412
50530
  fsyncSync11(fd);
49413
50531
  } finally {
49414
50532
  closeSync28(fd);
@@ -49419,10 +50537,10 @@ function applySumiStopInstall(options) {
49419
50537
  if (!pinsVerified(options.pins))
49420
50538
  throw new SumiStopInstallError("pins_drifted");
49421
50539
  if (state.text !== undefined)
49422
- renameSync8(temporary, options.path);
50540
+ renameSync9(temporary, options.path);
49423
50541
  else {
49424
50542
  linkSync6(temporary, options.path);
49425
- unlinkSync9(temporary);
50543
+ unlinkSync10(temporary);
49426
50544
  }
49427
50545
  syncDirectory5(directory3);
49428
50546
  const after = readState(options.path);
@@ -49439,10 +50557,10 @@ function applySumiStopInstall(options) {
49439
50557
  closeSync28(lockFD);
49440
50558
  const currentTemporary = lstatSync39(temporary, { throwIfNoEntry: false });
49441
50559
  if (temporaryIdentity && currentTemporary?.dev === temporaryIdentity.dev && currentTemporary.ino === temporaryIdentity.ino)
49442
- unlinkSync9(temporary);
50560
+ unlinkSync10(temporary);
49443
50561
  const currentLock = lstatSync39(lock, { throwIfNoEntry: false });
49444
50562
  if (currentLock?.dev === lockIdentity.dev && currentLock.ino === lockIdentity.ino)
49445
- unlinkSync9(lock);
50563
+ unlinkSync10(lock);
49446
50564
  }
49447
50565
  }
49448
50566
  function verifySumiStopInstall(options) {
@@ -49453,7 +50571,7 @@ function verifySumiStopInstall(options) {
49453
50571
  throw new SumiStopInstallError("entry_missing");
49454
50572
  if (!pinsVerified(pins))
49455
50573
  throw new SumiStopInstallError("pins_drifted");
49456
- const home = realpathSync26(options.home ?? homedir18());
50574
+ const home = realpathSync26(options.home ?? homedir19());
49457
50575
  return {
49458
50576
  ok: true,
49459
50577
  target: "sumi",
@@ -49491,15 +50609,15 @@ __export(exports_custom_install, {
49491
50609
  installCustomSource: () => installCustomSource,
49492
50610
  ensureCustomDir: () => ensureCustomDir
49493
50611
  });
49494
- import { existsSync as existsSync19, mkdirSync as mkdirSync17, mkdtempSync as mkdtempSync2, readFileSync as readFileSync30, rmSync as rmSync6 } from "fs";
49495
- import { join as join47 } from "path";
49496
- import { tmpdir as tmpdir2 } from "os";
50612
+ import { existsSync as existsSync20, mkdirSync as mkdirSync18, mkdtempSync as mkdtempSync2, readFileSync as readFileSync32, rmSync as rmSync6 } from "fs";
50613
+ import { join as join48 } from "path";
50614
+ import { tmpdir as tmpdir3 } from "os";
49497
50615
  function manifestAt(dir) {
49498
- const path = join47(dir, "manifest.json");
49499
- if (!existsSync19(path))
50616
+ const path = join48(dir, "manifest.json");
50617
+ if (!existsSync20(path))
49500
50618
  return;
49501
50619
  try {
49502
- return parseManifest(readFileSync30(path, "utf-8"));
50620
+ return parseManifest(readFileSync32(path, "utf-8"));
49503
50621
  } catch {
49504
50622
  return;
49505
50623
  }
@@ -49518,8 +50636,8 @@ function writeFromManifest(manifest, srcDir, source, kind) {
49518
50636
  return { name, version: manifest.version, kind, source, dir, scriptPath };
49519
50637
  }
49520
50638
  async function cloneToTemp(gitUrl) {
49521
- const tmp = mkdtempSync2(join47(tmpdir2(), "hooks-install-"));
49522
- const proc = Bun.spawn(["git", "clone", "--depth", "1", "--quiet", gitUrl, join47(tmp, "repo")], {
50639
+ const tmp = mkdtempSync2(join48(tmpdir3(), "hooks-install-"));
50640
+ const proc = Bun.spawn(["git", "clone", "--depth", "1", "--quiet", gitUrl, join48(tmp, "repo")], {
49523
50641
  stdout: "pipe",
49524
50642
  stderr: "pipe"
49525
50643
  });
@@ -49532,7 +50650,7 @@ async function cloneToTemp(gitUrl) {
49532
50650
  rmSync6(tmp, { recursive: true, force: true });
49533
50651
  throw new Error(`git clone failed (${exitCode}): ${stderr.trim()}`);
49534
50652
  }
49535
- return join47(tmp, "repo");
50653
+ return join48(tmp, "repo");
49536
50654
  }
49537
50655
  function isGitUrl(value) {
49538
50656
  return value.startsWith("git@") || value.startsWith("ssh://") || value.startsWith("file://") || value.endsWith(".git");
@@ -49542,7 +50660,7 @@ function isCustomSource(value) {
49542
50660
  return true;
49543
50661
  if (value.startsWith("http://") || value.startsWith("https://"))
49544
50662
  return true;
49545
- return existsSync19(value);
50663
+ return existsSync20(value);
49546
50664
  }
49547
50665
  async function installCustomSource(source) {
49548
50666
  if (isGitUrl(source)) {
@@ -49556,11 +50674,11 @@ async function installCustomSource(source) {
49556
50674
  if (source.startsWith("http://") || source.startsWith("https://")) {
49557
50675
  return installManifestUrl(source);
49558
50676
  }
49559
- if (!existsSync19(source)) {
50677
+ if (!existsSync20(source)) {
49560
50678
  throw new Error(`No such local path: ${source}`);
49561
50679
  }
49562
50680
  if (source.endsWith("manifest.json")) {
49563
- const manifest = parseManifest(readFileSync30(source, "utf-8"));
50681
+ const manifest = parseManifest(readFileSync32(source, "utf-8"));
49564
50682
  return writeFromManifest(manifest, source.substring(0, source.lastIndexOf("/")), source, "local");
49565
50683
  }
49566
50684
  return copyManifestDir(source, source, "local");
@@ -49591,7 +50709,7 @@ async function installManifestUrl(url2) {
49591
50709
  }
49592
50710
  function ensureCustomDir() {
49593
50711
  const dir = getCustomHooksDir();
49594
- mkdirSync17(dir, { recursive: true });
50712
+ mkdirSync18(dir, { recursive: true });
49595
50713
  return dir;
49596
50714
  }
49597
50715
  var init_custom_install = __esm(() => {
@@ -49609,14 +50727,14 @@ __export(exports_sync, {
49609
50727
  fetchPinnedHook: () => fetchPinnedHook,
49610
50728
  commitSyncArtifacts: () => commitSyncArtifacts
49611
50729
  });
49612
- import { createHash as createHash38, randomUUID as randomUUID12 } from "crypto";
49613
- import { readFileSync as readFileSync31, lstatSync as lstatSync40, mkdirSync as mkdirSync18, writeFileSync as writeFileSync16, accessSync as accessSync5, constants as constants28, existsSync as existsSync20 } from "fs";
49614
- import { dirname as dirname40, join as join48, resolve as resolve40, sep as sep18 } from "path";
50730
+ import { createHash as createHash38, randomUUID as randomUUID13 } from "crypto";
50731
+ import { readFileSync as readFileSync33, lstatSync as lstatSync40, mkdirSync as mkdirSync19, writeFileSync as writeFileSync17, accessSync as accessSync5, constants as constants28, existsSync as existsSync21 } from "fs";
50732
+ import { dirname as dirname41, join as join49, resolve as resolve40, sep as sep18 } from "path";
49615
50733
  function sha256OfText(text4) {
49616
50734
  return createHash38("sha256").update(text4).digest("hex");
49617
50735
  }
49618
50736
  function sha256OfPath(path) {
49619
- return createHash38("sha256").update(readFileSync31(path)).digest("hex");
50737
+ return createHash38("sha256").update(readFileSync33(path)).digest("hex");
49620
50738
  }
49621
50739
  function collectBundledCatalog() {
49622
50740
  const out = [];
@@ -49776,7 +50894,7 @@ function prepareRegistryCommit(staged) {
49776
50894
  if (!lstatSync40(path).isFile())
49777
50895
  throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
49778
50896
  accessSync5(path, constants28.W_OK);
49779
- originals.set(path, readFileSync31(path));
50897
+ originals.set(path, readFileSync33(path));
49780
50898
  } catch (error61) {
49781
50899
  if (error61.code !== "ENOENT")
49782
50900
  throw error61;
@@ -49787,10 +50905,10 @@ function prepareRegistryCommit(staged) {
49787
50905
  const script = resolve40(root, item.scriptRel);
49788
50906
  if (script !== root && !script.startsWith(root + sep18))
49789
50907
  throw new ScriptContainmentError(script, root, item.scriptRel);
49790
- const manifest = join48(root, "manifest.json");
50908
+ const manifest = join49(root, "manifest.json");
49791
50909
  if (script === manifest || script === root)
49792
50910
  throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
49793
- for (let path = dirname40(script);; path = dirname40(path)) {
50911
+ for (let path = dirname41(script);; path = dirname41(path)) {
49794
50912
  try {
49795
50913
  if (!lstatSync40(path).isDirectory())
49796
50914
  throw new Error("REGISTRY_SYNC_DESTINATION_INVALID");
@@ -49802,24 +50920,24 @@ function prepareRegistryCommit(staged) {
49802
50920
  if (path === root)
49803
50921
  break;
49804
50922
  }
49805
- if (existsSync20(root))
50923
+ if (existsSync21(root))
49806
50924
  assertContained(script, root, item.scriptRel);
49807
50925
  inspectFile(script);
49808
50926
  inspectFile(manifest);
49809
50927
  }
49810
50928
  inspectFile(getLockPath());
49811
50929
  if (originals.size) {
49812
- const recovery = join48(getHooksDataDir(), "registry-preservation", randomUUID12());
49813
- mkdirSync18(recovery, { recursive: true, mode: 448 });
50930
+ const recovery = join49(getHooksDataDir(), "registry-preservation", randomUUID13());
50931
+ mkdirSync19(recovery, { recursive: true, mode: 448 });
49814
50932
  const receipt = [];
49815
50933
  for (const [target, bytes] of originals) {
49816
- const path = join48(recovery, `${receipt.length}.original`);
49817
- writeFileSync16(path, bytes, { flag: "wx", mode: 384 });
49818
- if (!readFileSync31(path).equals(bytes))
50934
+ const path = join49(recovery, `${receipt.length}.original`);
50935
+ writeFileSync17(path, bytes, { flag: "wx", mode: 384 });
50936
+ if (!readFileSync33(path).equals(bytes))
49819
50937
  throw new Error("REGISTRY_PRESERVATION_READBACK_FAILED");
49820
50938
  receipt.push({ target, preserved: path, sha256: createHash38("sha256").update(bytes).digest("hex"), readback: true });
49821
50939
  }
49822
- writeFileSync16(join48(recovery, "receipt.json"), JSON.stringify(receipt, null, 2) + `
50940
+ writeFileSync17(join49(recovery, "receipt.json"), JSON.stringify(receipt, null, 2) + `
49823
50941
  `, { flag: "wx", mode: 384 });
49824
50942
  }
49825
50943
  for (const item of staged)
@@ -51921,13 +53039,13 @@ __export(exports_serve, {
51921
53039
  SERVE_HOST: () => SERVE_HOST,
51922
53040
  DEFAULT_SERVE_PORT: () => DEFAULT_SERVE_PORT
51923
53041
  });
51924
- import { readFileSync as readFileSync32 } from "fs";
51925
- import { dirname as dirname41, join as join49 } from "path";
53042
+ import { readFileSync as readFileSync34 } from "fs";
53043
+ import { dirname as dirname43, join as join50 } from "path";
51926
53044
  import { fileURLToPath as fileURLToPath6 } from "url";
51927
53045
  function packageVersion() {
51928
53046
  try {
51929
- const pkgPath = join49(dirname41(fileURLToPath6(import.meta.url)), "..", "package.json");
51930
- return JSON.parse(readFileSync32(pkgPath, "utf-8")).version || "0.0.0";
53047
+ const pkgPath = join50(dirname43(fileURLToPath6(import.meta.url)), "..", "package.json");
53048
+ return JSON.parse(readFileSync34(pkgPath, "utf-8")).version || "0.0.0";
51931
53049
  } catch {
51932
53050
  return "0.0.0";
51933
53051
  }
@@ -52128,17 +53246,17 @@ var exports_publish = {};
52128
53246
  __export(exports_publish, {
52129
53247
  prepareRegistryPublication: () => prepareRegistryPublication
52130
53248
  });
52131
- import { readFileSync as readFileSync33 } from "fs";
52132
- import { dirname as dirname43, resolve as resolve41 } from "path";
53249
+ import { readFileSync as readFileSync35 } from "fs";
53250
+ import { dirname as dirname45, resolve as resolve41 } from "path";
52133
53251
  async function prepareRegistryPublication(manifestPath) {
52134
- const path = resolve41(manifestPath), manifest = parseManifest(readFileSync33(path, "utf8"));
53252
+ const path = resolve41(manifestPath), manifest = parseManifest(readFileSync35(path, "utf8"));
52135
53253
  if (manifest.env && Object.keys(manifest.env).length)
52136
53254
  throw new Error("REGISTRY_MANIFEST_ENV_REFUSED: use the installed credential resolver, not artifact environment values");
52137
53255
  if (manifest.script_kind === "inline" || manifest.script.includes(`
52138
53256
  `))
52139
53257
  throw new Error("REGISTRY_PUBLICATION_FILE_REQUIRED: provide a source file to bundle");
52140
- const source = resolveScript(manifest, dirname43(path));
52141
- const result = await Bun.build({ entrypoints: [resolve41(dirname43(path), source.path)], target: "bun", format: "esm", packages: "bundle", sourcemap: "none" });
53258
+ const source = resolveScript(manifest, dirname45(path));
53259
+ const result = await Bun.build({ entrypoints: [resolve41(dirname45(path), source.path)], target: "bun", format: "esm", packages: "bundle", sourcemap: "none" });
52142
53260
  if (!result.success || result.outputs.length !== 1)
52143
53261
  throw new Error("REGISTRY_BUNDLE_FAILED");
52144
53262
  const script = await result.outputs[0].text();
@@ -52542,7 +53660,7 @@ __export(exports_legacy_registry_import, {
52542
53660
  importLegacyRegistryExport: () => importLegacyRegistryExport
52543
53661
  });
52544
53662
  import { constants as constants29, closeSync as closeSync29, fstatSync as fstatSync29, lstatSync as lstatSync41, openSync as openSync29, readSync as readSync6, realpathSync as realpathSync27 } from "fs";
52545
- import { dirname as dirname45, isAbsolute as isAbsolute41, join as join50, resolve as resolve43 } from "path";
53663
+ import { dirname as dirname46, isAbsolute as isAbsolute41, join as join51, resolve as resolve43 } from "path";
52546
53664
  function refuse6() {
52547
53665
  throw new RegistryError(400, "REGISTRY_LEGACY_EXPORT_INVALID");
52548
53666
  }
@@ -52554,10 +53672,10 @@ function decode3(bytes) {
52554
53672
  }
52555
53673
  }
52556
53674
  function fileBytes(root, relative12, expected) {
52557
- const path = join50(root, relative12);
53675
+ const path = join51(root, relative12);
52558
53676
  if (resolve43(path) !== path || !path.startsWith(root + "/") || realpathSync27(path) !== path)
52559
53677
  refuse6();
52560
- for (let component = path;component !== root; component = dirname45(component))
53678
+ for (let component = path;component !== root; component = dirname46(component))
52561
53679
  if (lstatSync41(component).isSymbolicLink())
52562
53680
  refuse6();
52563
53681
  if (expected && (expected.path !== relative12 || !Number.isSafeInteger(expected.bytes) || expected.bytes < 1 || expected.bytes > REGISTRY_MAX_BYTES || !SHA256.test(expected.sha256)))
@@ -52589,7 +53707,7 @@ function readLegacyRegistryExport(manifestPath, expectedSha256) {
52589
53707
  try {
52590
53708
  if (!isAbsolute41(manifestPath) || resolve43(manifestPath) !== manifestPath || !SHA256.test(expectedSha256))
52591
53709
  refuse6();
52592
- const root = dirname45(manifestPath);
53710
+ const root = dirname46(manifestPath);
52593
53711
  if (realpathSync27(root) !== root || lstatSync41(root).isSymbolicLink() || !lstatSync41(root).isDirectory())
52594
53712
  refuse6();
52595
53713
  const manifestWire = decode3(fileBytes(root, manifestPath.slice(root.length + 1)));
@@ -52793,17 +53911,17 @@ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
52793
53911
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
52794
53912
  import { z as z3 } from "zod";
52795
53913
  import { createServer } from "http";
52796
- import { existsSync as existsSync21, readFileSync as readFileSync34 } from "fs";
52797
- import { join as join51, dirname as dirname46 } from "path";
53914
+ import { existsSync as existsSync23, readFileSync as readFileSync36 } from "fs";
53915
+ import { join as join53, dirname as dirname47 } from "path";
52798
53916
  import { fileURLToPath as fileURLToPath7 } from "url";
52799
53917
  async function runVerifiedHook(name, stdin, timeoutMs) {
52800
53918
  const { resolveHook: resolveHook2, resolveScriptPath: resolveScriptPath2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
52801
53919
  const resolved = resolveHook2(name);
52802
53920
  const hookScript = resolveScriptPath2(name);
52803
- if (!resolved || !hookScript || !existsSync21(hookScript)) {
53921
+ if (!resolved || !hookScript || !existsSync23(hookScript)) {
52804
53922
  throw new Error(`Hook '${name}' not found`);
52805
53923
  }
52806
- const content = readFileSync34(hookScript);
53924
+ const content = readFileSync36(hookScript);
52807
53925
  const sha8 = sha256Of(content);
52808
53926
  const check2 = checkScriptHash(name, sha8);
52809
53927
  if (!check2.ok) {
@@ -53014,7 +54132,7 @@ function createHooksServer() {
53014
54132
  const settingsPath = getSettingsPath(scope);
53015
54133
  const issues = [];
53016
54134
  const healthy = [];
53017
- const settingsExist = existsSync21(settingsPath);
54135
+ const settingsExist = existsSync23(settingsPath);
53018
54136
  if (!settingsExist) {
53019
54137
  issues.push({ hook: "(settings)", issue: `${settingsPath} not found`, severity: "warning" });
53020
54138
  }
@@ -53024,7 +54142,7 @@ function createHooksServer() {
53024
54142
  const meta3 = custom2 ? resolveHookMeta(name) : getHook(name);
53025
54143
  let hookHealthy = true;
53026
54144
  if (custom2) {
53027
- if (!existsSync21(custom2.scriptPath)) {
54145
+ if (!existsSync23(custom2.scriptPath)) {
53028
54146
  issues.push({ hook: name, issue: `Custom hook script missing: ${custom2.scriptPath}`, severity: "error" });
53029
54147
  hookHealthy = false;
53030
54148
  }
@@ -53034,14 +54152,14 @@ function createHooksServer() {
53034
54152
  continue;
53035
54153
  }
53036
54154
  const hookDir = getHookPath(name);
53037
- if (!existsSync21(join51(hookDir, "src", "hook.ts"))) {
54155
+ if (!existsSync23(join53(hookDir, "src", "hook.ts"))) {
53038
54156
  issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
53039
54157
  hookHealthy = false;
53040
54158
  }
53041
54159
  }
53042
54160
  if (meta3 && settingsExist) {
53043
54161
  try {
53044
- const settings = JSON.parse(readFileSync34(settingsPath, "utf-8"));
54162
+ const settings = JSON.parse(readFileSync36(settingsPath, "utf-8"));
53045
54163
  if (!hookRegisteredInSettings(settings, name, meta3.event, matcherFor(meta3, "claude"))) {
53046
54164
  const eventName = meta3.event.split(":")[0];
53047
54165
  issues.push({ hook: name, issue: `Not registered under correct event (${eventName})`, severity: "error" });
@@ -53078,10 +54196,10 @@ function createHooksServer() {
53078
54196
  return { content: [{ type: "text", text: JSON.stringify({ error: `Hook '${name}' not found` }) }] };
53079
54197
  }
53080
54198
  const hookPath = getHookPath(name);
53081
- const readmePath = join51(hookPath, "README.md");
54199
+ const readmePath = join53(hookPath, "README.md");
53082
54200
  let readme = "";
53083
- if (existsSync21(readmePath)) {
53084
- readme = readFileSync34(readmePath, "utf-8");
54201
+ if (existsSync23(readmePath)) {
54202
+ readme = readFileSync36(readmePath, "utf-8");
53085
54203
  }
53086
54204
  if (verbose) {
53087
54205
  return { content: [{ type: "text", text: JSON.stringify({ ...meta3, readme }) }] };
@@ -53264,7 +54382,7 @@ function createHooksServer() {
53264
54382
  const ctx = {
53265
54383
  scope,
53266
54384
  settings_path: settingsPath,
53267
- settings_exists: existsSync21(settingsPath),
54385
+ settings_exists: existsSync23(settingsPath),
53268
54386
  registered_hooks: hooks,
53269
54387
  hook_count: hooks.length,
53270
54388
  healthy,
@@ -53788,13 +54906,13 @@ var init_server = __esm(() => {
53788
54906
  init_redact();
53789
54907
  init_authority2();
53790
54908
  init_storage();
53791
- __dirname3 = dirname46(fileURLToPath7(import.meta.url));
54909
+ __dirname3 = dirname47(fileURLToPath7(import.meta.url));
53792
54910
  pkg = { name: "@hasna/hooks", version: "0.0.0" };
53793
54911
  try {
53794
54912
  for (const rel of ["../../package.json", "../package.json", "../../../package.json"]) {
53795
- const p = join51(__dirname3, rel);
53796
- if (existsSync21(p)) {
53797
- pkg = JSON.parse(readFileSync34(p, "utf-8"));
54913
+ const p = join53(__dirname3, rel);
54914
+ if (existsSync23(p)) {
54915
+ pkg = JSON.parse(readFileSync36(p, "utf-8"));
53798
54916
  break;
53799
54917
  }
53800
54918
  }
@@ -53868,19 +54986,19 @@ __export(exports_native_readiness_binding, {
53868
54986
  registerTrashReadinessBinding: () => registerTrashReadinessBinding,
53869
54987
  ReadinessBindingError: () => ReadinessBindingError
53870
54988
  });
53871
- import { createHash as createHash40, randomUUID as randomUUID13 } from "crypto";
53872
- import { closeSync as closeSync30, constants as constants30, fsyncSync as fsyncSync12, lstatSync as lstatSync43, mkdirSync as mkdirSync19, openSync as openSync30, realpathSync as realpathSync28, writeFileSync as writeFileSync17 } from "fs";
53873
- import { homedir as homedir19 } from "os";
53874
- import { dirname as dirname47, join as join53 } from "path";
54989
+ import { createHash as createHash40, randomUUID as randomUUID14 } from "crypto";
54990
+ import { closeSync as closeSync30, constants as constants30, fsyncSync as fsyncSync12, lstatSync as lstatSync43, mkdirSync as mkdirSync20, openSync as openSync30, realpathSync as realpathSync28, writeFileSync as writeFileSync18 } from "fs";
54991
+ import { homedir as homedir20 } from "os";
54992
+ import { dirname as dirname48, join as join55 } from "path";
53875
54993
  function need16(value, code2) {
53876
54994
  if (!value)
53877
54995
  throw new ReadinessBindingError(code2);
53878
54996
  }
53879
54997
  function safeDirectory4(path) {
53880
- for (let p = path;; p = dirname47(p)) {
54998
+ for (let p = path;; p = dirname48(p)) {
53881
54999
  const s = lstatSync43(p);
53882
55000
  need16(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "binding_invalid");
53883
- if (p === dirname47(p))
55001
+ if (p === dirname48(p))
53884
55002
  break;
53885
55003
  }
53886
55004
  }
@@ -53895,15 +55013,15 @@ function syncDirectory6(path) {
53895
55013
  function exclusive3(path, bytes) {
53896
55014
  const fd = openSync30(path, constants30.O_WRONLY | constants30.O_CREAT | constants30.O_EXCL | constants30.O_NOFOLLOW, 384);
53897
55015
  try {
53898
- writeFileSync17(fd, bytes);
55016
+ writeFileSync18(fd, bytes);
53899
55017
  fsyncSync12(fd);
53900
55018
  } finally {
53901
55019
  closeSync30(fd);
53902
55020
  }
53903
- syncDirectory6(dirname47(path));
55021
+ syncDirectory6(dirname48(path));
53904
55022
  }
53905
55023
  async function registerTrashReadinessBinding(input2, expectedSHA256) {
53906
- const home = realpathSync28(homedir19()), b = parseTrashReadinessBinding(input2, input2?.provider, home);
55024
+ const home = realpathSync28(homedir20()), b = parseTrashReadinessBinding(input2, input2?.provider, home);
53907
55025
  need16(/^(?:absent|[a-f0-9]{64})$/.test(expectedSHA256), "binding_invalid");
53908
55026
  const target = trashReadinessBindingPath(b.provider, home);
53909
55027
  const read4 = () => {
@@ -53926,25 +55044,25 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
53926
55044
  `, digest5 = sha11(next);
53927
55045
  if (before?.sha256 === digest5)
53928
55046
  return { ok: true, changed: false, path: target, sha256: digest5, configurationReady: true, nativeAdoptionVerified: false };
53929
- const operationId = randomUUID13();
55047
+ const operationId = randomUUID14();
53930
55048
  let directory3 = home;
53931
55049
  for (const part of [".hasna", "hooks", "native", "trash-readiness"]) {
53932
- directory3 = join53(directory3, part);
55050
+ directory3 = join55(directory3, part);
53933
55051
  try {
53934
- mkdirSync19(directory3, { mode: 448 });
53935
- syncDirectory6(dirname47(directory3));
55052
+ mkdirSync20(directory3, { mode: 448 });
55053
+ syncDirectory6(dirname48(directory3));
53936
55054
  } catch (error61) {
53937
55055
  if (error61?.code !== "EEXIST")
53938
55056
  throw new ReadinessBindingError("binding_invalid");
53939
55057
  }
53940
55058
  safeDirectory4(directory3);
53941
55059
  }
53942
- const operation = join53(directory3, operationId);
53943
- mkdirSync19(operation, { mode: 448 });
55060
+ const operation = join55(directory3, operationId);
55061
+ mkdirSync20(operation, { mode: 448 });
53944
55062
  syncDirectory6(directory3);
53945
55063
  if (before)
53946
- exclusive3(join53(operation, "binding.before"), before.raw);
53947
- exclusive3(join53(operation, "intent.json"), JSON.stringify({ operationId, target, expectedSHA256, desiredSHA256: digest5 }) + `
55064
+ exclusive3(join55(operation, "binding.before"), before.raw);
55065
+ exclusive3(join55(operation, "intent.json"), JSON.stringify({ operationId, target, expectedSHA256, desiredSHA256: digest5 }) + `
53948
55066
  `);
53949
55067
  let writeMayHaveStarted = false;
53950
55068
  try {
@@ -53962,7 +55080,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
53962
55080
  syncDirectory6(directory3);
53963
55081
  need16(read4()?.sha256 === digest5, "binding_changed");
53964
55082
  const receipt = { ok: true, changed: true, operationId, path: target, sha256: digest5, configurationReady: true, nativeAdoptionVerified: false };
53965
- exclusive3(join53(operation, "receipt.json"), JSON.stringify(receipt) + `
55083
+ exclusive3(join55(operation, "receipt.json"), JSON.stringify(receipt) + `
53966
55084
  `);
53967
55085
  return receipt;
53968
55086
  } catch (error61) {
@@ -53971,7 +55089,7 @@ async function registerTrashReadinessBinding(input2, expectedSHA256) {
53971
55089
  const code2 = error61?.code;
53972
55090
  const refusal3 = { code: typeof code2 === "string" && code2 ? code2 : "writer_refused", message: error61 instanceof Error ? error61.message : String(error61) };
53973
55091
  try {
53974
- exclusive3(join53(operation, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, path: target, expectedSHA256, refusal: refusal3 }) + `
55092
+ exclusive3(join55(operation, "refused.json"), JSON.stringify({ ok: false, outcome: "refused", operationId, path: target, expectedSHA256, refusal: refusal3 }) + `
53975
55093
  `);
53976
55094
  } catch {
53977
55095
  throw new ReadinessBindingError("binding_outcome_uncertain", operationId);
@@ -54004,10 +55122,10 @@ import { resolve as resolve45 } from "path";
54004
55122
  init_native_safety();
54005
55123
  init_native_safety2();
54006
55124
  init_registry();
54007
- import { constants as constants16, closeSync as closeSync10, fstatSync as fstatSync10, lstatSync as lstatSync26, openSync as openSync10, readFileSync as readFileSync18, realpathSync as realpathSync16 } from "fs";
55125
+ import { constants as constants16, closeSync as closeSync10, fstatSync as fstatSync10, lstatSync as lstatSync26, openSync as openSync10, readFileSync as readFileSync21, realpathSync as realpathSync16 } from "fs";
54008
55126
  import { createHash as createHash20 } from "crypto";
54009
- import { dirname as dirname27, isAbsolute as isAbsolute17, join as join32, resolve as resolve33 } from "path";
54010
- import { homedir as homedir11 } from "os";
55127
+ import { dirname as dirname29, isAbsolute as isAbsolute17, join as join35, resolve as resolve33 } from "path";
55128
+ import { homedir as homedir12 } from "os";
54011
55129
 
54012
55130
  class ClaudeSafetyError extends Error {
54013
55131
  code;
@@ -54025,17 +55143,17 @@ var sha9 = (value) => createHash20("sha256").update(value).digest("hex");
54025
55143
  function read5(path) {
54026
55144
  try {
54027
55145
  const resolved = realpathSync16(path);
54028
- for (let parent = dirname27(resolved);; parent = dirname27(parent)) {
55146
+ for (let parent = dirname29(resolved);; parent = dirname29(parent)) {
54029
55147
  const s = lstatSync26(parent);
54030
55148
  need13(s.isDirectory() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18), "settings_unsafe");
54031
- if (dirname27(parent) === parent)
55149
+ if (dirname29(parent) === parent)
54032
55150
  break;
54033
55151
  }
54034
55152
  const fd = openSync10(resolved, constants16.O_RDONLY | constants16.O_NOFOLLOW | constants16.O_NONBLOCK);
54035
55153
  try {
54036
55154
  const s = fstatSync10(fd);
54037
55155
  need13(s.isFile() && [0, process.getuid?.()].includes(s.uid) && !(s.mode & 18) && s.size <= 1048576, "settings_unsafe");
54038
- const raw = readFileSync18(fd, "utf8");
55156
+ const raw = readFileSync21(fd, "utf8");
54039
55157
  need13(Buffer.byteLength(raw) <= 1048576, "settings_unsafe");
54040
55158
  return { path, resolved, sha256: sha9(raw), raw };
54041
55159
  } finally {
@@ -54050,11 +55168,11 @@ function read5(path) {
54050
55168
  }
54051
55169
  }
54052
55170
  async function verifyClaudeSafetyConfiguration(options = {}, dependencies = {}) {
54053
- const home = realpathSync16(options.home ?? homedir11()), cwd = realpathSync16(options.cwd ?? process.cwd());
55171
+ const home = realpathSync16(options.home ?? homedir12()), cwd = realpathSync16(options.cwd ?? process.cwd());
54054
55172
  const paths = [
54055
- options.userSettingsPath ?? join32(home, ".claude/settings.json"),
54056
- join32(cwd, ".claude/settings.json"),
54057
- options.localSettingsPath ?? join32(cwd, ".claude/settings.local.json")
55173
+ options.userSettingsPath ?? join35(home, ".claude/settings.json"),
55174
+ join35(cwd, ".claude/settings.json"),
55175
+ options.localSettingsPath ?? join35(cwd, ".claude/settings.local.json")
54058
55176
  ];
54059
55177
  need13(paths.every((path) => isAbsolute17(path) && resolve33(path) === path), "settings_unsafe");
54060
55178
  const inspect2 = () => [...new Set(paths)].map(read5);
@@ -54123,15 +55241,15 @@ import { chmod, mkdir, readFile as readFile2, rename, writeFile } from "fs/promi
54123
55241
  import { Buffer as Buffer2 } from "buffer";
54124
55242
  import { existsSync as existsSync22 } from "fs";
54125
55243
  import { join as join210 } from "path";
54126
- import { existsSync as existsSync14 } from "fs";
54127
- import { homedir as homedir14 } from "os";
54128
- import { join as join35, resolve as resolve36 } from "path";
55244
+ import { existsSync as existsSync16 } from "fs";
55245
+ import { homedir as homedir15 } from "os";
55246
+ import { join as join41, resolve as resolve36 } from "path";
54129
55247
  import { homedir as pathsResolverHomedir3 } from "os";
54130
55248
  import { join as pathsResolverJoin3 } from "path";
54131
55249
  import { createHmac, timingSafeEqual } from "crypto";
54132
55250
  import { lookup as dnsLookup } from "dns/promises";
54133
55251
  import { isIP } from "net";
54134
- import { randomUUID as randomUUID9 } from "crypto";
55252
+ import { randomUUID as randomUUID10 } from "crypto";
54135
55253
  import { spawn as spawn4 } from "child_process";
54136
55254
  import { request as nodeHttpRequest } from "http";
54137
55255
  import { request as nodeHttpsRequest } from "https";
@@ -54293,10 +55411,10 @@ var HASNA_EVENTS_DIR_ENV = "HASNA_EVENTS_DIR";
54293
55411
  var HASNA_EVENTS_HOME_ENV = "HASNA_EVENTS_HOME";
54294
55412
  var EVENTS_STORE_SENTINEL_FILE = "events.json";
54295
55413
  function effectiveHome2() {
54296
- return process.env["HOME"] || process.env["USERPROFILE"] || homedir14();
55414
+ return process.env["HOME"] || process.env["USERPROFILE"] || homedir15();
54297
55415
  }
54298
55416
  function legacyHomeDir() {
54299
- return join35(effectiveHome2(), ".hasna", "events");
55417
+ return join41(effectiveHome2(), ".hasna", "events");
54300
55418
  }
54301
55419
  function resolverHome() {
54302
55420
  return dataDir3({ app: "events", home: effectiveHome2() || undefined });
@@ -54305,7 +55423,7 @@ function adoptResolverHome(resolved, env = process.env) {
54305
55423
  const dataOverride = env.HASNA_DATA_HOME;
54306
55424
  if (typeof dataOverride === "string" && dataOverride.trim().length > 0)
54307
55425
  return true;
54308
- return existsSync14(join35(resolved, EVENTS_STORE_SENTINEL_FILE));
55426
+ return existsSync16(join41(resolved, EVENTS_STORE_SENTINEL_FILE));
54309
55427
  }
54310
55428
  function exactEventsHome() {
54311
55429
  const dir = process.env[HASNA_EVENTS_DIR_ENV];
@@ -55139,7 +56257,7 @@ async function dispatchChannel(event, channel, options = {}) {
55139
56257
  function createDeliveryResult(event, channel, attempts) {
55140
56258
  const status = attempts.some((attempt) => attempt.status === "success") ? "success" : attempts.every((attempt) => attempt.status === "skipped") ? "skipped" : "failed";
55141
56259
  return {
55142
- id: randomUUID9(),
56260
+ id: randomUUID10(),
55143
56261
  eventId: event.id,
55144
56262
  channelId: channel.id,
55145
56263
  transport: channel.transport,
@@ -55775,9 +56893,10 @@ var {
55775
56893
 
55776
56894
  // src/cli/index.tsx
55777
56895
  import chalk2 from "chalk";
55778
- import { existsSync as existsSync23, readFileSync as readFileSync35, rmSync as rmSync7 } from "fs";
55779
- import { join as join55, dirname as dirname48 } from "path";
56896
+ import { existsSync as existsSync25, readFileSync as readFileSync37, rmSync as rmSync7 } from "fs";
56897
+ import { join as join56, dirname as dirname49 } from "path";
55780
56898
  import { fileURLToPath as fileURLToPath8 } from "url";
56899
+ import { homedir as homedir21 } from "os";
55781
56900
 
55782
56901
  // src/cli/components/App.tsx
55783
56902
  import { useState as useState7 } from "react";
@@ -56957,6 +58076,8 @@ init_codex_safety_check();
56957
58076
  init_registry();
56958
58077
  init_installer();
56959
58078
  init_registration();
58079
+ init_targets();
58080
+ init_target_adapters();
56960
58081
  init_redact();
56961
58082
  init_profiles();
56962
58083
  init_manifest();
@@ -56967,40 +58088,70 @@ init_app_home();
56967
58088
  init_config();
56968
58089
  init_local_opt_in();
56969
58090
  init_transport2();
58091
+
58092
+ // src/lib/gate-route.ts
58093
+ init_transport2();
58094
+ var KEYCHAIN_INTERACTION_NOT_ALLOWED_STATUS = 36;
58095
+ var HOOKS_RUN_UNREADABLE_KEYCHAIN_AUTHORITY = "configured by the Keychain item hasna.credentials.hooks.api-key, which this session may not read " + "(security exit 36); hooks run executes the hook pinned in hooks.lock and uses no registry credential";
58096
+ var UNREADABLE_HOOKS_KEYCHAIN_ITEM = /^The Keychain lookup for keychain:hasna\.credentials\.hooks\.api-(?:key|url)@\S+ failed \(security exited 36(?:[:)])/;
58097
+ function isHooksKeychainInteractionRefusal(error61) {
58098
+ let current2 = error61;
58099
+ for (let depth = 0;depth < 4 && current2 instanceof Error; depth++) {
58100
+ if (current2.name === "CredentialResolutionError") {
58101
+ const status = current2.keychainStatus;
58102
+ if (status !== undefined)
58103
+ return status === KEYCHAIN_INTERACTION_NOT_ALLOWED_STATUS;
58104
+ return UNREADABLE_HOOKS_KEYCHAIN_ITEM.test(current2.message);
58105
+ }
58106
+ current2 = current2.cause;
58107
+ }
58108
+ return false;
58109
+ }
58110
+ function hooksAmbientGateRoute(command, env = process.env, options = {}) {
58111
+ let transport;
58112
+ try {
58113
+ transport = resolveHooksTransport(env, options);
58114
+ } catch (error61) {
58115
+ if (command === "run" && isHooksKeychainInteractionRefusal(error61)) {
58116
+ return { kind: "hosted", authority: HOOKS_RUN_UNREADABLE_KEYCHAIN_AUTHORITY };
58117
+ }
58118
+ return { kind: "fail", detail: error61 instanceof Error ? error61.message : String(error61) };
58119
+ }
58120
+ if (transport.mode !== "remote" || !transport.authority)
58121
+ return { kind: "fail" };
58122
+ return { kind: "hosted", authority: transport.authority.v1BaseUrl };
58123
+ }
58124
+
58125
+ // src/cli/index.tsx
56970
58126
  init_db();
56971
58127
  import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
56972
- var __dirname4 = dirname48(fileURLToPath8(import.meta.url));
56973
- var pkgPath = existsSync23(join55(__dirname4, "..", "package.json")) ? join55(__dirname4, "..", "package.json") : join55(__dirname4, "..", "..", "package.json");
56974
- var pkg2 = JSON.parse(readFileSync35(pkgPath, "utf-8"));
58128
+ var __dirname4 = dirname49(fileURLToPath8(import.meta.url));
58129
+ var pkgPath = existsSync25(join56(__dirname4, "..", "package.json")) ? join56(__dirname4, "..", "package.json") : join56(__dirname4, "..", "..", "package.json");
58130
+ var pkg2 = JSON.parse(readFileSync37(pkgPath, "utf-8"));
56975
58131
  var program3 = new Command;
56976
58132
  function resolveScope(options) {
56977
58133
  if (options.project)
56978
58134
  return "project";
56979
58135
  return "global";
56980
58136
  }
58137
+ function installTargetRefusal(target) {
58138
+ return installCapabilityRefusal("", target, { events: [], requiresFinalMessage: false, requiresBlock: false }) ?? `Unknown target '${target}'; expected one of: ${INSTALL_TARGET_NAMES.join(", ")}, all.`;
58139
+ }
56981
58140
  function resolveTarget(options) {
56982
- if (options.target === "gemini")
56983
- return "gemini";
56984
- if (options.target === "codex")
56985
- return "codex";
56986
- if (options.target === "codewith")
56987
- return "codewith";
56988
- if (options.target === "all")
56989
- return "all";
56990
58141
  if (options.target === undefined || options.target === "claude")
56991
58142
  return "claude";
56992
- return program3.error("Unknown target; expected claude, gemini, codewith, codex or all", { code: "hooks.target_invalid" });
58143
+ if (options.target === "all")
58144
+ return "all";
58145
+ if (isInstallTargetName(options.target))
58146
+ return options.target;
58147
+ return program3.error(installTargetRefusal(options.target), { code: "hooks.target_invalid" });
56993
58148
  }
56994
58149
  function resolveConcreteTarget(options) {
56995
- if (options.target === "gemini")
56996
- return "gemini";
56997
- if (options.target === "codex")
56998
- return "codex";
56999
- if (options.target === "codewith")
57000
- return "codewith";
57001
58150
  if (options.target === undefined || options.target === "claude")
57002
58151
  return "claude";
57003
- return program3.error("Unknown target; expected claude, gemini, codewith or codex", { code: "hooks.target_invalid" });
58152
+ if (isInstallTargetName(options.target))
58153
+ return options.target;
58154
+ return program3.error(installTargetRefusal(options.target), { code: "hooks.target_invalid" });
57004
58155
  }
57005
58156
  function reportSumiBinding(result) {
57006
58157
  if (result.ok) {
@@ -57019,24 +58170,16 @@ function reportSumiBinding(result) {
57019
58170
  function formatSettingsPath(scope, target) {
57020
58171
  if (target === "all")
57021
58172
  return "target-specific settings";
57022
- const actual = getSettingsPath(scope, target);
57023
- if (scope === "project") {
57024
- if (target === "codewith")
57025
- return ".codewith/config.toml";
57026
- if (target === "gemini")
57027
- return ".gemini/settings.json";
57028
- if (target === "codex")
57029
- return ".codex/hooks.json";
57030
- return ".claude/settings.json";
57031
- }
57032
- if (target === "codewith") {
57033
- return process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH ? "$HASNA_HOOKS_CODEWITH_CONFIG_PATH" : "~/.codewith/config.toml";
58173
+ if (target === "codewith" && scope === "global" && process.env.HASNA_HOOKS_CODEWITH_CONFIG_PATH) {
58174
+ return "$HASNA_HOOKS_CODEWITH_CONFIG_PATH";
57034
58175
  }
57035
- if (target === "gemini")
57036
- return "~/.gemini/settings.json";
57037
- if (target === "codex")
57038
- return "~/.codex/hooks.json";
57039
- return actual === getSettingsPath("global", "claude") ? "~/.claude/settings.json" : actual;
58176
+ const actual = getSettingsPath(scope, target);
58177
+ const base = scope === "project" ? resolve45(process.cwd()) : homedir21();
58178
+ if (actual === base)
58179
+ return scope === "project" ? "." : "~";
58180
+ if (!actual.startsWith(`${base}/`))
58181
+ return actual;
58182
+ return `${scope === "project" ? "" : "~/"}` + actual.slice(base.length + 1);
57040
58183
  }
57041
58184
  function parseLimit(value, fallback, max) {
57042
58185
  const parsed = value ? parseInt(value, 10) : fallback;
@@ -57069,7 +58212,7 @@ async function openLocalStoreOrExit(json4) {
57069
58212
  function readToken(tokenFile) {
57070
58213
  if (tokenFile) {
57071
58214
  try {
57072
- return readFileSync35(tokenFile, "utf-8").trim();
58215
+ return readFileSync37(tokenFile, "utf-8").trim();
57073
58216
  } catch {
57074
58217
  return;
57075
58218
  }
@@ -57207,13 +58350,13 @@ program3.command("init").description("Register a new agent profile with a unique
57207
58350
  if (profile.name) {
57208
58351
  console.log(` ${chalk2.dim("Name:")} ${profile.name}`);
57209
58352
  }
57210
- console.log(` ${chalk2.dim("Profile:")} ${join55(getProfilesDir(), `${profile.agent_id}.json`)}`);
58353
+ console.log(` ${chalk2.dim("Profile:")} ${join56(getProfilesDir(), `${profile.agent_id}.json`)}`);
57211
58354
  console.log();
57212
58355
  console.log(chalk2.dim(" Install hooks with this profile:"));
57213
58356
  console.log(` hooks install gitguard --profile ${profile.agent_id}`);
57214
58357
  console.log();
57215
58358
  });
57216
- program3.command("run").argument("<hook>", "Hook to run").option("--target <target>", "Trusted native target (claude, codex, gemini, codewith, sumi, opencode)").option("--profile <id>", "Agent profile ID").option("--enable-mementos", "Enable mementos-context for this invocation (provider assistance remains separately opt-in)").option("--disable-mementos", "Disable mementos-context for this invocation").option("--openrouter-secret-ref <reference>", "Secrets reference for the enabled Mementos hook; never a key value").description("Execute a hook (called by AI coding agents)").exitOverride((err) => {
58359
+ program3.command("run").argument("<hook>", "Hook to run").option("--target <target>", `Trusted native target (${runTargetHelp()})`).option("--profile <id>", "Agent profile ID").option("--enable-mementos", "Enable mementos-context for this invocation (provider assistance remains separately opt-in)").option("--disable-mementos", "Disable mementos-context for this invocation").option("--openrouter-secret-ref <reference>", "Secrets reference for the enabled Mementos hook; never a key value").description("Execute a hook (called by AI coding agents)").exitOverride((err) => {
57217
58360
  if (err.exitCode !== 0) {
57218
58361
  const guard = runPreToolUseGuard(process.argv.slice(2));
57219
58362
  if (guard)
@@ -57221,6 +58364,11 @@ program3.command("run").argument("<hook>", "Hook to run").option("--target <targ
57221
58364
  }
57222
58365
  process.exit(err.exitCode);
57223
58366
  }).action(async (hook, options) => {
58367
+ const targetRefusal = options.target === undefined ? undefined : runTargetRefusal(options.target);
58368
+ if (targetRefusal) {
58369
+ console.error(targetRefusal);
58370
+ exitHookNotRun(hook, isTargetName(options.target) ? "its --target has no hook payload shape" : "its native target is invalid");
58371
+ }
57224
58372
  let mementos;
57225
58373
  try {
57226
58374
  mementos = mementosRegistrationFromFlags(hook, options);
@@ -57237,7 +58385,7 @@ program3.command("run").argument("<hook>", "Hook to run").option("--target <targ
57237
58385
  exitHookNotRun(hook, "its script is missing");
57238
58386
  }
57239
58387
  const hookScript = resolveScriptPath2(hook);
57240
- if (!hookScript || !existsSync23(hookScript)) {
58388
+ if (!hookScript || !existsSync25(hookScript)) {
57241
58389
  console.error(JSON.stringify({ error: `Hook script not found: ${hookScript ?? hook}` }));
57242
58390
  exitHookNotRun(hook, "its script is missing");
57243
58391
  }
@@ -57245,7 +58393,7 @@ program3.command("run").argument("<hook>", "Hook to run").option("--target <targ
57245
58393
  let sha8;
57246
58394
  let check2;
57247
58395
  try {
57248
- content = readFileSync35(hookScript);
58396
+ content = readFileSync37(hookScript);
57249
58397
  sha8 = sha256Of2(content);
57250
58398
  check2 = checkScriptHash2(hook, sha8);
57251
58399
  } catch (error61) {
@@ -57273,7 +58421,7 @@ program3.command("run").argument("<hook>", "Hook to run").option("--target <targ
57273
58421
  console.error(JSON.stringify({ error: error61 instanceof Error ? error61.message : "Invalid native target" }));
57274
58422
  exitHookNotRun(hook, "its native target is invalid");
57275
58423
  }
57276
- const stdin = await new Response(Bun.stdin.stream()).text();
58424
+ const stdin = shapeTargetInput(options.target, await new Response(Bun.stdin.stream()).text());
57277
58425
  let hookStdin = stdin;
57278
58426
  if (options.profile) {
57279
58427
  const profile = getProfile(options.profile);
@@ -57364,11 +58512,12 @@ program3.command("run").argument("<hook>", "Hook to run").option("--target <targ
57364
58512
  durationMs,
57365
58513
  projectDir: process.cwd()
57366
58514
  });
57367
- if (stdout)
57368
- process.stdout.write(stdout);
57369
- if (stderr)
57370
- process.stderr.write(stderr);
57371
- process.exit(exitCode);
58515
+ const shaped = shapeTargetOutput(options.target, { stdout, stderr, exitCode });
58516
+ if (shaped.stdout)
58517
+ process.stdout.write(shaped.stdout);
58518
+ if (shaped.stderr)
58519
+ process.stderr.write(shaped.stderr);
58520
+ process.exit(shaped.exitCode);
57372
58521
  });
57373
58522
  async function installOpenCodeStopReview(hooks, options) {
57374
58523
  const { OpenCodeStopInstallError: OpenCodeStopInstallError2, applyOpenCodeStopInstall: applyOpenCodeStopInstall2, installedOpenCodeStopPins: installedOpenCodeStopPins2, openCodeConfigPath: openCodeConfigPath2, planOpenCodeStopInstall: planOpenCodeStopInstall2, verifyOpenCodeStopInstall: verifyOpenCodeStopInstall2 } = await Promise.resolve().then(() => (init_opencode_stop_install(), exports_opencode_stop_install));
@@ -57416,7 +58565,7 @@ async function installSumiStopReview(hooks, options) {
57416
58565
  process.exitCode = 1;
57417
58566
  }
57418
58567
  }
57419
- program3.command("install").alias("add").argument("[hooks...]", "Hooks to install").option("-o, --overwrite", "Overwrite existing hooks", false).option("-a, --all", "Install all available hooks", false).option("-c, --category <category>", "Install all hooks in a category").option("-g, --global", "Install globally (~/.claude/settings.json)", false).option("-p, --project", "Install for current project (.claude/settings.json)", false).option("-t, --target <target>", "Agent target: claude, gemini, codewith, codex, all, or opencode/sumi for stop-review (default: claude)", "claude").option("--profile <id>", "Agent profile ID to scope hooks to").option("--enable-mementos", "Persistently enable mementos-context (provider assistance remains separately opt-in)").option("--disable-mementos", "Persistently disable mementos-context").option("--openrouter-secret-ref <reference>", "Secrets reference for the enabled Mementos hook; never a key value").option("--dry-run", "Preview what would be installed without writing to settings", false).option("--apply-codewith", "Explicitly append Codewith TOML to a config file (prefer configs for managed configs)", false).option("--codewith-config <path>", "Explicit Codewith config path required with --apply-codewith").option("--expected-config-sha256 <sha256>", 'OpenCode/Sumi: exact current registration digest from --dry-run ("absent" for a new file)').option("--verify", "OpenCode/Sumi: read-only drift check of the registered stop-review entry", false).option("-j, --json", "Output as JSON", false).description("Install one or more hooks (registry names, local paths, git URLs, manifest URLs, or <name>@<version> pinned installs)").action(async (hooks, options) => {
58568
+ program3.command("install").alias("add").argument("[hooks...]", "Hooks to install").option("-o, --overwrite", "Overwrite existing hooks", false).option("-a, --all", "Install all available hooks", false).option("-c, --category <category>", "Install all hooks in a category").option("-g, --global", "Install globally (~/.claude/settings.json)", false).option("-p, --project", "Install for current project (.claude/settings.json)", false).option("-t, --target <target>", `Agent target: ${runTargetHelp()}, or all (default: claude); opencode/sumi resolve to stop-review`, "claude").option("--profile <id>", "Agent profile ID to scope hooks to").option("--enable-mementos", "Persistently enable mementos-context (provider assistance remains separately opt-in)").option("--disable-mementos", "Persistently disable mementos-context").option("--openrouter-secret-ref <reference>", "Secrets reference for the enabled Mementos hook; never a key value").option("--dry-run", "Preview what would be installed without writing to settings", false).option("--apply-codewith", "Explicitly append Codewith TOML to a config file (prefer configs for managed configs)", false).option("--codewith-config <path>", "Explicit Codewith config path required with --apply-codewith").option("--expected-config-sha256 <sha256>", 'OpenCode/Sumi: exact current registration digest from --dry-run ("absent" for a new file)').option("--verify", "OpenCode/Sumi: read-only drift check of the registered stop-review entry", false).option("-j, --json", "Output as JSON", false).description("Install one or more hooks (registry names, local paths, git URLs, manifest URLs, or <name>@<version> pinned installs)").action(async (hooks, options) => {
57420
58569
  if (options.target === "sumi") {
57421
58570
  await installSumiStopReview(hooks, options);
57422
58571
  return;
@@ -57471,7 +58620,7 @@ program3.command("install").alias("add").argument("[hooks...]", "Hooks to instal
57471
58620
  }
57472
58621
  const { isCustomSource: isCustomSource2, installCustomSource: installCustomSource2 } = await Promise.resolve().then(() => (init_custom_install(), exports_custom_install));
57473
58622
  const { readCustomManifest: readCustomManifest2, HOOK_NAME_RE: HOOK_NAME_RE2 } = await Promise.resolve().then(() => (init_manifest(), exports_manifest));
57474
- const { resolveHooksTransport: resolveHooksTransport3 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
58623
+ const { resolveHooksTransport: resolveHooksTransport4 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
57475
58624
  const { sha256Of: sha256Of2, pinInstalledHook: pinInstalledHook2 } = await Promise.resolve().then(() => (init_store(), exports_store));
57476
58625
  const { installPinnedFromBundled: installPinnedFromBundled2, fetchPinnedHook: fetchPinnedHook2 } = await Promise.resolve().then(() => (init_sync(), exports_sync));
57477
58626
  const { readFileSync: readFileSyncFs } = await import("fs");
@@ -57566,7 +58715,7 @@ Dry run \u2014 would install (${scope}, ${target}):
57566
58715
  const installedPinned = [];
57567
58716
  for (const { arg, pinned } of pinnedRequests) {
57568
58717
  try {
57569
- const transport = resolveHooksTransport3();
58718
+ const transport = resolveHooksTransport4();
57570
58719
  const pinnedInstall = transport.mode === "remote" && transport.authority ? await fetchPinnedHook2(pinned.name, pinned.version, transport.authority.origin, transport.authority) : await installPinnedFromBundled2(pinned.name, pinned.version);
57571
58720
  installedPinned.push(pinnedInstall.name);
57572
58721
  if (options.json) {
@@ -57671,7 +58820,7 @@ Installing hooks (${scope}, ${target})...
57671
58820
  Registered in ${settingsFile}`));
57672
58821
  reportSumiBinding(sumiBinding);
57673
58822
  });
57674
- program3.command("list").alias("ls").option("-c, --category <category>", "Filter by category").option("-a, --all", "Show all available hooks", false).option("-i, --installed", "Show only installed hooks", false).option("-r, --registered", "Show registered hooks", false).option("-g, --global", "Check global settings", false).option("-p, --project", "Check project settings", false).option("-t, --target <target>", "Agent target: claude, gemini, codewith, codex (default: claude)", "claude").option("-n, --limit <n>", "Max rows to show in compact output", "20").option("--verbose", "Show descriptions and full detail columns", false).option("-j, --json", "Output as JSON", false).description("List available or installed hooks (bundled + custom/registry)").action((options) => {
58823
+ program3.command("list").alias("ls").option("-c, --category <category>", "Filter by category").option("-a, --all", "Show all available hooks", false).option("-i, --installed", "Show only installed hooks", false).option("-r, --registered", "Show registered hooks", false).option("-g, --global", "Check global settings", false).option("-p, --project", "Check project settings", false).option("-t, --target <target>", `Agent target: ${INSTALL_TARGET_NAMES.join(", ")} (default: claude)`, "claude").option("-n, --limit <n>", "Max rows to show in compact output", "20").option("--verbose", "Show descriptions and full detail columns", false).option("-j, --json", "Output as JSON", false).description("List available or installed hooks (bundled + custom/registry)").action((options) => {
57675
58824
  const scope = resolveScope(options);
57676
58825
  const limit = options.all ? Number.MAX_SAFE_INTEGER : parseLimit(options.limit, 20, 200);
57677
58826
  const storeHooks = listStoreHooks();
@@ -57799,10 +58948,10 @@ Found ${results2.length} hook(s), showing ${visible.length}:
57799
58948
  console.log(hookSummaryLine(h, { verbose: options.verbose }));
57800
58949
  printDisclosureHint(results2.length - visible.length, "hooks info <name>");
57801
58950
  });
57802
- program3.command("remove").alias("rm").argument("<hook>", "Hook to remove").option("-g, --global", "Remove from global settings", false).option("-p, --project", "Remove from project settings", false).option("-t, --target <target>", "Agent target: claude, gemini, codewith, codex, all (default: claude)", "claude").option("-j, --json", "Output as JSON", false).description("Remove an installed hook (settings registration + store + lock + DB)").action(async (hook, options) => {
58951
+ program3.command("remove").alias("rm").argument("<hook>", "Hook to remove").option("-g, --global", "Remove from global settings", false).option("-p, --project", "Remove from project settings", false).option("-t, --target <target>", `Agent target: ${INSTALL_TARGET_NAMES.join(", ")}, or all (default: claude)`, "claude").option("-j, --json", "Output as JSON", false).description("Remove an installed hook (settings registration + store + lock + DB)").action(async (hook, options) => {
57803
58952
  const scope = resolveScope(options);
57804
58953
  const target = resolveTarget(options);
57805
- const { uninstallHook: uninstallHook2 } = await Promise.resolve().then(() => (init_installer(), exports_installer));
58954
+ const { uninstallHook: uninstallHook2, removeFailureMessage: removeFailureMessage2 } = await Promise.resolve().then(() => (init_installer(), exports_installer));
57806
58955
  const result = uninstallHook2(hook, scope, target);
57807
58956
  if (!result.removed) {
57808
58957
  process.exitCode = 1;
@@ -57817,12 +58966,17 @@ program3.command("remove").alias("rm").argument("<hook>", "Hook to remove").opti
57817
58966
  pin_removed: result.pinRemoved,
57818
58967
  db_record_removed: result.dbRecordRemoved,
57819
58968
  registrations_remaining: result.registrationsRemaining,
58969
+ ...result.notes && result.notes.length > 0 ? { notes: result.notes } : {},
57820
58970
  scope,
57821
58971
  target,
57822
58972
  ...result.error ? { error: result.error } : {}
57823
58973
  }));
57824
58974
  } else if (result.removed) {
57825
58975
  console.log(chalk2.green(`\u2713 Removed ${result.name} (${scope}, ${target})`));
58976
+ if (result.notes && result.notes.length > 0) {
58977
+ for (const note of result.notes)
58978
+ console.log(chalk2.dim(` \xB7 ${note}`));
58979
+ }
57826
58980
  if (result.source === "custom" && result.storeDirRemoved) {
57827
58981
  console.log(chalk2.dim(` store dir removed; lock pin ${result.pinRemoved ? "removed" : "absent"}; DB record ${result.dbRecordRemoved ? "removed" : "absent"}`));
57828
58982
  }
@@ -57830,9 +58984,11 @@ program3.command("remove").alias("rm").argument("<hook>", "Hook to remove").opti
57830
58984
  console.log(chalk2.yellow(` \u26A0 registrations remaining: ${result.registrationsRemaining.join(", ")} \u2014 remove them in that target's own config`));
57831
58985
  }
57832
58986
  } else {
57833
- const suggestions = suggestHooks(hook);
57834
- const hint = suggestions.length ? ` \u2014 did you mean: ${suggestions.join(", ")}?` : "";
57835
- console.log(chalk2.red(`\u2717 Hook '${hook}' not found${hint}`));
58987
+ console.log(chalk2.red(removeFailureMessage2(result, hook, suggestHooks(hook))));
58988
+ if (result.notes && result.notes.length > 0) {
58989
+ for (const note of result.notes)
58990
+ console.log(chalk2.dim(` \xB7 ${note}`));
58991
+ }
57836
58992
  }
57837
58993
  });
57838
58994
  program3.command("categories").option("-j, --json", "Output as JSON", false).description("List all categories").action((options) => {
@@ -57900,13 +59056,17 @@ ${meta3.displayName}
57900
59056
  console.log(chalk2.dim(" \u25CB Not installed in project"));
57901
59057
  }
57902
59058
  });
57903
- program3.command("doctor").option("-g, --global", "Check global settings", false).option("-p, --project", "Check project settings", false).option("-f, --fix", "Remove stale registrations (a .bak is written beside each settings file)", false).option("-j, --json", "Output as JSON", false).description("Check health of installed hooks; --fix removes registrations whose hook cannot resolve").action((options) => {
59059
+ program3.command("doctor").option("-g, --global", "Check global settings", false).option("-p, --project", "Check project settings", false).option("-f, --fix", "Remove stale registrations (a .bak is written beside each settings file)", false).option("-t, --target <target>", `Check one target's own config (default: claude)`).option("-j, --json", "Output as JSON", false).description("Check health of installed hooks; --fix removes registrations whose hook cannot resolve").action((options) => {
57904
59060
  const scope = resolveScope(options);
57905
- const settingsPath = getSettingsPath(scope);
59061
+ const selectedTarget = options.target === undefined ? undefined : resolveConcreteTarget(options);
59062
+ const target = selectedTarget ?? "claude";
59063
+ const claudeSettings = selectedTarget === undefined || selectedTarget === "claude";
59064
+ const settingsBased = claudeSettings || target === "gemini" || target === "codex" || target === "qwen";
59065
+ const settingsPath = getSettingsPath(scope, target);
57906
59066
  const issues = [];
57907
59067
  const healthy = [];
57908
- const fixed = options.fix ? pruneStaleRegistrations(scope) : [];
57909
- const stale = scanStaleRegistrations(scope);
59068
+ const fixed = options.fix && claudeSettings ? pruneStaleRegistrations(scope) : [];
59069
+ const stale = claudeSettings ? scanStaleRegistrations(scope) : [];
57910
59070
  for (const finding of stale) {
57911
59071
  issues.push({
57912
59072
  hook: finding.hook,
@@ -57915,15 +59075,45 @@ program3.command("doctor").option("-g, --global", "Check global settings", false
57915
59075
  });
57916
59076
  }
57917
59077
  const staleNames = new Set(stale.map((finding) => finding.hook));
57918
- const settingsExist = existsSync23(settingsPath);
57919
- if (!settingsExist) {
59078
+ const settingsExist = existsSync25(settingsPath);
59079
+ if (!settingsExist && !isAdapterTarget(target)) {
57920
59080
  issues.push({ hook: "(settings)", issue: `${settingsPath} not found`, severity: "warning" });
57921
59081
  }
57922
- const registered = getRegisteredHooks(scope);
59082
+ let registered = getRegisteredHooksForTarget(scope, target);
59083
+ if (isAdapterTarget(target)) {
59084
+ const state = readAdapterState(target, adapterOptions(scope));
59085
+ if (state.status === "unverified") {
59086
+ issues.push({ hook: `(${target})`, issue: `Cannot verify ${target}: ${state.reason}`, severity: "warning" });
59087
+ registered = [];
59088
+ } else {
59089
+ registered = state.registrations.map((entry) => entry.hook);
59090
+ if (target === "muse") {
59091
+ const muse = state;
59092
+ for (const hook of muse.inactive) {
59093
+ if (registered.includes(hook))
59094
+ continue;
59095
+ issues.push({
59096
+ hook,
59097
+ issue: `Installed in Muse but not enabled, so it never runs. Enable it: \`muse plugins enable hasna-hook-${hook}\``,
59098
+ severity: "error"
59099
+ });
59100
+ }
59101
+ for (const entry of readAdapterRegistrations("muse", adapterOptions(scope))) {
59102
+ if (registered.includes(entry.hook) || muse.inactive.includes(entry.hook))
59103
+ continue;
59104
+ issues.push({
59105
+ hook: entry.hook,
59106
+ issue: `A Hooks Muse bundle is on disk but ${muse.source} does not carry it, so nothing runs. Reinstall: \`hooks install ${entry.hook} --target muse\``,
59107
+ severity: "error"
59108
+ });
59109
+ }
59110
+ }
59111
+ }
59112
+ }
57923
59113
  let wiringCount = 0;
57924
- if (settingsExist) {
59114
+ if (settingsExist && settingsBased) {
57925
59115
  try {
57926
- const settings = JSON.parse(readFileSync35(settingsPath, "utf-8"));
59116
+ const settings = JSON.parse(readFileSync37(settingsPath, "utf-8"));
57927
59117
  wiringCount = countSettingsWiring(settings);
57928
59118
  } catch {}
57929
59119
  }
@@ -57934,7 +59124,7 @@ program3.command("doctor").option("-g, --global", "Check global settings", false
57934
59124
  const meta3 = custom2 ? resolveHookMeta(name) : getHook(name);
57935
59125
  let hookHealthy = true;
57936
59126
  if (custom2) {
57937
- if (!existsSync23(custom2.scriptPath)) {
59127
+ if (!existsSync25(custom2.scriptPath)) {
57938
59128
  issues.push({ hook: name, issue: `Custom hook script missing: ${custom2.scriptPath}`, severity: "error" });
57939
59129
  hookHealthy = false;
57940
59130
  }
@@ -57945,15 +59135,15 @@ program3.command("doctor").option("-g, --global", "Check global settings", false
57945
59135
  continue;
57946
59136
  }
57947
59137
  const hookDir = getHookPath(name);
57948
- const hookScript = join55(hookDir, "src", "hook.ts");
57949
- if (!existsSync23(hookScript)) {
59138
+ const hookScript = join56(hookDir, "src", "hook.ts");
59139
+ if (!existsSync25(hookScript)) {
57950
59140
  issues.push({ hook: name, issue: "Missing src/hook.ts in package", severity: "error" });
57951
59141
  hookHealthy = false;
57952
59142
  }
57953
59143
  }
57954
- if (meta3 && settingsExist) {
59144
+ if (meta3 && settingsExist && claudeSettings) {
57955
59145
  try {
57956
- const settings = JSON.parse(readFileSync35(settingsPath, "utf-8"));
59146
+ const settings = JSON.parse(readFileSync37(settingsPath, "utf-8"));
57957
59147
  if (!hookRegisteredInSettings(settings, name, meta3.event, matcherFor(meta3, "claude"))) {
57958
59148
  const eventName = meta3.event.split(":")[0];
57959
59149
  issues.push({ hook: name, issue: `Not registered under correct event (${eventName})`, severity: "error" });
@@ -57982,14 +59172,17 @@ program3.command("doctor").option("-g, --global", "Check global settings", false
57982
59172
  backups: fixed.map((result) => result.backupPath),
57983
59173
  registered,
57984
59174
  wiring_count: wiringCount,
57985
- scope
59175
+ scope,
59176
+ ...selectedTarget ? { target } : {}
57986
59177
  }));
57987
59178
  if (issues.some((issue2) => issue2.severity === "error"))
57988
59179
  process.exitCode = 1;
59180
+ else if (registered.length === 0 && issues.length > 0)
59181
+ process.exitCode = 1;
57989
59182
  return;
57990
59183
  }
57991
59184
  console.log(chalk2.bold(`
57992
- Hook Health Check (${scope})
59185
+ Hook Health Check (${scope}${selectedTarget ? `/${target}` : ""})
57993
59186
  `));
57994
59187
  if (fixed.length > 0) {
57995
59188
  for (const result of fixed) {
@@ -58056,7 +59249,7 @@ program3.command("update").argument("[hooks...]", "Hooks to update (defaults to
58056
59249
  const { resolveHook: resolveHook2 } = await Promise.resolve().then(() => (init_resolve(), exports_resolve));
58057
59250
  const { sha256File: sha256File2, setPinnedHook: setPinnedHook2, upsertHookRecord: upsertHookRecord2 } = await Promise.resolve().then(() => (init_store(), exports_store));
58058
59251
  const { getDb: getDb2, isLocalStoreRefused: isLocalStoreRefused2 } = await Promise.resolve().then(() => (init_db(), exports_db));
58059
- const { resolveHooksTransport: resolveHooksTransport3 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
59252
+ const { resolveHooksTransport: resolveHooksTransport4 } = await Promise.resolve().then(() => (init_transport2(), exports_transport));
58060
59253
  const { installPinnedFromBundled: installPinnedFromBundled2, fetchPinnedHook: fetchPinnedHook2 } = await Promise.resolve().then(() => (init_sync(), exports_sync));
58061
59254
  const { isCustomSource: isCustomSource2 } = await Promise.resolve().then(() => (init_custom_install(), exports_custom_install));
58062
59255
  const { HOOK_NAME_RE: HOOK_NAME_RE2 } = await Promise.resolve().then(() => (init_manifest(), exports_manifest));
@@ -58079,7 +59272,7 @@ program3.command("update").argument("[hooks...]", "Hooks to update (defaults to
58079
59272
  const pinned = parseNameVersion(arg);
58080
59273
  if (pinned) {
58081
59274
  try {
58082
- const transport = resolveHooksTransport3();
59275
+ const transport = resolveHooksTransport4();
58083
59276
  const pinnedInstall = transport.mode === "remote" && transport.authority ? await fetchPinnedHook2(pinned.name, pinned.version, transport.authority.origin, transport.authority) : await installPinnedFromBundled2(pinned.name, pinned.version);
58084
59277
  const registered = installHook(pinnedInstall.name, { scope, overwrite: true });
58085
59278
  if (!registered.success) {
@@ -58156,10 +59349,10 @@ program3.command("docs").argument("[hook]", "Hook name (shows general docs if om
58156
59349
  return;
58157
59350
  }
58158
59351
  const hookPath = getHookPath(hook);
58159
- const readmePath = join55(hookPath, "README.md");
59352
+ const readmePath = join56(hookPath, "README.md");
58160
59353
  let readme = "";
58161
- if (existsSync23(readmePath)) {
58162
- readme = readFileSync35(readmePath, "utf-8");
59354
+ if (existsSync25(readmePath)) {
59355
+ readme = readFileSync37(readmePath, "utf-8");
58163
59356
  }
58164
59357
  if (options.json) {
58165
59358
  console.log(JSON.stringify({ ...meta3, readme }));
@@ -59157,17 +60350,10 @@ function enforceTransportGate() {
59157
60350
  announceHooksLocalMode();
59158
60351
  return;
59159
60352
  }
59160
- let transport;
59161
- try {
59162
- transport = resolveHooksTransport(process.env);
59163
- } catch (error61) {
59164
- const message = error61 instanceof Error ? error61.message : String(error61);
59165
- failClosedForMissingApiEnv(message);
59166
- }
59167
- if (transport.mode !== "remote" || !transport.authority) {
59168
- failClosedForMissingApiEnv();
59169
- }
59170
- refuseLocalStore(hooksHostedRouteLocalStoreRefusal(transport.authority.v1BaseUrl));
60353
+ const route = hooksAmbientGateRoute(token, process.env);
60354
+ if (route.kind === "fail")
60355
+ failClosedForMissingApiEnv(route.detail);
60356
+ refuseLocalStore(hooksHostedRouteLocalStoreRefusal(route.authority));
59171
60357
  }
59172
60358
  enforceTransportGate();
59173
60359
  program3.parse();