forjajs 4.1.2 → 5.0.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 (180) hide show
  1. package/.claude/settings.json +2 -2
  2. package/.gemini-instructions.md +1 -1
  3. package/.github/copilot-instructions.md +1 -1
  4. package/.openai-instructions.md +1 -1
  5. package/CHANGELOG.md +139 -0
  6. package/DOC-MAP.md +2 -2
  7. package/README.md +62 -10
  8. package/README.pt-BR.md +46 -7
  9. package/boilerplates/01-api-rest/README.md +1 -1
  10. package/boilerplates/06-clean-arch/README.md +5 -3
  11. package/boilerplates/06-clean-arch/backend/.oxlintrc.json +10 -0
  12. package/boilerplates/06-clean-arch/backend/nest-cli.json +8 -0
  13. package/boilerplates/06-clean-arch/backend/package.json +22 -24
  14. package/boilerplates/06-clean-arch/backend/src/app.module.ts +4 -4
  15. package/boilerplates/06-clean-arch/backend/src/main.ts +2 -2
  16. package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts +4 -4
  17. package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts +2 -2
  18. package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.entity.ts +3 -3
  19. package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.repository.ts +1 -1
  20. package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/typeorm-order.repository.ts +5 -5
  21. package/boilerplates/06-clean-arch/backend/src/modules/orders/orders.module.ts +6 -6
  22. package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts +3 -3
  23. package/boilerplates/06-clean-arch/backend/src/modules/products/products.controller.ts +1 -1
  24. package/boilerplates/06-clean-arch/backend/src/modules/products/products.module.ts +2 -2
  25. package/boilerplates/06-clean-arch/backend/test/orders/place-order.spec.ts +2 -2
  26. package/boilerplates/06-clean-arch/backend/tsconfig.build.json +15 -0
  27. package/boilerplates/06-clean-arch/backend/tsconfig.json +24 -10
  28. package/boilerplates/06-clean-arch/backend/vitest.config.ts +11 -0
  29. package/boilerplates/06-clean-arch/boilerplate.manifest.json +6 -5
  30. package/boilerplates/README.md +24 -44
  31. package/dist/apps/cli/src/index.js +6 -6
  32. package/dist/apps/dashboard/next.config.d.mts +5 -5
  33. package/dist/apps/server/src/app.module.js +1 -1
  34. package/dist/apps/server/src/forja-nest.module.js +1 -1
  35. package/dist/apps/server/src/index.js +1 -1
  36. package/dist/apps/server/src/main.js +20 -20
  37. package/dist/apps/worker/src/main.js +4 -4
  38. package/dist/bin/create-memory-nest-kit.js +5 -5
  39. package/dist/bin/forja.js +28 -14
  40. package/dist/bin/init-project.d.ts +4 -9
  41. package/dist/bin/init-project.js +126 -182
  42. package/dist/lib/audit.js +1 -1
  43. package/dist/lib/context-builder.d.ts +6 -1
  44. package/dist/lib/context-builder.js +21 -12
  45. package/dist/lib/core/architecture-gate.js +2 -4
  46. package/dist/lib/core/checks.d.ts +1 -1
  47. package/dist/lib/core/drift-gate.js +2 -4
  48. package/dist/lib/core/gates.js +5 -5
  49. package/dist/lib/core/health.d.ts +0 -1
  50. package/dist/lib/core/health.js +33 -7
  51. package/dist/lib/core/journey.d.ts +30 -0
  52. package/dist/lib/core/journey.js +142 -0
  53. package/dist/lib/core/model-pricing.js +3 -5
  54. package/dist/lib/core/project-smoke.d.ts +6 -2
  55. package/dist/lib/core/project-smoke.js +60 -61
  56. package/dist/lib/core/registry.d.ts +1 -12
  57. package/dist/lib/core/registry.js +42 -32
  58. package/dist/lib/core/release.d.ts +1 -1
  59. package/dist/lib/core/release.js +31 -3
  60. package/dist/lib/core/risk-collect.js +4 -4
  61. package/dist/lib/drift-sentinel.js +1 -1
  62. package/dist/lib/generators/memory-generator.d.ts +30 -30
  63. package/dist/lib/generators/memory-generator.js +19 -8
  64. package/dist/lib/generators/nest-generator.js +192 -275
  65. package/dist/lib/generators/readme-generator.js +1 -1
  66. package/dist/lib/governance-report.js +4 -4
  67. package/dist/lib/handoffs-index.d.ts +16 -2
  68. package/dist/lib/handoffs-index.js +32 -5
  69. package/dist/lib/llm/session.js +1 -1
  70. package/dist/lib/llm/validation.js +1 -1
  71. package/dist/lib/memory-audit.js +1 -1
  72. package/dist/lib/paths.d.ts +39 -0
  73. package/dist/lib/paths.js +73 -0
  74. package/dist/lib/project-upgrade.d.ts +0 -4
  75. package/dist/lib/project-upgrade.js +19 -1
  76. package/dist/lib/project-wiring.d.ts +54 -0
  77. package/dist/lib/project-wiring.js +391 -0
  78. package/dist/lib/status-model.js +18 -7
  79. package/dist/lib/templates.d.ts +24 -0
  80. package/dist/lib/templates.js +77 -0
  81. package/dist/lib/validators/structure-validator.js +0 -1
  82. package/dist/lib/workspace.d.ts +7 -0
  83. package/dist/lib/workspace.js +20 -2
  84. package/dist/packages/adapter-git/src/index.js +2 -2
  85. package/dist/packages/context/src/index.js +1 -1
  86. package/dist/packages/core/src/index.js +1 -1
  87. package/dist/packages/evals/src/index.js +1 -1
  88. package/dist/packages/events/src/index.js +1 -1
  89. package/dist/packages/graph/src/index.js +1 -1
  90. package/dist/packages/mcp/src/index.d.ts +1 -1
  91. package/dist/packages/observability/src/index.js +1 -1
  92. package/dist/packages/orchestration/src/index.js +1 -1
  93. package/dist/packages/planner/src/index.js +1 -1
  94. package/dist/packages/policy/src/index.js +1 -1
  95. package/dist/packages/runtime/src/index.js +1 -1
  96. package/dist/packages/sandbox/src/index.js +1 -1
  97. package/dist/packages/validator/src/index.js +1 -1
  98. package/dist/scripts/adr.js +4 -4
  99. package/dist/scripts/agent-harness.js +30 -23
  100. package/dist/scripts/agent-router.js +22 -5
  101. package/dist/scripts/agent.js +5 -5
  102. package/dist/scripts/architecture.js +6 -6
  103. package/dist/scripts/audit-query.js +1 -1
  104. package/dist/scripts/audit-sync.js +1 -1
  105. package/dist/scripts/build-smart-context.d.ts +19 -1
  106. package/dist/scripts/build-smart-context.js +84 -68
  107. package/dist/scripts/check-standards.js +8 -3
  108. package/dist/scripts/code-context.js +1 -1
  109. package/dist/scripts/compress-memory.js +3 -2
  110. package/dist/scripts/compress-project-memory.js +2 -2
  111. package/dist/scripts/context-ops.js +13 -5
  112. package/dist/scripts/cost-economy.js +4 -4
  113. package/dist/scripts/demo-autonomy.js +11 -11
  114. package/dist/scripts/demo-workspace.js +12 -4
  115. package/dist/scripts/dev.js +8 -7
  116. package/dist/scripts/drift-check.js +5 -5
  117. package/dist/scripts/engineer.js +11 -11
  118. package/dist/scripts/evidence.js +4 -4
  119. package/dist/scripts/extract-global-knowledge.js +6 -4
  120. package/dist/scripts/forja-setup.js +2 -1
  121. package/dist/scripts/forja-status.js +5 -4
  122. package/dist/scripts/gates.js +1 -1
  123. package/dist/scripts/generate-dashboard.js +6 -4
  124. package/dist/scripts/governance-dashboard.js +2 -2
  125. package/dist/scripts/hook-session-start.js +11 -10
  126. package/dist/scripts/hook-user-prompt.js +3 -2
  127. package/dist/scripts/incident.js +4 -4
  128. package/dist/scripts/llm-fit.js +11 -11
  129. package/dist/scripts/memory-audit.js +1 -1
  130. package/dist/scripts/memory-schema.js +3 -2
  131. package/dist/scripts/orchestrate.js +4 -5
  132. package/dist/scripts/project-smoke.js +13 -2
  133. package/dist/scripts/project-templates.d.ts +1 -0
  134. package/dist/scripts/project-templates.js +20 -0
  135. package/dist/scripts/project-upgrade.d.ts +13 -0
  136. package/dist/scripts/project-upgrade.js +110 -40
  137. package/dist/scripts/project-wire.d.ts +8 -0
  138. package/dist/scripts/project-wire.js +55 -0
  139. package/dist/scripts/provenance.js +3 -3
  140. package/dist/scripts/query-universal-memory.js +7 -4
  141. package/dist/scripts/release-check.js +1 -1
  142. package/dist/scripts/risk.js +4 -4
  143. package/dist/scripts/simulate.js +9 -9
  144. package/dist/scripts/spec-cli.d.ts +1 -0
  145. package/dist/scripts/spec-cli.js +25 -5
  146. package/dist/scripts/sprint-manager.js +4 -3
  147. package/dist/scripts/sync-universal-memory.js +22 -15
  148. package/dist/scripts/token-benchmark.js +4 -3
  149. package/dist/scripts/token-economy.js +4 -3
  150. package/dist/scripts/tools-doctor.d.ts +1 -1
  151. package/dist/scripts/tools-doctor.js +25 -3
  152. package/docs/GUIA-ONBOARDING-EXECUTIVO.md +1 -2
  153. package/docs/GUIA-ONBOARDING-OPERACIONAL-PAPEIS.md +5 -6
  154. package/docs/GUIA-ONBOARDING-PROJETO.md +7 -9
  155. package/docs/glossary.md +4 -4
  156. package/docs/init-project.md +88 -444
  157. package/docs/manual-operacional-cli-sdd-gsd.md +1 -1
  158. package/docs/modos-de-operacao.md +1 -1
  159. package/docs/processo-projeto.md +14 -11
  160. package/docs/produto/roteiro-demo.md +15 -18
  161. package/docs/publishing.md +5 -0
  162. package/docs/quick-reference.md +15 -23
  163. package/docs/structure.md +16 -30
  164. package/lib/core/model-pricing.json +19 -0
  165. package/memory/30-projects/README.md +1 -1
  166. package/memory/90-decisions/0022-congelar-dashboard-web.md +1 -1
  167. package/memory/90-decisions/0086-projeto-conectado-e-jornada-como-gate.md +95 -0
  168. package/memory/90-decisions/0087-remover-dashboard-legado.md +35 -0
  169. package/memory/90-decisions/0088-templates-validados.md +55 -0
  170. package/package.json +26 -26
  171. package/templates/project/AGENTS.md +75 -0
  172. package/templates/project/CLAUDE.md +9 -0
  173. package/templates/project/agents/context-engineer.md +15 -0
  174. package/templates/project/agents/governance.md +15 -0
  175. package/templates/project/agents/marketing.md +15 -0
  176. package/templates/project/agents/orchestrator.md +15 -0
  177. package/templates/project/agents/product.md +15 -0
  178. package/templates/project/agents/sdd-architect.md +15 -0
  179. package/dist/lib/multi-ai-instructions.d.ts +0 -28
  180. package/dist/lib/multi-ai-instructions.js +0 -83
