@rulemetric/cli 0.5.4 → 0.6.1

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 (59) hide show
  1. package/dist/chunk-3AEVHOTS.js +33 -0
  2. package/dist/chunk-3AEVHOTS.js.map +7 -0
  3. package/dist/{chunk-WLFX4PYR.js → chunk-6TPJGYFF.js} +4 -4
  4. package/dist/{chunk-4LHEN2FS.js → chunk-CVMRMSV4.js} +14 -14
  5. package/dist/{chunk-ANOWI23I.js → chunk-HWGRTIXN.js} +98 -105
  6. package/dist/chunk-HWGRTIXN.js.map +7 -0
  7. package/dist/{chunk-H3C6EGR2.js → chunk-MUOUV5LY.js} +4 -4
  8. package/dist/{chunk-JNFIYBFL.js → chunk-N2X35ITW.js} +7 -1
  9. package/dist/{chunk-JNFIYBFL.js.map → chunk-N2X35ITW.js.map} +2 -2
  10. package/dist/{chunk-FTJRMUID.js → chunk-OVGP4OGK.js} +25 -1
  11. package/dist/chunk-OVGP4OGK.js.map +7 -0
  12. package/dist/{chunk-7K4ILWS7.js → chunk-UPXIO7CG.js} +4 -4
  13. package/dist/{chunk-IATQXFJA.js → chunk-VBGUNFKY.js} +4 -4
  14. package/dist/{chunk-BCIUSUEV.js → chunk-VIYUIQHW.js} +4 -4
  15. package/dist/{chunk-LTT2YMYY.js → chunk-YDTUPCBL.js} +94 -21
  16. package/dist/chunk-YDTUPCBL.js.map +7 -0
  17. package/dist/commands/auth/login.js +19 -1
  18. package/dist/commands/auth/login.js.map +2 -2
  19. package/dist/commands/auth/signup.js +81 -0
  20. package/dist/commands/auth/signup.js.map +7 -0
  21. package/dist/commands/evals/agent.js +10 -10
  22. package/dist/commands/gateway/ensure.js +1 -1
  23. package/dist/commands/hooks/install.js +92 -53
  24. package/dist/commands/hooks/install.js.map +2 -2
  25. package/dist/commands/hooks/run.js +5 -3
  26. package/dist/commands/hooks/run.js.map +2 -2
  27. package/dist/commands/hooks/uninstall.js +53 -7
  28. package/dist/commands/hooks/uninstall.js.map +2 -2
  29. package/dist/commands/proxy/env.js +1 -1
  30. package/dist/commands/proxy/status.js +1 -1
  31. package/dist/commands/service/install.js +8 -2
  32. package/dist/commands/service/install.js.map +2 -2
  33. package/dist/commands/setup.js +6 -6
  34. package/dist/commands/setup.js.map +2 -2
  35. package/dist/dashboard/Dashboard.js +11 -11
  36. package/dist/dashboard/launcher/LauncherOverlay.js +3 -3
  37. package/dist/lib/agent-loop.js +10 -10
  38. package/dist/lib/ensure-api-key.js +10 -0
  39. package/dist/lib/ensure-api-key.js.map +7 -0
  40. package/dist/lib/gateway-lifecycle.js +7 -3
  41. package/dist/lib/handlers/cron-suggest-instructions.js +2 -2
  42. package/dist/lib/handlers/process-announcement.js +2 -2
  43. package/dist/lib/handlers/process-run-cleanup.js +2 -2
  44. package/dist/lib/handlers/process-session-goal.js +2 -2
  45. package/dist/lib/hooks-config.js +7 -1
  46. package/dist/lib/manual-tasks.js +2 -2
  47. package/dist/lib/setup-steps.js +7 -3
  48. package/dist/lib/statusline-shim.js +3 -1
  49. package/oclif.manifest.json +52 -1
  50. package/package.json +6 -6
  51. package/dist/chunk-ANOWI23I.js.map +0 -7
  52. package/dist/chunk-FTJRMUID.js.map +0 -7
  53. package/dist/chunk-LTT2YMYY.js.map +0 -7
  54. /package/dist/{chunk-WLFX4PYR.js.map → chunk-6TPJGYFF.js.map} +0 -0
  55. /package/dist/{chunk-4LHEN2FS.js.map → chunk-CVMRMSV4.js.map} +0 -0
  56. /package/dist/{chunk-H3C6EGR2.js.map → chunk-MUOUV5LY.js.map} +0 -0
  57. /package/dist/{chunk-7K4ILWS7.js.map → chunk-UPXIO7CG.js.map} +0 -0
  58. /package/dist/{chunk-IATQXFJA.js.map → chunk-VBGUNFKY.js.map} +0 -0
  59. /package/dist/{chunk-BCIUSUEV.js.map → chunk-VIYUIQHW.js.map} +0 -0
@@ -0,0 +1,81 @@
1
+ import {
2
+ ensureDeviceApiKey
3
+ } from "../../chunk-3AEVHOTS.js";
4
+ import {
5
+ BaseCommand
6
+ } from "../../chunk-SZ7VDCD6.js";
7
+ import "../../chunk-R56PH7YE.js";
8
+ import {
9
+ bootstrapActiveOrg
10
+ } from "../../chunk-SLL3OBKN.js";
11
+ import "../../chunk-EKJ2CABV.js";
12
+ import {
13
+ ApiError,
14
+ apiPost
15
+ } from "../../chunk-ZRLYHBPN.js";
16
+ import {
17
+ saveEnvFile,
18
+ saveToken
19
+ } from "../../chunk-W2YERO7E.js";
20
+ import "../../chunk-NSBPE2FW.js";
21
+
22
+ // src/commands/auth/signup.ts
23
+ import { Flags } from "@oclif/core";
24
+ var AuthSignup = class _AuthSignup extends BaseCommand {
25
+ static description = "Create a RuleMetric account from the CLI";
26
+ static examples = [
27
+ "<%= config.bin %> auth signup",
28
+ "<%= config.bin %> auth signup -e user@example.com"
29
+ ];
30
+ static flags = {
31
+ email: Flags.string({ char: "e", description: "Email address" }),
32
+ password: Flags.string({ char: "p", description: "Password (min 8 chars; for non-interactive use)" })
33
+ };
34
+ async run() {
35
+ const { flags } = await this.parse(_AuthSignup);
36
+ let email = flags.email;
37
+ let password = flags.password;
38
+ if (!email || !password) {
39
+ if (!process.stdin.isTTY) {
40
+ this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.");
41
+ }
42
+ const { input, password: passwordPrompt } = await import("@inquirer/prompts");
43
+ if (!email) {
44
+ email = await input({ message: "Email:" });
45
+ }
46
+ if (!password) {
47
+ password = await passwordPrompt({ message: "Password (min 8 chars):" });
48
+ }
49
+ }
50
+ let data;
51
+ try {
52
+ data = await apiPost("/auth/signup", { email, password });
53
+ } catch (err) {
54
+ if (err instanceof ApiError && err.statusCode === 409) {
55
+ this.error(`An account with ${email} already exists. Run: rulemetric auth login -e ${email}`);
56
+ }
57
+ throw err;
58
+ }
59
+ if (data.confirmationRequired || !data.accessToken || !data.refreshToken) {
60
+ this.log(`Account created for ${data.email}.`);
61
+ this.log("Check your email and click the confirmation link, then run:");
62
+ this.log(` rulemetric auth login -e ${data.email}`);
63
+ return;
64
+ }
65
+ const expiresAt = data.expiresAt ?? new Date(Date.now() + 3600 * 1e3).toISOString();
66
+ saveToken({
67
+ accessToken: data.accessToken,
68
+ refreshToken: data.refreshToken,
69
+ expiresAt,
70
+ email: data.email
71
+ });
72
+ saveEnvFile(data.accessToken, process.env.RULEMETRIC_API_URL);
73
+ await bootstrapActiveOrg();
74
+ await ensureDeviceApiKey(this.log.bind(this), this.warn.bind(this));
75
+ this.log(`Signed up and logged in as ${data.email}`);
76
+ }
77
+ };
78
+ export {
79
+ AuthSignup as default
80
+ };
81
+ //# sourceMappingURL=signup.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/commands/auth/signup.ts"],
4
+ "sourcesContent": ["import { Flags } from '@oclif/core';\nimport { BaseCommand } from '../../base-command.js';\nimport { saveToken, saveEnvFile } from '../../lib/auth.js';\nimport { apiPost, ApiError } from '../../lib/api-client.js';\nimport { bootstrapActiveOrg } from '../../lib/active-org-refresh.js';\nimport { ensureDeviceApiKey } from '../../lib/ensure-api-key.js';\n\ninterface SignupResponse {\n confirmationRequired: boolean;\n accessToken?: string;\n refreshToken?: string;\n expiresAt?: string | null;\n email: string;\n}\n\nexport default class AuthSignup extends BaseCommand {\n static override description = 'Create a RuleMetric account from the CLI';\n\n static override examples = [\n '<%= config.bin %> auth signup',\n '<%= config.bin %> auth signup -e user@example.com',\n ];\n\n static override flags = {\n email: Flags.string({ char: 'e', description: 'Email address' }),\n password: Flags.string({ char: 'p', description: 'Password (min 8 chars; for non-interactive use)' }),\n };\n\n async run(): Promise<void> {\n const { flags } = await this.parse(AuthSignup);\n\n let email = flags.email;\n let password = flags.password;\n\n if (!email || !password) {\n // Interactive prompts hang forever with no output in a non-TTY (CI, SSH\n // pipe, an agent driving the CLI). Fail fast with actionable guidance.\n if (!process.stdin.isTTY) {\n this.error('Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.');\n }\n const { input, password: passwordPrompt } = await import('@inquirer/prompts');\n\n if (!email) {\n email = await input({ message: 'Email:' });\n }\n if (!password) {\n password = await passwordPrompt({ message: 'Password (min 8 chars):' });\n }\n }\n\n let data: SignupResponse;\n try {\n data = await apiPost<SignupResponse>('/auth/signup', { email, password });\n } catch (err) {\n // 409 = the email is already registered \u2014 steer to login, not a retry loop.\n if (err instanceof ApiError && err.statusCode === 409) {\n this.error(`An account with ${email} already exists. Run: rulemetric auth login -e ${email}`);\n }\n throw err;\n }\n\n // Email confirmation is ON: no session yet. Tell the user exactly what to do\n // next instead of leaving them at a dead end.\n if (data.confirmationRequired || !data.accessToken || !data.refreshToken) {\n this.log(`Account created for ${data.email}.`);\n this.log('Check your email and click the confirmation link, then run:');\n this.log(` rulemetric auth login -e ${data.email}`);\n return;\n }\n\n // Confirmation OFF: a session came back \u2014 log in immediately.\n const expiresAt = data.expiresAt ?? new Date(Date.now() + 3600 * 1000).toISOString();\n saveToken({\n accessToken: data.accessToken,\n refreshToken: data.refreshToken,\n expiresAt,\n email: data.email,\n });\n saveEnvFile(data.accessToken, process.env.RULEMETRIC_API_URL);\n\n await bootstrapActiveOrg();\n await ensureDeviceApiKey(this.log.bind(this), this.warn.bind(this));\n\n this.log(`Signed up and logged in as ${data.email}`);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAetB,IAAqB,aAArB,MAAqB,oBAAmB,YAAY;AAAA,EAClD,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,OAAO,MAAM,OAAO,EAAE,MAAM,KAAK,aAAa,gBAAgB,CAAC;AAAA,IAC/D,UAAU,MAAM,OAAO,EAAE,MAAM,KAAK,aAAa,kDAAkD,CAAC;AAAA,EACtG;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,KAAK,MAAM,W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E;AAAA,EACrD;AACF;",
6
+ "names": []
7
+ }
@@ -1,26 +1,26 @@
1
1
  import {
2
2
  runAgentLoop
3
- } from "../../chunk-4LHEN2FS.js";
3
+ } from "../../chunk-CVMRMSV4.js";
4
4
  import "../../chunk-JEJ3J5J6.js";
