Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(hooks): add the hook engine, module loader and closed actions
Jack Rudenko90abd6fe39b4
diff --git a/packages/cli/src/behavior/engine.ts b/packages/cli/src/behavior/engine.tsindex b2562b1a..ccfdbaa1 100644--- a/packages/cli/src/behavior/engine.ts+++ b/packages/cli/src/behavior/engine.ts@@ -12,15 +12,22 @@* cannot read each other's plan file path.*/-import { log } from "../logger.js";-import { resolveSeverity } from "./config.js";-import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";-import { type Decision, type Surface, classifyPath, recordDecision } from "./journal.js";+import {+ type Decision,+ type Surface,+ classifyPath,+ isUploadDecision,+ isUploadSurface,+ recordDecision,+} from "../hooks/journal.js";import {recordTelemetryDecision,recordTelemetryTurn,setTelemetryConsent,-} from "./telemetry/aggregate.js";+} from "../hooks/telemetry/aggregate.js";+import { log } from "../logger.js";+import { resolveSeverity } from "./config.js";+import { detectHarnessFacts, extractAvailableSkills, extractSessionId } from "./harness.js";import type {BehaviorConfig,BehaviorContext,@@ -411,16 +418,17 @@ export class BehaviorSession {// Same call site as the local journal, so the two can never disagree about// what happened. This one only counts — no paths, no values; see// telemetry/aggregate.ts. It is a no-op unless telemetry is opted in.- recordTelemetryDecision({- sessionId: this.sessionId,- model: this.modelId,- provider: this.providerName,- surface,- decision,- ruleId: detail.ruleId,- toolName: detail.toolName,- pathRelation,- });+ if (isUploadSurface(surface) && isUploadDecision(decision))+ recordTelemetryDecision({+ sessionId: this.sessionId,+ model: this.modelId,+ provider: this.providerName,+ surface,+ decision,+ ruleId: detail.ruleId,+ toolName: detail.toolName,+ pathRelation,+ });void recordDecision({ts: new Date().toISOString(),@@ -432,7 +440,7 @@ export class BehaviorSession {toolName: detail.toolName,argKeys: detail.argKeys,pathRelation,- // Full detail stays local; toUploadable() drops this wholesale.+ // Full detail stays local; nothing uploads a journal line.local: {observedPath: detail.observedPath,expectedPath: detail.expectedPath,@@ -564,7 +572,7 @@ export class BehaviorEngine {// background of a live process, because shutdown is synchronous and cannot// await a POST. Never awaited, never allowed to throw.if (optedIn) {- void import("./telemetry/upload.js")+ void import("../hooks/telemetry/upload.js").then((m) => m.drainOutbox()).catch((err) => log(`[behavior:telemetry] drain unavailable: ${err}`));}diff --git a/packages/cli/src/behavior/index.ts b/packages/cli/src/behavior/index.tsindex f2b48136..70e83260 100644--- a/packages/cli/src/behavior/index.ts+++ b/packages/cli/src/behavior/index.ts@@ -33,9 +33,9 @@ export {setSessionContextWindow,setTelemetryConsent,spoolPendingSync,-} from "./telemetry/aggregate.js";-export type { ContextBucket, SessionReport } from "./telemetry/aggregate.js";-export { drainOutbox, resetDrainState } from "./telemetry/upload.js";+} from "../hooks/telemetry/aggregate.js";+export type { ContextBucket, SessionReport } from "../hooks/telemetry/aggregate.js";+export { drainOutbox, resetDrainState } from "../hooks/telemetry/upload.js";export type {BehaviorConfig,BehaviorContext,diff --git a/packages/cli/src/behavior/output-rules.test.ts b/packages/cli/src/behavior/output-rules.test.tsindex 57055880..1949fa8d 100644--- a/packages/cli/src/behavior/output-rules.test.ts+++ b/packages/cli/src/behavior/output-rules.test.ts@@ -1,8 +1,8 @@import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";+import * as journal from "../hooks/journal.js";import * as logger from "../logger.js";import type { BehaviorEngine } from "./engine.js";import { createBehaviorEngine } from "./index.js";-import * as journal from "./journal.js";import type { BehaviorRule, ModelOutputContext, Severity } from "./types.js";const SESSION_A = "ce7d9e68-f907-444f-9680-69ec3048ce9c";diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.tsindex 7eeaa599..6286b65f 100644--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@ -1927,7 +1927,7 @@ export async function runClaudeWithProxy(// above go on the CHILD's env, while the proxy runs here in the parent and// only knows the model's spec window. No-op unless telemetry is opted in.try {- const { setSessionContextWindow } = await import("./behavior/telemetry/aggregate.js");+ const { setSessionContextWindow } = await import("./hooks/telemetry/aggregate.js");setSessionContextWindow(realWindow);} catch {// Telemetry must never affect launching Claude Code.diff --git a/packages/cli/src/hooks/actions.test.ts b/packages/cli/src/hooks/actions.test.tsnew file mode 100644index 00000000..a7c53fcd--- /dev/null+++ b/packages/cli/src/hooks/actions.test.ts@@ -0,0 +1,445 @@+import { describe, expect, it } from "bun:test";+import {+ type MutableClaudeRequest,+ type PlannedAction,+ applyStageA,+ applyStageB,+ applyToolCallActions,+ validateAction,+} from "./actions.js";+import { type RequestAction, type ToolCallAction, act } from "./public.js";++const plan = (hookId: string, action: RequestAction): PlannedAction<RequestAction> => ({+ hookId,+ action,+});++function request(overrides: Partial<MutableClaudeRequest> = {}): MutableClaudeRequest {+ return {+ system: "base",+ messages: [+ { role: "user", content: "first question" },+ {+ role: "assistant",+ content: [+ { type: "thinking", thinking: "secret plan", signature: "sig" },+ { type: "text", text: "let me check" },+ { type: "tool_use", id: "toolu_1", name: "Read", input: { path: "plan" } },+ ],+ },+ {+ role: "user",+ content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "plan contents" }],+ },+ ],+ tools: [+ { name: "Read", description: "Read a file", input_schema: { type: "object" } },+ { name: "Write", description: "Write a file", input_schema: { type: "object" } },+ { name: "ExitPlanMode", description: "Exit.", input_schema: { type: "object" } },+ ],+ ...overrides,+ };+}++describe("validateAction", () => {+ it("allows only the event's actions", () => {+ expect(validateAction("request", act.injectSystemNote("x")).ok).toBe(true);+ expect(validateAction("request", act.appendText("x"))).toEqual({+ ok: false,+ reason: "not_allowed:appendText",+ });+ expect(validateAction("responseEnd", act.injectUserTurn("go")).ok).toBe(true);+ expect(validateAction("sessionBlocked", act.injectUserTurn("go")).ok).toBe(false);+ expect(validateAction("sessionEnd", act.warn("w")).ok).toBe(true);+ });++ it("restricts an observe-mode toolCall hook to warn", () => {+ expect(+ validateAction("toolCall", act.repairToolArgs({ a: 1 }, "r"), { observe: true })+ ).toEqual({ ok: false, reason: "observe_only" });+ expect(validateAction("toolCall", act.warn("w"), { observe: true }).ok).toBe(true);+ });++ it("rejects non-actions and unknown types", () => {+ expect(validateAction("request", null)).toEqual({ ok: false, reason: "not_an_action" });+ expect(validateAction("request", { type: "launchMissiles" })).toEqual({+ ok: false,+ reason: "not_allowed:launchMissiles",+ });+ });++ it("refuses an injectUserTurn starting with a slash once leading whitespace is ignored", () => {+ expect(validateAction("sessionIdle", act.injectUserTurn(" /clear"))).toEqual({+ ok: false,+ reason: "slash_command",+ });+ expect(validateAction("sessionIdle", act.injectUserTurn("\n\t/compact"))).toEqual({+ ok: false,+ reason: "slash_command",+ });+ expect(validateAction("sessionIdle", act.injectUserTurn("run a/b")).ok).toBe(true);+ });++ it("enforces text limits", () => {+ expect(validateAction("request", act.injectSystemNote(""))).toEqual({+ ok: false,+ reason: "empty_text",+ });+ expect(validateAction("request", act.injectSystemNote("x".repeat(20_000))).ok).toBe(true);+ expect(validateAction("request", act.injectSystemNote("x".repeat(20_001))).ok).toBe(false);+ expect(validateAction("request", act.rewriteToolDescription("T", "x".repeat(4_001))).ok).toBe(+ false+ );+ expect(validateAction("sessionIdle", act.injectUserTurn("x".repeat(100_001))).ok).toBe(false);+ });++ it("checks replaceToolSchema shape and size", () => {+ expect(+ validateAction("request", {+ type: "replaceToolSchema",+ tool: "Write",+ inputSchema: { type: "array" },+ })+ ).toEqual({ ok: false, reason: "schema_not_object" });+ expect(+ validateAction(+ "request",+ act.replaceToolSchema("Write", { type: "object", description: "x".repeat(70_000) })+ )+ ).toEqual({ ok: false, reason: "schema_too_large" });+ expect(+ validateAction("request", act.replaceToolSchema("Write", { type: "object", f: () => 1 }))+ ).toEqual({ ok: false, reason: "schema_not_json" });+ });++ it("checks annotateTurn key and value", () => {+ expect(validateAction("responseEnd", act.annotateTurn("files.read", ["a", 1])).ok).toBe(true);+ expect(validateAction("responseEnd", act.annotateTurn("Bad Key", 1))).toEqual({+ ok: false,+ reason: "invalid_key",+ });+ expect(validateAction("responseEnd", act.annotateTurn("k", "x".repeat(17_000)))).toEqual({+ ok: false,+ reason: "value_too_large",+ });+ });++ it("checks repairToolArgs and a regex find", () => {+ expect(validateAction("toolCall", act.repairToolArgs({ a: 1 }, "why")).ok).toBe(true);+ expect(validateAction("toolCall", { type: "repairToolArgs", args: [1], reason: "r" })).toEqual({+ ok: false,+ reason: "args_not_object",+ });+ expect(validateAction("request", act.replaceMessageText("(", "x", { regex: true }))).toEqual({+ ok: false,+ reason: "invalid_regex",+ });+ expect(+ validateAction("request", {+ type: "replaceMessageText",+ find: "a",+ replace: "b",+ roles: ["system"],+ })+ ).toEqual({ ok: false, reason: "invalid_roles" });+ });+});++describe("applyStageA — system notes", () => {+ it("appends to a string system as a new paragraph, once per identical text", () => {+ const req = request();+ const { results } = applyStageA(req, [+ plan("a", act.injectSystemNote("NOTE")),+ plan("b", act.injectSystemNote("NOTE")),+ ]);+ expect(req.system).toBe("base\n\nNOTE");+ expect(results.map((r) => [r.hookId, r.decision])).toEqual([+ ["a", "matched"],+ ["b", "superseded"],+ ]);+ });++ it("appends a text block to an array system without mutating the original array", () => {+ const original = [{ type: "text", text: "base" }];+ const req = request({ system: original });+ applyStageA(req, [plan("a", act.injectSystemNote("NOTE"))]);+ expect(req.system).toEqual([+ { type: "text", text: "base" },+ { type: "text", text: "NOTE" },+ ]);+ expect(original.length).toBe(1);+ });++ it("sets the system prompt when the request has none", () => {+ const req = request({ system: undefined });+ applyStageA(req, [plan("a", act.injectSystemNote("NOTE"))]);+ expect(req.system).toBe("NOTE");+ });+});++describe("applyStageA — message text", () => {+ it("appendUserText lands at the end of the last user message, after tool_result", () => {+ const req = request();+ applyStageA(req, [plan("a", act.appendUserText("REMINDER"))]);+ const last = req.messages?.[2];+ expect(last.content).toEqual([+ { type: "tool_result", tool_use_id: "toolu_1", content: "plan contents" },+ { type: "text", text: "REMINDER" },+ ]);+ });++ it("appendUserText normalises a string content to blocks first", () => {+ const req = request({ messages: [{ role: "user", content: "hi" }] });+ applyStageA(req, [plan("a", act.appendUserText("there"))]);+ expect(req.messages?.[0].content).toEqual([+ { type: "text", text: "hi" },+ { type: "text", text: "there" },+ ]);+ });++ it("appendUserText with no user message is invalid", () => {+ const req = request({ messages: [{ role: "assistant", content: "x" }] });+ const { results } = applyStageA(req, [plan("a", act.appendUserText("x"))]);+ expect(results[0]).toMatchObject({ decision: "invalid", detail: "no_user_message" });+ });++ it("identical appended texts are applied once", () => {+ const req = request({ messages: [{ role: "user", content: "q" }] });+ const { results } = applyStageA(req, [+ plan("a", act.appendUserText("same")),+ plan("b", act.appendUserText("same")),+ ]);+ expect(req.messages?.[0].content.length).toBe(2);+ expect(results.map((r) => r.decision)).toEqual(["matched", "superseded"]);+ });++ it("never touches tool_use, tool_result or thinking, and defaults roles to user", () => {+ const req = request();+ const before = structuredClone(req.messages);+ applyStageA(req, [plan("a", act.replaceMessageText("plan", "PLAN"))]);+ // User string content was edited; the assistant turn (default roles) was not.+ expect(req.messages?.[0].content).toBe("first question");+ expect(req.messages?.[1]).toEqual(before?.[1]);+ // tool_result content is never edited even though it contains "plan".+ expect(req.messages?.[2]).toEqual(before?.[2]);++ applyStageA(req, [+ plan("a", act.replaceMessageText("check", "verify", { roles: ["assistant"] })),+ ]);+ const blocks = req.messages?.[1].content;+ expect(blocks[0]).toEqual({ type: "thinking", thinking: "secret plan", signature: "sig" });+ expect(blocks[1]).toEqual({ type: "text", text: "let me verify" });+ expect(blocks[2].input).toEqual({ path: "plan" });+ });++ it("inserts a literal $500 verbatim and expands $1 in regex mode", () => {+ const req = request({ messages: [{ role: "user", content: "cost N, name: Ada Lovelace" }] });+ applyStageA(req, [+ plan("a", act.replaceMessageText("N", "$500")),+ plan("b", act.replaceMessageText("(\\w+) (\\w+)$", "$2 $1", { regex: true })),+ ]);+ expect(req.messages?.[0].content).toBe("cost $500, name: Lovelace Ada");+ });++ it("drops an emptied text block, and reverts an edit that would empty a message", () => {+ const req = request({+ messages: [+ {+ role: "user",+ content: [+ { type: "text", text: "DROP" },+ { type: "text", text: "keep" },+ ],+ },+ { role: "assistant", content: "ok" },+ { role: "user", content: "DROP" },+ ],+ });+ const { results } = applyStageA(req, [plan("a", act.removeMessageText("DROP"))]);+ expect(req.messages?.[0].content).toEqual([{ type: "text", text: "keep" }]);+ expect(req.messages?.[2].content).toBe("DROP");+ expect(results[0]).toMatchObject({ decision: "matched", detail: "empty_message_reverted:1" });+ });++ it("reports invalid empty_message when every changed message was reverted", () => {+ const req = request({ messages: [{ role: "user", content: "only" }] });+ const { results } = applyStageA(req, [plan("a", act.removeMessageText("only"))]);+ expect(req.messages?.[0].content).toBe("only");+ expect(results[0]).toMatchObject({ decision: "invalid", detail: "empty_message" });+ });++ it("applies message edits sequentially in effective order", () => {+ const req = request({ messages: [{ role: "user", content: "a" }] });+ applyStageA(req, [+ plan("a", act.replaceMessageText("a", "b")),+ plan("b", act.replaceMessageText("b", "c")),+ plan("c", act.appendUserText("d")),+ ]);+ expect(req.messages?.[0].content).toEqual([+ { type: "text", text: "c" },+ { type: "text", text: "d" },+ ]);+ });++ it("does not mutate the original message objects", () => {+ const original = { role: "user", content: [{ type: "text", text: "x" }] };+ const req = request({ messages: [original] });+ applyStageA(req, [plan("a", act.replaceMessageText("x", "y"))]);+ expect(original.content[0]?.text).toBe("x");+ expect(req.messages?.[0]).not.toBe(original);+ });+});++describe("applyStageA — tools", () => {+ it("removeTool is refused while a message holds a tool_use of that tool", () => {+ const req = request();+ const { results } = applyStageA(req, [plan("a", act.removeTool("Read"))]);+ expect(results[0]).toMatchObject({ decision: "invalid", detail: "tool_in_history" });+ expect(req.tools?.map((t) => t.name)).toEqual(["Read", "Write", "ExitPlanMode"]);+ });++ it("removes a tool, and supersedes every other action on it", () => {+ const req = request();+ const stage = applyStageA(req, [+ plan("a", act.replaceToolSchema("Write", { type: "object", properties: {} })),+ plan("b", act.removeTool("Write")),+ plan("c", act.removeTool("Write")),+ plan("d", act.rewriteToolDescription("Write", " more")),+ ]);+ expect(req.tools?.map((t) => t.name)).toEqual(["Read", "ExitPlanMode"]);+ expect(stage.results.map((r) => [r.hookId, r.decision, r.detail])).toEqual([+ ["a", "superseded", "tool_removed"],+ ["b", "matched", undefined],+ ["c", "superseded", "already_removed"],+ ]);+ const stageB = applyStageB(req.tools ?? [], null, stage.held, stage.removedTools);+ expect(stageB[0]).toMatchObject({+ hookId: "d",+ decision: "superseded",+ detail: "tool_removed",+ });+ });++ it("replaceToolSchema: first wins per tool; an unknown tool is invalid", () => {+ const original = request().tools?.[1];+ const req = request();+ const { results } = applyStageA(req, [+ plan("a", act.replaceToolSchema("Write", { type: "object", properties: { a: {} } })),+ plan("b", act.replaceToolSchema("Write", { type: "object", properties: { b: {} } })),+ plan("c", act.replaceToolSchema("Nope", { type: "object" })),+ ]);+ expect(req.tools?.[1].input_schema).toEqual({ type: "object", properties: { a: {} } });+ expect(original?.input_schema).toEqual({ type: "object" });+ expect(results.map((r) => [r.hookId, r.decision, r.detail])).toEqual([+ ["a", "matched", undefined],+ ["b", "superseded", undefined],+ ["c", "invalid", "unknown_tool"],+ ]);+ });++ it("removeTool on an unknown tool is invalid", () => {+ const { results } = applyStageA(request(), [plan("a", act.removeTool("Nope"))]);+ expect(results[0]).toMatchObject({ decision: "invalid", detail: "unknown_tool" });+ });++ it("holds description actions for stage B in effective order", () => {+ const { held } = applyStageA(request(), [+ plan("a", act.rewriteToolDescription("Write", " A")),+ plan("b", act.injectSystemNote("x")),+ plan("c", act.replaceToolDescription("Read", "R")),+ plan("d", act.warn("ignored here")),+ ]);+ expect(held.map((h) => h.hookId)).toEqual(["a", "c"]);+ });+});++describe("applyStageB — tool descriptions", () => {+ const claudeTools = () => [+ { name: "ExitPlanMode", description: "Exit plan mode." },+ { name: "Write", description: "Write." },+ ];+ // Chat Completions shape wraps in `function`; Responses shape does not.+ const chatTools = () => [+ { type: "function", function: { name: "ExitPlanMode", description: "Exit plan mode." } },+ { type: "function", function: { name: "Write", description: "Write." } },+ ];++ it("applies to both representations, after conversion", () => {+ const claude = claudeTools();+ const converted = chatTools();+ const results = applyStageB(claude, converted, [+ plan("plan", act.rewriteToolDescription("ExitPlanMode", " Write to /p.md first.")),+ ]);+ expect(claude[0]?.description).toBe("Exit plan mode. Write to /p.md first.");+ expect(converted[0]?.function.description).toBe("Exit plan mode. Write to /p.md first.");+ expect(results[0]).toMatchObject({ decision: "matched" });+ });++ it("appends after a summarised converted description, keeping the full append", () => {+ const claude = [{ name: "ExitPlanMode", description: "Long. Very long description." }];+ // What --summarize-tools left on the converted side: the first sentence.+ const converted = [{ name: "ExitPlanMode", description: "Long." }];+ const append = " IMPORTANT: the plan file is /exact/path.md; write it there.";+ applyStageB(claude, converted, [plan("p", act.rewriteToolDescription("ExitPlanMode", append))]);+ expect(converted[0]?.description).toBe(`Long.${append}`);+ });++ it("first description action per tool wins across append and replace", () => {+ const claude = claudeTools();+ const results = applyStageB(claude, chatTools(), [+ plan("a", act.replaceToolDescription("Write", "NEW")),+ plan("b", act.rewriteToolDescription("Write", " more")),+ ]);+ expect(claude[1]?.description).toBe("NEW");+ expect(results.map((r) => r.decision)).toEqual(["matched", "superseded"]);+ });++ it("an unknown tool is invalid; a capped tool changes the Claude copy only", () => {+ const claude = claudeTools();+ const converted = [chatTools()[0]];+ const results = applyStageB(claude, converted, [+ plan("a", act.rewriteToolDescription("Nope", " x")),+ plan("b", act.rewriteToolDescription("Write", " x")),+ ]);+ expect(results.map((r) => [r.decision, r.detail])).toEqual([+ ["invalid", "unknown_tool"],+ ["matched", "capped"],+ ]);+ expect(claude[1]?.description).toBe("Write. x");+ });++ it("applies once when both representations are the same array (native)", () => {+ const tools = claudeTools();+ applyStageB(tools, tools, [plan("a", act.rewriteToolDescription("Write", " x"))]);+ expect(tools[1]?.description).toBe("Write. x");+ const solo = claudeTools();+ applyStageB(solo, null, [plan("a", act.rewriteToolDescription("Write", " x"))]);+ expect(solo[1]?.description).toBe("Write. x");+ });++ it("replaces array elements instead of mutating tool objects", () => {+ const claude = claudeTools();+ const original = claude[1];+ applyStageB(claude, null, [plan("a", act.rewriteToolDescription("Write", " x"))]);+ expect(original?.description).toBe("Write.");+ expect(claude[1]).not.toBe(original);+ });+});++describe("applyToolCallActions", () => {+ it("first repairToolArgs wins; later ones are superseded", () => {+ const items: PlannedAction<ToolCallAction>[] = [+ { hookId: "a", action: act.repairToolArgs({ file_path: "/a" }, "a") },+ { hookId: "b", action: act.repairToolArgs({ file_path: "/b" }, "b") },+ ];+ const out = applyToolCallActions(items);+ expect(out.args).toEqual({ file_path: "/a" });+ expect(out.results.map((r) => r.decision)).toEqual(["matched", "superseded"]);+ });++ it("returns no args when nothing repaired", () => {+ expect(applyToolCallActions([{ hookId: "a", action: act.warn("w") }])).toEqual({+ results: [],+ });+ });+});diff --git a/packages/cli/src/hooks/actions.ts b/packages/cli/src/hooks/actions.tsnew file mode 100644index 00000000..1d0b7a81--- /dev/null+++ b/packages/cli/src/hooks/actions.ts@@ -0,0 +1,591 @@+/**+ * Closed actions: which actions each event may return, the shape and limit+ * check every action passes before it is applied, and the appliers for the+ * request and tool-call targets.+ *+ * Actions are plain data (the Command pattern as a discriminated union), so+ * they can be validated, severity-gated, conflict-checked, journaled and, for+ * `injectUserTurn` / `annotateTurn`, serialised into the hook inbox. Nothing+ * here runs hook code.+ *+ * The request appliers never mutate a message, block or tool object in place.+ * Stage A replaces `system`, `messages` and `tools` (and every changed message+ * or tool) with new objects on the request object it is given; stage B replaces+ * ELEMENTS of the two tool arrays it is given, so a converted array the provider+ * payload aliases sees the change. That makes them safe on the NativeHandler's+ * copy-on-write view as well as on ComposedHandler's deep copy.+ */++import type {+ ClaudeContentBlock,+ HookAction,+ JsonValue,+ RemoveMessageText,+ ReplaceMessageText,+ RequestAction,+ ToolCallAction,+} from "./public.js";+import { compileMatcher } from "./text-rewrite.js";++/** The events whose handlers return closed actions. */+export type ClosedEvent =+ | "request"+ | "toolCall"+ | "responseRewrite"+ | "responseEnd"+ | "sessionStart"+ | "sessionIdle"+ | "sessionBlocked"+ | "sessionEnd";++export const CLOSED_EVENTS: ReadonlyArray<ClosedEvent> = [+ "request",+ "toolCall",+ "responseRewrite",+ "responseEnd",+ "sessionStart",+ "sessionIdle",+ "sessionBlocked",+ "sessionEnd",+];++type ActionType = HookAction["type"];++/** §4.4 "Allowed actions", per event. */+export const ALLOWED_ACTIONS: Readonly<Record<ClosedEvent, ReadonlySet<ActionType>>> = {+ request: new Set<ActionType>([+ "injectSystemNote",+ "appendUserText",+ "replaceMessageText",+ "removeMessageText",+ "rewriteToolDescription",+ "replaceToolDescription",+ "replaceToolSchema",+ "removeTool",+ "warn",+ ]),+ toolCall: new Set<ActionType>(["repairToolArgs", "warn"]),+ responseRewrite: new Set<ActionType>([+ "appendText",+ "prependText",+ "replaceText",+ "removeText",+ "warn",+ ]),+ responseEnd: new Set<ActionType>(["injectSystemNote", "injectUserTurn", "annotateTurn", "warn"]),+ sessionStart: new Set<ActionType>(["injectUserTurn", "warn"]),+ sessionIdle: new Set<ActionType>(["injectUserTurn", "warn"]),+ sessionBlocked: new Set<ActionType>(["warn"]),+ sessionEnd: new Set<ActionType>(["warn"]),+};++/** Only `warn` is allowed from an observe-mode `toolCall` hook. */+const OBSERVE_ONLY: ReadonlySet<ActionType> = new Set<ActionType>(["warn"]);++/* ───────────── limits ───────────── */++export const LIMITS = {+ systemNote: 20_000,+ userText: 20_000,+ toolDescriptionAppend: 4_000,+ toolDescription: 20_000,+ toolSchemaBytes: 64 * 1024,+ repairArgsBytes: 1024 * 1024,+ responseText: 1_000_000,+ injectUserTurn: 100_000,+ annotationValueBytes: 16 * 1024,+ warn: 20_000,+} as const;++const ANNOTATION_KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/;+const ROLES = new Set(["user", "assistant"]);++export type Validation = { ok: true; action: HookAction } | { ok: false; reason: string };++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return !!v && typeof v === "object" && !Array.isArray(v);+}++function textIn(v: unknown, max: number): string | null {+ if (typeof v !== "string") return "not_string";+ if (v.length === 0) return "empty_text";+ if (v.length > max) return "too_long";+ return null;+}++/** Bytes of a value's JSON, or null when it does not serialise. */+function jsonBytes(v: unknown): number | null {+ try {+ const s = JSON.stringify(v);+ return s === undefined ? null : Buffer.byteLength(s);+ } catch {+ return null;+ }+}++/** True for a value that round-trips through JSON as itself (no functions, NaN, cycles…). */+function isJsonValue(v: unknown, depth = 0): v is JsonValue {+ if (depth > 64) return false;+ if (v === null || typeof v === "string" || typeof v === "boolean") return true;+ if (typeof v === "number") return Number.isFinite(v);+ if (Array.isArray(v)) return v.every((x) => isJsonValue(x, depth + 1));+ if (isPlainObject(v)) {+ const proto = Object.getPrototypeOf(v);+ if (proto !== Object.prototype && proto !== null) return false;+ return Object.values(v).every((x) => isJsonValue(x, depth + 1));+ }+ return false;+}++function matchProblem(a: { find?: unknown; regex?: unknown; flags?: unknown }): string | null {+ if (a.regex !== undefined && typeof a.regex !== "boolean") return "regex_not_boolean";+ if (a.flags !== undefined && typeof a.flags !== "string") return "invalid_flags";+ const compiled = compileMatcher(a as ReplaceMessageText);+ return "invalid" in compiled ? compiled.invalid : null;+}++/**+ * Check one value a hook returned: is it a known action, allowed for this+ * event, well-formed and within its limits. `observe` restricts a `toolCall`+ * hook to `warn`.+ */+export function validateAction(+ event: ClosedEvent,+ value: unknown,+ opts: { observe?: boolean } = {}+): Validation {+ if (!isPlainObject(value) || typeof value.type !== "string") {+ return { ok: false, reason: "not_an_action" };+ }+ const type = value.type as ActionType;+ if (!ALLOWED_ACTIONS[event].has(type)) {+ return { ok: false, reason: `not_allowed:${String(value.type)}` };+ }+ if (opts.observe && !OBSERVE_ONLY.has(type)) return { ok: false, reason: "observe_only" };++ const problem = shapeProblem(value);+ return problem ? { ok: false, reason: problem } : { ok: true, action: value as HookAction };+}++function shapeProblem(a: Record<string, unknown>): string | null {+ switch (a.type as ActionType) {+ case "injectSystemNote":+ return textIn(a.text, LIMITS.systemNote);+ case "appendUserText":+ return textIn(a.text, LIMITS.userText);+ case "replaceMessageText":+ case "removeMessageText": {+ if (a.type === "replaceMessageText" && typeof a.replace !== "string") {+ return "replace_not_string";+ }+ if (a.roles !== undefined) {+ if (!Array.isArray(a.roles) || a.roles.length === 0) return "invalid_roles";+ if (!a.roles.every((r) => typeof r === "string" && ROLES.has(r))) return "invalid_roles";+ }+ return matchProblem(a);+ }+ case "rewriteToolDescription":+ return toolName(a.tool) ?? textIn(a.append, LIMITS.toolDescriptionAppend);+ case "replaceToolDescription":+ return toolName(a.tool) ?? textIn(a.description, LIMITS.toolDescription);+ case "replaceToolSchema": {+ const bad = toolName(a.tool);+ if (bad) return bad;+ if (!isPlainObject(a.inputSchema) || a.inputSchema.type !== "object") {+ return "schema_not_object";+ }+ if (!isJsonValue(a.inputSchema)) return "schema_not_json";+ const bytes = jsonBytes(a.inputSchema);+ if (bytes === null) return "schema_not_json";+ return bytes > LIMITS.toolSchemaBytes ? "schema_too_large" : null;+ }+ case "removeTool":+ return toolName(a.tool);+ case "repairToolArgs": {+ if (!isPlainObject(a.args)) return "args_not_object";+ if (!isJsonValue(a.args)) return "args_not_json";+ const bytes = jsonBytes(a.args);+ if (bytes === null) return "args_not_json";+ if (bytes > LIMITS.repairArgsBytes) return "args_too_large";+ return typeof a.reason === "string" ? null : "reason_not_string";+ }+ case "appendText":+ case "prependText":+ return textIn(a.text, LIMITS.responseText);+ case "replaceText":+ case "removeText": {+ if (a.type === "replaceText" && typeof a.replace !== "string") return "replace_not_string";+ if ("roles" in a) return "roles_not_allowed";+ return matchProblem(a);+ }+ case "injectUserTurn": {+ const bad = textIn(a.text, LIMITS.injectUserTurn);+ if (bad) return bad;+ return (a.text as string).trimStart().startsWith("/") ? "slash_command" : null;+ }+ case "annotateTurn": {+ if (typeof a.key !== "string" || !ANNOTATION_KEY.test(a.key)) return "invalid_key";+ if (!("value" in a) || !isJsonValue(a.value)) return "value_not_json";+ const bytes = jsonBytes(a.value);+ if (bytes === null) return "value_not_json";+ return bytes > LIMITS.annotationValueBytes ? "value_too_large" : null;+ }+ case "warn":+ return typeof a.message === "string" ? null : "message_not_string";+ default:+ return `unknown_action:${String(a.type)}`;+ }+}++function toolName(v: unknown): string | null {+ return typeof v === "string" && v.length > 0 ? null : "invalid_tool";+}++/* ───────────── appliers ───────────── */++/** One action to apply, attributed to the hook that returned it. */+export interface PlannedAction<A extends HookAction = HookAction> {+ hookId: string;+ action: A;+}++/** What happened to one planned action. */+export interface ActionResult<A extends HookAction = HookAction> {+ hookId: string;+ action: A;+ decision: "matched" | "superseded" | "invalid" | "ignored";+ detail?: string;+}++/** The mutable slice of a Claude-format request the appliers touch. */+export interface MutableClaudeRequest {+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format request fields are untyped at this layer+ system?: any;+ // biome-ignore lint/suspicious/noExplicitAny: see above+ messages?: any[];+ // biome-ignore lint/suspicious/noExplicitAny: see above+ tools?: any[];+}++const STAGE_B: ReadonlySet<string> = new Set(["rewriteToolDescription", "replaceToolDescription"]);++/** The outcome of stage A, and what stage B still has to do. */+export interface StageAResult {+ results: ActionResult<RequestAction>[];+ /** Tool-description actions, held for stage B in effective order. */+ held: PlannedAction<RequestAction>[];+ /** Tools stage A removed; description actions on them are `superseded`. */+ removedTools: ReadonlySet<string>;+}++/**+ * Stage A, before conversion: system notes, then message text, then tool+ * schemas, then tool removal. `items` are in effective order and already+ * severity-gated (fix only) and validated; `warn` actions are skipped.+ *+ * Conflict rules: identical system notes and identical appended user texts are+ * applied once (later copies `superseded`); message text actions apply+ * sequentially; one schema per tool (first wins); one removal per tool (first+ * wins); every other action on a removed tool is `superseded`.+ */+export function applyStageA(+ req: MutableClaudeRequest,+ items: ReadonlyArray<PlannedAction<RequestAction>>+): StageAResult {+ const results: ActionResult<RequestAction>[] = [];+ const held: PlannedAction<RequestAction>[] = [];+ const result = (+ item: PlannedAction<RequestAction>,+ decision: ActionResult["decision"],+ detail?: string+ ) => results.push(detail === undefined ? { ...item, decision } : { ...item, decision, detail });++ const notes: PlannedAction<RequestAction>[] = [];+ const messageEdits: PlannedAction<RequestAction>[] = [];+ const schemas: PlannedAction<RequestAction>[] = [];+ const removals: PlannedAction<RequestAction>[] = [];+ for (const item of items) {+ const t = item.action.type;+ if (t === "warn") continue;+ if (t === "injectSystemNote") notes.push(item);+ else if (t === "appendUserText" || t === "replaceMessageText" || t === "removeMessageText") {+ messageEdits.push(item);+ } else if (t === "replaceToolSchema") schemas.push(item);+ else if (t === "removeTool") removals.push(item);+ else if (STAGE_B.has(t)) held.push(item);+ }++ // 1. System notes.+ const seenNotes = new Set<string>();+ for (const item of notes) {+ const text = (item.action as { text: string }).text;+ if (seenNotes.has(text)) {+ result(item, "superseded", "duplicate");+ continue;+ }+ seenNotes.add(text);+ req.system = withSystemNote(req.system, text);+ result(item, "matched");+ }++ // 2. Message text, sequentially in effective order.+ const seenAppends = new Set<string>();+ for (const item of messageEdits) {+ const a = item.action;+ if (a.type === "appendUserText") {+ if (seenAppends.has(a.text)) {+ result(item, "superseded", "duplicate");+ continue;+ }+ seenAppends.add(a.text);+ const r = appendUserText(req, a.text);+ if (r) result(item, "invalid", r);+ else result(item, "matched");+ continue;+ }+ const edit = editMessageText(req, a as ReplaceMessageText | RemoveMessageText);+ if (edit.invalid) result(item, "invalid", edit.invalid);+ else if (edit.reverted > 0 && !edit.changed) result(item, "invalid", "empty_message");+ else if (edit.reverted > 0) result(item, "matched", `empty_message_reverted:${edit.reverted}`);+ else if (!edit.changed) result(item, "ignored", "no_match");+ else result(item, "matched");+ }++ // 3. Decide removals first, so a schema action on a removed tool is superseded.+ const toolNames = new Set<string>((req.tools ?? []).map((t) => t?.name));+ const removed = new Set<string>();+ const removalOutcome = new Map<+ PlannedAction<RequestAction>,+ [ActionResult["decision"], string?]+ >();+ for (const item of removals) {+ const name = (item.action as { tool: string }).tool;+ if (removed.has(name)) removalOutcome.set(item, ["superseded", "already_removed"]);+ else if (!toolNames.has(name)) removalOutcome.set(item, ["invalid", "unknown_tool"]);+ else if (toolInHistory(req.messages, name)) {+ removalOutcome.set(item, ["invalid", "tool_in_history"]);+ } else {+ removed.add(name);+ removalOutcome.set(item, ["matched"]);+ }+ }++ // 4. Schemas: one per tool, first wins.+ const schemaDone = new Set<string>();+ for (const item of schemas) {+ const a = item.action as { tool: string; inputSchema: Record<string, unknown> };+ if (!toolNames.has(a.tool)) result(item, "invalid", "unknown_tool");+ else if (removed.has(a.tool)) result(item, "superseded", "tool_removed");+ else if (schemaDone.has(a.tool)) result(item, "superseded");+ else {+ schemaDone.add(a.tool);+ req.tools = (req.tools ?? []).map((t) =>+ t?.name === a.tool ? { ...t, input_schema: structuredClone(a.inputSchema) } : t+ );+ result(item, "matched");+ }+ }++ // 5. Removal.+ if (removed.size > 0) req.tools = (req.tools ?? []).filter((t) => !removed.has(t?.name));+ for (const item of removals) {+ const [decision, detail] = removalOutcome.get(item) ?? ["invalid"];+ result(item, decision, detail);+ }++ return { results, held, removedTools: removed };+}++/**+ * Stage B, after conversion: tool descriptions on BOTH representations, so+ * `--summarize-tools` (which truncates the converted description to its first+ * sentence) can never cut an appended instruction. One description action per+ * tool (first wins). A tool present in `claudeTools` but not in the converted+ * array (the tool-count cap removed it) gets the Claude-format change only and is+ * `matched` with detail `capped`.+ *+ * `convertedTools` is null on a route with one representation (native).+ */+export function applyStageB(+ // biome-ignore lint/suspicious/noExplicitAny: Claude-format and provider-format tools+ claudeTools: any[],+ // biome-ignore lint/suspicious/noExplicitAny: see above+ convertedTools: any[] | null,+ held: ReadonlyArray<PlannedAction<RequestAction>>,+ removedTools: ReadonlySet<string> = new Set()+): ActionResult<RequestAction>[] {+ const results: ActionResult<RequestAction>[] = [];+ const done = new Set<string>();+ const sameArray = convertedTools === claudeTools;++ for (const item of held) {+ const a = item.action;+ if (a.type !== "rewriteToolDescription" && a.type !== "replaceToolDescription") continue;+ if (removedTools.has(a.tool)) {+ results.push({ ...item, decision: "superseded", detail: "tool_removed" });+ continue;+ }+ if (done.has(a.tool)) {+ results.push({ ...item, decision: "superseded" });+ continue;+ }+ const describe = (current: unknown) =>+ a.type === "rewriteToolDescription"+ ? `${typeof current === "string" ? current : ""}${a.append}`+ : a.description;++ let claudeHits = 0;+ claudeTools.forEach((t, i) => {+ if (t?.name !== a.tool) return;+ claudeTools[i] = { ...t, description: describe(t.description) };+ claudeHits++;+ });+ if (claudeHits === 0) {+ results.push({ ...item, decision: "invalid", detail: "unknown_tool" });+ continue;+ }+ done.add(a.tool);++ let convertedHits = 0;+ if (convertedTools && !sameArray) {+ convertedTools.forEach((t, i) => {+ // Chat Completions wraps the definition in `function`; Responses does not.+ if (t?.function?.name === a.tool) {+ convertedTools[i] = {+ ...t,+ function: { ...t.function, description: describe(t.function.description) },+ };+ convertedHits++;+ } else if (!t?.function && t?.name === a.tool) {+ convertedTools[i] = { ...t, description: describe(t.description) };+ convertedHits++;+ }+ });+ }+ const capped = convertedTools !== null && !sameArray && convertedHits === 0;+ results.push(+ capped ? { ...item, decision: "matched", detail: "capped" } : { ...item, decision: "matched" }+ );+ }+ return results;+}++/** The outcome of the `repairToolArgs` actions for one call. */+export interface ToolCallApplied {+ /** The replacement arguments, or undefined when nothing was applied. */+ args?: Record<string, unknown>;+ results: ActionResult<ToolCallAction>[];+}++/** One call's arguments: the first `repairToolArgs` in effective order wins. */+export function applyToolCallActions(+ items: ReadonlyArray<PlannedAction<ToolCallAction>>+): ToolCallApplied {+ const results: ActionResult<ToolCallAction>[] = [];+ let args: Record<string, unknown> | undefined;+ for (const item of items) {+ if (item.action.type !== "repairToolArgs") continue;+ if (args !== undefined) {+ results.push({ ...item, decision: "superseded" });+ continue;+ }+ args = structuredClone(item.action.args);+ results.push({ ...item, decision: "matched" });+ }+ return args === undefined ? { results } : { args, results };+}++/* ───────────── request helpers ───────────── */++// biome-ignore lint/suspicious/noExplicitAny: Claude-format system is a string or a block array+function withSystemNote(system: any, text: string): any {+ if (typeof system === "string") return system.length > 0 ? `${system}\n\n${text}` : text;+ if (Array.isArray(system)) return [...system, { type: "text", text }];+ return text;+}++/** @returns an invalid reason, or null when applied. */+function appendUserText(req: MutableClaudeRequest, text: string): string | null {+ const messages = req.messages ?? [];+ let last = -1;+ for (let i = messages.length - 1; i >= 0; i--) {+ if (messages[i]?.role === "user") {+ last = i;+ break;+ }+ }+ if (last === -1) return "no_user_message";+ const msg = messages[last];+ const content: ClaudeContentBlock[] =+ typeof msg.content === "string"+ ? [{ type: "text", text: msg.content }]+ : Array.isArray(msg.content)+ ? [...msg.content]+ : [];+ content.push({ type: "text", text });+ req.messages = messages.map((m, i) => (i === last ? { ...m, content } : m));+ return null;+}++/** Apply a replace/remove to every text block of the messages whose role is in `roles`. */+function editMessageText(+ req: MutableClaudeRequest,+ a: ReplaceMessageText | RemoveMessageText+): { changed: boolean; reverted: number; invalid?: string } {+ const matcher = compileMatcher(a);+ if ("invalid" in matcher) return { changed: false, reverted: 0, invalid: matcher.invalid };+ const roles = new Set<string>(a.roles ?? ["user"]);+ let changed = false;+ let reverted = 0;++ const messages = (req.messages ?? []).map((m) => {+ if (!m || !roles.has(m.role)) return m;+ if (typeof m.content === "string") {+ const next = matcher.apply(m.content);+ if (next === m.content) return m;+ if (next === "") {+ reverted++;+ return m;+ }+ changed = true;+ return { ...m, content: next };+ }+ if (!Array.isArray(m.content)) return m;+ let touched = false;+ const content: ClaudeContentBlock[] = [];+ for (const block of m.content as ClaudeContentBlock[]) {+ if (block?.type !== "text" || typeof (block as { text?: unknown }).text !== "string") {+ content.push(block);+ continue;+ }+ const text = (block as { text: string }).text;+ const next = matcher.apply(text);+ if (next === text) {+ content.push(block);+ continue;+ }+ touched = true;+ if (next !== "") content.push({ ...block, text: next } as ClaudeContentBlock);+ }+ if (!touched) return m;+ if (content.length === 0) {+ reverted++;+ return m;+ }+ changed = true;+ return { ...m, content };+ });++ if (changed) req.messages = messages;+ return { changed, reverted };+}++/** True while any message holds a `tool_use` block of `name`. */+// biome-ignore lint/suspicious/noExplicitAny: Claude-format messages+function toolInHistory(messages: any[] | undefined, name: string): boolean {+ for (const m of messages ?? []) {+ if (!Array.isArray(m?.content)) continue;+ for (const b of m.content) if (b?.type === "tool_use" && b?.name === name) return true;+ }+ return false;+}diff --git a/packages/cli/src/hooks/config.test.ts b/packages/cli/src/hooks/config.test.tsnew file mode 100644index 00000000..32cc2dfd--- /dev/null+++ b/packages/cli/src/hooks/config.test.ts@@ -0,0 +1,311 @@+import { afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { setConfigFileOverride } from "../config-override.js";+import { loadConfig, saveConfig } from "../profile-config.js";+import {+ hooksConfigDir,+ maxConsecutiveInjections,+ parseHooksConfig,+ reportBehaviorBlock,+ reportProjectHooks,+ resetConfigReportersForTests,+ resolveSeverity,+} from "./config.js";++function capture() {+ const lines: string[] = [];+ return { lines, warn: (line: string) => lines.push(line) };+}++afterEach(() => resetConfigReportersForTests());++describe("parseHooksConfig", () => {+ it("accepts the documented shape", () => {+ const sink = capture();+ const parsed = parseHooksConfig(+ {+ modules: ["~/.claudish/hooks/ping.ts", "hooks/add-marker.ts"],+ severity: { "plan-mode/*": "warn", "gpt-5.6-*:plan-mode/plan-file-path": "fix" },+ injection: { maxConsecutive: 5 },+ observer: { enabled: false, mode: "off", timeoutMs: 1500, watchTools: ["Write"] },+ telemetry: { enabled: false },+ },+ sink.warn+ );+ expect(sink.lines).toEqual([]);+ expect(parsed.modules).toEqual(["~/.claudish/hooks/ping.ts", "hooks/add-marker.ts"]);+ expect(maxConsecutiveInjections(parsed)).toBe(5);+ });++ it("treats a missing block as empty with the default injection cap", () => {+ expect(parseHooksConfig(undefined)).toEqual({});+ expect(maxConsecutiveInjections({})).toBe(3);+ });++ it("warns once per issue, prefixed, and degrades an invalid block to {}", () => {+ const sink = capture();+ const parsed = parseHooksConfig(+ {+ modules: "not-an-array",+ severity: { "plan-mode/*": "rewrite-everything" },+ injection: { maxConsecutive: 21 },+ },+ sink.warn+ );+ expect(parsed).toEqual({});+ expect(sink.lines.length).toBe(3);+ for (const line of sink.lines) expect(line.startsWith("hooks config: ")).toBe(true);+ expect(sink.lines.some((l) => l.includes("injection.maxConsecutive"))).toBe(true);+ });++ it("rejects observer mode enforce", () => {+ const sink = capture();+ expect(parseHooksConfig({ observer: { mode: "enforce" } }, sink.warn)).toEqual({});+ expect(sink.lines.length).toBe(1);+ });++ it("bounds maxConsecutive to 1..20", () => {+ const sink = capture();+ expect(parseHooksConfig({ injection: { maxConsecutive: 0 } }, sink.warn)).toEqual({});+ expect(parseHooksConfig({ injection: { maxConsecutive: 1 } }, sink.warn)).toEqual({+ injection: { maxConsecutive: 1 },+ });+ expect(parseHooksConfig({ injection: { maxConsecutive: 20 } }, sink.warn)).toEqual({+ injection: { maxConsecutive: 20 },+ });+ });+});++describe("reportBehaviorBlock", () => {+ it("prints what to change for each key present, once per process", () => {+ const sink = capture();+ expect(+ reportBehaviorBlock(+ { rules: { "plan-mode/*": "off" }, hooks: ["a.ts"], telemetry: { enabled: true } },+ sink.warn+ )+ ).toBe(true);+ const text = sink.lines.join("\n");+ expect(text).toContain("behavior.rules → hooks.severity");+ expect(text).toContain("behavior.hooks → hooks.modules");+ expect(text).toContain("apiVersion: 1");+ expect(text).toContain("consent is NOT carried over");+ expect(text).not.toContain("behavior.preset");++ expect(reportBehaviorBlock({ rules: {} }, sink.warn)).toBe(false);+ });++ it("prints nothing when there is no behavior block", () => {+ const sink = capture();+ expect(reportBehaviorBlock(undefined, sink.warn)).toBe(false);+ expect(sink.lines).toEqual([]);+ });+});++describe("reportProjectHooks", () => {+ it("reports a hooks key in the project file and ignores it", () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-config-"));+ try {+ const path = join(dir, ".claudish.json");+ writeFileSync(path, JSON.stringify({ hooks: { modules: ["evil.ts"] } }));+ const sink = capture();+ expect(reportProjectHooks(path, sink.warn)).toBe(true);+ expect(sink.lines).toEqual([+ `hooks in ${path} ignored: hooks are read from the global config only`,+ ]);+ expect(reportProjectHooks(path, sink.warn)).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("is silent for a project file without hooks, or none at all", () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-config-"));+ try {+ const path = join(dir, ".claudish.json");+ const sink = capture();+ expect(reportProjectHooks(path, sink.warn)).toBe(false);+ writeFileSync(path, JSON.stringify({ defaultProvider: "x" }));+ expect(reportProjectHooks(path, sink.warn)).toBe(false);+ expect(sink.lines).toEqual([]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe("resolveSeverity", () => {+ it("prefers an exact rule id over a matching glob", () => {+ expect(+ resolveSeverity("plan-mode/plan-file-path", "warn", {+ "plan-mode/*": "off",+ "plan-mode/plan-file-path": "fix",+ })+ ).toBe("fix");+ });++ it("uses the longest matching glob", () => {+ expect(+ resolveSeverity("plan-mode/plan-file-path", "warn", {+ "*": "off",+ "plan-*": "warn",+ "plan-mode/plan-*": "fix",+ })+ ).toBe("fix");+ });++ it("allows a specific rule to be re-enabled inside a disabled namespace", () => {+ const config = {+ "plan-mode/*": "off" as const,+ "plan-mode/plan-file-path": "fix" as const,+ };++ expect(resolveSeverity("plan-mode/other-rule", "warn", config)).toBe("off");+ expect(resolveSeverity("plan-mode/plan-file-path", "warn", config)).toBe("fix");+ });++ it("falls back to the rule's default severity when unconfigured", () => {+ expect(resolveSeverity("plan-mode/plan-file-path", "fix", undefined)).toBe("fix");+ expect(+ resolveSeverity("plan-mode/plan-file-path", "warn", { "other-namespace/*": "off" })+ ).toBe("warn");+ });++ it("uses an unscoped key when no model-scoped key matches", () => {+ expect(+ resolveSeverity(+ "plan-mode/plan-file-path",+ "warn",+ {+ "plan-mode/plan-file-path": "fix",+ "other-model:plan-mode/plan-file-path": "off",+ },+ "gpt-5.6-sol"+ )+ ).toBe("fix");+ });++ it("lets a matching model-scoped key beat an unscoped key", () => {+ expect(+ resolveSeverity(+ "plan-mode/plan-file-path",+ "warn",+ {+ "plan-mode/plan-file-path": "off",+ "gpt-5.6-sol:plan-mode/plan-file-path": "fix",+ },+ "gpt-5.6-sol"+ )+ ).toBe("fix");+ });++ it("does not apply a model-scoped key to a different model", () => {+ expect(+ resolveSeverity(+ "plan-mode/plan-file-path",+ "warn",+ {+ "plan-mode/plan-file-path": "warn",+ "gpt-5.6-sol:plan-mode/plan-file-path": "fix",+ },+ "gpt-5.6-codex"+ )+ ).toBe("warn");+ });++ it("matches model globs", () => {+ expect(+ resolveSeverity(+ "plan-mode/plan-file-path",+ "warn",+ { "gpt-5.6-*:plan-mode/plan-file-path": "fix" },+ "gpt-5.6-sol"+ )+ ).toBe("fix");+ });++ it("prefers an exact rule id over a rule glob in both scope tiers", () => {+ const unscoped = {+ "plan-mode/*": "off" as const,+ "plan-mode/plan-file-path": "fix" as const,+ };+ const scoped = {+ "gpt-5.6-*:plan-mode/*": "off" as const,+ "gpt-5.6-*:plan-mode/plan-file-path": "fix" as const,+ };++ expect(resolveSeverity("plan-mode/plan-file-path", "warn", unscoped, "gpt-5.6-sol")).toBe(+ "fix"+ );+ expect(resolveSeverity("plan-mode/plan-file-path", "warn", scoped, "gpt-5.6-sol")).toBe("fix");+ });++ it("prefers the longer rule glob in both scope tiers", () => {+ const unscoped = {+ "plan-*": "off" as const,+ "plan-mode/plan-*": "fix" as const,+ };+ const scoped = {+ "gpt-5.6-*:plan-*": "off" as const,+ "gpt-5.6-*:plan-mode/plan-*": "fix" as const,+ };++ expect(resolveSeverity("plan-mode/plan-file-path", "warn", unscoped, "gpt-5.6-sol")).toBe(+ "fix"+ );+ expect(resolveSeverity("plan-mode/plan-file-path", "warn", scoped, "gpt-5.6-sol")).toBe("fix");+ });++ it("does not mis-parse a hook rule id as a model scope", () => {+ expect(+ resolveSeverity(+ "hook:my-file/my-rule",+ "warn",+ { "hook:my-file/my-rule": "fix" },+ "gpt-5.6-sol"+ )+ ).toBe("fix");+ });++ it("uses unscoped-only behavior when modelId is omitted", () => {+ expect(+ resolveSeverity("plan-mode/plan-file-path", "off", {+ "plan-mode/plan-file-path": "warn",+ "gpt-5.6-sol:plan-mode/plan-file-path": "fix",+ })+ ).toBe("warn");+ });+});++describe("the hooks key survives loadConfig's allowlist", () => {+ it("round-trips through saveConfig(loadConfig()) and resolves modules against the file's dir", () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-config-"));+ const file = join(dir, "config.json");+ const hooks = { modules: ["hooks/a.ts"], severity: { "hook:a/*": "warn" } };+ writeFileSync(+ file,+ JSON.stringify({+ version: "1.0.0",+ defaultProfile: "",+ profiles: {},+ hooks,+ behavior: { rules: {} },+ })+ );+ setConfigFileOverride(file);+ try {+ expect(loadConfig().hooks).toEqual(hooks);+ expect(hooksConfigDir()).toBe(dir);+ saveConfig(loadConfig());+ const saved = JSON.parse(readFileSync(file, "utf8"));+ expect(saved.hooks).toEqual(hooks);+ // The old block is kept on disk until the user moves it.+ expect(saved.behavior).toEqual({ rules: {} });+ } finally {+ setConfigFileOverride(null);+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/cli/src/hooks/config.ts b/packages/cli/src/hooks/config.tsnew file mode 100644index 00000000..a13e1868--- /dev/null+++ b/packages/cli/src/hooks/config.ts@@ -0,0 +1,259 @@+/**+ * Hook-system configuration: the `hooks` key's schema, severity resolution, and+ * the two reporters for config that is no longer read.+ *+ * Validation lives here rather than in profile-config.ts on purpose — that+ * module is deliberately Zod-free because `loadConfig` runs on many lightweight+ * startup paths. Same rule as custom endpoints: validate at the point of+ * consumption, warn and fall back rather than throwing, so a malformed `hooks`+ * block can never stop claudish from starting.+ *+ * `hooks` is read from the GLOBAL config only (`~/.claudish/config.json`, or the+ * `--config` / `CLAUDISH_CONFIG` override, which replaces both scopes). A+ * project `.claudish.json` is repo-controlled, and executing code it names would+ * need a trust model claudish does not have.+ */++import { existsSync, readFileSync } from "node:fs";+import { dirname } from "node:path";+import { z } from "zod";+import { getConfigFileOverride } from "../config-override.js";+import { logStderr } from "../logger.js";+import { activeConfigFile, getLocalConfigPath } from "../profile-config.js";+import type { Severity } from "./public.js";++const SeveritySchema = z.enum(["off", "warn", "fix"]);++/** Default and bounds of the host cap on consecutive hook-caused turns. */+export const INJECTION_MAX_CONSECUTIVE_DEFAULT = 3;++export const HooksConfigSchema = z.object({+ /** Loaded in order. Absolute, "~/…", or relative to the CONFIG FILE's directory. */+ modules: z.array(z.string().min(1)).optional(),+ /** "[modelGlob:]hookIdGlob" → severity. */+ severity: z.record(z.string(), SeveritySchema).optional(),+ injection: z+ .object({+ maxConsecutive: z.number().int().min(1).max(20).optional(),+ })+ .optional(),+ observer: z+ .object({+ enabled: z.boolean().optional(),+ // "enforce" is deliberately NOT accepted. The observer is advisory and+ // fire-and-forget; a user who asks for enforcement must be told it does+ // not exist, not left believing their calls are being gated.+ mode: z.enum(["off", "suggest"]).optional(),+ model: z.string().optional(),+ timeoutMs: z.number().int().positive().optional(),+ watchTools: z.array(z.string()).optional(),+ })+ .optional(),+ /** Behaviour-telemetry upload consent. Default off. Local journaling is always on. */+ telemetry: z.object({ enabled: z.boolean().optional() }).optional(),+});++export type HooksConfig = z.infer<typeof HooksConfigSchema>;++/** Where warnings go. A parameter so tests can capture them without touching stderr. */+export type WarnSink = (line: string) => void;++/** `logStderr` prefixes `[claudish] ` itself. */+const defaultWarn: WarnSink = (line) => logStderr(line);++/**+ * Parse a raw `hooks` value. Invalid input warns once per Zod issue and degrades+ * to `{}`: built-in hooks run at their default severity and no user module+ * loads. claudish always starts.+ */+export function parseHooksConfig(raw: unknown, warn: WarnSink = defaultWarn): HooksConfig {+ if (raw === undefined || raw === null) return {};+ const result = HooksConfigSchema.safeParse(raw);+ if (!result.success) {+ for (const issue of result.error.issues) {+ const where = issue.path.length > 0 ? `${issue.path.join(".")}: ` : "";+ warn(`hooks config: ${where}${issue.message}`);+ }+ return {};+ }+ return result.data;+}++/** The host cap on consecutive hook-caused turns for this config. */+export function maxConsecutiveInjections(config: HooksConfig): number {+ return config.injection?.maxConsecutive ?? INJECTION_MAX_CONSECUTIVE_DEFAULT;+}++/**+ * The directory relative module paths resolve against: the ACTIVE config file's+ * directory, never `process.cwd()` — in a pane child the cwd is the MCP+ * server's.+ */+export function hooksConfigDir(): string {+ return dirname(activeConfigFile());+}++/* ───────────── severity ───────────── */++/**+ * Resolve the effective severity for a hook id.+ *+ * Ported verbatim from the behavior layer (`behavior/config.ts`), with the map+ * now read from `hooks.severity`. Precedence: model-scoped keys beat unscoped+ * ones; within a tier an exact id beats a glob and a longer glob beats a+ * shorter one; otherwise the hook's own default.+ *+ * { "plan-mode/*": "off", "plan-mode/plan-file-path": "fix" }+ */+export function resolveSeverity(+ hookId: string,+ defaultSeverity: Severity,+ severityMap: Record<string, Severity> | undefined,+ modelId?: string+): Severity {+ const rules = severityMap;+ if (!rules) return defaultSeverity;++ // Model-scoped keys beat unscoped ones. Nothing transfers between models — a+ // rule proven on one is a hypothesis on the next — so a user must be able to+ // arm a rule for the model that needs it without arming it for every model:+ //+ // { "plan-mode/*": "warn", "gpt-5.6-*:plan-mode/plan-file-path": "fix" }+ //+ // Pass 1 considers only `model:rule` keys, pass 2 only unscoped keys.+ if (modelId) {+ const scoped = bestMatch(rules, hookId, modelId);+ if (scoped) return scoped;+ }+ return bestMatch(rules, hookId, undefined) ?? defaultSeverity;+}++/**+ * Best matching severity within one scope tier.+ *+ * Specificity wins: an exact match beats a glob, and a longer glob beats a+ * shorter one, so `{"plan-mode/*":"off","plan-mode/plan-file-path":"fix"}`+ * re-enables the single rule.+ */+function bestMatch(+ rules: Record<string, Severity>,+ ruleId: string,+ modelId: string | undefined+): Severity | null {+ let best: { score: number; severity: Severity } | null = null;++ for (const [key, severity] of Object.entries(rules)) {+ const { model: keyModel, rule: keyRule } = parseRuleKey(key);+ if (!scopeMatches(keyModel, modelId)) continue;+ if (!globMatches(keyRule, ruleId)) continue;+ const score = specificity(keyRule);+ if (!best || score > best.score) best = { score, severity };+ }++ return best ? best.severity : null;+}++/**+ * Split a config key into its optional model scope and its rule pattern.+ *+ * A `:` only introduces a model scope when it precedes the rule namespace. Rule+ * ids themselves never contain one, but HOOK ids look like `hook:file/rule` —+ * an unanchored split would silently mis-read every hook rule as model-scoped.+ */+function parseRuleKey(key: string): { model?: string; rule: string } {+ const sep = key.indexOf(":");+ if (sep <= 0 || key.startsWith("hook:")) return { rule: key };+ return { model: key.slice(0, sep), rule: key.slice(sep + 1) };+}++/** Scoped keys match only in the scoped pass, unscoped keys only in the unscoped pass. */+function scopeMatches(keyModel: string | undefined, modelId: string | undefined): boolean {+ if (modelId === undefined) return keyModel === undefined;+ return keyModel !== undefined && globMatches(keyModel, modelId);+}++/** Exact beats glob; among globs, more literal characters wins. */+function specificity(pattern: string): number {+ return pattern.includes("*") ? pattern.replace(/\*/g, "").length : Number.MAX_SAFE_INTEGER;+}++/** `*` matches any run of characters, including `/`. Anchored at both ends. */+export function globMatches(pattern: string, value: string): boolean {+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");+ return new RegExp(`^${escaped}$`).test(value);+}++/* ───────────── reporters ───────────── */++/** Pre-hook-system `behavior` keys and what replaced each. */+const BEHAVIOR_MOVES: ReadonlyArray<readonly [string, string]> = [+ ["rules", "behavior.rules → hooks.severity"],+ [+ "hooks",+ "behavior.hooks → hooks.modules (modules must be rewritten to the claudish/hooks contract, apiVersion: 1)",+ ],+ ["observer", "behavior.observer → hooks.observer"],+ [+ "telemetry",+ "behavior.telemetry → hooks.telemetry (consent is NOT carried over: set hooks.telemetry.enabled yourself)",+ ],+ ["preset", "behavior.preset → removed"],+];++let behaviorReported = false;++/**+ * Report a `behavior` block in the global config, once per process.+ *+ * Reported, never migrated: old modules cannot be ported mechanically, so an+ * automatic rewrite would point `hooks.modules` at files that fail the shape+ * check, and copying telemetry consent silently would launder it.+ *+ * @returns true when it printed.+ */+export function reportBehaviorBlock(behavior: unknown, warn: WarnSink = defaultWarn): boolean {+ if (behaviorReported || behavior === undefined || behavior === null) return false;+ behaviorReported = true;+ const keys =+ typeof behavior === "object" && !Array.isArray(behavior)+ ? Object.keys(behavior as Record<string, unknown>)+ : [];+ warn('the "behavior" config block is no longer read. Move it to "hooks":');+ const relevant = BEHAVIOR_MOVES.filter(([key]) => keys.includes(key));+ for (const [, line] of relevant.length > 0 ? relevant : BEHAVIOR_MOVES) warn(` ${line}`);+ return true;+}++let projectHooksReported = false;++/**+ * Report a `hooks` key in the project `.claudish.json`, once per process.+ *+ * With a `--config` / `CLAUDISH_CONFIG` override the project scope is suppressed+ * entirely, so there is nothing to report.+ *+ * @returns true when it printed.+ */+export function reportProjectHooks(+ projectConfigPath: string = getLocalConfigPath(),+ warn: WarnSink = defaultWarn+): boolean {+ if (projectHooksReported || getConfigFileOverride()) return false;+ try {+ if (!existsSync(projectConfigPath)) return false;+ const parsed = JSON.parse(readFileSync(projectConfigPath, "utf-8")) as unknown;+ if (!parsed || typeof parsed !== "object" || !("hooks" in parsed)) return false;+ } catch {+ // An unreadable or garbled project file is someone else's error to report.+ return false;+ }+ projectHooksReported = true;+ warn(`hooks in ${projectConfigPath} ignored: hooks are read from the global config only`);+ return true;+}++/** Test seam: let both reporters print again. */+export function resetConfigReportersForTests(): void {+ behaviorReported = false;+ projectHooksReported = false;+}diff --git a/packages/cli/src/hooks/engine.test.ts b/packages/cli/src/hooks/engine.test.tsnew file mode 100644index 00000000..8f0ee384--- /dev/null+++ b/packages/cli/src/hooks/engine.test.ts@@ -0,0 +1,504 @@+import { afterEach, describe, expect, it, spyOn } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import * as logger from "../logger.js";+import { applyStageA, applyToolCallActions } from "./actions.js";+import {+ BREAKER_THRESHOLD,+ type BaseContextParts,+ HookEngine,+ MAX_PENDING_SESSIONS,+} from "./engine.js";+import type { JournalEntry } from "./journal.js";+import { type HookDefinition, act } from "./public.js";+import { type ApplicableHook, HookRegistry, type UserHookInput } from "./registry.js";+import {+ type SessionReport,+ resetTelemetryState,+ setTelemetryConsent,+ spoolPendingSync,+} from "./telemetry/aggregate.js";++const META = { model: "glm-5", provider: "zai", sessionId: "s-1" };+const ROUTE = { modelId: "glm-5", provider: "zai", native: false };++function userHook(id: string, def: Omit<HookDefinition, "apiVersion" | "id">, index = 0) {+ return {+ id: `hook:m/${id}`,+ module: "/hooks/m.ts",+ moduleIndex: 0,+ exportIndex: index,+ def: { apiVersion: 1, id, ...def } as HookDefinition,+ } satisfies UserHookInput;+}++function engineWith(+ users: UserHookInput[],+ builtins: HookDefinition[] = [],+ severity?: Record<string, "off" | "warn" | "fix">+) {+ const journal: JournalEntry[] = [];+ const warnings: string[] = [];+ const engine = new HookEngine({+ registry: new HookRegistry(builtins, users, severity),+ config: severity ? { severity } : {},+ hostMode: "other",+ journalSink: (e) => journal.push(e),+ warn: (l) => warnings.push(l),+ drainTelemetryOutbox: false,+ });+ return { engine, journal, warnings };+}++/** A minimal RequestContext builder. */+const requestCtx = (_a: ApplicableHook, base: BaseContextParts) => ({+ ...base,+ event: "request",+ host: { mode: "other" },+ route: ROUTE,+ request: { model: "glm-5", stream: true, systemText: "", messages: [], tools: [] },+ harness: { planModeActive: false },+ session: null,+});++afterEach(() => resetTelemetryState());++describe("HookEngine.run", () => {+ it("runs hooks concurrently and returns actions in effective order", async () => {+ const started: string[] = [];+ const slow = userHook(+ "slow",+ {+ on: {+ request: async () => {+ started.push("slow");+ await Bun.sleep(40);+ return [act.injectSystemNote("SLOW")];+ },+ },+ },+ 0+ );+ const fast = userHook(+ "fast",+ {+ on: {+ request: () => {+ started.push("fast");+ return [act.injectSystemNote("FAST")];+ },+ },+ },+ 1+ );+ const { engine } = engineWith([slow, fast]);+ const t0 = performance.now();+ const result = await engine.run(+ "request",+ engine.select("request", { route: ROUTE }),+ requestCtx,+ META+ );+ // Both started before either finished, and the slow one did not serialise the fast one.+ expect(started).toEqual(["slow", "fast"]);+ expect(performance.now() - t0).toBeLessThan(400);+ expect(result.apply.map((p) => [p.hookId, p.action])).toEqual([+ ["hook:m/slow", act.injectSystemNote("SLOW")],+ ["hook:m/fast", act.injectSystemNote("FAST")],+ ]);+ const req = { system: "base" };+ applyStageA(req, result.apply);+ expect(req.system).toBe("base\n\nSLOW\n\nFAST");+ });++ it("times out a hook: its signal aborts, its result is discarded, others still apply", async () => {+ let seen: AbortSignal | undefined;+ let lateMutation = false;+ const hung = userHook("hung", {+ timeoutMs: 50,+ on: {+ request: async (ctx) => {+ seen = ctx.signal;+ await Bun.sleep(150);+ lateMutation = true;+ return [act.injectSystemNote("LATE")];+ },+ },+ });+ const ok = userHook("ok", { on: { request: () => [act.injectSystemNote("OK")] } }, 1);+ const { engine, journal } = engineWith([hung, ok]);+ const result = await engine.run(+ "request",+ engine.select("request", { route: ROUTE }),+ requestCtx,+ META+ );+ expect(seen?.aborted).toBe(true);+ expect(result.runs.map((r) => r.status)).toEqual(["timeout", "ok"]);+ expect(result.apply.map((p) => p.hookId)).toEqual(["hook:m/ok"]);+ expect(journal.find((e) => e.decision === "timeout")?.hookId).toBe("hook:m/hung");+ await Bun.sleep(150);+ expect(lateMutation).toBe(true);+ expect(result.apply.length).toBe(1);+ });++ it("clamps timeoutMs to the event maximum", async () => {+ const { timeoutFor } = await import("./engine.js");+ const d = { apiVersion: 1, id: "x", timeoutMs: 999_999 } as HookDefinition;+ expect(timeoutFor(d, "request")).toBe(5_000);+ expect(timeoutFor(d, "responseRewrite")).toBe(10_000);+ expect(timeoutFor(d, "sessionEnd")).toBe(1_500);+ expect(timeoutFor({ apiVersion: 1, id: "x" } as HookDefinition, "sessionIdle")).toBe(5_000);+ });++ it("fails open on a throw, a rejection and an invalid return value", async () => {+ const thrower = userHook("thrower", {+ on: {+ request: () => {+ throw new Error("boom");+ },+ },+ });+ const rejecter = userHook(+ "rejecter",+ { on: { request: async () => Promise.reject(new Error("no")) } },+ 1+ );+ const wrong = userHook("wrong", { on: { request: (() => "nope") as never } }, 2);+ const fine = userHook("fine", { on: { request: () => [act.injectSystemNote("F")] } }, 3);+ const { engine, journal } = engineWith([thrower, rejecter, wrong, fine]);+ const result = await engine.run(+ "request",+ engine.select("request", { route: ROUTE }),+ requestCtx,+ META+ );+ expect(result.runs.map((r) => r.status)).toEqual(["error", "error", "invalid", "ok"]);+ expect(result.apply.map((p) => p.hookId)).toEqual(["hook:m/fine"]);+ expect(journal.filter((e) => e.decision === "error").map((e) => e.detail)).toEqual([+ "boom",+ "no",+ ]);+ });++ it("journals and ignores an action not allowed for the event, keeping the valid ones", async () => {+ const mixed = userHook("mixed", {+ on: {+ request: () => [act.appendText("nope"), act.injectSystemNote("yes")] as never,+ },+ });+ const { engine, journal } = engineWith([mixed]);+ const result = await engine.run(+ "request",+ engine.select("request", { route: ROUTE }),+ requestCtx,+ META+ );+ expect(result.apply.map((p) => p.action.type)).toEqual(["injectSystemNote"]);+ expect(journal.find((e) => e.decision === "invalid")).toMatchObject({+ action: "appendText",+ detail: "not_allowed:appendText",+ schema: 2,+ event: "request",+ });+ });++ it("at warn severity journals warned and applies nothing; warn actions always journal", async () => {+ const h = userHook("w", {+ on: { request: () => [act.injectSystemNote("N"), act.warn("look out")] },+ });+ const { engine, journal } = engineWith([h], [], { "hook:m/w": "warn" });+ const result = await engine.run(+ "request",+ engine.select("request", { route: ROUTE }),+ requestCtx,+ META+ );+ expect(result.apply).toEqual([]);+ expect(journal.map((e) => [e.action, e.decision])).toEqual([+ ["injectSystemNote", "warned"],+ ["warn", "warned"],+ ]);+ });++ it("does not call an off hook", async () => {+ let called = false;+ const h = userHook("off", {+ on: {+ request: () => {+ called = true;+ return [];+ },+ },+ });+ const { engine } = engineWith([h], [], { "hook:*": "off" });+ expect(engine.select("request", { route: ROUTE })).toEqual([]);+ await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);+ expect(called).toBe(false);+ });++ it("hands the handler a frozen context with hookId, severity, log and signal", async () => {+ let captured: Record<string, unknown> | undefined;+ const h = userHook("ctx", {+ on: {+ request: (ctx) => {+ captured = ctx as unknown as Record<string, unknown>;+ return [];+ },+ },+ });+ const { engine } = engineWith([h]);+ await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);+ expect(Object.isFrozen(captured)).toBe(true);+ expect(captured?.hookId).toBe("hook:m/ctx");+ expect(captured?.severity).toBe("fix");+ expect(typeof captured?.log).toBe("function");+ expect(captured?.signal).toBeInstanceOf(AbortSignal);+ });++ it("restricts an observe-mode toolCall hook to warn", async () => {+ const obs = userHook("obs", {+ on: {+ toolCall: {+ tools: ["Write"],+ observe: true,+ handle: () => [act.repairToolArgs({ x: 1 }, "r"), act.warn("seen")],+ },+ },+ });+ const { engine, journal } = engineWith([obs]);+ const result = await engine.run(+ "toolCall",+ engine.select("toolCall", { route: ROUTE }),+ requestCtx,+ { ...META, toolName: "Write" }+ );+ expect(result.apply).toEqual([]);+ expect(journal.map((e) => e.decision)).toContain("invalid");+ expect(journal.find((e) => e.decision === "invalid")?.detail).toBe("observe_only");+ });++ it("an aborted parent signal ends unfinished hooks as aborted, unjournaled", async () => {+ const h = userHook("idle", {+ on: {+ sessionIdle: async (ctx) => {+ await new Promise((r) => ctx.signal.addEventListener("abort", r));+ return [act.injectUserTurn("late")];+ },+ },+ });+ const { engine, journal } = engineWith([h]);+ const parent = new AbortController();+ const running = engine.run(+ "sessionIdle",+ engine.select("sessionIdle", { sessionModel: "glm-5" }),+ (_a, base) => ({ ...base, event: "sessionIdle" }),+ META,+ { signal: parent.signal }+ );+ await Bun.sleep(10);+ parent.abort("caller");+ const result = await running;+ expect(result.runs[0]?.status).toBe("aborted");+ expect(result.apply).toEqual([]);+ expect(journal).toEqual([]);+ });+});++describe("circuit breaker", () => {+ it("disables a hook after 5 consecutive failures, with one stderr line", async () => {+ let calls = 0;+ const flaky = userHook("flaky", {+ on: {+ request: () => {+ calls++;+ throw new Error("always");+ },+ },+ });+ const { engine, journal, warnings } = engineWith([flaky]);+ for (let i = 0; i < BREAKER_THRESHOLD + 2; i++) {+ await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);+ }+ expect(calls).toBe(BREAKER_THRESHOLD);+ expect(engine.isDisabled("hook:m/flaky")).toBe(true);+ expect(journal.filter((e) => e.decision === "disabled").length).toBe(1);+ expect(warnings).toEqual([+ "hook hook:m/flaky disabled after 5 consecutive failures (see the debug log)",+ ]);+ });++ it("any success resets the count", async () => {+ let n = 0;+ const sometimes = userHook("sometimes", {+ on: {+ request: () => {+ n++;+ if (n % 4 === 0) return [];+ throw new Error("x");+ },+ },+ });+ const { engine } = engineWith([sometimes]);+ for (let i = 0; i < 12; i++) {+ await engine.run("request", engine.select("request", { route: ROUTE }), requestCtx, META);+ }+ expect(engine.isDisabled("hook:m/sometimes")).toBe(false);+ expect(n).toBe(12);+ });+});++describe("journal fan-out and the upload projection", () => {+ it("uploads a user hook as rule_id user and withholds an mcp__ tool name", async () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-engine-"));+ try {+ setTelemetryConsent(true);+ const repair = userHook("fix-args", {+ on: { toolCall: { tools: ["*"], handle: () => [act.repairToolArgs({ q: 1 }, "x")] } },+ });+ const builtin = {+ apiVersion: 1,+ id: "plan-mode/plan-file-path",+ on: { toolCall: { tools: ["Write"], handle: () => [act.repairToolArgs({ p: 1 }, "y")] } },+ } as HookDefinition;+ const { engine, journal } = engineWith([repair], [builtin]);+ // The engine constructor pushes consent from config (off here); turn it on after.+ setTelemetryConsent(true);++ for (const toolName of ["mcp__srv__x", "Write"]) {+ const meta = { ...META, toolName };+ const result = await engine.run(+ "toolCall",+ engine.select("toolCall", { route: ROUTE }),+ requestCtx,+ meta+ );+ for (const planned of result.apply) {+ engine.recordResults("toolCall", applyToolCallActions([planned]).results, meta);+ }+ }++ const outbox = join(dir, "outbox.jsonl");+ expect(spoolPendingSync(outbox)).toBe(1);+ const report = JSON.parse(readFileSync(outbox, "utf8").trim()) as SessionReport;+ const rows = report.decisions.map((d) => [d.rule_id, d.tool_name, d.counts.repaired]);+ expect(rows).toContainEqual(["user", undefined, 1]); // mcp__srv__x withheld+ expect(rows).toContainEqual(["user", "Write", 1]); // built-in tool names are not user data+ expect(rows).toContainEqual(["plan-mode/plan-file-path", "Write", 1]);+ // A built-in keeps an mcp__ tool name: only user rows are projected.+ expect(+ rows.some(([id, tool]) => id === "plan-mode/plan-file-path" && tool === "mcp__srv__x")+ ).toBe(true);+ expect(JSON.stringify(report)).not.toContain("hook:m/fix-args");++ // The local journal keeps the real id and tool.+ expect(journal).toContainEqual(+ expect.objectContaining({+ hookId: "hook:m/fix-args",+ ruleId: "hook:m/fix-args",+ toolName: "mcp__srv__x",+ decision: "repaired",+ surface: "tool_call",+ schema: 2,+ })+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("keeps local-only surfaces and decisions out of the upload", () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-engine-"));+ try {+ const { engine } = engineWith([]);+ setTelemetryConsent(true);+ engine.journal({ ...META, event: "responseRewrite", hookId: "x", decision: "matched" });+ engine.journal({ ...META, event: "request", hookId: "x", decision: "superseded" });+ engine.journal({ ...META, event: "sessionIdle", hookId: "x", decision: "delivered" });+ expect(spoolPendingSync(join(dir, "o.jsonl"))).toBe(0);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("clips detail to 200 characters and never throws on a failing sink", () => {+ const entries: JournalEntry[] = [];+ const { engine } = engineWith([]);+ const clipped = new HookEngine({+ registry: new HookRegistry([], [], undefined),+ config: {},+ hostMode: "other",+ journalSink: (e) => entries.push(e),+ drainTelemetryOutbox: false,+ });+ clipped.journal({+ ...META,+ event: "request",+ hookId: "x",+ decision: "error",+ detail: "d".repeat(500),+ });+ expect(entries[0]?.detail?.length).toBe(200);++ const logSpy = spyOn(logger, "log");+ const broken = new HookEngine({+ registry: new HookRegistry([], [], undefined),+ config: {},+ hostMode: "other",+ journalSink: () => {+ throw new Error("disk full");+ },+ drainTelemetryOutbox: false,+ });+ expect(() =>+ broken.journal({ ...META, event: "request", hookId: "x", decision: "error" })+ ).not.toThrow();+ logSpy.mockRestore();+ expect(engine).toBeDefined();+ });+});++describe("pending notes", () => {+ it("peeks without removing, and consumes only what a committed request carried", () => {+ const { engine } = engineWith([]);+ engine.queueNote("s", "hook:m/a", "one");+ const first = engine.peekNotes("s");+ // A concurrent request that started before any commit sees the same note.+ expect(engine.peekNotes("s").map((n) => n.text)).toEqual(["one"]);+ engine.queueNote("s", "hook:m/a", "two");+ engine.consumeNotes(+ "s",+ first.map((n) => n.seq)+ );+ expect(engine.peekNotes("s").map((n) => n.text)).toEqual(["two"]);+ expect(engine.peekNotes(undefined)).toEqual([]);+ });++ it("tracks at most 64 sessions, evicting the oldest", () => {+ const { engine } = engineWith([]);+ for (let i = 0; i <= MAX_PENDING_SESSIONS; i++) engine.queueNote(`s${i}`, "h", "n");+ expect(engine.peekNotes("s0")).toEqual([]);+ expect(engine.peekNotes(`s${MAX_PENDING_SESSIONS}`).length).toBe(1);+ });+});++describe("callPredicate", () => {+ it("treats a throw or a non-true value as false and defaults an absent predicate", () => {+ const { engine } = engineWith([]);+ expect(engine.callPredicate("h", undefined, null, {})).toBe(true);+ expect(engine.callPredicate("h", undefined, null, {}, false)).toBe(false);+ expect(+ engine.callPredicate(+ "h",+ () => {+ throw new Error("x");+ },+ null,+ {}+ )+ ).toBe(false);+ expect(engine.callPredicate("h", (() => 1) as never, null, {})).toBe(false);+ expect(engine.callPredicate("h", (() => true) as never, null, {})).toBe(true);+ });+});diff --git a/packages/cli/src/hooks/engine.ts b/packages/cli/src/hooks/engine.tsnew file mode 100644index 00000000..4cb9bfa4--- /dev/null+++ b/packages/cli/src/hooks/engine.ts@@ -0,0 +1,657 @@+/**+ * The hook engine: runs one event's hooks and turns what they return into+ * attributed, severity-gated, validated actions.+ *+ * Execution: every applicable hook's handler is invoked CONCURRENTLY, each with+ * its own timeout and `AbortSignal`, against a shallow-frozen context, inside+ * the hook output scope. Results are collected and returned in EFFECTIVE ORDER;+ * the appliers (actions.ts, text-rewrite.ts) then apply them sequentially.+ * Closed handlers cannot see each other's results, so concurrency changes no+ * outcome — it only bounds latency to the slowest hook.+ *+ * Failure posture: fail open, always. A throw, a rejection, a timeout or an+ * invalid return value is journaled and treated as "no actions"; an invalid+ * action is journaled and ignored. Five consecutive failures of one hook disable+ * it for the process (journal `disabled`, one stderr line); any success resets+ * the count. There is no fail-closed option: a throwing hook never breaks a+ * request or a session.+ *+ * Observability: one private `journal()` fans out to the local journal and —+ * for the surfaces and decision values the telemetry backend accepts — to+ * `recordTelemetryDecision`, the session aggregate that actually uploads. The+ * two privacy rules are applied there, before the aggregate sees anything: a+ * user hook's id uploads as `"user"`, and an `mcp__` tool name on a user hook's+ * row is withheld. Built-in ids and tool names pass through. The local line+ * keeps the real id.+ */++import { log, logStderr } from "../logger.js";+import {+ type ActionResult,+ type ClosedEvent,+ type PlannedAction,+ validateAction,+} from "./actions.js";+import type { HooksConfig, WarnSink } from "./config.js";+import {+ type Decision,+ JOURNAL_SCHEMA_VERSION,+ type JournalEntry,+ type JournalEvent,+ MAX_DETAIL_CHARS,+ type Surface,+ classifyPath,+ isUploadDecision,+ isUploadSurface,+ recordDecision,+} from "./journal.js";+import { runInHookScope } from "./output-capture.js";+import type {+ HookAction,+ HookDefinition,+ HostMode,+ ObserveAction,+ RequestAction,+ ResponseEndAction,+ RewriteAction,+ SessionAction,+ Severity,+ ToolCallAction,+} from "./public.js";+import type {+ ApplicabilityScope,+ ApplicableHook,+ HookEventName,+ HookRegistry,+} from "./registry.js";+import { recordTelemetryDecision, setTelemetryConsent } from "./telemetry/aggregate.js";++/* ───────────── timeouts (§4.5) ───────────── */++/** Default and maximum handler timeout per event, in ms. */+export const EVENT_TIMEOUTS: Readonly<Record<HookEventName, { default: number; max: number }>> = {+ request: { default: 1_000, max: 5_000 },+ toolCall: { default: 1_000, max: 5_000 },+ responseRewrite: { default: 2_000, max: 10_000 },+ responseEnd: { default: 5_000, max: 30_000 },+ sessionStart: { default: 5_000, max: 30_000 },+ sessionIdle: { default: 5_000, max: 30_000 },+ sessionBlocked: { default: 5_000, max: 30_000 },+ // Shared across hooks: they run concurrently from one start, so a per-hook+ // bound of 1,500 ms bounds the whole dispatch to 1,500 ms.+ sessionEnd: { default: 1_500, max: 1_500 },+ "raw.providerRequest": { default: 1_000, max: 5_000 },+ // Synchronous; no timeout applies.+ "raw.providerChunk": { default: 0, max: 0 },+ "raw.providerStreamEnd": { default: 1_000, max: 5_000 },+ "raw.response": { default: 1_000, max: 5_000 },+};++/** A hook's timeout for an event: its own `timeoutMs` clamped to the event's maximum. */+export function timeoutFor(def: HookDefinition, event: HookEventName): number {+ const bounds = EVENT_TIMEOUTS[event];+ const own = def.timeoutMs;+ if (typeof own !== "number" || !Number.isFinite(own) || own <= 0) return bounds.default;+ return Math.min(own, bounds.max);+}++/** Consecutive failures that disable a hook for the process. */+export const BREAKER_THRESHOLD = 5;++/** The synthetic hook id carried by a pending note on the request it is applied to. */+export const PENDING_NOTE_ID = "behavior/pending-correction";++/** Sessions the pending-note store tracks; the oldest is evicted past this. */+export const MAX_PENDING_SESSIONS = 64;++/** Journal surface per event. `responseEnd` keeps the old `onModelOutput` surface. */+export const SURFACE_OF: Readonly<Record<HookEventName, Surface>> = {+ request: "request",+ toolCall: "tool_call",+ responseRewrite: "response",+ responseEnd: "model_output",+ sessionStart: "session",+ sessionIdle: "session",+ sessionBlocked: "session",+ sessionEnd: "session",+ "raw.providerRequest": "request",+ "raw.providerChunk": "response",+ "raw.providerStreamEnd": "response",+ "raw.response": "response",+};++/** The action union each closed event returns. */+export interface EventActions {+ request: RequestAction;+ toolCall: ToolCallAction;+ responseRewrite: RewriteAction;+ responseEnd: ResponseEndAction;+ sessionStart: SessionAction;+ sessionIdle: SessionAction;+ sessionBlocked: ObserveAction;+ sessionEnd: ObserveAction;+}++/** The engine-built part of every context (§4.3 `BaseContext`). */+export interface BaseContextParts {+ hookId: string;+ severity: Exclude<Severity, "off">;+ log(message: string): void;+ signal: AbortSignal;+}++/** Facts every journal line of one dispatch shares. */+export interface JournalMeta {+ model: string;+ provider: string;+ sessionId?: string;+ toolName?: string;+}++/** Everything one journal line can carry. */+export interface JournalInput extends JournalMeta {+ event: HookEventName | JournalEvent;+ hookId: string;+ decision: Decision;+ action?: string;+ surface?: Surface;+ argKeys?: string[];+ observedPath?: string;+ expectedPath?: string;+ note?: string;+ detail?: string;+}++export type HookRunStatus = "ok" | "timeout" | "error" | "invalid" | "aborted";++/** One hook's run within a dispatch. */+export interface HookRun<A extends HookAction> {+ applicable: ApplicableHook;+ status: HookRunStatus;+ /** Every valid action the hook returned, `warn` included, before the severity gate. */+ returned: A[];+}++export interface RunResult<A extends HookAction> {+ runs: Array<HookRun<A>>;+ /** Valid, non-`warn` actions of fix-severity hooks, in effective order: what to apply. */+ apply: Array<PlannedAction<A>>;+}++export interface RunOptions {+ /** Aborting it aborts every hook's signal; unfinished hooks end `aborted`, unjournaled. */+ signal?: AbortSignal;+}++function isUserHook(hookId: string): boolean {+ return hookId.startsWith("hook:");+}++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++function clip(text: string | undefined): string | undefined {+ if (text === undefined) return undefined;+ return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS - 1)}…` : text;+}++/** The function and its `this` for one event of a definition. */+function handlerOf(+ def: HookDefinition,+ event: ClosedEvent+): { fn: (ctx: unknown) => unknown; self: unknown } | null {+ const on = (def.on ?? {}) as Record<string, unknown>;+ const entry = on[event];+ if (event === "toolCall" || event === "responseRewrite") {+ const container = entry as { handle?: unknown } | undefined;+ return typeof container?.handle === "function"+ ? { fn: container.handle as (ctx: unknown) => unknown, self: container }+ : null;+ }+ return typeof entry === "function" ? { fn: entry as (ctx: unknown) => unknown, self: on } : null;+}++interface PendingNote {+ seq: number;+ hookId: string;+ text: string;+}++export interface HookEngineOptions {+ registry: HookRegistry;+ config: HooksConfig;+ hostMode: HostMode;+ /** Local journal writer. Default: append to `~/.claudish/behavior-journal.jsonl`. */+ journalSink?: (entry: JournalEntry) => void;+ /** Where the breaker's stderr line goes. Default: `logStderr`. */+ warn?: WarnSink;+ /**+ * Deliver telemetry a previous process spooled, in the background, when+ * consent is on. Default true; tests turn it off so nothing reaches the network.+ */+ drainTelemetryOutbox?: boolean;+}++export class HookEngine {+ readonly registry: HookRegistry;+ readonly config: HooksConfig;+ readonly hostMode: HostMode;++ private readonly journalSink: (entry: JournalEntry) => void;+ private readonly warnSink: WarnSink;+ private readonly failures = new Map<string, number>();+ private readonly disabled = new Set<string>();+ private readonly notes = new Map<string, PendingNote[]>();+ private noteSeq = 0;++ constructor(opts: HookEngineOptions) {+ this.registry = opts.registry;+ this.config = opts.config;+ this.hostMode = opts.hostMode;+ this.journalSink = opts.journalSink ?? ((entry) => void recordDecision(entry));+ this.warnSink = opts.warn ?? ((line) => logStderr(line));++ // The engine owns the parsed config, so consent is pushed to the collector+ // from here rather than re-read on the request path.+ const optedIn = opts.config.telemetry?.enabled === true;+ setTelemetryConsent(optedIn);+ // Deliver what a PREVIOUS process spooled at exit. In the background of a+ // live process, because shutdown is synchronous and cannot await a POST.+ if (optedIn && opts.drainTelemetryOutbox !== false) {+ void import("./telemetry/upload.js")+ .then((m) => m.drainOutbox())+ .catch((err) => log(`[hooks:telemetry] drain unavailable: ${err}`));+ }+ }++ /* ───────────── selection ───────────── */++ /** Applicable hooks for an event, in effective order, minus those the breaker disabled. */+ select(event: HookEventName, scope: ApplicabilityScope = {}): ApplicableHook[] {+ return this.registry.applicable(event, scope).filter((a) => !this.disabled.has(a.hook.id));+ }++ /** True when the circuit breaker disabled this hook. */+ isDisabled(hookId: string): boolean {+ return this.disabled.has(hookId);+ }++ /* ───────────── dispatch ───────────── */++ /**+ * Run one closed event's handlers concurrently and collect their actions.+ *+ * `context` builds the event's full context from the engine's base parts;+ * the result is shallow-frozen before the handler sees it.+ */+ async run<E extends ClosedEvent>(+ event: E,+ hooks: ReadonlyArray<ApplicableHook>,+ context: (applicable: ApplicableHook, base: BaseContextParts) => object,+ meta: JournalMeta,+ opts: RunOptions = {}+ ): Promise<RunResult<EventActions[E]>> {+ const runs = await Promise.all(+ hooks.map((applicable) => this.runOne(event, applicable, context, meta, opts.signal))+ );++ const apply: Array<PlannedAction<EventActions[E]>> = [];+ for (const run of runs) {+ const { hook, severity } = run.applicable;+ for (const action of run.returned) {+ if (action.type === "warn") {+ log(`[hooks] ${hook.id} warn: ${action.message}`);+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ action: "warn",+ decision: "warned",+ detail: action.message,+ });+ continue;+ }+ if (severity !== "fix") {+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ action: action.type,+ decision: "warned",+ detail: "severity warn: not applied",+ });+ continue;+ }+ apply.push({ hookId: hook.id, action });+ }+ }+ return { runs, apply };+ }++ private runOne<E extends ClosedEvent>(+ event: E,+ applicable: ApplicableHook,+ context: (applicable: ApplicableHook, base: BaseContextParts) => object,+ meta: JournalMeta,+ parent: AbortSignal | undefined+ ): Promise<HookRun<EventActions[E]>> {+ const { hook, severity } = applicable;+ const done = (status: HookRunStatus, returned: Array<EventActions[E]> = []) => ({+ applicable,+ status,+ returned,+ });++ const handler = handlerOf(hook.def, event);+ if (!handler) return Promise.resolve(done("ok"));+ if (parent?.aborted) return Promise.resolve(done("aborted"));++ const controller = new AbortController();+ const timeoutMs = timeoutFor(hook.def, event);+ const observe =+ event === "toolCall" &&+ (hook.def.on?.toolCall as { observe?: boolean } | undefined)?.observe === true;++ return new Promise((resolveRun) => {+ let settled = false;+ const finish = (run: HookRun<EventActions[E]>) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ parent?.removeEventListener("abort", onParentAbort);+ resolveRun(run);+ };++ const onParentAbort = () => {+ controller.abort(parent?.reason ?? new Error("aborted"));+ finish(done("aborted"));+ };+ parent?.addEventListener("abort", onParentAbort, { once: true });++ const timer = setTimeout(() => {+ controller.abort(new Error(`hook ${hook.id} timed out after ${timeoutMs} ms`));+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ decision: "timeout",+ detail: `${timeoutMs} ms`,+ });+ this.noteFailure(hook.id, meta, event);+ finish(done("timeout"));+ }, timeoutMs);++ const base: BaseContextParts = {+ hookId: hook.id,+ severity,+ log: (message: string) => log(`[hook ${hook.id}] ${message}`),+ signal: controller.signal,+ };++ let value: unknown;+ try {+ const ctx = Object.freeze(context(applicable, base));+ value = runInHookScope(hook.id, () => handler.fn.call(handler.self, ctx));+ } catch (err) {+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ decision: "error",+ detail: errorText(err),+ });+ this.noteFailure(hook.id, meta, event);+ finish(done("error"));+ return;+ }++ Promise.resolve(value).then(+ (returned) => {+ if (settled) return;+ const result = this.collect(event, hook.id, returned, meta, observe);+ if (result === null) {+ this.noteFailure(hook.id, meta, event);+ finish(done("invalid"));+ return;+ }+ this.noteSuccess(hook.id);+ finish(done("ok", result as Array<EventActions[E]>));+ },+ (err: unknown) => {+ if (settled) return;+ this.journal({+ ...meta,+ event,+ hookId: hook.id,+ decision: "error",+ detail: errorText(err),+ });+ this.noteFailure(hook.id, meta, event);+ finish(done("error"));+ }+ );+ });+ }++ /**+ * Validate a handler's return value. Returns the valid actions, or null when+ * the value itself is invalid (not an array, not undefined).+ */+ private collect(+ event: ClosedEvent,+ hookId: string,+ returned: unknown,+ meta: JournalMeta,+ observe: boolean+ ): HookAction[] | null {+ if (returned === undefined || returned === null) return [];+ if (!Array.isArray(returned)) {+ this.journal({+ ...meta,+ event,+ hookId,+ decision: "invalid",+ detail: "return value is not an array",+ });+ return null;+ }+ const valid: HookAction[] = [];+ for (const value of returned) {+ const checked = validateAction(event, value, { observe });+ if (checked.ok) {+ valid.push(checked.action);+ continue;+ }+ const type = (value as { type?: unknown } | null)?.type;+ this.journal({+ ...meta,+ event,+ hookId,+ action: typeof type === "string" ? type : undefined,+ decision: "invalid",+ detail: checked.reason,+ });+ }+ return valid;+ }++ /**+ * Call a synchronous predicate (`armed`, `claims`) inside the hook's scope.+ * A throw, or a non-boolean, counts as `false`.+ */+ callPredicate(+ hookId: string,+ fn: ((ctx: never) => unknown) | undefined,+ self: unknown,+ ctx: object,+ fallback = true+ ): boolean {+ if (typeof fn !== "function") return fallback;+ try {+ const value = runInHookScope(hookId, () =>+ (fn as (c: object) => unknown).call(self, Object.freeze(ctx))+ );+ return value === true;+ } catch (err) {+ log(`[hooks] ${hookId} predicate threw: ${errorText(err)}`);+ return false;+ }+ }++ /* ───────────── circuit breaker ───────────── */++ /** Count one failed call. The fifth in a row disables the hook for the process. */+ noteFailure(hookId: string, meta: JournalMeta, event: HookEventName | JournalEvent): void {+ if (this.disabled.has(hookId)) return;+ const count = (this.failures.get(hookId) ?? 0) + 1;+ this.failures.set(hookId, count);+ if (count < BREAKER_THRESHOLD) return;+ this.disabled.add(hookId);+ this.journal({+ ...meta,+ event,+ hookId,+ decision: "disabled",+ detail: `${BREAKER_THRESHOLD} consecutive failures`,+ });+ this.warnSink(+ `hook ${hookId} disabled after ${BREAKER_THRESHOLD} consecutive failures (see the debug log)`+ );+ }++ /** Any success resets the consecutive-failure count. */+ noteSuccess(hookId: string): void {+ this.failures.delete(hookId);+ }++ /* ───────────── journal ───────────── */++ /**+ * The single fan-out: the local journal line, and — for an uploadable+ * surface and decision — the telemetry aggregate, after the privacy+ * projection. Fire-and-forget; journaling never sits on the request path.+ */+ journal(input: JournalInput): void {+ const event = input.event.startsWith("raw.") ? "raw" : (input.event as JournalEvent);+ const surface = input.surface ?? SURFACE_OF[input.event as HookEventName] ?? "request";+ const upload = isUploadSurface(surface);+ const pathRelation = upload ? classifyPath(input.observedPath, input.expectedPath) : undefined;++ if (upload && isUploadDecision(input.decision)) {+ const user = isUserHook(input.hookId);+ recordTelemetryDecision({+ sessionId: input.sessionId,+ model: input.model,+ provider: input.provider,+ surface,+ decision: input.decision,+ // A user hook's id is a user-chosen name, and so is an MCP server's.+ ruleId: user ? "user" : input.hookId,+ toolName: user && input.toolName?.startsWith("mcp__") ? undefined : input.toolName,+ pathRelation,+ });+ }++ const entry: JournalEntry = {+ schema: JOURNAL_SCHEMA_VERSION,+ ts: new Date().toISOString(),+ event,+ hookId: input.hookId,+ model: input.model,+ provider: input.provider,+ surface,+ decision: input.decision,+ ruleId: input.hookId,+ };+ if (input.action !== undefined) entry.action = input.action;+ if (input.sessionId !== undefined) entry.sessionId = input.sessionId;+ if (input.toolName !== undefined) entry.toolName = input.toolName;+ if (input.argKeys !== undefined) entry.argKeys = input.argKeys;+ if (pathRelation !== undefined) entry.pathRelation = pathRelation;+ if (+ input.observedPath !== undefined ||+ input.expectedPath !== undefined ||+ input.note !== undefined+ ) {+ entry.local = {+ observedPath: input.observedPath,+ expectedPath: input.expectedPath,+ note: input.note,+ };+ }+ const detail = clip(input.detail);+ if (detail !== undefined) entry.detail = detail;++ try {+ this.journalSink(entry);+ } catch (err) {+ log(`[hooks:journal] could not record: ${errorText(err)}`);+ }+ }++ /** Journal what the appliers decided for each planned action. */+ recordResults(+ event: HookEventName,+ results: ReadonlyArray<ActionResult>,+ meta: JournalMeta,+ extra?: (result: ActionResult) => Partial<JournalInput>+ ): void {+ for (const r of results) {+ const toolName =+ "tool" in r.action && typeof r.action.tool === "string" ? r.action.tool : meta.toolName;+ // A repaired tool call keeps the decision the telemetry backend knows it by.+ const decision: Decision =+ r.action.type === "repairToolArgs" && r.decision === "matched" ? "repaired" : r.decision;+ this.journal({+ ...meta,+ toolName,+ event,+ hookId: r.hookId,+ action: r.action.type,+ decision,+ detail: r.detail,+ ...(extra?.(r) ?? {}),+ });+ }+ }++ /* ───────────── pending notes ───────────── */++ /**+ * Store an `injectSystemNote` from `responseEnd` for the Claude session's+ * NEXT request. Bounded to MAX_PENDING_SESSIONS sessions, oldest evicted.+ */+ queueNote(sessionId: string, hookId: string, text: string): void {+ const list = this.notes.get(sessionId) ?? [];+ list.push({ seq: ++this.noteSeq, hookId, text });+ // Re-insert so a busy session is the newest, not evicted first.+ this.notes.delete(sessionId);+ this.notes.set(sessionId, list);+ while (this.notes.size > MAX_PENDING_SESSIONS) {+ const oldest = this.notes.keys().next().value;+ if (oldest === undefined) break;+ this.notes.delete(oldest);+ }+ }++ /**+ * The notes pending for a session, WITHOUT removing them. They are removed by+ * `consumeNotes` only once a request carrying them is accepted, so a failed+ * fallback attempt cannot lose a note.+ */+ peekNotes(sessionId: string | undefined): ReadonlyArray<Readonly<PendingNote>> {+ if (!sessionId) return [];+ return [...(this.notes.get(sessionId) ?? [])];+ }++ /** Remove the notes a committed request carried (by `seq`; already-removed ones are ignored). */+ consumeNotes(sessionId: string, seqs: ReadonlyArray<number>): void {+ const list = this.notes.get(sessionId);+ if (!list) return;+ const drop = new Set(seqs);+ const rest = list.filter((n) => !drop.has(n.seq));+ if (rest.length === 0) this.notes.delete(sessionId);+ else this.notes.set(sessionId, rest);+ }+}diff --git a/packages/cli/src/behavior/journal.test.ts b/packages/cli/src/hooks/journal.test.tssimilarity index 76%rename from packages/cli/src/behavior/journal.test.tsrename to packages/cli/src/hooks/journal.test.tsindex 7c365a51..5a83d591 100644--- a/packages/cli/src/behavior/journal.test.ts+++ b/packages/cli/src/hooks/journal.test.ts@@ -7,8 +7,9 @@ import {type JournalEntry,MAX_JOURNAL_BYTES,classifyPath,+ isUploadDecision,+ isUploadSurface,recordDecision,- toUploadable,} from "./journal.js";async function inTempDir(run: (dir: string) => Promise<void>): Promise<void> {@@ -35,56 +36,35 @@ function journalEntry(overrides: Partial<JournalEntry> = {}): JournalEntry {};}-describe("toUploadable", () => {- it("preserves the non-identifying signal while stripping all local path detail", () => {- const entry = journalEntry({- local: {- observedPath: "/Users/jack/dev/acme/acme-portal/plans/wrong.md",- expectedPath: "/Users/jack/dev/acme/acme-portal/plans/assigned.md",- note: "jack wrote wrong.md for the acme portal instead of assigned.md",- },- });-- const uploadable = toUploadable(entry);- const serialized = JSON.stringify(uploadable);-- for (const identifyingFragment of [- "/Users",- "jack",- "acme",- "acme-portal",- "wrong.md",- "assigned.md",- ]) {- expect(serialized).not.toContain(identifyingFragment);+describe("upload sets", () => {+ it("accepts only the surfaces and decisions the telemetry backend lists", () => {+ // docs/specs/behavior-telemetry-backend.md, "Enumerations" — closed sets.+ for (const surface of ["request", "tool_call", "model_output", "sequence"] as const) {+ expect(isUploadSurface(surface)).toBe(true);+ }+ for (const surface of ["response", "session"] as const) {+ expect(isUploadSurface(surface)).toBe(false);+ }+ for (const decision of ["ignored", "matched", "warned", "repaired", "novel"] as const) {+ expect(isUploadDecision(decision)).toBe(true);+ }+ for (const decision of [+ "superseded",+ "invalid",+ "timeout",+ "error",+ "disabled",+ "dropped",+ "queued",+ "delivered",+ "raw",+ ] as const) {+ expect(isUploadDecision(decision)).toBe(false);}- expect(Object.hasOwn(uploadable, "local")).toBe(false);- expect(serialized).not.toContain('"local"');- expect(uploadable).toEqual({- schema: JOURNAL_SCHEMA_VERSION,- ts: entry.ts,- model: entry.model,- provider: entry.provider,- surface: entry.surface,- decision: entry.decision,- ruleId: entry.ruleId,- toolName: entry.toolName,- argKeys: entry.argKeys,- pathRelation: entry.pathRelation,- });- expect(uploadable.schema).toBe(JOURNAL_SCHEMA_VERSION);});- it("does not upload fields added to a local entry unless explicitly allowed", () => {- const entry = {- ...journalEntry(),- futureSensitiveField: "top-secret-client-name",- } as JournalEntry;-- const serialized = JSON.stringify(toUploadable(entry));-- expect(serialized).not.toContain("futureSensitiveField");- expect(serialized).not.toContain("top-secret-client-name");+ it("writes schema 2 locally", () => {+ expect(JOURNAL_SCHEMA_VERSION).toBe(2);});});diff --git a/packages/cli/src/behavior/journal.ts b/packages/cli/src/hooks/journal.tssimilarity index 64%rename from packages/cli/src/behavior/journal.tsrename to packages/cli/src/hooks/journal.tsindex 7dfca793..95cb260f 100644--- a/packages/cli/src/behavior/journal.ts+++ b/packages/cli/src/hooks/journal.ts@@ -1,5 +1,8 @@/**- * Behavior decision journal.+ * Hook decision journal (`~/.claudish/behavior-journal.jsonl`).+ *+ * The file keeps its name: it names the behaviour-telemetry product and its+ * `POST /v1/behavior` endpoint, not the deleted `behavior/` module.** Records what the supervisor SAW and what it DECIDED, so the decisions can be* analysed later and turned into deterministic rules. This is the input to the@@ -12,7 +15,7 @@* genuinely needs it: "the model wrote to <this> instead of <that>" is the whole* signal, and stripping it leaves nothing to learn from.*- * An UPLOADABLE record carries no paths at all. Not sanitized paths — none. The+ * What may LEAVE the machine carries no paths at all. Not sanitized paths — none. The* existing `sanitizeForReport()` masks the home directory but keeps the rest, so* `/Users/***\/dev/acme/acme-portal/...` still names a client. For aggregate* analysis the literal path is not needed anyway: what matters is the CATEGORY@@ -28,7 +31,7 @@** Local journalling is always on and needs no consent: it is the user's own data* on their own disk, exactly like `logs/`. Upload is a SEPARATE opt-in- * (`behavior.telemetry.enabled`) and deliberately does NOT ride on the existing+ * (`hooks.telemetry.enabled`) and deliberately does NOT ride on the existing* `stats.enabled` consent — that consent was given for usage statistics, and* silently reusing it to ship behavioural records would be consent laundering.*/@@ -38,11 +41,28 @@ import { homedir } from "node:os";import { dirname, join } from "node:path";import { log } from "../logger.js";-/** Bump when the uploadable shape changes, so consumers can version-gate. */-export const JOURNAL_SCHEMA_VERSION = 1;+/**+ * Local journal line schema. 2 since the hook system: the line names the event,+ * the hook and the action. Uploads are NOT journal lines — they are the session+ * aggregate built by `telemetry/aggregate.ts`, which keeps its own schema (1).+ */+export const JOURNAL_SCHEMA_VERSION = 2;/** Which supervision surface produced this decision. */-export type Surface = "request" | "tool_call" | "model_output" | "sequence";+export type Surface =+ | "request"+ | "tool_call"+ | "model_output"+ | "sequence"+ | "response"+ | "session";++/**+ * The surfaces the telemetry backend accepts. A CLOSED set fixed by the server+ * contract (`docs/specs/behavior-telemetry-backend.md`); `response` and+ * `session` are local only.+ */+export type UploadSurface = "request" | "tool_call" | "model_output" | "sequence";/** What the supervisor did. */export type Decision =@@ -50,7 +70,44 @@ export type Decision =| "matched" // a rule matched and applied| "warned" // a rule matched but severity was warn| "repaired" // arguments were rewritten- | "novel"; // nothing matched and the observer was consulted+ | "novel" // nothing matched and the observer was consulted+ | "superseded" // an earlier hook won the same target+ | "invalid" // the action was refused (shape, limit, not allowed for the event)+ | "timeout" // the handler did not return within its timeout+ | "error" // the handler threw or rejected+ | "disabled" // the circuit breaker disabled the hook+ | "dropped" // an injection or annotation was dropped+ | "queued" // an injection or note was queued+ | "delivered" // an injection was delivered+ | "raw"; // a raw (unsafe) hook touched the request or response++/**+ * The decision values the telemetry backend accepts — the `counts.*` keys of+ * the server contract. Everything added since is local only.+ */+export type UploadDecision = "ignored" | "matched" | "warned" | "repaired" | "novel";++const UPLOAD_SURFACES: ReadonlySet<string> = new Set<UploadSurface>([+ "request",+ "tool_call",+ "model_output",+ "sequence",+]);+const UPLOAD_DECISIONS: ReadonlySet<string> = new Set<UploadDecision>([+ "ignored",+ "matched",+ "warned",+ "repaired",+ "novel",+]);++export function isUploadSurface(surface: Surface): surface is UploadSurface {+ return UPLOAD_SURFACES.has(surface);+}++export function isUploadDecision(decision: Decision): decision is UploadDecision {+ return UPLOAD_DECISIONS.has(decision);+}/*** How a file path related to the one the harness expected.@@ -65,60 +122,55 @@ export type PathRelation =| "no_expectation"| "not_applicable";+/** Hook events, plus `raw` for every raw-tier stage. */+export type JournalEvent =+ | "request"+ | "toolCall"+ | "responseRewrite"+ | "responseEnd"+ | "sessionStart"+ | "sessionIdle"+ | "sessionBlocked"+ | "sessionEnd"+ | "raw";++/**+ * One local journal line. Never uploaded as-is: the upload is the per-session+ * aggregate, and the only fields that reach it are passed explicitly by the+ * hook engine's `journal()` fan-out, which also applies the user-hook privacy+ * rules there.+ */export interface JournalEntry {+ /** JOURNAL_SCHEMA_VERSION. Absent on lines written by the pre-hook engine. */+ schema?: number;ts: string;+ event?: JournalEvent;+ /** The real hook id — local only. */+ hookId?: string;+ action?: string;model: string;provider: string;+ sessionId?: string;surface: Surface;decision: Decision;+ /** Same as hookId (kept for readers of schema 1). */ruleId?: string;toolName?: string;/** Argument KEYS only — never values. */argKeys?: string[];pathRelation?: PathRelation;- /** Full local detail. Stripped from anything uploaded. */+ /** Full local detail. Never uploaded. */local?: {observedPath?: string;expectedPath?: string;note?: string;};+ /** At most 200 chars. Local only. */+ detail?: string;}-/** The subset that may leave the machine. Constructed by omission, not by masking. */-export interface UploadableEntry {- schema: number;- ts: string;- model: string;- provider: string;- surface: Surface;- decision: Decision;- ruleId?: string;- toolName?: string;- argKeys?: string[];- pathRelation?: PathRelation;-}--/**- * Project a journal entry to its uploadable form.- *- * Deliberately an ALLOW-list: new fields added to JournalEntry do not leak by- * default, they have to be added here explicitly. A deny-list would ship the- * next contributor's new field to the cloud by accident.- */-export function toUploadable(entry: JournalEntry): UploadableEntry {- return {- schema: JOURNAL_SCHEMA_VERSION,- ts: entry.ts,- model: entry.model,- provider: entry.provider,- surface: entry.surface,- decision: entry.decision,- ruleId: entry.ruleId,- toolName: entry.toolName,- argKeys: entry.argKeys,- pathRelation: entry.pathRelation,- };-}+/** The longest `detail` a journal line carries. */+export const MAX_DETAIL_CHARS = 200;/** Classify an observed path against the expected one, without keeping either. */export function classifyPath(observed?: string, expected?: string): PathRelation {diff --git a/packages/cli/src/hooks/loader.test.ts b/packages/cli/src/hooks/loader.test.tsnew file mode 100644index 00000000..e7cedb2e--- /dev/null+++ b/packages/cli/src/hooks/loader.test.ts@@ -0,0 +1,328 @@+import { afterEach, describe, expect, it } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join } from "node:path";+import { HookEngine } from "./engine.js";+import { loadUserHooks, moduleName, resetLoaderForTests, resolveModulePath } from "./loader.js";+import { HookRegistry } from "./registry.js";++const dirs: string[] = [];+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-loader-"));+ dirs.push(dir);+ return dir;+}+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+ resetLoaderForTests();+});++/** Write `name` into `dir` and return its absolute path. */+function write(dir: string, name: string, source: string): string {+ const path = join(dir, name);+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, source);+ return path;+}++async function load(modules: string[], configDir: string, loadTimeoutMs?: number) {+ const warnings: string[] = [];+ const result = await loadUserHooks({+ modules,+ configDir,+ hostMode: "interactive",+ loadTimeoutMs,+ warn: (l) => warnings.push(l),+ });+ return { ...result, warnings };+}++const VALID = `export default { apiVersion: 1, id: "add", on: { request: () => [] } };`;++describe("loadUserHooks — valid modules", () => {+ it("loads a .ts default export and namespaces its id with the module basename", async () => {+ const dir = tempDir();+ const path = write(dir, "add-marker.ts", VALID);+ const r = await load([path], dir);+ expect(r.errors).toEqual([]);+ expect(r.hooks.map((h) => [h.id, h.module, h.moduleIndex, h.exportIndex])).toEqual([+ ["hook:add-marker/add", path, 0, 0],+ ]);+ });++ it("loads a .js default array, in export order", async () => {+ const dir = tempDir();+ const path = write(+ dir,+ "pair.js",+ `export default [+ { apiVersion: 1, id: "one", on: { sessionIdle: () => [] } },+ { apiVersion: 1, id: "two/sub", order: "pre", on: { responseEnd: () => [] } },+ ];`+ );+ const r = await load([path], dir);+ expect(r.hooks.map((h) => [h.id, h.exportIndex])).toEqual([+ ["hook:pair/one", 0],+ ["hook:pair/two/sub", 1],+ ]);+ });++ it("serves claudish/hooks as a value import and erases a type-only import", async () => {+ const dir = tempDir();+ const value = write(+ dir,+ "value.ts",+ `import { defineHook, act, HOOK_API_VERSION } from "claudish/hooks";+ export default defineHook({+ apiVersion: HOOK_API_VERSION,+ id: "v",+ on: { request: () => [act.injectSystemNote("from value import")] },+ });`+ );+ const typed = write(+ dir,+ "typed.ts",+ `import type { HookDefinition } from "claudish/hooks";+ export default { apiVersion: 1, id: "t", on: { request: () => [] } } satisfies HookDefinition;`+ );+ const r = await load([value, typed], dir);+ expect(r.errors).toEqual([]);+ expect(r.hooks.map((h) => h.id)).toEqual(["hook:value/v", "hook:typed/t"]);+ const out = (r.hooks[0]?.def.on?.request as () => unknown)();+ expect(out).toEqual([{ type: "injectSystemNote", text: "from value import" }]);+ });++ it("resolves a relative path against the config directory, not the cwd", async () => {+ const dir = tempDir();+ write(dir, "hooks/rel.ts", VALID);+ const r = await load(["hooks/rel.ts"], dir);+ expect(r.hooks.map((h) => h.module)).toEqual([join(dir, "hooks/rel.ts")]);+ });++ it("defaults a user hook to fix severity", async () => {+ const dir = tempDir();+ const r = await load([write(dir, "sev.ts", VALID)], dir);+ const engine = new HookEngine({+ registry: new HookRegistry([], r.hooks, undefined),+ config: {},+ hostMode: "other",+ journalSink: () => {},+ drainTelemetryOutbox: false,+ });+ const route = { modelId: "m", provider: "p", native: false };+ expect(engine.select("request", { route })[0]?.severity).toBe("fix");+ });+});++describe("loadUserHooks — rejections", () => {+ it("rejects a wrong or missing apiVersion with the exact message", async () => {+ const dir = tempDir();+ const path = write(+ dir,+ "ver.ts",+ `export default [+ { apiVersion: 2, id: "two", on: { request: () => [] } },+ { id: "none", on: { request: () => [] } },+ { apiVersion: 1, id: "ok", on: { request: () => [] } },+ ];`+ );+ const r = await load([path], dir);+ expect(r.hooks.map((h) => h.id)).toEqual(["hook:ver/ok"]);+ expect(r.warnings).toEqual([+ `hook ${path}#two: apiVersion 2 is not supported (this claudish supports 1)`,+ `hook ${path}#none: apiVersion undefined is not supported (this claudish supports 1)`,+ ]);+ });++ it("rejects a missing id, a bad id, no handlers, and raw without unsafe", async () => {+ const dir = tempDir();+ const path = write(+ dir,+ "bad.ts",+ `export default [+ { apiVersion: 1, on: { request: () => [] } },+ { apiVersion: 1, id: "Bad Id", on: { request: () => [] } },+ { apiVersion: 1, id: "${"x".repeat(65)}", on: { request: () => [] } },+ { apiVersion: 1, id: "empty" },+ { apiVersion: 1, id: "raw", raw: { providerRequest: () => {} } },+ { apiVersion: 1, id: "typo", on: { onRequest: () => [] } },+ { apiVersion: 1, id: "tc", on: { toolCall: { handle: () => [] } } },+ ];`+ );+ const r = await load([path], dir);+ expect(r.hooks).toEqual([]);+ const reasons = r.errors.map((e) => e.reason);+ expect(reasons[0]).toBe("#0: id is missing");+ expect(reasons[1]).toContain('id "Bad Id" does not match');+ expect(reasons[2]).toContain("longer than 64");+ expect(reasons[3]).toBe("empty: declares no handler in on or raw");+ expect(reasons[4]).toBe("raw: raw requires unsafe: true");+ expect(reasons[5]).toBe("typo: on.onRequest is not a hook event");+ expect(reasons[6]).toBe("tc: on.toolCall.tools must be a non-empty array of tool names");+ });++ it("rejects a declared async providerChunk at load and keeps its sibling", async () => {+ const dir = tempDir();+ const path = write(+ dir,+ "chunky.ts",+ `export default [+ { apiVersion: 1, id: "async-chunk", unsafe: true, raw: { async providerChunk() {} } },+ { apiVersion: 1, id: "sync-chunk", unsafe: true, raw: { providerChunk() {} } },+ ];`+ );+ const r = await load([path], dir);+ expect(r.hooks.map((h) => h.id)).toEqual(["hook:chunky/sync-chunk"]);+ expect(r.warnings).toContain(+ `hook ${path}#async-chunk: raw.providerChunk must be synchronous (it runs on the parser's loop)`+ );+ expect(r.warnings).toContain(+ "hook hook:chunky/sync-chunk is UNSAFE (raw middleware): it receives live request and response objects"+ );+ });++ it("skips a module that throws on import, and one with no default export", async () => {+ const dir = tempDir();+ const thrower = write(dir, "thrower.ts", `throw new Error("import exploded");`);+ const named = write(dir, "named.ts", `export const hook = { apiVersion: 1, id: "x" };`);+ const ok = write(dir, "ok.ts", VALID);+ const r = await load([thrower, named, ok], dir);+ expect(r.hooks.map((h) => h.id)).toEqual(["hook:ok/add"]);+ expect(r.warnings).toEqual([+ `hook module ${thrower} skipped: import exploded`,+ `hook module ${named} skipped: no default export`,+ ]);+ });++ it("skips a missing file with a warning naming it", async () => {+ const dir = tempDir();+ const missing = join(dir, "nope.ts");+ const r = await load([missing], dir);+ expect(r.hooks).toEqual([]);+ expect(r.warnings.length).toBe(1);+ expect(r.warnings[0]?.startsWith(`hook module ${missing} skipped:`)).toBe(true);+ });++ it("times out a module whose top-level await never settles", async () => {+ const dir = tempDir();+ const hung = write(dir, "hung.ts", "await new Promise(() => {}); export default {};");+ const ok = write(dir, "after.ts", VALID);+ const t0 = performance.now();+ const r = await load([hung, ok], dir, 150);+ expect(performance.now() - t0).toBeLessThan(2_000);+ expect(r.warnings).toEqual([`hook module ${hung} skipped: load timed out after 150 ms`]);+ expect(r.hooks.map((h) => h.id)).toEqual(["hook:after/add"]);+ });++ it("keeps the first of two hooks with the same id in one module", async () => {+ const dir = tempDir();+ const path = write(+ dir,+ "dup.ts",+ `export default [+ { apiVersion: 1, id: "same", description: "first", on: { request: () => [] } },+ { apiVersion: 1, id: "same", description: "second", on: { request: () => [] } },+ ];`+ );+ const r = await load([path], dir);+ expect(r.hooks.map((h) => h.def.description)).toEqual(["first"]);+ expect(r.warnings).toEqual([+ `hook ${path}#same: duplicate id hook:dup/same, keeping the first`,+ ]);+ });++ it("skips the later of two modules sharing a basename, whole", async () => {+ const dir = tempDir();+ const a = write(dir, "a/ping.ts", VALID);+ const b = write(+ dir,+ "b/ping.js",+ `export default [{ apiVersion: 1, id: "other", on: { request: () => [] } }];`+ );+ const r = await load([a, b], dir);+ expect(r.hooks.map((h) => [h.id, h.module])).toEqual([["hook:ping/add", a]]);+ expect(r.warnings).toEqual([+ `hook module ${b} skipped: its name "ping" is already used by ${a}; rename one`,+ ]);+ });+});++describe("paths", () => {+ it("expands ~ and resolves relative paths against the config dir", () => {+ expect(resolveModulePath("~/.claudish/hooks/p.ts", "/cfg")).toBe(+ join(homedir(), ".claudish/hooks/p.ts")+ );+ expect(resolveModulePath("hooks/p.ts", "/cfg")).toBe("/cfg/hooks/p.ts");+ expect(resolveModulePath("/abs/p.ts", "/cfg")).toBe("/abs/p.ts");+ });++ it("names a module by its basename without the extension", () => {+ expect(moduleName("/x/add-marker.ts")).toBe("add-marker");+ expect(moduleName("/x/ping.test.js")).toBe("ping.test");+ });+});++describe("hook output stays off stdout (spawned process)", () => {+ const HELPER = join(import.meta.dir, "test-helpers", "capture-child.ts");+ const NOISY = `+ console.log("IMPORT-LOG");+ process.stdout.write("IMPORT-WRITE\\n");+ setTimeout(() => { console.log("IMPORT-TIMER"); }, 20);+ export default {+ apiVersion: 1,+ id: "noisy",+ on: {+ request: async () => {+ console.log("HANDLER-LOG");+ console.error("HANDLER-ERR");+ setTimeout(() => { process.stdout.write("HANDLER-TIMER\\n"); }, 20);+ await Bun.sleep(5);+ console.info("HANDLER-AFTER-AWAIT");+ return [];+ },+ },+ };`;++ it("routes import-time, handler and timer output to the debug log", async () => {+ const dir = tempDir();+ const mod = write(dir, "noisy.ts", NOISY);+ const proc = Bun.spawn(["bun", HELPER, "interactive", mod], {+ cwd: dir,+ stdout: "pipe",+ stderr: "pipe",+ });+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ await proc.exited;+ expect(stdout).toBe("");+ const report = JSON.parse(stderr.slice(stderr.indexOf("REPORT ") + 7).split("\n")[0] ?? "{}");+ expect(report.hooks).toEqual(["hook:noisy/noisy"]);+ expect(report.statuses).toEqual(["ok"]);+ expect(stderr).not.toContain("HANDLER-ERR");++ const logs = readdirSync(join(dir, "logs"));+ const log = readFileSync(join(dir, "logs", logs[0] as string), "utf8");+ expect(log).toContain(`[hook ${mod}] IMPORT-LOG`);+ expect(log).toContain(`[hook ${mod}] IMPORT-WRITE`);+ expect(log).toContain(`[hook ${mod}] IMPORT-TIMER`);+ expect(log).toContain("[hook hook:noisy/noisy] HANDLER-LOG");+ expect(log).toContain("[hook hook:noisy/noisy] HANDLER-ERR");+ expect(log).toContain("[hook hook:noisy/noisy] HANDLER-TIMER");+ expect(log).toContain("[hook hook:noisy/noisy] HANDLER-AFTER-AWAIT");+ });++ it("positive control: the same module imported without the loader writes to stdout", async () => {+ const dir = tempDir();+ const mod = write(dir, "noisy.ts", NOISY);+ const proc = Bun.spawn(+ ["bun", "-e", `await import(${JSON.stringify(mod)}); await Bun.sleep(100);`],+ { cwd: dir, stdout: "pipe", stderr: "pipe" }+ );+ const stdout = await new Response(proc.stdout).text();+ await proc.exited;+ expect(stdout).toContain("IMPORT-LOG");+ expect(stdout).toContain("IMPORT-TIMER");+ });+});diff --git a/packages/cli/src/hooks/loader.ts b/packages/cli/src/hooks/loader.tsnew file mode 100644index 00000000..41966104--- /dev/null+++ b/packages/cli/src/hooks/loader.ts@@ -0,0 +1,360 @@+/**+ * User hook module loading.+ *+ * Resolves each `hooks.modules` path, imports it with a load timeout inside the+ * hook output scope, checks the default export's shape, and returns the hooks+ * with namespaced ids. Everything here is non-fatal: a module that fails to+ * import, times out, has the wrong shape or throws produces one stderr warning+ * naming the module and the reason, and is skipped. claudish always starts —+ * least of all should a broken hook stop it when the user is starting it in+ * order to fix that hook.+ *+ * Before the first user import, the `claudish/hooks` virtual module is+ * registered as a Bun runtime plugin answering with the HOST's own public+ * exports, so `import { defineHook, act } from "claudish/hooks"` needs nothing+ * installed. It must come first: under plain `bun` (the npm route) an+ * unresolved bare import would otherwise trigger npm auto-install (measured in+ * P1), and once claudish exports `./hooks` on npm it would resolve to a copy+ * other than the host's. `import type` needs no runtime resolution at all.+ */++import { homedir } from "node:os";+import { basename, isAbsolute, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { logStderr } from "../logger.js";+import type { WarnSink } from "./config.js";+import { protocolIsolation, runImportInScope } from "./output-capture.js";+import * as publicApi from "./public.js";+import type { HookDefinition, HostMode } from "./public.js";+import type { UserHookInput } from "./registry.js";++/** How long one module import may take. */+export const LOAD_TIMEOUT_MS = 10_000;++const ID_PATTERN = /^[a-z0-9][a-z0-9._-]*(\/[a-z0-9._-]+)*$/;+const MAX_ID_LENGTH = 64;++const ON_FUNCTION_KEYS = [+ "request",+ "responseEnd",+ "sessionStart",+ "sessionIdle",+ "sessionBlocked",+ "sessionEnd",+] as const;+const ON_KEYS = new Set<string>([...ON_FUNCTION_KEYS, "toolCall", "responseRewrite"]);+const RAW_KEYS = new Set(["providerRequest", "providerChunk", "providerStreamEnd", "response"]);+const SEVERITIES = new Set(["off", "warn", "fix"]);+const ORDERS = new Set(["pre", "normal", "post"]);+const ROUTES = new Set(["foreign", "native", "all"]);++export const MCP_NO_ISOLATION_LINE =+ "hook modules not loaded by the MCP server: this platform cannot keep hook output off the MCP protocol stream";++export interface LoadError {+ /** The module path as configured. */+ module: string;+ reason: string;+}++export interface LoadResult {+ hooks: UserHookInput[];+ errors: LoadError[];+}++export interface LoadOptions {+ /** `hooks.modules`, in order. */+ modules: ReadonlyArray<string> | undefined;+ /** Directory relative paths resolve against: the active config file's. */+ configDir: string;+ hostMode: HostMode;+ /** Defaults to LOAD_TIMEOUT_MS; tests shorten it. */+ loadTimeoutMs?: number;+ /** Defaults to stderr through `logStderr`. */+ warn?: WarnSink;+}++/* ───────────── virtual module ───────────── */++let virtualModuleRegistered = false;++/**+ * Register `claudish/hooks` → the host's own public exports. Idempotent; runs+ * before the first user import.+ */+export function registerHooksVirtualModule(): void {+ if (virtualModuleRegistered) return;+ virtualModuleRegistered = true;+ const exports = {+ HOOK_API_VERSION: publicApi.HOOK_API_VERSION,+ defineHook: publicApi.defineHook,+ act: publicApi.act,+ };+ Bun.plugin({+ name: "claudish-hooks-virtual-module",+ setup(build) {+ build.module("claudish/hooks", () => ({ exports, loader: "object" }));+ },+ });+}++/* ───────────── paths ───────────── */++/** Absolute, `~` / `~/…`, or relative to the config file's directory. */+export function resolveModulePath(raw: string, configDir: string): string {+ if (raw === "~") return homedir();+ if (raw.startsWith("~/")) return resolve(homedir(), raw.slice(2));+ return isAbsolute(raw) ? resolve(raw) : resolve(configDir, raw);+}++/** A module's name in hook ids: its basename without the extension. */+export function moduleName(absPath: string): string {+ const base = basename(absPath);+ const dot = base.lastIndexOf(".");+ return dot > 0 ? base.slice(0, dot) : base;+}++/* ───────────── shape check ───────────── */++function isFn(v: unknown): v is (...a: unknown[]) => unknown {+ return typeof v === "function";+}++function isAsyncFunction(v: unknown): boolean {+ return (+ isFn(v) && (v as { constructor?: { name?: string } }).constructor?.name === "AsyncFunction"+ );+}++/**+ * Check one exported definition. Returns the reason it is rejected, or null.+ * The apiVersion check comes first and has its own exact message.+ */+function definitionProblem(def: Record<string, unknown>): string | null {+ if (typeof def.id !== "string" || def.id.length === 0) return "id is missing";+ if (def.id.length > MAX_ID_LENGTH) return `id is longer than ${MAX_ID_LENGTH} characters`;+ if (!ID_PATTERN.test(def.id)) return `id "${def.id}" does not match ${ID_PATTERN.source}`;+ if (def.description !== undefined && typeof def.description !== "string") {+ return "description must be a string";+ }+ if (def.defaultSeverity !== undefined && !SEVERITIES.has(def.defaultSeverity as string)) {+ return 'defaultSeverity must be "off", "warn" or "fix"';+ }+ if (def.order !== undefined && !ORDERS.has(def.order as string)) {+ return 'order must be "pre", "normal" or "post"';+ }+ if (def.routes !== undefined && !ROUTES.has(def.routes as string)) {+ return 'routes must be "foreign", "native" or "all"';+ }+ if (def.models !== undefined) {+ const ok =+ (typeof def.models === "string" && def.models.length > 0) ||+ (Array.isArray(def.models) &&+ def.models.length > 0 &&+ def.models.every((m) => typeof m === "string" && m.length > 0));+ if (!ok) return "models must be a glob string or a non-empty array of glob strings";+ }+ if (+ def.timeoutMs !== undefined &&+ (typeof def.timeoutMs !== "number" || !Number.isFinite(def.timeoutMs) || def.timeoutMs <= 0)+ ) {+ return "timeoutMs must be a positive number";+ }++ let handlers = 0;+ if (def.on !== undefined) {+ if (!def.on || typeof def.on !== "object" || Array.isArray(def.on)) {+ return "on must be an object";+ }+ const on = def.on as Record<string, unknown>;+ for (const key of Object.keys(on)) {+ if (on[key] === undefined) continue;+ if (!ON_KEYS.has(key)) return `on.${key} is not a hook event`;+ handlers++;+ }+ for (const key of ON_FUNCTION_KEYS) {+ if (on[key] !== undefined && !isFn(on[key])) return `on.${key} must be a function`;+ }+ if (on.toolCall !== undefined) {+ const tc = on.toolCall as Record<string, unknown>;+ if (!tc || typeof tc !== "object") return "on.toolCall must be an object";+ if (+ !Array.isArray(tc.tools) ||+ tc.tools.length === 0 ||+ !tc.tools.every((t) => typeof t === "string" && t.length > 0)+ ) {+ return "on.toolCall.tools must be a non-empty array of tool names";+ }+ if (!isFn(tc.handle)) return "on.toolCall.handle must be a function";+ if (tc.armed !== undefined && !isFn(tc.armed)) return "on.toolCall.armed must be a function";+ if (tc.observe !== undefined && typeof tc.observe !== "boolean") {+ return "on.toolCall.observe must be a boolean";+ }+ }+ if (on.responseRewrite !== undefined) {+ const rr = on.responseRewrite as Record<string, unknown>;+ if (!rr || typeof rr !== "object") return "on.responseRewrite must be an object";+ if (!isFn(rr.handle)) return "on.responseRewrite.handle must be a function";+ if (rr.claims !== undefined && !isFn(rr.claims)) {+ return "on.responseRewrite.claims must be a function";+ }+ }+ }++ if (def.raw !== undefined) {+ if (def.unsafe !== true) return "raw requires unsafe: true";+ if (!def.raw || typeof def.raw !== "object" || Array.isArray(def.raw)) {+ return "raw must be an object";+ }+ const raw = def.raw as Record<string, unknown>;+ for (const key of Object.keys(raw)) {+ if (raw[key] === undefined) continue;+ if (!RAW_KEYS.has(key)) return `raw.${key} is not a raw stage`;+ if (!isFn(raw[key])) return `raw.${key} must be a function`;+ handlers++;+ }+ if (isAsyncFunction(raw.providerChunk)) {+ return "raw.providerChunk must be synchronous (it runs on the parser's loop)";+ }+ } else if (def.unsafe !== undefined && def.unsafe !== true) {+ return "unsafe must be true or absent";+ }++ if (handlers === 0) return "declares no handler in on or raw";+ return null;+}++/* ───────────── loading ───────────── */++let mcpRefusalPrinted = false;++/** Race an import against the load timeout. */+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error(`load timed out after ${ms} ms`)), ms);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/**+ * Load every configured user module, in order.+ *+ * In host mode `mcp`, user modules load only when `isolateProtocolStdout()` is+ * active: without descriptor isolation, nothing can keep a hook's output off+ * the JSON-RPC stream, so the MCP server runs built-in hooks only and says so+ * once per process.+ */+export async function loadUserHooks(opts: LoadOptions): Promise<LoadResult> {+ const warn = opts.warn ?? ((line: string) => logStderr(line));+ const modules = opts.modules ?? [];+ const result: LoadResult = { hooks: [], errors: [] };+ if (modules.length === 0) return result;++ if (opts.hostMode === "mcp" && protocolIsolation()?.active !== true) {+ if (!mcpRefusalPrinted) {+ mcpRefusalPrinted = true;+ warn(MCP_NO_ISOLATION_LINE);+ }+ return result;+ }++ registerHooksVirtualModule();+ const timeoutMs = opts.loadTimeoutMs ?? LOAD_TIMEOUT_MS;+ const byName = new Map<string, string>();++ for (const [moduleIndex, configured] of modules.entries()) {+ const abs = resolveModulePath(configured, opts.configDir);+ const name = moduleName(abs);+ const fail = (reason: string, line: string) => {+ result.errors.push({ module: configured, reason });+ warn(line);+ };++ const earlier = byName.get(name);+ if (earlier !== undefined) {+ fail(+ `its name "${name}" is already used by ${earlier}`,+ `hook module ${configured} skipped: its name "${name}" is already used by ${earlier}; rename one`+ );+ continue;+ }+ byName.set(name, configured);++ let mod: Record<string, unknown>;+ try {+ mod = (await runImportInScope(configured, () =>+ withTimeout(import(pathToFileURL(abs).href), timeoutMs)+ )) as Record<string, unknown>;+ } catch (err) {+ const reason = errorText(err);+ fail(reason, `hook module ${configured} skipped: ${reason}`);+ continue;+ }++ const exported = mod?.default;+ if (exported === undefined) {+ fail("no default export", `hook module ${configured} skipped: no default export`);+ continue;+ }+ const defs = Array.isArray(exported) ? exported : [exported];+ const seen = new Set<string>();++ for (const [exportIndex, candidate] of defs.entries()) {+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {+ fail(+ `export #${exportIndex} is not a hook definition`,+ `hook module ${configured} skipped export #${exportIndex}: not a hook definition`+ );+ continue;+ }+ const def = candidate as Record<string, unknown>;+ const label = typeof def.id === "string" && def.id.length > 0 ? def.id : `#${exportIndex}`;+ const reject = (reason: string) =>+ fail(`${label}: ${reason}`, `hook ${configured}#${label}: ${reason}`);++ if (def.apiVersion !== publicApi.HOOK_API_VERSION) {+ reject(+ `apiVersion ${String(def.apiVersion)} is not supported (this claudish supports ${publicApi.HOOK_API_VERSION})`+ );+ continue;+ }+ const problem = definitionProblem(def);+ if (problem) {+ reject(problem);+ continue;+ }++ const id = `hook:${name}/${def.id as string}`;+ if (seen.has(id)) {+ warn(`hook ${configured}#${label}: duplicate id ${id}, keeping the first`);+ result.errors.push({ module: configured, reason: `${label}: duplicate id ${id}` });+ continue;+ }+ seen.add(id);++ if (def.unsafe === true) {+ warn(+ `hook ${id} is UNSAFE (raw middleware): it receives live request and response objects`+ );+ }+ result.hooks.push({+ id,+ module: abs,+ moduleIndex,+ exportIndex,+ def: candidate as unknown as HookDefinition,+ });+ }+ }+ return result;+}++/** Test seam: let the once-per-process `mcp` refusal line print again. */+export function resetLoaderForTests(): void {+ mcpRefusalPrinted = false;+}diff --git a/packages/cli/src/hooks/output-capture.test.ts b/packages/cli/src/hooks/output-capture.test.tsnew file mode 100644index 00000000..357fcb7a--- /dev/null+++ b/packages/cli/src/hooks/output-capture.test.ts@@ -0,0 +1,110 @@+import { afterEach, describe, expect, it } from "bun:test";+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { MCP_NO_ISOLATION_LINE } from "./loader.js";+import { currentHookLabel, runInHookScope, setCaptureSinkForTests } from "./output-capture.js";++const HELPERS = join(import.meta.dir, "test-helpers");+const dirs: string[] = [];+function tempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-hooks-capture-"));+ dirs.push(dir);+ return dir;+}+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe("runInHookScope (in process)", () => {+ it("attributes console and stream writes inside the scope, and nothing outside it", async () => {+ const lines: string[] = [];+ const previous = setCaptureSinkForTests((l) => lines.push(l));+ try {+ expect(currentHookLabel()).toBeNull();+ runInHookScope("hook:m/a", () => {+ console.log("in %s", "scope");+ process.stderr.write("err-write\n");+ expect(currentHookLabel()).toBe("hook:m/a");+ });+ await runInHookScope("hook:m/b", async () => {+ await Bun.sleep(1);+ await new Promise<void>((r) =>+ setTimeout(() => {+ console.warn("after timer");+ r();+ }, 1)+ );+ });+ expect(currentHookLabel()).toBeNull();+ expect(lines).toEqual([+ "[hook hook:m/a] in scope",+ "[hook hook:m/a] err-write",+ "[hook hook:m/b] after timer",+ ]);+ } finally {+ setCaptureSinkForTests(previous);+ }+ });+});++describe("isolateProtocolStdout (spawned process)", () => {+ it("X-11: an unbindable libc leaves stdout untouched and the MCP server loads no user module", async () => {+ const dir = tempDir();+ const mod = join(dir, "user.ts");+ writeFileSync(mod, `export default { apiVersion: 1, id: "u", on: { request: () => [] } };`);+ const proc = Bun.spawn(["bun", join(HELPERS, "capture-child.ts"), "mcp-unbound", mod], {+ cwd: dir,+ stdout: "pipe",+ stderr: "pipe",+ });+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ expect(await proc.exited).toBe(0);+ expect(stdout).toBe("");+ const report = JSON.parse(stderr.slice(stderr.indexOf("REPORT ") + 7).split("\n")[0] ?? "{}");+ expect(report.isolation).toEqual({ active: false, sameAsStdout: true });+ expect(report.hooks).toEqual([]);+ const refusals = stderr.split("\n").filter((l) => l === `[claudish] ${MCP_NO_ISOLATION_LINE}`);+ expect(refusals.length).toBe(1);+ });++ it(+ "X-12: the protocol writer is the only thing on stdout, and a 4 MiB frame survives a late reader",+ async () => {+ const dir = tempDir();+ const size = 4 * 1024 * 1024;+ const proc = Bun.spawn(["bun", join(HELPERS, "isolate-child.ts"), String(size)], {+ cwd: dir,+ stdout: "pipe",+ stderr: "pipe",+ });+ const stderrText = new Response(proc.stderr).text();+ await Bun.sleep(1_000); // the reader starts late, so the pipe fills+ const stdout = Buffer.from(await new Response(proc.stdout).arrayBuffer());+ expect(await proc.exited).toBe(0);+ const stderr = await stderrText;++ expect(stderr).toContain("ACTIVE true");+ expect(stderr).toContain("CALLBACK");+ expect(stdout.length).toBe(size);+ expect(stdout[0]).toBe("{".charCodeAt(0));+ expect(stdout.subarray(size - 2).toString()).toBe("}\n");+ expect(stdout.includes("NOISE")).toBe(false);+ // Direct descriptor writes land on stderr.+ expect(stderr).toContain("NOISE-FD");+ expect(stderr).toContain("NOISE-BUNWRITE");++ // Stdout-bound console calls and process.stdout.write go to the debug log.+ const logs = readdirSync(join(dir, "logs"));+ const log = readFileSync(join(dir, "logs", logs[0] as string), "utf8");+ expect(log).toContain("[stdout] NOISE-CONSOLE");+ expect(log).toContain("[stdout] NOISE-INFO");+ expect(log).toContain("[stdout] NOISE-WRITE");+ expect(log).toContain("[hook hook:x/y] SCOPED-CONSOLE");+ },+ { timeout: 20_000 }+ );+});diff --git a/packages/cli/src/hooks/output-capture.ts b/packages/cli/src/hooks/output-capture.tsnew file mode 100644index 00000000..c14eb1ab--- /dev/null+++ b/packages/cli/src/hooks/output-capture.ts@@ -0,0 +1,302 @@+/**+ * Hook output capture, and protocol-stdout isolation for the MCP server.+ *+ * Two layers with different jobs:+ *+ * 1. **The hook scope** (`AsyncLocalStorage`) is for ATTRIBUTION. Every module+ * import and every handler call runs inside it. While it is active,+ * `console.*` and `process.stdout`/`stderr.write` go to claudish's debug log,+ * prefixed `[hook <label>]`, or are dropped when the debug log is off. Calls+ * outside the scope — all of claudish's own code — are untouched. Timers and+ * promise continuations a handler schedules inherit the scope.+ *+ * Measured on Bun 1.4.0: the scope does NOT reach a module's top-level code+ * during `import()` (module evaluation runs outside the caller's async+ * context), and stack attribution cannot replace it (JSC's proper tail calls+ * drop the callback's frame). So an import runs in an IMPORT WINDOW: while it+ * is in flight, unscoped writes are attributed to the module being imported,+ * and timers registered during the window are bound to its scope. Imports are+ * serial, so the window names one module at a time. Anything else claudish+ * writes inside that window (it is short, and loading is awaited at startup+ * before any handler exists) lands in the debug log too.+ *+ * A callback the scope does not reach still runs unscoped: a listener a hook+ * registers at import and claudish's own I/O emits later (`process.stdin`+ * `data`, a signal). That is why the scope is never relied on for protocol+ * safety.+ *+ * 2. **`isolateProtocolStdout()`** is for PROTOCOL SAFETY in `mcp` mode, where+ * stdout is the JSON-RPC channel. It is the first statement of the MCP entry.+ * Through `bun:ffi` on libc it takes a private duplicate of descriptor 1 for+ * the protocol writer and points descriptor 1 at stderr, so every other+ * route — Bun's native `console.log`, `process.stdout.write`,+ * `fs.writeSync(1, …)`, `Bun.write(Bun.stdout, …)`, inheriting children —+ * lands on stderr. On top of that, stdout-bound `console` methods and+ * `process.stdout.write` are diverted process-wide to the debug log.+ * Where the libc symbols cannot be bound, it changes nothing and reports+ * `active: false`; the loader then loads no user module in `mcp` mode.+ */++import { AsyncLocalStorage } from "node:async_hooks";+import { Writable } from "node:stream";+import { format, inspect } from "node:util";+import { log } from "../logger.js";++interface ScopeStore {+ label: string;+}++const scope = new AsyncLocalStorage<ScopeStore>();++/** Label of the module whose import is in flight, or null. */+let importLabel: string | null = null;++/** True in `mcp` mode once stdout is isolated: unscoped stdout writes go to the debug log. */+let stdoutDiverted = false;++let installed = false;++/** Where captured text goes. Replaceable for tests. */+let sink: (line: string) => void = (line) => log(line);++/** The label in force for a write made right now, or null when it is claudish's own. */+export function currentHookLabel(): string | null {+ return scope.getStore()?.label ?? importLabel;+}++function emit(label: string, text: string): void {+ const trimmed = text.endsWith("\n") ? text.slice(0, -1) : text;+ sink(`[${label}] ${trimmed}`);+}++function chunkToText(chunk: unknown, encoding?: unknown): string {+ if (typeof chunk === "string") return chunk;+ if (chunk instanceof Uint8Array) {+ return Buffer.from(chunk).toString(+ typeof encoding === "string" ? (encoding as BufferEncoding) : "utf8"+ );+ }+ return String(chunk);+}++const STDOUT_CONSOLE = ["log", "info", "debug", "dir", "table"] as const;+const STDERR_CONSOLE = ["warn", "error"] as const;+type ConsoleMethod = (typeof STDOUT_CONSOLE)[number] | (typeof STDERR_CONSOLE)[number];++function formatConsole(method: ConsoleMethod, args: unknown[]): string {+ if (method === "dir") return inspect(args[0], (args[1] as object | undefined) ?? {});+ if (method === "table") return inspect(args[0]);+ return format(...args);+}++/**+ * Patch `console.*` and both stream writers once per process. Each replacement+ * checks the scope at call time, so outside a hook (and outside `mcp`+ * diversion) the original runs with the original arguments.+ */+function install(): void {+ if (installed) return;+ installed = true;++ const con = console as unknown as Record<ConsoleMethod, (...a: unknown[]) => void>;+ for (const method of [...STDOUT_CONSOLE, ...STDERR_CONSOLE]) {+ const original = con[method].bind(console);+ const stdoutBound = (STDOUT_CONSOLE as readonly string[]).includes(method);+ con[method] = (...args: unknown[]) => {+ const label = currentHookLabel();+ if (label !== null) return emit(`hook ${label}`, formatConsole(method, args));+ if (stdoutDiverted && stdoutBound) return emit("stdout", formatConsole(method, args));+ return original(...args);+ };+ }++ const patchWrite = (stream: NodeJS.WriteStream, isStdout: boolean) => {+ const original = stream.write.bind(stream) as (...a: unknown[]) => boolean;+ // biome-ignore lint/suspicious/noExplicitAny: Node's overloaded write signature+ (stream as any).write = (chunk: unknown, encoding?: unknown, callback?: unknown): boolean => {+ const label = currentHookLabel();+ const diverted = isStdout && stdoutDiverted;+ if (label === null && !diverted) return original(chunk, encoding, callback);+ emit(label !== null ? `hook ${label}` : "stdout", chunkToText(chunk, encoding));+ const cb = typeof encoding === "function" ? encoding : callback;+ if (typeof cb === "function") queueMicrotask(() => (cb as () => void)());+ return true;+ };+ };+ patchWrite(process.stdout, true);+ patchWrite(process.stderr, false);+}++/**+ * Run `fn` inside a hook's scope. `label` is the effective hook id (`[hook <id>]`+ * in the debug log). Synchronous throws propagate; the caller isolates them.+ */+export function runInHookScope<T>(label: string, fn: () => T): T {+ install();+ return scope.run({ label }, fn);+}++type TimerFn = (cb: (...a: unknown[]) => void, ...rest: unknown[]) => unknown;++/** Bind timer callbacks registered during the window to the module's scope. */+function bindTimers(label: string): () => void {+ const g = globalThis as unknown as Record<string, TimerFn | undefined>;+ const names = ["setTimeout", "setInterval", "setImmediate", "queueMicrotask"] as const;+ const saved = names.map((name) => [name, g[name]] as const);+ for (const [name, original] of saved) {+ if (typeof original !== "function") continue;+ const wrapped: TimerFn = (cb, ...rest) =>+ original(+ typeof cb === "function" ? (...a: unknown[]) => scope.run({ label }, () => cb(...a)) : cb,+ ...rest+ );+ // Keep `setTimeout[util.promisify.custom]` and friends reachable.+ Object.setPrototypeOf(wrapped, original);+ g[name] = wrapped;+ }+ return () => {+ for (const [name, original] of saved) g[name] = original;+ };+}++/**+ * Run a module import inside the import window (see the header). `label` is the+ * configured module path (`[hook <module>]` in the debug log). The window closes+ * when `fn` settles — on a load timeout the caller races `fn` and the window+ * closes at the race, so an import still hanging afterwards runs unscoped.+ */+export async function runImportInScope<T>(label: string, fn: () => Promise<T>): Promise<T> {+ install();+ const previous = importLabel;+ importLabel = label;+ const restoreTimers = bindTimers(label);+ try {+ return await scope.run({ label }, fn);+ } finally {+ restoreTimers();+ importLabel = previous;+ }+}++/* ───────────── protocol stdout (mcp mode) ───────────── */++export interface ProtocolStdout {+ /** false → stdout untouched; mcp mode then loads no user module */+ active: boolean;+ /** the only writer of the real stdout; process.stdout when inactive */+ protocolOut: Writable;+ /** why isolation is inactive */+ reason?: string;+}++export interface LibcBinding {+ dup(fd: number): number;+ dup2(from: number, to: number): number;+}++let isolation: ProtocolStdout | null = null;++/** The isolation result of this process, or null when `isolateProtocolStdout()` never ran. */+export function protocolIsolation(): ProtocolStdout | null {+ return isolation;+}++/** libc through `bun:ffi`. Throws where no binding exists (Windows, unknown libc). */+function bindLibc(): LibcBinding {+ const library =+ process.platform === "darwin"+ ? "libSystem.B.dylib"+ : process.platform === "linux"+ ? "libc.so.6"+ : null;+ if (!library) throw new Error(`no libc binding for platform ${process.platform}`);+ // Required lazily: `bun:ffi` is only needed in mcp mode, and only here.+ const { dlopen, FFIType } = require("bun:ffi") as typeof import("bun:ffi");+ const lib = dlopen(library, {+ dup: { args: [FFIType.i32], returns: FFIType.i32 },+ dup2: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },+ });+ return {+ dup: (fd) => lib.symbols.dup(fd) as number,+ dup2: (from, to) => lib.symbols.dup2(from, to) as number,+ };+}++/**+ * A `Writable` over a private descriptor. Each frame goes to a Bun `FileSink`,+ * and the write callback fires when its `flush()` settles, so a slow reader+ * applies the caller's `drain` backpressure instead of growing memory.+ */+function protocolWriter(fd: number): Writable {+ const fileSink = Bun.file(fd).writer();+ return new Writable({+ write(chunk: Buffer, _encoding, callback) {+ try {+ fileSink.write(chunk);+ const flushed = fileSink.flush();+ if (flushed instanceof Promise) {+ flushed.then(+ () => callback(),+ (err: unknown) => callback(err instanceof Error ? err : new Error(String(err)))+ );+ } else {+ callback();+ }+ } catch (err) {+ callback(err instanceof Error ? err : new Error(String(err)));+ }+ },+ final(callback) {+ try {+ const ended = fileSink.end();+ if (ended instanceof Promise) ended.then(() => callback(), callback);+ else callback();+ } catch (err) {+ callback(err instanceof Error ? err : new Error(String(err)));+ }+ },+ });+}++/**+ * Hand descriptor 1 to the MCP protocol writer alone. `mcp` mode only;+ * idempotent. `bind` replaces the libc binding, for tests.+ */+export function isolateProtocolStdout(opts?: { bind?: () => LibcBinding }): ProtocolStdout {+ if (isolation) return isolation;++ const inactive = (reason: string): ProtocolStdout => {+ isolation = { active: false, protocolOut: process.stdout, reason };+ return isolation;+ };++ let libc: LibcBinding;+ try {+ libc = (opts?.bind ?? bindLibc)();+ } catch (err) {+ return inactive(err instanceof Error ? err.message : String(err));+ }++ let privateFd: number;+ try {+ privateFd = libc.dup(1);+ if (privateFd < 0) return inactive("dup(1) failed");+ if (libc.dup2(2, 1) < 0) return inactive("dup2(2, 1) failed");+ } catch (err) {+ return inactive(err instanceof Error ? err.message : String(err));+ }++ install();+ stdoutDiverted = true;+ isolation = { active: true, protocolOut: protocolWriter(privateFd) };+ return isolation;+}++/* ───────────── test seams ───────────── */++/** Redirect captured lines (default: the debug log). Returns the previous sink. */+export function setCaptureSinkForTests(next: (line: string) => void): (line: string) => void {+ const previous = sink;+ sink = next;+ return previous;+}diff --git a/packages/cli/src/hooks/public.test.ts b/packages/cli/src/hooks/public.test.tsnew file mode 100644index 00000000..1f5c492a--- /dev/null+++ b/packages/cli/src/hooks/public.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from "bun:test";+import { readFileSync, readdirSync, statSync } from "node:fs";+import { join, relative } from "node:path";+import { HOOK_API_VERSION, act, defineHook } from "./public.js";++describe("claudish/hooks public exports", () => {+ it("is version 1", () => {+ expect(HOOK_API_VERSION).toBe(1);+ });++ it("defineHook is the identity", () => {+ const hook = { apiVersion: 1, id: "x", on: { request: () => [] } } as const;+ expect(defineHook(hook)).toBe(hook);+ });++ it("act constructors equal the object literals", () => {+ expect(act.injectSystemNote("n")).toEqual({ type: "injectSystemNote", text: "n" });+ expect(act.appendUserText("u")).toEqual({ type: "appendUserText", text: "u" });+ expect(act.replaceMessageText("a", "b")).toEqual({+ type: "replaceMessageText",+ find: "a",+ replace: "b",+ });+ expect(+ act.replaceMessageText("a", "b", { regex: true, flags: "gi", roles: ["assistant"] })+ ).toEqual({+ type: "replaceMessageText",+ find: "a",+ replace: "b",+ regex: true,+ flags: "gi",+ roles: ["assistant"],+ });+ expect(act.removeMessageText("a")).toEqual({ type: "removeMessageText", find: "a" });+ expect(act.rewriteToolDescription("T", " x")).toEqual({+ type: "rewriteToolDescription",+ tool: "T",+ append: " x",+ });+ expect(act.replaceToolDescription("T", "d")).toEqual({+ type: "replaceToolDescription",+ tool: "T",+ description: "d",+ });+ expect(act.replaceToolSchema("T", { type: "object" })).toEqual({+ type: "replaceToolSchema",+ tool: "T",+ inputSchema: { type: "object" },+ });+ expect(act.removeTool("T")).toEqual({ type: "removeTool", tool: "T" });+ expect(act.repairToolArgs({ a: 1 }, "r")).toEqual({+ type: "repairToolArgs",+ args: { a: 1 },+ reason: "r",+ });+ expect(act.appendText("t")).toEqual({ type: "appendText", text: "t" });+ expect(act.prependText("t")).toEqual({ type: "prependText", text: "t" });+ expect(act.replaceText("a", "b", { regex: true })).toEqual({+ type: "replaceText",+ find: "a",+ replace: "b",+ regex: true,+ });+ expect(act.removeText("a")).toEqual({ type: "removeText", find: "a" });+ expect(act.injectUserTurn("go")).toEqual({ type: "injectUserTurn", text: "go" });+ expect(act.annotateTurn("k", { v: [1] })).toEqual({+ type: "annotateTurn",+ key: "k",+ value: { v: [1] },+ });+ expect(act.warn("w")).toEqual({ type: "warn", message: "w" });+ });+});++/** Every .ts file under `dir`, recursively. */+function sources(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) return sources(path);+ return name.endsWith(".ts") ? [path] : [];+ });+}++const IMPORT =+ /(?:^|\n)\s*(?:import|export)[^;]*?from\s+["']([^"']+)["']|import\(\s*["']([^"']+)["']\s*\)/g;++function importsOf(path: string): string[] {+ const text = readFileSync(path, "utf8");+ return [...text.matchAll(IMPORT)].map((m) => (m[1] ?? m[2]) as string);+}++describe("module boundaries", () => {+ const hooksDir = import.meta.dir;++ it("public.ts imports nothing", () => {+ expect(importsOf(join(hooksDir, "public.ts"))).toEqual([]);+ });++ it("nothing under hooks/ imports behavior/ or middleware/", () => {+ const offenders = sources(hooksDir).flatMap((file) =>+ importsOf(file)+ .filter((spec) => /(^|\/)(behavior|middleware)\//.test(spec))+ .map((spec) => `${relative(hooksDir, file)} → ${spec}`)+ );+ expect(offenders).toEqual([]);+ });++ it("the import scanner sees a real import (control)", () => {+ expect(importsOf(join(hooksDir, "engine.ts"))).toContain("./actions.js");+ });+});diff --git a/packages/cli/src/hooks/public.ts b/packages/cli/src/hooks/public.tsnew file mode 100644index 00000000..fa3f01c4--- /dev/null+++ b/packages/cli/src/hooks/public.ts@@ -0,0 +1,508 @@+/**+ * claudish/hooks — the public hook contract.+ *+ * Everything a hook author can import lives here, and nothing else does. This+ * file imports nothing from the rest of claudish and has no side effects, so it+ * can be built on its own into `dist/hooks.js` + `dist/hooks.d.ts` and served to+ * user modules as the `claudish/hooks` virtual module (see `loader.ts`).+ *+ * Every internal hooks module takes its types from here, so the contract has a+ * single source.+ *+ * ## Process isolation+ *+ * A hook module's top-level state is PER PROCESS. In the interactive launcher,+ * proxy events (`request` … `responseEnd`, raw) and session events+ * (`sessionStart` … `sessionEnd`) run in one process. In `create_session` and+ * team children they do not: proxy events run in the pane child, and session+ * events run in the MCP server or the CLI process that drives the pane. Pass+ * per-turn data from a proxy event to `sessionIdle` with `annotateTurn`, never+ * with module variables.+ *+ * ## Output+ *+ * Log with `ctx.log`. `console.*` and `process.stdout`/`stderr` writes made by a+ * hook are routed to claudish's debug log, never to the terminal or the MCP+ * protocol stream.+ */++export const HOOK_API_VERSION = 1;++export type Severity = "off" | "warn" | "fix";+export type HookOrder = "pre" | "normal" | "post";+/** native = RouteInfo.native true; foreign = RouteInfo.native false; all = both */+export type RouteScope = "foreign" | "native" | "all";+export type HostMode = "interactive" | "pane-child" | "serve" | "mcp" | "other";++export type JsonValue =+ | string+ | number+ | boolean+ | null+ | ReadonlyArray<JsonValue>+ | { readonly [k: string]: JsonValue };++/* ───────────── facts ───────────── */++export interface HarnessFacts {+ planModeActive: boolean;+ planFilePath?: string;+ planDir?: string;+ /** Claude Code session id from request metadata */+ sessionId?: string;+ /** empty = no listing found, not "no skills" */+ skills?: ReadonlyArray<{ name: string; description: string }>;+}++export interface RouteInfo {+ /** bare model name the handler serves, e.g. "glm-5" */+ modelId: string;+ /** claudish provider name, e.g. "openrouter"; "anthropic" for native */+ provider: string;+ /**+ * true when the request is served by the native Anthropic handler, OR when+ * !forceForeignModel && (/^claude[-.]/i.test(modelId) || provider === "anthropic")+ * where forceForeignModel is the provider profile's opt-in override. This is the exact+ * rule the plan-mode built-in has always used (a claude-* uid on an aggregator that sets+ * forceForeignModel is foreign).+ */+ native: boolean;+}++export interface ClaudeTool {+ name: string;+ description?: string;+ input_schema?: unknown;+}++/** A Claude-format content block. Only `text` blocks are editable by closed actions. */+export type ClaudeContentBlock =+ | { type: "text"; text: string }+ | { type: "tool_use"; id: string; name: string; input: unknown }+ | { type: "tool_result"; tool_use_id: string; content?: unknown; is_error?: boolean }+ | { type: "thinking"; thinking: string; signature?: string }+ | { type: string; [k: string]: unknown };++export interface ClaudeMessage {+ role: "user" | "assistant";+ content: string | ReadonlyArray<ClaudeContentBlock>;+}++export interface RequestFacts {+ /** as Claude Code asked for it */+ model: string;+ stream: boolean;+ /** system prompt flattened to text */+ systemText: string;+ /** read-only view; change it through actions */+ messages: ReadonlyArray<ClaudeMessage>;+ /** read-only view; change it through actions */+ tools: ReadonlyArray<ClaudeTool>;+}++/** Which session a proxy event belongs to, when claudish knows. */+export interface ProxySessionRef {+ kind: SessionKind;+ id: string;+ role: "slot" | "judge" | null;+}++interface BaseContext {+ readonly hookId: string;+ /** "warn" or "fix" (an "off" hook is never called) */+ readonly severity: Severity;+ /** writes to claudish's debug log; never to the terminal */+ log(message: string): void;+ /** aborted when this hook's timeout elapses */+ readonly signal: AbortSignal;+}++export interface ProxyContext extends BaseContext {+ readonly host: { mode: HostMode };+ readonly route: RouteInfo;+ readonly request: RequestFacts;+ readonly harness: HarnessFacts;+ readonly session: ProxySessionRef | null;+}++export interface RequestContext extends ProxyContext {+ readonly event: "request";+}++export interface ToolCallContext extends ProxyContext {+ readonly event: "toolCall";+ readonly tool: {+ id: string;+ name: string;+ args: Readonly<Record<string, unknown>>;+ rawArgs: string;+ };+}++export type ResponseBlock =+ | { type: "text"; text: string }+ | { type: "thinking"; thinking: string }+ | { type: "tool_use"; id: string; name: string; input: unknown }+ | { type: "other"; blockType: string };++export interface ResponseView {+ blocks: ReadonlyArray<ResponseBlock>;+ /** every text block, joined with "\n\n" */+ text: string;+ /** every thinking block, joined with "\n\n" */+ reasoning: string;+ toolNames: ReadonlyArray<string>;+ /** "tool_use" = an intermediate step of a tool loop; the turn continues after the tool runs */+ stopReason: string | null;+}++export interface ResponseRewriteContext extends ProxyContext {+ readonly event: "responseRewrite";+ readonly response: ResponseView;+}+/** response = the final bytes the client received: after any rewrite AND any raw `response` replacement */+export interface ResponseEndContext extends ProxyContext {+ readonly event: "responseEnd";+ readonly response: ResponseView;+}++export type SessionKind = "interactive" | "channel" | "team";++export interface SessionInfo {+ kind: SessionKind;+ /** team only; null otherwise */+ role: "slot" | "judge" | null;+ /** channel: the 8-hex session_id · team: "<run_id>:<slot id>" · interactive: the Claude Code session id */+ id: string;+ claudeSessionId: string | null;+ /** as the caller asked for it */+ model: string;+ cwd: string;+ /** a one-shot session stays "one-shot" through a hook-extended turn chain */+ shape: "interactive" | "one-shot";+ injection: "available" | "unavailable";+}++export interface SessionStartContext extends BaseContext {+ readonly event: "sessionStart";+ readonly session: SessionInfo;+}++export interface TurnAnnotation {+ hookId: string;+ key: string;+ value: JsonValue;+}++export interface SessionIdleContext extends BaseContext {+ readonly event: "sessionIdle";+ readonly session: SessionInfo;+ readonly turn: {+ /** 1-based within the session; a re-woken turn keeps its index */+ index: number;+ /** this turn's assistant text */+ answer: string;+ stopReason: string | null;+ apiError: boolean;+ /** this turn was started by an injection */+ hookCaused: boolean;+ /** annotateTurn actions from this turn's responses, in arrival order */+ annotations: ReadonlyArray<TurnAnnotation>;+ };+ readonly consecutiveHookTurns: number;+ /** caller/human input is queued; an injection returned now will be dropped as stale */+ readonly callerInputPending: boolean;+}++export interface SessionBlockedContext extends BaseContext {+ readonly event: "sessionBlocked";+ readonly session: SessionInfo;+ readonly block: { kind: "question" | "permission"; text: string };+}++export interface SessionEndContext extends BaseContext {+ readonly event: "sessionEnd";+ readonly session: SessionInfo;+ readonly outcome: { state: string; reason: string | null; exitCode: number | null };+}++/* ───────────── actions (closed) ───────────── */++type TextMatch = { find: string; regex?: boolean; flags?: string };+/** default ["user"] */+type MessageRoles = { roles?: ReadonlyArray<"user" | "assistant"> };++// request: system prompt+export type InjectSystemNote = { type: "injectSystemNote"; text: string };+// request: messages+export type AppendUserText = { type: "appendUserText"; text: string };+export type ReplaceMessageText = { type: "replaceMessageText"; replace: string } & TextMatch &+ MessageRoles;+export type RemoveMessageText = { type: "removeMessageText" } & TextMatch & MessageRoles;+// request: tools+export type RewriteToolDescription = {+ type: "rewriteToolDescription";+ tool: string;+ append: string;+};+export type ReplaceToolDescription = {+ type: "replaceToolDescription";+ tool: string;+ description: string;+};+export type ReplaceToolSchema = {+ type: "replaceToolSchema";+ tool: string;+ inputSchema: { type: "object"; [k: string]: unknown };+};+export type RemoveTool = { type: "removeTool"; tool: string };+// toolCall+export type RepairToolArgs = {+ type: "repairToolArgs";+ args: Record<string, unknown>;+ reason: string;+};+// responseRewrite+export type AppendText = { type: "appendText"; text: string };+export type PrependText = { type: "prependText"; text: string };+export type ReplaceText = { type: "replaceText"; replace: string } & TextMatch;+export type RemoveText = { type: "removeText" } & TextMatch;+// responseEnd / session+export type InjectUserTurn = { type: "injectUserTurn"; text: string };+export type AnnotateTurn = { type: "annotateTurn"; key: string; value: JsonValue };+// any+export type Warn = { type: "warn"; message: string };++export type RequestAction =+ | InjectSystemNote+ | AppendUserText+ | ReplaceMessageText+ | RemoveMessageText+ | RewriteToolDescription+ | ReplaceToolDescription+ | ReplaceToolSchema+ | RemoveTool+ | Warn;+export type ToolCallAction = RepairToolArgs | Warn;+export type RewriteAction = AppendText | PrependText | ReplaceText | RemoveText | Warn;+export type ResponseEndAction = InjectSystemNote | InjectUserTurn | AnnotateTurn | Warn;+export type SessionAction = InjectUserTurn | Warn;+export type ObserveAction = Warn;+export type HookAction =+ | RequestAction+ | ToolCallAction+ | RewriteAction+ | ResponseEndAction+ | SessionAction;++// biome-ignore lint/suspicious/noConfusingVoidType: an `async` handler that returns nothing is Promise<void>; `undefined` would reject it+export type HookResult<A> = A[] | void | Promise<A[] | void>;++/* ───────────── handlers ───────────── */++export interface HookHandlers {+ request?(ctx: RequestContext): HookResult<RequestAction>;+ toolCall?: {+ /** tool names whose completed arguments this hook sees; "*" = every tool (costs streaming of all tool input) */+ tools: ReadonlyArray<string>;+ /** synchronous, per request; default true. false = not armed for this request */+ armed?(ctx: RequestContext): boolean;+ /** true = see the call after it was forwarded; can only warn; never holds the stream */+ observe?: boolean;+ handle(ctx: ToolCallContext): HookResult<ToolCallAction>;+ };+ responseRewrite?: {+ /** synchronous, per request, evaluated before the response starts; default true */+ claims?(ctx: RequestContext): boolean;+ handle(ctx: ResponseRewriteContext): HookResult<RewriteAction>;+ };+ responseEnd?(ctx: ResponseEndContext): HookResult<ResponseEndAction>;+ sessionStart?(ctx: SessionStartContext): HookResult<SessionAction>;+ sessionIdle?(ctx: SessionIdleContext): HookResult<SessionAction>;+ sessionBlocked?(ctx: SessionBlockedContext): HookResult<ObserveAction>;+ sessionEnd?(ctx: SessionEndContext): HookResult<ObserveAction>;+}++/* ───────────── raw (unsafe) tier ───────────── */++export interface RawProviderRequestContext {+ readonly hookId: string;+ readonly route: RouteInfo;+ // biome-ignore lint/suspicious/noExplicitAny: the raw tier hands out provider-format objects by contract+ claudeRequest: any; // a clone of the post-request-stage request+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ messages: any[]; // a clone, provider format+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ tools: any[]; // a clone, provider format+}+export interface RawProviderChunkContext {+ readonly hookId: string;+ readonly route: RouteInfo;+ /** A clone of the parsed provider event. Whatever this field holds when the call returns is+ * what the parser reads from then on, so it may be edited in place or replaced. */+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ chunk: any;+ /** The delta object inside `chunk` at call time (Responses wire: `chunk` itself). Edit it in+ * place; assigning a new object to this field has no effect. */+ // biome-ignore lint/suspicious/noExplicitAny: provider format+ delta: any;+ /** per-stream, shared across this hook's chunk calls; never cloned */+ metadata: Map<string, unknown>;+}+export interface RawProviderStreamEndContext {+ readonly hookId: string;+ readonly route: RouteInfo;+ metadata: Map<string, unknown>;+}+export interface RawResponseContext {+ readonly hookId: string;+ readonly route: RouteInfo;+ readonly request: RequestFacts;+ /** A replay of the current Claude-format response (SSE, or JSON for stream:false), read at the+ * hook's own pace. claudish drains the original itself, so leaving this unread delays nothing. */+ response: Response;+}+export interface RawMiddleware {+ /**+ * Receives clones. They replace the live request only when this call returns (or its promise+ * resolves) within its timeout. A throw, a rejection or a timeout discards every change.+ */+ providerRequest?(ctx: RawProviderRequestContext): void | Promise<void>;+ /**+ * MUST be synchronous. Called on the parser's loop, on a clone of the chunk. On a normal return+ * of anything but a thenable, the clone (whatever `ctx.chunk` holds then) is committed: it+ * becomes the object the parser reads, deletions included. On a throw nothing is committed.+ * A declared `async` function is rejected at load. Any other thenable return is an invalid+ * invocation: the clone is discarded even if the hook mutated it before returning, the call is+ * journaled `invalid` (`async_return`) and counts toward the circuit breaker, and a rejection+ * handler is attached, so a rejection is journaled `error` and never becomes an+ * unhandledRejection.+ */+ providerChunk?(ctx: RawProviderChunkContext): void;+ providerStreamEnd?(ctx: RawProviderStreamEndContext): void | Promise<void>;+ /**+ * Return a replacement Response, or nothing to keep the current one. A replacement is read+ * whole and forwarded only when it completes cleanly; on any failure the original is forwarded.+ * The client never sees a partial replacement. A replacement must close within this hook's+ * timeout after the later of this call's return and the end of the original; the original's end+ * never depends on whether `ctx.response` is read.+ */+ // biome-ignore lint/suspicious/noConfusingVoidType: an `async` hook that returns nothing is Promise<void>+ response?(ctx: RawResponseContext): Response | void | Promise<Response | void>;+}++/* ───────────── definition ───────────── */++interface HookBase {+ apiVersion: 1;+ id: string;+ description?: string;+ /** default "fix" for user hooks */+ defaultSeverity?: Severity;+ /** default "normal" */+ order?: HookOrder;+ /** globs on RouteInfo.modelId; default "*"; proxy events only */+ models?: string | ReadonlyArray<string>;+ /** default "all"; proxy events only */+ routes?: RouteScope;+ /** per-handler; clamped to the event's maximum */+ timeoutMs?: number;+ on?: HookHandlers;+}+export interface SafeHook extends HookBase {+ unsafe?: never;+ raw?: never;+}+export interface UnsafeHook extends HookBase {+ unsafe: true;+ raw: RawMiddleware;+}+/**+ * One hook. Module-level state is per process: in `create_session` and team+ * children, proxy events run in the pane child and session events in the MCP+ * server or CLI process. Pass per-turn data from proxy events to `sessionIdle`+ * with `annotateTurn`, never with module variables.+ */+export type HookDefinition = SafeHook | UnsafeHook;++/** Identity function: gives editor type-checking and inference. */+export function defineHook<const H extends HookDefinition>(hook: H): H {+ return hook;+}++type RegexOpts = { regex?: boolean; flags?: string };+type RoleOpts = { roles?: ReadonlyArray<"user" | "assistant"> };++/** Copy only the options that are set, so a constructed action equals the literal. */+function matchOpts(opts: (RegexOpts & RoleOpts) | undefined): RegexOpts & RoleOpts {+ const out: RegexOpts & RoleOpts = {};+ if (opts?.regex !== undefined) out.regex = opts.regex;+ if (opts?.flags !== undefined) out.flags = opts.flags;+ if (opts?.roles !== undefined) out.roles = opts.roles;+ return out;+}++/** Action constructors (plain data; equivalent to writing the object literal). */+export const act: {+ injectSystemNote(text: string): InjectSystemNote;+ appendUserText(text: string): AppendUserText;+ replaceMessageText(+ find: string,+ replace: string,+ opts?: { regex?: boolean; flags?: string; roles?: ReadonlyArray<"user" | "assistant"> }+ ): ReplaceMessageText;+ removeMessageText(+ find: string,+ opts?: { regex?: boolean; flags?: string; roles?: ReadonlyArray<"user" | "assistant"> }+ ): RemoveMessageText;+ rewriteToolDescription(tool: string, append: string): RewriteToolDescription;+ replaceToolDescription(tool: string, description: string): ReplaceToolDescription;+ replaceToolSchema(+ tool: string,+ inputSchema: { type: "object"; [k: string]: unknown }+ ): ReplaceToolSchema;+ removeTool(tool: string): RemoveTool;+ repairToolArgs(args: Record<string, unknown>, reason: string): RepairToolArgs;+ appendText(text: string): AppendText;+ prependText(text: string): PrependText;+ replaceText(+ find: string,+ replace: string,+ opts?: { regex?: boolean; flags?: string }+ ): ReplaceText;+ removeText(find: string, opts?: { regex?: boolean; flags?: string }): RemoveText;+ injectUserTurn(text: string): InjectUserTurn;+ annotateTurn(key: string, value: JsonValue): AnnotateTurn;+ warn(message: string): Warn;+} = {+ injectSystemNote: (text) => ({ type: "injectSystemNote", text }),+ appendUserText: (text) => ({ type: "appendUserText", text }),+ replaceMessageText: (find, replace, opts) => ({+ type: "replaceMessageText",+ find,+ replace,+ ...matchOpts(opts),+ }),+ removeMessageText: (find, opts) => ({ type: "removeMessageText", find, ...matchOpts(opts) }),+ rewriteToolDescription: (tool, append) => ({ type: "rewriteToolDescription", tool, append }),+ replaceToolDescription: (tool, description) => ({+ type: "replaceToolDescription",+ tool,+ description,+ }),+ replaceToolSchema: (tool, inputSchema) => ({ type: "replaceToolSchema", tool, inputSchema }),+ removeTool: (tool) => ({ type: "removeTool", tool }),+ repairToolArgs: (args, reason) => ({ type: "repairToolArgs", args, reason }),+ appendText: (text) => ({ type: "appendText", text }),+ prependText: (text) => ({ type: "prependText", text }),+ replaceText: (find, replace, opts) => ({+ type: "replaceText",+ find,+ replace,+ ...matchOpts(opts),+ }),+ removeText: (find, opts) => ({ type: "removeText", find, ...matchOpts(opts) }),+ injectUserTurn: (text) => ({ type: "injectUserTurn", text }),+ annotateTurn: (key, value) => ({ type: "annotateTurn", key, value }),+ warn: (message) => ({ type: "warn", message }),+};diff --git a/packages/cli/src/hooks/registry.test.ts b/packages/cli/src/hooks/registry.test.tsnew file mode 100644index 00000000..2ca94235--- /dev/null+++ b/packages/cli/src/hooks/registry.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from "bun:test";+import type { HookDefinition, RouteInfo } from "./public.js";+import { type BuiltinHook, HookRegistry, type UserHookInput, eventsOf } from "./registry.js";++const handler = () => [];++function def(id: string, extra: Partial<HookDefinition> = {}): HookDefinition {+ return { apiVersion: 1, id, on: { request: handler }, ...extra } as HookDefinition;+}++function user(id: string, moduleIndex: number, exportIndex: number, extra = {}): UserHookInput {+ return {+ id: `hook:m${moduleIndex}/${id}`,+ module: `/hooks/m${moduleIndex}.ts`,+ moduleIndex,+ exportIndex,+ def: def(id, extra),+ };+}++const foreign: RouteInfo = { modelId: "glm-5", provider: "zai", native: false };+const native: RouteInfo = { modelId: "claude-opus-5", provider: "anthropic", native: true };++describe("HookRegistry effective order", () => {+ it("orders by bucket, then built-ins first, then module position, then export order", () => {+ const builtins: BuiltinHook[] = [def("b/normal"), def("b/post", { order: "post" })];+ const users = [+ user("u1-late", 1, 0),+ user("u0-second", 0, 1),+ user("u0-first", 0, 0),+ user("u1-pre", 1, 1, { order: "pre" }),+ ];+ const reg = new HookRegistry(builtins, users, undefined);+ expect(reg.hooks.map((h) => h.id)).toEqual([+ "hook:m1/u1-pre",+ "b/normal",+ "hook:m0/u0-first",+ "hook:m0/u0-second",+ "hook:m1/u1-late",+ "b/post",+ ]);+ expect(reg.hooks.map((h) => h.source)).toEqual([+ "user",+ "builtin",+ "user",+ "user",+ "user",+ "builtin",+ ]);+ });+});++describe("HookRegistry applicability", () => {+ it("filters proxy events by routes and model globs", () => {+ const reg = new HookRegistry(+ [def("foreign-only", { routes: "foreign" }), def("native-only", { routes: "native" })],+ [user("glm", 0, 0, { models: ["glm-*", "kimi-*"] })],+ undefined+ );+ expect(reg.applicable("request", { route: foreign }).map((a) => a.hook.id)).toEqual([+ "foreign-only",+ "hook:m0/glm",+ ]);+ expect(reg.applicable("request", { route: native }).map((a) => a.hook.id)).toEqual([+ "native-only",+ ]);+ });++ it("drops severity off and resolves model-scoped keys against the route model", () => {+ const reg = new HookRegistry([def("plan-mode/plan-file-path")], [], {+ "plan-mode/*": "off",+ "glm-*:plan-mode/plan-file-path": "warn",+ });+ expect(reg.applicable("request", { route: foreign })).toEqual([+ { hook: reg.hooks[0] as never, severity: "warn" },+ ]);+ expect(reg.applicable("request", { route: { ...foreign, modelId: "kimi-k3" } })).toEqual([]);+ });++ it("defaults user hooks to fix", () => {+ const reg = new HookRegistry([], [user("x", 0, 0)], undefined);+ expect(reg.applicable("request", { route: foreign })[0]?.severity).toBe("fix");+ });++ it("does not filter session events by route; scopes severity by the session model", () => {+ const sessionDef = {+ apiVersion: 1,+ id: "ping",+ routes: "native",+ models: "nothing-*",+ on: { sessionIdle: handler },+ } as HookDefinition;+ const reg = new HookRegistry([], [{ ...user("ping", 0, 0), def: sessionDef }], {+ "gpt-*:hook:m0/ping": "off",+ });+ expect(reg.applicable("sessionIdle", { sessionModel: "glm-5" }).length).toBe(1);+ expect(reg.applicable("sessionIdle", { sessionModel: "gpt-6" }).length).toBe(0);+ });++ it("indexes hooks by every event they declare, raw stages included", () => {+ const raw = {+ apiVersion: 1,+ id: "gemini/thought-signature",+ unsafe: true,+ raw: { providerRequest: handler, providerChunk: handler },+ on: { toolCall: { tools: ["Write"], handle: handler } },+ } as unknown as HookDefinition;+ expect(eventsOf(raw)).toEqual(["toolCall", "raw.providerRequest", "raw.providerChunk"]);+ const reg = new HookRegistry([{ ...raw, statsName: "GeminiThoughtSignature" }], [], undefined);+ expect(reg.has("raw.providerChunk")).toBe(true);+ expect(reg.has("raw.response")).toBe(false);+ expect(reg.hooks[0]?.unsafe).toBe(true);+ expect(reg.hooks[0]?.statsName).toBe("GeminiThoughtSignature");+ });+});diff --git a/packages/cli/src/hooks/registry.ts b/packages/cli/src/hooks/registry.tsnew file mode 100644index 00000000..ab9bded5--- /dev/null+++ b/packages/cli/src/hooks/registry.ts@@ -0,0 +1,223 @@+/**+ * The hook registry: built-in and user hooks in effective order, indexed by+ * event, with applicability (severity ≠ off, `models`, `routes`).+ *+ * Effective order is the order every closed action is applied in, and the+ * order every raw hook runs in: `order` bucket (`pre`, `normal`, `post`), then+ * built-ins before user hooks, then position in `hooks.modules`, then export+ * order within a module. `claudish hooks list` prints exactly this order.+ */++import { globMatches, resolveSeverity } from "./config.js";+import type { HookDefinition, HookOrder, RouteInfo, RouteScope, Severity } from "./public.js";++/** Every point a hook can declare: the closed events plus the four raw stages. */+export type HookEventName =+ | "request"+ | "toolCall"+ | "responseRewrite"+ | "responseEnd"+ | "sessionStart"+ | "sessionIdle"+ | "sessionBlocked"+ | "sessionEnd"+ | "raw.providerRequest"+ | "raw.providerChunk"+ | "raw.providerStreamEnd"+ | "raw.response";++const CLOSED_HANDLER_KEYS = [+ "request",+ "toolCall",+ "responseRewrite",+ "responseEnd",+ "sessionStart",+ "sessionIdle",+ "sessionBlocked",+ "sessionEnd",+] as const;++const RAW_KEYS = ["providerRequest", "providerChunk", "providerStreamEnd", "response"] as const;++/** Proxy events are filtered by `models` and `routes`; session events are not. */+const PROXY_EVENTS: ReadonlySet<HookEventName> = new Set<HookEventName>([+ "request",+ "toolCall",+ "responseRewrite",+ "responseEnd",+ "raw.providerRequest",+ "raw.providerChunk",+ "raw.providerStreamEnd",+ "raw.response",+]);++export function isProxyEvent(event: HookEventName): boolean {+ return PROXY_EVENTS.has(event);+}++/** A built-in hook. Its id carries no `hook:` prefix. */+export type BuiltinHook = HookDefinition & {+ /** Name reported in stats `middleware_names` while this raw built-in is active. */+ statsName?: string;+};++/** A user hook as the loader produced it. */+export interface UserHookInput {+ /** Effective id, `hook:<module basename>/<id>`. */+ id: string;+ /** Absolute module path. */+ module: string;+ /** Position of the module in `hooks.modules`. */+ moduleIndex: number;+ /** Position of the hook in the module's default export. */+ exportIndex: number;+ def: HookDefinition;+}++export interface RegisteredHook {+ /** Effective id: the built-in's own id, or `hook:<module basename>/<id>`. */+ id: string;+ source: "builtin" | "user";+ /** Absolute module path; undefined for a built-in. */+ module?: string;+ def: HookDefinition;+ order: HookOrder;+ defaultSeverity: Severity;+ routes: RouteScope;+ models: ReadonlyArray<string>;+ unsafe: boolean;+ /** Every event this hook declares a handler for, in a fixed order. */+ events: ReadonlyArray<HookEventName>;+ statsName?: string;+}++/** A hook selected for one event, with its resolved severity. */+export interface ApplicableHook {+ hook: RegisteredHook;+ severity: Exclude<Severity, "off">;+}++/** What applicability is judged against. */+export interface ApplicabilityScope {+ /** Proxy events: the route (models, routes, model-scoped severity keys). */+ route?: RouteInfo;+ /** Session events: the model the caller asked for (model-scoped severity keys). */+ sessionModel?: string;+}++const ORDER_RANK: Record<HookOrder, number> = { pre: 0, normal: 1, post: 2 };++/** The events a definition declares, in a fixed order. */+export function eventsOf(def: HookDefinition): HookEventName[] {+ const events: HookEventName[] = [];+ const on = (def.on ?? {}) as Record<string, unknown>;+ for (const key of CLOSED_HANDLER_KEYS) if (on[key] !== undefined) events.push(key);+ const raw = ((def as { raw?: unknown }).raw ?? {}) as Record<string, unknown>;+ for (const key of RAW_KEYS) if (typeof raw[key] === "function") events.push(`raw.${key}`);+ return events;+}++function normalizeModels(models: HookDefinition["models"]): string[] {+ if (models === undefined) return ["*"];+ return typeof models === "string" ? [models] : [...models];+}++function register(+ def: HookDefinition,+ id: string,+ source: RegisteredHook["source"],+ module?: string,+ statsName?: string+): RegisteredHook {+ const hook: RegisteredHook = {+ id,+ source,+ def,+ order: def.order ?? "normal",+ defaultSeverity: def.defaultSeverity ?? "fix",+ routes: def.routes ?? "all",+ models: normalizeModels(def.models),+ unsafe: (def as { unsafe?: unknown }).unsafe === true,+ events: eventsOf(def),+ };+ if (module !== undefined) hook.module = module;+ if (statsName !== undefined) hook.statsName = statsName;+ return hook;+}++export class HookRegistry {+ /** Every hook in effective order. */+ readonly hooks: ReadonlyArray<RegisteredHook>;+ private readonly byEvent = new Map<HookEventName, RegisteredHook[]>();++ constructor(+ builtins: ReadonlyArray<BuiltinHook>,+ users: ReadonlyArray<UserHookInput>,+ private readonly severityMap: Record<string, Severity> | undefined+ ) {+ const ranked = [+ ...builtins.map((def, i) => ({+ hook: register(def, def.id, "builtin", undefined, def.statsName),+ key: [0, 0, i] as const,+ })),+ ...users.map((u) => ({+ hook: register(u.def, u.id, "user", u.module),+ key: [1, u.moduleIndex, u.exportIndex] as const,+ })),+ ];+ ranked.sort(+ (a, b) =>+ ORDER_RANK[a.hook.order] - ORDER_RANK[b.hook.order] ||+ a.key[0] - b.key[0] ||+ a.key[1] - b.key[1] ||+ a.key[2] - b.key[2]+ );+ this.hooks = ranked.map((r) => r.hook);+ for (const hook of this.hooks) {+ for (const event of hook.events) {+ const list = this.byEvent.get(event) ?? [];+ list.push(hook);+ this.byEvent.set(event, list);+ }+ }+ }++ /** Hooks declaring `event`, in effective order, before applicability. */+ declaring(event: HookEventName): ReadonlyArray<RegisteredHook> {+ return this.byEvent.get(event) ?? [];+ }++ /** True when any hook declares `event` at all. */+ has(event: HookEventName): boolean {+ return (this.byEvent.get(event)?.length ?? 0) > 0;+ }++ /** A hook's severity for a model (or unscoped when `modelId` is undefined). */+ severityOf(hook: RegisteredHook, modelId?: string): Severity {+ return resolveSeverity(hook.id, hook.defaultSeverity, this.severityMap, modelId);+ }++ /**+ * Hooks that apply to `event` in this scope, in effective order: severity is+ * not `off`, and for proxy events the route's model matches `models` and its+ * nativeness matches `routes`.+ */+ applicable(event: HookEventName, scope: ApplicabilityScope = {}): ApplicableHook[] {+ const proxy = isProxyEvent(event);+ const modelId = proxy ? scope.route?.modelId : scope.sessionModel;+ const out: ApplicableHook[] = [];+ for (const hook of this.declaring(event)) {+ if (proxy && scope.route && !routeMatches(hook, scope.route)) continue;+ const severity = this.severityOf(hook, modelId);+ if (severity === "off") continue;+ out.push({ hook, severity });+ }+ return out;+ }+}++function routeMatches(hook: RegisteredHook, route: RouteInfo): boolean {+ if (hook.routes === "native" && !route.native) return false;+ if (hook.routes === "foreign" && route.native) return false;+ return hook.models.some((glob) => globMatches(glob, route.modelId));+}diff --git a/packages/cli/src/hooks/sse-codec.test.ts b/packages/cli/src/hooks/sse-codec.test.tsnew file mode 100644index 00000000..a46fa571--- /dev/null+++ b/packages/cli/src/hooks/sse-codec.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "bun:test";+import {+ SseSplitter,+ chunkText,+ encodeUtf8,+ eventJson,+ parseSseFields,+ serializeSseEvent,+} from "./sse-codec.js";++const bytes = (s: string) => new TextEncoder().encode(s);++describe("SseSplitter", () => {+ it("splits complete events and keeps each raw text with its terminator", () => {+ const s = new SseSplitter();+ const events = s.push(+ bytes('event: ping\ndata: {"type":"ping"}\n\nevent: message_stop\ndata: {}\n\n')+ );+ expect(events.map((e) => e.event)).toEqual(["ping", "message_stop"]);+ expect(events[0]?.raw).toBe('event: ping\ndata: {"type":"ping"}\n\n');+ expect(eventJson(events[0] as { data: string | null })).toEqual({ type: "ping" });+ expect(events.every((e) => e.complete)).toBe(true);+ });++ it("holds a partial event until its terminator arrives", () => {+ const s = new SseSplitter();+ expect(s.push(bytes('event: content_block_delta\ndata: {"a"'))).toEqual([]);+ expect(s.pending).toBeGreaterThan(0);+ expect(s.push(bytes(":1}\n"))).toEqual([]);+ const events = s.push(bytes("\nevent: ping\n"));+ expect(events.map((e) => e.data)).toEqual(['{"a":1}']);+ expect(s.end().map((e) => [e.raw, e.complete])).toEqual([["event: ping\n", false]]);+ });++ it("decodes a multi-byte character split across chunks", () => {+ const whole = bytes('data: {"text":"héllo 😀"}\n\n');+ // Cut inside the 4-byte emoji and inside the 2-byte é.+ const emojiAt = whole.indexOf(0xf0);+ const eAt = whole.indexOf(0xc3);+ const s = new SseSplitter();+ const out = [+ ...s.push(whole.slice(0, eAt + 1)),+ ...s.push(whole.slice(eAt + 1, emojiAt + 2)),+ ...s.push(whole.slice(emojiAt + 2)),+ ];+ expect(out.length).toBe(1);+ expect(eventJson(out[0] as { data: string | null })).toEqual({ text: "héllo 😀" });+ // Raw-preserving: re-encoding reproduces the input bytes exactly.+ expect(Buffer.from(encodeUtf8(out[0]?.raw ?? "")).equals(Buffer.from(whole))).toBe(true);+ });++ it("splits on CRLF terminators too", () => {+ const s = new SseSplitter();+ const events = s.push(bytes("event: a\r\ndata: 1\r\n\r\nevent: b\r\ndata: 2\r\n\r\n"));+ expect(events.map((e) => [e.event, e.data])).toEqual([+ ["a", "1"],+ ["b", "2"],+ ]);+ });++ it("keeps an unparseable event rather than dropping it", () => {+ const s = new SseSplitter();+ const events = s.push(bytes("garbage line\n\n"));+ expect(events.length).toBe(1);+ expect(events[0]?.raw).toBe("garbage line\n\n");+ expect(eventJson(events[0] as { data: string | null })).toBeUndefined();+ });++ it("flushes an unterminated remainder at end of stream", () => {+ const s = new SseSplitter();+ s.push(bytes("data: tail"));+ expect(s.end()).toEqual([{ raw: "data: tail", event: null, data: "tail", complete: false }]);+ expect(s.end()).toEqual([]);+ });+});++describe("parseSseFields", () => {+ it("joins data lines, strips one leading space, ignores comments", () => {+ expect(parseSseFields(": comment\nevent:x\ndata: a\ndata: b\n\n")).toEqual({+ event: "x",+ data: "a\n b",+ });+ });+});++describe("serializeSseEvent", () => {+ it("round-trips through the splitter", () => {+ const wire = serializeSseEvent("content_block_delta", {+ type: "content_block_delta",+ index: 2,+ delta: { type: "text_delta", text: "a\nb" },+ });+ expect(wire.endsWith("\n\n")).toBe(true);+ const [event] = new SseSplitter().push(wire);+ expect(event?.event).toBe("content_block_delta");+ expect(eventJson(event as { data: string | null })).toEqual({+ type: "content_block_delta",+ index: 2,+ delta: { type: "text_delta", text: "a\nb" },+ });+ });++ it("omits the event line for an unnamed event and splits multi-line data", () => {+ expect(serializeSseEvent(null, "a\nb")).toBe("data: a\ndata: b\n\n");+ });+});++describe("chunkText", () => {+ it("cuts at the limit without splitting a surrogate pair", () => {+ const text = `${"a".repeat(1023)}😀tail`;+ const pieces = chunkText(text, 1024);+ expect(pieces[0]).toBe("a".repeat(1023));+ expect(pieces.join("")).toBe(text);+ for (const p of pieces) expect(p.length).toBeLessThanOrEqual(1024);+ for (const p of pieces) expect(() => encodeURIComponent(p)).not.toThrow();+ });++ it("returns nothing for empty text and one piece for short text", () => {+ expect(chunkText("")).toEqual([]);+ expect(chunkText("short")).toEqual(["short"]);+ });+});diff --git a/packages/cli/src/hooks/sse-codec.ts b/packages/cli/src/hooks/sse-codec.tsnew file mode 100644index 00000000..d8d69a9c--- /dev/null+++ b/packages/cli/src/hooks/sse-codec.ts@@ -0,0 +1,145 @@+/**+ * Claude-SSE codec for the response seam.+ *+ * A streaming splitter that turns network chunks into whole SSE events, and the+ * serialisers the seam uses to re-emit them. Three properties carry the seam's+ * safety rules:+ *+ * - **UTF-8 safe.** Bytes pass through ONE `TextDecoder("utf-8")` in stream+ * mode, so a multi-byte character split across two network chunks is decoded+ * whole, and text actions operate on JS strings that never hold half of one.+ * - **Raw-preserving.** Every event keeps its exact decoded text, terminator+ * included, so an event forwarded unchanged is re-encoded byte-identically+ * (for valid UTF-8).+ * - **Never drops.** An unparseable event is still an event (`raw` is kept and+ * `data` may be null); at end of stream an unterminated remainder is returned+ * as an incomplete event to forward raw.+ */++/** One SSE event as it arrived. */+export interface SseEvent {+ /** The exact decoded text, including its blank-line terminator when complete. */+ raw: string;+ /** The `event:` field, or null. */+ event: string | null;+ /** The `data:` lines joined with "\n", or null when there were none. */+ data: string | null;+ /** False only for an unterminated remainder flushed at end of stream. */+ complete: boolean;+}++const SEPARATORS = ["\r\n\r\n", "\n\n"] as const;++/** Index and length of the earliest event terminator in `text`, or null. */+function findTerminator(text: string): { at: number; length: number } | null {+ let best: { at: number; length: number } | null = null;+ for (const sep of SEPARATORS) {+ const at = text.indexOf(sep);+ if (at !== -1 && (best === null || at < best.at)) best = { at, length: sep.length };+ }+ return best;+}++/** Parse the fields of one event's text (terminator optional). */+export function parseSseFields(raw: string): { event: string | null; data: string | null } {+ let event: string | null = null;+ const data: string[] = [];+ for (const line of raw.split(/\r\n|\n|\r/)) {+ if (line === "" || line.startsWith(":")) continue;+ const colon = line.indexOf(":");+ const field = colon === -1 ? line : line.slice(0, colon);+ let value = colon === -1 ? "" : line.slice(colon + 1);+ if (value.startsWith(" ")) value = value.slice(1);+ if (field === "event") event = value;+ else if (field === "data") data.push(value);+ }+ return { event, data: data.length > 0 ? data.join("\n") : null };+}++/** Streaming splitter. One instance per response body. */+export class SseSplitter {+ private readonly decoder = new TextDecoder("utf-8");+ private buffer = "";++ /** Feed one network chunk; returns every event it completed, in order. */+ push(chunk: Uint8Array | string): SseEvent[] {+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });+ return this.drain();+ }++ /** End of stream: flush the decoder and return any remainder as an incomplete event. */+ end(): SseEvent[] {+ this.buffer += this.decoder.decode();+ const events = this.drain();+ if (this.buffer.length > 0) {+ const raw = this.buffer;+ this.buffer = "";+ events.push({ raw, ...parseSseFields(raw), complete: false });+ }+ return events;+ }++ /** Bytes of decoded text held while waiting for a terminator (UTF-16 units). */+ get pending(): number {+ return this.buffer.length;+ }++ private drain(): SseEvent[] {+ const events: SseEvent[] = [];+ for (;;) {+ const term = findTerminator(this.buffer);+ if (!term) break;+ const raw = this.buffer.slice(0, term.at + term.length);+ this.buffer = this.buffer.slice(term.at + term.length);+ events.push({ raw, ...parseSseFields(raw), complete: true });+ }+ return events;+ }+}++/** The event's `data` parsed as JSON, or undefined when absent or unparseable. */+export function eventJson(event: Pick<SseEvent, "data">): unknown {+ if (event.data === null) return undefined;+ try {+ return JSON.parse(event.data);+ } catch {+ return undefined;+ }+}++/** Serialise one event: `event:` line (when named), one `data:` line per data line, blank line. */+export function serializeSseEvent(event: string | null, data: string | object): string {+ const payload = typeof data === "string" ? data : JSON.stringify(data);+ const lines = event ? [`event: ${event}`] : [];+ for (const line of payload.split("\n")) lines.push(`data: ${line}`);+ return `${lines.join("\n")}\n\n`;+}++const encoder = new TextEncoder();++/** Encode text for the wire. */+export function encodeUtf8(text: string): Uint8Array {+ return encoder.encode(text);+}++/**+ * Split text into pieces of at most `max` UTF-16 code units, never between the+ * two halves of a surrogate pair. Used to re-emit a rewritten text block as+ * `text_delta` events of bounded size.+ */+export function chunkText(text: string, max = 1024): string[] {+ if (max < 2) throw new RangeError("chunkText max must be at least 2");+ const pieces: string[] = [];+ let at = 0;+ while (at < text.length) {+ let end = Math.min(at + max, text.length);+ if (end < text.length) {+ const last = text.charCodeAt(end - 1);+ // A high surrogate at the cut would be separated from its low half.+ if (last >= 0xd800 && last <= 0xdbff) end--;+ }+ pieces.push(text.slice(at, end));+ at = end;+ }+ return pieces;+}diff --git a/packages/cli/src/behavior/telemetry.test.ts b/packages/cli/src/hooks/telemetry.test.tssimilarity index 100%rename from packages/cli/src/behavior/telemetry.test.tsrename to packages/cli/src/hooks/telemetry.test.tsdiff --git a/packages/cli/src/behavior/telemetry/aggregate.ts b/packages/cli/src/hooks/telemetry/aggregate.tssimilarity index 93%rename from packages/cli/src/behavior/telemetry/aggregate.tsrename to packages/cli/src/hooks/telemetry/aggregate.tsindex 918411ce..6a3d3ddc 100644--- a/packages/cli/src/behavior/telemetry/aggregate.ts+++ b/packages/cli/src/hooks/telemetry/aggregate.ts@@ -19,8 +19,17 @@** ## Consent*- * Everything here is a no-op unless `behavior.telemetry.enabled` is true. That- * flag is deliberately separate from `stats.enabled` — see BehaviorConfig.+ * Everything here is a no-op unless `hooks.telemetry.enabled` is true. That+ * flag is deliberately separate from `stats.enabled`: that consent was granted+ * for usage statistics, and reusing it for behavioural records would be consent+ * laundering.+ *+ * ## Privacy of user hooks+ *+ * This module stores what it is given. The hook engine's `journal()` fan-out is+ * the only caller in the hook system, and it passes a user hook's id as `"user"`+ * and withholds an `mcp__` tool name on such a row BEFORE calling+ * `recordTelemetryDecision` (hooks/engine.ts).*/import { createHash, randomBytes } from "node:crypto";@@ -29,7 +38,7 @@ import { homedir } from "node:os";import { dirname, join } from "node:path";import { log } from "../../logger.js";import { VERSION } from "../../version.js";-import type { Decision, PathRelation, Surface } from "../journal.js";+import type { PathRelation, UploadDecision, UploadSurface } from "../journal.js";/** Pinned by the deployed server contract. Bump only with the backend. */export const TELEMETRY_SCHEMA_VERSION = 1;@@ -134,9 +143,9 @@ function hashSessionId(rawSessionId: string, model: string): string {/** One row of the `decisions[]` array, accumulated. */interface DecisionAggregate {rule_id?: string;- surface: Surface;+ surface: UploadSurface;tool_name?: string;- counts: Partial<Record<Decision, number>>;+ counts: Partial<Record<UploadDecision, number>>;path_relations: Partial<Record<PathRelation, number>>;}@@ -163,9 +172,9 @@ export interface SessionReport {turns: number;decisions: Array<{rule_id?: string;- surface: Surface;+ surface: UploadSurface;tool_name?: string;- counts: Partial<Record<Decision, number>>;+ counts: Partial<Record<UploadDecision, number>>;path_relations: Partial<Record<PathRelation, number>>;}>;}@@ -194,7 +203,7 @@ const sessions = new Map<string, SessionState>();/*** Consent. PUSHED in by BehaviorEngine rather than read from config here.*- * The engine already holds the parsed, validated `behavior` block, so re-reading+ * The engine already holds the parsed, validated `hooks` block, so re-reading* config from the request path would be both wasteful and a second place for the* flag to be interpreted. Default false: nothing is collected until an opt-in is* observed, so a code path that forgets to set it fails closed.@@ -271,8 +280,8 @@ export function recordTelemetryDecision(p: {sessionId?: string;model: string;provider: string;- surface: Surface;- decision: Decision;+ surface: UploadSurface;+ decision: UploadDecision;ruleId?: string;toolName?: string;pathRelation?: PathRelation;diff --git a/packages/cli/src/behavior/telemetry/upload.ts b/packages/cli/src/hooks/telemetry/upload.tssimilarity index 100%rename from packages/cli/src/behavior/telemetry/upload.tsrename to packages/cli/src/hooks/telemetry/upload.tsdiff --git a/packages/cli/src/hooks/test-helpers/capture-child.ts b/packages/cli/src/hooks/test-helpers/capture-child.tsnew file mode 100644index 00000000..a748fa48--- /dev/null+++ b/packages/cli/src/hooks/test-helpers/capture-child.ts@@ -0,0 +1,59 @@+/**+ * Spawned by loader.test.ts and output-capture.test.ts: load hook modules+ * through the real loader in one host mode, run one event, and report.+ *+ * argv: <mode: "interactive" | "mcp-unbound"> <module path>...+ * cwd: a temp dir — the debug log is written to <cwd>/logs/.+ * Output: one line `REPORT <json>` on STDERR, so stdout stays exactly what the+ * hooks left on it (the assertion is that they left nothing).+ */++import { initLogger } from "../../logger.js";+import { HookEngine } from "../engine.js";+import { loadUserHooks } from "../loader.js";+import { isolateProtocolStdout } from "../output-capture.js";+import { HookRegistry } from "../registry.js";++const [mode, ...modules] = process.argv.slice(2);+initLogger(true, "debug", true);++let isolation: { active: boolean; sameAsStdout: boolean } | null = null;+if (mode === "mcp-unbound") {+ const iso = isolateProtocolStdout({+ bind: () => {+ throw new Error("no ffi");+ },+ });+ isolation = { active: iso.active, sameAsStdout: iso.protocolOut === process.stdout };+}++const hostMode = mode === "interactive" ? "interactive" : "mcp";+const load = await loadUserHooks({ modules, configDir: process.cwd(), hostMode });+// A second load in the same process must not print the mcp refusal again.+if (hostMode === "mcp") await loadUserHooks({ modules, configDir: process.cwd(), hostMode });++const engine = new HookEngine({+ registry: new HookRegistry([], load.hooks, undefined),+ config: {},+ hostMode,+ journalSink: () => {},+ drainTelemetryOutbox: false,+});+const route = { modelId: "m", provider: "p", native: false };+const result = await engine.run(+ "request",+ engine.select("request", { route }),+ (_a, base) => ({ ...base, event: "request", route }),+ { model: "m", provider: "p" }+);++// Let timers the hooks scheduled fire, and the logger's interval flush run.+await Bun.sleep(300);+const report = {+ hooks: load.hooks.map((h) => h.id),+ errors: load.errors,+ statuses: result.runs.map((r) => r.status),+ isolation,+};+process.stderr.write(`REPORT ${JSON.stringify(report)}\n`);+process.exit(0);diff --git a/packages/cli/src/hooks/test-helpers/isolate-child.ts b/packages/cli/src/hooks/test-helpers/isolate-child.tsnew file mode 100644index 00000000..9fe53db0--- /dev/null+++ b/packages/cli/src/hooks/test-helpers/isolate-child.ts@@ -0,0 +1,37 @@+/**+ * Spawned by output-capture.test.ts (X-12): isolate protocol stdout for real,+ * then write one large frame through `protocolOut` while every other stdout+ * route is exercised. The parent pipes stdout and starts reading late.+ *+ * argv: <frame bytes>+ * cwd: a temp dir — the debug log is written to <cwd>/logs/.+ */++import { writeSync } from "node:fs";+import { initLogger } from "../../logger.js";+import { isolateProtocolStdout, runInHookScope } from "../output-capture.js";++initLogger(true, "debug", true);+const iso = isolateProtocolStdout();+process.stderr.write(`ACTIVE ${iso.active}\n`);++// Every route but the protocol writer must miss stdout.+console.log("NOISE-CONSOLE");+console.info("NOISE-INFO");+process.stdout.write("NOISE-WRITE\n");+writeSync(1, "NOISE-FD\n");+await Bun.write(Bun.stdout, "NOISE-BUNWRITE\n");+runInHookScope("hook:x/y", () => console.log("SCOPED-CONSOLE"));++const size = Number(process.argv[2] ?? 4 * 1024 * 1024);+const frame = Buffer.alloc(size, "x");+frame.write("{", 0);+frame.write("}", size - 2);+frame.write("\n", size - 1);++await new Promise<void>((resolve, reject) => {+ iso.protocolOut.write(frame, (err) => (err ? reject(err) : resolve()));+});+process.stderr.write("CALLBACK\n");+await Bun.sleep(200);+process.exit(0);diff --git a/packages/cli/src/hooks/text-rewrite.test.ts b/packages/cli/src/hooks/text-rewrite.test.tsnew file mode 100644index 00000000..f197aa26--- /dev/null+++ b/packages/cli/src/hooks/text-rewrite.test.ts@@ -0,0 +1,177 @@+import { describe, expect, it } from "bun:test";+import { act } from "./public.js";+import { type RewriteBlock, applyTextActions, compileMatcher } from "./text-rewrite.js";++const text = (t: string): RewriteBlock => ({ type: "text", text: t });+const thinking: RewriteBlock = { type: "thinking", text: undefined };+const tool = (name: string) => ({ type: "tool_use", id: `toolu_${name}`, name });++/** Output as `type:text` strings, for compact assertions. */+function shape(result: ReturnType<typeof applyTextActions>): string[] {+ return result.blocks.map((b) =>+ b.block.type === "text" ? `text:${b.block.text}` : String(b.block.type)+ );+}++describe("applyTextActions — insert positions", () => {+ it("appendText extends the LAST text block", () => {+ const r = applyTextActions([text("a"), tool("x"), text("b")], [act.appendText("!")]);+ expect(shape(r)).toEqual(["text:a", "tool_use", "text:b!"]);+ expect(r.blocks.map((b) => b.source)).toEqual([0, 1, 2]);+ expect(r.blocks.map((b) => b.changed)).toEqual([false, false, true]);+ });++ it("appendText with no text block inserts before the first tool_use", () => {+ const r = applyTextActions([thinking, tool("a"), tool("b")], [act.appendText("NOTE")]);+ expect(shape(r)).toEqual(["thinking", "text:NOTE", "tool_use", "tool_use"]);+ expect(r.blocks.map((b) => b.source)).toEqual([0, null, 1, 2]);+ });++ it("appendText with only thinking appends after the last block", () => {+ const r = applyTextActions([thinking, thinking], [act.appendText("END")]);+ expect(shape(r)).toEqual(["thinking", "thinking", "text:END"]);+ });++ it("appendText on an empty response inserts the only block", () => {+ expect(shape(applyTextActions([], [act.appendText("x")]))).toEqual(["text:x"]);+ });++ it("prependText extends the FIRST text block", () => {+ const r = applyTextActions([text("a"), text("b")], [act.prependText(">")]);+ expect(shape(r)).toEqual(["text:>a", "text:b"]);+ });++ it("prependText with no text block inserts after leading thinking", () => {+ const r = applyTextActions([thinking, tool("a")], [act.prependText("FIRST")]);+ expect(shape(r)).toEqual(["thinking", "text:FIRST", "tool_use"]);+ });++ it("prependText on a tool-only response lands before the tools", () => {+ const r = applyTextActions([tool("a"), tool("b")], [act.prependText("P")]);+ expect(shape(r)).toEqual(["text:P", "tool_use", "tool_use"]);+ });++ it("locked text blocks are never targets and never rewritten", () => {+ const locked = { type: "text", text: "cited REMOVE", locked: true };+ const r = applyTextActions(+ [locked, tool("a")],+ [act.appendText("+"), act.removeText("REMOVE")]+ );+ expect(shape(r)).toEqual(["text:cited REMOVE", "text:+", "tool_use"]);+ expect(r.blocks[0]?.block).toBe(locked);+ });+});++describe("applyTextActions — replace and remove", () => {+ it("applies each action to each text block independently, in order", () => {+ const r = applyTextActions(+ [text("cat cat"), tool("x"), text("a cat")],+ [act.replaceText("cat", "dog"), act.replaceText("dog", "fox")]+ );+ expect(shape(r)).toEqual(["text:fox fox", "tool_use", "text:a fox"]);+ expect(r.applied.map((a) => a.changed)).toEqual([true, true]);+ });++ it("removes with a regex without leaving a double space", () => {+ const r = applyTextActions(+ [text("KEEP REMOVE-ME KEEP")],+ [act.removeText("\\s*REMOVE-ME", { regex: true })]+ );+ expect(shape(r)).toEqual(["text:KEEP KEEP"]);+ });++ it("drops a text block left empty and reports the shift", () => {+ const r = applyTextActions([text("gone"), tool("a")], [act.removeText("gone")]);+ expect(shape(r)).toEqual(["tool_use"]);+ expect(r.blocks[0]?.source).toBe(1);+ });++ it("passes an originally empty, untouched text block through", () => {+ const empty = text("");+ const r = applyTextActions([empty], [act.replaceText("x", "y")]);+ expect(r.blocks[0]?.block).toBe(empty);+ expect(r.applied[0]?.changed).toBe(false);+ });++ it("keeps a block whose edits cancel out as the original", () => {+ const original = text("abc");+ const r = applyTextActions([original], [act.replaceText("b", "X"), act.replaceText("X", "b")]);+ expect(r.blocks[0]?.block).toBe(original);+ expect(r.blocks[0]?.changed).toBe(false);+ });++ it("inserts a literal replacement verbatim; regex mode expands $1", () => {+ const literal = applyTextActions([text("price: N")], [act.replaceText("N", "$500")]);+ expect(shape(literal)).toEqual(["text:price: $500"]);+ const literalAmp = applyTextActions([text("x")], [act.replaceText("x", "$&$&")]);+ expect(shape(literalAmp)).toEqual(["text:$&$&"]);+ const regex = applyTextActions(+ [text("John Smith")],+ [act.replaceText("(\\w+) (\\w+)", "$2, $1", { regex: true })]+ );+ expect(shape(regex)).toEqual(["text:Smith, John"]);+ });++ it("honours regex flags and defaults them to g", () => {+ expect(+ shape(applyTextActions([text("aAa")], [act.replaceText("a", "x", { regex: true })]))+ ).toEqual(["text:xAx"]);+ expect(+ shape(+ applyTextActions([text("aAa")], [act.replaceText("a", "x", { regex: true, flags: "gi" })])+ )+ ).toEqual(["text:xxx"]);+ // Without g only the first match goes.+ expect(+ shape(+ applyTextActions([text("aaa")], [act.replaceText("a", "x", { regex: true, flags: "i" })])+ )+ ).toEqual(["text:xaa"]);+ });++ it("rejects an invalid regex, bad flags and flags without regex", () => {+ const r = applyTextActions(+ [text("abc")],+ [+ act.replaceText("(", "x", { regex: true }),+ act.replaceText("a", "x", { regex: true, flags: "gq" }),+ act.replaceText("a", "x", { regex: true, flags: "gg" }),+ act.replaceText("a", "x", { flags: "i" }),+ act.appendText("!"),+ ]+ );+ expect(r.rejected.map((x) => [x.index, x.reason])).toEqual([+ [0, "invalid_regex"],+ [1, "invalid_flags"],+ [2, "invalid_flags"],+ [3, "flags_without_regex"],+ ]);+ expect(shape(r)).toEqual(["text:abc!"]);+ });++ it("applies text actions sequentially, each over the previous result", () => {+ const r = applyTextActions(+ [text("hello")],+ [act.appendText(" world"), act.replaceText("world", "there"), act.prependText("> ")]+ );+ expect(shape(r)).toEqual(["text:> hello there"]);+ });+});++describe("compileMatcher", () => {+ it("rejects an empty find", () => {+ expect(compileMatcher(act.removeText(""))).toEqual({ invalid: "empty_find" });+ });++ it("replaces every literal occurrence including regex metacharacters", () => {+ const m = compileMatcher(act.replaceText("a.b", "X"));+ expect("apply" in m && m.apply("a.b axb a.b")).toBe("X axb X");+ });++ it("restarts a global regex for each block", () => {+ const m = compileMatcher(act.replaceText("a", "x", { regex: true }));+ if (!("apply" in m)) throw new Error("expected a matcher");+ expect(m.apply("aa")).toBe("xx");+ expect(m.apply("aa")).toBe("xx");+ });+});diff --git a/packages/cli/src/hooks/text-rewrite.ts b/packages/cli/src/hooks/text-rewrite.tsnew file mode 100644index 00000000..e0050284--- /dev/null+++ b/packages/cli/src/hooks/text-rewrite.ts@@ -0,0 +1,225 @@+/**+ * Pure text rewriting over content blocks.+ *+ * One implementation for every place text is rewritten: the response seam's+ * `buffer` mode (the held blocks), its non-streaming JSON branch (the whole+ * `content[]`), and the request's message-text actions. It never touches a+ * non-text block, and it reports where each output block came from so the seam+ * can re-emit unchanged blocks from their original bytes and re-index the rest.+ */++import type {+ AppendText,+ PrependText,+ RemoveMessageText,+ RemoveText,+ ReplaceMessageText,+ ReplaceText,+} from "./public.js";++/** The text actions this module applies. `warn` never reaches it. */+export type TextAction = AppendText | PrependText | ReplaceText | RemoveText;++/** A matcher action from either surface (response text or message text). */+export type MatchAction = ReplaceText | RemoveText | ReplaceMessageText | RemoveMessageText;++/** Regex flags a hook may pass. */+const ALLOWED_FLAGS = new Set(["g", "i", "m", "s", "u", "y"]);++/** A compiled `find`: a replacer that never interprets `$` in literal mode. */+export interface Matcher {+ apply(text: string): string;+}++/**+ * Compile an action's `find` into a matcher, or return the reason it is invalid.+ *+ * Literal mode (the default) replaces every occurrence and inserts `replace`+ * verbatim through a replacer FUNCTION, so `"$500"` stays `$500`. Regex mode+ * uses `flags` (a subset of `gimsuy`, default `"g"`) and applies JavaScript+ * replacement patterns (`$1`, `$<name>`, `$&`, `$$`).+ */+export function compileMatcher(action: MatchAction): Matcher | { invalid: string } {+ const replace = "replace" in action ? action.replace : "";+ if (typeof action.find !== "string" || action.find.length === 0) return { invalid: "empty_find" };+ if (typeof replace !== "string") return { invalid: "replace_not_string" };++ if (action.regex === true) {+ const flags = action.flags ?? "g";+ if (typeof flags !== "string") return { invalid: "invalid_flags" };+ const seen = new Set<string>();+ for (const f of flags) {+ if (!ALLOWED_FLAGS.has(f) || seen.has(f)) return { invalid: "invalid_flags" };+ seen.add(f);+ }+ let re: RegExp;+ try {+ re = new RegExp(action.find, flags);+ } catch {+ return { invalid: "invalid_regex" };+ }+ return {+ apply(text) {+ re.lastIndex = 0;+ return text.replace(re, replace);+ },+ };+ }++ if (action.flags !== undefined) return { invalid: "flags_without_regex" };+ const find = action.find;+ return { apply: (text) => text.split(find).join(replace) };+}++/** A block as the rewriter sees it. Only unlocked `text` blocks are editable. */+export interface RewriteBlock {+ type: string;+ text?: string;+ /**+ * An excluded text block (e.g. one that carried `citations_delta`): never+ * rewritten, and never chosen as the target of an append or prepend.+ */+ locked?: boolean;+}++export interface RewrittenBlock<B extends RewriteBlock> {+ /** The original block, or for an edited/inserted text block a new `{type:"text", text}`. */+ block: B | { type: "text"; text: string };+ /** Index of the original block, or null for an inserted one. */+ source: number | null;+ /** True when the text differs from the original (always true for an inserted block). */+ changed: boolean;+}++export interface TextRewriteResult<B extends RewriteBlock> {+ blocks: Array<RewrittenBlock<B>>;+ /** Index into `actions` of every action that was evaluated. */+ applied: Array<{ index: number; action: TextAction; changed: boolean }>;+ /** Index into `actions` of every action refused, with the reason. */+ rejected: Array<{ index: number; action: TextAction; reason: string }>;+}++const THINKING_TYPES = new Set(["thinking", "redacted_thinking"]);++interface WorkBlock<B extends RewriteBlock> {+ original: B | null;+ source: number | null;+ text: string | null;+ editable: boolean;+ touched: boolean;+}++/**+ * Apply response text actions sequentially, each over the previous result.+ *+ * Insert rules (the held region starts at the first block that is not+ * thinking, so both insert points always lie inside it):+ * - `appendText` → end of the LAST text block; with none, a new text block+ * immediately BEFORE the first `tool_use` block; with none of those either,+ * after the last block.+ * - `prependText` → start of the FIRST text block; with none, a new text block+ * after any leading thinking blocks.+ * - `replaceText` / `removeText` → each text block independently, in order.+ *+ * A text block left empty by an edit is dropped (an empty text block is a 400 on+ * Anthropic-compatible endpoints when replayed). An originally empty block that+ * no action touched passes through unchanged.+ */+export function applyTextActions<B extends RewriteBlock>(+ blocks: ReadonlyArray<B>,+ actions: ReadonlyArray<TextAction>+): TextRewriteResult<B> {+ const work: Array<WorkBlock<B>> = blocks.map((b, i) => {+ const editable = b.type === "text" && !b.locked && typeof b.text === "string";+ return {+ original: b,+ source: i,+ text: editable ? (b.text as string) : null,+ editable,+ touched: false,+ };+ });+ const applied: TextRewriteResult<B>["applied"] = [];+ const rejected: TextRewriteResult<B>["rejected"] = [];++ const newText = (text: string): WorkBlock<B> => ({+ original: null,+ source: null,+ text,+ editable: true,+ touched: true,+ });++ actions.forEach((action, index) => {+ switch (action.type) {+ case "appendText":+ case "prependText": {+ if (typeof action.text !== "string" || action.text.length === 0) {+ rejected.push({ index, action, reason: "empty_text" });+ return;+ }+ const editableIdx = work.flatMap((w, i) => (w.editable ? [i] : []));+ if (editableIdx.length > 0) {+ const target = work[+ action.type === "appendText" ? editableIdx[editableIdx.length - 1] : editableIdx[0]+ ] as WorkBlock<B>;+ target.text =+ action.type === "appendText"+ ? `${target.text ?? ""}${action.text}`+ : `${action.text}${target.text ?? ""}`;+ target.touched = true;+ } else if (action.type === "appendText") {+ const firstTool = work.findIndex((w) => w.original?.type === "tool_use");+ work.splice(firstTool === -1 ? work.length : firstTool, 0, newText(action.text));+ } else {+ let leading = 0;+ while (leading < work.length && THINKING_TYPES.has(work[leading]?.original?.type ?? "")) {+ leading++;+ }+ work.splice(leading, 0, newText(action.text));+ }+ applied.push({ index, action, changed: true });+ return;+ }+ case "replaceText":+ case "removeText": {+ const matcher = compileMatcher(action);+ if ("invalid" in matcher) {+ rejected.push({ index, action, reason: matcher.invalid });+ return;+ }+ let changed = false;+ for (const w of work) {+ if (!w.editable || w.text === null) continue;+ const next = matcher.apply(w.text);+ if (next !== w.text) {+ w.text = next;+ w.touched = true;+ changed = true;+ }+ }+ applied.push({ index, action, changed });+ return;+ }+ default: {+ const unknown = action as { type?: unknown };+ rejected.push({+ index,+ action: action as TextAction,+ reason: `not_a_text_action:${String(unknown.type)}`,+ });+ }+ }+ });++ const out: Array<RewrittenBlock<B>> = [];+ for (const w of work) {+ if (w.editable && w.touched && (w.text ?? "") === "") continue;+ if (w.original && (!w.editable || w.text === w.original.text)) {+ out.push({ block: w.original, source: w.source, changed: false });+ continue;+ }+ out.push({ block: { type: "text", text: w.text ?? "" }, source: w.source, changed: true });+ }+ return { blocks: out, applied, rejected };+}diff --git a/packages/cli/src/profile-config.ts b/packages/cli/src/profile-config.tsindex d6a254c2..63a992b5 100644--- a/packages/cli/src/profile-config.ts+++ b/packages/cli/src/profile-config.ts@@ -241,12 +241,22 @@ export interface ClaudishProfileConfig {predefinedEndpoints?: Record<string, unknown>;/**- * Layer 4 behavior-compatibility settings (rule severities, hooks, observer).- * Validated at the consumption site via Zod in behavior/config.ts, not here —- * `loadConfig` runs on lightweight startup paths and stays Zod-free.+ * The pre-hook-system `behavior` block. The hook system never reads it: its+ * only reader there is the reporter in hooks/config.ts, which tells the user+ * what to move into `hooks`.+ * It stays on the allowlist as an opaque passthrough so the next global save+ * does not silently drop it before the user has moved it.*/behavior?: Record<string, unknown>;+ /**+ * The hook system (modules, severity, injection cap, observer, telemetry+ * consent). Read from the GLOBAL config only — a project `.claudish.json` is+ * repo-controlled and must not name code to run. Validated at the consumption+ * site via Zod in hooks/config.ts; `loadConfig` stays Zod-free.+ */+ hooks?: Record<string, unknown>;+/*** Apply a model's catalog provider-preset (e.g. `reasoning.mode=pro`) while* the Claude Code session is in ultracode. Opt-in and default OFF — a pro@@ -412,6 +422,12 @@ export function loadConfig(): ClaudishProfileConfig {if (config.behavior !== undefined) {merged.behavior = config.behavior;}+ // Same trap as keychain/onepasswordEnvironments: omitted from this+ // allowlist, the block survives on disk until the first global save and is+ // then silently dropped — every user hook would stop loading with no error.+ if (config.hooks !== undefined) {+ merged.hooks = config.hooks;+ }// Same trap as keychain/onepasswordEnvironments above: omitted from this// allowlist, the field survives on disk until the first global save and is// then silently dropped — quietly turning the feature off with no error.diff --git a/packages/cli/src/providers/predefined-endpoint-schema.ts b/packages/cli/src/providers/predefined-endpoint-schema.tsindex d67de3e2..df3b3625 100644--- a/packages/cli/src/providers/predefined-endpoint-schema.ts+++ b/packages/cli/src/providers/predefined-endpoint-schema.ts@@ -17,9 +17,10 @@* claudish refusing a model that actually works. Model metadata comes from* models-index or is absent. The schema is `.strict()`, so a future* contributor cannot add one of those keys by accident — an unknown key is- * a parse error, not a silently ignored field. Same doctrine as- * `telemetry/toUploadable()`: an allow-list projection, where leaking has to- * be done on purpose.+ * a parse error, not a silently ignored field. Same doctrine as the upload+ * projection in the hook engine's `journal()` fan-out (hooks/engine.ts): only+ * fields passed explicitly reach the telemetry report, so leaking has to be+ * done on purpose.** 2. **`apiPath` is REQUIRED, with no default.** Measured 2026-08-14: DeepInfra* (`/v1/openai` + `/chat/completions`), Novita (`/v3/openai` +