forjajs 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/.claude/settings.json +7 -7
  2. package/CHANGELOG.md +41 -0
  3. package/README.en.md +5 -0
  4. package/README.md +5 -0
  5. package/dist/bin/create-memory-nest-kit.d.ts +2 -0
  6. package/dist/bin/create-memory-nest-kit.js +110 -0
  7. package/dist/bin/forja.d.ts +13 -0
  8. package/dist/bin/forja.js +136 -0
  9. package/dist/bin/init-project.d.ts +2 -0
  10. package/dist/bin/init-project.js +516 -0
  11. package/dist/lib/audit.d.ts +67 -0
  12. package/dist/lib/audit.js +143 -0
  13. package/dist/lib/context-builder.d.ts +58 -0
  14. package/dist/lib/context-builder.js +233 -0
  15. package/dist/lib/core/checks.d.ts +91 -0
  16. package/dist/lib/core/checks.js +119 -0
  17. package/dist/lib/core/doc-graph.d.ts +60 -0
  18. package/dist/lib/core/doc-graph.js +235 -0
  19. package/dist/lib/core/health.d.ts +103 -0
  20. package/dist/lib/core/health.js +538 -0
  21. package/dist/lib/core/registry.d.ts +296 -0
  22. package/dist/lib/core/registry.js +317 -0
  23. package/dist/lib/core/release.d.ts +334 -0
  24. package/dist/lib/core/release.js +465 -0
  25. package/dist/lib/generators/memory-generator.d.ts +83 -0
  26. package/{lib → dist/lib}/generators/memory-generator.js +107 -178
  27. package/dist/lib/generators/nest-generator.d.ts +15 -0
  28. package/{lib → dist/lib}/generators/nest-generator.js +47 -71
  29. package/dist/lib/generators/readme-generator.d.ts +15 -0
  30. package/{lib → dist/lib}/generators/readme-generator.js +9 -14
  31. package/dist/lib/governance-report.d.ts +49 -0
  32. package/dist/lib/governance-report.js +170 -0
  33. package/dist/lib/templates/harness/code-intel.d.mts +2 -0
  34. package/dist/lib/templates/harness/code-intel.mjs +126 -0
  35. package/dist/lib/utils/file-helpers.d.ts +9 -0
  36. package/dist/lib/utils/file-helpers.js +34 -0
  37. package/dist/lib/validators/structure-validator.d.ts +48 -0
  38. package/dist/lib/validators/structure-validator.js +232 -0
  39. package/dist/lib/workspace.d.ts +40 -0
  40. package/dist/lib/workspace.js +174 -0
  41. package/dist/scripts/agent-harness.d.ts +2 -0
  42. package/dist/scripts/agent-harness.js +556 -0
  43. package/dist/scripts/agent-router.d.ts +30 -0
  44. package/dist/scripts/agent-router.js +208 -0
  45. package/dist/scripts/audit-query.d.ts +2 -0
  46. package/dist/scripts/audit-query.js +43 -0
  47. package/dist/scripts/audit-sync.d.ts +2 -0
  48. package/dist/scripts/audit-sync.js +19 -0
  49. package/dist/scripts/build-smart-context.d.ts +1 -0
  50. package/dist/scripts/build-smart-context.js +75 -0
  51. package/dist/scripts/check-standards.d.ts +1 -0
  52. package/dist/scripts/check-standards.js +87 -0
  53. package/dist/scripts/compress-memory.d.ts +16 -0
  54. package/dist/scripts/compress-memory.js +157 -0
  55. package/dist/scripts/compress-project-memory.d.ts +1 -0
  56. package/dist/scripts/compress-project-memory.js +48 -0
  57. package/dist/scripts/context-ops.d.ts +2 -0
  58. package/dist/scripts/context-ops.js +464 -0
  59. package/dist/scripts/dev.d.ts +96 -0
  60. package/dist/scripts/dev.js +312 -0
  61. package/dist/scripts/extract-global-knowledge.d.ts +1 -0
  62. package/dist/scripts/extract-global-knowledge.js +43 -0
  63. package/dist/scripts/generate-dashboard.d.ts +1 -0
  64. package/dist/scripts/generate-dashboard.js +48 -0
  65. package/dist/scripts/governance-dashboard.d.ts +2 -0
  66. package/dist/scripts/governance-dashboard.js +36 -0
  67. package/dist/scripts/hook-guard-paths.d.ts +17 -0
  68. package/dist/scripts/hook-guard-paths.js +68 -0
  69. package/dist/scripts/hook-post-edit.d.ts +20 -0
  70. package/dist/scripts/hook-post-edit.js +70 -0
  71. package/dist/scripts/hook-session-start.d.ts +17 -0
  72. package/dist/scripts/hook-session-start.js +108 -0
  73. package/dist/scripts/hook-user-prompt.d.ts +22 -0
  74. package/dist/scripts/hook-user-prompt.js +193 -0
  75. package/dist/scripts/memory-schema.d.ts +6 -0
  76. package/{scripts/memory-schema.mjs → dist/scripts/memory-schema.js} +27 -20
  77. package/dist/scripts/query-universal-memory.d.ts +1 -0
  78. package/dist/scripts/query-universal-memory.js +44 -0
  79. package/dist/scripts/release-check.d.ts +14 -0
  80. package/dist/scripts/release-check.js +48 -0
  81. package/dist/scripts/spec-cli.d.ts +29 -0
  82. package/dist/scripts/spec-cli.js +261 -0
  83. package/dist/scripts/sprint-manager.d.ts +1 -0
  84. package/dist/scripts/sprint-manager.js +187 -0
  85. package/dist/scripts/sync-universal-memory.d.ts +1 -0
  86. package/dist/scripts/sync-universal-memory.js +277 -0
  87. package/dist/scripts/token-benchmark.d.ts +20 -0
  88. package/dist/scripts/token-benchmark.js +181 -0
  89. package/dist/scripts/tools-doctor.d.ts +20 -0
  90. package/dist/scripts/tools-doctor.js +120 -0
  91. package/memory/90-decisions/0028-governanca-visivel.md +84 -0
  92. package/package.json +54 -56
  93. package/specs/governanca-visivel/plan.md +122 -0
  94. package/specs/governanca-visivel/spec.md +112 -0
  95. package/specs/governanca-visivel/tasks.md +60 -0
  96. package/specs/ts-migration/plan.md +24 -13
  97. package/bin/create-memory-nest-kit.js +0 -125
  98. package/bin/forja.mjs +0 -143
  99. package/bin/init-project.js +0 -612
  100. package/lib/context-builder.js +0 -257
  101. package/lib/core/checks.mjs +0 -155
  102. package/lib/core/doc-graph.mjs +0 -231
  103. package/lib/core/health.mjs +0 -577
  104. package/lib/core/registry.mjs +0 -312
  105. package/lib/core/release.mjs +0 -492
  106. package/lib/templates/harness/code-intel.mjs +0 -119
  107. package/lib/templates/harness/mcp.json +0 -10
  108. package/lib/utils/file-helpers.js +0 -40
  109. package/lib/validators/structure-validator.js +0 -253
  110. package/lib/workspace.mjs +0 -213
  111. package/scripts/agent-harness.mjs +0 -580
  112. package/scripts/agent-router.mjs +0 -189
  113. package/scripts/build-smart-context.js +0 -87
  114. package/scripts/check-standards.js +0 -98
  115. package/scripts/compress-memory.mjs +0 -198
  116. package/scripts/compress-project-memory.js +0 -58
  117. package/scripts/context-ops.mjs +0 -466
  118. package/scripts/dev.mjs +0 -349
  119. package/scripts/extract-global-knowledge.js +0 -52
  120. package/scripts/generate-dashboard.js +0 -59
  121. package/scripts/hook-guard-paths.mjs +0 -76
  122. package/scripts/hook-post-edit.mjs +0 -79
  123. package/scripts/hook-session-start.mjs +0 -104
  124. package/scripts/hook-user-prompt.mjs +0 -185
  125. package/scripts/pre-commit.sh +0 -102
  126. package/scripts/query-universal-memory.js +0 -50
  127. package/scripts/release-check.mjs +0 -56
  128. package/scripts/spec-cli.mjs +0 -261
  129. package/scripts/sprint-manager.js +0 -200
  130. package/scripts/sync-universal-memory.js +0 -286
  131. package/scripts/token-benchmark.mjs +0 -203
  132. package/scripts/tools-doctor.mjs +0 -132
