forjajs 2.0.2 → 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 (42) hide show
  1. package/README.md +22 -0
  2. package/README.pt-BR.md +22 -0
  3. package/dist/apps/server/src/main.d.ts +3 -2
  4. package/dist/apps/server/src/main.js +8 -6
  5. package/dist/bin/forja.js +8 -3
  6. package/dist/lib/core/registry.d.ts +10 -0
  7. package/dist/lib/core/registry.js +10 -0
  8. package/dist/lib/core/release.d.ts +10 -0
  9. package/dist/packages/adapter-git/src/index.d.ts +2 -0
  10. package/dist/packages/adapter-git/src/index.js +22 -1
  11. package/dist/packages/contracts/src/index.d.ts +1 -1
  12. package/dist/packages/plugin-docker/src/index.d.ts +3 -0
  13. package/dist/packages/plugin-docker/src/index.js +13 -0
  14. package/dist/packages/plugin-github/src/index.d.ts +3 -0
  15. package/dist/packages/plugin-github/src/index.js +13 -0
  16. package/dist/packages/sandbox/src/index.d.ts +2 -0
  17. package/dist/packages/sandbox/src/index.js +10 -0
  18. package/dist/scripts/context-benchmark.d.ts +2 -0
  19. package/dist/scripts/context-benchmark.js +39 -0
  20. package/dist/scripts/demo-autonomy.d.ts +15 -0
  21. package/dist/scripts/demo-autonomy.js +200 -0
  22. package/dist/scripts/server-persistence-probe.d.mts +1 -0
  23. package/dist/scripts/server-persistence-probe.d.ts +1 -0
  24. package/dist/scripts/server-persistence-probe.js +52 -0
  25. package/dist/scripts/server-persistence-probe.mjs +52 -0
  26. package/docs/2x/IMPLEMENTATION-AUDIT.md +36 -128
  27. package/docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md +40 -0
  28. package/docs/2x/SPRINT-13-MCP-STDIO-PLAN.md +26 -0
  29. package/docs/2x/SPRINT-14-SERVER-RESTART-PLAN.md +28 -0
  30. package/docs/2x/SPRINT-15-CHAOS-SECURITY-PLAN.md +22 -0
  31. package/docs/2x/SPRINT-16-LAST-MILE-PLAN.md +25 -0
  32. package/memory/50-orchestration/handoffs/2026-08-01_sprint-12-real-autonomy.md +16 -0
  33. package/memory/50-orchestration/handoffs/2026-08-02_sprint-13-mcp-stdio.md +14 -0
  34. package/memory/50-orchestration/handoffs/2026-08-02_sprint-14-server-restart.md +15 -0
  35. package/memory/50-orchestration/handoffs/2026-08-02_sprint-15-chaos-security.md +13 -0
  36. package/memory/50-orchestration/handoffs/2026-08-02_sprint-16-last-mile.md +11 -0
  37. package/memory/90-decisions/0069-real-autonomy-demo.md +16 -0
  38. package/memory/90-decisions/0070-mcp-stdio-real.md +11 -0
  39. package/memory/90-decisions/0071-server-persistence-composition.md +12 -0
  40. package/memory/90-decisions/0072-sandbox-security-boundaries.md +9 -0
  41. package/memory/90-decisions/0073-last-mile-rollback-benchmark-plugins.md +17 -0
  42. package/package.json +13 -3
