forjajs 4.0.1 → 4.1.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 (96) hide show
  1. package/CHANGELOG.md +170 -7
  2. package/DOC-MAP.md +1 -0
  3. package/README.md +10 -2
  4. package/README.pt-BR.md +3 -0
  5. package/dist/apps/cli/src/index.d.ts +18 -1
  6. package/dist/apps/cli/src/index.js +161 -26
  7. package/dist/apps/cli/src/params.d.ts +44 -0
  8. package/dist/apps/cli/src/params.js +123 -0
  9. package/dist/bin/forja.js +234 -13
  10. package/dist/bin/init-project.js +11 -62
  11. package/dist/lib/cli-output.d.ts +29 -0
  12. package/dist/lib/cli-output.js +39 -0
  13. package/dist/lib/core/checks.d.ts +1 -1
  14. package/dist/lib/core/health.d.ts +9 -0
  15. package/dist/lib/core/health.js +9 -0
  16. package/dist/lib/core/project-smoke.d.ts +6 -2
  17. package/dist/lib/core/project-smoke.js +83 -7
  18. package/dist/lib/core/registry.d.ts +38 -571
  19. package/dist/lib/core/registry.js +174 -25
  20. package/dist/lib/core/release.d.ts +1 -571
  21. package/dist/lib/core/release.js +0 -3
  22. package/dist/lib/handoffs-index.d.ts +16 -0
  23. package/dist/lib/handoffs-index.js +29 -0
  24. package/dist/lib/llm/claude-output.d.ts +8 -0
  25. package/dist/lib/llm/claude-output.js +54 -0
  26. package/dist/lib/llm/context.d.ts +22 -0
  27. package/dist/lib/llm/context.js +39 -0
  28. package/dist/lib/llm/session.d.ts +6 -1
  29. package/dist/lib/llm/session.js +12 -2
  30. package/dist/lib/multi-ai-instructions.d.ts +28 -0
  31. package/dist/lib/multi-ai-instructions.js +83 -0
  32. package/dist/lib/orchestrate.d.ts +5 -0
  33. package/dist/lib/orchestrate.js +18 -0
  34. package/dist/lib/specs-index.d.ts +20 -0
  35. package/dist/lib/specs-index.js +51 -0
  36. package/dist/lib/sprint-index.d.ts +15 -0
  37. package/dist/lib/sprint-index.js +34 -0
  38. package/dist/lib/status-model.d.ts +64 -0
  39. package/dist/lib/status-model.js +180 -0
  40. package/dist/packages/evals/src/index.d.ts +2 -0
  41. package/dist/packages/evals/src/index.js +21 -0
  42. package/dist/packages/llm/src/index.d.ts +24 -3
  43. package/dist/packages/llm/src/index.js +51 -5
  44. package/dist/scripts/cost-economy.js +12 -10
  45. package/dist/scripts/drift-check.d.ts +2 -0
  46. package/dist/scripts/drift-check.js +57 -1
  47. package/dist/scripts/engineer.js +7 -4
  48. package/dist/scripts/forja-setup.d.ts +14 -0
  49. package/dist/scripts/forja-setup.js +58 -0
  50. package/dist/scripts/forja-status.d.ts +11 -0
  51. package/dist/scripts/forja-status.js +70 -0
  52. package/dist/scripts/hook-session-start.js +20 -46
  53. package/dist/scripts/llm-fit.js +113 -8
  54. package/dist/scripts/project-smoke.js +13 -3
  55. package/dist/scripts/simulate.js +18 -6
  56. package/dist/scripts/token-economy.js +34 -28
  57. package/dist/scripts/tools-doctor.js +14 -6
  58. package/docs/2x/CLI-CAPABILITIES.md +34 -10
  59. package/docs/agent-operating-contract.md +3 -1
  60. package/docs/cli-first-operacao.md +17 -0
  61. package/docs/contrato-saida-cli.md +79 -0
  62. package/docs/llm-evolution.md +2 -1
  63. package/docs/llm-fit-loop.md +74 -2
  64. package/docs/publishing.md +13 -16
  65. package/docs/quick-reference.md +13 -0
  66. package/docs/roadmap-v4.1.md +199 -0
  67. package/memory/90-decisions/0082-contrato-saida-cli.md +95 -0
  68. package/memory/90-decisions/0083-mcp-cobertura-declarativa.md +103 -0
  69. package/memory/90-decisions/0084-drift-sentinel-fecha.md +79 -0
  70. package/memory/90-decisions/0085-adaptador-claude-paridade.md +85 -0
  71. package/package.json +4 -1
  72. package/specs/cli-intuitiva-v1/plan.md +169 -0
  73. package/specs/cli-intuitiva-v1/spec.md +163 -0
  74. package/specs/cli-intuitiva-v1/tasks.md +224 -0
  75. package/specs/contrato-saida-cli/plan.md +162 -0
  76. package/specs/contrato-saida-cli/spec.md +157 -0
  77. package/specs/contrato-saida-cli/tasks.md +153 -0
  78. package/specs/drift-sentinel/spec.md +17 -8
  79. package/specs/forja-status-caminho-feliz/plan.md +149 -0
  80. package/specs/forja-status-caminho-feliz/spec.md +158 -0
  81. package/specs/forja-status-caminho-feliz/tasks.md +175 -0
  82. package/specs/llm-adaptador-claude/plan.md +117 -0
  83. package/specs/llm-adaptador-claude/spec.md +144 -0
  84. package/specs/llm-adaptador-claude/tasks.md +100 -0
  85. package/specs/llm-benchmark-recomendacao/plan.md +121 -0
  86. package/specs/llm-benchmark-recomendacao/spec.md +141 -0
  87. package/specs/llm-benchmark-recomendacao/tasks.md +88 -0
  88. package/specs/llm-contexto-e-sessoes/plan.md +143 -0
  89. package/specs/llm-contexto-e-sessoes/spec.md +139 -0
  90. package/specs/llm-contexto-e-sessoes/tasks.md +127 -0
  91. package/specs/mcp-cobertura-nucleo/plan.md +158 -0
  92. package/specs/mcp-cobertura-nucleo/spec.md +161 -0
  93. package/specs/mcp-cobertura-nucleo/tasks.md +169 -0
  94. package/specs/projeto-gerado-confiavel/plan.md +148 -0
  95. package/specs/projeto-gerado-confiavel/spec.md +142 -0
  96. package/specs/projeto-gerado-confiavel/tasks.md +139 -0
