forjajs 2.0.1 → 2.0.3

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 (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +22 -0
  3. package/README.pt-BR.md +22 -0
  4. package/dist/apps/cli/src/index.d.ts +44 -0
  5. package/dist/apps/cli/src/index.js +304 -0
  6. package/dist/apps/server/src/main.d.ts +9 -3
  7. package/dist/apps/server/src/main.js +70 -19
  8. package/dist/bin/forja.js +213 -0
  9. package/dist/lib/core/health.js +2 -1
  10. package/dist/lib/core/registry.d.ts +17 -0
  11. package/dist/lib/core/registry.js +17 -0
  12. package/dist/lib/core/release.d.ts +16 -0
  13. package/dist/packages/adapter-git/src/index.d.ts +14 -0
  14. package/dist/packages/adapter-git/src/index.js +66 -0
  15. package/dist/packages/adapter-sqlite/src/index.d.ts +59 -2
  16. package/dist/packages/adapter-sqlite/src/index.js +136 -0
  17. package/dist/packages/context/src/index.d.ts +8 -0
  18. package/dist/packages/context/src/index.js +7 -0
  19. package/dist/packages/contracts/src/index.d.ts +1 -1
  20. package/dist/packages/events/src/index.d.ts +2 -0
  21. package/dist/packages/events/src/index.js +16 -0
  22. package/dist/packages/graph/src/index.d.ts +59 -3
  23. package/dist/packages/graph/src/index.js +139 -21
  24. package/dist/packages/mcp/src/index.d.ts +14 -0
  25. package/dist/packages/mcp/src/index.js +39 -5
  26. package/dist/packages/plugin-docker/src/index.d.ts +3 -0
  27. package/dist/packages/plugin-docker/src/index.js +13 -0
  28. package/dist/packages/plugin-github/src/index.d.ts +3 -0
  29. package/dist/packages/plugin-github/src/index.js +13 -0
  30. package/dist/packages/policy/src/index.d.ts +7 -0
  31. package/dist/packages/policy/src/index.js +17 -1
  32. package/dist/packages/runtime/src/index.d.ts +20 -1
  33. package/dist/packages/runtime/src/index.js +34 -1
  34. package/dist/packages/sandbox/src/index.d.ts +2 -0
  35. package/dist/packages/sandbox/src/index.js +10 -0
  36. package/dist/scripts/context-benchmark.d.ts +2 -0
  37. package/dist/scripts/context-benchmark.js +39 -0
  38. package/dist/scripts/demo-autonomy.d.ts +15 -0
  39. package/dist/scripts/demo-autonomy.js +200 -0
  40. package/dist/scripts/server-persistence-probe.d.mts +1 -0
  41. package/dist/scripts/server-persistence-probe.d.ts +1 -0
  42. package/dist/scripts/server-persistence-probe.js +52 -0
  43. package/dist/scripts/server-persistence-probe.mjs +52 -0
  44. package/docs/2x/CLI-CAPABILITIES.md +35 -0
  45. package/docs/2x/IMPLEMENTATION-AUDIT.md +40 -0
  46. package/docs/2x/SPRINT-1-CLI-CAPABILITY-PLAN.md +53 -0
  47. package/docs/2x/SPRINT-10-GRAPH-SYNC-PLAN.md +54 -0
  48. package/docs/2x/SPRINT-11-GRAPH-SYNC-CLI-MCP-PLAN.md +38 -0
  49. package/docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md +40 -0
  50. package/docs/2x/SPRINT-13-MCP-STDIO-PLAN.md +26 -0
  51. package/docs/2x/SPRINT-14-SERVER-RESTART-PLAN.md +28 -0
  52. package/docs/2x/SPRINT-15-CHAOS-SECURITY-PLAN.md +22 -0
  53. package/docs/2x/SPRINT-16-LAST-MILE-PLAN.md +25 -0
  54. package/docs/2x/SPRINT-2-CLI-CAPABILITY-PLAN.md +39 -0
  55. package/docs/2x/SPRINT-3-RUNTIME-PERSISTENCE-PLAN.md +42 -0
  56. package/docs/2x/SPRINT-4-MCP-REGISTRY-PLAN.md +35 -0
  57. package/docs/2x/SPRINT-5-SERVER-APPROVALS-AUDIT-PLAN.md +31 -0
  58. package/docs/2x/SPRINT-6-EVENTS-E2E-PLAN.md +55 -0
  59. package/docs/2x/SPRINT-7-GRAPHLOOP-PERSISTENCE-PLAN.md +60 -0
  60. package/docs/2x/SPRINT-8-CONTEXT-GRAPH-PLAN.md +64 -0
  61. package/docs/2x/SPRINT-9-DETERMINISTIC-EXTRACTORS-PLAN.md +51 -0
  62. package/memory/50-orchestration/handoffs/2026-08-01_sprint-1-cli-capabilities.md +41 -0
  63. package/memory/50-orchestration/handoffs/2026-08-01_sprint-10-graph-sync.md +23 -0
  64. package/memory/50-orchestration/handoffs/2026-08-01_sprint-11-graph-sync-cli-mcp.md +22 -0
  65. package/memory/50-orchestration/handoffs/2026-08-01_sprint-12-real-autonomy.md +16 -0
  66. package/memory/50-orchestration/handoffs/2026-08-01_sprint-2-cli-capabilities.md +30 -0
  67. package/memory/50-orchestration/handoffs/2026-08-01_sprint-3-runtime-persistence.md +29 -0
  68. package/memory/50-orchestration/handoffs/2026-08-01_sprint-4-mcp.md +29 -0
  69. package/memory/50-orchestration/handoffs/2026-08-01_sprint-5-server-approvals-audit.md +22 -0
  70. package/memory/50-orchestration/handoffs/2026-08-01_sprint-6-events-e2e.md +25 -0
  71. package/memory/50-orchestration/handoffs/2026-08-01_sprint-7-graphloop.md +23 -0
  72. package/memory/50-orchestration/handoffs/2026-08-01_sprint-8-context-graph.md +23 -0
  73. package/memory/50-orchestration/handoffs/2026-08-01_sprint-9-extractors.md +21 -0
  74. package/memory/50-orchestration/handoffs/2026-08-02_sprint-13-mcp-stdio.md +14 -0
  75. package/memory/50-orchestration/handoffs/2026-08-02_sprint-14-server-restart.md +15 -0
  76. package/memory/50-orchestration/handoffs/2026-08-02_sprint-15-chaos-security.md +13 -0
  77. package/memory/50-orchestration/handoffs/2026-08-02_sprint-16-last-mile.md +11 -0
  78. package/memory/90-decisions/0059-cli-adapter-capability-registry.md +17 -0
  79. package/memory/90-decisions/0060-runtime-persistence-port.md +17 -0
  80. package/memory/90-decisions/0061-mcp-dynamic-registry-stdio.md +16 -0
  81. package/memory/90-decisions/0062-server-catalog-approval-audit.md +17 -0
  82. package/memory/90-decisions/0063-events-persistent-e2e.md +19 -0
  83. package/memory/90-decisions/0064-graphloop-sqlite-store.md +20 -0
  84. package/memory/90-decisions/0065-context-graph-source-cache.md +20 -0
  85. package/memory/90-decisions/0066-graph-deterministic-extractors.md +16 -0
  86. package/memory/90-decisions/0067-graph-sync-capability.md +17 -0
  87. package/memory/90-decisions/0068-graph-sync-cli-mcp.md +17 -0
  88. package/memory/90-decisions/0069-real-autonomy-demo.md +16 -0
  89. package/memory/90-decisions/0070-mcp-stdio-real.md +11 -0
  90. package/memory/90-decisions/0071-server-persistence-composition.md +12 -0
  91. package/memory/90-decisions/0072-sandbox-security-boundaries.md +9 -0
  92. package/memory/90-decisions/0073-last-mile-rollback-benchmark-plugins.md +17 -0
  93. package/package.json +13 -3
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ Histórico consolidado das mudanças estruturais do framework. Para decisões ar
4
4
 
5
5
  ---
6
6
 
7
+ ## [2.0.2] — 2026-08-01 — Integração operacional das Sprints 1–11
8
+
9
+ Consolida a evolução do ForjaJS 2.x após a fundação 2.0.1, conectando a CLI,
10
+ Capability Registry, Runtime, MCP, SQLite, GraphLoop e Context Engine em um
11
+ fluxo persistente, auditável e testado.
12
+
13
+ ### Adicionado
14
+ - Adapter da CLI sobre o Capability Registry com `ExecutionResult` estruturado.
15
+ - Persistência SQLite para runtime, aprovações, eventos e GraphLoop.
16
+ - MCP dinâmico derivado das capabilities registradas.
17
+ - Context Engine integrado ao GraphLoop, com cache por checksum e orçamento.
18
+ - Extractors determinísticos e capability `graph.sync` para CLI/MCP.
19
+ - Testes de recuperação, autonomia E2E, contratos e integração.
20
+ - ADRs, auditoria de implementação e handoffs das Sprints 1–11.
21
+
7
22
  ## [2.0.1] — 2026-08-01 — Higiene de dependências do pacote
8
23
 
9
24
  Move as dependências de NestJS e dashboard para os manifests das aplicações e
package/README.md CHANGED
@@ -121,6 +121,28 @@ forja spec:tasks my-feature
121
121
  forja spec:check my-feature
122
122
  ```
123
123
 
124
+ ### Prove supervised autonomy locally
125
+
126
+ The deterministic offline proof uses an external fixture, a real Git worktree,
127
+ human approval, a real `npm test`, diff validation, promotion, SQLite state,
128
+ GraphLoop evidence and a compact handoff:
129
+
130
+ ```bash
131
+ npm run demo:autonomy
132
+ ```
133
+
134
+ The full flow is documented in [`docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md`](docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md).
135
+
136
+ Measure the deterministic context baseline and cache evidence:
137
+
138
+ ```bash
139
+ npm run benchmark:context
140
+ ```
141
+
142
+ The sandbox also exposes an explicit, auditable rollback after promotion. Official
143
+ plugin boundaries are available as `@forja/plugin-github` and `@forja/plugin-docker`;
144
+ external network or Docker handlers must be injected and permissioned by the host.
145
+
124
146
  > Cloned the repo instead of installing? The same commands run as
125
147
  > `node bin/forja.ts <command>` — the npm scripts are just thin aliases of the core.
126
148
  > The source is TypeScript and runs natively: **dev needs Node ≥ 22.6** (type stripping). The
package/README.pt-BR.md CHANGED
@@ -108,6 +108,28 @@ forja spec:tasks minha-feature
108
108
  forja spec:check minha-feature
109
109
  ```
110
110
 
111
+ ### Provar autonomia supervisionada localmente
112
+
113
+ A prova offline determinística usa uma fixture externa, Git worktree real,
114
+ aprovação humana, `npm test` real, validação de diff, promoção, estado SQLite,
115
+ evidências no GraphLoop e handoff compacto:
116
+
117
+ ```bash
118
+ npm run demo:autonomy
119
+ ```
120
+
121
+ O fluxo completo está documentado em [`docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md`](docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md).
122
+
123
+ Meça o baseline determinístico de contexto e a evidência de cache:
124
+
125
+ ```bash
126
+ npm run benchmark:context
127
+ ```
128
+
129
+ O sandbox também expõe rollback explícito e auditável após promoção. Os limites
130
+ oficiais dos plugins `@forja/plugin-github` e `@forja/plugin-docker` estão disponíveis;
131
+ handlers externos de rede ou Docker precisam ser injetados e permissionados pelo host.
132
+
111
133
  > Clonou o repo em vez de instalar? Os mesmos comandos rodam como
112
134
  > `node bin/forja.ts <comando>` — os scripts npm são apenas aliases finos do core.
113
135
  > A fonte é TypeScript e roda nativa: **dev exige Node ≥ 22.6** (strip-types). O pacote *publicado*
@@ -0,0 +1,44 @@
1
+ import { type AgentIdentity, type CapabilityId, type ExecutionResult } from '../../../packages/contracts/src/index.ts';
2
+ import { CapabilityRegistry } from '../../../packages/core/src/index.ts';
3
+ import { PolicyEngine } from '../../../packages/policy/src/index.ts';
4
+ import { GraphLoop, type GraphDocumentSource } from '../../../packages/graph/src/index.ts';
5
+ export interface LegacyCliResult {
6
+ readonly exitCode: number;
7
+ readonly stdout: string;
8
+ readonly stderr: string;
9
+ }
10
+ export type LegacyCliRunner = (command: string, args: readonly string[]) => LegacyCliResult | Promise<LegacyCliResult>;
11
+ export interface CliExecutionPayload {
12
+ readonly command: string;
13
+ readonly args: readonly string[];
14
+ readonly exitCode: number;
15
+ readonly stdout: string;
16
+ readonly stderr: string;
17
+ }
18
+ export interface CliCapabilityRuntime {
19
+ readonly registry: CapabilityRegistry;
20
+ readonly policy: PolicyEngine;
21
+ readonly agent: AgentIdentity;
22
+ }
23
+ export interface GraphSyncComposition {
24
+ readonly graph: GraphLoop;
25
+ readonly source: GraphDocumentSource;
26
+ }
27
+ export declare function createLegacyCliRunner(root: string, cwd?: string): LegacyCliRunner;
28
+ interface InputRecord {
29
+ readonly [key: string]: unknown;
30
+ }
31
+ export declare const CLI_COMMAND_TO_CAPABILITY: Readonly<Record<string, CapabilityId>>;
32
+ /** Interface commands for discovering/executing capabilities; handlers remain in the registry. */
33
+ export declare const CLI_INTERFACE_COMMANDS: readonly ["capabilities:list", "capabilities:describe", "capability:execute", "mcp:start"];
34
+ export declare function createCliCapabilityRuntime(runner: LegacyCliRunner, graphSync?: GraphSyncComposition): CliCapabilityRuntime;
35
+ export declare function registerCliCapabilities(registry: CapabilityRegistry, runner: LegacyCliRunner): void;
36
+ export declare function registerGraphSyncCapability(registry: CapabilityRegistry, graph: GraphLoop, source: GraphDocumentSource): void;
37
+ export declare function capabilityIdForCommand(command: string): CapabilityId | undefined;
38
+ export declare function parseLegacyCommandInput(command: string, args: readonly string[]): {
39
+ readonly capabilityId: CapabilityId;
40
+ readonly payload: InputRecord;
41
+ };
42
+ export declare function executeCliCapability(runtime: CliCapabilityRuntime, capabilityId: CapabilityId, payload: unknown, correlationId?: string): Promise<ExecutionResult>;
43
+ export declare function normalizeCliResult(result: ExecutionResult): ExecutionResult;
44
+ export {};
@@ -0,0 +1,304 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { CONTRACT_VERSION, } from "../../../packages/contracts/src/index.js";
4
+ import { CapabilityRegistry, } from "../../../packages/core/src/index.js";
5
+ import { PolicyEngine } from "../../../packages/policy/src/index.js";
6
+ import { COMMANDS, resolveScript } from "../../../lib/core/registry.js";
7
+ import { GraphIndexer } from "../../../packages/graph/src/index.js";
8
+ export function createLegacyCliRunner(root, cwd = process.cwd()) {
9
+ return (command, args) => {
10
+ const definition = COMMANDS[command];
11
+ if (definition === undefined)
12
+ return { exitCode: 127, stdout: '', stderr: `Legacy command not found: ${command}` };
13
+ const invocation = definition.node
14
+ ? { command: process.execPath, args: [resolveScript(root, definition.node), ...(definition.args ?? []), ...args] }
15
+ : { command: definition.bin ?? command, args: [...(definition.args ?? []), ...args] };
16
+ const result = spawnSync(invocation.command, invocation.args, { cwd, encoding: 'utf8', stdio: 'pipe' });
17
+ return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: [result.stderr ?? '', result.error?.message ?? ''].filter(Boolean).join('\n') };
18
+ };
19
+ }
20
+ const CLI_CAPABILITY_SPECS = [
21
+ {
22
+ id: 'system.doctor',
23
+ command: 'tools:doctor',
24
+ description: 'Diagnostica o núcleo e as ferramentas opcionais do Forja.',
25
+ categories: ['read'],
26
+ permissions: ['read'],
27
+ risk: 'low',
28
+ sideEffects: [],
29
+ validateInput: emptyInput,
30
+ toArgs: () => [],
31
+ },
32
+ {
33
+ id: 'code.impact',
34
+ command: 'code:impact',
35
+ description: 'Calcula chamadores e blast radius de um símbolo.',
36
+ categories: ['read', 'execution'],
37
+ permissions: ['read'],
38
+ risk: 'low',
39
+ sideEffects: [],
40
+ validateInput: validateCodeImpactInput,
41
+ toArgs: (input) => input.depth === undefined ? [input.symbol] : [input.symbol, String(input.depth)],
42
+ },
43
+ {
44
+ id: 'context.budget',
45
+ command: 'context:budget',
46
+ description: 'Calcula o orçamento de tokens de um contexto ou runbook.',
47
+ categories: ['read', 'database'],
48
+ permissions: ['read'],
49
+ risk: 'low',
50
+ sideEffects: ['context_run_record'],
51
+ validateInput: validateContextBudgetInput,
52
+ toArgs: (input) => input.limitTokens === undefined ? [input.target] : [input.target, String(input.limitTokens)],
53
+ },
54
+ {
55
+ id: 'spec.validate',
56
+ command: 'spec:check',
57
+ description: 'Valida a estrutura e os estados de uma spec.',
58
+ categories: ['read'],
59
+ permissions: ['read'],
60
+ risk: 'low',
61
+ sideEffects: [],
62
+ validateInput: validateSpecCheckInput,
63
+ toArgs: (input) => input.feature === undefined ? [] : [input.feature],
64
+ },
65
+ {
66
+ id: 'sprint.status',
67
+ command: 'sprint:status',
68
+ description: 'Consulta o status da sprint atual.',
69
+ categories: ['read'],
70
+ permissions: ['read'],
71
+ risk: 'low',
72
+ sideEffects: [],
73
+ validateInput: validateSprintStatusInput,
74
+ toArgs: (input) => input.project === undefined ? [] : [input.project],
75
+ },
76
+ {
77
+ id: 'handoff.create',
78
+ command: 'gsd:handoff',
79
+ description: 'Registra um handoff GSD com fase, spec e contexto.',
80
+ categories: ['write', 'database'],
81
+ permissions: ['write'],
82
+ risk: 'low',
83
+ sideEffects: ['handoff_record'],
84
+ validateInput: validateHandoffInput,
85
+ toArgs: (input) => [input.phase, input.slug, ...(input.context === undefined ? [] : [input.context])],
86
+ },
87
+ ];
88
+ export const CLI_COMMAND_TO_CAPABILITY = Object.freeze(Object.fromEntries(CLI_CAPABILITY_SPECS.map((spec) => [spec.command, spec.id])));
89
+ /** Interface commands for discovering/executing capabilities; handlers remain in the registry. */
90
+ export const CLI_INTERFACE_COMMANDS = Object.freeze([
91
+ 'capabilities:list',
92
+ 'capabilities:describe',
93
+ 'capability:execute',
94
+ 'mcp:start',
95
+ ]);
96
+ export function createCliCapabilityRuntime(runner, graphSync) {
97
+ const registry = new CapabilityRegistry();
98
+ registerCliCapabilities(registry, runner);
99
+ if (graphSync !== undefined)
100
+ registerGraphSyncCapability(registry, graphSync.graph, graphSync.source);
101
+ const policy = new PolicyEngine({
102
+ rules: [{
103
+ id: 'cli-local-read',
104
+ priority: 10,
105
+ effect: 'ALLOW',
106
+ reason: 'CLI proof capabilities are local analysis operations',
107
+ scope: { roles: ['cli'], environments: ['local'], categories: ['read', 'execution', 'database', 'write'] },
108
+ }],
109
+ });
110
+ return {
111
+ registry,
112
+ policy,
113
+ agent: {
114
+ id: 'agent.cli',
115
+ name: 'Forja CLI',
116
+ role: 'cli',
117
+ autonomy: 'supervised',
118
+ },
119
+ };
120
+ }
121
+ export function registerCliCapabilities(registry, runner) {
122
+ for (const spec of CLI_CAPABILITY_SPECS)
123
+ registerCliCapability(registry, runner, spec);
124
+ }
125
+ export function registerGraphSyncCapability(registry, graph, source) {
126
+ const now = new Date().toISOString();
127
+ registry.register({
128
+ definition: { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId: 'graph-capability-catalog', id: 'graph.sync', version: '1.0.0', description: 'Indexa arquivos rastreáveis do workspace no GraphLoop por checksum.', permissions: ['write'], risk: 'low', sideEffects: ['graph_write'], requirements: ['git'], supportsAutonomy: true, idempotent: true, timeoutMs: 60_000, retry: { maxAttempts: 1, backoffMs: 0 }, aliases: [] },
129
+ validateInput: (value) => { if (value === undefined || value === null)
130
+ return {}; if (!isRecord(value) || Object.keys(value).length > 0)
131
+ throw new Error('graph.sync input must be an empty object'); return {}; },
132
+ validateOutput: (value) => { if (!isRecord(value) || !['documents', 'indexed', 'skipped', 'nodes', 'edges', 'durationMs'].every((key) => typeof value[key] === 'number') || !Array.isArray(value.files) || !value.files.every((file) => typeof file === 'string'))
133
+ throw new Error('graph.sync output is invalid'); return value; },
134
+ handler: async () => ({ capabilityId: 'graph.sync', payload: await new GraphIndexer(graph).sync(source), evidence: [{ id: randomUUID(), source: 'forja.graph', locator: 'graph.sync', capturedAt: new Date().toISOString(), status: 'verified' }] }),
135
+ });
136
+ }
137
+ export function capabilityIdForCommand(command) {
138
+ return command === 'graph:sync' ? 'graph.sync' : CLI_COMMAND_TO_CAPABILITY[command];
139
+ }
140
+ export function parseLegacyCommandInput(command, args) {
141
+ if (command === 'graph:sync')
142
+ return { capabilityId: 'graph.sync', payload: {} };
143
+ const capabilityId = capabilityIdForCommand(command);
144
+ if (capabilityId === undefined)
145
+ throw new Error(`Command is not migrated to a capability: ${command}`);
146
+ if (command === 'tools:doctor')
147
+ return { capabilityId, payload: {} };
148
+ if (command === 'code:impact') {
149
+ const [symbol, depth] = args;
150
+ return { capabilityId, payload: { symbol, ...(depth === undefined ? {} : { depth: Number(depth) }) } };
151
+ }
152
+ if (command === 'context:budget') {
153
+ const [target, limitTokens] = args;
154
+ return { capabilityId, payload: { target, ...(limitTokens === undefined ? {} : { limitTokens: Number(limitTokens) }) } };
155
+ }
156
+ if (command === 'spec:check')
157
+ return { capabilityId, payload: args[0] === undefined ? {} : { feature: args[0] } };
158
+ if (command === 'sprint:status')
159
+ return { capabilityId, payload: args[0] === undefined ? {} : { project: args[0] } };
160
+ const [phase, slug, ...contextParts] = args;
161
+ return { capabilityId, payload: { phase, slug, ...(contextParts.length === 0 ? {} : { context: contextParts.join(' ') }) } };
162
+ }
163
+ export async function executeCliCapability(runtime, capabilityId, payload, correlationId) {
164
+ const definition = runtime.registry.describe(capabilityId);
165
+ const categories = categoriesFor(definition.id);
166
+ const result = await runtime.registry.execute({
167
+ input: { capabilityId, payload },
168
+ agent: runtime.agent,
169
+ policy: runtime.policy,
170
+ correlationId,
171
+ environment: 'local',
172
+ categories,
173
+ files: [],
174
+ });
175
+ return normalizeCliResult(result);
176
+ }
177
+ export function normalizeCliResult(result) {
178
+ if (result.status !== 'succeeded' || result.output === undefined || !isRecord(result.output.payload))
179
+ return result;
180
+ const exitCode = result.output.payload.exitCode;
181
+ if (typeof exitCode !== 'number' || exitCode === 0)
182
+ return result;
183
+ return {
184
+ ...result,
185
+ status: 'failed',
186
+ error: {
187
+ code: 'LEGACY_COMMAND_FAILED',
188
+ message: `Legacy command exited with status ${exitCode}`,
189
+ retryable: false,
190
+ },
191
+ };
192
+ }
193
+ function registerCliCapability(registry, runner, spec) {
194
+ const now = new Date().toISOString();
195
+ const definition = {
196
+ schemaVersion: CONTRACT_VERSION,
197
+ createdAt: now,
198
+ updatedAt: now,
199
+ correlationId: 'cli-capability-catalog',
200
+ id: spec.id,
201
+ version: '1.0.0',
202
+ description: spec.description,
203
+ permissions: spec.permissions,
204
+ risk: spec.risk,
205
+ sideEffects: spec.sideEffects,
206
+ requirements: [],
207
+ supportsAutonomy: true,
208
+ idempotent: true,
209
+ timeoutMs: 30_000,
210
+ retry: { maxAttempts: 1, backoffMs: 0 },
211
+ aliases: [spec.command],
212
+ };
213
+ const registration = {
214
+ definition,
215
+ validateInput: spec.validateInput,
216
+ validateOutput: validateCliPayload,
217
+ handler: async (input) => {
218
+ const args = spec.toArgs(input);
219
+ const result = await runner(spec.command, args);
220
+ const capturedAt = new Date().toISOString();
221
+ const evidence = {
222
+ id: randomUUID(),
223
+ source: 'forja.cli',
224
+ locator: [spec.command, ...args].join(' '),
225
+ capturedAt,
226
+ status: result.exitCode === 0 ? 'verified' : 'contradicted',
227
+ };
228
+ return {
229
+ capabilityId: spec.id,
230
+ payload: { command: spec.command, args, ...result },
231
+ evidence: [evidence],
232
+ };
233
+ },
234
+ };
235
+ registry.register(registration);
236
+ }
237
+ function categoriesFor(id) {
238
+ return CLI_CAPABILITY_SPECS.find((spec) => spec.id === id)?.categories ?? ['read'];
239
+ }
240
+ function emptyInput(value) {
241
+ if (value === undefined || value === null)
242
+ return {};
243
+ if (!isRecord(value) || Object.keys(value).length > 0)
244
+ throw new Error('Input must be an empty object');
245
+ return {};
246
+ }
247
+ function validateCodeImpactInput(value) {
248
+ const input = requireRecord(value);
249
+ const symbol = input.symbol;
250
+ const depth = input.depth;
251
+ if (typeof symbol !== 'string' || symbol.trim().length === 0)
252
+ throw new Error('symbol is required');
253
+ if (depth !== undefined && (!Number.isInteger(depth) || depth < 1 || depth > 10))
254
+ throw new Error('depth must be an integer between 1 and 10');
255
+ return { symbol, ...(depth === undefined ? {} : { depth }) };
256
+ }
257
+ function validateContextBudgetInput(value) {
258
+ const input = requireRecord(value);
259
+ const target = input.target;
260
+ const limitTokens = input.limitTokens;
261
+ if (typeof target !== 'string' || target.trim().length === 0)
262
+ throw new Error('target is required');
263
+ if (limitTokens !== undefined && (!Number.isInteger(limitTokens) || limitTokens < 1))
264
+ throw new Error('limitTokens must be a positive integer');
265
+ return { target, ...(limitTokens === undefined ? {} : { limitTokens }) };
266
+ }
267
+ function validateSpecCheckInput(value) {
268
+ const input = requireRecord(value);
269
+ if (input.feature !== undefined && (typeof input.feature !== 'string' || input.feature.trim().length === 0))
270
+ throw new Error('feature must be a non-empty string');
271
+ return input.feature === undefined ? {} : { feature: input.feature };
272
+ }
273
+ function validateSprintStatusInput(value) {
274
+ const input = requireRecord(value);
275
+ if (input.project !== undefined && (typeof input.project !== 'string' || input.project.trim().length === 0))
276
+ throw new Error('project must be a non-empty string');
277
+ return input.project === undefined ? {} : { project: input.project };
278
+ }
279
+ function validateHandoffInput(value) {
280
+ const input = requireRecord(value);
281
+ if (!['spec', 'plan', 'implement', 'review'].includes(String(input.phase)))
282
+ throw new Error('phase must be spec, plan, implement or review');
283
+ if (typeof input.slug !== 'string' || input.slug.trim().length === 0)
284
+ throw new Error('slug is required');
285
+ if (input.context !== undefined && typeof input.context !== 'string')
286
+ throw new Error('context must be a string');
287
+ return { phase: input.phase, slug: input.slug, ...(input.context === undefined ? {} : { context: input.context }) };
288
+ }
289
+ function validateCliPayload(value) {
290
+ const payload = requireRecord(value);
291
+ if (typeof payload.command !== 'string' || !Array.isArray(payload.args) || !payload.args.every((arg) => typeof arg === 'string'))
292
+ throw new Error('CLI output has invalid command or args');
293
+ if (typeof payload.exitCode !== 'number' || typeof payload.stdout !== 'string' || typeof payload.stderr !== 'string')
294
+ throw new Error('CLI output has invalid result fields');
295
+ return payload;
296
+ }
297
+ function requireRecord(value) {
298
+ if (!isRecord(value))
299
+ throw new Error('Input must be an object');
300
+ return value;
301
+ }
302
+ function isRecord(value) {
303
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
304
+ }
@@ -2,11 +2,17 @@ import 'reflect-metadata';
2
2
  import { CapabilityRegistry } from '../../../packages/core/src/index.ts';
