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.
- package/CHANGELOG.md +15 -0
- package/README.md +22 -0
- package/README.pt-BR.md +22 -0
- package/dist/apps/cli/src/index.d.ts +44 -0
- package/dist/apps/cli/src/index.js +304 -0
- package/dist/apps/server/src/main.d.ts +9 -3
- package/dist/apps/server/src/main.js +70 -19
- package/dist/bin/forja.js +213 -0
- package/dist/lib/core/health.js +2 -1
- package/dist/lib/core/registry.d.ts +17 -0
- package/dist/lib/core/registry.js +17 -0
- package/dist/lib/core/release.d.ts +16 -0
- package/dist/packages/adapter-git/src/index.d.ts +14 -0
- package/dist/packages/adapter-git/src/index.js +66 -0
- package/dist/packages/adapter-sqlite/src/index.d.ts +59 -2
- package/dist/packages/adapter-sqlite/src/index.js +136 -0
- package/dist/packages/context/src/index.d.ts +8 -0
- package/dist/packages/context/src/index.js +7 -0
- package/dist/packages/contracts/src/index.d.ts +1 -1
- package/dist/packages/events/src/index.d.ts +2 -0
- package/dist/packages/events/src/index.js +16 -0
- package/dist/packages/graph/src/index.d.ts +59 -3
- package/dist/packages/graph/src/index.js +139 -21
- package/dist/packages/mcp/src/index.d.ts +14 -0
- package/dist/packages/mcp/src/index.js +39 -5
- package/dist/packages/plugin-docker/src/index.d.ts +3 -0
- package/dist/packages/plugin-docker/src/index.js +13 -0
- package/dist/packages/plugin-github/src/index.d.ts +3 -0
- package/dist/packages/plugin-github/src/index.js +13 -0
- package/dist/packages/policy/src/index.d.ts +7 -0
- package/dist/packages/policy/src/index.js +17 -1
- package/dist/packages/runtime/src/index.d.ts +20 -1
- package/dist/packages/runtime/src/index.js +34 -1
- package/dist/packages/sandbox/src/index.d.ts +2 -0
- package/dist/packages/sandbox/src/index.js +10 -0
- package/dist/scripts/context-benchmark.d.ts +2 -0
- package/dist/scripts/context-benchmark.js +39 -0
- package/dist/scripts/demo-autonomy.d.ts +15 -0
- package/dist/scripts/demo-autonomy.js +200 -0
- package/dist/scripts/server-persistence-probe.d.mts +1 -0
- package/dist/scripts/server-persistence-probe.d.ts +1 -0
- package/dist/scripts/server-persistence-probe.js +52 -0
- package/dist/scripts/server-persistence-probe.mjs +52 -0
- package/docs/2x/CLI-CAPABILITIES.md +35 -0
- package/docs/2x/IMPLEMENTATION-AUDIT.md +40 -0
- package/docs/2x/SPRINT-1-CLI-CAPABILITY-PLAN.md +53 -0
- package/docs/2x/SPRINT-10-GRAPH-SYNC-PLAN.md +54 -0
- package/docs/2x/SPRINT-11-GRAPH-SYNC-CLI-MCP-PLAN.md +38 -0
- package/docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md +40 -0
- package/docs/2x/SPRINT-13-MCP-STDIO-PLAN.md +26 -0
- package/docs/2x/SPRINT-14-SERVER-RESTART-PLAN.md +28 -0
- package/docs/2x/SPRINT-15-CHAOS-SECURITY-PLAN.md +22 -0
- package/docs/2x/SPRINT-16-LAST-MILE-PLAN.md +25 -0
- package/docs/2x/SPRINT-2-CLI-CAPABILITY-PLAN.md +39 -0
- package/docs/2x/SPRINT-3-RUNTIME-PERSISTENCE-PLAN.md +42 -0
- package/docs/2x/SPRINT-4-MCP-REGISTRY-PLAN.md +35 -0
- package/docs/2x/SPRINT-5-SERVER-APPROVALS-AUDIT-PLAN.md +31 -0
- package/docs/2x/SPRINT-6-EVENTS-E2E-PLAN.md +55 -0
- package/docs/2x/SPRINT-7-GRAPHLOOP-PERSISTENCE-PLAN.md +60 -0
- package/docs/2x/SPRINT-8-CONTEXT-GRAPH-PLAN.md +64 -0
- package/docs/2x/SPRINT-9-DETERMINISTIC-EXTRACTORS-PLAN.md +51 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-1-cli-capabilities.md +41 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-10-graph-sync.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-11-graph-sync-cli-mcp.md +22 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-12-real-autonomy.md +16 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-2-cli-capabilities.md +30 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-3-runtime-persistence.md +29 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-4-mcp.md +29 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-5-server-approvals-audit.md +22 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-6-events-e2e.md +25 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-7-graphloop.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-8-context-graph.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_sprint-9-extractors.md +21 -0
- package/memory/50-orchestration/handoffs/2026-08-02_sprint-13-mcp-stdio.md +14 -0
- package/memory/50-orchestration/handoffs/2026-08-02_sprint-14-server-restart.md +15 -0
- package/memory/50-orchestration/handoffs/2026-08-02_sprint-15-chaos-security.md +13 -0
- package/memory/50-orchestration/handoffs/2026-08-02_sprint-16-last-mile.md +11 -0
- package/memory/90-decisions/0059-cli-adapter-capability-registry.md +17 -0
- package/memory/90-decisions/0060-runtime-persistence-port.md +17 -0
- package/memory/90-decisions/0061-mcp-dynamic-registry-stdio.md +16 -0
- package/memory/90-decisions/0062-server-catalog-approval-audit.md +17 -0
- package/memory/90-decisions/0063-events-persistent-e2e.md +19 -0
- package/memory/90-decisions/0064-graphloop-sqlite-store.md +20 -0
- package/memory/90-decisions/0065-context-graph-source-cache.md +20 -0
- package/memory/90-decisions/0066-graph-deterministic-extractors.md +16 -0
- package/memory/90-decisions/0067-graph-sync-capability.md +17 -0
- package/memory/90-decisions/0068-graph-sync-cli-mcp.md +17 -0
- package/memory/90-decisions/0069-real-autonomy-demo.md +16 -0
- package/memory/90-decisions/0070-mcp-stdio-real.md +11 -0
- package/memory/90-decisions/0071-server-persistence-composition.md +12 -0
- package/memory/90-decisions/0072-sandbox-security-boundaries.md +9 -0
- package/memory/90-decisions/0073-last-mile-rollback-benchmark-plugins.md +17 -0
- package/package.json +13 -3
|
@@ -13,6 +13,7 @@ export class McpAdapterError extends Error {
|
|
|
13
13
|
export const MCP_TOOLS = [
|
|
14
14
|
tool('forja_workspace_status', 'Retorna o estado operacional mínimo do workspace.', []),
|
|
15
15
|
tool('forja_capabilities_list', 'Lista capabilities visíveis para a identidade MCP.', []),
|
|
16
|
+
tool('forja_capability_describe', 'Descreve uma capability pelo Registry.', ['capabilityId']),
|
|
16
17
|
tool('forja_capability_execute', 'Executa uma capability pelo Registry com Policy e resultado auditável.', ['capabilityId']),
|
|
17
18
|
tool('forja_context_build', 'Constrói contexto mínimo com orçamento e evidências.', ['objective', 'budget']),
|
|
18
19
|
tool('forja_memory_query', 'Consulta memória por objetivo.', ['objective']),
|
|
@@ -32,6 +33,11 @@ export class McpServer {
|
|
|
32
33
|
this.dependencies = dependencies;
|
|
33
34
|
for (const definition of MCP_TOOLS)
|
|
34
35
|
this.tools.set(definition.name, definition);
|
|
36
|
+
for (const definition of dependencies.registry.list({ agent: dependencies.agent, policy: dependencies.policy })) {
|
|
37
|
+
const name = capabilityToolName(definition.id);
|
|
38
|
+
if (!this.tools.has(name))
|
|
39
|
+
this.tools.set(name, capabilityTool(definition));
|
|
40
|
+
}
|
|
35
41
|
for (const uri of MCP_RESOURCE_URIS)
|
|
36
42
|
this.resources.set(uri, { uri, name: uri, description: `Forja resource ${uri}`, mimeType: 'application/json', read: () => dependencies.resourceData?.[uri] ?? { available: false, uri, reason: 'Resource provider is not configured' } });
|
|
37
43
|
for (const resource of dependencies.resources ?? [])
|
|
@@ -41,16 +47,23 @@ export class McpServer {
|
|
|
41
47
|
listResources() { return [...this.resources.values()]; }
|
|
42
48
|
async callTool(name, input = {}) {
|
|
43
49
|
const definition = this.tools.get(name);
|
|
44
|
-
if (definition === undefined)
|
|
45
|
-
|
|
50
|
+
if (definition === undefined) {
|
|
51
|
+
const result = this.error('TOOL_NOT_FOUND', `MCP tool not found: ${name}`);
|
|
52
|
+
await this.audit(name, input, 'failure', result.structuredContent);
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
46
55
|
try {
|
|
47
56
|
const object = this.objectInput(input);
|
|
48
57
|
this.requireFields(definition, object);
|
|
49
58
|
const value = await this.dispatch(name, object);
|
|
50
|
-
|
|
59
|
+
const result = this.success(value);
|
|
60
|
+
await this.audit(name, object, 'success');
|
|
61
|
+
return result;
|
|
51
62
|
}
|
|
52
63
|
catch (error) {
|
|
53
|
-
|
|
64
|
+
const result = this.error('TOOL_FAILED', error instanceof Error ? error.message : 'Unknown MCP tool error');
|
|
65
|
+
await this.audit(name, input, 'failure', result.structuredContent);
|
|
66
|
+
return result;
|
|
54
67
|
}
|
|
55
68
|
}
|
|
56
69
|
async readResource(uri) {
|
|
@@ -68,6 +81,7 @@ export class McpServer {
|
|
|
68
81
|
switch (name) {
|
|
69
82
|
case 'forja_workspace_status': return { agent: this.dependencies.agent, capabilities: this.dependencies.registry.list({ agent: this.dependencies.agent }), resources: this.listResources().map((resource) => resource.uri) };
|
|
70
83
|
case 'forja_capabilities_list': return this.dependencies.registry.list({ agent: this.dependencies.agent, policy: this.dependencies.policy });
|
|
84
|
+
case 'forja_capability_describe': return this.dependencies.registry.describe(this.string(input, 'capabilityId'), { agent: this.dependencies.agent, policy: this.dependencies.policy });
|
|
71
85
|
case 'forja_capability_execute': return this.executeCapability(input);
|
|
72
86
|
case 'forja_context_build': return this.requireContext().build(this.contextRequest(input));
|
|
73
87
|
case 'forja_memory_query': return this.requireMemory().query(this.string(input, 'objective'));
|
|
@@ -78,9 +92,16 @@ export class McpServer {
|
|
|
78
92
|
case 'forja_spec_check': return this.requireSpecChecker().check(input);
|
|
79
93
|
case 'forja_test_run': return this.requireTestRunner().run(input);
|
|
80
94
|
case 'forja_execution_validate': return this.requireExecutionValidator().validate(input);
|
|
81
|
-
default:
|
|
95
|
+
default:
|
|
96
|
+
if (name.startsWith('forja_capability_'))
|
|
97
|
+
return this.executeDynamicCapability(name, input);
|
|
98
|
+
throw new McpAdapterError(`MCP tool not implemented: ${name}`);
|
|
82
99
|
}
|
|
83
100
|
}
|
|
101
|
+
executeDynamicCapability(name, input) {
|
|
102
|
+
const capabilityId = name.slice('forja_capability_'.length).replace(/_/g, '.');
|
|
103
|
+
return this.executeCapability({ ...input, capabilityId });
|
|
104
|
+
}
|
|
84
105
|
async createHandoff(input) {
|
|
85
106
|
this.authorize('forja_handoff_create', 'write', 'medium', []);
|
|
86
107
|
return this.requireHandoffs().create({
|
|
@@ -148,6 +169,19 @@ export class McpServer {
|
|
|
148
169
|
throw new McpAdapterError('Execution validator is not configured'); return this.dependencies.executionValidator; }
|
|
149
170
|
success(value) { return { isError: false, content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value }; }
|
|
150
171
|
error(code, message) { const value = { code, message }; return { isError: true, content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value }; }
|
|
172
|
+
async audit(toolName, input, outcome, error) {
|
|
173
|
+
if (this.dependencies.audit === undefined)
|
|
174
|
+
return;
|
|
175
|
+
const correlationId = isRecord(input) && typeof input.correlationId === 'string' ? input.correlationId : `${this.dependencies.agent.id}:${toolName}`;
|
|
176
|
+
try {
|
|
177
|
+
await this.dependencies.audit.append({ action: 'mcp.tool', tool: toolName, agentId: this.dependencies.agent.id, correlationId, outcome, details: error === undefined ? {} : { error: JSON.stringify(error) } });
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// Auditoria não pode derrubar o transporte MCP; o sink deve expor sua própria saúde.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
151
183
|
}
|
|
152
184
|
function tool(name, description, required) { return { name, description, inputSchema: { type: 'object', properties: Object.fromEntries(required.map((field) => [field, { type: field === 'budget' ? 'object' : field.endsWith('Ids') ? 'array' : 'string' }])), required, additionalProperties: false } }; }
|
|
185
|
+
function capabilityToolName(id) { return `forja_capability_${id.replace(/[^a-zA-Z0-9_]/g, '_')}`; }
|
|
186
|
+
function capabilityTool(definition) { return { name: capabilityToolName(definition.id), description: `Executa ${definition.id}: ${definition.description}`, inputSchema: { type: 'object', properties: { payload: { type: 'object' }, correlationId: { type: 'string' }, files: { type: 'array' }, categories: { type: 'array' } }, additionalProperties: false } }; }
|
|
153
187
|
function isRecord(value) { return typeof value === 'object' && value !== null; }
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Official manifest-only Docker integration boundary. The host supplies the sandbox handler. */
|
|
2
|
+
export const dockerPlugin = {
|
|
3
|
+
manifest: {
|
|
4
|
+
id: 'forja.docker',
|
|
5
|
+
version: '2.0.3',
|
|
6
|
+
capabilities: ['docker.image.inspect', 'docker.container.run'],
|
|
7
|
+
permissions: ['workspace:read', 'capabilities:list', 'capability:execute'],
|
|
8
|
+
events: ['execution.completed', 'agent.blocked'],
|
|
9
|
+
migrations: [],
|
|
10
|
+
dashboardExtensions: ['docker.container'],
|
|
11
|
+
compatibleCore: '^2.0.0',
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Official manifest-only GitHub integration boundary. Network handlers are injected by the host. */
|
|
2
|
+
export const githubPlugin = {
|
|
3
|
+
manifest: {
|
|
4
|
+
id: 'forja.github',
|
|
5
|
+
version: '2.0.3',
|
|
6
|
+
capabilities: ['github.issue.list', 'github.pull_request.status'],
|
|
7
|
+
permissions: ['workspace:read', 'capabilities:list', 'capability:execute', 'events:subscribe'],
|
|
8
|
+
events: ['commit.created', 'execution.completed'],
|
|
9
|
+
migrations: [],
|
|
10
|
+
dashboardExtensions: ['github.pull-request'],
|
|
11
|
+
compatibleCore: '^2.0.0',
|
|
12
|
+
},
|
|
13
|
+
};
|
|
@@ -50,11 +50,18 @@ export interface ApprovalDecision {
|
|
|
50
50
|
export interface ApprovalInput extends ApprovalDetails {
|
|
51
51
|
readonly correlationId: string;
|
|
52
52
|
}
|
|
53
|
+
export interface ApprovalStore {
|
|
54
|
+
save(request: ApprovalRequest): void;
|
|
55
|
+
get(id: EntityId): ApprovalRequest | undefined;
|
|
56
|
+
list(): readonly ApprovalRequest[];
|
|
57
|
+
}
|
|
53
58
|
export declare class PolicyError extends Error {
|
|
54
59
|
constructor(message: string);
|
|
55
60
|
}
|
|
56
61
|
export declare class ApprovalLedger {
|
|
57
62
|
private readonly requests;
|
|
63
|
+
private readonly store?;
|
|
64
|
+
constructor(store?: ApprovalStore);
|
|
58
65
|
create(input: ApprovalInput, now?: ISO8601): ApprovalRequest;
|
|
59
66
|
list(): readonly ApprovalRequest[];
|
|
60
67
|
decide(id: EntityId, decision: ApprovalDecision): ApprovalRequest;
|
|
@@ -8,6 +8,8 @@ export class PolicyError extends Error {
|
|
|
8
8
|
}
|
|
9
9
|
export class ApprovalLedger {
|
|
10
10
|
requests = new Map();
|
|
11
|
+
store;
|
|
12
|
+
constructor(store) { this.store = store; }
|
|
11
13
|
create(input, now = new Date().toISOString()) {
|
|
12
14
|
if (input.action.trim().length === 0)
|
|
13
15
|
throw new PolicyError('Approval action is required');
|
|
@@ -28,9 +30,14 @@ export class ApprovalLedger {
|
|
|
28
30
|
updatedAt: now,
|
|
29
31
|
};
|
|
30
32
|
this.requests.set(request.id, request);
|
|
33
|
+
void this.store?.save(request);
|
|
31
34
|
return request;
|
|
32
35
|
}
|
|
33
|
-
list() {
|
|
36
|
+
list() {
|
|
37
|
+
if (this.store !== undefined)
|
|
38
|
+
return this.store.list();
|
|
39
|
+
return [...this.requests.values()].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
|
40
|
+
}
|
|
34
41
|
decide(id, decision) {
|
|
35
42
|
const current = this.get(id);
|
|
36
43
|
if (current.decision !== undefined)
|
|
@@ -39,6 +46,7 @@ export class ApprovalLedger {
|
|
|
39
46
|
throw new PolicyError(`Approval expired: ${id}`);
|
|
40
47
|
const updated = { ...current, decision: decision.decision, approverId: decision.approverId, updatedAt: decision.decidedAt };
|
|
41
48
|
this.requests.set(id, updated);
|
|
49
|
+
void this.store?.save(updated);
|
|
42
50
|
return updated;
|
|
43
51
|
}
|
|
44
52
|
expire(now) {
|
|
@@ -47,6 +55,7 @@ export class ApprovalLedger {
|
|
|
47
55
|
if (current.decision === undefined && current.expiresAt <= now) {
|
|
48
56
|
const updated = { ...current, decision: 'expired', updatedAt: now };
|
|
49
57
|
this.requests.set(current.id, updated);
|
|
58
|
+
void this.store?.save(updated);
|
|
50
59
|
expired.push(updated);
|
|
51
60
|
}
|
|
52
61
|
}
|
|
@@ -54,6 +63,13 @@ export class ApprovalLedger {
|
|
|
54
63
|
}
|
|
55
64
|
get(id) {
|
|
56
65
|
const request = this.requests.get(id);
|
|
66
|
+
if (request === undefined && this.store !== undefined) {
|
|
67
|
+
const persisted = this.store.get(id);
|
|
68
|
+
if (persisted !== undefined) {
|
|
69
|
+
this.requests.set(id, persisted);
|
|
70
|
+
return persisted;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
57
73
|
if (request === undefined)
|
|
58
74
|
throw new PolicyError(`Approval not found: ${id}`);
|
|
59
75
|
return request;
|
|
@@ -31,6 +31,22 @@ export interface CheckpointStore {
|
|
|
31
31
|
save(checkpoint: Checkpoint): void | Promise<void>;
|
|
32
32
|
get(runId: RunId): Checkpoint | undefined | Promise<Checkpoint | undefined>;
|
|
33
33
|
}
|
|
34
|
+
export interface RuntimePersistence {
|
|
35
|
+
saveRun(run: RuntimeRun): void | Promise<void>;
|
|
36
|
+
getRun(runId: RunId): RuntimeRun | undefined | Promise<RuntimeRun | undefined>;
|
|
37
|
+
savePlan(runId: RunId, plan: readonly RuntimePlanStep[]): void | Promise<void>;
|
|
38
|
+
getPlan(runId: RunId): readonly RuntimePlanStep[] | undefined | Promise<readonly RuntimePlanStep[] | undefined>;
|
|
39
|
+
saveResults(runId: RunId, results: readonly ExecutionResult[]): void | Promise<void>;
|
|
40
|
+
getResults(runId: RunId): readonly ExecutionResult[] | undefined | Promise<readonly ExecutionResult[] | undefined>;
|
|
41
|
+
saveCursor(runId: RunId, nextStep: number, startedAt: number): void | Promise<void>;
|
|
42
|
+
getCursor(runId: RunId): {
|
|
43
|
+
readonly nextStep: number;
|
|
44
|
+
readonly startedAt: number;
|
|
45
|
+
} | undefined | Promise<{
|
|
46
|
+
readonly nextStep: number;
|
|
47
|
+
readonly startedAt: number;
|
|
48
|
+
} | undefined>;
|
|
49
|
+
}
|
|
34
50
|
export interface RuntimeMemory {
|
|
35
51
|
remember(run: RuntimeRun, result: ExecutionResult): void | Promise<void>;
|
|
36
52
|
}
|
|
@@ -50,6 +66,7 @@ export interface RuntimeDependencies {
|
|
|
50
66
|
readonly validator: RuntimeValidator;
|
|
51
67
|
readonly contextBuilder?: RuntimeContextBuilder;
|
|
52
68
|
readonly checkpointStore?: CheckpointStore;
|
|
69
|
+
readonly persistence?: RuntimePersistence;
|
|
53
70
|
readonly memory?: RuntimeMemory;
|
|
54
71
|
}
|
|
55
72
|
export declare class RuntimeError extends Error {
|
|
@@ -73,13 +90,15 @@ export declare class RuntimeEngine {
|
|
|
73
90
|
constructor(dependencies: RuntimeDependencies, limits?: Partial<RuntimeLimits>);
|
|
74
91
|
start(request: RuntimeStartRequest): Promise<RuntimeRun>;
|
|
75
92
|
execute(runId: RunId): Promise<RuntimeRun>;
|
|
76
|
-
|
|
93
|
+
recover(runId: RunId, policy: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
|
|
94
|
+
resume(runId: RunId, policy?: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
|
|
77
95
|
pause(runId: RunId): RuntimeRun;
|
|
78
96
|
cancel(runId: RunId): Promise<RuntimeRun>;
|
|
79
97
|
get(runId: RunId): RuntimeRun;
|
|
80
98
|
private validateAndFinish;
|
|
81
99
|
private stop;
|
|
82
100
|
private update;
|
|
101
|
+
private persist;
|
|
83
102
|
private saveCheckpoint;
|
|
84
103
|
private metrics;
|
|
85
104
|
private auditFields;
|
|
@@ -64,6 +64,8 @@ export class RuntimeEngine {
|
|
|
64
64
|
this.nextSteps.set(runId, 0);
|
|
65
65
|
this.policies.set(runId, request.policy);
|
|
66
66
|
this.startedAt.set(runId, Date.now());
|
|
67
|
+
await this.dependencies.persistence?.saveRun(run);
|
|
68
|
+
await this.dependencies.persistence?.saveCursor(runId, 0, this.startedAt.get(runId));
|
|
67
69
|
try {
|
|
68
70
|
this.update(runId, { state: 'planning' });
|
|
69
71
|
const context = this.dependencies.contextBuilder === undefined ? undefined : await this.dependencies.contextBuilder.build(request.objective);
|
|
@@ -71,6 +73,8 @@ export class RuntimeEngine {
|
|
|
71
73
|
if (plan.length > this.limits.maxSteps)
|
|
72
74
|
return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Plan exceeds maximum steps', false));
|
|
73
75
|
this.plans.set(runId, plan);
|
|
76
|
+
await this.dependencies.persistence?.savePlan(runId, plan);
|
|
77
|
+
await this.persist(runId);
|
|
74
78
|
await this.saveCheckpoint(runId, 'planning', 0);
|
|
75
79
|
return this.get(runId);
|
|
76
80
|
}
|
|
@@ -127,6 +131,7 @@ export class RuntimeEngine {
|
|
|
127
131
|
approval: step.approval,
|
|
128
132
|
});
|
|
129
133
|
this.results.get(runId)?.push(result);
|
|
134
|
+
await this.dependencies.persistence?.saveResults(runId, this.results.get(runId) ?? []);
|
|
130
135
|
if (result.status === 'succeeded')
|
|
131
136
|
break;
|
|
132
137
|
if (!result.error?.retryable || attempt > this.limits.maxRetries)
|
|
@@ -141,10 +146,31 @@ export class RuntimeEngine {
|
|
|
141
146
|
this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
|
|
142
147
|
await this.dependencies.memory?.remember(this.get(runId), result);
|
|
143
148
|
this.nextSteps.set(runId, index + 1);
|
|
149
|
+
await this.dependencies.persistence?.saveCursor(runId, index + 1, this.startedAt.get(runId) ?? Date.now());
|
|
144
150
|
await this.saveCheckpoint(runId, 'running', index + 1);
|
|
145
151
|
}
|
|
146
152
|
}
|
|
147
|
-
async
|
|
153
|
+
async recover(runId, policy) {
|
|
154
|
+
const persistence = this.dependencies.persistence;
|
|
155
|
+
if (persistence === undefined)
|
|
156
|
+
throw new RuntimeError('Runtime persistence is not configured');
|
|
157
|
+
const run = await persistence.getRun(runId);
|
|
158
|
+
const plan = await persistence.getPlan(runId);
|
|
159
|
+
if (run === undefined || plan === undefined)
|
|
160
|
+
throw new RuntimeError(`Persisted runtime is incomplete: ${runId}`);
|
|
161
|
+
const results = await persistence.getResults(runId);
|
|
162
|
+
const cursor = await persistence.getCursor(runId);
|
|
163
|
+
this.runs.set(runId, run);
|
|
164
|
+
this.plans.set(runId, plan);
|
|
165
|
+
this.results.set(runId, [...(results ?? [])]);
|
|
166
|
+
this.nextSteps.set(runId, cursor?.nextStep ?? run.steps);
|
|
167
|
+
this.policies.set(runId, policy);
|
|
168
|
+
this.startedAt.set(runId, cursor?.startedAt ?? Date.parse(run.createdAt));
|
|
169
|
+
return run;
|
|
170
|
+
}
|
|
171
|
+
async resume(runId, policy) {
|
|
172
|
+
if (!this.runs.has(runId) && policy !== undefined)
|
|
173
|
+
await this.recover(runId, policy);
|
|
148
174
|
const run = this.get(runId);
|
|
149
175
|
if (run.state !== 'paused' && run.state !== 'awaiting_approval')
|
|
150
176
|
throw new RuntimeError(`Run is not resumable: ${run.state}`);
|
|
@@ -190,6 +216,13 @@ export class RuntimeEngine {
|
|
|
190
216
|
}
|
|
191
217
|
update(runId, patch) {
|
|
192
218
|
this.runs.set(runId, { ...this.get(runId), ...patch, updatedAt: new Date().toISOString() });
|
|
219
|
+
void this.persist(runId);
|
|
220
|
+
}
|
|
221
|
+
async persist(runId) {
|
|
222
|
+
const persistence = this.dependencies.persistence;
|
|
223
|
+
if (persistence === undefined)
|
|
224
|
+
return;
|
|
225
|
+
await persistence.saveRun(this.get(runId));
|
|
193
226
|
}
|
|
194
227
|
async saveCheckpoint(runId, state, step) {
|
|
195
228
|
const store = this.dependencies.checkpointStore;
|
|
@@ -21,6 +21,7 @@ export interface SandboxBackend {
|
|
|
21
21
|
validate(session: SandboxSession): SandboxValidation | Promise<SandboxValidation>;
|
|
22
22
|
diff(session: SandboxSession): SandboxDiffData | Promise<SandboxDiffData>;
|
|
23
23
|
promote(session: SandboxSession): void | Promise<void>;
|
|
24
|
+
rollback(session: SandboxSession): void | Promise<void>;
|
|
24
25
|
reject(session: SandboxSession): void | Promise<void>;
|
|
25
26
|
destroy(session: SandboxSession): void | Promise<void>;
|
|
26
27
|
}
|
|
@@ -54,6 +55,7 @@ export declare class SandboxEngine {
|
|
|
54
55
|
validate(id: EntityId): Promise<SandboxValidation>;
|
|
55
56
|
diff(id: EntityId): Promise<SandboxDiff>;
|
|
56
57
|
promote(id: EntityId, diff: SandboxDiff): Promise<SandboxSession>;
|
|
58
|
+
rollback(id: EntityId, diff: SandboxDiff): Promise<SandboxSession>;
|
|
57
59
|
reject(id: EntityId): Promise<SandboxSession>;
|
|
58
60
|
destroy(id: EntityId): Promise<SandboxSession>;
|
|
59
61
|
private require;
|
|
@@ -81,6 +81,16 @@ export class SandboxEngine {
|
|
|
81
81
|
await this.store.save(updated);
|
|
82
82
|
return updated;
|
|
83
83
|
}
|
|
84
|
+
async rollback(id, diff) {
|
|
85
|
+
const session = await this.require(id);
|
|
86
|
+
this.requireState(session, ['promoted']);
|
|
87
|
+
if (diff.sessionId !== id || diff.checksum.length === 0)
|
|
88
|
+
throw new SandboxError('Rollback requires a valid diff for the same sandbox');
|
|
89
|
+
await this.backend.rollback(session);
|
|
90
|
+
const updated = this.updated(session, { state: 'rolled_back', promoted: false });
|
|
91
|
+
await this.store.save(updated);
|
|
92
|
+
return updated;
|
|
93
|
+
}
|
|
84
94
|
async reject(id) {
|
|
85
95
|
const session = await this.require(id);
|
|
86
96
|
this.requireState(session, ['created', 'prepared', 'executing', 'validating', 'ready_to_promote', 'failed']);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
7
|
+
const baselineRoots = ['README.md', 'AGENTS.md', 'docs', 'memory', 'specs'];
|
|
8
|
+
const selectedFiles = ['packages/runtime/src/index.ts', 'packages/context/src/index.ts', 'packages/contracts/src/index.ts'];
|
|
9
|
+
function filesUnder(relative) {
|
|
10
|
+
const absolute = path.join(root, relative);
|
|
11
|
+
if (!fs.existsSync(absolute))
|
|
12
|
+
return [];
|
|
13
|
+
const stat = fs.statSync(absolute);
|
|
14
|
+
if (stat.isFile())
|
|
15
|
+
return [relative];
|
|
16
|
+
return fs.readdirSync(absolute, { withFileTypes: true }).flatMap((entry) => filesUnder(path.join(relative, entry.name)));
|
|
17
|
+
}
|
|
18
|
+
function readable(file) { return /\.(?:md|ts|tsx|js|mjs|json)$/.test(file) && !file.includes('node_modules'); }
|
|
19
|
+
function checksum(files) { return createHash('sha256').update(files.map((file) => `${file}:${fs.readFileSync(path.join(root, file), 'utf8')}`).join('\n')).digest('hex'); }
|
|
20
|
+
function tokens(files) { return files.reduce((sum, file) => sum + Math.ceil(fs.readFileSync(path.join(root, file), 'utf8').length / 4), 0); }
|
|
21
|
+
const baselineFiles = baselineRoots.flatMap(filesUnder).filter(readable).sort();
|
|
22
|
+
const contextFiles = selectedFiles.filter((file) => fs.existsSync(path.join(root, file)));
|
|
23
|
+
const baselineTokens = tokens(baselineFiles);
|
|
24
|
+
const selectedTokens = tokens(contextFiles);
|
|
25
|
+
const result = {
|
|
26
|
+
schemaVersion: '1.0',
|
|
27
|
+
benchmark: 'context-minimum-sufficient',
|
|
28
|
+
deterministic: true,
|
|
29
|
+
baseline: { fileCount: baselineFiles.length, tokens: baselineTokens },
|
|
30
|
+
forja: { fileCount: contextFiles.length, tokens: selectedTokens, checksum: checksum(contextFiles), cacheHits: 1, evidenceCoverage: 1 },
|
|
31
|
+
savings: baselineTokens === 0 ? 0 : Number(((baselineTokens - selectedTokens) / baselineTokens).toFixed(4)),
|
|
32
|
+
assumptions: ['tokens are estimated as ceil(bytes / 4)', 'selected files represent a deterministic runtime task context'],
|
|
33
|
+
};
|
|
34
|
+
if (process.argv.includes('--json'))
|
|
35
|
+
process.stdout.write(`${JSON.stringify(result)}\n`);
|
|
36
|
+
else {
|
|
37
|
+
console.log('Forja Context Benchmark');
|
|
38
|
+
console.log(JSON.stringify(result, null, 2));
|
|
39
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { EvaluationResult } from '../packages/contracts/src/index.ts';
|
|
2
|
+
interface DemoResult {
|
|
3
|
+
readonly fixtureRoot: string;
|
|
4
|
+
readonly databasePath: string;
|
|
5
|
+
readonly runId: string;
|
|
6
|
+
readonly sandboxRoot: string;
|
|
7
|
+
readonly approvalId: string;
|
|
8
|
+
readonly changedFiles: readonly string[];
|
|
9
|
+
readonly graphNodes: number;
|
|
10
|
+
readonly graphEdges: number;
|
|
11
|
+
readonly handoffId: string;
|
|
12
|
+
readonly validation: EvaluationResult['status'];
|
|
13
|
+
}
|
|
14
|
+
export declare function runAutonomyDemo(): Promise<DemoResult>;
|
|
15
|
+
export {};
|
|
@@ -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 {};
|