@hasna/hooks 0.2.6 → 0.2.8

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 (49) hide show
  1. package/bin/index.js +645 -43
  2. package/dist/index.js +89 -5
  3. package/hooks/hook-affected-tests/LICENSE +191 -0
  4. package/hooks/hook-affected-tests/README.md +37 -0
  5. package/hooks/hook-affected-tests/package.json +50 -0
  6. package/hooks/hook-affected-tests/src/hook.ts +148 -0
  7. package/hooks/hook-affected-tests/tsconfig.json +25 -0
  8. package/hooks/hook-agentmessages/bin/cli.ts +125 -0
  9. package/hooks/hook-announce-start/LICENSE +191 -0
  10. package/hooks/hook-announce-start/README.md +35 -0
  11. package/hooks/hook-announce-start/package.json +51 -0
  12. package/hooks/hook-announce-start/src/hook.ts +137 -0
  13. package/hooks/hook-announce-start/tsconfig.json +25 -0
  14. package/hooks/hook-announce-stop/LICENSE +191 -0
  15. package/hooks/hook-announce-stop/README.md +35 -0
  16. package/hooks/hook-announce-stop/package.json +51 -0
  17. package/hooks/hook-announce-stop/src/hook.ts +160 -0
  18. package/hooks/hook-announce-stop/tsconfig.json +25 -0
  19. package/hooks/hook-checkdocs/bun.lock +25 -0
  20. package/hooks/hook-commandlog/src/hook.ts +15 -38
  21. package/hooks/hook-conflict-detect/LICENSE +191 -0
  22. package/hooks/hook-conflict-detect/README.md +38 -0
  23. package/hooks/hook-conflict-detect/package.json +50 -0
  24. package/hooks/hook-conflict-detect/src/hook.ts +116 -0
  25. package/hooks/hook-conflict-detect/tsconfig.json +25 -0
  26. package/hooks/hook-costwatch/src/hook.ts +39 -42
  27. package/hooks/hook-dm-inject/LICENSE +191 -0
  28. package/hooks/hook-dm-inject/README.md +42 -0
  29. package/hooks/hook-dm-inject/package.json +51 -0
  30. package/hooks/hook-dm-inject/src/hook.ts +115 -0
  31. package/hooks/hook-dm-inject/tsconfig.json +25 -0
  32. package/hooks/hook-errornotify/src/hook.ts +20 -65
  33. package/hooks/hook-failure-to-task/LICENSE +191 -0
  34. package/hooks/hook-failure-to-task/README.md +40 -0
  35. package/hooks/hook-failure-to-task/package.json +51 -0
  36. package/hooks/hook-failure-to-task/src/hook.ts +171 -0
  37. package/hooks/hook-failure-to-task/tsconfig.json +25 -0
  38. package/hooks/hook-filelock/LICENSE +191 -0
  39. package/hooks/hook-filelock/README.md +44 -0
  40. package/hooks/hook-filelock/package.json +50 -0
  41. package/hooks/hook-filelock/src/hook.ts +147 -0
  42. package/hooks/hook-filelock/tsconfig.json +25 -0
  43. package/hooks/hook-sessionlog/src/hook.ts +11 -52
  44. package/hooks/hook-typecheck-gate/LICENSE +191 -0
  45. package/hooks/hook-typecheck-gate/README.md +46 -0
  46. package/hooks/hook-typecheck-gate/package.json +50 -0
  47. package/hooks/hook-typecheck-gate/src/hook.ts +152 -0
  48. package/hooks/hook-typecheck-gate/tsconfig.json +25 -0
  49. package/package.json +1 -1
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 Hasna
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,38 @@
1
+ # hook-conflict-detect
2
+
3
+ A PreToolUse hook that checks for unresolved git merge conflict markers before editing files. Prevents editing files mid-conflict and making things worse.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ hooks install conflict-detect
9
+ ```
10
+
11
+ ## How it works
12
+
13
+ Before every `Edit` or `Write`:
14
+ 1. Reads the target file
15
+ 2. Checks for all three conflict markers: `<<<<<<<`, `=======`, `>>>>>>>`
16
+ 3. If all three are present → blocks the edit with a helpful message
17
+ 4. Otherwise → approves normally
18
+
19
+ ## Example block message
20
+
21
+ ```
22
+ File 'auth.ts' contains unresolved git merge conflicts. Resolve them before editing:
23
+
24
+ <<<<<<< HEAD
25
+ const user = await getUser(id);
26
+ =======
27
+ >>>>>>> feature/new-auth
28
+
29
+ Run `git diff auth.ts` to see the full conflict.
30
+ ```
31
+
32
+ ## Why all three markers?
33
+
34
+ The hook requires all three markers to be present to avoid false positives on files that legitimately use `<` or `>` characters.
35
+
36
+ ## Event
37
+
38
+ - **PreToolUse** (matcher: `Edit|Write`)
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@hasna/hook-conflict-detect",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code hook that blocks edits on files with unresolved git merge conflict markers",
5
+ "type": "module",
6
+ "main": "./dist/hook.js",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/hook.js",
10
+ "types": "./dist/hook.d.ts"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "build": "bun build ./src/hook.ts --outdir ./dist --target node",
19
+ "prepublishOnly": "bun run build",
20
+ "typecheck": "tsc --noEmit"
21
+ },
22
+ "keywords": [
23
+ "claude-code",
24
+ "claude",
25
+ "hook",
26
+ "git",
27
+ "conflicts",
28
+ "merge",
29
+ "safety"
30
+ ],
31
+ "author": "Hasna",
32
+ "license": "Apache-2.0",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/hasna/hooks.git"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org/"
40
+ },
41
+ "engines": {
42
+ "node": ">=18",
43
+ "bun": ">=1.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/bun": "^1.3.8",
47
+ "@types/node": "^20",
48
+ "typescript": "^5.0.0"
49
+ }
50
+ }
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * Claude Code Hook: conflict-detect
5
+ *
6
+ * PreToolUse hook that checks for git merge conflict markers before editing files.
7
+ * Blocks edits on files that contain unresolved conflicts (<<<<<<, =======, >>>>>>>).
8
+ */
9
+
10
+ import { readFileSync, existsSync } from "fs";
11
+ import { basename } from "path";
12
+ import { execSync } from "child_process";
13
+
14
+ interface HookInput {
15
+ session_id: string;
16
+ cwd: string;
17
+ tool_name: string;
18
+ tool_input: Record<string, unknown>;
19
+ }
20
+
21
+ interface HookOutput {
22
+ decision: "approve" | "block";
23
+ reason?: string;
24
+ }
25
+
26
+ // Git conflict marker patterns
27
+ const CONFLICT_MARKERS = [
28
+ /^<{7}\s/m, // <<<<<<< HEAD
29
+ /^={7}$/m, // =======
30
+ /^>{7}\s/m, // >>>>>>> branch
31
+ ];
32
+
33
+ function readStdinJson(): HookInput | null {
34
+ try {
35
+ const input = readFileSync(0, "utf-8").trim();
36
+ if (!input) return null;
37
+ return JSON.parse(input);
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function respond(output: HookOutput): void {
44
+ console.log(JSON.stringify(output));
45
+ }
46
+
47
+ function hasConflictMarkers(filePath: string): { found: boolean; lines: string[] } {
48
+ try {
49
+ if (!existsSync(filePath)) return { found: false, lines: [] };
50
+
51
+ const content = readFileSync(filePath, "utf-8");
52
+ const hasConflicts = CONFLICT_MARKERS.every((pattern) => pattern.test(content));
53
+
54
+ if (!hasConflicts) return { found: false, lines: [] };
55
+
56
+ // Extract lines with conflict markers for the reason message
57
+ const conflictLines = content
58
+ .split("\n")
59
+ .filter((line) => /^(<{7}|={7}|>{7})/.test(line))
60
+ .slice(0, 6);
61
+
62
+ return { found: true, lines: conflictLines };
63
+ } catch {
64
+ return { found: false, lines: [] };
65
+ }
66
+ }
67
+
68
+ function isTrackedByGit(filePath: string, cwd: string): boolean {
69
+ try {
70
+ execSync(`git ls-files --error-unmatch "${filePath}"`, {
71
+ cwd,
72
+ stdio: ["pipe", "pipe", "pipe"],
73
+ timeout: 5_000,
74
+ });
75
+ return true;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ export function run(): void {
82
+ const input = readStdinJson();
83
+
84
+ if (!input) {
85
+ respond({ decision: "approve" });
86
+ return;
87
+ }
88
+
89
+ const filePath = input.tool_input?.file_path as string | undefined;
90
+
91
+ if (!filePath || typeof filePath !== "string") {
92
+ respond({ decision: "approve" });
93
+ return;
94
+ }
95
+
96
+ const { found, lines } = hasConflictMarkers(filePath);
97
+
98
+ if (!found) {
99
+ respond({ decision: "approve" });
100
+ return;
101
+ }
102
+
103
+ const name = basename(filePath);
104
+ const markerPreview = lines.join("\n");
105
+
106
+ console.error(`[hook-conflict-detect] Conflict markers found in ${name} — blocking edit`);
107
+
108
+ respond({
109
+ decision: "block",
110
+ reason: `File '${name}' contains unresolved git merge conflicts. Resolve them before editing:\n\n${markerPreview}\n\nRun \`git diff ${name}\` to see the full conflict.`,
111
+ });
112
+ }
113
+
114
+ if (import.meta.main) {
115
+ run();
116
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "lib": ["ESNext"],
6
+ "moduleResolution": "bundler",
7
+ "allowImportingTsExtensions": true,
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "skipLibCheck": true,
11
+ "forceConsistentCasingInFileNames": true,
12
+ "resolveJsonModule": true,
13
+ "isolatedModules": true,
14
+ "noEmit": true,
15
+ "noUnusedLocals": true,
16
+ "noUnusedParameters": true,
17
+ "declaration": true,
18
+ "declarationMap": true,
19
+ "outDir": "./dist",
20
+ "rootDir": "./src",
21
+ "types": ["bun-types"]
22
+ },
23
+ "include": ["src/**/*"],
24
+ "exclude": ["node_modules", "dist"]
25
+ }
@@ -3,24 +3,19 @@
3
3
  /**
4
4
  * Claude Code Hook: costwatch
5
5
  *
6
- * Stop hook that estimates session token usage and warns if a budget
7
- * threshold is exceeded.
6
+ * Stop hook that estimates session token usage and persists cost data to
7
+ * SQLite (~/.hooks/hooks.db) for cross-session history queries.
8
8
  *
9
9
  * Configuration:
10
10
  * - Environment variable: COST_WATCH_BUDGET (max $ per session, e.g. "5.00")
11
11
  * - If not set, no budget enforcement (just logs a reminder)
12
12
  *
13
- * Token estimation is rough:
14
- * - ~4 characters per token (English text average)
15
- * - Claude Opus pricing: ~$15/M input tokens, ~$75/M output tokens
16
- * - We estimate a blended rate of ~$30/M tokens for simplicity
17
- *
18
- * Since the Stop event provides limited session info, this hook
19
- * primarily serves as a reminder to check actual usage.
13
+ * Token estimation: ~4 chars/token, blended rate ~$30/M tokens.
20
14
  */