5
+ import "../../chunk-RCMXTLQF.js";
6
+ import "../../chunk-N5A2IQAK.js";
5
7
  import "../../chunk-OTOWLUOJ.js";
6
- import "../../chunk-WLFX4PYR.js";
8
+ import "../../chunk-6TPJGYFF.js";
7
9
  import "../../chunk-Y4BJXXYV.js";
8
10
  import "../../chunk-W53GKIZQ.js";
9
- import "../../chunk-H3C6EGR2.js";
11
+ import "../../chunk-MUOUV5LY.js";
12
+ import "../../chunk-XZXS2W24.js";
10
13
  import "../../chunk-RQ2TMLKG.js";
11
- import "../../chunk-IATQXFJA.js";
12
- import "../../chunk-BCIUSUEV.js";
14
+ import "../../chunk-VBGUNFKY.js";
15
+ import "../../chunk-FZKLLNDS.js";
16
+ import "../../chunk-VIYUIQHW.js";
17
+ import "../../chunk-DGHWRQXL.js";
13
18
  import "../../chunk-E3BIT53W.js";
14
19
  import "../../chunk-QSN77T7C.js";
15
20
  import {
16
21
  closeDb
17
22
  } from "../../chunk-QNSVCSHG.js";
18
23
  import "../../chunk-3POYC5NA.js";
19
- import "../../chunk-RCMXTLQF.js";
20
- import "../../chunk-N5A2IQAK.js";
21
- import "../../chunk-XZXS2W24.js";
22
- import "../../chunk-FZKLLNDS.js";
23
- import "../../chunk-DGHWRQXL.js";
24
24
  import "../../chunk-DR5WLIOU.js";
25
25
  import "../../chunk-J7N3DLH6.js";
26
26
  import "../../chunk-52WIYRZH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  isGatewayRunning,
3
3
  spawnGateway
4
- } from "../../chunk-FTJRMUID.js";
4
+ } from "../../chunk-OVGP4OGK.js";
5
5
  import {
6
6
  BaseCommand
7
7
  } from "../../chunk-SZ7VDCD6.js";
@@ -1,18 +1,20 @@
1
+ import {
2
+ detectTmux
3
+ } from "../../chunk-BO76WKJR.js";
1
4
  import {
2
5
  STATUSLINE_SETTINGS_VALUE,
3
6
  isStatuslineShimInstalled,
4
7
  readCurrentStatusLine,
5
8
  writeStatuslineShim
6
- } from "../../chunk-JNFIYBFL.js";
7
- import {
8
- detectTmux
9
- } from "../../chunk-BO76WKJR.js";
9
+ } from "../../chunk-N2X35ITW.js";
10
10
  import {
11
11
  installMacOSProxyEnv,
12
12
  mergeClaudeCodeHooks,
13
+ readClaudeSettings,
13
14
  removeClaudeCodeHooks,
14
15
  writeAntigravityHooks,
15
16
  writeAntigravityUserHooks,
17
+ writeClaudeSettingsWithBackup,
16
18
  writeCopilotHooks,
17
19
  writeCursorHooks,
18
20
  writeCursorProxyConfig,
@@ -20,13 +22,14 @@ import {
20
22
  writeCursorUserProxyConfig,
21
23
  writeVSCodeProxyConfig,
22
24
  writeVSCodeUserProxyConfig
23
- } from "../../chunk-ANOWI23I.js";
24
- import "../../chunk-KRBQLMOP.js";
25
+ } from "../../chunk-HWGRTIXN.js";
25
26
  import {
26
27
  GATEWAY_PORT,
27
28
  isGatewayRunning,
28
- spawnGateway
29
- } from "../../chunk-FTJRMUID.js";
29
+ spawnGateway,
30
+ waitForGatewayListening
31
+ } from "../../chunk-OVGP4OGK.js";
32
+ import "../../chunk-KRBQLMOP.js";
30
33
  import {
31
34
  BaseCommand
32
35
  } from "../../chunk-SZ7VDCD6.js";
@@ -42,9 +45,19 @@ import "../../chunk-NSBPE2FW.js";
42
45
  // src/commands/hooks/install.ts
43
46
  import { Flags } from "@oclif/core";
44
47
  import { execFileSync, execSync, spawnSync } from "node:child_process";
45
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
48
+ import { existsSync } from "node:fs";
46
49
  import { homedir } from "node:os";
