@hasna/hooks 0.12.20 → 0.12.22

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.
@@ -38,6 +38,18 @@ for (const meta of entries) {
38
38
  assert.equal(sdk.exitCode, 0, sdk.stderr);
39
39
  assert.deepEqual(sdk.output, {});
40
40
  }
41
+ // A compact SessionStart runs the whole bundle but never reaches the Scratchpad
42
+ // CLI, so the proof writes nothing and needs no Scratchpad install.
43
+ if (meta.name === "scratch-lifecycle") {
44
+ const input = JSON.stringify({ hook_event_name: "SessionStart", session_id: "packed-probe", source: "compact" });
45
+ const result = spawnSync(process.execPath, [expected, "--harness", "codex"], {
46
+ cwd: ${JSON.stringify(consumerDir)}, encoding: "utf8", input, timeout: 5000,
47
+ env: { PATH: process.env.PATH, HOME: process.env.HOME }
48
+ });
49
+ assert.equal(result.status, 0, result.stderr);
50
+ assert.deepEqual(JSON.parse(result.stdout), {});
51
+ assert.deepEqual(JSON.parse(result.stderr), { hook: "scratch-lifecycle", reason: "skipped_compact" });
52
+ }
41
53
  // A broken published bundle must fail closed even while its historical raw
42
54
  // hook source is still packed. Only this synthetic extracted copy is moved.
43
55
  const missing = expected + ".fixture-missing";
