@rulemetric/cli 0.2.4 → 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 (64) hide show
  1. package/dist/{chunk-JM6BQSRE.js → chunk-2WWGG2A5.js} +11 -11
  2. package/dist/{chunk-4A7FKR2O.js → chunk-42A3HEEH.js} +50 -3
  3. package/dist/chunk-42A3HEEH.js.map +7 -0
  4. package/dist/{chunk-PDURR7O3.js → chunk-46LMTDRE.js} +2 -2
  5. package/dist/{chunk-ISDA2QFX.js → chunk-4QGATD5Y.js} +209 -2
  6. package/dist/chunk-4QGATD5Y.js.map +7 -0
  7. package/dist/{chunk-L674RNKQ.js → chunk-ANOWI23I.js} +51 -1
  8. package/dist/chunk-ANOWI23I.js.map +7 -0
  9. package/dist/{chunk-3LHLSY7V.js → chunk-C7SRRSPA.js} +6 -6
  10. package/dist/{chunk-B3HILODD.js → chunk-CLC7ZFH2.js} +6 -6
  11. package/dist/{chunk-PIOVE3TN.js → chunk-FUS5C4SB.js} +2 -2
  12. package/dist/{chunk-PHLMIZKM.js → chunk-JNFIYBFL.js} +30 -5
  13. package/dist/chunk-JNFIYBFL.js.map +7 -0
  14. package/dist/{chunk-RDIH4AG2.js → chunk-MTLAIJED.js} +3 -3
  15. package/dist/{chunk-NIDLJO6F.js → chunk-QSN77T7C.js} +23 -1
  16. package/dist/{chunk-NIDLJO6F.js.map → chunk-QSN77T7C.js.map} +2 -2
  17. package/dist/chunk-SO3T35U7.js +80 -0
  18. package/dist/chunk-SO3T35U7.js.map +7 -0
  19. package/dist/{chunk-ELL34R3K.js → chunk-XMWHTOCC.js} +3 -3
  20. package/dist/{chunk-3IU7GFXS.js → chunk-YEBBX4HQ.js} +2 -2
  21. package/dist/commands/evals/agent.js +12 -14
  22. package/dist/commands/evals/agent.js.map +2 -2
  23. package/dist/commands/hooks/emit-instructions.js +25 -0
  24. package/dist/commands/hooks/emit-instructions.js.map +7 -0
  25. package/dist/commands/hooks/install.js +18 -24
  26. package/dist/commands/hooks/install.js.map +2 -2
  27. package/dist/commands/hooks/uninstall.js +4 -4
  28. package/dist/commands/hooks/uninstall.js.map +2 -2
  29. package/dist/commands/research/backfill.js +3 -3
  30. package/dist/commands/research/tail-transcript.js +3 -3
  31. package/dist/commands/service/install.js +186 -11
  32. package/dist/commands/service/install.js.map +2 -2
  33. package/dist/commands/service/uninstall.js +33 -2
  34. package/dist/commands/service/uninstall.js.map +2 -2
  35. package/dist/dashboard/Dashboard.js +12 -12
  36. package/dist/dashboard/data.js +2 -2
  37. package/dist/{dist-I6BCOLNG.js → dist-NEECHU47.js} +6 -2
  38. package/dist/lib/agent-loop.js +12 -12
  39. package/dist/lib/handlers/process-announcement.js +3 -3
  40. package/dist/lib/handlers/process-changelog.js +3 -3
  41. package/dist/lib/handlers/process-launch.js +3 -3
  42. package/dist/lib/handlers/process-run-cleanup.js +4 -4
  43. package/dist/lib/handlers/process-session-goal.js +2 -2
  44. package/dist/lib/hooks-config.js +7 -1
  45. package/dist/lib/instruction-snapshot.js +8 -0
  46. package/dist/lib/instruction-snapshot.js.map +7 -0
  47. package/dist/lib/manual-tasks.js +3 -3
  48. package/dist/lib/statusline-shim.js +1 -1
  49. package/dist/lib/worktree.js +2 -2
  50. package/oclif.manifest.json +1014 -977
  51. package/package.json +18 -15
  52. package/dist/chunk-4A7FKR2O.js.map +0 -7
  53. package/dist/chunk-ISDA2QFX.js.map +0 -7
  54. package/dist/chunk-L674RNKQ.js.map +0 -7
  55. package/dist/chunk-PHLMIZKM.js.map +0 -7
  56. /package/dist/{chunk-JM6BQSRE.js.map → chunk-2WWGG2A5.js.map} +0 -0
  57. /package/dist/{chunk-PDURR7O3.js.map → chunk-46LMTDRE.js.map} +0 -0
  58. /package/dist/{chunk-3LHLSY7V.js.map → chunk-C7SRRSPA.js.map} +0 -0
  59. /package/dist/{chunk-B3HILODD.js.map → chunk-CLC7ZFH2.js.map} +0 -0
  60. /package/dist/{chunk-PIOVE3TN.js.map → chunk-FUS5C4SB.js.map} +0 -0
  61. /package/dist/{chunk-RDIH4AG2.js.map → chunk-MTLAIJED.js.map} +0 -0
  62. /package/dist/{chunk-ELL34R3K.js.map → chunk-XMWHTOCC.js.map} +0 -0
  63. /package/dist/{chunk-3IU7GFXS.js.map → chunk-YEBBX4HQ.js.map} +0 -0
  64. /package/dist/{dist-I6BCOLNG.js.map → dist-NEECHU47.js.map} +0 -0
@@ -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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
3
- } from "./chunk-PIOVE3TN.js";
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
- } from "./chunk-4A7FKR2O.js";
9
- import {
10
- PermanentJobError
11
- } from "./chunk-DGHWRQXL.js";
11
+ } from "./chunk-42A3HEEH.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-3LHLSY7V.js.map
99
+ //# sourceMappingURL=chunk-C7SRRSPA.js.map
@@ -1,16 +1,16 @@
1
+ import {
2
+ PermanentJobError
3
+ } from "./chunk-DGHWRQXL.js";
1
4
  import {
2
5
  sendEmail
3
- } from "./chunk-NIDLJO6F.js";
6
+ } from "./chunk-QSN77T7C.js";
4
7
  import {
5
8
  announcementDeliveries,
6
9
  announcements,
7
10
  getDb,
8
11
  notificationPreferences,
9
12
  profiles
10
- } from "./chunk-4A7FKR2O.js";
11
- import {
12
- PermanentJobError
13
- } from "./chunk-DGHWRQXL.js";
13
+ } from "./chunk-42A3HEEH.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-B3HILODD.js.map
157
+ //# sourceMappingURL=chunk-CLC7ZFH2.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  worktreePathFor
3
- } from "./chunk-ISDA2QFX.js";
3
+ } from "./chunk-4QGATD5Y.js";
4
4
  import {
5
5
  tmuxSpawnEnv
6
6
  } from "./chunk-KRBQLMOP.js";
@@ -145,4 +145,4 @@ export {
145
145
  ensureWorktree,
146
146
  removeWorktree
147
147
  };
148
- //# sourceMappingURL=chunk-PIOVE3TN.js.map
148
+ //# sourceMappingURL=chunk-FUS5C4SB.js.map
@@ -41,6 +41,8 @@ ${chainBlock}
41
41
  fi
42
42
 
43
43
  OBSERVED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
44
+ CACHE_DIR="$HOME/.config/rulemetric"
45
+ mkdir -p "$CACHE_DIR" 2>/dev/null || true
44
46
 
45
47
  for WIRE_KEY in five_hour seven_day seven_day_opus; do
46
48
  # Map wire key \u2192 limit_type (case statement avoids bash 4 associative arrays).
@@ -74,6 +76,32 @@ for WIRE_KEY in five_hour seven_day seven_day_opus; do
74
76
  RESETS_AT_ISO=""
75
77
  fi
76
78
 
