preclaim 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/dist/commands/check.d.ts +2 -0
  3. package/dist/commands/check.d.ts.map +1 -0
  4. package/dist/commands/check.js +25 -0
  5. package/dist/commands/check.js.map +1 -0
  6. package/dist/commands/config.d.ts +5 -0
  7. package/dist/commands/config.d.ts.map +1 -0
  8. package/dist/commands/config.js +37 -0
  9. package/dist/commands/config.js.map +1 -0
  10. package/dist/commands/init.d.ts +5 -0
  11. package/dist/commands/init.d.ts.map +1 -0
  12. package/dist/commands/init.js +95 -0
  13. package/dist/commands/init.js.map +1 -0
  14. package/dist/commands/install-hooks.d.ts +2 -0
  15. package/dist/commands/install-hooks.d.ts.map +1 -0
  16. package/dist/commands/install-hooks.js +58 -0
  17. package/dist/commands/install-hooks.js.map +1 -0
  18. package/dist/commands/lock.d.ts +5 -0
  19. package/dist/commands/lock.d.ts.map +1 -0
  20. package/dist/commands/lock.js +27 -0
  21. package/dist/commands/lock.js.map +1 -0
  22. package/dist/commands/login.d.ts +2 -0
  23. package/dist/commands/login.d.ts.map +1 -0
  24. package/dist/commands/login.js +106 -0
  25. package/dist/commands/login.js.map +1 -0
  26. package/dist/commands/status.d.ts +2 -0
  27. package/dist/commands/status.d.ts.map +1 -0
  28. package/dist/commands/status.js +12 -0
  29. package/dist/commands/status.js.map +1 -0
  30. package/dist/commands/unlock.d.ts +5 -0
  31. package/dist/commands/unlock.d.ts.map +1 -0
  32. package/dist/commands/unlock.js +20 -0
  33. package/dist/commands/unlock.js.map +1 -0
  34. package/dist/commands/whoami.d.ts +2 -0
  35. package/dist/commands/whoami.d.ts.map +1 -0
  36. package/dist/commands/whoami.js +13 -0
  37. package/dist/commands/whoami.js.map +1 -0
  38. package/dist/hooks/heartbeat-daemon.d.ts +3 -0
  39. package/dist/hooks/heartbeat-daemon.d.ts.map +1 -0
  40. package/dist/hooks/heartbeat-daemon.js +41 -0
  41. package/dist/hooks/heartbeat-daemon.js.map +1 -0
  42. package/dist/hooks/post-tool-use.d.ts +3 -0
  43. package/dist/hooks/post-tool-use.d.ts.map +1 -0
  44. package/dist/hooks/post-tool-use.js +41 -0
  45. package/dist/hooks/post-tool-use.js.map +1 -0
  46. package/dist/hooks/pre-tool-use.d.ts +3 -0
  47. package/dist/hooks/pre-tool-use.d.ts.map +1 -0
  48. package/dist/hooks/pre-tool-use.js +101 -0
  49. package/dist/hooks/pre-tool-use.js.map +1 -0
  50. package/dist/hooks/session-start.d.ts +3 -0
  51. package/dist/hooks/session-start.d.ts.map +1 -0
  52. package/dist/hooks/session-start.js +77 -0
  53. package/dist/hooks/session-start.js.map +1 -0
  54. package/dist/hooks/stop.d.ts +3 -0
  55. package/dist/hooks/stop.d.ts.map +1 -0
  56. package/dist/hooks/stop.js +40 -0
  57. package/dist/hooks/stop.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +62 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/lib/auth.d.ts +3 -0
  63. package/dist/lib/auth.d.ts.map +1 -0
  64. package/dist/lib/auth.js +15 -0
  65. package/dist/lib/auth.js.map +1 -0
  66. package/dist/lib/client-factory.d.ts +8 -0
  67. package/dist/lib/client-factory.d.ts.map +1 -0
  68. package/dist/lib/client-factory.js +17 -0
  69. package/dist/lib/client-factory.js.map +1 -0
  70. package/dist/lib/hook-io.d.ts +13 -0
  71. package/dist/lib/hook-io.d.ts.map +1 -0
  72. package/dist/lib/hook-io.js +24 -0
  73. package/dist/lib/hook-io.js.map +1 -0
  74. package/dist/lib/output.d.ts +4 -0
  75. package/dist/lib/output.d.ts.map +1 -0
  76. package/dist/lib/output.js +17 -0
  77. package/dist/lib/output.js.map +1 -0
  78. package/package.json +24 -0
  79. package/src/commands/check.ts +28 -0
  80. package/src/commands/config.ts +43 -0
  81. package/src/commands/init.ts +109 -0
  82. package/src/commands/install-hooks.ts +72 -0
  83. package/src/commands/lock.ts +30 -0
  84. package/src/commands/login.ts +120 -0
  85. package/src/commands/status.ts +15 -0
  86. package/src/commands/unlock.ts +25 -0
  87. package/src/commands/whoami.ts +15 -0
  88. package/src/hooks/heartbeat-daemon.ts +49 -0
  89. package/src/hooks/post-tool-use.ts +44 -0
  90. package/src/hooks/pre-tool-use.ts +110 -0
  91. package/src/hooks/session-start.ts +87 -0
  92. package/src/hooks/stop.ts +43 -0
  93. package/src/index.ts +74 -0
  94. package/src/lib/auth.ts +17 -0
  95. package/src/lib/client-factory.ts +26 -0
  96. package/src/lib/hook-io.ts +37 -0
  97. package/src/lib/output.ts +20 -0
  98. package/tsconfig.json +8 -0