47
- import { join } from "node:path";
50
+ import { join, dirname } from "node:path";
51
+ function resolveHookBinDir() {
52
+ try {
53
+ const out = execFileSync("/bin/sh", ["-c", "command -v rulemetric"], {
54
+ encoding: "utf-8"
55
+ }).trim();
56
+ if (out && existsSync(out)) return dirname(out);
57
+ } catch {
58
+ }
59
+ return void 0;
60
+ }
48
61
  function isGatewayLaunchdManaged() {
49
62
  try {
50
63
  execFileSync("launchctl", ["list", "com.rulemetric.gateway"], {
@@ -88,15 +101,17 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
88
101
  const configDir = join(projectPath, ".claude");
89
102
  const configPath = join(configDir, "settings.json");
90
103
  const noProxy = flags["no-proxy"];
104
+ let proxyActive = false;
91
105
  if (isGlobal) {
92
106
  this.log(`Installing hooks globally \u2192 ${configPath}`);
93
107
  }
94
- let settings = {};
95
- if (existsSync(configPath)) {
96
- settings = JSON.parse(readFileSync(configPath, "utf-8"));
108
+ const { settings, recoveredBackup } = readClaudeSettings(configPath);
109
+ if (recoveredBackup) {
110
+ this.log(`[!!] ${configPath} was not valid JSON \u2014 backed it up to ${recoveredBackup} and continued with a fresh file.`);
97
111
  }
98
112
  const refreshedHooks = removeClaudeCodeHooks(settings);
99
- mergeClaudeCodeHooks(settings);
113
+ const hookBinDir = resolveHookBinDir();
114
+ mergeClaudeCodeHooks(settings, hookBinDir);
100
115
  this.log(
101
116
  refreshedHooks ? "[OK] Refreshed RuleMetric Claude Code session hooks \u2192 .claude/settings.json" : "[OK] Installed RuleMetric Claude Code session hooks \u2192 .claude/settings.json"
102
117
  );
@@ -129,10 +144,12 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
129
144
  } else {
130
145
  this.log("[OK] CA certificate found");
131
146
  }
132
- if (existsSync(CERT_PATH) && !this.isCACertTrusted()) {
147
+ const caGenerated = existsSync(CERT_PATH);
148
+ let caTrusted = false;
149
+ if (caGenerated && !this.isCACertTrusted()) {
133
150
  this.log("[..] Installing CA certificate into system trust store (requires admin)...");
134
- const trusted = this.trustCACert();
135
- if (trusted) {
151
+ caTrusted = this.trustCACert();
152
+ if (caTrusted) {
136
153
  this.log("[OK] CA certificate trusted by system");
137
154
  } else {
138
155
  this.log("[!!] Could not install CA cert automatically.");
@@ -142,36 +159,9 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
142
159
  this.log(` Run manually: sudo cp ${CERT_PATH} /usr/local/share/ca-certificates/mitmproxy-ca.crt && sudo update-ca-certificates`);
143
160
  }
144
161
  }
145
- } else if (existsSync(CERT_PATH)) {
162
+ } else if (caGenerated) {
146
163
  this.log("[OK] CA certificate already trusted");
147
- }
148
- const env = settings.env ?? {};
149
- env.HTTPS_PROXY = `http://localhost:${GATEWAY_PORT}`;
150
- env.NO_PROXY = "localhost,127.0.0.1,*.supabase.co,*.supabase.in";
151
- if (existsSync(CERT_PATH)) {
152
- env.NODE_EXTRA_CA_CERTS = CERT_PATH;
153
- }
154
- settings.env = env;
155
- this.log(`[OK] HTTPS_PROXY set to gateway on :${GATEWAY_PORT} (permanent)`);
156
- const cursorProxy = writeCursorProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);
157
- if (cursorProxy) {
158
- this.log("[OK] Cursor proxy configured \u2192 .cursor/settings.json");
159
- }
160
- const vscodeProxy = writeVSCodeProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);
161
- if (vscodeProxy) {
162
- this.log("[OK] VS Code workspace proxy configured \u2192 .vscode/settings.json");
163
- }
164
- const vscodeUserProxy = writeVSCodeUserProxyConfig(GATEWAY_PORT);
165
- if (vscodeUserProxy) {
166
- this.log("[OK] VS Code user proxy configured \u2192 ~/Library/Application Support/Code/User/settings.json");
167
- }
168
- const cursorUserProxy = writeCursorUserProxyConfig(GATEWAY_PORT);
169
- if (cursorUserProxy) {
170
- this.log("[OK] Cursor user proxy configured \u2192 ~/Library/Application Support/Cursor/User/settings.json");
171
- }
172
- const macProxy = installMacOSProxyEnv(GATEWAY_PORT, CERT_PATH);
173
- if (macProxy) {
174
- this.log("[OK] HTTPS_PROXY set for GUI apps (launchctl + LaunchAgent)");
164
+ caTrusted = true;
175
165
  }
176
166
  if (isGatewayLaunchdManaged()) {
177
167
  this.log("[OK] Gateway managed by launchd (com.rulemetric.gateway)");
@@ -183,16 +173,59 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
183
173
  this.log(`[OK] Gateway started (PID ${pid})`);
184
174
  } catch (err) {
185
175
  this.log(`[!!] Could not start gateway: ${err.message}`);
186
- this.log(" The session-start hook will auto-start it on next Claude Code session.");
176
+ }
177
+ }
178
+ const gatewayLive = await waitForGatewayListening(GATEWAY_PORT, { timeoutMs: 4e3 });
179
+ if (!caGenerated) {
180
+ this.log("[!!] No CA certificate \u2014 NOT setting HTTPS_PROXY (capture stays hooks-only).");
181
+ this.log(" Install mitmproxy, then re-run: rulemetric hooks install");
182
+ } else if (!gatewayLive) {
183
+ this.log(`[!!] Gateway is not answering on :${GATEWAY_PORT} \u2014 NOT setting HTTPS_PROXY.`);
184
+ this.log(" Capture still works via hooks. To enable deep (proxy) capture later:");
185
+ this.log(" rulemetric proxy start && rulemetric hooks install");
186
+ } else {
187
+ const env = settings.env ?? {};
188
+ env.HTTPS_PROXY = `http://localhost:${GATEWAY_PORT}`;
189
+ env.NO_PROXY = "localhost,127.0.0.1,*.supabase.co,*.supabase.in";
190
+ if (existsSync(CERT_PATH)) {
191
+ env.NODE_EXTRA_CA_CERTS = CERT_PATH;
192
+ }
193
+ settings.env = env;
194
+ proxyActive = true;
195
+ this.log(`[OK] HTTPS_PROXY set to gateway on :${GATEWAY_PORT} (verified live)`);
196
+ const cursorProxy = writeCursorProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);
197
+ if (cursorProxy) {
198
+ this.log("[OK] Cursor proxy configured \u2192 .cursor/settings.json");
199
+ }
200
+ const vscodeProxy = writeVSCodeProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);
201
+ if (vscodeProxy) {
202
+ this.log("[OK] VS Code workspace proxy configured \u2192 .vscode/settings.json");
203
+ }
204
+ const vscodeUserProxy = writeVSCodeUserProxyConfig(GATEWAY_PORT);
205
+ if (vscodeUserProxy) {
206
+ this.log("[OK] VS Code user proxy configured \u2192 ~/Library/Application Support/Code/User/settings.json");
207
+ }
208
+ const cursorUserProxy = writeCursorUserProxyConfig(GATEWAY_PORT);
209
+ if (cursorUserProxy) {
210
+ this.log("[OK] Cursor user proxy configured \u2192 ~/Library/Application Support/Cursor/User/settings.json");
211
+ }
212
+ if (caTrusted) {
213
+ const macProxy = installMacOSProxyEnv(GATEWAY_PORT, CERT_PATH);
214
+ if (macProxy) {
215
+ this.log("[OK] HTTPS_PROXY set for GUI apps (launchctl + LaunchAgent)");
216
+ }
217
+ } else {
218
+ this.log("[!!] CA not trusted \u2014 skipping machine-wide GUI proxy (would break native-app TLS).");
219
+ this.log(" Claude Code capture is unaffected. Trust the CA + re-run to enable cross-app capture.");
187
220
  }
188
221
  }
189
222
  }
190
223
  if (!isGlobal) {
191
- const cursorHooks = writeCursorHooks(projectPath);
224
+ const cursorHooks = writeCursorHooks(projectPath, hookBinDir);
192
225
  if (cursorHooks) {
193
226
  this.log(`[OK] Cursor hooks configured \u2192 ${cursorHooks}`);
194
227
  }
195
- const copilotHooks = writeCopilotHooks(projectPath);
228
+ const copilotHooks = writeCopilotHooks(projectPath, hookBinDir);
196
229
  if (copilotHooks) {
197
230
  this.log(`[OK] Copilot Agent hooks configured \u2192 ${copilotHooks}`);
198
231
  }
@@ -205,7 +238,7 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
205
238
  if (antigravityUserHooks) {
206
239
  this.log(`[OK] Antigravity user hooks configured \u2192 ${antigravityUserHooks}`);
207
240
  }
208
- const cursorUserHooks = writeCursorUserHooks();
241
+ const cursorUserHooks = writeCursorUserHooks(hookBinDir);
209
242
  if (cursorUserHooks) {
210
243
  this.log(`[OK] Cursor user hooks configured \u2192 ${cursorUserHooks}`);
211
244
  }
@@ -224,8 +257,10 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
224
257
  this.log(" Rate-limit rings will now update on Claude Code's statusline refresh cadence");
225
258
  }
226
259
  }
227
- mkdirSync(configDir, { recursive: true });
228
- writeFileSync(configPath, JSON.stringify(settings, null, 2) + "\n");
260
+ const { backupPath } = writeClaudeSettingsWithBackup(configPath, settings);
261
+ if (backupPath) {
262
+ this.log(`[OK] Backed up previous settings \u2192 ${backupPath}`);
263
+ }
229
264
  this.log("");
230
265
  this.log("Setup complete! Next steps:");