@@ -0,0 +1,200 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import Database from 'better-sqlite3';
7
+ import { CapabilityRegistry } from "../packages/core/src/index.js";
8
+ import { ContextEngine, GraphContextSource } from "../packages/context/src/index.js";
9
+ import { SqliteApprovalStore, SqliteAuditStore, SqliteCheckpointStore, SqliteContextCache, SqliteEventStore, SqliteGraphStore, SqliteMigrationRunner, SqliteOrchestrationStore, SqliteSandboxStore, SqliteRuntimePersistence } from "../packages/adapter-sqlite/src/index.js";
10
+ import { GitGraphDocumentSource, GitWorktreeBackend, SpawnCommandRunner } from "../packages/adapter-git/src/index.js";
11
+ import { GraphExecutionMemory, GraphIndexer, GraphLoop } from "../packages/graph/src/index.js";
12
+ import { EventBus } from "../packages/events/src/index.js";
13
+ import { ApprovalLedger, PolicyEngine } from "../packages/policy/src/index.js";
14
+ import { RuntimeEngine } from "../packages/runtime/src/index.js";
15
+ import { SandboxEngine } from "../packages/sandbox/src/index.js";
16
+ import { SprintEngine, TaskEngine, HandoffEngine } from "../packages/orchestration/src/index.js";
17
+ import { DeterministicValidator } from "../packages/validator/src/index.js";
18
+ const now = () => new Date().toISOString();
19
+ const budget = { inputTokens: 600, outputTokens: 300, totalTokens: 900, usedTokens: 0 };
20
+ function command(executable, args, cwd, input) {
21
+ const result = spawnSync(executable, [...args], { cwd, input, encoding: 'utf8', stdio: 'pipe' });
22
+ return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: [result.stderr ?? '', result.error?.message ?? ''].filter(Boolean).join('\n') };
23
+ }
24
+ function mustCommand(executable, args, cwd, input) {
25
+ const result = command(executable, args, cwd, input);
26
+ if (result.exitCode !== 0)
27
+ throw new Error(`${executable} ${args.join(' ')} failed: ${result.stderr || result.stdout}`);
28
+ return result;
29
+ }
30
+ function createFixture() {
31
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-autonomy-fixture-'));
32
+ fs.mkdirSync(path.join(root, 'tests'), { recursive: true });
33
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: 'forja-autonomy-fixture', private: true, type: 'module', scripts: { test: 'node --test' } }, null, 2) + '\n');
34
+ fs.writeFileSync(path.join(root, 'math.js'), 'export function add(left, right) { return left + right; }\n');
35
+ fs.writeFileSync(path.join(root, 'tests', 'math.test.js'), "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { add } from '../math.js';\n\ntest('add adds two numbers', () => { assert.equal(add(1, 1), 3); });\n");
36
+ fs.writeFileSync(path.join(root, '.gitignore'), '.forja/\nnode_modules/\n');
37
+ mustCommand('git', ['init', '-q'], root);
38
+ mustCommand('git', ['config', 'user.email', 'forja-demo@example.invalid'], root);
39
+ mustCommand('git', ['config', 'user.name', 'Forja Demo Agent'], root);
40
+ mustCommand('git', ['add', '.'], root);
41
+ mustCommand('git', ['commit', '-qm', 'fixture: introduce failing test'], root);
42
+ return root;
43
+ }
44
+ class GitPatchApplier {
45
+ apply(root, patch) {
46
+ const patchRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-promotion-'));
47
+ const patchFile = path.join(patchRoot, 'promotion.patch');
48
+ try {
49
+ fs.writeFileSync(patchFile, patch);
50
+ mustCommand('git', ['-C', root, 'apply', '--binary', patchFile], root);
51
+ }
52
+ finally {
53
+ fs.rmSync(patchRoot, { recursive: true, force: true });
54
+ }
55
+ }
56
+ revert(root, patch) {
57
+ const patchRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-rollback-'));
58
+ const patchFile = path.join(patchRoot, 'rollback.patch');
59
+ try {
60
+ fs.writeFileSync(patchFile, patch);
61
+ mustCommand('git', ['-C', root, 'apply', '--reverse', '--binary', patchFile], root);
62
+ }
63
+ finally {
64
+ fs.rmSync(patchRoot, { recursive: true, force: true });
65
+ }
66
+ }
67
+ }
68
+ function evidence(source, locator, status = 'verified') {
69
+ return { id: randomUUID(), source, locator, capturedAt: now(), status };
70
+ }
71
+ function createPlan(runId, testFile, evidenceIds) {
72
+ const fields = { schemaVersion: '2.0', createdAt: now(), updatedAt: now(), correlationId: `plan:${runId}` };
73
+ return {
74
+ ...fields,
75
+ id: `plan:${runId}`,
76
+ objective: 'Corrigir teste falhando na fixture externa',
77
+ risk: 'medium',
78
+ budget,
79
+ evidenceIds,
80
+ steps: [{
81
+ ...fields,
82
+ id: `step:${runId}`,
83
+ objective: 'Corrigir a expectativa do teste da fixture',
84
+ acceptanceCriteria: ['npm test passa na fixture', 'diff contém somente o teste falho'],
85
+ allowedFiles: [testFile],
86
+ dependencyIds: [],
87
+ evidenceIds,
88
+ risk: 'medium',
89
+ budget,
90
+ status: 'ready',
91
+ }],
92
+ };
93
+ }
94
+ export async function runAutonomyDemo() {
95
+ const fixtureRoot = createFixture();
96
+ const databasePath = path.join(fixtureRoot, '.forja', 'runtime.db');
97
+ fs.mkdirSync(path.dirname(databasePath), { recursive: true });
98
+ const database = new Database(databasePath);
99
+ new SqliteMigrationRunner(database).apply();
100
+ const correlationId = `demo:${randomUUID()}`;
101
+ const runId = `run:${randomUUID()}`;
102
+ const agent = { id: 'agent.demo', name: 'Forja deterministic demo agent', role: 'developer', autonomy: 'supervised' };
103
+ const testFile = 'tests/math.test.js';
104
+ const initialEvidence = evidence('fixture', testFile);
105
+ const runner = new SpawnCommandRunner();
106
+ const graph = new GraphLoop(new SqliteGraphStore(database));
107
+ const graphSource = new GitGraphDocumentSource(fixtureRoot, runner);
108
+ const graphBefore = await new GraphIndexer(graph).sync(graphSource);
109
+ const context = await new ContextEngine({
110
+ graph: new GraphContextSource({ searchContext: (objective) => graph.contextRecords(objective) }),
111
+ cache: new SqliteContextCache(database),
112
+ }).build({ objective: 'corrigir teste falhando math.test.js', budget, includeContent: true, requireEvidence: false, correlationId });
113
+ const approvals = new ApprovalLedger(new SqliteApprovalStore(database));
114
+ let approved = false;
115
+ const policy = new PolicyEngine({
116
+ rules: [{ id: 'demo-code-write', priority: 100, effect: 'REQUIRE_APPROVAL', reason: 'Alteração de código exige aprovação humana', scope: { agentIds: [agent.id], capabilityIds: ['fixture.code.write'], environments: ['local'], categories: ['write'] } }],
117
+ approvalLedger: approvals,
118
+ });
119
+ const patchApplier = new GitPatchApplier();
120
+ const sandbox = new SandboxEngine(new SqliteSandboxStore(database), new GitWorktreeBackend(runner, { repositoryRoot: fixtureRoot, sourceRef: 'HEAD', patchApplier }));
121
+ const session = await sandbox.create({ runId: runId, root: path.join(fixtureRoot, '..', `${path.basename(fixtureRoot)}-worktree`), correlationId });
122
+ await sandbox.prepare(session.id);
123
+ const registry = new CapabilityRegistry();
124
+ const capabilityId = 'fixture.code.write';
125
+ registry.register({
126
+ definition: { schemaVersion: '2.0', createdAt: now(), updatedAt: now(), correlationId, id: capabilityId, version: '1.0.0', description: 'Corrige a expectativa do teste da fixture em sandbox Git real', permissions: ['write'], risk: 'medium', sideEffects: ['sandbox_write'], requirements: ['git', 'npm'], supportsAutonomy: false, idempotent: true, timeoutMs: 60_000, retry: { maxAttempts: 1, backoffMs: 0 }, aliases: [] },
127
+ validateInput: (input) => { if (input !== undefined && (typeof input !== 'object' || input === null))
128
+ throw new Error('fixture.code.write input must be an object'); return {}; },
129
+ validateOutput: (output) => output,
130
+ handler: async () => {
131
+ const worktreeFile = path.join(session.root, testFile);
132
+ const source = fs.readFileSync(worktreeFile, 'utf8');
133
+ if (!source.includes('assert.equal(add(1, 1), 3)'))
134
+ throw new Error('Expected failing assertion was not found');
135
+ fs.writeFileSync(worktreeFile, source.replace('assert.equal(add(1, 1), 3)', 'assert.equal(add(1, 1), 2)'));
136
+ const testExecution = await sandbox.execute(session.id, { executable: 'npm', args: ['test'], cwd: session.root });
137
+ if (testExecution.exitCode !== 0)
138
+ throw new Error(`Fixture tests failed after edit: ${testExecution.stderr || testExecution.stdout}`);
139
+ const validation = await sandbox.validate(session.id);
140
+ if (validation.status !== 'accepted')
141
+ throw new Error(validation.summary);
142
+ const testEvidence = evidence('sandbox.npm.test', `${testFile}:npm test`);
143
+ const editEvidence = evidence('sandbox.agent', testFile);
144
+ return { capabilityId, payload: { changedFile: testFile, testExitCode: testExecution.exitCode, stdout: testExecution.stdout, validation: validation.summary }, evidence: [initialEvidence, editEvidence, testEvidence] };
145
+ },
146
+ });
147
+ const runtime = new RuntimeEngine({
148
+ registry,
149
+ planner: { plan: () => [{ capabilityId, payload: {}, estimatedTokens: 80, files: [testFile], environment: 'local', categories: ['write'], approval: { action: 'code.write', justification: 'Corrigir a asserção determinística que falha na fixture', impact: 'Altera somente tests/math.test.js dentro do worktree', expectedDiff: testFile, expiresAt: '2099-01-01T00:00:00.000Z' } }] },
150
+ contextBuilder: { build: () => context },
151
+ checkpointStore: new SqliteCheckpointStore(database),
152
+ persistence: new SqliteRuntimePersistence(database),
153
+ memory: new GraphExecutionMemory(graph),
154
+ validator: { validate: (run, results) => {
155
+ const plan = createPlan(run.runId, testFile, [...new Set([...context.references.map((item) => item.id), ...results.flatMap((result) => result.evidence.map((item) => item.id))])]);
156
+ const successfulResults = results.filter((result) => result.status === 'succeeded');
157
+ const testEvidenceIds = successfulResults.flatMap((result) => result.evidence.map((item) => item.id));
158
+ const testPassed = successfulResults.length > 0;
159
+ return new DeterministicValidator().validate({ plan, changedFiles: run.changedFiles, checks: [{ name: 'build', passed: true, evidenceIds: [] }, { name: 'tests', passed: testPassed, evidenceIds: testEvidenceIds }, { name: 'diff', passed: true, evidenceIds: testEvidenceIds }, { name: 'typecheck', passed: true, evidenceIds: [] }, { name: 'lint', passed: true, evidenceIds: [] }], acceptance: [{ criterion: 'npm test passa na fixture', passed: testPassed, evidenceIds: testEvidenceIds }, { criterion: 'diff contém somente o teste falho', passed: run.changedFiles.length === 1 && run.changedFiles[0] === testFile, evidenceIds: [] }], correlationId: run.correlationId });
160
+ } },
161
+ });
162
+ const started = await runtime.start({ objective: 'Corrigir teste falhando na fixture externa', agent, budget, policy: { authorize: (request) => approved ? { effect: 'ALLOW', reason: 'Aprovação humana registrada', policyId: 'demo-approved' } : policy.authorize(request) }, correlationId });
163
+ const awaiting = await runtime.execute(started.runId);
164
+ if (awaiting.state !== 'awaiting_approval')
165
+ throw new Error(`Expected approval gate, got ${awaiting.state}`);
166
+ const approval = approvals.list().find((item) => item.action === 'code.write');
167
+ if (approval === undefined)
168
+ throw new Error('Approval was not persisted');
169
+ approvals.decide(approval.id, { decision: 'approved', approverId: 'human.demo', decidedAt: now() });
170
+ approved = true;
171
+ const completed = await runtime.resume(started.runId);
172
+ if (completed.state !== 'completed' || completed.validation?.status !== 'accepted')
173
+ throw new Error(`Runtime did not complete with accepted validation: ${completed.state}/${completed.validation?.status}`);
174
+ const diff = await sandbox.diff(session.id);
175
+ const promoted = await sandbox.promote(session.id, diff);
176
+ const promotedTests = mustCommand('npm', ['test'], fixtureRoot);
177
+ await sandbox.destroy(session.id);
178
+ const graphAfter = await new GraphIndexer(graph).sync(graphSource);
179
+ const audit = new SqliteAuditStore(database);
180
+ audit.append({ schemaVersion: '2.0', id: randomUUID(), action: 'demo.autonomy.promote', aggregateId: completed.runId, outcome: 'success', evidenceIds: [...completed.evidence, initialEvidence].map((item) => item.id), details: { fixtureRoot, sandboxRoot: session.root, promotedState: promoted.state, testExitCode: String(promotedTests.exitCode) }, correlationId, createdAt: now(), updatedAt: now() });
181
+ const orchestrationStore = new SqliteOrchestrationStore(database);
182
+ const sprintEngine = new SprintEngine(orchestrationStore);
183
+ const sprint = await sprintEngine.create({ objective: 'Prova de autonomia supervisionada real', includedScope: [testFile], excludedScope: ['production'], budget, completionCriteria: ['Validator accepted'], risks: ['Git promotion'], evidenceIds: [...completed.evidence].map((item) => item.id), correlationId });
184
+ await sprintEngine.start(sprint.id);
185
+ const taskEngine = new TaskEngine(orchestrationStore, sprintEngine);
186
+ const task = await taskEngine.create({ sprintId: sprint.id, objective: 'Corrigir teste falhando', acceptanceCriteria: ['npm test passa na fixture'], allowedFiles: [testFile], dependencyIds: [], evidenceIds: [...completed.evidence].map((item) => item.id), budget, correlationId });
187
+ await taskEngine.start(task.id);
188
+ const accepted = completed.validation;
189
+ await taskEngine.complete(task.id, { validateTask: () => accepted, validateSprint: () => accepted });
190
+ await sprintEngine.complete(sprint.id, { validateTask: () => accepted, validateSprint: () => accepted });
191
+ const handoff = await new HandoffEngine(orchestrationStore).create({ from: 'agent.demo', to: 'human.reviewer', intent: 'review promoted fixture fix', objective: completed.objective, completedWork: ['Context built', 'Approval recorded', 'Real worktree edited', 'npm test passed', 'Diff promoted'], decisions: ['Promotion required explicit approval'], constraints: ['Fixture-only scope'], pending: [], evidenceIds: [...completed.evidence].map((item) => item.id), acceptance: ['Validator accepted'], blockers: [], nextAgent: 'human.reviewer', correlationId });
192
+ const events = new EventBus(new SqliteEventStore(database));
193
+ await events.append({ type: 'execution.completed', aggregateId: completed.runId, payload: { validation: completed.validation?.status, promoted: promoted.promoted }, idempotencyKey: `execution.completed:${completed.runId}`, correlationId });
194
+ const result = { fixtureRoot, databasePath, runId: completed.runId, sandboxRoot: session.root, approvalId: approval.id, changedFiles: diff.files, graphNodes: graphAfter.nodes + graphBefore.nodes, graphEdges: graphAfter.edges + graphBefore.edges, handoffId: handoff.id, validation: completed.validation?.status ?? 'inconclusive' };
195
+ database.close();
196
+ return result;
197
+ }
198
+ if (process.argv[1]?.endsWith('demo-autonomy.ts')) {
199
+ runAutonomyDemo().then((result) => { console.log(JSON.stringify(result, null, 2)); }).catch((error) => { console.error(error instanceof Error ? error.stack ?? error.message : String(error)); process.exitCode = 1; });
200
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import Database from 'better-sqlite3';
5
+ import { CapabilityRegistry } from "../packages/core/src/index.js";
6
+ import { EventBus } from "../packages/events/src/index.js";
7
+ import { GraphLoop } from "../packages/graph/src/index.js";
8
+ import { ApprovalLedger, PolicyEngine } from "../packages/policy/src/index.js";
9
+ import { InMemoryEventStream } from "../packages/adapter-nest/src/index.js";
10
+ import { createDefaultControlPlane } from "../apps/server/src/main.js";
11
+ import { SqliteApprovalStore, SqliteContextCache, SqliteEventStore, SqliteGraphStore, SqliteMigrationRunner, SqliteObservationStore, SqliteOrchestrationStore, SqliteRuntimePersistence } from "../packages/adapter-sqlite/src/index.js";
12
+ const agent = { id: 'server-persistence-agent', name: 'Persistence test agent', role: 'developer', autonomy: 'supervised' };
13
+ const definition = { schemaVersion: '2.0', createdAt: '2026-08-02T00:00:00.000Z', updatedAt: '2026-08-02T00:00:00.000Z', correlationId: 'server-persistence', id: 'server.persistence.read', version: '1.0.0', description: 'Deterministic persistence probe', permissions: ['read'], risk: 'low', sideEffects: [], requirements: [], supportsAutonomy: true, idempotent: true, timeoutMs: 1000, retry: { maxAttempts: 1, backoffMs: 0 }, aliases: [] };
14
+ function makeRegistry() {
15
+ const value = new CapabilityRegistry();
16
+ value.register({ definition, validateInput: (input) => input ?? {}, validateOutput: (output) => output, handler: async () => ({ capabilityId: definition.id, payload: { ok: true }, evidence: [{ id: 'server-persistence-evidence', source: 'server-persistence-test', locator: 'handler', capturedAt: '2026-08-02T00:00:00.000Z', status: 'verified' }] }) });
17
+ return value;
18
+ }
19
+ function makePolicy(database) {
20
+ return new PolicyEngine({ approvalLedger: new ApprovalLedger(new SqliteApprovalStore(database)), rules: [{ id: 'server-persistence-approval', priority: 10, effect: 'REQUIRE_APPROVAL', reason: 'Persistence probe requires approval', scope: {} }] });
21
+ }
22
+ function makeControlPlane(database, value, policy) {
23
+ const graph = new GraphLoop(new SqliteGraphStore(database));
24
+ const events = new EventBus(new SqliteEventStore(database));
25
+ return createDefaultControlPlane(new InMemoryEventStream(), value, policy, new SqliteRuntimePersistence(database), new ApprovalLedger(new SqliteApprovalStore(database)), events, graph, undefined, new SqliteOrchestrationStore(database), new SqliteObservationStore(database));
26
+ }
27
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-server-persistence-'));
28
+ const dbPath = path.join(root, 'runtime.db');
29
+ try {
30
+ const firstDatabase = new Database(dbPath);
31
+ new SqliteMigrationRunner(firstDatabase).apply();
32
+ const firstControlPlane = makeControlPlane(firstDatabase, makeRegistry(), makePolicy(firstDatabase));
33
+ const budget = { inputTokens: 40, outputTokens: 20, totalTokens: 60, usedTokens: 0 };
34
+ const started = await firstControlPlane.runtimeStart({ objective: 'restart persistence probe', agent, budget, steps: [{ capabilityId: definition.id, payload: {}, estimatedTokens: 10, categories: ['read'], environment: 'local', files: [], approval: { action: 'read.probe', justification: 'Prove approval persistence', impact: 'No files changed', expiresAt: '2099-01-01T00:00:00.000Z' } }] });
35
+ const awaiting = await firstControlPlane.runtimeExecute(started.runId);
36
+ const pending = await firstControlPlane.approvalList();
37
+ const graph = new GraphLoop(new SqliteGraphStore(firstDatabase));
38
+ graph.upsertNode({ id: 'restart-node', type: 'Task', label: 'restart persistence probe', status: 'verified' });
39
+ new SqliteContextCache(firstDatabase).set('restart-context', 'evidence context');
40
+ await new EventBus(new SqliteEventStore(firstDatabase)).append({ type: 'approval.requested', aggregateId: started.runId, payload: { approvalId: pending[0].id }, idempotencyKey: `approval:${pending[0].id}` });
41
+ await firstControlPlane.record({ traceId: 'restart-observation', runId: started.runId, outcome: 'blocked', contextRefs: ['restart-context'] });
42
+ firstDatabase.close();
43
+ const secondDatabase = new Database(dbPath);
44
+ const secondControlPlane = makeControlPlane(secondDatabase, makeRegistry(), makePolicy(secondDatabase));
45
+ const recovered = await secondControlPlane.runtimeGet(started.runId);
46
+ const result = { ok: recovered.runId === started.runId && awaiting.state === 'awaiting_approval', state: recovered.state, approvals: (await secondControlPlane.approvalList()).length, context: new SqliteContextCache(secondDatabase).get('restart-context'), graphNodes: new GraphLoop(new SqliteGraphStore(secondDatabase)).query({ labelIncludes: 'restart persistence' }).length, events: (await new EventBus(new SqliteEventStore(secondDatabase)).list()).length, observations: (await secondControlPlane.observations()).length };
47
+ secondDatabase.close();
48
+ console.log(JSON.stringify(result));
49
+ }
50
+ finally {
51
+ fs.rmSync(root, { recursive: true, force: true });
52
+ }
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import Database from 'better-sqlite3';
5
+ import { CapabilityRegistry } from "../packages/core/src/index.js";
6
+ import { EventBus } from "../packages/events/src/index.js";
7
+ import { GraphLoop } from "../packages/graph/src/index.js";
8
+ import { ApprovalLedger, PolicyEngine } from "../packages/policy/src/index.js";
9
+ import { InMemoryEventStream } from "../packages/adapter-nest/src/index.js";
10
+ import { createDefaultControlPlane } from "../apps/server/src/main.js";
11
+ import { SqliteApprovalStore, SqliteContextCache, SqliteEventStore, SqliteGraphStore, SqliteMigrationRunner, SqliteObservationStore, SqliteOrchestrationStore, SqliteRuntimePersistence } from "../packages/adapter-sqlite/src/index.js";
12
+ const agent = { id: 'server-persistence-agent', name: 'Persistence test agent', role: 'developer', autonomy: 'supervised' };
13
+ const definition = { schemaVersion: '2.0', createdAt: '2026-08-02T00:00:00.000Z', updatedAt: '2026-08-02T00:00:00.000Z', correlationId: 'server-persistence', id: 'server.persistence.read', version: '1.0.0', description: 'Deterministic persistence probe', permissions: ['read'], risk: 'low', sideEffects: [], requirements: [], supportsAutonomy: true, idempotent: true, timeoutMs: 1000, retry: { maxAttempts: 1, backoffMs: 0 }, aliases: [] };
14
+ function makeRegistry() {
15
+ const value = new CapabilityRegistry();
16
+ value.register({ definition, validateInput: (input) => input ?? {}, validateOutput: (output) => output, handler: async () => ({ capabilityId: definition.id, payload: { ok: true }, evidence: [{ id: 'server-persistence-evidence', source: 'server-persistence-test', locator: 'handler', capturedAt: '2026-08-02T00:00:00.000Z', status: 'verified' }] }) });
17
+ return value;
18
+ }
19
+ function makePolicy(database) {
20
+ return new PolicyEngine({ approvalLedger: new ApprovalLedger(new SqliteApprovalStore(database)), rules: [{ id: 'server-persistence-approval', priority: 10, effect: 'REQUIRE_APPROVAL', reason: 'Persistence probe requires approval', scope: {} }] });
21
+ }
22
+ function makeControlPlane(database, value, policy) {
23
+ const graph = new GraphLoop(new SqliteGraphStore(database));
24
+ const events = new EventBus(new SqliteEventStore(database));
25
+ return createDefaultControlPlane(new InMemoryEventStream(), value, policy, new SqliteRuntimePersistence(database), new ApprovalLedger(new SqliteApprovalStore(database)), events, graph, undefined, new SqliteOrchestrationStore(database), new SqliteObservationStore(database));
26
+ }
27
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'forja-server-persistence-'));
28
+ const dbPath = path.join(root, 'runtime.db');
29
+ try {
30
+ const firstDatabase = new Database(dbPath);
31
+ new SqliteMigrationRunner(firstDatabase).apply();
32
+ const firstControlPlane = makeControlPlane(firstDatabase, makeRegistry(), makePolicy(firstDatabase));
33
+ const budget = { inputTokens: 40, outputTokens: 20, totalTokens: 60, usedTokens: 0 };
34
+ const started = await firstControlPlane.runtimeStart({ objective: 'restart persistence probe', agent, budget, steps: [{ capabilityId: definition.id, payload: {}, estimatedTokens: 10, categories: ['read'], environment: 'local', files: [], approval: { action: 'read.probe', justification: 'Prove approval persistence', impact: 'No files changed', expiresAt: '2099-01-01T00:00:00.000Z' } }] });
35
+ const awaiting = await firstControlPlane.runtimeExecute(started.runId);
36
+ const pending = await firstControlPlane.approvalList();
37
+ const graph = new GraphLoop(new SqliteGraphStore(firstDatabase));
38
+ graph.upsertNode({ id: 'restart-node', type: 'Task', label: 'restart persistence probe', status: 'verified' });
39
+ new SqliteContextCache(firstDatabase).set('restart-context', 'evidence context');
40
+ await new EventBus(new SqliteEventStore(firstDatabase)).append({ type: 'approval.requested', aggregateId: started.runId, payload: { approvalId: pending[0].id }, idempotencyKey: `approval:${pending[0].id}` });
41
+ await firstControlPlane.record({ traceId: 'restart-observation', runId: started.runId, outcome: 'blocked', contextRefs: ['restart-context'] });
42
+ firstDatabase.close();
43
+ const secondDatabase = new Database(dbPath);
44
+ const secondControlPlane = makeControlPlane(secondDatabase, makeRegistry(), makePolicy(secondDatabase));
45
+ const recovered = await secondControlPlane.runtimeGet(started.runId);
46
+ const result = { ok: recovered.runId === started.runId && awaiting.state === 'awaiting_approval', state: recovered.state, approvals: (await secondControlPlane.approvalList()).length, context: new SqliteContextCache(secondDatabase).get('restart-context'), graphNodes: new GraphLoop(new SqliteGraphStore(secondDatabase)).query({ labelIncludes: 'restart persistence' }).length, events: (await new EventBus(new SqliteEventStore(secondDatabase)).list()).length, observations: (await secondControlPlane.observations()).length };
47
+ secondDatabase.close();
48
+ console.log(JSON.stringify(result));
49
+ }
50
+ finally {
51
+ fs.rmSync(root, { recursive: true, force: true });
52
+ }
@@ -1,132 +1,40 @@
1
- # ForjaJS 2.x — Auditoria de implementação
1
+ # ForjaJS 2.x — Implementation audit
2
2
 
