command-instructions.md

Comprehensive guide for creating new commands with contract-first development approach and best practices

command-instructions.mdv1.0.015.2 KB
command-instructions.md(markdown)
1# Command Development Instructions
2
3## Critical Context for AI Developers
4
5**Only read this document when creating new commands.** This document contains specific patterns and rules for command development in the codebase.
6
7## 🚨 MANDATORY: Contract-First Development Process
8
9### STOP! Define Contracts Before Implementation
10
11**AI developers MUST follow this process when creating new commands:**
12
131. **NEVER start coding a command without contract approval**
142. **ALWAYS present the proposed contracts for review first**
153. **WAIT for human developer confirmation before proceeding**
164. **DON'T Guess, ask questions to confirm**
175. **DON'T Assume Type or Class Properties** - You MUST check any types or classes referenced to ensure they exist with correct properties and methods
186. **When Creating new classes or deleting code** - You MUST check with the user, explain your approach, then wait for approval
19
20### MANDATORY Type and Interface Verification Checklist
21
22Before using ANY type, interface, or calling ANY method:
23
241. **Search for existing types**: `rg \"TypeName\" --type ts`
252. **Read the actual definition**: `rg \"interface TypeName\" -A 10` or `rg \"type TypeName\" -A 5`
263. **Verify method signatures**: Check service interfaces before calling methods
274. **Import from source**: Never redefine existing types - import them
285. **Run type check**: Use `npm run typecheck` after any type-related changes
29
30**Examples of what to check:**
31- `AgentModelConfig` → Search first, then import from `@/config`
32- `IQueueService.getQueueLength()` → Check interface, find it's actually `getMessageCount()`
33- Any service method → Verify the method exists and its signature
34
35**Common Mistakes to Avoid:**
36- Creating duplicate interfaces (e.g., defining `AgentModelConfig` when it already exists)
37- Assuming method names (e.g., `getQueueLength` vs `getMessageCount`)
38- Guessing property names (e.g., `model` vs `modelName`)
39- Using properties without verification (e.g., assuming `maxTokens` exists)
40
41### 🚀 PRE-IMPLEMENTATION CHECKLIST FOR AI DEVELOPERS
42
43**Use this checklist BEFORE writing ANY code to prevent type assumption errors:**
44
45#### ✅ Phase 1: Type and Interface Discovery
46- [ ] Search for ALL referenced types: `rg \"TypeName\" --type ts`
47- [ ] Read complete interface definitions: `rg \"interface TypeName\" -A 20`
48- [ ] Verify ALL method signatures exist: `rg \"methodName\" src/services/interfaces/`
49- [ ] Check import paths for each type: `rg \"export.*TypeName\"`
50- [ ] Document any missing types to ask human about
51
52#### ✅ Phase 2: Contract Verification  
53- [ ] Present complete input/output/error contracts for human review
54- [ ] Wait for explicit human confirmation before proceeding
55- [ ] Include ALL dependencies in contract review
56- [ ] Verify all command dependencies exist: `rg \"CommandName\" src/commands/`
57
58#### ✅ Phase 3: Service Method Verification
59- [ ] Check each service interface for available methods: `rg \"interface IServiceName\" -A 50`
60- [ ] Verify method parameter types match intended usage
61- [ ] Confirm return types align with expectations
62- [ ] Note any async/await requirements
63
64#### ✅ Phase 4: Architecture Pattern Verification
65- [ ] Confirm command category matches folder name
66- [ ] Verify using CommandRegistry pattern (never `new Command()`)
67- [ ] Check dependency injection patterns match existing commands
68- [ ] Ensure all types are defined in same file as command
69
70#### ✅ Phase 5: Pre-Code Validation
71- [ ] Run `npm run build` to ensure clean baseline
72- [ ] Run `npm run typecheck` to verify no existing type errors
73- [ ] Check for any existing implementations: `rg \"CommandName\"`
74- [ ] Verify test file patterns match existing commands
75
76#### ✅ Phase 6: Implementation Readiness
77- [ ] All types verified and imported correctly
78- [ ] All method signatures confirmed to exist
79- [ ] Human has approved contracts
80- [ ] Clean build confirmed
81- [ ] Ready to implement with confidence
82
83**🎯 Success Criteria:**
84- Zero type assumptions made
85- All interfaces verified to exist
86- All method calls verified against actual signatures
87- Human approval obtained for all contracts
88- Clean build baseline confirmed
89
90**⚠️ If ANY checkbox is unchecked, STOP and complete that step before proceeding.**
91
92## Contract Confirmation Template
93
94When asked to create a new command, respond with:
95
96```
97I'll create the [CommandName] for you. First, let me confirm the contracts:
98
99**Command**: `[CommandName]`
100**Category**: `[category-folder]`
101**Purpose**: [Brief description of what the command does]
102
103**Input Contract** (`[CommandName]Input`):
104```typescript
105interface [CommandName]Input {
106  field1: string;        // Description of field1
107  field2?: number;       // Optional field with description
108  // ... other fields
109}
110```
111
112**Output Contract** (`[CommandName]Output`):
113```typescript
114interface [CommandName]Output {
115  result: string;        // Description of result
116  metadata?: {           // Optional metadata
117    processedAt: Date;
118    // ... other metadata
119  };
120}
121```
122
123**Error Contract** (`[CommandName]Error`):
124- Will extend `ErrorBase`
125- Potential error codes: `VALIDATION_ERROR`, `NOT_FOUND`, etc.
126
127**Dependencies**:
128- Services: `['IServiceName1', 'IServiceName2']`
129- Commands: `['category/OtherCommand']`
130- External: `['library-name']`
131
132**Questions/Considerations**:
1331. Should field X be optional or required?
1342. Do we need additional validation for Y?
1353. Should this command compose other commands or be standalone?
136
137Please confirm these contracts look correct, or let me know what changes you'd like.
138```
139
140## Contract Design Guidelines
141
142When proposing contracts:
143
1441. **Be Explicit**: No `any` types, define all fields clearly
1452. **Consider Optionality**: Which fields are truly required?
1463. **Think About Composition**: Will this output feed into another command?
1474. **Plan for Errors**: What can go wrong? What error information is needed?
1485. **Check Existing Contracts**: Reuse types where appropriate
1496. **Validate Feasibility**: Can the output be produced from the input?
150
151## Example Contract Discussion
152
153**Human**: "Create a command to process user uploads"
154
155**AI**: 
156```
157I'll create the ProcessUserUploadCommand for you. First, let me confirm the contracts:
158
159**Command**: `ProcessUserUploadCommand`
160**Category**: `upload`
161**Purpose**: Process and validate user file uploads
162
163**Input Contract** (`ProcessUserUploadInput`):
164```typescript
165interface ProcessUserUploadInput {
166  userId: string;           // User who uploaded the file
167  fileData: Buffer;         // Raw file data
168  fileName: string;         // Original file name
169  mimeType: string;         // File MIME type
170  maxSizeBytes?: number;    // Optional size limit (default: 10MB)
171}
172```
173
174**Output Contract** (`ProcessUserUploadOutput`):
175```typescript
176interface ProcessUserUploadOutput {
177  uploadId: string;         // Unique identifier for this upload
178  blobPath: string;         // Storage path of processed file
179  fileSize: number;         // File size in bytes
180  checksumMd5: string;      // MD5 checksum for verification
181  processedAt: Date;        // When processing completed
182  metadata: {
183    originalName: string;
184    sanitizedName: string;
185    mimeType: string;
186    isValid: boolean;
187  };
188}
189```
190
191**Questions**:
1921. Should we include virus scanning in this command or separate?
1932. Do we need to support batch uploads?
1943. Should the command handle storage directly or return data for another command to store?
195
196Please confirm these contracts or suggest modifications.
197```
198
199**Human**: "Looks good, but let's make virus scanning a separate command and have this one just validate and prepare the file"
200
201**AI**: "Perfect! I'll update the contracts to focus on validation and preparation only, then implement the command with those confirmed contracts..."
202
203## Contract Modification Process
204
205If contracts need to change after implementation:
206
2071. **Stop and Discuss**: Don't guess at contract changes
2082. **Impact Analysis**: Identify all commands affected by the change
2093. **Get Approval**: Confirm changes before modifying code
2104. **Update Documentation**: Keep command-index.md current
211
212Remember: Taking time to get contracts right upfront saves hours of debugging and rework later!
213
214## Command Implementation Rules
215
216### Structure Requirements
217```typescript
218// CORRECT: Command structure
219export class CreateUserCommand implements OutputCommand<CreateUserInput, CreateUserOutput, CreateUserError> {
220  static readonly metadata: CommandMetadata = {
221    name: "CreateUserCommand",
222    category: "user",  // MUST match folder name
223    // ... other metadata
224  };
225}
226```
227
228### Critical Rules
2291. **Category = Folder Name**: The `category` in metadata MUST match the parent folder name
230   - `/commands/user/CreateUserCommand.ts``category: "user"`
231   - `/commands/cache/SetCacheCommand.ts``category: "cache"`
232   
2332. **Never Instantiate Commands Directly**: Always use CommandRegistry
234   ```typescript
235   // ❌ WRONG
236   const command = new CreateUserCommand(input);
237   
238   // ✅ CORRECT
239   const command = await commandRegistry.get<CreateUserCommand>(
240     CreateUserCommand, 
241     input,
242     logger
243   );
244   ```
245
2463. **All Types in Same File**: Keep Input, Output, and Error types with the command
247   ```typescript
248   // In CreateUserCommand.ts
249   export interface CreateUserInput { ... }
250   export interface CreateUserOutput { ... }
251   export class CreateUserError extends ErrorBase { ... }
252   export class CreateUserCommand implements OutputCommand<...> { ... }
253   ```
254
255## No Defaults or Fallbacks Rule
256
257**IMPORTANT**: When implementing commands, DO NOT add default values or fallback behaviors unless explicitly discussed and agreed upon with the human developer. This includes:
258
2591. **No default values for optional parameters** - If a parameter is optional in the contract, let it be undefined
2602. **No fallback behaviors** - If required data is missing, fail validation rather than assuming defaults
2613. **No implicit configuration** - All configuration must be explicitly provided through input
2624. **Fail fast on missing data** - Better to catch configuration issues during validation than hide them with defaults
263
264**Why this matters**:
265- Defaults hide configuration errors that surface later in production
266- Explicit configuration makes the system more predictable and debuggable
267- Early validation failures are easier to fix than subtle runtime bugs
268- It's easier to add defaults later than to remove them once code depends on them
269
270## Critical Data Validation Rule
271
272**MANDATORY**: For critical business data (especially cost-related, security-related, or data integrity operations), commands MUST enforce strict validation and fail fast rather than silently ignoring missing or invalid data.
273
274### When to Apply Strict Validation
275
276Apply this rule when dealing with:
2771. **Cost-related data**: Token usage, API calls, resource consumption
2782. **Security data**: User IDs, authentication tokens, permissions
2793. **Data integrity**: Database operations, file operations, state changes
2804. **Compliance requirements**: Audit trails, logging, tracking
281
282### Implementation Guidelines
283
2841. **Make Critical Fields Required**: Use required fields in TypeScript interfaces, not optional ones
2852. **Validate in Constructor**: Check for required dependencies and fail immediately if missing
2863. **Fail Fast in Validation**: Throw specific errors for missing critical data
2874. **No Silent Failures**: Don't catch and ignore critical validation errors
2885. **Clear Error Messages**: Provide specific error codes and messages for debugging
289
290## Command Composition Patterns
291
292### Workflow Commands
293Commands can orchestrate other commands:
294```typescript
295export class ProcessYouTubeVideoCommand {
296  async execute(): Promise<ProcessVideoOutput> {
297    // Step 1: Create job
298    const createJobCmd = await this.commandRegistry.get<CreateProcessingJobCommand>(
299      CreateProcessingJobCommand,
300      { videoUrl: this.input.url }
301    );
302    const job = await createJobCmd.execute();
303    
304    // Step 2: Extract transcript
305    const transcriptCmd = await this.commandRegistry.get<RequestYouTubeTranscriptionCommand>(
306      RequestYouTubeTranscriptionCommand,
307      { jobId: job.id, videoUrl: this.input.url }
308    );
309    const transcript = await transcriptCmd.execute();
310    
311    // Continue workflow...
312  }
313}
314```
315
316## Adding New Features
317
3181. **Identify Commands Needed**: Break feature into granular commands
3192. **Define Contracts First**: Follow the Contract-First Development Process above
3203. **Create Command Structure**:
321   ```
322   src/commands/
323     feature-name/
324       CreateFeatureCommand.ts
325       UpdateFeatureCommand.ts
326       GetFeatureCommand.ts
327   ```
3284. **Implement Commands**: Follow micro-block pattern exactly
3295. **Register Services**: If new services needed, see [services-instructions.md](./services-instructions.md)
3306. **Create API Routes**: Use commands via CommandRegistry
3317. **Add UI Components**: Keep business logic in commands
3328. **Category**: the 'feature-name' must match the 'category' of the commands metadata description
333
334## Command Implementation Checklist
335
336- [ ] Contracts confirmed with human developer
337- [ ] Command implements correct interface (OutputCommand or InputOnlyCommand)
338- [ ] Static metadata property with all required fields
339- [ ] Category matches folder name exactly
340- [ ] Input/Output/Error types defined in same file
341- [ ] Error class extends ErrorBase
342- [ ] Dependencies object with services/commands/external arrays
343- [ ] Constructor handles both services and commands parameters
344- [ ] Dependency validation in constructor (throw if missing)
345- [ ] Validate method implemented
346- [ ] Proper error handling with custom error types
347- [ ] Test file created with >80% coverage
348- [ ] Documentation updated (command-index.md, system-features.md)
349
350## API Route Pattern
351
352```typescript
353// app/api/feature/route.ts
354import { getServiceRegistry } from '@/core/utils/nextjs-helpers';
355
356export async function POST(request: NextRequest) {
357  const logger = new ConsoleLogger('FeatureAPI');
358  const serviceRegistry = getServiceRegistry();
359  const commandRegistry = serviceRegistry.getCommandRegistry();
360  
361  try {
362    const body = await request.json();
363    
364    // Use command via registry
365    const command = await commandRegistry.get<CreateFeatureCommand>(
366      CreateFeatureCommand,
367      body,
368      logger
369    );
370    const result = await command.execute();
371    
372    return NextResponse.json(result);
373  } catch (error) {
374    // Handle errors...
375  }
376}
377```
378
379## Command Testing Patterns
380
381```typescript
382describe('MyCommand', () => {
383  let command: MyCommand;
384  let mockServices: Record<string, any>;
385  let mockCommands: Record<string, any>;
386  
387  beforeEach(() => {
388    mockServices = {
389      'IServiceName': createMockService<IServiceName>({
390        someMethod: vi.fn()
391      })
392    };
393    
394    mockCommands = {
395      'category/SomeCommand': createMockCommand({
396        execute: vi.fn().mockResolvedValue({ result: 'test' })
397      })
398    };
399    
400    command = new MyCommand(
401      undefined,
402      undefined,
403      mockServices,
404      mockCommands
405    );
406  });
407  
408  it('should validate input contracts', async () => {
409    // Test input validation
410  });
411  
412  it('should execute successfully with valid input', async () => {
413    // Test successful execution
414  });
415  
416  it('should handle errors appropriately', async () => {
417    // Test error scenarios
418  });
419});
420```
421
422Remember: Commands are the core business logic units of the system. They should be focused, testable, and composable. Always follow the established patterns even for simple operations.

Metadata

Path
utaba/main/guidance/development/command-instructions.md
Namespace
utaba/main/guidance/development
Author
utaba
Category
guidance
Technology
typescript
Contract Version
1.0.0
MIME Type
text/markdown
Published
18-Jul-2025
Last Updated
18-Jul-2025