231
266
  if (isGlobal) {
@@ -235,7 +270,11 @@ var HooksInstall = class _HooksInstall extends BaseCommand {
235
270
  this.log("The API service starts on login and restarts on crash.");
236
271
  } else if (!noProxy) {
237
272
  this.log(" 1. Start Claude Code \u2014 sessions are captured by hooks immediately");
238
- this.log(" 2. Start the capture proxy for full depth: rulemetric proxy start");
273
+ if (proxyActive) {
274
+ this.log(" 2. Full-depth capture is ON \u2014 the proxy is live on :" + GATEWAY_PORT + ".");
275
+ } else {
276
+ this.log(" 2. Enable full depth (proxy not yet live): rulemetric proxy start");
277
+ }
239
278
  this.log("");
240
279
  this.log("Hooks capture every session (lifecycle + transcript). The proxy adds the");
241
280
  this.log("rendered system prompt (instruction-effectiveness linking) + cross-tool capture.");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/commands/hooks/install.ts"],
4
- "sourcesContent": ["import { Flags } from '@oclif/core';\nimport { execFileSync, execSync, spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { BaseCommand } from '../../base-command.js';\nimport { isGatewayRunning, spawnGateway, GATEWAY_PORT } from '../../lib/gateway-lifecycle.js';\n\n// True iff `rulemetric service install` has wired the gateway up as a launchd\n// agent. When this returns true, hooks install must NOT spawn its own\n// detached gateway \u2014 two processes fighting for :8787 means one crash-loops\n// and Claude Code's HTTPS_PROXY breaks.\nfunction isGatewayLaunchdManaged(): boolean {\n try {\n execFileSync('launchctl', ['list', 'com.rulemetric.gateway'], {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return true;\n } catch {\n // Non-zero exit = label not loaded\n return false;\n }\n}\nimport {\n writeStatuslineShim,\n readCurrentStatusLine,\n isStatuslineShimInstalled,\n STATUSLINE_SETTINGS_VALUE,\n} from '../../lib/statusline-shim.js';\nimport {\n mergeClaudeCodeHooks,\n removeClaudeCodeHooks,\n writeCursorProxyConfig,\n writeCursorUserProxyConfig,\n writeVSCodeProxyConfig,\n installMacOSProxyEnv,\n writeVSCodeUserProxyConfig,\n writeCursorHooks,\n writeCursorUserHooks,\n writeCopilotHooks,\n writeAntigravityHooks,\n writeAntigravityUserHooks,\n} from '../../lib/hooks-config.js';\nimport { bootstrapActiveOrg } from '../../lib/active-org-refresh.js';\nimport { detectTmux } from '../../lib/detect-tmux.js';\n\nconst CERT_PATH = join(homedir(), '.mitmproxy', 'mitmproxy-ca-cert.pem');\n\nexport default class HooksInstall extends BaseCommand {\n static override description = 'Install session tracking hooks and context capture proxy for Claude Code';\n\n static override examples = [\n '<%= config.bin %> hooks install',\n '<%= config.bin %> hooks install --global',\n '<%= config.bin %> hooks install --no-proxy',\n ];\n\n static override flags = {\n 'no-proxy': Flags.boolean({\n default: false,\n description: 'Skip proxy/gateway configuration (hooks only)',\n }),\n 'project-dir': Flags.string({\n description: 'Project directory to install hooks in (defaults to cwd)',\n }),\n global: Flags.boolean({\n char: 'g',\n default: false,\n description: 'Install hooks globally (~/.claude/settings.json) so all projects are tracked',\n }),\n 'statusline-usage': Flags.boolean({\n default: false,\n description: 'Install the statusline shim so Claude Code pushes live rate_limits on every refresh (makes /usage rings update in real time without needing the proxy)',\n }),\n };\n\n async run(): Promise<void> {\n const { flags } = await this.parse(HooksInstall);\n const isGlobal = flags.global;\n const projectPath = isGlobal ? homedir() : (flags['project-dir'] ?? process.cwd());\n const configDir = join(projectPath, '.claude');\n const configPath = join(configDir, 'settings.json');\n const noProxy = flags['no-proxy'];\n\n if (isGlobal) {\n this.log(`Installing hooks globally \u2192 ${configPath}`);\n }\n\n // Read or create .claude/settings.json\n let settings: Record<string, unknown> = {};\n if (existsSync(configPath)) {\n settings = JSON.parse(readFileSync(configPath, 'utf-8'));\n }\n\n // \u2500\u2500 1. Install Claude Code session-tracking hooks (hooks-first, zero-proxy\n // capture). Strip any stale rulemetric entries first \u2014 handles old command\n // formats, preserves the user's own hooks \u2014 then merge the current canonical\n // set. Runs regardless of --no-proxy: this is the whole point of the hooks\n // path, which captures full sessions (lifecycle + SessionEnd transcript\n // reimport) without mitmproxy / CA trust / gateway. The proxy adds the\n // rendered system prompt (instruction-linking) + cross-tool capture on top.\n const refreshedHooks = removeClaudeCodeHooks(settings);\n mergeClaudeCodeHooks(settings);\n this.log(\n refreshedHooks\n ? '[OK] Refreshed RuleMetric Claude Code session hooks \u2192 .claude/settings.json'\n : '[OK] Installed RuleMetric Claude Code session hooks \u2192 .claude/settings.json',\n );\n\n // \u2500\u2500 2. Configure gateway + proxy \u2500\u2500\u2500\u2500\u2500\u2500\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 if (!noProxy) {\n // Ensure mitmproxy is available\n const hasMitmproxy = this.findBinary('mitmdump');\n if (!hasMitmproxy) {\n this.log('');\n this.log('[!!] mitmproxy not found \u2014 installing...');\n const installed = this.installMitmproxy();\n if (!installed) {\n this.log('[!!] Could not install mitmproxy. Skipping proxy config.');\n this.log(' Install manually: pipx install mitmproxy');\n this.log(' Then re-run: rulemetric hooks install');\n }\n }\n\n // Generate CA cert if missing\n if (!existsSync(CERT_PATH)) {\n this.log('[..] Generating CA certificate...');\n const mitmdump = this.findBinary('mitmdump');\n if (mitmdump) {\n spawnSync(mitmdump, ['--set', 'listen_port=0', '-q'], {\n timeout: 5000,\n stdio: 'ignore',\n });\n if (existsSync(CERT_PATH)) {\n this.log(`[OK] CA certificate generated at ${CERT_PATH}`);\n } else {\n this.log('[!!] Could not generate CA cert');\n }\n }\n } else {\n this.log('[OK] CA certificate found');\n }\n\n // Trust CA cert in system store (if not already trusted)\n if (existsSync(CERT_PATH) && !this.isCACertTrusted()) {\n this.log('[..] Installing CA certificate into system trust store (requires admin)...');\n const trusted = this.trustCACert();\n if (trusted) {\n this.log('[OK] CA certificate trusted by system');\n } else {\n this.log('[!!] Could not install CA cert automatically.');\n if (process.platform === 'darwin') {\n this.log(` Run manually: sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${CERT_PATH}`);\n } else if (process.platform === 'linux') {\n this.log(` Run manually: sudo cp ${CERT_PATH} /usr/local/share/ca-certificates/mitmproxy-ca.crt && sudo update-ca-certificates`);\n }\n }\n } else if (existsSync(CERT_PATH)) {\n this.log('[OK] CA certificate already trusted');\n }\n\n // Set permanent HTTPS_PROXY and NODE_EXTRA_CA_CERTS in settings.json\n // These point to the gateway (always running), not mitmproxy directly\n const env = (settings.env ?? {}) as Record<string, string>;\n env.HTTPS_PROXY = `http://localhost:${GATEWAY_PORT}`;\n // Bypass proxy for non-Anthropic traffic (Supabase auth, npm, etc.)\n env.NO_PROXY = 'localhost,127.0.0.1,*.supabase.co,*.supabase.in';\n if (existsSync(CERT_PATH)) {\n env.NODE_EXTRA_CA_CERTS = CERT_PATH;\n }\n settings.env = env;\n this.log(`[OK] HTTPS_PROXY set to gateway on :${GATEWAY_PORT} (permanent)`);\n\n // Configure Cursor proxy (if .cursor/ exists)\n const cursorProxy = writeCursorProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);\n if (cursorProxy) {\n this.log('[OK] Cursor proxy configured \u2192 .cursor/settings.json');\n }\n\n // Configure VS Code proxy for Copilot capture (workspace settings)\n const vscodeProxy = writeVSCodeProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);\n if (vscodeProxy) {\n this.log('[OK] VS Code workspace proxy configured \u2192 .vscode/settings.json');\n }\n\n // Set http.proxy in VS Code user settings (workspace-level is silently ignored\n // for http.proxy due to APPLICATION scope \u2014 microsoft/vscode#236932)\n const vscodeUserProxy = writeVSCodeUserProxyConfig(GATEWAY_PORT);\n if (vscodeUserProxy) {\n this.log('[OK] VS Code user proxy configured \u2192 ~/Library/Application Support/Code/User/settings.json');\n }\n\n // Same for Cursor (VS Code fork inherits the APPLICATION-scope restriction).\n const cursorUserProxy = writeCursorUserProxyConfig(GATEWAY_PORT);\n if (cursorUserProxy) {\n this.log('[OK] Cursor user proxy configured \u2192 ~/Library/Application Support/Cursor/User/settings.json');\n }\n\n // Set HTTPS_PROXY for all GUI apps via launchctl + LaunchAgent (macOS)\n // Copilot reads process.env.HTTPS_PROXY directly \u2014 VS Code settings alone\n // are insufficient because workspace http.proxy is ignored and extensions\n // may bypass vscode-proxy-agent (microsoft/vscode#12588)\n const macProxy = installMacOSProxyEnv(GATEWAY_PORT, CERT_PATH);\n if (macProxy) {\n this.log('[OK] HTTPS_PROXY set for GUI apps (launchctl + LaunchAgent)');\n }\n\n // Start gateway if not already running. Three possible owners (in order\n // of precedence):\n // 1. launchd (`rulemetric service install` plist) \u2014 authoritative;\n // hooks must NOT spawn a competing copy that would fight for :8787\n // 2. legacy PID-file (this same code path from a previous run)\n // 3. nothing \u2014 spawn a fresh detached process\n if (isGatewayLaunchdManaged()) {\n this.log('[OK] Gateway managed by launchd (com.rulemetric.gateway)');\n } else if (isGatewayRunning()) {\n this.log('[OK] Gateway already running');\n } else {\n try {\n const pid = spawnGateway(this.config.version);\n this.log(`[OK] Gateway started (PID ${pid})`);\n } catch (err) {\n this.log(`[!!] Could not start gateway: ${(err as Error).message}`);\n this.log(' The session-start hook will auto-start it on next Claude Code session.');\n }\n }\n }\n\n // \u2500\u2500 3. Write Cursor + Copilot hook configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // These are independent of the proxy (they capture editor lifecycle\n // events, not LLM traffic), so they run regardless of --no-proxy. Both\n // helpers no-op when the target directory (.cursor/ or .github/)\n // doesn't exist.\n if (!isGlobal) {\n const cursorHooks = writeCursorHooks(projectPath);\n if (cursorHooks) {\n this.log(`[OK] Cursor hooks configured \u2192 ${cursorHooks}`);\n }\n\n const copilotHooks = writeCopilotHooks(projectPath);\n if (copilotHooks) {\n this.log(`[OK] Copilot Agent hooks configured \u2192 ${copilotHooks}`);\n }\n\n const antigravityHooks = writeAntigravityHooks(projectPath);\n if (antigravityHooks) {\n this.log(`[OK] Antigravity workspace hooks configured \u2192 ${antigravityHooks}`);\n }\n }\n\n // User-level Antigravity hooks at ~/.gemini/config/hooks.json. Required\n // because the GUI Antigravity process is launched once per machine and\n // covers any workspace the user opens, not just the install-time cwd.\n const antigravityUserHooks = writeAntigravityUserHooks();\n if (antigravityUserHooks) {\n this.log(`[OK] Antigravity user hooks configured \u2192 ${antigravityUserHooks}`);\n }\n\n // User-level Cursor hooks (~/.cursor/hooks.json) are required for global\n // capture because Cursor's chat traffic bypasses HTTP proxies (HTTP/2\n // multiplexed persistent connection \u2014 see cursor.com/docs/hooks). Without\n // hooks, we get zero Cursor visibility for sessions outside this project.\n // Runs in both --global and per-project modes since the user file is\n // machine-wide either way.\n const cursorUserHooks = writeCursorUserHooks();\n if (cursorUserHooks) {\n this.log(`[OK] Cursor user hooks configured \u2192 ${cursorUserHooks}`);\n }\n\n // \u2500\u2500 4. Statusline shim (rate_limits freshness) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When --statusline-usage is set, write ~/.claude/statusline-rulemetric.sh\n // and point settings.statusLine at it. If the user already has a statusLine\n // command configured, chain it so their prompt text is preserved.\n if (flags['statusline-usage']) {\n if (isStatuslineShimInstalled(settings)) {\n this.log('[OK] Statusline shim already installed');\n } else {\n const prevCmd = readCurrentStatusLine(settings);\n writeStatuslineShim(prevCmd);\n settings.statusLine = STATUSLINE_SETTINGS_VALUE;\n if (prevCmd) {\n this.log(`[OK] Statusline shim installed \u2192 ${STATUSLINE_SETTINGS_VALUE.command} (chains to: ${prevCmd})`);\n } else {\n this.log(`[OK] Statusline shim installed \u2192 ${STATUSLINE_SETTINGS_VALUE.command}`);\n }\n this.log(' Rate-limit rings will now update on Claude Code\\'s statusline refresh cadence');\n }\n }\n\n // \u2500\u2500 5. Write Claude Code settings \u2500\u2500\u2500\u2500\u2500\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 mkdirSync(configDir, { recursive: true });\n writeFileSync(configPath, JSON.stringify(settings, null, 2) + '\\n');\n\n this.log('');\n this.log('Setup complete! Next steps:');\n if (isGlobal) {\n this.log(' 1. Install always-on API: rulemetric service install');\n this.log(' 2. Start Claude Code in any project \u2014 all sessions tracked automatically');\n this.log('');\n this.log('The API service starts on login and restarts on crash.');\n } else if (!noProxy) {\n this.log(' 1. Start Claude Code \u2014 sessions are captured by hooks immediately');\n this.log(' 2. Start the capture proxy for full depth: rulemetric proxy start');\n this.log('');\n this.log('Hooks capture every session (lifecycle + transcript). The proxy adds the');\n this.log('rendered system prompt (instruction-effectiveness linking) + cross-tool capture.');\n this.log('');\n this.log('To capture traffic from other clients (Python, curl, etc.):');\n this.log(' eval \"$(rulemetric proxy env --all)\"');\n } else {\n // --no-proxy still installs the Claude Code session hooks above, so full\n // sessions ARE captured (lifecycle + SessionEnd transcript reimport) with\n // no mitmproxy / CA trust / gateway. Only the proxy-exclusive layer\n // (rendered system prompt \u2192 instruction-linking, cross-tool) is skipped.\n this.log(' 1. Start Claude Code \u2014 sessions are captured by the hooks just installed');\n this.log('');\n this.log('No proxy means no mitmproxy / CA cert needed. The hooks capture full');\n this.log('sessions on their own; re-run without --no-proxy to also capture system');\n this.log('prompts for instruction-effectiveness linking.');\n }\n\n // Ensure the active-org cache is populated before the user starts a\n // Claude Code session. BaseCommand fired the guarded refresh earlier\n // but may have raced with auth init or hit a transient error; this\n // explicit retry guarantees the cache reflects the user's current\n // active_org_id at the end of `hooks install`.\n await bootstrapActiveOrg();\n\n // Soft tmux capability check \u2014 live message send needs tmux on the\n // user's machine. We do not auto-install; just surface one line.\n const tmux = await detectTmux();\n this.log('');\n if (tmux.available) {\n this.log(`[OK] tmux found${tmux.version ? ` (v${tmux.version})` : ''} \u2014 live send enabled`);\n } else {\n this.log('[!!] tmux not found \u2014 live send will fall back to opening Terminal. Install with: brew install tmux');\n }\n }\n\n private findBinary(name: string): string | null {\n try {\n return execSync(`which ${name} 2>/dev/null`, { encoding: 'utf-8' }).trim() || null;\n } catch {\n return null;\n }\n }\n\n private installMitmproxy(): boolean {\n for (const [cmd, args] of [\n ['pipx', ['install', 'mitmproxy']],\n ['uv', ['tool', 'install', 'mitmproxy']],\n ['brew', ['install', 'mitmproxy']],\n ] as const) {\n if (this.findBinary(cmd)) {\n this.log(` Installing via ${cmd}...`);\n const result = spawnSync(cmd, [...args], { stdio: 'inherit' });\n if (result.status === 0) return true;\n }\n }\n return false;\n }\n\n private isCACertTrusted(): boolean {\n if (process.platform === 'darwin') {\n const result = spawnSync('security', ['verify-cert', '-c', CERT_PATH], {\n stdio: 'pipe',\n });\n return result.status === 0;\n }\n\n if (process.platform === 'linux') {\n return existsSync('/usr/local/share/ca-certificates/mitmproxy-ca.crt');\n }\n\n if (process.platform === 'win32') {\n // On Windows, check if cert is in the Root store\n const result = spawnSync('certutil', ['-verify', CERT_PATH], {\n stdio: 'pipe',\n });\n return result.status === 0;\n }\n\n return false;\n }\n\n private trustCACert(): boolean {\n if (process.platform === 'darwin') {\n const result = spawnSync('sudo', [\n 'security', 'add-trusted-cert', '-d', '-r', 'trustRoot',\n '-k', '/Library/Keychains/System.keychain', CERT_PATH,\n ], { stdio: 'inherit' });\n return result.status === 0;\n }\n\n if (process.platform === 'linux') {\n const cp = spawnSync('sudo', [\n 'cp', CERT_PATH, '/usr/local/share/ca-certificates/mitmproxy-ca.crt',\n ], { stdio: 'inherit' });\n if (cp.status !== 0) return false;\n const update = spawnSync('sudo', ['update-ca-certificates'], { stdio: 'inherit' });\n return update.status === 0;\n }\n\n if (process.platform === 'win32') {\n const result = spawnSync('certutil', [\n '-addstore', '-f', 'Root', CERT_PATH,\n ], { stdio: 'inherit' });\n return result.status === 0;\n }\n\n return false;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,cAAc,UAAU,iBAAiB;AAClD,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,YAAY;AAQrB,SAAS,0BAAmC;AAC1C,MAAI;AACF,iBAAa,aAAa,CAAC,QAAQ,wBAAwB,GAAG;AAAA,MAC5D,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,IAClC,CAAC;AACD,WAAO;AAAA,EACT,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;AAwBA,IAAM,YAAY,KAAK,QAAQ,GAAG,cAAc,uBAAuB;AAEvE,IAAqB,eAArB,MAAqB,sBAAqB,YAAY;AAAA,EACpD,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,YAAY,MAAM,QAAQ;AAAA,MACxB,SAAS;AAAA,MACT,aAAa;AAAA,IACf,CAAC;AAAA,IACD,eAAe,MAAM,OAAO;AAAA,MAC1B,aAAa;AAAA,IACf,CAAC;AAAA,IACD,QAAQ,MAAM,QAAQ;AAAA,MACpB,MAAM;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,IACf,CAAC;AAAA,IACD,oBAAoB,MAAM,QAAQ;AAAA,MAChC,SAAS;AAAA,MACT,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,KAAK,MAAM,aAAY;AAC/C,UAAM,WAAW,MAAM;AACvB,UAAM,cAAc,WAAW,QAAQ,IAAK,MAAM,aAA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UAAU,YAAY;AAAA,QACnC;AAAA,QAAa;AAAA,QAAM;AAAA,QAAQ;AAAA,MAC7B,GAAG,EAAE,OAAO,UAAU,CAAC;AACvB,aAAO,OAAO,WAAW;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import { Flags } from '@oclif/core';\nimport { execFileSync, execSync, spawnSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, dirname } from 'node:path';\nimport { BaseCommand } from '../../base-command.js';\nimport { isGatewayRunning, waitForGatewayListening, spawnGateway, GATEWAY_PORT } from '../../lib/gateway-lifecycle.js';\n\n// Resolve the directory holding the `rulemetric` executable, so hook commands\n// can prepend it to PATH. Claude Code runs hooks via `/bin/sh -c` with a\n// minimal PATH that omits nvm/pnpm global bin dirs \u2014 so a bare `rulemetric`\n// hits \"command not found\" and capture (plus the session-start gateway\n// auto-start) silently fails. We resolve it here, in the install process's\n// full PATH, and bake the dir into the hook command. Returns undefined on\n// failure \u2192 callers fall back to the bare `rulemetric` (dev/back-compat).\nfunction resolveHookBinDir(): string | undefined {\n try {\n const out = execFileSync('/bin/sh', ['-c', 'command -v rulemetric'], {\n encoding: 'utf-8',\n }).trim();\n if (out && existsSync(out)) return dirname(out);\n } catch {\n /* not resolvable \u2014 fall back to bare `rulemetric` */\n }\n return undefined;\n}\n\n// True iff `rulemetric service install` has wired the gateway up as a launchd\n// agent. When this returns true, hooks install must NOT spawn its own\n// detached gateway \u2014 two processes fighting for :8787 means one crash-loops\n// and Claude Code's HTTPS_PROXY breaks.\nfunction isGatewayLaunchdManaged(): boolean {\n try {\n execFileSync('launchctl', ['list', 'com.rulemetric.gateway'], {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return true;\n } catch {\n // Non-zero exit = label not loaded\n return false;\n }\n}\nimport {\n writeStatuslineShim,\n readCurrentStatusLine,\n isStatuslineShimInstalled,\n STATUSLINE_SETTINGS_VALUE,\n} from '../../lib/statusline-shim.js';\nimport {\n mergeClaudeCodeHooks,\n removeClaudeCodeHooks,\n readClaudeSettings,\n writeClaudeSettingsWithBackup,\n writeCursorProxyConfig,\n writeCursorUserProxyConfig,\n writeVSCodeProxyConfig,\n installMacOSProxyEnv,\n writeVSCodeUserProxyConfig,\n writeCursorHooks,\n writeCursorUserHooks,\n writeCopilotHooks,\n writeAntigravityHooks,\n writeAntigravityUserHooks,\n} from '../../lib/hooks-config.js';\nimport { bootstrapActiveOrg } from '../../lib/active-org-refresh.js';\nimport { detectTmux } from '../../lib/detect-tmux.js';\n\nconst CERT_PATH = join(homedir(), '.mitmproxy', 'mitmproxy-ca-cert.pem');\n\nexport default class HooksInstall extends BaseCommand {\n static override description = 'Install session tracking hooks and context capture proxy for Claude Code';\n\n static override examples = [\n '<%= config.bin %> hooks install',\n '<%= config.bin %> hooks install --global',\n '<%= config.bin %> hooks install --no-proxy',\n ];\n\n static override flags = {\n 'no-proxy': Flags.boolean({\n default: false,\n description: 'Skip proxy/gateway configuration (hooks only)',\n }),\n 'project-dir': Flags.string({\n description: 'Project directory to install hooks in (defaults to cwd)',\n }),\n global: Flags.boolean({\n char: 'g',\n default: false,\n description: 'Install hooks globally (~/.claude/settings.json) so all projects are tracked',\n }),\n 'statusline-usage': Flags.boolean({\n default: false,\n description: 'Install the statusline shim so Claude Code pushes live rate_limits on every refresh (makes /usage rings update in real time without needing the proxy)',\n }),\n };\n\n async run(): Promise<void> {\n const { flags } = await this.parse(HooksInstall);\n const isGlobal = flags.global;\n const projectPath = isGlobal ? homedir() : (flags['project-dir'] ?? process.cwd());\n const configDir = join(projectPath, '.claude');\n const configPath = join(configDir, 'settings.json');\n const noProxy = flags['no-proxy'];\n // Whether the capture proxy actually went live this run (HTTPS_PROXY pinned\n // against a verified-live gateway). Drives the \"next steps\" copy so we never\n // tell the user to start a proxy that is already running.\n let proxyActive = false;\n\n if (isGlobal) {\n this.log(`Installing hooks globally \u2192 ${configPath}`);\n }\n\n // Read or create .claude/settings.json. Never crash on a malformed file \u2014\n // a fresh user's hand-edited settings.json must not block capture install.\n const { settings, recoveredBackup } = readClaudeSettings(configPath);\n if (recoveredBackup) {\n this.log(`[!!] ${configPath} was not valid JSON \u2014 backed it up to ${recoveredBackup} and continued with a fresh file.`);\n }\n\n // \u2500\u2500 1. Install Claude Code session-tracking hooks (hooks-first, zero-proxy\n // capture). Strip any stale rulemetric entries first \u2014 handles old command\n // formats, preserves the user's own hooks \u2014 then merge the current canonical\n // set. Runs regardless of --no-proxy: this is the whole point of the hooks\n // path, which captures full sessions (lifecycle + SessionEnd transcript\n // reimport) without mitmproxy / CA trust / gateway. The proxy adds the\n // rendered system prompt (instruction-linking) + cross-tool capture on top.\n const refreshedHooks = removeClaudeCodeHooks(settings);\n // Resolve once; every hook writer (Claude Code, Cursor, Copilot) needs the\n // same PATH prefix so a GUI-launched tool with a minimal PATH can find the CLI.\n const hookBinDir = resolveHookBinDir();\n mergeClaudeCodeHooks(settings, hookBinDir);\n this.log(\n refreshedHooks\n ? '[OK] Refreshed RuleMetric Claude Code session hooks \u2192 .claude/settings.json'\n : '[OK] Installed RuleMetric Claude Code session hooks \u2192 .claude/settings.json',\n );\n\n // \u2500\u2500 2. Configure gateway + proxy \u2500\u2500\u2500\u2500\u2500\u2500\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 if (!noProxy) {\n // Ensure mitmproxy is available\n const hasMitmproxy = this.findBinary('mitmdump');\n if (!hasMitmproxy) {\n this.log('');\n this.log('[!!] mitmproxy not found \u2014 installing...');\n const installed = this.installMitmproxy();\n if (!installed) {\n this.log('[!!] Could not install mitmproxy. Skipping proxy config.');\n this.log(' Install manually: pipx install mitmproxy');\n this.log(' Then re-run: rulemetric hooks install');\n }\n }\n\n // Generate CA cert if missing\n if (!existsSync(CERT_PATH)) {\n this.log('[..] Generating CA certificate...');\n const mitmdump = this.findBinary('mitmdump');\n if (mitmdump) {\n spawnSync(mitmdump, ['--set', 'listen_port=0', '-q'], {\n timeout: 5000,\n stdio: 'ignore',\n });\n if (existsSync(CERT_PATH)) {\n this.log(`[OK] CA certificate generated at ${CERT_PATH}`);\n } else {\n this.log('[!!] Could not generate CA cert');\n }\n }\n } else {\n this.log('[OK] CA certificate found');\n }\n\n // Trust CA cert in system store (if not already trusted). Track the\n // result: whether the CA is trusted decides if we may route MACHINE-WIDE /\n // native-app traffic through the MITM proxy (native apps validate against\n // the system keychain, so an untrusted CA breaks their TLS).\n const caGenerated = existsSync(CERT_PATH);\n let caTrusted = false;\n if (caGenerated && !this.isCACertTrusted()) {\n this.log('[..] Installing CA certificate into system trust store (requires admin)...');\n caTrusted = this.trustCACert();\n if (caTrusted) {\n this.log('[OK] CA certificate trusted by system');\n } else {\n this.log('[!!] Could not install CA cert automatically.');\n if (process.platform === 'darwin') {\n this.log(` Run manually: sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${CERT_PATH}`);\n } else if (process.platform === 'linux') {\n this.log(` Run manually: sudo cp ${CERT_PATH} /usr/local/share/ca-certificates/mitmproxy-ca.crt && sudo update-ca-certificates`);\n }\n }\n } else if (caGenerated) {\n this.log('[OK] CA certificate already trusted');\n caTrusted = true;\n }\n\n // Start the gateway BEFORE pinning HTTPS_PROXY. Three possible owners (in\n // order of precedence):\n // 1. launchd (`rulemetric service install` plist) \u2014 authoritative;\n // hooks must NOT spawn a competing copy that would fight for :8787\n // 2. legacy PID-file (this same code path from a previous run)\n // 3. nothing \u2014 spawn a fresh detached process\n if (isGatewayLaunchdManaged()) {\n this.log('[OK] Gateway managed by launchd (com.rulemetric.gateway)');\n } else if (isGatewayRunning()) {\n this.log('[OK] Gateway already running');\n } else {\n try {\n const pid = spawnGateway(this.config.version);\n this.log(`[OK] Gateway started (PID ${pid})`);\n } catch (err) {\n this.log(`[!!] Could not start gateway: ${(err as Error).message}`);\n }\n }\n\n // Liveness guard: ONLY pin HTTPS_PROXY once :8787 actually accepts\n // connections. Writing it against a dead port is the fresh-laptop\n // ConnectionRefused footgun \u2014 it breaks all of Claude Code's HTTPS. If the\n // gateway isn't answering, we leave Claude Code talking to Anthropic\n // directly; capture still works via the hooks installed in \u00A71.\n // Poll (not a one-shot probe): a just-spawned gateway needs a moment to\n // bind :8787, and a single immediate probe would fail-close every fresh\n // install and silently disable deep capture.\n const gatewayLive = await waitForGatewayListening(GATEWAY_PORT, { timeoutMs: 4000 });\n if (!caGenerated) {\n // No CA \u2192 mitmproxy will regenerate one and intercept, but nothing\n // trusts it, so pinning HTTPS_PROXY would break even Claude Code's TLS.\n // Stay hooks-only rather than pin a proxy nothing can validate.\n this.log('[!!] No CA certificate \u2014 NOT setting HTTPS_PROXY (capture stays hooks-only).');\n this.log(' Install mitmproxy, then re-run: rulemetric hooks install');\n } else if (!gatewayLive) {\n this.log(`[!!] Gateway is not answering on :${GATEWAY_PORT} \u2014 NOT setting HTTPS_PROXY.`);\n this.log(' Capture still works via hooks. To enable deep (proxy) capture later:');\n this.log(' rulemetric proxy start && rulemetric hooks install');\n } else {\n // Set permanent HTTPS_PROXY and NODE_EXTRA_CA_CERTS in settings.json.\n // These point to the gateway (verified live above), not mitmproxy directly.\n const env = (settings.env ?? {}) as Record<string, string>;\n env.HTTPS_PROXY = `http://localhost:${GATEWAY_PORT}`;\n // Bypass proxy for non-Anthropic traffic (Supabase auth, npm, etc.)\n env.NO_PROXY = 'localhost,127.0.0.1,*.supabase.co,*.supabase.in';\n if (existsSync(CERT_PATH)) {\n env.NODE_EXTRA_CA_CERTS = CERT_PATH;\n }\n settings.env = env;\n proxyActive = true;\n this.log(`[OK] HTTPS_PROXY set to gateway on :${GATEWAY_PORT} (verified live)`);\n\n // Configure Cursor proxy (if .cursor/ exists)\n const cursorProxy = writeCursorProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);\n if (cursorProxy) {\n this.log('[OK] Cursor proxy configured \u2192 .cursor/settings.json');\n }\n\n // Configure VS Code proxy for Copilot capture (workspace settings)\n const vscodeProxy = writeVSCodeProxyConfig(projectPath, GATEWAY_PORT, CERT_PATH);\n if (vscodeProxy) {\n this.log('[OK] VS Code workspace proxy configured \u2192 .vscode/settings.json');\n }\n\n // Set http.proxy in VS Code user settings (workspace-level is silently ignored\n // for http.proxy due to APPLICATION scope \u2014 microsoft/vscode#236932)\n const vscodeUserProxy = writeVSCodeUserProxyConfig(GATEWAY_PORT);\n if (vscodeUserProxy) {\n this.log('[OK] VS Code user proxy configured \u2192 ~/Library/Application Support/Code/User/settings.json');\n }\n\n // Same for Cursor (VS Code fork inherits the APPLICATION-scope restriction).\n const cursorUserProxy = writeCursorUserProxyConfig(GATEWAY_PORT);\n if (cursorUserProxy) {\n this.log('[OK] Cursor user proxy configured \u2192 ~/Library/Application Support/Cursor/User/settings.json');\n }\n\n // Set HTTPS_PROXY for all GUI apps via launchctl + LaunchAgent (macOS)\n // Copilot reads process.env.HTTPS_PROXY directly \u2014 VS Code settings alone\n // are insufficient because workspace http.proxy is ignored and extensions\n // may bypass vscode-proxy-agent (microsoft/vscode#12588).\n //\n // GATED ON CA TRUST: this routes EVERY GUI/native app's HTTPS through the\n // MITM proxy machine-wide. Native apps validate against the system\n // keychain, so if the CA isn't trusted (sudo declined / non-admin) this\n // would break their TLS with an unknown-CA error attributed to nothing\n // obvious. Claude Code + Node apps are unaffected either way (they trust\n // NODE_EXTRA_CA_CERTS), so we keep that path and only skip the\n // machine-wide native layer.\n if (caTrusted) {\n const macProxy = installMacOSProxyEnv(GATEWAY_PORT, CERT_PATH);\n if (macProxy) {\n this.log('[OK] HTTPS_PROXY set for GUI apps (launchctl + LaunchAgent)');\n }\n } else {\n this.log('[!!] CA not trusted \u2014 skipping machine-wide GUI proxy (would break native-app TLS).');\n this.log(' Claude Code capture is unaffected. Trust the CA + re-run to enable cross-app capture.');\n }\n }\n }\n\n // \u2500\u2500 3. Write Cursor + Copilot hook configs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // These are independent of the proxy (they capture editor lifecycle\n // events, not LLM traffic), so they run regardless of --no-proxy. Both\n // helpers no-op when the target directory (.cursor/ or .github/)\n // doesn't exist.\n if (!isGlobal) {\n const cursorHooks = writeCursorHooks(projectPath, hookBinDir);\n if (cursorHooks) {\n this.log(`[OK] Cursor hooks configured \u2192 ${cursorHooks}`);\n }\n\n const copilotHooks = writeCopilotHooks(projectPath, hookBinDir);\n if (copilotHooks) {\n this.log(`[OK] Copilot Agent hooks configured \u2192 ${copilotHooks}`);\n }\n\n const antigravityHooks = writeAntigravityHooks(projectPath);\n if (antigravityHooks) {\n this.log(`[OK] Antigravity workspace hooks configured \u2192 ${antigravityHooks}`);\n }\n }\n\n // User-level Antigravity hooks at ~/.gemini/config/hooks.json. Required\n // because the GUI Antigravity process is launched once per machine and\n // covers any workspace the user opens, not just the install-time cwd.\n const antigravityUserHooks = writeAntigravityUserHooks();\n if (antigravityUserHooks) {\n this.log(`[OK] Antigravity user hooks configured \u2192 ${antigravityUserHooks}`);\n }\n\n // User-level Cursor hooks (~/.cursor/hooks.json) are required for global\n // capture because Cursor's chat traffic bypasses HTTP proxies (HTTP/2\n // multiplexed persistent connection \u2014 see cursor.com/docs/hooks). Without\n // hooks, we get zero Cursor visibility for sessions outside this project.\n // Runs in both --global and per-project modes since the user file is\n // machine-wide either way.\n const cursorUserHooks = writeCursorUserHooks(hookBinDir);\n if (cursorUserHooks) {\n this.log(`[OK] Cursor user hooks configured \u2192 ${cursorUserHooks}`);\n }\n\n // \u2500\u2500 4. Statusline shim (rate_limits freshness) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When --statusline-usage is set, write ~/.claude/statusline-rulemetric.sh\n // and point settings.statusLine at it. If the user already has a statusLine\n // command configured, chain it so their prompt text is preserved.\n if (flags['statusline-usage']) {\n if (isStatuslineShimInstalled(settings)) {\n this.log('[OK] Statusline shim already installed');\n } else {\n const prevCmd = readCurrentStatusLine(settings);\n writeStatuslineShim(prevCmd);\n settings.statusLine = STATUSLINE_SETTINGS_VALUE;\n if (prevCmd) {\n this.log(`[OK] Statusline shim installed \u2192 ${STATUSLINE_SETTINGS_VALUE.command} (chains to: ${prevCmd})`);\n } else {\n this.log(`[OK] Statusline shim installed \u2192 ${STATUSLINE_SETTINGS_VALUE.command}`);\n }\n this.log(' Rate-limit rings will now update on Claude Code\\'s statusline refresh cadence');\n }\n }\n\n // \u2500\u2500 5. Write Claude Code settings (backup prior file \u2192 reversible) \u2500\u2500\u2500\u2500\u2500\n const { backupPath } = writeClaudeSettingsWithBackup(configPath, settings);\n if (backupPath) {\n this.log(`[OK] Backed up previous settings \u2192 ${backupPath}`);\n }\n\n this.log('');\n this.log('Setup complete! Next steps:');\n if (isGlobal) {\n this.log(' 1. Install always-on API: rulemetric service install');\n this.log(' 2. Start Claude Code in any project \u2014 all sessions tracked automatically');\n this.log('');\n this.log('The API service starts on login and restarts on crash.');\n } else if (!noProxy) {\n this.log(' 1. Start Claude Code \u2014 sessions are captured by hooks immediately');\n if (proxyActive) {\n // The proxy IS live (pinned against a verified gateway above) \u2014 don't\n // tell the user to start something that's already running.\n this.log(' 2. Full-depth capture is ON \u2014 the proxy is live on :' + GATEWAY_PORT + '.');\n } else {\n this.log(' 2. Enable full depth (proxy not yet live): rulemetric proxy start');\n }\n this.log('');\n this.log('Hooks capture every session (lifecycle + transcript). The proxy adds the');\n this.log('rendered system prompt (instruction-effectiveness linking) + cross-tool capture.');\n this.log('');\n this.log('To capture traffic from other clients (Python, curl, etc.):');\n this.log(' eval \"$(rulemetric proxy env --all)\"');\n } else {\n // --no-proxy still installs the Claude Code session hooks above, so full\n // sessions ARE captured (lifecycle + SessionEnd transcript reimport) with\n // no mitmproxy / CA trust / gateway. Only the proxy-exclusive layer\n // (rendered system prompt \u2192 instruction-linking, cross-tool) is skipped.\n this.log(' 1. Start Claude Code \u2014 sessions are captured by the hooks just installed');\n this.log('');\n this.log('No proxy means no mitmproxy / CA cert needed. The hooks capture full');\n this.log('sessions on their own; re-run without --no-proxy to also capture system');\n this.log('prompts for instruction-effectiveness linking.');\n }\n\n // Ensure the active-org cache is populated before the user starts a\n // Claude Code session. BaseCommand fired the guarded refresh earlier\n // but may have raced with auth init or hit a transient error; this\n // explicit retry guarantees the cache reflects the user's current\n // active_org_id at the end of `hooks install`.\n await bootstrapActiveOrg();\n\n // Soft tmux capability check \u2014 live message send needs tmux on the\n // user's machine. We do not auto-install; just surface one line.\n const tmux = await detectTmux();\n this.log('');\n if (tmux.available) {\n this.log(`[OK] tmux found${tmux.version ? ` (v${tmux.version})` : ''} \u2014 live send enabled`);\n } else {\n this.log('[!!] tmux not found \u2014 live send will fall back to opening Terminal. Install with: brew install tmux');\n }\n }\n\n private findBinary(name: string): string | null {\n try {\n return execSync(`which ${name} 2>/dev/null`, { encoding: 'utf-8' }).trim() || null;\n } catch {\n return null;\n }\n }\n\n private installMitmproxy(): boolean {\n for (const [cmd, args] of [\n ['pipx', ['install', 'mitmproxy']],\n ['uv', ['tool', 'install', 'mitmproxy']],\n ['brew', ['install', 'mitmproxy']],\n ] as const) {\n if (this.findBinary(cmd)) {\n this.log(` Installing via ${cmd}...`);\n const result = spawnSync(cmd, [...args], { stdio: 'inherit' });\n if (result.status === 0) return true;\n }\n }\n return false;\n }\n\n private isCACertTrusted(): boolean {\n if (process.platform === 'darwin') {\n const result = spawnSync('security', ['verify-cert', '-c', CERT_PATH], {\n stdio: 'pipe',\n });\n return result.status === 0;\n }\n\n if (process.platform === 'linux') {\n return existsSync('/usr/local/share/ca-certificates/mitmproxy-ca.crt');\n }\n\n if (process.platform === 'win32') {\n // On Windows, check if cert is in the Root store\n const result = spawnSync('certutil', ['-verify', CERT_PATH], {\n stdio: 'pipe',\n });\n return result.status === 0;\n }\n\n return false;\n }\n\n private trustCACert(): boolean {\n if (process.platform === 'darwin') {\n const result = spawnSync('sudo', [\n 'security', 'add-trusted-cert', '-d', '-r', 'trustRoot',\n '-k', '/Library/Keychains/System.keychain', CERT_PATH,\n ], { stdio: 'inherit' });\n return result.status === 0;\n }\n\n if (process.platform === 'linux') {\n const cp = spawnSync('sudo', [\n 'cp', CERT_PATH, '/usr/local/share/ca-certificates/mitmproxy-ca.crt',\n ], { stdio: 'inherit' });\n if (cp.status !== 0) return false;\n const update = spawnSync('sudo', ['update-ca-certificates'], { stdio: 'inherit' });\n return update.status === 0;\n }\n\n if (process.platform === 'win32') {\n const result = spawnSync('certutil', [\n '-addstore', '-f', 'Root', CERT_PATH,\n ], { stdio: 'inherit' });\n return result.status === 0;\n }\n\n return false;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,cAAc,UAAU,iBAAiB;AAClD,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAW9B,SAAS,oBAAwC;AAC/C,MAAI;AACF,UAAM,MAAM,aAAa,WAAW,CAAC,MAAM,uBAAuB,GAAG;AAAA,MACnE,UAAU;AAAA,IACZ,CAAC,EAAE,KAAK;AACR,QAAI,OAAO,WAAW,GAAG,EAAG,QAAO,QAAQ,GAAG;AAAA,EAChD,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAMA,SAAS,0BAAmC;AAC1C,MAAI;AACF,iBAAa,aAAa,CAAC,QAAQ,wBAAwB,GAAG;AAAA,MAC5D,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,IAClC,CAAC;AACD,WAAO;AAAA,EACT,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;AA0BA,IAAM,YAAY,KAAK,QAAQ,GAAG,cAAc,uBAAuB;AAEvE,IAAqB,eAArB,MAAqB,sBAAqB,YAAY;AAAA,EACpD,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACz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,MAC7B,GAAG,EAAE,OAAO,UAAU,CAAC;AACvB,aAAO,OAAO,WAAW;AAAA,IAC3B;AAEA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -12,7 +12,7 @@ import "../../chunk-NSBPE2FW.js";
12
12
  import { Args } from "@oclif/core";
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { existsSync } from "node:fs";
15
- import { join } from "node:path";
15
+ import { join, delimiter } from "node:path";
16
16
  var VALID_HOOKS = ["session-start", "session-end", "user-prompt", "post-tool-use", "assistant-response"];
17
17
  var HooksRun = class _HooksRun extends BaseCommand {
18
18
  static description = "Execute a hook script (called by AI tool hooks, not for direct use)";
@@ -34,11 +34,13 @@ var HooksRun = class _HooksRun extends BaseCommand {
34
34
  }
35
35
  try {
36
36
  const stdin = await this.readStdin();
37
+ const augmentedPath = `${process.env.PATH ?? ""}${delimiter}${scriptsDir}`;
38
+ const timeout = hookName === "session-end" ? 3e4 : 1e4;
37
39
  execFileSync("bash", [scriptPath], {
38
40
  input: stdin,
39
41
  stdio: ["pipe", "inherit", "inherit"],
40
- timeout: 1e4,
41
- env: process.env
42
+ timeout,
43
+ env: { ...process.env, PATH: augmentedPath }
42
44
  });
43
45
  if (process.env.RULEMETRIC_HOOK_TOOL === "antigravity" && hookName === "post-tool-use") {
44
46
  try {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/commands/hooks/run.ts"],
4
- "sourcesContent": ["import { Args } from '@oclif/core';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { BaseCommand } from '../../base-command.js';\n\nconst VALID_HOOKS = ['session-start', 'session-end', 'user-prompt', 'post-tool-use', 'assistant-response'] as const;\n\nexport default class HooksRun extends BaseCommand {\n static override description = 'Execute a hook script (called by AI tool hooks, not for direct use)';\n static override hidden = true;\n\n static override args = {\n hook: Args.string({\n description: 'Hook name to run',\n required: true,\n options: [...VALID_HOOKS],\n }),\n };\n\n async run(): Promise<void> {\n const { args } = await this.parse(HooksRun);\n const hookName = args.hook;\n\n // Resolve bundled script path\n const { scriptsDir } = await import('@rulemetric/hooks/scripts-dir');\n const scriptPath = join(scriptsDir, `${hookName}.sh`);\n\n if (!existsSync(scriptPath)) {\n this.error(`Hook script not found: ${scriptPath}`);\n }\n\n try {\n // Read stdin and pass it to the bash script\n const stdin = await this.readStdin();\n execFileSync('bash', [scriptPath], {\n input: stdin,\n stdio: ['pipe', 'inherit', 'inherit'],\n timeout: 10_000,\n env: process.env,\n });\n\n // Antigravity-specific: tail the conversation transcript and emit\n // user_message / assistant_response / tool_result events that the\n // bash hook can't see. Antigravity does not fire UserPromptSubmit\n // or Stop hooks, and the Gemini streaming traffic bypasses the\n // proxy. First fire for a conversation primes state to the current\n // transcript end and returns immediately \u2014 capture is forward-only.\n if (\n process.env.RULEMETRIC_HOOK_TOOL === 'antigravity' &&\n hookName === 'post-tool-use'\n ) {\n try {\n const { tailAntigravityTranscript } = await import(\n '../../lib/antigravity-transcript.js'\n );\n await tailAntigravityTranscript(stdin);\n } catch (err) {\n process.stderr.write(\n `[antigravity-tailer] ${(err as Error).message}\\n`,\n );\n }\n }\n } catch (error: unknown) {\n // Hooks should not crash the AI tool \u2014 exit silently\n const code = (error as { status?: number }).status;\n if (code) {\n process.exitCode = code;\n }\n }\n }\n\n private readStdin(): Promise<string> {\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk) => chunks.push(chunk));\n process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));\n // If stdin is already closed (no piped input), resolve immediately\n if (process.stdin.readableEnded) {\n resolve(Buffer.concat(chunks).toString('utf-8'));\n }\n });\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAGrB,IAAM,cAAc,CAAC,iBAAiB,eAAe,eAA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AAC;AAC1B,cAAQ,MAAM,GAAG,QAAQ,CAAC,UAAU,OAAO,KAAK,KAAK,CAAC;AACtD,cAAQ,MAAM,GAAG,OAAO,MAAM,QAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC;AAE9E,UAAI,QAAQ,MAAM,eAAe;AAC/B,gBAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,OAAO,CAAC;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
4
+ "sourcesContent": ["import { Args } from '@oclif/core';\nimport { execFileSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { join, delimiter } from 'node:path';\nimport { BaseCommand } from '../../base-command.js';\n\nconst VALID_HOOKS = ['session-start', 'session-end', 'user-prompt', 'post-tool-use', 'assistant-response'] as const;\n\nexport default class HooksRun extends BaseCommand {\n static override description = 'Execute a hook script (called by AI tool hooks, not for direct use)';\n static override hidden = true;\n\n static override args = {\n hook: Args.string({\n description: 'Hook name to run',\n required: true,\n options: [...VALID_HOOKS],\n }),\n };\n\n async run(): Promise<void> {\n const { args } = await this.parse(HooksRun);\n const hookName = args.hook;\n\n // Resolve bundled script path\n const { scriptsDir } = await import('@rulemetric/hooks/scripts-dir');\n const scriptPath = join(scriptsDir, `${hookName}.sh`);\n\n if (!existsSync(scriptPath)) {\n this.error(`Hook script not found: ${scriptPath}`);\n }\n\n try {\n // Read stdin and pass it to the bash script\n const stdin = await this.readStdin();\n // APPEND the bundled scripts dir to PATH so the shipped `jq` shim resolves\n // when the host has no real jq (macOS ships none). Appended, not prepended,\n // so a real jq earlier on PATH still wins. Every hook `source`s\n // _normalize.sh, which calls bare `jq` under `set -e` \u2014 without this the\n // whole hooks-capture path silently dies on a jq-less machine.\n const augmentedPath = `${process.env.PATH ?? ''}${delimiter}${scriptsDir}`;\n // session-end reimports the full transcript + enrich/link/cleanup \u2014 it\n // budgets ~17s of network internally, so a 10s cap SIGKILLs it mid-reimport\n // and silently drops the session. Give it headroom; other hooks are quick.\n const timeout = hookName === 'session-end' ? 30_000 : 10_000;\n execFileSync('bash', [scriptPath], {\n input: stdin,\n stdio: ['pipe', 'inherit', 'inherit'],\n timeout,\n env: { ...process.env, PATH: augmentedPath },\n });\n\n // Antigravity-specific: tail the conversation transcript and emit\n // user_message / assistant_response / tool_result events that the\n // bash hook can't see. Antigravity does not fire UserPromptSubmit\n // or Stop hooks, and the Gemini streaming traffic bypasses the\n // proxy. First fire for a conversation primes state to the current\n // transcript end and returns immediately \u2014 capture is forward-only.\n if (\n process.env.RULEMETRIC_HOOK_TOOL === 'antigravity' &&\n hookName === 'post-tool-use'\n ) {\n try {\n const { tailAntigravityTranscript } = await import(\n '../../lib/antigravity-transcript.js'\n );\n await tailAntigravityTranscript(stdin);\n } catch (err) {\n process.stderr.write(\n `[antigravity-tailer] ${(err as Error).message}\\n`,\n );\n }\n }\n } catch (error: unknown) {\n // Hooks should not crash the AI tool \u2014 exit silently\n const code = (error as { status?: number }).status;\n if (code) {\n process.exitCode = code;\n }\n }\n }\n\n private readStdin(): Promise<string> {\n return new Promise((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk) => chunks.push(chunk));\n process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));\n // If stdin is already closed (no piped input), resolve immediately\n if (process.stdin.readableEnded) {\n resolve(Buffer.concat(chunks).toString('utf-8'));\n }\n });\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,MAAM,iBAAiB;AAGhC,IAAM,cAAc,CAAC,iBAAiB,eAAe,eAAe,iBAAiB,oBAAoB;AAEzG,IAAqB,WAArB,MAAqB,kBAAiB,YAAY;AAAA,EAChD,OAAgB,cAAc;AAAA,EAC9B,OAAgB,SAAS;AAAA,EAEzB,OAAgB,OAAO;AAAA,IACrB,MAAM,KAAK,OAAO;AAAA,MAChB,aAAa;AAAA,MAC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