@hasna/hooks 0.0.1 → 0.0.2

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 (62) hide show
  1. package/dist/index.js +366 -0
  2. package/hooks/hook-agentmessages/bin/cli.ts +125 -0
  3. package/package.json +2 -2
  4. package/hooks/hook-agentmessages/src/check-messages.ts +0 -151
  5. package/hooks/hook-agentmessages/src/install.ts +0 -126
  6. package/hooks/hook-agentmessages/src/session-start.ts +0 -255
  7. package/hooks/hook-agentmessages/src/uninstall.ts +0 -89
  8. package/hooks/hook-branchprotect/src/cli.ts +0 -126
  9. package/hooks/hook-branchprotect/src/hook.ts +0 -88
  10. package/hooks/hook-branchprotect/tsconfig.json +0 -25
  11. package/hooks/hook-checkbugs/src/cli.ts +0 -628
  12. package/hooks/hook-checkbugs/src/hook.ts +0 -335
  13. package/hooks/hook-checkbugs/tsconfig.json +0 -15
  14. package/hooks/hook-checkdocs/src/cli.ts +0 -628
  15. package/hooks/hook-checkdocs/src/hook.ts +0 -310
  16. package/hooks/hook-checkdocs/tsconfig.json +0 -15
  17. package/hooks/hook-checkfiles/src/cli.ts +0 -545
  18. package/hooks/hook-checkfiles/src/hook.ts +0 -321
  19. package/hooks/hook-checkfiles/tsconfig.json +0 -15
  20. package/hooks/hook-checklint/src/cli-patch.ts +0 -32
  21. package/hooks/hook-checklint/src/cli.ts +0 -667
  22. package/hooks/hook-checklint/src/hook.ts +0 -473
  23. package/hooks/hook-checklint/tsconfig.json +0 -15
  24. package/hooks/hook-checkpoint/src/cli.ts +0 -191
  25. package/hooks/hook-checkpoint/src/hook.ts +0 -207
  26. package/hooks/hook-checkpoint/tsconfig.json +0 -25
  27. package/hooks/hook-checksecurity/src/cli.ts +0 -601
  28. package/hooks/hook-checksecurity/src/hook.ts +0 -334
  29. package/hooks/hook-checksecurity/tsconfig.json +0 -15
  30. package/hooks/hook-checktasks/src/cli.ts +0 -578
  31. package/hooks/hook-checktasks/src/hook.ts +0 -308
  32. package/hooks/hook-checktasks/tsconfig.json +0 -20
  33. package/hooks/hook-checktests/src/cli.ts +0 -627
  34. package/hooks/hook-checktests/src/hook.ts +0 -334
  35. package/hooks/hook-checktests/tsconfig.json +0 -15
  36. package/hooks/hook-contextrefresh/src/cli.ts +0 -152
  37. package/hooks/hook-contextrefresh/src/hook.ts +0 -148
  38. package/hooks/hook-contextrefresh/tsconfig.json +0 -25
  39. package/hooks/hook-gitguard/src/cli.ts +0 -159
  40. package/hooks/hook-gitguard/src/hook.ts +0 -129
  41. package/hooks/hook-gitguard/tsconfig.json +0 -25
  42. package/hooks/hook-packageage/src/cli.ts +0 -165
  43. package/hooks/hook-packageage/src/hook.ts +0 -177
  44. package/hooks/hook-packageage/tsconfig.json +0 -25
  45. package/hooks/hook-phonenotify/src/cli.ts +0 -196
  46. package/hooks/hook-phonenotify/src/hook.ts +0 -139
  47. package/hooks/hook-phonenotify/tsconfig.json +0 -25
  48. package/hooks/hook-precompact/src/cli.ts +0 -168
  49. package/hooks/hook-precompact/src/hook.ts +0 -122
  50. package/hooks/hook-precompact/tsconfig.json +0 -25
  51. package/src/cli/components/App.tsx +0 -191
  52. package/src/cli/components/CategorySelect.tsx +0 -37
  53. package/src/cli/components/DataTable.tsx +0 -133
  54. package/src/cli/components/Header.tsx +0 -18
  55. package/src/cli/components/HookSelect.tsx +0 -29
  56. package/src/cli/components/InstallProgress.tsx +0 -105
  57. package/src/cli/components/SearchView.tsx +0 -86
  58. package/src/cli/index.tsx +0 -218
  59. package/src/index.ts +0 -31
  60. package/src/lib/installer.ts +0 -288
  61. package/src/lib/registry.ts +0 -205
  62. package/tsconfig.json +0 -17