@@ -1,6 +1,6 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
- import { copyFile, mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises";
3
+ import { chmod, copyFile, mkdtemp, mkdir, readFile, realpath, rm, symlink, writeFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { validatePackedBundledHooks } from "./validate-bundled-hooks";
6
6
 
@@ -231,6 +231,47 @@ console.log("packed credential-file reference, rotation and terminal failure pas
231
231
  * Lanes: CLI help, serve /health, MCP stdio startup (initialize handshake),
232
232
  * a runtime SDK import, and one bundled-hook run with an isolated data dir.
233
233
  */
234
+ /** HO-00079: exercise the extracted Hooks parser, not the source Skills parser.
235
+ * The generator uses the exact declared installed Skills dependency. Only the
236
+ * fixtures are planner-generated test data; neither check applies a registration. */
237
+ async function validatePackedSkillsPolicy(pkg: PackageJson, packageDir: string, smokeDir: string): Promise<void> {
238
+ const installedSkills = Bun.resolveSync("@hasna/skills", join(root, "src/test"));
239
+ const dependency = await readPackageJson(join(dirname(dirname(installedSkills)), "package.json"));
240
+ const declaredVersion = pkg.dependencies?.["@hasna/skills"];
241
+ if (!declaredVersion || dependency.name !== "@hasna/skills" || dependency.version !== declaredVersion)
242
+ throw new Error("Packed policy validation requires the exact declared Skills dependency");
243
+ const home = join(smokeDir, "skills-policy-home");
244
+ await mkdir(home, { mode: 0o700 });
245
+ const fixture = join(smokeDir, "skills-policy-smoke.ts");
246
+ await writeFile(fixture, `
247
+ import assert from "node:assert/strict";
248
+ import { join } from "node:path";
249
+ import { planNativeSafetyRegistration } from ${JSON.stringify(join(packageDir, "dist/index.js"))};
250
+ import { generatePackedReaderPolicy, policyHashModes, treeSnapshot, withPolicyMutation } from ${JSON.stringify(join(root, "src/test/skills-policy-fixture.ts"))};
251
+ const home = process.env.HOME, dataDir = join(home, "skills-data");
252
+ generatePackedReaderPolicy(home, dataDir);
253
+ assert.deepEqual(policyHashModes(dataDir).codex, ["codex-settings-v6", "bytes"]);
254
+ const options = { target: "claude" }, dependencies = { verify: async () => ({}) };
255
+ const before = treeSnapshot(home);
256
+ const plan = await planNativeSafetyRegistration(options, dependencies);
257
+ assert.equal(plan.action, "register");
258
+ assert.equal(plan.nativeAdoptionVerified, false);
259
+ assert.deepEqual(treeSnapshot(home), before);
260
+ withPolicyMutation(dataDir, policy => { policy.bridge.discovery.codex.sources[0].hashMode = "codex-settings-v99"; });
261
+ const damaged = treeSnapshot(home);
262
+ await assert.rejects(() => planNativeSafetyRegistration(options, dependencies), error =>
263
+ error.code === "writer_refused" && error.refusal?.message === "The Skills agent loading policy has invalid collection bounds; refusing legacy fallback.");
264
+ assert.deepEqual(treeSnapshot(home), damaged);
265
+ console.log("packed Hooks accepts codex-settings-v6 and refuses unknown mode without writes");
266
+ `);
267
+ const result = spawnSync(process.execPath, ["--config=/dev/null", "--no-env-file", "--no-macros", "--no-install", fixture], {
268
+ cwd: smokeDir, env: { HOME: home, PATH: process.env.PATH, HASNA_SKILLS_DIR: join(home, "skills-data") },
269
+ encoding: "utf8", timeout: 30_000,
270
+ });
271
+ if (result.status !== 0) throw new Error(`Packed Skills policy compatibility failed: ${result.stderr}`);
272
+ console.log(result.stdout.trim());
273
+ }
274
+
234
275
  async function validatePackedNativeSafety(packageDir: string, smokeDir: string): Promise<void> {
235
276
  const worker = join(packageDir, "bin/native-safety-entry.js");
236
277
  const bytes = await readFile(worker);
@@ -281,6 +322,49 @@ async function validatePackedNativeSafety(packageDir: string, smokeDir: string):
281
322
  } finally { await writeFile(worker, bytes); }
282
323
  }
283
324
 
325
+ /**
326
+ * HO-00087: a harness starts `hooks run <hook>` and `hooks-mcp` in the project
327
+ * it works on. Executed through their own shebang, as a harness does, the packed
328
+ * bins must not run that project's bunfig.toml preload or read its .env, and a
329
+ * hook they start must not either.
330
+ */
331
+ async function validatePackedEntryIsolation(options: {
332
+ binIndex: string;
333
+ binMcp: string;
334
+ workspace: string;
335
+ env: NodeJS.ProcessEnv;
336
+ failClosedEnv: NodeJS.ProcessEnv;
337
+ }): Promise<void> {
338
+ const { binIndex, binMcp, workspace, env, failClosedEnv } = options;
339
+ const project = join(workspace, "hostile-project");
340
+ const marker = join(workspace, "hostile-preload-ran");
341
+ await mkdir(project);
342
+ await writeFile(join(project, "preload.ts"), `require("node:fs").appendFileSync(${JSON.stringify(marker)}, process.argv[1] + "\\n");\n`);
343
+ await writeFile(join(project, "bunfig.toml"), `preload = ["./preload.ts"]\n`);
344
+ // Without the shebang's --no-env-file this opt-in would turn the fail-closed runs below into local-mode runs.
345
+ await writeFile(join(project, ".env"), "HASNA_HOOKS_LOCAL=1\n");
346
+ // npm makes bin targets executable on install; the extracted tarball keeps the packed mode.
347
+ for (const bin of [binIndex, binMcp]) await chmod(bin, 0o755);
348
+
349
+ // Positive control: plain bun in that directory does run the preload.
350
+ const control = spawnSync("bun", [binIndex, "--version"], { cwd: project, env, encoding: "utf8", timeout: 20000 });
351
+ if (control.status !== 0 || !existsSync(marker)) throw new Error(`hostile-project control did not run its preload (exit ${control.status})`);
352
+ await rm(marker);
353
+
354
+ const input = JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command: "echo smoke" } });
355
+ const ran = spawnSync(binIndex, ["run", "gitguard"], { cwd: project, env, encoding: "utf8", input, timeout: 20000 });
356
+ if (ran.status !== 0 || !/decision/.test(ran.stdout)) throw new Error(`packed CLI run through its shebang failed (exit ${ran.status}): ${ran.stderr.slice(0, 300)}`);
357
+ for (const [label, bin, args] of [["packed CLI `hooks categories`", binIndex, ["categories"]], ["packed hooks-mcp", binMcp, []]] as Array<[string, string, string[]]>) {
358
+ const refused = spawnSync(bin, args, { cwd: project, env: failClosedEnv, encoding: "utf8", input: "", timeout: 20000 });
359
+ if (refused.status === 0) throw new Error(`${label} read the project's .env opt-in (exit 0 with nothing configured)`);
360
+ // Only the fail-closed refusal text proves the bin started through its shebang at all.
361
+ if (!/HASNA_HOOKS_LOCAL=1/.test(refused.stderr) || !/hasna\.credentials\.hooks\.api-key/.test(refused.stderr)) {
362
+ throw new Error(`${label} did not start through its shebang and reach the fail-closed refusal (exit ${refused.status}): ${refused.stderr.slice(0, 300)}`);
363
+ }
364
+ }
365
+ if (existsSync(marker)) throw new Error(`a packed bin or its hook ran the project's bunfig.toml preload: ${(await readFile(marker, "utf8")).trim()}`);
366
+ }
367
+
284
368
  async function validateExtractedSmoke(pkg: PackageJson): Promise<void> {
285
369
  const tempRoot = join(root, "temp");
286
370
  await mkdir(tempRoot, { recursive: true });
@@ -414,6 +498,7 @@ async function validateExtractedSmoke(pkg: PackageJson): Promise<void> {
414
498
  if (sdkOut.sdk !== "fail-closed" || !sdkOut.hasClient) throw new Error(`packed ./sdk export did not fail closed with nothing configured: ${JSON.stringify(sdkOut)}`);
415
499
  await validatePackedCredentialReferences(pkg, packageDir, smokeDir);
416
500
  await validatePackedNativeSafety(packageDir, smokeDir);
501
+ await validatePackedSkillsPolicy(pkg, packageDir, smokeDir);
417
502
 
418
503
  // 5. One bundled-hook run from the packed artifact (isolated data dir;
419
504
  // first run self-trusts, then executes).
@@ -426,6 +511,8 @@ async function validateExtractedSmoke(pkg: PackageJson): Promise<void> {
426
511
  });
427
512
  if (runRes.status !== 0) throw new Error(`packed bundled-hook run failed (exit ${runRes.status}): ${runRes.stderr}`);
428
513
  if (!/decision/.test(runRes.stdout)) throw new Error(`packed bundled-hook run produced no hook decision: ${runRes.stdout.slice(0, 200)}`);
514
+
515
+ await validatePackedEntryIsolation({ binIndex, binMcp, workspace, env, failClosedEnv: fcEnv });
429
516
  } finally {
430
517
  await rm(workspace, { force: true, recursive: true });
431
518
  }