@hasna/hooks 0.0.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 (110) hide show
  1. package/.npmrc.example +2 -0
  2. package/AGENTS.md +54 -0
  3. package/CLAUDE.md +70 -0
  4. package/CONTRIBUTING.md +45 -0
  5. package/README.md +232 -0
  6. package/bin/index.js +5171 -0
  7. package/hooks/hook-agentmessages/CLAUDE.md +79 -0
  8. package/hooks/hook-agentmessages/LICENSE +21 -0
  9. package/hooks/hook-agentmessages/README.md +107 -0
  10. package/hooks/hook-agentmessages/package.json +31 -0
  11. package/hooks/hook-agentmessages/src/check-messages.ts +151 -0
  12. package/hooks/hook-agentmessages/src/install.ts +126 -0
  13. package/hooks/hook-agentmessages/src/session-start.ts +255 -0
  14. package/hooks/hook-agentmessages/src/uninstall.ts +89 -0
  15. package/hooks/hook-branchprotect/CLAUDE.md +23 -0
  16. package/hooks/hook-branchprotect/README.md +25 -0
  17. package/hooks/hook-branchprotect/package.json +42 -0
  18. package/hooks/hook-branchprotect/src/cli.ts +126 -0
  19. package/hooks/hook-branchprotect/src/hook.ts +88 -0
  20. package/hooks/hook-branchprotect/tsconfig.json +25 -0
  21. package/hooks/hook-checkbugs/LICENSE +21 -0
  22. package/hooks/hook-checkbugs/README.md +140 -0
  23. package/hooks/hook-checkbugs/package.json +58 -0
  24. package/hooks/hook-checkbugs/src/cli.ts +628 -0
  25. package/hooks/hook-checkbugs/src/hook.ts +335 -0
  26. package/hooks/hook-checkbugs/tsconfig.json +15 -0
  27. package/hooks/hook-checkdocs/README.md +137 -0
  28. package/hooks/hook-checkdocs/package.json +57 -0
  29. package/hooks/hook-checkdocs/src/cli.ts +628 -0
  30. package/hooks/hook-checkdocs/src/hook.ts +310 -0
  31. package/hooks/hook-checkdocs/tsconfig.json +15 -0
  32. package/hooks/hook-checkfiles/LICENSE +21 -0
  33. package/hooks/hook-checkfiles/README.md +141 -0
  34. package/hooks/hook-checkfiles/package.json +56 -0
  35. package/hooks/hook-checkfiles/src/cli.ts +545 -0
  36. package/hooks/hook-checkfiles/src/hook.ts +321 -0
  37. package/hooks/hook-checkfiles/tsconfig.json +15 -0
  38. package/hooks/hook-checklint/LICENSE +21 -0
  39. package/hooks/hook-checklint/README.md +147 -0
  40. package/hooks/hook-checklint/package.json +57 -0
  41. package/hooks/hook-checklint/src/cli-patch.ts +32 -0
  42. package/hooks/hook-checklint/src/cli.ts +667 -0
  43. package/hooks/hook-checklint/src/hook.ts +473 -0
  44. package/hooks/hook-checklint/tsconfig.json +15 -0
  45. package/hooks/hook-checkpoint/CLAUDE.md +23 -0
  46. package/hooks/hook-checkpoint/README.md +37 -0
  47. package/hooks/hook-checkpoint/package.json +58 -0
  48. package/hooks/hook-checkpoint/src/cli.ts +191 -0
  49. package/hooks/hook-checkpoint/src/hook.ts +207 -0
  50. package/hooks/hook-checkpoint/tsconfig.json +25 -0
  51. package/hooks/hook-checksecurity/LICENSE +21 -0
  52. package/hooks/hook-checksecurity/README.md +158 -0
  53. package/hooks/hook-checksecurity/package.json +57 -0
  54. package/hooks/hook-checksecurity/src/cli.ts +601 -0
  55. package/hooks/hook-checksecurity/src/hook.ts +334 -0
  56. package/hooks/hook-checksecurity/tsconfig.json +15 -0
  57. package/hooks/hook-checktasks/README.md +144 -0
  58. package/hooks/hook-checktasks/package.json +55 -0
  59. package/hooks/hook-checktasks/src/cli.ts +578 -0
  60. package/hooks/hook-checktasks/src/hook.ts +308 -0
  61. package/hooks/hook-checktasks/tsconfig.json +20 -0
  62. package/hooks/hook-checktests/LICENSE +21 -0
  63. package/hooks/hook-checktests/README.md +137 -0
  64. package/hooks/hook-checktests/package.json +57 -0
  65. package/hooks/hook-checktests/src/cli.ts +627 -0
  66. package/hooks/hook-checktests/src/hook.ts +334 -0
  67. package/hooks/hook-checktests/tsconfig.json +15 -0
  68. package/hooks/hook-contextrefresh/CLAUDE.md +23 -0
  69. package/hooks/hook-contextrefresh/README.md +42 -0
  70. package/hooks/hook-contextrefresh/package.json +42 -0
  71. package/hooks/hook-contextrefresh/src/cli.ts +152 -0
  72. package/hooks/hook-contextrefresh/src/hook.ts +148 -0
  73. package/hooks/hook-contextrefresh/tsconfig.json +25 -0
  74. package/hooks/hook-gitguard/CLAUDE.md +22 -0
  75. package/hooks/hook-gitguard/README.md +30 -0
  76. package/hooks/hook-gitguard/package.json +57 -0
  77. package/hooks/hook-gitguard/src/cli.ts +159 -0
  78. package/hooks/hook-gitguard/src/hook.ts +129 -0
  79. package/hooks/hook-gitguard/tsconfig.json +25 -0
  80. package/hooks/hook-packageage/CLAUDE.md +23 -0
  81. package/hooks/hook-packageage/README.md +33 -0
  82. package/hooks/hook-packageage/package.json +42 -0
  83. package/hooks/hook-packageage/src/cli.ts +165 -0
  84. package/hooks/hook-packageage/src/hook.ts +177 -0
  85. package/hooks/hook-packageage/tsconfig.json +25 -0
  86. package/hooks/hook-phonenotify/CLAUDE.md +25 -0
  87. package/hooks/hook-phonenotify/README.md +44 -0
  88. package/hooks/hook-phonenotify/package.json +42 -0
  89. package/hooks/hook-phonenotify/src/cli.ts +196 -0
  90. package/hooks/hook-phonenotify/src/hook.ts +139 -0
  91. package/hooks/hook-phonenotify/tsconfig.json +25 -0
  92. package/hooks/hook-precompact/CLAUDE.md +23 -0
  93. package/hooks/hook-precompact/README.md +36 -0
  94. package/hooks/hook-precompact/package.json +42 -0
  95. package/hooks/hook-precompact/src/cli.ts +168 -0
  96. package/hooks/hook-precompact/src/hook.ts +122 -0
  97. package/hooks/hook-precompact/tsconfig.json +25 -0
  98. package/package.json +61 -0
  99. package/src/cli/components/App.tsx +191 -0
  100. package/src/cli/components/CategorySelect.tsx +37 -0
  101. package/src/cli/components/DataTable.tsx +133 -0
  102. package/src/cli/components/Header.tsx +18 -0
  103. package/src/cli/components/HookSelect.tsx +29 -0
  104. package/src/cli/components/InstallProgress.tsx +105 -0
  105. package/src/cli/components/SearchView.tsx +86 -0
  106. package/src/cli/index.tsx +218 -0
  107. package/src/index.ts +31 -0
  108. package/src/lib/installer.ts +288 -0
  109. package/src/lib/registry.ts +205 -0
  110. package/tsconfig.json +17 -0
