@rulemetric/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/{chunk-LCT6MT2V.js → chunk-2WWGG2A5.js} +9 -9
  2. package/dist/{chunk-L674RNKQ.js → chunk-ANOWI23I.js} +51 -1
  3. package/dist/chunk-ANOWI23I.js.map +7 -0
  4. package/dist/{chunk-Y2ARLMWZ.js → chunk-C7SRRSPA.js} +4 -4
  5. package/dist/{chunk-2BCPVUSF.js → chunk-CLC7ZFH2.js} +4 -4
  6. package/dist/chunk-SO3T35U7.js +80 -0
  7. package/dist/chunk-SO3T35U7.js.map +7 -0
  8. package/dist/commands/evals/agent.js +6 -6
  9. package/dist/commands/hooks/emit-instructions.js +25 -0
  10. package/dist/commands/hooks/emit-instructions.js.map +7 -0
  11. package/dist/commands/hooks/install.js +17 -23
  12. package/dist/commands/hooks/install.js.map +2 -2
  13. package/dist/commands/hooks/uninstall.js +4 -4
  14. package/dist/commands/hooks/uninstall.js.map +2 -2
  15. package/dist/commands/research/backfill.js +3 -3
  16. package/dist/commands/research/tail-transcript.js +3 -3
  17. package/dist/commands/service/install.js +7 -1
  18. package/dist/commands/service/install.js.map +2 -2
  19. package/dist/dashboard/Dashboard.js +9 -9
  20. package/dist/lib/agent-loop.js +6 -6
  21. package/dist/lib/handlers/process-announcement.js +2 -2
  22. package/dist/lib/handlers/process-run-cleanup.js +2 -2
  23. package/dist/lib/hooks-config.js +7 -1
  24. package/dist/lib/instruction-snapshot.js +8 -0
  25. package/dist/lib/instruction-snapshot.js.map +7 -0
  26. package/oclif.manifest.json +1004 -974
  27. package/package.json +6 -6
  28. package/dist/chunk-L674RNKQ.js.map +0 -7
  29. /package/dist/{chunk-LCT6MT2V.js.map → chunk-2WWGG2A5.js.map} +0 -0
  30. /package/dist/{chunk-Y2ARLMWZ.js.map → chunk-C7SRRSPA.js.map} +0 -0
  31. /package/dist/{chunk-2BCPVUSF.js.map → chunk-CLC7ZFH2.js.map} +0 -0
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  startTerminalTargetHeartbeat
3
3
  } from "./chunk-JX5UI6RW.js";
4
+ import {
5
+ processEval
6
+ } from "./chunk-QJXAULRC.js";
4
7
  import {
5
8
  processInsights
6
9
  } from "./chunk-EHABPBGH.js";
@@ -9,7 +12,7 @@ import {
9
12
  } from "./chunk-XMWHTOCC.js";
10
13
  import {
11
14
  processRunCleanup
12
- } from "./chunk-Y2ARLMWZ.js";
15
+ } from "./chunk-C7SRRSPA.js";
13
16
  import {
14
17
  processSendMessage
15
18
  } from "./chunk-W53GKIZQ.js";
@@ -24,16 +27,13 @@ import {
24
27
  } from "./chunk-YBNW7ARH.js";
25
28
  import {
26
29
  processAnnouncement
27
- } from "./chunk-2BCPVUSF.js";
28
- import {
29
- processConversation
30
- } from "./chunk-BD7CY42U.js";
31
- import {
32
- processEval
33
- } from "./chunk-QJXAULRC.js";
30
+ } from "./chunk-CLC7ZFH2.js";
34
31
  import {
35
32
  isPermanentJobError
36
33
  } from "./chunk-DGHWRQXL.js";
34
+ import {
35
+ processConversation
36
+ } from "./chunk-BD7CY42U.js";
37
37
  import {
38
38
  ApiError,
39
39
  apiGet,
@@ -266,4 +266,4 @@ export {
266
266
  pollForWork,
267
267
  runAgentLoop
268
268
  };
269
- //# sourceMappingURL=chunk-LCT6MT2V.js.map
269
+ //# sourceMappingURL=chunk-2WWGG2A5.js.map
@@ -83,6 +83,53 @@ function generateCopilotHooksConfig() {
83
83
  }
84
84
  };
85
85
  }
