kiro-spec-engine 1.2.2 → 1.2.3

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,615 @@
1
+ # Developer Guide
2
+
3
+ This guide is for developers who want to contribute to Kiro Spec Engine or extend its functionality.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Architecture Overview](#architecture-overview)
8
+ - [Core Components](#core-components)
9
+ - [Migration Script Interface](#migration-script-interface)
10
+ - [Extension Points](#extension-points)
11
+ - [API Documentation](#api-documentation)
12
+ - [Testing Guidelines](#testing-guidelines)
13
+ - [Contributing](#contributing)
14
+
15
+ ---
16
+
17
+ ## Architecture Overview
18
+
19
+ Kiro Spec Engine follows a modular architecture with clear separation of concerns:
20
+
21
+ ```
22
+ ┌─────────────────────────────────────────────────────────────┐
23
+ │ CLI Layer │
24
+ │ (bin/kiro-spec-engine.js, lib/commands/*.js) │
25
+ └─────────────────────────────────────────────────────────────┘
26
+
27
+
28
+ ┌─────────────────────────────────────────────────────────────┐
29
+ │ Core Systems │
30
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
31
+ │ │ Adoption │ │ Upgrade │ │ Backup │ │
32
+ │ │ System │ │ System │ │ System │ │
33
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
34
+ └─────────────────────────────────────────────────────────────┘
35
+
36
+
37
+ ┌─────────────────────────────────────────────────────────────┐
38
+ │ Utility Layer │
39
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
40
+ │ │ Version │ │ Validation │ │ File System │ │
41
+ │ │ Manager │ │ Utils │ │ Utils │ │
42
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
43
+ └─────────────────────────────────────────────────────────────┘
44
+ ```
45
+
46
+ ### Design Principles
47
+
48
+ 1. **Modularity**: Each component has a single responsibility
49
+ 2. **Safety**: All operations are atomic with automatic backups
50
+ 3. **Extensibility**: Clear extension points for future features
51
+ 4. **Testability**: Components are designed for easy testing
52
+ 5. **User-Friendly**: Clear error messages and progress indicators
53
+
54
+ ---
55
+
56
+ ## Core Components
57
+
58
+ ### 1. DetectionEngine (`lib/adoption/detection-engine.js`)
59
+
60
+ Analyzes project structure and determines the appropriate adoption strategy.
61
+
62
+ **Key Methods**:
63
+ - `analyze(projectPath)`: Scans project structure
64
+ - `determineStrategy()`: Selects adoption mode (fresh/partial/full)
65
+ - `detectProjectType()`: Identifies Node.js/Python/mixed projects
66
+ - `detectConflicts()`: Finds template file conflicts
67
+
68
+ **Usage Example**:
69
+ ```javascript
70
+ const DetectionEngine = require('./lib/adoption/detection-engine');
71
+
72
+ const engine = new DetectionEngine('/path/to/project');
73
+ const analysis = engine.analyze();
74
+ console.log(analysis.mode); // 'fresh', 'partial', or 'full'
75
+ ```
76
+
77
+ ### 2. AdoptionStrategy (`lib/adoption/adoption-strategy.js`)
78
+
79
+ Implements different adoption modes for various project states.
80
+
81
+ **Strategies**:
82
+ - `FreshAdoption`: Creates complete .kiro/ structure from scratch
83
+ - `PartialAdoption`: Adds missing components to existing .kiro/
84
+ - `FullAdoption`: Upgrades existing complete .kiro/ to current version
85
+
86
+ **Usage Example**:
87
+ ```javascript
88
+ const { getStrategy } = require('./lib/adoption/adoption-strategy');
89
+
90
+ const strategy = getStrategy('fresh');
91
+ await strategy.execute('/path/to/project', {
92
+ preserveSpecs: true,
93
+ backupFirst: true
94
+ });
95
+ ```
96
+
97
+ ### 3. VersionManager (`lib/version/version-manager.js`)
98
+
99
+ Manages project versions and upgrade paths.
100
+
101
+ **Key Methods**:
102
+ - `readVersion(projectPath)`: Reads version.json
103
+ - `writeVersion(projectPath, versionInfo)`: Writes version.json atomically
104
+ - `needsUpgrade(currentVersion, targetVersion)`: Checks if upgrade needed
105
+ - `calculateUpgradePath(from, to)`: Calculates intermediate versions
106
+
107
+ **Usage Example**:
108
+ ```javascript
109
+ const VersionManager = require('./lib/version/version-manager');
110
+
111
+ const vm = new VersionManager();
112
+ const needsUpgrade = vm.needsUpgrade('1.0.0', '1.2.0');
113
+ if (needsUpgrade) {
114
+ const path = vm.calculateUpgradePath('1.0.0', '1.2.0');
115
+ console.log(path); // ['1.0.0', '1.1.0', '1.2.0']
116
+ }
117
+ ```
118
+
119
+ ### 4. MigrationEngine (`lib/upgrade/migration-engine.js`)
120
+
121
+ Plans and executes version upgrades with migration scripts.
122
+
123
+ **Key Methods**:
124
+ - `planUpgrade(from, to)`: Creates upgrade plan
125
+ - `executeUpgrade(projectPath, plan)`: Runs migrations sequentially
126
+ - `loadMigration(version)`: Loads migration script
127
+ - `validate(projectPath)`: Post-upgrade validation
128
+
129
+ **Usage Example**:
130
+ ```javascript
131
+ const MigrationEngine = require('./lib/upgrade/migration-engine');
132
+
133
+ const engine = new MigrationEngine();
134
+ const plan = engine.planUpgrade('1.0.0', '1.2.0');
135
+ await engine.executeUpgrade('/path/to/project', plan);
136
+ ```
137
+
138
+ ### 5. BackupSystem (`lib/backup/backup-system.js`)
139
+
140
+ Creates, manages, and restores backups for safe operations.
141
+
142
+ **Key Methods**:
143
+ - `createBackup(projectPath, reason)`: Creates timestamped backup
144
+ - `listBackups(projectPath)`: Lists available backups
145
+ - `restore(projectPath, backupId)`: Restores from backup
146
+ - `validateBackup(backupPath)`: Verifies backup integrity
147
+
148
+ **Usage Example**:
149
+ ```javascript
150
+ const BackupSystem = require('./lib/backup/backup-system');
151
+
152
+ const backup = new BackupSystem();
153
+ const backupId = await backup.createBackup('/path/to/project', 'before-upgrade');
154
+ // ... perform operations ...
155
+ if (failed) {
156
+ await backup.restore('/path/to/project', backupId);
157
+ }
158
+ ```
159
+
160
+ ---
161
+
162
+ ## Migration Script Interface
163
+
164
+ Migration scripts enable smooth upgrades between versions with breaking changes.
165
+
166
+ ### Script Structure
167
+
168
+ Create migration scripts in `lib/upgrade/migrations/` with the naming pattern:
169
+ `{from-version}-to-{to-version}.js`
170
+
171
+ Example: `1.0.0-to-1.1.0.js`
172
+
173
+ ### Required Interface
174
+
175
+ ```javascript
176
+ /**
177
+ * Migration script from version X to version Y
178
+ */
179
+ module.exports = {
180
+ /**
181
+ * Migrate project from old version to new version
182
+ * @param {string} projectPath - Absolute path to project root
183
+ * @param {Object} context - Migration context
184
+ * @param {Object} context.oldVersion - Old version info
185
+ * @param {Object} context.newVersion - New version info
186
+ * @param {Object} context.logger - Logger instance
187
+ * @returns {Promise<Object>} Migration result
188
+ */
189
+ async migrate(projectPath, context) {
190
+ const { oldVersion, newVersion, logger } = context;
191
+
192
+ logger.info(`Migrating from ${oldVersion.version} to ${newVersion.version}`);
193
+
194
+ // Perform migration steps
195
+ // 1. Read existing files
196
+ // 2. Transform data/structure
197
+ // 3. Write new files
198
+ // 4. Update configuration
199
+
200
+ return {
201
+ success: true,
202
+ changes: [
203
+ 'Added new steering file: ENVIRONMENT.md',
204
+ 'Updated version.json structure'
205
+ ],
206
+ warnings: []
207
+ };
208
+ },
209
+
210
+ /**
211
+ * Rollback migration (optional but recommended)
212
+ * @param {string} projectPath - Absolute path to project root
213
+ * @param {Object} context - Migration context
214
+ * @returns {Promise<Object>} Rollback result
215
+ */
216
+ async rollback(projectPath, context) {
217
+ const { logger } = context;
218
+
219
+ logger.info('Rolling back migration');
220
+
221
+ // Reverse migration steps
222
+ // Usually handled by backup restore, but can be implemented
223
+ // for more granular control
224
+
225
+ return {
226
+ success: true,
227
+ message: 'Rollback completed'
228
+ };
229
+ },
230
+
231
+ /**
232
+ * Validate migration result (optional)
233
+ * @param {string} projectPath - Absolute path to project root
234
+ * @returns {Promise<Object>} Validation result
235
+ */
236
+ async validate(projectPath) {
237
+ // Verify migration was successful
238
+ // Check file existence, structure, etc.
239
+
240
+ return {
241
+ valid: true,
242
+ errors: []
243
+ };
244
+ }
245
+ };
246
+ ```
247
+
248
+ ### Migration Best Practices
249
+
250
+ 1. **Idempotency**: Migrations should be safe to run multiple times
251
+ 2. **Validation**: Always validate before and after migration
252
+ 3. **Logging**: Log all significant operations
253
+ 4. **Error Handling**: Handle errors gracefully with clear messages
254
+ 5. **Rollback**: Implement rollback when possible
255
+ 6. **Testing**: Test migrations with various project states
256
+
257
+ ### Example Migration Script
258
+
259
+ ```javascript
260
+ const fs = require('fs-extra');
261
+ const path = require('path');
262
+
263
+ module.exports = {
264
+ async migrate(projectPath, context) {
265
+ const { logger } = context;
266
+ const changes = [];
267
+
268
+ // Add new steering file
269
+ const steeringDir = path.join(projectPath, '.kiro', 'steering');
270
+ const envFile = path.join(steeringDir, 'ENVIRONMENT.md');
271
+
272
+ if (!fs.existsSync(envFile)) {
273
+ const template = `# Environment Configuration
274
+ ...template content...`;
275
+ await fs.writeFile(envFile, template, 'utf8');
276
+ changes.push('Created ENVIRONMENT.md');
277
+ logger.info('✅ Created ENVIRONMENT.md');
278
+ }
279
+
280
+ // Update version.json structure
281
+ const versionFile = path.join(projectPath, '.kiro', 'version.json');
282
+ const versionData = await fs.readJson(versionFile);
283
+
284
+ if (!versionData.upgradeHistory) {
285
+ versionData.upgradeHistory = [];
286
+ await fs.writeJson(versionFile, versionData, { spaces: 2 });
287
+ changes.push('Added upgradeHistory to version.json');
288
+ logger.info('✅ Updated version.json structure');
289
+ }
290
+
291
+ return {
292
+ success: true,
293
+ changes,
294
+ warnings: []
295
+ };
296
+ },
297
+
298
+ async validate(projectPath) {
299
+ const errors = [];
300
+
301
+ // Check ENVIRONMENT.md exists
302
+ const envFile = path.join(projectPath, '.kiro', 'steering', 'ENVIRONMENT.md');
303
+ if (!fs.existsSync(envFile)) {
304
+ errors.push('ENVIRONMENT.md not found');
305
+ }
306
+
307
+ // Check version.json structure
308
+ const versionFile = path.join(projectPath, '.kiro', 'version.json');
309
+ const versionData = await fs.readJson(versionFile);
310
+ if (!versionData.upgradeHistory) {
311
+ errors.push('version.json missing upgradeHistory field');
312
+ }
313
+
314
+ return {
315
+ valid: errors.length === 0,
316
+ errors
317
+ };
318
+ }
319
+ };
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Extension Points
325
+
326
+ ### 1. Custom Adoption Strategies
327
+
328
+ Add new adoption strategies by extending the base class:
329
+
330
+ ```javascript
331
+ const { AdoptionStrategy } = require('./lib/adoption/adoption-strategy');
332
+
333
+ class CustomAdoption extends AdoptionStrategy {
334
+ async execute(projectPath, options) {
335
+ // Custom adoption logic
336
+ }
337
+ }
338
+
339
+ // Register strategy
340
+ const strategies = {
341
+ custom: CustomAdoption
342
+ };
343
+ ```
344
+
345
+ ### 2. Custom Validation Rules
346
+
347
+ Extend validation system with custom rules:
348
+
349
+ ```javascript
350
+ const validation = require('./lib/utils/validation');
351
+
352
+ function validateCustomRule(projectPath) {
353
+ // Custom validation logic
354
+ return {
355
+ valid: true,
356
+ errors: []
357
+ };
358
+ }
359
+
360
+ // Use in validation pipeline
361
+ const result = await validation.validateProject(projectPath, {
362
+ customValidators: [validateCustomRule]
363
+ });
364
+ ```
365
+
366
+ ### 3. Custom Migration Hooks
367
+
368
+ Add hooks to migration process:
369
+
370
+ ```javascript
371
+ const MigrationEngine = require('./lib/upgrade/migration-engine');
372
+
373
+ class CustomMigrationEngine extends MigrationEngine {
374
+ async beforeMigration(projectPath, plan) {
375
+ // Pre-migration hook
376
+ }
377
+
378
+ async afterMigration(projectPath, result) {
379
+ // Post-migration hook
380
+ }
381
+ }
382
+ ```
383
+
384
+ ### 4. Custom CLI Commands
385
+
386
+ Add new commands to the CLI:
387
+
388
+ ```javascript
389
+ // lib/commands/my-command.js
390
+ module.exports = {
391
+ name: 'my-command',
392
+ description: 'My custom command',
393
+
394
+ async execute(options) {
395
+ // Command logic
396
+ }
397
+ };
398
+
399
+ // Register in bin/kiro-spec-engine.js
400
+ program
401
+ .command('my-command')
402
+ .description('My custom command')
403
+ .action(require('../lib/commands/my-command').execute);
404
+ ```
405
+
406
+ ---
407
+
408
+ ## API Documentation
409
+
410
+ ### DetectionEngine API
411
+
412
+ #### `constructor(projectPath)`
413
+ Creates a new DetectionEngine instance.
414
+
415
+ #### `analyze()`
416
+ Analyzes project structure and returns analysis result.
417
+
418
+ **Returns**: `Object`
419
+ ```javascript
420
+ {
421
+ mode: 'fresh' | 'partial' | 'full',
422
+ projectType: 'nodejs' | 'python' | 'mixed',
423
+ hasKiroDir: boolean,
424
+ hasSpecs: boolean,
425
+ hasVersion: boolean,
426
+ conflicts: string[],
427
+ currentVersion: string | null
428
+ }
429
+ ```
430
+
431
+ ### VersionManager API
432
+
433
+ #### `readVersion(projectPath)`
434
+ Reads version.json from project.
435
+
436
+ **Returns**: `Promise<Object>`
437
+ ```javascript
438
+ {
439
+ version: '1.2.0',
440
+ kseVersion: '1.2.0',
441
+ createdAt: '2026-01-23T00:00:00.000Z',
442
+ updatedAt: '2026-01-23T00:00:00.000Z',
443
+ upgradeHistory: []
444
+ }
445
+ ```
446
+
447
+ #### `needsUpgrade(currentVersion, targetVersion)`
448
+ Checks if upgrade is needed.
449
+
450
+ **Returns**: `boolean`
451
+
452
+ #### `calculateUpgradePath(fromVersion, toVersion)`
453
+ Calculates intermediate versions for upgrade.
454
+
455
+ **Returns**: `string[]` - Array of versions in upgrade order
456
+
457
+ ### BackupSystem API
458
+
459
+ #### `createBackup(projectPath, reason)`
460
+ Creates a timestamped backup.
461
+
462
+ **Returns**: `Promise<string>` - Backup ID
463
+
464
+ #### `listBackups(projectPath)`
465
+ Lists available backups.
466
+
467
+ **Returns**: `Promise<Array>`
468
+ ```javascript
469
+ [
470
+ {
471
+ id: 'backup-20260123-120000',
472
+ timestamp: '2026-01-23T12:00:00.000Z',
473
+ reason: 'before-upgrade',
474
+ size: 1024000
475
+ }
476
+ ]
477
+ ```
478
+
479
+ #### `restore(projectPath, backupId)`
480
+ Restores project from backup.
481
+
482
+ **Returns**: `Promise<void>`
483
+
484
+ ---
485
+
486
+ ## Testing Guidelines
487
+
488
+ ### Unit Tests
489
+
490
+ Unit tests are located in `tests/unit/` and test individual components.
491
+
492
+ **Running unit tests**:
493
+ ```bash
494
+ npm run test:unit
495
+ ```
496
+
497
+ **Writing unit tests**:
498
+ ```javascript
499
+ const DetectionEngine = require('../../lib/adoption/detection-engine');
500
+
501
+ describe('DetectionEngine', () => {
502
+ test('should detect fresh adoption mode', () => {
503
+ const engine = new DetectionEngine('/path/to/project');
504
+ const analysis = engine.analyze();
505
+ expect(analysis.mode).toBe('fresh');
506
+ });
507
+ });
508
+ ```
509
+
510
+ ### Property-Based Tests
511
+
512
+ Property-based tests are located in `tests/properties/` and test universal properties.
513
+
514
+ **Running property tests**:
515
+ ```bash
516
+ npm run test:properties
517
+ ```
518
+
519
+ **Writing property tests**:
520
+ ```javascript
521
+ const fc = require('fast-check');
522
+ const VersionManager = require('../../lib/version/version-manager');
523
+
524
+ describe('VersionManager Properties', () => {
525
+ test('version comparison is transitive', () => {
526
+ fc.assert(
527
+ fc.property(
528
+ fc.string(), fc.string(), fc.string(),
529
+ (v1, v2, v3) => {
530
+ const vm = new VersionManager();
531
+ // If v1 < v2 and v2 < v3, then v1 < v3
532
+ // Property test logic
533
+ }
534
+ )
535
+ );
536
+ });
537
+ });
538
+ ```
539
+
540
+ ### Integration Tests
541
+
542
+ Integration tests are located in `tests/integration/` and test end-to-end flows.
543
+
544
+ **Running integration tests**:
545
+ ```bash
546
+ npm run test:integration
547
+ ```
548
+
549
+ ---
550
+
551
+ ## Contributing
552
+
553
+ ### Development Setup
554
+
555
+ 1. Clone the repository:
556
+ ```bash
557
+ git clone https://github.com/heguangyong/kiro-spec-engine.git
558
+ cd kiro-spec-engine
559
+ ```
560
+
561
+ 2. Install dependencies:
562
+ ```bash
563
+ npm install
564
+ ```
565
+
566
+ 3. Run tests:
567
+ ```bash
568
+ npm test
569
+ ```
570
+
571
+ 4. Install globally for testing:
572
+ ```bash
573
+ npm run install-global
574
+ ```
575
+
576
+ ### Code Style
577
+
578
+ - Use 2 spaces for indentation
579
+ - Use semicolons
580
+ - Use single quotes for strings
581
+ - Follow existing code patterns
582
+ - Add JSDoc comments for public APIs
583
+
584
+ ### Pull Request Process
585
+
586
+ 1. Create a feature branch from `main`
587
+ 2. Make your changes with tests
588
+ 3. Ensure all tests pass
589
+ 4. Update documentation if needed
590
+ 5. Submit pull request with clear description
591
+
592
+ ### Commit Message Format
593
+
594
+ Follow conventional commits:
595
+ ```
596
+ feat: add new adoption strategy
597
+ fix: correct version comparison logic
598
+ docs: update developer guide
599
+ test: add property tests for backup system
600
+ ```
601
+
602
+ ---
603
+
604
+ ## Additional Resources
605
+
606
+ - [User Adoption Guide](./adoption-guide.md)
607
+ - [User Upgrade Guide](./upgrade-guide.md)
608
+ - [Spec Workflow Guide](../.kiro/specs/SPEC_WORKFLOW_GUIDE.md)
609
+ - [GitHub Repository](https://github.com/heguangyong/kiro-spec-engine)
610
+ - [Issue Tracker](https://github.com/heguangyong/kiro-spec-engine/issues)
611
+
612
+ ---
613
+
614
+ **Version**: 1.0
615
+ **Last Updated**: 2026-01-23