79
+ # Skip stale windows. Claude Code can keep re-emitting a cached rate_limits
80
+ # block after the reset time has passed; storing those rows floods the DB and
81
+ # corrupts the "current limits" view.
82
+ if [ -n "$RESETS_AT_EPOCH" ] && [ "$RESETS_AT_EPOCH" != "null" ]; then
83
+ NOW_EPOCH="$(date -u +%s)"
84
+ if [ "$RESETS_AT_EPOCH" -lt "$NOW_EPOCH" ] 2>/dev/null; then
85
+ continue
86
+ fi
87
+ else
88
+ NOW_EPOCH="$(date -u +%s)"
89
+ fi
90
+
91
+ # Local duplicate suppression mirrors the API's 30-minute freshness floor.
92
+ # The statusline refreshes often; if the same window/value/reset is already
93
+ # posted recently, another POST only burns an API request and DB connection.
94
+ CACHE_FILE="$CACHE_DIR/statusline-usage-\${LIMIT_TYPE}.cache"
95
+ CACHE_KEY="\${LIMIT_TYPE}|\${USED_PCT}|\${RESETS_AT_ISO}"
96
+ if [ -f "$CACHE_FILE" ]; then
97
+ read -r CACHED_AT CACHED_KEY < "$CACHE_FILE" || true
98
+ if [ "\${CACHED_KEY:-}" = "$CACHE_KEY" ] && [ $((NOW_EPOCH - \${CACHED_AT:-0})) -lt 1800 ] 2>/dev/null; then
99
+ continue
100
+ fi
101
+ fi
102
+ printf '%s %s
103
+ ' "$NOW_EPOCH" "$CACHE_KEY" > "$CACHE_FILE.tmp" 2>/dev/null && mv "$CACHE_FILE.tmp" "$CACHE_FILE" 2>/dev/null || true
104
+
77
105
  PAYLOAD="$(jq -nc \\
78
106
  --arg provider "anthropic" \\
79
107
  --arg plan "unknown" \\
@@ -100,12 +128,9 @@ for WIRE_KEY in five_hour seven_day seven_day_opus; do
100
128
  -H "Content-Type: application/json" \\
101
129
  -H "Authorization: Bearer $AUTH_TOKEN" \\
102
130
  --max-time 3 \\
103
- --data "$PAYLOAD" &
131
+ --data "$PAYLOAD" >/dev/null 2>&1 &
104
132
  done
105
133
 
106
- # Wait for background curls (non-blocking from Claude Code's perspective \u2014
107
- # the shim itself exits promptly; curl jobs are fire-and-forget).
108
- wait
109
134
  ${chainBlock}
110
135
  exit 0
111
136
  `;
@@ -150,4 +175,4 @@ export {
150
175
  readCurrentStatusLine,
151
176
  isStatuslineShimInstalled
152
177
  };
153
- //# sourceMappingURL=chunk-PHLMIZKM.js.map
178
+ //# sourceMappingURL=chunk-JNFIYBFL.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/statusline-shim.ts"],
4
+ "sourcesContent": ["import { existsSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n// Path where the shim script lives \u2014 readable by the `statusLine` config key.\nexport const STATUSLINE_SHIM_PATH = join(homedir(), '.claude', 'statusline-rulemetric.sh');\n\n/**\n * Write ~/.claude/statusline-rulemetric.sh.\n *\n * The script is invoked by Claude Code on every statusline refresh cycle.\n * Claude Code feeds a JSON payload on stdin that includes `rate_limits`\n * (same shape as GET /api/oauth/usage) using its own in-memory token \u2014\n * so freshness is tied to the statusline cadence, not the proxy capturing\n * a stale keychain token.\n *\n * The script:\n * 1. Reads stdin once (Claude Code closes it after the payload).\n * 2. If jq is available, extracts each rate_limit window and POSTs it to\n * POST /api/internal/research/observe as an oauth_usage observation.\n * 3. If a `prevCommand` is supplied (the user's original statusLine value),\n * it is executed with the same stdin forwarded so the user's prompt text\n * is still displayed \u2014 we must chain, not replace.\n * 4. Exits 0 regardless so Claude Code always gets a clean statusline.\n *\n * Auth is read from the same priority chain as the hook scripts:\n * ~/.config/rulemetric/env (RULEMETRIC_ACCESS_TOKEN / RULEMETRIC_API_KEY)\n * RULEMETRIC_API_KEY / RULEMETRIC_ACCESS_TOKEN env vars\n *\n * Returns the path written.\n */\nexport function writeStatuslineShim(prevCommand?: string): string {\n const chainBlock = prevCommand\n ? `\n# Chain to the original statusLine command so the user's prompt is preserved.\necho \"$STDIN_PAYLOAD\" | ${prevCommand}`\n : '';\n\n const script = `#!/usr/bin/env bash\n# RuleMetric statusline shim \u2014 auto-generated by \\`rulemetric hooks install --statusline-usage\\`\n# Captures Claude Code rate_limits from statusline stdin and forwards to the research pipeline.\n# DO NOT EDIT \u2014 re-run \\`rulemetric hooks install --statusline-usage\\` to regenerate.\n\nset -euo pipefail\n\n# Read stdin once (Claude Code closes the pipe after the payload).\nSTDIN_PAYLOAD=\"$(cat)\"\n\n# \u2500\u2500 Auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nCONFIG_ENV=\"$HOME/.config/rulemetric/env\"\nif [ -f \"$CONFIG_ENV\" ]; then\n # shellcheck source=/dev/null\n source \"$CONFIG_ENV\"\nfi\n\nAPI_URL=\"\\${RULEMETRIC_API_URL:-https://rulemetric.com}\"\nAUTH_TOKEN=\"\\${RULEMETRIC_ACCESS_TOKEN:-\\${RULEMETRIC_API_KEY:-}}\"\n\nif [ -z \"$AUTH_TOKEN\" ]; then\n # No auth \u2014 still chain so the user's statusline works.\n${chainBlock}\n exit 0\nfi\n\n# \u2500\u2500 Extract + POST rate_limit windows \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nif ! command -v jq &>/dev/null; then\n # jq missing \u2014 chain and bail; don't break the user's statusline.\n${chainBlock}\n exit 0\nfi\n\nOBSERVED_AT=\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"\nCACHE_DIR=\"$HOME/.config/rulemetric\"\nmkdir -p \"$CACHE_DIR\" 2>/dev/null || true\n\nfor WIRE_KEY in five_hour seven_day seven_day_opus; do\n # Map wire key \u2192 limit_type (case statement avoids bash 4 associative arrays).\n case \"$WIRE_KEY\" in\n five_hour) LIMIT_TYPE=\"five_hour_percent\" ;;\n seven_day) LIMIT_TYPE=\"seven_day_percent\" ;;\n seven_day_opus) LIMIT_TYPE=\"seven_day_opus_percent\" ;;\n *) continue ;;\n esac\n\n # Try both wire shapes:\n # Legacy: { \"rate_limits\": { \"five_hour\": { \"used_percentage\": ..., \"resets_at\": ... } } }\n # Current: { \"five_hour\": { \"used_percentage\": ..., \"resets_at\": ... } }\n WINDOW=\"$(echo \"$STDIN_PAYLOAD\" | jq -c \".rate_limits.\\${WIRE_KEY} // .\\${WIRE_KEY} // empty\" 2>/dev/null || true)\"\n\n if [ -z \"$WINDOW\" ] || [ \"$WINDOW\" = \"null\" ]; then\n continue\n fi\n\n USED_PCT=\"$(echo \"$WINDOW\" | jq '.used_percentage // empty' 2>/dev/null || true)\"\n RESETS_AT_EPOCH=\"$(echo \"$WINDOW\" | jq '.resets_at // empty' 2>/dev/null || true)\"\n\n if [ -z \"$USED_PCT\" ] || [ \"$USED_PCT\" = \"null\" ]; then\n continue\n fi\n\n # Convert unix epoch to ISO-8601 if present.\n if [ -n \"$RESETS_AT_EPOCH\" ] && [ \"$RESETS_AT_EPOCH\" != \"null\" ]; then\n RESETS_AT_ISO=\"$(date -u -r \"$RESETS_AT_EPOCH\" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \\\n || date -u -d \"@$RESETS_AT_EPOCH\" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \\\n || echo \"\")\"\n else\n RESETS_AT_ISO=\"\"\n fi\n\n # Skip stale windows. Claude Code can keep re-emitting a cached rate_limits\n # block after the reset time has passed; storing those rows floods the DB and\n # corrupts the \"current limits\" view.\n if [ -n \"$RESETS_AT_EPOCH\" ] && [ \"$RESETS_AT_EPOCH\" != \"null\" ]; then\n NOW_EPOCH=\"$(date -u +%s)\"\n if [ \"$RESETS_AT_EPOCH\" -lt \"$NOW_EPOCH\" ] 2>/dev/null; then\n continue\n fi\n else\n NOW_EPOCH=\"$(date -u +%s)\"\n fi\n\n # Local duplicate suppression mirrors the API's 30-minute freshness floor.\n # The statusline refreshes often; if the same window/value/reset is already\n # posted recently, another POST only burns an API request and DB connection.\n CACHE_FILE=\"$CACHE_DIR/statusline-usage-\\${LIMIT_TYPE}.cache\"\n CACHE_KEY=\"\\${LIMIT_TYPE}|\\${USED_PCT}|\\${RESETS_AT_ISO}\"\n if [ -f \"$CACHE_FILE\" ]; then\n read -r CACHED_AT CACHED_KEY < \"$CACHE_FILE\" || true\n if [ \"\\${CACHED_KEY:-}\" = \"$CACHE_KEY\" ] && [ $((NOW_EPOCH - \\${CACHED_AT:-0})) -lt 1800 ] 2>/dev/null; then\n continue\n fi\n fi\n printf '%s %s\\n' \"$NOW_EPOCH\" \"$CACHE_KEY\" > \"$CACHE_FILE.tmp\" 2>/dev/null \\\n && mv \"$CACHE_FILE.tmp\" \"$CACHE_FILE\" 2>/dev/null || true\n\n PAYLOAD=\"$(jq -nc \\\\\n --arg provider \"anthropic\" \\\\\n --arg plan \"unknown\" \\\\\n --argjson value \"$USED_PCT\" \\\\\n --arg limitType \"$LIMIT_TYPE\" \\\\\n --arg observedAt \"$OBSERVED_AT\" \\\\\n --arg resetsAt \"$RESETS_AT_ISO\" \\\\\n '{\n provider: $provider,\n plan: $plan,\n limitType: $limitType,\n value: $value,\n unit: \"percentage\",\n comparator: \"=\",\n sourceType: \"oauth_usage\",\n sourceUrl: null,\n confidence: 1.0,\n observedAt: $observedAt,\n resetsAt: (if $resetsAt == \"\" then null else $resetsAt end)\n }')\"\n\n curl -sf -o /dev/null \\\\\n -X POST \"$API_URL/api/internal/research/observe\" \\\\\n -H \"Content-Type: application/json\" \\\\\n -H \"Authorization: Bearer $AUTH_TOKEN\" \\\\\n --max-time 3 \\\\\n --data \"$PAYLOAD\" >/dev/null 2>&1 &\ndone\n\n${chainBlock}\nexit 0\n`;\n\n writeFileSync(STATUSLINE_SHIM_PATH, script, { encoding: 'utf-8' });\n chmodSync(STATUSLINE_SHIM_PATH, 0o755);\n return STATUSLINE_SHIM_PATH;\n}\n\n// The settings object shape for statusLine (Claude Code v1.x+).\nexport const STATUSLINE_SETTINGS_VALUE = {\n type: 'command' as const,\n command: STATUSLINE_SHIM_PATH,\n refreshInterval: 30,\n};\n\n/**\n * Read the current statusLine command from a settings object, if any.\n * Returns undefined if not set or already points to the shim (idempotent).\n * Handles both the legacy string form and the current object form.\n */\nexport function readCurrentStatusLine(\n settings: Record<string, unknown>,\n): string | undefined {\n const current = settings.statusLine;\n if (!current) return undefined;\n if (typeof current === 'string') {\n if (current === STATUSLINE_SHIM_PATH) return undefined;\n return current;\n }\n if (typeof current === 'object' && current !== null) {\n const cmd = (current as Record<string, unknown>).command;\n if (typeof cmd !== 'string') return undefined;\n if (cmd === STATUSLINE_SHIM_PATH) return undefined; // already installed\n return cmd;\n }\n return undefined;\n}\n\n/**\n * Returns true if the settings object already points to the shim.\n */\nexport function isStatuslineShimInstalled(settings: Record<string, unknown>): boolean {\n const current = settings.statusLine;\n if (!current) return false;\n if (typeof current === 'string') return current === STATUSLINE_SHIM_PATH;\n if (typeof current === 'object' && current !== null) {\n return (current as Record<string, unknown>).command === STATUSLINE_SHIM_PATH;\n }\n return false;\n}\n"],
5
+ "mappings": ";AAAA,SAAmC,eAAe,iBAAiB;AACnE,SAAS,eAAe;AACxB,SAAS,YAAY;AAGd,IAAM,uBAAuB,KAAK,QAAQ,GAAG,WAAW,0BAA0B;AA0BlF,SAAS,oBAAoB,aAA8B;AAChE,QAAM,aAAa,cACf;AAAA;AAAA,0BAEoB,WAAW,KAC/B;AAEJ,QAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBf,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiGV,UAAU;AAAA;AAAA;AAIV,gBAAc,sBAAsB,QAAQ,EAAE,UAAU,QAAQ,CAAC;AACjE,YAAU,sBAAsB,GAAK;AACrC,SAAO;AACT;AAGO,IAAM,4BAA4B;AAAA,EACvC,MAAM;AAAA,EACN,SAAS;AAAA,EACT,iBAAiB;AACnB;AAOO,SAAS,sBACd,UACoB;AACpB,QAAM,UAAU,SAAS;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,OAAO,YAAY,UAAU;AAC/B,QAAI,YAAY,qBAAsB,QAAO;AAC7C,WAAO;AAAA,EACT;AACA,MAAI,OAAO,YAAY,YAAY,YAAY,MAAM;AACnD,UAAM,MAAO,QAAoC;AACjD,QAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAI,QAAQ,qBAAsB,QAAO;AACzC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAKO,SAAS,0BAA0B,UAA4C;AACpF,QAAM,UAAU,SAAS;AACzB,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,OAAO,YAAY,SAAU,QAAO,YAAY;AACpD,MAAI,OAAO,YAAY,YAAY,YAAY,MAAM;AACnD,WAAQ,QAAoC,YAAY;AAAA,EAC1D;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -4,11 +4,11 @@ import {
4
4
  } from "./chunk-K3BFZ7KG.js";