@@ -0,0 +1,109 @@
1
+ import { writeFile, readFile } from 'node:fs/promises';
2
+ import { join, basename } from 'node:path';
3
+ import { defaultConfig, loadCredentials, PreclaimClient } from '@preclaim/core';
4
+ import { loginCommand } from './login.js';
5
+
6
+ const DEFAULT_BACKEND = 'https://preclaim.dev';
7
+
8
+ export async function initCommand(opts: { backend?: string; projectId?: string }) {
9
+ const configPath = join(process.cwd(), '.preclaim.json');
10
+
11
+ // Check if already exists
12
+ try {
13
+ await readFile(configPath, 'utf-8');
14
+ console.log('.preclaim.json already exists. Use `preclaim config` to modify.');
15
+ return;
16
+ } catch {
17
+ // File doesn't exist, proceed
18
+ }
19
+
20
+ const backend = opts.backend ?? DEFAULT_BACKEND;
21
+
22
+ // If project ID provided directly, skip onboarding
23
+ if (opts.projectId) {
24
+ const config = defaultConfig(opts.projectId, backend);
25
+ await writeFile(configPath, JSON.stringify(config, null, 2) + '\n');
26
+ console.log(`Created .preclaim.json (project: ${opts.projectId})`);
27
+ printNextSteps();
28
+ return;
29
+ }
30
+
31
+ // Check if logged in, if not: login first
32
+ let creds = await loadCredentials();
33
+ if (!creds) {
34
+ console.log('Not logged in. Starting authentication...\n');
35
+ await loginCommand();
36
+ creds = await loadCredentials();
37
+ if (!creds) {
38
+ console.error('Login failed. Please try again.');
39
+ process.exit(1);
40
+ }
41
+ console.log('');
42
+ }
43
+
44
+ // Derive project name from directory
45
+ const dirName = basename(process.cwd());
46
+ const projectSlug = dirName.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-');
47
+ const projectName = dirName;
48
+
49
+ console.log(`Setting up Preclaim for "${projectName}"...`);
50
+
51
+ // Call onboard API
52
+ const client = new PreclaimClient({
53
+ baseUrl: backend,
54
+ accessToken: creds.accessToken,
55
+ timeoutMs: 10000,
56
+ });
57
+
58
+ const res = await fetch(`${backend}/api/v1/onboard`, {
59
+ method: 'POST',
60
+ headers: {
61
+ 'Content-Type': 'application/json',
62
+ 'Authorization': `Bearer ${creds.accessToken}`,
63
+ },
64
+ body: JSON.stringify({
65
+ project_name: projectName,
66
+ project_slug: projectSlug,
67
+ }),
68
+ });
69
+
70
+ if (!res.ok) {
71
+ const body = await res.text();
72
+ console.error(`Failed to create project: ${body}`);
73
+ process.exit(1);
74
+ }
75
+
76
+ const { data } = await res.json() as { data: { project_id: string; org_id: string; already_existed: boolean } };
77
+
78
+ if (data.already_existed) {
79
+ console.log(`Project "${projectName}" already exists, using existing project.`);
80
+ } else {
81
+ console.log(`Project "${projectName}" created.`);
82
+ }
83
+
84
+ // Update credentials with org_id
85
+ if (creds.user.orgId !== data.org_id) {
86
+ creds.user.orgId = data.org_id;
87
+ const { getCredentialsPath } = await import('@preclaim/core');
88
+ const { writeFile: wf, mkdir } = await import('node:fs/promises');
89
+ const { dirname } = await import('node:path');
90
+ const credPath = getCredentialsPath();
91
+ await mkdir(dirname(credPath), { recursive: true });
92
+ await wf(credPath, JSON.stringify(creds, null, 2) + '\n', { mode: 0o600 });
93
+ }
94
+
95
+ // Write config
96
+ const config = defaultConfig(data.project_id, backend);
97
+ await writeFile(configPath, JSON.stringify(config, null, 2) + '\n');
98
+
99
+ console.log(`\nCreated .preclaim.json`);
100
+ printNextSteps();
101
+ }
102
+
103
+ function printNextSteps() {
104
+ console.log('');
105
+ console.log('Next steps:');
106
+ console.log(' 1. preclaim install-hooks');
107
+ console.log(' 2. Commit .preclaim.json to your repo');
108
+ console.log(' 3. Open multiple Claude Code terminals — locks are automatic');
109
+ }
@@ -0,0 +1,72 @@
1
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
2
+ import { join, dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url));
6
+
7
+ interface ClaudeSettings {
8
+ hooks?: Record<string, Array<{
9
+ matcher: string;
10
+ hooks: Array<{
11
+ type: string;
12
+ command: string;
13
+ }>;
14
+ }>>;
15
+ }
16
+
17
+ export async function installHooksCommand() {
18
+ const hooksDir = join(__dirname, '..', 'hooks');
19
+ const settingsDir = join(process.cwd(), '.claude');
20
+ const settingsPath = join(settingsDir, 'settings.json');
21
+
22
+ // Read existing settings or create new
23
+ let settings: ClaudeSettings = {};
24
+ try {
25
+ const raw = await readFile(settingsPath, 'utf-8');
26
+ settings = JSON.parse(raw);
27
+ } catch {
28
+ // File doesn't exist
29
+ }
30
+
31
+ settings.hooks = {
32
+ PreToolUse: [{
33
+ matcher: '',
34
+ hooks: [{
35
+ type: 'command',
36
+ command: `node ${join(hooksDir, 'pre-tool-use.js')}`,
37
+ }],
38
+ }],
39
+ PostToolUse: [{
40
+ matcher: '',
41
+ hooks: [{
42
+ type: 'command',
43
+ command: `node ${join(hooksDir, 'post-tool-use.js')}`,
44
+ }],
45
+ }],
46
+ Stop: [{
47
+ matcher: '',
48
+ hooks: [{
49
+ type: 'command',
50
+ command: `node ${join(hooksDir, 'stop.js')}`,
51
+ }],
52
+ }],
53
+ SessionStart: [{
54
+ matcher: '',
55
+ hooks: [{
56
+ type: 'command',
57
+ command: `node ${join(hooksDir, 'session-start.js')}`,
58
+ }],
59
+ }],
60
+ };
61
+
62
+ await mkdir(settingsDir, { recursive: true });
63
+ await writeFile(settingsPath, JSON.stringify(settings, null, 2) + '\n');
64
+
65
+ console.log('Claude Code hooks installed in .claude/settings.json');
66
+ console.log('');
67
+ console.log('Hooks configured:');
68
+ console.log(' - PreToolUse: file lock gatekeeper');
69
+ console.log(' - PostToolUse: commit detection → release locks');
70
+ console.log(' - Stop: session cleanup');
71
+ console.log(' - SessionStart: session registration + heartbeat');
72
+ }
@@ -0,0 +1,30 @@
1
+ import { resolveContext } from '../lib/client-factory.js';
2
+
3
+ export async function lockCommand(filePath: string, opts: { session?: string; ttl?: string }) {
4
+ const { client, config, credentials } = await resolveContext();
5
+ const sessionId = opts.session ?? `manual_${crypto.randomUUID().slice(0, 8)}`;
6
+ const ttl = opts.ttl ? parseInt(opts.ttl, 10) : config.ttl;
7
+
8
+ const result = await client.claimFile({
9
+ project_id: config.projectId,
10
+ file_path: filePath,
11
+ session_id: sessionId,
12
+ ttl_minutes: ttl,
13
+ });
14
+
15
+ if (result.error) {
16
+ console.error(`Failed to lock: ${result.error}`);
17
+ process.exit(1);
18
+ }
19
+
20
+ const data = result.data!;
21
+
22
+ if (data.status === 'acquired' || data.status === 'already_held') {
23
+ console.log(`Locked: ${filePath} (expires: ${new Date(data.expires_at!).toLocaleTimeString()})`);
24
+ } else if (data.status === 'conflict') {
25
+ console.error(`Conflict: ${filePath} is locked by session ${data.holder!.session_id.slice(0, 8)}…`);
26
+ console.error(` Acquired: ${new Date(data.holder!.acquired_at).toLocaleTimeString()}`);
27
+ console.error(` Expires: ${new Date(data.holder!.expires_at).toLocaleTimeString()}`);
28
+ process.exit(1);
29
+ }
30
+ }
@@ -0,0 +1,120 @@
1
+ import { createServer, type Server } from 'node:http';
2
+ import { writeFile, mkdir } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import { getCredentialsPath, findConfig } from '@preclaim/core';
5
+
6
+ const SUPABASE_URL = 'https://aawbukcvngdffueowjsa.supabase.co';
7
+ const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFhd2J1a2N2bmdkZmZ1ZW93anNhIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM3NjI2NTcsImV4cCI6MjA4OTMzODY1N30.pwAyjgnbdoZmmJdsG2jF0nbvT4hueb8UZvstsdYhFFs';
8
+
9
+ export async function loginCommand() {
10
+ const server = createServer();
11
+
12
+ const port = await new Promise<number>((resolve) => {
13
+ server.listen(0, () => {
14
+ resolve((server.address() as { port: number }).port);
15
+ });
16
+ });
17
+
18
+ const redirectTo = `http://localhost:${port}/callback`;
19
+ const oauthUrl = `${SUPABASE_URL}/auth/v1/authorize?provider=github&redirect_to=${encodeURIComponent(redirectTo)}`;
20
+
21
+ console.log('Opening browser for GitHub authentication...');
22
+ console.log(`If browser doesn't open, visit:\n${oauthUrl}\n`);
23
+
24
+ const { exec } = await import('node:child_process');
25
+ const openCmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
26
+ exec(`${openCmd} "${oauthUrl}"`);
27
+
28
+ await handleAuthCallback(server);
29
+ }
30
+
31
+ function handleAuthCallback(server: Server): Promise<void> {
32
+ return new Promise((resolve, reject) => {
33
+ server.on('request', async (req, res) => {
34
+ const url = new URL(req.url!, `http://localhost`);
35
+
36
+ if (url.pathname === '/callback') {
37
+ // Supabase implicit flow: tokens come in hash fragment.
38
+ // Serve a page that extracts them and POSTs to /token.
39
+ res.writeHead(200, { 'Content-Type': 'text/html' });
40
+ res.end(`<!DOCTYPE html><html><body>
41
+ <h1>Logging in to Preclaim...</h1>
42
+ <script>
43
+ const hash = window.location.hash.substring(1);
44
+ const params = new URLSearchParams(hash);
45
+ const access_token = params.get('access_token');
46
+ const refresh_token = params.get('refresh_token');
47
+ const expires_in = params.get('expires_in');
48
+ if (access_token) {
49
+ fetch('/token', {
50
+ method: 'POST',
51
+ headers: { 'Content-Type': 'application/json' },
52
+ body: JSON.stringify({ access_token, refresh_token, expires_in })
53
+ }).then(() => {
54
+ document.body.innerHTML = '<h1>Logged in to Preclaim!</h1><p>You can close this tab.</p>';
55
+ });
56
+ } else {
57
+ document.body.innerHTML = '<h1>Login failed</h1><p>No token received. Check the URL.</p>';
58
+ }
59
+ </script></body></html>`);
60
+ return;
61
+ }
62
+
63
+ if (url.pathname === '/token' && req.method === 'POST') {
64
+ let body = '';
65
+ req.on('data', (chunk: Buffer) => { body += chunk; });
66
+ req.on('end', async () => {
67
+ try {
68
+ const { access_token, refresh_token, expires_in } = JSON.parse(body);
69
+
70
+ // Get user info
71
+ const userRes = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
72
+ headers: {
73
+ 'Authorization': `Bearer ${access_token}`,
74
+ 'apikey': SUPABASE_ANON_KEY,
75
+ },
76
+ });
77
+
78
+ if (!userRes.ok) throw new Error(`Failed to get user info: ${userRes.status}`);
79
+
80
+ const user = await userRes.json() as { id: string; email?: string };
81
+
82
+ // Save credentials
83
+ const credPath = getCredentialsPath();
84
+ await mkdir(dirname(credPath), { recursive: true });
85
+ await writeFile(credPath, JSON.stringify({
86
+ accessToken: access_token,
87
+ refreshToken: refresh_token,
88
+ expiresAt: new Date(Date.now() + parseInt(expires_in) * 1000).toISOString(),
89
+ user: {
90
+ id: user.id,
91
+ email: user.email ?? '',
92
+ orgId: '',
93
+ },
94
+ }, null, 2) + '\n', { mode: 0o600 });
95
+
96
+ res.writeHead(200);
97
+ res.end('ok');
98
+
99
+ console.log(`Logged in as ${user.email ?? user.id}`);
100
+ server.close();
101
+ resolve();
102
+ } catch (err) {
103
+ res.writeHead(500);
104
+ res.end('error');
105
+ console.error('Login failed:', err);
106
+ server.close();
107
+ reject(err);
108
+ }
109
+ });
110
+ return;
111
+ }
112
+ });
113
+
114
+ setTimeout(() => {
115
+ console.error('Login timed out.');
116
+ server.close();
117
+ process.exit(1);
118
+ }, 120_000);
119
+ });
120
+ }
@@ -0,0 +1,15 @@
1
+ import { resolveContext } from '../lib/client-factory.js';
2
+ import { formatLockTable } from '../lib/output.js';
3
+
4
+ export async function statusCommand() {
5
+ const { client, config } = await resolveContext();
6
+
7
+ const result = await client.listLocks(config.projectId);
8
+
9
+ if (result.error) {
10
+ console.error(`Failed to fetch status: ${result.error}`);
11
+ process.exit(1);
12
+ }
13
+
14
+ console.log(formatLockTable(result.data!));
15
+ }
@@ -0,0 +1,25 @@
1
+ import { resolveContext } from '../lib/client-factory.js';
2
+
3
+ export async function unlockCommand(filePath: string | undefined, opts: { session?: string; all?: boolean }) {
4
+ const { client, config } = await resolveContext();
5
+
6
+ if (!filePath && !opts.all) {
7
+ console.error('Specify a file path or use --all to release all locks.');
8
+ process.exit(1);
9
+ }
10
+
11
+ const sessionId = opts.session ?? `manual_${crypto.randomUUID().slice(0, 8)}`;
12
+
13
+ const result = await client.releaseLocks({
14
+ project_id: config.projectId,
15
+ file_path: filePath,
16
+ session_id: sessionId,
17
+ });
18
+
19
+ if (result.error) {
20
+ console.error(`Failed to unlock: ${result.error}`);
21
+ process.exit(1);
22
+ }
23
+
24
+ console.log(`Released ${result.data!.released} lock(s).`);
25
+ }
@@ -0,0 +1,15 @@
1
+ import { loadCredentials } from '@preclaim/core';
2
+
3
+ export async function whoamiCommand() {
4
+ const creds = await loadCredentials();
5
+
6
+ if (!creds) {
7
+ console.log('Not logged in. Run `preclaim login` to authenticate.');
8
+ return;
9
+ }
10
+
11
+ console.log(`Email: ${creds.user.email}`);
12
+ console.log(`User: ${creds.user.id}`);
13
+ console.log(`Org: ${creds.user.orgId ?? 'none'}`);
14
+ console.log(`Expires: ${new Date(creds.expiresAt).toLocaleString()}`);
15
+ }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env node
2
+ // Heartbeat daemon — runs as detached background process
3
+ // Extends TTL on all session locks every 60s
4
+
5
+ import { PreclaimClient } from '@preclaim/core';
6
+
7
+ const sessionId = process.env.PRECLAIM_SESSION_ID;
8
+ const backend = process.env.PRECLAIM_BACKEND;
9
+ const accessToken = process.env.PRECLAIM_ACCESS_TOKEN;
10
+
11
+ if (!sessionId || !backend || !accessToken) {
12
+ process.exit(1);
13
+ }
14
+
15
+ const client = new PreclaimClient({
16
+ baseUrl: backend,
17
+ accessToken,
18
+ timeoutMs: 5000,
19
+ });
20
+
21
+ const INTERVAL_MS = 60_000;
22
+ const MAX_FAILURES = 5;
23
+ let failures = 0;
24
+
25
+ async function heartbeat() {
26
+ const result = await client.heartbeat({ session_id: sessionId! });
27
+
28
+ if (result.error) {
29
+ failures++;
30
+ if (failures >= MAX_FAILURES) {
31
+ process.exit(1);
32
+ }
33
+ } else {
34
+ failures = 0;
35
+ }
36
+ }
37
+
38
+ // Run immediately, then every 60s
39
+ heartbeat();
40
+ const interval = setInterval(heartbeat, INTERVAL_MS);
41
+
42
+ // Cleanup on signals
43
+ function shutdown() {
44
+ clearInterval(interval);
45
+ process.exit(0);
46
+ }
47
+
48
+ process.on('SIGTERM', shutdown);
49
+ process.on('SIGINT', shutdown);
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ // PostToolUse hook — commit detection
3
+ // Detects git commit commands and releases all session locks
4
+
5
+ import { PreclaimClient, findConfig, loadCredentials } from '@preclaim/core';
6
+ import { readHookInput } from '../lib/hook-io.js';
7
+
8
+ async function main() {
9
+ try {
10
+ const input = await readHookInput();
11
+
12
+ // Only match Bash tool calls
13
+ if (input.tool_name !== 'Bash') return;
14
+
15
+ const command = input.tool_input?.command as string | undefined;
16
+ if (!command) return;
17
+
18
+ // Detect git commit (not amend, not just `git commit --help`)
19
+ const isCommit = /\bgit\s+commit\b/.test(command) && !/--help/.test(command);
20
+ if (!isCommit) return;
21
+
22
+ const found = await findConfig();
23
+ if (!found) return;
24
+
25
+ const creds = await loadCredentials();
26
+ if (!creds) return;
27
+
28
+ const client = new PreclaimClient({
29
+ baseUrl: found.config.backend,
30
+ accessToken: creds.accessToken,
31
+ timeoutMs: 3000,
32
+ });
33
+
34
+ // Release all locks for this session
35
+ await client.releaseLocks({
36
+ project_id: found.config.projectId,
37
+ session_id: input.session_id,
38
+ });
39
+ } catch {
40
+ // Silent fail — non-critical
41
+ }
42
+ }
43
+
44
+ main();
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse hook — the gatekeeper
3
+ // Intercepts Edit/Write/MultiEdit tool calls, claims file locks
4
+
5
+ import { PreclaimClient, findConfig, loadCredentials } from '@preclaim/core';
6
+ import { readHookInput, writeHookOutput } from '../lib/hook-io.js';
7
+ import { minimatch } from 'minimatch';
8
+
9
+ const WRITE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit']);
10
+
11
+ async function main() {
12
+ try {
13
+ const input = await readHookInput();
14
+
15
+ // Only intercept file-writing tools
16
+ if (!input.tool_name || !WRITE_TOOLS.has(input.tool_name)) {
17
+ return; // No output = allow
18
+ }
19
+
20
+ // Extract file path from tool input
21
+ const filePath = input.tool_input?.file_path as string | undefined;
22
+ if (!filePath) {
23
+ return; // No file path = allow
24
+ }
25
+
26
+ // Load config
27
+ const found = await findConfig();
28
+ if (!found) {
29
+ return; // No config = allow (not a preclaim project)
30
+ }
31
+
32
+ // Check ignore patterns
33
+ const relativePath = filePath.startsWith('/') ? filePath : filePath;
34
+ if (found.config.ignore.some(pattern => minimatch(relativePath, pattern))) {
35
+ return; // Ignored file = allow
36
+ }
37
+
38
+ // Load credentials
39
+ const creds = await loadCredentials();
40
+ if (!creds) {
41
+ if (found.config.failOpen) return;
42
+ writeHookOutput({
43
+ permissionDecision: 'deny',
44
+ reason: 'Preclaim: not authenticated. Run `preclaim login`.',
45
+ });
46
+ return;
47
+ }
48
+
49
+ // Claim file
50
+ const client = new PreclaimClient({
51
+ baseUrl: found.config.backend,
52
+ accessToken: creds.accessToken,
53
+ timeoutMs: 2000, // Must be fast
54
+ });
55
+
56
+ const result = await client.claimFile({
57
+ project_id: found.config.projectId,
58
+ file_path: relativePath,
59
+ session_id: input.session_id,
60
+ ttl_minutes: found.config.ttl,
61
+ });
62
+
63
+ // Network error — fail open
64
+ if (result.error) {
65
+ if (found.config.failOpen) {
66
+ writeHookOutput({
67
+ permissionDecision: 'allow',
68
+ systemMessage: `[Preclaim] Warning: could not reach server (${result.error}). Proceeding without lock.`,
69
+ });
70
+ return;
71
+ }
72
+ writeHookOutput({
73
+ permissionDecision: 'deny',
74
+ reason: `Preclaim: server error — ${result.error}`,
75
+ });
76
+ return;
77
+ }
78
+
79
+ const data = result.data!;
80
+
81
+ if (data.status === 'acquired') {
82
+ writeHookOutput({
83
+ permissionDecision: 'allow',
84
+ systemMessage: `[Preclaim] Locked: ${relativePath} (expires: ${data.expires_at})`,
85
+ });
86
+ } else if (data.status === 'already_held') {
87
+ writeHookOutput({
88
+ permissionDecision: 'allow',
89
+ systemMessage: `[Preclaim] Lock extended: ${relativePath} (expires: ${data.expires_at})`,
90
+ });
91
+ } else if (data.status === 'conflict') {
92
+ writeHookOutput({
93
+ permissionDecision: 'deny',
94
+ reason: [
95
+ `Preclaim: ${relativePath} is locked by another session.`,
96
+ ` Session: ${data.holder!.session_id.slice(0, 8)}…`,
97
+ ` Since: ${new Date(data.holder!.acquired_at).toLocaleTimeString()}`,
98
+ ` Expires: ${new Date(data.holder!.expires_at).toLocaleTimeString()}`,
99
+ '',
100
+ 'Wait for the lock to expire or work on a different file.',
101
+ ].join('\n'),
102
+ });
103
+ }
104
+ } catch {
105
+ // Fail open — never block development
106
+ return;
107
+ }
108
+ }
109
+
110
+ main();
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart hook — init
3
+ // Registers session, starts heartbeat daemon, injects system message
4
+
5
+ import { spawn } from 'node:child_process';
6
+ import { writeFile } from 'node:fs/promises';
7
+ import { join, dirname } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { PreclaimClient, findConfig, loadCredentials } from '@preclaim/core';
10
+ import { readHookInput, writeHookOutput } from '../lib/hook-io.js';
11
+
12
+ async function main() {
13
+ try {
14
+ const input = await readHookInput();
15
+
16
+ const found = await findConfig();
17
+ if (!found) return;
18
+
19
+ const creds = await loadCredentials();
20
+ if (!creds) {
21
+ writeHookOutput({
22
+ systemMessage: '[Preclaim] Not authenticated. File locking disabled. Run `preclaim login` to enable.',
23
+ });
24
+ return;
25
+ }
26
+
27
+ const client = new PreclaimClient({
28
+ baseUrl: found.config.backend,
29
+ accessToken: creds.accessToken,
30
+ timeoutMs: 3000,
31
+ });
32
+
33
+ // Register session
34
+ const result = await client.registerSession({
35
+ session_id: input.session_id,
36
+ project_id: found.config.projectId,
37
+ provider: 'claude-code',
38
+ });
39
+
40
+ if (result.error) {
41
+ if (found.config.failOpen) {
42
+ writeHookOutput({
43
+ systemMessage: `[Preclaim] Warning: could not register session (${result.error}). File locking may not work.`,
44
+ });
45
+ return;
46
+ }
47
+ }
48
+
49
+ // Start heartbeat daemon
50
+ const __dirname = dirname(fileURLToPath(import.meta.url));
51
+ const heartbeatScript = join(__dirname, 'heartbeat-daemon.js');
52
+
53
+ const daemon = spawn('node', [heartbeatScript], {
54
+ detached: true,
55
+ stdio: 'ignore',
56
+ env: {
57
+ ...process.env,
58
+ PRECLAIM_SESSION_ID: input.session_id,
59
+ PRECLAIM_BACKEND: found.config.backend,
60
+ PRECLAIM_ACCESS_TOKEN: creds.accessToken,
61
+ },
62
+ });
63
+
64
+ daemon.unref();
65
+
66
+ // Save PID for cleanup
67
+ if (daemon.pid) {
68
+ await writeFile(join(process.cwd(), '.preclaim.pid'), String(daemon.pid));
69
+ }
70
+
71
+ writeHookOutput({
72
+ systemMessage: [
73
+ '[Preclaim] Session registered. File locking is active.',
74
+ '',
75
+ 'Preclaim coordinates file access across multiple AI sessions:',
76
+ '- Files are automatically locked when you edit them',
77
+ '- Locks prevent other sessions from editing the same files',
78
+ '- Locks are released when you commit or this session ends',
79
+ '- If a lock is denied, work on a different file',
80
+ ].join('\n'),
81
+ });
82
+ } catch {
83
+ // Fail open
84
+ }
85
+ }
86
+
87
+ main();