forjajs 2.0.3 → 3.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 (160) hide show
  1. package/.claude/agents/release-auditor.md +19 -10
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +80 -0
  4. package/DOC-MAP.md +9 -0
  5. package/README.md +85 -5
  6. package/README.pt-BR.md +34 -5
  7. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +8 -1
  8. package/dist/apps/dashboard/app/api/forja/guard.d.ts +24 -0
  9. package/dist/apps/dashboard/app/api/forja/guard.js +63 -0
  10. package/dist/apps/server/src/forja-nest.module.js +9 -4
  11. package/dist/apps/server/src/main.js +10 -1
  12. package/dist/bin/forja.js +14 -2
  13. package/dist/lib/code-context.js +6 -0
  14. package/dist/lib/core/architecture-gate.d.ts +20 -0
  15. package/dist/lib/core/architecture-gate.js +60 -0
  16. package/dist/lib/core/doc-graph.js +6 -4
  17. package/dist/lib/core/drift-gate.d.ts +18 -0
  18. package/dist/lib/core/drift-gate.js +55 -0
  19. package/dist/lib/core/gates.d.ts +9 -2
  20. package/dist/lib/core/gates.js +13 -2
  21. package/dist/lib/core/health.js +15 -0
  22. package/dist/lib/core/incident-search.d.ts +19 -0
  23. package/dist/lib/core/incident-search.js +32 -0
  24. package/dist/lib/core/model-pricing.d.ts +31 -0
  25. package/dist/lib/core/model-pricing.js +74 -0
  26. package/dist/lib/core/registry.d.ts +248 -0
  27. package/dist/lib/core/registry.js +249 -0
  28. package/dist/lib/core/release.d.ts +247 -0
  29. package/dist/lib/core/release.js +5 -1
  30. package/dist/lib/core/risk-collect.d.ts +19 -0
  31. package/dist/lib/core/risk-collect.js +173 -0
  32. package/dist/lib/drift-sentinel.d.ts +59 -0
  33. package/dist/lib/drift-sentinel.js +126 -0
  34. package/dist/lib/generators/memory-generator.js +8 -6
  35. package/dist/lib/generators/nest-generator.js +24 -10
  36. package/dist/lib/project-upgrade.js +1 -1
  37. package/dist/lib/workspace.d.ts +7 -0
  38. package/dist/lib/workspace.js +34 -5
  39. package/dist/packages/adapter-git/src/index.d.ts +1 -1
  40. package/dist/packages/adapter-git/src/index.js +11 -6
  41. package/dist/packages/adapter-nest/src/index.d.ts +19 -0
  42. package/dist/packages/adapter-nest/src/index.js +26 -1
  43. package/dist/packages/adapter-sqlite/src/index.d.ts +27 -1
  44. package/dist/packages/adapter-sqlite/src/index.js +49 -0
  45. package/dist/packages/contracts/src/index.d.ts +33 -0
  46. package/dist/packages/contracts/src/index.js +13 -0
  47. package/dist/packages/core/src/index.d.ts +12 -0
  48. package/dist/packages/core/src/index.js +29 -0
  49. package/dist/packages/engineering/architecture/src/index.d.ts +76 -0
  50. package/dist/packages/engineering/architecture/src/index.js +131 -0
  51. package/dist/packages/engineering/evidence/src/index.d.ts +41 -0
  52. package/dist/packages/engineering/evidence/src/index.js +31 -0
  53. package/dist/packages/engineering/identity/src/index.d.ts +57 -0
  54. package/dist/packages/engineering/identity/src/index.js +88 -0
  55. package/dist/packages/engineering/monitoring/src/index.d.ts +37 -0
  56. package/dist/packages/engineering/monitoring/src/index.js +40 -0
  57. package/dist/packages/engineering/provenance/src/index.d.ts +25 -0
  58. package/dist/packages/engineering/provenance/src/index.js +21 -0
  59. package/dist/packages/engineering/risk/src/index.d.ts +89 -0
  60. package/dist/packages/engineering/risk/src/index.js +120 -0
  61. package/dist/packages/graph/src/index.d.ts +23 -1
  62. package/dist/packages/graph/src/index.js +88 -15
  63. package/dist/packages/llm/src/index.d.ts +43 -0
  64. package/dist/packages/llm/src/index.js +131 -0
  65. package/dist/packages/mcp/src/index.js +27 -8
  66. package/dist/packages/orchestration/src/index.d.ts +11 -1
  67. package/dist/packages/orchestration/src/index.js +34 -7
  68. package/dist/packages/policy/src/index.d.ts +40 -0
  69. package/dist/packages/policy/src/index.js +39 -4
  70. package/dist/packages/runtime/src/index.js +3 -0
  71. package/dist/packages/sandbox/src/index.d.ts +47 -0
  72. package/dist/packages/sandbox/src/index.js +59 -0
  73. package/dist/packages/validator/src/index.d.ts +8 -0
  74. package/dist/packages/validator/src/index.js +21 -6
  75. package/dist/scripts/adr.d.ts +17 -0
  76. package/dist/scripts/adr.js +152 -0
  77. package/dist/scripts/agent-harness.js +14 -4
  78. package/dist/scripts/agent.d.ts +27 -0
  79. package/dist/scripts/agent.js +249 -0
  80. package/dist/scripts/architecture.d.ts +16 -0
  81. package/dist/scripts/architecture.js +186 -0
  82. package/dist/scripts/cost-economy.d.ts +2 -0
  83. package/dist/scripts/cost-economy.js +79 -0
  84. package/dist/scripts/demo-autonomy.js +15 -8
  85. package/dist/scripts/demo-workspace.d.ts +6 -0
  86. package/dist/scripts/demo-workspace.js +101 -0
  87. package/dist/scripts/drift-check.d.ts +17 -0
  88. package/dist/scripts/drift-check.js +63 -0
  89. package/dist/scripts/engineer.d.ts +20 -0
  90. package/dist/scripts/engineer.js +208 -0
  91. package/dist/scripts/evidence.d.ts +12 -0
  92. package/dist/scripts/evidence.js +55 -0
  93. package/dist/scripts/gates.d.ts +6 -2
  94. package/dist/scripts/gates.js +14 -4
  95. package/dist/scripts/incident.d.ts +19 -0
  96. package/dist/scripts/incident.js +103 -0
  97. package/dist/scripts/llm-fit.js +160 -0
  98. package/dist/scripts/provenance.d.ts +14 -0
  99. package/dist/scripts/provenance.js +114 -0
  100. package/dist/scripts/risk.d.ts +15 -0
  101. package/dist/scripts/risk.js +81 -0
  102. package/dist/scripts/simulate.d.ts +20 -0
  103. package/dist/scripts/simulate.js +150 -0
  104. package/dist/scripts/sync-universal-memory.js +19 -6
  105. package/docs/architecture/FORJA-3-ENGINEERING-INTELLIGENCE-ARCHITECTURE.md +442 -0
  106. package/docs/llm-fit-loop.md +41 -0
  107. package/docs/modos-de-operacao.md +52 -0
  108. package/docs/produto/factsheet-marketing.md +151 -0
  109. package/docs/produto/roteiro-demo.md +47 -0
  110. package/memory/40-delivery/current-sprint.md +3 -6
  111. package/memory/90-decisions/0074-llm-fit-loop-cli-adapters.md +51 -0
  112. package/memory/90-decisions/0075-workspace-demo-isolado.md +43 -0
  113. package/memory/90-decisions/0076-modos-embedded-e-studio.md +43 -0
  114. package/memory/90-decisions/0077-cost-aware-autonomy-budget.md +95 -0
  115. package/memory/90-decisions/0078-forjajs-3-engineering-control-plane.md +116 -0
  116. package/memory/90-decisions/0079-autonomous-maintenance-readiness.md +102 -0
  117. package/package.json +9 -2
  118. package/specs/agent-identity-reputation/plan.md +133 -0
  119. package/specs/agent-identity-reputation/spec.md +125 -0
  120. package/specs/agent-identity-reputation/tasks.md +51 -0
  121. package/specs/agent-runtime-monitoring/plan.md +78 -0
  122. package/specs/agent-runtime-monitoring/spec.md +92 -0
  123. package/specs/agent-runtime-monitoring/tasks.md +39 -0
  124. package/specs/ai-code-provenance/plan.md +71 -0
  125. package/specs/ai-code-provenance/spec.md +97 -0
  126. package/specs/ai-code-provenance/tasks.md +39 -0
  127. package/specs/architecture-constitution/plan.md +110 -0
  128. package/specs/architecture-constitution/spec.md +114 -0
  129. package/specs/architecture-constitution/tasks.md +58 -0
  130. package/specs/change-risk-engine/plan.md +130 -0
  131. package/specs/change-risk-engine/spec.md +119 -0
  132. package/specs/change-risk-engine/tasks.md +72 -0
  133. package/specs/cost-aware-autonomy-budget/spec.md +102 -0
  134. package/specs/drift-sentinel/spec.md +117 -0
  135. package/specs/engineer-facade-extension/plan.md +71 -0
  136. package/specs/engineer-facade-extension/spec.md +98 -0
  137. package/specs/engineer-facade-extension/tasks.md +36 -0
  138. package/specs/engineering-evidence-ledger/plan.md +121 -0
  139. package/specs/engineering-evidence-ledger/spec.md +90 -0
  140. package/specs/engineering-evidence-ledger/tasks.md +54 -0
  141. package/specs/engineering-graph-extensions/plan.md +92 -0
  142. package/specs/engineering-graph-extensions/spec.md +101 -0
  143. package/specs/engineering-graph-extensions/tasks.md +60 -0
  144. package/specs/engineering-intelligence/spec.md +177 -0
  145. package/specs/learning-loop-incidents/plan.md +59 -0
  146. package/specs/learning-loop-incidents/spec.md +93 -0
  147. package/specs/learning-loop-incidents/tasks.md +36 -0
  148. package/specs/predictive-change-simulation/plan.md +109 -0
  149. package/specs/predictive-change-simulation/spec.md +107 -0
  150. package/specs/predictive-change-simulation/tasks.md +41 -0
  151. package/specs/release-auditor-health/plan.md +88 -0
  152. package/specs/release-auditor-health/spec.md +82 -0
  153. package/specs/release-auditor-health/tasks.md +72 -0
  154. package/specs/smart-agent-routing/plan.md +55 -0
  155. package/specs/smart-agent-routing/spec.md +85 -0
  156. package/specs/smart-agent-routing/tasks.md +26 -0
  157. package/dist/scripts/server-persistence-probe.d.ts +0 -1
  158. package/dist/scripts/server-persistence-probe.js +0 -52
  159. package/dist/scripts/server-persistence-probe.mjs +0 -52
  160. /package/dist/scripts/{server-persistence-probe.d.mts → llm-fit.d.ts} +0 -0
