forjajs 4.1.2 → 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.
- package/.claude/settings.json +2 -2
- package/.gemini-instructions.md +1 -1
- package/.github/copilot-instructions.md +1 -1
- package/.openai-instructions.md +1 -1
- package/CHANGELOG.md +109 -0
- package/DOC-MAP.md +2 -2
- package/README.md +62 -10
- package/README.pt-BR.md +46 -7
- package/boilerplates/01-api-rest/README.md +1 -1
- package/boilerplates/06-clean-arch/README.md +5 -3
- package/boilerplates/06-clean-arch/backend/.oxlintrc.json +10 -0
- package/boilerplates/06-clean-arch/backend/nest-cli.json +8 -0
- package/boilerplates/06-clean-arch/backend/package.json +22 -24
- package/boilerplates/06-clean-arch/backend/src/app.module.ts +4 -4
- package/boilerplates/06-clean-arch/backend/src/main.ts +2 -2
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts +4 -4
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts +2 -2
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.entity.ts +3 -3
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.repository.ts +1 -1
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/typeorm-order.repository.ts +5 -5
- package/boilerplates/06-clean-arch/backend/src/modules/orders/orders.module.ts +6 -6
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts +3 -3
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.controller.ts +1 -1
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.module.ts +2 -2
- package/boilerplates/06-clean-arch/backend/test/orders/place-order.spec.ts +2 -2
- package/boilerplates/06-clean-arch/backend/tsconfig.build.json +15 -0
- package/boilerplates/06-clean-arch/backend/tsconfig.json +24 -10
- package/boilerplates/06-clean-arch/backend/vitest.config.ts +11 -0
- package/boilerplates/06-clean-arch/boilerplate.manifest.json +6 -5
- package/boilerplates/README.md +24 -44
- package/dist/apps/cli/src/index.js +6 -6
- package/dist/apps/dashboard/next.config.d.mts +5 -5
- package/dist/apps/server/src/app.module.js +1 -1
- package/dist/apps/server/src/forja-nest.module.js +1 -1
- package/dist/apps/server/src/index.js +1 -1
- package/dist/apps/server/src/main.js +20 -20
- package/dist/apps/worker/src/main.js +4 -4
- package/dist/bin/create-memory-nest-kit.js +5 -5
- package/dist/bin/forja.js +28 -14
- package/dist/bin/init-project.d.ts +4 -9
- package/dist/bin/init-project.js +126 -182
- package/dist/lib/audit.js +1 -1
- package/dist/lib/context-builder.d.ts +6 -1
- package/dist/lib/context-builder.js +21 -12
- package/dist/lib/core/architecture-gate.js +2 -4
- package/dist/lib/core/checks.d.ts +1 -1
- package/dist/lib/core/drift-gate.js +2 -4
- package/dist/lib/core/gates.js +5 -5
- package/dist/lib/core/health.d.ts +0 -1
- package/dist/lib/core/health.js +33 -7
- package/dist/lib/core/journey.d.ts +30 -0
- package/dist/lib/core/journey.js +142 -0
- package/dist/lib/core/model-pricing.js +3 -5
- package/dist/lib/core/project-smoke.d.ts +6 -2
- package/dist/lib/core/project-smoke.js +60 -61
- package/dist/lib/core/registry.d.ts +1 -12
- package/dist/lib/core/registry.js +42 -32
- package/dist/lib/core/release.d.ts +1 -1
- package/dist/lib/core/release.js +31 -3
- package/dist/lib/core/risk-collect.js +4 -4
- package/dist/lib/drift-sentinel.js +1 -1
- package/dist/lib/generators/memory-generator.d.ts +30 -30
- package/dist/lib/generators/memory-generator.js +19 -8
- package/dist/lib/generators/nest-generator.js +192 -275
- package/dist/lib/generators/readme-generator.js +1 -1
- package/dist/lib/governance-report.js +4 -4
- package/dist/lib/handoffs-index.d.ts +16 -2
- package/dist/lib/handoffs-index.js +32 -5
- package/dist/lib/llm/session.js +1 -1
- package/dist/lib/llm/validation.js +1 -1
- package/dist/lib/memory-audit.js +1 -1
- package/dist/lib/paths.d.ts +39 -0
- package/dist/lib/paths.js +73 -0
- package/dist/lib/project-wiring.d.ts +54 -0
- package/dist/lib/project-wiring.js +391 -0
- package/dist/lib/status-model.js +18 -7
- package/dist/lib/templates.d.ts +24 -0
- package/dist/lib/templates.js +77 -0
- package/dist/lib/validators/structure-validator.js +0 -1
- package/dist/lib/workspace.d.ts +7 -0
- package/dist/lib/workspace.js +20 -2
- package/dist/packages/adapter-git/src/index.js +2 -2
- package/dist/packages/context/src/index.js +1 -1
- package/dist/packages/core/src/index.js +1 -1
- package/dist/packages/evals/src/index.js +1 -1
- package/dist/packages/events/src/index.js +1 -1
- package/dist/packages/graph/src/index.js +1 -1
- package/dist/packages/mcp/src/index.d.ts +1 -1
- package/dist/packages/observability/src/index.js +1 -1
- package/dist/packages/orchestration/src/index.js +1 -1
- package/dist/packages/planner/src/index.js +1 -1
- package/dist/packages/policy/src/index.js +1 -1
- package/dist/packages/runtime/src/index.js +1 -1
- package/dist/packages/sandbox/src/index.js +1 -1
- package/dist/packages/validator/src/index.js +1 -1
- package/dist/scripts/adr.js +4 -4
- package/dist/scripts/agent-harness.js +30 -23
- package/dist/scripts/agent-router.js +22 -5
- package/dist/scripts/agent.js +5 -5
- package/dist/scripts/architecture.js +6 -6
- package/dist/scripts/audit-query.js +1 -1
- package/dist/scripts/audit-sync.js +1 -1
- package/dist/scripts/build-smart-context.d.ts +19 -1
- package/dist/scripts/build-smart-context.js +84 -68
- package/dist/scripts/check-standards.js +8 -3
- package/dist/scripts/code-context.js +1 -1
- package/dist/scripts/compress-memory.js +3 -2
- package/dist/scripts/compress-project-memory.js +2 -2
- package/dist/scripts/context-ops.js +13 -5
- package/dist/scripts/cost-economy.js +4 -4
- package/dist/scripts/demo-autonomy.js +11 -11
- package/dist/scripts/demo-workspace.js +12 -4
- package/dist/scripts/dev.js +8 -7
- package/dist/scripts/drift-check.js +5 -5
- package/dist/scripts/engineer.js +11 -11
- package/dist/scripts/evidence.js +4 -4
- package/dist/scripts/extract-global-knowledge.js +6 -4
- package/dist/scripts/forja-setup.js +2 -1
- package/dist/scripts/forja-status.js +5 -4
- package/dist/scripts/gates.js +1 -1
- package/dist/scripts/generate-dashboard.js +6 -4
- package/dist/scripts/governance-dashboard.js +2 -2
- package/dist/scripts/hook-session-start.js +11 -10
- package/dist/scripts/hook-user-prompt.js +3 -2
- package/dist/scripts/incident.js +4 -4
- package/dist/scripts/llm-fit.js +11 -11
- package/dist/scripts/memory-audit.js +1 -1
- package/dist/scripts/memory-schema.js +3 -2
- package/dist/scripts/orchestrate.js +4 -5
- package/dist/scripts/project-smoke.js +13 -2
- package/dist/scripts/project-templates.d.ts +1 -0
- package/dist/scripts/project-templates.js +20 -0
- package/dist/scripts/project-upgrade.d.ts +13 -0
- package/dist/scripts/project-upgrade.js +107 -40
- package/dist/scripts/project-wire.d.ts +8 -0
- package/dist/scripts/project-wire.js +55 -0
- package/dist/scripts/provenance.js +3 -3
- package/dist/scripts/query-universal-memory.js +7 -4
- package/dist/scripts/release-check.js +1 -1
- package/dist/scripts/risk.js +4 -4
- package/dist/scripts/simulate.js +9 -9
- package/dist/scripts/spec-cli.d.ts +1 -0
- package/dist/scripts/spec-cli.js +25 -5
- package/dist/scripts/sprint-manager.js +4 -3
- package/dist/scripts/sync-universal-memory.js +22 -15
- package/dist/scripts/token-benchmark.js +4 -3
- package/dist/scripts/token-economy.js +4 -3
- package/dist/scripts/tools-doctor.d.ts +1 -1
- package/dist/scripts/tools-doctor.js +25 -3
- package/docs/GUIA-ONBOARDING-EXECUTIVO.md +1 -2
- package/docs/GUIA-ONBOARDING-OPERACIONAL-PAPEIS.md +5 -6
- package/docs/GUIA-ONBOARDING-PROJETO.md +7 -9
- package/docs/glossary.md +4 -4
- package/docs/init-project.md +88 -444
- package/docs/manual-operacional-cli-sdd-gsd.md +1 -1
- package/docs/modos-de-operacao.md +1 -1
- package/docs/processo-projeto.md +14 -11
- package/docs/produto/roteiro-demo.md +15 -18
- package/docs/publishing.md +5 -0
- package/docs/quick-reference.md +15 -23
- package/docs/structure.md +16 -30
- package/lib/core/model-pricing.json +19 -0
- package/memory/30-projects/README.md +1 -1
- package/memory/90-decisions/0022-congelar-dashboard-web.md +1 -1
- package/memory/90-decisions/0086-projeto-conectado-e-jornada-como-gate.md +95 -0
- package/memory/90-decisions/0087-remover-dashboard-legado.md +35 -0
- package/memory/90-decisions/0088-templates-validados.md +55 -0
- package/package.json +25 -25
- package/templates/project/AGENTS.md +75 -0
- package/templates/project/CLAUDE.md +9 -0
- package/templates/project/agents/context-engineer.md +15 -0
- package/templates/project/agents/governance.md +15 -0
- package/templates/project/agents/marketing.md +15 -0
- package/templates/project/agents/orchestrator.md +15 -0
- package/templates/project/agents/product.md +15 -0
- package/templates/project/agents/sdd-architect.md +15 -0
- package/dist/lib/multi-ai-instructions.d.ts +0 -28
- 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
|
+
}
|
package/dist/lib/status-model.js
CHANGED
|
@@ -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
|
|
12
|
-
import { listSpecs } from
|
|
13
|
-
import { readSprint } from
|
|
14
|
-
import { openHandoffs } from
|
|
15
|
-
import {
|
|
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
|
}
|
|
@@ -106,7 +107,7 @@ export async function collectStatus(repoRoot, opts = {}) {
|
|
|
106
107
|
}
|
|
107
108
|
let handoffs;
|
|
108
109
|
try {
|
|
109
|
-
handoffs = ok(await openHandoffs());
|
|
110
|
+
handoffs = ok(await openHandoffs(10, currentProjectName()));
|
|
110
111
|
}
|
|
111
112
|
catch (e) {
|
|
112
113
|
handoffs = unavailable(reasonOf(e));
|
|
@@ -176,7 +177,17 @@ export function recommendNext(model) {
|
|
|
176
177
|
};
|
|
177
178
|
}
|
|
178
179
|
}
|
|
179
|
-
// 7 —
|
|
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
|
|
180
191
|
return {
|
|
181
192
|
action: 'orchestrate',
|
|
182
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
|
+
}
|
package/dist/lib/workspace.d.ts
CHANGED
|
@@ -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;
|
package/dist/lib/workspace.js
CHANGED
|
@@ -22,6 +22,7 @@ import fs from 'node:fs';
|
|
|
22
22
|
import path from 'node:path';
|
|
23
23
|
import os from 'node:os';
|
|
24
24
|
import { fileURLToPath } from 'node:url';
|
|
25
|
+
import { pkgRoot } from './paths.js';
|
|
25
26
|
const __filename = fileURLToPath(import.meta.url);
|
|
26
27
|
const __dirname = path.dirname(__filename);
|
|
27
28
|
const DEFAULT_WORKSPACE_NAME = 'forja-workspace';
|
|
@@ -51,7 +52,7 @@ export function getForjaMode() {
|
|
|
51
52
|
if (process.env.FORJA_WORKSPACE)
|
|
52
53
|
return 'studio';
|
|
53
54
|
const cwd = path.resolve(process.cwd());
|
|
54
|
-
const frameworkRoot =
|
|
55
|
+
const frameworkRoot = pkgRoot;
|
|
55
56
|
if (cwd !== frameworkRoot && !cwd.startsWith(`${frameworkRoot}${path.sep}`) && fs.existsSync(path.join(cwd, 'package.json')))
|
|
56
57
|
return 'embedded';
|
|
57
58
|
return 'studio';
|
|
@@ -204,7 +205,7 @@ Fichas de projetos gerados pelo Forja. Cada arquivo representa um produto ativo
|
|
|
204
205
|
return root;
|
|
205
206
|
}
|
|
206
207
|
export function isInsideFrameworkRepo(filePath) {
|
|
207
|
-
const frameworkRoot =
|
|
208
|
+
const frameworkRoot = pkgRoot;
|
|
208
209
|
const resolved = path.resolve(filePath);
|
|
209
210
|
return resolved === frameworkRoot || resolved.startsWith(frameworkRoot + path.sep);
|
|
210
211
|
}
|
|
@@ -213,3 +214,20 @@ export function assertOutsideFrameworkRepo(filePath, operation = 'operacao') {
|
|
|
213
214
|
throw new Error(`${operation} não pode ser executada dentro do repositório do framework Forja. Use o workspace externo (~/forja-workspace).`);
|
|
214
215
|
}
|
|
215
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* Nome do projeto em que o comando roda: `forja` no repo do framework, o próprio projeto no modo
|
|
219
|
+
* embedded, o projeto do workspace que contém o cwd no studio; `null` fora de qualquer projeto.
|
|
220
|
+
* Usado para carimbar e filtrar handoffs — antes, um handoff de produto aparecia no briefing do
|
|
221
|
+
* framework (e vice-versa), porque todos caíam no mesmo banco sem dono.
|
|
222
|
+
*/
|
|
223
|
+
export function currentProjectName(cwd = process.cwd()) {
|
|
224
|
+
const resolved = path.resolve(cwd);
|
|
225
|
+
if (isInsideFrameworkRepo(resolved))
|
|
226
|
+
return 'forja';
|
|
227
|
+
if (getForjaMode() === 'embedded')
|
|
228
|
+
return path.basename(getWorkspaceRoot());
|
|
229
|
+
const rel = path.relative(getProjectsDir(), resolved);
|
|
230
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
|
|
231
|
+
return null;
|
|
232
|
+
return rel.split(path.sep)[0] || null;
|
|
233
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
|
-
import { graphDocumentId } from
|
|
5
|
-
import { isPathWithinRoot } from
|
|
4
|
+
import { graphDocumentId } from '../../graph/src/index.js';
|
|
5
|
+
import { isPathWithinRoot } from '../../contracts/src/index.js';
|
|
6
6
|
export class SpawnCommandRunner {
|
|
7
7
|
run(command) {
|
|
8
8
|
const started = Date.now();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { CONTRACT_VERSION, validateTokenBudget, } from
|
|
2
|
+
import { CONTRACT_VERSION, validateTokenBudget, } from '../../contracts/src/index.js';
|
|
3
3
|
export class GraphContextSource {
|
|
4
4
|
provider;
|
|
5
5
|
constructor(provider) { this.provider = provider; }
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { CONTRACT_VERSION, validateCapabilityDefinition, } from
|
|
2
|
+
import { CONTRACT_VERSION, validateCapabilityDefinition, } from '../../contracts/src/index.js';
|
|
3
3
|
export class CapabilityRegistryError extends Error {
|
|
4
4
|
constructor(message) {
|
|
5
5
|
super(message);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { CONTRACT_VERSION } from
|
|
2
|
+
import { CONTRACT_VERSION } from '../../contracts/src/index.js';
|
|
3
3
|
export class EvaluationError extends Error {
|
|
4
4
|
constructor(message) { super(message); this.name = 'EvaluationError'; }
|
|
5
5
|
}
|