@codebakers/cli 3.3.18 → 3.4.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.
@@ -1,16 +1,135 @@
1
1
  import chalk from 'chalk';
2
2
  import ora from 'ora';
3
- import { existsSync, writeFileSync, mkdirSync } from 'fs';
3
+ import { existsSync, writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync, copyFileSync, chmodSync } from 'fs';
4
4
  import { join } from 'path';
5
5
  import { getApiKey, getApiUrl } from '../config.js';
6
6
  import { checkForUpdates, getCliVersion } from '../lib/api.js';
7
7
 
8
+ // Pre-commit hook script for session enforcement
9
+ const PRE_COMMIT_SCRIPT = `#!/bin/sh
10
+ # CodeBakers Pre-Commit Hook - Session Enforcement
11
+ # Blocks commits unless AI called discover_patterns and validate_complete
12
+ node "$(dirname "$0")/validate-session.js"
13
+ exit $?
14
+ `;
15
+
16
+ const VALIDATE_SESSION_SCRIPT = `#!/usr/bin/env node
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const RED = '\\x1b[31m', GREEN = '\\x1b[32m', YELLOW = '\\x1b[33m', CYAN = '\\x1b[36m', RESET = '\\x1b[0m';
20
+ function log(c, m) { console.log(c + m + RESET); }
21
+
22
+ async function validate() {
23
+ const stateFile = path.join(process.cwd(), '.codebakers.json');
24
+ if (!fs.existsSync(stateFile)) return { valid: true, reason: 'not-codebakers' };
25
+
26
+ let state;
27
+ try { state = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); }
28
+ catch { return { valid: false, reason: 'invalid-state' }; }
29
+
30
+ if (!state.serverEnforced) return { valid: true, reason: 'legacy' };
31
+
32
+ const v = state.lastValidation;
33
+ if (!v) return { valid: false, reason: 'no-validation', msg: 'AI must call validate_complete before commit' };
34
+ if (!v.passed) return { valid: false, reason: 'failed', msg: 'Validation failed - fix issues first' };
35
+
36
+ const age = Date.now() - new Date(v.timestamp).getTime();
37
+ if (age > 30 * 60 * 1000) return { valid: false, reason: 'stale', msg: 'Validation expired - call validate_complete again' };
38
+
39
+ return { valid: true, reason: 'ok' };
40
+ }
41
+
42
+ async function main() {
43
+ console.log(''); log(CYAN, ' 🍪 CodeBakers Pre-Commit');
44
+ const r = await validate();
45
+ if (r.valid) { log(GREEN, ' ✓ Commit allowed'); console.log(''); process.exit(0); }
46
+ else { log(RED, ' ✗ Blocked: ' + r.reason); if (r.msg) log(YELLOW, ' ' + r.msg);
47
+ console.log(''); log(YELLOW, ' Bypass: git commit --no-verify'); console.log(''); process.exit(1); }
48
+ }
49
+ main().catch(e => { log(RED, ' Error: ' + e.message); process.exit(1); });
50
+ `;
51
+
52
+ /**
53
+ * Install pre-commit hook for session enforcement
54
+ */
55
+ function installPrecommitHook(cwd: string): void {
56
+ const gitDir = join(cwd, '.git');
57
+ if (!existsSync(gitDir)) {
58
+ console.log(chalk.gray(' ⏭️ Skipping pre-commit hook (not a git repo)'));
59
+ return;
60
+ }
61
+
62
+ const hooksDir = join(gitDir, 'hooks');
63
+ if (!existsSync(hooksDir)) {
64
+ mkdirSync(hooksDir, { recursive: true });
65
+ }
66
+
67
+ // Write pre-commit hook
68
+ const preCommitPath = join(hooksDir, 'pre-commit');
69
+ writeFileSync(preCommitPath, PRE_COMMIT_SCRIPT);
70
+ try { chmodSync(preCommitPath, '755'); } catch { /* Windows */ }
71
+
72
+ // Write validation script
73
+ const validatePath = join(hooksDir, 'validate-session.js');
74
+ writeFileSync(validatePath, VALIDATE_SESSION_SCRIPT);
75
+
76
+ console.log(chalk.green(' ✓ Installed pre-commit hook (blocks commits without validation)'));
77
+ }
78
+
8
79
  interface ContentResponse {
9
80
  version: string;
10
81
  router: string;
11
82
  modules: Record<string, string>;
12
83
  }
13
84
 