@@ -25,6 +25,20 @@ export class EvaluationEngine {
25
25
  const candidate = scope === 'run' ? value.runId : scope === 'agent' ? value.agentId : scope === 'task' ? value.taskId : scope === 'sprint' ? value.sprintId : scope === 'capability' ? value.capabilityId : scope === 'model' ? value.model : undefined;
26
26
  return candidate === scopeId;
27
27
  }
28
+ /** Percentil por interpolação linear (`p·(n-1)`); `[]` → 0. SPEC-049. */
29
+ percentile(values, p) {
30
+ if (values.length === 0)
31
+ return 0;
32
+ const sorted = [...values].sort((a, b) => a - b);
33
+ if (sorted.length === 1)
34
+ return sorted[0];
35
+ const rank = (p / 100) * (sorted.length - 1);
36
+ const low = Math.floor(rank);
37
+ const high = Math.ceil(rank);
38
+ if (low === high)
39
+ return sorted[low];
40
+ return sorted[low] + (sorted[high] - sorted[low]) * (rank - low);
41
+ }
28
42
  metrics(values) {
29
43
  const total = values.length;
30
44
  const succeeded = values.filter((value) => value.outcome === 'succeeded').length;
@@ -53,6 +67,13 @@ export class EvaluationEngine {
53
67
  totalInputTokens: values.reduce((sum, value) => sum + value.inputTokens, 0),
54
68
  totalOutputTokens: values.reduce((sum, value) => sum + value.outputTokens, 0),
55
69
  totalCost: values.reduce((sum, value) => sum + (value.cost ?? 0), 0),
70
+ // SPEC-049 — latência por percentil e custo por tarefa aprovada. `costPerAcceptedTask` = 0
71
+ // quando nenhuma foi aceita (não Infinity nem null): `metrics` é Record<string, number>.
72
+ durationMsP50: this.percentile(values.map((value) => value.durationMs), 50),
73
+ durationMsP95: this.percentile(values.map((value) => value.durationMs), 95),
74
+ costPerAcceptedTask: accepted === 0
75
+ ? 0
76
+ : values.reduce((sum, value) => sum + (value.cost ?? 0), 0) / accepted,
56
77
  };
57
78
  }