3
3
  import { PolicyEngine } from '../../../packages/policy/src/index.ts';
4
4
  import { McpServer } from '../../../packages/mcp/src/index.ts';
5
- import { ControlPlane } from '../../../packages/observability/src/index.ts';
5
+ import { ControlPlane, type ObservationStore } from '../../../packages/observability/src/index.ts';
6
+ import { ApprovalLedger } from '../../../packages/policy/src/index.ts';
7
+ import { type OrchestrationStore } from '../../../packages/orchestration/src/index.ts';
6
8
  import { InMemoryEventStream, type LocalAuthenticator } from '../../../packages/adapter-nest/src/index.ts';
7
9
  import { GraphLoop } from '../../../packages/graph/src/index.ts';
8
- export declare function createDefaultMcp(registry?: CapabilityRegistry, policy?: PolicyEngine, graph?: GraphLoop): McpServer;
10
+ import { ContextEngine } from '../../../packages/context/src/index.ts';
11
+ import { EventBus } from '../../../packages/events/src/index.ts';
12
+ import type { RuntimePersistence } from '../../../packages/runtime/src/index.ts';
13
+ export declare function createDefaultCapabilityRegistry(root?: string, cwd?: string): CapabilityRegistry;
14
+ export declare function createDefaultMcp(registry?: CapabilityRegistry, policy?: PolicyEngine, graph?: GraphLoop, audit?: import('../../../packages/mcp/src/index.ts').McpAuditSink, context?: ContextEngine): McpServer;
9
15
  export declare function createDefaultPolicy(): PolicyEngine;