@@ -1,126 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Install hook-agentmessages into Claude Code settings
4
- *
5
- * Adds hooks to ~/.claude/settings.json:
6
- * - SessionStart: Auto-register agent, project, session
7
- * - Stop: Check for unread messages
8
- */
9
-
10
- import { homedir } from 'os';
11
- import { join } from 'path';
12
-
13
- const CLAUDE_SETTINGS_DIR = join(homedir(), '.claude');
14
- const CLAUDE_SETTINGS_FILE = join(CLAUDE_SETTINGS_DIR, 'settings.json');
15
- const HOOK_DIR = import.meta.dir.replace('/src', '');
16
-
17
- interface HookConfig {
18
- type: 'command';
19
- command: string;
20
- timeout?: number;
21
- }
22
-
23
- interface HookMatcher {
24
- matcher?: string;
25
- hooks: HookConfig[];
26
- }
27
-
28
- interface Settings {
29
- hooks?: {
30
- SessionStart?: HookMatcher[];
31
- Stop?: HookMatcher[];
32
- [key: string]: HookMatcher[] | undefined;
33
- };
34
- [key: string]: unknown;
35
- }
36
-
37
- async function readSettings(): Promise<Settings> {
38
- try {
39
- const file = Bun.file(CLAUDE_SETTINGS_FILE);
40
- if (await file.exists()) {
41
- return await file.json();
42
- }
43
- } catch {}
44
- return {};
45
- }
46
-
47
- async function writeSettings(settings: Settings): Promise<void> {
48
- // Ensure .claude directory exists
49
- await Bun.write(join(CLAUDE_SETTINGS_DIR, '.gitkeep'), '');
50
- await Bun.write(CLAUDE_SETTINGS_FILE, JSON.stringify(settings, null, 2));
51
- }
52
-
53
- function findHookIndex(hooks: HookMatcher[], command: string): number {
54
- return hooks.findIndex(h =>
55
- h.hooks.some(hook => hook.command.includes('hook-agentmessages'))
56
- );
57
- }
58
-
59
- async function main() {
60
- console.log('Installing hook-agentmessages into Claude Code...\n');
61
-
62
- const settings = await readSettings();
63
-
64
- // Initialize hooks object if not exists
65
- if (!settings.hooks) {
66
- settings.hooks = {};
67
- }
68
-
69
- // SessionStart hook
70
- const sessionStartHook: HookMatcher = {
71
- hooks: [
72
- {
73
- type: 'command',
74
- command: `bun ${join(HOOK_DIR, 'src/session-start.ts')}`,
75
- timeout: 10,
76
- },
77
- ],
78
- };
79
-
80
- if (!settings.hooks.SessionStart) {
81
- settings.hooks.SessionStart = [];
82
- }
83
-
84
- // Remove existing hook-agentmessages hooks
85
- const existingSessionStartIdx = findHookIndex(settings.hooks.SessionStart, 'hook-agentmessages');
86
- if (existingSessionStartIdx >= 0) {
87
- settings.hooks.SessionStart.splice(existingSessionStartIdx, 1);
88
- }
89
- settings.hooks.SessionStart.push(sessionStartHook);
90
-
91
- // Stop hook (check messages after each response)
92
- const stopHook: HookMatcher = {
93
- hooks: [
94
- {
95
- type: 'command',
96
- command: `bun ${join(HOOK_DIR, 'src/check-messages.ts')}`,
97
- timeout: 5,
98
- },
99
- ],
100
- };
101
-
102
- if (!settings.hooks.Stop) {
103
- settings.hooks.Stop = [];
104
- }
105
-
106
- const existingStopIdx = findHookIndex(settings.hooks.Stop, 'hook-agentmessages');
107
- if (existingStopIdx >= 0) {
108
- settings.hooks.Stop.splice(existingStopIdx, 1);
109
- }
110
- settings.hooks.Stop.push(stopHook);
111
-
112
- // Write updated settings
113
- await writeSettings(settings);
114
-
115
- console.log('Hooks installed successfully!\n');
116
- console.log('Installed hooks:');
117
- console.log(' - SessionStart: Auto-registers agent, project, and session');
118
- console.log(' - Stop: Checks for unread messages after each response\n');
119
- console.log(`Settings file: ${CLAUDE_SETTINGS_FILE}`);
120
- console.log('\nRestart Claude Code for hooks to take effect.');
121
- }
122
-
123
- main().catch((err) => {
124
- console.error('Installation failed:', err.message);
125
- process.exit(1);
126
- });
@@ -1,255 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * SessionStart hook for service-message
4
- *
5
- * Does NOT auto-generate agents. Agent must be registered via:
6
- * service-message init
7
- *
8
- * Auto-registers project and session if agent exists.
9
- */
10
-
11
- import { homedir } from 'os';
12
- import { join, basename } from 'path';
13
- import { mkdir, appendFile } from 'fs/promises';
14
-
15
- interface HookInput {
16
- session_id?: string;
17
- cwd?: string;
18
- model?: string;
19
- }
20
-
21
- interface Agent {
22
- id: string;
23
- name: string;
24
- createdAt: number;
25
- lastSeen?: number;
26
- }
27
-
28
- interface Project {
29
- id: string;
30
- name: string;
31
- path?: string;
32
- createdAt: number;
33
- }
34
-
35
- interface Session {
36
- id: string;
37
- agentId: string;
38
- projectId: string;
39
- startedAt: number;
40
- }
41
-
42
- interface Config {
43
- agentId?: string;
44
- }
45
-
46
- const SERVICE_DIR = join(homedir(), '.service', 'service-message');
47
-
48
- async function ensureDir(dir: string): Promise<void> {
49
- try {
50
- await mkdir(dir, { recursive: true });
51
- } catch {}
52
- }
53
-
54
- async function readJson<T>(path: string): Promise<T | null> {
55
- try {
56
- const file = Bun.file(path);
57
- if (await file.exists()) {
58
- return await file.json();
59
- }
60
- } catch {}
61
- return null;
62
- }
63
-
64
- async function writeJson(path: string, data: unknown): Promise<void> {
65
- await Bun.write(path, JSON.stringify(data, null, 2));
66
- }
67
-
68
- async function readStdinWithTimeout(timeoutMs: number): Promise<string> {
69
- return new Promise((resolve) => {
70
- const timeout = setTimeout(() => resolve('{}'), timeoutMs);
71
-
72
- let data = '';
73
- process.stdin.setEncoding('utf8');
74
- process.stdin.on('data', (chunk) => {
75
- data += chunk;
76
- });
77
- process.stdin.on('end', () => {
78
- clearTimeout(timeout);
79
- resolve(data || '{}');
80
- });
81
- process.stdin.on('error', () => {
82
- clearTimeout(timeout);
83
- resolve('{}');
84
- });
85
-
86
- if (process.stdin.isTTY) {
87
- clearTimeout(timeout);
88
- resolve('{}');
89
- }
90
- });
91
- }
92
-
93
- /**
94
- * Sanitize ID to prevent path traversal attacks
95
- */
96
- function sanitizeId(id: string): string | null {
97
- if (!id || typeof id !== 'string') return null;
98
- // Only allow alphanumeric, dash, underscore
99
- if (!/^[a-zA-Z0-9_-]+$/.test(id)) return null;
100
- // Reject path traversal attempts
101
- if (id.includes('..') || id.includes('/') || id.includes('\\')) return null;
102
- return id;
103
- }
104
-
105
- /**
106
- * Get existing agent - does NOT create one
107
- */
108
- async function getAgent(): Promise<Agent | null> {
109
- const configPath = join(SERVICE_DIR, 'config.json');
110
- const config = await readJson<Config>(configPath);
111
-
112
- if (!config?.agentId) {
113
- return null;
114
- }
115
-
116
- // Sanitize agentId to prevent path traversal
117
- const safeAgentId = sanitizeId(config.agentId);
118
- if (!safeAgentId) {
119
- return null;
120
- }
121
-
122
- const agentsDir = join(SERVICE_DIR, 'agents');
123
- const agent = await readJson<Agent>(join(agentsDir, `${safeAgentId}.json`));
124
-
125
- if (agent) {
126
- // Verify agent.id matches safeAgentId to prevent tampering
127
- if (agent.id !== safeAgentId) {
128
- return null;
129
- }
130
- // Update lastSeen
131
- agent.lastSeen = Date.now();
132
- await writeJson(join(agentsDir, `${safeAgentId}.json`), agent);
133
- }
134
-
135
- return agent;
136
- }
137
-
138
- function getProjectNameFromPath(projectDir: string): string {
139
- if (projectDir === '/' || projectDir === homedir()) {
140
- return 'root';
141
- }
142
-
143
- const folderName = basename(projectDir);
144
- if (!folderName || folderName === '.' || folderName === '..') {
145
- return 'root';
146
- }
147
-
148
- return folderName;
149
- }
150
-
151
- function normalizeId(name: string): string {
152
- return name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || 'default';
153
- }
154
-
155
- async function getOrCreateProject(projectDir: string): Promise<Project> {
156
- const projectsDir = join(SERVICE_DIR, 'projects');
157
- await ensureDir(projectsDir);
158
-
159
- const projectName = getProjectNameFromPath(projectDir);
160
- const projectId = normalizeId(projectName);
161
-
162
- const existingProject = await readJson<Project>(join(projectsDir, `${projectId}.json`));
163
- if (existingProject) {
164
- if (existingProject.path !== projectDir) {
165
- existingProject.path = projectDir;
166
- await writeJson(join(projectsDir, `${projectId}.json`), existingProject);
167
- }
168
- return existingProject;
169
- }
170
-
171
- const project: Project = {
172
- id: projectId,
173
- name: projectName,
174
- path: projectDir,
175
- createdAt: Date.now(),
176
- };
177
-
178
- await writeJson(join(projectsDir, `${projectId}.json`), project);
179
- return project;
180
- }
181
-
182
- async function startSession(agentId: string, projectId: string, claudeSessionId: string): Promise<Session> {
183
- const sessionsDir = join(SERVICE_DIR, 'sessions');
184
- await ensureDir(sessionsDir);
185
-
186
- const rawSessionId = claudeSessionId || `local-${Date.now()}`;
187
- // Sanitize session ID - only keep alphanumeric chars
188
- const safeSessionId = rawSessionId.replace(/[^a-zA-Z0-9]/g, '').slice(0, 12) || 'default';
189
- const sessionId = `cs-${safeSessionId}`;
190
-
191
- const existingSession = await readJson<Session>(join(sessionsDir, `${sessionId}.json`));
192
- if (existingSession) {
193
- return existingSession;
194
- }
195
-
196
- const session: Session = {
197
- id: sessionId,
198
- agentId,
199
- projectId,
200
- startedAt: Date.now(),
201
- };
202
-
203
- await writeJson(join(sessionsDir, `${sessionId}.json`), session);
204
- return session;
205
- }
206
-
207
- async function main() {
208
- const stdinData = await readStdinWithTimeout(2000);
209
-
210
- let input: HookInput = {};
211
- try {
212
- input = JSON.parse(stdinData);
213
- } catch {}
214
-
215
- const sessionId = input.session_id || `local-${Date.now()}`;
216
- const cwd = input.cwd || process.cwd();
217
- const projectDir = process.env.CLAUDE_PROJECT_DIR || cwd;
218
- const envFile = process.env.CLAUDE_ENV_FILE;
219
-
220
- await ensureDir(SERVICE_DIR);
221
-
222
- // Get existing agent - do NOT create one
223
- const agent = await getAgent();
224
-
225
- if (!agent) {
226
- // No agent configured - silently continue without setting env vars
227
- // User needs to run: service-message init
228
- console.log(JSON.stringify({ continue: true }));
229
- return;
230
- }
231
-
232
- // Auto-register project and session
233
- const project = await getOrCreateProject(projectDir);
234
- const session = await startSession(agent.id, project.id, sessionId);
235
-
236
- if (envFile) {
237
- try {
238
- // Escape values to prevent shell injection
239
- const escapeShellValue = (val: string) => val.replace(/[`$"\\]/g, '\\$&');
240
- const envContent = [
241
- `export SMSG_AGENT_ID="${escapeShellValue(agent.id)}"`,
242
- `export SMSG_SESSION_ID="${escapeShellValue(session.id)}"`,
243
- `export SMSG_PROJECT_ID="${escapeShellValue(project.id)}"`,
244
- ].join('\n') + '\n';
245
- await appendFile(envFile, envContent);
246
- } catch {}
247
- }
248
-
249
- console.log(JSON.stringify({ continue: true }));
250
- }
251
-
252
- main().catch(() => {
253
- console.log(JSON.stringify({ continue: true }));
254
- process.exit(0);
255
- });
@@ -1,89 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Uninstall hook-agentmessages from Claude Code settings
4
- */
5
-
6
- import { homedir } from 'os';
7
- import { join } from 'path';
8
-
9
- const CLAUDE_SETTINGS_FILE = join(homedir(), '.claude', 'settings.json');
10
-
11
- interface HookConfig {
12
- type: 'command';
13
- command: string;
14
- }
15
-
16
- interface HookMatcher {
17
- matcher?: string;
18
- hooks: HookConfig[];
19
- }
20
-
21
- interface Settings {
22
- hooks?: {
23
- [key: string]: HookMatcher[] | undefined;
24
- };
25
- [key: string]: unknown;
26
- }
27
-
28
- async function readSettings(): Promise<Settings> {
29
- try {
30
- const file = Bun.file(CLAUDE_SETTINGS_FILE);
31
- if (await file.exists()) {
32
- return await file.json();
33
- }
34
- } catch {}
35
- return {};
36
- }
37
-
38
- async function writeSettings(settings: Settings): Promise<void> {
39
- await Bun.write(CLAUDE_SETTINGS_FILE, JSON.stringify(settings, null, 2));
40
- }
41
-
42
- function removeHookMessageHooks(hooks: HookMatcher[]): HookMatcher[] {
43
- return hooks.filter(h =>
44
- !h.hooks.some(hook => hook.command.includes('hook-agentmessages'))
45
- );
46
- }
47
-
48
- async function main() {
49
- console.log('Uninstalling hook-agentmessages from Claude Code...\n');
50
-
51
- const settings = await readSettings();
52
-
53
- if (!settings.hooks) {
54
- console.log('No hooks found. Nothing to uninstall.');
55
- return;
56
- }
57
-
58
- let removed = 0;
59
-
60
- // Remove from all hook events
61
- for (const eventName of Object.keys(settings.hooks)) {
62
- const hooks = settings.hooks[eventName];
63
- if (hooks && Array.isArray(hooks)) {
64
- const before = hooks.length;
65
- settings.hooks[eventName] = removeHookMessageHooks(hooks);
66
- removed += before - settings.hooks[eventName]!.length;
67
-
68
- // Remove empty arrays
69
- if (settings.hooks[eventName]!.length === 0) {
70
- delete settings.hooks[eventName];
71
- }
72
- }
73
- }
74
-
75
- // Remove empty hooks object
76
- if (Object.keys(settings.hooks).length === 0) {
77
- delete settings.hooks;
78
- }
79
-
80
- await writeSettings(settings);
81
-
82
- console.log(`Removed ${removed} hook(s).`);
83
- console.log('\nRestart Claude Code for changes to take effect.');
84
- }
85
-
86
- main().catch((err) => {
87
- console.error('Uninstall failed:', err.message);
88
- process.exit(1);
89
- });
@@ -1,126 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- /**
4
- * CLI for hook-branchprotect
5
- */
6
-
7
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
8
- import { join } from "path";
9
- import { homedir } from "os";
10
-
11
- const HOOK_NAME = "hook-branchprotect";
12
- const SETTINGS_PATH = join(homedir(), ".claude", "settings.json");
13
-
14
- interface ClaudeSettings {
15
- hooks?: {
16
- PreToolUse?: Array<{
17
- matcher: string;
18
- hooks: Array<{ type: "command"; command: string }>;
19
- }>;
20
- };
21
- [key: string]: unknown;
22
- }
23
-
24
- function readSettings(): ClaudeSettings {
25
- try {
26
- if (existsSync(SETTINGS_PATH)) {
27
- return JSON.parse(readFileSync(SETTINGS_PATH, "utf-8"));
28
- }
29
- } catch {}
30
- return {};
31
- }
32
-
33
- function writeSettings(settings: ClaudeSettings): void {
34
- const dir = join(homedir(), ".claude");
35
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
36
- writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
37
- }
38
-
39
- function install(): void {
40
- const settings = readSettings();
41
- if (!settings.hooks) settings.hooks = {};
42
- if (!settings.hooks.PreToolUse) settings.hooks.PreToolUse = [];
43
-
44
- const existing = settings.hooks.PreToolUse.find((h) =>
45
- h.hooks.some((hook) => hook.command.includes(HOOK_NAME))
46
- );
47
-
48
- if (existing) {
49
- console.log(`${HOOK_NAME} is already installed`);
50
- return;
51
- }
52
-
53
- settings.hooks.PreToolUse.push({
54
- matcher: "Write|Edit|NotebookEdit",
55
- hooks: [{ type: "command", command: `bunx @hasnaxyz/${HOOK_NAME}` }],
56
- });
57
-
58
- writeSettings(settings);
59
- console.log(`${HOOK_NAME} installed successfully`);
60
- console.log("Hook will prevent file modifications on main/master branch");
61
- }
62
-
63
- function uninstall(): void {
64
- const settings = readSettings();
65
- if (!settings.hooks?.PreToolUse) {
66
- console.log(`${HOOK_NAME} is not installed`);
67
- return;
68
- }
69
-
70
- const before = settings.hooks.PreToolUse.length;
71
- settings.hooks.PreToolUse = settings.hooks.PreToolUse.filter(
72
- (h) => !h.hooks.some((hook) => hook.command.includes(HOOK_NAME))
73
- );
74
-
75
- if (before === settings.hooks.PreToolUse.length) {
76
- console.log(`${HOOK_NAME} is not installed`);
77
- return;
78
- }
79
-
80
- writeSettings(settings);
81
- console.log(`${HOOK_NAME} uninstalled successfully`);
82
- }
83
-
84
- function status(): void {
85
- const settings = readSettings();
86
- const installed = settings.hooks?.PreToolUse?.some((h) =>
87
- h.hooks.some((hook) => hook.command.includes(HOOK_NAME))
88
- );
89
- console.log(`${HOOK_NAME} is ${installed ? "installed" : "not installed"}`);
90
- }
91
-
92
- function help(): void {
93
- console.log(`
94
- ${HOOK_NAME} - Prevent file modifications on protected branches
95
-
96
- Usage: ${HOOK_NAME} <command>
97
-
98
- Commands:
99
- install Install hook to Claude Code settings
100
- uninstall Remove hook from Claude Code settings
101
- status Check if hook is installed
102
- help Show this help message
103
-
104
- Protected branches: main, master
105
- Blocked tools: Write, Edit, NotebookEdit
106
- `);
107
- }
108
-
109
- const command = process.argv[2];
110
-
111
- switch (command) {
112
- case "install": install(); break;
113
- case "uninstall": uninstall(); break;
114
- case "status": status(); break;
115
- case "help":
116
- case "--help":
117
- case "-h": help(); break;
118
- default:
119
- if (!command) {
120
- import("./hook.ts").then((m) => m.run());
121
- } else {
122
- console.error(`Unknown command: ${command}`);
123
- help();
124
- process.exit(1);
125
- }
126
- }
@@ -1,88 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- /**
4
- * Claude Code Hook: branchprotect
5
- *
6
- * PreToolUse hook that prevents file modifications (Write/Edit) when
7
- * the current git branch is main or master. Forces feature branch workflow.
8
- */
9
-
10
- import { readFileSync } from "fs";
11
- import { execSync } from "child_process";
12
-
13
- interface HookInput {
14
- session_id: string;
15
- cwd: string;
16
- tool_name: string;
17
- tool_input: Record<string, unknown>;
18
- }
19
-
20
- interface HookOutput {
21
- decision?: "approve" | "block";
22
- reason?: string;
23
- }
24
-
25
- const PROTECTED_BRANCHES = ["main", "master"];
26
- const FILE_MODIFYING_TOOLS = ["Write", "Edit", "NotebookEdit"];
27
-
28
- function readStdinJson(): HookInput | null {
29
- try {
30
- const input = readFileSync(0, "utf-8").trim();
31
- if (!input) return null;
32
- return JSON.parse(input);
33
- } catch {
34
- return null;
35
- }
36
- }
37
-
38
- function getCurrentBranch(cwd: string): string | null {
39
- try {
40
- return execSync("git rev-parse --abbrev-ref HEAD", {
41
- cwd,
42
- encoding: "utf-8",
43
- stdio: ["pipe", "pipe", "pipe"],
44
- }).trim();
45
- } catch {
46
- return null;
47
- }
48
- }
49
-
50
- function respond(output: HookOutput): void {
51
- console.log(JSON.stringify(output));
52
- }
53
-
54
- export function run(): void {
55
- const input = readStdinJson();
56
-
57
- if (!input) {
58
- respond({ decision: "approve" });
59
- return;
60
- }
61
-
62
- // Only check file-modifying tools
63
- if (!FILE_MODIFYING_TOOLS.includes(input.tool_name)) {
64
- respond({ decision: "approve" });
65
- return;
66
- }
67
-
68
- const branch = getCurrentBranch(input.cwd);
69
-
70
- if (!branch) {
71
- // Not a git repo — allow
72
- respond({ decision: "approve" });
73
- return;
74
- }
75
-
76
- if (PROTECTED_BRANCHES.includes(branch)) {
77
- const reason = `Blocked: cannot modify files on '${branch}' branch. Create a feature branch first (git checkout -b feat/your-change).`;
78
- console.error(`[hook-branchprotect] ${reason}`);
79
- respond({ decision: "block", reason });
80
- return;
81
- }
82
-
83
- respond({ decision: "approve" });
84
- }
85
-
86
- if (import.meta.main) {
87
- run();
88
- }
@@ -1,25 +0,0 @@
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
- }