forjajs 1.7.3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +223 -217
- package/README.pt-BR.md +323 -0
- package/dist/apps/dashboard/app/api/forja/[...path]/route.d.ts +10 -0
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +36 -0
- package/dist/apps/dashboard/app/api/forja/approval.d.ts +1 -0
- package/dist/apps/dashboard/app/api/forja/approval.js +8 -0
- package/dist/apps/dashboard/app/dashboard-client.d.ts +1 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +62 -0
- package/dist/apps/dashboard/app/layout.d.ts +9 -0
- package/dist/apps/dashboard/app/layout.jsx +7 -0
- package/dist/apps/dashboard/app/page.d.ts +1 -0
- package/dist/apps/dashboard/app/page.jsx +5 -0
- package/dist/apps/dashboard/app/providers.d.ts +4 -0
- package/dist/apps/dashboard/app/providers.jsx +7 -0
- package/dist/apps/dashboard/next.config.d.mts +6 -0
- package/dist/apps/dashboard/next.config.mjs +8 -0
- package/dist/apps/dashboard/src/index.d.ts +14 -0
- package/dist/apps/dashboard/src/index.js +16 -0
- package/dist/apps/server/src/app.module.d.ts +5 -0
- package/dist/apps/server/src/app.module.js +16 -0
- package/dist/apps/server/src/forja-nest.module.d.ts +59 -0
- package/dist/apps/server/src/forja-nest.module.js +316 -0
- package/dist/apps/server/src/index.d.ts +15 -0
- package/dist/apps/server/src/index.js +7 -0
- package/dist/apps/server/src/main.d.ts +12 -0
- package/dist/apps/server/src/main.js +105 -0
- package/dist/apps/worker/src/main.d.ts +12 -0
- package/dist/apps/worker/src/main.js +18 -0
- package/dist/lib/core/health.js +1 -1
- package/dist/packages/adapter-git/src/index.d.ts +27 -0
- package/dist/packages/adapter-git/src/index.js +53 -0
- package/dist/packages/adapter-nest/src/index.d.ts +71 -0
- package/dist/packages/adapter-nest/src/index.js +142 -0
- package/dist/packages/adapter-sqlite/src/index.d.ts +99 -0
- package/dist/packages/adapter-sqlite/src/index.js +108 -0
- package/dist/packages/context/src/index.d.ts +52 -0
- package/dist/packages/context/src/index.js +108 -0
- package/dist/packages/contracts/src/index.d.ts +368 -0
- package/dist/packages/contracts/src/index.js +27 -0
- package/dist/packages/core/src/index.d.ts +68 -0
- package/dist/packages/core/src/index.js +141 -0
- package/dist/packages/evals/src/index.d.ts +22 -0
- package/dist/packages/evals/src/index.js +65 -0
- package/dist/packages/events/src/index.d.ts +47 -0
- package/dist/packages/events/src/index.js +96 -0
- package/dist/packages/graph/src/index.d.ts +80 -0
- package/dist/packages/graph/src/index.js +163 -0
- package/dist/packages/mcp/src/index.d.ts +119 -0
- package/dist/packages/mcp/src/index.js +153 -0
- package/dist/packages/observability/src/index.d.ts +132 -0
- package/dist/packages/observability/src/index.js +86 -0
- package/dist/packages/orchestration/src/index.d.ts +122 -0
- package/dist/packages/orchestration/src/index.js +178 -0
- package/dist/packages/planner/src/index.d.ts +22 -0
- package/dist/packages/planner/src/index.js +70 -0
- package/dist/packages/plugin-sdk/src/index.d.ts +56 -0
- package/dist/packages/plugin-sdk/src/index.js +55 -0
- package/dist/packages/policy/src/index.d.ts +80 -0
- package/dist/packages/policy/src/index.js +136 -0
- package/dist/packages/runtime/src/index.d.ts +91 -0
- package/dist/packages/runtime/src/index.js +217 -0
- package/dist/packages/sandbox/src/index.d.ts +64 -0
- package/dist/packages/sandbox/src/index.js +108 -0
- package/dist/packages/scheduler/src/index.d.ts +56 -0
- package/dist/packages/scheduler/src/index.js +123 -0
- package/dist/packages/sdk/src/index.d.ts +122 -0
- package/dist/packages/sdk/src/index.js +40 -0
- package/dist/packages/validator/src/index.d.ts +36 -0
- package/dist/packages/validator/src/index.js +60 -0
- package/docs/architecture/FORJA-2.0-ARCHITECTURE.md +109 -0
- package/docs/architecture/FORJA-2.0-IMPACT-FOUNDATION.md +273 -0
- package/docs/security/FORJA-2.0-RELEASE-AUDIT-2026-08-01.md +95 -0
- package/docs/vision/FORJA-2.0-VISION.md +72 -0
- package/memory/50-orchestration/handoffs/2026-07-31_architect_foundation-contracts.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_backend-nest.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_context-engine.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_control-plane.md +28 -0
- package/memory/50-orchestration/handoffs/2026-07-31_core-capability-registry.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_evals-plugin-sdk.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_events-scheduler.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_graphloop.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_mcp.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_nest-bootstrap.md +28 -0
- package/memory/50-orchestration/handoffs/2026-07-31_next-dashboard.md +22 -0
- package/memory/50-orchestration/handoffs/2026-07-31_observability.md +27 -0
- package/memory/50-orchestration/handoffs/2026-07-31_orchestration.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_planner-validator.md +16 -0
- package/memory/50-orchestration/handoffs/2026-07-31_policy-engine.md +14 -0
- package/memory/50-orchestration/handoffs/2026-07-31_runtime-control-plane.md +23 -0
- package/memory/50-orchestration/handoffs/2026-07-31_runtime-controlado.md +15 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sandbox.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sdk.md +27 -0
- package/memory/50-orchestration/handoffs/2026-07-31_sqlite-adapter.md +21 -0
- package/memory/50-orchestration/handoffs/2026-07-31_worker-dashboard-boundary.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_approval-server-identity.md +23 -0
- package/memory/50-orchestration/handoffs/2026-08-01_dashboard-auth-query.md +24 -0
- package/memory/50-orchestration/handoffs/2026-08-01_graphloop-approvals.md +23 -0
- package/memory/90-decisions/0034-forja-2-core-e-contratos.md +29 -0
- package/memory/90-decisions/0035-forja-2-local-first-e-autonomia.md +23 -0
- package/memory/90-decisions/0036-forja-2-capability-registry.md +30 -0
- package/memory/90-decisions/0037-forja-2-policy-engine-obrigatorio.md +28 -0
- package/memory/90-decisions/0038-forja-2-runtime-controlado.md +28 -0
- package/memory/90-decisions/0039-forja-2-event-bus-scheduler-local-first.md +31 -0
- package/memory/90-decisions/0040-forja-2-context-engine-budget-cache.md +32 -0
- package/memory/90-decisions/0041-forja-2-graphloop-separado-codegraph.md +32 -0
- package/memory/90-decisions/0042-forja-2-planner-validator-independentes.md +29 -0
- package/memory/90-decisions/0043-forja-2-orchestration-entities.md +16 -0
- package/memory/90-decisions/0044-forja-2-sandbox-worktree.md +19 -0
- package/memory/90-decisions/0045-forja-2-sqlite-adapter.md +19 -0
- package/memory/90-decisions/0046-forja-2-mcp-adapter.md +18 -0
- package/memory/90-decisions/0047-forja-2-backend-nest-adapter.md +19 -0
- package/memory/90-decisions/0048-forja-2-sdk-transport.md +18 -0
- package/memory/90-decisions/0049-forja-2-observability-control-plane.md +18 -0
- package/memory/90-decisions/0050-forja-2-control-plane-application-ports.md +18 -0
- package/memory/90-decisions/0051-forja-2-runtime-control-plane-composition.md +18 -0
- package/memory/90-decisions/0052-forja-2-deterministic-evaluation.md +15 -0
- package/memory/90-decisions/0053-forja-2-plugin-sdk-permissionado.md +16 -0
- package/memory/90-decisions/0054-forja-2-worker-dashboard-boundary.md +15 -0
- package/memory/90-decisions/0055-forja-2-next-dashboard-distribution.md +16 -0
- package/memory/90-decisions/0056-forja-2-dashboard-proxy-auth-query.md +16 -0
- package/memory/90-decisions/0057-forja-2-graphloop-approvals-dashboard.md +15 -0
- package/memory/90-decisions/0058-forja-2-approval-server-identity.md +15 -0
- package/package.json +28 -3
- package/README.en.md +0 -329
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
|
+
export function createBearerAuthenticator(token) {
|
|
3
|
+
if (token.length === 0)
|
|
4
|
+
throw new NestAdapterError('Bearer token is required');
|
|
5
|
+
return { authenticate: (headers) => { const value = headers.authorization; if (value === undefined || !value.startsWith('Bearer '))
|
|
6
|
+
return false; return constantTimeEqual(value.slice(7), token); } };
|
|
7
|
+
}
|
|
8
|
+
function constantTimeEqual(left, right) {
|
|
9
|
+
const leftBuffer = Buffer.from(left);
|
|
10
|
+
const rightBuffer = Buffer.from(right);
|
|
11
|
+
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
|
12
|
+
}
|
|
13
|
+
export const FORJA_NEST_MODULES = [
|
|
14
|
+
{ name: 'WorkspaceModule', routes: ['/health', '/api/workspace/status'] },
|
|
15
|
+
{ name: 'CapabilityModule', routes: ['/api/capabilities', '/api/capabilities/:id/execute'] },
|
|
16
|
+
{ name: 'RuntimeModule', routes: ['/api/executions/:id'] },
|
|
17
|
+
{ name: 'GraphModule', routes: ['/api/graph/query', '/api/graph/impact'] },
|
|
18
|
+
{ name: 'ContextModule', routes: ['/api/context/build'] },
|
|
19
|
+
{ name: 'PolicyModule', routes: ['/api/policies'] },
|
|
20
|
+
{ name: 'SprintModule', routes: ['/api/sprints', '/api/sprints/:id/start', '/api/sprints/:id/pause'] },
|
|
21
|
+
{ name: 'TaskModule', routes: ['/api/tasks/next', '/api/tasks/:id/start', '/api/tasks/:id/block'] },
|
|
22
|
+
{ name: 'HandoffModule', routes: ['/api/handoffs'] },
|
|
23
|
+
{ name: 'ApprovalModule', routes: ['/api/approvals', '/api/approvals/:id', '/api/approvals/:id/decide'] },
|
|
24
|
+
{ name: 'EventModule', routes: ['/api/events'] },
|
|
25
|
+
{ name: 'AuditModule', routes: ['/api/audit', '/api/observability/observations'] },
|
|
26
|
+
{ name: 'ControlPlaneModule', routes: ['/api/control-plane/metrics'] },
|
|
27
|
+
{ name: 'McpModule', routes: ['/mcp/tools', '/mcp/resources'] },
|
|
28
|
+
];
|
|
29
|
+
export class NestAdapterError extends Error {
|
|
30
|
+
constructor(message) { super(message); this.name = 'NestAdapterError'; }
|
|
31
|
+
}
|
|
32
|
+
export class ForjaNestAdapter {
|
|
33
|
+
mcp;
|
|
34
|
+
stream;
|
|
35
|
+
authenticator;
|
|
36
|
+
controlPlane;
|
|
37
|
+
constructor(mcp, stream, authenticator, controlPlane) { this.mcp = mcp; this.stream = stream; this.authenticator = authenticator; this.controlPlane = controlPlane; }
|
|
38
|
+
async handle(request) {
|
|
39
|
+
const correlationId = request.correlationId ?? request.headers['x-correlation-id'] ?? `http:${request.method}:${request.path}`;
|
|
40
|
+
try {
|
|
41
|
+
if (this.authenticator !== undefined && !(await this.authenticator.authenticate(request.headers)))
|
|
42
|
+
return { status: 401, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId, 'www-authenticate': 'Bearer' }, body: { error: { code: 'UNAUTHENTICATED', message: 'Local authentication required' } }, correlationId };
|
|
43
|
+
const result = await this.dispatch(request);
|
|
44
|
+
return this.result(correlationId, result);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
return this.error(correlationId, error instanceof Error ? error.message : 'Unknown HTTP adapter error');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
subscribeSse(listener) {
|
|
51
|
+
if (this.stream === undefined)
|
|
52
|
+
throw new NestAdapterError('Event stream is not configured');
|
|
53
|
+
return this.stream.subscribe(listener);
|
|
54
|
+
}
|
|
55
|
+
modules() { return FORJA_NEST_MODULES; }
|
|
56
|
+
openApi() {
|
|
57
|
+
const paths = Object.fromEntries(FORJA_NEST_MODULES.flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }])));
|
|
58
|
+
return { openapi: '3.1.0', info: { title: 'ForjaJS 2.0 API', version: '2.0.0' }, paths };
|
|
59
|
+
}
|
|
60
|
+
async dispatch(request) {
|
|
61
|
+
if (request.method === 'GET' && request.path === '/health')
|
|
62
|
+
return { status: 'ok', service: 'forja-server', offline: true };
|
|
63
|
+
if (request.method === 'GET' && request.path === '/api/workspace/status')
|
|
64
|
+
return this.call('forja_workspace_status', {});
|
|
65
|
+
if (request.method === 'GET' && request.path === '/api/capabilities')
|
|
66
|
+
return this.call('forja_capabilities_list', {});
|
|
67
|
+
if (request.method === 'POST' && request.path.startsWith('/api/capabilities/') && request.path.endsWith('/execute'))
|
|
68
|
+
return this.call('forja_capability_execute', { ...(this.objectBody(request.body)), capabilityId: this.pathCapabilityId(request.path) });
|
|
69
|
+
if (request.method === 'POST' && request.path === '/api/context/build')
|
|
70
|
+
return this.call('forja_context_build', request.body ?? {});
|
|
71
|
+
if (request.method === 'GET' && request.path === '/api/graph/query')
|
|
72
|
+
return this.call('forja_graph_query', request.query);
|
|
73
|
+
if (request.method === 'GET' && request.path === '/api/graph/impact')
|
|
74
|
+
return this.call('forja_code_impact', request.query);
|
|
75
|
+
if (request.method === 'GET' && request.path === '/api/tasks/next')
|
|
76
|
+
return this.call('forja_task_next', request.query);
|
|
77
|
+
if (request.method === 'POST' && request.path === '/api/handoffs')
|
|
78
|
+
return this.call('forja_handoff_create', request.body ?? {});
|
|
79
|
+
if (request.method === 'POST' && request.path === '/api/executions')
|
|
80
|
+
return this.requireControlPlane().runtimeStart?.(request.body ?? {}) ?? this.missing('runtimeStart');
|
|
81
|
+
if (request.method === 'GET' && request.path.startsWith('/api/executions/'))
|
|
82
|
+
return this.requireControlPlane().runtimeGet?.(this.idFromPath(request.path, '/api/executions/')) ?? this.missing('runtimeGet');
|
|
83
|
+
if (request.method === 'POST' && request.path.endsWith('/execute') && request.path.startsWith('/api/executions/'))
|
|
84
|
+
return this.requireControlPlane().runtimeExecute?.(this.idFromPath(request.path, '/api/executions/')) ?? this.missing('runtimeExecute');
|
|
85
|
+
if (request.method === 'POST' && request.path.endsWith('/pause') && request.path.startsWith('/api/executions/'))
|
|
86
|
+
return this.requireControlPlane().runtimePause?.(this.idFromPath(request.path, '/api/executions/')) ?? this.missing('runtimePause');
|
|
87
|
+
if (request.method === 'POST' && request.path.endsWith('/resume') && request.path.startsWith('/api/executions/'))
|
|
88
|
+
return this.requireControlPlane().runtimeResume?.(this.idFromPath(request.path, '/api/executions/')) ?? this.missing('runtimeResume');
|
|
89
|
+
if (request.method === 'POST' && request.path.endsWith('/cancel') && request.path.startsWith('/api/executions/'))
|
|
90
|
+
return this.requireControlPlane().runtimeCancel?.(this.idFromPath(request.path, '/api/executions/')) ?? this.missing('runtimeCancel');
|
|
91
|
+
if (request.method === 'POST' && request.path === '/api/sprints')
|
|
92
|
+
return this.requireControlPlane().sprintCreate?.(request.body ?? {}) ?? this.missing('sprintCreate');
|
|
93
|
+
if (request.method === 'POST' && request.path.endsWith('/start') && request.path.startsWith('/api/sprints/'))
|
|
94
|
+
return this.requireControlPlane().sprintStart?.(this.idFromPath(request.path, '/api/sprints/')) ?? this.missing('sprintStart');
|
|
95
|
+
if (request.method === 'POST' && request.path.endsWith('/pause') && request.path.startsWith('/api/sprints/'))
|
|
96
|
+
return this.requireControlPlane().sprintPause?.(this.idFromPath(request.path, '/api/sprints/')) ?? this.missing('sprintPause');
|
|
97
|
+
if (request.method === 'POST' && request.path === '/api/tasks')
|
|
98
|
+
return this.requireControlPlane().taskCreate?.(request.body ?? {}) ?? this.missing('taskCreate');
|
|
99
|
+
if (request.method === 'POST' && request.path.endsWith('/start') && request.path.startsWith('/api/tasks/'))
|
|
100
|
+
return this.requireControlPlane().taskStart?.(this.idFromPath(request.path, '/api/tasks/')) ?? this.missing('taskStart');
|
|
101
|
+
if (request.method === 'POST' && request.path.endsWith('/block') && request.path.startsWith('/api/tasks/'))
|
|
102
|
+
return this.requireControlPlane().taskBlock?.(this.idFromPath(request.path, '/api/tasks/')) ?? this.missing('taskBlock');
|
|
103
|
+
if (request.method === 'GET' && request.path.startsWith('/api/approvals/'))
|
|
104
|
+
return this.requireControlPlane().approvalGet?.(this.idFromPath(request.path, '/api/approvals/')) ?? this.missing('approvalGet');
|
|
105
|
+
if (request.method === 'GET' && request.path === '/api/approvals')
|
|
106
|
+
return this.requireControlPlane().approvalList?.() ?? this.missing('approvalList');
|
|
107
|
+
if (request.method === 'POST' && request.path.endsWith('/decide') && request.path.startsWith('/api/approvals/'))
|
|
108
|
+
return this.requireControlPlane().approvalDecide?.(this.idFromPath(request.path, '/api/approvals/'), request.body ?? {}) ?? this.missing('approvalDecide');
|
|
109
|
+
if (request.method === 'GET' && request.path === '/api/control-plane/metrics')
|
|
110
|
+
return this.requireControlPlane().metrics();
|
|
111
|
+
if (request.method === 'GET' && request.path === '/api/observability/observations')
|
|
112
|
+
return this.requireControlPlane().observations();
|
|
113
|
+
if (request.method === 'GET' && request.path === '/mcp/tools')
|
|
114
|
+
return this.mcp.listTools();
|
|
115
|
+
if (request.method === 'GET' && request.path === '/mcp/resources')
|
|
116
|
+
return this.mcp.listResources();
|
|
117
|
+
if (request.method === 'GET' && request.path.startsWith('/mcp/resources/'))
|
|
118
|
+
return this.mcp.readResource(request.path.slice('/mcp/resources/'.length));
|
|
119
|
+
throw new NestAdapterError(`Route not found: ${request.method} ${request.path}`);
|
|
120
|
+
}
|
|
121
|
+
async call(tool, input) { const result = await this.mcp.callTool(tool, input); if (result.isError)
|
|
122
|
+
throw new NestAdapterError(this.errorMessage(result)); return result.structuredContent; }
|
|
123
|
+
result(correlationId, body) { return { status: 200, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId }, body, correlationId }; }
|
|
124
|
+
error(correlationId, message) { return { status: message.startsWith('Route not found') ? 404 : 400, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId }, body: { error: { code: message.startsWith('Route not found') ? 'NOT_FOUND' : 'BAD_REQUEST', message } }, correlationId }; }
|
|
125
|
+
objectBody(value) { if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
126
|
+
throw new NestAdapterError('Request body must be an object'); return value; }
|
|
127
|
+
pathCapabilityId(path) { const prefix = '/api/capabilities/'; const value = path.slice(prefix.length, -'/execute'.length); if (value.trim().length === 0 || value.includes('/'))
|
|
128
|
+
throw new NestAdapterError('Capability id is required'); return value; }
|
|
129
|
+
errorMessage(result) { const value = result.structuredContent; if (typeof value === 'object' && value !== null && 'message' in value && typeof value.message === 'string')
|
|
130
|
+
return value.message; return 'MCP operation failed'; }
|
|
131
|
+
requireControlPlane() { if (this.controlPlane === undefined)
|
|
132
|
+
throw new NestAdapterError('Control Plane is not configured'); return this.controlPlane; }
|
|
133
|
+
idFromPath(path, prefix) { const value = path.slice(prefix.length).split('/')[0]; if (value.trim().length === 0)
|
|
134
|
+
throw new NestAdapterError('Resource id is required'); return value; }
|
|
135
|
+
missing(name) { throw new NestAdapterError(`Control Plane service is not configured: ${name}`); }
|
|
136
|
+
}
|
|
137
|
+
export class InMemoryEventStream {
|
|
138
|
+
listeners = new Set();
|
|
139
|
+
subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
140
|
+
publish(event) { for (const listener of this.listeners)
|
|
141
|
+
listener(event); }
|
|
142
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { AuditRecord, Checkpoint, DomainEvent, EntityId, Handoff, Observation, RuntimeRun, SandboxSession, Sprint, Task, RunId } from '../../contracts/src/index.ts';
|
|
2
|
+
import type { EventStore } from '../../events/src/index.ts';
|
|
3
|
+
import type { CheckpointStore } from '../../runtime/src/index.ts';
|
|
4
|
+
import type { OrchestrationStore } from '../../orchestration/src/index.ts';
|
|
5
|
+
import type { SandboxStore } from '../../sandbox/src/index.ts';
|
|
6
|
+
import type { ObservationStore } from '../../observability/src/index.ts';
|
|
7
|
+
export interface SqliteStatement {
|
|
8
|
+
run(...parameters: readonly unknown[]): {
|
|
9
|
+
readonly changes?: number;
|
|
10
|
+
readonly lastInsertRowid?: number | bigint;
|
|
11
|
+
};
|
|
12
|
+
get(...parameters: readonly unknown[]): unknown;
|
|
13
|
+
all(...parameters: readonly unknown[]): readonly unknown[];
|
|
14
|
+
}
|
|
15
|
+
export interface SqliteConnection {
|
|
16
|
+
exec(sql: string): void;
|
|
17
|
+
prepare(sql: string): SqliteStatement;
|
|
18
|
+
}
|
|
19
|
+
export interface Migration {
|
|
20
|
+
readonly version: number;
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly sql: string;
|
|
23
|
+
}
|
|
24
|
+
export declare const MIGRATIONS: readonly Migration[];
|
|
25
|
+
export declare class SqliteAdapterError extends Error {
|
|
26
|
+
constructor(message: string);
|
|
27
|
+
}
|
|
28
|
+
export declare class SqliteMigrationRunner {
|
|
29
|
+
private readonly db;
|
|
30
|
+
private readonly migrations;
|
|
31
|
+
constructor(db: SqliteConnection, migrations?: readonly Migration[]);
|
|
32
|
+
apply(): readonly number[];
|
|
33
|
+
private numberField;
|
|
34
|
+
}
|
|
35
|
+
export declare class SqliteJsonRepository {
|
|
36
|
+
private readonly db;
|
|
37
|
+
constructor(db: SqliteConnection);
|
|
38
|
+
put(collection: string, id: string, value: unknown, updatedAt: string): void;
|
|
39
|
+
get<T>(collection: string, id: string): T | undefined;
|
|
40
|
+
list<T>(collection: string): readonly T[];
|
|
41
|
+
}
|
|
42
|
+
export declare class SqliteOrchestrationStore implements OrchestrationStore {
|
|
43
|
+
private readonly repository;
|
|
44
|
+
constructor(db: SqliteConnection);
|
|
45
|
+
saveSprint(value: Sprint): void;
|
|
46
|
+
getSprint(id: EntityId): Sprint | undefined;
|
|
47
|
+
listSprints(): readonly Sprint[];
|
|
48
|
+
saveTask(value: Task): void;
|
|
49
|
+
getTask(id: EntityId): Task | undefined;
|
|
50
|
+
listTasks(sprintId?: EntityId): readonly Task[];
|
|
51
|
+
saveHandoff(value: Handoff): void;
|
|
52
|
+
getHandoff(id: EntityId): Handoff | undefined;
|
|
53
|
+
listHandoffs(): readonly Handoff[];
|
|
54
|
+
}
|
|
55
|
+
export declare class SqliteSandboxStore implements SandboxStore {
|
|
56
|
+
private readonly repository;
|
|
57
|
+
constructor(db: SqliteConnection);
|
|
58
|
+
save(value: SandboxSession): void;
|
|
59
|
+
get(id: EntityId): SandboxSession | undefined;
|
|
60
|
+
}
|
|
61
|
+
export declare class SqliteCheckpointStore implements CheckpointStore {
|
|
62
|
+
private readonly repository;
|
|
63
|
+
constructor(db: SqliteConnection);
|
|
64
|
+
save(value: Checkpoint): void;
|
|
65
|
+
get(runId: RunId): Checkpoint | undefined;
|
|
66
|
+
}
|
|
67
|
+
export declare class SqliteEventStore implements EventStore {
|
|
68
|
+
private readonly db;
|
|
69
|
+
constructor(db: SqliteConnection);
|
|
70
|
+
append(event: DomainEvent): void;
|
|
71
|
+
list(): readonly DomainEvent[];
|
|
72
|
+
private eventFrom;
|
|
73
|
+
}
|
|
74
|
+
export declare class SqliteRuntimeRunStore {
|
|
75
|
+
private readonly repository;
|
|
76
|
+
constructor(db: SqliteConnection);
|
|
77
|
+
save(value: RuntimeRun): void;
|
|
78
|
+
get(runId: RunId): RuntimeRun | undefined;
|
|
79
|
+
}
|
|
80
|
+
export declare class SqliteObservationStore implements ObservationStore {
|
|
81
|
+
private readonly repository;
|
|
82
|
+
constructor(db: SqliteConnection);
|
|
83
|
+
append(value: Observation): void;
|
|
84
|
+
list(): readonly Observation[];
|
|
85
|
+
}
|
|
86
|
+
export declare class SqliteAuditStore {
|
|
87
|
+
private readonly db;
|
|
88
|
+
constructor(db: SqliteConnection);
|
|
89
|
+
append(value: AuditRecord): void;
|
|
90
|
+
list(): readonly AuditRecord[];
|
|
91
|
+
}
|
|
92
|
+
export declare function createAuditRecord(input: {
|
|
93
|
+
readonly action: string;
|
|
94
|
+
readonly aggregateId: EntityId;
|
|
95
|
+
readonly outcome: AuditRecord['outcome'];
|
|
96
|
+
readonly evidenceIds: readonly EntityId[];
|
|
97
|
+
readonly details?: Readonly<Record<string, string>>;
|
|
98
|
+
readonly correlationId?: string;
|
|
99
|
+
}): AuditRecord;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
export const MIGRATIONS = [
|
|
3
|
+
{
|
|
4
|
+
version: 1,
|
|
5
|
+
name: 'core-persistence',
|
|
6
|
+
sql: `CREATE TABLE IF NOT EXISTS forja_records (collection TEXT NOT NULL, id TEXT NOT NULL, payload TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (collection, id));
|
|
7
|
+
CREATE TABLE IF NOT EXISTS forja_events (id TEXT PRIMARY KEY, aggregate_id TEXT NOT NULL, sequence INTEGER NOT NULL, type TEXT NOT NULL, payload TEXT NOT NULL, idempotency_key TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL);
|
|
8
|
+
CREATE TABLE IF NOT EXISTS forja_audit (id TEXT PRIMARY KEY, aggregate_id TEXT NOT NULL, action TEXT NOT NULL, outcome TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL);`,
|
|
9
|
+
},
|
|
10
|
+
];
|
|
11
|
+
export class SqliteAdapterError extends Error {
|
|
12
|
+
constructor(message) { super(message); this.name = 'SqliteAdapterError'; }
|
|
13
|
+
}
|
|
14
|
+
export class SqliteMigrationRunner {
|
|
15
|
+
db;
|
|
16
|
+
migrations;
|
|
17
|
+
constructor(db, migrations = MIGRATIONS) { this.db = db; this.migrations = [...migrations].sort((a, b) => a.version - b.version); }
|
|
18
|
+
apply() {
|
|
19
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS forja_schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL);');
|
|
20
|
+
const rows = this.db.prepare('SELECT version FROM forja_schema_migrations ORDER BY version').all();
|
|
21
|
+
const applied = new Set(rows.map((row) => this.numberField(row, 'version')));
|
|
22
|
+
const executed = [];
|
|
23
|
+
for (const migration of this.migrations) {
|
|
24
|
+
if (applied.has(migration.version))
|
|
25
|
+
continue;
|
|
26
|
+
if (!Number.isInteger(migration.version) || migration.version < 1)
|
|
27
|
+
throw new SqliteAdapterError(`Invalid migration version: ${migration.version}`);
|
|
28
|
+
this.db.exec(migration.sql);
|
|
29
|
+
this.db.prepare('INSERT INTO forja_schema_migrations (version, name, applied_at) VALUES (?, ?, ?)').run(migration.version, migration.name, new Date().toISOString());
|
|
30
|
+
executed.push(migration.version);
|
|
31
|
+
}
|
|
32
|
+
return executed;
|
|
33
|
+
}
|
|
34
|
+
numberField(row, field) { if (!isRecord(row) || typeof row[field] !== 'number')
|
|
35
|
+
throw new SqliteAdapterError(`Invalid migration row: ${field}`); return row[field]; }
|
|
36
|
+
}
|
|
37
|
+
export class SqliteJsonRepository {
|
|
38
|
+
db;
|
|
39
|
+
constructor(db) { this.db = db; }
|
|
40
|
+
put(collection, id, value, updatedAt) {
|
|
41
|
+
this.db.prepare('INSERT INTO forja_records (collection, id, payload, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(collection, id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at').run(collection, id, JSON.stringify(value), updatedAt);
|
|
42
|
+
}
|
|
43
|
+
get(collection, id) {
|
|
44
|
+
const row = this.db.prepare('SELECT payload FROM forja_records WHERE collection = ? AND id = ?').get(collection, id);
|
|
45
|
+
if (!isRecord(row) || typeof row.payload !== 'string')
|
|
46
|
+
return undefined;
|
|
47
|
+
return JSON.parse(row.payload);
|
|
48
|
+
}
|
|
49
|
+
list(collection) {
|
|
50
|
+
return this.db.prepare('SELECT payload FROM forja_records WHERE collection = ? ORDER BY updated_at').all(collection).flatMap((row) => isRecord(row) && typeof row.payload === 'string' ? [JSON.parse(row.payload)] : []);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export class SqliteOrchestrationStore {
|
|
54
|
+
repository;
|
|
55
|
+
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
56
|
+
saveSprint(value) { this.repository.put('sprint', value.id, value, value.updatedAt); }
|
|
57
|
+
getSprint(id) { return this.repository.get('sprint', id); }
|
|
58
|
+
listSprints() { return this.repository.list('sprint'); }
|
|
59
|
+
saveTask(value) { this.repository.put('task', value.id, value, value.updatedAt); }
|
|
60
|
+
getTask(id) { return this.repository.get('task', id); }
|
|
61
|
+
listTasks(sprintId) { const tasks = this.repository.list('task'); return sprintId === undefined ? tasks : tasks.filter((task) => task.sprintId === sprintId); }
|
|
62
|
+
saveHandoff(value) { this.repository.put('handoff', value.id, value, value.updatedAt); }
|
|
63
|
+
getHandoff(id) { return this.repository.get('handoff', id); }
|
|
64
|
+
listHandoffs() { return this.repository.list('handoff'); }
|
|
65
|
+
}
|
|
66
|
+
export class SqliteSandboxStore {
|
|
67
|
+
repository;
|
|
68
|
+
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
69
|
+
save(value) { this.repository.put('sandbox', value.id, value, value.updatedAt); }
|
|
70
|
+
get(id) { return this.repository.get('sandbox', id); }
|
|
71
|
+
}
|
|
72
|
+
export class SqliteCheckpointStore {
|
|
73
|
+
repository;
|
|
74
|
+
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
75
|
+
save(value) { this.repository.put('checkpoint', value.runId, value, value.updatedAt); }
|
|
76
|
+
get(runId) { return this.repository.get('checkpoint', runId); }
|
|
77
|
+
}
|
|
78
|
+
export class SqliteEventStore {
|
|
79
|
+
db;
|
|
80
|
+
constructor(db) { this.db = db; }
|
|
81
|
+
append(event) { this.db.prepare('INSERT OR IGNORE INTO forja_events (id, aggregate_id, sequence, type, payload, idempotency_key, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)').run(event.id, event.aggregateId, event.sequence, event.type, JSON.stringify(event.payload), event.idempotencyKey, event.createdAt); }
|
|
82
|
+
list() { return this.db.prepare('SELECT id, aggregate_id, sequence, type, payload, idempotency_key, created_at FROM forja_events ORDER BY aggregate_id, sequence').all().flatMap((row) => this.eventFrom(row)); }
|
|
83
|
+
eventFrom(row) { if (!isRecord(row) || typeof row.id !== 'string' || typeof row.aggregate_id !== 'string' || typeof row.sequence !== 'number' || typeof row.type !== 'string' || typeof row.payload !== 'string' || typeof row.idempotency_key !== 'string' || typeof row.created_at !== 'string')
|
|
84
|
+
return []; return [{ schemaVersion: '2.0', id: row.id, aggregateId: row.aggregate_id, sequence: row.sequence, type: row.type, payload: JSON.parse(row.payload), idempotencyKey: row.idempotency_key, correlationId: row.idempotency_key, createdAt: row.created_at, updatedAt: row.created_at }]; }
|
|
85
|
+
}
|
|
86
|
+
export class SqliteRuntimeRunStore {
|
|
87
|
+
repository;
|
|
88
|
+
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
89
|
+
save(value) { this.repository.put('runtime_run', value.runId, value, value.updatedAt); }
|
|
90
|
+
get(runId) { return this.repository.get('runtime_run', runId); }
|
|
91
|
+
}
|
|
92
|
+
export class SqliteObservationStore {
|
|
93
|
+
repository;
|
|
94
|
+
constructor(db) { this.repository = new SqliteJsonRepository(db); }
|
|
95
|
+
append(value) { this.repository.put('observation', value.id, value, value.updatedAt); }
|
|
96
|
+
list() { return this.repository.list('observation'); }
|
|
97
|
+
}
|
|
98
|
+
export class SqliteAuditStore {
|
|
99
|
+
db;
|
|
100
|
+
constructor(db) { this.db = db; }
|
|
101
|
+
append(value) { this.db.prepare('INSERT OR IGNORE INTO forja_audit (id, aggregate_id, action, outcome, payload, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(value.id, value.aggregateId, value.action, value.outcome, JSON.stringify(value), value.createdAt); }
|
|
102
|
+
list() { return this.db.prepare('SELECT payload FROM forja_audit ORDER BY created_at, id').all().flatMap((row) => isRecord(row) && typeof row.payload === 'string' ? [JSON.parse(row.payload)] : []); }
|
|
103
|
+
}
|
|
104
|
+
export function createAuditRecord(input) {
|
|
105
|
+
const now = new Date().toISOString();
|
|
106
|
+
return { schemaVersion: '2.0', id: randomUUID(), action: input.action, aggregateId: input.aggregateId, outcome: input.outcome, evidenceIds: [...input.evidenceIds], details: input.details ?? {}, correlationId: input.correlationId ?? input.action, createdAt: now, updatedAt: now };
|
|
107
|
+
}
|
|
108
|
+
function isRecord(value) { return typeof value === 'object' && value !== null; }
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ContextPackage, type EntityId, type Evidence, type KnowledgeStatus, type TokenBudget } from '../../contracts/src/index.ts';
|
|
2
|
+
export interface ContextCandidate {
|
|
3
|
+
readonly id: EntityId;
|
|
4
|
+
readonly source: 'memory' | 'graph';
|
|
5
|
+
readonly locator: string;
|
|
6
|
+
readonly content: string;
|
|
7
|
+
readonly relevance: number;
|
|
8
|
+
readonly status: KnowledgeStatus;
|
|
9
|
+
readonly evidence: readonly Evidence[];
|
|
10
|
+
readonly checksum?: string;
|
|
11
|
+
readonly obsolete?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface ContextSource {
|
|
14
|
+
search(objective: string): readonly ContextCandidate[] | Promise<readonly ContextCandidate[]>;
|
|
15
|
+
}
|
|
16
|
+
export interface ContextCache {
|
|
17
|
+
get(checksum: string): string | undefined;
|
|
18
|
+
set(checksum: string, content: string): void;
|
|
19
|
+
}
|
|
20
|
+
export interface ContextBuildRequest {
|
|
21
|
+
readonly objective: string;
|
|
22
|
+
readonly budget: TokenBudget;
|
|
23
|
+
readonly includeContent?: boolean;
|
|
24
|
+
readonly maxItems?: number;
|
|
25
|
+
readonly requireEvidence?: boolean;
|
|
26
|
+
readonly correlationId?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface ContextDependencies {
|
|
29
|
+
readonly memory?: ContextSource;
|
|
30
|
+
readonly graph?: ContextSource;
|
|
31
|
+
readonly cache?: ContextCache;
|
|
32
|
+
}
|
|
33
|
+
export declare class ContextEngineError extends Error {
|
|
34
|
+
readonly code: 'INVALID_REQUEST' | 'INSUFFICIENT_EVIDENCE' | 'CONTEXT_BUDGET_EXCEEDED' | 'CONTENT_NOT_CACHED';
|
|
35
|
+
constructor(code: ContextEngineError['code'], message: string);
|
|
36
|
+
}
|
|
37
|
+
export declare class InMemoryContextCache implements ContextCache {
|
|
38
|
+
private readonly values;
|
|
39
|
+
get(checksum: string): string | undefined;
|
|
40
|
+
set(checksum: string, content: string): void;
|
|
41
|
+
}
|
|
42
|
+
export declare class ContextEngine {
|
|
43
|
+
private readonly dependencies;
|
|
44
|
+
constructor(dependencies: ContextDependencies);
|
|
45
|
+
build(request: ContextBuildRequest): Promise<ContextPackage>;
|
|
46
|
+
expand(checksum: string): string;
|
|
47
|
+
private isUsable;
|
|
48
|
+
private estimateTokens;
|
|
49
|
+
private checksum;
|
|
50
|
+
private uniqueEvidence;
|
|
51
|
+
private auditFields;
|
|
52
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { CONTRACT_VERSION, validateTokenBudget, } from "../../contracts/src/index.js";
|
|
3
|
+
export class ContextEngineError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
constructor(code, message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'ContextEngineError';
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export class InMemoryContextCache {
|
|
12
|
+
values = new Map();
|
|
13
|
+
get(checksum) {
|
|
14
|
+
return this.values.get(checksum);
|
|
15
|
+
}
|
|
16
|
+
set(checksum, content) {
|
|
17
|
+
this.values.set(checksum, content);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class ContextEngine {
|
|
21
|
+
dependencies;
|
|
22
|
+
constructor(dependencies) {
|
|
23
|
+
this.dependencies = dependencies;
|
|
24
|
+
}
|
|
25
|
+
async build(request) {
|
|
26
|
+
if (request.objective.trim().length === 0)
|
|
27
|
+
throw new ContextEngineError('INVALID_REQUEST', 'Context objective is required');
|
|
28
|
+
validateTokenBudget(request.budget);
|
|
29
|
+
const maxItems = request.maxItems ?? Number.MAX_SAFE_INTEGER;
|
|
30
|
+
if (!Number.isInteger(maxItems) || maxItems < 1)
|
|
31
|
+
throw new ContextEngineError('INVALID_REQUEST', 'maxItems must be a positive integer');
|
|
32
|
+
const sources = [this.dependencies.memory, this.dependencies.graph].filter((source) => source !== undefined);
|
|
33
|
+
const results = await Promise.all(sources.map((source) => source.search(request.objective)));
|
|
34
|
+
const candidates = results.flat().filter((candidate) => this.isUsable(candidate));
|
|
35
|
+
if (candidates.length === 0 && (request.requireEvidence ?? true))
|
|
36
|
+
throw new ContextEngineError('INSUFFICIENT_EVIDENCE', 'No current evidence matches the context objective');
|
|
37
|
+
const ranked = candidates
|
|
38
|
+
.map((candidate) => ({ candidate, checksum: candidate.checksum ?? this.checksum(candidate.content) }))
|
|
39
|
+
.sort((left, right) => right.candidate.relevance - left.candidate.relevance || left.candidate.locator.localeCompare(right.candidate.locator) || left.checksum.localeCompare(right.checksum));
|
|
40
|
+
const unique = new Map();
|
|
41
|
+
for (const item of ranked)
|
|
42
|
+
if (!unique.has(item.checksum))
|
|
43
|
+
unique.set(item.checksum, item);
|
|
44
|
+
const availableTokens = request.budget.totalTokens - request.budget.usedTokens;
|
|
45
|
+
let usedTokens = 0;
|
|
46
|
+
let cacheHits = 0;
|
|
47
|
+
const selected = [];
|
|
48
|
+
for (const item of [...unique.values()].slice(0, maxItems)) {
|
|
49
|
+
const tokens = this.estimateTokens(item.candidate.content);
|
|
50
|
+
if (usedTokens + tokens > availableTokens)
|
|
51
|
+
continue;
|
|
52
|
+
if (this.dependencies.cache?.get(item.checksum) !== undefined)
|
|
53
|
+
cacheHits += 1;
|
|
54
|
+
else
|
|
55
|
+
this.dependencies.cache?.set(item.checksum, item.candidate.content);
|
|
56
|
+
selected.push({ ...item, tokens });
|
|
57
|
+
usedTokens += tokens;
|
|
58
|
+
}
|
|
59
|
+
if (selected.length === 0 && (request.requireEvidence ?? true))
|
|
60
|
+
throw new ContextEngineError('CONTEXT_BUDGET_EXCEEDED', 'Context budget cannot fit any evidence');
|
|
61
|
+
const references = this.uniqueEvidence(selected.flatMap((item) => item.candidate.evidence));
|
|
62
|
+
const content = request.includeContent === false ? [] : selected.map((item) => item.candidate.content);
|
|
63
|
+
const metrics = {
|
|
64
|
+
candidateCount: candidates.length,
|
|
65
|
+
selectedCount: selected.length,
|
|
66
|
+
deduplicatedCount: candidates.length - unique.size,
|
|
67
|
+
cacheHits,
|
|
68
|
+
selectedTokens: usedTokens,
|
|
69
|
+
unusedTokens: availableTokens - usedTokens,
|
|
70
|
+
};
|
|
71
|
+
const fields = this.auditFields(request.correlationId ?? randomUUID());
|
|
72
|
+
return {
|
|
73
|
+
...fields,
|
|
74
|
+
id: randomUUID(),
|
|
75
|
+
references,
|
|
76
|
+
content,
|
|
77
|
+
budget: { ...request.budget, usedTokens: request.budget.usedTokens + usedTokens },
|
|
78
|
+
checksum: this.checksum(JSON.stringify({ objective: request.objective, refs: selected.map((item) => item.checksum), includeContent: request.includeContent !== false })),
|
|
79
|
+
metrics,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
expand(checksum) {
|
|
83
|
+
const content = this.dependencies.cache?.get(checksum);
|
|
84
|
+
if (content === undefined)
|
|
85
|
+
throw new ContextEngineError('CONTENT_NOT_CACHED', `Context content is not cached: ${checksum}`);
|
|
86
|
+
return content;
|
|
87
|
+
}
|
|
88
|
+
isUsable(candidate) {
|
|
89
|
+
return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0;
|
|
90
|
+
}
|
|
91
|
+
estimateTokens(content) {
|
|
92
|
+
return Math.max(1, Math.ceil(Buffer.byteLength(content, 'utf8') / 4));
|
|
93
|
+
}
|
|
94
|
+
checksum(value) {
|
|
95
|
+
return createHash('sha256').update(value).digest('hex');
|
|
96
|
+
}
|
|
97
|
+
uniqueEvidence(evidence) {
|
|
98
|
+
const unique = new Map();
|
|
99
|
+
for (const item of evidence)
|
|
100
|
+
if (!unique.has(item.id))
|
|
101
|
+
unique.set(item.id, item);
|
|
102
|
+
return [...unique.values()];
|
|
103
|
+
}
|
|
104
|
+
auditFields(correlationId) {
|
|
105
|
+
const now = new Date().toISOString();
|
|
106
|
+
return { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId };
|
|
107
|
+
}
|
|
108
|
+
}
|