85
+ // Ultra-minimal CLAUDE.md for v6.0 - ALL instructions come from server
86
+ const MINIMAL_CLAUDE_MD = `# CodeBakers v6.0
87
+
88
+ **MANDATORY: Before writing ANY code, call the \`discover_patterns\` MCP tool.**
89
+
90
+ \`\`\`
91
+ Tool: discover_patterns
92
+ Args: { task: "description of what you're building" }
93
+ \`\`\`
94
+
95
+ The server will return:
96
+ - All coding patterns and rules you must follow
97
+ - Test requirements
98
+ - Validation instructions
99
+
100
+ **You cannot write code without calling this tool first. The server tracks compliance.**
101
+
102
+ ---
103
+ *CodeBakers v6.0 - Server-Enforced*
104
+ `;
105
+
106
+ // Ultra-minimal .cursorrules for v6.0 - ALL instructions come from server
107
+ const MINIMAL_CURSORRULES = `# CodeBakers v6.0
108
+
109
+ MANDATORY: Before writing ANY code, call the discover_patterns MCP tool.
110
+
111
+ Tool: discover_patterns
112
+ Args: { task: "description of what you're building" }
113
+
114
+ The server returns all patterns, rules, and test requirements.
115
+ You cannot write code without calling this tool first.
116
+ `;
117
+
118
+ /**
119
+ * Compare semantic versions (returns true if v1 < v2)
120
+ */
121
+ function isVersionLessThan(v1: string, v2: string): boolean {
122
+ const parts1 = v1.split('.').map(Number);
123
+ const parts2 = v2.split('.').map(Number);
124
+ for (let i = 0; i < 3; i++) {
125
+ const p1 = parts1[i] || 0;
126
+ const p2 = parts2[i] || 0;
127
+ if (p1 < p2) return true;
128
+ if (p1 > p2) return false;
129
+ }
130
+ return false;
131
+ }
132
+
14
133
  interface ConfirmData {
15
134
  version: string;
16
135
  moduleCount: number;
@@ -37,6 +156,131 @@ async function confirmDownload(apiUrl: string, apiKey: string, data: ConfirmData
37
156
  }
38
157
  }
39
158
 