@@ -444,7 +444,7 @@ Antes de qualquer código ou plano de ação, preencha o bloco \`## Raciocínio
444
444
  'skills/llm-provider-routing/SKILL.md': `# Skill: Roteamento de LLM Providers
445
445
 
446
446
  ## Objetivo
447
- Selecionar e configurar uma LLM por papel sem amarrar o projeto a um unico fornecedor.
447
+ Selecionar e configurar uma LLM por papel sem amarrar o projeto a um unico fornecedor, usando o ciclo verificável do Forja.
448
448
 
449
449
  ## Quando usar
450
450
  - O usuario pedir DeepSeek, MiniMax, Mistral, Qwen, Ollama, OpenRouter, Together, Groq, xAI, Cohere, Perplexity ou outro provider.
@@ -454,16 +454,18 @@ Selecionar e configurar uma LLM por papel sem amarrar o projeto a um unico forne
454
454
  ## Regras
455
455
  - Preferir providers locais para tarefas sensiveis quando o modelo disponivel for suficiente.
456
456
  - Usar \`manual\` quando o provider nao tiver CLI local confiavel.
457
- - Registrar \`provider\`, \`model\`, \`command\`, \`taskTypes\` e \`notes\` em \`.memory/agent-llm-routing.json\`.
457
+ - Registrar perfis no workspace em \`.context/llm-profiles.json\` com \`provider\`, \`model\`, \`command\`, \`commandArgs\`, \`roles\`, \`taskTypes\`, \`privacy\` e \`enabled\`.
458
458
  - Nao assumir que uma CLI existe: validar o binario ou documentar o comando esperado.
459
459
  - Nao colocar API keys em memoria, specs, handoffs ou logs.
460
460
 
461
461
  ## Checklist
462
462
  1. Identificar papel e tipo de tarefa.
463
- 2. Escolher provider e modelo no dashboard ou via API \`/api/llm-routing/:role\`.
464
- 3. Preencher \`command\` com a CLI real ou wrapper local.
465
- 4. Rodar um teste pequeno antes de delegar sprint inteira.
466
- 5. Registrar handoff Hermes quando a troca impactar entrega.
463
+ 2. Inicializar ou revisar os perfis com \`forja llm:profiles:init\`.
464
+ 3. Preencher \`command\` com um único executável e \`commandArgs\` para argumentos fixos; nunca use shell ou grave credenciais.
465
+ 4. Rodar \`forja llm:probe <perfil>\` antes de delegar uma sprint inteira.
466
+ 5. Consultar \`forja llm:recommend --role <papel> --task <tipo>\` e aprovar explicitamente a escolha.
467
+ 6. Executar \`forja llm:run --profile <perfil> --task <arquivo>\` e avaliar com \`forja llm:eval --scope model --id <provider:model>\`.
468
+ 7. Registrar handoff Hermes quando a troca impactar entrega.
467
469
  `,