10
16
  export declare function createLocalAuthenticator(token?: string | undefined): LocalAuthenticator | undefined;
11
- export declare function createDefaultControlPlane(eventStream: InMemoryEventStream, registry?: CapabilityRegistry, policy?: PolicyEngine): ControlPlane;
17
+ export declare function createDefaultControlPlane(eventStream: InMemoryEventStream, registry?: CapabilityRegistry, policy?: PolicyEngine, persistence?: RuntimePersistence, approvals?: ApprovalLedger, events?: EventBus, graph?: GraphLoop, context?: ContextEngine, orchestrationStore?: OrchestrationStore, observationStore?: ObservationStore): ControlPlane;
12
18
  export declare function bootstrap(port?: number): Promise<import("@nestjs/common").INestApplication<any>>;
@@ -1,19 +1,38 @@
1
1
  import 'reflect-metadata';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import Database from 'better-sqlite3';
2
6
  import { NestFactory } from '@nestjs/core';
3
7
  import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
4
8
  import { CapabilityRegistry } from "../../../packages/core/src/index.js";
5
9
  import { PolicyEngine } from "../../../packages/policy/src/index.js";
6
10
  import { McpServer } from "../../../packages/mcp/src/index.js";
7
- import { ControlPlane } from "../../../packages/observability/src/index.js";
11
+ import { ControlPlane, InMemoryObservationStore, ObservabilityRecorder } from "../../../packages/observability/src/index.js";
8
12
  import { ApprovalLedger } from "../../../packages/policy/src/index.js";
