Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 16 additions & 112 deletions src/features/hooks/claudecode-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { join } from "node:path";

import type { AiFileParams } from "../../types/ai-file.js";
import type { ValidationResult } from "../../types/ai-file.js";
import type { HooksConfig } from "../../types/hooks.js";
import {
CLAUDE_HOOK_EVENTS,
CLAUDE_TO_CANONICAL_EVENT_NAMES,
CANONICAL_TO_CLAUDE_EVENT_NAMES,
} from "../../types/hooks.js";
import { formatError } from "../../utils/error.js";
import { readFileContentOrNull, readOrInitializeFileContent } from "../../utils/file.js";
import type { PascalHooksConverterConfig } from "./pascal-hooks-converter.js";
import { canonicalToPascalHooks, pascalHooksToCanonical } from "./pascal-hooks-converter.js";
import type { RulesyncHooks } from "./rulesync-hooks.js";
import {
ToolHooks,
Expand All @@ -19,117 +20,13 @@ import {
type ToolHooksSettablePaths,
} from "./tool-hooks.js";

/**
* Convert canonical hooks config to Claude format.
* Filters shared hooks to CLAUDE_HOOK_EVENTS, merges config.claudecode?.hooks,
* then converts to PascalCase and Claude matcher/hooks structure.
*/
function canonicalToClaudeHooks(config: HooksConfig): Record<string, unknown[]> {
const claudeSupported: Set<string> = new Set(CLAUDE_HOOK_EVENTS);
const sharedHooks: HooksConfig["hooks"] = {};
for (const [event, defs] of Object.entries(config.hooks)) {
if (claudeSupported.has(event)) {
sharedHooks[event] = defs;
}
}
const effectiveHooks: HooksConfig["hooks"] = {
...sharedHooks,
...config.claudecode?.hooks,
};
const claude: Record<string, unknown[]> = {};
for (const [eventName, definitions] of Object.entries(effectiveHooks)) {
const claudeEventName = CANONICAL_TO_CLAUDE_EVENT_NAMES[eventName] ?? eventName;
const byMatcher = new Map<string, HooksConfig["hooks"][string]>();
for (const def of definitions) {
const key = def.matcher ?? "";
const list = byMatcher.get(key);
if (list) list.push(def);
else byMatcher.set(key, [def]);
}
const entries: unknown[] = [];
for (const [matcherKey, defs] of byMatcher) {
const hooks = defs.map((def) => {
const command =
def.command !== undefined && def.command !== null && !def.command.startsWith("$")
? `$CLAUDE_PROJECT_DIR/${def.command.replace(/^\.\//, "")}`
: def.command;
return {
type: def.type ?? "command",
...(command !== undefined && command !== null && { command }),
...(def.timeout !== undefined && def.timeout !== null && { timeout: def.timeout }),
...(def.prompt !== undefined && def.prompt !== null && { prompt: def.prompt }),
};
});
entries.push(matcherKey ? { matcher: matcherKey, hooks } : { hooks });
}
claude[claudeEventName] = entries;
}
return claude;
}

/**
* Extract hooks from Claude settings.json into canonical format.
*/
type ClaudeMatcherEntry = {
matcher?: string;
hooks?: Array<Record<string, unknown>>;
const CLAUDE_CONVERTER_CONFIG: PascalHooksConverterConfig = {
supportedEvents: CLAUDE_HOOK_EVENTS,
canonicalToToolEventNames: CANONICAL_TO_CLAUDE_EVENT_NAMES,
toolToCanonicalEventNames: CLAUDE_TO_CANONICAL_EVENT_NAMES,
projectDirVar: "$CLAUDE_PROJECT_DIR",
};

function isClaudeMatcherEntry(x: unknown): x is ClaudeMatcherEntry {
if (x === null || typeof x !== "object") {
return false;
}
// Validate optional 'matcher' property: must be string if present
if ("matcher" in x && typeof x.matcher !== "string") {
return false;
}
// Validate optional 'hooks' property: must be array if present
if ("hooks" in x && !Array.isArray(x.hooks)) {
return false;
}
return true;
}

function claudeHooksToCanonical(claudeHooks: unknown): HooksConfig["hooks"] {
if (claudeHooks === null || claudeHooks === undefined || typeof claudeHooks !== "object") {
return {};
}
const canonical: HooksConfig["hooks"] = {};
for (const [claudeEventName, matcherEntries] of Object.entries(claudeHooks)) {
const eventName = CLAUDE_TO_CANONICAL_EVENT_NAMES[claudeEventName] ?? claudeEventName;
if (!Array.isArray(matcherEntries)) continue;
const defs: HooksConfig["hooks"][string] = [];
for (const rawEntry of matcherEntries) {
if (!isClaudeMatcherEntry(rawEntry)) continue;
const entry = rawEntry;
const hooks = entry.hooks ?? [];
for (const h of hooks) {
const cmd = typeof h.command === "string" ? h.command : undefined;
const command =
typeof cmd === "string" && cmd.includes("$CLAUDE_PROJECT_DIR/")
? cmd.replace(/^\$CLAUDE_PROJECT_DIR\/?/, "./")
: cmd;
const hookType = h.type === "command" || h.type === "prompt" ? h.type : "command";
const timeout = typeof h.timeout === "number" ? h.timeout : undefined;
const prompt = typeof h.prompt === "string" ? h.prompt : undefined;
defs.push({
type: hookType,
...(command !== undefined && command !== null && { command }),
...(timeout !== undefined && timeout !== null && { timeout }),
...(prompt !== undefined && prompt !== null && { prompt }),
...(entry.matcher !== undefined &&
entry.matcher !== null &&
entry.matcher !== "" && { matcher: entry.matcher }),
});
}
}
if (defs.length > 0) {
canonical[eventName] = defs;
}
}
return canonical;
}

export class ClaudecodeHooks extends ToolHooks {
constructor(params: AiFileParams) {
super({
Expand Down Expand Up @@ -187,7 +84,11 @@ export class ClaudecodeHooks extends ToolHooks {
);
}
const config = rulesyncHooks.getJson();
const claudeHooks = canonicalToClaudeHooks(config);
const claudeHooks = canonicalToPascalHooks({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say that the fact that for existing events simply converting the casing works is accidental. For some agents, the event names are completely different, and this might be the case for claude code or factorydroid if they add new events as well.

@saitota saitota Mar 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. Renamed pascal-hooks-converter.ts → tool-hooks-converter.ts and related symbols (canonicalToPascalHooks → canonicalToToolHooks, etc.) to align with the existing canonicalToCopilotHooks naming pattern.

config,
toolOverrideHooks: config.claudecode?.hooks,
converterConfig: CLAUDE_CONVERTER_CONFIG,
});
const merged = { ...settings, hooks: claudeHooks };
const fileContent = JSON.stringify(merged, null, 2);
return new ClaudecodeHooks({
Expand All @@ -211,7 +112,10 @@ export class ClaudecodeHooks extends ToolHooks {
},
);
}
const hooks = claudeHooksToCanonical(settings.hooks);
const hooks = pascalHooksToCanonical({
hooks: settings.hooks,
converterConfig: CLAUDE_CONVERTER_CONFIG,
});
return this.toRulesyncHooksDefault({
fileContent: JSON.stringify({ version: 1, hooks }, null, 2),
});
Expand Down
7 changes: 7 additions & 0 deletions src/features/hooks/cursor-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ export class CursorHooks extends ToolHooks {
...sharedHooks,
...config.cursor?.hooks,
};
// Map canonical event names to Cursor event names.
// Currently an identity mapping (camelCase → camelCase), but this loop maintains
// architectural consistency with other tool converters (Claude, Factory Droid) and
// becomes essential if Cursor's event naming diverges from canonical in the future.
const mappedHooks: HooksConfig["hooks"] = {};
for (const [eventName, defs] of Object.entries(mergedHooks)) {
const cursorEventName = CANONICAL_TO_CURSOR_EVENT_NAMES[eventName] ?? eventName;
Expand Down Expand Up @@ -104,6 +108,9 @@ export class CursorHooks extends ToolHooks {
const content = this.getFileContent();
const parsed: { version?: number; hooks?: HooksConfig["hooks"] } = JSON.parse(content);
const cursorHooks = parsed.hooks ?? {};
// Map Cursor event names back to canonical event names.
// Currently identity but kept explicit for forward compatibility
// (see CANONICAL_TO_CURSOR_EVENT_NAMES in types/hooks.ts).
const canonicalHooks: HooksConfig["hooks"] = {};
for (const [cursorEventName, defs] of Object.entries(cursorHooks)) {
const eventName = CURSOR_TO_CANONICAL_EVENT_NAMES[cursorEventName] ?? cursorEventName;
Expand Down
46 changes: 46 additions & 0 deletions src/features/hooks/factorydroid-hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,52 @@ describe("FactorydroidHooks", () => {
expect(parsed.hooks.Notification[0].matcher).toBe("permission_prompt");
});

it("should not leak Claude config hooks into Factory Droid output", async () => {
await ensureDir(join(testDir, ".factory"));
await writeFileContent(join(testDir, ".factory", "settings.json"), JSON.stringify({}));

const config = {
version: 1,
hooks: {
sessionStart: [{ type: "command", command: "shared.sh" }],
},
claudecode: {
hooks: {
sessionStart: [{ type: "command", command: "claude-only.sh" }],
notification: [{ command: "claude-notify.sh" }],
},
},
factorydroid: {
hooks: {
stop: [{ command: "factory-stop.sh" }],
},
},
};
const rulesyncHooks = new RulesyncHooks({
baseDir: testDir,
relativeDirPath: RULESYNC_RELATIVE_DIR_PATH,
relativeFilePath: "hooks.json",
fileContent: JSON.stringify(config),
validate: false,
});

const factorydroidHooks = await FactorydroidHooks.fromRulesyncHooks({
baseDir: testDir,
rulesyncHooks,
validate: false,
});

const content = factorydroidHooks.getFileContent();
const parsed = JSON.parse(content);
// Shared hooks should be present
expect(parsed.hooks.SessionStart[0].hooks[0].command).toContain("shared.sh");
// Factory Droid-specific override should be present
expect(parsed.hooks.Stop).toBeDefined();
// Claude-specific hooks must NOT leak into Factory Droid output
expect(JSON.stringify(parsed)).not.toContain("claude-only.sh");
expect(JSON.stringify(parsed)).not.toContain("claude-notify.sh");
});

it("should throw error with descriptive message when existing settings.json contains invalid JSON", async () => {
await ensureDir(join(testDir, ".factory"));
await writeFileContent(join(testDir, ".factory", "settings.json"), "invalid json {");
Expand Down
123 changes: 16 additions & 107 deletions src/features/hooks/factorydroid-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import { join } from "node:path";

import type { AiFileParams } from "../../types/ai-file.js";
import type { ValidationResult } from "../../types/ai-file.js";
import type { HooksConfig } from "../../types/hooks.js";
import {
FACTORYDROID_HOOK_EVENTS,
FACTORYDROID_TO_CANONICAL_EVENT_NAMES,
CANONICAL_TO_FACTORYDROID_EVENT_NAMES,
} from "../../types/hooks.js";
import { formatError } from "../../utils/error.js";
import { readFileContentOrNull, readOrInitializeFileContent } from "../../utils/file.js";
import type { PascalHooksConverterConfig } from "./pascal-hooks-converter.js";
import { canonicalToPascalHooks, pascalHooksToCanonical } from "./pascal-hooks-converter.js";
import type { RulesyncHooks } from "./rulesync-hooks.js";
import {
ToolHooks,
Expand All @@ -19,112 +20,13 @@ import {
type ToolHooksSettablePaths,
} from "./tool-hooks.js";

/**
* Convert canonical hooks config to Factory Droid format.
* Factory Droid uses PascalCase event names and a matcher/hooks structure,
* with $FACTORY_PROJECT_DIR as the project directory variable.
*/
function canonicalToFactorydroidHooks(config: HooksConfig): Record<string, unknown[]> {
const supported: Set<string> = new Set(FACTORYDROID_HOOK_EVENTS);
const sharedHooks: HooksConfig["hooks"] = {};
for (const [event, defs] of Object.entries(config.hooks)) {
if (supported.has(event)) {
sharedHooks[event] = defs;
}
}
const effectiveHooks: HooksConfig["hooks"] = {
...sharedHooks,
...config.factorydroid?.hooks,
};
const result: Record<string, unknown[]> = {};
for (const [eventName, definitions] of Object.entries(effectiveHooks)) {
const pascalEventName = CANONICAL_TO_FACTORYDROID_EVENT_NAMES[eventName] ?? eventName;
const byMatcher = new Map<string, HooksConfig["hooks"][string]>();
for (const def of definitions) {
const key = def.matcher ?? "";
const list = byMatcher.get(key);
if (list) list.push(def);
else byMatcher.set(key, [def]);
}
const entries: unknown[] = [];
for (const [matcherKey, defs] of byMatcher) {
const hooks = defs.map((def) => {
const command =
def.command !== undefined && def.command !== null && !def.command.startsWith("$")
? `$FACTORY_PROJECT_DIR/${def.command.replace(/^\.\//, "")}`
: def.command;
return {
type: def.type ?? "command",
...(command !== undefined && command !== null && { command }),
...(def.timeout !== undefined && def.timeout !== null && { timeout: def.timeout }),
...(def.prompt !== undefined && def.prompt !== null && { prompt: def.prompt }),
};
});
entries.push(matcherKey ? { matcher: matcherKey, hooks } : { hooks });
}
result[pascalEventName] = entries;
}
return result;
}

type FactorydroidMatcherEntry = {
matcher?: string;
hooks?: Array<Record<string, unknown>>;
const FACTORYDROID_CONVERTER_CONFIG: PascalHooksConverterConfig = {
supportedEvents: FACTORYDROID_HOOK_EVENTS,
canonicalToToolEventNames: CANONICAL_TO_FACTORYDROID_EVENT_NAMES,
toolToCanonicalEventNames: FACTORYDROID_TO_CANONICAL_EVENT_NAMES,
projectDirVar: "$FACTORY_PROJECT_DIR",
};

function isFactorydroidMatcherEntry(x: unknown): x is FactorydroidMatcherEntry {
if (x === null || typeof x !== "object") {
return false;
}
if ("matcher" in x && typeof x.matcher !== "string") {
return false;
}
if ("hooks" in x && !Array.isArray(x.hooks)) {
return false;
}
return true;
}

function factorydroidHooksToCanonical(hooks: unknown): HooksConfig["hooks"] {
if (hooks === null || hooks === undefined || typeof hooks !== "object") {
return {};
}
const canonical: HooksConfig["hooks"] = {};
for (const [pascalEventName, matcherEntries] of Object.entries(hooks)) {
const eventName = FACTORYDROID_TO_CANONICAL_EVENT_NAMES[pascalEventName] ?? pascalEventName;
if (!Array.isArray(matcherEntries)) continue;
const defs: HooksConfig["hooks"][string] = [];
for (const rawEntry of matcherEntries) {
if (!isFactorydroidMatcherEntry(rawEntry)) continue;
const entry = rawEntry;
const hookDefs = entry.hooks ?? [];
for (const h of hookDefs) {
const cmd = typeof h.command === "string" ? h.command : undefined;
const command =
typeof cmd === "string" && cmd.includes("$FACTORY_PROJECT_DIR/")
? cmd.replace(/^\$FACTORY_PROJECT_DIR\/?/, "./")
: cmd;
const hookType = h.type === "command" || h.type === "prompt" ? h.type : "command";
const timeout = typeof h.timeout === "number" ? h.timeout : undefined;
const prompt = typeof h.prompt === "string" ? h.prompt : undefined;
defs.push({
type: hookType,
...(command !== undefined && command !== null && { command }),
...(timeout !== undefined && timeout !== null && { timeout }),
...(prompt !== undefined && prompt !== null && { prompt }),
...(entry.matcher !== undefined &&
entry.matcher !== null &&
entry.matcher !== "" && { matcher: entry.matcher }),
});
}
}
if (defs.length > 0) {
canonical[eventName] = defs;
}
}
return canonical;
}

export class FactorydroidHooks extends ToolHooks {
constructor(params: AiFileParams) {
super({
Expand Down Expand Up @@ -180,7 +82,11 @@ export class FactorydroidHooks extends ToolHooks {
);
}
const config = rulesyncHooks.getJson();
const factorydroidHooks = canonicalToFactorydroidHooks(config);
const factorydroidHooks = canonicalToPascalHooks({
config,
toolOverrideHooks: config.factorydroid?.hooks,
converterConfig: FACTORYDROID_CONVERTER_CONFIG,
});
const merged = { ...settings, hooks: factorydroidHooks };
const fileContent = JSON.stringify(merged, null, 2);
return new FactorydroidHooks({
Expand All @@ -204,7 +110,10 @@ export class FactorydroidHooks extends ToolHooks {
},
);
}
const hooks = factorydroidHooksToCanonical(settings.hooks);
const hooks = pascalHooksToCanonical({
hooks: settings.hooks,
converterConfig: FACTORYDROID_CONVERTER_CONFIG,
});
return this.toRulesyncHooksDefault({
fileContent: JSON.stringify({ version: 1, hooks }, null, 2),
});
Expand Down
Loading