468
470
  'skills/MANIFEST.json': `{
469
471
  "version": "0.5.0",
@@ -104,6 +104,9 @@ import { AppModule } from './app.module';
104
104
  async function bootstrap(): Promise<void> {
105
105
  const app = await NestFactory.create(AppModule);
106
106
  app.setGlobalPrefix('api');
107
+ // Lets Nest call each provider's onModuleDestroy (e.g. OpsService closing its sqlite handle)
108
+ // on SIGINT/SIGTERM instead of the process exiting with the database handle left open.
109
+ app.enableShutdownHooks();
107
110
  await app.listen(process.env.PORT ? Number(process.env.PORT) : 3000);
108
111
  }
109
112
 
@@ -143,12 +146,12 @@ export class AppService {
143
146
  }
144
147
  }
145
148
  `,
146
- 'backend/src/modules/ops/ops.service.ts': `import { Injectable } from '@nestjs/common';
149
+ 'backend/src/modules/ops/ops.service.ts': `import { Injectable, OnModuleDestroy } from '@nestjs/common';
147
150
  import * as Database from 'better-sqlite3';
148
151
  import * as path from 'node:path';
149
152
 
150
153
  @Injectable()
151
- export class OpsService {
154
+ export class OpsService implements OnModuleDestroy {
152
155
  private db: any;
153
156
 
154
157
  constructor() {
@@ -160,14 +163,25 @@ export class OpsService {
160
163
  const agents = this.db.prepare('SELECT agent_name, status, current_task FROM agent_sessions').all();
161
164
  const tasks = this.db.prepare('SELECT status, COUNT(*) as count FROM tasks GROUP BY status').all();
162
165
  const handoffs = this.db.prepare('SELECT from_agent, to_agent, title, created_at FROM handoffs ORDER BY created_at DESC LIMIT 5').all();
163
-
166
+
164
167
  return { agents, tasks, handoffs };
165
168
  }
169
+
170
+ // Closes the sqlite handle on SIGINT/SIGTERM (via app.enableShutdownHooks() in main.ts),
171
+ // rather than leaving it open for the process to exit around.
172
+ onModuleDestroy() {
173
+ this.db.close();
174
+ }
166
175
  }
167
176
  `,
168
177
  'backend/src/modules/ops/ops.controller.ts': `import { Controller, Get } from '@nestjs/common';
169
178
  import { OpsService } from './ops.service';
170
179
 
180
+ /** Escapa HTML para evitar XSS refletido/armazenado via agent_name/current_task/status/title etc. (dados livres vindos do SQLite). */
181
+ function esc(value: unknown): string {
182
+ return String(value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' } as Record<string, string>)[c]);
183
+ }
184
+
171
185
  @Controller('ops')
172
186
  export class OpsController {
173
187
  constructor(private readonly opsService: OpsService) {}
@@ -180,7 +194,7 @@ export class OpsController {
180
194
  @Get()
181
195
  renderDashboard() {
182
196
  const stats = this.opsService.getStats();
183
-
197
+
184
198
  return \`
185
199
  <!DOCTYPE html>
186
200
  <html lang="pt-BR">
@@ -207,8 +221,8 @@ export class OpsController {
207
221
  <div class="space-y-4">
208
222
  \${stats.agents.map((a: any) => \`
209
223
  <div class="p-3 bg-gray-900 rounded-lg border-l-4 \${a.status === 'IDLE' ? 'border-green-500' : 'border-yellow-500'}">
210
- <div class="font-bold">\${a.agent_name}</div>
211
- <div class="text-xs text-gray-400">\${a.status} \${a.current_task ? ' - ' + a.current_task : ''}</div>
224
+ <div class="font-bold">\${esc(a.agent_name)}</div>
225
+ <div class="text-xs text-gray-400">\${esc(a.status)} \${a.current_task ? ' - ' + esc(a.current_task) : ''}</div>
212
226
  </div>
213
227
  \`).join('')}
214
228
  </div>
@@ -222,8 +236,8 @@ export class OpsController {
222
236
  <div class="space-y-4">
223
237
  \${stats.tasks.map((t: any) => \`
224
238
  <div class="flex justify-between items-center">
225
- <span class="capitalize">\${t.status}</span>
226
- <span class="bg-blue-600 px-2 py-1 rounded text-xs">\${t.count}</span>
239
+ <span class="capitalize">\${esc(t.status)}</span>
240
+ <span class="bg-blue-600 px-2 py-1 rounded text-xs">\${esc(t.count)}</span>
227
241
  </div>
228
242
  \`).join('')}
229
243
  </div>
@@ -237,8 +251,8 @@ export class OpsController {
237
251
  <div class="space-y-3">
238
252
  \${stats.handoffs.map((h: any) => \`
239
253
  <div class="text-xs border-b border-gray-700 pb-2">
240
- <div class="text-blue-300 font-medium">\${h.from_agent} → \${h.to_agent}</div>
241
- <div class="text-gray-400 truncate">\${h.title}</div>
254
+ <div class="text-blue-300 font-medium">\${esc(h.from_agent)} → \${esc(h.to_agent)}</div>
255
+ <div class="text-gray-400 truncate">\${esc(h.title)}</div>
242
256
  </div>
243
257
  \`).join('')}
244
258
  </div>
@@ -37,7 +37,7 @@ export function listFiles(root, env = defaultEnv) {
37
37
  if (st.isDirectory())
38
38
  walk(p);
39
39
  else
40
- out.push(path.relative(root, p));
40
+ out.push(path.relative(root, p).replaceAll(path.sep, '/'));
41
41
  }
42
42
  };
43
43
  walk(root);
@@ -18,7 +18,14 @@
18
18
  * .context/ # runbooks GSD de produto
19
19
  * .forjarc.json # config local do workspace (opcional)
20
20
  */
21
+ export type ForjaMode = 'embedded' | 'studio';
21
22
  export declare function getUserConfigPath(): string;
23
+ /**
24
+ * Studio administra vários produtos num workspace externo. Embedded opera a instalação do ForjaJS
25
+ * dentro do projeto consumidor. A detecção pelo package.json torna `npx forja`/bin local natural;
26
+ * FORJA_MODE existe para scripts e casos sem manifest.
27
+ */
28
+ export declare function getForjaMode(): ForjaMode;
22
29
  export declare function getWorkspaceRoot(): string;
23
30
  export declare function getWorkspaceInfo(): {
24
31
  root: string;
@@ -40,7 +40,25 @@ function readJsonSafe(filePath) {
40
40
  export function getUserConfigPath() {
41
41
  return path.join(getHomeDir(), '.forjarc.json');
42
42
  }
43
+ /**
44
+ * Studio administra vários produtos num workspace externo. Embedded opera a instalação do ForjaJS
45
+ * dentro do projeto consumidor. A detecção pelo package.json torna `npx forja`/bin local natural;
46
+ * FORJA_MODE existe para scripts e casos sem manifest.
47
+ */
48
+ export function getForjaMode() {
49
+ if (process.env.FORJA_MODE === 'embedded' || process.env.FORJA_MODE === 'studio')
50
+ return process.env.FORJA_MODE;
51
+ if (process.env.FORJA_WORKSPACE)
52
+ return 'studio';
53
+ const cwd = path.resolve(process.cwd());
54
+ const frameworkRoot = path.resolve(__dirname, '..');
55
+ if (cwd !== frameworkRoot && !cwd.startsWith(`${frameworkRoot}${path.sep}`) && fs.existsSync(path.join(cwd, 'package.json')))
56
+ return 'embedded';
57
+ return 'studio';
58
+ }
43
59
  export function getWorkspaceRoot() {
60
+ if (getForjaMode() === 'embedded')
61
+ return path.resolve(process.cwd());
44
62
  if (process.env.FORJA_WORKSPACE) {
45
63
  return path.resolve(process.env.FORJA_WORKSPACE);
46
64
  }
@@ -54,15 +72,19 @@ export function getWorkspaceInfo() {
54
72
  const root = getWorkspaceRoot();
55
73
  return {
56
74
  root,
57
- source: process.env.FORJA_WORKSPACE
58
- ? 'FORJA_WORKSPACE'
59
- : fs.existsSync(getUserConfigPath())
60
- ? '~/.forjarc.json'
61
- : 'default',
75
+ source: getForjaMode() === 'embedded'
76
+ ? 'project-cwd'
77
+ : process.env.FORJA_WORKSPACE
78
+ ? 'FORJA_WORKSPACE'
79
+ : fs.existsSync(getUserConfigPath())
80
+ ? '~/.forjarc.json'
81
+ : 'default',
62
82
  exists: fs.existsSync(root),
63
83
  };
64
84
  }
65
85
  export function getProjectsDir() {
86
+ if (getForjaMode() === 'embedded')
87
+ return getWorkspaceRoot();
66
88
  return path.join(getWorkspaceRoot(), 'projects');
67
89
  }
68
90
  export function getWorkspaceMemoryDir() {
@@ -110,6 +132,13 @@ export function ensureDir(dir) {
110
132
  }
111
133
  export function initWorkspace() {
112
134
  const root = ensureDir(getWorkspaceRoot());
135
+ if (getForjaMode() === 'embedded') {
136
+ ensureDir(getWorkspaceMemoryDir());
137
+ ensureDir(getWorkspaceDbDir());
138
+ ensureDir(getWorkspaceSpecsDir());
139
+ ensureDir(getWorkspaceContextDir());
140
+ return root;
141
+ }
113
142
  ensureDir(getProjectsDir());
114
143
  ensureDir(getWorkspaceMemoryDir());
115
144
  ensureDir(getWorkspaceDbDir());
@@ -1,5 +1,5 @@
1
1
  import type { DeterministicDocument, GraphDocumentSource } from '../../graph/src/index.ts';
2
- import type { ISO8601 } from '../../contracts/src/index.ts';
2
+ import { type ISO8601 } from '../../contracts/src/index.ts';
3
3
  import type { SandboxBackend, SandboxCommandResult, SandboxDiffData, SandboxValidation } from '../../sandbox/src/index.ts';
4
4
  import type { SandboxCommand, SandboxSession } from '../../contracts/src/index.ts';
5
5
  export interface CommandRunner {
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { graphDocumentId } from "../../graph/src/index.js";
5
+ import { isPathWithinRoot } from "../../contracts/src/index.js";
5
6
  export class SpawnCommandRunner {
6
7
  run(command) {
7
8
  const started = Date.now();
@@ -27,7 +28,7 @@ export class GitGraphDocumentSource {
27
28
  if (!isIndexable(relative))
28
29
  continue;
29
30
  const absolute = path.join(this.root, relative);
30
- if (!isWithinRoot(this.root, absolute))
31
+ if (!isPathWithinRoot(this.root, absolute))
31
32
  continue;
32
33
  try {
33
34
  const content = fs.readFileSync(absolute, 'utf8');
@@ -45,13 +46,17 @@ function isIndexable(relative) {
45
46
  return false;
46
47
  return /\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|yaml|yml)$/.test(relative);
47
48
  }
48
- function isWithinRoot(root, candidate) {
49
- const relative = path.relative(root, candidate);
50
- return relative.length === 0 || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
51
- }
49
+ /**
50
+ * `HOME`/`USERPROFILE` (SPEC-038 achado real): sem eles, `npm` não consegue resolver seu diretório
51
+ * de config/cache e trava indefinidamente em vez de falhar rápido — reproduzido rodando
52
+ * `forja simulate` com `--command "npm test"` contra este próprio repositório. Nenhum dos dois é
53
+ * segredo (são só um path de diretório), então passá-los adiante não viola o teste
54
+ * "runner não herda secrets do ambiente por padrão" (`test/adapter-git.test.js`) — esse teste
55
+ * cobre uma env var arbitrária do processo host, não este allowlist fixo.
56
+ */
52
57
  function sandboxEnvironment(overrides) {
53
58
  const inherited = {};
54
- for (const key of ['PATH', 'NODE_PATH', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP']) {
59
+ for (const key of ['PATH', 'NODE_PATH', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP', 'HOME', 'USERPROFILE']) {
55
60
  const value = process.env[key];
56
61
  if (value !== undefined)
57
62
  inherited[key] = value;
@@ -7,7 +7,17 @@ export interface HttpRequest {
7
7
  readonly body?: unknown;
8
8
  readonly headers: Readonly<Record<string, string | undefined>>;
9
9
  readonly correlationId?: string;
10
+ /** `req.socket.remoteAddress` (or equivalent) of the caller, when known. Used to fail closed to
11
+ * loopback-only access when no authenticator is configured — see `isLoopbackAddress`. */
12
+ readonly remoteAddress?: string;
10
13
  }
14
+ /**
15
+ * True for 127.0.0.0/8 and ::1 (with the common ::ffff:-mapped IPv4 form normalized first).
16
+ * `address === undefined` returns false — "unknown" is not "trusted" — but callers that only have
17
+ * a real remote address for genuine network connections (never for direct in-process calls) may
18
+ * choose to treat a missing address as trusted at the call site; this helper stays strict.
19
+ */
20
+ export declare function isLoopbackAddress(address: string | undefined): boolean;
11
21
  export interface HttpResponse {
12
22
  readonly status: number;
13
23
  readonly headers: Readonly<Record<string, string>>;
@@ -50,6 +60,15 @@ export declare class ForjaNestAdapter {
50
60
  private readonly controlPlane?;
51
61
  constructor(mcp: McpServer, stream?: EventStream, authenticator?: LocalAuthenticator, controlPlane?: ControlPlanePort);
52
62
  handle(request: HttpRequest): Promise<HttpResponse>;
63
+ /**
64
+ * Fails closed when no authenticator is configured: previously this meant "allow everyone", which
65
+ * left any request that reached the process (e.g. a container-network or port-forward hop) fully
66
+ * unauthenticated. Now it means "loopback callers only". `remoteAddress` being unset (rather than
67
+ * a real non-loopback address) is treated as an internal/direct call — e.g. dispatched in-process,
68
+ * not received over an actual socket — and stays trusted; a genuine HTTP layer always supplies it
69
+ * (see ForjaLocalAuthGuard, which reads it straight off the raw socket).
70
+ */
71
+ private isAuthenticated;
53
72
  subscribeSse(listener: (event: SseEvent) => void): () => void;
54
73
  modules(): readonly NestModuleDefinition[];
55
74
  openApi(): OpenApiDocument;
@@ -1,4 +1,16 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
+ /**
3
+ * True for 127.0.0.0/8 and ::1 (with the common ::ffff:-mapped IPv4 form normalized first).
4
+ * `address === undefined` returns false — "unknown" is not "trusted" — but callers that only have
5
+ * a real remote address for genuine network connections (never for direct in-process calls) may
6
+ * choose to treat a missing address as trusted at the call site; this helper stays strict.
7
+ */
8
+ export function isLoopbackAddress(address) {
9
+ if (address === undefined)
10
+ return false;
11
+ const value = address.startsWith('::ffff:') ? address.slice(7) : address;
12
+ return value === '127.0.0.1' || value === '::1' || value.startsWith('127.');
13
+ }
2
14
  export function createBearerAuthenticator(token) {
3
15
  if (token.length === 0)
4
16
  throw new NestAdapterError('Bearer token is required');
@@ -38,7 +50,7 @@ export class ForjaNestAdapter {
38
50
  async handle(request) {
39
51
  const correlationId = request.correlationId ?? request.headers['x-correlation-id'] ?? `http:${request.method}:${request.path}`;
40
52
  try {
41
- if (this.authenticator !== undefined && !(await this.authenticator.authenticate(request.headers)))
53
+ if (!(await this.isAuthenticated(request)))
42
54
  return { status: 401, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId, 'www-authenticate': 'Bearer' }, body: { error: { code: 'UNAUTHENTICATED', message: 'Local authentication required' } }, correlationId };
43
55
  const result = await this.dispatch(request);
44
56
  return this.result(correlationId, result);
@@ -47,6 +59,19 @@ export class ForjaNestAdapter {
47
59
  return this.error(correlationId, error instanceof Error ? error.message : 'Unknown HTTP adapter error');
48
60
  }
49
61
  }
62
+ /**
63
+ * Fails closed when no authenticator is configured: previously this meant "allow everyone", which
64
+ * left any request that reached the process (e.g. a container-network or port-forward hop) fully
65
+ * unauthenticated. Now it means "loopback callers only". `remoteAddress` being unset (rather than
66
+ * a real non-loopback address) is treated as an internal/direct call — e.g. dispatched in-process,
67
+ * not received over an actual socket — and stays trusted; a genuine HTTP layer always supplies it
68
+ * (see ForjaLocalAuthGuard, which reads it straight off the raw socket).
69
+ */
70
+ async isAuthenticated(request) {
71
+ if (this.authenticator === undefined)
72
+ return request.remoteAddress === undefined || isLoopbackAddress(request.remoteAddress);
73
+ return this.authenticator.authenticate(request.headers);
74
+ }
50
75
  subscribeSse(listener) {
51
76
  if (this.stream === undefined)
52
77
  throw new NestAdapterError('Event stream is not configured');
@@ -1,5 +1,6 @@
1
- import type { AuditRecord, Checkpoint, DomainEvent, EntityId, ExecutionResult, Handoff, Observation, RuntimeRun, SandboxSession, Sprint, Task, RunId } from '../../contracts/src/index.ts';
1
+ import type { AgentProfile2, AuditRecord, Checkpoint, DomainEvent, EntityId, ExecutionResult, Handoff, Observation, RuntimeRun, SandboxSession, Sprint, Task, RunId } from '../../contracts/src/index.ts';
2
2
  import type { EventStore } from '../../events/src/index.ts';
3
+ import type { ProvenanceRecord } from '../../engineering/provenance/src/index.ts';
3
4
  import type { ApprovalStore } from '../../policy/src/index.ts';
4
5
  import type { CheckpointStore, RuntimePersistence, RuntimePlanStep } from '../../runtime/src/index.ts';
5
6
  import type { McpAuditEvent, McpAuditSink } from '../../mcp/src/index.ts';
@@ -89,6 +90,16 @@ export declare class SqliteGraphStore implements GraphStore {
89
90
  saveEvidence(item: Evidence): void;
90
91
  getSourceChecksum(sourceKey: string): string | undefined;
91
92
  saveSourceChecksum(sourceKey: string, checksum: string): void;
93
+ /**
94
+ * Achado real de performance (`GraphIndexer.sync` contra ~1000 documentos): sem isto, cada
95
+ * `saveNode`/`saveEdge`/`saveEvidence` era um `INSERT` num commit implícito próprio — dezenas de
96
+ * milhares de fsyncs. Um `BEGIN`/`COMMIT` por chamada externa (não por `INSERT`), com
97
+ * `ROLLBACK` em erro. Contador de profundidade evita `BEGIN` aninhado (SQLite não suporta —
98
+ * chamadas aninhadas de `transaction()`, se algum código futuro fizer isso, só participam da
99
+ * transação já aberta pelo nível mais externo).
100
+ */
101
+ private transactionDepth;
102
+ transaction<T>(fn: () => T): T;
92
103
  private payload;
93
104
  private listPayload;
94
105
  }
@@ -104,6 +115,21 @@ export declare class SqliteRuntimeRunStore {
104
115
  save(value: RuntimeRun): void;
105
116
  get(runId: RunId): RuntimeRun | undefined;
106
117
  }
118
+ /** SPEC-036 — reaproveita `SqliteJsonRepository` (tabela genérica `forja_records`), sem migration própria (D3 do plan). */
119
+ export declare class SqliteAgentProfileStore {
120
+ private readonly repository;
121
+ constructor(db: SqliteConnection);
122
+ save(value: AgentProfile2): void;
123
+ get(id: EntityId): AgentProfile2 | undefined;
124
+ list(): readonly AgentProfile2[];
125
+ }
126
+ /** SPEC-039 — reaproveita `SqliteJsonRepository`, sem migration própria (mesmo padrão de `SqliteAgentProfileStore`). Chave `${runId}:${file}` — regravar o mesmo run é idempotente, não duplica. */
127
+ export declare class SqliteProvenanceStore {
128
+ private readonly repository;
129
+ constructor(db: SqliteConnection);
130
+ save(value: ProvenanceRecord): void;
131
+ list(): readonly ProvenanceRecord[];
132
+ }
107
133
  export declare class SqliteRuntimePersistence implements RuntimePersistence {
108
134
  private readonly db;
109
135
  constructor(db: SqliteConnection);
@@ -129,6 +129,40 @@ export class SqliteGraphStore {
129
129
  return isRecord(row) && typeof row.checksum === 'string' ? row.checksum : undefined;
130
130
  }
131
131
  saveSourceChecksum(sourceKey, checksum) { this.db.prepare('INSERT INTO graph_sources (source_key, checksum, updated_at) VALUES (?, ?, ?) ON CONFLICT(source_key) DO UPDATE SET checksum = excluded.checksum, updated_at = excluded.updated_at').run(sourceKey, checksum, new Date().toISOString()); }
132
+ /**
133
+ * Achado real de performance (`GraphIndexer.sync` contra ~1000 documentos): sem isto, cada
134
+ * `saveNode`/`saveEdge`/`saveEvidence` era um `INSERT` num commit implícito próprio — dezenas de
135
+ * milhares de fsyncs. Um `BEGIN`/`COMMIT` por chamada externa (não por `INSERT`), com
136
+ * `ROLLBACK` em erro. Contador de profundidade evita `BEGIN` aninhado (SQLite não suporta —
137
+ * chamadas aninhadas de `transaction()`, se algum código futuro fizer isso, só participam da
138
+ * transação já aberta pelo nível mais externo).
139
+ */
140
+ transactionDepth = 0;
141
+ transaction(fn) {
142
+ if (this.transactionDepth > 0) {
143
+ this.transactionDepth += 1;
144
+ try {
145
+ return fn();
146
+ }
147
+ finally {
148
+ this.transactionDepth -= 1;
149
+ }
150
+ }
151
+ this.transactionDepth = 1;
152
+ this.db.exec('BEGIN');
153
+ try {
154
+ const result = fn();
155
+ this.db.exec('COMMIT');
156
+ return result;
157
+ }
158
+ catch (error) {
159
+ this.db.exec('ROLLBACK');
160
+ throw error;
161
+ }
162
+ finally {
163
+ this.transactionDepth = 0;
164
+ }
165
+ }
132
166
  payload(sql, id) {
133
167
  const row = this.db.prepare(sql).get(id);
134
168
  return isRecord(row) && typeof row.payload === 'string' ? JSON.parse(row.payload) : undefined;
@@ -154,6 +188,21 @@ export class SqliteRuntimeRunStore {
154
188
  save(value) { this.repository.put('runtime_run', value.runId, value, value.updatedAt); }
155
189
  get(runId) { return this.repository.get('runtime_run', runId); }
156
190
  }
191
+ /** SPEC-036 — reaproveita `SqliteJsonRepository` (tabela genérica `forja_records`), sem migration própria (D3 do plan). */
192
+ export class SqliteAgentProfileStore {
193
+ repository;
194
+ constructor(db) { this.repository = new SqliteJsonRepository(db); }
195
+ save(value) { this.repository.put('agent_profile', value.id, value, value.updatedAt); }
196
+ get(id) { return this.repository.get('agent_profile', id); }
197
+ list() { return this.repository.list('agent_profile'); }
198
+ }
199
+ /** SPEC-039 — reaproveita `SqliteJsonRepository`, sem migration própria (mesmo padrão de `SqliteAgentProfileStore`). Chave `${runId}:${file}` — regravar o mesmo run é idempotente, não duplica. */
200
+ export class SqliteProvenanceStore {
201
+ repository;
202
+ constructor(db) { this.repository = new SqliteJsonRepository(db); }
203
+ save(value) { this.repository.put('provenance_record', `${value.runId}:${value.file}`, value, value.recordedAt); }
204
+ list() { return this.repository.list('provenance_record'); }
205
+ }
157
206
  export class SqliteRuntimePersistence {
158
207
  db;
159
208
  constructor(db) { this.db = db; }
@@ -88,6 +88,28 @@ export interface AgentProfile extends AgentIdentity {
88
88
  readonly capabilities: readonly CapabilityId[];
89
89
  readonly permissions: readonly string[];
90
90
  }
91
+ /**
92
+ * Registro persistente de agente (SPEC-036) — `AgentIdentity` continua sendo o tipo efêmero por
93
+ * run (`PolicyRequest`/`RuntimeRun`); este é o registro entre runs, com reputação derivada de
94
+ * comportamento real. `trustLevel`/`autonomyLevel`/`lastScoredAt` só são escritos por
95
+ * `computeReputationScore` (via `agent:score`) — nunca aceitos em `agent:register`.
96
+ */
97
+ export interface AgentProfile2 extends AuditFields {
98
+ readonly id: EntityId;
99
+ readonly role: string;
100
+ readonly provider?: string;
101
+ readonly model?: string;
102
+ readonly capabilities: readonly string[];
103
+ readonly architectureDomains: readonly string[];
104
+ readonly limits?: {
105
+ readonly maxFiles?: number;
106
+ readonly maxCostUsd?: number;
107
+ readonly maxDurationMs?: number;
108
+ };
109
+ readonly trustLevel?: number;
110
+ readonly autonomyLevel?: 'autonomous' | 'autonomous_with_review' | 'supervised' | 'human_in_the_loop';
111
+ readonly lastScoredAt?: ISO8601;
112
+ }
91
113
  export interface PolicyDecision {
92
114
  readonly effect: PolicyEffect;
93
115
  readonly reason: string;
@@ -188,6 +210,9 @@ export interface DomainEvent extends AuditFields {
188
210
  readonly payload: unknown;
189
211
  readonly idempotencyKey: string;
190
212
  }
213
+ /** `documentStatus` is the source document's own lifecycle (e.g. an ADR's accepted/superseded, a
214
+ * spec's draft/approved) — deliberately not `status: KnowledgeStatus`, which grades the epistemic
215
+ * confidence of a *relation*, not a document's lifecycle. Keep the two vocabularies separate. */
191
216
  export interface GraphNode extends AuditFields {
192
217
  readonly id: EntityId;
193
218
  readonly type: string;
@@ -195,6 +220,7 @@ export interface GraphNode extends AuditFields {
195
220
  readonly status: KnowledgeStatus;
196
221
  readonly validFrom?: ISO8601;
197
222
  readonly validTo?: ISO8601;
223
+ readonly documentStatus?: string;
198
224
  }
199
225
  export interface GraphEdge extends AuditFields {
200
226
  readonly id: EntityId;
@@ -365,4 +391,11 @@ export declare class ContractValidationError extends Error {
365
391
  }
366
392
  export declare function assertContract(condition: boolean, path: string, message: string): asserts condition;
367
393
  export declare function validateTokenBudget(value: TokenBudget): TokenBudget;
394
+ /**
395
+ * True only when `candidate` resolves inside `root` (or equals it). Uses `path.relative` +
396
+ * separator-boundary check rather than `String.startsWith(root)`, which a sibling path
397
+ * (`/root-evil`) or an unresolved `..` segment can satisfy without ever being inside `root`.
398
+ * Both arguments should already be absolute; relative inputs are resolved against `process.cwd()`.
399
+ */
400
+ export declare function isPathWithinRoot(root: string, candidate: string): boolean;
368
401
  export declare function validateCapabilityDefinition(value: CapabilityDefinition): CapabilityDefinition;
@@ -1,4 +1,5 @@
1
1
  /** Versioned, framework-independent contracts for ForjaJS 2.0. */
2
+ import path from 'node:path';
2
3
  export const CONTRACT_VERSION = '2.0';
3
4
  export class ContractValidationError extends Error {
4
5
  path;
@@ -15,6 +16,18 @@ export function validateTokenBudget(value) {
15
16
  assertContract(Number.isInteger(value.usedTokens) && value.usedTokens >= 0 && value.usedTokens <= value.totalTokens, 'budget.usedTokens', 'must be within totalTokens');
16
17
  return value;
17
18
  }
19
+ /**
20
+ * True only when `candidate` resolves inside `root` (or equals it). Uses `path.relative` +
21
+ * separator-boundary check rather than `String.startsWith(root)`, which a sibling path
22
+ * (`/root-evil`) or an unresolved `..` segment can satisfy without ever being inside `root`.
23
+ * Both arguments should already be absolute; relative inputs are resolved against `process.cwd()`.
24
+ */
25
+ export function isPathWithinRoot(root, candidate) {
26
+ const resolvedRoot = path.resolve(root);
27
+ const resolvedCandidate = path.resolve(candidate);
28
+ const relative = path.relative(resolvedRoot, resolvedCandidate);
29
+ return relative.length === 0 || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
30
+ }
18
31
  export function validateCapabilityDefinition(value) {
19
32
  assertContract(value.schemaVersion === CONTRACT_VERSION, 'schemaVersion', `must be ${CONTRACT_VERSION}`);
20
33
  assertContract(/^[-a-z0-9]+(?:\.[-a-z0-9]+)+$/.test(value.id), 'id', 'must be a namespaced capability id');
@@ -14,6 +14,7 @@ export interface CapabilityAuthorizationRequest {
14
14
  readonly definition: CapabilityDefinition;
15
15
  readonly input: CapabilityInput;
16
16
  readonly agent: AgentIdentity;
17
+ readonly correlationId?: string;
17
18
  readonly projectId?: string;
18
19
  readonly environment: string;
19
20
  readonly categories: readonly string[];
@@ -47,6 +48,16 @@ export interface CapabilityExecutionRequest {
47
48
  readonly files?: readonly string[];
48
49
  readonly budget?: TokenBudget;
49
50
  readonly approval?: CapabilityAuthorizationRequest['approval'];
51
+ /**
52
+ * Real dollar cost projected for this call (SPEC-029), computed by the CALLER from tokens +
53
+ * a local price table before `execute` runs. `packages/core` deliberately stays decoupled from
54
+ * pricing-table specifics (see docs/architecture/FORJA-2.0-ARCHITECTURE.md, "Direção de
55
+ * dependência") — it only compares this plain number against `PolicyLimits.maxCostUsd`, the same
56
+ * way `budget.totalTokens` is compared against `maxTokens`. Leave undefined when the caller has no
57
+ * price for the model/provider in play (unknown pricing must fail OPEN for cost enforcement
58
+ * specifically — see `checkLimits` — never DENY a legitimate execution over a pricing-table gap).
59
+ */
60
+ readonly estimatedCostUsd?: number;
50
61
  }
51
62
  export declare class CapabilityRegistryError extends Error {
52
63
  constructor(message: string);
@@ -58,6 +69,7 @@ export declare class CapabilityRegistry {
58
69
  list(filter?: CapabilityListFilter): readonly CapabilityDefinition[];
59
70
  describe(idOrAlias: string, filter?: CapabilityListFilter): CapabilityDefinition;
60
71
  execute(request: CapabilityExecutionRequest): Promise<ExecutionResult>;
72
+ private checkLimits;
61
73
  private resolve;
62
74
  private tryResolve;
63
75
  private isVisible;
@@ -66,6 +66,7 @@ export class CapabilityRegistry {
66
66
  definition: registration.definition,
67
67
  input: request.input,
68
68
  agent: request.agent,
69
+ correlationId: request.correlationId ?? runId,
69
70
  projectId: request.projectId,
70
71
  environment: request.environment ?? 'local',
71
72
  categories: request.categories ?? [],
@@ -91,6 +92,14 @@ export class CapabilityRegistry {
91
92
  evidence: [],
92
93
  };
93
94
  }
95
+ // `ALLOW_WITH_LIMITS` is only meaningful if the limits it carries actually bound the call —
96
+ // otherwise it behaves exactly like ALLOW, silently. maxFiles, maxTokens and maxCostUsd are
97
+ // checked here because all three are already known before the handler runs; maxDurationMs/
98
+ // maxRetries govern the runtime engine's own retry/step loop (RuntimeEngine.limits) rather than
99
+ // a single call.
100
+ const limitError = this.checkLimits(decision, request);
101
+ if (limitError !== undefined)
102
+ return this.failure(runId, timestamps, limitError);
94
103
  try {
95
104
  const output = await registration.handler(input, { runId, agent: request.agent, definition: registration.definition });
96
105
  registration.validateOutput(output.payload);
@@ -102,6 +111,26 @@ export class CapabilityRegistry {
102
111
  return this.failure(runId, timestamps, this.toExecutionError('HANDLER_FAILED', error, true));
103
112
  }
104
113
  }
114
+ checkLimits(decision, request) {
115
+ const limits = decision.limits;
116
+ if (limits === undefined)
117
+ return undefined;
118
+ const fileCount = request.files?.length ?? 0;
119
+ if (limits.maxFiles !== undefined && fileCount > limits.maxFiles) {
120
+ return { code: 'POLICY_LIMIT_EXCEEDED', message: `Policy limit exceeded: ${fileCount} files touched, maxFiles is ${limits.maxFiles}`, retryable: false };
121
+ }
122
+ const requestedTokens = request.budget?.totalTokens ?? 0;
123
+ if (limits.maxTokens !== undefined && requestedTokens > limits.maxTokens) {
124
+ return { code: 'POLICY_LIMIT_EXCEEDED', message: `Policy limit exceeded: budget of ${requestedTokens} tokens exceeds maxTokens ${limits.maxTokens}`, retryable: false };
125
+ }
126
+ // Fail-open by design (SPEC-029, AC-4): when the caller has no estimated cost (unknown
127
+ // provider/model pricing, or a capability that isn't priced at all), maxCostUsd simply isn't
128
+ // enforced for this call — a pricing-table gap must never block otherwise-legitimate work.
129
+ if (limits.maxCostUsd !== undefined && request.estimatedCostUsd !== undefined && request.estimatedCostUsd > limits.maxCostUsd) {
130
+ return { code: 'POLICY_LIMIT_EXCEEDED', message: `Policy limit exceeded: estimated cost $${request.estimatedCostUsd.toFixed(4)} exceeds maxCostUsd $${limits.maxCostUsd}`, retryable: false };
131
+ }
132
+ return undefined;
133
+ }
105
134
  resolve(idOrAlias) {
106
135
  const id = this.aliases.get(idOrAlias);
107
136
  if (id === undefined)