9
13
  import { HandoffEngine, InMemoryOrchestrationStore, SprintEngine, TaskEngine } from "../../../packages/orchestration/src/index.js";
10
14
  import { validateTokenBudget } from "../../../packages/contracts/src/index.js";
11
15
  import { createBearerAuthenticator, InMemoryEventStream } from "../../../packages/adapter-nest/src/index.js";
12
16
  import { AppModule } from "./app.module.js";
13
17
  import { RuntimeEngine } from "../../../packages/runtime/src/index.js";
14
- import { GraphLoop } from "../../../packages/graph/src/index.js";
15
- export function createDefaultMcp(registry = new CapabilityRegistry(), policy = createDefaultPolicy(), graph = new GraphLoop()) {
16
- return new McpServer({ registry, policy, graph, agent: { id: 'local-server', name: 'Forja local server', role: 'server', autonomy: 'supervised', permissions: [], capabilities: [] } });
18
+ import { GraphExecutionMemory, GraphLoop } from "../../../packages/graph/src/index.js";
19
+ import { ContextEngine, GraphContextSource } from "../../../packages/context/src/index.js";
20
+ import { SqliteContextCache, SqliteGraphStore, SqliteMigrationRunner, SqliteRuntimePersistence } from "../../../packages/adapter-sqlite/src/index.js";
21
+ import { SqliteApprovalStore, SqliteMcpAuditSink, SqliteObservationStore, SqliteOrchestrationStore } from "../../../packages/adapter-sqlite/src/index.js";
22
+ import { EventBus } from "../../../packages/events/src/index.js";
23
+ import { SqliteEventStore } from "../../../packages/adapter-sqlite/src/index.js";
24
+ import { getWorkspaceDbDir, getWorkspaceDbPath } from "../../../lib/workspace.js";
25
+ import { createLegacyCliRunner, registerCliCapabilities } from "../../cli/src/index.js";
26
+ import { registerGraphSyncCapability } from "../../cli/src/index.js";
27
+ import { GitGraphDocumentSource, SpawnCommandRunner } from "../../../packages/adapter-git/src/index.js";
28
+ const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
29
+ export function createDefaultCapabilityRegistry(root = serverRoot, cwd = process.cwd()) {
30
+ const registry = new CapabilityRegistry();
31
+ registerCliCapabilities(registry, createLegacyCliRunner(root, cwd));
32
+ return registry;
33
+ }
34
+ export function createDefaultMcp(registry = createDefaultCapabilityRegistry(), policy = createDefaultPolicy(), graph = new GraphLoop(), audit, context) {
35
+ return new McpServer({ registry, policy, graph, audit, context, agent: { id: 'local-server', name: 'Forja local server', role: 'server', autonomy: 'supervised', permissions: ['read', 'write', 'execution', 'database'], capabilities: registry.list().map((definition) => definition.id) } });
17
36
  }
18
37
  export function createDefaultPolicy() {
19
38
  const readOnlyRule = { id: 'local-read-only', priority: 10, effect: 'ALLOW', reason: 'Default local server permits read capabilities only', scope: { categories: ['read'], environments: ['local'] } };
@@ -28,19 +47,22 @@ class DefaultRuntimeApplication {
28
47
  contexts = new Map();
29
48
  runtime;
30
49
  policy;
31
- constructor(registry, policy) {
50
+ constructor(registry, policy, persistence, graph, context) {
32
51
  this.policy = policy;
33
52
  this.runtime = new RuntimeEngine({
34
53
  registry,
35
54
  planner: { plan: (_objective, context) => { if (!isRecord(context) || !Array.isArray(context.steps))
36
55
  throw new Error('Runtime plan context is missing'); return context.steps; } },
37
- contextBuilder: { build: async (objective) => this.contexts.get(objective) },
56
+ contextBuilder: { build: async (objective) => { const request = this.contexts.get(objective); if (request === undefined)
57
+ return undefined; const contextPackage = context === undefined ? undefined : await context.build({ objective, budget: request.budget, requireEvidence: false }); return { ...request, contextPackage }; } },
38
58
  validator: { validate: (run, results) => this.validate(run, results) },
59
+ persistence,
60
+ memory: graph === undefined ? undefined : new GraphExecutionMemory(graph),
39
61
  });
40
62
  }
41
63
  async start(input) {
42
64
  const value = runtimeInput(input);
43
- this.contexts.set(value.objective, { steps: value.steps });
65
+ this.contexts.set(value.objective, { steps: value.steps, budget: value.budget });
44
66
  try {
45
67
  return await this.runtime.start({ objective: value.objective, agent: value.agent, budget: value.budget, policy: this.policy, sprintId: value.sprintId, taskId: value.taskId, correlationId: value.correlationId });
46
68
  }
@@ -48,11 +70,29 @@ class DefaultRuntimeApplication {
48
70
  this.contexts.delete(value.objective);
49
71
  }
50
72
  }
51
- execute(id) { return this.runtime.execute(id); }
52
- get(id) { return this.runtime.get(id); }
73
+ async execute(id) { return this.executeWithRecovery(id); }
74
+ async get(id) { return this.getWithRecovery(id); }
53
75
  pause(id) { return this.runtime.pause(id); }
54
- resume(id) { return this.runtime.resume(id); }
76
+ resume(id) { return this.runtime.resume(id, this.policy); }
55
77
  cancel(id) { return this.runtime.cancel(id); }
78
+ async getWithRecovery(id) {
79
+ try {
80
+ return this.runtime.get(id);
81
+ }
82
+ catch {
83
+ await this.runtime.recover(id, this.policy);
84
+ return this.runtime.get(id);
85
+ }
86
+ }
87
+ async executeWithRecovery(id) {
88
+ try {
89
+ return await this.runtime.execute(id);
90
+ }
91
+ catch {
92
+ await this.runtime.recover(id, this.policy);
93
+ return this.runtime.execute(id);
94
+ }
95
+ }
56
96
  validate(run, results) {
57
97
  const passed = results.length === run.steps && results.every((result) => result.status === 'succeeded' && result.evidence.length > 0);
58
98
  const now = new Date().toISOString();
@@ -74,28 +114,39 @@ function runtimeInput(input) {
74
114
  return { objective: input.objective, agent, budget, steps, sprintId: typeof input.sprintId === 'string' ? input.sprintId : undefined, taskId: typeof input.taskId === 'string' ? input.taskId : undefined, correlationId: typeof input.correlationId === 'string' ? input.correlationId : undefined };
75
115
  }
76
116
  function isRecord(value) { return typeof value === 'object' && value !== null; }
77
- export function createDefaultControlPlane(eventStream, registry = new CapabilityRegistry(), policy = createDefaultPolicy()) {
78
- const store = new InMemoryOrchestrationStore();
117
+ export function createDefaultControlPlane(eventStream, registry = createDefaultCapabilityRegistry(), policy = createDefaultPolicy(), persistence, approvals = new ApprovalLedger(), events, graph, context, orchestrationStore = new InMemoryOrchestrationStore(), observationStore = new InMemoryObservationStore()) {
118
+ const store = orchestrationStore;
79
119
  const sprintEngine = new SprintEngine(store);
80
120
  const taskEngine = new TaskEngine(store, sprintEngine);
81
121
  const handoffEngine = new HandoffEngine(store);
82
- const approvals = new ApprovalLedger();
83
- const runtime = new DefaultRuntimeApplication(registry, policy);
84
- return new ControlPlane(undefined, {
122
+ const runtime = new DefaultRuntimeApplication(registry, policy, persistence, graph, context);
123
+ return new ControlPlane(new ObservabilityRecorder(observationStore), {
85
124
  runtime: { start: (input) => runtime.start(input), get: (input) => runtime.get(input), execute: (input) => runtime.execute(input), pause: (input) => runtime.pause(input), resume: (input) => runtime.resume(input), cancel: (input) => runtime.cancel(input) },
86
125
  sprint: { create: (input) => sprintEngine.create(input), start: (id) => sprintEngine.start(id), pause: (id) => sprintEngine.pause(id) },
87
126
  task: { create: (input) => taskEngine.create(input), start: (id) => taskEngine.start(id), block: (id) => taskEngine.block(id) },
88
127
  handoff: { create: (input) => handoffEngine.create(input) },
89
128
  approvals: { get: (id) => approvals.get(id), list: () => approvals.list(), decide: (input) => { const value = input; return approvals.decide(value.id, { decision: value.input.decision, approverId: value.input.approverId, decidedAt: value.input.decidedAt ?? new Date().toISOString() }); } },
90
- events: { publish: (event) => eventStream.publish({ id: event.id, event: event.type, data: event.data, correlationId: event.correlationId }) },
129
+ events: { publish: (event) => { eventStream.publish({ id: event.id, event: event.type, data: event.data, correlationId: event.correlationId }); void events?.append({ type: event.type, aggregateId: event.aggregateId, payload: event.data, idempotencyKey: `${event.type}:${event.id}`, correlationId: event.correlationId }); } },
91
130
  });
92
131
  }
93
132
  export async function bootstrap(port = Number(process.env.FORJA_PORT ?? 3000)) {
94
133
  const eventStream = new InMemoryEventStream();
95
- const registry = new CapabilityRegistry();
134
+ const registry = createDefaultCapabilityRegistry();
96
135
  const policy = createDefaultPolicy();
97
- const mcp = createDefaultMcp(registry, policy, new GraphLoop());
98
- const app = await NestFactory.create(AppModule.register({ mcp, eventStream, authenticator: createLocalAuthenticator(), controlPlane: createDefaultControlPlane(eventStream, registry, policy) }));
136
+ fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
137
+ const runtimeDatabase = new Database(process.env.FORJA_RUNTIME_DB ?? getWorkspaceDbPath());
138
+ new SqliteMigrationRunner(runtimeDatabase).apply();
139
+ const runtimePersistence = new SqliteRuntimePersistence(runtimeDatabase);
140
+ const approvals = new ApprovalLedger(new SqliteApprovalStore(runtimeDatabase));
141
+ const mcpAudit = new SqliteMcpAuditSink(runtimeDatabase);
142
+ const events = new EventBus(new SqliteEventStore(runtimeDatabase));
143
+ const graph = new GraphLoop(new SqliteGraphStore(runtimeDatabase));
144
+ const orchestrationStore = new SqliteOrchestrationStore(runtimeDatabase);
145
+ const observationStore = new SqliteObservationStore(runtimeDatabase);
146
+ registerGraphSyncCapability(registry, graph, new GitGraphDocumentSource(process.env.FORJA_GRAPH_ROOT ?? process.cwd(), new SpawnCommandRunner()));
147
+ const context = new ContextEngine({ graph: new GraphContextSource({ searchContext: (objective) => graph.contextRecords(objective) }), cache: new SqliteContextCache(runtimeDatabase) });
148
+ const mcp = createDefaultMcp(registry, policy, graph, mcpAudit, context);
149
+ const app = await NestFactory.create(AppModule.register({ mcp, eventStream, authenticator: createLocalAuthenticator(), controlPlane: createDefaultControlPlane(eventStream, registry, policy, runtimePersistence, approvals, events, graph, context, orchestrationStore, observationStore) }));
99
150
  const config = new DocumentBuilder().setTitle('ForjaJS 2.0 API').setDescription('Local-first agent control plane').setVersion('2.0.0').build();
100
151
  SwaggerModule.setup('docs', app, SwaggerModule.createDocument(app, config));
101
152
  await app.listen(port, '127.0.0.1');