58
79
  repeatedInputCount(values) {
@@ -36,15 +36,36 @@ export interface LlmExecutionOptions {
36
36
  readonly resume?: string;
37
37
  readonly outputSchema?: string;
38
38
  }
39
+ /**
40
+ * Provedores cujo adaptador suporta retomada de sessão (ADR-0081, ADR-0085). É propriedade do
41
+ * adaptador — o que a CLI do provedor oferece — não uma escolha do operador no perfil.
42
+ */
43
+ export declare const RESUME_PROVIDERS: ReadonlySet<string>;
39
44
  export declare function buildLlmExecution(profile: LlmProfile, prompt: string, options?: LlmExecutionOptions): LlmExecution;
40
45
  export declare function runLlm(execution: LlmExecution, cwd: string, timeoutMs?: number): Promise<LlmExecutionResult>;
41
- export declare function recommendProfile(profiles: LlmProfiles, observations: readonly {
46
+ interface RecommendObservation {
42
47
  readonly model?: string;
43
48
  readonly outcome: string;
44
49
  readonly durationMs: number;
45
50
  readonly cost?: number;
46
- }[], role: string, taskType: string, privacy?: LlmProfile['privacy']): readonly {
51
+ }
52
+ export interface ProfileRecommendation {
47
53
  readonly name: string;
48
54
  readonly score: number;
49
55
  readonly reasons: readonly string[];
50
- }[];
56
+ /** SPEC-049 — a base numérica da recomendação, para o operador ponderar/contestar. */
57
+ readonly evidence: {
58
+ readonly samples: number;
59
+ readonly medianDurationMs: number;
60
+ readonly meanCostUsd: number | null;
61
+ readonly successRate: number;
62
+ };
63
+ }
64
+ /**
65
+ * SPEC-049 — recomendação por fit declarado + evidência local, agora ponderando **latência** e
66
+ * **custo**. Os bônus de latência/custo somam no máximo 8 pontos: refinam entre pares próximos,
67
+ * nunca invertem um fit declarado (que vale 100+50). Nenhum percentual de ganho é afirmado —
68
+ * `evidence` expõe a base para o operador julgar.
69
+ */
70
+ export declare function recommendProfile(profiles: LlmProfiles, observations: readonly RecommendObservation[], role: string, taskType: string, privacy?: LlmProfile['privacy']): readonly ProfileRecommendation[];
71
+ export {};
@@ -20,14 +20,19 @@ export function validateProfiles(value) {
20
20
  profiles[name] = validateProfile(name, profile);
21
21
  return { version: LLM_PROFILE_VERSION, profiles };
22
22
  }
23
+ /**
24
+ * Provedores cujo adaptador suporta retomada de sessão (ADR-0081, ADR-0085). É propriedade do
25
+ * adaptador — o que a CLI do provedor oferece — não uma escolha do operador no perfil.
26
+ */
27
+ export const RESUME_PROVIDERS = new Set(['codex', 'claude']);
23
28
  export function buildLlmExecution(profile, prompt, options = {}) {
24
29
  validateProfile('execution', profile);
25
30
  if (!profile.enabled)
26
31
  throw new LlmProfileError('profile is disabled');
27
32
  if (prompt.trim().length === 0)
28
33
  throw new LlmProfileError('prompt is required');
29
- if (options.resume !== undefined && (profile.provider !== 'codex' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(options.resume))) {
30
- throw new LlmProfileError('resume requires codex and an explicit session ID');
34
+ if (options.resume !== undefined && (!RESUME_PROVIDERS.has(profile.provider) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(options.resume))) {
35
+ throw new LlmProfileError('resume requires a resume-capable adapter (codex, claude) and an explicit session ID');
31
36
  }
32
37
  const base = [...(profile.commandArgs ?? [])];
33
38
  if (profile.provider === 'codex')
@@ -42,7 +47,11 @@ export function buildLlmExecution(profile, prompt, options = {}) {
42
47
  stdin: prompt,
43
48
  };
44
49
  if (profile.provider === 'claude')
45
- return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '-p', prompt] };
50
+ return {
51
+ executable: profile.command,
52
+ args: [...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '-p', prompt,
53
+ '--output-format', 'json', ...(options.resume ? ['--resume', options.resume] : [])],
54
+ };
46
55
  if (profile.provider === 'gemini-cli')
47
56
  return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['-m', profile.model]), '-p', prompt] };
48
57
  if (profile.provider === 'ollama')
@@ -100,7 +109,24 @@ export async function runLlm(execution, cwd, timeoutMs = 120_000) {
100
109
  child.on('close', (code) => { clearTimeout(timer); clearTimeout(killTimer); finish({ exitCode: code ?? 1, stdout, stderr, ...(code === 0 ? {} : { errorCode: 'COMMAND_FAILED' }) }); });
101
110
  });
102
111
  }