5
5
  import {
6
6
  renderChangelogAnnouncement
7
- } from "./chunk-NIDLJO6F.js";
7
+ } from "./chunk-QSN77T7C.js";
8
8
  import {
9
9
  announcements,
10
10
  getDb
11
- } from "./chunk-4A7FKR2O.js";
11
+ } from "./chunk-42A3HEEH.js";
12
12
 
13
13
  // src/lib/handlers/process-changelog.ts
14
14
  import * as fs from "node:fs/promises";
@@ -119,4 +119,4 @@ async function processChangelog(deps = {}) {
119
119
  export {
120
120
  processChangelog
121
121
  };
122
- //# sourceMappingURL=chunk-RDIH4AG2.js.map
122
+ //# sourceMappingURL=chunk-MTLAIJED.js.map
@@ -203,6 +203,23 @@ function selectEmailProvider() {
203
203
  return "resend";
204
204
  return "noop";
205
205
  }
206
+ var RESERVED_TLDS = /* @__PURE__ */ new Set(["test", "example", "invalid", "localhost"]);
207
+ var RESERVED_EXAMPLE_DOMAINS = /^example\.(com|net|org)$/;
208
+ function isUndeliverableRecipient(to) {
209
+ const addr = to.trim().toLowerCase();
210
+ const at = addr.lastIndexOf("@");
211
+ if (at < 0)
212
+ return false;
213
+ const domain = addr.slice(at + 1);
214
+ if (!domain)
215
+ return false;
216
+ const tld = domain.slice(domain.lastIndexOf(".") + 1);
217
+ if (RESERVED_TLDS.has(tld))
218
+ return true;
219
+ if (RESERVED_EXAMPLE_DOMAINS.test(domain))
220
+ return true;
221
+ return false;
222
+ }
206
223
  var providerLogged = false;
207
224
  async function sendEmail(params) {
208
225
  const provider = selectEmailProvider();
@@ -213,6 +230,11 @@ async function sendEmail(params) {
213
230
  }
214
231
  switch (provider) {
215
232
  case "resend":
233
+ if (isUndeliverableRecipient(params.to)) {
234
+ process.stderr.write(`[email] skipping real send to reserved/undeliverable address ${params.to} (RFC 2606/6761) \u2014 routed to noop to protect sender reputation
235
+ `);
236
+ return sendNoopEmail(params);
237
+ }
216
238
  return sendResendEmail(params);
217
239
  case "smtp":
218
240
  return sendSmtpEmail(params);
@@ -225,4 +247,4 @@ export {
225
247
  renderChangelogAnnouncement,
226
248
  sendEmail
227
249
  };
228
- //# sourceMappingURL=chunk-NIDLJO6F.js.map
250
+ //# sourceMappingURL=chunk-QSN77T7C.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../packages/email/src/templates/changelog-announcement.ts", "../../../packages/email/src/providers/noop.ts", "../../../packages/email/src/providers/resend.ts", "../../../packages/email/src/providers/smtp.ts", "../../../packages/email/src/index.ts"],
4
- "sourcesContent": ["// Product-announcement email template. Pure function \u2014 given a parsed\n// CHANGELOG entry, returns subject + html + text. No provider work, no\n// env reads, no IO.\n//\n// Design notes:\n// - Conventions mirror invitation.ts: inline styles only, viewport meta,\n// simple table layout, hand-rolled plain-text body, same colour palette.\n// - Section order is fixed (Added \u2192 Changed \u2192 Fixed \u2192 Removed \u2192\n// Deprecated \u2192 Security) regardless of insertion order in the input,\n// so a single deployment can't produce inconsistent ordering across\n// recipients.\n// - Footer carries the unsubscribe URL twice (styled link + raw text)\n// for CAN-SPAM compliance and because some clients suppress link\n// rendering.\n\nimport type { RenderedEmail } from './invitation.js';\n\nexport type ChangelogSectionName =\n | 'Added'\n | 'Changed'\n | 'Fixed'\n | 'Removed'\n | 'Deprecated'\n | 'Security';\n\nexport interface ChangelogAnnouncementInput {\n /** Verbatim version string from CHANGELOG, e.g. \"2026.06.05\". */\n version: string;\n /** ISO date YYYY-MM-DD. */\n date: string;\n /** Section name \u2192 array of bullet items. Items are plain text (no markdown). */\n sections: Partial<Record<ChangelogSectionName, string[]>>;\n /** Fully-qualified unsubscribe URL embedded in the footer. */\n unsubscribeUrl: string;\n /** Product home URL (e.g. https://rulemetric.com). For the header logo link. */\n productUrl: string;\n /** Optional recipient first name to personalize greeting; falls back to \"Hi there,\". */\n recipientName?: string;\n}\n\nconst ACCENT = '#5b6cff';\nconst TEXT_PRIMARY = '#1a1a1a';\nconst TEXT_MUTED = '#666666';\nconst BG_OUTER = '#f5f5f7';\nconst BG_CARD = '#ffffff';\nconst BORDER = '#e5e5e9';\n\n/** Documented render order for sections \u2014 applied regardless of input key order. */\nconst SECTION_ORDER: ChangelogSectionName[] = [\n 'Added',\n 'Changed',\n 'Fixed',\n 'Removed',\n 'Deprecated',\n 'Security',\n];\n\n/**\n * \"June 5, 2026\" \u2014 locale-independent format identical to invitation.ts.\n * Accepts an ISO YYYY-MM-DD string; parsed as UTC to avoid off-by-one in\n * recipient timezones west of the build server.\n */\nfunction formatIsoDate(iso: string): string {\n const months = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n ];\n const [y, m, d] = iso.split('-').map((s) => parseInt(s, 10));\n // Defensive: if the input is malformed we still want a string. Fall back\n // to the raw ISO so the recipient at least sees something coherent.\n if (!y || !m || !d || m < 1 || m > 12) return iso;\n return `${months[m - 1]} ${d}, ${y}`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/** Returns sections in canonical order, dropping missing/empty ones. */\nfunction orderedSections(\n sections: ChangelogAnnouncementInput['sections'],\n): Array<{ name: ChangelogSectionName; items: string[] }> {\n const out: Array<{ name: ChangelogSectionName; items: string[] }> = [];\n for (const name of SECTION_ORDER) {\n const items = sections[name];\n if (items && items.length > 0) {\n out.push({ name, items });\n }\n }\n return out;\n}\n\nexport function renderChangelogAnnouncement(\n input: ChangelogAnnouncementInput,\n): RenderedEmail {\n const { version, date, sections, unsubscribeUrl, productUrl, recipientName } = input;\n\n const formattedDate = formatIsoDate(date);\n const subject = `What's new in RuleMetric \u2014 ${formattedDate}`;\n const greeting = recipientName ? `Hi ${recipientName},` : 'Hi there,';\n const ordered = orderedSections(sections);\n const year = new Date().getUTCFullYear();\n\n // \u2500\u2500 HTML sections \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sectionsHtml = ordered\n .map(({ name, items }) => {\n const lis = items\n .map(\n (it) =>\n ` <li style=\"margin:0 0 6px 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">${escapeHtml(it)}</li>`,\n )\n .join('\\n');\n return ` <h3 style=\"margin:24px 0 8px 0;font-size:16px;line-height:1.3;font-weight:600;color:${TEXT_PRIMARY};\">${name}</h3>\n <ul style=\"margin:0 0 8px 0;padding-left:20px;\">\n${lis}\n </ul>`;\n })\n .join('\\n');\n\n // \u2500\u2500 HTML \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const html = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${escapeHtml(subject)}</title>\n </head>\n <body style=\"margin:0;padding:0;background:${BG_OUTER};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:${TEXT_PRIMARY};\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"background:${BG_OUTER};padding:32px 16px;\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" width=\"560\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"max-width:560px;background:${BG_CARD};border:1px solid ${BORDER};border-radius:8px;overflow:hidden;\">\n <tr>\n <td style=\"padding:24px 32px 8px 32px;\">\n <a href=\"${escapeHtml(productUrl)}\" style=\"text-decoration:none;color:${ACCENT};font-size:14px;font-weight:600;\">RuleMetric</a>\n </td>\n </tr>\n <tr>\n <td style=\"padding:8px 32px 8px 32px;\">\n <h1 style=\"margin:0 0 8px 0;font-size:22px;line-height:1.3;font-weight:600;color:${TEXT_PRIMARY};\">\n What's new \u2014 ${escapeHtml(formattedDate)}\n </h1>\n <p style=\"margin:0 0 8px 0;font-size:13px;line-height:1.5;color:${TEXT_MUTED};\">\n Release ${escapeHtml(version)}\n </p>\n <p style=\"margin:16px 0 0 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">\n ${escapeHtml(greeting)}\n </p>\n <p style=\"margin:8px 0 0 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">\n Here's what shipped in the latest RuleMetric release.\n </p>\n </td>\n </tr>\n <tr>\n <td style=\"padding:0 32px 16px 32px;\">\n${sectionsHtml}\n </td>\n </tr>\n <tr>\n <td style=\"padding:16px 32px 24px 32px;border-top:1px solid ${BORDER};\">\n <p style=\"margin:0 0 8px 0;font-size:12px;line-height:1.5;color:${TEXT_MUTED};\">\n You're receiving this because you signed up for RuleMetric product updates. If you'd rather not hear about new releases, you can unsubscribe at any time.\n </p>\n <p style=\"margin:0 0 4px 0;font-size:12px;line-height:1.5;\">\n <a href=\"${escapeHtml(unsubscribeUrl)}\" style=\"color:${ACCENT};text-decoration:underline;\">Unsubscribe</a>\n </p>\n <p style=\"margin:0 0 12px 0;font-size:12px;line-height:1.5;color:${TEXT_MUTED};word-break:break-all;\">\n ${escapeHtml(unsubscribeUrl)}\n </p>\n <p style=\"margin:0;font-size:11px;line-height:1.5;color:${TEXT_MUTED};\">\n RuleMetric \u2022 ${year}\n </p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </body>\n</html>`;\n\n // \u2500\u2500 Plain text \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const textLines: string[] = [\n `What's new in RuleMetric \u2014 ${formattedDate}`,\n `Release ${version}`,\n '',\n greeting,\n '',\n `Here's what shipped in the latest RuleMetric release.`,\n '',\n ];\n for (const { name, items } of ordered) {\n textLines.push(`${name}:`);\n for (const it of items) {\n textLines.push(` - ${it}`);\n }\n textLines.push('');\n }\n textLines.push(\n '--',\n `You're receiving this because you signed up for RuleMetric product updates.`,\n `Unsubscribe: ${unsubscribeUrl}`,\n '',\n `RuleMetric \u2022 ${year}`,\n );\n const text = textLines.join('\\n');\n\n return { subject, html, text };\n}\n", "// No-op email provider. Used in dev/test when no real email infrastructure\n// is configured. Logs the destination + subject to stderr so operators can\n// see that a send was requested, then returns a synthetic id. Never throws.\n//\n// This is intentionally the default \u2014 it lets the test suite run without\n// any email environment variables and lets local development work without\n// an email account. Switch to `resend` by setting RESEND_API_KEY, or force\n// noop explicitly with RULEMETRIC_EMAIL_PROVIDER=noop.\n\nimport { randomBytes } from 'node:crypto';\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nexport async function sendNoopEmail(params: SendEmailParams): Promise<SendEmailResult> {\n // Use stderr (same convention as the dev-mode invite log) so it doesn't\n // pollute stdout if a caller is parsing JSON from there.\n const keyNote = params.idempotencyKey ? ` idempotencyKey=${params.idempotencyKey}` : '';\n process.stderr.write(\n `[email:noop] would send to=${params.to} subject=${JSON.stringify(params.subject)}${keyNote}\\n`,\n );\n return {\n id: `noop-${randomBytes(8).toString('hex')}`,\n provider: 'noop',\n };\n}\n", "// Resend provider. Activated when RESEND_API_KEY is set. The Resend SDK is\n// imported lazily so that environments without `resend` installed (or where\n// the dependency hasn't been hoisted yet) don't crash at module-load time \u2014\n// only when a send is actually attempted via this provider.\n//\n// `from` is computed from RESEND_FROM_EMAIL (default: onboarding@resend.dev,\n// which works out of the box with a fresh Resend account for testing).\n\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nlet cachedClient: {\n emails: {\n send: (input: ResendSendInput, options?: ResendSendOptions) => Promise<ResendSendResult>;\n };\n} | null = null;\n\ninterface ResendSendInput {\n from: string;\n to: string | string[];\n subject: string;\n html: string;\n text: string;\n}\n\ninterface ResendSendOptions {\n idempotencyKey?: string;\n}\n\ninterface ResendSendResult {\n data: { id: string } | null;\n error: { message: string; name?: string } | null;\n}\n\nasync function getClient() {\n if (cachedClient) return cachedClient;\n const apiKey = process.env.RESEND_API_KEY;\n if (!apiKey) {\n throw new Error('RESEND_API_KEY is not set');\n }\n // Lazy ESM import. Resend ships ESM-compatible types in its modern releases.\n const { Resend } = (await import('resend')) as {\n Resend: new (key: string) => {\n emails: {\n send: (input: ResendSendInput, options?: ResendSendOptions) => Promise<ResendSendResult>;\n };\n };\n };\n cachedClient = new Resend(apiKey);\n return cachedClient;\n}\n\nexport async function sendResendEmail(\n params: SendEmailParams,\n): Promise<SendEmailResult> {\n const fromName = params.fromName ?? 'RuleMetric';\n const fromEmail = process.env.RESEND_FROM_EMAIL ?? 'onboarding@resend.dev';\n const from = `${fromName} <${fromEmail}>`;\n\n const client = await getClient();\n // Idempotency-Key is a request option in the Resend SDK (not a body field).\n // Resend caches responses keyed on (api_key, idempotency_key) for 24 hours \u2014\n // a duplicate send with the same key returns the original response.\n const options: ResendSendOptions | undefined = params.idempotencyKey\n ? { idempotencyKey: params.idempotencyKey }\n : undefined;\n const result = await client.emails.send(\n {\n from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n },\n options,\n );\n\n if (result.error) {\n throw new Error(`Resend send failed: ${result.error.message}`);\n }\n if (!result.data) {\n throw new Error('Resend send returned no data and no error');\n }\n\n return { id: result.data.id, provider: 'resend' };\n}\n\n// For tests: reset the cached client so a fresh API key is picked up.\nexport function _resetResendClient() {\n cachedClient = null;\n}\n", "// SMTP provider \u2014 stub for now.\n//\n// We don't ship `nodemailer` yet. If you want SMTP-based delivery (e.g.\n// to use Supabase's project-level SMTP config), this is where it goes:\n// add `nodemailer` to package.json, parse SMTP_* env vars (or\n// SUPABASE_SMTP_*), build a transport, and call `transport.sendMail(...)`.\n//\n// Until that's wired, this stub throws \u2014 so selectEmailProvider() never\n// chooses 'smtp' unless a future env-var (`RULEMETRIC_EMAIL_PROVIDER=smtp`)\n// is explicitly set, in which case the caller will get a clear error\n// rather than silent failure.\n\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nexport async function sendSmtpEmail(\n _params: SendEmailParams,\n): Promise<SendEmailResult> {\n throw new Error(\n 'SMTP provider not implemented. Set RESEND_API_KEY to use Resend, or unset RULEMETRIC_EMAIL_PROVIDER to fall back to noop.',\n );\n}\n", "// @rulemetric/email \u2014 small abstraction over a transactional-email provider.\n//\n// At module load we DON'T pick a provider \u2014 we resolve it on the first call\n// to `sendEmail`. This is so tests can flip env vars (RESEND_API_KEY,\n// RULEMETRIC_EMAIL_PROVIDER) between cases and observe different behaviour\n// without juggling module imports.\n//\n// Provider selection (highest to lowest precedence):\n// 1. RULEMETRIC_EMAIL_PROVIDER env var ('resend' | 'smtp' | 'noop') \u2014 explicit.\n// 2. If RESEND_API_KEY is set \u2192 'resend'.\n// 3. Otherwise \u2192 'noop' (logs to stderr, returns synthetic id).\n//\n// `noop` is the default to keep the test suite from needing real email\n// infrastructure. Failures from real providers bubble up \u2014 the caller (e.g.\n// the invitation route) decides whether a delivery failure should fail the\n// request or just be logged.\n\nimport { sendNoopEmail } from './providers/noop.js';\nimport { sendResendEmail } from './providers/resend.js';\nimport { sendSmtpEmail } from './providers/smtp.js';\n\nexport interface SendEmailParams {\n to: string;\n subject: string;\n html: string;\n text: string;\n /** Display name for the From header. Defaults to 'RuleMetric'. */\n fromName?: string;\n /**\n * Provider-side idempotency key. When set, the provider deduplicates\n * concurrent / retried sends with the same key for a provider-defined\n * window (Resend: 24h). Required for safe-retry email pipelines \u2014\n * callers should derive this from a stable per-recipient row id\n * (e.g. `announcement_deliveries.id`), NOT a per-attempt nonce.\n */\n idempotencyKey?: string;\n}\n\nexport type EmailProvider = 'resend' | 'noop' | 'smtp';\n\nexport interface SendEmailResult {\n id: string;\n provider: EmailProvider;\n}\n\n/** Pure function \u2014 exported for testing. Reads `process.env` each call. */\nexport function selectEmailProvider(): EmailProvider {\n const explicit = process.env.RULEMETRIC_EMAIL_PROVIDER;\n if (explicit === 'resend' || explicit === 'smtp' || explicit === 'noop') {\n return explicit;\n }\n if (process.env.RESEND_API_KEY) return 'resend';\n return 'noop';\n}\n\n// Track whether we've logged the active provider yet \u2014 log-once so dev/test\n// stderr doesn't get spammed.\nlet providerLogged = false;\n\nexport async function sendEmail(params: SendEmailParams): Promise<SendEmailResult> {\n const provider = selectEmailProvider();\n if (!providerLogged) {\n providerLogged = true;\n process.stderr.write(`[email] active provider: ${provider}\\n`);\n }\n switch (provider) {\n case 'resend':\n return sendResendEmail(params);\n case 'smtp':\n return sendSmtpEmail(params);\n case 'noop':\n return sendNoopEmail(params);\n }\n}\n\n/** Test helper: reset the provider-logged flag. */\nexport function _resetEmailLogState() {\n providerLogged = false;\n}\n\nexport { renderInvitation } from './templates/invitation.js';\nexport type { InvitationTemplateInput, RenderedEmail } from './templates/invitation.js';\nexport { renderChangelogAnnouncement } from './templates/changelog-announcement.js';\nexport type {\n ChangelogAnnouncementInput,\n ChangelogSectionName,\n} from './templates/changelog-announcement.js';\n"],
5
- "mappings": ";AAwCA,IAAM,SAAS;AACf,IAAM,eAAe;AACrB,IAAM,aAAa;AACnB,IAAM,WAAW;AACjB,IAAM,UAAU;AAChB,IAAM,SAAS;AAGf,IAAM,gBAAwC;EAC5C;EACA;EACA;EACA;EACA;EACA;;AAQF,SAAS,cAAc,KAAW;AAChC,QAAM,SAAS;IACb;IAAW;IAAY;IAAS;IAAS;IAAO;IAChD;IAAQ;IAAU;IAAa;IAAW;IAAY;;AAExD,QAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAG3D,MAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,IAAI;AAAI,WAAO;AAC9C,SAAO,GAAG,OAAO,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;AACpC;AAEA,SAAS,WAAW,GAAS;AAC3B,SAAO,EACJ,QAAQ,MAAM,OAAO,EACrB,QAA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AAM,UAAS;AAI9B,QAAM,UAAyC,OAAO,iBAClD,EAAE,gBAAgB,OAAO,eAAc,IACvC;AACJ,QAAM,SAAS,MAAM,OAAO,OAAO,KACjC;IACE;IACA,IAAI,OAAO;IACX,SAAS,OAAO;IAChB,MAAM,OAAO;IACb,MAAM,OAAO;KAEf,OAAO;AAGT,MAAI,OAAO,OAAO;AAChB,UAAM,IAAI,MAAM,uBAAuB,OAAO,MAAM,OAAO,EAAE;EAC/D;AACA,MAAI,CAAC,OAAO,MAAM;AAChB,UAAM,IAAI,MAAM,2CAA2C;EAC7D;AAEA,SAAO,EAAE,IAAI,OAAO,KAAK,IAAI,UAAU,SAAQ;AACjD;;;ACtEA,eAAsB,cACpB,SAAwB;AAExB,QAAM,IAAI,MACR,2HAA2H;AAE/H;;;AC0BM,SAAU,sBAAmB;AACjC,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,aAAa,YAAY,aAAa,UAAU,aAAa,QAAQ;AACvE,WAAO;EACT;AACA,MAAI,QAAQ,IAAI;AAAgB,WAAO;AACvC,SAAO;AACT;AAIA,IAAI,iBAAiB;AAErB,eAAsB,UAAU,QAAuB;AACrD,QAAM,WAAW,oBAAmB;AACpC,MAAI,CAAC,gBAAgB;AACnB,qBAAiB;AACjB,YAAQ,OAAO,MAAM,4BAA4B,QAAQ;CAAI;EAC/D;AACA,UAAQ,UAAU;IAChB,KAAK;AACH,aAAO,gBAAgB,MAAM;IAC/B,KAAK;AACH,aAAO,cAAc,MAAM;IAC7B,KAAK;AACH,aAAO,cAAc,MAAM;EAC/B;AACF;",
4
+ "sourcesContent": ["// Product-announcement email template. Pure function \u2014 given a parsed\n// CHANGELOG entry, returns subject + html + text. No provider work, no\n// env reads, no IO.\n//\n// Design notes:\n// - Conventions mirror invitation.ts: inline styles only, viewport meta,\n// simple table layout, hand-rolled plain-text body, same colour palette.\n// - Section order is fixed (Added \u2192 Changed \u2192 Fixed \u2192 Removed \u2192\n// Deprecated \u2192 Security) regardless of insertion order in the input,\n// so a single deployment can't produce inconsistent ordering across\n// recipients.\n// - Footer carries the unsubscribe URL twice (styled link + raw text)\n// for CAN-SPAM compliance and because some clients suppress link\n// rendering.\n\nimport type { RenderedEmail } from './invitation.js';\n\nexport type ChangelogSectionName =\n | 'Added'\n | 'Changed'\n | 'Fixed'\n | 'Removed'\n | 'Deprecated'\n | 'Security';\n\nexport interface ChangelogAnnouncementInput {\n /** Verbatim version string from CHANGELOG, e.g. \"2026.06.05\". */\n version: string;\n /** ISO date YYYY-MM-DD. */\n date: string;\n /** Section name \u2192 array of bullet items. Items are plain text (no markdown). */\n sections: Partial<Record<ChangelogSectionName, string[]>>;\n /** Fully-qualified unsubscribe URL embedded in the footer. */\n unsubscribeUrl: string;\n /** Product home URL (e.g. https://rulemetric.com). For the header logo link. */\n productUrl: string;\n /** Optional recipient first name to personalize greeting; falls back to \"Hi there,\". */\n recipientName?: string;\n}\n\nconst ACCENT = '#5b6cff';\nconst TEXT_PRIMARY = '#1a1a1a';\nconst TEXT_MUTED = '#666666';\nconst BG_OUTER = '#f5f5f7';\nconst BG_CARD = '#ffffff';\nconst BORDER = '#e5e5e9';\n\n/** Documented render order for sections \u2014 applied regardless of input key order. */\nconst SECTION_ORDER: ChangelogSectionName[] = [\n 'Added',\n 'Changed',\n 'Fixed',\n 'Removed',\n 'Deprecated',\n 'Security',\n];\n\n/**\n * \"June 5, 2026\" \u2014 locale-independent format identical to invitation.ts.\n * Accepts an ISO YYYY-MM-DD string; parsed as UTC to avoid off-by-one in\n * recipient timezones west of the build server.\n */\nfunction formatIsoDate(iso: string): string {\n const months = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n ];\n const [y, m, d] = iso.split('-').map((s) => parseInt(s, 10));\n // Defensive: if the input is malformed we still want a string. Fall back\n // to the raw ISO so the recipient at least sees something coherent.\n if (!y || !m || !d || m < 1 || m > 12) return iso;\n return `${months[m - 1]} ${d}, ${y}`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/** Returns sections in canonical order, dropping missing/empty ones. */\nfunction orderedSections(\n sections: ChangelogAnnouncementInput['sections'],\n): Array<{ name: ChangelogSectionName; items: string[] }> {\n const out: Array<{ name: ChangelogSectionName; items: string[] }> = [];\n for (const name of SECTION_ORDER) {\n const items = sections[name];\n if (items && items.length > 0) {\n out.push({ name, items });\n }\n }\n return out;\n}\n\nexport function renderChangelogAnnouncement(\n input: ChangelogAnnouncementInput,\n): RenderedEmail {\n const { version, date, sections, unsubscribeUrl, productUrl, recipientName } = input;\n\n const formattedDate = formatIsoDate(date);\n const subject = `What's new in RuleMetric \u2014 ${formattedDate}`;\n const greeting = recipientName ? `Hi ${recipientName},` : 'Hi there,';\n const ordered = orderedSections(sections);\n const year = new Date().getUTCFullYear();\n\n // \u2500\u2500 HTML sections \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const sectionsHtml = ordered\n .map(({ name, items }) => {\n const lis = items\n .map(\n (it) =>\n ` <li style=\"margin:0 0 6px 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">${escapeHtml(it)}</li>`,\n )\n .join('\\n');\n return ` <h3 style=\"margin:24px 0 8px 0;font-size:16px;line-height:1.3;font-weight:600;color:${TEXT_PRIMARY};\">${name}</h3>\n <ul style=\"margin:0 0 8px 0;padding-left:20px;\">\n${lis}\n </ul>`;\n })\n .join('\\n');\n\n // \u2500\u2500 HTML \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const html = `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>${escapeHtml(subject)}</title>\n </head>\n <body style=\"margin:0;padding:0;background:${BG_OUTER};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:${TEXT_PRIMARY};\">\n <table role=\"presentation\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"background:${BG_OUTER};padding:32px 16px;\">\n <tr>\n <td align=\"center\">\n <table role=\"presentation\" width=\"560\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"max-width:560px;background:${BG_CARD};border:1px solid ${BORDER};border-radius:8px;overflow:hidden;\">\n <tr>\n <td style=\"padding:24px 32px 8px 32px;\">\n <a href=\"${escapeHtml(productUrl)}\" style=\"text-decoration:none;color:${ACCENT};font-size:14px;font-weight:600;\">RuleMetric</a>\n </td>\n </tr>\n <tr>\n <td style=\"padding:8px 32px 8px 32px;\">\n <h1 style=\"margin:0 0 8px 0;font-size:22px;line-height:1.3;font-weight:600;color:${TEXT_PRIMARY};\">\n What's new \u2014 ${escapeHtml(formattedDate)}\n </h1>\n <p style=\"margin:0 0 8px 0;font-size:13px;line-height:1.5;color:${TEXT_MUTED};\">\n Release ${escapeHtml(version)}\n </p>\n <p style=\"margin:16px 0 0 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">\n ${escapeHtml(greeting)}\n </p>\n <p style=\"margin:8px 0 0 0;font-size:15px;line-height:1.5;color:${TEXT_PRIMARY};\">\n Here's what shipped in the latest RuleMetric release.\n </p>\n </td>\n </tr>\n <tr>\n <td style=\"padding:0 32px 16px 32px;\">\n${sectionsHtml}\n </td>\n </tr>\n <tr>\n <td style=\"padding:16px 32px 24px 32px;border-top:1px solid ${BORDER};\">\n <p style=\"margin:0 0 8px 0;font-size:12px;line-height:1.5;color:${TEXT_MUTED};\">\n You're receiving this because you signed up for RuleMetric product updates. If you'd rather not hear about new releases, you can unsubscribe at any time.\n </p>\n <p style=\"margin:0 0 4px 0;font-size:12px;line-height:1.5;\">\n <a href=\"${escapeHtml(unsubscribeUrl)}\" style=\"color:${ACCENT};text-decoration:underline;\">Unsubscribe</a>\n </p>\n <p style=\"margin:0 0 12px 0;font-size:12px;line-height:1.5;color:${TEXT_MUTED};word-break:break-all;\">\n ${escapeHtml(unsubscribeUrl)}\n </p>\n <p style=\"margin:0;font-size:11px;line-height:1.5;color:${TEXT_MUTED};\">\n RuleMetric \u2022 ${year}\n </p>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </body>\n</html>`;\n\n // \u2500\u2500 Plain text \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const textLines: string[] = [\n `What's new in RuleMetric \u2014 ${formattedDate}`,\n `Release ${version}`,\n '',\n greeting,\n '',\n `Here's what shipped in the latest RuleMetric release.`,\n '',\n ];\n for (const { name, items } of ordered) {\n textLines.push(`${name}:`);\n for (const it of items) {\n textLines.push(` - ${it}`);\n }\n textLines.push('');\n }\n textLines.push(\n '--',\n `You're receiving this because you signed up for RuleMetric product updates.`,\n `Unsubscribe: ${unsubscribeUrl}`,\n '',\n `RuleMetric \u2022 ${year}`,\n );\n const text = textLines.join('\\n');\n\n return { subject, html, text };\n}\n", "// No-op email provider. Used in dev/test when no real email infrastructure\n// is configured. Logs the destination + subject to stderr so operators can\n// see that a send was requested, then returns a synthetic id. Never throws.\n//\n// This is intentionally the default \u2014 it lets the test suite run without\n// any email environment variables and lets local development work without\n// an email account. Switch to `resend` by setting RESEND_API_KEY, or force\n// noop explicitly with RULEMETRIC_EMAIL_PROVIDER=noop.\n\nimport { randomBytes } from 'node:crypto';\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nexport async function sendNoopEmail(params: SendEmailParams): Promise<SendEmailResult> {\n // Use stderr (same convention as the dev-mode invite log) so it doesn't\n // pollute stdout if a caller is parsing JSON from there.\n const keyNote = params.idempotencyKey ? ` idempotencyKey=${params.idempotencyKey}` : '';\n process.stderr.write(\n `[email:noop] would send to=${params.to} subject=${JSON.stringify(params.subject)}${keyNote}\\n`,\n );\n return {\n id: `noop-${randomBytes(8).toString('hex')}`,\n provider: 'noop',\n };\n}\n", "// Resend provider. Activated when RESEND_API_KEY is set. The Resend SDK is\n// imported lazily so that environments without `resend` installed (or where\n// the dependency hasn't been hoisted yet) don't crash at module-load time \u2014\n// only when a send is actually attempted via this provider.\n//\n// `from` is computed from RESEND_FROM_EMAIL (default: onboarding@resend.dev,\n// which works out of the box with a fresh Resend account for testing).\n\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nlet cachedClient: {\n emails: {\n send: (input: ResendSendInput, options?: ResendSendOptions) => Promise<ResendSendResult>;\n };\n} | null = null;\n\ninterface ResendSendInput {\n from: string;\n to: string | string[];\n subject: string;\n html: string;\n text: string;\n}\n\ninterface ResendSendOptions {\n idempotencyKey?: string;\n}\n\ninterface ResendSendResult {\n data: { id: string } | null;\n error: { message: string; name?: string } | null;\n}\n\nasync function getClient() {\n if (cachedClient) return cachedClient;\n const apiKey = process.env.RESEND_API_KEY;\n if (!apiKey) {\n throw new Error('RESEND_API_KEY is not set');\n }\n // Lazy ESM import. Resend ships ESM-compatible types in its modern releases.\n const { Resend } = (await import('resend')) as {\n Resend: new (key: string) => {\n emails: {\n send: (input: ResendSendInput, options?: ResendSendOptions) => Promise<ResendSendResult>;\n };\n };\n };\n cachedClient = new Resend(apiKey);\n return cachedClient;\n}\n\nexport async function sendResendEmail(\n params: SendEmailParams,\n): Promise<SendEmailResult> {\n const fromName = params.fromName ?? 'RuleMetric';\n const fromEmail = process.env.RESEND_FROM_EMAIL ?? 'onboarding@resend.dev';\n const from = `${fromName} <${fromEmail}>`;\n\n const client = await getClient();\n // Idempotency-Key is a request option in the Resend SDK (not a body field).\n // Resend caches responses keyed on (api_key, idempotency_key) for 24 hours \u2014\n // a duplicate send with the same key returns the original response.\n const options: ResendSendOptions | undefined = params.idempotencyKey\n ? { idempotencyKey: params.idempotencyKey }\n : undefined;\n const result = await client.emails.send(\n {\n from,\n to: params.to,\n subject: params.subject,\n html: params.html,\n text: params.text,\n },\n options,\n );\n\n if (result.error) {\n throw new Error(`Resend send failed: ${result.error.message}`);\n }\n if (!result.data) {\n throw new Error('Resend send returned no data and no error');\n }\n\n return { id: result.data.id, provider: 'resend' };\n}\n\n// For tests: reset the cached client so a fresh API key is picked up.\nexport function _resetResendClient() {\n cachedClient = null;\n}\n", "// SMTP provider \u2014 stub for now.\n//\n// We don't ship `nodemailer` yet. If you want SMTP-based delivery (e.g.\n// to use Supabase's project-level SMTP config), this is where it goes:\n// add `nodemailer` to package.json, parse SMTP_* env vars (or\n// SUPABASE_SMTP_*), build a transport, and call `transport.sendMail(...)`.\n//\n// Until that's wired, this stub throws \u2014 so selectEmailProvider() never\n// chooses 'smtp' unless a future env-var (`RULEMETRIC_EMAIL_PROVIDER=smtp`)\n// is explicitly set, in which case the caller will get a clear error\n// rather than silent failure.\n\nimport type { SendEmailParams, SendEmailResult } from '../index.js';\n\nexport async function sendSmtpEmail(\n _params: SendEmailParams,\n): Promise<SendEmailResult> {\n throw new Error(\n 'SMTP provider not implemented. Set RESEND_API_KEY to use Resend, or unset RULEMETRIC_EMAIL_PROVIDER to fall back to noop.',\n );\n}\n", "// @rulemetric/email \u2014 small abstraction over a transactional-email provider.\n//\n// At module load we DON'T pick a provider \u2014 we resolve it on the first call\n// to `sendEmail`. This is so tests can flip env vars (RESEND_API_KEY,\n// RULEMETRIC_EMAIL_PROVIDER) between cases and observe different behaviour\n// without juggling module imports.\n//\n// Provider selection (highest to lowest precedence):\n// 1. RULEMETRIC_EMAIL_PROVIDER env var ('resend' | 'smtp' | 'noop') \u2014 explicit.\n// 2. If RESEND_API_KEY is set \u2192 'resend'.\n// 3. Otherwise \u2192 'noop' (logs to stderr, returns synthetic id).\n//\n// `noop` is the default to keep the test suite from needing real email\n// infrastructure. Failures from real providers bubble up \u2014 the caller (e.g.\n// the invitation route) decides whether a delivery failure should fail the\n// request or just be logged.\n\nimport { sendNoopEmail } from './providers/noop.js';\nimport { sendResendEmail } from './providers/resend.js';\nimport { sendSmtpEmail } from './providers/smtp.js';\n\nexport interface SendEmailParams {\n to: string;\n subject: string;\n html: string;\n text: string;\n /** Display name for the From header. Defaults to 'RuleMetric'. */\n fromName?: string;\n /**\n * Provider-side idempotency key. When set, the provider deduplicates\n * concurrent / retried sends with the same key for a provider-defined\n * window (Resend: 24h). Required for safe-retry email pipelines \u2014\n * callers should derive this from a stable per-recipient row id\n * (e.g. `announcement_deliveries.id`), NOT a per-attempt nonce.\n */\n idempotencyKey?: string;\n}\n\nexport type EmailProvider = 'resend' | 'noop' | 'smtp';\n\nexport interface SendEmailResult {\n id: string;\n provider: EmailProvider;\n}\n\n/** Pure function \u2014 exported for testing. Reads `process.env` each call. */\nexport function selectEmailProvider(): EmailProvider {\n const explicit = process.env.RULEMETRIC_EMAIL_PROVIDER;\n if (explicit === 'resend' || explicit === 'smtp' || explicit === 'noop') {\n return explicit;\n }\n if (process.env.RESEND_API_KEY) return 'resend';\n return 'noop';\n}\n\n// Reserved TLDs that, per RFC 2606 (.test/.example/.invalid/.localhost +\n// example.com/net/org) and RFC 6761, are guaranteed never to resolve to a real\n// mailbox.\nconst RESERVED_TLDS = new Set(['test', 'example', 'invalid', 'localhost']);\nconst RESERVED_EXAMPLE_DOMAINS = /^example\\.(com|net|org)$/;\n\n/**\n * True when `to` addresses a reserved / structurally-undeliverable domain.\n *\n * Why this exists: our unit + e2e suites mint thousands of `*@rulemetric.test`\n * users. Handing those to a real provider (Resend) produces guaranteed HARD\n * BOUNCES, and a high bounce rate poisons the sending domain's reputation \u2014\n * which pushes legitimate transactional mail (password-reset links, invites)\n * into recipients' spam folders. An env-only guard\n * (`RULEMETRIC_EMAIL_PROVIDER=noop` in test) proved leaky: any runner that\n * forgets it (root vitest, CI with prod-like email secrets) sends for real.\n * This predicate makes the guard env-independent at the `sendEmail` boundary.\n *\n * Pure; exported for testing. Returns `false` for malformed input so the\n * provider remains responsible for address validation.\n */\nexport function isUndeliverableRecipient(to: string): boolean {\n const addr = to.trim().toLowerCase();\n const at = addr.lastIndexOf('@');\n if (at < 0) return false; // malformed \u2014 let the provider validate\n const domain = addr.slice(at + 1);\n if (!domain) return false;\n const tld = domain.slice(domain.lastIndexOf('.') + 1);\n if (RESERVED_TLDS.has(tld)) return true;\n if (RESERVED_EXAMPLE_DOMAINS.test(domain)) return true;\n return false;\n}\n\n// Track whether we've logged the active provider yet \u2014 log-once so dev/test\n// stderr doesn't get spammed.\nlet providerLogged = false;\n\nexport async function sendEmail(params: SendEmailParams): Promise<SendEmailResult> {\n const provider = selectEmailProvider();\n if (!providerLogged) {\n providerLogged = true;\n process.stderr.write(`[email] active provider: ${provider}\\n`);\n }\n switch (provider) {\n case 'resend':\n // Never hand a reserved/undeliverable address to the real provider \u2014 it\n // would hard-bounce and degrade domain reputation. Treat as a no-op\n // success (the address is undeliverable by definition, so callers that\n // only log failures behave identically).\n if (isUndeliverableRecipient(params.to)) {\n process.stderr.write(\n `[email] skipping real send to reserved/undeliverable address ` +\n `${params.to} (RFC 2606/6761) \u2014 routed to noop to protect sender reputation\\n`,\n );\n return sendNoopEmail(params);\n }\n return sendResendEmail(params);\n case 'smtp':\n // When a real SMTP sender is implemented here, apply the same\n // isUndeliverableRecipient() guard before dispatching.\n return sendSmtpEmail(params);\n case 'noop':\n return sendNoopEmail(params);\n }\n}\n\n/** Test helper: reset the provider-logged flag. */\nexport function _resetEmailLogState() {\n providerLogged = false;\n}\n\nexport { renderInvitation } from './templates/invitation.js';\nexport type { InvitationTemplateInput, RenderedEmail } from './templates/invitation.js';\nexport { renderChangelogAnnouncement } from './templates/changelog-announcement.js';\nexport type {\n ChangelogAnnouncementInput,\n ChangelogSectionName,\n} from './templates/changelog-announcement.js';\n"],
5
+ "mappings": ";AAwCA,IAAM,SAAS;AACf,IAAM,eAAe;AACrB,IAAM,aAAa;AACnB,IAAM,WAAW;AACjB,IAAM,UAAU;AAChB,IAAM,SAAS;AAGf,IAAM,gBAAwC;EAC5C;EACA;EACA;EACA;EACA;EACA;;AAQF,SAAS,cAAc,KAAW;AAChC,QAAM,SAAS;IACb;IAAW;IAAY;IAAS;IAAS;IAAO;IAChD;IAAQ;IAAU;IAAa;IAAW;IAAY;;AAExD,QAAM,CAAC,GAAG,GAAG,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAG3D,MAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,IAAI,KAAK,IAAI;AAAI,WAAO;AAC9C,SAAO,GAAG,OAAO,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;AACpC;AAEA,SAAS,WAAW,GAAS;AAC3B,SAAO,EACJ,QAAQ,MAAM,OAAO,EACrB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,MAAM,EACpB,QAAQ,MAAM,QAAQ,EACtB,QAAQ,MAAM,OAAO;AAC1B;AAGA,SAAS,gBACP,UAAgD;AAEhD,QA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AAG;AACvC,gBAAQ,OAAO,MACb,gEACK,OAAO,EAAE;CAAkE;AAElF,eAAO,cAAc,MAAM;MAC7B;AACA,aAAO,gBAAgB,MAAM;IAC/B,KAAK;AAGH,aAAO,cAAc,MAAM;IAC7B,KAAK;AACH,aAAO,cAAc,MAAM;EAC/B;AACF;",
6
6
  "names": []
7
7
  }
@@ -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
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AI,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,6 +1,6 @@
1
1
  import {
2
2
  ensureWorktree
3
- } from "./chunk-PIOVE3TN.js";
3
+ } from "./chunk-FUS5C4SB.js";
4
4
  import {
5
5
  PermanentJobError
6
6
  } from "./chunk-DGHWRQXL.js";
@@ -39,7 +39,7 @@ async function processLaunch(payload, helpers) {
39
39
  log(`Worktree resolved: ${config.projectPath} (branch ${config.gitBranch})`);
40
40
  }
41
41
  log(`Launching ${tool}...`);
42
- const { getLauncher } = await import("./dist-I6BCOLNG.js");
42
+ const { getLauncher } = await import("./dist-NEECHU47.js");
43
43
  const launcher = getLauncher(tool);
44
44
  const launcherResult = await launcher.launch(config);
45
45
  log(`Launch completed: sessionId=${launcherResult.sessionId}`);
@@ -58,4 +58,4 @@ export {
58
58
  resolveWorktreeForLaunch,
59
59
  processLaunch
60
60
  };
61
- //# sourceMappingURL=chunk-ELL34R3K.js.map
61
+ //# sourceMappingURL=chunk-XMWHTOCC.js.map
@@ -5,7 +5,7 @@ import {
5
5
  getDb,
6
6
  sessionEvents,
7
7
  sessions
8
- } from "./chunk-4A7FKR2O.js";
8
+ } from "./chunk-42A3HEEH.js";
9
9
 
10
10
  // src/lib/handlers/process-session-goal.ts
11
11
  import { eq, asc, sql } from "drizzle-orm";
@@ -52,4 +52,4 @@ async function processSessionGoal(payload, deps = {}) {
52
52
  export {
53
53
  processSessionGoal
54
54
  };
55
- //# sourceMappingURL=chunk-3IU7GFXS.js.map
55
+ //# sourceMappingURL=chunk-YEBBX4HQ.js.map