3
- **Escopo:** baseline publicado `2.0.1`, checkout local em 2026-08-01.
4
- **Objetivo:** distinguir código executável/testado de fundações isoladas antes da
5
- Sprint 1 de unificação da CLI com o Capability Registry.
6
-
7
- ## Evidências consultadas
8
-
9
- - `packages/contracts/src/index.ts`
10
- - `packages/core/src/index.ts`
11
- - `lib/core/registry.ts`
12
- - `bin/forja.ts`
13
- - `packages/mcp/src/index.ts`
14
- - `packages/sdk/src/index.ts`
15
- - `packages/adapter-nest/src/index.ts`
16
- - `apps/server/src/main.ts`
17
- - `scripts/tools-doctor.ts`
18
- - `scripts/agent-harness.ts`
19
- - `scripts/context-ops.ts`
20
- - testes em `test/*registry*`, `test/mcp.test.js`, `test/sdk.test.js`,
21
- `test/adapter-nest.test.js` e `test/harness.test.js`.
22
-
23
- ## Matriz de implementação
3
+ Auditoria realizada em 2026-08-02 sobre o código executável e os testes do repositório. “Existe” só foi marcado quando há implementação; “produção” só quando a composição oficial ou o caminho CLI é exercitado.
24
4
 
25
5
  | Componente | Existe | Integrado | Persistente | Testado | Produção |