@@ -0,0 +1,20 @@
1
+ /**
2
+ * forja project:templates — os boilerplates e o que dá para fazer com cada um (ADR-0088).
3
+ * Template validado: `forja project:new <nome> --template <t>`. Referência: consulta/adaptação.
4
+ */
5
+ import { listTemplates } from '../lib/templates.js';
6
+ const all = listTemplates();
7
+ if (process.argv.includes('--json')) {
8
+ console.log(JSON.stringify(all.map(({ dir, ...t }) => t), null, 2));
9
+ }
10
+ else {
11
+ const ready = all.filter((t) => t.ready);
12
+ console.log('Templates (forja project:new <nome> --template <template>):');
13
+ for (const t of ready)
14
+ console.log(` ${t.name.replace(/^\d+-/, '').padEnd(24)} ${t.title}${t.stack.length ? ` — ${t.stack.join(', ')}` : ''}`);
15
+ if (!ready.length)
16
+ console.log(' (nenhum)');
17
+ console.log('\nReferência (consulte em boilerplates/<nome>/; ainda sem validação de build):');
18
+ for (const t of all.filter((x) => !x.ready))
19
+ console.log(` ${t.name.padEnd(26)} ${t.title}`);
20
+ }
@@ -5,7 +5,20 @@
5
5
  * forja project:upgrade dry-run: lista o que falta (cwd)
