forjajs 4.1.1 → 5.0.0

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 (181) 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 +125 -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-wiring.d.ts +54 -0
  75. package/dist/lib/project-wiring.js +391 -0
  76. package/dist/lib/specs-index.d.ts +1 -0
  77. package/dist/lib/specs-index.js +22 -3
  78. package/dist/lib/status-model.js +24 -8
  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 +33 -3
  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.d.ts +1 -1
  122. package/dist/scripts/forja-status.js +31 -3
  123. package/dist/scripts/gates.js +1 -1
  124. package/dist/scripts/generate-dashboard.js +6 -4
  125. package/dist/scripts/governance-dashboard.js +2 -2
  126. package/dist/scripts/hook-session-start.js +18 -9
  127. package/dist/scripts/hook-user-prompt.js +3 -2
  128. package/dist/scripts/incident.js +4 -4
  129. package/dist/scripts/llm-fit.js +11 -11
  130. package/dist/scripts/memory-audit.js +1 -1
  131. package/dist/scripts/memory-schema.js +3 -2
  132. package/dist/scripts/orchestrate.js +4 -5
  133. package/dist/scripts/project-smoke.js +13 -2
  134. package/dist/scripts/project-templates.d.ts +1 -0
  135. package/dist/scripts/project-templates.js +20 -0
  136. package/dist/scripts/project-upgrade.d.ts +13 -0
  137. package/dist/scripts/project-upgrade.js +107 -40
  138. package/dist/scripts/project-wire.d.ts +8 -0
  139. package/dist/scripts/project-wire.js +55 -0
  140. package/dist/scripts/provenance.js +3 -3
  141. package/dist/scripts/query-universal-memory.js +7 -4
  142. package/dist/scripts/release-check.js +1 -1
  143. package/dist/scripts/risk.js +4 -4
  144. package/dist/scripts/simulate.js +9 -9
  145. package/dist/scripts/spec-cli.d.ts +1 -0
  146. package/dist/scripts/spec-cli.js +25 -5
  147. package/dist/scripts/sprint-manager.js +21 -8
  148. package/dist/scripts/sync-universal-memory.js +50 -27
  149. package/dist/scripts/token-benchmark.js +4 -3
  150. package/dist/scripts/token-economy.js +4 -3
  151. package/dist/scripts/tools-doctor.d.ts +1 -1
  152. package/dist/scripts/tools-doctor.js +25 -3
  153. package/docs/GUIA-ONBOARDING-EXECUTIVO.md +1 -2
  154. package/docs/GUIA-ONBOARDING-OPERACIONAL-PAPEIS.md +5 -6
  155. package/docs/GUIA-ONBOARDING-PROJETO.md +7 -9
  156. package/docs/glossary.md +4 -4
  157. package/docs/init-project.md +88 -444
  158. package/docs/manual-operacional-cli-sdd-gsd.md +1 -1
  159. package/docs/modos-de-operacao.md +1 -1
  160. package/docs/processo-projeto.md +14 -11
  161. package/docs/produto/roteiro-demo.md +15 -18
  162. package/docs/publishing.md +5 -0
  163. package/docs/quick-reference.md +15 -23
  164. package/docs/structure.md +16 -30
  165. package/lib/core/model-pricing.json +19 -0
  166. package/memory/30-projects/README.md +1 -1
  167. package/memory/90-decisions/0022-congelar-dashboard-web.md +1 -1
  168. package/memory/90-decisions/0086-projeto-conectado-e-jornada-como-gate.md +95 -0
  169. package/memory/90-decisions/0087-remover-dashboard-legado.md +35 -0
  170. package/memory/90-decisions/0088-templates-validados.md +55 -0
  171. package/package.json +25 -25
  172. package/templates/project/AGENTS.md +75 -0
  173. package/templates/project/CLAUDE.md +9 -0
  174. package/templates/project/agents/context-engineer.md +15 -0
  175. package/templates/project/agents/governance.md +15 -0
  176. package/templates/project/agents/marketing.md +15 -0
  177. package/templates/project/agents/orchestrator.md +15 -0
  178. package/templates/project/agents/product.md +15 -0
  179. package/templates/project/agents/sdd-architect.md +15 -0
  180. package/dist/lib/multi-ai-instructions.d.ts +0 -28
  181. package/dist/lib/multi-ai-instructions.js +0 -83