112
+ function median(values) {
113
+ if (values.length === 0)
114
+ return 0;
115
+ const sorted = [...values].sort((a, b) => a - b);
116
+ const mid = Math.floor(sorted.length / 2);
117
+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
118
+ }
119
+ /**
120
+ * SPEC-049 — recomendação por fit declarado + evidência local, agora ponderando **latência** e
121
+ * **custo**. Os bônus de latência/custo somam no máximo 8 pontos: refinam entre pares próximos,
122
+ * nunca invertem um fit declarado (que vale 100+50). Nenhum percentual de ganho é afirmado —
123
+ * `evidence` expõe a base para o operador julgar.
124
+ */
103
125
  export function recommendProfile(profiles, observations, role, taskType, privacy) {
126
+ const allDurations = observations.filter((value) => value.model !== undefined).map((value) => value.durationMs);
127
+ const definedCosts = observations.map((value) => value.cost).filter((value) => typeof value === 'number');
128
+ const cohortMedianLatency = median(allDurations);
129
+ const cohortMeanCost = definedCosts.length === 0 ? null : definedCosts.reduce((sum, value) => sum + value, 0) / definedCosts.length;
104
130
  return Object.entries(profiles.profiles)
105
131
  .filter(([, profile]) => profile.enabled && (privacy === undefined || profile.privacy === privacy))
106
132
  .map(([name, profile]) => {
@@ -108,13 +134,33 @@ export function recommendProfile(profiles, observations, role, taskType, privacy
108
134
  const samples = observations.filter((value) => value.model === model);
109
135
  const succeeded = samples.filter((value) => value.outcome === 'succeeded').length;
110
136
  const successRate = samples.length === 0 ? 0 : succeeded / samples.length;
111
- const score = (profile.roles.includes(role) ? 100 : 0) + (profile.taskTypes.includes(taskType) ? 50 : 0) + Math.round(successRate * 25) + Math.min(samples.length, 10);
137
+ const medianDurationMs = median(samples.map((value) => value.durationMs));
138
+ const sampleCosts = samples.map((value) => value.cost).filter((value) => typeof value === 'number');
139
+ const meanCostUsd = sampleCosts.length === 0 ? null : sampleCosts.reduce((sum, value) => sum + value, 0) / sampleCosts.length;
140
+ let latencyBonus = 0;
141
+ let costBonus = 0;
142
+ if (samples.length > 0) {
143
+ if (cohortMedianLatency > 0 && medianDurationMs < cohortMedianLatency) {
144
+ latencyBonus = Math.min(4, Math.round(4 * (1 - medianDurationMs / cohortMedianLatency)));
145
+ }
146
+ if (cohortMeanCost !== null && cohortMeanCost > 0 && meanCostUsd !== null && meanCostUsd < cohortMeanCost) {
147
+ costBonus = Math.min(4, Math.round(4 * (1 - meanCostUsd / cohortMeanCost)));
148
+ }
149
+ }
150
+ const score = (profile.roles.includes(role) ? 100 : 0)
151
+ + (profile.taskTypes.includes(taskType) ? 50 : 0)
152
+ + Math.round(successRate * 25)
153
+ + Math.min(samples.length, 10)
154
+ + latencyBonus
155
+ + costBonus;
112
156
  const reasons = [
113
157
  ...(profile.roles.includes(role) ? [`role:${role}`] : []),
114
158
  ...(profile.taskTypes.includes(taskType) ? [`task:${taskType}`] : []),
115
159
  ...(samples.length > 0 ? [`${succeeded}/${samples.length} successful runs`] : ['no local evidence yet']),
160
+ ...(samples.length > 0 ? [`latency:p50=${Math.round(medianDurationMs)}ms`] : []),
161
+ ...(meanCostUsd !== null ? [`cost:$${meanCostUsd.toFixed(4)}/run`] : []),
116
162
  ];
117
- return { name, score, reasons };
163
+ return { name, score, reasons, evidence: { samples: samples.length, medianDurationMs, meanCostUsd, successRate } };
118
164
  })
119
165
  .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
120
166
  }
@@ -21,7 +21,9 @@ import Database from 'better-sqlite3';
21
21
  import { SqliteMigrationRunner, SqliteObservationStore } from "../packages/adapter-sqlite/src/index.js";
22
22
  import { getWorkspaceDbDir, getWorkspaceDbPath, getWorkspaceInfo } from "../lib/workspace.js";
23
23
  import { loadPricingTable, lookupPrice } from "../lib/core/model-pricing.js";
24
+ import { emitOk } from "../lib/cli-output.js";
24
25
  function main() {
26
+ const json = process.argv.includes('--json');
25
27
  const info = getWorkspaceInfo();
26
28
  fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
27
29
  const db = new Database(process.env.FORJA_RUNTIME_DB ?? getWorkspaceDbPath());
@@ -47,6 +49,16 @@ function main() {
47
49
  if (!priceKnown)
48
50
  unknownPricingCount += 1;
49
51
  }
52
+ if (json) {
53
+ emitOk({
54
+ workspace: info.root,
55
+ currency: table.currency,
56
+ totalCostUsd,
57
+ observationCount: observations.length,
58
+ unknownPricingCount,
59
+ byModel: Object.fromEntries(byModel),
60
+ }); // termina o processo
61
+ }
50
62
  console.log(`\nCost economy — custo real acumulado (SPEC-029) — workspace: ${info.root}\n`);
51
63
  console.log('Estimativa baseada na tabela local de preços (lib/core/model-pricing.json), NÃO a fatura do provider.\n');
52
64
  if (observations.length === 0) {
@@ -65,15 +77,5 @@ function main() {
65
77
  console.log(`Aviso: ${unknownPricingCount} execução(ões) usaram modelo(s) sem preço na tabela local — custo real total pode ser maior que o mostrado. Atualize lib/core/model-pricing.json (\`forja llm:doctor\` lista os gaps).`);
66
78
  }
67
79
  }
68
- if (process.argv.includes('--json')) {
69
- console.log(JSON.stringify({
70
- workspace: info.root,
71
- currency: table.currency,
72
- totalCostUsd,
73
- observationCount: observations.length,
74
- unknownPricingCount,
75
- byModel: Object.fromEntries(byModel),
76
- }, null, 2));
77
- }
78
80
  }
79
81
  main();
@@ -4,6 +4,8 @@
4
4
  *
5
5
  * forja drift:check reindexa o workspace e reporta drift estrutural
6
6
  * forja drift:check --domain <d> restringe aos documentos cujo path passa por /<d>/
7
+ * forja drift:check --all roda em lote sobre cada projeto do workspace (SPEC-030 §3,
8
+ * ADR-0084); cada projeto num grafo isolado e persistente
7
9
  *
8
10
  * Reindexa via o mesmo mecanismo de `graph:sync` (checksum de fonte + extração determinística) e,
9
11
  * para cada documento cujo conteúdo mudou, compara as relações `verified` que ele produzia antes
@@ -4,6 +4,8 @@
4
4
  *
5
5
  * forja drift:check reindexa o workspace e reporta drift estrutural
6
6
  * forja drift:check --domain <d> restringe aos documentos cujo path passa por /<d>/
7
+ * forja drift:check --all roda em lote sobre cada projeto do workspace (SPEC-030 §3,
8
+ * ADR-0084); cada projeto num grafo isolado e persistente
7
9
  *
8
10
  * Reindexa via o mesmo mecanismo de `graph:sync` (checksum de fonte + extração determinística) e,
9
11
  * para cada documento cujo conteúdo mudou, compara as relações `verified` que ele produzia antes
@@ -15,16 +17,67 @@
15
17
  * julgamento humano ou de agente (SPEC-030 §5, fora de escopo deste comando).
16
18
  */
17
19
  import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { spawnSync } from 'node:child_process';
22
+ import { fileURLToPath } from 'node:url';
18
23
  import Database from 'better-sqlite3';
19
24
  import { checkDrift } from "../lib/drift-sentinel.js";
20
25
  import { GitGraphDocumentSource, SpawnCommandRunner } from "../packages/adapter-git/src/index.js";
21
26
  import { GraphLoop } from "../packages/graph/src/index.js";
22
27
  import { SqliteGraphStore, SqliteMigrationRunner } from "../packages/adapter-sqlite/src/index.js";
23
- import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
28
+ import { getWorkspaceDbDir, getWorkspaceDbPath, getProjectsDir, listProjects } from "../lib/workspace.js";
29
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
24
30
  function arg(name) {
25
31
  const i = process.argv.indexOf(name);
26
32
  return i >= 0 ? process.argv[i + 1] ?? null : null;
27
33
  }
34
+ /**
35
+ * `--all` (SPEC-030 §3, ADR-0084): roda `drift:check` uma vez por projeto do workspace, cada um
36
+ * contra o próprio dir (`FORJA_GRAPH_ROOT`) e um grafo isolado e **persistente**
37
+ * (`<projeto>/.context/drift-graph.db`) — a persistência é o que dá o "antes" para a próxima
38
+ * rodada detectar. Primeira rodada num projeto novo semeia; a partir da segunda, compara.
39
+ */
40
+ function runAll() {
41
+ const projectsDir = getProjectsDir();
42
+ const projects = listProjects();
43
+ console.log('\nForja drift:check --all — o verified continua verdade, projeto a projeto?\n');
44
+ if (projects.length === 0) {
45
+ console.log(`Nenhum projeto em ${projectsDir}. Gere um com \`forja project:new <nome>\`.`);
46
+ return 0;
47
+ }
48
+ let drifted = 0;
49
+ let failed = 0;
50
+ for (const name of projects) {
51
+ const projDir = path.join(projectsDir, name);
52
+ const dbDir = path.join(projDir, '.context');
53
+ fs.mkdirSync(dbDir, { recursive: true });
54
+ const result = spawnSync(process.execPath, [path.join(__dirname, 'drift-check.ts')], {
55
+ cwd: projDir,
56
+ encoding: 'utf8',
57
+ env: {
58
+ ...process.env,
59
+ FORJA_GRAPH_ROOT: projDir,
60
+ FORJA_RUNTIME_DB: path.join(dbDir, 'drift-graph.db'),
61
+ },
62
+ });
63
+ const code = result.status ?? 1;
64
+ const count = /(\d+) com drift detectado/.exec(result.stdout ?? '')?.[1] ?? '?';
65
+ if (code === 0) {
66
+ console.log(`✓ ${name.padEnd(28)} sem drift (${count === '?' ? 'semeado' : `${count} doc(s)`})`);
67
+ }
68
+ else if (code === 1) {
69
+ drifted += 1;
70
+ console.log(`✗ ${name.padEnd(28)} ${count} documento(s) com relação verified não reproduzível`);
71
+ }
72
+ else {
73
+ failed += 1;
74
+ console.log(`! ${name.padEnd(28)} drift:check não rodou (exit ${code}) — ${(result.stderr || '').trim().split('\n')[0]}`);
75
+ }
76
+ }
77
+ console.log(`\n${projects.length} projeto(s): ${drifted} com drift, ${failed} sem rodar.`);
78
+ console.log('É a rodada 2+ que detecta — a 1ª só semeia o grafo de cada projeto.');
79
+ return drifted > 0 || failed > 0 ? 1 : 0;
80
+ }
28
81
  function printReport(report, domain) {
29
82
  console.log(`\nForja drift:check${domain ? ` --domain ${domain}` : ''} — o verified continua verdade?\n`);
30
83
  console.log(`${report.documents} documento(s) verificado(s), ${report.unchanged} sem mudança, ${report.drifted} com drift detectado.\n`);
@@ -43,6 +96,9 @@ function printReport(report, domain) {
43
96
  console.log('drift:check só sinaliza — corrigir a ADR/spec desatualizada ou reverter o código é decisão humana/de agente, não deste comando.');
44
97
  }
45
98
  async function main() {
99
+ if (process.argv.includes('--all')) {
100
+ process.exit(runAll());
101
+ }
46
102
  const domain = arg('--domain');
47
103
  const graphRoot = process.env.FORJA_GRAPH_ROOT ?? process.cwd();
48
104
  fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
@@ -31,6 +31,7 @@ import { SqliteAgentProfileStore, SqliteGraphStore, SqliteMigrationRunner } from
31
31
  import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
32
32
  import { buildRiskInput, changedFiles, graphRoot } from "../lib/core/risk-collect.js";
33
33
  import { incidentRecords, rankIncidentsByQuery, titleOf } from "../lib/core/incident-search.js";
34
+ import { emitOk, emitError } from "../lib/cli-output.js";
34
35
  const CONSTITUTION_PATH = '.context/architecture/constitution.json';
35
36
  const FLUXO_PATH = 'docs/fluxo.md';
36
37
  /** Parseia a tabela "Etapa → papel → comando → capacidade" de docs/fluxo.md — D2 do plan: uma fonte de verdade, não copiada aqui. */
@@ -189,15 +190,17 @@ async function cmdEngineer(args) {
189
190
  }
190
191
  const objective = args.find((arg, index) => arg !== '--json' && !consumed.has(index));
191
192
  if (!objective) {
192
- console.error('Uso: forja engineer "<objetivo>" [--ref <ref>] [--role <role>] [--json]');
193
+ const usage = 'Uso: forja engineer "<objetivo>" [--ref <ref>] [--role <role>] [--json]';
194
+ if (json)
195
+ emitError(usage); // termina o processo
196
+ console.error(usage);
193
197
  process.exitCode = 1;
194
198
  return;
195
199
  }
196
200
  const report = await buildReport(objective, ref, role);
197
201
  if (json)
198
- console.log(JSON.stringify(report, null, 2));
199
- else
200
- printText(report);
202
+ emitOk({ ...report }); // termina o processo
203
+ printText(report);
201
204
  }
202
205
  async function main() {
203
206
  await cmdEngineer(process.argv.slice(2));
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forja setup — rotina de primeiro uso (SPEC-043 / cli-intuitiva-v1, T9).
4
+ *
5
+ * Roda, em ordem, uma allowlist FIXA de correções idempotentes e seguras. Não é configurável:
6
+ * o valor do comando é ser previsível. Sem `--yes`, pede confirmação; sem TTY e sem `--yes`,
7
+ * aborta sem executar nada — não há como confirmar com segurança num pipe.
8
+ *
9
+ * Cada passo é o próprio comando do core (`node bin/forja.ts <passo>`), então herda os gates e a
10
+ * trilha de auditoria de cada um. Este script não escreve no workspace diretamente.
11
+ *
12
+ * Uso: forja setup [--yes]
13
+ */
14
+ export {};
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forja setup — rotina de primeiro uso (SPEC-043 / cli-intuitiva-v1, T9).
4
+ *
5
+ * Roda, em ordem, uma allowlist FIXA de correções idempotentes e seguras. Não é configurável:
6
+ * o valor do comando é ser previsível. Sem `--yes`, pede confirmação; sem TTY e sem `--yes`,
7
+ * aborta sem executar nada — não há como confirmar com segurança num pipe.
8
+ *
9
+ * Cada passo é o próprio comando do core (`node bin/forja.ts <passo>`), então herda os gates e a
10
+ * trilha de auditoria de cada um. Este script não escreve no workspace diretamente.
11
+ *
12
+ * Uso: forja setup [--yes]
13
+ */
14
+ import { spawnSync } from 'node:child_process';
15
+ import path from 'node:path';
16
+ import readline from 'node:readline';
17
+ import { fileURLToPath } from 'node:url';
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ const forjaBin = path.resolve(__dirname, '..', 'bin', 'forja.ts');
20
+ // Allowlist fixa. Não ler de config, não aceitar via argv. Ordem importa: o índice precede a busca.
21
+ const STEPS = ['workspace:init', 'sync:universal'];
22
+ function ask(question) {
23
+ return new Promise((resolve) => {
24
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
25
+ rl.question(question, (answer) => {
26
+ rl.close();
27
+ resolve(/^s(im)?$/i.test(answer.trim()));
28
+ });
29
+ });
30
+ }
31
+ async function main() {
32
+ const yes = process.argv.slice(2).includes('--yes');
33
+ console.log('forja setup — rotina de primeiro uso');
34
+ console.log(`Passos (allowlist fixa): ${STEPS.join(', ')}\n`);
35
+ if (!yes) {
36
+ if (!process.stdin.isTTY) {
37
+ console.error('Sem TTY para confirmar. Rode `forja setup --yes` para execução não-interativa.');
38
+ return 1;
39
+ }
40
+ const ok = await ask('Executar estes passos agora? [s/N] ');
41
+ if (!ok) {
42
+ console.log('Cancelado. Nada foi executado.');
43
+ return 1;
44
+ }
45
+ }
46
+ for (const step of STEPS) {
47
+ console.log(`\n→ ${step}`);
48
+ const result = spawnSync('node', [forjaBin, step], { cwd: process.cwd(), stdio: 'inherit' });
49
+ const code = result.status ?? 1;
50
+ if (code !== 0) {
51
+ console.error(`\nPasso "${step}" falhou (exit ${code}). Interrompendo — nada além deste ponto foi executado.`);
52
+ return code;
53
+ }
54
+ }
55
+ console.log('\nSetup concluído. Próximo: `forja project:new <nome>` ou `forja spec:new <slug>`.');
56
+ return 0;
57
+ }
58
+ process.exit(await main());
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forja status / forja next (SPEC-044 / forja-status-caminho-feliz).
4
+ *
5
+ * `status` — retrato único do estado (workspace, sprint, corrida, specs, runs, handoffs).
6
+ * `next` — a próxima ação recomendada, uma linha, com o comando exato.
7
+ *
8
+ * Somente leitura. Sai 0 sempre que o modelo montou (subsistema indisponível não é falha do
9
+ * comando). O dispatch por `status`/`next` vem do `args` do registry.
10
+ */
11
+ export {};
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forja status / forja next (SPEC-044 / forja-status-caminho-feliz).
4
+ *
5
+ * `status` — retrato único do estado (workspace, sprint, corrida, specs, runs, handoffs).
6
+ * `next` — a próxima ação recomendada, uma linha, com o comando exato.
7
+ *
8
+ * Somente leitura. Sai 0 sempre que o modelo montou (subsistema indisponível não é falha do
9
+ * comando). O dispatch por `status`/`next` vem do `args` do registry.
10
+ */
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { collectStatus, recommendNext } from "../lib/status-model.js";
14
+ import { emitOk } from "../lib/cli-output.js";
15
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
+ const repoRoot = path.resolve(__dirname, '..');
17
+ function sub(s, render) {
18
+ return s.available ? render(s.value) : [` indisponível: ${s.reason}`];
19
+ }
20
+ function renderStatus(m) {
21
+ const L = ['forja status', ''];
22
+ L.push('Workspace:');
23
+ L.push(` ${m.workspace.root} (origem: ${m.workspace.source})`);
24
+ L.push(` existe: ${m.workspace.exists ? 'sim' : 'não'} · memória indexada: ${m.workspace.memoryIndexed ? 'sim' : 'não'}`);
25
+ L.push('', 'Sprint:');
26
+ L.push(...sub(m.sprint, (s) => s ? [` ${s.title ?? '(sem título)'} — ${s.done}/${s.items} itens`] : [' sem sprint ativa']));
27
+ L.push('', 'Corrida (orchestrate):');
28
+ L.push(...sub(m.orchestrate, ({ runs }) => runs.length === 0
29
+ ? [' nenhuma corrida aberta']
30
+ : runs.map((r) => r.concluded
31
+ ? ` ${r.slug} — concluída`
32
+ : ` ${r.slug} — etapa ${r.openStage}${r.openVerdict ? ` [${r.openVerdict}]` : ''}`)));
33
+ L.push('', 'Specs:');
34
+ L.push(...sub(m.specs, (specs) => {
35
+ if (specs.length === 0)
36
+ return [' nenhuma spec'];
37
+ const byStatus = new Map();
38
+ for (const s of specs) {
39
+ if (!byStatus.has(s.status))
40
+ byStatus.set(s.status, []);
41
+ byStatus.get(s.status).push(s.slug);
42
+ }
43
+ return [...byStatus.entries()].map(([st, slugs]) => ` ${st}: ${slugs.join(', ')}`);
44
+ }));
45
+ L.push('', 'Últimos runs:');
46
+ L.push(...sub(m.recentRuns, (runs) => runs.length
47
+ ? runs.map((r) => ` ${r.exitCode === 0 ? '✓' : '✗'} ${r.cmd} ${r.ts}`)
48
+ : [' nenhum run registrado']));
49
+ L.push('', 'Handoffs em aberto:');
50
+ L.push(...sub(m.handoffs, (hs) => hs.length
51
+ ? hs.map((h) => ` #${h.id} ${h.from} → ${h.to} (${h.intent})${h.slug ? ` — ${h.slug}` : ''}`)
52
+ : [' nenhum']));
53
+ return L.join('\n');
54
+ }
55
+ const argv = process.argv.slice(2);
56
+ const cmd = argv[0] === 'next' ? 'next' : 'status';
57
+ const json = argv.includes('--json');
58
+ const model = await collectStatus(repoRoot);
59
+ if (cmd === 'next') {
60
+ const next = recommendNext(model);
61
+ if (json)
62
+ emitOk({ ...next });
63
+ console.log(`→ ${next.command}`);
64
+ console.log(` ${next.reason}`);
65
+ process.exit(0);
66
+ }
67
+ if (json)
68
+ emitOk({ ...model });
69
+ console.log(renderStatus(model));
70
+ process.exit(0);
@@ -14,48 +14,14 @@
14
14
  * e "banco ausente" no mesmo `null`, e então prescrevia `npm install` — que não recompila binário
15
15
  * nativo. Quem seguisse o conselho do próprio framework não consertava nada.
16
16
  */
17
- import fs from 'node:fs';
18
17
  import path from 'node:path';
19
18
  import { fileURLToPath } from 'node:url';
20
- import { runChecks } from "../lib/core/health.js";
19
+ import { runChecks, bucketFor, BUCKET_LABEL } from "../lib/core/health.js";
20
+ import { listSpecs } from "../lib/specs-index.js";
21
+ import { openHandoffs } from "../lib/handoffs-index.js";
21
22
  const __filename = fileURLToPath(import.meta.url);
22
23
  const __dirname = path.dirname(__filename);
23
24
  const root = path.resolve(__dirname, '..');
24
- function safeReadDir(p) { try {
25
- return fs.readdirSync(p);
26
- }
27
- catch {
28
- return [];
29
- } }
30
- function listSpecs() {
31
- const specsDir = path.join(root, 'specs');
32
- const out = [];
33
- for (const slug of safeReadDir(specsDir)) {
34
- if (slug.startsWith('_') || slug.startsWith('.'))
35
- continue;
36
- const specPath = path.join(specsDir, slug, 'spec.md');
37
- if (!fs.existsSync(specPath))
38
- continue;
39
- const c = fs.readFileSync(specPath, 'utf8');
40
- const m = c.match(/-\s*\*\*Status\*\*:\s*([a-z]+)/i);
41
- out.push({ slug, status: m ? m[1] : 'unknown' });
42
- }
43
- return out;
44
- }
45
- /** Handoffs só fazem sentido com a memória de pé — daí o `memoriaOk` do caller. */
46
- async function openHandoffs() {
47
- try {
48
- const { getWorkspaceDbPath } = await import("../lib/workspace.js");
49
- const { default: Database } = await import('better-sqlite3');
50
- const db = new Database(getWorkspaceDbPath(), { readonly: true });
51
- const rows = db.prepare(`SELECT id, from_agent, to_agent, intent, spec_slug FROM handoffs WHERE status='open' ORDER BY id DESC LIMIT 10`).all();
52
- db.close();
53
- return rows;
54
- }
55
- catch {
56
- return [];
57
- }
58
- }
59
25
  /**
60
26
  * Nunca lança e nunca trava a sessão: o hook reporta, o `tools:doctor` é que é gate. Se a própria
61
27
  * lib de health não carregar, seguimos com o resto do briefing em vez de abortar (ADR-0021).
@@ -69,7 +35,7 @@ async function coreHealth() {
69
35
  }
70
36
  }
71
37
  (async function main() {
72
- const specs = listSpecs();
38
+ const specs = listSpecs(root);
73
39
  const health = await coreHealth();
74
40
  const problemas = health.filter((c) => c.status === 'fail' || c.status === 'warn');
75
41
  const memoriaOk = !health.some((c) => c.status === 'fail');
@@ -78,11 +44,19 @@ async function coreHealth() {
78
44
  lines.push(`Framework: forja (SDD + orquestração)`);
79
45
  if (problemas.length) {
80
46
  lines.push('');
81
- for (const p of problemas) {
82
- const icone = p.status === 'fail' ? '✖' : '⚠';
83
- lines.push(`${icone} ${p.title}: ${p.detail}`);
84
- if (p.fix)
85
- lines.push(` corrigir: ${p.fix}`);
47
+ for (const bucket of ['blocking', 'first-run']) {
48
+ const grp = problemas.filter((p) => bucketFor(p.id) === bucket);
49
+ if (!grp.length)
50
+ continue;
51
+ lines.push(`${BUCKET_LABEL[bucket]}:`);
52
+ for (const p of grp) {
53
+ const icone = p.status === 'fail' ? '✖' : '⚠';
54
+ lines.push(` ${icone} ${p.title}: ${p.detail}`);
55
+ if (p.fix)
56
+ lines.push(` corrigir: ${p.fix}`);
57
+ }
58
+ if (bucket === 'first-run')
59
+ lines.push(' (ou rode tudo: `npm run setup`)');
86
60
  }
87
61
  lines.push(' raio-x completo: `npm run tools:doctor`');
88
62
  }
@@ -94,10 +68,10 @@ async function coreHealth() {
94
68
  if (handoffs.length) {
95
69
  lines.push('\nHandoffs em aberto:');
96
70
  for (const h of handoffs)
97
- lines.push(` - #${h.id} ${h.from_agent} → ${h.to_agent} (${h.intent}) ${h.spec_slug || ''}`);
71
+ lines.push(` - #${h.id} ${h.from} → ${h.to} (${h.intent}) ${h.slug || ''}`);
98
72
  }
99
- lines.push('\nFluxo SDD: `npm run spec:new|plan|tasks|check`');
100
- lines.push('Handoff: `node scripts/agent-router.mjs append <json>`');
73
+ lines.push('\nFluxo SDD: `npm run spec:new|plan|tasks|check` · detalhe: `forja help <comando>`');
74
+ lines.push('Handoff: `npm run hermes:handoff -- \'<json ADR-0005>\'`');
101
75
  lines.push('</framework-status>');
102
76
  process.stdout.write(JSON.stringify({
103
77
  hookSpecificOutput: {