6
6
  * forja project:upgrade --apply copia as peças novas
7
7
  * forja project:upgrade --project <path> aponta para outro projeto
8
+ * forja project:upgrade --all [--apply] todos os projetos do workspace, com relatório
8
9
  *
9
10
  * Aditivo, nunca sobrescreve: só traz arquivos que o projeto não tem. O código do usuário é intocável.
11
+ * Desde a v5 também religa o projeto à inteligência do Forja (project:wire): instruções nativas,
12
+ * hooks, sub-agents e MCP — a migração de projetos gerados antes da v5 (ADR-0086).
10
13
  */
14
+ interface UpgradeReport {
15
+ readonly target: string;
16
+ readonly status: 'em-dia' | 'pendente' | 'aplicado' | 'nao-forja' | 'erro';
17
+ readonly newFiles: string[];
18
+ readonly wiringGaps: string[];
19
+ readonly applied: number;
20
+ readonly wired: number;
21
+ readonly error?: string;
22
+ }
23
+ export declare function upgradeProject(target: string, apply: boolean): UpgradeReport;
11
24
  export {};
@@ -5,61 +5,131 @@
5
5
  * forja project:upgrade dry-run: lista o que falta (cwd)
6
6
  * forja project:upgrade --apply copia as peças novas
7
7
  * forja project:upgrade --project <path> aponta para outro projeto
8
+ * forja project:upgrade --all [--apply] todos os projetos do workspace, com relatório
8
9
  *
9
10
  * Aditivo, nunca sobrescreve: só traz arquivos que o projeto não tem. O código do usuário é intocável.
11
+ * Desde a v5 também religa o projeto à inteligência do Forja (project:wire): instruções nativas,
12
+ * hooks, sub-agents e MCP — a migração de projetos gerados antes da v5 (ADR-0086).
10
13
  */
11
14
  import { execFileSync } from 'node:child_process';
12
15
  import fs from 'node:fs';
13
16
  import os from 'node:os';
14
17
  import path from 'node:path';
