diff --git a/src/agents/subagent-announce.ts b/src/agents/subagent-announce.ts index dfff96966..6db380460 100644 --- a/src/agents/subagent-announce.ts +++ b/src/agents/subagent-announce.ts @@ -16,10 +16,7 @@ import { } from "../auto-reply/reply/queue.js"; import { callGateway } from "../gateway/call.js"; import { defaultRuntime } from "../runtime.js"; -import { - isEmbeddedPiRunActive, - queueEmbeddedPiMessage, -} from "./pi-embedded.js"; +import { isEmbeddedPiRunActive, queueEmbeddedPiMessage } from "./pi-embedded.js"; import { readLatestAssistantReply } from "./tools/agent-step.js"; function formatDurationShort(valueMs?: number) { @@ -111,7 +108,10 @@ type AnnounceQueueState = { const ANNOUNCE_QUEUES = new Map(); -function getAnnounceQueue(key: string, settings: { mode: QueueMode; debounceMs?: number; cap?: number; dropPolicy?: QueueDropPolicy }) { +function getAnnounceQueue( + key: string, + settings: { mode: QueueMode; debounceMs?: number; cap?: number; dropPolicy?: QueueDropPolicy }, +) { const existing = ANNOUNCE_QUEUES.get(key); if (existing) { existing.mode = settings.mode; @@ -131,8 +131,7 @@ function getAnnounceQueue(key: string, settings: { mode: QueueMode; debounceMs?: draining: false, lastEnqueuedAt: 0, mode: settings.mode, - debounceMs: - typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1000, + debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1000, cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : 20, dropPolicy: settings.dropPolicy ?? "summarize", droppedCount: 0, @@ -341,9 +340,7 @@ function loadRequesterSessionEntry(requesterSessionKey: string) { ? canonicalKey.split(":").slice(2).join(":") : undefined; const entry = - store[canonicalKey] ?? - store[requesterSessionKey] ?? - (legacyKey ? store[legacyKey] : undefined); + store[canonicalKey] ?? store[requesterSessionKey] ?? (legacyKey ? store[legacyKey] : undefined); return { cfg, entry, canonicalKey }; } diff --git a/src/auto-reply/reply/commands-core.ts b/src/auto-reply/reply/commands-core.ts index 29715b2bb..e708aaa1d 100644 --- a/src/auto-reply/reply/commands-core.ts +++ b/src/auto-reply/reply/commands-core.ts @@ -56,18 +56,13 @@ export async function handleCommands(params: HandleCommandsParams): Promise { await handleCommands(params); - expect(spy).toHaveBeenCalledWith( - expect.objectContaining({ type: "command", action: "new" }), - ); + expect(spy).toHaveBeenCalledWith(expect.objectContaining({ type: "command", action: "new" })); spy.mockRestore(); }); }); diff --git a/src/auto-reply/reply/get-reply-inline-actions.ts b/src/auto-reply/reply/get-reply-inline-actions.ts index 31bead546..579438cbb 100644 --- a/src/auto-reply/reply/get-reply-inline-actions.ts +++ b/src/auto-reply/reply/get-reply-inline-actions.ts @@ -67,9 +67,9 @@ export async function handleInlineActions(params: { sessionCtx, cfg, agentId, - sessionEntry, - previousSessionEntry, - sessionStore, + sessionEntry, + previousSessionEntry, + sessionStore, sessionKey, storePath, sessionScope, diff --git a/src/cli/hooks-internal-cli.ts b/src/cli/hooks-internal-cli.ts index 774aa6eab..4ca110a81 100644 --- a/src/cli/hooks-internal-cli.ts +++ b/src/cli/hooks-internal-cli.ts @@ -202,9 +202,7 @@ export function formatHookInfo( } if (hook.requirements.config.length > 0) { const configStatus = hook.configChecks.map((check) => { - return check.satisfied - ? chalk.green(`āœ“ ${check.path}`) - : chalk.red(`āœ— ${check.path}`); + return check.satisfied ? chalk.green(`āœ“ ${check.path}`) : chalk.red(`āœ— ${check.path}`); }); lines.push(` Config: ${configStatus.join(", ")}`); } @@ -265,8 +263,7 @@ export function formatHooksCheck(report: HookStatusReport, opts: HooksCheckOptio if (hook.missing.anyBins.length > 0) reasons.push(`anyBins: ${hook.missing.anyBins.join(", ")}`); if (hook.missing.env.length > 0) reasons.push(`env: ${hook.missing.env.join(", ")}`); - if (hook.missing.config.length > 0) - reasons.push(`config: ${hook.missing.config.join(", ")}`); + if (hook.missing.config.length > 0) reasons.push(`config: ${hook.missing.config.join(", ")}`); if (hook.missing.os.length > 0) reasons.push(`os: ${hook.missing.os.join(", ")}`); lines.push(` ${hook.emoji ?? "šŸ”—"} ${hook.name} - ${reasons.join("; ")}`); } diff --git a/src/commands/onboard-hooks.test.ts b/src/commands/onboard-hooks.test.ts index c8cb8cd1b..ddb769668 100644 --- a/src/commands/onboard-hooks.test.ts +++ b/src/commands/onboard-hooks.test.ts @@ -1,21 +1,21 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { setupInternalHooks } from './onboard-hooks.js'; -import type { ClawdbotConfig } from '../config/config.js'; -import type { RuntimeEnv } from '../runtime.js'; -import type { WizardPrompter } from '../wizard/prompts.js'; -import type { HookStatusReport } from '../hooks/hooks-status.js'; +import { describe, expect, it, vi, beforeEach } from "vitest"; +import { setupInternalHooks } from "./onboard-hooks.js"; +import type { ClawdbotConfig } from "../config/config.js"; +import type { RuntimeEnv } from "../runtime.js"; +import type { WizardPrompter } from "../wizard/prompts.js"; +import type { HookStatusReport } from "../hooks/hooks-status.js"; // Mock hook discovery modules -vi.mock('../hooks/hooks-status.js', () => ({ +vi.mock("../hooks/hooks-status.js", () => ({ buildWorkspaceHookStatus: vi.fn(), })); -vi.mock('../agents/agent-scope.js', () => ({ - resolveAgentWorkspaceDir: vi.fn().mockReturnValue('/mock/workspace'), - resolveDefaultAgentId: vi.fn().mockReturnValue('main'), +vi.mock("../agents/agent-scope.js", () => ({ + resolveAgentWorkspaceDir: vi.fn().mockReturnValue("/mock/workspace"), + resolveDefaultAgentId: vi.fn().mockReturnValue("main"), })); -describe('onboard-hooks', () => { +describe("onboard-hooks", () => { beforeEach(() => { vi.clearAllMocks(); }); @@ -25,8 +25,8 @@ describe('onboard-hooks', () => { note: vi.fn().mockResolvedValue(undefined), intro: vi.fn().mockResolvedValue(undefined), outro: vi.fn().mockResolvedValue(undefined), - text: vi.fn().mockResolvedValue(''), - select: vi.fn().mockResolvedValue(''), + text: vi.fn().mockResolvedValue(""), + select: vi.fn().mockResolvedValue(""), multiselect: vi.fn().mockResolvedValue(multiselectValue), progress: vi.fn().mockReturnValue({ stop: vi.fn(), @@ -41,58 +41,58 @@ describe('onboard-hooks', () => { }); const createMockHookReport = (eligible = true): HookStatusReport => ({ - workspaceDir: '/mock/workspace', - managedHooksDir: '/mock/.clawdbot/hooks', + workspaceDir: "/mock/workspace", + managedHooksDir: "/mock/.clawdbot/hooks", hooks: [ { - name: 'session-memory', - description: 'Save session context to memory when /new command is issued', - source: 'clawdbot-bundled', - emoji: 'šŸ’¾', - events: ['command:new'], + name: "session-memory", + description: "Save session context to memory when /new command is issued", + source: "clawdbot-bundled", + emoji: "šŸ’¾", + events: ["command:new"], disabled: false, eligible, - requirements: { config: ['workspace.dir'] }, + requirements: { config: ["workspace.dir"] }, missing: {}, }, ], }); - describe('setupInternalHooks', () => { - it('should enable internal hooks when user selects them', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + describe("setupInternalHooks", () => { + it("should enable internal hooks when user selects them", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); const cfg: ClawdbotConfig = {}; - const prompter = createMockPrompter(['session-memory']); + const prompter = createMockPrompter(["session-memory"]); const runtime = createMockRuntime(); const result = await setupInternalHooks(cfg, runtime, prompter); expect(result.hooks?.internal?.enabled).toBe(true); expect(result.hooks?.internal?.entries).toEqual({ - 'session-memory': { enabled: true }, + "session-memory": { enabled: true }, }); expect(prompter.note).toHaveBeenCalledTimes(2); expect(prompter.multiselect).toHaveBeenCalledWith({ - message: 'Enable internal hooks?', + message: "Enable internal hooks?", options: [ - { value: '__skip__', label: 'Skip for now' }, + { value: "__skip__", label: "Skip for now" }, { - value: 'session-memory', - label: 'šŸ’¾ session-memory', - hint: 'Save session context to memory when /new command is issued', + value: "session-memory", + label: "šŸ’¾ session-memory", + hint: "Save session context to memory when /new command is issued", }, ], }); }); - it('should not enable hooks when user skips', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + it("should not enable hooks when user skips", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); const cfg: ClawdbotConfig = {}; - const prompter = createMockPrompter(['__skip__']); + const prompter = createMockPrompter(["__skip__"]); const runtime = createMockRuntime(); const result = await setupInternalHooks(cfg, runtime, prompter); @@ -101,8 +101,8 @@ describe('onboard-hooks', () => { expect(prompter.note).toHaveBeenCalledTimes(1); }); - it('should handle no eligible hooks', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + it("should handle no eligible hooks", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport(false)); const cfg: ClawdbotConfig = {}; @@ -114,58 +114,58 @@ describe('onboard-hooks', () => { expect(result).toEqual(cfg); expect(prompter.multiselect).not.toHaveBeenCalled(); expect(prompter.note).toHaveBeenCalledWith( - 'No eligible hooks found. You can configure hooks later in your config.', - 'No Hooks Available', + "No eligible hooks found. You can configure hooks later in your config.", + "No Hooks Available", ); }); - it('should preserve existing hooks config when enabled', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + it("should preserve existing hooks config when enabled", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); const cfg: ClawdbotConfig = { hooks: { enabled: true, - path: '/webhook', - token: 'existing-token', + path: "/webhook", + token: "existing-token", }, }; - const prompter = createMockPrompter(['session-memory']); + const prompter = createMockPrompter(["session-memory"]); const runtime = createMockRuntime(); const result = await setupInternalHooks(cfg, runtime, prompter); expect(result.hooks?.enabled).toBe(true); - expect(result.hooks?.path).toBe('/webhook'); - expect(result.hooks?.token).toBe('existing-token'); + expect(result.hooks?.path).toBe("/webhook"); + expect(result.hooks?.token).toBe("existing-token"); expect(result.hooks?.internal?.enabled).toBe(true); expect(result.hooks?.internal?.entries).toEqual({ - 'session-memory': { enabled: true }, + "session-memory": { enabled: true }, }); }); - it('should preserve existing config when user skips', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + it("should preserve existing config when user skips", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); const cfg: ClawdbotConfig = { - agents: { defaults: { workspace: '/workspace' } }, + agents: { defaults: { workspace: "/workspace" } }, }; - const prompter = createMockPrompter(['__skip__']); + const prompter = createMockPrompter(["__skip__"]); const runtime = createMockRuntime(); const result = await setupInternalHooks(cfg, runtime, prompter); expect(result).toEqual(cfg); - expect(result.agents?.defaults?.workspace).toBe('/workspace'); + expect(result.agents?.defaults?.workspace).toBe("/workspace"); }); - it('should show informative notes to user', async () => { - const { buildWorkspaceHookStatus } = await import('../hooks/hooks-status.js'); + it("should show informative notes to user", async () => { + const { buildWorkspaceHookStatus } = await import("../hooks/hooks-status.js"); vi.mocked(buildWorkspaceHookStatus).mockReturnValue(createMockHookReport()); const cfg: ClawdbotConfig = {}; - const prompter = createMockPrompter(['session-memory']); + const prompter = createMockPrompter(["session-memory"]); const runtime = createMockRuntime(); await setupInternalHooks(cfg, runtime, prompter); @@ -174,12 +174,12 @@ describe('onboard-hooks', () => { expect(noteCalls).toHaveLength(2); // First note should explain what internal hooks are - expect(noteCalls[0][0]).toContain('Internal hooks'); - expect(noteCalls[0][0]).toContain('automate actions'); + expect(noteCalls[0][0]).toContain("Internal hooks"); + expect(noteCalls[0][0]).toContain("automate actions"); // Second note should confirm configuration - expect(noteCalls[1][0]).toContain('Enabled 1 hook: session-memory'); - expect(noteCalls[1][0]).toContain('clawdbot hooks internal list'); + expect(noteCalls[1][0]).toContain("Enabled 1 hook: session-memory"); + expect(noteCalls[1][0]).toContain("clawdbot hooks internal list"); }); }); }); diff --git a/src/commands/onboard-hooks.ts b/src/commands/onboard-hooks.ts index ba622d4b0..06ec83ff8 100644 --- a/src/commands/onboard-hooks.ts +++ b/src/commands/onboard-hooks.ts @@ -24,9 +24,7 @@ export async function setupInternalHooks( const report = buildWorkspaceHookStatus(workspaceDir, { config: cfg }); // Filter for eligible and recommended hooks (session-memory is recommended) - const recommendedHooks = report.hooks.filter( - (h) => h.eligible && h.name === "session-memory", - ); + const recommendedHooks = report.hooks.filter((h) => h.eligible && h.name === "session-memory"); if (recommendedHooks.length === 0) { await prompter.note( diff --git a/src/gateway/server-startup.ts b/src/gateway/server-startup.ts index b6a482184..df178e8d5 100644 --- a/src/gateway/server-startup.ts +++ b/src/gateway/server-startup.ts @@ -98,7 +98,9 @@ export async function startGatewaySidecars(params: { clearInternalHooks(); const loadedCount = await loadInternalHooks(params.cfg, params.defaultWorkspaceDir); if (loadedCount > 0) { - params.logHooks.info(`loaded ${loadedCount} internal hook handler${loadedCount > 1 ? 's' : ''}`); + params.logHooks.info( + `loaded ${loadedCount} internal hook handler${loadedCount > 1 ? "s" : ""}`, + ); } } catch (err) { params.logHooks.error(`failed to load internal hooks: ${String(err)}`); diff --git a/src/hooks/bundled/README.md b/src/hooks/bundled/README.md index 10579c293..b09ddafb2 100644 --- a/src/hooks/bundled/README.md +++ b/src/hooks/bundled/README.md @@ -13,6 +13,7 @@ Automatically saves session context to memory when you issue `/new`. **Output**: `/memory/YYYY-MM-DD-slug.md` (defaults to `~/clawd`) **Enable**: + ```bash clawdbot hooks internal enable session-memory ``` @@ -26,6 +27,7 @@ Logs all command events to a centralized audit file. **Output**: `~/.clawdbot/logs/commands.log` **Enable**: + ```bash clawdbot hooks internal enable command-logger ``` @@ -38,6 +40,7 @@ Each hook is a directory containing: - **handler.ts**: The hook handler function (default export) Example structure: + ``` session-memory/ ā”œā”€ā”€ HOOK.md # Metadata + docs @@ -51,9 +54,9 @@ session-memory/ name: my-hook description: "Short description" homepage: https://docs.clawd.bot/hooks/my-hook -metadata: {"clawdbot":{"emoji":"šŸ”—","events":["command:new"],"requires":{"bins":["node"]}}} +metadata: + { "clawdbot": { "emoji": "šŸ”—", "events": ["command:new"], "requires": { "bins": ["node"] } } } --- - # Hook Title Documentation goes here... @@ -83,21 +86,25 @@ Custom hooks follow the same structure as bundled hooks. ## Managing Hooks List all hooks: + ```bash clawdbot hooks internal list ``` Show hook details: + ```bash clawdbot hooks internal info session-memory ``` Check hook status: + ```bash clawdbot hooks internal check ``` Enable/disable: + ```bash clawdbot hooks internal enable session-memory clawdbot hooks internal disable command-logger @@ -142,30 +149,30 @@ Hook handlers receive an `InternalHookEvent` object: ```typescript interface InternalHookEvent { - type: 'command' | 'session' | 'agent'; - action: string; // e.g., 'new', 'reset', 'stop' + type: "command" | "session" | "agent"; + action: string; // e.g., 'new', 'reset', 'stop' sessionKey: string; context: Record; timestamp: Date; - messages: string[]; // Push messages here to send to user + messages: string[]; // Push messages here to send to user } ``` Example handler: ```typescript -import type { InternalHookHandler } from '../../src/hooks/internal-hooks.js'; +import type { InternalHookHandler } from "../../src/hooks/internal-hooks.js"; const myHandler: InternalHookHandler = async (event) => { - if (event.type !== 'command' || event.action !== 'new') { + if (event.type !== "command" || event.action !== "new") { return; } // Your logic here - console.log('New command triggered!'); + console.log("New command triggered!"); // Optionally send message to user - event.messages.push('✨ Hook executed!'); + event.messages.push("✨ Hook executed!"); }; export default myHandler; diff --git a/src/hooks/bundled/command-logger/HOOK.md b/src/hooks/bundled/command-logger/HOOK.md index 4f579ab7d..24799cd8d 100644 --- a/src/hooks/bundled/command-logger/HOOK.md +++ b/src/hooks/bundled/command-logger/HOOK.md @@ -2,7 +2,15 @@ name: command-logger description: "Log all command events to a centralized audit file" homepage: https://docs.clawd.bot/internal-hooks#command-logger -metadata: {"clawdbot":{"emoji":"šŸ“","events":["command"],"install":[{"id":"bundled","kind":"bundled","label":"Bundled with Clawdbot"}]}} +metadata: + { + "clawdbot": + { + "emoji": "šŸ“", + "events": ["command"], + "install": [{ "id": "bundled", "kind": "bundled", "label": "Bundled with Clawdbot" }], + }, + } --- # Command Logger Hook @@ -44,6 +52,7 @@ No requirements - this hook works out of the box on all platforms. ## Configuration No configuration needed. The hook automatically: + - Creates the log directory if it doesn't exist - Appends to the log file (doesn't overwrite) - Handles errors silently without disrupting command execution @@ -75,6 +84,7 @@ Or via config: The hook does not automatically rotate logs. To manage log size, you can: 1. **Manual rotation**: + ```bash mv ~/.clawdbot/logs/commands.log ~/.clawdbot/logs/commands.log.old ``` @@ -94,16 +104,19 @@ The hook does not automatically rotate logs. To manage log size, you can: ## Viewing Logs View recent commands: + ```bash tail -n 20 ~/.clawdbot/logs/commands.log ``` Pretty-print with jq: + ```bash cat ~/.clawdbot/logs/commands.log | jq . ``` Filter by action: + ```bash grep '"action":"new"' ~/.clawdbot/logs/commands.log | jq . ``` diff --git a/src/hooks/bundled/command-logger/handler.ts b/src/hooks/bundled/command-logger/handler.ts index bc0a2ae7b..adeade81a 100644 --- a/src/hooks/bundled/command-logger/handler.ts +++ b/src/hooks/bundled/command-logger/handler.ts @@ -23,40 +23,41 @@ * ``` */ -import fs from 'node:fs/promises'; -import path from 'node:path'; -import os from 'node:os'; -import type { InternalHookHandler } from '../../internal-hooks.js'; +import fs from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; +import type { InternalHookHandler } from "../../internal-hooks.js"; /** * Log all command events to a file */ const logCommand: InternalHookHandler = async (event) => { // Only trigger on command events - if (event.type !== 'command') { + if (event.type !== "command") { return; } try { // Create log directory - const logDir = path.join(os.homedir(), '.clawdbot', 'logs'); + const logDir = path.join(os.homedir(), ".clawdbot", "logs"); await fs.mkdir(logDir, { recursive: true }); // Append to command log file - const logFile = path.join(logDir, 'commands.log'); - const logLine = JSON.stringify({ - timestamp: event.timestamp.toISOString(), - action: event.action, - sessionKey: event.sessionKey, - senderId: event.context.senderId ?? 'unknown', - source: event.context.commandSource ?? 'unknown', - }) + '\n'; + const logFile = path.join(logDir, "commands.log"); + const logLine = + JSON.stringify({ + timestamp: event.timestamp.toISOString(), + action: event.action, + sessionKey: event.sessionKey, + senderId: event.context.senderId ?? "unknown", + source: event.context.commandSource ?? "unknown", + }) + "\n"; - await fs.appendFile(logFile, logLine, 'utf-8'); + await fs.appendFile(logFile, logLine, "utf-8"); } catch (err) { console.error( - '[command-logger] Failed to log command:', - err instanceof Error ? err.message : String(err) + "[command-logger] Failed to log command:", + err instanceof Error ? err.message : String(err), ); } }; diff --git a/src/hooks/bundled/session-memory/HOOK.md b/src/hooks/bundled/session-memory/HOOK.md index 04032a76a..cb74c41d4 100644 --- a/src/hooks/bundled/session-memory/HOOK.md +++ b/src/hooks/bundled/session-memory/HOOK.md @@ -2,7 +2,16 @@ name: session-memory description: "Save session context to memory when /new command is issued" homepage: https://docs.clawd.bot/internal-hooks#session-memory -metadata: {"clawdbot":{"emoji":"šŸ’¾","events":["command:new"],"requires":{"config":["workspace.dir"]},"install":[{"id":"bundled","kind":"bundled","label":"Bundled with Clawdbot"}]}} +metadata: + { + "clawdbot": + { + "emoji": "šŸ’¾", + "events": ["command:new"], + "requires": { "config": ["workspace.dir"] }, + "install": [{ "id": "bundled", "kind": "bundled", "label": "Bundled with Clawdbot" }], + }, + } --- # Session Memory Hook @@ -49,6 +58,7 @@ The hook uses your configured LLM provider to generate slugs, so it works with a ## Configuration No additional configuration required. The hook automatically: + - Uses your workspace directory (`~/clawd` by default) - Uses your configured LLM for slug generation - Falls back to timestamp slugs if LLM is unavailable diff --git a/src/hooks/bundled/session-memory/handler.ts b/src/hooks/bundled/session-memory/handler.ts index c5ddde484..56408456f 100644 --- a/src/hooks/bundled/session-memory/handler.ts +++ b/src/hooks/bundled/session-memory/handler.ts @@ -5,21 +5,21 @@ * Creates a new dated memory file with LLM-generated slug */ -import fs from 'node:fs/promises'; -import path from 'node:path'; -import os from 'node:os'; -import type { ClawdbotConfig } from '../../../config/config.js'; -import { resolveAgentWorkspaceDir } from '../../../agents/agent-scope.js'; -import { resolveAgentIdFromSessionKey } from '../../../routing/session-key.js'; -import type { InternalHookHandler } from '../../internal-hooks.js'; +import fs from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; +import type { ClawdbotConfig } from "../../../config/config.js"; +import { resolveAgentWorkspaceDir } from "../../../agents/agent-scope.js"; +import { resolveAgentIdFromSessionKey } from "../../../routing/session-key.js"; +import type { InternalHookHandler } from "../../internal-hooks.js"; /** * Read recent messages from session file for slug generation */ async function getRecentSessionContent(sessionFilePath: string): Promise { try { - const content = await fs.readFile(sessionFilePath, 'utf-8'); - const lines = content.trim().split('\n'); + const content = await fs.readFile(sessionFilePath, "utf-8"); + const lines = content.trim().split("\n"); // Get last 15 lines (recent conversation) const recentLines = lines.slice(-15); @@ -30,15 +30,15 @@ async function getRecentSessionContent(sessionFilePath: string): Promise c.type === 'text')?.text + ? msg.content.find((c: any) => c.type === "text")?.text : msg.content; - if (text && !text.startsWith('/')) { + if (text && !text.startsWith("/")) { messages.push(`${role}: ${text}`); } } @@ -48,7 +48,7 @@ async function getRecentSessionContent(sessionFilePath: string): Promise { // Only trigger on 'new' command - if (event.type !== 'command' || event.action !== 'new') { + if (event.type !== "command" || event.action !== "new") { return; } try { - console.log('[session-memory] Hook triggered for /new command'); + console.log("[session-memory] Hook triggered for /new command"); const context = event.context || {}; const cfg = context.cfg as ClawdbotConfig | undefined; const agentId = resolveAgentIdFromSessionKey(event.sessionKey); const workspaceDir = cfg ? resolveAgentWorkspaceDir(cfg, agentId) - : path.join(os.homedir(), 'clawd'); - const memoryDir = path.join(workspaceDir, 'memory'); + : path.join(os.homedir(), "clawd"); + const memoryDir = path.join(workspaceDir, "memory"); await fs.mkdir(memoryDir, { recursive: true }); // Get today's date for filename const now = new Date(event.timestamp); - const dateStr = now.toISOString().split('T')[0]; // YYYY-MM-DD + const dateStr = now.toISOString().split("T")[0]; // YYYY-MM-DD // Generate descriptive slug from session using LLM - const sessionEntry = ( - context.previousSessionEntry || - context.sessionEntry || - {} - ) as Record; + const sessionEntry = (context.previousSessionEntry || context.sessionEntry || {}) as Record< + string, + unknown + >; const currentSessionId = sessionEntry.sessionId as string; const currentSessionFile = sessionEntry.sessionFile as string; - console.log('[session-memory] Current sessionId:', currentSessionId); - console.log('[session-memory] Current sessionFile:', currentSessionFile); - console.log('[session-memory] cfg present:', !!cfg); + console.log("[session-memory] Current sessionId:", currentSessionId); + console.log("[session-memory] Current sessionFile:", currentSessionFile); + console.log("[session-memory] cfg present:", !!cfg); const sessionFile = currentSessionFile || undefined; @@ -100,73 +99,76 @@ const saveSessionToMemory: InternalHookHandler = async (event) => { if (sessionFile) { // Get recent conversation content sessionContent = await getRecentSessionContent(sessionFile); - console.log('[session-memory] sessionContent length:', sessionContent?.length || 0); + console.log("[session-memory] sessionContent length:", sessionContent?.length || 0); if (sessionContent && cfg) { - console.log('[session-memory] Calling generateSlugViaLLM...'); + console.log("[session-memory] Calling generateSlugViaLLM..."); // Dynamically import the LLM slug generator (avoids module caching issues) // When compiled, handler is at dist/hooks/bundled/session-memory/handler.js // Going up ../.. puts us at dist/hooks/, so just add llm-slug-generator.js - const clawdbotRoot = path.resolve(path.dirname(import.meta.url.replace('file://', '')), '../..'); - const slugGenPath = path.join(clawdbotRoot, 'llm-slug-generator.js'); + const clawdbotRoot = path.resolve( + path.dirname(import.meta.url.replace("file://", "")), + "../..", + ); + const slugGenPath = path.join(clawdbotRoot, "llm-slug-generator.js"); const { generateSlugViaLLM } = await import(slugGenPath); // Use LLM to generate a descriptive slug slug = await generateSlugViaLLM({ sessionContent, cfg }); - console.log('[session-memory] Generated slug:', slug); + console.log("[session-memory] Generated slug:", slug); } } // If no slug, use timestamp if (!slug) { - const timeSlug = now.toISOString().split('T')[1]!.split('.')[0]!.replace(/:/g, ''); + const timeSlug = now.toISOString().split("T")[1]!.split(".")[0]!.replace(/:/g, ""); slug = timeSlug.slice(0, 4); // HHMM - console.log('[session-memory] Using fallback timestamp slug:', slug); + console.log("[session-memory] Using fallback timestamp slug:", slug); } // Create filename with date and slug const filename = `${dateStr}-${slug}.md`; const memoryFilePath = path.join(memoryDir, filename); - console.log('[session-memory] Generated filename:', filename); - console.log('[session-memory] Full path:', memoryFilePath); + console.log("[session-memory] Generated filename:", filename); + console.log("[session-memory] Full path:", memoryFilePath); // Format time as HH:MM:SS UTC - const timeStr = now.toISOString().split('T')[1]!.split('.')[0]; + const timeStr = now.toISOString().split("T")[1]!.split(".")[0]; // Extract context details - const sessionId = (sessionEntry.sessionId as string) || 'unknown'; - const source = (context.commandSource as string) || 'unknown'; + const sessionId = (sessionEntry.sessionId as string) || "unknown"; + const source = (context.commandSource as string) || "unknown"; // Build Markdown entry const entryParts = [ `# Session: ${dateStr} ${timeStr} UTC`, - '', + "", `- **Session Key**: ${event.sessionKey}`, `- **Session ID**: ${sessionId}`, `- **Source**: ${source}`, - '', + "", ]; // Include conversation content if available if (sessionContent) { - entryParts.push('## Conversation Summary', '', sessionContent, ''); + entryParts.push("## Conversation Summary", "", sessionContent, ""); } - const entry = entryParts.join('\n'); + const entry = entryParts.join("\n"); // Write to new memory file - await fs.writeFile(memoryFilePath, entry, 'utf-8'); - console.log('[session-memory] Memory file written successfully'); + await fs.writeFile(memoryFilePath, entry, "utf-8"); + console.log("[session-memory] Memory file written successfully"); // Send confirmation message to user with filename - const relPath = memoryFilePath.replace(os.homedir(), '~'); + const relPath = memoryFilePath.replace(os.homedir(), "~"); const confirmMsg = `šŸ’¾ Session context saved to memory before reset.\nšŸ“„ ${relPath}`; event.messages.push(confirmMsg); - console.log('[session-memory] Confirmation message queued:', confirmMsg); + console.log("[session-memory] Confirmation message queued:", confirmMsg); } catch (err) { console.error( - '[session-memory] Failed to save session memory:', - err instanceof Error ? err.message : String(err) + "[session-memory] Failed to save session memory:", + err instanceof Error ? err.message : String(err), ); } }; diff --git a/src/hooks/frontmatter.ts b/src/hooks/frontmatter.ts index 53bb6941f..26f3c0ffb 100644 --- a/src/hooks/frontmatter.ts +++ b/src/hooks/frontmatter.ts @@ -84,12 +84,7 @@ function parseFrontmatterBool(value: string | undefined, fallback: boolean): boo if (normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on") { return true; } - if ( - normalized === "false" || - normalized === "0" || - normalized === "no" || - normalized === "off" - ) { + if (normalized === "false" || normalized === "0" || normalized === "no" || normalized === "off") { return false; } return fallback; diff --git a/src/hooks/hooks-status.ts b/src/hooks/hooks-status.ts index a3ddd30d4..4ca73b3e8 100644 --- a/src/hooks/hooks-status.ts +++ b/src/hooks/hooks-status.ts @@ -2,17 +2,8 @@ import path from "node:path"; import type { ClawdbotConfig } from "../config/config.js"; import { CONFIG_DIR } from "../utils.js"; -import { - hasBinary, - isConfigPathTruthy, - resolveConfigPath, - resolveHookConfig, -} from "./config.js"; -import type { - HookEligibilityContext, - HookEntry, - HookInstallSpec, -} from "./types.js"; +import { hasBinary, isConfigPathTruthy, resolveConfigPath, resolveHookConfig } from "./config.js"; +import type { HookEligibilityContext, HookEntry, HookInstallSpec } from "./types.js"; import { loadWorkspaceHookEntries } from "./workspace.js"; export type HookStatusConfigCheck = { @@ -155,9 +146,7 @@ function buildHookStatus( return { path: pathStr, value, satisfied }; }); - const missingConfig = configChecks - .filter((check) => !check.satisfied) - .map((check) => check.path); + const missingConfig = configChecks.filter((check) => !check.satisfied).map((check) => check.path); const missing = always ? { bins: [], anyBins: [], env: [], config: [], os: [] } diff --git a/src/hooks/internal-hooks.test.ts b/src/hooks/internal-hooks.test.ts index 217ac3894..06645c6ac 100644 --- a/src/hooks/internal-hooks.test.ts +++ b/src/hooks/internal-hooks.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { clearInternalHooks, createInternalHookEvent, @@ -7,9 +7,9 @@ import { triggerInternalHook, unregisterInternalHook, type InternalHookEvent, -} from './internal-hooks.js'; +} from "./internal-hooks.js"; -describe('internal-hooks', () => { +describe("internal-hooks", () => { beforeEach(() => { clearInternalHooks(); }); @@ -18,174 +18,174 @@ describe('internal-hooks', () => { clearInternalHooks(); }); - describe('registerInternalHook', () => { - it('should register a hook handler', () => { + describe("registerInternalHook", () => { + it("should register a hook handler", () => { const handler = vi.fn(); - registerInternalHook('command:new', handler); + registerInternalHook("command:new", handler); const keys = getRegisteredEventKeys(); - expect(keys).toContain('command:new'); + expect(keys).toContain("command:new"); }); - it('should allow multiple handlers for the same event', () => { + it("should allow multiple handlers for the same event", () => { const handler1 = vi.fn(); const handler2 = vi.fn(); - registerInternalHook('command:new', handler1); - registerInternalHook('command:new', handler2); + registerInternalHook("command:new", handler1); + registerInternalHook("command:new", handler2); const keys = getRegisteredEventKeys(); - expect(keys).toContain('command:new'); + expect(keys).toContain("command:new"); }); }); - describe('unregisterInternalHook', () => { - it('should unregister a specific handler', () => { + describe("unregisterInternalHook", () => { + it("should unregister a specific handler", () => { const handler1 = vi.fn(); const handler2 = vi.fn(); - registerInternalHook('command:new', handler1); - registerInternalHook('command:new', handler2); + registerInternalHook("command:new", handler1); + registerInternalHook("command:new", handler2); - unregisterInternalHook('command:new', handler1); + unregisterInternalHook("command:new", handler1); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); void triggerInternalHook(event); expect(handler1).not.toHaveBeenCalled(); expect(handler2).toHaveBeenCalled(); }); - it('should clean up empty handler arrays', () => { + it("should clean up empty handler arrays", () => { const handler = vi.fn(); - registerInternalHook('command:new', handler); - unregisterInternalHook('command:new', handler); + registerInternalHook("command:new", handler); + unregisterInternalHook("command:new", handler); const keys = getRegisteredEventKeys(); - expect(keys).not.toContain('command:new'); + expect(keys).not.toContain("command:new"); }); }); - describe('triggerInternalHook', () => { - it('should trigger handlers for general event type', async () => { + describe("triggerInternalHook", () => { + it("should trigger handlers for general event type", async () => { const handler = vi.fn(); - registerInternalHook('command', handler); + registerInternalHook("command", handler); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); expect(handler).toHaveBeenCalledWith(event); }); - it('should trigger handlers for specific event action', async () => { + it("should trigger handlers for specific event action", async () => { const handler = vi.fn(); - registerInternalHook('command:new', handler); + registerInternalHook("command:new", handler); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); expect(handler).toHaveBeenCalledWith(event); }); - it('should trigger both general and specific handlers', async () => { + it("should trigger both general and specific handlers", async () => { const generalHandler = vi.fn(); const specificHandler = vi.fn(); - registerInternalHook('command', generalHandler); - registerInternalHook('command:new', specificHandler); + registerInternalHook("command", generalHandler); + registerInternalHook("command:new", specificHandler); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); expect(generalHandler).toHaveBeenCalledWith(event); expect(specificHandler).toHaveBeenCalledWith(event); }); - it('should handle async handlers', async () => { + it("should handle async handlers", async () => { const handler = vi.fn(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); }); - registerInternalHook('command:new', handler); + registerInternalHook("command:new", handler); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); expect(handler).toHaveBeenCalledWith(event); }); - it('should catch and log errors from handlers', async () => { - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + it("should catch and log errors from handlers", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); const errorHandler = vi.fn(() => { - throw new Error('Handler failed'); + throw new Error("Handler failed"); }); const successHandler = vi.fn(); - registerInternalHook('command:new', errorHandler); - registerInternalHook('command:new', successHandler); + registerInternalHook("command:new", errorHandler); + registerInternalHook("command:new", successHandler); - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); expect(errorHandler).toHaveBeenCalled(); expect(successHandler).toHaveBeenCalled(); expect(consoleError).toHaveBeenCalledWith( - expect.stringContaining('Internal hook error'), - expect.stringContaining('Handler failed') + expect.stringContaining("Internal hook error"), + expect.stringContaining("Handler failed"), ); consoleError.mockRestore(); }); - it('should not throw if no handlers are registered', async () => { - const event = createInternalHookEvent('command', 'new', 'test-session'); + it("should not throw if no handlers are registered", async () => { + const event = createInternalHookEvent("command", "new", "test-session"); await expect(triggerInternalHook(event)).resolves.not.toThrow(); }); }); - describe('createInternalHookEvent', () => { - it('should create a properly formatted event', () => { - const event = createInternalHookEvent('command', 'new', 'test-session', { - foo: 'bar', + describe("createInternalHookEvent", () => { + it("should create a properly formatted event", () => { + const event = createInternalHookEvent("command", "new", "test-session", { + foo: "bar", }); - expect(event.type).toBe('command'); - expect(event.action).toBe('new'); - expect(event.sessionKey).toBe('test-session'); - expect(event.context).toEqual({ foo: 'bar' }); + expect(event.type).toBe("command"); + expect(event.action).toBe("new"); + expect(event.sessionKey).toBe("test-session"); + expect(event.context).toEqual({ foo: "bar" }); expect(event.timestamp).toBeInstanceOf(Date); }); - it('should use empty context if not provided', () => { - const event = createInternalHookEvent('command', 'new', 'test-session'); + it("should use empty context if not provided", () => { + const event = createInternalHookEvent("command", "new", "test-session"); expect(event.context).toEqual({}); }); }); - describe('getRegisteredEventKeys', () => { - it('should return all registered event keys', () => { - registerInternalHook('command:new', vi.fn()); - registerInternalHook('command:stop', vi.fn()); - registerInternalHook('session:start', vi.fn()); + describe("getRegisteredEventKeys", () => { + it("should return all registered event keys", () => { + registerInternalHook("command:new", vi.fn()); + registerInternalHook("command:stop", vi.fn()); + registerInternalHook("session:start", vi.fn()); const keys = getRegisteredEventKeys(); - expect(keys).toContain('command:new'); - expect(keys).toContain('command:stop'); - expect(keys).toContain('session:start'); + expect(keys).toContain("command:new"); + expect(keys).toContain("command:stop"); + expect(keys).toContain("session:start"); }); - it('should return empty array when no handlers are registered', () => { + it("should return empty array when no handlers are registered", () => { const keys = getRegisteredEventKeys(); expect(keys).toEqual([]); }); }); - describe('clearInternalHooks', () => { - it('should remove all registered handlers', () => { - registerInternalHook('command:new', vi.fn()); - registerInternalHook('command:stop', vi.fn()); + describe("clearInternalHooks", () => { + it("should remove all registered handlers", () => { + registerInternalHook("command:new", vi.fn()); + registerInternalHook("command:stop", vi.fn()); clearInternalHooks(); @@ -194,33 +194,33 @@ describe('internal-hooks', () => { }); }); - describe('integration', () => { - it('should handle a complete hook lifecycle', async () => { + describe("integration", () => { + it("should handle a complete hook lifecycle", async () => { const results: InternalHookEvent[] = []; const handler = vi.fn((event: InternalHookEvent) => { results.push(event); }); // Register - registerInternalHook('command:new', handler); + registerInternalHook("command:new", handler); // Trigger - const event1 = createInternalHookEvent('command', 'new', 'session-1'); + const event1 = createInternalHookEvent("command", "new", "session-1"); await triggerInternalHook(event1); - const event2 = createInternalHookEvent('command', 'new', 'session-2'); + const event2 = createInternalHookEvent("command", "new", "session-2"); await triggerInternalHook(event2); // Verify expect(results).toHaveLength(2); - expect(results[0].sessionKey).toBe('session-1'); - expect(results[1].sessionKey).toBe('session-2'); + expect(results[0].sessionKey).toBe("session-1"); + expect(results[1].sessionKey).toBe("session-2"); // Unregister - unregisterInternalHook('command:new', handler); + unregisterInternalHook("command:new", handler); // Trigger again - should not call handler - const event3 = createInternalHookEvent('command', 'new', 'session-3'); + const event3 = createInternalHookEvent("command", "new", "session-3"); await triggerInternalHook(event3); expect(results).toHaveLength(2); diff --git a/src/hooks/internal-hooks.ts b/src/hooks/internal-hooks.ts index 6f1b91d8b..dfb31f4ce 100644 --- a/src/hooks/internal-hooks.ts +++ b/src/hooks/internal-hooks.ts @@ -5,7 +5,7 @@ * like command processing, session lifecycle, etc. */ -export type InternalHookEventType = 'command' | 'session' | 'agent'; +export type InternalHookEventType = "command" | "session" | "agent"; export interface InternalHookEvent { /** The type of event (command, session, agent, etc.) */ @@ -46,10 +46,7 @@ const handlers = new Map(); * }); * ``` */ -export function registerInternalHook( - eventKey: string, - handler: InternalHookHandler -): void { +export function registerInternalHook(eventKey: string, handler: InternalHookHandler): void { if (!handlers.has(eventKey)) { handlers.set(eventKey, []); } @@ -62,10 +59,7 @@ export function registerInternalHook( * @param eventKey - Event key the handler was registered for * @param handler - The handler function to remove */ -export function unregisterInternalHook( - eventKey: string, - handler: InternalHookHandler -): void { +export function unregisterInternalHook(eventKey: string, handler: InternalHookHandler): void { const eventHandlers = handlers.get(eventKey); if (!eventHandlers) { return; @@ -124,7 +118,7 @@ export async function triggerInternalHook(event: InternalHookEvent): Promise = {} + context: Record = {}, ): InternalHookEvent { return { type, diff --git a/src/hooks/llm-slug-generator.ts b/src/hooks/llm-slug-generator.ts index 992df6328..fcf32e5ec 100644 --- a/src/hooks/llm-slug-generator.ts +++ b/src/hooks/llm-slug-generator.ts @@ -2,12 +2,16 @@ * LLM-based slug generator for session memory filenames */ -import fs from 'node:fs/promises'; -import os from 'node:os'; -import path from 'node:path'; -import { runEmbeddedPiAgent } from '../agents/pi-embedded.js'; -import type { ClawdbotConfig } from '../config/config.js'; -import { resolveDefaultAgentId, resolveAgentWorkspaceDir, resolveAgentDir } from '../agents/agent-scope.js'; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { runEmbeddedPiAgent } from "../agents/pi-embedded.js"; +import type { ClawdbotConfig } from "../config/config.js"; +import { + resolveDefaultAgentId, + resolveAgentWorkspaceDir, + resolveAgentDir, +} from "../agents/agent-scope.js"; /** * Generate a short 1-2 word filename slug from session content using LLM @@ -24,8 +28,8 @@ export async function generateSlugViaLLM(params: { const agentDir = resolveAgentDir(params.cfg, agentId); // Create a temporary session file for this one-off LLM call - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'clawdbot-slug-')); - tempSessionFile = path.join(tempDir, 'session.jsonl'); + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-slug-")); + tempSessionFile = path.join(tempDir, "session.jsonl"); const prompt = `Based on this conversation, generate a short 1-2 word filename slug (lowercase, hyphen-separated, no file extension). @@ -36,7 +40,7 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design", const result = await runEmbeddedPiAgent({ sessionId: `slug-generator-${Date.now()}`, - sessionKey: 'temp:slug-generator', + sessionKey: "temp:slug-generator", sessionFile: tempSessionFile, workspaceDir, agentDir, @@ -54,9 +58,9 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design", const slug = text .trim() .toLowerCase() - .replace(/[^a-z0-9-]/g, '-') - .replace(/-+/g, '-') - .replace(/^-|-$/g, '') + .replace(/[^a-z0-9-]/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, "") .slice(0, 30); // Max 30 chars return slug || null; @@ -65,7 +69,7 @@ Reply with ONLY the slug, nothing else. Examples: "vendor-pitch", "api-design", return null; } catch (err) { - console.error('[llm-slug-generator] Failed to generate slug:', err); + console.error("[llm-slug-generator] Failed to generate slug:", err); return null; } finally { // Clean up temporary session file diff --git a/src/hooks/loader.test.ts b/src/hooks/loader.test.ts index 7383d6183..c6019e1cd 100644 --- a/src/hooks/loader.test.ts +++ b/src/hooks/loader.test.ts @@ -1,12 +1,17 @@ -import fs from 'node:fs/promises'; -import os from 'node:os'; -import path from 'node:path'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { loadInternalHooks } from './loader.js'; -import { clearInternalHooks, getRegisteredEventKeys, triggerInternalHook, createInternalHookEvent } from './internal-hooks.js'; -import type { ClawdbotConfig } from '../config/config.js'; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadInternalHooks } from "./loader.js"; +import { + clearInternalHooks, + getRegisteredEventKeys, + triggerInternalHook, + createInternalHookEvent, +} from "./internal-hooks.js"; +import type { ClawdbotConfig } from "../config/config.js"; -describe('loader', () => { +describe("loader", () => { let tmpDir: string; let originalBundledDir: string | undefined; @@ -18,7 +23,7 @@ describe('loader', () => { // Disable bundled hooks during tests by setting env var to non-existent directory originalBundledDir = process.env.CLAWDBOT_BUNDLED_HOOKS_DIR; - process.env.CLAWDBOT_BUNDLED_HOOKS_DIR = '/nonexistent/bundled/hooks'; + process.env.CLAWDBOT_BUNDLED_HOOKS_DIR = "/nonexistent/bundled/hooks"; }); afterEach(async () => { @@ -37,8 +42,8 @@ describe('loader', () => { } }); - describe('loadInternalHooks', () => { - it('should return 0 when internal hooks are not enabled', async () => { + describe("loadInternalHooks", () => { + it("should return 0 when internal hooks are not enabled", async () => { const cfg: ClawdbotConfig = { hooks: { internal: { @@ -51,21 +56,21 @@ describe('loader', () => { expect(count).toBe(0); }); - it('should return 0 when hooks config is missing', async () => { + it("should return 0 when hooks config is missing", async () => { const cfg: ClawdbotConfig = {}; const count = await loadInternalHooks(cfg, tmpDir); expect(count).toBe(0); }); - it('should load a handler from a module', async () => { + it("should load a handler from a module", async () => { // Create a test handler module - const handlerPath = path.join(tmpDir, 'test-handler.js'); + const handlerPath = path.join(tmpDir, "test-handler.js"); const handlerCode = ` export default async function(event) { // Test handler } `; - await fs.writeFile(handlerPath, handlerCode, 'utf-8'); + await fs.writeFile(handlerPath, handlerCode, "utf-8"); const cfg: ClawdbotConfig = { hooks: { @@ -73,7 +78,7 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', + event: "command:new", module: handlerPath, }, ], @@ -85,24 +90,24 @@ describe('loader', () => { expect(count).toBe(1); const keys = getRegisteredEventKeys(); - expect(keys).toContain('command:new'); + expect(keys).toContain("command:new"); }); - it('should load multiple handlers', async () => { + it("should load multiple handlers", async () => { // Create test handler modules - const handler1Path = path.join(tmpDir, 'handler1.js'); - const handler2Path = path.join(tmpDir, 'handler2.js'); + const handler1Path = path.join(tmpDir, "handler1.js"); + const handler2Path = path.join(tmpDir, "handler2.js"); - await fs.writeFile(handler1Path, 'export default async function() {}', 'utf-8'); - await fs.writeFile(handler2Path, 'export default async function() {}', 'utf-8'); + await fs.writeFile(handler1Path, "export default async function() {}", "utf-8"); + await fs.writeFile(handler2Path, "export default async function() {}", "utf-8"); const cfg: ClawdbotConfig = { hooks: { internal: { enabled: true, handlers: [ - { event: 'command:new', module: handler1Path }, - { event: 'command:stop', module: handler2Path }, + { event: "command:new", module: handler1Path }, + { event: "command:stop", module: handler2Path }, ], }, }, @@ -112,19 +117,19 @@ describe('loader', () => { expect(count).toBe(2); const keys = getRegisteredEventKeys(); - expect(keys).toContain('command:new'); - expect(keys).toContain('command:stop'); + expect(keys).toContain("command:new"); + expect(keys).toContain("command:stop"); }); - it('should support named exports', async () => { + it("should support named exports", async () => { // Create a handler module with named export - const handlerPath = path.join(tmpDir, 'named-export.js'); + const handlerPath = path.join(tmpDir, "named-export.js"); const handlerCode = ` export const myHandler = async function(event) { // Named export handler } `; - await fs.writeFile(handlerPath, handlerCode, 'utf-8'); + await fs.writeFile(handlerPath, handlerCode, "utf-8"); const cfg: ClawdbotConfig = { hooks: { @@ -132,9 +137,9 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', + event: "command:new", module: handlerPath, - export: 'myHandler', + export: "myHandler", }, ], }, @@ -145,8 +150,8 @@ describe('loader', () => { expect(count).toBe(1); }); - it('should handle module loading errors gracefully', async () => { - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + it("should handle module loading errors gracefully", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); const cfg: ClawdbotConfig = { hooks: { @@ -154,8 +159,8 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', - module: '/nonexistent/path/handler.js', + event: "command:new", + module: "/nonexistent/path/handler.js", }, ], }, @@ -165,19 +170,19 @@ describe('loader', () => { const count = await loadInternalHooks(cfg, tmpDir); expect(count).toBe(0); expect(consoleError).toHaveBeenCalledWith( - expect.stringContaining('Failed to load internal hook handler'), - expect.any(String) + expect.stringContaining("Failed to load internal hook handler"), + expect.any(String), ); consoleError.mockRestore(); }); - it('should handle non-function exports', async () => { - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + it("should handle non-function exports", async () => { + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); // Create a module with a non-function export - const handlerPath = path.join(tmpDir, 'bad-export.js'); - await fs.writeFile(handlerPath, 'export default "not a function";', 'utf-8'); + const handlerPath = path.join(tmpDir, "bad-export.js"); + await fs.writeFile(handlerPath, 'export default "not a function";', "utf-8"); const cfg: ClawdbotConfig = { hooks: { @@ -185,7 +190,7 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', + event: "command:new", module: handlerPath, }, ], @@ -195,17 +200,15 @@ describe('loader', () => { const count = await loadInternalHooks(cfg, tmpDir); expect(count).toBe(0); - expect(consoleError).toHaveBeenCalledWith( - expect.stringContaining('is not a function') - ); + expect(consoleError).toHaveBeenCalledWith(expect.stringContaining("is not a function")); consoleError.mockRestore(); }); - it('should handle relative paths', async () => { + it("should handle relative paths", async () => { // Create a handler module - const handlerPath = path.join(tmpDir, 'relative-handler.js'); - await fs.writeFile(handlerPath, 'export default async function() {}', 'utf-8'); + const handlerPath = path.join(tmpDir, "relative-handler.js"); + await fs.writeFile(handlerPath, "export default async function() {}", "utf-8"); // Get relative path from cwd const relativePath = path.relative(process.cwd(), handlerPath); @@ -216,7 +219,7 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', + event: "command:new", module: relativePath, }, ], @@ -228,9 +231,9 @@ describe('loader', () => { expect(count).toBe(1); }); - it('should actually call the loaded handler', async () => { + it("should actually call the loaded handler", async () => { // Create a handler that we can verify was called - const handlerPath = path.join(tmpDir, 'callable-handler.js'); + const handlerPath = path.join(tmpDir, "callable-handler.js"); const handlerCode = ` let callCount = 0; export default async function(event) { @@ -240,7 +243,7 @@ describe('loader', () => { return callCount; } `; - await fs.writeFile(handlerPath, handlerCode, 'utf-8'); + await fs.writeFile(handlerPath, handlerCode, "utf-8"); const cfg: ClawdbotConfig = { hooks: { @@ -248,7 +251,7 @@ describe('loader', () => { enabled: true, handlers: [ { - event: 'command:new', + event: "command:new", module: handlerPath, }, ], @@ -259,13 +262,13 @@ describe('loader', () => { await loadInternalHooks(cfg, tmpDir); // Trigger the hook - const event = createInternalHookEvent('command', 'new', 'test-session'); + const event = createInternalHookEvent("command", "new", "test-session"); await triggerInternalHook(event); // The handler should have been called, but we can't directly verify // the call count from this context without more complex test infrastructure // This test mainly verifies that loading and triggering doesn't crash - expect(getRegisteredEventKeys()).toContain('command:new'); + expect(getRegisteredEventKeys()).toContain("command:new"); }); }); }); diff --git a/src/hooks/loader.ts b/src/hooks/loader.ts index 70744fa48..0f212d12e 100644 --- a/src/hooks/loader.ts +++ b/src/hooks/loader.ts @@ -5,14 +5,14 @@ * and from directory-based discovery (bundled, managed, workspace) */ -import { pathToFileURL } from 'node:url'; -import path from 'node:path'; -import { registerInternalHook } from './internal-hooks.js'; -import type { ClawdbotConfig } from '../config/config.js'; -import type { InternalHookHandler } from './internal-hooks.js'; -import { loadWorkspaceHookEntries } from './workspace.js'; -import { resolveHookConfig } from './config.js'; -import { shouldIncludeHook } from './config.js'; +import { pathToFileURL } from "node:url"; +import path from "node:path"; +import { registerInternalHook } from "./internal-hooks.js"; +import type { ClawdbotConfig } from "../config/config.js"; +import type { InternalHookHandler } from "./internal-hooks.js"; +import { loadWorkspaceHookEntries } from "./workspace.js"; +import { resolveHookConfig } from "./config.js"; +import { shouldIncludeHook } from "./config.js"; /** * Load and register all internal hook handlers @@ -49,9 +49,7 @@ export async function loadInternalHooks( const hookEntries = loadWorkspaceHookEntries(workspaceDir, { config: cfg }); // Filter by eligibility - const eligible = hookEntries.filter((entry) => - shouldIncludeHook({ entry, config: cfg }), - ); + const eligible = hookEntries.filter((entry) => shouldIncludeHook({ entry, config: cfg })); for (const entry of eligible) { const hookConfig = resolveHookConfig(cfg, entry.hook.name); @@ -68,10 +66,10 @@ export async function loadInternalHooks( const mod = (await import(cacheBustedUrl)) as Record; // Get handler function (default or named export) - const exportName = entry.clawdbot?.export ?? 'default'; + const exportName = entry.clawdbot?.export ?? "default"; const handler = mod[exportName]; - if (typeof handler !== 'function') { + if (typeof handler !== "function") { console.error( `Internal hook error: Handler '${exportName}' from ${entry.hook.name} is not a function`, ); @@ -92,7 +90,7 @@ export async function loadInternalHooks( } console.log( - `Registered internal hook: ${entry.hook.name} -> ${events.join(', ')}${exportName !== 'default' ? ` (export: ${exportName})` : ''}`, + `Registered internal hook: ${entry.hook.name} -> ${events.join(", ")}${exportName !== "default" ? ` (export: ${exportName})` : ""}`, ); loadedCount++; } catch (err) { @@ -104,7 +102,7 @@ export async function loadInternalHooks( } } catch (err) { console.error( - 'Failed to load directory-based hooks:', + "Failed to load directory-based hooks:", err instanceof Error ? err.message : String(err), ); } @@ -124,10 +122,10 @@ export async function loadInternalHooks( const mod = (await import(cacheBustedUrl)) as Record; // Get the handler function - const exportName = handlerConfig.export ?? 'default'; + const exportName = handlerConfig.export ?? "default"; const handler = mod[exportName]; - if (typeof handler !== 'function') { + if (typeof handler !== "function") { console.error( `Internal hook error: Handler '${exportName}' from ${modulePath} is not a function`, ); @@ -137,7 +135,7 @@ export async function loadInternalHooks( // Register the handler registerInternalHook(handlerConfig.event, handler as InternalHookHandler); console.log( - `Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== 'default' ? `#${exportName}` : ''}`, + `Registered internal hook (legacy): ${handlerConfig.event} -> ${modulePath}${exportName !== "default" ? `#${exportName}` : ""}`, ); loadedCount++; } catch (err) { diff --git a/src/hooks/workspace.ts b/src/hooks/workspace.ts index fcbee602a..5bdba4b12 100644 --- a/src/hooks/workspace.ts +++ b/src/hooks/workspace.ts @@ -59,12 +59,7 @@ function loadHooksFromDir(params: { dir: string; source: string }): Hook[] { const description = frontmatter.description || ""; // Locate handler file (handler.ts, handler.js, index.ts, index.js) - const handlerCandidates = [ - "handler.ts", - "handler.js", - "index.ts", - "index.js", - ]; + const handlerCandidates = ["handler.ts", "handler.js", "index.ts", "index.js"]; let handlerPath: string | undefined; for (const candidate of handlerCandidates) {