thachvd-kit 1.0.31 → 1.0.33

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.
package/bin/cli.js CHANGED
@@ -1,126 +1,37 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { spawnSync } = require('child_process');
6
- const prompts = require('prompts');
7
- const pc = require('picocolors');
8
- const packageJson = require('../package.json');
9
-
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { spawnSync } = require('child_process');
6
+ const prompts = require('prompts');
7
+ const pc = require('picocolors');
8
+ const packageJson = require('../package.json');
9
+
10
10
  const sourceDir = path.resolve(__dirname, '..');
11
11
  const targetDir = process.cwd();
12
12
  const CODEBASE_MEMORY_PACKAGE = 'codebase-memory-mcp';
13
13
  const CODEBASE_MEMORY_BINARY = 'codebase-memory-mcp';
14
14
  const RTK_INSTALL_COMMAND = 'cargo install --git https://github.com/rtk-ai/rtk --branch master rtk';
15
-
16
- // --- Skill Resolver ---
17
-
18
- const LANG_SKILLS = {
19
- javascript: ["nodejs-best-practices", "api-design"],
20
- typescript: ["nodejs-best-practices", "api-design"],
21
- python: ["python-patterns"],
22
- go: ["golang-patterns", "golang-testing"],
23
- php: ["api-design"],
24
- rust: ["rust-pro"],
25
- java: ["api-design"],
26
- ruby: ["api-design"],
27
- swift: ["mobile-design"],
28
- kotlin: ["mobile-design"],
29
- csharp: ["api-design"],
30
- };
31
-
32
- const FRAMEWORK_SKILLS = {
33
- vue: ["frontend-design", "tailwind-patterns"],
34
- react: ["react-frontend", "frontend-design"],
35
- next: ["nextjs-react-expert", "frontend-design"],
36
- nuxt: ["frontend-design"],
37
- svelte: ["frontend-design"],
38
- angular: ["frontend-design"],
39
- laravel: ["laravel-patterns", "laravel-security", "laravel-tdd"],
40
- cakephp: ["api-design"],
41
- symfony: ["api-design"],
42
- codeigniter: ["api-design"],
43
- express: ["nodejs-best-practices", "api-design"],
44
- fastapi: ["python-patterns", "api-design"],
45
- django: ["python-patterns", "api-design"],
46
- flask: ["python-patterns", "api-design"],
47
- gin: ["golang-patterns", "golang-testing"],
48
- fiber: ["golang-patterns", "golang-testing"],
49
- echo: ["golang-patterns", "golang-testing"],
50
- nestjs: ["nodejs-best-practices", "api-design"],
51
- rails: ["api-design"],
52
- spring: ["api-design"],
53
- aspnet: ["api-design"],
54
- tauri: ["rust-pro", "desktop-design"],
55
- axum: ["rust-pro", "api-design"],
56
- actix: ["rust-pro", "api-design"],
57
- flutter: ["mobile-design"],
58
- "react-native": ["mobile-design"],
59
- };
60
-
61
- const INFRA_SKILLS = {
62
- docker: ["docker-patterns"],
63
- aws: ["deployment-procedures", "docker-patterns"],
64
- gcp: ["deployment-procedures", "docker-patterns"],
65
- azure: ["deployment-procedures", "docker-patterns"],
66
- vercel: ["deployment-procedures"],
67
- };
68
-
69
- function resolveSkills(data) {
70
- const skills = new Set();
71
- const lang = (data.primary_language || "").toLowerCase();
72
-
73
- if (LANG_SKILLS[lang]) {
74
- LANG_SKILLS[lang].forEach(s => skills.add(s));
75
- }
76
-
77
- (data.frameworks || []).forEach(fw => {
78
- const fwLower = fw.toLowerCase();
79
- for (const [key, vals] of Object.entries(FRAMEWORK_SKILLS)) {
80
- if (fwLower.includes(key)) vals.forEach(s => skills.add(s));
81
- }
82
- });
83
-
84
- (data.infrastructure || []).forEach(infra => {
85
- const infraLower = infra.toLowerCase();
86
- for (const [key, vals] of Object.entries(INFRA_SKILLS)) {
87
- if (infraLower.includes(key)) vals.forEach(s => skills.add(s));
88
- }
89
- });
90
-
91
- skills.add("clean-code");
92
- skills.add("systematic-debugging");
93
-
94
- return Array.from(skills).sort();
95
- }
96
-
97
- function resolveNativeSkills(data) {
98
- return Array.from(new Set([
99
- ...resolveSkills(data),
100
- 'verification-before-completion',
101
- 'webapp-testing'
102
- ])).sort();
103
- }
104
-
105
- const FRAMEWORK_CHOICES = [
106
- 'vue', 'react', 'next', 'nuxt', 'svelte', 'angular',
107
- 'laravel', 'cakephp', 'symfony', 'codeigniter',
108
- 'express', 'fastapi', 'django', 'flask', 'gin', 'fiber', 'echo', 'nestjs',
109
- 'rails', 'spring', 'aspnet',
110
- 'tauri', 'axum', 'actix', 'flutter', 'react-native'
111
- ];
112
-
113
- const LANGUAGE_CHOICES = ['typescript', 'javascript', 'python', 'go', 'php', 'rust', 'java', 'ruby', 'swift', 'kotlin', 'csharp', 'cpp'];
114
- const PROJECT_TYPE_CHOICES = ['web-app', 'api', 'mobile', 'desktop', 'cli', 'fullstack'];
115
- const DATABASE_CHOICES = ['postgres', 'mysql', 'sqlite', 'mongodb', 'redis', 'dynamodb', 'none'];
116
- const PACKAGE_MANAGER_CHOICES = ['npm', 'pnpm', 'yarn', 'bun', 'pip', 'uv', 'go mod', 'cargo', 'composer', 'auto-detect'];
117
- const TEST_FRAMEWORK_CHOICES = ['jest', 'vitest', 'pytest', 'go test', 'phpunit', 'pest', 'rspec', 'junit', 'auto-detect'];
118
- const CLOUD_CHOICES = ['aws', 'gcp', 'azure', 'vercel', 'fly', 'railway', 'none'];
119
- const FRONTEND_FRAMEWORKS = ['vue', 'react', 'next', 'nuxt', 'svelte', 'angular'];
120
- const BACKEND_FRAMEWORKS = ['laravel', 'cakephp', 'symfony', 'codeigniter', 'express', 'fastapi', 'django', 'flask', 'gin', 'fiber', 'echo', 'nestjs', 'rails', 'spring', 'aspnet', 'axum', 'actix'];
121
- const MOBILE_DESKTOP_FRAMEWORKS = ['tauri', 'flutter', 'react-native'];
122
- const IGNORED_SCAN_DIRS = new Set(['.git', 'node_modules', 'vendor', 'dist', 'build', 'coverage', '.next', '.nuxt', '.turbo', '.cache', 'storage', 'tmp']);
123
-
15
+
16
+ const FRAMEWORK_CHOICES = [
17
+ 'vue', 'react', 'next', 'nuxt', 'svelte', 'angular',
18
+ 'laravel', 'cakephp', 'symfony', 'codeigniter',
19
+ 'express', 'fastapi', 'django', 'flask', 'gin', 'fiber', 'echo', 'nestjs',
20
+ 'rails', 'spring', 'aspnet',
21
+ 'tauri', 'axum', 'actix', 'flutter', 'react-native'
22
+ ];
23
+
24
+ const LANGUAGE_CHOICES = ['typescript', 'javascript', 'python', 'go', 'php', 'rust', 'java', 'ruby', 'swift', 'kotlin', 'csharp', 'cpp'];
25
+ const PROJECT_TYPE_CHOICES = ['web-app', 'api', 'mobile', 'desktop', 'cli', 'fullstack'];
26
+ const DATABASE_CHOICES = ['postgres', 'mysql', 'sqlite', 'mongodb', 'redis', 'dynamodb', 'none'];
27
+ const PACKAGE_MANAGER_CHOICES = ['npm', 'pnpm', 'yarn', 'bun', 'pip', 'uv', 'go mod', 'cargo', 'composer', 'auto-detect'];
28
+ const TEST_FRAMEWORK_CHOICES = ['jest', 'vitest', 'pytest', 'go test', 'phpunit', 'pest', 'rspec', 'junit', 'auto-detect'];
29
+ const CLOUD_CHOICES = ['aws', 'gcp', 'azure', 'vercel', 'fly', 'railway', 'none'];
30
+ const FRONTEND_FRAMEWORKS = ['vue', 'react', 'next', 'nuxt', 'svelte', 'angular'];
31
+ const BACKEND_FRAMEWORKS = ['laravel', 'cakephp', 'symfony', 'codeigniter', 'express', 'fastapi', 'django', 'flask', 'gin', 'fiber', 'echo', 'nestjs', 'rails', 'spring', 'aspnet', 'axum', 'actix'];
32
+ const MOBILE_DESKTOP_FRAMEWORKS = ['tauri', 'flutter', 'react-native'];
33
+ const IGNORED_SCAN_DIRS = new Set(['.git', 'node_modules', 'vendor', 'dist', 'build', 'coverage', '.next', '.nuxt', '.turbo', '.cache', 'storage', 'tmp']);
34
+
124
35
  function printHelp() {
125
36
  console.log(`
126
37
  ${pc.bold('Usage:')}
@@ -139,7 +50,10 @@ ${pc.bold('Commands:')}
139
50
 
140
51
  ${pc.bold('Options:')}
141
52
  --yes Overwrite generated files or accept setup defaults
142
- --no-setup-mcp Skip MCP setup (legacy init compatibility)
53
+ --no-setup-mcp Skip MCP setup (legacy init compatibility)
54
+ --no-setup-hook Skip the Claude Code Definition-of-Done Stop hook during setup
55
+ --no-install-rtk Skip auto-installing rtk via cargo during setup
56
+ --no-index Skip auto-indexing the repository with codebase-memory-mcp during setup
143
57
  --version Show the installed CLI version
144
58
  --help Show this help message
145
59
 
@@ -165,734 +79,690 @@ ${pc.bold('Tip:')}
165
79
  Run thachvd-kit setup for the integration checklist and doctor to verify it.
166
80
  `);
167
81
  }