86
+ function generateClaudeCodeHooksConfig() {
87
+ const mk = (name) => ({
88
+ type: "command",
89
+ command: `rulemetric hooks run ${name}`
90
+ });
91
+ return {
92
+ SessionStart: [{ hooks: [mk("session-start")] }],
93
+ UserPromptSubmit: [{ hooks: [mk("user-prompt")] }],
94
+ PostToolUse: [{ matcher: ".*", hooks: [mk("post-tool-use")] }],
95
+ Stop: [{ hooks: [mk("assistant-response")] }],
96
+ SessionEnd: [{ hooks: [mk("session-end")] }]
97
+ };
98
+ }
99
+ function mergeClaudeCodeHooks(settings) {
100
+ const generated = generateClaudeCodeHooksConfig();
101
+ const hooks = settings.hooks ?? {};
102
+ for (const [event, blocks] of Object.entries(generated)) {
103
+ const current = hooks[event] ?? [];
104
+ const alreadyPresent = current.some(
105
+ (b) => b?.hooks?.some((h) => typeof h?.command === "string" && h.command.includes("rulemetric"))
106
+ );
107
+ if (!alreadyPresent) {
108
+ hooks[event] = [...current, ...blocks];
109
+ }
110
+ }
111
+ settings.hooks = hooks;
112
+ }
113
+ function removeClaudeCodeHooks(settings) {
114
+ if (!settings.hooks || typeof settings.hooks !== "object") return false;
115
+ const hooks = settings.hooks;
116
+ let removed = 0;
117
+ for (const event of Object.keys(hooks)) {
118
+ const entries = hooks[event];
119
+ if (!Array.isArray(entries)) continue;
120
+ const kept = entries.filter((block) => {
121
+ const isRulemetric = block?.hooks?.some(
122
+ (h) => typeof h?.command === "string" && h.command.includes("rulemetric")
123
+ );
124
+ if (isRulemetric) removed += 1;
125
+ return !isRulemetric;
126
+ });
127
+ if (kept.length === 0) delete hooks[event];
128
+ else hooks[event] = kept;
129
+ }
130
+ if (Object.keys(hooks).length === 0) delete settings.hooks;
131
+ return removed > 0;
132
+ }
86
133
  function writeCursorHooksToDir(cursorDir) {
87
134
  if (!existsSync(cursorDir)) {
88
135
  return null;
@@ -468,6 +515,9 @@ export {
468
515
  detectInstalledTools,
469
516
  generateCursorHooksConfig,
470
517
  generateCopilotHooksConfig,
518
+ generateClaudeCodeHooksConfig,
519
+ mergeClaudeCodeHooks,
520
+ removeClaudeCodeHooks,
471
521
  writeCursorHooks,
472
522
  writeCursorUserHooks,
473
523
  writeCopilotHooks,
@@ -489,4 +539,4 @@ export {
489
539
  removeAntigravityHooks,
490
540
  removeAntigravityUserHooks
491
541
  };
492
- //# sourceMappingURL=chunk-L674RNKQ.js.map
542
+ //# sourceMappingURL=chunk-ANOWI23I.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/hooks-config.ts"],
4
+ "sourcesContent": ["import { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport type DetectedTool = 'claude_code' | 'cursor' | 'copilot_agent' | 'antigravity';\n\n/**\n * Detect which AI coding tools are installed in the project by checking\n * for their config directories.\n */\nexport function detectInstalledTools(projectPath: string): DetectedTool[] {\n const tools: DetectedTool[] = ['claude_code'];\n\n if (existsSync(join(projectPath, '.cursor'))) {\n tools.push('cursor');\n }\n\n if (existsSync(join(projectPath, '.github'))) {\n tools.push('copilot_agent');\n }\n\n // Antigravity's workspace config lives at `.agents/`. The user-level\n // hooks file at ~/.gemini/config/hooks.json is installed unconditionally\n // by writeAntigravityUserHooks() so we don't gate on that here.\n if (existsSync(join(projectPath, '.agents'))) {\n tools.push('antigravity');\n }\n\n return tools;\n}\n\n/**\n * Generate Cursor hooks config object.\n *\n * Cursor uses event names like beforeSubmitPrompt, afterFileEdit, etc.\n * Each event maps to an array of hook objects with a `command` field.\n */\nexport function generateCursorHooksConfig(): object {\n // Event coverage matches Cursor 1.7+ hook API (cursor.com/docs/hooks).\n // `sessionStart` is required so the registry file is written with\n // conversation_id before any tool runs; without it the proxy-based linker\n // path would have nothing to map and we'd drop captures. `sessionEnd`\n // emits the session-end signal once per chat conversation (vs `stop`\n // which fires per-turn \u2014 those go through post-tool-use).\n return {\n version: 1,\n hooks: {\n sessionStart: [\n { command: 'rulemetric hooks run session-start' },\n ],\n beforeSubmitPrompt: [\n { command: 'rulemetric hooks run user-prompt' },\n ],\n afterFileEdit: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n beforeShellExecution: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n afterShellExecution: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n beforeMCPExecution: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n afterMCPExecution: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n // `afterAgentResponse` carries the full assistant response text +\n // token usage. Verified empirically via a probe hook on\n // 2026-05-12 \u2014 Cursor passes `text`, `input_tokens`,\n // `output_tokens`, `cache_read_tokens`, `cache_write_tokens`. This\n // is the cleanest path to per-turn assistant content for Cursor\n // (chat traffic itself bypasses the proxy via HTTP/2 \u2014 see\n // docs/audits/2026-05-11-cursor-capture-architecture.md).\n afterAgentResponse: [\n { command: 'rulemetric hooks run assistant-response' },\n ],\n // `stop` fires when the agent loop ends for a single turn (status:\n // completed|aborted|error). Per-turn, NOT per-session \u2014 route it to\n // post-tool-use, not session-end. The real session boundary is\n // `sessionEnd` below.\n stop: [\n { command: 'rulemetric hooks run post-tool-use' },\n ],\n sessionEnd: [\n { command: 'rulemetric hooks run session-end' },\n ],\n },\n };\n}\n\n/**\n * Generate Copilot Agent hooks config object.\n *\n * Copilot uses event names like sessionStart, userPromptSubmitted, etc.\n * Each event maps to an array of hook objects with `type` and `bash` fields.\n */\nexport function generateCopilotHooksConfig(): object {\n return {\n version: 1,\n hooks: {\n sessionStart: [\n { type: 'command', bash: 'rulemetric hooks run session-start' },\n ],\n userPromptSubmitted: [\n { type: 'command', bash: 'rulemetric hooks run user-prompt' },\n ],\n postToolUse: [\n { type: 'command', bash: 'rulemetric hooks run post-tool-use' },\n ],\n sessionEnd: [\n { type: 'command', bash: 'rulemetric hooks run session-end' },\n ],\n },\n };\n}\n\ninterface ClaudeHookEntry {\n type: 'command';\n command: string;\n}\n\ninterface ClaudeHookBlock {\n matcher?: string;\n hooks: ClaudeHookEntry[];\n}\n\n/** The `settings.hooks` map RuleMetric installs into a project's `.claude/settings.json`. */\nexport type ClaudeCodeHooksConfig = Record<\n 'SessionStart' | 'UserPromptSubmit' | 'PostToolUse' | 'Stop' | 'SessionEnd',\n ClaudeHookBlock[]\n>;\n\n/**\n * Generate the Claude Code hooks map for `.claude/settings.json`.\n *\n * Claude Code keys hook blocks by native event name, each block being\n * `{ matcher?, hooks: [{ type: 'command', command }] }`. Unlike Antigravity\n * these carry NO `RULEMETRIC_HOOK_TOOL` prefix \u2014 `_normalize.sh` defaults to\n * the `claude_code` branch (session_id + transcript_path payload shape).\n *\n * This is the hooks-first, zero-proxy capture path: SessionEnd runs\n * `session-end.sh`, which reimports the whole transcript via\n * `POST /api/sessions/:id/reimport` \u2014 no mitmproxy / CA trust / gateway needed.\n * The rendered system prompt is still proxy-only, so instruction-effectiveness\n * linking is handled separately (Phase 2 synthetic snapshot).\n */\nexport function generateClaudeCodeHooksConfig(): ClaudeCodeHooksConfig {\n // Bare `rulemetric` (NOT getRulemetricCommand): Claude Code runs hooks in the\n // user's shell where the CLI is on PATH, and the literal 'rulemetric' substring\n // is the marker that install.ts \u00A71 and mergeClaudeCodeHooks use to dedup/strip\n // our hooks. A resolved node+run.js path omits 'rulemetric' in a dev checkout,\n // which would silently break that dedup.\n const mk = (name: string): ClaudeHookEntry => ({\n type: 'command',\n command: `rulemetric hooks run ${name}`,\n });\n return {\n SessionStart: [{ hooks: [mk('session-start')] }],\n UserPromptSubmit: [{ hooks: [mk('user-prompt')] }],\n PostToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n Stop: [{ hooks: [mk('assistant-response')] }],\n SessionEnd: [{ hooks: [mk('session-end')] }],\n };\n}\n\n/**\n * Merge RuleMetric's Claude Code hooks into an in-memory `.claude/settings.json`\n * object. Claude Code hooks share the same settings.json that install.ts reads,\n * strips (\u00A71), and writes (\u00A75), so this mutates `settings.hooks` in place rather\n * than doing its own file I/O. Idempotent + non-destructive: per event it skips\n * adding when a rulemetric command is already present and otherwise appends,\n * preserving the user's own hooks.\n */\nexport function mergeClaudeCodeHooks(settings: Record<string, unknown>): void {\n const generated = generateClaudeCodeHooksConfig();\n const hooks = (settings.hooks ?? {}) as Record<string, ClaudeHookBlock[]>;\n for (const [event, blocks] of Object.entries(generated)) {\n const current = (hooks[event] ?? []) as ClaudeHookBlock[];\n const alreadyPresent = current.some((b) =>\n b?.hooks?.some((h) => typeof h?.command === 'string' && h.command.includes('rulemetric')),\n );\n if (!alreadyPresent) {\n hooks[event] = [...current, ...blocks];\n }\n }\n settings.hooks = hooks;\n}\n\n/**\n * Strip RuleMetric's Claude Code hooks from an in-memory settings object while\n * preserving the user's own hook entries. Mirrors install.ts \u00A71 but is reusable\n * for uninstall. Removes emptied event arrays and deletes `settings.hooks` if it\n * ends up empty. Returns true iff anything was removed.\n */\nexport function removeClaudeCodeHooks(settings: Record<string, unknown>): boolean {\n if (!settings.hooks || typeof settings.hooks !== 'object') return false;\n const hooks = settings.hooks as Record<string, ClaudeHookBlock[]>;\n let removed = 0;\n for (const event of Object.keys(hooks)) {\n const entries = hooks[event];\n if (!Array.isArray(entries)) continue;\n const kept = entries.filter((block) => {\n const isRulemetric = block?.hooks?.some(\n (h) => typeof h?.command === 'string' && h.command.includes('rulemetric'),\n );\n if (isRulemetric) removed += 1;\n return !isRulemetric;\n });\n if (kept.length === 0) delete hooks[event];\n else hooks[event] = kept;\n }\n if (Object.keys(hooks).length === 0) delete settings.hooks;\n return removed > 0;\n}\n\n/**\n * Merge rulemetric hooks into a Cursor `hooks.json` at the given directory.\n *\n * Used by both the project (`<repo>/.cursor/`) and user (`~/.cursor/`) writers.\n * Returns the config file path, or null if the cursor dir doesn't exist.\n */\nfunction writeCursorHooksToDir(cursorDir: string): string | null {\n if (!existsSync(cursorDir)) {\n return null;\n }\n\n const configPath = join(cursorDir, 'hooks.json');\n const generated = generateCursorHooksConfig() as {\n version: number;\n hooks: Record<string, Array<{ command: string }>>;\n };\n\n let existing: { version?: number; hooks?: Record<string, unknown[]> } = {};\n if (existsSync(configPath)) {\n try {\n existing = JSON.parse(readFileSync(configPath, 'utf-8'));\n } catch {\n existing = {};\n }\n }\n\n const merged: Record<string, unknown[]> = { ...(existing.hooks ?? {}) };\n\n for (const [event, hooks] of Object.entries(generated.hooks)) {\n const current = merged[event] ?? [];\n const hasRulemetric = current.some(\n (h: unknown) =>\n typeof h === 'object' &&\n h !== null &&\n 'command' in h &&\n typeof (h as { command: string }).command === 'string' &&\n (h as { command: string }).command.includes('rulemetric'),\n );\n if (!hasRulemetric) {\n merged[event] = [...current, ...hooks];\n }\n }\n\n const result = {\n version: existing.version ?? generated.version,\n hooks: merged,\n };\n\n writeFileSync(configPath, JSON.stringify(result, null, 2) + '\\n');\n return configPath;\n}\n\n/**\n * Write Cursor hooks config to `<projectPath>/.cursor/hooks.json`.\n * Merges with existing config \u2014 appends rulemetric hooks without duplicating.\n * Returns the config file path, or null if `.cursor/` doesn't exist.\n */\nexport function writeCursorHooks(projectPath: string): string | null {\n return writeCursorHooksToDir(join(projectPath, '.cursor'));\n}\n\n/**\n * Write Cursor hooks config to user-level `~/.cursor/hooks.json` so capture\n * works for every Cursor conversation without per-project setup.\n *\n * Returns the config file path, or null if `~/.cursor/` doesn't exist\n * (i.e., Cursor has never been launched on this machine).\n */\nexport function writeCursorUserHooks(): string | null {\n return writeCursorHooksToDir(join(homedir(), '.cursor'));\n}\n\n/**\n * Write Copilot Agent hooks config to `.github/hooks/rulemetric.json`.\n * Creates the hooks directory if needed.\n * Returns the config file path, or null if `.github/` doesn't exist.\n */\nexport function writeCopilotHooks(projectPath: string): string | null {\n const githubDir = join(projectPath, '.github');\n if (!existsSync(githubDir)) {\n return null;\n }\n\n const hooksDir = join(githubDir, 'hooks');\n mkdirSync(hooksDir, { recursive: true });\n\n const configPath = join(hooksDir, 'rulemetric.json');\n const config = generateCopilotHooksConfig();\n\n writeFileSync(configPath, JSON.stringify(config, null, 2) + '\\n');\n return configPath;\n}\n\n/**\n * Strip rulemetric hooks from a Cursor `hooks.json` at the given path.\n * Preserves other hooks and removes empty event arrays.\n * Returns true if changes were made.\n */\nfunction removeCursorHooksFromFile(configPath: string): boolean {\n if (!existsSync(configPath)) {\n return false;\n }\n\n let config: { version?: number; hooks?: Record<string, unknown[]> };\n try {\n config = JSON.parse(readFileSync(configPath, 'utf-8'));\n } catch {\n return false;\n }\n\n if (!config.hooks) {\n return false;\n }\n\n let changed = false;\n for (const [event, hooks] of Object.entries(config.hooks)) {\n const filtered = hooks.filter((h: unknown) => {\n if (typeof h !== 'object' || h === null || !('command' in h)) return true;\n const cmd = (h as { command: string }).command;\n if (typeof cmd === 'string' && cmd.includes('rulemetric')) {\n changed = true;\n return false;\n }\n return true;\n });\n\n if (filtered.length === 0) {\n delete config.hooks[event];\n } else {\n config.hooks[event] = filtered;\n }\n }\n\n if (changed) {\n writeFileSync(configPath, JSON.stringify(config, null, 2) + '\\n');\n }\n\n return changed;\n}\n\n/**\n * Remove rulemetric hooks from `<projectPath>/.cursor/hooks.json`.\n */\nexport function removeCursorHooks(projectPath: string): boolean {\n return removeCursorHooksFromFile(join(projectPath, '.cursor', 'hooks.json'));\n}\n\n/**\n * Remove rulemetric hooks from user-level `~/.cursor/hooks.json`.\n */\nexport function removeCursorUserHooks(): boolean {\n return removeCursorHooksFromFile(join(homedir(), '.cursor', 'hooks.json'));\n}\n\n/**\n * Write Cursor proxy config to `.cursor/settings.json`.\n * Sets `http.proxy` and `http.proxyStrictSSL` while preserving existing settings.\n * Returns true if `.cursor/` exists and config was written, false otherwise.\n */\nexport function writeCursorProxyConfig(projectPath: string, gatewayPort: number, certPath: string): boolean {\n const cursorDir = join(projectPath, '.cursor');\n if (!existsSync(cursorDir)) return false;\n\n const settingsPath = join(cursorDir, 'settings.json');\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { /* empty */ }\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = existsSync(certPath);\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Write VS Code proxy config to `.vscode/settings.json` for Copilot capture.\n * Sets `http.proxy`, `http.proxyStrictSSL`, and Copilot-specific override\n * while preserving existing settings.\n * Returns true if config was written, false if `.vscode/` doesn't exist.\n */\nexport function writeVSCodeProxyConfig(projectPath: string, gatewayPort: number, certPath: string): boolean {\n const vscodeDir = join(projectPath, '.vscode');\n mkdirSync(vscodeDir, { recursive: true });\n\n const settingsPath = join(vscodeDir, 'settings.json');\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { /* empty */ }\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = existsSync(certPath);\n\n // Copilot-specific override for surgical proxy targeting\n const copilotAdvanced = (settings['github.copilot.advanced'] ?? {}) as Record<string, unknown>;\n copilotAdvanced['debug.overrideProxyUrl'] = `http://localhost:${gatewayPort}`;\n settings['github.copilot.advanced'] = copilotAdvanced;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove VS Code proxy config from `.vscode/settings.json`.\n * Removes `http.proxy`, `http.proxyStrictSSL`, and Copilot proxy override.\n * Returns true if changes were made.\n */\nexport function removeVSCodeProxyConfig(projectPath: string): boolean {\n const settingsPath = join(projectPath, '.vscode', 'settings.json');\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n let changed = false;\n\n if (settings['http.proxy']) {\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n changed = true;\n }\n\n const copilotAdvanced = settings['github.copilot.advanced'] as Record<string, unknown> | undefined;\n if (copilotAdvanced?.['debug.overrideProxyUrl']) {\n delete copilotAdvanced['debug.overrideProxyUrl'];\n if (Object.keys(copilotAdvanced).length === 0) {\n delete settings['github.copilot.advanced'];\n }\n changed = true;\n }\n\n if (changed) {\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n }\n\n return changed;\n}\n\n/**\n * Remove Copilot Agent hooks by deleting `.github/hooks/rulemetric.json`.\n * Returns true if the file was removed.\n */\nexport function removeCopilotHooks(projectPath: string): boolean {\n const configPath = join(projectPath, '.github', 'hooks', 'rulemetric.json');\n if (!existsSync(configPath)) {\n return false;\n }\n\n unlinkSync(configPath);\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// macOS LaunchAgent for GUI app env vars (HTTPS_PROXY, NODE_EXTRA_CA_CERTS)\n// ---------------------------------------------------------------------------\n\nconst LAUNCH_AGENT_LABEL = 'com.rulemetric.env';\n\nfunction getLaunchAgentPath(): string {\n return join(homedir(), 'Library', 'LaunchAgents', `${LAUNCH_AGENT_LABEL}.plist`);\n}\n\n/**\n * Set HTTPS_PROXY and NODE_EXTRA_CA_CERTS for all GUI apps on macOS.\n *\n * Two layers:\n * 1. `launchctl setenv` \u2014 immediate effect for newly launched apps\n * 2. LaunchAgent plist \u2014 persists across reboots\n *\n * This ensures VS Code / Copilot / Cursor route LLM traffic through the\n * gateway even when launched from Dock or Spotlight (not a terminal).\n *\n * References:\n * - anthropics/claude-code#30318 (same pattern for Claude Desktop)\n * - Snyk IDE docs recommend launchctl setenv for macOS\n * - Apple QA1067 (archived) \u2014 original env var mechanism removed in 10.10\n */\nexport function installMacOSProxyEnv(gatewayPort: number, certPath: string): boolean {\n if (process.platform !== 'darwin') return false;\n\n const proxyUrl = `http://localhost:${gatewayPort}`;\n\n // Layer 1: immediate effect via launchctl setenv\n try {\n execSync(`launchctl setenv HTTPS_PROXY ${proxyUrl}`, { stdio: 'pipe' });\n if (existsSync(certPath)) {\n execSync(`launchctl setenv NODE_EXTRA_CA_CERTS ${certPath}`, { stdio: 'pipe' });\n }\n } catch {\n return false;\n }\n\n // Layer 2: LaunchAgent plist for persistence across reboots\n const plistPath = getLaunchAgentPath();\n const agentsDir = join(homedir(), 'Library', 'LaunchAgents');\n mkdirSync(agentsDir, { recursive: true });\n\n const certLine = existsSync(certPath)\n ? `launchctl setenv NODE_EXTRA_CA_CERTS ${certPath};`\n : '';\n\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\"\n \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${LAUNCH_AGENT_LABEL}</string>\n <key>ProgramArguments</key>\n <array>\n <string>/bin/sh</string>\n <string>-c</string>\n <string>launchctl setenv HTTPS_PROXY ${proxyUrl};${certLine}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n</dict>\n</plist>\n`;\n\n writeFileSync(plistPath, plist);\n return true;\n}\n\n/**\n * Remove the RuleMetric LaunchAgent and unset env vars.\n */\nexport function uninstallMacOSProxyEnv(): boolean {\n if (process.platform !== 'darwin') return false;\n\n let changed = false;\n\n // Unset env vars for current session\n try {\n execSync('launchctl unsetenv HTTPS_PROXY', { stdio: 'pipe' });\n execSync('launchctl unsetenv NODE_EXTRA_CA_CERTS', { stdio: 'pipe' });\n } catch { /* may not be set */ }\n\n // Remove LaunchAgent plist\n const plistPath = getLaunchAgentPath();\n if (existsSync(plistPath)) {\n unlinkSync(plistPath);\n changed = true;\n }\n\n return changed;\n}\n\n// ---------------------------------------------------------------------------\n// VS Code user-level proxy settings\n// ---------------------------------------------------------------------------\n\nfunction getVSCodeUserSettingsPath(): string {\n if (process.platform === 'darwin') {\n return join(homedir(), 'Library', 'Application Support', 'Code', 'User', 'settings.json');\n }\n if (process.platform === 'win32') {\n return join(process.env.APPDATA ?? '', 'Code', 'User', 'settings.json');\n }\n return join(homedir(), '.config', 'Code', 'User', 'settings.json');\n}\n\n/**\n * Set http.proxy in VS Code user settings (not workspace).\n *\n * Workspace-level http.proxy is silently ignored because VS Code restricts\n * it to APPLICATION scope (microsoft/vscode#236932). User-level settings\n * are the only reliable way to configure http.proxy.\n */\nexport function writeVSCodeUserProxyConfig(gatewayPort: number): boolean {\n const settingsPath = getVSCodeUserSettingsPath();\n if (!existsSync(join(settingsPath, '..'))) return false;\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { /* empty */ }\n }\n\n // Only set if not already configured by the user\n if (settings['http.proxy'] && !(settings['http.proxy'] as string).includes('localhost')) {\n return false; // user has a custom proxy, don't overwrite\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = false;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove RuleMetric proxy config from VS Code user settings.\n */\nexport function removeVSCodeUserProxyConfig(): boolean {\n const settingsPath = getVSCodeUserSettingsPath();\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n const proxy = settings['http.proxy'] as string | undefined;\n if (!proxy?.includes('localhost')) return false;\n\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Cursor user-level proxy settings\n// ---------------------------------------------------------------------------\n//\n// Cursor is a VS Code fork and uses the same settings.json shape, but reads\n// from `Cursor/User/settings.json` instead of `Code/User/settings.json`. The\n// `.cursor/settings.json` (workspace) path can't reach Cursor's Electron main\n// process for the same reason VS Code's workspace path can't reach VS Code's\n// \u2014 the http.proxy setting is restricted to APPLICATION scope and only the\n// user-level file is honored.\n\nfunction getCursorUserSettingsPath(): string {\n if (process.platform === 'darwin') {\n return join(homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'settings.json');\n }\n if (process.platform === 'win32') {\n return join(process.env.APPDATA ?? '', 'Cursor', 'User', 'settings.json');\n }\n return join(homedir(), '.config', 'Cursor', 'User', 'settings.json');\n}\n\n/**\n * Set http.proxy in Cursor user settings (not workspace). Mirrors\n * `writeVSCodeUserProxyConfig` \u2014 workspace-level http.proxy is silently\n * ignored due to APPLICATION-scope restriction (Cursor inherits this from\n * VS Code, see microsoft/vscode#236932).\n *\n * Returns true if config was written, false if Cursor isn't installed\n * (User dir absent) or the user already has a non-localhost proxy set.\n */\nexport function writeCursorUserProxyConfig(gatewayPort: number): boolean {\n const settingsPath = getCursorUserSettingsPath();\n if (!existsSync(join(settingsPath, '..'))) return false;\n\n let settings: Record<string, unknown> = {};\n if (existsSync(settingsPath)) {\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { /* empty */ }\n }\n\n if (settings['http.proxy'] && !(settings['http.proxy'] as string).includes('localhost')) {\n return false;\n }\n\n settings['http.proxy'] = `http://localhost:${gatewayPort}`;\n settings['http.proxyStrictSSL'] = false;\n\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n/**\n * Remove RuleMetric proxy config from Cursor user settings.\n */\nexport function removeCursorUserProxyConfig(): boolean {\n const settingsPath = getCursorUserSettingsPath();\n if (!existsSync(settingsPath)) return false;\n\n let settings: Record<string, unknown>;\n try { settings = JSON.parse(readFileSync(settingsPath, 'utf-8')); } catch { return false; }\n\n const proxy = settings['http.proxy'] as string | undefined;\n if (!proxy?.includes('localhost')) return false;\n\n delete settings['http.proxy'];\n delete settings['http.proxyStrictSSL'];\n writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\\n');\n return true;\n}\n\n// \u2500\u2500\u2500 Antigravity (Google's Gemini-based agentic IDE) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Antigravity hooks live in `.agents/hooks.json` (workspace) and\n// `~/.gemini/config/hooks.json` (user-level). Events follow the\n// SessionStart / UserPromptSubmit / PreToolUse / PostToolUse / Stop /\n// SessionEnd vocabulary. Each hook command sets `RULEMETRIC_HOOK_TOOL=\n// antigravity` so `_normalize.sh` routes through the Antigravity branch.\n\ninterface AntigravityHookEntry {\n type: 'command';\n command: string;\n timeout?: number;\n}\n\ninterface AntigravityHookBlock {\n matcher?: string;\n hooks: AntigravityHookEntry[];\n}\n\ninterface AntigravityRuleMetricBlock {\n enabled: boolean;\n SessionStart: AntigravityHookBlock[];\n UserPromptSubmit: AntigravityHookBlock[];\n PreToolUse: AntigravityHookBlock[];\n PostToolUse: AntigravityHookBlock[];\n Stop: AntigravityHookBlock[];\n SessionEnd: AntigravityHookBlock[];\n}\n\nexport type AntigravityHooksConfig = { rulemetric: AntigravityRuleMetricBlock };\n\n/** Resolve the binary string to invoke for a hook command. */\nfunction getRulemetricCommand(): string {\n // Prefer the local Node binary + bin/run.js so the hook works even when\n // `rulemetric` isn't on PATH for the GUI Antigravity process.\n const nodeBin = process.execPath;\n // bin/run.js lives next to dist/ in the installed CLI; resolve from\n // import.meta isn't available in a portable way here, so we use the\n // process argv1 if it's pointing at the CLI entry, else fall back to\n // the bare command name. In practice this function is called inside\n // `rulemetric hooks install`, where process.argv[1] is bin/run.js.\n const cliEntry = process.argv[1];\n if (cliEntry && cliEntry.endsWith('run.js')) {\n return `${nodeBin} ${cliEntry}`;\n }\n return 'rulemetric';\n}\n\nexport function generateAntigravityHooksConfig(): AntigravityHooksConfig {\n const cmd = getRulemetricCommand();\n const mk = (name: string): AntigravityHookEntry => ({\n type: 'command',\n command: `RULEMETRIC_HOOK_TOOL=antigravity ${cmd} hooks run ${name}`,\n timeout: 30,\n });\n return {\n rulemetric: {\n enabled: true,\n SessionStart: [{ hooks: [mk('session-start')] }],\n UserPromptSubmit: [{ hooks: [mk('user-prompt')] }],\n PreToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n PostToolUse: [{ matcher: '.*', hooks: [mk('post-tool-use')] }],\n Stop: [{ hooks: [mk('assistant-response')] }],\n SessionEnd: [{ hooks: [mk('session-end')] }],\n },\n };\n}\n\nfunction writeAntigravityHooksToDir(dir: string): string | null {\n const configPath = join(dir, 'hooks.json');\n let existing: Record<string, unknown> = {};\n if (existsSync(configPath)) {\n try { existing = JSON.parse(readFileSync(configPath, 'utf-8')); } catch { existing = {}; }\n }\n const generated = generateAntigravityHooksConfig();\n // Antigravity keys hook blocks by name; RuleMetric owns its own block\n // and never touches sibling blocks the user may have added.\n const merged = { ...existing, rulemetric: generated.rulemetric };\n mkdirSync(dir, { recursive: true });\n writeFileSync(configPath, JSON.stringify(merged, null, 2) + '\\n');\n return configPath;\n}\n\nexport function writeAntigravityHooks(projectPath: string): string | null {\n return writeAntigravityHooksToDir(join(projectPath, '.agents'));\n}\n\nexport function writeAntigravityUserHooks(): string | null {\n const configDir = join(homedir(), '.gemini', 'config');\n return writeAntigravityHooksToDir(configDir);\n}\n\nfunction removeAntigravityHooksFromFile(configPath: string): boolean {\n if (!existsSync(configPath)) return false;\n let existing: Record<string, unknown>;\n try { existing = JSON.parse(readFileSync(configPath, 'utf-8')); } catch { return false; }\n if (!('rulemetric' in existing)) return false;\n delete existing.rulemetric;\n if (Object.keys(existing).length === 0) {\n // No other blocks \u2014 remove the file entirely.\n try { unlinkSync(configPath); } catch { /* ignore */ }\n } else {\n writeFileSync(configPath, JSON.stringify(existing, null, 2) + '\\n');\n }\n return true;\n}\n\nexport function removeAntigravityHooks(projectPath: string): boolean {\n return removeAntigravityHooksFromFile(join(projectPath, '.agents', 'hooks.json'));\n}\n\nexport function removeAntigravityUserHooks(): boolean {\n const modern = removeAntigravityHooksFromFile(join(homedir(), '.gemini', 'config', 'hooks.json'));\n const legacy = removeAntigravityHooksFromFile(join(homedir(), '.gemini', 'hooks.json'));\n return modern || legacy;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY,WAAW,cAAc,eAAe,kBAAkB;AAC/E,SAAS,eAAe;AACxB,SAAS,YAAY;AAQd,SAAS,qBAAqB,aAAqC;AACxE,QAAM,QAAwB,CAAC,aAAa;AAE5C,MAAI,WAAW,KAAK,aAAa,SAAS,CAAC,GAAG;AAC5C,UAAM,KAAK,QAAQ;AAAA,EACrB;AAEA,MAAI,WAA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,SAAS,sBAAsB,aAAoC;AACxE,SAAO,2BAA2B,KAAK,aAAa,SAAS,CAAC;AAChE;AAEO,SAAS,4BAA2C;AACzD,QAAM,YAAY,KAAK,QAAQ,GAAG,WAAW,QAAQ;AACrD,SAAO,2BAA2B,SAAS;AAC7C;AAEA,SAAS,+BAA+B,YAA6B;AACnE,MAAI,CAAC,WAAW,UAAU,EAAG,QAAO;AACpC,MAAI;AACJ,MAAI;AAAE,eAAW,KAAK,MAAM,aAAa,YAAY,OAAO,CAAC;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAO;AACxF,MAAI,EAAE,gBAAgB,UAAW,QAAO;AACxC,SAAO,SAAS;AAChB,MAAI,OAAO,KAAK,QAAQ,EAAE,WAAW,GAAG;AAEtC,QAAI;AAAE,iBAAW,UAAU;AAAA,IAAG,QAAQ;AAAA,IAAe;AAAA,EACvD,OAAO;AACL,kBAAc,YAAY,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;AAAA,EACpE;AACA,SAAO;AACT;AAEO,SAAS,uBAAuB,aAA8B;AACnE,SAAO,+BAA+B,KAAK,aAAa,WAAW,YAAY,CAAC;AAClF;AAEO,SAAS,6BAAsC;AACpD,QAAM,SAAS,+BAA+B,KAAK,QAAQ,GAAG,WAAW,UAAU,YAAY,CAAC;AAChG,QAAM,SAAS,+BAA+B,KAAK,QAAQ,GAAG,WAAW,YAAY,CAAC;AACtF,SAAO,UAAU;AACnB;",
6
+ "names": []
7
+ }
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  removeWorktree
3
3
  } from "./chunk-FUS5C4SB.js";
4
+ import {
5
+ PermanentJobError
6
+ } from "./chunk-DGHWRQXL.js";
4
7
  import {
5
8
  agentRuns,
6
9
  getDb,
7
10
  sessions
8
11
  } from "./chunk-42A3HEEH.js";
9
- import {
10
- PermanentJobError
11
- } from "./chunk-DGHWRQXL.js";
12
12
 
13
13
  // src/lib/handlers/process-run-cleanup.ts
14
14
  import { and, eq, isNotNull } from "drizzle-orm";
@@ -96,4 +96,4 @@ async function processRunCleanup(payload, deps = {}) {
96
96
  export {
97
97
  processRunCleanup
98
98
  };
99
- //# sourceMappingURL=chunk-Y2ARLMWZ.js.map
99
+ //# sourceMappingURL=chunk-C7SRRSPA.js.map
@@ -1,3 +1,6 @@
1
+ import {
2
+ PermanentJobError
3
+ } from "./chunk-DGHWRQXL.js";
1
4
  import {
2
5
  sendEmail
3
6
  } from "./chunk-QSN77T7C.js";
@@ -8,9 +11,6 @@ import {
8
11
  notificationPreferences,
9
12
  profiles
10
13
  } from "./chunk-42A3HEEH.js";
11
- import {
12
- PermanentJobError
13
- } from "./chunk-DGHWRQXL.js";
14
14
 
15
15
  // src/lib/handlers/process-announcement.ts
16
16
  import { and, asc, eq, gt, isNotNull } from "drizzle-orm";
@@ -154,4 +154,4 @@ async function sendOne(args) {
154
154
  export {
155
155
  processAnnouncement
156
156
  };
157
- //# sourceMappingURL=chunk-2BCPVUSF.js.map
157
+ //# sourceMappingURL=chunk-CLC7ZFH2.js.map
@@ -0,0 +1,80 @@
1
+ // src/lib/instruction-snapshot.ts
2
+ import { createHash } from "node:crypto";
3
+ import { readdirSync, readFileSync } from "node:fs";
4
+ import { join, relative } from "node:path";
5
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
6
+ "node_modules",
7
+ ".git",
8
+ "dist",
9
+ "build",
10
+ "out",
11
+ ".next",
12
+ "coverage",
13
+ ".turbo",
14
+ "vendor",
15
+ ".venv"
16
+ ]);
17
+ var MAX_FILES = 50;
18
+ var MAX_DEPTH = 8;
19
+ var sha256 = (s) => createHash("sha256").update(s).digest("hex");
20
+ function findClaudeMdFiles(root) {
21
+ const found = [];
22
+ const walk = (dir, depth) => {
23
+ if (found.length >= MAX_FILES || depth > MAX_DEPTH) return;
24
+ let entries;
25
+ try {
26
+ entries = readdirSync(dir, { withFileTypes: true });
27
+ } catch {
28
+ return;
29
+ }
30
+ for (const entry of entries) {
31
+ if (found.length >= MAX_FILES) return;
32
+ if (entry.isDirectory()) {
33
+ if (SKIP_DIRS.has(entry.name) || entry.name.startsWith(".")) continue;
34
+ walk(join(dir, entry.name), depth + 1);
35
+ } else if (entry.isFile() && entry.name === "CLAUDE.md") {
36
+ found.push(join(dir, entry.name));
37
+ }
38
+ }
39
+ };
40
+ walk(root, 0);
41
+ return found.sort();
42
+ }
43
+ function buildInstructionSnapshot(projectDir) {
44
+ const context_items = [];
45
+ const injected_instructions = [];
46
+ for (const filePath of findClaudeMdFiles(projectDir)) {
47
+ let body;
48
+ try {
49
+ body = readFileSync(filePath, "utf-8");
50
+ } catch {
51
+ continue;
52
+ }
53
+ if (!body.trim()) continue;
54
+ const instruction_index = injected_instructions.length;
55
+ injected_instructions.push(body);
56
+ context_items.push({
57
+ type: "claude_md",
58
+ name: relative(projectDir, filePath) || "CLAUDE.md",
59
+ content_hash: sha256(body),
60
+ char_count: body.length,
61
+ estimated_tokens: Math.ceil(body.length / 4),
62
+ instruction_index
63
+ });
64
+ }
65
+ if (context_items.length === 0) return null;
66
+ return {
67
+ provider: "claude_code",
68
+ model: "unknown",
69
+ system_prompt: "",
70
+ system_hash: sha256(""),
71
+ injected_instructions,
72
+ context_items,
73
+ metadata: { source: "hook_instruction_snapshot" }
74
+ };
75
+ }
76
+
77
+ export {
78
+ buildInstructionSnapshot
79
+ };
80
+ //# sourceMappingURL=chunk-SO3T35U7.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/instruction-snapshot.ts"],
4
+ "sourcesContent": ["import { createHash } from 'node:crypto';\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\n\n/**\n * A synthetic instruction snapshot for the hooks-first (zero-proxy) capture path.\n *\n * The proxy captures the *rendered* system prompt and classifies it into\n * `context_items` that `link-instructions` matches on. Hooks-only sessions never\n * hit the proxy, so this reconstructs an equivalent snapshot from the on-disk\n * instruction files (CLAUDE.md) \u2014 enough for `link-instructions` to auto-create\n * and link `claude_md` instructions.\n *\n * LIMITATION (by design): this hashes the RAW file body, whereas the proxy hashes\n * the rendered/normalized system-prompt text, so hook-sourced and proxy-sourced\n * instructions live in different content_hash namespaces and will NOT merge. It is\n * also STATIC \u2014 it cannot see runtime-injected context (skills invoked mid-session,\n * @-imports resolved on demand, subagent prompts). It is a partial, best-effort\n * bridge for zero-proxy users, not proxy parity.\n */\nexport interface InstructionContextItem {\n type: 'claude_md';\n name: string;\n content_hash: string;\n char_count: number;\n estimated_tokens: number;\n instruction_index: number;\n}\n\nexport interface InstructionSnapshot {\n provider: string;\n model: string;\n system_prompt: string;\n system_hash: string;\n injected_instructions: string[];\n context_items: InstructionContextItem[];\n metadata: Record<string, unknown>;\n}\n\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', 'out', '.next', 'coverage', '.turbo', 'vendor', '.venv',\n]);\nconst MAX_FILES = 50;\nconst MAX_DEPTH = 8;\n\nconst sha256 = (s: string) => createHash('sha256').update(s).digest('hex');\n\n/** Recursively locate CLAUDE.md files, skipping heavy/hidden dirs. */\nfunction findClaudeMdFiles(root: string): string[] {\n const found: string[] = [];\n const walk = (dir: string, depth: number): void => {\n if (found.length >= MAX_FILES || depth > MAX_DEPTH) return;\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (found.length >= MAX_FILES) return;\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;\n walk(join(dir, entry.name), depth + 1);\n } else if (entry.isFile() && entry.name === 'CLAUDE.md') {\n found.push(join(dir, entry.name));\n }\n }\n };\n walk(root, 0);\n return found.sort();\n}\n\n/**\n * Build a synthetic context snapshot from a project's on-disk instruction files,\n * ready to `POST /api/sessions/:id/context-snapshots`. Returns null when the\n * project has no non-empty instruction files (nothing to link).\n */\nexport function buildInstructionSnapshot(projectDir: string): InstructionSnapshot | null {\n const context_items: InstructionContextItem[] = [];\n const injected_instructions: string[] = [];\n\n for (const filePath of findClaudeMdFiles(projectDir)) {\n let body: string;\n try {\n body = readFileSync(filePath, 'utf-8');\n } catch {\n continue;\n }\n if (!body.trim()) continue;\n const instruction_index = injected_instructions.length;\n injected_instructions.push(body);\n context_items.push({\n type: 'claude_md',\n name: relative(projectDir, filePath) || 'CLAUDE.md',\n content_hash: sha256(body),\n char_count: body.length,\n estimated_tokens: Math.ceil(body.length / 4),\n instruction_index,\n });\n }\n\n if (context_items.length === 0) return null;\n\n return {\n provider: 'claude_code',\n model: 'unknown',\n system_prompt: '',\n system_hash: sha256(''),\n injected_instructions,\n context_items,\n metadata: { source: 'hook_instruction_snapshot' },\n };\n}\n"],
5
+ "mappings": ";AAAA,SAAS,kBAAkB;AAC3B,SAAS,aAAa,oBAAoB;AAC1C,SAAS,MAAM,gBAAgB;AAqC/B,IAAM,YAAY,oBAAI,IAAI;AAAA,EACxB;AAAA,EAAgB;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAO;AAAA,EAAS;AAAA,EAAY;AAAA,EAAU;AAAA,EAAU;AAC3F,CAAC;AACD,IAAM,YAAY;AAClB,IAAM,YAAY;AAElB,IAAM,SAAS,CAAC,MAAc,WAAW,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK;AAGzE,SAAS,kBAAkB,MAAwB;AACjD,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,CAAC,KAAa,UAAwB;AACjD,QAAI,MAAM,UAAU,aAAa,QAAQ,UAAW;AACpD,QAAI;AACJ,QAAI;AACF,gBAAU,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IACpD,QAAQ;AACN;AAAA,IACF;AACA,eAAW,SAAS,SAAS;AAC3B,UAAI,MAAM,UAAU,UAAW;AAC/B,UAAI,MAAM,YAAY,GAAG;AACvB,YAAI,UAAU,IAAI,MAAM,IAAI,KAAK,MAAM,KAAK,WAAW,GAAG,EAAG;AAC7D,aAAK,KAAK,KAAK,MAAM,IAAI,GAAG,QAAQ,CAAC;AAAA,MACvC,WAAW,MAAM,OAAO,KAAK,MAAM,SAAS,aAAa;AACvD,cAAM,KAAK,KAAK,KAAK,MAAM,IAAI,CAAC;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AACA,OAAK,MAAM,CAAC;AACZ,SAAO,MAAM,KAAK;AACpB;AAOO,SAAS,yBAAyB,YAAgD;AACvF,QAAM,gBAA0C,CAAC;AACjD,QAAM,wBAAkC,CAAC;AAEzC,aAAW,YAAY,kBAAkB,UAAU,GAAG;AACpD,QAAI;AACJ,QAAI;AACF,aAAO,aAAa,UAAU,OAAO;AAAA,IACvC,QAAQ;AACN;AAAA,IACF;AACA,QAAI,CAAC,KAAK,KAAK,EAAG;AAClB,UAAM,oBAAoB,sBAAsB;AAChD,0BAAsB,KAAK,IAAI;AAC/B,kBAAc,KAAK;AAAA,MACjB,MAAM;AAAA,MACN,MAAM,SAAS,YAAY,QAAQ,KAAK;AAAA,MACxC,cAAc,OAAO,IAAI;AAAA,MACzB,YAAY,KAAK;AAAA,MACjB,kBAAkB,KAAK,KAAK,KAAK,SAAS,CAAC;AAAA,MAC3C;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,cAAc,WAAW,EAAG,QAAO;AAEvC,SAAO;AAAA,IACL,UAAU;AAAA,IACV,OAAO;AAAA,IACP,eAAe;AAAA,IACf,aAAa,OAAO,EAAE;AAAA,IACtB;AAAA,IACA;AAAA,IACA,UAAU,EAAE,QAAQ,4BAA4B;AAAA,EAClD;AACF;",
6
+ "names": []
7
+ }
@@ -1,10 +1,11 @@
1
1
  import {
2
2
  runAgentLoop
3
- } from "../../chunk-LCT6MT2V.js";
3
+ } from "../../chunk-2WWGG2A5.js";
4
4
  import "../../chunk-JX5UI6RW.js";