15
- import { fileURLToPath } from 'node:url';
16
- import { planUpgrade, applyUpgrade } from "../lib/project-upgrade.js";
17
- import { resolveScript } from "../lib/core/registry.js";
18
- const __filename = fileURLToPath(import.meta.url);
19
- const repoRoot = path.resolve(path.dirname(__filename), '..');
20
- function main() {
21
- const i = process.argv.indexOf('--project');
22
- const target = path.resolve(i >= 0 ? process.argv[i + 1] : process.cwd());
23
- const apply = process.argv.includes('--apply');
18
+ import { planUpgrade, applyUpgrade } from '../lib/project-upgrade.js';
19
+ import { COMMANDS } from '../lib/core/registry.js';
20
+ import { wireProject, checkProjectWiring, detectWiredAi } from '../lib/project-wiring.js';
21
+ import { getProjectsDir, listProjects } from '../lib/workspace.js';
22
+ import { script } from '../lib/paths.js';
23
+ /**
24
+ * Scaffold de referência num tmp isolado (ambiente limpo, a lição do release:check). Sempre sem
25
+ * backend: o upgrade traz a camada do Forja (memória, agentes, prompts, skills, scripts) e nunca
26
+ * toca `backend/`, que é código do usuário — e pode nem ser NestJS (um backend Python receberia um
27
+ * app Nest inteiro com o critério antigo "tem pasta backend → traz o scaffold do backend").
28
+ */
29
+ function freshScaffold(tmp) {
30
+ const fresh = path.join(tmp, 'fresh');
31
+ const env = { ...process.env };
32
+ delete env.NODE_PATH;
33
+ for (const k of Object.keys(env))
34
+ if (k.startsWith('npm_'))
35
+ delete env[k];
36
+ const args = [script('bin/create-memory-nest-kit'), fresh, '--only-memory', '--force'];
37
+ try {
38
+ execFileSync(process.execPath, args, { cwd: tmp, env, stdio: 'pipe' });
39
+ }
40
+ catch (e) {
41
+ const out = `${e.stdout ?? ''}${e.stderr ?? ''}`.trim().split('\n').slice(-15).join('\n');
42
+ throw new Error(`o gerador de referência falhou — nada foi alterado.\n${out}`);
43
+ }
44
+ return fresh;
45
+ }
46
+ export function upgradeProject(target, apply) {
47
+ const base = { target, newFiles: [], wiringGaps: [], applied: 0, wired: 0 };
24
48
  if (!fs.existsSync(path.join(target, 'AGENTS.md'))) {
25
- console.error(`${target} não parece um projeto Forja (sem AGENTS.md).`);
26
- console.error('Rode dentro de um projeto gerado, ou aponte com --project <path>.');
27
- process.exit(1);
49
+ return { ...base, status: 'nao-forja', error: 'ainda não usa o Forja (sem AGENTS.md) — entre nele e rode forja project:wire' };
28
50
  }
29
- // Gera um scaffold fresco num tmp isolado, com o ambiente limpo (a lição do release:check).
30
51
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-upgrade-'));
31
- const fresh = path.join(tmp, 'fresh');
32
52
  try {
33
- const env = { ...process.env };
34
- delete env.NODE_PATH;
35
- for (const k of Object.keys(env))
36
- if (k.startsWith('npm_'))
37
- delete env[k];
38
- // resolveScript acha .ts em dev e dist/bin/create-memory-nest-kit.js no publicado — cravar .ts
39
- // quebrava o comando instalado com module-not-found (o dist não tem .ts).
40
- const generator = resolveScript(repoRoot, 'bin/create-memory-nest-kit');
41
- execFileSync(process.execPath, [generator, fresh, '--force'], {
42
- cwd: tmp,
43
- env,
44
- stdio: 'pipe',
45
- });
53
+ const fresh = freshScaffold(tmp);
46
54
  const plan = planUpgrade(fresh, target);
47
- if (!plan.newFiles.length) {
48
- console.log(`Projeto já em dia — ${plan.existing} arquivo(s) de scaffold presentes, nenhuma peça nova.`);
49
- return;
50
- }
51
- console.log(`${plan.newFiles.length} peça(s) de scaffold nova(s) que este projeto ainda não tem:\n`);
52
- for (const rel of plan.newFiles)
53
- console.log(` + ${rel}`);
54
- if (!apply) {
55
- console.log(`\nDry-run. Rode com --apply para copiar. Aditivo: nada existente é sobrescrito.`);
56
- return;
57
- }
58
- const applied = applyUpgrade(fresh, target, plan);
59
- console.log(`\n✓ ${applied.length} arquivo(s) copiado(s). Revise o diff antes de commitar.`);
55
+ const ai = detectWiredAi(target);
56
+ const wiringGaps = checkProjectWiring(target, { commands: COMMANDS, ai: ai.length ? ai : undefined })
57
+ .filter((c) => c.status === 'fail')
58
+ .map((c) => `${c.id}: ${c.detail}`);
59
+ if (!plan.newFiles.length && !wiringGaps.length)
60
+ return { ...base, status: 'em-dia' };
61
+ if (!apply)
62
+ return { ...base, status: 'pendente', newFiles: plan.newFiles, wiringGaps };
63
+ const applied = applyUpgrade(fresh, target, plan).length;
64
+ const wired = wireProject(target, { ai: ai.length ? ai : undefined }).filter((c) => c.action !== 'unchanged').length;
65
+ return { ...base, status: 'aplicado', newFiles: plan.newFiles, wiringGaps, applied, wired };
66
+ }
67
+ catch (e) {
68
+ return { ...base, status: 'erro', error: e.message };
60
69
  }
61
70
  finally {
62
71
  fs.rmSync(tmp, { recursive: true, force: true });
63
72
  }
64
73
  }
74
+ function printOne(r, apply) {
75
+ if (r.status === 'erro' || r.status === 'nao-forja') {
76
+ console.error(`${r.target}: ${r.error}`);
77
+ return;
78
+ }
79
+ if (r.status === 'em-dia') {
80
+ console.log('Projeto já em dia — scaffold completo e conexão com a IA em ordem.');
81
+ return;
82
+ }
83
+ if (r.newFiles.length) {
84
+ console.log(`${r.newFiles.length} peça(s) de scaffold nova(s) que este projeto ainda não tem:\n`);
85
+ for (const rel of r.newFiles)
86
+ console.log(` + ${rel}`);
87
+ }
88
+ if (r.wiringGaps.length) {
89
+ console.log('\nConexão com a IA a refazer (project:wire):');
90
+ for (const g of r.wiringGaps)
91
+ console.log(` ~ ${g}`);
92
+ }
93
+ if (!apply)
94
+ console.log('\nDry-run. Rode com --apply para aplicar. Arquivos do usuário não são sobrescritos; nos de instrução só o bloco forja:begin/end muda.');
95
+ else
96
+ console.log(`\n✓ ${r.applied} arquivo(s) copiado(s), ${r.wired} de conexão escrito(s). Revise o diff antes de commitar.`);
97
+ }
98
+ function main() {
99
+ const argv = process.argv.slice(2);
100
+ const apply = argv.includes('--apply');
101
+ const json = argv.includes('--json');
102
+ if (argv.includes('--all')) {
103
+ const names = listProjects();
104
+ if (!names.length) {
105
+ console.log(`Nenhum projeto em ${getProjectsDir()}.`);
106
+ return;
107
+ }
108
+ const reports = names.map((n) => ({ name: n, ...upgradeProject(path.join(getProjectsDir(), n), apply) }));
109
+ if (json) {
110
+ console.log(JSON.stringify(reports, null, 2));
111
+ }
112
+ else {
113
+ console.log(`${apply ? 'Upgrade' : 'Dry-run'} de ${names.length} projeto(s) em ${getProjectsDir()}:\n`);
114
+ for (const r of reports) {
115
+ const what = r.status === 'erro' || r.status === 'nao-forja' ? r.error
116
+ : r.status === 'em-dia' ? 'em dia'
117
+ : r.status === 'pendente' ? `${r.newFiles.length} peça(s) nova(s), ${r.wiringGaps.length} lacuna(s) de conexão`
118
+ : `${r.applied} copiada(s), ${r.wired} de conexão`;
119
+ console.log(` ${r.status.padEnd(9)} ${r.name.padEnd(32)} ${what}`);
120
+ }
121
+ if (!apply && reports.some((r) => r.status === 'pendente'))
122
+ console.log('\nDry-run. Detalhe de um: cd <projeto> && forja project:upgrade · aplicar em todos: --all --apply');
123
+ }
124
+ process.exit(reports.some((r) => r.status === 'erro') ? 1 : 0);
125
+ }
126
+ const i = argv.indexOf('--project');
127
+ const target = path.resolve(i >= 0 ? argv[i + 1] : process.cwd());
128
+ const report = upgradeProject(target, apply);
129
+ if (json)
130
+ console.log(JSON.stringify(report, null, 2));
131
+ else
132
+ printOne(report, apply);
133
+ process.exit(report.status === 'erro' || report.status === 'nao-forja' ? 1 : 0);
134
+ }
65
135
  main();
@@ -0,0 +1,8 @@
1
+ /**
2
+ * forja project:wire — conecta (ou verifica) o projeto do cwd à inteligência do Forja (ADR-0086).
3
+ *
4
+ * forja project:wire escreve/atualiza instruções, hooks, sub-agents, MCP
5
+ * forja project:wire --ai claude,codex escolhe as IAs (padrão: as já conectadas, ou todas)
6
+ * forja project:wire --check [--json] só verifica; exit 1 se algo essencial está desligado
7
+ */
8
+ export {};
@@ -0,0 +1,55 @@
1
+ /**
2
+ * forja project:wire — conecta (ou verifica) o projeto do cwd à inteligência do Forja (ADR-0086).
3
+ *
4
+ * forja project:wire escreve/atualiza instruções, hooks, sub-agents, MCP
5
+ * forja project:wire --ai claude,codex escolhe as IAs (padrão: as já conectadas, ou todas)
6
+ * forja project:wire --check [--json] só verifica; exit 1 se algo essencial está desligado
7
+ */
8
+ import process from 'node:process';
9
+ import { COMMANDS } from '../lib/core/registry.js';
10
+ import { wireProject, checkProjectWiring, detectWiredAi } from '../lib/project-wiring.js';
11
+ import { isInsideFrameworkRepo } from '../lib/workspace.js';
12
+ function fail(msg) {
13
+ console.error(msg);
14
+ process.exit(1);
15
+ }
16
+ const argv = process.argv.slice(2);
17
+ const check = argv.includes('--check');
18
+ const json = argv.includes('--json');
19
+ const aiIdx = argv.indexOf('--ai');
20
+ const ai = aiIdx >= 0 ? (argv[aiIdx + 1] ?? fail('--ai exige uma lista: claude,codex,gemini,copilot')).split(',') : undefined;
21
+ const dir = process.cwd();
22
+ if (isInsideFrameworkRepo(dir)) {
23
+ fail('project:wire opera um projeto, não o repositório do framework. Rode dentro do projeto (ou use forja project:new).');
24
+ }
25
+ if (!check) {
26
+ let changes;
27
+ try {
28
+ changes = wireProject(dir, { ai: ai ?? (detectWiredAi(dir).length ? detectWiredAi(dir) : undefined) });
29
+ }
30
+ catch (e) {
31
+ fail(e.message);
32
+ }
33
+ if (json) {
34
+ console.log(JSON.stringify({ changes }, null, 2));
35
+ }
36
+ else {
37
+ for (const c of changes)
38
+ if (c.action !== 'unchanged')
39
+ console.log(`${c.action === 'created' ? '+' : '~'} ${c.file}`);
40
+ const touched = changes.filter((c) => c.action !== 'unchanged').length;
41
+ console.log(touched ? `✓ projeto conectado (${touched} arquivo(s))` : '✓ projeto já estava conectado');
42
+ }
43
+ }
44
+ const checks = checkProjectWiring(dir, { commands: COMMANDS, ai });
45
+ const failed = checks.filter((c) => c.status === 'fail');
46
+ if (json && check) {
47
+ console.log(JSON.stringify({ ok: failed.length === 0, checks }, null, 2));
48
+ }
49
+ else if (check || failed.length) {
50
+ for (const c of checks)
51
+ console.log(`${c.status === 'ok' ? 'OK ' : c.status === 'warn' ? 'WARN' : 'FAIL'} ${c.id.padEnd(14)} ${c.detail}`);
52
+ if (failed.length)
53
+ console.log('\nCorrija com: forja project:wire');
54
+ }
55
+ process.exit(failed.length ? 1 : 0);
@@ -13,9 +13,9 @@
13
13
  */
14
14
  import fs from 'node:fs';
15
15
  import Database from 'better-sqlite3';
16
- import { extractProvenance } from "../packages/engineering/provenance/src/index.js";
17
- import { SqliteMigrationRunner, SqliteProvenanceStore, SqliteRuntimeRunStore } from "../packages/adapter-sqlite/src/index.js";
18
- import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
16
+ import { extractProvenance } from '../packages/engineering/provenance/src/index.js';
17
+ import { SqliteMigrationRunner, SqliteProvenanceStore, SqliteRuntimeRunStore } from '../packages/adapter-sqlite/src/index.js';
18
+ import { getWorkspaceDbDir, getWorkspaceDbPath } from '../lib/workspace.js';
19
19
  function openDatabase() {
20
20
  fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
21
21
  const database = new Database(process.env.FORJA_RUNTIME_DB ?? getWorkspaceDbPath());
@@ -1,13 +1,14 @@
1
1
  import Database from 'better-sqlite3';
2
- import { getDbPath, ensureSchema } from "./memory-schema.js";
2
+ import { getDbPath, ensureSchema } from './memory-schema.js';
3
+ import { ftsQuery } from '../lib/context-builder.js';
3
4
  ensureSchema({ silent: true });
4
5
  const dbPath = getDbPath();
5
6
  const args = process.argv.slice(2);
6
7
  const query = args[0] || '';
7
8
  const limit = Number(args[1] || 5);
8
9
  if (!query) {
9
- console.log('Uso: node scripts/query-universal-memory.js "termo de busca" [limite]');
10
- process.exit(0);
10
+ console.error('Uso: forja query:universal "termo de busca" [limite]');
11
+ process.exit(1);
11
12
  }
12
13
  const db = new Database(dbPath, { readonly: true });
13
14
  const search = db.prepare(`
@@ -25,7 +26,8 @@ const search = db.prepare(`
25
26
  LIMIT ?
26
27
  `);
27
28
  try {
28
- const results = search.all(query, limit);
29
+ // Termo livre → FTS seguro (`pix-qr`, `auth:jwt` eram sintaxe inválida e a busca lançava).
30
+ const results = search.all(ftsQuery(query), limit);
29
31
  if (results.length === 0) {
30
32
  console.log(`Nenhum resultado encontrado para: "${query}"`);
31
33
  }
@@ -40,5 +42,6 @@ try {
40
42
  }
41
43
  catch (e) {
42
44
  console.error('Erro na busca:', e.message);
45
+ process.exitCode = 1;
43
46
  }
44
47
  db.close();
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * Diagnostica e autoriza; nunca publica. `npm publish` continua sendo um ato humano.
13
13
  */
14
- import { runReleaseChecks, worstStatus } from "../lib/core/release.js";
14
+ import { runReleaseChecks, worstStatus } from '../lib/core/release.js';
15
15
  const TAG = { ok: 'OK ', warn: 'AVISO', fail: 'FALHA', skipped: '— ' };
16
16
  async function main() {
17
17
  const publish = process.argv.includes('--publish');
@@ -16,10 +16,10 @@ import fs from 'node:fs';
16
16
  import path from 'node:path';
17
17
  import { randomUUID } from 'node:crypto';
18
18
  import Database from 'better-sqlite3';
19
- import { assessRisk, explainAssessment } from "../packages/engineering/risk/src/index.js";
20
- import { SqliteMigrationRunner } from "../packages/adapter-sqlite/src/index.js";
21
- import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
22
- import { buildRiskInput, changedFiles, graphRoot } from "../lib/core/risk-collect.js";
19
+ import { assessRisk, explainAssessment } from '../packages/engineering/risk/src/index.js';
20
+ import { SqliteMigrationRunner } from '../packages/adapter-sqlite/src/index.js';
21
+ import { getWorkspaceDbDir, getWorkspaceDbPath } from '../lib/workspace.js';
22
+ import { buildRiskInput, changedFiles, graphRoot } from '../lib/core/risk-collect.js';
23
23
  const RISK_DIR = '.context/risk';
24
24
  function assessmentPath(id) {
25
25
  return path.join(graphRoot(), RISK_DIR, `${id}.json`);
@@ -22,15 +22,15 @@ import os from 'node:os';
22
22
  import path from 'node:path';
23
23
  import { randomUUID } from 'node:crypto';
24
24
  import Database from 'better-sqlite3';
25
- import { checkConstitution } from "../packages/engineering/architecture/src/index.js";
26
- import { assessRisk } from "../packages/engineering/risk/src/index.js";
27
- import { SandboxEngine, InMemorySandboxStore } from "../packages/sandbox/src/index.js";
28
- import { GitWorktreeBackend, SpawnCommandRunner } from "../packages/adapter-git/src/index.js";
29
- import { GitGraphDocumentSource } from "../packages/adapter-git/src/index.js";
30
- import { GraphIndexer, GraphLoop } from "../packages/graph/src/index.js";
31
- import { SqliteGraphStore, SqliteMigrationRunner } from "../packages/adapter-sqlite/src/index.js";
32
- import { buildRiskInput, changedFiles } from "../lib/core/risk-collect.js";
33
- import { emitOk, emitError, emitRejected } from "../lib/cli-output.js";
25
+ import { checkConstitution } from '../packages/engineering/architecture/src/index.js';
26
+ import { assessRisk } from '../packages/engineering/risk/src/index.js';
27
+ import { SandboxEngine, InMemorySandboxStore } from '../packages/sandbox/src/index.js';
28
+ import { GitWorktreeBackend, SpawnCommandRunner } from '../packages/adapter-git/src/index.js';
29
+ import { GitGraphDocumentSource } from '../packages/adapter-git/src/index.js';
30
+ import { GraphIndexer, GraphLoop } from '../packages/graph/src/index.js';
31
+ import { SqliteGraphStore, SqliteMigrationRunner } from '../packages/adapter-sqlite/src/index.js';
32
+ import { buildRiskInput, changedFiles } from '../lib/core/risk-collect.js';
33
+ import { emitOk, emitError, emitRejected } from '../lib/cli-output.js';
34
34
  const CONSTITUTION_PATH = '.context/architecture/constitution.json';
35
35
  function repoRoot() {
36
36
  return process.env.FORJA_GRAPH_ROOT ?? process.cwd();
@@ -39,3 +39,4 @@ export declare function addSpecToAllowlist(content: any, slug: any): {
39
39
  content: any;
40
40
  reason: string;
41
41
  };
42
+ export declare function nextSpecId(dir?: string): string;
@@ -71,7 +71,10 @@ function fillTemplate(tpl, vars) {
71
71
  .replace(/{{FEATURE}}/g, vars.feature)
72
72
  .replace(/{{ID}}/g, vars.id)
73
73
  .replace(/{{OWNER}}/g, vars.owner || '—')
74
- .replace(/{{DATE}}/g, vars.date);
74
+ .replace(/{{DATE}}/g, vars.date)
75
+ // O template lista os status possíveis; o artefato nasce `draft` (antes nascia com a lista
76
+ // inteira, e o índice da memória e o painel ops a exibiam como se fosse o status).
77
+ .replace(/^(-\s*\*\*Status\*\*:\s*)draft(\s*\|[^\n]*)$/m, '$1draft');
75
78
  }
76
79
  function readStatus(filePath) {
77
80
  if (!fs.existsSync(filePath))
@@ -147,18 +150,35 @@ function ensureSpecVersioned(slug) {
147
150
  out(` ⚠ não foi possível escrever .gitignore — adicione "!/specs/${slug}" manualmente.`);
148
151
  }
149
152
  }
153
+ export function nextSpecId(dir = specsDir) {
154
+ let max = 0;
155
+ if (fs.existsSync(dir)) {
156
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
157
+ if (!entry.isDirectory())
158
+ continue;
159
+ const spec = path.join(dir, entry.name, 'spec.md');
160
+ const m = fs.existsSync(spec) ? fs.readFileSync(spec, 'utf8').match(/\*\*ID\*\*:\s*SPEC-(\d+)/) : null;
161
+ if (m)
162
+ max = Math.max(max, Number(m[1]));
163
+ }
164
+ }
165
+ return `SPEC-${String(max + 1).padStart(3, '0')}`;
166
+ }
150
167
  function cmdNew(feature) {
151
168
  if (!feature)
152
- fail('uso: spec:new <feature>');
169
+ fail('uso: forja spec:new <feature>');
153
170
  const slug = slugify(feature);
154
171
  const dir = path.join(specsDir, slug);
155
172
  if (fs.existsSync(dir))
156
173
  fail(`spec ${slug} já existe em ${dir}`);
174
+ // Maior ID existente + 1, calculado ANTES do mkdir: contar pastas depois de criá-la fazia a
175
+ // primeira spec de um projeto nascer SPEC-002, e remover uma spec gerava IDs repetidos.
176
+ const id = nextSpecId();
157
177
  fs.mkdirSync(dir, { recursive: true });
158
178
  const tpl = readTemplate('spec');
159
179
  const content = fillTemplate(tpl, {
160
180
  feature: slug,
161
- id: `SPEC-${String(listFeatures().length + 1).padStart(3, '0')}`,
181
+ id,
162
182
  owner: process.env.USER || '—',
163
183
  date: todayISO(),
164
184
  });
@@ -169,7 +189,7 @@ function cmdNew(feature) {
169
189
  }
170
190
  function cmdNextStage(stage, feature) {
171
191
  if (!feature)
172
- fail(`uso: spec:${stage} <feature>`);
192
+ fail(`uso: forja spec:${stage} <feature>`);
173
193
  const slug = slugify(feature);
174
194
  const dir = path.join(specsDir, slug);
175
195
  if (!fs.existsSync(dir))
@@ -237,7 +257,7 @@ function cmdCheck(feature) {
237
257
  }
238
258
  function cmdSetStatus(feature, stage, status) {
239
259
  if (!feature || !stage || !status)
240
- fail('uso: spec:set-status <feature> <spec|plan|tasks> <status>');
260
+ fail('uso: forja spec:set-status <feature> <spec|plan|tasks> <status>');
241
261
  if (!STAGES.includes(stage))
242
262
  fail(`stage inválido: ${stage}. Use: ${STAGES.join('|')}`);
243
263
  if (!VALID_STATUSES.includes(status))
@@ -1,14 +1,15 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
- import { resolveProject, initWorkspace, isInsideFrameworkRepo } from "../lib/workspace.js";
4
+ import { resolveProject, initWorkspace, isInsideFrameworkRepo } from '../lib/workspace.js';
5
+ import { pkgRoot } from '../lib/paths.js';
5
6
  const __filename = fileURLToPath(import.meta.url);
6
7
  const __dirname = path.dirname(__filename);
7
- const frameworkRoot = path.resolve(__dirname, '..');
8
+ const frameworkRoot = pkgRoot;
8
9
  const cwd = path.resolve(process.cwd());
9
10
  const [cmd, projectArg, ...args] = process.argv.slice(2);
10
11
  if (!cmd) {
11
- console.log('Uso: node scripts/sprint-manager.js <start|status|complete> [projeto|.|root] [args]');
12
+ console.log('Uso: forja sprint:<start|status|complete> [projeto|.|root] [args]');
12
13
  console.log(' . ou root = framework raiz; outro nome = projeto no workspace');
13
14
  process.exit(0);
14
15
  }
@@ -3,14 +3,18 @@ import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
4
  import Database from 'better-sqlite3';
5
5
  import { fileURLToPath } from 'node:url';
6
- import { ensureSchema, getDbPath } from "./memory-schema.js";
7
- import { initWorkspace, getForjaMode, getWorkspaceRoot, getProjectsDir, getWorkspaceSpecsDir, getWorkspaceProjectsMemoryDir, listProjects, } from "../lib/workspace.js";
6
+ import { ensureSchema, getDbPath } from './memory-schema.js';
7
+ import { initWorkspace, getForjaMode, getWorkspaceRoot, getProjectsDir, getWorkspaceSpecsDir, getWorkspaceProjectsMemoryDir, listProjects, } from '../lib/workspace.js';
8
+ import { pkgRoot } from '../lib/paths.js';
8
9
  const __filename = fileURLToPath(import.meta.url);
9
10
  const __dirname = path.dirname(__filename);
10
- const root = path.resolve(__dirname, '..');
11
+ const root = pkgRoot;
11
12
  initWorkspace();
12
13
  const mode = getForjaMode();
13
14
  const operationRoot = getWorkspaceRoot();
15
+ // Fonte do conteúdo indexado: no modo embedded é o PROJETO, nunca o pacote. Ler specs/, boilerplates/
16
+ // e design-md/ de `root` (o pacote) vazava as specs do framework para a memória do produto.
17
+ const contentRoot = mode === 'embedded' ? operationRoot : root;
14
18
  const dbPath = getDbPath();
15
19
  const args = process.argv.slice(2);
16
20
  const projectArgIndex = args.indexOf('--project');
@@ -89,7 +93,7 @@ const upsertProject = db.prepare('INSERT INTO projects (name, path, created_at)
89
93
  // Sem ele restaria `lastInsertRowid`, que num upsert-que-atualizou guarda o id do
90
94
  // último INSERT da conexão — um id alheio, e o FTS acabava indexando o conteúdo de
91
95
  // um documento sob o node_id de outro (ADR-0021).
92
- const upsertNode = db.prepare('INSERT INTO memory_nodes (project_id, path, kind, title, content, content_hash, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title=excluded.title, content=excluded.content, content_hash=excluded.content_hash, updated_at=excluded.updated_at RETURNING id');
96
+ const upsertNode = db.prepare('INSERT INTO memory_nodes (project_id, path, kind, title, content, content_hash, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET project_id=excluded.project_id, kind=excluded.kind, title=excluded.title, content=excluded.content, content_hash=excluded.content_hash, updated_at=excluded.updated_at RETURNING id');
93
97
  const getProjectId = db.prepare('SELECT id FROM projects WHERE name = ?');
94
98
  const deleteFts = db.prepare('DELETE FROM search_idx WHERE node_id = ?');
95
99
  const insertFts = db.prepare('INSERT INTO search_idx (node_id, title, content) VALUES (?, ?, ?)');
@@ -143,7 +147,7 @@ function extractSection(content, heading, maxChars = 1200) {
143
147
  return match ? match[1].trim().slice(0, maxChars) : '';
144
148
  }
145
149
  function summarizeReadme(relPath) {
146
- const full = path.join(root, relPath);
150
+ const full = path.join(contentRoot, relPath);
147
151
  if (!fs.existsSync(full))
148
152
  return null;
149
153
  const content = fs.readFileSync(full, 'utf8');
@@ -155,7 +159,7 @@ function summarizeReadme(relPath) {
155
159
  .slice(0, 450);
156
160
  }
157
161
  function readJson(relPath) {
158
- const full = path.join(root, relPath);
162
+ const full = path.join(contentRoot, relPath);
159
163
  if (!fs.existsSync(full))
160
164
  return null;
161
165
  try {
@@ -166,7 +170,7 @@ function readJson(relPath) {
166
170
  }
167
171
  }
168
172
  function syncSpecSummaries() {
169
- const specsDir = path.join(root, 'specs');
173
+ const specsDir = path.join(contentRoot, 'specs');
170
174
  if (!fs.existsSync(specsDir))
171
175
  return;
172
176
  let count = 0;
@@ -175,7 +179,7 @@ function syncSpecSummaries() {
175
179
  continue;
176
180
  const slug = entry.name;
177
181
  const rel = path.join('specs', slug, 'spec.md');
178
- const full = path.join(root, rel);
182
+ const full = path.join(contentRoot, rel);
179
183
  if (!fs.existsSync(full))
180
184
  continue;
181
185
  const content = fs.readFileSync(full, 'utf8');
@@ -193,7 +197,7 @@ function syncSpecSummaries() {
193
197
  }
194
198
  function syncAssetCatalog() {
195
199
  const assets = [];
196
- const boilerRoot = path.join(root, 'boilerplates');
200
+ const boilerRoot = path.join(contentRoot, 'boilerplates');
197
201
  if (fs.existsSync(boilerRoot)) {
198
202
  for (const entry of fs.readdirSync(boilerRoot, { withFileTypes: true })) {
199
203
  if (!entry.isDirectory())
@@ -207,7 +211,7 @@ function syncAssetCatalog() {
207
211
  assets.push({ type: 'boilerplate', name: entry.name, path: rel, summary, tags });
208
212
  }
209
213
  }
210
- const designRoot = path.join(root, 'design-md');
214
+ const designRoot = path.join(contentRoot, 'design-md');
211
215
  if (fs.existsSync(designRoot)) {
212
216
  for (const entry of fs.readdirSync(designRoot, { withFileTypes: true })) {
213
217
  if (!entry.isDirectory())
@@ -228,7 +232,7 @@ function syncAssetCatalog() {
228
232
  }
229
233
  function syncFiles(files, projectId = null) {
230
234
  for (const abs of files) {
231
- let rel = path.relative(root, abs);
235
+ let rel = path.relative(contentRoot, abs);
232
236
  if (rel.startsWith('..')) {
233
237
  rel = path.relative(operationRoot, abs);
234
238
  }
@@ -249,10 +253,12 @@ function syncFiles(files, projectId = null) {
249
253
  // 1. Sincronizar Memória/Docs/Prompts Globais
250
254
  if (syncGlobal) {
251
255
  log('Sincronizando Memória Global...', 'info');
252
- const globalFiles = [
253
- ...walk(path.join(mode === 'embedded' ? operationRoot : root, 'memory')),
254
- ...walk(path.join(mode === 'embedded' ? operationRoot : root, 'docs')),
255
- ...walk(path.join(mode === 'embedded' ? operationRoot : root, 'prompts')),
256
+ // Embedded: memória/docs/prompts SÃO do projeto — indexados no passo 2 com o project_id. Indexá-los
257
+ // aqui também (como globais, project_id NULL) fazia o modo domain/task do context:smart não achar nada.
258
+ const globalFiles = mode === 'embedded' ? [] : [
259
+ ...walk(path.join(contentRoot, 'memory')),
260
+ ...walk(path.join(contentRoot, 'docs')),
261
+ ...walk(path.join(contentRoot, 'prompts')),
256
262
  ];
257
263
  syncFiles(globalFiles);
258
264
  syncSpecSummaries();
@@ -267,6 +273,7 @@ if (syncProjects && mode === 'embedded') {
267
273
  syncFiles([
268
274
  ...walk(path.join(operationRoot, 'memory')),
269
275
  ...walk(path.join(operationRoot, 'docs')),
276
+ ...walk(path.join(operationRoot, 'prompts')),
270
277
  ...walk(path.join(operationRoot, 'specs')),
271
278
  ...walk(path.join(operationRoot, 'design-md')),
272
279
  ], pid);
@@ -11,11 +11,12 @@
11
11
  */
12
12
  import fs from 'node:fs';
13
13
  import path from 'node:path';
14
- import ContextBuilder from "../lib/context-builder.js";
14
+ import ContextBuilder from '../lib/context-builder.js';
15
15
  import { fileURLToPath } from 'node:url';
16
- import { getDbPath, ensureSchema } from "./memory-schema.js";
16
+ import { getDbPath, ensureSchema } from './memory-schema.js';
17
+ import { pkgRoot } from '../lib/paths.js';
17
18
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
18
- const root = path.resolve(__dirname, '..');
19
+ const root = pkgRoot;
19
20
  /**
20
21
  * Estimar tokens (1KB ≈ 250 tokens, aproximação)
21
22
  */
@@ -20,14 +20,15 @@
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import { fileURLToPath } from 'node:url';
23
- import { domainsOf, buildContextPack } from "../lib/code-context.js";
24
- import { emitOk } from "../lib/cli-output.js";
23
+ import { domainsOf, buildContextPack } from '../lib/code-context.js';
24
+ import { emitOk } from '../lib/cli-output.js';
25
+ import { pkgRoot } from '../lib/paths.js';
25
26
  const JSON_MODE = process.argv.includes('--json');
26
27
  /** No modo `--json` o stdout é só o objeto final (ADR-0082); o texto de análise é suprimido. */
27
28
  const say = (line = '') => { if (!JSON_MODE)
28
29
  console.log(line); };
29
30
  const __filename = fileURLToPath(import.meta.url);
30
- const root = path.resolve(path.dirname(__filename), '..');
31
+ const root = pkgRoot;
31
32
  /**
32
33
  * Modo `--project <path>`: mede o eixo memória nos domínios REAIS do usuário, não na fixture. Para
33
34
  * cada domínio, o mapa (`context.md`) vs ler todo o código da fatia — o número fica dele.
@@ -15,6 +15,6 @@
15
15
  * Diagnostica e prescreve; não conserta. Rodar `npm rebuild` sem consentimento é a classe de
16
16
  * risco oposta à que este comando existe para fechar.
17
17
  *
18
- * Uso: node scripts/tools-doctor.mjs
18
+ * Uso: forja tools:doctor
19
19
  */
20
20
  export {};