21
15
 
22
16
  import { readFileSync, existsSync, readdirSync, statSync } from "fs";
23
17
  import { join } from "path";
18
+ import { writeHookEvent } from "../../../src/lib/db-writer";
24
19
 
25
20
  interface HookInput {
26
21
  session_id: string;
@@ -33,10 +28,7 @@ interface HookOutput {
33
28
  continue: boolean;
34
29
  }
35
30
 
36
- /** Approximate cost per million tokens (blended input/output estimate) */
37
31
  const BLENDED_COST_PER_MILLION_TOKENS = 30;
38
-
39
- /** Average characters per token */
40
32
  const CHARS_PER_TOKEN = 4;
41
33
 
42
34
  function readStdinJson(): HookInput | null {
@@ -59,8 +51,8 @@ function getBudget(): number | null {
59
51
 
60
52
  const budget = parseFloat(budgetStr);
61
53
  if (isNaN(budget) || budget <= 0) {
62
- console.error(
63
- `[hook-costwatch] Invalid COST_WATCH_BUDGET value: "${budgetStr}". Must be a positive number.`
54
+ process.stderr.write(
55
+ `[hook-costwatch] Invalid COST_WATCH_BUDGET value: "${budgetStr}". Must be a positive number.\n`
64
56
  );
65
57
  return null;
66
58
  }
@@ -74,12 +66,10 @@ function estimateTranscriptCost(transcriptPath: string): {
74
66
  } | null {
75
67
  try {
76
68
  if (!existsSync(transcriptPath)) return null;
77
-
78
69
  const stat = statSync(transcriptPath);
79
70
  const charCount = stat.size;
80
71
  const estimatedTokens = Math.ceil(charCount / CHARS_PER_TOKEN);
81
72
  const estimatedCost = (estimatedTokens / 1_000_000) * BLENDED_COST_PER_MILLION_TOKENS;
82
-
83
73
  return { charCount, estimatedTokens, estimatedCost };
84
74
  } catch {
85
75
  return null;
@@ -87,7 +77,6 @@ function estimateTranscriptCost(transcriptPath: string): {
87
77
  }
88
78
 
89
79
  function findSessionTranscript(cwd: string, sessionId: string): string | null {
90
- // Check common transcript locations
91
80
  const possibleDirs = [
92
81
  join(cwd, ".claude"),
93
82
  join(process.env.HOME || "", ".claude", "projects"),
@@ -98,9 +87,8 @@ function findSessionTranscript(cwd: string, sessionId: string): string | null {
98
87
  try {
99
88
  const files = readdirSync(dir, { recursive: true }) as string[];
100
89
  for (const file of files) {
101
- const filePath = join(dir, file);
102
90
  if (typeof file === "string" && file.includes(sessionId)) {
103
- return filePath;
91
+ return join(dir, file);
104
92
  }
105
93
  }
106
94
  } catch {
@@ -121,19 +109,13 @@ export function run(): void {
121
109
 
122
110
  const budget = getBudget();
123
111
 
124
- // Try to estimate cost from transcript
125
- let estimate: {
126
- charCount: number;
127
- estimatedTokens: number;
128
- estimatedCost: number;
129
- } | null = null;
112
+ let estimate: { charCount: number; estimatedTokens: number; estimatedCost: number } | null = null;
130
113
 
131
114
  if (input.transcript_path) {
132
115
  estimate = estimateTranscriptCost(input.transcript_path);
133
116
  }
134
117
 
135
118
  if (!estimate) {
136
- // Try to find transcript by session ID
137
119
  const transcriptPath = findSessionTranscript(input.cwd, input.session_id);
138
120
  if (transcriptPath) {
139
121
  estimate = estimateTranscriptCost(transcriptPath);
@@ -143,31 +125,46 @@ export function run(): void {
143
125
  if (estimate) {
144
126
  const costStr = estimate.estimatedCost.toFixed(2);
145
127
  const tokensStr = (estimate.estimatedTokens / 1000).toFixed(1);
128
+ const budgetExceeded = budget !== null && estimate.estimatedCost > budget;
146
129
 
147
- console.error(`[hook-costwatch] Session estimate: ~${tokensStr}K tokens, ~$${costStr}`);
130
+ process.stderr.write(`[hook-costwatch] Session estimate: ~${tokensStr}K tokens, ~$${costStr}\n`);
148
131
 
149
- if (budget !== null && estimate.estimatedCost > budget) {
150
- console.error(
151
- `[hook-costwatch] WARNING: Estimated cost ($${costStr}) exceeds budget ($${budget.toFixed(2)})!`
152
- );
153
- console.error(
154
- `[hook-costwatch] Check your actual usage at https://console.anthropic.com/`
132
+ if (budgetExceeded) {
133
+ process.stderr.write(
134
+ `[hook-costwatch] WARNING: Estimated cost ($${costStr}) exceeds budget ($${budget!.toFixed(2)})!\n`
155
135
  );
136
+ process.stderr.write(`[hook-costwatch] Check your actual usage at https://console.anthropic.com/\n`);
156
137
  }
138
+
139
+ writeHookEvent({
140
+ session_id: input.session_id,
141
+ hook_name: "costwatch",
142
+ event_type: "Stop",
143
+ project_dir: input.cwd,
144
+ metadata: JSON.stringify({
145
+ char_count: estimate.charCount,
146
+ estimated_tokens: estimate.estimatedTokens,
147
+ estimated_cost_usd: estimate.estimatedCost,
148
+ budget_usd: budget,
149
+ budget_exceeded: budgetExceeded,
150
+ }),
151
+ });
157
152
  } else {
158
- console.error(
159
- `[hook-costwatch] Could not estimate session cost (no transcript found).`
160
- );
153
+ process.stderr.write(`[hook-costwatch] Could not estimate session cost (no transcript found).\n`);
154
+
155
+ writeHookEvent({
156
+ session_id: input.session_id,
157
+ hook_name: "costwatch",
158
+ event_type: "Stop",
159
+ project_dir: input.cwd,
160
+ metadata: JSON.stringify({ error: "no_transcript", budget_usd: budget }),
161
+ });
161
162
  }
162
163
 
163
164
  if (budget !== null) {
164
- console.error(
165
- `[hook-costwatch] Budget: $${budget.toFixed(2)}/session. Remember to check actual usage.`
166
- );
165
+ process.stderr.write(`[hook-costwatch] Budget: $${budget.toFixed(2)}/session. Remember to check actual usage.\n`);
167
166
  } else {
168
- console.error(
169
- `[hook-costwatch] No budget set. Set COST_WATCH_BUDGET env var to enable budget warnings.`
170
- );
167
+ process.stderr.write(`[hook-costwatch] No budget set. Set COST_WATCH_BUDGET env var to enable budget warnings.\n`);
171
168
  }
172
169
 
173
170
  respond({ continue: true });