@@ -0,0 +1,391 @@
1
+ /**
2
+ * lib/project-wiring.ts — liga um projeto à inteligência do Forja (ADR-0086).
3
+ *
4
+ * Um projeto gerado só é "Forja" se a IA que o abre enxergar o processo: instruções nativas que
5
+ * cada ferramenta lê sozinha, hooks que trazem o estado na abertura da sessão, sub-agents por papel
6
+ * e o MCP do Forja. Antes da v5 nada disso era emitido — as instruções iam para `.ia-instructions/`
7
+ * (que nenhuma IA lê), copiadas do texto do FRAMEWORK (com `npm run` que não existe no projeto).
8
+ *
9
+ * Duas faces da mesma fonte de verdade:
10
+ * - `wireProject` escreve/atualiza (idempotente; preserva conteúdo do usuário).
11
+ * - `checkProjectWiring` verifica, incluindo que todo `forja <cmd>` citado existe no registry e
12
+ * que todo `node <arquivo>` dos package.json aponta para arquivo real.
13
+ *
14
+ * Conteúdo gerenciado em Markdown vive entre `<!-- forja:begin -->` e `<!-- forja:end -->`: o
15
+ * wire reescreve só o bloco, o resto do arquivo é do usuário.
16
+ */
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { spawnSync } from 'node:child_process';
20
+ import { asset } from './paths.js';
21
+ export const BEGIN = '<!-- forja:begin -->';
22
+ export const END = '<!-- forja:end -->';
23
+ const AGENT_MARK = '<!-- forja:managed -->';
24
+ export const SUPPORTED_AI = ['claude', 'codex', 'gemini', 'copilot'];
25
+ /** Onde cada IA lê as instruções nativamente. */
26
+ export const INSTRUCTION_FILE = {
27
+ claude: 'CLAUDE.md',
28
+ codex: 'AGENTS.md',
29
+ gemini: 'GEMINI.md',
30
+ copilot: '.github/copilot-instructions.md',
31
+ };
32
+ const CODEX_MCP = '# Forja — servidor MCP (forja project:wire)\n[mcp_servers.forja]\ncommand = "forja"\nargs = ["mcp:start"]\n';
33
+ const GITIGNORE = ['memory/sqlite/', '.context/'];
34
+ export const ROLES = ['orchestrator', 'product', 'sdd-architect', 'context-engineer', 'governance', 'marketing'];
35
+ /** Hooks do Claude Code. Guardados por `command -v`: sem `forja` no PATH, a sessão abre sem erro. */
36
+ export const HOOKS = {
37
+ SessionStart: 'hook:session-start',
38
+ UserPromptSubmit: 'hook:user-prompt',
39
+ };
40
+ export function hookCommand(cmd) {
41
+ return `command -v forja >/dev/null 2>&1 && forja ${cmd} || true`;
42
+ }
43
+ function template(rel) {
44
+ return fs.readFileSync(asset('templates', 'project', rel), 'utf8').trimEnd();
45
+ }
46
+ function hasBinary(bin) {
47
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { encoding: 'utf8' });
48
+ return r.status === 0;
49
+ }
50
+ /** Substitui (ou acrescenta) o bloco gerenciado preservando o resto do arquivo. */
51
+ export function upsertManagedBlock(existing, body) {
52
+ const block = `${BEGIN}\n${body.trimEnd()}\n${END}`;
53
+ if (existing == null || existing.trim() === '')
54
+ return `${block}\n`;
55
+ const start = existing.indexOf(BEGIN);
56
+ const end = existing.indexOf(END);
57
+ if (start !== -1 && end > start) {
58
+ return existing.slice(0, start) + block + existing.slice(end + END.length);
59
+ }
60
+ return `${block}\n\n${existing.trimStart()}`;
61
+ }
62
+ function readOrNull(file) {
63
+ try {
64
+ return fs.readFileSync(file, 'utf8');
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ function readJson(file) {
71
+ const raw = readOrNull(file);
72
+ if (raw == null)
73
+ return null;
74
+ try {
75
+ return JSON.parse(raw);
76
+ }
77
+ catch {
78
+ throw new Error(`${file} não é JSON válido — corrija antes de rodar project:wire`);
79
+ }
80
+ }
81
+ function write(dir, rel, content, changes) {
82
+ const file = path.join(dir, rel);
83
+ const before = readOrNull(file);
84
+ if (before === content) {
85
+ changes.push({ file: rel, action: 'unchanged' });
86
+ return;
87
+ }
88
+ fs.mkdirSync(path.dirname(file), { recursive: true });
89
+ fs.writeFileSync(file, content, 'utf8');
90
+ changes.push({ file: rel, action: before == null ? 'created' : 'updated' });
91
+ }
92
+ function writeJson(dir, rel, data, changes) {
93
+ write(dir, rel, `${JSON.stringify(data, null, 2)}\n`, changes);
94
+ }
95
+ function normalizeAi(ai) {
96
+ const list = (ai && ai.length ? ai : SUPPORTED_AI).map((a) => a.trim().toLowerCase()).filter(Boolean);
97
+ const unknown = list.filter((a) => !SUPPORTED_AI.includes(a));
98
+ if (unknown.length)
99
+ throw new Error(`IA desconhecida: ${unknown.join(', ')} (suportadas: ${SUPPORTED_AI.join(', ')})`);
100
+ return [...new Set(list)];
101
+ }
102
+ /** IAs já conectadas a um projeto, deduzidas dos arquivos nativos (para `project:wire` sem `--ai`). */
103
+ export function detectWiredAi(dir) {
104
+ try {
105
+ const chain = JSON.parse(fs.readFileSync(path.join(dir, '.forja', 'models.json'), 'utf8')).fallback_chain;
106
+ if (Array.isArray(chain) && chain.length)
107
+ return chain.filter((a) => SUPPORTED_AI.includes(a));
108
+ }
109
+ catch { /* sem models.json: deduz pelos arquivos */ }
110
+ const found = [];
111
+ if (fs.existsSync(path.join(dir, 'CLAUDE.md')) || fs.existsSync(path.join(dir, '.claude')))
112
+ found.push('claude');
113
+ if (fs.existsSync(path.join(dir, 'AGENTS.md')))
114
+ found.push('codex');
115
+ if (fs.existsSync(path.join(dir, 'GEMINI.md')))
116
+ found.push('gemini');
117
+ if (fs.existsSync(path.join(dir, '.github', 'copilot-instructions.md')))
118
+ found.push('copilot');
119
+ // Projetos pré-v5 registravam as IAs só em .ia-instructions/<ai>.md.
120
+ const legacy = path.join(dir, '.ia-instructions');
121
+ if (fs.existsSync(legacy)) {
122
+ for (const ai of SUPPORTED_AI)
123
+ if (fs.existsSync(path.join(legacy, `${ai}.md`)))
124
+ found.push(ai);
125
+ }
126
+ return [...new Set(found)];
127
+ }
128
+ const HARNESS_SCRIPTS = {
129
+ 'code:check': 'forja code:check',
130
+ 'code:impact': 'forja code:impact',
131
+ 'tools:doctor': 'forja tools:doctor',
132
+ };
133
+ /** Scripts emitidos por versões antigas que apontavam para arquivos que nunca chegavam ao projeto. */
134
+ const LEGACY_SCRIPT_RE = /^node scripts\/(code-intel|tools-doctor)\.mjs\b/;
135
+ /** Escreve/atualiza a conexão do projeto. Idempotente. */
136
+ export function wireProject(dir, opts = {}) {
137
+ const ai = normalizeAi(opts.ai);
138
+ const changes = [];
139
+ const agentsBody = template('AGENTS.md');
140
+ write(dir, 'AGENTS.md', upsertManagedBlock(readOrNull(path.join(dir, 'AGENTS.md')), agentsBody), changes);
141
+ if (ai.includes('claude')) {
142
+ write(dir, 'CLAUDE.md', upsertManagedBlock(readOrNull(path.join(dir, 'CLAUDE.md')), template('CLAUDE.md')), changes);
143
+ const settingsRel = path.join('.claude', 'settings.json');
144
+ const settings = readJson(path.join(dir, settingsRel)) ?? {};
145
+ settings.hooks ??= {};
146
+ for (const [event, cmd] of Object.entries(HOOKS)) {
147
+ const groups = (settings.hooks[event] ??= []);
148
+ const wired = groups.some((g) => (g.hooks || []).some((h) => String(h.command || '').includes(`forja ${cmd}`)));
149
+ if (!wired)
150
+ groups.push({ hooks: [{ type: 'command', command: hookCommand(cmd), timeout: 10 }] });
151
+ }
152
+ settings.permissions ??= {};
153
+ const allow = (settings.permissions.allow ??= []);
154
+ if (!allow.includes('Bash(forja *)'))
155
+ allow.push('Bash(forja *)');
156
+ writeJson(dir, settingsRel, settings, changes);
157
+ for (const role of ROLES) {
158
+ const rel = path.join('.claude', 'agents', `${role}.md`);
159
+ const current = readOrNull(path.join(dir, rel));
160
+ // Sub-agent editado à mão (sem a marca) é do usuário: não sobrescreve.
161
+ if (current != null && !current.includes(AGENT_MARK)) {
162
+ changes.push({ file: rel, action: 'unchanged' });
163
+ continue;
164
+ }
165
+ write(dir, rel, `${template(path.join('agents', `${role}.md`))}\n\n${AGENT_MARK}\n`, changes);
166
+ }
167
+ }
168
+ if (ai.includes('gemini')) {
169
+ write(dir, 'GEMINI.md', upsertManagedBlock(readOrNull(path.join(dir, 'GEMINI.md')), '@AGENTS.md'), changes);
170
+ }
171
+ if (ai.includes('copilot')) {
172
+ const rel = path.join('.github', 'copilot-instructions.md');
173
+ write(dir, rel, upsertManagedBlock(readOrNull(path.join(dir, rel)), agentsBody), changes);
174
+ }
175
+ // Artefatos locais nunca vão para o git: o índice SQLite e os packs/auditoria em .context/.
176
+ const giPath = path.join(dir, '.gitignore');
177
+ const gi = readOrNull(giPath) ?? '';
178
+ const giLines = new Set(gi.split('\n').map((l) => l.trim()));
179
+ const missingIgnores = GITIGNORE.filter((l) => !giLines.has(l));
180
+ if (missingIgnores.length) {
181
+ write(dir, '.gitignore', `${gi}${gi && !gi.endsWith('\n') ? '\n' : ''}${gi ? '\n' : ''}# Forja — artefatos locais\n${missingIgnores.join('\n')}\n`, changes);
182
+ }
183
+ // Cadeia de fallback entre IAs (protocolo "Engine Switch" de memory/00-global/context-policy.md).
184
+ // Toda IA lê as mesmas instruções (AGENTS.md); o arquivo diz a ordem e onde cada uma as encontra.
185
+ const modelsRel = path.join('.forja', 'models.json');
186
+ const prevModels = (() => { try {
187
+ return readJson(path.join(dir, modelsRel));
188
+ }
189
+ catch {
190
+ return null;
191
+ } })();
192
+ writeJson(dir, modelsRel, {
193
+ active_engine: prevModels?.active_engine && ai.includes(prevModels.active_engine) ? prevModels.active_engine : ai[0],
194
+ fallback_chain: ai,
195
+ engines: Object.fromEntries(ai.map((a) => [a, { instruction_file: INSTRUCTION_FILE[a], status: 'ready' }])),
196
+ }, changes);
197
+ // MCP: o servidor do próprio Forja sempre; codegraph só se existir (senão a IA vê um MCP quebrado).
198
+ const mcp = readJson(path.join(dir, '.mcp.json')) ?? {};
199
+ mcp.mcpServers ??= {};
200
+ mcp.mcpServers.forja ??= { type: 'stdio', command: 'forja', args: ['mcp:start'], env: {} };
201
+ const withCodegraph = opts.codegraph ?? hasBinary('codegraph');
202
+ if (withCodegraph)
203
+ mcp.mcpServers.codegraph ??= { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'], env: {} };
204
+ else if (mcp.mcpServers.codegraph && !hasBinary('codegraph'))
205
+ delete mcp.mcpServers.codegraph;
206
+ writeJson(dir, '.mcp.json', mcp, changes);
207
+ // O mesmo servidor nas outras IAs, cada uma na config de projeto que ela lê sozinha.
208
+ if (ai.includes('codex')) {
209
+ const rel = path.join('.codex', 'config.toml');
210
+ const toml = readOrNull(path.join(dir, rel)) ?? '';
211
+ if (!/^\[mcp_servers\.forja\]/m.test(toml)) {
212
+ write(dir, rel, `${toml}${toml && !toml.endsWith('\n') ? '\n' : ''}${toml ? '\n' : ''}${CODEX_MCP}`, changes);
213
+ }
214
+ else
215
+ changes.push({ file: rel, action: 'unchanged' });
216
+ }
217
+ if (ai.includes('gemini')) {
218
+ const rel = path.join('.gemini', 'settings.json');
219
+ const gem = readJson(path.join(dir, rel)) ?? {};
220
+ gem.mcpServers ??= {};
221
+ gem.mcpServers.forja ??= { command: 'forja', args: ['mcp:start'] };
222
+ writeJson(dir, rel, gem, changes);
223
+ }
224
+ if (ai.includes('copilot')) {
225
+ const rel = path.join('.vscode', 'mcp.json');
226
+ const vs = readJson(path.join(dir, rel)) ?? {};
227
+ vs.servers ??= {};
228
+ vs.servers.forja ??= { type: 'stdio', command: 'forja', args: ['mcp:start'] };
229
+ writeJson(dir, rel, vs, changes);
230
+ }
231
+ const pkgPath = path.join(dir, 'package.json');
232
+ const pkg = readJson(pkgPath) ?? { name: path.basename(dir), version: '0.1.0', private: true, type: 'module' };
233
+ pkg.scripts ??= {};
234
+ for (const [key, value] of Object.entries(HARNESS_SCRIPTS)) {
235
+ if (!pkg.scripts[key] || LEGACY_SCRIPT_RE.test(pkg.scripts[key]))
236
+ pkg.scripts[key] = value;
237
+ }
238
+ writeJson(dir, 'package.json', pkg, changes);
239
+ // Backend pré-v5: memory:db:* apontavam para memory-db-*.mjs, que nunca foram gerados.
240
+ const backendPkgPath = path.join(dir, 'backend', 'package.json');
241
+ const backendPkg = readJson(backendPkgPath);
242
+ if (backendPkg?.scripts) {
243
+ const s = backendPkg.scripts;
244
+ const dead = (k) => typeof s[k] === 'string' && /scripts\/memory-db-\w+\.mjs/.test(s[k])
245
+ && !fs.existsSync(path.join(dir, 'backend', s[k].replace(/^node\s+/, '').split(/\s/)[0]));
246
+ const migrate = ['memory:db:init', 'memory:db:sync', 'memory:db:query'].filter(dead);
247
+ if (migrate.includes('memory:db:init'))
248
+ delete s['memory:db:init'];
249
+ if (migrate.includes('memory:db:sync'))
250
+ s['memory:db:sync'] = 'cd .. && forja sync:universal';
251
+ if (migrate.includes('memory:db:query'))
252
+ s['memory:db:query'] = 'cd .. && forja query:universal';
253
+ // Só reescreve quando migrou algo: o package.json do backend é do usuário.
254
+ if (migrate.length)
255
+ write(dir, path.join('backend', 'package.json'), `${JSON.stringify(backendPkg, null, 2)}\n`, changes);
256
+ }
257
+ return changes;
258
+ }
259
+ /** Todo `forja <comando>` citado num texto (blocos de código e inline). */
260
+ export function citedForjaCommands(text) {
261
+ const out = new Set();
262
+ for (const m of text.matchAll(/(?:^|[\s`(&|;])forja ([a-z][a-z0-9-]*(?::[a-z0-9-]+)*)/gm))
263
+ out.add(m[1]);
264
+ return [...out];
265
+ }
266
+ /** `node <arquivo>` dos scripts de um package.json cujo arquivo não existe. */
267
+ export function brokenNodeScripts(pkgDir) {
268
+ const pkg = (() => { try {
269
+ return JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8'));
270
+ }
271
+ catch {
272
+ return null;
273
+ } })();
274
+ if (!pkg?.scripts)
275
+ return [];
276
+ const broken = [];
277
+ for (const [name, cmd] of Object.entries(pkg.scripts)) {
278
+ for (const m of String(cmd).matchAll(/(?:^|&&\s*|;\s*)node\s+(?:--[\w-]+(?:=\S+)?\s+)*([^\s-][^\s]*\.(?:m?js|cjs|ts))/g)) {
279
+ if (!fs.existsSync(path.resolve(pkgDir, m[1])))
280
+ broken.push(`${name} → ${m[1]}`);
281
+ }
282
+ }
283
+ return broken;
284
+ }
285
+ export function checkProjectWiring(dir, { commands, ai }) {
286
+ const checks = [];
287
+ const wiredAi = ai && ai.length ? normalizeAi(ai) : detectWiredAi(dir);
288
+ const add = (id, status, detail) => checks.push({ id, status, detail });
289
+ const agents = readOrNull(path.join(dir, 'AGENTS.md'));
290
+ if (!agents?.includes(BEGIN))
291
+ add('instructions', 'fail', 'AGENTS.md sem o bloco do Forja — rode: forja project:wire');
292
+ else
293
+ add('instructions', 'ok', 'AGENTS.md com o bloco do Forja');
294
+ if (wiredAi.includes('claude')) {
295
+ const claude = readOrNull(path.join(dir, 'CLAUDE.md'));
296
+ add('claude-md', claude?.includes('@AGENTS.md') ? 'ok' : 'fail', claude ? 'CLAUDE.md importa AGENTS.md' : 'CLAUDE.md ausente');
297
+ let settings;
298
+ try {
299
+ settings = readJson(path.join(dir, '.claude', 'settings.json'));
300
+ }
301
+ catch (e) {
302
+ add('claude-hooks', 'fail', e.message);
303
+ }
304
+ if (settings !== undefined) {
305
+ const missing = Object.entries(HOOKS).filter(([event, cmd]) => !(settings?.hooks?.[event] || []).some((g) => (g.hooks || []).some((h) => String(h.command || '').includes(`forja ${cmd}`))));
306
+ add('claude-hooks', missing.length ? 'fail' : 'ok', missing.length ? `hooks ausentes: ${missing.map(([e]) => e).join(', ')}` : 'SessionStart + UserPromptSubmit');
307
+ }
308
+ const absent = ROLES.filter((r) => !fs.existsSync(path.join(dir, '.claude', 'agents', `${r}.md`)));
309
+ add('claude-agents', absent.length ? 'fail' : 'ok', absent.length ? `sub-agents ausentes: ${absent.join(', ')}` : `${ROLES.length} sub-agents`);
310
+ }
311
+ if (wiredAi.includes('gemini')) {
312
+ add('gemini-md', readOrNull(path.join(dir, 'GEMINI.md'))?.includes('@AGENTS.md') ? 'ok' : 'fail', 'GEMINI.md importa AGENTS.md');
313
+ }
314
+ if (wiredAi.includes('copilot')) {
315
+ add('copilot-md', readOrNull(path.join(dir, '.github', 'copilot-instructions.md'))?.includes(BEGIN) ? 'ok' : 'fail', '.github/copilot-instructions.md com o bloco do Forja');
316
+ }
317
+ let models;
318
+ try {
319
+ models = readJson(path.join(dir, '.forja', 'models.json'));
320
+ }
321
+ catch {
322
+ models = null;
323
+ }
324
+ const chain = Array.isArray(models?.fallback_chain) ? models.fallback_chain : null;
325
+ if (!chain)
326
+ add('models', 'fail', '.forja/models.json ausente ou inválido');
327
+ else if (JSON.stringify([...chain].sort()) !== JSON.stringify([...wiredAi].sort()))
328
+ add('models', 'fail', `fallback_chain ${JSON.stringify(chain)} ≠ IAs conectadas ${JSON.stringify(wiredAi)}`);
329
+ else
330
+ add('models', 'ok', `fallback: ${chain.join(' → ')}`);
331
+ let mcp;
332
+ try {
333
+ mcp = readJson(path.join(dir, '.mcp.json'));
334
+ }
335
+ catch (e) {
336
+ add('mcp', 'fail', e.message);
337
+ }
338
+ if (mcp !== undefined) {
339
+ if (mcp?.mcpServers?.forja?.command !== 'forja')
340
+ add('mcp', 'fail', '.mcp.json sem o servidor forja');
341
+ else if (mcp.mcpServers.codegraph && !hasBinary('codegraph'))
342
+ add('mcp', 'warn', 'codegraph registrado no .mcp.json mas ausente do PATH');
343
+ else
344
+ add('mcp', 'ok', `servidores: ${Object.keys(mcp.mcpServers).join(', ')}`);
345
+ }
346
+ // MCP nas outras IAs conectadas.
347
+ const mcpGaps = [];
348
+ if (wiredAi.includes('codex') && !/^\[mcp_servers\.forja\]/m.test(readOrNull(path.join(dir, '.codex', 'config.toml')) ?? ''))
349
+ mcpGaps.push('.codex/config.toml');
350
+ const jsonHas = (rel, pick) => { try {
351
+ return Boolean(pick(readJson(path.join(dir, rel))));
352
+ }
353
+ catch {
354
+ return false;
355
+ } };
356
+ if (wiredAi.includes('gemini') && !jsonHas(path.join('.gemini', 'settings.json'), (j) => j?.mcpServers?.forja))
357
+ mcpGaps.push('.gemini/settings.json');
358
+ if (wiredAi.includes('copilot') && !jsonHas(path.join('.vscode', 'mcp.json'), (j) => j?.servers?.forja))
359
+ mcpGaps.push('.vscode/mcp.json');
360
+ const others = wiredAi.filter((a) => a !== 'claude');
361
+ if (others.length)
362
+ add('mcp-ias', mcpGaps.length ? 'fail' : 'ok', mcpGaps.length ? `servidor forja ausente em: ${mcpGaps.join(', ')}` : `servidor forja também em: ${others.join(', ')}`);
363
+ // Todo comando citado ao usuário/IA precisa existir — é o que impede instrução que não funciona.
364
+ const cited = new Map();
365
+ const texts = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', path.join('.github', 'copilot-instructions.md'),
366
+ ...ROLES.map((r) => path.join('.claude', 'agents', `${r}.md`))];
367
+ for (const rel of texts) {
368
+ const t = readOrNull(path.join(dir, rel));
369
+ if (t)
370
+ for (const c of citedForjaCommands(t))
371
+ if (!cited.has(c))
372
+ cited.set(c, rel);
373
+ }
374
+ try {
375
+ const s = readJson(path.join(dir, '.claude', 'settings.json'));
376
+ for (const c of citedForjaCommands(JSON.stringify(s ?? {})))
377
+ if (!cited.has(c))
378
+ cited.set(c, '.claude/settings.json');
379
+ }
380
+ catch { /* já reportado acima */ }
381
+ const unknown = [...cited].filter(([c]) => !(c in commands)).map(([c, f]) => `${c} (${f})`);
382
+ add('commands', unknown.length ? 'fail' : 'ok', unknown.length ? `comandos inexistentes citados: ${unknown.join(', ')}` : `${cited.size} comandos citados, todos no registry`);
383
+ const broken = ['.', 'backend'].flatMap((sub) => fs.existsSync(path.join(dir, sub, 'package.json'))
384
+ ? brokenNodeScripts(path.join(dir, sub)).map((b) => (sub === '.' ? b : `${sub}/${b}`)) : []);
385
+ add('scripts', broken.length ? 'fail' : 'ok', broken.length ? `scripts apontam para arquivo ausente: ${broken.join('; ')}` : 'todo `node <arquivo>` dos package.json existe');
386
+ const gi = new Set((readOrNull(path.join(dir, '.gitignore')) ?? '').split('\n').map((l) => l.trim()));
387
+ const unignored = GITIGNORE.filter((l) => !gi.has(l));
388
+ add('gitignore', unignored.length ? 'warn' : 'ok', unignored.length ? `fora do .gitignore (o índice iria para o git): ${unignored.join(', ')}` : 'índice e .context/ fora do git');
389
+ add('forja-bin', hasBinary('forja') ? 'ok' : 'warn', hasBinary('forja') ? 'forja no PATH' : 'forja fora do PATH — hooks e MCP ficam inativos (npm i -g forjajs)');
390
+ return checks;
391
+ }
@@ -13,6 +13,7 @@ export interface SpecEntry {
13
13
  /** Status de `tasks.md`, ou `null` se o arquivo não existe. */
14
14
  readonly tasks: string | null;
15
15
  }
16
+ export declare function normalizeStatus(raw: string): string;
16
17
  /**
17
18
  * Lista as specs versionadas do repo com o status de cada artefato SDD. `root` é a raiz do repo
18
19
  * (onde vive `specs/`). Nunca lança.
@@ -6,7 +6,25 @@
6
6
  */
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
- const STATUS_RE = /-\s*\*\*Status\*\*:\s*([a-z]+)/i;
9
+ const STATUS_LINE_RE = /(?:^|\n)[-*]?\s*\*+Status\*+:\s*([^\n\r]+)/i;
10
+ const STATUS_ALT_RE = /(?:^|\n)Status:\s*([^\n\r]+)/i;
11
+ export function normalizeStatus(raw) {
12
+ const trimmed = raw.replace(/[`*]/g, '').trim().toLowerCase();
13
+ if (/^(done|conclu[íi]do|concluida|concluido|completed|finalizado)/i.test(trimmed))
14
+ return 'done';
15
+ if (/^(implementing|em implementa[çc][ãa]o|implementando)/i.test(trimmed))
16
+ return 'implementing';
17
+ if (/^(approved|aprovado|aprovada)/i.test(trimmed))
18
+ return 'approved';
19
+ if (/^(review|em revis[ãa]o|revis[ãa]o|revisao)/i.test(trimmed))
20
+ return 'review';
21
+ if (/^(draft|rascunho)/i.test(trimmed))
22
+ return 'draft';
23
+ if (/^(abandoned|abandonado|cancelado)/i.test(trimmed))
24
+ return 'abandoned';
25
+ const firstWord = trimmed.split(/[\s|—–-]+/)[0];
26
+ return firstWord || 'unknown';
27
+ }
10
28
  function safeReadDir(p) {
11
29
  try {
12
30
  return fs.readdirSync(p);
@@ -19,8 +37,9 @@ function statusOf(file) {
19
37
  try {
20
38
  if (!fs.existsSync(file))
21
39
  return null;
22
- const m = fs.readFileSync(file, 'utf8').match(STATUS_RE);
23
- return m ? m[1].toLowerCase() : 'unknown';
40
+ const content = fs.readFileSync(file, 'utf8');
41
+ const m = content.match(STATUS_LINE_RE) || content.match(STATUS_ALT_RE);
42
+ return m ? normalizeStatus(m[1]) : 'unknown';
24
43
  }
25
44
  catch {
26
45
  return null;
@@ -8,11 +8,12 @@
8
8
  */
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
- import { getWorkspaceInfo, getWorkspaceContextDir, getWorkspaceDbPath } from "./workspace.js";
12
- import { listSpecs } from "./specs-index.js";
13
- import { readSprint } from "./sprint-index.js";
14
- import { openHandoffs } from "./handoffs-index.js";
15
- import { listRuns, loadState } from "./orchestrate.js";
11
+ import { getWorkspaceInfo, getWorkspaceContextDir, getWorkspaceDbPath } from './workspace.js';
12
+ import { listSpecs } from './specs-index.js';
13
+ import { readSprint } from './sprint-index.js';
14
+ import { openHandoffs } from './handoffs-index.js';
15
+ import { currentProjectName } from './workspace.js';
16
+ import { listRuns, loadState } from './orchestrate.js';
16
17
  function ok(value) {
17
18
  return { available: true, value };
18
19
  }
@@ -93,7 +94,12 @@ export async function collectStatus(repoRoot, opts = {}) {
93
94
  }
94
95
  let recentRuns;
95
96
  try {
96
- const dir = wi.exists ? getWorkspaceContextDir() : path.join(repoRoot, '.context');
97
+ const projectDir = path.join(repoRoot, '.context');
98
+ const dir = fs.existsSync(path.join(projectDir, 'forja-runs.jsonl'))
99
+ ? projectDir
100
+ : wi.exists
101
+ ? getWorkspaceContextDir()
102
+ : projectDir;
97
103
  recentRuns = ok(readRecentRuns(dir, runsLimit));
98
104
  }
99
105
  catch (e) {
@@ -101,7 +107,7 @@ export async function collectStatus(repoRoot, opts = {}) {
101
107
  }
102
108
  let handoffs;
103
109
  try {
104
- handoffs = ok(await openHandoffs());
110
+ handoffs = ok(await openHandoffs(10, currentProjectName()));
105
111
  }
106
112
  catch (e) {
107
113
  handoffs = unavailable(reasonOf(e));
@@ -171,7 +177,17 @@ export function recommendNext(model) {
171
177
  };
172
178
  }
173
179
  }
174
- // 7 — nada pendente
180
+ // 7 — handoff aberto: alguém está esperando um parecer ou uma entrega. O mais antigo primeiro
181
+ // (a lista vem do mais recente para o mais antigo).
182
+ if (model.handoffs.available && model.handoffs.value.length) {
183
+ const oldest = model.handoffs.value[model.handoffs.value.length - 1];
184
+ return {
185
+ action: 'handoff',
186
+ command: `forja agent:route show ${oldest.id}`,
187
+ reason: `${model.handoffs.value.length} handoff(s) em aberto — o mais antigo é #${oldest.id} ${oldest.from} → ${oldest.to} (${oldest.intent})${oldest.slug ? ` em ${oldest.slug}` : ''}; feche com forja agent:route done ${oldest.id}`,
188
+ };
189
+ }
190
+ // 8 — nada pendente
175
191
  return {
176
192
  action: 'orchestrate',
177
193
  command: 'forja orchestrate "<objetivo>" --slug <slug>',
@@ -0,0 +1,24 @@
1
+ /**
2
+ * lib/templates.ts — boilerplates como ponto de partida de um projeto (`project:new --template`).
3
+ *
4
+ * Um boilerplate só vira template quando o manifest declara `"template": true`: isso promete que
5
+ * o backend dele instala, compila, passa nos testes e no lint — promessa cobrada pelo
6
+ * `project:smoke --full --template <nome>`. Os demais seguem como arquitetura de referência
7
+ * (catálogo), e o `--template` os recusa dizendo por quê, em vez de gerar um projeto quebrado.
8
+ */
9
+ export interface TemplateInfo {
10
+ readonly name: string;
11
+ readonly dir: string;
12
+ readonly title: string;
13
+ readonly ready: boolean;
14
+ readonly stack: readonly string[];
15
+ }
16
+ export declare function listTemplates(root?: string): TemplateInfo[];
17
+ /** Aceita o nome inteiro (`06-clean-arch`) ou sem o prefixo numérico (`clean-arch`). */
18
+ export declare function resolveTemplate(name: string, root?: string): TemplateInfo;
19
+ /**
20
+ * Aplica o template sobre um projeto já com a memória gerada: o código e a memória específica do
21
+ * boilerplate prevalecem sobre os genéricos (o README do boilerplate vai para `docs/template.md`, o
22
+ * do projeto fica). Registra a origem em `.forja/template.json`.
23
+ */
24
+ export declare function applyTemplate(projectDir: string, template: TemplateInfo): string[];
@@ -0,0 +1,77 @@
1
+ /**
2
+ * lib/templates.ts — boilerplates como ponto de partida de um projeto (`project:new --template`).
3
+ *
4
+ * Um boilerplate só vira template quando o manifest declara `"template": true`: isso promete que
5
+ * o backend dele instala, compila, passa nos testes e no lint — promessa cobrada pelo
6
+ * `project:smoke --full --template <nome>`. Os demais seguem como arquitetura de referência
7
+ * (catálogo), e o `--template` os recusa dizendo por quê, em vez de gerar um projeto quebrado.
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { asset } from './paths.js';
12
+ /** Arquivos do boilerplate que descrevem o boilerplate, não o projeto. */
13
+ const SKIP = new Set(['boilerplate.manifest.json', 'node_modules', 'dist', '.git']);
14
+ export function listTemplates(root = asset('boilerplates')) {
15
+ if (!fs.existsSync(root))
16
+ return [];
17
+ return fs.readdirSync(root, { withFileTypes: true })
18
+ .filter((e) => e.isDirectory())
19
+ .map((e) => {
20
+ const dir = path.join(root, e.name);
21
+ let manifest = {};
22
+ try {
23
+ manifest = JSON.parse(fs.readFileSync(path.join(dir, 'boilerplate.manifest.json'), 'utf8'));
24
+ }
25
+ catch { /* sem manifest */ }
26
+ return { name: e.name, dir, title: String(manifest.title ?? e.name), ready: manifest.template === true, stack: manifest.stack ?? [] };
27
+ })
28
+ .sort((a, b) => a.name.localeCompare(b.name));
29
+ }
30
+ /** Aceita o nome inteiro (`06-clean-arch`) ou sem o prefixo numérico (`clean-arch`). */
31
+ export function resolveTemplate(name, root) {
32
+ const all = listTemplates(root);
33
+ const found = all.find((t) => t.name === name || t.name.replace(/^\d+-/, '') === name);
34
+ const ready = all.filter((t) => t.ready).map((t) => t.name.replace(/^\d+-/, ''));
35
+ if (!found)
36
+ throw new Error(`template desconhecido: ${name}. Disponíveis: ${ready.join(', ') || '(nenhum)'} — veja forja project:templates`);
37
+ if (!found.ready) {
38
+ throw new Error(`${found.name} é arquitetura de referência, ainda não um template validado (instalação/build/testes). ` +
39
+ `Disponíveis: ${ready.join(', ') || '(nenhum)'}. Use-o como referência: boilerplates/${found.name}/`);
40
+ }
41
+ return found;
42
+ }
43
+ function copyTree(src, dest, out, rel = '') {
44
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
45
+ if (SKIP.has(e.name))
46
+ continue;
47
+ const s = path.join(src, e.name);
48
+ const r = path.join(rel, e.name);
49
+ if (e.isDirectory())
50
+ copyTree(s, dest, out, r);
51
+ else {
52
+ fs.mkdirSync(path.dirname(path.join(dest, r)), { recursive: true });
53
+ fs.copyFileSync(s, path.join(dest, r));
54
+ out.push(r);
55
+ }
56
+ }
57
+ }
58
+ /**
59
+ * Aplica o template sobre um projeto já com a memória gerada: o código e a memória específica do
60
+ * boilerplate prevalecem sobre os genéricos (o README do boilerplate vai para `docs/template.md`, o
61
+ * do projeto fica). Registra a origem em `.forja/template.json`.
62
+ */
63
+ export function applyTemplate(projectDir, template) {
64
+ const copied = [];
65
+ const staging = path.join(projectDir, '.forja', '.template-staging');
66
+ fs.rmSync(staging, { recursive: true, force: true });
67
+ copyTree(template.dir, staging, []);
68
+ const readme = path.join(staging, 'README.md');
69
+ if (fs.existsSync(readme)) {
70
+ fs.mkdirSync(path.join(staging, 'docs'), { recursive: true });
71
+ fs.renameSync(readme, path.join(staging, 'docs', 'template.md'));
72
+ }
73
+ copyTree(staging, projectDir, copied);
74
+ fs.rmSync(staging, { recursive: true, force: true });
75
+ fs.writeFileSync(path.join(projectDir, '.forja', 'template.json'), `${JSON.stringify({ name: template.name, title: template.title, appliedAt: new Date().toISOString() }, null, 2)}\n`);
76
+ return copied;
77
+ }
@@ -50,7 +50,6 @@ const NEST_CRITICAL_DIRS = [
50
50
  'backend/src',
51
51
  'backend/src/modules/ops',
52
52
  'backend/test',
53
- 'backend/scripts',
54
53
  ];
55
54
  /**
56
55
  * Valida estrutura de memória
@@ -45,3 +45,10 @@ export declare function ensureDir(dir: any): any;
45
45
  export declare function initWorkspace(): any;
46
46
  export declare function isInsideFrameworkRepo(filePath: any): boolean;
47
47
  export declare function assertOutsideFrameworkRepo(filePath: any, operation?: string): void;
48
+ /**
49
+ * Nome do projeto em que o comando roda: `forja` no repo do framework, o próprio projeto no modo
50
+ * embedded, o projeto do workspace que contém o cwd no studio; `null` fora de qualquer projeto.
51
+ * Usado para carimbar e filtrar handoffs — antes, um handoff de produto aparecia no briefing do
52
+ * framework (e vice-versa), porque todos caíam no mesmo banco sem dono.
53
+ */
54
+ export declare function currentProjectName(cwd?: string): string | null;