168
-
82
+
169
83
  function formatScanPreviewLines(scanned) {
170
- return [
171
- ['App root', scanned.app_root || '.'],
172
- ['Project type', scanned.project_type || 'unknown'],
173
- ['Primary language', scanned.primary_language || 'unknown'],
174
- ['Frameworks', (scanned.frameworks || []).join(', ') || 'no framework'],
175
- ['Database', scanned.database || 'none'],
176
- ['Package manager', scanned.package_manager || 'auto-detect'],
177
- ['Test framework', scanned.test_framework || 'auto-detect'],
178
- ['Cloud', scanned.cloud || 'none'],
179
- ['Infrastructure', (scanned.infrastructure || []).join(', ') || 'none'],
180
- ['CI/CD', scanned.ci_cd || 'none']
181
- ];
182
- }
183
-
184
- async function askQuestions(questions) {
185
- return prompts(questions, {
186
- onCancel: () => {
187
- console.log(pc.yellow('\nCancelled.'));
188
- process.exit(130);
189
- }
190
- });
191
- }
192
-
193
- function fileExists(...parts) {
194
- return fs.existsSync(path.join(targetDir, ...parts));
195
- }
196
-
197
- function fileExistsAt(baseDir, ...parts) {
198
- return fs.existsSync(path.join(baseDir, ...parts));
199
- }
200
-
201
- function readJsonIfExists(...parts) {
202
- const fullPath = path.join(targetDir, ...parts);
203
- if (!fs.existsSync(fullPath)) return null;
204
- try {
205
- return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
206
- } catch {
207
- return null;
208
- }
209
- }
210
-
211
- function readJsonIfExistsAt(baseDir, ...parts) {
212
- const fullPath = path.join(baseDir, ...parts);
213
- if (!fs.existsSync(fullPath)) return null;
214
- try {
215
- return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
216
- } catch {
217
- return null;
218
- }
219
- }
220
-
221
- function readTextIfExists(...parts) {
222
- const fullPath = path.join(targetDir, ...parts);
223
- if (!fs.existsSync(fullPath)) return '';
224
- try {
225
- return fs.readFileSync(fullPath, 'utf8');
226
- } catch {
227
- return '';
228
- }
229
- }
230
-
231
- function readTextIfExistsAt(baseDir, ...parts) {
232
- const fullPath = path.join(baseDir, ...parts);
233
- if (!fs.existsSync(fullPath)) return '';
234
- try {
235
- return fs.readFileSync(fullPath, 'utf8');
236
- } catch {
237
- return '';
238
- }
239
- }
240
-
241
- function detectPackageManager(baseDir = targetDir) {
242
- if (fileExistsAt(baseDir, 'pnpm-lock.yaml')) return 'pnpm';
243
- if (fileExistsAt(baseDir, 'yarn.lock')) return 'yarn';
244
- if (fileExistsAt(baseDir, 'bun.lockb') || fileExistsAt(baseDir, 'bun.lock')) return 'bun';
245
- if (fileExistsAt(baseDir, 'package-lock.json')) return 'npm';
246
- if (fileExistsAt(baseDir, 'uv.lock')) return 'uv';
247
- if (fileExistsAt(baseDir, 'poetry.lock')) return 'pip';
248
- if (fileExistsAt(baseDir, 'requirements.txt') || fileExistsAt(baseDir, 'pyproject.toml')) return 'pip';
249
- if (fileExistsAt(baseDir, 'go.mod')) return 'go mod';
250
- if (fileExistsAt(baseDir, 'Cargo.toml')) return 'cargo';
251
- if (fileExistsAt(baseDir, 'composer.json')) return 'composer';
252
- return 'auto-detect';
253
- }
254
-
255
- function uniq(values) {
256
- return Array.from(new Set(values.filter(Boolean)));
257
- }
258
-
259
- function detectAppRoot(baseDir) {
260
- const candidates = [baseDir];
261
- const queue = [{ dir: baseDir, depth: 0 }];
262
-
263
- while (queue.length > 0) {
264
- const { dir, depth } = queue.shift();
265
- if (depth >= 2) continue;
266
- let entries = [];
267
- try {
268
- entries = fs.readdirSync(dir, { withFileTypes: true });
269
- } catch {
270
- continue;
271
- }
272
- for (const entry of entries) {
273
- if (!entry.isDirectory()) continue;
274
- if (IGNORED_SCAN_DIRS.has(entry.name)) continue;
275
- const nextDir = path.join(dir, entry.name);
276
- candidates.push(nextDir);
277
- queue.push({ dir: nextDir, depth: depth + 1 });
278
- }
279
- }
280
-
281
- const scoreCandidate = dir => {
282
- let score = 0;
283
- if (fileExistsAt(dir, 'composer.json')) score += 5;
284
- if (fileExistsAt(dir, 'package.json')) score += 4;
285
- if (fileExistsAt(dir, 'Cargo.toml')) score += 4;
286
- if (fileExistsAt(dir, 'go.mod')) score += 4;
287
- if (fileExistsAt(dir, 'pyproject.toml') || fileExistsAt(dir, 'requirements.txt')) score += 4;
288
- if (fileExistsAt(dir, 'artisan')) score += 5;
289
- if (fileExistsAt(dir, 'bin', 'cake') || fileExistsAt(dir, 'app', 'Config', 'core.php')) score += 5;
290
- if (fileExistsAt(dir, 'src-tauri', 'tauri.conf.json') || fileExistsAt(dir, 'src-tauri', 'tauri.conf.json5')) score += 5;
291
- if (fileExistsAt(dir, 'manage.py')) score += 4;
292
- if (fileExistsAt(dir, 'Gemfile')) score += 4;
293
- if (fileExistsAt(dir, 'pom.xml') || fileExistsAt(dir, 'build.gradle') || fileExistsAt(dir, 'build.gradle.kts')) score += 4;
294
- if (fileExistsAt(dir, 'app', 'View') || fileExistsAt(dir, 'resources', 'views') || fileExistsAt(dir, 'templates') || fileExistsAt(dir, 'app', 'views')) score += 2;
295
- return score;
296
- };
297
-
298
- const ranked = candidates
299
- .map(dir => ({ dir, score: scoreCandidate(dir) }))
300
- .filter(item => item.score > 0)
301
- .sort((a, b) => (b.score - a.score) || (a.dir.length - b.dir.length));
302
-
303
- return ranked[0]?.dir || baseDir;
304
- }
305
-
306
- function repoHasAny(baseDir, relativePaths, maxDepth = 3) {
307
- const queue = [{ dir: baseDir, depth: 0 }];
308
- while (queue.length > 0) {
309
- const { dir, depth } = queue.shift();
310
- for (const relativePath of relativePaths) {
311
- if (fileExistsAt(dir, ...relativePath)) return true;
312
- }
313
- if (depth >= maxDepth) continue;
314
- let entries = [];
315
- try {
316
- entries = fs.readdirSync(dir, { withFileTypes: true });
317
- } catch {
318
- continue;
319
- }
320
- for (const entry of entries) {
321
- if (!entry.isDirectory()) continue;
322
- if (IGNORED_SCAN_DIRS.has(entry.name)) continue;
323
- queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
324
- }
325
- }
326
- return false;
327
- }
328
-
329
- function evidenceIf(condition, label, weight = 1) {
330
- return condition ? { label, weight } : null;
331
- }
332
-
333
- function buildDetection(id, evidence, meta = {}) {
334
- const hits = evidence.filter(Boolean);
335
- const score = hits.reduce((sum, hit) => sum + hit.weight, 0);
336
- return {
337
- id,
338
- score,
339
- evidence: hits.map(hit => hit.label),
340
- ...meta
341
- };
342
- }
343
-
344
- function confidenceLabel(score) {
345
- if (score >= 6) return 'high';
346
- if (score >= 3) return 'medium';
347
- return 'low';
348
- }
349
-
350
- function hasDependency(depNames, ...names) {
351
- return names.some(name => depNames.has(name));
352
- }
353
-
354
- function hasComposerDependency(composerDepNames, ...names) {
355
- return names.some(name => composerDepNames.has(name));
356
- }
357
-
358
- function hasRootFile(rootEntries, ...filenames) {
359
- return filenames.some(name => rootEntries.has(name));
360
- }
361
-
362
- function textMatches(text, pattern) {
363
- return Boolean(text && pattern.test(text));
364
- }
365
-
366
- const LANGUAGE_DETECTORS = [
367
- {
368
- id: 'typescript',
369
- detect: ctx => buildDetection('typescript', [
370
- evidenceIf(ctx.fileExists('tsconfig.json'), 'found tsconfig.json', 4),
371
- evidenceIf(hasDependency(ctx.depNames, 'typescript', 'ts-node', 'tsx'), 'package.json -> typescript toolchain', 2)
372
- ])
373
- },
374
- {
375
- id: 'javascript',
376
- detect: ctx => buildDetection('javascript', [
377
- evidenceIf(ctx.fileExists('package.json'), 'found package.json', 2),
378
- evidenceIf(ctx.depNames.size > 0, 'package.json -> JavaScript dependency graph', 1)
379
- ])
380
- },
381
- {
382
- id: 'python',
383
- detect: ctx => buildDetection('python', [
384
- evidenceIf(ctx.fileExists('requirements.txt'), 'found requirements.txt', 3),
385
- evidenceIf(ctx.fileExists('pyproject.toml'), 'found pyproject.toml', 2),
386
- evidenceIf(textMatches(ctx.pyprojectText, /\[tool\.(poetry|uv|hatch|pdm)\]/i), 'pyproject.toml -> Python tool section', 2)
387
- ])
388
- },
389
- {
390
- id: 'go',
391
- detect: ctx => buildDetection('go', [
392
- evidenceIf(ctx.fileExists('go.mod'), 'found go.mod', 4)
393
- ])
394
- },
395
- {
396
- id: 'php',
397
- detect: ctx => buildDetection('php', [
398
- evidenceIf(ctx.fileExists('composer.json'), 'found composer.json', 4),
399
- evidenceIf(ctx.composerDepNames.size > 0, 'composer.json -> PHP dependency graph', 1)
400
- ])
401
- },
402
- {
403
- id: 'rust',
404
- detect: ctx => buildDetection('rust', [
405
- evidenceIf(ctx.fileExists('Cargo.toml'), 'found Cargo.toml', 4),
406
- evidenceIf(ctx.fileExists('src-tauri', 'Cargo.toml'), 'found src-tauri/Cargo.toml', 5)
407
- ])
408
- },
409
- {
410
- id: 'java',
411
- detect: ctx => buildDetection('java', [
412
- evidenceIf(ctx.fileExists('pom.xml'), 'found pom.xml', 4),
413
- evidenceIf(ctx.fileExists('build.gradle') || ctx.fileExists('build.gradle.kts'), 'found Gradle build file', 3)
414
- ])
415
- },
416
- {
417
- id: 'ruby',
418
- detect: ctx => buildDetection('ruby', [
419
- evidenceIf(ctx.fileExists('Gemfile'), 'found Gemfile', 4),
420
- evidenceIf(ctx.fileExists('config.ru'), 'found config.ru', 1)
421
- ])
422
- },
423
- {
424
- id: 'csharp',
425
- detect: ctx => buildDetection('csharp', [
426
- evidenceIf(ctx.rootEntries.some(name => name.endsWith('.sln') || name.endsWith('.csproj')), 'found .sln/.csproj', 4),
427
- evidenceIf(ctx.fileExists('Program.cs'), 'found Program.cs', 1)
428
- ])
429
- }
430
- ];
431
-
432
- const FRAMEWORK_DETECTORS = [
433
- {
434
- id: 'next',
435
- kind: 'frontend',
436
- projectType: 'web-app',
437
- detect: ctx => buildDetection('next', [
438
- evidenceIf(hasDependency(ctx.depNames, 'next'), 'package.json -> next', 4),
439
- evidenceIf(ctx.fileExists('next.config.js') || ctx.fileExists('next.config.mjs') || ctx.fileExists('next.config.ts'), 'found next.config.*', 3),
440
- evidenceIf(ctx.fileExists('app') || ctx.fileExists('pages'), 'found app/ or pages/', 1)
441
- ])
442
- },
443
- {
444
- id: 'react',
445
- kind: 'frontend',
446
- projectType: 'web-app',
447
- detect: ctx => buildDetection('react', [
448
- evidenceIf(hasDependency(ctx.depNames, 'react'), 'package.json -> react', 4),
449
- evidenceIf(hasDependency(ctx.depNames, 'react-dom'), 'package.json -> react-dom', 2)
450
- ])
451
- },
452
- {
453
- id: 'vue',
454
- kind: 'frontend',
455
- projectType: 'web-app',
456
- detect: ctx => buildDetection('vue', [
457
- evidenceIf(hasDependency(ctx.depNames, 'vue'), 'package.json -> vue', 4)
458
- ])
459
- },
460
- {
461
- id: 'nuxt',
462
- kind: 'frontend',
463
- projectType: 'web-app',
464
- detect: ctx => buildDetection('nuxt', [
465
- evidenceIf(hasDependency(ctx.depNames, 'nuxt'), 'package.json -> nuxt', 4),
466
- evidenceIf(ctx.fileExists('nuxt.config.ts') || ctx.fileExists('nuxt.config.js'), 'found nuxt.config.*', 3)
467
- ])
468
- },
469
- {
470
- id: 'svelte',
471
- kind: 'frontend',
472
- projectType: 'web-app',
473
- detect: ctx => buildDetection('svelte', [
474
- evidenceIf(hasDependency(ctx.depNames, 'svelte', '@sveltejs/kit'), 'package.json -> svelte', 4)
475
- ])
476
- },
477
- {
478
- id: 'angular',
479
- kind: 'frontend',
480
- projectType: 'web-app',
481
- detect: ctx => buildDetection('angular', [
482
- evidenceIf(hasDependency(ctx.depNames, '@angular/core'), 'package.json -> @angular/core', 4),
483
- evidenceIf(ctx.fileExists('angular.json'), 'found angular.json', 3)
484
- ])
485
- },
486
- {
487
- id: 'express',
488
- kind: 'backend',
489
- language: 'javascript',
490
- projectType: 'api',
491
- detect: ctx => buildDetection('express', [
492
- evidenceIf(hasDependency(ctx.depNames, 'express'), 'package.json -> express', 4)
493
- ])
494
- },
495
- {
496
- id: 'nestjs',
497
- kind: 'backend',
498
- language: 'javascript',
499
- projectType: 'api',
500
- detect: ctx => buildDetection('nestjs', [
501
- evidenceIf(hasDependency(ctx.depNames, '@nestjs/core'), 'package.json -> @nestjs/core', 4)
502
- ])
503
- },
504
- {
505
- id: 'fastapi',
506
- kind: 'backend',
507
- language: 'python',
508
- projectType: 'api',
509
- detect: ctx => buildDetection('fastapi', [
510
- evidenceIf(textMatches(ctx.requirementsText, /\bfastapi\b/i) || textMatches(ctx.pyprojectText, /\bfastapi\b/i), 'Python deps -> fastapi', 4)
511
- ])
512
- },
513
- {
514
- id: 'django',
515
- kind: 'backend',
516
- language: 'python',
517
- projectType: 'web-app',
518
- detect: ctx => buildDetection('django', [
519
- evidenceIf(textMatches(ctx.requirementsText, /\bdjango\b/i) || textMatches(ctx.pyprojectText, /\bdjango\b/i), 'Python deps -> django', 4),
520
- evidenceIf(ctx.fileExists('manage.py'), 'found manage.py', 2),
521
- evidenceIf(ctx.fileExists('templates'), 'found templates/', 1)
522
- ])
523
- },
524
- {
525
- id: 'flask',
526
- kind: 'backend',
527
- language: 'python',
528
- projectType: 'api',
529
- detect: ctx => buildDetection('flask', [
530
- evidenceIf(textMatches(ctx.requirementsText, /\bflask\b/i) || textMatches(ctx.pyprojectText, /\bflask\b/i), 'Python deps -> flask', 4)
531
- ])
532
- },
533
- {
534
- id: 'laravel',
535
- kind: 'backend',
536
- language: 'php',
537
- projectType: 'web-app',
538
- detect: ctx => buildDetection('laravel', [
539
- evidenceIf(hasComposerDependency(ctx.composerDepNames, 'laravel/framework'), 'composer.json -> laravel/framework', 4),
540
- evidenceIf(ctx.fileExists('artisan'), 'found artisan', 3),
541
- evidenceIf(ctx.fileExists('resources', 'views'), 'found resources/views', 1)
542
- ])
543
- },
544
- {
545
- id: 'cakephp',
546
- kind: 'backend',
547
- language: 'php',
548
- projectType: 'web-app',
549
- detect: ctx => buildDetection('cakephp', [
550
- evidenceIf(hasComposerDependency(ctx.composerDepNames, 'cakephp/cakephp'), 'composer.json -> cakephp/cakephp', 4),
551
- evidenceIf(ctx.fileExists('bin', 'cake'), 'found bin/cake', 3),
552
- evidenceIf(ctx.fileExists('config', 'app.php'), 'found config/app.php', 2),
553
- evidenceIf(ctx.fileExists('app', 'Config', 'core.php'), 'found app/Config/core.php (CakePHP legacy)', 3),
554
- evidenceIf(ctx.fileExists('app', 'Controller', 'AppController.php'), 'found app/Controller/AppController.php', 2),
555
- evidenceIf(ctx.fileExists('app', 'Model', 'AppModel.php'), 'found app/Model/AppModel.php', 2),
556
- evidenceIf(ctx.fileExists('lib', 'Cake'), 'found lib/Cake', 3),
557
- evidenceIf(ctx.fileExists('cake', 'console', 'cake'), 'found cake/console/cake', 3),
558
- evidenceIf(ctx.fileExists('app', 'View'), 'found app/View', 2),
559
- evidenceIf(textMatches(ctx.viewFilesText, /\.ctp$/im), 'found .ctp view templates', 2)
560
- ])
561
- },
562
- {
563
- id: 'symfony',
564
- kind: 'backend',
565
- language: 'php',
566
- projectType: 'web-app',
567
- detect: ctx => buildDetection('symfony', [
568
- evidenceIf(hasComposerDependency(ctx.composerDepNames, 'symfony/framework-bundle'), 'composer.json -> symfony/framework-bundle', 4),
569
- evidenceIf(ctx.fileExists('bin', 'console'), 'found bin/console', 2),
570
- evidenceIf(ctx.fileExists('config', 'bundles.php'), 'found config/bundles.php', 1),
571
- evidenceIf(ctx.fileExists('templates'), 'found templates/', 1)
572
- ])
573
- },
574
- {
575
- id: 'codeigniter',
576
- kind: 'backend',
577
- language: 'php',
578
- projectType: 'api',
579
- detect: ctx => buildDetection('codeigniter', [
580
- evidenceIf(hasComposerDependency(ctx.composerDepNames, 'codeigniter4/framework'), 'composer.json -> codeigniter4/framework', 4),
581
- evidenceIf(ctx.fileExists('spark'), 'found spark', 2),
582
- evidenceIf(ctx.fileExists('app', 'Config', 'App.php'), 'found app/Config/App.php', 1)
583
- ])
584
- },
585
- {
586
- id: 'gin',
587
- kind: 'backend',
588
- language: 'go',
589
- projectType: 'api',
590
- detect: ctx => buildDetection('gin', [
591
- evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/gin-gonic\/gin\b/i), 'go.mod -> github.com/gin-gonic/gin', 4)
592
- ])
593
- },
594
- {
595
- id: 'fiber',
596
- kind: 'backend',
597
- language: 'go',
598
- projectType: 'api',
599
- detect: ctx => buildDetection('fiber', [
600
- evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/gofiber\/fiber\b/i), 'go.mod -> github.com/gofiber/fiber', 4)
601
- ])
602
- },
603
- {
604
- id: 'echo',
605
- kind: 'backend',
606
- language: 'go',
607
- projectType: 'api',
608
- detect: ctx => buildDetection('echo', [
609
- evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/labstack\/echo\b/i), 'go.mod -> github.com/labstack/echo', 4)
610
- ])
611
- },
612
- {
613
- id: 'rails',
614
- kind: 'backend',
615
- language: 'ruby',
616
- projectType: 'web-app',
617
- detect: ctx => buildDetection('rails', [
618
- evidenceIf(textMatches(ctx.gemfileText, /^\s*gem\s+["']rails["']/im), 'Gemfile -> rails', 4),
619
- evidenceIf(ctx.fileExists('bin', 'rails'), 'found bin/rails', 2),
620
- evidenceIf(ctx.fileExists('app', 'views'), 'found app/views', 1)
621
- ])
622
- },
623
- {
624
- id: 'spring',
625
- kind: 'backend',
626
- language: 'java',
627
- projectType: 'api',
628
- detect: ctx => buildDetection('spring', [
629
- evidenceIf(textMatches(ctx.pomText, /spring-boot/i) || textMatches(ctx.gradleText, /spring-boot/i), 'Java build -> spring-boot', 4)
630
- ])
631
- },
632
- {
633
- id: 'aspnet',
634
- kind: 'backend',
635
- language: 'csharp',
636
- projectType: 'api',
637
- detect: ctx => buildDetection('aspnet', [
638
- evidenceIf(textMatches(ctx.csprojText, /Microsoft\.NET\.Sdk\.Web/i), '.csproj -> Microsoft.NET.Sdk.Web', 4),
639
- evidenceIf(textMatches(ctx.programCsText, /WebApplication\.CreateBuilder/i), 'Program.cs -> WebApplication.CreateBuilder', 2)
640
- ])
641
- },
642
- {
643
- id: 'tauri',
644
- kind: 'desktop',
645
- language: 'rust',
646
- projectType: 'desktop',
647
- detect: ctx => buildDetection('tauri', [
648
- evidenceIf(hasDependency(ctx.depNames, '@tauri-apps/api'), 'package.json -> @tauri-apps/api', 4),
649
- evidenceIf(ctx.fileExists('src-tauri', 'tauri.conf.json') || ctx.fileExists('src-tauri', 'tauri.conf.json5'), 'found src-tauri/tauri.conf.*', 4),
650
- evidenceIf(ctx.fileExists('src-tauri', 'Cargo.toml'), 'found src-tauri/Cargo.toml', 2)
651
- ])
652
- },
653
- {
654
- id: 'axum',
655
- kind: 'backend',
656
- language: 'rust',
657
- projectType: 'api',
658
- detect: ctx => buildDetection('axum', [
659
- evidenceIf(textMatches(ctx.cargoText, /\baxum\b/i), 'Cargo.toml -> axum', 4)
660
- ])
661
- },
662
- {
663
- id: 'actix',
664
- kind: 'backend',
665
- language: 'rust',
666
- projectType: 'api',
667
- detect: ctx => buildDetection('actix', [
668
- evidenceIf(textMatches(ctx.cargoText, /\bactix-web\b/i), 'Cargo.toml -> actix-web', 4)
669
- ])
670
- },
671
- {
672
- id: 'flutter',
673
- kind: 'mobile',
674
- projectType: 'mobile',
675
- detect: ctx => buildDetection('flutter', [
676
- evidenceIf(textMatches(ctx.pubspecText, /^\s*flutter\s*:/im), 'pubspec.yaml -> flutter', 4)
677
- ])
678
- },
679
- {
680
- id: 'react-native',
681
- kind: 'mobile',
682
- projectType: 'mobile',
683
- detect: ctx => buildDetection('react-native', [
684
- evidenceIf(hasDependency(ctx.depNames, 'react-native', 'expo'), 'package.json -> react-native/expo', 4)
685
- ])
686
- }
687
- ];
688
-
689
- function scanProject() {
690
- const appRoot = detectAppRoot(targetDir);
691
- const pkg = readJsonIfExistsAt(appRoot, 'package.json') || {};
692
- const composer = readJsonIfExistsAt(appRoot, 'composer.json') || {};
693
- const rootEntries = fs.existsSync(appRoot) ? fs.readdirSync(appRoot) : [];
694
- const rootCsproj = rootEntries.find(name => name.endsWith('.csproj')) || '';
695
- const deps = {
696
- ...(pkg.dependencies || {}),
697
- ...(pkg.devDependencies || {}),
698
- ...(pkg.peerDependencies || {})
699
- };
700
- const depNames = new Set(Object.keys(deps));
701
- const composerDeps = {
702
- ...(composer.require || {}),
703
- ...(composer['require-dev'] || {})
704
- };
705
- const composerDepNames = new Set(Object.keys(composerDeps));
706
- const ctx = {
707
- pkg,
708
- composer,
709
- depNames,
710
- composerDepNames,
711
- rootEntries,
712
- fileExists: (...parts) => fileExistsAt(appRoot, ...parts),
713
- requirementsText: readTextIfExistsAt(appRoot, 'requirements.txt'),
714
- pyprojectText: readTextIfExistsAt(appRoot, 'pyproject.toml'),
715
- goModText: readTextIfExistsAt(appRoot, 'go.mod'),
716
- pubspecText: readTextIfExistsAt(appRoot, 'pubspec.yaml'),
717
- gemfileText: readTextIfExistsAt(appRoot, 'Gemfile'),
718
- pomText: readTextIfExistsAt(appRoot, 'pom.xml'),
719
- gradleText: `${readTextIfExistsAt(appRoot, 'build.gradle')}\n${readTextIfExistsAt(appRoot, 'build.gradle.kts')}`,
720
- cargoText: `${readTextIfExistsAt(appRoot, 'Cargo.toml')}\n${readTextIfExistsAt(appRoot, 'src-tauri', 'Cargo.toml')}`,
721
- csprojText: rootCsproj ? readTextIfExistsAt(appRoot, rootCsproj) : '',
722
- programCsText: readTextIfExistsAt(appRoot, 'Program.cs'),
723
- viewFilesText: fs.existsSync(path.join(appRoot, 'app', 'View'))
724
- ? fs.readdirSync(path.join(appRoot, 'app', 'View'), { recursive: true }).join('\n')
725
- : ''
726
- };
727
-
728
- const languageDetections = LANGUAGE_DETECTORS
729
- .map(detector => detector.detect(ctx))
730
- .filter(result => result.score >= 2)
731
- .sort((a, b) => b.score - a.score);
732
-
733
- const frameworkDetails = FRAMEWORK_DETECTORS
734
- .map(detector => {
735
- const result = detector.detect(ctx);
736
- if (result.score < 3) return null;
737
- return {
738
- ...result,
739
- kind: detector.kind,
740
- language: detector.language,
741
- projectType: detector.projectType,
742
- confidence: confidenceLabel(result.score)
743
- };
744
- })
745
- .filter(Boolean)
746
- .sort((a, b) => b.score - a.score);
747
-
748
- const frameworkLanguageScores = frameworkDetails.reduce((acc, item) => {
749
- if (!item.language) return acc;
750
- acc[item.language] = (acc[item.language] || 0) + item.score;
751
- return acc;
752
- }, {});
753
- const primaryLanguage = Object.keys(frameworkLanguageScores).sort((a, b) => frameworkLanguageScores[b] - frameworkLanguageScores[a])[0]
754
- || languageDetections[0]?.id
755
- || 'typescript';
756
- const frameworks = uniq(frameworkDetails.map(item => item.id)).filter(name => FRAMEWORK_CHOICES.includes(name));
757
- const infrastructure = [];
758
- let projectType = '';
759
- let database = 'none';
760
- let testFramework = 'auto-detect';
761
- let cloud = 'none';
762
- let ciCd = 'none';
763
-
764
- if (frameworkDetails.some(item => item.projectType === 'desktop')) projectType = 'desktop';
765
- else if (frameworkDetails.some(item => item.projectType === 'mobile')) projectType = 'mobile';
766
- else if (frameworkDetails.some(item => item.kind === 'frontend') && frameworkDetails.some(item => item.kind === 'backend')) projectType = 'fullstack';
767
- else if (frameworkDetails.some(item => item.projectType === 'web-app')) projectType = 'web-app';
768
- else if (frameworkDetails.some(item => item.kind === 'backend')) projectType = 'api';
769
- else if (frameworkDetails.some(item => item.kind === 'frontend')) projectType = 'web-app';
770
- else if (fileExistsAt(appRoot, 'package.json') && pkg.bin) projectType = 'cli';
771
- else if (['php', 'python', 'go', 'java', 'ruby', 'csharp', 'rust'].includes(primaryLanguage)) projectType = 'api';
772
-
773
- if (hasDependency(depNames, 'pg', 'postgres', '@prisma/client') || /postgres/i.test(JSON.stringify(pkg))) database = 'postgres';
774
- else if (hasDependency(depNames, 'mysql', 'mysql2')) database = 'mysql';
775
- else if (hasDependency(depNames, 'sqlite3', 'better-sqlite3', 'rusqlite')) database = 'sqlite';
776
- else if (hasDependency(depNames, 'mongodb', 'mongoose')) database = 'mongodb';
777
- else if (hasDependency(depNames, 'redis', 'ioredis')) database = 'redis';
778
- else if (hasDependency(depNames, '@aws-sdk/client-dynamodb')) database = 'dynamodb';
779
-
780
- if (hasDependency(depNames, 'vitest')) testFramework = 'vitest';
781
- else if (hasDependency(depNames, 'jest')) testFramework = 'jest';
782
- else if (hasDependency(depNames, 'pytest') || textMatches(ctx.requirementsText, /\bpytest\b/i) || textMatches(ctx.pyprojectText, /\bpytest\b/i)) testFramework = 'pytest';
783
- else if (hasComposerDependency(composerDepNames, 'phpunit/phpunit')) testFramework = 'phpunit';
784
- else if (hasComposerDependency(composerDepNames, 'pestphp/pest')) testFramework = 'pest';
785
- else if (fileExistsAt(appRoot, 'go.mod')) testFramework = 'go test';
786
- else if (textMatches(ctx.gemfileText, /^\s*gem\s+["']rspec["']/im)) testFramework = 'rspec';
787
-
788
- if (repoHasAny(targetDir, [['Dockerfile'], ['docker-compose.yml'], ['docker-compose.yaml']])) {
789
- infrastructure.push('docker');
790
- }
791
-
792
- if (repoHasAny(targetDir, [['vercel.json']])) {
793
- cloud = 'vercel';
794
- infrastructure.push('vercel');
795
- } else if (repoHasAny(targetDir, [['fly.toml']])) {
796
- cloud = 'fly';
797
- infrastructure.push('fly');
798
- } else if (repoHasAny(targetDir, [['railway.json'], ['railway.toml']])) {
799
- cloud = 'railway';
800
- infrastructure.push('railway');
801
- }
802
-
803
- if (repoHasAny(targetDir, [['.github', 'workflows'], ['.gitlab-ci.yml'], ['.circleci', 'config.yml'], ['Jenkinsfile']], 2)) {
804
- if (repoHasAny(targetDir, [['.github', 'workflows']], 2)) ciCd = 'github-actions';
805
- else if (repoHasAny(targetDir, [['.gitlab-ci.yml']], 2)) ciCd = 'gitlab-ci';
806
- else if (repoHasAny(targetDir, [['.circleci', 'config.yml']], 2)) ciCd = 'circleci';
807
- else if (repoHasAny(targetDir, [['Jenkinsfile']], 2)) ciCd = 'jenkins';
808
- }
809
-
810
- const scanEvidence = [
811
- ...(languageDetections[0] ? [`language:${languageDetections[0].id} => ${languageDetections[0].evidence.join('; ')}`] : []),
812
- ...frameworkDetails.map(item => `${item.id} [${item.confidence}] => ${item.evidence.join('; ')}`)
813
- ];
814
-
815
- return {
816
- project_name: path.basename(targetDir),
817
- app_root: path.relative(targetDir, appRoot) || '.',
818
- description: pkg.description || composer.description || 'A software project',
819
- project_type: PROJECT_TYPE_CHOICES.includes(projectType) ? projectType : 'web-app',
820
- primary_language: LANGUAGE_CHOICES.includes(primaryLanguage) ? primaryLanguage : 'typescript',
821
- frameworks,
822
- framework_details: frameworkDetails,
823
- scan_evidence: scanEvidence,
824
- database: DATABASE_CHOICES.includes(database) ? database : 'none',
825
- package_manager: PACKAGE_MANAGER_CHOICES.includes(detectPackageManager(appRoot)) ? detectPackageManager(appRoot) : 'auto-detect',
826
- uses_docker: infrastructure.includes('docker'),
827
- cloud,
828
- infrastructure: uniq(infrastructure),
829
- ci_cd: ciCd,
830
- test_framework: TEST_FRAMEWORK_CHOICES.includes(testFramework) ? testFramework : 'auto-detect',
831
- max_file_lines: '300',
832
- code_style: 'project-standard',
833
- architecture_notes: '<!-- Add notes -->',
834
- current_phase: 'Initial setup',
835
- next_phase: '-',
836
- known_issues: '<!-- None yet -->'
837
- };
838
- }
839
-
840
- function resolveAgentTable(data) {
841
- const rows = [];
842
- const frameworks = (data.frameworks || []).map(f => f.toLowerCase());
843
- const lang = (data.primary_language || "").toLowerCase();
844
-
845
- // Frontend
846
- const frontendFws = frameworks.filter(f => FRONTEND_FRAMEWORKS.includes(f));
847
- if (frontendFws.length > 0) {
848
- let feSkills = [];
849
- frontendFws.forEach(fw => {
850
- feSkills.push(...(FRAMEWORK_SKILLS[fw] || []));
851
- });
852
- rows.push(["Frontend UI", "frontend-specialist", Array.from(new Set(feSkills)).slice(0, 3).join(", ")]);
853
- }
854
-
855
- // Backend
856
- let beSkills = [...(LANG_SKILLS[lang] || ["api-design"])];
857
- const backendFws = frameworks.filter(f => BACKEND_FRAMEWORKS.includes(f));
858
- backendFws.forEach(fw => {
859
- beSkills.push(...(FRAMEWORK_SKILLS[fw] || []));
860
- });
861
- rows.push(["Backend API", "backend-specialist", Array.from(new Set(beSkills)).slice(0, 3).join(", ")]);
862
-
863
- // Mobile/Desktop
864
- const mobileFws = frameworks.filter(f => MOBILE_DESKTOP_FRAMEWORKS.includes(f));
865
- if (mobileFws.length > 0) {
866
- let mobileSkills = [];
867
- mobileFws.forEach(fw => {
868
- mobileSkills.push(...(FRAMEWORK_SKILLS[fw] || []));
869
- });
870
- rows.push(["Mobile/Desktop", "mobile-developer", Array.from(new Set(mobileSkills)).slice(0, 3).join(", ")]);
871
- }
872
-
873
- // DevOps
874
- if (data.uses_docker || data.cloud !== "none") {
875
- rows.push(["DevOps/Infra", "devops-engineer", "docker-patterns, deployment-procedures"]);
876
- }
877
-
878
- rows.push(["Debug", "debugger", "systematic-debugging"]);
879
- rows.push(["Security", "security-auditor", "vulnerability-scanner"]);
880
- rows.push(["Planning", "project-planner", "brainstorming, plan-writing"]);
881
-
882
84
  return rows;
883
- }
884
- // --- File Generators ---
885
-
85
+ return [
86
+ ['App root', scanned.app_root || '.'],
87
+ ['Project type', scanned.project_type || 'unknown'],
88
+ ['Primary language', scanned.primary_language || 'unknown'],
89
+ ['Frameworks', (scanned.frameworks || []).join(', ') || 'no framework'],
90
+ ['Database', scanned.database || 'none'],
91
+ ['Package manager', scanned.package_manager || 'auto-detect'],
92
+ ['Test framework', scanned.test_framework || 'auto-detect'],
93
+ ['Cloud', scanned.cloud || 'none'],
94
+ ['Infrastructure', (scanned.infrastructure || []).join(', ') || 'none'],
95
+ ['CI/CD', scanned.ci_cd || 'none']
96
+ ];
97
+ }
98
+
99
+ async function askQuestions(questions) {
100
+ return prompts(questions, {
101
+ onCancel: () => {
102
+ console.log(pc.yellow('\nCancelled.'));
103
+ process.exit(130);
104
+ }
105
+ });
106
+ }
107
+
108
+ function fileExists(...parts) {
109
+ return fs.existsSync(path.join(targetDir, ...parts));
110
+ }
111
+
112
+ function fileExistsAt(baseDir, ...parts) {
113
+ return fs.existsSync(path.join(baseDir, ...parts));
114
+ }
115
+
116
+ function readJsonIfExists(...parts) {
117
+ const fullPath = path.join(targetDir, ...parts);
118
+ if (!fs.existsSync(fullPath)) return null;
119
+ try {
120
+ return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
121
+ } catch {
122
+ return null;
123
+ }
124
+ }
125
+
126
+ function readJsonIfExistsAt(baseDir, ...parts) {
127
+ const fullPath = path.join(baseDir, ...parts);
128
+ if (!fs.existsSync(fullPath)) return null;
129
+ try {
130
+ return JSON.parse(fs.readFileSync(fullPath, 'utf8'));
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+
136
+ function readTextIfExists(...parts) {
137
+ const fullPath = path.join(targetDir, ...parts);
138
+ if (!fs.existsSync(fullPath)) return '';
139
+ try {
140
+ return fs.readFileSync(fullPath, 'utf8');
141
+ } catch {
142
+ return '';
143
+ }
144
+ }
145
+
146
+ function readTextIfExistsAt(baseDir, ...parts) {
147
+ const fullPath = path.join(baseDir, ...parts);
148
+ if (!fs.existsSync(fullPath)) return '';
149
+ try {
150
+ return fs.readFileSync(fullPath, 'utf8');
151
+ } catch {
152
+ return '';
153
+ }
154
+ }
155
+
156
+ function detectPackageManager(baseDir = targetDir) {
157
+ if (fileExistsAt(baseDir, 'pnpm-lock.yaml')) return 'pnpm';
158
+ if (fileExistsAt(baseDir, 'yarn.lock')) return 'yarn';
159
+ if (fileExistsAt(baseDir, 'bun.lockb') || fileExistsAt(baseDir, 'bun.lock')) return 'bun';
160
+ if (fileExistsAt(baseDir, 'package-lock.json')) return 'npm';
161
+ if (fileExistsAt(baseDir, 'uv.lock')) return 'uv';
162
+ if (fileExistsAt(baseDir, 'poetry.lock')) return 'pip';
163
+ if (fileExistsAt(baseDir, 'requirements.txt') || fileExistsAt(baseDir, 'pyproject.toml')) return 'pip';
164
+ if (fileExistsAt(baseDir, 'go.mod')) return 'go mod';
165
+ if (fileExistsAt(baseDir, 'Cargo.toml')) return 'cargo';
166
+ if (fileExistsAt(baseDir, 'composer.json')) return 'composer';
167
+ return 'auto-detect';
168
+ }
169
+
170
+ function uniq(values) {
171
+ return Array.from(new Set(values.filter(Boolean)));
172
+ }
173
+
174
+ function detectAppRoot(baseDir) {
175
+ const candidates = [baseDir];
176
+ const queue = [{ dir: baseDir, depth: 0 }];
177
+
178
+ while (queue.length > 0) {
179
+ const { dir, depth } = queue.shift();
180
+ if (depth >= 2) continue;
181
+ let entries = [];
182
+ try {
183
+ entries = fs.readdirSync(dir, { withFileTypes: true });
184
+ } catch {
185
+ continue;
186
+ }
187
+ for (const entry of entries) {
188
+ if (!entry.isDirectory()) continue;
189
+ if (IGNORED_SCAN_DIRS.has(entry.name)) continue;
190
+ const nextDir = path.join(dir, entry.name);
191
+ candidates.push(nextDir);
192
+ queue.push({ dir: nextDir, depth: depth + 1 });
193
+ }
194
+ }
195
+
196
+ const scoreCandidate = dir => {
197
+ let score = 0;
198
+ if (fileExistsAt(dir, 'composer.json')) score += 5;
199
+ if (fileExistsAt(dir, 'package.json')) score += 4;
200
+ if (fileExistsAt(dir, 'Cargo.toml')) score += 4;
201
+ if (fileExistsAt(dir, 'go.mod')) score += 4;
202
+ if (fileExistsAt(dir, 'pyproject.toml') || fileExistsAt(dir, 'requirements.txt')) score += 4;
203
+ if (fileExistsAt(dir, 'artisan')) score += 5;
204
+ if (fileExistsAt(dir, 'bin', 'cake') || fileExistsAt(dir, 'app', 'Config', 'core.php')) score += 5;
205
+ if (fileExistsAt(dir, 'src-tauri', 'tauri.conf.json') || fileExistsAt(dir, 'src-tauri', 'tauri.conf.json5')) score += 5;
206
+ if (fileExistsAt(dir, 'manage.py')) score += 4;
207
+ if (fileExistsAt(dir, 'Gemfile')) score += 4;
208
+ if (fileExistsAt(dir, 'pom.xml') || fileExistsAt(dir, 'build.gradle') || fileExistsAt(dir, 'build.gradle.kts')) score += 4;
209
+ if (fileExistsAt(dir, 'app', 'View') || fileExistsAt(dir, 'resources', 'views') || fileExistsAt(dir, 'templates') || fileExistsAt(dir, 'app', 'views')) score += 2;
210
+ return score;
211
+ };
212
+
213
+ const ranked = candidates
214
+ .map(dir => ({ dir, score: scoreCandidate(dir) }))
215
+ .filter(item => item.score > 0)
216
+ .sort((a, b) => (b.score - a.score) || (a.dir.length - b.dir.length));
217
+
218
+ return ranked[0]?.dir || baseDir;
219
+ }
220
+
221
+ function repoHasAny(baseDir, relativePaths, maxDepth = 3) {
222
+ const queue = [{ dir: baseDir, depth: 0 }];
223
+ while (queue.length > 0) {
224
+ const { dir, depth } = queue.shift();
225
+ for (const relativePath of relativePaths) {
226
+ if (fileExistsAt(dir, ...relativePath)) return true;
227
+ }
228
+ if (depth >= maxDepth) continue;
229
+ let entries = [];
230
+ try {
231
+ entries = fs.readdirSync(dir, { withFileTypes: true });
232
+ } catch {
233
+ continue;
234
+ }
235
+ for (const entry of entries) {
236
+ if (!entry.isDirectory()) continue;
237
+ if (IGNORED_SCAN_DIRS.has(entry.name)) continue;
238
+ queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
239
+ }
240
+ }
241
+ return false;
242
+ }
243
+
244
+ function evidenceIf(condition, label, weight = 1) {
245
+ return condition ? { label, weight } : null;
246
+ }
247
+
248
+ function buildDetection(id, evidence, meta = {}) {
249
+ const hits = evidence.filter(Boolean);
250
+ const score = hits.reduce((sum, hit) => sum + hit.weight, 0);
251
+ return {
252
+ id,
253
+ score,
254
+ evidence: hits.map(hit => hit.label),
255
+ ...meta
256
+ };
257
+ }
258
+
259
+ function confidenceLabel(score) {
260
+ if (score >= 6) return 'high';
261
+ if (score >= 3) return 'medium';
262
+ return 'low';
263
+ }
264
+
265
+ function hasDependency(depNames, ...names) {
266
+ return names.some(name => depNames.has(name));
267
+ }
268
+
269
+ function hasComposerDependency(composerDepNames, ...names) {
270
+ return names.some(name => composerDepNames.has(name));
271
+ }
272
+
273
+ function hasRootFile(rootEntries, ...filenames) {
274
+ return filenames.some(name => rootEntries.has(name));
275
+ }
276
+
277
+ function textMatches(text, pattern) {
278
+ return Boolean(text && pattern.test(text));
279
+ }
280
+
281
+ const LANGUAGE_DETECTORS = [
282
+ {
283
+ id: 'typescript',
284
+ detect: ctx => buildDetection('typescript', [
285
+ evidenceIf(ctx.fileExists('tsconfig.json'), 'found tsconfig.json', 4),
286
+ evidenceIf(hasDependency(ctx.depNames, 'typescript', 'ts-node', 'tsx'), 'package.json -> typescript toolchain', 2)
287
+ ])
288
+ },
289
+ {
290
+ id: 'javascript',
291
+ detect: ctx => buildDetection('javascript', [
292
+ evidenceIf(ctx.fileExists('package.json'), 'found package.json', 2),
293
+ evidenceIf(ctx.depNames.size > 0, 'package.json -> JavaScript dependency graph', 1)
294
+ ])
295
+ },
296
+ {
297
+ id: 'python',
298
+ detect: ctx => buildDetection('python', [
299
+ evidenceIf(ctx.fileExists('requirements.txt'), 'found requirements.txt', 3),
300
+ evidenceIf(ctx.fileExists('pyproject.toml'), 'found pyproject.toml', 2),
301
+ evidenceIf(textMatches(ctx.pyprojectText, /\[tool\.(poetry|uv|hatch|pdm)\]/i), 'pyproject.toml -> Python tool section', 2)
302
+ ])
303
+ },
304
+ {
305
+ id: 'go',
306
+ detect: ctx => buildDetection('go', [
307
+ evidenceIf(ctx.fileExists('go.mod'), 'found go.mod', 4)
308
+ ])
309
+ },
310
+ {
311
+ id: 'php',
312
+ detect: ctx => buildDetection('php', [
313
+ evidenceIf(ctx.fileExists('composer.json'), 'found composer.json', 4),
314
+ evidenceIf(ctx.composerDepNames.size > 0, 'composer.json -> PHP dependency graph', 1)
315
+ ])
316
+ },
317
+ {
318
+ id: 'rust',
319
+ detect: ctx => buildDetection('rust', [
320
+ evidenceIf(ctx.fileExists('Cargo.toml'), 'found Cargo.toml', 4),
321
+ evidenceIf(ctx.fileExists('src-tauri', 'Cargo.toml'), 'found src-tauri/Cargo.toml', 5)
322
+ ])
323
+ },
324
+ {
325
+ id: 'java',
326
+ detect: ctx => buildDetection('java', [
327
+ evidenceIf(ctx.fileExists('pom.xml'), 'found pom.xml', 4),
328
+ evidenceIf(ctx.fileExists('build.gradle') || ctx.fileExists('build.gradle.kts'), 'found Gradle build file', 3)
329
+ ])
330
+ },
331
+ {
332
+ id: 'ruby',
333
+ detect: ctx => buildDetection('ruby', [
334
+ evidenceIf(ctx.fileExists('Gemfile'), 'found Gemfile', 4),
335
+ evidenceIf(ctx.fileExists('config.ru'), 'found config.ru', 1)
336
+ ])
337
+ },
338
+ {
339
+ id: 'csharp',
340
+ detect: ctx => buildDetection('csharp', [
341
+ evidenceIf(ctx.rootEntries.some(name => name.endsWith('.sln') || name.endsWith('.csproj')), 'found .sln/.csproj', 4),
342
+ evidenceIf(ctx.fileExists('Program.cs'), 'found Program.cs', 1)
343
+ ])
344
+ }
345
+ ];
346
+
347
+ const FRAMEWORK_DETECTORS = [
348
+ {
349
+ id: 'next',
350
+ kind: 'frontend',
351
+ projectType: 'web-app',
352
+ detect: ctx => buildDetection('next', [
353
+ evidenceIf(hasDependency(ctx.depNames, 'next'), 'package.json -> next', 4),
354
+ evidenceIf(ctx.fileExists('next.config.js') || ctx.fileExists('next.config.mjs') || ctx.fileExists('next.config.ts'), 'found next.config.*', 3),
355
+ evidenceIf(ctx.fileExists('app') || ctx.fileExists('pages'), 'found app/ or pages/', 1)
356
+ ])
357
+ },
358
+ {
359
+ id: 'react',
360
+ kind: 'frontend',
361
+ projectType: 'web-app',
362
+ detect: ctx => buildDetection('react', [
363
+ evidenceIf(hasDependency(ctx.depNames, 'react'), 'package.json -> react', 4),
364
+ evidenceIf(hasDependency(ctx.depNames, 'react-dom'), 'package.json -> react-dom', 2)
365
+ ])
366
+ },
367
+ {
368
+ id: 'vue',
369
+ kind: 'frontend',
370
+ projectType: 'web-app',
371
+ detect: ctx => buildDetection('vue', [
372
+ evidenceIf(hasDependency(ctx.depNames, 'vue'), 'package.json -> vue', 4)
373
+ ])
374
+ },
375
+ {
376
+ id: 'nuxt',
377
+ kind: 'frontend',
378
+ projectType: 'web-app',
379
+ detect: ctx => buildDetection('nuxt', [
380
+ evidenceIf(hasDependency(ctx.depNames, 'nuxt'), 'package.json -> nuxt', 4),
381
+ evidenceIf(ctx.fileExists('nuxt.config.ts') || ctx.fileExists('nuxt.config.js'), 'found nuxt.config.*', 3)
382
+ ])
383
+ },
384
+ {
385
+ id: 'svelte',
386
+ kind: 'frontend',
387
+ projectType: 'web-app',
388
+ detect: ctx => buildDetection('svelte', [
389
+ evidenceIf(hasDependency(ctx.depNames, 'svelte', '@sveltejs/kit'), 'package.json -> svelte', 4)
390
+ ])
391
+ },
392
+ {
393
+ id: 'angular',
394
+ kind: 'frontend',
395
+ projectType: 'web-app',
396
+ detect: ctx => buildDetection('angular', [
397
+ evidenceIf(hasDependency(ctx.depNames, '@angular/core'), 'package.json -> @angular/core', 4),
398
+ evidenceIf(ctx.fileExists('angular.json'), 'found angular.json', 3)
399
+ ])
400
+ },
401
+ {
402
+ id: 'express',
403
+ kind: 'backend',
404
+ language: 'javascript',
405
+ projectType: 'api',
406
+ detect: ctx => buildDetection('express', [
407
+ evidenceIf(hasDependency(ctx.depNames, 'express'), 'package.json -> express', 4)
408
+ ])
409
+ },
410
+ {
411
+ id: 'nestjs',
412
+ kind: 'backend',
413
+ language: 'javascript',
414
+ projectType: 'api',
415
+ detect: ctx => buildDetection('nestjs', [
416
+ evidenceIf(hasDependency(ctx.depNames, '@nestjs/core'), 'package.json -> @nestjs/core', 4)
417
+ ])
418
+ },
419
+ {
420
+ id: 'fastapi',
421
+ kind: 'backend',
422
+ language: 'python',
423
+ projectType: 'api',
424
+ detect: ctx => buildDetection('fastapi', [
425
+ evidenceIf(textMatches(ctx.requirementsText, /\bfastapi\b/i) || textMatches(ctx.pyprojectText, /\bfastapi\b/i), 'Python deps -> fastapi', 4)
426
+ ])
427
+ },
428
+ {
429
+ id: 'django',
430
+ kind: 'backend',
431
+ language: 'python',
432
+ projectType: 'web-app',
433
+ detect: ctx => buildDetection('django', [
434
+ evidenceIf(textMatches(ctx.requirementsText, /\bdjango\b/i) || textMatches(ctx.pyprojectText, /\bdjango\b/i), 'Python deps -> django', 4),
435
+ evidenceIf(ctx.fileExists('manage.py'), 'found manage.py', 2),
436
+ evidenceIf(ctx.fileExists('templates'), 'found templates/', 1)
437
+ ])
438
+ },
439
+ {
440
+ id: 'flask',
441
+ kind: 'backend',
442
+ language: 'python',
443
+ projectType: 'api',
444
+ detect: ctx => buildDetection('flask', [
445
+ evidenceIf(textMatches(ctx.requirementsText, /\bflask\b/i) || textMatches(ctx.pyprojectText, /\bflask\b/i), 'Python deps -> flask', 4)
446
+ ])
447
+ },
448
+ {
449
+ id: 'laravel',
450
+ kind: 'backend',
451
+ language: 'php',
452
+ projectType: 'web-app',
453
+ detect: ctx => buildDetection('laravel', [
454
+ evidenceIf(hasComposerDependency(ctx.composerDepNames, 'laravel/framework'), 'composer.json -> laravel/framework', 4),
455
+ evidenceIf(ctx.fileExists('artisan'), 'found artisan', 3),
456
+ evidenceIf(ctx.fileExists('resources', 'views'), 'found resources/views', 1)
457
+ ])
458
+ },
459
+ {
460
+ id: 'cakephp',
461
+ kind: 'backend',
462
+ language: 'php',
463
+ projectType: 'web-app',
464
+ detect: ctx => buildDetection('cakephp', [
465
+ evidenceIf(hasComposerDependency(ctx.composerDepNames, 'cakephp/cakephp'), 'composer.json -> cakephp/cakephp', 4),
466
+ evidenceIf(ctx.fileExists('bin', 'cake'), 'found bin/cake', 3),
467
+ evidenceIf(ctx.fileExists('config', 'app.php'), 'found config/app.php', 2),
468
+ evidenceIf(ctx.fileExists('app', 'Config', 'core.php'), 'found app/Config/core.php (CakePHP legacy)', 3),
469
+ evidenceIf(ctx.fileExists('app', 'Controller', 'AppController.php'), 'found app/Controller/AppController.php', 2),
470
+ evidenceIf(ctx.fileExists('app', 'Model', 'AppModel.php'), 'found app/Model/AppModel.php', 2),
471
+ evidenceIf(ctx.fileExists('lib', 'Cake'), 'found lib/Cake', 3),
472
+ evidenceIf(ctx.fileExists('cake', 'console', 'cake'), 'found cake/console/cake', 3),
473
+ evidenceIf(ctx.fileExists('app', 'View'), 'found app/View', 2),
474
+ evidenceIf(textMatches(ctx.viewFilesText, /\.ctp$/im), 'found .ctp view templates', 2)
475
+ ])
476
+ },
477
+ {
478
+ id: 'symfony',
479
+ kind: 'backend',
480
+ language: 'php',
481
+ projectType: 'web-app',
482
+ detect: ctx => buildDetection('symfony', [
483
+ evidenceIf(hasComposerDependency(ctx.composerDepNames, 'symfony/framework-bundle'), 'composer.json -> symfony/framework-bundle', 4),
484
+ evidenceIf(ctx.fileExists('bin', 'console'), 'found bin/console', 2),
485
+ evidenceIf(ctx.fileExists('config', 'bundles.php'), 'found config/bundles.php', 1),
486
+ evidenceIf(ctx.fileExists('templates'), 'found templates/', 1)
487
+ ])
488
+ },
489
+ {
490
+ id: 'codeigniter',
491
+ kind: 'backend',
492
+ language: 'php',
493
+ projectType: 'api',
494
+ detect: ctx => buildDetection('codeigniter', [
495
+ evidenceIf(hasComposerDependency(ctx.composerDepNames, 'codeigniter4/framework'), 'composer.json -> codeigniter4/framework', 4),
496
+ evidenceIf(ctx.fileExists('spark'), 'found spark', 2),
497
+ evidenceIf(ctx.fileExists('app', 'Config', 'App.php'), 'found app/Config/App.php', 1)
498
+ ])
499
+ },
500
+ {
501
+ id: 'gin',
502
+ kind: 'backend',
503
+ language: 'go',
504
+ projectType: 'api',
505
+ detect: ctx => buildDetection('gin', [
506
+ evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/gin-gonic\/gin\b/i), 'go.mod -> github.com/gin-gonic/gin', 4)
507
+ ])
508
+ },
509
+ {
510
+ id: 'fiber',
511
+ kind: 'backend',
512
+ language: 'go',
513
+ projectType: 'api',
514
+ detect: ctx => buildDetection('fiber', [
515
+ evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/gofiber\/fiber\b/i), 'go.mod -> github.com/gofiber/fiber', 4)
516
+ ])
517
+ },
518
+ {
519
+ id: 'echo',
520
+ kind: 'backend',
521
+ language: 'go',
522
+ projectType: 'api',
523
+ detect: ctx => buildDetection('echo', [
524
+ evidenceIf(textMatches(ctx.goModText, /\bgithub\.com\/labstack\/echo\b/i), 'go.mod -> github.com/labstack/echo', 4)
525
+ ])
526
+ },
527
+ {
528
+ id: 'rails',
529
+ kind: 'backend',
530
+ language: 'ruby',
531
+ projectType: 'web-app',
532
+ detect: ctx => buildDetection('rails', [
533
+ evidenceIf(textMatches(ctx.gemfileText, /^\s*gem\s+["']rails["']/im), 'Gemfile -> rails', 4),
534
+ evidenceIf(ctx.fileExists('bin', 'rails'), 'found bin/rails', 2),
535
+ evidenceIf(ctx.fileExists('app', 'views'), 'found app/views', 1)
536
+ ])
537
+ },
538
+ {
539
+ id: 'spring',
540
+ kind: 'backend',
541
+ language: 'java',
542
+ projectType: 'api',
543
+ detect: ctx => buildDetection('spring', [
544
+ evidenceIf(textMatches(ctx.pomText, /spring-boot/i) || textMatches(ctx.gradleText, /spring-boot/i), 'Java build -> spring-boot', 4)
545
+ ])
546
+ },
547
+ {
548
+ id: 'aspnet',
549
+ kind: 'backend',
550
+ language: 'csharp',
551
+ projectType: 'api',
552
+ detect: ctx => buildDetection('aspnet', [
553
+ evidenceIf(textMatches(ctx.csprojText, /Microsoft\.NET\.Sdk\.Web/i), '.csproj -> Microsoft.NET.Sdk.Web', 4),
554
+ evidenceIf(textMatches(ctx.programCsText, /WebApplication\.CreateBuilder/i), 'Program.cs -> WebApplication.CreateBuilder', 2)
555
+ ])
556
+ },
557
+ {
558
+ id: 'tauri',
559
+ kind: 'desktop',
560
+ language: 'rust',
561
+ projectType: 'desktop',
562
+ detect: ctx => buildDetection('tauri', [
563
+ evidenceIf(hasDependency(ctx.depNames, '@tauri-apps/api'), 'package.json -> @tauri-apps/api', 4),
564
+ evidenceIf(ctx.fileExists('src-tauri', 'tauri.conf.json') || ctx.fileExists('src-tauri', 'tauri.conf.json5'), 'found src-tauri/tauri.conf.*', 4),
565
+ evidenceIf(ctx.fileExists('src-tauri', 'Cargo.toml'), 'found src-tauri/Cargo.toml', 2)
566
+ ])
567
+ },
568
+ {
569
+ id: 'axum',
570
+ kind: 'backend',
571
+ language: 'rust',
572
+ projectType: 'api',
573
+ detect: ctx => buildDetection('axum', [
574
+ evidenceIf(textMatches(ctx.cargoText, /\baxum\b/i), 'Cargo.toml -> axum', 4)
575
+ ])
576
+ },
577
+ {
578
+ id: 'actix',
579
+ kind: 'backend',
580
+ language: 'rust',
581
+ projectType: 'api',
582
+ detect: ctx => buildDetection('actix', [
583
+ evidenceIf(textMatches(ctx.cargoText, /\bactix-web\b/i), 'Cargo.toml -> actix-web', 4)
584
+ ])
585
+ },
586
+ {
587
+ id: 'flutter',
588
+ kind: 'mobile',
589
+ projectType: 'mobile',
590
+ detect: ctx => buildDetection('flutter', [
591
+ evidenceIf(textMatches(ctx.pubspecText, /^\s*flutter\s*:/im), 'pubspec.yaml -> flutter', 4)
592
+ ])
593
+ },
594
+ {
595
+ id: 'react-native',
596
+ kind: 'mobile',
597
+ projectType: 'mobile',
598
+ detect: ctx => buildDetection('react-native', [
599
+ evidenceIf(hasDependency(ctx.depNames, 'react-native', 'expo'), 'package.json -> react-native/expo', 4)
600
+ ])
601
+ }
602
+ ];
603
+
604
+ function scanProject() {
605
+ const appRoot = detectAppRoot(targetDir);
606
+ const pkg = readJsonIfExistsAt(appRoot, 'package.json') || {};
607
+ const composer = readJsonIfExistsAt(appRoot, 'composer.json') || {};
608
+ const rootEntries = fs.existsSync(appRoot) ? fs.readdirSync(appRoot) : [];
609
+ const rootCsproj = rootEntries.find(name => name.endsWith('.csproj')) || '';
610
+ const deps = {
611
+ ...(pkg.dependencies || {}),
612
+ ...(pkg.devDependencies || {}),
613
+ ...(pkg.peerDependencies || {})
614
+ };
615
+ const depNames = new Set(Object.keys(deps));
616
+ const composerDeps = {
617
+ ...(composer.require || {}),
618
+ ...(composer['require-dev'] || {})
619
+ };
620
+ const composerDepNames = new Set(Object.keys(composerDeps));
621
+ const ctx = {
622
+ pkg,
623
+ composer,
624
+ depNames,
625
+ composerDepNames,
626
+ rootEntries,
627
+ fileExists: (...parts) => fileExistsAt(appRoot, ...parts),
628
+ requirementsText: readTextIfExistsAt(appRoot, 'requirements.txt'),
629
+ pyprojectText: readTextIfExistsAt(appRoot, 'pyproject.toml'),
630
+ goModText: readTextIfExistsAt(appRoot, 'go.mod'),
631
+ pubspecText: readTextIfExistsAt(appRoot, 'pubspec.yaml'),
632
+ gemfileText: readTextIfExistsAt(appRoot, 'Gemfile'),
633
+ pomText: readTextIfExistsAt(appRoot, 'pom.xml'),
634
+ gradleText: `${readTextIfExistsAt(appRoot, 'build.gradle')}\n${readTextIfExistsAt(appRoot, 'build.gradle.kts')}`,
635
+ cargoText: `${readTextIfExistsAt(appRoot, 'Cargo.toml')}\n${readTextIfExistsAt(appRoot, 'src-tauri', 'Cargo.toml')}`,
636
+ csprojText: rootCsproj ? readTextIfExistsAt(appRoot, rootCsproj) : '',
637
+ programCsText: readTextIfExistsAt(appRoot, 'Program.cs'),
638
+ viewFilesText: fs.existsSync(path.join(appRoot, 'app', 'View'))
639
+ ? fs.readdirSync(path.join(appRoot, 'app', 'View'), { recursive: true }).join('\n')
640
+ : ''
641
+ };
642
+
643
+ const languageDetections = LANGUAGE_DETECTORS
644
+ .map(detector => detector.detect(ctx))
645
+ .filter(result => result.score >= 2)
646
+ .sort((a, b) => b.score - a.score);
647
+
648
+ const frameworkDetails = FRAMEWORK_DETECTORS
649
+ .map(detector => {
650
+ const result = detector.detect(ctx);
651
+ if (result.score < 3) return null;
652
+ return {
653
+ ...result,
654
+ kind: detector.kind,
655
+ language: detector.language,
656
+ projectType: detector.projectType,
657
+ confidence: confidenceLabel(result.score)
658
+ };
659
+ })
660
+ .filter(Boolean)
661
+ .sort((a, b) => b.score - a.score);
662
+
663
+ const frameworkLanguageScores = frameworkDetails.reduce((acc, item) => {
664
+ if (!item.language) return acc;
665
+ acc[item.language] = (acc[item.language] || 0) + item.score;
666
+ return acc;
667
+ }, {});
668
+ const primaryLanguage = Object.keys(frameworkLanguageScores).sort((a, b) => frameworkLanguageScores[b] - frameworkLanguageScores[a])[0]
669
+ || languageDetections[0]?.id
670
+ || 'typescript';
671
+ const frameworks = uniq(frameworkDetails.map(item => item.id)).filter(name => FRAMEWORK_CHOICES.includes(name));
672
+ const infrastructure = [];
673
+ let projectType = '';
674
+ let database = 'none';
675
+ let testFramework = 'auto-detect';
676
+ let cloud = 'none';
677
+ let ciCd = 'none';
678
+
679
+ if (frameworkDetails.some(item => item.projectType === 'desktop')) projectType = 'desktop';
680
+ else if (frameworkDetails.some(item => item.projectType === 'mobile')) projectType = 'mobile';
681
+ else if (frameworkDetails.some(item => item.kind === 'frontend') && frameworkDetails.some(item => item.kind === 'backend')) projectType = 'fullstack';
682
+ else if (frameworkDetails.some(item => item.projectType === 'web-app')) projectType = 'web-app';
683
+ else if (frameworkDetails.some(item => item.kind === 'backend')) projectType = 'api';
684
+ else if (frameworkDetails.some(item => item.kind === 'frontend')) projectType = 'web-app';
685
+ else if (fileExistsAt(appRoot, 'package.json') && pkg.bin) projectType = 'cli';
686
+ else if (['php', 'python', 'go', 'java', 'ruby', 'csharp', 'rust'].includes(primaryLanguage)) projectType = 'api';
687
+
688
+ if (hasDependency(depNames, 'pg', 'postgres', '@prisma/client') || /postgres/i.test(JSON.stringify(pkg))) database = 'postgres';
689
+ else if (hasDependency(depNames, 'mysql', 'mysql2')) database = 'mysql';
690
+ else if (hasDependency(depNames, 'sqlite3', 'better-sqlite3', 'rusqlite')) database = 'sqlite';
691
+ else if (hasDependency(depNames, 'mongodb', 'mongoose')) database = 'mongodb';
692
+ else if (hasDependency(depNames, 'redis', 'ioredis')) database = 'redis';
693
+ else if (hasDependency(depNames, '@aws-sdk/client-dynamodb')) database = 'dynamodb';
694
+
695
+ if (hasDependency(depNames, 'vitest')) testFramework = 'vitest';
696
+ else if (hasDependency(depNames, 'jest')) testFramework = 'jest';
697
+ else if (hasDependency(depNames, 'pytest') || textMatches(ctx.requirementsText, /\bpytest\b/i) || textMatches(ctx.pyprojectText, /\bpytest\b/i)) testFramework = 'pytest';
698
+ else if (hasComposerDependency(composerDepNames, 'phpunit/phpunit')) testFramework = 'phpunit';
699
+ else if (hasComposerDependency(composerDepNames, 'pestphp/pest')) testFramework = 'pest';
700
+ else if (fileExistsAt(appRoot, 'go.mod')) testFramework = 'go test';
701
+ else if (textMatches(ctx.gemfileText, /^\s*gem\s+["']rspec["']/im)) testFramework = 'rspec';
702
+
703
+ if (repoHasAny(targetDir, [['Dockerfile'], ['docker-compose.yml'], ['docker-compose.yaml']])) {
704
+ infrastructure.push('docker');
705
+ }
706
+
707
+ if (repoHasAny(targetDir, [['vercel.json']])) {
708
+ cloud = 'vercel';
709
+ infrastructure.push('vercel');
710
+ } else if (repoHasAny(targetDir, [['fly.toml']])) {
711
+ cloud = 'fly';
712
+ infrastructure.push('fly');
713
+ } else if (repoHasAny(targetDir, [['railway.json'], ['railway.toml']])) {
714
+ cloud = 'railway';
715
+ infrastructure.push('railway');
716
+ }
717
+
718
+ if (repoHasAny(targetDir, [['.github', 'workflows'], ['.gitlab-ci.yml'], ['.circleci', 'config.yml'], ['Jenkinsfile']], 2)) {
719
+ if (repoHasAny(targetDir, [['.github', 'workflows']], 2)) ciCd = 'github-actions';
720
+ else if (repoHasAny(targetDir, [['.gitlab-ci.yml']], 2)) ciCd = 'gitlab-ci';
721
+ else if (repoHasAny(targetDir, [['.circleci', 'config.yml']], 2)) ciCd = 'circleci';
722
+ else if (repoHasAny(targetDir, [['Jenkinsfile']], 2)) ciCd = 'jenkins';
723
+ }
724
+
725
+ const scanEvidence = [
726
+ ...(languageDetections[0] ? [`language:${languageDetections[0].id} => ${languageDetections[0].evidence.join('; ')}`] : []),
727
+ ...frameworkDetails.map(item => `${item.id} [${item.confidence}] => ${item.evidence.join('; ')}`)
728
+ ];
729
+
730
+ return {
731
+ project_name: path.basename(targetDir),
732
+ app_root: path.relative(targetDir, appRoot) || '.',
733
+ description: pkg.description || composer.description || 'A software project',
734
+ project_type: PROJECT_TYPE_CHOICES.includes(projectType) ? projectType : 'web-app',
735
+ primary_language: LANGUAGE_CHOICES.includes(primaryLanguage) ? primaryLanguage : 'typescript',
736
+ frameworks,
737
+ framework_details: frameworkDetails,
738
+ scan_evidence: scanEvidence,
739
+ database: DATABASE_CHOICES.includes(database) ? database : 'none',
740
+ package_manager: PACKAGE_MANAGER_CHOICES.includes(detectPackageManager(appRoot)) ? detectPackageManager(appRoot) : 'auto-detect',
741
+ uses_docker: infrastructure.includes('docker'),
742
+ cloud,
743
+ infrastructure: uniq(infrastructure),
744
+ ci_cd: ciCd,
745
+ test_framework: TEST_FRAMEWORK_CHOICES.includes(testFramework) ? testFramework : 'auto-detect',
746
+ max_file_lines: '300',
747
+ code_style: 'project-standard',
748
+ architecture_notes: '<!-- Add notes -->',
749
+ current_phase: 'Initial setup',
750
+ next_phase: '-',
751
+ known_issues: '<!-- None yet -->'
752
+ };
753
+ }
754
+ // --- File Generators ---
755
+
886
756
  function generateSharedAgentsMd(data) {
887
757
  return `# AGENTS.md
888
758
 
889
759
  Shared operating instructions for Codex, Antigravity, Claude Code, and Cursor.
890
-
891
- ## Startup
892
-
893
- 1. Read this file first.
894
- 2. Read \`.agent/docs/project.md\` for detected stack, commands, and routing.
895
- 3. Read \`.agent/docs/workflow.md\` for the task flow before editing.
896
- 4. Read \`.agent/docs/architecture.md\` and \`.agent/docs/conventions.md\` before planning code changes.
760
+
761
+ ## Startup
762
+
763
+ 1. Read this file first.
764
+ 2. Read \`.agent/docs/project.md\` for detected stack, commands, and routing.
765
+ 3. Read \`.agent/docs/workflow.md\` for the task flow before editing.
766
+ 4. Read \`.agent/docs/architecture.md\` and \`.agent/docs/conventions.md\` before planning code changes.
897
767
  5. Read \`.agent/docs/tooling.md\` when the task needs MCP, RTK, or browser verification.
898
768
 
899
769
  If any \`.agent/docs/*.md\` file still contains \`TODO: refine\`, update the docs by scanning the project before making product code changes.
@@ -911,18 +781,18 @@ Superpowers is the primary workflow backend. Use its native skills when availabl
911
781
  Questions and research do not edit product code. A simple fix may use a fast path only when it is one-file, unambiguous, and changes no behavior or contract. State the scope and verification before editing. If the scope grows, switch to the full Superpowers flow.
912
782
 
913
783
  If Superpowers is unavailable, follow the plain-language flow in \`.agent/docs/workflow.md\`; do not expect this kit to provide a second copy of the workflow engine.
914
-
915
- ## Rules
916
-
917
- - Respond in the user's language; keep code, identifiers, and code comments in English.
918
- - State assumptions when the request is ambiguous.
919
- - Prefer the existing project style over new abstractions.
920
- - Keep changes surgical and remove only dead code introduced by your change.
784
+
785
+ ## Rules
786
+
787
+ - Respond in the user's language; keep code, identifiers, and code comments in English.
788
+ - State assumptions when the request is ambiguous.
789
+ - Prefer the existing project style over new abstractions.
790
+ - Keep changes surgical and remove only dead code introduced by your change.
921
791
  - **MCP First**: Prioritize \`codebase-memory-mcp\` for symbols, call paths, architecture, and impact; use \`context7\` for API/docs queries and \`playwright\` for browser/UI verification. Fall back to normal file search when an integration is unavailable.
922
792
  - Prefer \`rtk\` by default for verbose shell commands such as \`rtk git status\`, \`rtk npm test\`, and \`rtk git log\`. Run the underlying command directly only when RTK is unavailable or incompatible.
923
- - Tests or equivalent verification are mandatory before claiming done.
924
- - Keep files under ${data.max_file_lines || '300'} lines unless the project already has a different standard in \`.agent/docs/conventions.md\`.
925
-
793
+ - Tests or equivalent verification are mandatory before claiming done.
794
+ - Keep files under ${data.max_file_lines || '300'} lines unless the project already has a different standard in \`.agent/docs/conventions.md\`.
795
+
926
796
  ## Shared Knowledge
927
797
 
928
798
  - Project context: \`.agent/docs/\`
@@ -953,188 +823,188 @@ function printProjectPrompt() {
953
823
  }
954
824
  console.log(fs.readFileSync(promptPath, 'utf8'));
955
825
  }
956
-
957
- function generateSharedClaudeMd() {
958
- return `@AGENTS.md
959
-
960
- ## Claude Code
961
-
962
- This repository uses AGENTS.md as the shared cross-agent entry file. Follow the imported instructions and keep Claude-specific notes here only when they cannot apply to Codex or Antigravity.
963
- `;
964
- }
965
-
966
- function generateSharedGeminiMd() {
967
- return `# GEMINI.md
968
-
969
- Antigravity entry file for this project.
970
-
971
- Read AGENTS.md first, then follow the shared docs under .agent/docs/.
972
- `;
973
- }
974
-
975
- function generateSharedCursorrules(data) {
826
+
827
+ function generateSharedClaudeMd() {
828
+ return `@AGENTS.md
829
+
830
+ ## Claude Code
831
+
832
+ This repository uses AGENTS.md as the shared cross-agent entry file. Follow the imported instructions and keep Claude-specific notes here only when they cannot apply to Codex or Antigravity.
833
+ `;
834
+ }
835
+
836
+ function generateSharedGeminiMd() {
837
+ return `# GEMINI.md
838
+
839
+ Antigravity entry file for this project.
840
+
841
+ Read AGENTS.md first, then follow the shared docs under .agent/docs/.
842
+ `;
843
+ }
844
+
845
+ function generateSharedCursorrules(data) {
976
846
  return `# Cursor Rules
977
-
978
- This repository uses AGENTS.md as the shared cross-agent entry file. Follow the instructions in AGENTS.md and keep Cursor-specific notes here only when they cannot apply to Codex, Antigravity, or Claude Code.
979
-
980
- Read AGENTS.md first, then follow the shared docs under .agent/docs/.
981
-
982
- ---
983
-
847
+
848
+ This repository uses AGENTS.md as the shared cross-agent entry file. Follow the instructions in AGENTS.md and keep Cursor-specific notes here only when they cannot apply to Codex, Antigravity, or Claude Code.
849
+
850
+ Read AGENTS.md first, then follow the shared docs under .agent/docs/.
851
+
852
+ ---
853
+
984
854
  ${generateSharedAgentsMd(data).trimEnd()}
985
855
  `;
986
- }
987
-
988
- function resolveCommands(data) {
989
- const frameworks = data.frameworks || [];
990
- const primaryLang = data.primary_language || 'javascript';
991
- const pkgManager = data.package_manager || 'npm';
992
- const testFramework = data.test_framework || 'auto-detect';
993
-
994
- const isPython = primaryLang === 'python';
995
- const isGo = primaryLang === 'go';
996
- const isRust = primaryLang === 'rust';
997
- const isPhp = primaryLang === 'php';
998
-
999
- let install = 'npm install';
1000
- let dev = 'npm run dev';
1001
- let build = 'npm run build';
1002
- let test = 'npm test';
1003
- let lint = 'npm run lint';
1004
-
1005
- if (pkgManager === 'pnpm') { install = 'pnpm install'; dev = 'pnpm dev'; build = 'pnpm build'; test = 'pnpm test'; lint = 'pnpm lint'; }
1006
- else if (pkgManager === 'yarn') { install = 'yarn'; dev = 'yarn dev'; build = 'yarn build'; test = 'yarn test'; lint = 'yarn lint'; }
1007
- else if (pkgManager === 'bun') { install = 'bun install'; dev = 'bun dev'; build = 'bun run build'; test = 'bun test'; lint = 'bun run lint'; }
1008
- else if (isPython) { install = 'pip install -r requirements.txt'; dev = 'python manage.py runserver'; build = '# no build step'; test = 'pytest'; lint = 'ruff check .'; }
1009
- else if (isGo) { install = 'go mod download'; dev = 'go run .'; build = 'go build ./...'; test = 'go test ./...'; lint = 'golangci-lint run'; }
1010
- else if (isRust) { install = 'cargo build'; dev = 'cargo run'; build = 'cargo build --release'; test = 'cargo test'; lint = 'cargo clippy'; }
1011
- else if (isPhp) {
1012
- install = 'composer install';
1013
- build = '# no build step';
1014
- test = testFramework === 'pest' ? './vendor/bin/pest' : './vendor/bin/phpunit';
1015
- const isCakePHP = frameworks.some(f => f.toLowerCase().includes('cakephp'));
1016
- const isSymfony = frameworks.some(f => f.toLowerCase().includes('symfony'));
1017
- const isCodeIgniter = frameworks.some(f => f.toLowerCase().includes('codeigniter'));
1018
- if (isCakePHP) {
1019
- dev = 'bin/cake server';
1020
- lint = './vendor/bin/phpcs';
1021
- } else if (isSymfony) {
1022
- dev = 'bin/console server:run';
1023
- lint = './vendor/bin/phpcs';
1024
- } else if (isCodeIgniter) {
1025
- dev = 'php spark serve';
1026
- lint = './vendor/bin/phpcs';
1027
- } else {
1028
- dev = 'php artisan serve';
1029
- lint = 'php artisan pint';
1030
- }
1031
- }
1032
-
1033
- if (testFramework === 'vitest') test = `${pkgManager === 'pnpm' ? 'pnpm' : pkgManager === 'yarn' ? 'yarn' : pkgManager === 'bun' ? 'bun run' : 'npx'} vitest`;
1034
- else if (testFramework === 'jest') test = `${pkgManager === 'pnpm' ? 'pnpm' : pkgManager === 'yarn' ? 'yarn' : 'npx'} jest`;
1035
-
1036
- return { install, dev, build, test, lint };
1037
- }
1038
-
1039
- function generateProjectDoc(data) {
1040
- const commands = resolveCommands(data);
1041
- const evidence = (data.scan_evidence || []).length > 0
1042
- ? (data.scan_evidence || []).map(line => `- ${line}`).join('\n')
1043
- : '- TODO: refine scan evidence by inspecting the project.';
1044
-
1045
- return `# Project Rules
1046
-
1047
- Generated by thachvd-kit on ${new Date().toISOString().split('T')[0]}.
1048
-
1049
- ## Summary
1050
-
1051
- - Name: ${data.project_name}
1052
- - Description: ${data.description}
1053
- - Type: ${data.project_type}
1054
- - App root: ${data.app_root || '.'}
1055
-
1056
- ## Stack
1057
-
1058
- - Language: ${data.primary_language}
1059
- - Frameworks: ${(data.frameworks || []).join(', ') || 'none'}
1060
- - Database: ${data.database || 'none'}
1061
- - Infrastructure: ${(data.infrastructure || []).join(', ') || 'none'}
1062
- - Package manager: ${data.package_manager || 'auto-detect'}
1063
- - Test framework: ${data.test_framework || 'auto-detect'}
1064
-
1065
- ## Commands
1066
-
1067
- - Install: \`${commands.install}\`
1068
- - Dev: \`${commands.dev}\`
1069
- - Build: \`${commands.build}\`
1070
- - Test: \`${commands.test}\`
1071
- - Lint: \`${commands.lint}\`
1072
-
856
+ }
857
+
858
+ function resolveCommands(data) {
859
+ const frameworks = data.frameworks || [];
860
+ const primaryLang = data.primary_language || 'javascript';
861
+ const pkgManager = data.package_manager || 'npm';
862
+ const testFramework = data.test_framework || 'auto-detect';
863
+
864
+ const isPython = primaryLang === 'python';
865
+ const isGo = primaryLang === 'go';
866
+ const isRust = primaryLang === 'rust';
867
+ const isPhp = primaryLang === 'php';
868
+
869
+ let install = 'npm install';
870
+ let dev = 'npm run dev';
871
+ let build = 'npm run build';
872
+ let test = 'npm test';
873
+ let lint = 'npm run lint';
874
+
875
+ if (pkgManager === 'pnpm') { install = 'pnpm install'; dev = 'pnpm dev'; build = 'pnpm build'; test = 'pnpm test'; lint = 'pnpm lint'; }
876
+ else if (pkgManager === 'yarn') { install = 'yarn'; dev = 'yarn dev'; build = 'yarn build'; test = 'yarn test'; lint = 'yarn lint'; }
877
+ else if (pkgManager === 'bun') { install = 'bun install'; dev = 'bun dev'; build = 'bun run build'; test = 'bun test'; lint = 'bun run lint'; }
878
+ else if (isPython) { install = 'pip install -r requirements.txt'; dev = 'python manage.py runserver'; build = '# no build step'; test = 'pytest'; lint = 'ruff check .'; }
879
+ else if (isGo) { install = 'go mod download'; dev = 'go run .'; build = 'go build ./...'; test = 'go test ./...'; lint = 'golangci-lint run'; }
880
+ else if (isRust) { install = 'cargo build'; dev = 'cargo run'; build = 'cargo build --release'; test = 'cargo test'; lint = 'cargo clippy'; }
881
+ else if (isPhp) {
882
+ install = 'composer install';
883
+ build = '# no build step';
884
+ test = testFramework === 'pest' ? './vendor/bin/pest' : './vendor/bin/phpunit';
885
+ const isCakePHP = frameworks.some(f => f.toLowerCase().includes('cakephp'));
886
+ const isSymfony = frameworks.some(f => f.toLowerCase().includes('symfony'));
887
+ const isCodeIgniter = frameworks.some(f => f.toLowerCase().includes('codeigniter'));
888
+ if (isCakePHP) {
889
+ dev = 'bin/cake server';
890
+ lint = './vendor/bin/phpcs';
891
+ } else if (isSymfony) {
892
+ dev = 'bin/console server:run';
893
+ lint = './vendor/bin/phpcs';
894
+ } else if (isCodeIgniter) {
895
+ dev = 'php spark serve';
896
+ lint = './vendor/bin/phpcs';
897
+ } else {
898
+ dev = 'php artisan serve';
899
+ lint = 'php artisan pint';
900
+ }
901
+ }
902
+
903
+ if (testFramework === 'vitest') test = `${pkgManager === 'pnpm' ? 'pnpm' : pkgManager === 'yarn' ? 'yarn' : pkgManager === 'bun' ? 'bun run' : 'npx'} vitest`;
904
+ else if (testFramework === 'jest') test = `${pkgManager === 'pnpm' ? 'pnpm' : pkgManager === 'yarn' ? 'yarn' : 'npx'} jest`;
905
+
906
+ return { install, dev, build, test, lint };
907
+ }
908
+
909
+ function generateProjectDoc(data) {
910
+ const commands = resolveCommands(data);
911
+ const evidence = (data.scan_evidence || []).length > 0
912
+ ? (data.scan_evidence || []).map(line => `- ${line}`).join('\n')
913
+ : '- TODO: refine scan evidence by inspecting the project.';
914
+
915
+ return `# Project Rules
916
+
917
+ Generated by thachvd-kit on ${new Date().toISOString().split('T')[0]}.
918
+
919
+ ## Summary
920
+
921
+ - Name: ${data.project_name}
922
+ - Description: ${data.description}
923
+ - Type: ${data.project_type}
924
+ - App root: ${data.app_root || '.'}
925
+
926
+ ## Stack
927
+
928
+ - Language: ${data.primary_language}
929
+ - Frameworks: ${(data.frameworks || []).join(', ') || 'none'}
930
+ - Database: ${data.database || 'none'}
931
+ - Infrastructure: ${(data.infrastructure || []).join(', ') || 'none'}
932
+ - Package manager: ${data.package_manager || 'auto-detect'}
933
+ - Test framework: ${data.test_framework || 'auto-detect'}
934
+
935
+ ## Commands
936
+
937
+ - Install: \`${commands.install}\`
938
+ - Dev: \`${commands.dev}\`
939
+ - Build: \`${commands.build}\`
940
+ - Test: \`${commands.test}\`
941
+ - Lint: \`${commands.lint}\`
942
+
1073
943
  ## Available Integrations
1074
-
944
+
1075
945
  Use these integrations when available. Run thachvd-kit doctor to check the current machine.
1076
-
1077
- | MCP | When to Use |
1078
- |-----|-------------|
946
+
947
+ | MCP | When to Use |
948
+ |-----|-------------|
1079
949
  | \`codebase-memory-mcp\` | Explore symbols, trace call chains, architecture, and impact |
1080
- | \`context7\` | Look up library/framework docs, API signatures, migration guides |
950
+ | \`context7\` | Look up library/framework docs, API signatures, migration guides |
1081
951
  | \`playwright\` | Verify UI behavior, take screenshots, test forms and navigation |
1082
952
  | \`rtk\` | Recommended proxy for noisy git, tests, builds, and package commands |
1083
-
1084
- > Check \`.agent/docs/tooling.md\` for setup details and additional MCP servers.
1085
-
953
+
954
+ > Check \`.agent/docs/tooling.md\` for setup details and additional MCP servers.
955
+
1086
956
  ## Scan Evidence
1087
-
1088
- ${evidence}
1089
- `;
1090
- }
1091
-
1092
- function generateArchitectureDoc(data) {
1093
- const appRootLine = data.app_root && data.app_root !== '.'
1094
- ? `- App root is currently detected as \`${data.app_root}\`.`
1095
- : '- App root is the repository root unless refined below.';
1096
- const evidence = (data.scan_evidence || []).length > 0
1097
- ? (data.scan_evidence || []).map(line => `- ${line}`).join('\n')
1098
- : '- TODO: refine architecture by scanning source directories.';
1099
-
1100
- return `# Architecture Notes
1101
-
1102
- ## Current Map
1103
-
1104
- ${appRootLine}
1105
- - TODO: refine major directories and responsibilities.
1106
- - TODO: refine main entry points, routing, state boundaries, and integration boundaries.
1107
-
1108
- ## Detected Evidence
1109
-
1110
- ${evidence}
1111
-
1112
- ## AI Maintenance Rule
1113
-
1114
- Before non-trivial implementation work, inspect this file. If it is stale or still contains TODO items relevant to the task, update it from the code before editing product code.
1115
- `;
1116
- }
1117
-
1118
- function generateConventionsDoc(data) {
1119
- return `# Coding Conventions
1120
-
1121
- ## Current Standards
1122
-
1123
- - Maximum file length: ${data.max_file_lines || '300'} lines unless the existing project standard is stricter.
1124
- - Code comments and identifiers should be written in English.
1125
- - Keep changes scoped to the user request.
1126
- - Prefer existing local patterns over introducing new abstractions.
1127
- - TODO: refine naming, formatting, folder, API, state, styling, and testing conventions from the real codebase.
1128
-
1129
- ## Verification
1130
-
1131
- - Run the focused test or lint command that matches the touched area.
1132
- - If no automated check exists, document the manual verification performed.
1133
- - For UI/web changes, prioritize using Playwright MCP to automatically verify client-side behavior and capture screenshots.
1134
- - Do not claim completion without verification evidence.
1135
- `;
1136
- }
1137
-
957
+
958
+ ${evidence}
959
+ `;
960
+ }
961
+
962
+ function generateArchitectureDoc(data) {
963
+ const appRootLine = data.app_root && data.app_root !== '.'
964
+ ? `- App root is currently detected as \`${data.app_root}\`.`
965
+ : '- App root is the repository root unless refined below.';
966
+ const evidence = (data.scan_evidence || []).length > 0
967
+ ? (data.scan_evidence || []).map(line => `- ${line}`).join('\n')
968
+ : '- TODO: refine architecture by scanning source directories.';
969
+
970
+ return `# Architecture Notes
971
+
972
+ ## Current Map
973
+
974
+ ${appRootLine}
975
+ - TODO: refine major directories and responsibilities.
976
+ - TODO: refine main entry points, routing, state boundaries, and integration boundaries.
977
+
978
+ ## Detected Evidence
979
+
980
+ ${evidence}
981
+
982
+ ## AI Maintenance Rule
983
+
984
+ Before non-trivial implementation work, inspect this file. If it is stale or still contains TODO items relevant to the task, update it from the code before editing product code.
985
+ `;
986
+ }
987
+
988
+ function generateConventionsDoc(data) {
989
+ return `# Coding Conventions
990
+
991
+ ## Current Standards
992
+
993
+ - Maximum file length: ${data.max_file_lines || '300'} lines unless the existing project standard is stricter.
994
+ - Code comments and identifiers should be written in English.
995
+ - Keep changes scoped to the user request.
996
+ - Prefer existing local patterns over introducing new abstractions.
997
+ - TODO: refine naming, formatting, folder, API, state, styling, and testing conventions from the real codebase.
998
+
999
+ ## Verification
1000
+
1001
+ - Run the focused test or lint command that matches the touched area.
1002
+ - If no automated check exists, document the manual verification performed.
1003
+ - For UI/web changes, prioritize using Playwright MCP to automatically verify client-side behavior and capture screenshots.
1004
+ - Do not claim completion without verification evidence.
1005
+ `;
1006
+ }
1007
+
1138
1008
  function generateWorkflowDoc() {
1139
1009
  return `# Agent Workflow
1140
1010
 
@@ -1174,89 +1044,8 @@ Use it only for one-file, unambiguous changes with no behavior, API, schema, sec
1174
1044
  - Update project.md when stack, scripts, or test tooling changes.
1175
1045
  - Keep AGENTS.md concise and put project-specific detail under .agent/docs/.
1176
1046
  `;
1177
- /* Legacy workflow text below remains unreachable for source compatibility. */
1178
- return `# Agent Workflow
1179
-
1180
- ## Before Every Task
1181
-
1182
- 1. Read AGENTS.md.
1183
- 2. Read .agent/docs/project.md.
1184
- 3. Use the matching native Superpowers skill for the task.
1185
- 4. Read only the relevant docs under .agent/agents, .agent/skills, .claude/skills, and .agent/workflows.
1186
- 5. Use codebase-memory MCP for structural discovery when available, then verify the actual files before editing.
1187
-
1188
- ## Route Matrix
1047
+ }
1189
1048
 
1190
- | Situation | Command | Workflow / gate |
1191
- |---|---|---|
1192
- | Question or analysis only | direct answer | no edits |
1193
- | One obvious local fix | fast path | inspect -> edit -> focused verify |
1194
- | Bug, regression, failing test, or unknown error | systematic-debugging | reproduce -> root cause -> regression test -> fix -> verify |
1195
- | Research request | direct research | evidence report, no edits |
1196
- | New behavior, multi-file change, or unclear scope | brainstorming -> writing-plans -> executing-plans | explicit approval before implementation |
1197
- | Pre-merge review | requesting-code-review | blocking findings resolved |
1198
- | Several specialist domains | subagent-driven-development | task review and final review |
1199
-
1200
- If a task is not clearly simple, use the standard flow. Never use the fast path for behavior, API, schema, security, CI, dependency, workflow, or release changes.
1201
-
1202
- ## Superpowers Skills
1203
-
1204
- - Use brainstorming for unclear requirements.
1205
- - Use using-git-worktrees and writing-plans before non-trivial implementation.
1206
- - Use test-driven-development, executing-plans or subagent-driven-development during implementation.
1207
- - Use systematic-debugging for bugs and requesting-code-review before completion.
1208
- - thachvd-kit does not copy or replace Superpowers skills.
1209
- - Do not load skill bodies by default.
1210
- - Load a skill when the user mentions it, the task clearly matches its SKILL.md description, or .agent/docs/project.md routes the task to it.
1211
- - Use explicit skill names in prompts for predictable behavior, for example $webapp-testing or $clean-code.
1212
- - Run thachvd-kit --help to see common workflow and skill recommendations.
1213
-
1214
- ## Implementation Flow
1215
-
1216
- For \`/forge-fast\` fixes, state the fast-path decision before editing:
1217
-
1218
- \`\`\`text
1219
- FAST_PATH: simple-fix
1220
- REASON: [why Spec/Plan/Review are not needed]
1221
- SCOPE: [file or narrow area]
1222
- \`\`\`
1223
-
1224
- Then:
1225
-
1226
- 1. State assumptions and success criteria when the task is not trivial.
1227
- 2. Inspect dependent files before editing.
1228
- 3. Make the smallest coherent change.
1229
- 4. Add or update focused tests when behavior changes.
1230
- 5. Run verification (prioritize using Playwright MCP for web/UI changes to automate verification and capture screenshots).
1231
- 6. Summarize changed files and verification evidence.
1232
-
1233
- For bugs, use \`/forge-debug\` with Superpowers' \`systematic-debugging\` when available, otherwise the matching local skill, plus the \`debugger\` agent and \`testing-patterns\`: reproduce, isolate the root cause, add regression protection, make the smallest fix, and verify.
1234
-
1235
- For features or refactors, prefer the Superpowers chain when available: brainstorm/spec -> worktree -> detailed plan -> approval -> TDD/task execution -> per-task review -> final review -> finish branch. Otherwise use the local gated flow defined in AGENTS.md (spec -> plan -> implement -> review). Steps 3-5 above are the "Implement" phase, and step 6 is not a substitute for the mandatory review gate.
1236
-
1237
- ## Definition of Done (feature or refactor)
1238
-
1239
- A feature/refactor task is only complete when all of the following hold — not when code compiles or tests pass:
1240
-
1241
- The Spec checkbox may be skipped only when the documented \`/forge-fast\` protocol is stated and its criteria are met.
1242
-
1243
- - [ ] \`.agent/workflows/spec.md\` exit criteria met (or explicitly skipped as a trivial/self-contained change)
1244
- - [ ] \`.agent/workflows/plan.md\` produced a plan file, approved by the user
1245
- - [ ] Tests added/updated for the changed behavior and passing
1246
- - [ ] \`.agent/workflows/review.md\` five-axis review completed with all 🔴 BLOCKING items resolved or accepted with rationale
1247
- - [ ] Changed files and verification evidence summarized to the user
1248
-
1249
- Do not report a feature/refactor task as done if any box above is unchecked — say explicitly which gate is still open.
1250
-
1251
- ## When To Update Docs
1252
-
1253
- - Update .agent/docs/architecture.md when structure, boundaries, or entry points change.
1254
- - Update .agent/docs/conventions.md when repeated project patterns become clear.
1255
- - Update .agent/docs/project.md when stack, scripts, app root, test tooling, or routing changes.
1256
- - Keep AGENTS.md concise. Put project-specific detail in .agent/docs.
1257
- `;
1258
- }
1259
-
1260
1049
  function generateGettingStartedDoc() {
1261
1050
  return `# Getting Started
1262
1051
 
@@ -1288,124 +1077,26 @@ Use \`systematic-debugging\`: reproduce the symptom, inspect the path with codeb
1288
1077
 
1289
1078
  Use a fast path only for one-file, unambiguous changes with no behavior or contract change. State the scope and verification before editing. If the scope expands, return to brainstorming and writing-plans.
1290
1079
  `;
1291
- /* Legacy text below remains unreachable for source compatibility and is removed in a later major cleanup. */
1292
- return `# Getting Started With This Kit
1293
-
1294
- Read this after \`thachvd-kit init\`. The kit gives every member one entry point, then selects only the process and expertise the task needs.
1295
-
1296
- ## Forge Command Map
1297
-
1298
- | Client | Task | Fast | Debug | Research | Review |
1299
- |---|---|---|---|---|---|
1300
- | Codex | \`$forge-task\` | \`$forge-fast\` | \`$forge-debug\` | \`$forge-research\` | \`$forge-review\` |
1301
- | Antigravity | \`/forge-task\` | \`/forge-fast\` | \`/forge-debug\` | \`/forge-research\` | \`/forge-review\` |
1302
- | Claude Code | \`/forge-task\` | \`/forge-fast\` | \`/forge-debug\` | \`/forge-research\` | \`/forge-review\` |
1303
- | Cursor | \`/forge-task\` | \`/forge-fast\` | \`/forge-debug\` | \`/forge-research\` | \`/forge-review\` |
1304
-
1305
- Forge commands accept free-form text after the command and continue the selected workflow in the same turn. Plain questions remain normal chat; edit requests without a command are implicitly routed as \`forge-task\`.
1306
-
1307
- Forge is a routing layer. For feature/refactor work, prefer native Superpowers skills when available: brainstorming, using-git-worktrees, writing-plans, subagent-driven-development or executing-plans, test-driven-development, requesting-code-review, and finishing-a-development-branch. If Superpowers is not installed, use the matching \`.agent/skills/\` and \`.agent/workflows/\` fallback; do not maintain a competing duplicate methodology. Install the full execution backend from https://github.com/obra/superpowers#quickstart.
1308
-
1309
- Codex Forge skills live in \`~/.codex/skills/forge-*/SKILL.md\`. Antigravity Forge workflows live in \`.agent/workflows/forge-*.md\`. Claude Code Forge commands live in \`.claude/commands/forge-*.md\`. Cursor Forge commands live in \`.cursor/commands/forge-*.md\`.
1310
-
1311
- ## Start Every Task With Forge
1312
-
1313
- Use the matching Forge command before editing whenever the request is not a simple question. \`forge-task\` must route internally and continue; it must not stop by asking the member to type a second command.
1314
-
1315
- \`\`\`text
1316
- ROUTE: question | fast | feature | bug | research | review | multi-domain
1317
- WORKFLOW: [exact .agent/workflows/<name>.md file]
1318
- SKILLS: [matching skills, or none]
1319
- AGENTS: [matching specialist agents, or none]
1320
- GATE: fast-path | standard | human-approval
1321
- BACKEND: superpowers-native | forge-fallback
1322
- ACTION: [what the agent is doing next in this turn]
1323
- \`\`\`
1324
-
1325
- A workflow is the process and its gates. A skill is the method or checklist. An agent is the specialist role. Chat alone is not a route: the member must select the route and invoke the matching workflow or explicitly choose the question path.
1326
-
1327
- ## Route Matrix
1328
-
1329
- | Situation | Command | Gate | Required next step |
1330
- |---|---|---|---|
1331
- | Explain, inspect, or brainstorm only | direct answer or \`/brainstorm\` | none | no code until the request becomes actionable |
1332
- | One obvious local fix | \`/forge-fast <request>\` | fast-path | inspect -> edit -> focused verify |
1333
- | New behavior, multi-file change, unclear scope, or >~30 min | \`/forge-task <request>\` | standard | route -> research/spec/plan -> approval when required -> continue |
1334
- | Bug, regression, failing test, or unknown error | \`/forge-debug <symptom>\` | bug | reproduce -> isolate -> regression test -> fix -> verify |
1335
- | Research request | \`/forge-research <question>\` | research | evidence report, no edits |
1336
- | Pre-merge or independent review | \`/forge-review\` | review | five-axis review; resolve blocking findings |
1337
- | Frontend + backend + data/security together | \`/orchestrate\` | standard | plan -> approval -> specialist work -> integration verify |
1338
-
1339
- ## Standard Feature Flow
1340
-
1341
- The gated sequence is Spec -> Plan -> Implement -> Review. \`/forge-task\` manages this sequence internally and pauses only at the explicit user approval gate before implementation.
1342
-
1343
- The plan is a gate, not a suggestion. Do not start product-code implementation before explicit approval. Load only the relevant specialist agent and skills, such as \`$frontend-design\`, \`$api-design\`, or \`$webapp-testing\`.
1344
-
1345
- ## Bug Fix Flow
1346
-
1347
- Use \`/forge-debug <symptom>\`, not the feature flow, when something is failing or the root cause is unknown:
1348
-
1349
- 1. Capture the exact symptom, environment, reproduction, and expected result.
1350
- 2. Inspect the relevant code path with codebase-memory MCP when available.
1351
- 3. Form and test a small number of hypotheses; do not patch by guesswork.
1352
- 4. Add or update a regression test that fails before the fix when practical.
1353
- 5. Make the smallest root-cause fix.
1354
- 6. Run focused tests, then broader verification when the blast radius is shared.
1355
- 7. Use \`/review\` when the fix touches multiple files, contracts, security, or release behavior.
1356
-
1357
- Load Superpowers' \`systematic-debugging\` when available, otherwise the matching local skill, plus the \`debugger\` agent and \`testing-patterns\` for this route.
1358
-
1359
- ## Simple Fast Path
1360
-
1361
- Use \`/forge-fast <request>\` only when the change is one obvious file, the result is unambiguous, and it changes no behavior, API, schema, security, CI, dependency, workflow, or release contract. Before editing, state:
1362
-
1363
- \`\`\`text
1364
- FAST_PATH: simple-fix
1365
- REASON: [why Spec/Plan/Review are not needed]
1366
- SCOPE: [file or narrow area]
1367
- \`\`\`
1368
-
1369
- This bypasses only Spec, Plan, and the feature/refactor Review gate. It never bypasses inspection, focused verification, or reporting evidence. If the scope expands, stop and re-route internally through \`forge-task\`.
1370
-
1371
- ## Command And Skill Map
1372
-
1373
- - \`/brainstorm\`: clarify intent and tradeoffs; no code.
1374
- - \`forge-research\`: evidence-based codebase/technical/domain research; no product-code edits.
1375
- - \`/plan\`: create an approved implementation plan; no code before approval.
1376
- - \`/enhance\` or \`/create\`: implement an approved feature with the relevant specialist agent.
1377
- - \`forge-debug\`: systematic root-cause investigation and regression protection.
1378
- - \`/test\`: add or run tests and assess coverage.
1379
- - \`/review\`: five-axis review before completion or merge.
1380
- - \`$clean-code\` and \`$verification-before-completion\`: default implementation hygiene.
1381
- - \`$webapp-testing\`: browser/UI verification; use Playwright when available.
1382
-
1383
- ## Enforcement
1384
-
1385
- Claude Code has a project Stop hook in \`.claude/settings.json\` for standard feature/refactor work. An explicit \`FAST_PATH: simple-fix\` is accepted only when the simple criteria are met; it still requires verification. Codex, Antigravity, and Cursor use the same written rules through \`AGENTS.md\`, \`.cursorrules\`, and \`.agent/rules/GEMINI.md\`.
1080
+ }
1386
1081
 
1387
- Full details live in \`AGENTS.md\`, \`.agent/docs/workflow.md\`, and the matching file under \`.agent/workflows/\`.
1388
- `;
1082
+ function resolveToolingSetup(data) {
1083
+ const primaryLang = data.primary_language || 'javascript';
1084
+ const packageManager = data.package_manager || 'npm';
1085
+ const isPython = primaryLang === 'python';
1086
+ const runner = packageManager === 'pnpm'
1087
+ ? 'pnpm dlx'
1088
+ : packageManager === 'yarn'
1089
+ ? 'yarn dlx'
1090
+ : packageManager === 'bun'
1091
+ ? 'bunx'
1092
+ : 'npx';
1093
+ const playwrightCommand = isPython
1094
+ ? 'pip install playwright && playwright install chromium'
1095
+ : `${runner} playwright install`;
1096
+
1097
+ return { runner, playwrightCommand };
1389
1098
  }
1390
1099
 
1391
- function resolveToolingSetup(data) {
1392
- const primaryLang = data.primary_language || 'javascript';
1393
- const packageManager = data.package_manager || 'npm';
1394
- const isPython = primaryLang === 'python';
1395
- const runner = packageManager === 'pnpm'
1396
- ? 'pnpm dlx'
1397
- : packageManager === 'yarn'
1398
- ? 'yarn dlx'
1399
- : packageManager === 'bun'
1400
- ? 'bunx'
1401
- : 'npx';
1402
- const playwrightCommand = isPython
1403
- ? 'pip install playwright && playwright install chromium'
1404
- : `${runner} playwright install`;
1405
-
1406
- return { runner, playwrightCommand };
1407
- }
1408
-
1409
1100
  function generateToolingDoc(data) {
1410
1101
  const { runner, playwrightCommand } = resolveToolingSetup(data);
1411
1102
 
@@ -1447,365 +1138,33 @@ RTK is the recommended command-output layer, not a workflow engine. Prefer it by
1447
1138
  - Browser install: \`${playwrightCommand}\`
1448
1139
  - Use the project's existing Playwright scripts when available.
1449
1140
  `;
1450
- /* Legacy tooling text below remains unreachable for source compatibility. */
1451
-
1452
- return `# Optional Tooling
1453
-
1454
- This kit keeps tool setup explicit. Do not assume these tools are available until you verify them in the current environment.
1455
-
1456
- ## Playwright
1457
-
1458
- Use Playwright for browser and UI verification when a task touches web behavior.
1459
-
1460
- - Check availability: \`${runner} playwright --version\`
1461
- - Install browsers: \`${playwrightCommand}\`
1462
- - Codex MCP CLI setup: \`codex mcp add playwright -- playwright-mcp\`
1463
- - Auto setup: \`thachvd-kit\`
1464
- - Kit helper: \`python .agent/skills/webapp-testing/scripts/playwright_runner.py <url> --screenshot\`
1465
-
1466
- If the project already has Playwright configured, prefer the project's existing scripts.
1467
-
1468
- Codex \`config.toml\` example:
1469
-
1470
- \`\`\`toml
1471
- [mcp_servers.context7]
1472
- command = "context7-mcp"
1473
- startup_timeout_sec = 20
1474
- tool_timeout_sec = 120
1475
-
1476
- [mcp_servers.filesystem]
1477
- command = "npx"
1478
- args = ["-y", "@modelcontextprotocol/server-filesystem", "<projectPath>"]
1479
- startup_timeout_sec = 20
1480
- tool_timeout_sec = 120
1481
-
1482
- [mcp_servers.playwright]
1483
- command = "playwright-mcp"
1484
- startup_timeout_sec = 20
1485
- tool_timeout_sec = 120
1486
- \`\`\`
1487
-
1488
- ## Codebase Memory MCP
1489
-
1490
- Use codebase-memory-mcp for codebase exploration. The index is local state and should not be committed unless the team explicitly chooses a shared snapshot.
1491
-
1492
- - Check for an index: use the codebase-memory CLI status/index commands.
1493
- - Check CLI availability: \`codebase-memory-mcp --help\`
1494
- - Install CLI if needed: \`npm install -g codebase-memory-mcp\`
1495
- - Index the repository: \`codebase-memory-mcp cli index_repository --repo-path .\`
1496
- - Auto setup: \`thachvd-kit\`
1497
- - If your Codex environment provides the codebase-memory CLI, run its indexing step from the repository root.
1498
- - Keep local codebase-memory state ignored in git.
1499
-
1500
- Codex \`config.toml\` example:
1501
-
1502
- \`\`\`toml
1503
- [mcp_servers.codebase-memory-mcp]
1504
- command = "codebase-memory-mcp"
1505
- startup_timeout_sec = 20
1506
- tool_timeout_sec = 120
1507
- \`\`\`
1508
-
1509
- Codex reads MCP servers from \`~/.codex/config.toml\` by default. For repo-local setup, use \`.codex/config.toml\`; Codex loads project config only for trusted projects.
1510
-
1511
- Gemini CLI / Antigravity \`mcp_config.json\` example:
1512
-
1513
- \`\`\`json
1514
- {
1515
- "mcpServers": {
1516
- "codebase-memory-mcp": {
1517
- "command": "codebase-memory-mcp"
1518
- },
1519
- "context7": {
1520
- "command": "context7-mcp"
1521
- },
1522
- "filesystem": {
1523
- "command": "npx",
1524
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
1525
- },
1526
- "playwright": {
1527
- "command": "playwright-mcp"
1528
- }
1529
- }
1530
- }
1531
- \`\`\`
1532
-
1533
- Common local paths:
1534
-
1535
- - Gemini CLI: \`~/.gemini/config/mcp_config.json\`
1536
- - Antigravity IDE: \`~/.gemini/antigravity-ide/mcp_config.json\`
1537
- - Older Antigravity setups may use \`~/.gemini/antigravity/mcp_config.json\`
1538
-
1539
- Claude Code user config example:
1540
-
1541
- \`\`\`json
1542
- {
1543
- "mcpServers": {
1544
- "codebase-memory-mcp": {
1545
- "type": "stdio",
1546
- "command": "codebase-memory-mcp"
1547
- },
1548
- "context7": {
1549
- "type": "stdio",
1550
- "command": "context7-mcp"
1551
- },
1552
- "filesystem": {
1553
- "type": "stdio",
1554
- "command": "npx",
1555
- "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
1556
- },
1557
- "playwright": {
1558
- "type": "stdio",
1559
- "command": "playwright-mcp"
1560
- }
1561
- }
1562
- }
1563
- \`\`\`
1564
-
1565
- Common local path:
1566
-
1567
- - Claude Code: \`~/.claude.json\` or \`~/.claude/settings.json\`
1568
-
1569
- ## Native Skill Folders
1570
-
1571
- The shared kit skills live in \`.agent/skills/\`. Antigravity reads that folder directly. Codex shows skills from \`~/.codex/skills/\` in the \`$\` menu. Claude Code reads project skills from \`.claude/skills/\`.
1572
-
1573
- - Codex global skills: \`~/.codex/skills/\` — installed by \`thachvd-kit init\`, visible in Codex \`$\` menu
1574
- - Claude Code project skills: \`.claude/skills/\`
1575
- - Antigravity: reads \`.agent/skills/\` directly (no copy needed)
1576
- - Keep \`.agent/skills/\` as the full shared source of truth committed with the repo.
1577
- - Do not commit \`~/.codex/skills/\`; it is local user state.
1578
-
1579
- Recommended candidates to copy first:
1580
-
1581
- - \`clean-code\`
1582
- - \`systematic-debugging\`
1583
- - \`verification-before-completion\`
1584
- - Stack-specific skills listed in \`.agent/docs/project.md\`
1585
- `;
1586
- }
1587
-
1588
- // --- Agent Folder Copy ---
1589
-
1590
- function copyAgentFolder() {
1591
- const srcAgent = path.join(sourceDir, '.agent');
1592
- if (!fs.existsSync(srcAgent)) return { copied: 0, skipped: 0 };
1593
-
1594
- const destAgent = path.join(targetDir, '.agent');
1595
- let copied = 0;
1596
-
1597
- function copyDir(src, dest) {
1598
- fs.mkdirSync(dest, { recursive: true });
1599
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
1600
- const srcPath = path.join(src, entry.name);
1601
- const destPath = path.join(dest, entry.name);
1602
- const relativeSrc = path.relative(srcAgent, srcPath).split(path.sep).join('/');
1603
- if (relativeSrc === 'docs' || relativeSrc.startsWith('docs/')) {
1604
- continue;
1605
- }
1606
- if (entry.isDirectory()) {
1607
- copyDir(srcPath, destPath);
1608
- } else {
1609
- fs.copyFileSync(srcPath, destPath);
1610
- copied++;
1611
- }
1612
- }
1613
- }
1614
-
1615
- copyDir(srcAgent, destAgent);
1616
- return { copied, skipped: 0 };
1617
- }
1618
-
1619
- function copySelectedSkillFolders(data, assumeYes) {
1620
- const srcSkills = path.join(sourceDir, '.agent', 'skills');
1621
- if (!fs.existsSync(srcSkills)) return { copied: 0, skipped: 0, missing: 0, skills: [] };
1622
-
1623
- const selectedSkills = resolveNativeSkills(data);
1624
-
1625
- // ~/.codex/skills/ — global Codex user skills dir, always visible in the $ menu
1626
- const codexSkillsDir = homePath('.codex', 'skills');
1627
- // .claude/skills/ — project-level Claude Code skills
1628
- const claudeSkillsDir = path.join(targetDir, '.claude', 'skills');
1629
-
1630
- const destinations = [claudeSkillsDir];
1631
- if (codexSkillsDir) destinations.push(codexSkillsDir);
1632
-
1633
- let copied = 0;
1634
- let missing = 0;
1635
-
1636
- function copyDir(src, dest) {
1637
- fs.mkdirSync(dest, { recursive: true });
1638
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
1639
- const srcPath = path.join(src, entry.name);
1640
- const destPath = path.join(dest, entry.name);
1641
- if (entry.isDirectory()) {
1642
- copyDir(srcPath, destPath);
1643
- } else {
1644
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
1645
- fs.copyFileSync(srcPath, destPath);
1646
- copied++;
1647
- }
1648
- }
1649
- }
1650
-
1651
- for (const skill of selectedSkills) {
1652
- const srcSkill = path.join(srcSkills, skill);
1653
- if (!fs.existsSync(srcSkill)) {
1654
- missing++;
1655
- continue;
1656
- }
1657
- for (const destSkills of destinations) {
1658
- copyDir(srcSkill, path.join(destSkills, skill));
1659
- }
1660
- }
1661
-
1662
- return { copied, skipped: 0, missing, skills: selectedSkills };
1663
1141
  }
1664
1142
 
1665
- function copyCodexPrompts() {
1666
- const srcPrompts = path.join(sourceDir, 'prompts');
1667
- const codexPromptsDir = homePath('.codex', 'prompts');
1668
- if (!fs.existsSync(srcPrompts) || !codexPromptsDir) {
1669
- return { copied: 0, prompts: [] };
1670
- }
1671
-
1672
- let copied = 0;
1673
- const prompts = [];
1674
- fs.mkdirSync(codexPromptsDir, { recursive: true });
1675
- for (const entry of fs.readdirSync(srcPrompts, { withFileTypes: true })) {
1676
- if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
1677
- fs.copyFileSync(path.join(srcPrompts, entry.name), path.join(codexPromptsDir, entry.name));
1678
- copied++;
1679
- prompts.push(path.basename(entry.name, '.md'));
1680
- }
1681
- return { copied, prompts };
1682
- }
1683
-
1684
- function copyClientWorkflowCommands() {
1685
- const srcPrompts = path.join(sourceDir, 'prompts');
1686
- const claudeSkillsDir = path.join(targetDir, '.claude', 'skills');
1687
- const cursorCommandsDir = path.join(targetDir, '.cursor', 'commands');
1688
- if (!fs.existsSync(srcPrompts)) {
1689
- return { claude: 0, cursor: 0, prompts: [] };
1690
- }
1691
-
1692
- let claude = 0;
1693
- let cursor = 0;
1694
- const prompts = [];
1695
- for (const entry of fs.readdirSync(srcPrompts, { withFileTypes: true })) {
1696
- if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
1697
- const name = path.basename(entry.name, '.md');
1698
- const sourcePath = path.join(srcPrompts, entry.name);
1699
- const sourceContent = fs.readFileSync(sourcePath, 'utf8');
1700
- const cursorContent = sourceContent.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
1701
- fs.mkdirSync(path.join(claudeSkillsDir, name), { recursive: true });
1702
- fs.copyFileSync(sourcePath, path.join(claudeSkillsDir, name, 'SKILL.md'));
1703
- fs.mkdirSync(cursorCommandsDir, { recursive: true });
1704
- fs.writeFileSync(path.join(cursorCommandsDir, entry.name), cursorContent, 'utf8');
1705
- claude++;
1706
- cursor++;
1707
- prompts.push(name);
1708
- }
1709
- return { claude, cursor, prompts };
1710
- }
1711
-
1712
- function stripFrontmatter(content) {
1713
- return content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').trimStart();
1714
- }
1715
-
1716
- function copyForgeCommands() {
1717
- const srcCommands = path.join(sourceDir, 'commands');
1718
- const codexSkillsDir = homePath('.codex', 'skills');
1719
- if (!fs.existsSync(srcCommands)) {
1720
- return { antigravity: 0, claude: 0, cursor: 0, codex: 0, commands: [] };
1721
- }
1722
-
1723
- const destinations = {
1724
- antigravity: path.join(targetDir, '.agent', 'workflows'),
1725
- claude: path.join(targetDir, '.claude', 'commands'),
1726
- cursor: path.join(targetDir, '.cursor', 'commands')
1727
- };
1728
-
1729
- for (const commandName of REMOVED_FORGE_COMMANDS) {
1730
- const filename = `${commandName}.md`;
1731
- for (const destination of Object.values(destinations)) {
1732
- const commandPath = path.join(destination, filename);
1733
- if (fs.existsSync(commandPath)) fs.rmSync(commandPath, { force: true });
1143
+ async function writeGeneratedFile(relativePath, content, assumeYes) {
1144
+ const outputPath = path.join(targetDir, relativePath);
1145
+ const exists = fs.existsSync(outputPath);
1146
+ if (exists && !assumeYes) {
1147
+ const response = await prompts({
1148
+ type: 'confirm',
1149
+ name: 'overwrite',
1150
+ message: `File ${pc.bold(relativePath)} already exists. Do you want to overwrite it?`,
1151
+ initial: false
1152
+ });
1153
+ if (response.overwrite === undefined) {
1154
+ console.log(pc.yellow('\nCancelled.'));
1155
+ process.exit(130);
1734
1156
  }
1735
- if (codexSkillsDir) {
1736
- const codexSkillPath = path.join(codexSkillsDir, commandName);
1737
- if (fs.existsSync(codexSkillPath)) fs.rmSync(codexSkillPath, { recursive: true, force: true });
1738
- }
1739
- }
1740
-
1741
- let antigravity = 0;
1742
- let claude = 0;
1743
- let cursor = 0;
1744
- let codex = 0;
1745
- const commands = [];
1746
-
1747
- for (const commandName of FORGE_COMMANDS) {
1748
- const filename = `${commandName}.md`;
1749
- const sourcePath = path.join(srcCommands, filename);
1750
- if (!fs.existsSync(sourcePath)) continue;
1751
- const sourceContent = fs.readFileSync(sourcePath, 'utf8');
1752
- const body = stripFrontmatter(sourceContent);
1753
-
1754
- fs.mkdirSync(destinations.antigravity, { recursive: true });
1755
- fs.copyFileSync(sourcePath, path.join(destinations.antigravity, filename));
1756
- antigravity++;
1757
-
1758
- fs.mkdirSync(destinations.claude, { recursive: true });
1759
- fs.copyFileSync(sourcePath, path.join(destinations.claude, filename));
1760
- claude++;
1761
-
1762
- fs.mkdirSync(destinations.cursor, { recursive: true });
1763
- fs.writeFileSync(path.join(destinations.cursor, filename), body, 'utf8');
1764
- cursor++;
1765
-
1766
- if (codexSkillsDir) {
1767
- const skillDir = path.join(codexSkillsDir, commandName);
1768
- fs.mkdirSync(skillDir, { recursive: true });
1769
- const skillBody = body.replace(/\$ARGUMENTS/g, 'the request supplied with this skill');
1770
- fs.writeFileSync(
1771
- path.join(skillDir, 'SKILL.md'),
1772
- `---\nname: ${commandName}\ndescription: ${sourceContent.match(/^description:\s*(.+)$/m)?.[1] || `Run ${commandName}`}\n---\n\nThis skill is invoked as $${commandName}. Treat the user's text supplied with the skill as the request.\n\n${skillBody}`,
1773
- 'utf8'
1774
- );
1775
- codex++;
1776
- }
1777
-
1778
- commands.push(commandName);
1157
+ if (!response.overwrite) return false;
1779
1158
  }
1780
1159
 
1781
- return { antigravity, claude, cursor, codex, commands };
1160
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
1161
+ fs.writeFileSync(outputPath, content, 'utf8');
1162
+ return true;
1782
1163
  }
1783
-
1784
- async function writeGeneratedFile(relativePath, content, assumeYes) {
1785
- const outputPath = path.join(targetDir, relativePath);
1786
- const exists = fs.existsSync(outputPath);
1787
- if (exists && !assumeYes) {
1788
- const response = await prompts({
1789
- type: 'confirm',
1790
- name: 'overwrite',
1791
- message: `File ${pc.bold(relativePath)} already exists. Do you want to overwrite it?`,
1792
- initial: false
1793
- });
1794
- if (response.overwrite === undefined) {
1795
- console.log(pc.yellow('\nCancelled.'));
1796
- process.exit(130);
1797
- }
1798
- if (!response.overwrite) return false;
1799
- }
1800
-
1801
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
1802
- fs.writeFileSync(outputPath, content, 'utf8');
1803
- return true;
1804
- }
1805
-
1164
+
1806
1165
  function homePath(...parts) {
1807
- const home = process.env.USERPROFILE || process.env.HOME;
1808
- return home ? path.join(home, ...parts) : null;
1166
+ const home = process.env.USERPROFILE || process.env.HOME;
1167
+ return home ? path.join(home, ...parts) : null;
1809
1168
  }
1810
1169
 
1811
1170
  function printSuperpowersInstallGuide() {
@@ -1849,6 +1208,9 @@ function runDoctor() {
1849
1208
 
1850
1209
  async function runSetup(args) {
1851
1210
  const skipMcpSetup = args.includes('--no-setup-mcp');
1211
+ const skipHookSetup = args.includes('--no-setup-hook');
1212
+ const skipRtkInstall = args.includes('--no-install-rtk');
1213
+ const skipIndex = args.includes('--no-index');
1852
1214
  console.log(pc.bold(pc.cyan('thachvd-kit setup')));
1853
1215
  printSuperpowersInstallGuide();
1854
1216
  if (!skipMcpSetup) {
@@ -1857,24 +1219,35 @@ async function runSetup(args) {
1857
1219
  const marker = result.ok ? pc.green('OK') : pc.yellow('WARN');
1858
1220
  console.log(` ${marker} ${result.message}`);
1859
1221
  }
1222
+ if (!skipIndex) {
1223
+ const indexResult = indexRepository();
1224
+ const marker = indexResult.ok ? pc.green('OK') : pc.yellow('WARN');
1225
+ console.log(` ${marker} ${indexResult.message}`);
1226
+ }
1860
1227
  }
1861
- console.log(`\n${pc.bold('RTK (recommended)')}`);
1862
- if (commandExists('rtk')) {
1863
- console.log(` ${pc.green('OK')} rtk already installed`);
1864
- } else {
1865
- console.log(` ${pc.yellow('WARN')} recommended: rtk is not installed; run: ${RTK_INSTALL_COMMAND}`);
1228
+ if (!skipHookSetup) {
1229
+ console.log(`\n${pc.bold('Claude Code Definition-of-Done hook')}`);
1230
+ const claudeProjectSettings = path.join(targetDir, '.claude', 'settings.json');
1231
+ const result = mergeClaudeProjectHooks(claudeProjectSettings);
1232
+ const marker = result.ok ? pc.green('OK') : pc.yellow('WARN');
1233
+ console.log(` ${marker} ${result.message}`);
1234
+ console.log(' This hook only checks for plan/review/verification evidence; it never prescribes which skill produces it.');
1866
1235
  }
1236
+ console.log(`\n${pc.bold('RTK (recommended)')}`);
1237
+ const rtkResult = ensureRtkInstalled(!skipRtkInstall);
1238
+ const rtkMarker = rtkResult.ok ? pc.green('OK') : pc.yellow('WARN');
1239
+ console.log(` ${rtkMarker} ${rtkResult.message}`);
1867
1240
  console.log('\nRestart your AI client after installing plugins or changing MCP configuration.');
1868
1241
  console.log('Your onboarding prompt is saved at .agent/docs/index-project-prompt.md. Run thachvd-kit prompt to print it again.');
1869
1242
  }
1870
1243
 
1871
1244
  function commandExists(command) {
1872
- const checker = process.platform === 'win32' ? 'where' : 'command';
1873
- const args = process.platform === 'win32' ? [command] : ['-v', command];
1874
- const result = spawnSync(checker, args, { encoding: 'utf8', shell: process.platform !== 'win32' });
1875
- return result.status === 0;
1876
- }
1877
-
1245
+ const checker = process.platform === 'win32' ? 'where' : 'command';
1246
+ const args = process.platform === 'win32' ? [command] : ['-v', command];
1247
+ const result = spawnSync(checker, args, { encoding: 'utf8', shell: process.platform !== 'win32' });
1248
+ return result.status === 0;
1249
+ }
1250
+
1878
1251
  function ensureGlobalNpmPackage(binaryName, packageName, install = false) {
1879
1252
  if (commandExists(binaryName)) {
1880
1253
  return { ok: true, message: `${binaryName} already installed` };
@@ -1883,113 +1256,149 @@ function ensureGlobalNpmPackage(binaryName, packageName, install = false) {
1883
1256
  return { ok: false, message: `${binaryName} is missing; run: npm install -g ${packageName}` };
1884
1257
  }
1885
1258
  if (!commandExists('npm')) {
1886
- return { ok: false, message: `npm not found; run: npm install -g ${packageName}` };
1887
- }
1888
- const result = spawnSync('npm', ['install', '-g', packageName], {
1889
- encoding: 'utf8',
1890
- stdio: 'pipe'
1891
- });
1892
- if (result.status !== 0) {
1893
- return { ok: false, message: `failed to install ${binaryName}; run: npm install -g ${packageName}` };
1894
- }
1895
- return { ok: true, message: `installed ${binaryName}` };
1896
- }
1897
-
1259
+ return { ok: false, message: `npm not found; run: npm install -g ${packageName}` };
1260
+ }
1261
+ const result = spawnSync('npm', ['install', '-g', packageName], {
1262
+ encoding: 'utf8',
1263
+ stdio: 'pipe',
1264
+ shell: process.platform === 'win32'
1265
+ });
1266
+ if (result.status !== 0) {
1267
+ return { ok: false, message: `failed to install ${binaryName}; run: npm install -g ${packageName}` };
1268
+ }
1269
+ return { ok: true, message: `installed ${binaryName}` };
1270
+ }
1271
+
1898
1272
  function ensureCodebaseMemoryCli(install = false) {
1899
1273
  return ensureGlobalNpmPackage(CODEBASE_MEMORY_BINARY, CODEBASE_MEMORY_PACKAGE, install);
1900
1274
  }
1901
-
1902
- function readJsonFile(filePath) {
1903
- if (!fs.existsSync(filePath)) return {};
1904
- try {
1905
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1906
- } catch {
1907
- return null;
1908
- }
1909
- }
1910
-
1911
- function writeJsonFile(filePath, data) {
1912
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
1913
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
1914
- }
1915
-
1916
- function mergeMcpJson(filePath, withType = false) {
1917
- const data = readJsonFile(filePath);
1918
- if (data === null) {
1919
- return { ok: false, message: `${filePath} is not valid JSON; skipped` };
1920
- }
1921
- data.mcpServers = data.mcpServers || {};
1275
+
1276
+ function ensureRtkInstalled(install = false) {
1277
+ if (commandExists('rtk')) {
1278
+ return { ok: true, message: 'rtk already installed' };
1279
+ }
1280
+ if (!install) {
1281
+ return { ok: false, message: `rtk is missing; run: ${RTK_INSTALL_COMMAND}` };
1282
+ }
1283
+ if (!commandExists('cargo')) {
1284
+ return { ok: false, message: `cargo not found; install Rust, then run: ${RTK_INSTALL_COMMAND}` };
1285
+ }
1286
+ console.log(pc.dim(' Installing rtk via cargo (compiles from source; this can take a few minutes)...'));
1287
+ const result = spawnSync('cargo', ['install', '--git', 'https://github.com/rtk-ai/rtk', '--branch', 'master', 'rtk'], {
1288
+ encoding: 'utf8',
1289
+ stdio: 'inherit',
1290
+ shell: process.platform === 'win32'
1291
+ });
1292
+ if (result.status !== 0) {
1293
+ return { ok: false, message: `failed to install rtk; run: ${RTK_INSTALL_COMMAND}` };
1294
+ }
1295
+ return { ok: true, message: 'installed rtk' };
1296
+ }
1297
+
1298
+ function indexRepository() {
1299
+ if (!commandExists(CODEBASE_MEMORY_BINARY)) {
1300
+ return { ok: false, message: `${CODEBASE_MEMORY_BINARY} is not installed; skipped indexing` };
1301
+ }
1302
+ console.log(pc.dim(` Running ${CODEBASE_MEMORY_BINARY} cli index_repository --repo-path . (first index of a large repo can take a while)...`));
1303
+ const result = spawnSync(CODEBASE_MEMORY_BINARY, ['cli', 'index_repository', '--repo-path', '.'], {
1304
+ cwd: targetDir,
1305
+ encoding: 'utf8',
1306
+ stdio: 'inherit',
1307
+ shell: process.platform === 'win32'
1308
+ });
1309
+ if (result.status !== 0) {
1310
+ return { ok: false, message: `indexing failed; run manually: ${CODEBASE_MEMORY_BINARY} cli index_repository --repo-path .` };
1311
+ }
1312
+ return { ok: true, message: 'indexed repository with codebase-memory-mcp' };
1313
+ }
1314
+
1315
+ function readJsonFile(filePath) {
1316
+ if (!fs.existsSync(filePath)) return {};
1317
+ try {
1318
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1319
+ } catch {
1320
+ return null;
1321
+ }
1322
+ }
1323
+
1324
+ function writeJsonFile(filePath, data) {
1325
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1326
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
1327
+ }
1328
+
1329
+ function mergeMcpJson(filePath, withType = false) {
1330
+ const data = readJsonFile(filePath);
1331
+ if (data === null) {
1332
+ return { ok: false, message: `${filePath} is not valid JSON; skipped` };
1333
+ }
1334
+ data.mcpServers = data.mcpServers || {};
1922
1335
  const baseServers = {
1923
1336
  'codebase-memory-mcp': { command: CODEBASE_MEMORY_BINARY, args: [] },
1924
1337
  playwright: { command: 'playwright-mcp' },
1925
1338
  context7: { command: 'context7-mcp' }
1926
- };
1927
- if (data.permissions && Array.isArray(data.permissions.allow)) {
1928
- const requiredPermissions = [
1929
- "mcp__context7__resolve-library-id",
1930
- "mcp__context7__query-docs"
1931
- ];
1932
- for (const perm of requiredPermissions) {
1933
- if (!data.permissions.allow.includes(perm)) {
1934
- data.permissions.allow.push(perm);
1935
- }
1936
- }
1937
- }
1938
- for (const [name, server] of Object.entries(baseServers)) {
1939
- if (!data.mcpServers[name]) {
1940
- data.mcpServers[name] = withType ? { type: 'stdio', ...server } : server;
1941
- }
1942
- }
1943
- writeJsonFile(filePath, data);
1944
- const tools = Object.keys(baseServers).join(', ');
1945
- return { ok: true, message: `configured ${tools} MCP in ${filePath}` };
1946
- }
1947
-
1948
- function appendMcpTomlIfMissing(filePath) {
1949
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
1950
- const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
1951
- const blocks = [];
1952
- if (!/\[mcp_servers\.context7\]/.test(existing)) {
1953
- blocks.push(`[mcp_servers.context7]
1954
- command = "context7-mcp"
1955
- startup_timeout_sec = 20
1956
- tool_timeout_sec = 120
1957
- `);
1958
- }
1339
+ };
1340
+ if (data.permissions && Array.isArray(data.permissions.allow)) {
1341
+ const requiredPermissions = [
1342
+ "mcp__context7__resolve-library-id",
1343
+ "mcp__context7__query-docs"
1344
+ ];
1345
+ for (const perm of requiredPermissions) {
1346
+ if (!data.permissions.allow.includes(perm)) {
1347
+ data.permissions.allow.push(perm);
1348
+ }
1349
+ }
1350
+ }
1351
+ for (const [name, server] of Object.entries(baseServers)) {
1352
+ if (!data.mcpServers[name]) {
1353
+ data.mcpServers[name] = withType ? { type: 'stdio', ...server } : server;
1354
+ }
1355
+ }
1356
+ writeJsonFile(filePath, data);
1357
+ const tools = Object.keys(baseServers).join(', ');
1358
+ return { ok: true, message: `configured ${tools} MCP in ${filePath}` };
1359
+ }
1360
+
1361
+ function appendMcpTomlIfMissing(filePath) {
1362
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1363
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
1364
+ const blocks = [];
1365
+ if (!/\[mcp_servers\.context7\]/.test(existing)) {
1366
+ blocks.push(`[mcp_servers.context7]
1367
+ command = "context7-mcp"
1368
+ startup_timeout_sec = 20
1369
+ tool_timeout_sec = 120
1370
+ `);
1371
+ }
1959
1372
  if (!/\[mcp_servers\.codebase-memory-mcp\]/.test(existing)) {
1960
1373
  blocks.push(`[mcp_servers.codebase-memory-mcp]
1961
1374
  command = "${CODEBASE_MEMORY_BINARY}"
1962
1375
  startup_timeout_sec = 20
1963
1376
  tool_timeout_sec = 120
1964
1377
  `);
1965
- }
1966
- if (!/\[mcp_servers\.playwright\]/.test(existing)) {
1967
- blocks.push(`[mcp_servers.playwright]
1968
- command = "playwright-mcp"
1969
- startup_timeout_sec = 20
1970
- tool_timeout_sec = 120
1971
- `);
1972
- }
1973
- if (blocks.length === 0) { return { ok: true, message: `already configured ${filePath}` };
1974
- }
1975
- const separator = existing && !existing.endsWith('\n') ? '\n\n' : existing ? '\n' : '';
1976
- fs.writeFileSync(filePath, existing + separator + blocks.join('\n'), 'utf8');
1378
+ }
1379
+ if (!/\[mcp_servers\.playwright\]/.test(existing)) {
1380
+ blocks.push(`[mcp_servers.playwright]
1381
+ command = "playwright-mcp"
1382
+ startup_timeout_sec = 20
1383
+ tool_timeout_sec = 120
1384
+ `);
1385
+ }
1386
+ if (blocks.length === 0) { return { ok: true, message: `already configured ${filePath}` };
1387
+ }
1388
+ const separator = existing && !existing.endsWith('\n') ? '\n\n' : existing ? '\n' : '';
1389
+ fs.writeFileSync(filePath, existing + separator + blocks.join('\n'), 'utf8');
1977
1390
  return { ok: true, message: `configured codebase-memory-mcp, context7, playwright MCP in ${filePath}` };
1978
- }
1979
-
1391
+ }
1392
+
1980
1393
  const DOD_HOOK_MARKER = 'feature/refactor Definition-of-Done gate';
1981
1394
 
1982
1395
  function generateDodStopHookPrompt() {
1983
- return `Input JSON (Stop hook payload): $ARGUMENTS\n\nCheck this project's ${DOD_HOOK_MARKER} (defined in AGENTS.md "Gated Flow" and .agent/docs/workflow.md "Definition of Done"). Use the \`last_assistant_message\` field as the authoritative final response. Use \`transcript_path\` only for additional context because the transcript may not contain the final response yet.\n\nFor a feature or refactor (multi-file change, new behavior, or non-trivial refactor), the work must go through spec -> plan -> implement -> review before being reported as complete:\n- spec: \`.agent/workflows/spec.md\` (skip allowed for trivial/self-contained changes)\n- plan: \`.agent/workflows/plan.md\`, with a plan artifact such as \`docs/PLAN-*.md\` and explicit user approval\n- review: \`.agent/workflows/review.md\` five-axis review, with blocking issues resolved\n\nSimple/self-contained fixes (single-line, typo, or unambiguous one-file change) may use /simple and are explicitly exempt from spec+plan+review only when the final response states FAST_PATH: simple-fix, its reason, and its narrow scope. They should never be blocked when those criteria are met. Verification is still mandatory.\n\nSteps:\n1. If the input JSON has \`stop_hook_active: true\`, allow stopping immediately (already checked once this cycle; never block twice in a row).\n2. Inspect the changed files and the \`last_assistant_message\` field.\n3. If no source files changed, the final response does not claim the task is done/complete, or the final response explicitly contains FAST_PATH: simple-fix and the changed scope is clearly a simple/self-contained fix, allow stopping.\n4. If it is a feature/refactor-scale change and the final response claims completion, verify that a plan artifact exists with evidence of user approval and that a review pass was completed. If either gate is missing, block; a generic statement that the task was simple is not enough.\n5. Return exactly JSON: {"ok": true} to allow stopping, or {"ok": false, "reason": "..."} to block.\n\nWhen blocking, name exactly which gate is missing and instruct the assistant to run the relevant workflow or explicitly state why the task qualifies as a simple fix.`;
1396
+ return `Input JSON (Stop hook payload): $ARGUMENTS\n\nCheck this project's ${DOD_HOOK_MARKER}. This kit does not define its own workflow steps; it only verifies that evidence of the gate exists, regardless of which skill produced it (a Superpowers skill such as \`writing-plans\`/\`requesting-code-review\`, or an equivalent documented step). Use the \`last_assistant_message\` field as the authoritative final response. Use \`transcript_path\` only for additional context because the transcript may not contain the final response yet.\n\nFor a feature or refactor (multi-file change, new behavior, or non-trivial refactor), completion requires evidence of:\n- Plan: a plan was written and explicitly approved by the human before implementation started.\n- Review: the change was reviewed (correctness, simplicity, architecture, security, performance) and blocking issues were resolved.\n- Verification: tests or equivalent verification ran and passed.\n\nA one-file, unambiguous fix with no behavior/contract change is exempt from the Plan and Review evidence only when the final response states FAST_PATH: simple-fix, its reason, and its narrow scope. Verification is still mandatory in that case.\n\nSteps:\n1. If the input JSON has \`stop_hook_active: true\`, allow stopping immediately (already checked once this cycle; never block twice in a row).\n2. Inspect the changed files and the \`last_assistant_message\` field.\n3. If no source files changed, the final response does not claim the task is done/complete, or the final response explicitly contains FAST_PATH: simple-fix and the changed scope is clearly a simple/self-contained fix, allow stopping.\n4. If it is a feature/refactor-scale change and the final response claims completion, verify that the response (or the visible transcript) shows evidence of an approved plan and a completed review. If either is missing, block; a generic statement that the task was simple is not enough.\n5. Return exactly JSON: {"ok": true} to allow stopping, or {"ok": false, "reason": "..."} to block.\n\nWhen blocking, name exactly which gate is missing without prescribing which skill or workflow must produce it.`;
1984
1397
  }
1985
1398
 
1986
1399
  function isDefinitionOfDoneHook(hook) {
1987
1400
  const prompt = hook && typeof hook.prompt === 'string' ? hook.prompt : '';
1988
- return prompt.includes(DOD_HOOK_MARKER) || (
1989
- prompt.includes('Input JSON (Stop hook payload)') &&
1990
- prompt.includes('.agent/workflows/spec.md') &&
1991
- prompt.includes('.agent/workflows/review.md')
1992
- );
1401
+ return prompt.includes(DOD_HOOK_MARKER);
1993
1402
  }
1994
1403
 
1995
1404
  function mergeClaudeProjectHooks(filePath) {
@@ -2055,42 +1464,42 @@ function setupMcpServers(options = {}) {
2055
1464
  results.push(ensureCodebaseMemoryCli(install));
2056
1465
  results.push(ensureGlobalNpmPackage('context7-mcp', '@upstash/context7-mcp', install));
2057
1466
  results.push(ensureGlobalNpmPackage('playwright-mcp', '@playwright/mcp', install));
2058
-
2059
- const codexConfig = homePath('.codex', 'config.toml');
2060
- if (codexConfig) results.push(appendMcpTomlIfMissing(codexConfig));
2061
-
2062
- const geminiConfig = homePath('.gemini', 'config', 'mcp_config.json');
2063
- if (geminiConfig) results.push(mergeMcpJson(geminiConfig, false));
2064
-
2065
- const antigravityIdeConfig = homePath('.gemini', 'antigravity-ide', 'mcp_config.json');
2066
- if (antigravityIdeConfig) results.push(mergeMcpJson(antigravityIdeConfig, false));
2067
-
2068
- const antigravityConfig = homePath('.gemini', 'antigravity', 'mcp_config.json');
2069
- if (antigravityConfig && fs.existsSync(path.dirname(antigravityConfig))) {
2070
- results.push(mergeMcpJson(antigravityConfig, false));
2071
- }
2072
-
2073
- const claudeConfig = homePath('.claude.json');
2074
- if (claudeConfig) results.push(mergeMcpJson(claudeConfig, true));
2075
-
2076
- const claudeSettings = homePath('.claude', 'settings.json');
2077
- if (claudeSettings) results.push(mergeMcpJson(claudeSettings, true));
2078
-
2079
- return results;
2080
- }
2081
-
2082
- // --- Main CLI ---
2083
-
2084
- async function main() {
2085
- const rawArgs = process.argv.slice(2);
2086
- const command = rawArgs[0] && !rawArgs[0].startsWith('-') ? rawArgs[0] : 'init';
2087
- const args = command === 'init' ? rawArgs.slice(rawArgs[0] === 'init' ? 1 : 0) : rawArgs.slice(1);
2088
-
2089
- if (rawArgs.includes('--version') || rawArgs.includes('-v')) {
2090
- console.log(packageJson.version);
2091
- return;
2092
- }
2093
-
1467
+
1468
+ const codexConfig = homePath('.codex', 'config.toml');
1469
+ if (codexConfig) results.push(appendMcpTomlIfMissing(codexConfig));
1470
+
1471
+ const geminiConfig = homePath('.gemini', 'config', 'mcp_config.json');
1472
+ if (geminiConfig) results.push(mergeMcpJson(geminiConfig, false));
1473
+
1474
+ const antigravityIdeConfig = homePath('.gemini', 'antigravity-ide', 'mcp_config.json');
1475
+ if (antigravityIdeConfig) results.push(mergeMcpJson(antigravityIdeConfig, false));
1476
+
1477
+ const antigravityConfig = homePath('.gemini', 'antigravity', 'mcp_config.json');
1478
+ if (antigravityConfig && fs.existsSync(path.dirname(antigravityConfig))) {
1479
+ results.push(mergeMcpJson(antigravityConfig, false));
1480
+ }
1481
+
1482
+ const claudeConfig = homePath('.claude.json');
1483
+ if (claudeConfig) results.push(mergeMcpJson(claudeConfig, true));
1484
+
1485
+ const claudeSettings = homePath('.claude', 'settings.json');
1486
+ if (claudeSettings) results.push(mergeMcpJson(claudeSettings, true));
1487
+
1488
+ return results;
1489
+ }
1490
+
1491
+ // --- Main CLI ---
1492
+
1493
+ async function main() {
1494
+ const rawArgs = process.argv.slice(2);
1495
+ const command = rawArgs[0] && !rawArgs[0].startsWith('-') ? rawArgs[0] : 'init';
1496
+ const args = command === 'init' ? rawArgs.slice(rawArgs[0] === 'init' ? 1 : 0) : rawArgs.slice(1);
1497
+
1498
+ if (rawArgs.includes('--version') || rawArgs.includes('-v')) {
1499
+ console.log(packageJson.version);
1500
+ return;
1501
+ }
1502
+
2094
1503
  if (rawArgs.includes('--help') || rawArgs.includes('-h')) {
2095
1504
  printHelp();
2096
1505
  return;
@@ -2112,131 +1521,131 @@ async function main() {
2112
1521
  }
2113
1522
 
2114
1523
  if (command !== 'init') {
2115
- console.error(pc.red(`Unknown command: ${command}`));
2116
- printHelp();
2117
- process.exit(1);
2118
- }
2119
-
2120
- const assumeYes = args.includes('--yes') || args.includes('-y');
2121
- const skipMcpSetup = args.includes('--no-setup-mcp') || process.env.THACHVD_KIT_SKIP_MCP_SETUP === '1';
2122
-
2123
- console.log(pc.bold(pc.cyan('='.repeat(50))));
2124
- console.log(' ' + pc.bold('thachvd-kit') + ' - AI Project Bootstrap');
2125
- console.log(' Generates shared agent rules and configures MCP tooling');
2126
- console.log(pc.bold(pc.cyan('='.repeat(50))));
2127
-
2128
- console.log(pc.dim(' Scanning current project files for a baseline...\n'));
2129
- const scanned = scanProject();
2130
-
2131
- console.log(` ${pc.bold('Detected context:')}`);
2132
- formatScanPreviewLines(scanned).forEach(([label, value]) => {
2133
- console.log(` - ${label}: ${value}`);
2134
- });
2135
- console.log('');
2136
- if ((scanned.scan_evidence || []).length > 0) {
2137
- console.log(` ${pc.bold('Evidence:')}`);
2138
- scanned.scan_evidence.forEach(line => console.log(` - ${line}`));
2139
- console.log('');
2140
- }
2141
-
2142
- // Combine data
2143
- const data = {
2144
- project_name: scanned?.project_name || path.basename(targetDir),
2145
- description: scanned?.description || 'A software project',
2146
- project_type: scanned?.project_type || 'web-app',
2147
- primary_language: scanned?.primary_language || 'typescript',
2148
- frameworks: scanned?.frameworks || [],
2149
- database: scanned?.database || 'none',
2150
- uses_docker: scanned?.uses_docker ?? true,
2151
- cloud: scanned?.cloud || 'none',
2152
- package_manager: scanned?.package_manager || 'auto-detect',
2153
- test_framework: scanned?.test_framework || 'auto-detect',
2154
- max_file_lines: scanned?.max_file_lines || '300'
2155
- };
2156
-
2157
- data.database = data.database || scanned?.database || 'none';
2158
- data.uses_docker = typeof data.uses_docker === 'boolean' ? data.uses_docker : (scanned?.uses_docker ?? true);
2159
- data.cloud = data.cloud || scanned?.cloud || 'none';
2160
- data.package_manager = data.package_manager || scanned?.package_manager || 'auto-detect';
2161
- data.test_framework = data.test_framework || scanned?.test_framework || 'auto-detect';
2162
- data.max_file_lines = data.max_file_lines || scanned?.max_file_lines || '300';
2163
- data.framework_details = scanned?.framework_details || [];
2164
- data.scan_evidence = scanned?.scan_evidence || [];
2165
- data.app_root = scanned?.app_root || '.';
2166
-
2167
- data.infrastructure = [];
2168
- if (data.uses_docker) data.infrastructure.push('docker');
2169
- if (data.cloud !== 'none') data.infrastructure.push(data.cloud);
2170
-
1524
+ console.error(pc.red(`Unknown command: ${command}`));
1525
+ printHelp();
1526
+ process.exit(1);
1527
+ }
1528
+
1529
+ const assumeYes = args.includes('--yes') || args.includes('-y');
1530
+ const skipMcpSetup = args.includes('--no-setup-mcp') || process.env.THACHVD_KIT_SKIP_MCP_SETUP === '1';
1531
+
1532
+ console.log(pc.bold(pc.cyan('='.repeat(50))));
1533
+ console.log(' ' + pc.bold('thachvd-kit') + ' - AI Project Bootstrap');
1534
+ console.log(' Generates shared agent rules and configures MCP tooling');
1535
+ console.log(pc.bold(pc.cyan('='.repeat(50))));
1536
+
1537
+ console.log(pc.dim(' Scanning current project files for a baseline...\n'));
1538
+ const scanned = scanProject();
1539
+
1540
+ console.log(` ${pc.bold('Detected context:')}`);
1541
+ formatScanPreviewLines(scanned).forEach(([label, value]) => {
1542
+ console.log(` - ${label}: ${value}`);
1543
+ });
1544
+ console.log('');
1545
+ if ((scanned.scan_evidence || []).length > 0) {
1546
+ console.log(` ${pc.bold('Evidence:')}`);
1547
+ scanned.scan_evidence.forEach(line => console.log(` - ${line}`));
1548
+ console.log('');
1549
+ }
1550
+
1551
+ // Combine data
1552
+ const data = {
1553
+ project_name: scanned?.project_name || path.basename(targetDir),
1554
+ description: scanned?.description || 'A software project',
1555
+ project_type: scanned?.project_type || 'web-app',
1556
+ primary_language: scanned?.primary_language || 'typescript',
1557
+ frameworks: scanned?.frameworks || [],
1558
+ database: scanned?.database || 'none',
1559
+ uses_docker: scanned?.uses_docker ?? true,
1560
+ cloud: scanned?.cloud || 'none',
1561
+ package_manager: scanned?.package_manager || 'auto-detect',
1562
+ test_framework: scanned?.test_framework || 'auto-detect',
1563
+ max_file_lines: scanned?.max_file_lines || '300'
1564
+ };
1565
+
1566
+ data.database = data.database || scanned?.database || 'none';
1567
+ data.uses_docker = typeof data.uses_docker === 'boolean' ? data.uses_docker : (scanned?.uses_docker ?? true);
1568
+ data.cloud = data.cloud || scanned?.cloud || 'none';
1569
+ data.package_manager = data.package_manager || scanned?.package_manager || 'auto-detect';
1570
+ data.test_framework = data.test_framework || scanned?.test_framework || 'auto-detect';
1571
+ data.max_file_lines = data.max_file_lines || scanned?.max_file_lines || '300';
1572
+ data.framework_details = scanned?.framework_details || [];
1573
+ data.scan_evidence = scanned?.scan_evidence || [];
1574
+ data.app_root = scanned?.app_root || '.';
1575
+
1576
+ data.infrastructure = [];
1577
+ if (data.uses_docker) data.infrastructure.push('docker');
1578
+ if (data.cloud !== 'none') data.infrastructure.push(data.cloud);
1579
+
2171
1580
  const shouldSetupMcp = args.includes('--setup-mcp') && !skipMcpSetup;
2172
-
2173
- console.log(`\n${pc.bold(pc.cyan('Generating Files'))}`);
2174
-
2175
- // Shared entry files are written after the .agent folder is available.
2176
-
1581
+
1582
+ console.log(`\n${pc.bold(pc.cyan('Generating Files'))}`);
1583
+
1584
+ // Shared entry files are written after the .agent folder is available.
1585
+
2177
1586
  console.log(` ${pc.green('OK')} Project context generation enabled; workflow skills remain client-managed by Superpowers`);
2178
-
2179
-
2180
- const generatedFiles = [
2181
- ['AGENTS.md', generateSharedAgentsMd(data)],
2182
- ['CLAUDE.md', generateSharedClaudeMd()],
2183
- ['GEMINI.md', generateSharedGeminiMd()],
2184
- ['.cursorrules', generateSharedCursorrules(data)],
2185
- [path.join('.agent', 'docs', 'project.md'), generateProjectDoc(data)],
2186
- [path.join('.agent', 'docs', 'architecture.md'), generateArchitectureDoc(data)],
2187
- [path.join('.agent', 'docs', 'conventions.md'), generateConventionsDoc(data)],
1587
+
1588
+
1589
+ const generatedFiles = [
1590
+ ['AGENTS.md', generateSharedAgentsMd(data)],
1591
+ ['CLAUDE.md', generateSharedClaudeMd()],
1592
+ ['GEMINI.md', generateSharedGeminiMd()],
1593
+ ['.cursorrules', generateSharedCursorrules(data)],
1594
+ [path.join('.agent', 'docs', 'project.md'), generateProjectDoc(data)],
1595
+ [path.join('.agent', 'docs', 'architecture.md'), generateArchitectureDoc(data)],
1596
+ [path.join('.agent', 'docs', 'conventions.md'), generateConventionsDoc(data)],
2188
1597
  [path.join('.agent', 'docs', 'workflow.md'), generateWorkflowDoc()],
2189
1598
  [path.join('.agent', 'docs', 'tooling.md'), generateToolingDoc(data)],
2190
1599
  [path.join('.agent', 'docs', 'getting-started.md'), generateGettingStartedDoc()],
2191
1600
  [path.join('.agent', 'docs', 'index-project-prompt.md'), generateIndexProjectPrompt()]
2192
- ];
2193
-
2194
- for (const [relativePath, content] of generatedFiles) {
2195
- const wrote = await writeGeneratedFile(relativePath, content, assumeYes);
2196
- if (wrote) console.log(` ${pc.green('OK')} Generated ${pc.bold(relativePath)}`);
2197
- else console.log(` ${pc.yellow('~')} Skipped ${pc.bold(relativePath)}`);
2198
- }
2199
-
1601
+ ];
1602
+
1603
+ for (const [relativePath, content] of generatedFiles) {
1604
+ const wrote = await writeGeneratedFile(relativePath, content, assumeYes);
1605
+ if (wrote) console.log(` ${pc.green('OK')} Generated ${pc.bold(relativePath)}`);
1606
+ else console.log(` ${pc.yellow('~')} Skipped ${pc.bold(relativePath)}`);
1607
+ }
1608
+
2200
1609
  if (shouldSetupMcp) {
2201
- console.log(`\n${pc.bold(pc.cyan('Configuring MCP'))}`);
2202
- for (const result of setupMcpServers()) {
2203
- const marker = result.ok ? pc.green('OK') : pc.yellow('~');
2204
- console.log(` ${marker} ${result.message}`);
2205
- }
2206
- }
2207
-
2208
- console.log(`\n${pc.bold(pc.green('Done!'))}
2209
-
2210
- ${pc.bold('Project:')} ${data.project_name}
2211
- ${pc.bold('Stack:')} ${data.primary_language} | ${(data.frameworks || []).join(', ') || 'no framework'}
2212
-
2213
- ${pc.bold('Generated:')}
2214
- - ${pc.bold('AGENTS.md')} shared entry for Codex, Antigravity, Claude Code, and Cursor
2215
- - ${pc.bold('CLAUDE.md')} Claude Code entry that imports AGENTS.md
2216
- - ${pc.bold('GEMINI.md')} Antigravity entry
2217
- - ${pc.bold('.cursorrules')} Cursor entry
1610
+ console.log(`\n${pc.bold(pc.cyan('Configuring MCP'))}`);
1611
+ for (const result of setupMcpServers()) {
1612
+ const marker = result.ok ? pc.green('OK') : pc.yellow('~');
1613
+ console.log(` ${marker} ${result.message}`);
1614
+ }
1615
+ }
1616
+
1617
+ console.log(`\n${pc.bold(pc.green('Done!'))}
1618
+
1619
+ ${pc.bold('Project:')} ${data.project_name}
1620
+ ${pc.bold('Stack:')} ${data.primary_language} | ${(data.frameworks || []).join(', ') || 'no framework'}
1621
+
1622
+ ${pc.bold('Generated:')}
1623
+ - ${pc.bold('AGENTS.md')} shared entry for Codex, Antigravity, Claude Code, and Cursor
1624
+ - ${pc.bold('CLAUDE.md')} Claude Code entry that imports AGENTS.md
1625
+ - ${pc.bold('GEMINI.md')} Antigravity entry
1626
+ - ${pc.bold('.cursorrules')} Cursor entry
2218
1627
  - ${pc.bold('.agent/docs/')} scan-based project rules and local operating notes
2219
1628
  - ${pc.bold('.agent/docs/index-project-prompt.md')} durable onboarding prompt
2220
-
2221
- ${pc.bold('MCP/tooling setup:')}
1629
+
1630
+ ${pc.bold('MCP/tooling setup:')}
2222
1631
  - Superpowers is the workflow backend; install it from the official client/plugin surface
2223
1632
  - Run ${pc.bold('thachvd-kit setup')} to configure codebase-memory MCP and recommended RTK
2224
-
2225
- ${pc.bold('Next steps:')}
1633
+
1634
+ ${pc.bold('Next steps:')}
2226
1635
  1. Run ${pc.bold('thachvd-kit prompt')} and paste the saved prompt into your AI editor
2227
1636
  2. Install Superpowers and RTK, then run ${pc.bold('thachvd-kit setup')}
2228
1637
  3. Run ${pc.bold('thachvd-kit doctor')} to verify the machine
2229
1638
  4. Re-run ${pc.bold('thachvd-kit prompt')} whenever you need the onboarding prompt again
2230
-
1639
+
2231
1640
  ${pc.bold('Onboarding prompt saved to .agent/docs/index-project-prompt.md:')}
2232
1641
  ${pc.dim('---')}
2233
1642
  ${generateIndexProjectPrompt().trim()}
2234
1643
  ${pc.dim('---')}
2235
1644
  `);
2236
1645
  }
2237
-
2238
- main().catch(err => {
2239
- console.error(pc.red('\nError during init:'), err);
2240
- process.exit(1);
2241
- });
2242
-
1646
+
1647
+ main().catch(err => {
1648
+ console.error(pc.red('\nError during init:'), err);
1649
+ process.exit(1);
1650
+ });
1651
+