ralphie 1.0.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.
@@ -0,0 +1,576 @@
1
+ # Claude Coding Standards for Ralphie Projects
2
+
3
+ This file defines coding standards and preferences for AI agents working in Ralphie loops.
4
+
5
+ ## Language Preferences
6
+
7
+ ### Default: TypeScript
8
+ - Use TypeScript by default for all new projects unless requirements explicitly state otherwise
9
+ - Prefer strict mode: `"strict": true` in tsconfig.json
10
+ - Use modern ES6+ syntax (async/await, destructuring, arrow functions)
11
+
12
+ ### When to use Python
13
+ - Data science, ML, or scientific computing projects
14
+ - When SPEC explicitly requires Python
15
+ - When existing codebase is Python
16
+ - For CLI tools where Python stdlib is sufficient
17
+
18
+ ### When to use other languages
19
+ - Follow the existing codebase language
20
+ - Respect SPEC requirements
21
+ - Go for systems programming or high-performance needs
22
+ - Rust for systems-level safety requirements
23
+
24
+ ## Code Style
25
+
26
+ ### Comments
27
+ - **NO comments unless absolutely necessary**
28
+ - Code should be self-documenting through clear naming
29
+ - Only add comments for:
30
+ - Complex algorithms that aren't immediately obvious
31
+ - Edge cases and gotchas
32
+ - Public API documentation (JSDoc/docstrings)
33
+ - "Why" not "what" - explain reasoning, not mechanics
34
+
35
+ **Bad:**
36
+ ```typescript
37
+ // Get the user name
38
+ const userName = user.name;
39
+
40
+ // Loop through items
41
+ for (const item of items) {
42
+ // Process the item
43
+ processItem(item);
44
+ }
45
+ ```
46
+
47
+ **Good:**
48
+ ```typescript
49
+ const userName = user.name;
50
+
51
+ for (const item of items) {
52
+ processItem(item);
53
+ }
54
+ ```
55
+
56
+ **Acceptable comment:**
57
+ ```typescript
58
+ // Use binary search instead of linear - dataset can be 100k+ items
59
+ const index = binarySearch(sortedItems, target);
60
+
61
+ // Edge case: API returns null instead of empty array for new users
62
+ const orders = response.orders ?? [];
63
+ ```
64
+
65
+ ### Naming Conventions
66
+ - Use descriptive, meaningful names
67
+ - Prefer `getUserById` over `get` or `fetchUser`
68
+ - Boolean variables: `isLoading`, `hasPermission`, `canEdit`
69
+ - Avoid abbreviations unless widely known (`id`, `url`, `api` are fine)
70
+
71
+ ### Function Size
72
+ - Keep functions small and focused (< 50 lines ideal)
73
+ - One responsibility per function
74
+ - Extract complex logic into named helper functions
75
+
76
+ ### Error Handling
77
+ - Use proper error handling, don't swallow errors silently
78
+ - TypeScript: Return types with explicit error types
79
+ - Python: Raise specific exceptions, not generic Exception
80
+ - Log errors with context before re-throwing
81
+
82
+ ## Testing Standards
83
+
84
+ ### Coverage Requirements
85
+ - Aim for **80% minimum** code coverage
86
+ - 100% coverage for:
87
+ - Core business logic
88
+ - Utility functions
89
+ - Security-critical code
90
+ - Public APIs
91
+
92
+ ### Testing Strategy
93
+ - Write tests BEFORE marking a feature complete
94
+ - Unit tests for individual functions/classes
95
+ - Integration tests for workflows
96
+ - E2E tests for critical user paths
97
+
98
+ ### Test Structure
99
+ ```typescript
100
+ describe('UserService', () => {
101
+ describe('getUserById', () => {
102
+ it('returns user when found', async () => {
103
+ // Arrange
104
+ const userId = '123';
105
+ const expectedUser = { id: userId, name: 'Alice' };
106
+
107
+ // Act
108
+ const user = await userService.getUserById(userId);
109
+
110
+ // Assert
111
+ expect(user).toEqual(expectedUser);
112
+ });
113
+
114
+ it('throws NotFoundError when user does not exist', async () => {
115
+ await expect(userService.getUserById('nonexistent'))
116
+ .rejects.toThrow(NotFoundError);
117
+ });
118
+ });
119
+ });
120
+ ```
121
+
122
+ ## Architecture Patterns
123
+
124
+ ### Keep It Simple
125
+ - Don't over-engineer
126
+ - Avoid premature abstraction
127
+ - Three similar lines > one premature abstraction
128
+ - Build for current requirements, not hypothetical future
129
+
130
+ ### File Organization
131
+ ```
132
+ src/
133
+ ├── models/ # Data models/types
134
+ ├── services/ # Business logic
135
+ ├── controllers/ # Request handlers (if web app)
136
+ ├── utils/ # Pure utility functions
137
+ ├── config/ # Configuration
138
+ └── index.ts # Entry point
139
+
140
+ tests/
141
+ ├── unit/
142
+ ├── integration/
143
+ └── e2e/
144
+ ```
145
+
146
+ ### Separation of Concerns
147
+ - Models: Data structures only
148
+ - Services: Business logic, orchestration
149
+ - Controllers: Input validation, response formatting
150
+ - Utils: Pure functions, no side effects
151
+
152
+ ## Git Commit Standards
153
+
154
+ ### Commit Messages
155
+ Follow conventional commits:
156
+
157
+ ```
158
+ type(scope): brief description
159
+
160
+ Longer explanation if needed.
161
+
162
+ - Bullet points for multiple changes
163
+ - Reference issue numbers: #123
164
+ ```
165
+
166
+ **Types:**
167
+ - `feat:` New feature
168
+ - `fix:` Bug fix
169
+ - `refactor:` Code change that neither fixes bug nor adds feature
170
+ - `test:` Adding or updating tests
171
+ - `docs:` Documentation only changes
172
+ - `chore:` Maintenance tasks
173
+
174
+ **Examples:**
175
+ ```
176
+ feat(auth): add JWT token refresh mechanism
177
+
178
+ fix(api): handle null response from user service
179
+
180
+ refactor(utils): extract duplicate validation logic
181
+
182
+ test(user-service): add tests for edge cases
183
+ ```
184
+
185
+ ### Commit Size
186
+ - **One logical change per commit**
187
+ - Commits should be atomic and revertable
188
+ - If you can't describe it in one line, it's probably too big
189
+
190
+ ## Performance Considerations
191
+
192
+ ### Do Optimize
193
+ - Database queries (use indexes, avoid N+1)
194
+ - API response times (< 200ms ideal)
195
+ - Bundle sizes for web apps
196
+ - Memory leaks in long-running processes
197
+
198
+ ### Don't Optimize Prematurely
199
+ - Micro-optimizations before profiling
200
+ - Complex caching before measuring benefit
201
+ - Over-engineering for hypothetical scale
202
+
203
+ ### When to Profile
204
+ - After implementing a feature, before optimizing
205
+ - When performance issues are reported
206
+ - For critical paths (hot loops, frequent API calls)
207
+
208
+ ## Security Best Practices
209
+
210
+ ### Always Validate
211
+ - Validate ALL user input
212
+ - Sanitize data before DB queries
213
+ - Use parameterized queries (never string concatenation)
214
+ - Validate file uploads (type, size, content)
215
+
216
+ ### Never Commit
217
+ - API keys, secrets, passwords
218
+ - `.env` files with real credentials
219
+ - Private keys or certificates
220
+ - Personal or sensitive data
221
+
222
+ ### Authentication & Authorization
223
+ - Use established libraries (Passport.js, Auth0, etc.)
224
+ - Never roll your own crypto
225
+ - Implement rate limiting
226
+ - Use HTTPS only in production
227
+
228
+ ## Dependencies
229
+
230
+ ### When to Add Dependencies
231
+ - Established, well-maintained libraries for complex problems
232
+ - Security-critical functionality (auth, crypto)
233
+ - Significant time savings vs. implementation cost
234
+
235
+ ### When NOT to Add Dependencies
236
+ - Simple utilities you can write in 10 lines
237
+ - Poorly maintained packages (old, few contributors)
238
+ - Dependencies with dependencies with dependencies
239
+ - For functionality already in stdlib
240
+
241
+ ### Check Before Adding
242
+ ```bash
243
+ # Check package stats
244
+ npm info <package>
245
+
246
+ # Check for vulnerabilities
247
+ npm audit
248
+
249
+ # Check bundle size impact
250
+ npx bundlephobia <package>
251
+ ```
252
+
253
+ ## Ralphie-Specific Guidelines
254
+
255
+ ### Required Reading
256
+ Before starting work in a Ralphie loop:
257
+ - **Always read:** `SPEC.md` - Project requirements and task list
258
+ - **Read if needed:** `STATE.txt` - Check if unsure what's already done
259
+ - **Read if needed:** `.ai/ralphie/index.md` - Last 3-5 commits for context
260
+
261
+ Lazy load context. SPEC has the tasks; only read progress/index if you need to verify state.
262
+
263
+ ### Integration Verification
264
+
265
+ When building code that integrates with existing systems:
266
+
267
+ 1. **Read existing code first** - Don't assume API shapes or response formats
268
+ 2. **Check shared types** - Use existing type definitions, don't create duplicates
269
+ 3. **Verify at runtime** - Test against real endpoints when possible
270
+
271
+ **Example:**
272
+ ```
273
+ SPEC says: "Add client for /api/status"
274
+
275
+ WRONG: Assume response is { workers: [], status: "ok" }
276
+ RIGHT: Read the server code to find actual response type
277
+ ```
278
+
279
+ Common integration mistakes:
280
+ - Building against imagined APIs that don't match the real server
281
+ - Creating new types when shared types already exist
282
+ - Assuming request/response shapes without reading existing handlers
283
+
284
+ **Before implementing any integration:**
285
+ ```bash
286
+ # Find the actual endpoint handler
287
+ grep -r "app.get('/api/status" src/
288
+
289
+ # Find existing types
290
+ grep -r "interface.*Response" src/types/
291
+ ```
292
+
293
+ ### Creating SPECs (Interactive)
294
+
295
+ When a user wants to create a new SPEC, **interview them** to gather requirements before writing it:
296
+
297
+ 1. **Ask clarifying questions** about:
298
+ - What they're building and the core use case
299
+ - Target users and how they'll interact with it
300
+ - Technology preferences (or recommend based on project)
301
+ - Must-have vs nice-to-have features
302
+ - Any constraints (time, dependencies, existing code)
303
+
304
+ 2. **Dig into details:**
305
+ - Edge cases and error handling needs
306
+ - Authentication/authorization requirements
307
+ - Data storage and persistence
308
+ - External integrations or APIs
309
+ - Testing expectations
310
+
311
+ 3. **Generate the SPEC** once you have enough context to create specific, actionable tasks.
312
+
313
+ **Example interview flow:**
314
+ ```
315
+ User: I want a CLI tool for managing dotfiles
316
+ You: What operations should it support? (backup, restore, sync across machines?)
317
+ User: Backup and restore, plus linking dotfiles to a git repo
318
+ You: Should it handle conflicts when restoring? (overwrite, skip, prompt?)
319
+ User: Prompt the user
320
+ You: Any specific dotfiles it must support, or auto-discover from home directory?
321
+ ...
322
+ [Generate SPEC after gathering sufficient detail]
323
+ ```
324
+
325
+ **Important:** When starting a new project, replace the existing SPEC.md entirely. Each SPEC represents one project or feature set.
326
+
327
+ ### Writing SPECs
328
+
329
+ When generating a SPEC, optimize for **iteration efficiency**. Each checkbox = one Ralphie iteration (~3 min), so structure matters.
330
+
331
+ **Batch by default.** Group related tasks under one checkbox:
332
+
333
+ ```markdown
334
+ # BAD - 4 iterations (12 min)
335
+ - [ ] Create ThoughtItem.tsx
336
+ - [ ] Create ToolActivityItem.tsx
337
+ - [ ] Create CommitItem.tsx
338
+ - [ ] Create PhaseIndicator.tsx
339
+
340
+ # GOOD - 1 iteration (4 min)
341
+ - [ ] Create activity feed components (ThoughtItem, ToolActivityItem, CommitItem, PhaseIndicator)
342
+ ```
343
+
344
+ **Batch when:**
345
+ - Same file or same directory
346
+ - Similar structure (4 similar components = 1 task)
347
+ - Tightly coupled (interface + implementation)
348
+ - Style/config changes across files
349
+
350
+ **Don't batch when:**
351
+ - Different areas of codebase
352
+ - Complex logic needing focus
353
+ - Tasks where one failure shouldn't block others
354
+
355
+ **Always include tests with implementation:**
356
+ ```markdown
357
+ # BAD - tests as separate task
358
+ - [ ] Create usePulse.ts hook
359
+ - [ ] Create usePulse.test.ts
360
+
361
+ # GOOD - tests included
362
+ - [ ] Create usePulse.ts hook with tests
363
+ ```
364
+
365
+ **Task naming:**
366
+ - Start with verb: Create, Add, Update, Fix, Refactor
367
+ - Be specific about scope: "Create activity feed components" not "Build UI"
368
+ - Include file hints when helpful
369
+
370
+ **Include verification steps:**
371
+
372
+ ```markdown
373
+ ## Phase 2: Core Features
374
+ - [ ] Implement authentication system
375
+ - POST /auth/register - create user with hashed password
376
+ - POST /auth/login - validate credentials, return JWT
377
+ - POST /auth/logout - invalidate token
378
+ - Middleware for protected routes
379
+ - Tests for all auth flows
380
+
381
+ **Verify:**
382
+ - `curl -X POST localhost:3000/auth/register -d '{"email":"test@test.com","password":"test123"}'` → 201
383
+ - `curl -X POST localhost:3000/auth/login -d '{"email":"test@test.com","password":"test123"}'` → returns JWT
384
+ - Use JWT on protected route → 200
385
+
386
+ - [ ] Build posts API with full CRUD
387
+ - GET/POST/PUT/DELETE endpoints
388
+ - Authorization (only author can edit/delete)
389
+ - Pagination for list endpoint
390
+ - Tests for all operations
391
+
392
+ **Verify:**
393
+ - `curl localhost:3000/posts` → 200 with array
394
+ - Create post with valid JWT → 201
395
+ - Edit post as non-author → 403
396
+ ```
397
+
398
+ ### Verification Steps
399
+
400
+ Each task should include a **Verify:** section with concrete checks to run before marking complete.
401
+
402
+ **Good verification steps:**
403
+ - API calls with expected response codes
404
+ - CLI commands with expected output
405
+ - Database queries to confirm data was written
406
+ - File existence checks
407
+
408
+ **Verification format:**
409
+ ```
410
+ **Verify:**
411
+ - `<command>` → <expected result>
412
+ - `<command>` → <expected result>
413
+ ```
414
+
415
+ **Examples:**
416
+ ```markdown
417
+ **Verify:**
418
+ - `npm test` → all tests pass
419
+ - `curl localhost:3000/health` → 200
420
+ - `ls dist/` → contains index.js
421
+ - `node dist/cli.js --version` → prints version number
422
+ ```
423
+
424
+ If verification can't run (server not available, etc.), note this in the commit and leave the checkbox unchecked.
425
+
426
+ ### Task Completion Criteria
427
+ A task is ONLY complete when:
428
+ - [ ] Code is written and works
429
+ - [ ] Tests are written and passing
430
+ - [ ] No linting errors
431
+ - [ ] Documentation updated (if public API)
432
+ - [ ] Changes committed with clear message
433
+
434
+ **A task is NOT complete if:**
435
+ - Code contains `// TODO:` or `// FIXME:` comments
436
+ - Implementation is stubbed or placeholder
437
+ - Tests don't pass or are skipped
438
+ - Functions throw "not implemented" errors
439
+
440
+ **If you can't implement something:**
441
+ 1. Leave the checkbox unchecked
442
+ 2. Document the blocker in STATE.txt
443
+ 3. Move to the next task or create a sub-task for the blocker
444
+
445
+ **Example of incomplete code (don't mark as done):**
446
+ ```typescript
447
+ async function processPayment(amount: number): Promise<void> {
448
+ // TODO: implement payment processing
449
+ throw new Error('Not implemented');
450
+ }
451
+ ```
452
+
453
+ ### Progress Updates
454
+ When updating `STATE.txt`, be specific:
455
+ ```
456
+ ✅ 2024-01-08: Implemented user authentication with JWT
457
+ - Added login/register endpoints
458
+ - Created User model with bcrypt password hashing
459
+ - Tests: 15 passing (auth.test.ts)
460
+ - Commit: feat(auth): add JWT authentication
461
+ ```
462
+
463
+ ### Error Recovery
464
+ If a task fails:
465
+ 1. Document the error in STATE.txt
466
+ 2. Don't mark task as complete
467
+ 3. Create a new task to fix the blocker
468
+ 4. If blocked on external factor, note it and move to next task
469
+
470
+ ## Code Review Checklist
471
+
472
+ Before committing, verify:
473
+ - [ ] Code works (manual test + automated tests)
474
+ - [ ] Tests pass with good coverage
475
+ - [ ] No linting errors
476
+ - [ ] No commented-out code
477
+ - [ ] No console.log/print statements (use proper logging)
478
+ - [ ] No TODO comments (convert to tasks)
479
+ - [ ] Error handling is present
480
+ - [ ] Security vulnerabilities checked
481
+ - [ ] Performance is acceptable
482
+ - [ ] Commit message is clear
483
+
484
+ ## Anti-Patterns to Avoid
485
+
486
+ ### Don't Do This
487
+ - ❌ Catch and ignore errors without logging
488
+ - ❌ Use `any` type in TypeScript
489
+ - ❌ Mutate function parameters
490
+ - ❌ Write god functions (> 100 lines)
491
+ - ❌ Nest callbacks > 3 levels deep
492
+ - ❌ Copy-paste code instead of extracting function
493
+ - ❌ Skip tests "to save time"
494
+ - ❌ Commit broken code
495
+ - ❌ Push directly to main without PR (in team settings)
496
+
497
+ ### Do This Instead
498
+ - ✅ Log errors with context, then throw/return
499
+ - ✅ Use specific types (string, number, CustomType)
500
+ - ✅ Return new values, don't mutate
501
+ - ✅ Extract into smaller, named functions
502
+ - ✅ Use async/await or Promises
503
+ - ✅ Extract to shared utility function
504
+ - ✅ Write tests first or immediately after
505
+ - ✅ Fix before committing
506
+ - ✅ Use feature branches + PR for review
507
+
508
+ ## Tools and Linters
509
+
510
+ ### Recommended Setup
511
+
512
+ **TypeScript:**
513
+ ```json
514
+ {
515
+ "extends": "@typescript-eslint/recommended",
516
+ "rules": {
517
+ "@typescript-eslint/no-explicit-any": "error",
518
+ "@typescript-eslint/explicit-function-return-type": "warn",
519
+ "no-console": "warn"
520
+ }
521
+ }
522
+ ```
523
+
524
+ **Python:**
525
+ ```ini
526
+ [tool:pytest]
527
+ testpaths = tests
528
+ python_files = test_*.py
529
+ python_functions = test_*
530
+ addopts = --cov=src --cov-report=html --cov-report=term
531
+
532
+ [mypy]
533
+ strict = true
534
+ warn_return_any = true
535
+ warn_unused_configs = true
536
+ ```
537
+
538
+ ### Run Before Every Commit
539
+ ```bash
540
+ # TypeScript
541
+ npm run lint
542
+ npm run type-check
543
+ npm test
544
+
545
+ # Python
546
+ pylint src/
547
+ mypy src/
548
+ pytest --cov=src --cov-fail-under=80
549
+ ```
550
+
551
+ ## Tips
552
+
553
+ - **Write verify steps**: Tasks without verification may be marked complete without actually working
554
+ - **Test locally first**: If verification needs a running server, start it before Ralphie runs
555
+ - **Keep verify steps simple**: One command, one expected result
556
+ - **Fail fast**: Put the most likely-to-fail verification first
557
+
558
+ ## Philosophical Principles
559
+
560
+ 1. **Simplicity over cleverness** - Code is read more than written
561
+ 2. **Explicit over implicit** - Make intentions clear
562
+ 3. **Working over perfect** - Ship working code, iterate
563
+ 4. **Tested over untested** - Tests are documentation that code works
564
+ 5. **Documented over undocumented** - Future you will thank present you
565
+ 6. **Consistent over innovative** - Follow existing patterns in codebase
566
+
567
+ ---
568
+
569
+ When in doubt, prioritize:
570
+ 1. **Working code** - Does it work?
571
+ 2. **Tested code** - How do we know it works?
572
+ 3. **Readable code** - Can others understand it?
573
+ 4. **Maintainable code** - Can it be changed safely?
574
+ 5. **Performant code** - Is it fast enough?
575
+
576
+ In that order.
@@ -0,0 +1,25 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/anthropics/claude-code/main/schemas/settings.json",
3
+ "hooks": {
4
+ "Stop": [
5
+ {
6
+ "type": "prompt",
7
+ "promptFile": "scripts/validate-iteration.md",
8
+ "description": "Validate Ralphie iteration completion before allowing next iteration"
9
+ }
10
+ ]
11
+ },
12
+ "permissions": {
13
+ "allow": [
14
+ "Bash(npm test:*)",
15
+ "Bash(npm run type-check:*)",
16
+ "Bash(npx vitest:*)",
17
+ "Bash(git add:*)",
18
+ "Bash(git commit:*)",
19
+ "Bash(git status:*)",
20
+ "Bash(git diff:*)",
21
+ "Bash(git log:*)"
22
+ ],
23
+ "deny": []
24
+ }
25
+ }