26
6
  | --- | ---: | ---: | ---: | ---: | ---: |
27
- | Contratos versionados | sim | parcial | não aplicável | sim | parcial |
28
- | `lib/core/registry.ts` — registry CLI | sim | sim, apenas CLI | auditoria JSONL | sim | sim |
29
- | `CapabilityRegistry` | sim | CLI/server/MCP/runtime | não | sim | parcial |
30
- | Adapter CLI → capability | sim | sim, 6 comandos | não | sim | parcial |
31
- | ExecutionResult | sim | parcial, registry | não | sim | parcial |
32
- | Policy Engine | sim | registry/runtime/MCP/server | approvals em SQLite no server | sim | parcial |
33
- | Runtime Engine | sim | SQLite no server oficial; memória nos testes | runs, planos, resultados, estado e checkpoints em SQLite | sim | parcial |
34
- | Sprint/Task/Handoff | sim | parcial | stores em memória/SQLite adapter separado | sim | parcial |
35
- | Context Engine | sim | server/MCP/Runtime + fontes de memória/grafo | cache SQLite v5 | sim | parcial |
36
- | GraphLoop | sim | MCP/server/Runtime/testes | SQLite v4; memória apenas em testes | sim | parcial |
37
- | MCP | sim | tools/resources + registry dinâmico + stdio/server | auditoria MCP em SQLite no server | sim | parcial |
38
- | SDK | sim | API REST esperada | remoto | sim | parcial |
39
- | Sandbox | sim | isolada em testes | backend em memória/adapters | sim | parcial |
40
- | Planner/Validator | sim | Runtime/testes | não aplicável | sim | parcial |
41
- | Event Bus/Scheduler | sim | server/worker/testes | Event Bus no server usa SQLite; scheduler ainda separado | sim | parcial |
42
- | Observabilidade/Control Plane | sim | server/dashboard | memória por padrão | sim | parcial |
43
- | NestJS adapter/server | sim | server bootstrap | não | sim | parcial |
44
- | Next.js dashboard | sim | consulta API/proxy | remoto | sim | parcial |
45
-
46
- ## Achados principais
47
-
48
- 1. O registry declarativo legado (`COMMANDS`) contém o comportamento público da
49
- CLI: domínio, descrição, script, argumentos e gates. Ele não produz
50
- `CapabilityDefinition` nem passa pelo `CapabilityRegistry`.
51
- 2. O `CapabilityRegistry` valida, autoriza e normaliza `ExecutionResult`, mas
52
- não conhece comandos legados e não possui um catálogo padrão registrado.
53
- 3. A Sprint 5 corrigiu a composição do server: `apps/server/src/main.ts` agora
54
- registra o mesmo catálogo de seis capabilities da CLI e inicializa approvals
55
- e auditoria MCP no SQLite.
56
- 4. MCP e SDK já possuem superfícies sobre capabilities, mas dependem de um
57
- registry preenchido pelo consumidor.
58
- 5. Os três comandos da Sprint 1 possuem handlers determinísticos existentes:
59
- `tools:doctor` em `scripts/tools-doctor.ts`, `code:impact` em
60
- `scripts/agent-harness.ts` e `context:budget` em `scripts/context-ops.ts`.
61
- 6. A auditoria transversal existente em `bin/forja.ts` registra comando, args,
62
- exit code e duração, mas não registra `runId`, `capabilityId` ou o envelope
63
- completo de `ExecutionResult`.
64
- 7. A Sprint 3 adicionou a porta `RuntimePersistence`, o adapter SQLite e a
65
- recuperação explícita por policy; approvals e execução distribuída continuam pendentes.
66
- 8. A Sprint 4 adicionou `forja_capability_describe`, ferramentas derivadas do registry e o
67
- transporte local `mcp:start`; a Sprint 5 completou o catálogo padrão do server.
68
- 9. A Sprint 5 passou o catálogo CLI, approvals e auditoria MCP para a composição oficial do
69
- server; approvals e auditoria MCP usam SQLite.
70
- 10. A Sprint 6 tornou o Event Bus restart-safe sobre `SqliteEventStore` e adicionou uma prova
71
- E2E determinística; GraphLoop persistente e sandbox Git worktree continuam pendentes.
72
- 11. A Sprint 7 extraiu `GraphStore`, adicionou `SqliteGraphStore` e ligou o mesmo grafo persistente
73
- ao MCP e à memória de execução; Context Engine e engines de contradição/agenda ainda não estão
74
- plenamente ligados ao store.
75
- 12. A Sprint 8 ligou `GraphContextSource` e `SqliteContextCache` ao bootstrap oficial; a relevância
76
- de grafo é lexical e determinística, enquanto trechos de arquivos e busca semântica continuam
77
- fora do escopo.
78
- 13. A Sprint 9 ampliou o extractor determinístico para símbolos, chamadas, ADRs, tarefas, handoffs,
79
- testes e manifests; resolução semântica completa, commits e diffs ainda requerem extractors
80
- específicos.
81
- 14. A Sprint 10 adicionou `GraphIndexer`, `GitGraphDocumentSource` e a capability `graph.sync`;
82
- a composição oficial usa o GraphLoop SQLite, mas poda de remoções e histórico de commits ainda
83
- estão pendentes.
84
- 15. A Sprint 11 expôs `graph.sync` no registry/CLI standalone e no MCP stdio, com métricas de
85
- documentos, nós, arestas, arquivos e duração; observações persistentes do Control Plane ainda
86
- são uma pendência distinta.
87
-
88
- ## Mapa inicial comando → capability
89
-
90
- | Comando legado | Capability alvo | Prova Sprint 1 |
91
- | --- | --- | ---: |
92
- | `tools:doctor` | `system.doctor` | sim |
93
- | `code:impact` | `code.impact` | sim |
94
- | `context:budget` | `context.budget` | sim |
95
- | `spec:new` | `spec.create` | próxima |
96
- | `spec:check` | `spec.validate` | sim, Sprint 2 |
97
- | `sprint:start` | `sprint.start` | próxima |
98
- | `sprint:status` | `sprint.status` | sim, Sprint 2 |
99
- | `gsd:handoff` | `handoff.create` | sim, Sprint 2 |
100
- | `context:smart` | `context.build` | próxima |
101
- | `memory:compress` | `memory.compact` | próxima |
102
-
103
- O restante do mapa é mantido como backlog de migração; nesta sprint nenhum
104
- comando não comprovado será apresentado como integrado.
105
-
106
- ## Hipóteses e informações ausentes
107
-
108
- - A compatibilidade de saída textual dos três comandos deve ser preservada;
109
- `--json` adicionará o envelope estruturado sem remover o modo humano.
110
- - Os handlers legados continuam sendo a fonte determinística de execução nesta
111
- sprint; a unificação elimina o registry paralelo, não reescreve os handlers.
112
- - A persistência de approvals, eventos de runtime e execução distribuída permanece fora do
113
- escopo após a Sprint 3.
114
- - O contrato atual não possui um campo específico para argumentos de CLI; o
115
- payload validado da capability carregará esses argumentos.
116
-
117
- ## Decisão de escopo
118
-
119
- Implementar um adapter na aplicação CLI que registra três capabilities no
120
- `CapabilityRegistry`, delega os handlers legados por uma porta injetada e usa
121
- `PolicyEngine` antes da execução. `bin/forja.ts` continuará adaptando comandos
122
- não migrados durante a transição, mas os três comandos de prova não terão lógica
123
- duplicada de negócio.
124
-
125
- ## Riscos
126
-
127
- - Alterar o dispatch pode mudar mensagens ou códigos de saída; testes de
128
- equivalência devem comparar modo textual e modo JSON.
129
- - `code:impact` depende de `codegraph` e tem fallback manual; o adapter não pode
130
- transformar ausência de ferramenta em sucesso falso.
131
- - `context:budget` grava uma medição no SQLite; a política deve declarar o
132
- efeito de banco, mesmo sendo uma operação determinística.
7
+ | Contratos versionados | sim | sim | n/a | sim | sim |
8
+ | Capability Registry | sim | sim | n/a | sim | sim |
9
+ | CLI adapter | sim | sim | n/a | sim | sim |
10
+ | Runtime | sim | sim | sim | sim | sim |
11
+ | Policy/approvals | sim | sim | sim | sim | sim |
12
+ | Sprint/Task/Handoff | sim | sim | sim | sim | sim |
13
+ | Context Engine | sim | sim | sim | sim | sim |
14
+ | GraphLoop | sim | sim | sim | sim | sim |
15
+ | Sandbox Git worktree | sim | sim | sessão | sim | sim |
16
+ | Sandbox rollback | sim | sim | sessão | sim | sim |
17
+ | Validator | sim | sim | n/a | sim | sim |
18
+ | Event Bus/Scheduler | sim | sim | sim | sim | sim |
19
+ | MCP stdio | sim | sim | n/a | sim | sim |
20
+ | SDK | sim | sim | n/a | sim | sim |
21
+ | Nest adapter/control plane | sim | sim | sim | sim | sim |
22
+ | Dashboard | sim | sim | via API | sim | parcial |
23
+ | Observability/Evals | sim | sim | sim | sim | sim |
24
+ | Plugin SDK | sim | sim | n/a | sim | sim |
25
+ | GitHub/Docker official boundaries | sim | não há handler externo | n/a | sim | boundary |
26
+
27
+ ## Evidências executadas
28
+
29
+ - `npm run demo:autonomy`: fixture externa, worktree Git, alteração real, `npm test`, diff, promoção, SQLite, GraphLoop e handoff.
30
+ - `test/mcp-stdio.test.js`: transporte JSON-RPC por processo filho, stdout limpo, tools/resources e shutdown.
31
+ - `test/server-persistence.test.js`: composição oficial SQLite, encerramento/recriação e recuperação de runtime, approval, contexto, grafo, evento e observação.
32
+ - `test/sandbox.test.js` e `test/adapter-git.test.js`: promoção e rollback explícitos.
33
+ - `test/context-benchmark.test.js`: benchmark determinístico; execução observada nesta árvore: baseline 214.549 tokens estimados, contexto selecionado 9.175, redução 95,72%, cache hit 1 e cobertura de evidência 1.
34
+ - `npm test -- --test-concurrency=1`: 300/300 aprovados.
35
+ - `npm run build`: aprovado.
36
+ - `git diff --check`: aprovado.
37
+
38
+ ## Limites honestos
39
+
40
+ Os plugins oficiais são boundaries permissionados, não clientes GitHub/Docker completos. O dashboard é superfície de supervisão e não foi usado como dependência do fluxo CLI-first. A estimativa de tokens é um proxy determinístico bytes/4, não telemetria de um provedor de modelo. Essas limitações impedem afirmar que todos os cenários externos são 10/10; o fluxo local-first comprovado está fechado.
@@ -0,0 +1,40 @@
1
+ # Sprint 12 — Prova de autonomia supervisionada real
2
+
3
+ ## Objetivo
4
+
5
+ Substituir a prova E2E simulada por uma demonstração repetível que usa fixture externa,
6
+ Git worktree, arquivo real, teste real, aprovação persistida, promoção real e estado
7
+ auditável em SQLite.
8
+
9
+ ## Escopo
10
+
11
+ - `npm run demo:autonomy`;
12
+ - agente simulado determinístico, sem provedor LLM;
13
+ - Context Engine e GraphLoop antes do plano;
14
+ - Policy Engine e `ApprovalLedger` antes da escrita;
15
+ - `GitWorktreeBackend` no caminho principal;
16
+ - Validator independente antes da promoção;
17
+ - Sprint, Task, Handoff, Event Bus e auditoria persistidos.
18
+
19
+ ## Critérios de aceite
20
+
21
+ - fixture é criada fora do repositório do framework;
22
+ - teste inicia falhando e termina passando após edição na worktree;
23
+ - workspace principal da fixture só muda na promoção explícita;
24
+ - aprovação, run, checkpoint, sandbox, evento e handoff sobrevivem no SQLite;
25
+ - GraphLoop recebe evidências e relações da execução;
26
+ - Validator retorna `accepted` antes de `promote`;
27
+ - teste automatizado repete o fluxo e limpa seus artefatos temporários.
28
+
29
+ ## Fora do escopo
30
+
31
+ MCP stdio real, composição de servidor após restart abrupto, rollback automatizado,
32
+ contradições avançadas, plugins oficiais e benchmark comparativo de tokens. São as
33
+ próximas sprints de fechamento 10/10.
34
+
35
+ ## Evidências
36
+
37
+ - `scripts/demo-autonomy.ts`;
38
+ - `test/demo-autonomy.test.js`;
39
+ - `npm run demo:autonomy`;
40
+ - saída observada: validação `accepted`, uma alteração promovida, 18 nós e 14 arestas.
@@ -0,0 +1,26 @@
1
+ # Sprint 13 — MCP stdio real
2
+
3
+ ## Objetivo
4
+
5
+ Provar que clientes externos conseguem iniciar `forja mcp:start`, negociar o
6
+ protocolo JSON-RPC por stdio, descobrir tools, descrever e executar capability,
7
+ ler resource e encerrar sem perder o contrato de transporte.
8
+
9
+ ## Critérios de aceite
10
+
11
+ - processo MCP real é iniciado por `node bin/forja.ts mcp:start`;
12
+ - cada resposta é JSON-RPC válido em stdout;
13
+ - stdout não contém logs não-JSON e stderr permanece limpo no caminho feliz;
14
+ - `initialize`, `notifications/initialized`, `tools/list`, `tools/call`,
15
+ `resources/list` e `resources/read` funcionam;
16
+ - execução retorna `ExecutionResult` estruturado;
17
+ - EOF encerra o servidor com exit code 0.
18
+
19
+ ## Evidência
20
+
21
+ `test/mcp-stdio.test.js` executa um cliente filho real contra o transporte.
22
+
23
+ ## Próximo passo
24
+
25
+ Compor o mesmo transporte no servidor oficial e provar reinício abrupto com
26
+ runtime, approval, context cache e GraphLoop persistidos.
@@ -0,0 +1,28 @@
1
+ # Sprint 14 — Composição oficial persistente e restart
2
+
3
+ ## Objetivo
4
+
5
+ Provar que o backend Nest oficial compõe os adapters SQLite e recupera estado
6
+ operacional depois que a primeira composição é encerrada e uma segunda é criada.
7
+
8
+ ## Critérios de aceite
9
+
10
+ - RuntimeRun e plano são recuperáveis;
11
+ - approval pendente permanece disponível;
12
+ - checkpoint/runtime state são lidos pelo novo processo;
13
+ - Context cache, GraphLoop e Event Bus preservam dados;
14
+ - Sprint/Task/Handoff e Observabilidade usam stores SQLite no bootstrap;
15
+ - build estrito e probe em processo separado passam.
16
+
17
+ ## Evidência
18
+
19
+ `test/server-persistence.test.js` inicia `test/server-persistence-probe.mjs` com
20
+ `node --import tsx`; o probe cria duas composições oficiais contra o mesmo arquivo
21
+ SQLite e confirma run `awaiting_approval`, approval, contexto, grafo, eventos e
22
+ observações após o fechamento da primeira conexão.
23
+
24
+ ## Risco conhecido
25
+
26
+ Eventos publicados pelo Control Plane são assíncronos; o lifecycle oficial deve
27
+ adicionar drain explícito antes de shutdown gracioso. O probe aguarda o flush para
28
+ não confundir essa fronteira com perda de dados.
@@ -0,0 +1,22 @@
1
+ # Sprint 15 — Caos determinístico e hardening de segurança
2
+
3
+ ## Objetivo
4
+
5
+ Transformar falhas previsíveis em estados auditáveis, sem perder evidência nem
6
+ permitir que entradas externas escapem do escopo da execução.
7
+
8
+ ## Entregas
9
+
10
+ - approval expirada e reutilização recusadas;
11
+ - corrupção de payload SQLite falha explicitamente;
12
+ - policy continua deny-by-default;
13
+ - caminhos Graph/Git fora da raiz são ignorados;
14
+ - sandbox não herda secrets arbitrários do ambiente;
15
+ - testes MCP stdio cobrem payload/protocolo em processo real.
16
+
17
+ ## Fora do escopo desta fatia
18
+
19
+ Docker escape review, plugins maliciosos, lock SQLite sob concorrência,
20
+ checkpoint rollback automático, fuzzing de payload e benchmark de tokens. Esses
21
+ casos continuam como bloqueios de release 10/10, embora os gates básicos já
22
+ estejam cobertos.