159
+ /**
160
+ * Get current installed version from .claude/.version.json
161
+ */
162
+ function getCurrentVersion(cwd: string): string | null {
163
+ const versionFile = join(cwd, '.claude', '.version.json');
164
+ const codebakersFile = join(cwd, '.codebakers.json');
165
+
166
+ try {
167
+ if (existsSync(versionFile)) {
168
+ const data = JSON.parse(readFileSync(versionFile, 'utf-8'));
169
+ return data.version || null;
170
+ }
171
+ if (existsSync(codebakersFile)) {
172
+ const data = JSON.parse(readFileSync(codebakersFile, 'utf-8'));
173
+ return data.version || null;
174
+ }
175
+ } catch {
176
+ // Ignore errors
177
+ }
178
+ return null;
179
+ }
180
+
181
+ /**
182
+ * Backup old files before migration
183
+ */
184
+ function backupOldFiles(cwd: string): void {
185
+ const backupDir = join(cwd, '.codebakers', 'backup', new Date().toISOString().replace(/[:.]/g, '-'));
186
+ mkdirSync(backupDir, { recursive: true });
187
+
188
+ // Backup CLAUDE.md
189
+ const claudeMd = join(cwd, 'CLAUDE.md');
190
+ if (existsSync(claudeMd)) {
191
+ copyFileSync(claudeMd, join(backupDir, 'CLAUDE.md'));
192
+ }
193
+
194
+ // Backup .cursorrules
195
+ const cursorrules = join(cwd, '.cursorrules');
196
+ if (existsSync(cursorrules)) {
197
+ copyFileSync(cursorrules, join(backupDir, '.cursorrules'));
198
+ }
199
+
200
+ // Backup .claude folder
201
+ const claudeDir = join(cwd, '.claude');
202
+ if (existsSync(claudeDir)) {
203
+ const claudeBackup = join(backupDir, '.claude');
204
+ mkdirSync(claudeBackup, { recursive: true });
205
+ const files = readdirSync(claudeDir);
206
+ for (const file of files) {
207
+ const src = join(claudeDir, file);
208
+ const dest = join(claudeBackup, file);
209
+ try {
210
+ copyFileSync(src, dest);
211
+ } catch {
212
+ // Ignore copy errors
213
+ }
214
+ }
215
+ }
216
+
217
+ console.log(chalk.gray(` Backup saved to: ${backupDir}`));
218
+ }
219
+
220
+ /**
221
+ * Migrate to v6.0 server-enforced patterns
222
+ */
223
+ function migrateToV6(cwd: string): void {
224
+ console.log(chalk.yellow('\n 📦 Migrating to v6.0 Server-Enforced Patterns...\n'));
225
+
226
+ // Backup old files
227
+ console.log(chalk.gray(' Backing up old files...'));
228
+ backupOldFiles(cwd);
229
+
230
+ // Replace CLAUDE.md with minimal version
231
+ const claudeMd = join(cwd, 'CLAUDE.md');
232
+ writeFileSync(claudeMd, MINIMAL_CLAUDE_MD);
233
+ console.log(chalk.green(' ✓ Updated CLAUDE.md (minimal server-enforced version)'));
234
+
235
+ // Replace .cursorrules with minimal version
236
+ const cursorrules = join(cwd, '.cursorrules');
237
+ writeFileSync(cursorrules, MINIMAL_CURSORRULES);
238
+ console.log(chalk.green(' ✓ Updated .cursorrules (minimal server-enforced version)'));
239
+
240
+ // Delete .claude folder (patterns now come from server)
241
+ const claudeDir = join(cwd, '.claude');
242
+ if (existsSync(claudeDir)) {
243
+ try {
244
+ rmSync(claudeDir, { recursive: true, force: true });
245
+ console.log(chalk.green(' ✓ Removed .claude/ folder (patterns now server-side)'));
246
+ } catch (error) {
247
+ console.log(chalk.yellow(' ⚠️ Could not remove .claude/ folder - please delete manually'));
248
+ }
249
+ }
250
+
251
+ // Create .codebakers directory if it doesn't exist
252
+ const codebakersDir = join(cwd, '.codebakers');
253
+ if (!existsSync(codebakersDir)) {
254
+ mkdirSync(codebakersDir, { recursive: true });
255
+ }
256
+
257
+ // Update version in .codebakers.json
258
+ const stateFile = join(cwd, '.codebakers.json');
259
+ let state: Record<string, unknown> = {};
260
+ if (existsSync(stateFile)) {
261
+ try {
262
+ state = JSON.parse(readFileSync(stateFile, 'utf-8'));
263
+ } catch {
264
+ // Ignore errors
265
+ }
266
+ }
267
+ state.version = '6.0';
268
+ state.migratedAt = new Date().toISOString();
269
+ state.serverEnforced = true;
270
+ writeFileSync(stateFile, JSON.stringify(state, null, 2));
271
+
272
+ // Auto-install pre-commit hook for enforcement
273
+ installPrecommitHook(cwd);
274
+
275
+ console.log(chalk.green('\n ✅ Migration to v6.0 complete!\n'));
276
+ console.log(chalk.cyan(' What changed:'));
277
+ console.log(chalk.gray(' - Patterns are now fetched from server in real-time'));
278
+ console.log(chalk.gray(' - discover_patterns creates a server-tracked session'));
279
+ console.log(chalk.gray(' - validate_complete verifies with server before completion'));
280
+ console.log(chalk.gray(' - Pre-commit hook blocks commits without validation'));
281
+ console.log(chalk.gray(' - No local pattern files needed\n'));
282
+ }
283
+
40
284
  /**
41
285
  * Upgrade CodeBakers patterns to the latest version
42
286
  */