5
+ import "../../chunk-QJXAULRC.js";
5
6
  import "../../chunk-EHABPBGH.js";
6
7
  import "../../chunk-XMWHTOCC.js";
7
- import "../../chunk-Y2ARLMWZ.js";
8
+ import "../../chunk-C7SRRSPA.js";
8
9
  import "../../chunk-FUS5C4SB.js";
9
10
  import "../../chunk-W53GKIZQ.js";
10
11
  import "../../chunk-YEBBX4HQ.js";
@@ -12,18 +13,17 @@ import "../../chunk-XZXS2W24.js";
12
13
  import "../../chunk-RQ2TMLKG.js";
13
14
  import "../../chunk-YBNW7ARH.js";
14
15
  import "../../chunk-FZKLLNDS.js";
15
- import "../../chunk-2BCPVUSF.js";
16
+ import "../../chunk-CLC7ZFH2.js";
17
+ import "../../chunk-DGHWRQXL.js";
16
18
  import "../../chunk-K3BFZ7KG.js";
17
19
  import "../../chunk-QSN77T7C.js";
18
20
  import {
19
21
  closeDb
20
22
  } from "../../chunk-42A3HEEH.js";
21
23
  import "../../chunk-BD7CY42U.js";
22
- import "../../chunk-QJXAULRC.js";
23
- import "../../chunk-DGHWRQXL.js";
24
+ import "../../chunk-IWYCRLEK.js";
24
25
  import "../../chunk-J7N3DLH6.js";