@@ -1,612 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * init-project.js
4
- *
5
- * Comando universal para inicializar novo projeto com agentes orquestrados.
6
- * Puxa configuração de Copilot, Claude, Gemini, Codex e outros.
7
- *
8
- * Uso:
9
- * node bin/init-project.js meu-projeto
10
- * node bin/init-project.js meu-projeto --ai copilot,claude,gemini
11
- * node bin/init-project.js meu-projeto --skip-backend
12
- * node bin/init-project.js --interactive
13
- */
14
-
15
- import fs from 'node:fs';
16
- import path from 'node:path';
17
- import process from 'node:process';
18
- import { execSync } from 'node:child_process';
19
- import { fileURLToPath } from 'node:url';
20
- import {
21
- getWorkspaceRoot,
22
- getProjectsDir,
23
- resolveProject,
24
- initWorkspace,
25
- getWorkspaceProjectsMemoryDir,
26
- assertOutsideFrameworkRepo,
27
- } from '../lib/workspace.mjs';
28
-
29
- const __filename = fileURLToPath(import.meta.url);
30
- const __dirname = path.dirname(__filename);
31
- const kitRoot = path.resolve(__dirname, '..');
32
-
33
- // ============================================================================
34
- // CONFIGURAÇÃO
35
- // ============================================================================
36
-
37
- const DEFAULT_AI_AGENTS = ['copilot', 'claude', 'gemini', 'codex'];
38
- // Conteúdo canônico único (ADR-0020): toda IA recebe a mesma explicação da
39
- // estrutura Forja; só o cabeçalho muda. CLAUDE.md do framework NÃO é copiado —
40
- // ele descreve o repo do motor, não o projeto gerado.
41
- const CANONICAL_INSTRUCTIONS = '.gemini-instructions.md';
42
- const AI_LABELS = {
43
- copilot: 'GitHub Copilot',
44
- claude: 'Claude',
45
- gemini: 'Gemini',
46
- codex: 'OpenAI Codex',
47
- };
48
-
49
- const SETUP_CHECKLIST = [
50
- '00-git-init',
51
- '01-generate-structure',
52
- '01b-copy-design-library',
53
- '01c-emit-harness',
54
- '02-copy-instructions',
55
- '03-install-backend',
56
- '04-init-memory-db',
57
- '05-build-context-pack',
58
- '06-universal-memory-sync',
59
- '07-show-next-steps',
60
- ];
61
-
62
- // ============================================================================
63
- // HELPERS
64
- // ============================================================================
65
-
66
- function log(msg, level = 'info') {
67
- const prefix = {
68
- info: '📌',
69
- success: '✅',
70
- warn: '⚠️',
71
- error: '❌',
72
- step: '🔄',
73
- done: '✨',
74
- }[level] || '→';
75
- console.log(`${prefix} ${msg}`);
76
- }
77
-
78
- function logSection(title) {
79
- console.log(`\n${'═'.repeat(80)}`);
80
- console.log(` ${title}`);
81
- console.log(`${'═'.repeat(80)}\n`);
82
- }
83
-
84
- function execCmd(cmd, opts = {}) {
85
- try {
86
- return execSync(cmd, {
87
- stdio: opts.quiet ? 'pipe' : 'inherit',
88
- ...opts
89
- });
90
- } catch (err) {
91
- if (!opts.ignoreError) {
92
- log(`Comando falhou: ${cmd}`, 'error');
93
- throw err;
94
- }
95
- }
96
- }
97
-
98
- function ensureDir(dir) {
99
- if (!fs.existsSync(dir)) {
100
- fs.mkdirSync(dir, { recursive: true });
101
- }
102
- }
103
-
104
- function copyFile(src, dest) {
105
- const content = fs.readFileSync(src, 'utf-8');
106
- fs.writeFileSync(dest, content, 'utf-8');
107
- }
108
-
109
- function copyFileIfExists(src, dest) {
110
- if (fs.existsSync(src)) {
111
- copyFile(src, dest);
112
- return true;
113
- }
114
- return false;
115
- }
116
-
117
- function copyDir(src, dest) {
118
- ensureDir(dest);
119
- const entries = fs.readdirSync(src, { withFileTypes: true });
120
-
121
- for (const entry of entries) {
122
- const srcPath = path.join(src, entry.name);
123
- const destPath = path.join(dest, entry.name);
124
-
125
- if (entry.isDirectory()) {
126
- copyDir(srcPath, destPath);
127
- } else {
128
- fs.copyFileSync(srcPath, destPath);
129
- }
130
- }
131
- }
132
-
133
- // ============================================================================
134
- // PARSEARGS
135
- // ============================================================================
136
-
137
- function parseArgs() {
138
- const args = process.argv.slice(2);
139
- const opts = {
140
- interactive: args.includes('--interactive'),
141
- skipBackend: args.includes('--skip-backend'),
142
- skipDb: args.includes('--skip-db'),
143
- skipGit: args.includes('--skip-git'),
144
- skipDesign: args.includes('--skip-design'),
145
- ai: DEFAULT_AI_AGENTS,
146
- verbose: args.includes('--verbose'),
147
- };
148
-
149
- // Parse --ai flag
150
- const aiIdx = args.findIndex(a => a === '--ai');
151
- if (aiIdx >= 0 && aiIdx + 1 < args.length) {
152
- opts.ai = args[aiIdx + 1].split(',').map(s => s.trim());
153
- }
154
-
155
- // Project name (primeiro arg sem --)
156
- const projectName = args.find(a => !a.startsWith('--'));
157
-
158
- // Projetos de produto vivem obrigatoriamente no workspace externo.
159
- // init-project nao aceita mais path customizado para evitar poluicao do repo do framework.
160
- const projectDir = projectName ? resolveProject(projectName) : null;
161
-
162
- return { projectName, projectPath: projectDir, opts };
163
- }
164
-
165
- // ============================================================================
166
- // SETUP STEPS
167
- // ============================================================================
168
-
169
- async function step00GitInit(projectDir, opts) {
170
- if (opts.skipGit) return;
171
-
172
- log('Preparando diretório...', 'step');
173
-
174
- ensureDir(projectDir);
175
-
176
- // Se for um sub-projeto dentro do repo principal, talvez não queira git init
177
- // Mas se for independente, git init faz sentido.
178
- // Como o usuário quer ignorar a pasta projects/, podemos opcionalmente dar git init.
179
-
180
- if (!fs.existsSync(path.join(projectDir, '.git'))) {
181
- try {
182
- execCmd(`cd "${projectDir}" && git init`, { quiet: true });
183
-
184
- // Criar .gitignore se não existir
185
- const gitignore = path.join(projectDir, '.gitignore');
186
- if (!fs.existsSync(gitignore)) {
187
- fs.writeFileSync(gitignore, `node_modules/\n.env\n.env.local\ndist/\n.DS_Store\n.context/\n.memory/\n`);
188
- }
189
-
190
- log('Git repository inicializado no projeto', 'success');
191
- } catch (e) {
192
- log('Aviso: falha ao rodar git init (talvez diretório já em repo git)', 'warn');
193
- }
194
- }
195
- }
196
-
197
- async function step01GenerateStructure(projectDir, opts) {
198
- log('Gerando estrutura de agentes e memória...', 'step');
199
-
200
- // Verifica se já existe código (ex: backend) para decidir se usa --only-memory
201
- const hasBackend = fs.existsSync(path.join(projectDir, 'backend')) || fs.existsSync(path.join(projectDir, 'package.json'));
202
- const onlyMemory = hasBackend ? '--only-memory' : '';
203
-
204
- const cmd = opts.skipBackend
205
- ? `node "${path.join(kitRoot, 'bin/create-memory-nest-kit.js')}" "${projectDir}" --only-memory --force`
206
- : `node "${path.join(kitRoot, 'bin/create-memory-nest-kit.js')}" "${projectDir}" ${onlyMemory} --force`;
207
-
208
- try {
209
- execCmd(cmd);
210
- log('Estrutura gerada com sucesso', 'success');
211
-
212
- // Adicionar camadas extras de escalonamento e growth
213
- addScalingLayers(projectDir);
214
- } catch (err) {
215
- log('Erro ao gerar estrutura', 'error');
216
- throw err;
217
- }
218
- }
219
-
220
- function addScalingLayers(projectDir) {
221
- const memoryDir = path.join(projectDir, 'memory');
222
-
223
- const layers = {
224
- '10-product/growth/vision.md': '# Estratégia de Growth\n\nDescreva como o produto irá crescer e atrair novos usuários.',
225
- '10-product/scaling/strategy.md': '# Estratégia de Escalonamento de Produto\n\nDescreva como o produto irá suportar o aumento de carga e usuários.',
226
- '20-architecture/scaling-patterns.md': '# Padrões de Escalonamento Arquitetural\n\n- Cache\n- Filas\n- Microsserviços\n- Otimização de Queries',
227
- };
228
-
229
- for (const [rel, content] of Object.entries(layers)) {
230
- const abs = path.join(memoryDir, rel);
231
- ensureDir(path.dirname(abs));
232
- if (!fs.existsSync(abs)) {
233
- fs.writeFileSync(abs, content, 'utf8');
234
- }
235
- }
236
- log('Camadas de Growth e Scaling adicionadas', 'success');
237
- }
238
-
239
- async function step01bCopyDesignLibrary(projectDir, opts) {
240
- if (opts.skipDesign) {
241
- log('Skipping design library copy (--skip-design)', 'warn');
242
- return;
243
- }
244
-
245
- const srcDesignDir = path.join(kitRoot, 'design-md');
246
- const destDesignDir = path.join(projectDir, 'design-md');
247
-
248
- if (!fs.existsSync(srcDesignDir)) {
249
- log('Biblioteca de design não encontrada no kit root', 'warn');
250
- return;
251
- }
252
-
253
- log('Copiando biblioteca de referências de design (design-md)...', 'step');
254
-
255
- try {
256
- copyDir(srcDesignDir, destDesignDir);
257
- log('Biblioteca design-md copiada para o projeto', 'success');
258
- } catch (err) {
259
- log('Erro ao copiar biblioteca de design', 'error');
260
- if (opts.verbose) console.error(err);
261
- }
262
- }
263
-
264
- // Camada de code intelligence + ferramentas de processo (ADR-0017, ADR-0018).
265
- // Cada projeto gerado herda codegraph (MCP) + scripts code:* + tools:doctor,
266
- // de forma auto-contida (so dependem do binario codegraph, opcional).
267
- const HARNESS_SCRIPTS = {
268
- 'code:index': 'codegraph init',
269
- 'code:sync': 'codegraph sync',
270
- 'code:status': 'codegraph status',
271
- 'code:query': 'codegraph query',
272
- 'code:check': 'node scripts/code-intel.mjs check',
273
- 'code:impact': 'node scripts/code-intel.mjs impact',
274
- 'tools:doctor': 'node scripts/tools-doctor.mjs',
275
- };
276
-
277
- async function step01cEmitHarness(projectDir, opts) {
278
- log('Emitindo harness de code intelligence (codegraph + tools)...', 'step');
279
-
280
- // 1. .mcp.json (codegraph) — aditivo, nao sobrescreve config existente
281
- const mcpDest = path.join(projectDir, '.mcp.json');
282
- const mcpSrc = path.join(kitRoot, 'lib/templates/harness/mcp.json');
283
- if (!fs.existsSync(mcpDest)) {
284
- copyFileIfExists(mcpSrc, mcpDest);
285
- }
286
-
287
- // 2. scripts auto-contidos
288
- const scriptsDir = path.join(projectDir, 'scripts');
289
- ensureDir(scriptsDir);
290
- copyFileIfExists(
291
- path.join(kitRoot, 'lib/templates/harness/code-intel.mjs'),
292
- path.join(scriptsDir, 'code-intel.mjs'),
293
- );
294
- copyFileIfExists(
295
- path.join(kitRoot, 'scripts/tools-doctor.mjs'),
296
- path.join(scriptsDir, 'tools-doctor.mjs'),
297
- );
298
-
299
- // 3. merge dos scripts no package.json (cria minimo se ausente)
300
- const pkgPath = path.join(projectDir, 'package.json');
301
- let pkg;
302
- if (fs.existsSync(pkgPath)) {
303
- try {
304
- pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
305
- } catch {
306
- log('package.json ilegivel; harness scripts nao injetados', 'warn');
307
- return;
308
- }
309
- } else {
310
- pkg = { name: path.basename(projectDir), version: '0.1.0', type: 'module', scripts: {} };
311
- }
312
- pkg.scripts = pkg.scripts || {};
313
- for (const [key, value] of Object.entries(HARNESS_SCRIPTS)) {
314
- if (!pkg.scripts[key]) pkg.scripts[key] = value;
315
- }
316
- fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
317
-
318
- log('Harness emitido: .mcp.json + code:* + tools:doctor', 'success');
319
- }
320
-
321
- async function step02CopyInstructions(projectDir, opts) {
322
- log('Copiando instruções para IAs...', 'step');
323
-
324
- const instructionsDir = path.join(projectDir, '.ia-instructions');
325
- ensureDir(instructionsDir);
326
-
327
- const canonicalPath = path.join(kitRoot, CANONICAL_INSTRUCTIONS);
328
- let canonical = null;
329
- if (fs.existsSync(canonicalPath)) {
330
- canonical = fs.readFileSync(canonicalPath, 'utf8');
331
- }
332
-
333
- let copied = 0;
334
- for (const ai of opts.ai) {
335
- const label = AI_LABELS[ai];
336
- if (!label || !canonical) {
337
- log(`${ai.toUpperCase()}: não encontrado`, 'warn');
338
- continue;
339
- }
340
-
341
- const others = Object.entries(AI_LABELS)
342
- .filter(([key]) => key !== ai)
343
- .map(([, name]) => name);
344
- const content = canonical
345
- .replace(/^# Instruções para .+ — Forja$/m, `# Instruções para ${label} — Forja`)
346
- .replace(
347
- /^> Guia para .+ multi-IA por design\.$/m,
348
- `> Guia para ${label} operar a Forja. O conteúdo é o mesmo para ${others.slice(0, -1).join(', ')} e ${others.at(-1)} — a Forja é multi-IA por design.`
349
- );
350
-
351
- fs.writeFileSync(path.join(instructionsDir, `${ai}.md`), content, 'utf8');
352
- log(`${ai.toUpperCase()}: ✓`, 'success');
353
- copied++;
354
- }
355
-
356
- // Criar INDEX
357
- const indexContent = `# IA Assistants Configuration
358
-
359
- Este diretório contém instruções específicas para cada IA assistant.
360
-
361
- ## Gestão de Cotas & Alternância
362
- Para trocar de IA (ex: se acabar a cota), use o arquivo [models.json](./models.json) para identificar o próximo motor na fila de fallback.
363
-
364
- ## IAs Configuradas
365
-
366
- ${opts.ai.map(ai => `- [${ai.toUpperCase()}](./${ai}.md)`).join('\n')}
367
- `;
368
-
369
- fs.writeFileSync(path.join(instructionsDir, 'README.md'), indexContent);
370
-
371
- // Criar models.json para interoperabilidade
372
- const modelsJson = {
373
- active_engine: opts.ai[0] || 'copilot',
374
- fallback_chain: opts.ai,
375
- engines: opts.ai.reduce((acc, ai) => {
376
- acc[ai] = {
377
- name: ai.toUpperCase(),
378
- instruction_file: `.ia-instructions/${ai}.md`,
379
- status: "ready"
380
- };
381
- return acc;
382
- }, {})
383
- };
384
- fs.writeFileSync(path.join(instructionsDir, 'models.json'), JSON.stringify(modelsJson, null, 2));
385
-
386
- log(`${copied} instruções copiadas para .ia-instructions/`, 'success');
387
- }
388
-
389
- async function step03InstallBackend(projectDir, opts) {
390
- if (opts.skipBackend) {
391
- log('Skipping backend install (--skip-backend)', 'warn');
392
- return;
393
- }
394
-
395
- const backendDir = path.join(projectDir, 'backend');
396
- if (!fs.existsSync(backendDir)) {
397
- log('Backend directory não encontrado', 'warn');
398
- return;
399
- }
400
-
401
- log('Instalando dependências do backend...', 'step');
402
-
403
- try {
404
- execCmd(`cd "${backendDir}" && npm install --quiet`, { quiet: true });
405
- log('npm install concluído', 'success');
406
- } catch (err) {
407
- log('Erro ao rodar npm install', 'error');
408
- if (!opts.verbose) {
409
- log('Use --verbose para mais detalhes', 'warn');
410
- }
411
- // Não falha o setup inteiro
412
- }
413
- }
414
-
415
- async function step04InitMemoryDb(projectDir, opts) {
416
- if (opts.skipDb || opts.skipBackend) {
417
- log('Skipping DB init', 'warn');
418
- return;
419
- }
420
-
421
- const backendDir = path.join(projectDir, 'backend');
422
- const scriptPath = path.join(backendDir, 'scripts/memory-db-init.mjs');
423
-
424
- if (!fs.existsSync(scriptPath)) {
425
- log('Script de init DB não encontrado', 'warn');
426
- return;
427
- }
428
-
429
- log('Inicializando banco de dados SQLite...', 'step');
430
-
431
- try {
432
- execCmd(`cd "${backendDir}" && npm run memory:db:init 2>/dev/null`, { quiet: true, ignoreError: true });
433
- log('SQLite inicializado em .memory/sqlite/context.db', 'success');
434
- } catch (err) {
435
- log('Erro ao inicializar DB', 'warn');
436
- }
437
- }
438
-
439
- async function step05BuildContextPack(projectDir, opts) {
440
- const scriptsDir = path.join(projectDir, 'scripts');
441
- const scriptPath = path.join(scriptsDir, 'build-context-pack.mjs');
442
-
443
- if (!fs.existsSync(scriptPath)) {
444
- log('Script context-pack não encontrado', 'warn');
445
- return;
446
- }
447
-
448
- log('Construindo context pack...', 'step');
449
-
450
- try {
451
- execCmd(`cd "${projectDir}" && node scripts/build-context-pack.mjs 2>/dev/null`, { quiet: true, ignoreError: true });
452
- log('Context pack criado em .context/context-pack.md', 'success');
453
- } catch (err) {
454
- log('Erro ao criar context pack', 'warn');
455
- }
456
- }
457
-
458
- async function step06UniversalMemorySync(projectDir, opts) {
459
- log('Sincronizando com Memória Universal...', 'step');
460
-
461
- const projectName = path.basename(projectDir);
462
- const rootMemoryDir = getWorkspaceProjectsMemoryDir();
463
- ensureDir(rootMemoryDir);
464
-
465
- const projectInfoFile = path.join(rootMemoryDir, `${projectName}.md`);
466
- const content = `# Projeto: ${projectName}\n\n- **Status**: Ativo\n- **Diretório**: ${projectDir}\n- **Workspace**: ${getWorkspaceRoot()}\n- **Criado em**: ${new Date().toISOString()}\n\n## Descrição\n(Descreva o projeto aqui)\n`;
467
-
468
- if (!fs.existsSync(projectInfoFile)) {
469
- fs.writeFileSync(projectInfoFile, content, 'utf8');
470
- }
471
-
472
- log(`Projeto ${projectName} registrado na Memória Universal do workspace`, 'success');
473
- }
474
-
475
- async function step07ShowNextSteps(projectDir, opts) {
476
- const relPath = path.relative(process.cwd(), projectDir) || '.';
477
-
478
- logSection('✨ SETUP COMPLETO!');
479
-
480
- console.log(`📁 Projeto criado em: ${relPath}\n`);
481
-
482
- console.log('📚 Próximos Passos:\n');
483
-
484
- console.log(` 1. Entrar no projeto:`);
485
- console.log(` cd ${relPath}\n`);
486
-
487
- console.log(` 2. Ver estrutura de memória:`);
488
- console.log(` ls -la memory/\n`);
489
-
490
- console.log(` 3. Carregar instruções para IA:`);
491
- console.log(` cat .ia-instructions/copilot.md`);
492
- console.log(` cat .ia-instructions/claude.md\n`);
493
-
494
- if (!opts.skipBackend) {
495
- console.log(` 4. Iniciar backend em dev mode:`);
496
- console.log(` cd backend && npm run start:dev\n`);
497
-
498
- console.log(` 5. Rodar testes:`);
499
- console.log(` cd backend && npm test\n`);
500
- }
501
-
502
- console.log(` 6. Atualizar documentação em memory/\n`);
503
-
504
- console.log(` 7. Sincronizar contexto com BD:`);
505
- console.log(` cd backend && npm run memory:db:sync\n`);
506
-
507
- console.log(` 8. Limpar memória antiga (Vacuum):`);
508
- console.log(` node scripts/memory-vacuum.mjs\n`);
509
-
510
- console.log(` 9. Consultar contexto:`);
511
- console.log(` cd backend && npm run memory:db:query -- "search" "auth" 10\n`);
512
-
513
- console.log('📖 Recursos:');
514
- console.log(` • Documentação: cat memory/README.md`);
515
- console.log(` • Agentes: cat AGENTS.md`);
516
- console.log(` • Decisões: cat memory/90-decisions/ADR-*.md\n`);
517
-
518
- console.log('🤖 Instruções para IAs:');
519
- for (const ai of opts.ai) {
520
- const aiFile = path.join(relPath, `.ia-instructions/${ai}.md`);
521
- console.log(` • ${ai.toUpperCase()}: .ia-instructions/${ai}.md`);
522
- }
523
-
524
- console.log('\n🚀 Tudo pronto! Comece a codificar!\n');
525
- }
526
-
527
- // ============================================================================
528
- // MAIN
529
- // ============================================================================
530
-
531
- async function main() {
532
- const { projectName, projectPath, opts } = parseArgs();
533
-
534
- if (!projectName && !opts.interactive) {
535
- console.log(`
536
- init-project v0.6.0 (Workspace separado)
537
-
538
- Cria projetos de produto no workspace Forja (padrão: ~/forja-workspace/projects).
539
- O repositório do framework permanece isolado.
540
-
541
- Uso: node bin/init-project.js <project-name> [opções]
542
-
543
- Opções:
544
- --ai <list> IAs para configurar (padrão: copilot,claude,gemini,codex)
545
- --skip-backend Pula instalação do backend NestJS
546
- --skip-db Pula inicialização do SQLite
547
- --skip-git Pula inicialização do Git
548
- --skip-design Pula cópia da biblioteca design-md
549
- --interactive Modo interativo
550
- --verbose Output detalhado
551
-
552
- Workspace:
553
- O caminho é resolvido por prioridade:
554
- 1. Variável de ambiente FORJA_WORKSPACE
555
- 2. Campo workspaceRoot em ~/.forjarc.json
556
- 3. Padrão: ~/forja-workspace
557
-
558
- Exemplos:
559
- node bin/init-project.js meu-projeto
560
- node bin/init-project.js meu-projeto --ai copilot,claude
561
- node bin/init-project.js meu-projeto --skip-backend
562
- node bin/init-project.js --interactive
563
- `);
564
- process.exit(0);
565
- }
566
-
567
- let target = projectName;
568
-
569
- // Interactive mode
570
- if (opts.interactive || !projectName) {
571
- logSection('🎯 Modo Interativo');
572
-
573
- // Simular input (em produção, usar package como prompt ou readline)
574
- target = projectName || 'meu-projeto';
575
- log(`Projeto: ${target}`, 'info');
576
- log(`IAs: ${opts.ai.join(', ')}`, 'info');
577
- }
578
-
579
- // Garante workspace pronto
580
- initWorkspace();
581
-
582
- const projectDir = projectPath || resolveProject(target);
583
- assertOutsideFrameworkRepo(projectDir, 'init-project');
584
-
585
- logSection('🚀 Inicializando Novo Projeto com Agentes Orquestrados');
586
- log(`Workspace ativo: ${getWorkspaceRoot()}`, 'info');
587
- log(`Projeto: ${projectDir}`, 'info');
588
-
589
- try {
590
- // Executar checklist de setup
591
- for (const step of SETUP_CHECKLIST) {
592
- if (step === '00-git-init') await step00GitInit(projectDir, opts);
593
- else if (step === '01-generate-structure') await step01GenerateStructure(projectDir, opts);
594
- else if (step === '01b-copy-design-library') await step01bCopyDesignLibrary(projectDir, opts);
595
- else if (step === '01c-emit-harness') await step01cEmitHarness(projectDir, opts);
596
- else if (step === '02-copy-instructions') await step02CopyInstructions(projectDir, opts);
597
- else if (step === '03-install-backend') await step03InstallBackend(projectDir, opts);
598
- else if (step === '04-init-memory-db') await step04InitMemoryDb(projectDir, opts);
599
- else if (step === '05-build-context-pack') await step05BuildContextPack(projectDir, opts);
600
- else if (step === '06-universal-memory-sync') await step06UniversalMemorySync(projectDir, opts);
601
- else if (step === '07-show-next-steps') await step07ShowNextSteps(projectDir, opts);
602
- }
603
-
604
- log('Init completo!', 'done');
605
- process.exit(0);
606
- } catch (err) {
607
- console.error('\n❌ Erro durante setup:', err.message);
608
- process.exit(1);
609
- }
610
- }
611
-
612
- main();