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.
- package/README.md +22 -0
- package/README.pt-BR.md +22 -0
- package/dist/apps/server/src/main.d.ts +3 -2
- package/dist/apps/server/src/main.js +8 -6
- package/dist/bin/forja.js +8 -3
- package/dist/lib/core/registry.d.ts +10 -0
- package/dist/lib/core/registry.js +10 -0
- package/dist/lib/core/release.d.ts +10 -0
- package/dist/packages/adapter-git/src/index.d.ts +2 -0
- package/dist/packages/adapter-git/src/index.js +22 -1
- package/dist/packages/contracts/src/index.d.ts +1 -1
- 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/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/IMPLEMENTATION-AUDIT.md +36 -128
- 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/memory/50-orchestration/handoffs/2026-08-01_sprint-12-real-autonomy.md +16 -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/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
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*
|
|
@@ -2,8 +2,9 @@ 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
6
|
import { ApprovalLedger } from '../../../packages/policy/src/index.ts';
|
|
7
|
+
import { type OrchestrationStore } from '../../../packages/orchestration/src/index.ts';
|
|
7
8
|
import { InMemoryEventStream, type LocalAuthenticator } from '../../../packages/adapter-nest/src/index.ts';
|
|
8
9
|
import { GraphLoop } from '../../../packages/graph/src/index.ts';
|
|
9
10
|
import { ContextEngine } from '../../../packages/context/src/index.ts';
|
|
@@ -13,5 +14,5 @@ export declare function createDefaultCapabilityRegistry(root?: string, cwd?: str
|
|
|
13
14
|
export declare function createDefaultMcp(registry?: CapabilityRegistry, policy?: PolicyEngine, graph?: GraphLoop, audit?: import('../../../packages/mcp/src/index.ts').McpAuditSink, context?: ContextEngine): McpServer;
|
|
14
15
|
export declare function createDefaultPolicy(): PolicyEngine;
|
|
15
16
|
export declare function createLocalAuthenticator(token?: string | undefined): LocalAuthenticator | undefined;
|
|
16
|
-
export declare function createDefaultControlPlane(eventStream: InMemoryEventStream, registry?: CapabilityRegistry, policy?: PolicyEngine, persistence?: RuntimePersistence, approvals?: ApprovalLedger, events?: EventBus, graph?: GraphLoop, context?: ContextEngine): 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;
|
|
17
18
|
export declare function bootstrap(port?: number): Promise<import("@nestjs/common").INestApplication<any>>;
|
|
@@ -8,7 +8,7 @@ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
|
|
8
8
|
import { CapabilityRegistry } from "../../../packages/core/src/index.js";
|
|
9
9
|
import { PolicyEngine } from "../../../packages/policy/src/index.js";
|
|
10
10
|
import { McpServer } from "../../../packages/mcp/src/index.js";
|
|
11
|
-
import { ControlPlane } from "../../../packages/observability/src/index.js";
|
|
11
|
+
import { ControlPlane, InMemoryObservationStore, ObservabilityRecorder } from "../../../packages/observability/src/index.js";
|
|
12
12
|
import { ApprovalLedger } from "../../../packages/policy/src/index.js";
|
|
13
13
|
import { HandoffEngine, InMemoryOrchestrationStore, SprintEngine, TaskEngine } from "../../../packages/orchestration/src/index.js";
|
|
14
14
|
import { validateTokenBudget } from "../../../packages/contracts/src/index.js";
|
|
@@ -18,7 +18,7 @@ import { RuntimeEngine } from "../../../packages/runtime/src/index.js";
|
|
|
18
18
|
import { GraphExecutionMemory, GraphLoop } from "../../../packages/graph/src/index.js";
|
|
19
19
|
import { ContextEngine, GraphContextSource } from "../../../packages/context/src/index.js";
|
|
20
20
|
import { SqliteContextCache, SqliteGraphStore, SqliteMigrationRunner, SqliteRuntimePersistence } from "../../../packages/adapter-sqlite/src/index.js";
|
|
21
|
-
import { SqliteApprovalStore, SqliteMcpAuditSink } from "../../../packages/adapter-sqlite/src/index.js";
|
|
21
|
+
import { SqliteApprovalStore, SqliteMcpAuditSink, SqliteObservationStore, SqliteOrchestrationStore } from "../../../packages/adapter-sqlite/src/index.js";
|
|
22
22
|
import { EventBus } from "../../../packages/events/src/index.js";
|
|
23
23
|
import { SqliteEventStore } from "../../../packages/adapter-sqlite/src/index.js";
|
|
24
24
|
import { getWorkspaceDbDir, getWorkspaceDbPath } from "../../../lib/workspace.js";
|
|
@@ -114,13 +114,13 @@ function runtimeInput(input) {
|
|
|
114
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 };
|
|
115
115
|
}
|
|
116
116
|
function isRecord(value) { return typeof value === 'object' && value !== null; }
|
|
117
|
-
export function createDefaultControlPlane(eventStream, registry = createDefaultCapabilityRegistry(), policy = createDefaultPolicy(), persistence, approvals = new ApprovalLedger(), events, graph, context) {
|
|
118
|
-
const store =
|
|
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;
|
|
119
119
|
const sprintEngine = new SprintEngine(store);
|
|
120
120
|
const taskEngine = new TaskEngine(store, sprintEngine);
|
|
121
121
|
const handoffEngine = new HandoffEngine(store);
|
|
122
122
|
const runtime = new DefaultRuntimeApplication(registry, policy, persistence, graph, context);
|
|
123
|
-
return new ControlPlane(
|
|
123
|
+
return new ControlPlane(new ObservabilityRecorder(observationStore), {
|
|
124
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) },
|
|
125
125
|
sprint: { create: (input) => sprintEngine.create(input), start: (id) => sprintEngine.start(id), pause: (id) => sprintEngine.pause(id) },
|
|
126
126
|
task: { create: (input) => taskEngine.create(input), start: (id) => taskEngine.start(id), block: (id) => taskEngine.block(id) },
|
|
@@ -141,10 +141,12 @@ export async function bootstrap(port = Number(process.env.FORJA_PORT ?? 3000)) {
|
|
|
141
141
|
const mcpAudit = new SqliteMcpAuditSink(runtimeDatabase);
|
|
142
142
|
const events = new EventBus(new SqliteEventStore(runtimeDatabase));
|
|
143
143
|
const graph = new GraphLoop(new SqliteGraphStore(runtimeDatabase));
|
|
144
|
+
const orchestrationStore = new SqliteOrchestrationStore(runtimeDatabase);
|
|
145
|
+
const observationStore = new SqliteObservationStore(runtimeDatabase);
|
|
144
146
|
registerGraphSyncCapability(registry, graph, new GitGraphDocumentSource(process.env.FORJA_GRAPH_ROOT ?? process.cwd(), new SpawnCommandRunner()));
|
|
145
147
|
const context = new ContextEngine({ graph: new GraphContextSource({ searchContext: (objective) => graph.contextRecords(objective) }), cache: new SqliteContextCache(runtimeDatabase) });
|
|
146
148
|
const mcp = createDefaultMcp(registry, policy, graph, mcpAudit, context);
|
|
147
|
-
const app = await NestFactory.create(AppModule.register({ mcp, eventStream, authenticator: createLocalAuthenticator(), controlPlane: createDefaultControlPlane(eventStream, registry, policy, runtimePersistence, approvals, events, graph, 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) }));
|
|
148
150
|
const config = new DocumentBuilder().setTitle('ForjaJS 2.0 API').setDescription('Local-first agent control plane').setVersion('2.0.0').build();
|
|
149
151
|
SwaggerModule.setup('docs', app, SwaggerModule.createDocument(app, config));
|
|
150
152
|
await app.listen(port, '127.0.0.1');
|
package/dist/bin/forja.js
CHANGED
|
@@ -235,12 +235,17 @@ async function runMcpStdio() {
|
|
|
235
235
|
if (line.trim().length === 0)
|
|
236
236
|
return;
|
|
237
237
|
let request;
|
|
238
|
+
let id = null;
|
|
238
239
|
try {
|
|
239
240
|
request = JSON.parse(line);
|
|
240
|
-
|
|
241
|
+
id = request.id ?? null;
|
|
242
|
+
if (request.method === 'notifications/initialized')
|
|
243
|
+
return;
|
|
244
|
+
if (request.method === 'notifications/cancelled')
|
|
245
|
+
return;
|
|
241
246
|
let result;
|
|
242
247
|
if (request.method === 'initialize')
|
|
243
|
-
result = { protocolVersion: '2025-06-18', capabilities: { tools: {}, resources: {} }, serverInfo: { name: 'forja', version: '2.0.
|
|
248
|
+
result = { protocolVersion: '2025-06-18', capabilities: { tools: {}, resources: {} }, serverInfo: { name: 'forja', version: '2.0.3' } };
|
|
244
249
|
else if (request.method === 'tools/list')
|
|
245
250
|
result = { tools: mcp.listTools() };
|
|
246
251
|
else if (request.method === 'resources/list')
|
|
@@ -254,7 +259,7 @@ async function runMcpStdio() {
|
|
|
254
259
|
process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, result })}\n`);
|
|
255
260
|
}
|
|
256
261
|
catch (error) {
|
|
257
|
-
process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id
|
|
262
|
+
process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32000, message: error instanceof Error ? error.message : 'MCP request failed' } })}\n`);
|
|
258
263
|
}
|
|
259
264
|
};
|
|
260
265
|
let buffer = '';
|
|
@@ -298,6 +298,11 @@ export declare const COMMANDS: {
|
|
|
298
298
|
desc: string;
|
|
299
299
|
node: string;
|
|
300
300
|
};
|
|
301
|
+
'benchmark:context': {
|
|
302
|
+
domain: string;
|
|
303
|
+
desc: string;
|
|
304
|
+
node: string;
|
|
305
|
+
};
|
|
301
306
|
'project:check': {
|
|
302
307
|
domain: string;
|
|
303
308
|
desc: string;
|
|
@@ -308,6 +313,11 @@ export declare const COMMANDS: {
|
|
|
308
313
|
desc: string;
|
|
309
314
|
node: string;
|
|
310
315
|
};
|
|
316
|
+
'demo:autonomy': {
|
|
317
|
+
domain: string;
|
|
318
|
+
desc: string;
|
|
319
|
+
node: string;
|
|
320
|
+
};
|
|
311
321
|
'release:check': {
|
|
312
322
|
domain: string;
|
|
313
323
|
desc: string;
|
|
@@ -317,6 +317,11 @@ export const COMMANDS = {
|
|
|
317
317
|
desc: 'Economia de token: eixos arquitetura + memória; --project mede seus domínios reais (ADR-0009/0027)',
|
|
318
318
|
node: 'scripts/token-economy.ts',
|
|
319
319
|
},
|
|
320
|
+
'benchmark:context': {
|
|
321
|
+
domain: 'contexto',
|
|
322
|
+
desc: 'Benchmark JSON determinístico de baseline, contexto mínimo, checksum e cache',
|
|
323
|
+
node: 'scripts/context-benchmark.ts',
|
|
324
|
+
},
|
|
320
325
|
// --- Governança & qualidade ---------------------------------------------------
|
|
321
326
|
'project:check': {
|
|
322
327
|
domain: 'governanca',
|
|
@@ -328,6 +333,11 @@ export const COMMANDS = {
|
|
|
328
333
|
desc: 'Raio-x do núcleo (gate, exit 1) + ferramentas de processo (ADR-0023, ADR-0018)',
|
|
329
334
|
node: 'scripts/tools-doctor.ts',
|
|
330
335
|
},
|
|
336
|
+
'demo:autonomy': {
|
|
337
|
+
domain: 'governanca',
|
|
338
|
+
desc: 'Executa a prova offline de autonomia supervisionada com Git worktree real',
|
|
339
|
+
node: 'scripts/demo-autonomy.ts',
|
|
340
|
+
},
|
|
331
341
|
'release:check': {
|
|
332
342
|
domain: 'governanca',
|
|
333
343
|
desc: 'Gate do tarball: instala limpo e prova que o pacote funciona (ADR-0024). --publish para o modo estrito',
|
|
@@ -305,6 +305,11 @@ export declare function defaultEnv(overrides?: {}): {
|
|
|
305
305
|
desc: string;
|
|
306
306
|
node: string;
|
|
307
307
|
};
|
|
308
|
+
'benchmark:context': {
|
|
309
|
+
domain: string;
|
|
310
|
+
desc: string;
|
|
311
|
+
node: string;
|
|
312
|
+
};
|
|
308
313
|
'project:check': {
|
|
309
314
|
domain: string;
|
|
310
315
|
desc: string;
|
|
@@ -315,6 +320,11 @@ export declare function defaultEnv(overrides?: {}): {
|
|
|
315
320
|
desc: string;
|
|
316
321
|
node: string;
|
|
317
322
|
};
|
|
323
|
+
'demo:autonomy': {
|
|
324
|
+
domain: string;
|
|
325
|
+
desc: string;
|
|
326
|
+
node: string;
|
|
327
|
+
};
|
|
318
328
|
'release:check': {
|
|
319
329
|
domain: string;
|
|
320
330
|
desc: string;
|
|
@@ -17,6 +17,7 @@ export declare class GitGraphDocumentSource implements GraphDocumentSource {
|
|
|
17
17
|
}
|
|
18
18
|
export interface PatchApplier {
|
|
19
19
|
apply(root: string, patch: string): void | Promise<void>;
|
|
20
|
+
revert(root: string, patch: string): void | Promise<void>;
|
|
20
21
|
}
|
|
21
22
|
export interface GitWorktreeOptions {
|
|
22
23
|
readonly repositoryRoot: string;
|
|
@@ -33,6 +34,7 @@ export declare class GitWorktreeBackend implements SandboxBackend {
|
|
|
33
34
|
validate(session: SandboxSession): Promise<SandboxValidation>;
|
|
34
35
|
diff(session: SandboxSession): Promise<SandboxDiffData>;
|
|
35
36
|
promote(session: SandboxSession): Promise<void>;
|
|
37
|
+
rollback(session: SandboxSession): Promise<void>;
|
|
36
38
|
reject(session: SandboxSession): Promise<void>;
|
|
37
39
|
destroy(session: SandboxSession): Promise<void>;
|
|
38
40
|
private runGit;
|
|
@@ -5,7 +5,7 @@ import { graphDocumentId } from "../../graph/src/index.js";
|
|
|
5
5
|
export class SpawnCommandRunner {
|
|
6
6
|
run(command) {
|
|
7
7
|
const started = Date.now();
|
|
8
|
-
const result = spawnSync(command.executable, [...command.args], { cwd: command.cwd, env: command.env
|
|
8
|
+
const result = spawnSync(command.executable, [...command.args], { cwd: command.cwd, env: sandboxEnvironment(command.env), encoding: 'utf8' });
|
|
9
9
|
return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: [result.stderr ?? '', result.error?.message ?? ''].filter(Boolean).join('\n'), durationMs: Date.now() - started };
|
|
10
10
|
}
|
|
11
11
|
}
|
|
@@ -27,6 +27,8 @@ export class GitGraphDocumentSource {
|
|
|
27
27
|
if (!isIndexable(relative))
|
|
28
28
|
continue;
|
|
29
29
|
const absolute = path.join(this.root, relative);
|
|
30
|
+
if (!isWithinRoot(this.root, absolute))
|
|
31
|
+
continue;
|
|
30
32
|
try {
|
|
31
33
|
const content = fs.readFileSync(absolute, 'utf8');
|
|
32
34
|
if (content.includes('\0') || Buffer.byteLength(content, 'utf8') > 1_000_000)
|
|
@@ -43,6 +45,19 @@ function isIndexable(relative) {
|
|
|
43
45
|
return false;
|
|
44
46
|
return /\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|yaml|yml)$/.test(relative);
|
|
45
47
|
}
|
|
48
|
+
function isWithinRoot(root, candidate) {
|
|
49
|
+
const relative = path.relative(root, candidate);
|
|
50
|
+
return relative.length === 0 || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
|
|
51
|
+
}
|
|
52
|
+
function sandboxEnvironment(overrides) {
|
|
53
|
+
const inherited = {};
|
|
54
|
+
for (const key of ['PATH', 'NODE_PATH', 'SystemRoot', 'TMPDIR', 'TMP', 'TEMP']) {
|
|
55
|
+
const value = process.env[key];
|
|
56
|
+
if (value !== undefined)
|
|
57
|
+
inherited[key] = value;
|
|
58
|
+
}
|
|
59
|
+
return { ...inherited, ...(overrides ?? {}) };
|
|
60
|
+
}
|
|
46
61
|
export class GitWorktreeBackend {
|
|
47
62
|
runner;
|
|
48
63
|
options;
|
|
@@ -86,6 +101,12 @@ export class GitWorktreeBackend {
|
|
|
86
101
|
throw new Error(`Git promotion diff failed: ${patch.stderr}`);
|
|
87
102
|
await this.options.patchApplier.apply(this.options.repositoryRoot, patch.stdout);
|
|
88
103
|
}
|
|
104
|
+
async rollback(session) {
|
|
105
|
+
const patch = await this.runGit(['-C', session.root, 'diff', '--binary']);
|
|
106
|
+
if (patch.exitCode !== 0)
|
|
107
|
+
throw new Error(`Git rollback diff failed: ${patch.stderr}`);
|
|
108
|
+
await this.options.patchApplier.revert(this.options.repositoryRoot, patch.stdout);
|
|
109
|
+
}
|
|
89
110
|
async reject(session) {
|
|
90
111
|
await this.runGit(['-C', this.options.repositoryRoot, 'worktree', 'remove', '--force', session.root]);
|
|
91
112
|
}
|
|
@@ -13,7 +13,7 @@ export type KnowledgeStatus = 'verified' | 'inferred' | 'hypothesis' | 'contradi
|
|
|
13
13
|
export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
|
|
14
14
|
export type PolicyEffect = 'ALLOW' | 'DENY' | 'REQUIRE_APPROVAL' | 'ALLOW_WITH_LIMITS';
|
|
15
15
|
export type ExecutionState = 'created' | 'planning' | 'awaiting_approval' | 'running' | 'validating' | 'paused' | 'blocked' | 'failed' | 'completed' | 'cancelled' | 'rolled_back';
|
|
16
|
-
export type SandboxState = 'created' | 'prepared' | 'executing' | 'validating' | 'ready_to_promote' | 'promoted' | 'rejected' | 'destroyed' | 'failed';
|
|
16
|
+
export type SandboxState = 'created' | 'prepared' | 'executing' | 'validating' | 'ready_to_promote' | 'promoted' | 'rolled_back' | 'rejected' | 'destroyed' | 'failed';
|
|
17
17
|
export interface AuditFields {
|
|
18
18
|
readonly schemaVersion: typeof CONTRACT_VERSION;
|
|
19
19
|
readonly createdAt: ISO8601;
|
|
@@ -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
|
+
};
|
|
@@ -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 {};
|