25
26
  import "../../chunk-52WIYRZH.js";
26
- import "../../chunk-IWYCRLEK.js";
27
27
  import "../../chunk-EKP32DLN.js";
28
28
  import "../../chunk-4QGATD5Y.js";
29
29
  import "../../chunk-OQSQC7VB.js";
@@ -0,0 +1,25 @@
1
+ import {
2
+ buildInstructionSnapshot
3
+ } from "../../chunk-SO3T35U7.js";
4
+ import "../../chunk-NSBPE2FW.js";
5
+
6
+ // src/commands/hooks/emit-instructions.ts
7
+ import { Command, Flags } from "@oclif/core";
8
+ var HooksEmitInstructions = class _HooksEmitInstructions extends Command {
9
+ static description = "Print a synthetic instruction snapshot (on-disk CLAUDE.md) as JSON for zero-proxy instruction linking";
10
+ static hidden = true;
11
+ static flags = {
12
+ "project-dir": Flags.string({ description: "Project directory to scan (defaults to cwd)" })
13
+ };
14
+ async run() {
15
+ const { flags } = await this.parse(_HooksEmitInstructions);
16
+ const snapshot = buildInstructionSnapshot(flags["project-dir"] ?? process.cwd());
17
+ if (snapshot) {
18
+ process.stdout.write(JSON.stringify(snapshot));
19
+ }
20
+ }
21
+ };
22
+ export {
23
+ HooksEmitInstructions as default
24
+ };
25
+ //# sourceMappingURL=emit-instructions.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/commands/hooks/emit-instructions.ts"],
4
+ "sourcesContent": ["import { Command, Flags } from '@oclif/core';\nimport { buildInstructionSnapshot } from '../../lib/instruction-snapshot.js';\n\n/**\n * Prints a synthetic instruction snapshot (built from on-disk CLAUDE.md files) as\n * JSON on stdout. Consumed by `session-end.sh`, which POSTs it to\n * `/api/sessions/:id/context-snapshots` so `link-instructions` can link\n * `claude_md` instructions on a hooks-only (zero-proxy) session.\n *\n * Extends raw oclif `Command` (not BaseCommand): it does no network or auth \u2014 it\n * only reads local files \u2014 and stdout MUST be clean JSON for the curl in\n * session-end.sh. Prints nothing when the project has no instruction files.\n */\nexport default class HooksEmitInstructions extends Command {\n static override description =\n 'Print a synthetic instruction snapshot (on-disk CLAUDE.md) as JSON for zero-proxy instruction linking';\n\n static override hidden = true;\n\n static override flags = {\n 'project-dir': Flags.string({ description: 'Project directory to scan (defaults to cwd)' }),\n };\n\n async run(): Promise<void> {\n const { flags } = await this.parse(HooksEmitInstructions);\n const snapshot = buildInstructionSnapshot(flags['project-dir'] ?? process.cwd());\n if (snapshot) {\n process.stdout.write(JSON.stringify(snapshot));\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;AAAA,SAAS,SAAS,aAAa;AAa/B,IAAqB,wBAArB,MAAqB,+BAA8B,QAAQ;AAAA,EACzD,OAAgB,cACd;AAAA,EAEF,OAAgB,SAAS;AAAA,EAEzB,OAAgB,QAAQ;AAAA,IACtB,eAAe,MAAM,OAAO,EAAE,aAAa,8CAA8C,CAAC;AAAA,EAC5F;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,KAAK,MAAM,sBAAqB;AACxD,UAAM,WAAW,yBAAyB,MAAM,aAAa,KAAK,QAAQ,IAAI,CAAC;AAC/E,QAAI,UAAU;AACZ,cAAQ,OAAO,MAAM,KAAK,UAAU,QAAQ,CAAC;AAAA,IAC/C;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -9,6 +9,8 @@ import {
9
9
  } from "../../chunk-BO76WKJR.js";