@@ -46,9 +290,10 @@ export async function upgrade(): Promise<void> {
46
290
  const cwd = process.cwd();
47
291
  const claudeMdPath = join(cwd, 'CLAUDE.md');
48
292
  const claudeDir = join(cwd, '.claude');
293
+ const codebakersJson = join(cwd, '.codebakers.json');
49
294
 
50
295
  // Check if this is a CodeBakers project
51
- if (!existsSync(claudeMdPath) && !existsSync(claudeDir)) {
296
+ if (!existsSync(claudeMdPath) && !existsSync(claudeDir) && !existsSync(codebakersJson)) {
52
297
  console.log(chalk.yellow(' No CodeBakers installation found in this directory.\n'));
53
298
  console.log(chalk.gray(' Run `codebakers install` to set up patterns first.\n'));
54
299
  return;
@@ -72,11 +317,71 @@ export async function upgrade(): Promise<void> {
72
317
  return;
73
318
  }
74
319
 
75
- // Fetch latest patterns
76
- const spinner = ora('Fetching latest patterns...').start();
320
+ // Check current version and determine if migration is needed
321
+ const currentVersion = getCurrentVersion(cwd);
322
+ const spinner = ora('Checking server for latest version...').start();
77
323
 
78
324
  try {
79
325
  const apiUrl = getApiUrl();
326
+
327
+ // Check latest version from server
328
+ const versionResponse = await fetch(`${apiUrl}/api/content/version`, {
329
+ method: 'GET',
330
+ headers: {
331
+ 'Authorization': `Bearer ${apiKey}`,
332
+ },
333
+ });
334
+
335
+ if (!versionResponse.ok) {
336
+ throw new Error('Failed to check version');
337
+ }
338
+
339
+ const versionData = await versionResponse.json();
340
+ const latestVersion = versionData.version;
341
+
342
+ spinner.succeed(`Latest version: v${latestVersion}`);
343
+
344
+ // Check if we need to migrate to v6.0
345
+ const needsV6Migration = currentVersion && isVersionLessThan(currentVersion, '6.0') &&
346
+ !isVersionLessThan(latestVersion, '6.0');
347
+
348
+ if (needsV6Migration || (!currentVersion && !isVersionLessThan(latestVersion, '6.0'))) {
349
+ // Need to migrate to v6.0 server-enforced patterns
350
+ migrateToV6(cwd);
351
+
352
+ // Confirm migration to server
353
+ confirmDownload(apiUrl, apiKey, {
354
+ version: '6.0',
355
+ moduleCount: 0, // No local modules in v6
356
+ cliVersion: getCliVersion(),
357
+ command: 'upgrade-v6-migration',
358
+ }).catch(() => {});
359
+
360
+ return;
361
+ }
362
+
363
+ // For v6.0+, just confirm the installation is up to date
364
+ const stateFile = join(cwd, '.codebakers.json');
365
+ let state: Record<string, unknown> = {};
366
+ if (existsSync(stateFile)) {
367
+ try {
368
+ state = JSON.parse(readFileSync(stateFile, 'utf-8'));
369
+ } catch {
370
+ // Ignore
371
+ }
372
+ }
373
+
374
+ if (state.serverEnforced) {
375
+ // Already on v6.0+ server-enforced mode
376
+ console.log(chalk.green('\n ✅ Already using v6.0 server-enforced patterns!\n'));
377
+ console.log(chalk.gray(' Patterns are fetched from server in real-time.'));
378
+ console.log(chalk.gray(' No local updates needed.\n'));
379
+ return;
380
+ }
381
+
382
+ // Legacy upgrade for pre-6.0 versions (fetch full content)
383
+ const contentSpinner = ora('Fetching latest patterns...').start();
384
+
80
385
  const response = await fetch(`${apiUrl}/api/content`, {
81
386
  method: 'GET',
82
387
  headers: {
@@ -91,7 +396,7 @@ export async function upgrade(): Promise<void> {
91
396
 
92
397
  const content: ContentResponse = await response.json();
93
398
 
94
- spinner.succeed(`Patterns v${content.version} downloaded`);
399
+ contentSpinner.succeed(`Patterns v${content.version} downloaded`);
95
400
 
96
401
  // Count what we're updating
97
402
  const moduleCount = Object.keys(content.modules).length;
@@ -124,6 +429,10 @@ export async function upgrade(): Promise<void> {
124
429
  updatedAt: new Date().toISOString(),
125
430
  cliVersion: getCliVersion(),
126
431
  };
432
+
433
+ if (!existsSync(claudeDir)) {
434
+ mkdirSync(claudeDir, { recursive: true });
435
+ }
127
436
  writeFileSync(join(claudeDir, '.version.json'), JSON.stringify(versionInfo, null, 2));
128
437
  console.log(chalk.green(' ✓ Version info saved'));
129
438
 
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { install } from './commands/install.js';
7
7
  import { status } from './commands/status.js';
8
8
  import { uninstall } from './commands/uninstall.js';
9
9
  import { installHook, uninstallHook } from './commands/install-hook.js';
10
+ import { installPrecommit } from './commands/install-precommit.js';
10
11
  import { doctor } from './commands/doctor.js';
11
12
  import { init } from './commands/init.js';
12
13
  import { serve } from './commands/serve.js';
@@ -471,6 +472,11 @@ program
471
472
  .description('Remove the CodeBakers hook from Claude Code')
472
473
  .action(uninstallHook);
473
474
 
475
+ program
476
+ .command('install-precommit')
477
+ .description('Install git pre-commit hook for session enforcement (v6.0)')
478
+ .action(installPrecommit);
479
+
474
480
  program
475
481
  .command('doctor')
476
482
  .description('Check if CodeBakers is set up correctly')