claudekit-cli 1.0.0 → 1.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 (116) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +19 -0
  3. package/CLAUDE.md +7 -0
  4. package/README.md +61 -3
  5. package/biome.json +3 -0
  6. package/dist/index.js +102 -0
  7. package/package.json +1 -1
  8. package/src/commands/version.ts +135 -0
  9. package/src/index.ts +11 -0
  10. package/src/types.ts +7 -0
  11. package/tests/commands/version.test.ts +297 -0
  12. package/.claude/agents/brainstormer.md +0 -96
  13. package/.claude/agents/code-reviewer.md +0 -141
  14. package/.claude/agents/copywriter.md +0 -108
  15. package/.claude/agents/database-admin.md +0 -86
  16. package/.claude/agents/debugger.md +0 -124
  17. package/.claude/agents/docs-manager.md +0 -115
  18. package/.claude/agents/git-manager.md +0 -60
  19. package/.claude/agents/journal-writer.md +0 -111
  20. package/.claude/agents/planner.md +0 -87
  21. package/.claude/agents/project-manager.md +0 -113
  22. package/.claude/agents/researcher.md +0 -173
  23. package/.claude/agents/scout.md +0 -123
  24. package/.claude/agents/tester.md +0 -95
  25. package/.claude/agents/ui-ux-designer.md +0 -206
  26. package/.claude/commands/bootstrap.md +0 -104
  27. package/.claude/commands/brainstorm.md +0 -67
  28. package/.claude/commands/content/enhance.md +0 -13
  29. package/.claude/commands/content/fast.md +0 -11
  30. package/.claude/commands/content/good.md +0 -13
  31. package/.claude/commands/cook.md +0 -19
  32. package/.claude/commands/debug.md +0 -10
  33. package/.claude/commands/design/3d.md +0 -65
  34. package/.claude/commands/design/describe.md +0 -13
  35. package/.claude/commands/design/fast.md +0 -19
  36. package/.claude/commands/design/good.md +0 -23
  37. package/.claude/commands/design/screenshot.md +0 -23
  38. package/.claude/commands/design/video.md +0 -23
  39. package/.claude/commands/docs/init.md +0 -13
  40. package/.claude/commands/docs/summarize.md +0 -10
  41. package/.claude/commands/docs/update.md +0 -21
  42. package/.claude/commands/fix/ci.md +0 -11
  43. package/.claude/commands/fix/fast.md +0 -12
  44. package/.claude/commands/fix/hard.md +0 -18
  45. package/.claude/commands/fix/logs.md +0 -16
  46. package/.claude/commands/fix/test.md +0 -18
  47. package/.claude/commands/fix/types.md +0 -10
  48. package/.claude/commands/git/cm.md +0 -5
  49. package/.claude/commands/git/cp.md +0 -4
  50. package/.claude/commands/integrate/polar.md +0 -42
  51. package/.claude/commands/plan/ci.md +0 -12
  52. package/.claude/commands/plan/two.md +0 -13
  53. package/.claude/commands/plan.md +0 -10
  54. package/.claude/commands/scout.md +0 -29
  55. package/.claude/commands/test.md +0 -7
  56. package/.claude/commands/watzup.md +0 -8
  57. package/.claude/hooks/telegram_notify.sh +0 -136
  58. package/.claude/send-discord.sh +0 -64
  59. package/.claude/settings.json +0 -7
  60. package/.claude/statusline.sh +0 -143
  61. package/.claude/workflows/development-rules.md +0 -80
  62. package/.claude/workflows/documentation-management.md +0 -28
  63. package/.claude/workflows/orchestration-protocol.md +0 -16
  64. package/.claude/workflows/primary-workflow.md +0 -41
  65. package/.opencode/agent/code-reviewer.md +0 -141
  66. package/.opencode/agent/debugger.md +0 -74
  67. package/.opencode/agent/docs-manager.md +0 -119
  68. package/.opencode/agent/git-manager.md +0 -60
  69. package/.opencode/agent/planner-researcher.md +0 -100
  70. package/.opencode/agent/planner.md +0 -87
  71. package/.opencode/agent/project-manager.md +0 -113
  72. package/.opencode/agent/researcher.md +0 -173
  73. package/.opencode/agent/solution-brainstormer.md +0 -89
  74. package/.opencode/agent/system-architecture.md +0 -192
  75. package/.opencode/agent/tester.md +0 -96
  76. package/.opencode/agent/ui-ux-designer.md +0 -203
  77. package/.opencode/agent/ui-ux-developer.md +0 -97
  78. package/.opencode/command/cook.md +0 -7
  79. package/.opencode/command/debug.md +0 -10
  80. package/.opencode/command/design/3d.md +0 -65
  81. package/.opencode/command/design/fast.md +0 -18
  82. package/.opencode/command/design/good.md +0 -21
  83. package/.opencode/command/design/screenshot.md +0 -22
  84. package/.opencode/command/design/video.md +0 -22
  85. package/.opencode/command/docs/init.md +0 -11
  86. package/.opencode/command/docs/summarize.md +0 -10
  87. package/.opencode/command/docs/update.md +0 -18
  88. package/.opencode/command/fix/ci.md +0 -8
  89. package/.opencode/command/fix/fast.md +0 -11
  90. package/.opencode/command/fix/hard.md +0 -15
  91. package/.opencode/command/fix/logs.md +0 -16
  92. package/.opencode/command/fix/test.md +0 -18
  93. package/.opencode/command/fix/types.md +0 -10
  94. package/.opencode/command/git/cm.md +0 -5
  95. package/.opencode/command/git/cp.md +0 -4
  96. package/.opencode/command/plan/ci.md +0 -12
  97. package/.opencode/command/plan/two.md +0 -13
  98. package/.opencode/command/plan.md +0 -10
  99. package/.opencode/command/test.md +0 -7
  100. package/.opencode/command/watzup.md +0 -8
  101. package/docs/code-standards.md +0 -1128
  102. package/docs/codebase-summary.md +0 -821
  103. package/docs/github-setup.md +0 -176
  104. package/docs/project-pdr.md +0 -739
  105. package/docs/system-architecture.md +0 -950
  106. package/docs/tech-stack.md +0 -290
  107. package/plans/251008-claudekit-cli-implementation-plan.md +0 -1469
  108. package/plans/reports/251008-from-code-reviewer-to-developer-review-report.md +0 -864
  109. package/plans/reports/251008-from-tester-to-developer-test-summary-report.md +0 -409
  110. package/plans/reports/251008-researcher-download-extraction-report.md +0 -1377
  111. package/plans/reports/251008-researcher-github-api-report.md +0 -1339
  112. package/plans/research/251008-cli-frameworks-bun-research.md +0 -1051
  113. package/plans/templates/bug-fix-template.md +0 -69
  114. package/plans/templates/feature-implementation-template.md +0 -84
  115. package/plans/templates/refactor-template.md +0 -82
  116. package/plans/templates/template-usage-guide.md +0 -58