@@ -0,0 +1,255 @@
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
+ });
@@ -0,0 +1,89 @@
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
+ });
@@ -0,0 +1,23 @@
1
+ # CLAUDE.md
2
+
3
+ ## hook-branchprotect
4
+
5
+ A PreToolUse hook that prevents file modifications on protected branches (main/master).
6
+
7
+ ### Key Files
8
+
9
+ | File | Purpose |
10
+ |------|---------|
11
+ | `src/hook.ts` | Main hook logic — checks current branch, blocks on main/master |
12
+ | `src/cli.ts` | CLI — install/uninstall/status |
13
+
14
+ ### Hook Events
15
+
16
+ - **PreToolUse** (matcher: `Write|Edit|NotebookEdit`)
17
+
18
+ ### Behavior
19
+
20
+ - Checks current git branch before allowing file modifications
21
+ - Blocks Write/Edit/NotebookEdit on main/master branches
22
+ - Suggests creating a feature branch in the block message
23
+ - Approves everything on non-protected branches or non-git directories
@@ -0,0 +1,25 @@
1
+ # hook-branchprotect
2
+
3
+ Claude Code hook that prevents editing files on main/master branch.
4
+
5
+ ## Overview
6
+
7
+ Forces a feature branch workflow by blocking all Write/Edit/NotebookEdit operations when the current git branch is `main` or `master`.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ bun install -g @hasnaxyz/hook-branchprotect
13
+ hook-branchprotect install
14
+ ```
15
+
16
+ ## How It Works
17
+
18
+ 1. Intercepts Write/Edit/NotebookEdit tool calls (PreToolUse)
19
+ 2. Checks the current git branch via `git rev-parse --abbrev-ref HEAD`
20
+ 3. Blocks if on `main` or `master`, suggests creating a feature branch
21
+ 4. Approves all operations on any other branch
22
+
23
+ ## License
24
+
25
+ MIT
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@hasnaxyz/hook-branchprotect",
3
+ "version": "0.1.0",
4
+ "description": "Claude Code hook that prevents editing files on main/master branch",
5
+ "type": "module",
6
+ "bin": {
7
+ "hook-branchprotect": "./dist/cli.js"
8
+ },
9
+ "main": "./dist/hook.js",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/hook.js",
13
+ "types": "./dist/hook.d.ts"
14
+ },
15
+ "./cli": {
16
+ "import": "./dist/cli.js"
17
+ }
18
+ },
19
+ "files": ["dist", "README.md"],
20
+ "scripts": {
21
+ "build": "bun build ./src/cli.ts ./src/hook.ts --outdir ./dist --target node",
22
+ "prepublishOnly": "bun run build",
23
+ "typecheck": "tsc --noEmit"
24
+ },
25
+ "keywords": ["claude-code", "claude", "hook", "branch", "protection", "git", "cli"],
26
+ "author": "Hasna",
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/hasnaxyz/hook-branchprotect.git"
31
+ },
32
+ "publishConfig": {
33
+ "access": "restricted",
34
+ "registry": "https://registry.npmjs.org/"
35
+ },
36
+ "engines": { "node": ">=18", "bun": ">=1.0" },
37
+ "devDependencies": {
38
+ "@types/bun": "^1.3.8",
39
+ "@types/node": "^20",
40
+ "typescript": "^5.0.0"
41
+ }
42
+ }
@@ -0,0 +1,126 @@
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
+ }
@@ -0,0 +1,88 @@
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
+ }
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Hasna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.