10
10
  import {
11
11
  installMacOSProxyEnv,
12
+ mergeClaudeCodeHooks,
13
+ removeClaudeCodeHooks,
12
14
  writeAntigravityHooks,
13
15
  writeAntigravityUserHooks,
14
16
  writeCopilotHooks,
@@ -18,7 +20,7 @@ import {
18
20
  writeCursorUserProxyConfig,
19
21
  writeVSCodeProxyConfig,
20
22
  writeVSCodeUserProxyConfig
21
- } from "../../chunk-L674RNKQ.js";
23
+ } from "../../chunk-ANOWI23I.js";
22
24
  import "../../chunk-KRBQLMOP.js";
23
25
  import {
24
26
  GATEWAY_PORT,
@@ -93,23 +95,11 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
93
95
  if (existsSync(configPath)) {
94
96
  settings = JSON.parse(readFileSync(configPath, "utf-8"));
95
97
  }
96
- if (settings.hooks && typeof settings.hooks === "object") {
97
- const hooks = settings.hooks;
98
- let removed = 0;
99
- for (const event of Object.keys(hooks)) {
100
- const entries = hooks[event];
101
- if (!Array.isArray(entries)) continue;
102
- const kept = entries.filter((entry) => {
103
- const isRulemetric = entry?.hooks?.some((h) => typeof h?.command === "string" && h.command.includes("rulemetric"));
104
- if (isRulemetric) removed += 1;
105
- return !isRulemetric;
106
- });
107
- if (kept.length === 0) delete hooks[event];
108
- else hooks[event] = kept;
109
- }
110
- if (Object.keys(hooks).length === 0) delete settings.hooks;
111
- if (removed > 0) this.log(`[OK] Removed ${removed} legacy rulemetric session hook(s) (no longer needed)`);
112
- }
98
+ const refreshedHooks = removeClaudeCodeHooks(settings);
99
+ mergeClaudeCodeHooks(settings);
100
+ this.log(
101
+ refreshedHooks ? "[OK] Refreshed RuleMetric Claude Code session hooks \u2192 .claude/settings.json" : "[OK] Installed RuleMetric Claude Code session hooks \u2192 .claude/settings.json"
102
+ );
113
103
  if (!noProxy) {
114
104
  const hasMitmproxy = this.findBinary("mitmdump");
115
105
  if (!hasMitmproxy) {
@@ -244,16 +234,20 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
244
234
  this.log("");
245
235
  this.log("The API service starts on login and restarts on crash.");
246
236
  } else if (!noProxy) {
247
- this.log(" 1. Start the capture proxy: rulemetric proxy start");
248
- this.log(" 2. Start Claude Code \u2014 context will be captured automatically");
237
+ this.log(" 1. Start Claude Code \u2014 sessions are captured by hooks immediately");
238
+ this.log(" 2. Start the capture proxy for full depth: rulemetric proxy start");
249
239
  this.log("");
250
- this.log("The gateway routes traffic direct when the proxy is off \u2014 Claude Code always works.");
240
+ this.log("Hooks capture every session (lifecycle + transcript). The proxy adds the");
241
+ this.log("rendered system prompt (instruction-effectiveness linking) + cross-tool capture.");
251
242
  this.log("");
252
243
  this.log("To capture traffic from other clients (Python, curl, etc.):");
253
244
  this.log(' eval "$(rulemetric proxy env --all)"');
254
245
  } else {
255
- this.log(" 1. Start Claude Code \u2014 session events will be tracked");
256
- this.log(" (Run without --no-proxy to also capture system prompts)");
246
+ this.log(" 1. Start Claude Code \u2014 sessions are captured by the hooks just installed");
247
+ this.log("");
248
+ this.log("No proxy means no mitmproxy / CA cert needed. The hooks capture full");
249
+ this.log("sessions on their own; re-run without --no-proxy to also capture system");
250
+ this.log("prompts for instruction-effectiveness linking.");
257
251
  }
258
252
  await bootstrapActiveOrg();
259
253
  const tmux = await detectTmux();