@@ -1,1469 +0,0 @@
1
- # ClaudeKit CLI Implementation Plan
2
-
3
- **Date**: 2025-10-08
4
- **Type**: Feature Implementation
5
- **Status**: ✅ Code Review Complete - Production Ready
6
- **Code Review**: See `./plans/reports/251008-from-code-reviewer-to-developer-review-report.md`
7
- **Context**: Initial implementation of ClaudeKit CLI tool for bootstrapping and updating projects with private GitHub repository releases
8
-
9
- ## Executive Summary
10
-
11
- ClaudeKit CLI (`ck`) is a command-line tool built with Bun and TypeScript that enables developers to quickly bootstrap new projects and update existing projects using releases from private GitHub repositories. The tool implements intelligent authentication fallback (GitHub CLI → environment variables → credential storage → user prompt), streaming downloads with progress tracking, smart file merging with conflict detection, and secure token management.
12
-
13
- **Key Value Propositions:**
14
- - Zero-configuration setup for users with GitHub CLI authentication
15
- - Fast project initialization (leveraging Bun's performance)
16
- - Safe updates with intelligent conflict resolution
17
- - Secure token management using OS-native credential stores
18
-
19
- ## Context Links
20
-
21
- - **Research Reports**:
22
- - `./plans/research/251008-cli-frameworks-bun-research.md` - CLI framework analysis
23
- - `./plans/reports/251008-researcher-github-api-report.md` - GitHub API integration
24
- - `./plans/reports/251008-researcher-download-extraction-report.md` - Download/extraction strategies
25
- - **Related Projects**:
26
- - ClaudeKit Engineer: https://github.com/mrgoonie/claudekit-engineer (private)
27
- - ClaudeKit Marketing: [coming soon]
28
- - **Reference Docs**: Will be created in `./docs` directory
29
-
30
- ## Requirements
31
-
32
- ### Functional Requirements
33
-
34
- **Core Commands:**
35
- - [ ] `ck new` - Bootstrap new project from release
36
- - [ ] Directory selection (default: current, prompt if not provided)
37
- - [ ] Kit selection (engineer, marketing [coming soon])
38
- - [ ] Version selection (default: latest)
39
- - [ ] Download and extract to target directory
40
- - [ ] Skip configuration files if they exist
41
-
42
- - [ ] `ck update` - Update existing project
43
- - [ ] Directory selection (default: current)
44
- - [ ] Kit selection
45
- - [ ] Version selection (default: latest)
46
- - [ ] Confirmation prompt before overwriting
47
- - [ ] Smart merge with conflict detection
48
- - [ ] Backup option for existing files
49
-
50
- - [ ] `ck --version` / `ck -v` - Show version information
51
- - [ ] `ck --help` / `ck -h` - Display help information
52
-
53
- **Authentication:**
54
- - [ ] Detect and use GitHub CLI authentication
55
- - [ ] Check environment variables (GITHUB_TOKEN, GH_TOKEN)
56
- - [ ] Check stored credentials in OS keychain
57
- - [ ] Prompt user for token with validation
58
- - [ ] Securely store token with user consent
59
-
60
- **Download & Extraction:**
61
- - [ ] Fetch latest release by default
62
- - [ ] Support specific version downloads
63
- - [ ] Stream downloads with progress bar
64
- - [ ] Support both .tar.gz and .zip formats
65
- - [ ] Automatic format detection
66
- - [ ] Show extraction progress
67
-
68
- **File Management:**
69
- - [ ] Smart file merging
70
- - [ ] Protected file patterns (config files, .env, etc.)
71
- - [ ] Path traversal protection
72
- - [ ] Automatic cleanup of temporary files
73
-
74
- ### Non-Functional Requirements
75
-
76
- **Performance:**
77
- - [ ] Stream large files to avoid memory issues
78
- - [ ] Use Bun's native APIs for optimal performance
79
- - [ ] Parallel operations where possible
80
- - [ ] Download speed ≥ 10MB/s on good connections
81
-
82
- **Security:**
83
- - [ ] Secure token storage using OS keychain
84
- - [ ] Path traversal validation
85
- - [ ] Input sanitization
86
- - [ ] No token logging or exposure in errors
87
- - [ ] Fine-grained PAT with minimal permissions
88
-
89
- **Usability:**
90
- - [ ] Clear progress indicators
91
- - [ ] Helpful error messages
92
- - [ ] Interactive prompts with validation
93
- - [ ] Colorized output for better readability
94
- - [ ] Graceful handling of interruptions
95
-
96
- **Reliability:**
97
- - [ ] Automatic retry with exponential backoff
98
- - [ ] Rate limit handling
99
- - [ ] Network error recovery
100
- - [ ] Atomic operations (rollback on failure)
101
- - [ ] Comprehensive error handling
102
-
103
- **Maintainability:**
104
- - [ ] TypeScript with strict mode
105
- - [ ] Modular architecture
106
- - [ ] Comprehensive JSDoc comments
107
- - [ ] Unit test coverage ≥ 80%
108
- - [ ] Clear separation of concerns
109
-
110
- ## Architecture Overview
111
-
112
- ```mermaid
113
- graph TD
114
- A[CLI Entry Point] --> B[Command Parser - CAC]
115
- B --> C{Command Type}
116
-
117
- C -->|new| D[New Command Handler]
118
- C -->|update| E[Update Command Handler]
119
- C -->|version/help| F[Info Handler]
120
-
121
- D --> G[Auth Manager]
122
- E --> G
123
-
124
- G --> H{Auth Source}
125
- H -->|gh CLI| I[GitHub CLI Token]
126
- H -->|env var| J[Environment Variable]
127
- H -->|stored| K[Keychain]
128
- H -->|prompt| L[User Input]
129
-
130
- D --> M[GitHub API Client]
131
- E --> M
132
-
133
- M --> N[Release Fetcher]
134
- N --> O[Download Manager]
135
-
136
- O --> P[Progress Tracker]
137
- O --> Q[Stream Handler]
138
-
139
- Q --> R[Temp File Manager]
140
- R --> S[Archive Extractor]
141
-
142
- S --> T{File Type}
143
- T -->|.tar.gz| U[TAR Extractor]
144
- T -->|.zip| V[ZIP Extractor]
145
-
146
- U --> W[File Merger]
147
- V --> W
148
-
149
- W --> X[Conflict Resolver]
150
- X --> Y[Target Directory]
151
-
152
- R --> Z[Cleanup Manager]
153
- ```
154
-
155
- ### Key Components
156
-
157
- **1. CLI Interface (`src/index.ts`)**
158
- - Entry point with shebang for Bun runtime
159
- - Command registration and routing
160
- - Global error handling
161
- - Version and help display
162
-
163
- **2. Command Handlers (`src/commands/`)**
164
- - `new.ts` - New project bootstrapping logic
165
- - `update.ts` - Existing project update logic
166
- - Shared validation and orchestration
167
-
168
- **3. Authentication Manager (`src/lib/auth.ts`)**
169
- - Multi-tier authentication fallback
170
- - Token validation
171
- - Secure storage integration
172
- - GitHub CLI detection
173
-
174
- **4. GitHub Client (`src/lib/github.ts`)**
175
- - Octokit wrapper with retry logic
176
- - Release listing and fetching
177
- - Asset metadata retrieval
178
- - Rate limit handling
179
-
180
- **5. Download Manager (`src/lib/download.ts`)**
181
- - Streaming download with progress
182
- - Format detection
183
- - Checksum verification (if available)
184
- - Network error recovery
185
-
186
- **6. Archive Extractor (`src/lib/extract.ts`)**
187
- - Format-specific extraction (tar, zip)
188
- - Path traversal protection
189
- - Streaming extraction
190
- - Progress reporting
191
-
192
- **7. File Merger (`src/lib/merge.ts`)**
193
- - Smart conflict detection
194
- - Protected file patterns
195
- - Interactive resolution (optional)
196
- - Backup creation
197
-
198
- **8. Utilities (`src/utils/`)**
199
- - `config.ts` - Configuration management
200
- - `logger.ts` - Structured logging with colors
201
- - `errors.ts` - Custom error classes
202
- - `validation.ts` - Input validation with Zod
203
-
204
- **9. Prompt Manager (`src/lib/prompts.ts`)**
205
- - Interactive prompts for user input
206
- - Validation and error handling
207
- - Selection menus
208
- - Confirmation dialogs
209
-
210
- ## Data Models
211
-
212
- ### Configuration Schema (Zod)
213
-
214
- ```typescript
215
- import { z } from 'zod';
216
-
217
- // CLI Options Schema
218
- export const NewCommandOptionsSchema = z.object({
219
- dir: z.string().default('.'),
220
- kit: z.enum(['engineer', 'marketing']).optional(),
221
- version: z.string().optional(),
222
- });
223
-
224
- export const UpdateCommandOptionsSchema = z.object({
225
- dir: z.string().default('.'),
226
- kit: z.enum(['engineer', 'marketing']).optional(),
227
- version: z.string().optional(),
228
- skipConfirm: z.boolean().default(false),
229
- backup: z.boolean().default(false),
230
- });
231
-
232
- // GitHub Token Schema
233
- export const GitHubTokenSchema = z.string()
234
- .regex(/^(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9_]+$/, {
235
- message: 'Invalid GitHub token format'
236
- });
237
-
238
- // Repository Configuration
239
- export const RepositoryConfigSchema = z.object({
240
- owner: z.string().min(1),
241
- repo: z.string().min(1),
242
- private: z.boolean().default(true),
243
- });
244
-
245
- // Kit Configuration
246
- export const KitConfigSchema = z.object({
247
- engineer: RepositoryConfigSchema.default({
248
- owner: 'mrgoonie',
249
- repo: 'claudekit-engineer',
250
- private: true,
251
- }),
252
- marketing: RepositoryConfigSchema.optional(),
253
- });
254
-
255
- // Release Asset Schema
256
- export const ReleaseAssetSchema = z.object({
257
- id: z.number(),
258
- name: z.string(),
259
- size: z.number(),
260
- browser_download_url: z.string().url(),
261
- content_type: z.string(),
262
- created_at: z.string(),
263
- });
264
-
265
- // Release Schema
266
- export const ReleaseSchema = z.object({
267
- id: z.number(),
268
- tag_name: z.string(),
269
- name: z.string().nullable(),
270
- body: z.string().nullable(),
271
- draft: z.boolean(),
272
- prerelease: z.boolean(),
273
- created_at: z.string(),
274
- published_at: z.string().nullable(),
275
- tarball_url: z.string().url(),
276
- zipball_url: z.string().url(),
277
- assets: z.array(ReleaseAssetSchema),
278
- });
279
-
280
- // Protected Files Pattern
281
- export const ProtectedFilePatternsSchema = z.array(z.instanceof(RegExp)).default([
282
- /\.env(\..*)?$/,
283
- /config\.(json|yaml|yml|toml)$/,
284
- /\.config\.(js|ts)$/,
285
- /package\.json$/,
286
- /bun\.lockb$/,
287
- /node_modules\//,
288
- /\.git\//,
289
- ]);
290
-
291
- // Download Progress Event
292
- export const DownloadProgressSchema = z.object({
293
- transferred: z.number(),
294
- total: z.number(),
295
- percent: z.number().min(0).max(100),
296
- bytesPerSecond: z.number().optional(),
297
- });
298
-
299
- // Authentication Result
300
- export const AuthResultSchema = z.object({
301
- method: z.enum(['github-cli', 'env-var', 'stored', 'prompt']),
302
- token: GitHubTokenSchema,
303
- username: z.string().optional(),
304
- });
305
-
306
- // Merge Conflict
307
- export const MergeConflictSchema = z.object({
308
- path: z.string(),
309
- action: z.enum(['skip', 'overwrite', 'backup']),
310
- reason: z.string().optional(),
311
- });
312
-
313
- // Operation Result
314
- export const OperationResultSchema = z.object({
315
- success: z.boolean(),
316
- message: z.string(),
317
- filesCreated: z.number().default(0),
318
- filesSkipped: z.number().default(0),
319
- filesOverwritten: z.number().default(0),
320
- conflicts: z.array(MergeConflictSchema).default([]),
321
- });
322
- ```
323
-
324
- ### TypeScript Types
325
-
326
- ```typescript
327
- // Derived types from Zod schemas
328
- export type NewCommandOptions = z.infer<typeof NewCommandOptionsSchema>;
329
- export type UpdateCommandOptions = z.infer<typeof UpdateCommandOptionsSchema>;
330
- export type GitHubToken = z.infer<typeof GitHubTokenSchema>;
331
- export type RepositoryConfig = z.infer<typeof RepositoryConfigSchema>;
332
- export type KitConfig = z.infer<typeof KitConfigSchema>;
333
- export type ReleaseAsset = z.infer<typeof ReleaseAssetSchema>;
334
- export type Release = z.infer<typeof ReleaseSchema>;
335
- export type ProtectedFilePatterns = z.infer<typeof ProtectedFilePatternsSchema>;
336
- export type DownloadProgress = z.infer<typeof DownloadProgressSchema>;
337
- export type AuthResult = z.infer<typeof AuthResultSchema>;
338
- export type MergeConflict = z.infer<typeof MergeConflictSchema>;
339
- export type OperationResult = z.infer<typeof OperationResultSchema>;
340
-
341
- // Additional utility types
342
- export type AuthMethod = 'github-cli' | 'env-var' | 'stored' | 'prompt';
343
- export type KitName = 'engineer' | 'marketing';
344
- export type ConflictAction = 'skip' | 'overwrite' | 'backup';
345
- export type ArchiveFormat = 'tar.gz' | 'zip';
346
-
347
- // Error types
348
- export class CLIError extends Error {
349
- constructor(
350
- message: string,
351
- public readonly code: string,
352
- public readonly cause?: Error
353
- ) {
354
- super(message);
355
- this.name = 'CLIError';
356
- }
357
- }
358
-
359
- export class AuthenticationError extends CLIError {
360
- constructor(message: string, cause?: Error) {
361
- super(message, 'AUTH_ERROR', cause);
362
- this.name = 'AuthenticationError';
363
- }
364
- }
365
-
366
- export class DownloadError extends CLIError {
367
- constructor(message: string, cause?: Error) {
368
- super(message, 'DOWNLOAD_ERROR', cause);
369
- this.name = 'DownloadError';
370
- }
371
- }
372
-
373
- export class ExtractionError extends CLIError {
374
- constructor(message: string, cause?: Error) {
375
- super(message, 'EXTRACTION_ERROR', cause);
376
- this.name = 'ExtractionError';
377
- }
378
- }
379
-
380
- export class FileConflictError extends CLIError {
381
- constructor(message: string, public readonly conflicts: MergeConflict[]) {
382
- super(message, 'FILE_CONFLICT_ERROR');
383
- this.name = 'FileConflictError';
384
- }
385
- }
386
- ```
387
-
388
- ## Implementation Phases
389
-
390
- ### Phase 1: Project Setup & Core Infrastructure (Est: 1 day)
391
-
392
- **Scope**: Initialize project structure, configure tooling, set up base infrastructure
393
-
394
- **Tasks**:
395
- 1. [ ] Initialize Bun project - file: `package.json`
396
- - Set up package.json with proper bin configuration
397
- - Install dependencies: cac, @clack/prompts, ora, cli-progress, picocolors, zod, @octokit/rest, keytar, tar, unzipper, fs-extra, tmp, ignore
398
- - Install dev dependencies: @types/*, bun-types
399
- - Configure scripts: dev, build, test, lint
400
-
401
- 2. [ ] Create project structure - files: `src/` directory tree
402
- ```
403
- src/
404
- ├── index.ts # CLI entry point
405
- ├── commands/
406
- │ ├── new.ts # New command
407
- │ └── update.ts # Update command
408
- ├── lib/
409
- │ ├── auth.ts # Authentication manager
410
- │ ├── github.ts # GitHub API client
411
- │ ├── download.ts # Download manager
412
- │ ├── extract.ts # Archive extractor
413
- │ ├── merge.ts # File merger
414
- │ └── prompts.ts # Prompt utilities
415
- └── utils/
416
- ├── config.ts # Configuration
417
- ├── logger.ts # Logger
418
- ├── errors.ts # Error classes
419
- └── validation.ts # Validation schemas
420
- ```
421
-
422
- 3. [ ] Set up TypeScript configuration - file: `tsconfig.json`
423
- - Enable strict mode
424
- - Configure module resolution for Bun
425
- - Set up path aliases
426
-
427
- 4. [ ] Create base configuration - file: `src/utils/config.ts`
428
- - Define kit repository mappings
429
- - Set protected file patterns
430
- - Configure defaults
431
-
432
- 5. [ ] Implement logger utility - file: `src/utils/logger.ts`
433
- - Structured logging with picocolors
434
- - Log levels (error, warn, info, debug)
435
- - Pretty formatting
436
-
437
- 6. [ ] Define error classes - file: `src/utils/errors.ts`
438
- - CLIError base class
439
- - Specific error types (Auth, Download, Extraction, FileConflict)
440
- - Error serialization
441
-
442
- 7. [ ] Create validation schemas - file: `src/utils/validation.ts`
443
- - Implement all Zod schemas
444
- - Export TypeScript types
445
- - Validation helpers
446
-
447
- **Acceptance Criteria**:
448
- - [ ] Project initializes with `bun install`
449
- - [ ] TypeScript compiles without errors
450
- - [ ] All base files created with proper exports
451
- - [ ] Logger outputs colored messages
452
- - [ ] Validation schemas parse correctly
453
-
454
- ### Phase 2: Authentication System (Est: 2 days)
455
-
456
- **Scope**: Implement multi-tier authentication with secure storage
457
-
458
- **Tasks**:
459
- 1. [ ] Implement GitHub CLI detection - file: `src/lib/auth.ts`
460
- - Execute `gh auth status` and `gh auth token`
461
- - Parse and validate token
462
- - Handle errors gracefully
463
-
464
- 2. [ ] Implement environment variable auth - file: `src/lib/auth.ts`
465
- - Check GITHUB_TOKEN and GH_TOKEN
466
- - Validate token format
467
- - Log auth method used
468
-
469
- 3. [ ] Implement credential storage - file: `src/lib/auth.ts`
470
- - Integration with keytar for OS keychain
471
- - Store with service name: 'claudekit-cli'
472
- - Retrieve and validate stored tokens
473
-
474
- 4. [ ] Implement user prompt - file: `src/lib/auth.ts`
475
- - Prompt for token with masked input
476
- - Validate token format
477
- - Show instructions for token creation
478
-
479
- 5. [ ] Implement token storage flow - file: `src/lib/auth.ts`
480
- - Ask user permission to store token
481
- - Save to keychain if approved
482
- - Handle storage errors
483
-
484
- 6. [ ] Create AuthManager class - file: `src/lib/auth.ts`
485
- - Orchestrate authentication flow
486
- - Implement fallback chain
487
- - Verify token with GitHub API
488
- - Delete stored token on failure
489
-
490
- 7. [ ] Add authentication tests - file: `tests/auth.test.ts`
491
- - Test each auth method
492
- - Test fallback chain
493
- - Test token validation
494
- - Mock GitHub API and keytar
495
-
496
- **Acceptance Criteria**:
497
- - [ ] GitHub CLI auth detected when available
498
- - [ ] Environment variables checked correctly
499
- - [ ] Tokens stored securely in OS keychain
500
- - [ ] User prompted when no auth found
501
- - [ ] Invalid tokens rejected with clear messages
502
- - [ ] Token storage requires user consent
503
- - [ ] All auth tests pass
504
-
505
- ### Phase 3: GitHub API Integration (Est: 2 days)
506
-
507
- **Scope**: Implement GitHub release fetching with retry logic
508
-
509
- **Tasks**:
510
- 1. [ ] Create Octokit wrapper - file: `src/lib/github.ts`
511
- - Initialize Octokit with auth token
512
- - Configure retry plugin
513
- - Configure throttling plugin
514
- - Set custom user agent
515
-
516
- 2. [ ] Implement release listing - file: `src/lib/github.ts`
517
- - Fetch releases with pagination
518
- - Sort by publish date
519
- - Filter out drafts and prereleases (optional)
520
- - Return release metadata
521
-
522
- 3. [ ] Implement latest release fetch - file: `src/lib/github.ts`
523
- - Get latest non-prerelease
524
- - Handle "no releases" case
525
- - Parse release metadata
526
-
527
- 4. [ ] Implement specific version fetch - file: `src/lib/github.ts`
528
- - Fetch release by tag name
529
- - Handle version not found
530
- - Support version prefixes (v1.0.0, 1.0.0)
531
-
532
- 5. [ ] Implement release download URL - file: `src/lib/github.ts`
533
- - Generate tarball/zipball URL
534
- - Handle private repository URLs
535
- - Add authentication headers
536
-
537
- 6. [ ] Implement rate limit handling - file: `src/lib/github.ts`
538
- - Check rate limit headers
539
- - Wait when rate limited
540
- - Show warning to user
541
- - Implement exponential backoff
542
-
543
- 7. [ ] Add error handling - file: `src/lib/github.ts`
544
- - Handle 404 (not found / no permission)
545
- - Handle 401 (invalid token)
546
- - Handle 403 (rate limited)
547
- - Handle network errors
548
-
549
- 8. [ ] Create GitHub client tests - file: `tests/github.test.ts`
550
- - Mock Octokit responses
551
- - Test release fetching
552
- - Test error scenarios
553
- - Test rate limiting
554
-
555
- **Acceptance Criteria**:
556
- - [ ] Latest release fetched successfully
557
- - [ ] Specific versions fetched by tag
558
- - [ ] Private repositories accessible with token
559
- - [ ] Rate limits handled gracefully
560
- - [ ] 404 errors show helpful messages
561
- - [ ] All GitHub tests pass
562
-
563
- ### Phase 4: Download & Extraction (Est: 2 days)
564
-
565
- **Scope**: Implement streaming download with progress and archive extraction
566
-
567
- **Tasks**:
568
- 1. [ ] Implement streaming download - file: `src/lib/download.ts`
569
- - Use Bun's native fetch
570
- - Stream to temporary file
571
- - Track transfer progress
572
- - Calculate speed
573
-
574
- 2. [ ] Implement progress tracking - file: `src/lib/download.ts`
575
- - Create cli-progress bar
576
- - Update with download progress
577
- - Show bytes transferred and total
578
- - Show transfer speed and ETA
579
-
580
- 3. [ ] Add download error handling - file: `src/lib/download.ts`
581
- - Handle network timeouts
582
- - Implement retry logic
583
- - Clean up on failure
584
- - Show meaningful error messages
585
-
586
- 4. [ ] Implement tar.gz extraction - file: `src/lib/extract.ts`
587
- - Use tar package
588
- - Strip top-level directory
589
- - Stream extraction
590
- - Path traversal protection
591
-
592
- 5. [ ] Implement zip extraction - file: `src/lib/extract.ts`
593
- - Use unzipper package
594
- - Stream extraction
595
- - Path traversal protection
596
- - Handle corrupted archives
597
-
598
- 6. [ ] Add format detection - file: `src/lib/extract.ts`
599
- - Detect from Content-Type header
600
- - Detect from file extension
601
- - Detect from magic bytes
602
- - Fallback to tar.gz
603
-
604
- 7. [ ] Implement extraction progress - file: `src/lib/extract.ts`
605
- - Show spinner during extraction
606
- - List files as extracted
607
- - Count total files extracted
608
- - Handle extraction errors
609
-
610
- 8. [ ] Create temporary file manager - file: `src/lib/download.ts`
611
- - Use tmp package with auto-cleanup
612
- - Generate unique temp directories
613
- - Clean up on success
614
- - Clean up on failure
615
-
616
- 9. [ ] Add download/extraction tests - file: `tests/download.test.ts`, `tests/extract.test.ts`
617
- - Mock fetch responses
618
- - Test progress tracking
619
- - Test both archive formats
620
- - Test error scenarios
621
-
622
- **Acceptance Criteria**:
623
- - [ ] Files download with streaming
624
- - [ ] Progress bar shows accurate progress
625
- - [ ] Both tar.gz and zip formats extract
626
- - [ ] Top-level directory stripped correctly
627
- - [ ] Path traversal attacks prevented
628
- - [ ] Temp files cleaned up automatically
629
- - [ ] All download/extraction tests pass
630
-
631
- ### Phase 5: File Merging & Conflict Resolution (Est: 2 days)
632
-
633
- **Scope**: Implement smart file merging with conflict detection
634
-
635
- **Tasks**:
636
- 1. [ ] Implement conflict detection - file: `src/lib/merge.ts`
637
- - Scan target directory for existing files
638
- - Compare with extracted files
639
- - Identify conflicts
640
- - Categorize by file type
641
-
642
- 2. [ ] Implement protected file filtering - file: `src/lib/merge.ts`
643
- - Define protected patterns
644
- - Check each file against patterns
645
- - Skip protected files if they exist
646
- - Log skipped files
647
-
648
- 3. [ ] Implement smart merge logic - file: `src/lib/merge.ts`
649
- - Skip existing config files
650
- - Overwrite code files
651
- - Create new files
652
- - Preserve directory structure
653
-
654
- 4. [ ] Add interactive conflict resolution - file: `src/lib/merge.ts`
655
- - Show conflicts to user
656
- - Prompt for each conflict
657
- - Options: skip, overwrite, backup
658
- - Remember choice for similar files
659
-
660
- 5. [ ] Implement backup functionality - file: `src/lib/merge.ts`
661
- - Create timestamped backup directory
662
- - Copy conflicting files to backup
663
- - Show backup location
664
- - Option to restore from backup
665
-
666
- 6. [ ] Add merge progress - file: `src/lib/merge.ts`
667
- - Show spinner during merge
668
- - List files as they're processed
669
- - Count files created/skipped/overwritten
670
- - Summary at the end
671
-
672
- 7. [ ] Create file merger tests - file: `tests/merge.test.ts`
673
- - Test conflict detection
674
- - Test protected file filtering
675
- - Test merge strategies
676
- - Test backup creation
677
-
678
- **Acceptance Criteria**:
679
- - [ ] Conflicts detected accurately
680
- - [ ] Protected files never overwritten
681
- - [ ] Interactive mode prompts for conflicts
682
- - [ ] Backup created when requested
683
- - [ ] Merge summary shows accurate counts
684
- - [ ] All merge tests pass
685
-
686
- ### Phase 6: Command Implementation (Est: 2 days)
687
-
688
- **Scope**: Implement `ck new` and `ck update` commands
689
-
690
- **Tasks**:
691
- 1. [ ] Implement `ck new` command - file: `src/commands/new.ts`
692
- - Parse command options
693
- - Validate directory (must not exist or be empty)
694
- - Prompt for kit if not provided
695
- - Prompt for directory if not provided
696
- - Orchestrate auth → fetch → download → extract → merge
697
- - Show success message with next steps
698
-
699
- 2. [ ] Implement `ck update` command - file: `src/commands/update.ts`
700
- - Parse command options
701
- - Validate directory (must exist)
702
- - Prompt for kit if not provided
703
- - Show confirmation prompt
704
- - Orchestrate auth → fetch → download → extract → merge
705
- - Show update summary
706
-
707
- 3. [ ] Implement directory validation - file: `src/commands/new.ts`, `src/commands/update.ts`
708
- - Check directory exists
709
- - Check directory is empty (for new)
710
- - Check directory is writable
711
- - Expand relative paths
712
-
713
- 4. [ ] Implement kit selection - file: `src/lib/prompts.ts`
714
- - Show selection menu
715
- - List available kits
716
- - Show kit descriptions
717
- - Validate selection
718
-
719
- 5. [ ] Implement version selection - file: `src/lib/prompts.ts`
720
- - Fetch available versions
721
- - Show selection menu
722
- - Default to latest
723
- - Validate version exists
724
-
725
- 6. [ ] Add confirmation prompts - file: `src/lib/prompts.ts`
726
- - Confirm before update
727
- - Show what will be changed
728
- - Allow cancellation
729
- - Default to yes/no appropriately
730
-
731
- 7. [ ] Create command tests - file: `tests/commands.test.ts`
732
- - Test new command flow
733
- - Test update command flow
734
- - Test validation
735
- - Test error handling
736
-
737
- **Acceptance Criteria**:
738
- - [ ] `ck new` creates new projects successfully
739
- - [ ] `ck update` updates existing projects
740
- - [ ] Directory validation works correctly
741
- - [ ] Prompts show when options missing
742
- - [ ] Confirmation required for updates
743
- - [ ] Error messages are helpful
744
- - [ ] All command tests pass
745
-
746
- ### Phase 7: CLI Interface & Entry Point (Est: 1 day)
747
-
748
- **Scope**: Implement main CLI entry point with CAC
749
-
750
- **Tasks**:
751
- 1. [ ] Create CLI entry point - file: `src/index.ts`
752
- - Add shebang for Bun runtime
753
- - Initialize CAC
754
- - Register commands
755
- - Set up global options
756
- - Implement error handling
757
-
758
- 2. [ ] Implement version command - file: `src/index.ts`
759
- - Read version from package.json
760
- - Show version with `--version` or `-v`
761
- - Show runtime info (Bun version)
762
-
763
- 3. [ ] Implement help command - file: `src/index.ts`
764
- - Generate help text automatically
765
- - Show usage examples
766
- - List all commands and options
767
- - Show with `--help` or `-h`
768
-
769
- 4. [ ] Add global error handler - file: `src/index.ts`
770
- - Catch all unhandled errors
771
- - Show user-friendly messages
772
- - Log stack traces in debug mode
773
- - Exit with appropriate codes
774
-
775
- 5. [ ] Configure package.json bin - file: `package.json`
776
- - Set bin field to src/index.ts
777
- - Ensure executable permissions
778
- - Test with `bun link`
779
-
780
- 6. [ ] Add color theming - file: `src/utils/logger.ts`
781
- - Success messages in green
782
- - Errors in red
783
- - Warnings in yellow
784
- - Info in cyan
785
- - Dimmed for secondary info
786
-
787
- 7. [ ] Create CLI integration tests - file: `tests/cli.test.ts`
788
- - Test command parsing
789
- - Test version display
790
- - Test help display
791
- - Test error handling
792
-
793
- **Acceptance Criteria**:
794
- - [ ] CLI starts with `ck` command
795
- - [ ] All commands accessible
796
- - [ ] Help text is comprehensive
797
- - [ ] Version displays correctly
798
- - [ ] Errors show helpful messages
799
- - [ ] Colors enhance readability
800
- - [ ] All CLI tests pass
801
-
802
- ### Phase 8: Testing & Quality Assurance (Est: 2 days)
803
-
804
- **Scope**: Comprehensive testing and quality assurance
805
-
806
- **Tasks**:
807
- 1. [ ] Write unit tests - files: `tests/*.test.ts`
808
- - Authentication manager tests
809
- - GitHub client tests
810
- - Download manager tests
811
- - Extraction tests
812
- - Merge logic tests
813
- - Validation tests
814
- - Target: 80% coverage
815
-
816
- 2. [ ] Write integration tests - file: `tests/integration.test.ts`
817
- - End-to-end new command flow
818
- - End-to-end update command flow
819
- - Error scenario testing
820
- - Mock GitHub API responses
821
-
822
- 3. [ ] Add input validation tests - file: `tests/validation.test.ts`
823
- - Test all Zod schemas
824
- - Test edge cases
825
- - Test error messages
826
- - Test type inference
827
-
828
- 4. [ ] Create test fixtures - directory: `tests/fixtures/`
829
- - Sample archives
830
- - Mock GitHub responses
831
- - Sample directory structures
832
- - Configuration files
833
-
834
- 5. [ ] Set up test infrastructure - file: `tests/setup.ts`
835
- - Configure test environment
836
- - Mock external dependencies
837
- - Set up test helpers
838
- - Configure test timeouts
839
-
840
- 6. [ ] Manual testing checklist - file: `tests/MANUAL_TESTING.md`
841
- - Test on macOS
842
- - Test with GitHub CLI auth
843
- - Test with token auth
844
- - Test with invalid credentials
845
- - Test new project creation
846
- - Test project updates
847
- - Test conflict resolution
848
- - Test error scenarios
849
-
850
- 7. [ ] Code quality checks - various files
851
- - Run linter
852
- - Fix linting issues
853
- - Add JSDoc comments
854
- - Review error messages
855
-
856
- **Acceptance Criteria**:
857
- - [ ] Unit test coverage ≥ 80%
858
- - [ ] All integration tests pass
859
- - [ ] Manual testing checklist complete
860
- - [ ] No linting errors
861
- - [ ] All functions have JSDoc comments
862
- - [ ] Error messages are helpful and actionable
863
-
864
- ### Phase 9: Documentation & Distribution (Est: 1 day)
865
-
866
- **Scope**: Create documentation and build distribution
867
-
868
- **Tasks**:
869
- 1. [ ] Create README.md - file: `README.md`
870
- - Project overview
871
- - Installation instructions
872
- - Usage examples
873
- - Command reference
874
- - Authentication setup
875
- - Troubleshooting guide
876
-
877
- 2. [ ] Create CONTRIBUTING.md - file: `CONTRIBUTING.md`
878
- - Development setup
879
- - Code style guide
880
- - Testing requirements
881
- - Pull request process
882
-
883
- 3. [ ] Create CHANGELOG.md - file: `CHANGELOG.md`
884
- - Initial release notes
885
- - Feature list
886
- - Known limitations
887
-
888
- 4. [ ] Add inline documentation - various files
889
- - JSDoc for all public functions
890
- - Type documentation
891
- - Usage examples in comments
892
-
893
- 5. [ ] Configure build process - file: `package.json`
894
- - Add build script for compilation
895
- - Configure Bun bundler
896
- - Set up cross-platform builds
897
- - Create standalone executables
898
-
899
- 6. [ ] Test distribution - local
900
- - Build executable with `bun build --compile`
901
- - Test on clean system
902
- - Verify all features work
903
- - Check file size
904
-
905
- 7. [ ] Create release checklist - file: `.github/RELEASE_CHECKLIST.md`
906
- - Pre-release testing
907
- - Version bumping
908
- - Changelog update
909
- - Tag creation
910
- - Binary builds
911
-
912
- **Acceptance Criteria**:
913
- - [ ] README is comprehensive and clear
914
- - [ ] All public APIs documented
915
- - [ ] Executable builds successfully
916
- - [ ] Build size is reasonable (< 100MB)
917
- - [ ] Executable runs on clean system
918
- - [ ] Documentation covers all features
919
-
920
- ## Testing Strategy
921
-
922
- ### Unit Tests
923
-
924
- **Target Coverage**: 80%+
925
-
926
- **Test Files**:
927
- - `tests/auth.test.ts` - Authentication manager
928
- - `tests/github.test.ts` - GitHub API client
929
- - `tests/download.test.ts` - Download manager
930
- - `tests/extract.test.ts` - Archive extraction
931
- - `tests/merge.test.ts` - File merging
932
- - `tests/validation.test.ts` - Input validation
933
- - `tests/config.test.ts` - Configuration
934
- - `tests/logger.test.ts` - Logger utility
935
-
936
- **Mocking Strategy**:
937
- - Mock `fetch` for HTTP requests
938
- - Mock `execSync` for GitHub CLI
939
- - Mock `keytar` for credential storage
940
- - Mock file system operations
941
- - Mock Octokit responses
942
-
943
- **Example Test**:
944
- ```typescript
945
- import { describe, test, expect, mock } from 'bun:test';
946
- import { AuthManager } from '../src/lib/auth';
947
-
948
- describe('AuthManager', () => {
949
- test('should detect GitHub CLI token', async () => {
950
- const mockExecSync = mock(() => 'ghp_mocktoken123');
951
- const authManager = new AuthManager();
952
- const result = await authManager.getToken();
953
-
954
- expect(result.method).toBe('github-cli');
955
- expect(result.token).toMatch(/^ghp_/);
956
- });
957
-
958
- test('should fall back to environment variable', async () => {
959
- process.env.GITHUB_TOKEN = 'ghp_envtoken456';
960
- const authManager = new AuthManager();
961
- const result = await authManager.getToken();
962
-
963
- expect(result.method).toBe('env-var');
964
- expect(result.token).toBe('ghp_envtoken456');
965
- });
966
-
967
- test('should prompt user when no auth found', async () => {
968
- // Mock all auth sources to fail
969
- // Mock prompt to return token
970
- const authManager = new AuthManager();
971
- const result = await authManager.getToken();
972
-
973
- expect(result.method).toBe('prompt');
974
- });
975
- });
976
- ```
977
-
978
- ### Integration Tests
979
-
980
- **Test Scenarios**:
981
- 1. **New Project Flow**
982
- - Start with empty directory
983
- - Run `ck new --kit engineer`
984
- - Verify files created
985
- - Verify configuration preserved
986
-
987
- 2. **Update Project Flow**
988
- - Start with existing project
989
- - Modify some files
990
- - Run `ck update`
991
- - Verify updates applied
992
- - Verify custom files preserved
993
-
994
- 3. **Authentication Flow**
995
- - Test with no auth
996
- - Test with GitHub CLI
997
- - Test with environment variable
998
- - Test with stored token
999
- - Test with invalid token
1000
-
1001
- 4. **Error Scenarios**
1002
- - Network timeout
1003
- - Invalid version
1004
- - No permission
1005
- - Rate limited
1006
- - Disk full
1007
-
1008
- **Example Integration Test**:
1009
- ```typescript
1010
- import { describe, test, expect } from 'bun:test';
1011
- import { execSync } from 'child_process';
1012
- import fs from 'fs-extra';
1013
- import path from 'path';
1014
- import tmp from 'tmp';
1015
-
1016
- describe('Integration: ck new', () => {
1017
- test('should create new project', async () => {
1018
- const tmpDir = tmp.dirSync({ unsafeCleanup: true });
1019
-
1020
- try {
1021
- // Run CLI command
1022
- execSync(`bun run src/index.ts new --dir ${tmpDir.name} --kit engineer`, {
1023
- env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }
1024
- });
1025
-
1026
- // Verify files created
1027
- expect(fs.existsSync(path.join(tmpDir.name, 'package.json'))).toBe(true);
1028
- expect(fs.existsSync(path.join(tmpDir.name, 'README.md'))).toBe(true);
1029
-
1030
- // Verify config files preserved
1031
- const hasEnvExample = fs.existsSync(path.join(tmpDir.name, '.env.example'));
1032
- expect(hasEnvExample).toBe(true);
1033
- } finally {
1034
- tmpDir.removeCallback();
1035
- }
1036
- });
1037
- });
1038
- ```
1039
-
1040
- ### E2E Tests
1041
-
1042
- **Manual Testing Scenarios**:
1043
- 1. Fresh installation on clean system
1044
- 2. Authentication with each method
1045
- 3. Creating new project
1046
- 4. Updating existing project
1047
- 5. Handling conflicts
1048
- 6. Network interruption recovery
1049
- 7. Invalid input handling
1050
- 8. Help and version commands
1051
-
1052
- **Test Environments**:
1053
- - macOS (primary)
1054
- - Linux (CI/CD)
1055
- - Windows (optional)
1056
-
1057
- ### Performance Tests
1058
-
1059
- **Metrics to Track**:
1060
- - Download speed (should match network speed)
1061
- - Extraction time (< 10s for 50MB archive)
1062
- - Memory usage (< 100MB during operation)
1063
- - Startup time (< 500ms)
1064
-
1065
- **Benchmarking**:
1066
- ```typescript
1067
- import { describe, test } from 'bun:test';
1068
-
1069
- describe('Performance', () => {
1070
- test('should download 50MB in reasonable time', async () => {
1071
- const start = Date.now();
1072
- await downloadFile('https://example.com/50mb.tar.gz');
1073
- const duration = Date.now() - start;
1074
-
1075
- // Should complete in < 30s on 10Mbps connection
1076
- expect(duration).toBeLessThan(30000);
1077
- });
1078
-
1079
- test('should use < 100MB memory', async () => {
1080
- const before = process.memoryUsage().heapUsed;
1081
- await downloadAndExtract(largeArchiveUrl);
1082
- const after = process.memoryUsage().heapUsed;
1083
- const used = (after - before) / 1024 / 1024;
1084
-
1085
- expect(used).toBeLessThan(100);
1086
- });
1087
- });
1088
- ```
1089
-
1090
- ## Security Considerations
1091
-
1092
- ### Token Security
1093
-
1094
- **Storage**:
1095
- - [ ] Use OS-native keychain (keytar)
1096
- - [ ] Never store tokens in plain text files
1097
- - [ ] Never log tokens
1098
- - [ ] Sanitize tokens in error messages
1099
- - [ ] Clear tokens from memory after use
1100
-
1101
- **Validation**:
1102
- - [ ] Validate token format with regex
1103
- - [ ] Verify token with GitHub API before storing
1104
- - [ ] Set minimal required permissions
1105
- - [ ] Support fine-grained PATs
1106
-
1107
- **Code Example**:
1108
- ```typescript
1109
- // Good: Sanitized error logging
1110
- try {
1111
- await octokit.request('/user');
1112
- } catch (error) {
1113
- logger.error('Authentication failed. Please check your token.');
1114
- // Never: logger.error(`Auth failed with token: ${token}`);
1115
- }
1116
-
1117
- // Good: Token validation
1118
- const isValidToken = (token: string): boolean => {
1119
- return /^(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9_]+$/.test(token);
1120
- };
1121
- ```
1122
-
1123
- ### Path Traversal Protection
1124
-
1125
- **Validation**:
1126
- - [ ] Resolve all paths to absolute
1127
- - [ ] Check paths are within target directory
1128
- - [ ] Reject paths with `..`
1129
- - [ ] Validate before extraction
1130
-
1131
- **Code Example**:
1132
- ```typescript
1133
- function isPathSafe(basePath: string, targetPath: string): boolean {
1134
- const resolvedBase = path.resolve(basePath);
1135
- const resolvedTarget = path.resolve(targetPath);
1136
- return resolvedTarget.startsWith(resolvedBase);
1137
- }
1138
-
1139
- // Use in extraction filter
1140
- await tar.extract({
1141
- file: archivePath,
1142
- cwd: outputDir,
1143
- filter: (filePath) => {
1144
- const fullPath = path.join(outputDir, filePath);
1145
- if (!isPathSafe(outputDir, fullPath)) {
1146
- logger.warn(`Blocked path traversal attempt: ${filePath}`);
1147
- return false;
1148
- }
1149
- return true;
1150
- }
1151
- });
1152
- ```
1153
-
1154
- ### Input Validation
1155
-
1156
- **Validation Points**:
1157
- - [ ] Command arguments
1158
- - [ ] Option values
1159
- - [ ] File paths
1160
- - [ ] URLs
1161
- - [ ] Tokens
1162
-
1163
- **Code Example**:
1164
- ```typescript
1165
- import { z } from 'zod';
1166
-
1167
- // Validate directory path
1168
- const DirectorySchema = z.string()
1169
- .min(1, 'Directory path cannot be empty')
1170
- .refine((p) => !p.includes('..'), 'Invalid path')
1171
- .transform((p) => path.resolve(p));
1172
-
1173
- // Validate GitHub token
1174
- const TokenSchema = z.string()
1175
- .regex(/^(ghp_|gho_)[a-zA-Z0-9_]+$/, 'Invalid token format');
1176
-
1177
- // Validate kit name
1178
- const KitSchema = z.enum(['engineer', 'marketing'], {
1179
- errorMap: () => ({ message: 'Invalid kit name' })
1180
- });
1181
- ```
1182
-
1183
- ### Network Security
1184
-
1185
- **Best Practices**:
1186
- - [ ] Use HTTPS only
1187
- - [ ] Verify SSL certificates
1188
- - [ ] Implement request timeouts
1189
- - [ ] Rate limit protection
1190
- - [ ] Retry with exponential backoff
1191
-
1192
- **Code Example**:
1193
- ```typescript
1194
- // Good: Proper fetch configuration
1195
- const response = await fetch(url, {
1196
- headers: {
1197
- 'Authorization': `Bearer ${token}`,
1198
- 'User-Agent': 'claudekit-cli/1.0.0'
1199
- },
1200
- signal: AbortSignal.timeout(30000), // 30s timeout
1201
- // Never: rejectUnauthorized: false
1202
- });
1203
- ```
1204
-
1205
- ### File System Security
1206
-
1207
- **Best Practices**:
1208
- - [ ] Check file permissions
1209
- - [ ] Validate before write
1210
- - [ ] Clean up temporary files
1211
- - [ ] Atomic operations
1212
- - [ ] Handle EACCES errors
1213
-
1214
- **Code Example**:
1215
- ```typescript
1216
- // Check write permission
1217
- async function canWrite(dirPath: string): Promise<boolean> {
1218
- try {
1219
- await fs.access(dirPath, fs.constants.W_OK);
1220
- return true;
1221
- } catch {
1222
- return false;
1223
- }
1224
- }
1225
-
1226
- // Atomic write operation
1227
- async function safeWrite(filePath: string, content: string) {
1228
- const tmpFile = `${filePath}.tmp`;
1229
- try {
1230
- await fs.writeFile(tmpFile, content);
1231
- await fs.rename(tmpFile, filePath);
1232
- } catch (error) {
1233
- await fs.remove(tmpFile).catch(() => {});
1234
- throw error;
1235
- }
1236
- }
1237
- ```
1238
-
1239
- ## Risk Assessment
1240
-
1241
- | Risk | Impact | Probability | Mitigation |
1242
- |------|--------|-------------|------------|
1243
- | **GitHub API rate limiting** | High | Medium | Implement exponential backoff, cache release data, use authenticated requests |
1244
- | **Network interruption during download** | Medium | Medium | Implement retry logic, resume support, show clear error messages |
1245
- | **Token exposure in logs/errors** | High | Low | Sanitize all logs, use structured logging, never log tokens |
1246
- | **Path traversal attack** | High | Low | Validate all paths, use allowlist approach, test with malicious archives |
1247
- | **Dependency vulnerabilities** | Medium | Medium | Regular updates, use `bun audit`, pin versions |
1248
- | **Incomplete cleanup on error** | Low | Medium | Use try-finally blocks, tmp package auto-cleanup, process exit handlers |
1249
- | **File permission issues** | Medium | Medium | Check permissions before write, handle EACCES gracefully |
1250
- | **Memory exhaustion on large files** | Medium | Low | Stream all operations, limit chunk sizes, monitor memory usage |
1251
- | **Configuration file overwrite** | High | Low | Protected file patterns, confirmation prompts, backup option |
1252
- | **Breaking changes in GitHub API** | Medium | Low | Pin Octokit version, test with multiple API versions |
1253
- | **Incompatible archive formats** | Low | Low | Detect format before extraction, show clear error messages |
1254
- | **Keychain access denied** | Low | Medium | Fallback to environment variables, show clear instructions |
1255
-
1256
- ## Quick Reference
1257
-
1258
- ### Key Commands
1259
-
1260
- ```bash
1261
- # Development
1262
- bun install # Install dependencies
1263
- bun run dev # Run in development mode
1264
- bun test # Run tests
1265
- bun run build # Build executable
1266
-
1267
- # Testing locally
1268
- bun link # Link globally for testing
1269
- ck new --kit engineer # Test new command
1270
- ck update --kit engineer # Test update command
1271
- bun unlink # Unlink after testing
1272
-
1273
- # Building
1274
- bun build --compile src/index.ts --outfile ck # Build standalone executable
1275
- bun build --compile --minify --sourcemap src/index.ts --outfile ck # Optimized build
1276
-
1277
- # Cross-platform builds
1278
- bun build --compile src/index.ts --target=bun-darwin-arm64 --outfile ck-macos-arm64
1279
- bun build --compile src/index.ts --target=bun-darwin-x64 --outfile ck-macos-x64
1280
- bun build --compile src/index.ts --target=bun-linux-x64 --outfile ck-linux
1281
- bun build --compile src/index.ts --target=bun-windows-x64 --outfile ck.exe
1282
- ```
1283
-
1284
- ### Configuration Files
1285
-
1286
- - `package.json`: Project metadata, dependencies, scripts, bin configuration
1287
- - `tsconfig.json`: TypeScript compiler configuration
1288
- - `bunfig.toml`: Bun runtime configuration (optional)
1289
- - `src/utils/config.ts`: Application configuration, kit mappings, protected patterns
1290
- - `.env`: Local environment variables (not committed)
1291
- - `.env.example`: Example environment variables template
1292
-
1293
- ### Environment Variables
1294
-
1295
- ```bash
1296
- # GitHub Authentication
1297
- GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx # Personal Access Token
1298
- GH_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx # Alternative name
1299
-
1300
- # CLI Configuration (optional)
1301
- CK_DEFAULT_KIT=engineer # Default kit name
1302
- CK_SKIP_CONFIRMATION=false # Skip update confirmation
1303
- CK_BACKUP_ON_UPDATE=false # Always create backup on update
1304
- CK_DEBUG=false # Enable debug logging
1305
- ```
1306
-
1307
- ### Protected File Patterns
1308
-
1309
- Files that will never be overwritten if they exist:
1310
- - `.env`, `.env.*` - Environment variables
1311
- - `config.json`, `config.yaml`, `config.yml`, `config.toml` - Configuration files
1312
- - `*.config.js`, `*.config.ts` - Configuration modules
1313
- - `package.json` - Package metadata
1314
- - `bun.lockb` - Dependency lock file
1315
- - `node_modules/` - Dependencies
1316
- - `.git/` - Git repository
1317
-
1318
- ### GitHub Token Permissions
1319
-
1320
- **Fine-Grained PAT (Recommended)**:
1321
- - Repository access: Select specific repository (e.g., `mrgoonie/claudekit-engineer`)
1322
- - Permissions:
1323
- - ✅ Contents: Read
1324
- - ✅ Metadata: Read (auto-included)
1325
-
1326
- **Classic PAT (Legacy)**:
1327
- - Scopes: `repo` (full repository access)
1328
-
1329
- **Creating a Token**:
1330
- 1. Go to https://github.com/settings/tokens
1331
- 2. Generate new token (fine-grained recommended)
1332
- 3. Set expiration (30-90 days recommended)
1333
- 4. Select repository access
1334
- 5. Grant minimum required permissions
1335
- 6. Copy token immediately (shown only once)
1336
-
1337
- ## TODO Checklist
1338
-
1339
- ### Phase 1: Setup
1340
- - [ ] Initialize Bun project with package.json
1341
- - [ ] Install all dependencies
1342
- - [ ] Create directory structure
1343
- - [ ] Configure TypeScript
1344
- - [ ] Implement base utilities (logger, config, errors)
1345
- - [ ] Define Zod schemas
1346
-
1347
- ### Phase 2: Authentication
1348
- - [ ] Implement GitHub CLI detection
1349
- - [ ] Implement environment variable auth
1350
- - [ ] Implement keychain storage
1351
- - [ ] Implement user prompt
1352
- - [ ] Create AuthManager class
1353
- - [ ] Add authentication tests
1354
-
1355
- ### Phase 3: GitHub API
1356
- - [ ] Create Octokit wrapper
1357
- - [ ] Implement release listing
1358
- - [ ] Implement latest release fetch
1359
- - [ ] Implement version fetch
1360
- - [ ] Add rate limit handling
1361
- - [ ] Add error handling
1362
- - [ ] Create GitHub tests
1363
-
1364
- ### Phase 4: Download & Extract
1365
- - [ ] Implement streaming download
1366
- - [ ] Add progress tracking
1367
- - [ ] Implement tar.gz extraction
1368
- - [ ] Implement zip extraction
1369
- - [ ] Add format detection
1370
- - [ ] Create temp file manager
1371
- - [ ] Add download/extraction tests
1372
-
1373
- ### Phase 5: File Merging
1374
- - [ ] Implement conflict detection
1375
- - [ ] Add protected file filtering
1376
- - [ ] Implement smart merge
1377
- - [ ] Add interactive resolution
1378
- - [ ] Implement backup functionality
1379
- - [ ] Create merge tests
1380
-
1381
- ### Phase 6: Commands
1382
- - [ ] Implement `ck new` command
1383
- - [ ] Implement `ck update` command
1384
- - [ ] Add directory validation
1385
- - [ ] Create prompt utilities
1386
- - [ ] Add command tests
1387
-
1388
- ### Phase 7: CLI Interface
1389
- - [ ] Create CLI entry point
1390
- - [ ] Implement version command
1391
- - [ ] Implement help command
1392
- - [ ] Add global error handler
1393
- - [ ] Configure package.json bin
1394
- - [ ] Add CLI tests
1395
-
1396
- ### Phase 8: Testing
1397
- - [ ] Write all unit tests
1398
- - [ ] Write integration tests
1399
- - [ ] Create test fixtures
1400
- - [ ] Manual testing
1401
- - [ ] Code quality checks
1402
-
1403
- ### Phase 9: Documentation
1404
- - [ ] Create README.md
1405
- - [ ] Create CONTRIBUTING.md
1406
- - [ ] Create CHANGELOG.md
1407
- - [ ] Add inline documentation
1408
- - [ ] Configure build process
1409
- - [ ] Test distribution
1410
-
1411
- ### Final Checks
1412
- - [ ] All tests pass
1413
- - [ ] Test coverage ≥ 80%
1414
- - [ ] No linting errors
1415
- - [ ] Manual testing complete
1416
- - [ ] Documentation complete
1417
- - [ ] Executable builds successfully
1418
- - [ ] Ready for release
1419
-
1420
- ---
1421
-
1422
- ## Implementation Notes
1423
-
1424
- ### Development Workflow
1425
-
1426
- 1. **Start with authentication** - It's foundational for all other features
1427
- 2. **Test incrementally** - Write tests as you implement each module
1428
- 3. **Mock external dependencies** - Don't rely on real GitHub API during development
1429
- 4. **Use temporary directories** - Always clean up after tests
1430
- 5. **Handle errors gracefully** - Every operation should have proper error handling
1431
-
1432
- ### Code Organization
1433
-
1434
- - Keep files under 500 lines
1435
- - One class/function per file when possible
1436
- - Separate concerns: auth, download, extract, merge
1437
- - Use dependency injection for testability
1438
- - Export interfaces for all public APIs
1439
-
1440
- ### Performance Considerations
1441
-
1442
- - Stream everything (downloads, extraction, file operations)
1443
- - Use Bun's native APIs (Bun.write, Bun.file)
1444
- - Avoid loading large files into memory
1445
- - Use progress indicators for long operations
1446
- - Implement timeouts for network operations
1447
-
1448
- ### Error Handling
1449
-
1450
- - Create specific error classes
1451
- - Include context in error messages
1452
- - Show actionable error messages to users
1453
- - Log full errors in debug mode
1454
- - Handle cleanup in finally blocks
1455
-
1456
- ### Testing Strategy
1457
-
1458
- - Mock external dependencies
1459
- - Test error paths
1460
- - Test edge cases
1461
- - Use fixtures for consistent test data
1462
- - Run tests in isolation
1463
-
1464
- ---
1465
-
1466
- **Plan Created**: 2025-10-08
1467
- **Estimated Total Time**: 13 days
1468
- **Priority**: High
1469
- **Status**: Ready for Implementation