forjajs 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/apps/cli/src/index.d.ts +44 -0
  3. package/dist/apps/cli/src/index.js +304 -0
  4. package/dist/apps/server/src/main.d.ts +7 -2
  5. package/dist/apps/server/src/main.js +65 -16
  6. package/dist/bin/forja.js +208 -0
  7. package/dist/lib/core/health.js +2 -1
  8. package/dist/lib/core/registry.d.ts +7 -0
  9. package/dist/lib/core/registry.js +7 -0
  10. package/dist/lib/core/release.d.ts +6 -0
  11. package/dist/packages/adapter-git/src/index.d.ts +12 -0
  12. package/dist/packages/adapter-git/src/index.js +45 -0
  13. package/dist/packages/adapter-sqlite/src/index.d.ts +59 -2
  14. package/dist/packages/adapter-sqlite/src/index.js +136 -0
  15. package/dist/packages/context/src/index.d.ts +8 -0
  16. package/dist/packages/context/src/index.js +7 -0
  17. package/dist/packages/events/src/index.d.ts +2 -0
  18. package/dist/packages/events/src/index.js +16 -0
  19. package/dist/packages/graph/src/index.d.ts +59 -3
  20. package/dist/packages/graph/src/index.js +139 -21
  21. package/dist/packages/mcp/src/index.d.ts +14 -0
  22. package/dist/packages/mcp/src/index.js +39 -5
  23. package/dist/packages/policy/src/index.d.ts +7 -0
  24. package/dist/packages/policy/src/index.js +17 -1
  25. package/dist/packages/runtime/src/index.d.ts +20 -1
  26. package/dist/packages/runtime/src/index.js +34 -1
  27. package/docs/2x/CLI-CAPABILITIES.md +35 -0
  28. package/docs/2x/IMPLEMENTATION-AUDIT.md +132 -0
  29. package/docs/2x/SPRINT-1-CLI-CAPABILITY-PLAN.md +53 -0
  30. package/docs/2x/SPRINT-10-GRAPH-SYNC-PLAN.md +54 -0
  31. package/docs/2x/SPRINT-11-GRAPH-SYNC-CLI-MCP-PLAN.md +38 -0
  32. package/docs/2x/SPRINT-2-CLI-CAPABILITY-PLAN.md +39 -0
  33. package/docs/2x/SPRINT-3-RUNTIME-PERSISTENCE-PLAN.md +42 -0
  34. package/docs/2x/SPRINT-4-MCP-REGISTRY-PLAN.md +35 -0
  35. package/docs/2x/SPRINT-5-SERVER-APPROVALS-AUDIT-PLAN.md +31 -0
  36. package/docs/2x/SPRINT-6-EVENTS-E2E-PLAN.md +55 -0
  37. package/docs/2x/SPRINT-7-GRAPHLOOP-PERSISTENCE-PLAN.md +60 -0
  38. package/docs/2x/SPRINT-8-CONTEXT-GRAPH-PLAN.md +64 -0
  39. package/docs/2x/SPRINT-9-DETERMINISTIC-EXTRACTORS-PLAN.md +51 -0
  40. package/memory/50-orchestration/handoffs/2026-08-01_sprint-1-cli-capabilities.md +41 -0
  41. package/memory/50-orchestration/handoffs/2026-08-01_sprint-10-graph-sync.md +23 -0
  42. package/memory/50-orchestration/handoffs/2026-08-01_sprint-11-graph-sync-cli-mcp.md +22 -0
  43. package/memory/50-orchestration/handoffs/2026-08-01_sprint-2-cli-capabilities.md +30 -0
  44. package/memory/50-orchestration/handoffs/2026-08-01_sprint-3-runtime-persistence.md +29 -0
  45. package/memory/50-orchestration/handoffs/2026-08-01_sprint-4-mcp.md +29 -0
  46. package/memory/50-orchestration/handoffs/2026-08-01_sprint-5-server-approvals-audit.md +22 -0
  47. package/memory/50-orchestration/handoffs/2026-08-01_sprint-6-events-e2e.md +25 -0
  48. package/memory/50-orchestration/handoffs/2026-08-01_sprint-7-graphloop.md +23 -0
  49. package/memory/50-orchestration/handoffs/2026-08-01_sprint-8-context-graph.md +23 -0
  50. package/memory/50-orchestration/handoffs/2026-08-01_sprint-9-extractors.md +21 -0
  51. package/memory/90-decisions/0059-cli-adapter-capability-registry.md +17 -0
  52. package/memory/90-decisions/0060-runtime-persistence-port.md +17 -0
  53. package/memory/90-decisions/0061-mcp-dynamic-registry-stdio.md +16 -0
  54. package/memory/90-decisions/0062-server-catalog-approval-audit.md +17 -0
  55. package/memory/90-decisions/0063-events-persistent-e2e.md +19 -0
  56. package/memory/90-decisions/0064-graphloop-sqlite-store.md +20 -0
  57. package/memory/90-decisions/0065-context-graph-source-cache.md +20 -0
  58. package/memory/90-decisions/0066-graph-deterministic-extractors.md +16 -0
  59. package/memory/90-decisions/0067-graph-sync-capability.md +17 -0
  60. package/memory/90-decisions/0068-graph-sync-cli-mcp.md +17 -0
  61. package/package.json +12 -13
package/dist/bin/forja.js CHANGED
@@ -14,8 +14,15 @@ import fs from 'node:fs';
14
14
  import path from 'node:path';
15
15
  import { spawnSync } from 'node:child_process';
16
16
  import { fileURLToPath } from 'node:url';
17
+ import Database from 'better-sqlite3';
17
18
  import { COMMANDS, DOMAINS, resolveScript } from "../lib/core/registry.js";
18
19
  import { getWorkspaceInfo, getWorkspaceContextDir } from "../lib/workspace.js";
20
+ import { capabilityIdForCommand, createCliCapabilityRuntime, executeCliCapability, parseLegacyCommandInput, } from "../apps/cli/src/index.js";
21
+ import { GitGraphDocumentSource, SpawnCommandRunner } from "../packages/adapter-git/src/index.js";
22
+ import { GraphLoop } from "../packages/graph/src/index.js";
23
+ import { SqliteGraphStore, SqliteMigrationRunner } from "../packages/adapter-sqlite/src/index.js";
24
+ import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
25
+ import { McpServer } from "../packages/mcp/src/index.js";
19
26
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
27
  const root = path.resolve(__dirname, '..');
21
28
  function printHelp() {
@@ -37,6 +44,11 @@ function printHelp() {
37
44
  }
38
45
  console.log('');
39
46
  }
47
+ console.log('Capabilities:');
48
+ console.log(' capabilities:list Lista capabilities descobríveis');
49
+ console.log(' capabilities:describe Descreve uma capability');
50
+ console.log(' capability:execute Executa uma capability com input JSON');
51
+ console.log(' mcp:start Inicia o transporte MCP JSON-RPC por stdio');
40
52
  console.log('Toda execução é auditada em .context/forja-runs.jsonl (workspace, se existir).');
41
53
  }
42
54
  function suggest(input) {
@@ -76,11 +88,204 @@ function audit(entry) {
76
88
  console.error(`Aviso: auditoria indisponível (${error.message}).`);
77
89
  }
78
90
  }
91
+ function runLegacyCaptured(command, args) {
92
+ const cmd = COMMANDS[command];
93
+ if (!cmd)
94
+ return { exitCode: 127, stdout: '', stderr: `Comando legado não encontrado: ${command}` };
95
+ let result;
96
+ if (cmd.node) {
97
+ const script = resolveScript(root, cmd.node);
98
+ result = spawnSync('node', [script, ...(cmd.args || []), ...args], {
99
+ cwd: process.cwd(),
100
+ encoding: 'utf8',
101
+ stdio: 'pipe',
102
+ });
103
+ }
104
+ else {
105
+ result = spawnSync(cmd.bin, [...(cmd.args || []), ...args], {
106
+ cwd: process.cwd(),
107
+ encoding: 'utf8',
108
+ stdio: 'pipe',
109
+ });
110
+ }
111
+ const error = result.error;
112
+ const stderr = [result.stderr || '', error ? error.message : ''].filter(Boolean).join('\n');
113
+ return {
114
+ exitCode: result.status ?? 1,
115
+ stdout: result.stdout || '',
116
+ stderr,
117
+ };
118
+ }
119
+ function jsonFlag(args) {
120
+ return args.includes('--json');
121
+ }
122
+ function withoutFlag(args, flag) {
123
+ return args.filter((arg) => arg !== flag);
124
+ }
125
+ function printExecutionResult(result, json) {
126
+ if (json) {
127
+ console.log(JSON.stringify(result));
128
+ return;
129
+ }
130
+ const execution = result;
131
+ const payload = execution.output?.payload;
132
+ if (payload?.stdout)
133
+ process.stdout.write(payload.stdout);
134
+ if (payload?.stderr)
135
+ process.stderr.write(payload.stderr);
136
+ if (payload && typeof payload.indexed === 'number' && typeof payload.skipped === 'number')
137
+ console.log(`Graph sync: ${payload.indexed} indexado(s), ${payload.skipped} ignorado(s), ${payload.edges ?? 0} aresta(s) em ${payload.durationMs ?? 0}ms.`);
138
+ if (execution.error?.message)
139
+ console.error(execution.error.message);
140
+ }
141
+ async function runCapabilityCommand(command, args) {
142
+ const needsGraph = command === 'graph:sync' || command === 'capability:execute' || command === 'capabilities:list' || command === 'capabilities:describe';
143
+ const runtime = createCliCapabilityRuntime(runLegacyCaptured, needsGraph ? createGraphSyncComposition() : undefined);
144
+ const started = Date.now();
145
+ const json = jsonFlag(args);
146
+ let result;
147
+ let capabilityId;
148
+ let commandSucceeded = true;
149
+ let inputArgs = withoutFlag(args, '--json');
150
+ if (command === 'capabilities:list') {
151
+ result = runtime.registry.list();
152
+ }
153
+ else if (command === 'capabilities:describe') {
154
+ const id = inputArgs[0];
155
+ if (!id) {
156
+ result = { error: 'Capability id is required' };
157
+ commandSucceeded = false;
158
+ }
159
+ else {
160
+ try {
161
+ result = runtime.registry.describe(id);
162
+ }
163
+ catch (error) {
164
+ result = { error: error instanceof Error ? error.message : 'Capability not found' };
165
+ commandSucceeded = false;
166
+ }
167
+ }
168
+ }
169
+ else if (command === 'capability:execute') {
170
+ capabilityId = inputArgs.shift();
171
+ const inputIndex = inputArgs.indexOf('--input');
172
+ if (!capabilityId || inputIndex < 0 || inputArgs[inputIndex + 1] === undefined) {
173
+ result = { error: 'Usage: capability:execute <id> --input \'{}\' [--json]' };
174
+ commandSucceeded = false;
175
+ }
176
+ else {
177
+ try {
178
+ const payload = JSON.parse(inputArgs[inputIndex + 1]);
179
+ result = await executeCliCapability(runtime, capabilityId, payload);
180
+ }
181
+ catch (error) {
182
+ result = { error: error instanceof Error ? error.message : 'Invalid capability input' };
183
+ commandSucceeded = false;
184
+ }
185
+ }
186
+ }
187
+ else {
188
+ const migrated = capabilityIdForCommand(command);
189
+ if (!migrated)
190
+ return 1;
191
+ capabilityId = migrated;
192
+ try {
193
+ const parsed = parseLegacyCommandInput(command, inputArgs);
194
+ result = await executeCliCapability(runtime, parsed.capabilityId, parsed.payload);
195
+ }
196
+ catch (error) {
197
+ result = { error: error instanceof Error ? error.message : 'Invalid command input' };
198
+ commandSucceeded = false;
199
+ }
200
+ }
201
+ printExecutionResult(result, json || command.startsWith('capabilit'));
202
+ const execution = result;
203
+ const payload = execution.output?.payload;
204
+ audit({
205
+ ts: new Date().toISOString(),
206
+ cmd: command,
207
+ args,
208
+ capabilityId,
209
+ runId: execution.runId,
210
+ correlationId: execution.correlationId,
211
+ status: execution.status,
212
+ exitCode: commandSucceeded && (execution.status === undefined || execution.status === 'succeeded') ? 0 : 1,
213
+ durationMs: Date.now() - started,
214
+ metrics: capabilityId === 'graph.sync' && payload === undefined ? undefined : capabilityId === 'graph.sync' ? { documents: payload?.documents, indexed: payload?.indexed, skipped: payload?.skipped, nodes: payload?.nodes, edges: payload?.edges, durationMs: payload?.durationMs, files: payload?.files } : undefined,
215
+ });
216
+ return commandSucceeded && (execution.status === undefined || execution.status === 'succeeded') ? 0 : 1;
217
+ }
218
+ async function runMcpStdio() {
219
+ const runtime = createCliCapabilityRuntime(runLegacyCaptured, createGraphSyncComposition());
220
+ const definitions = runtime.registry.list();
221
+ const mcp = new McpServer({
222
+ registry: runtime.registry,
223
+ policy: runtime.policy,
224
+ agent: {
225
+ ...runtime.agent,
226
+ permissions: ['read', 'write', 'execution', 'database'],
227
+ capabilities: definitions.map((definition) => definition.id),
228
+ },
229
+ audit: {
230
+ append: (event) => audit({ ts: new Date().toISOString(), cmd: `mcp:${event.tool}`, args: [], capabilityId: event.tool, correlationId: event.correlationId, status: event.outcome === 'success' ? 'succeeded' : event.outcome === 'blocked' ? 'blocked' : 'failed', exitCode: event.outcome === 'success' ? 0 : 1, durationMs: 0 }),
231
+ },
232
+ });
233
+ process.stdin.setEncoding('utf8');
234
+ const handleLine = async (line) => {
235
+ if (line.trim().length === 0)
236
+ return;
237
+ let request;
238
+ try {
239
+ request = JSON.parse(line);
240
+ const id = request.id ?? null;
241
+ let result;
242
+ if (request.method === 'initialize')
243
+ result = { protocolVersion: '2025-06-18', capabilities: { tools: {}, resources: {} }, serverInfo: { name: 'forja', version: '2.0.1' } };
244
+ else if (request.method === 'tools/list')
245
+ result = { tools: mcp.listTools() };
246
+ else if (request.method === 'resources/list')
247
+ result = { resources: mcp.listResources() };
248
+ else if (request.method === 'tools/call')
249
+ result = await mcp.callTool(String(request.params?.name ?? ''), request.params?.arguments ?? {});
250
+ else if (request.method === 'resources/read')
251
+ result = await mcp.readResource(String(request.params?.uri ?? ''));
252
+ else
253
+ throw new Error(`Unsupported MCP method: ${request.method ?? 'missing'}`);
254
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, result })}\n`);
255
+ }
256
+ catch (error) {
257
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message: error instanceof Error ? error.message : 'MCP request failed' } })}\n`);
258
+ }
259
+ };
260
+ let buffer = '';
261
+ for await (const chunk of process.stdin) {
262
+ buffer += chunk;
263
+ const lines = buffer.split('\n');
264
+ buffer = lines.pop() ?? '';
265
+ for (const line of lines)
266
+ await handleLine(line);
267
+ }
268
+ await handleLine(buffer);
269
+ return 0;
270
+ }
271
+ function createGraphSyncComposition() {
272
+ fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
273
+ const database = new Database(process.env.FORJA_RUNTIME_DB ?? getWorkspaceDbPath());
274
+ new SqliteMigrationRunner(database).apply();
275
+ const graphRoot = process.env.FORJA_GRAPH_ROOT ?? process.cwd();
276
+ return { graph: new GraphLoop(new SqliteGraphStore(database)), source: new GitGraphDocumentSource(graphRoot, new SpawnCommandRunner()) };
277
+ }
79
278
  const [name, ...rest] = process.argv.slice(2);
80
279
  if (!name || name === 'help' || name === '--help' || name === '-h') {
81
280
  printHelp();
82
281
  process.exit(0);
83
282
  }
283
+ if (name === 'capabilities:list' || name === 'capabilities:describe' || name === 'capability:execute') {
284
+ process.exit(await runCapabilityCommand(name, rest));
285
+ }
286
+ if (name === 'mcp:start') {
287
+ process.exit(await runMcpStdio());
288
+ }
84
289
  const cmd = COMMANDS[name];
85
290
  if (!cmd) {
86
291
  console.error(`Comando desconhecido: ${name}`);
@@ -106,6 +311,9 @@ if (gateErrors.length) {
106
311
  });
107
312
  process.exit(1);
108
313
  }
314
+ if (capabilityIdForCommand(name) !== undefined) {
315
+ process.exit(await runCapabilityCommand(name, rest));
316
+ }
109
317
  const started = Date.now();
110
318
  let result;
111
319
  // Os filhos rodam ONDE O USUÁRIO INVOCOU, não na raiz do pacote. `cwd: root` funcionava por
@@ -40,6 +40,7 @@ import { runChecks as run, worstStatus, stripTemplateLiterals, asErrno } from ".
40
40
  import { COMMANDS } from "./registry.js";
41
41
  import { scanCommands, scanLinks, projectCommands, scanAdrRefs, adrNumbers, commandCited } from "./doc-graph.js";
42
42
  import { topologyIssues } from "../agent-topology.js";
43
+ import { CLI_INTERFACE_COMMANDS } from "../../apps/cli/src/index.js";
43
44
  /** @typedef {import('./checks.ts').Status} Status */
44
45
  // O runner vive em checks.mjs e é compartilhado com o catálogo de release (SPEC-010). Re-exportado
45
46
  // aqui para que `tools:doctor` e o hook SessionStart sigam importando de um lugar só.
@@ -458,7 +459,7 @@ const docsCommands = {
458
459
  if (!isFrameworkRepo(env)) {
459
460
  return { status: 'ok', detail: 'fora do repo do framework — não se aplica', fix: null };
460
461
  }
461
- const known = new Set([...Object.keys(COMMANDS), ...projectCommands(env)]);
462
+ const known = new Set([...Object.keys(COMMANDS), ...CLI_INTERFACE_COMMANDS, ...projectCommands(env)]);
462
463
  const ghosts = scanCommands(env).filter((c) => !known.has(c.command));
463
464
  if (ghosts.length) {
464
465
  const amostra = ghosts.slice(0, 5).map((g) => `${g.command} (${g.file}:${g.line})`).join(', ');
@@ -7,6 +7,7 @@
7
7
  * Alvos:
8
8
  * - node: script do repo executado com `node <script> [...args]`
9
9
  * - bin: binário externo no PATH (ex.: codegraph)
10
+ * - capability: handler compartilhado do Capability Registry
10
11
  *
11
12
  * Gates (aplicados por bin/forja.mjs antes do alvo):
12
13
  * - workspace bloqueia se o workspace (ADR-0019) não existir
@@ -179,6 +180,12 @@ export declare const COMMANDS: {
179
180
  node: string;
180
181
  args: string[];
181
182
  };
183
+ 'graph:sync': {
184
+ domain: string;
185
+ desc: string;
186
+ capability: string;
187
+ gates: string[];
188
+ };
182
189
  'code:context': {
183
190
  domain: string;
184
191
  desc: string;
@@ -7,6 +7,7 @@
7
7
  * Alvos:
8
8
  * - node: script do repo executado com `node <script> [...args]`
9
9
  * - bin: binário externo no PATH (ex.: codegraph)
10
+ * - capability: handler compartilhado do Capability Registry
10
11
  *
11
12
  * Gates (aplicados por bin/forja.mjs antes do alvo):
12
13
  * - workspace bloqueia se o workspace (ADR-0019) não existir
@@ -196,6 +197,12 @@ export const COMMANDS = {
196
197
  node: 'scripts/agent-harness.ts',
197
198
  args: ['code:impact'],
198
199
  },
200
+ 'graph:sync': {
201
+ domain: 'code',
202
+ desc: 'Indexa arquivos rastreáveis do workspace no GraphLoop por checksum',
203
+ capability: 'graph.sync',
204
+ gates: ['workspace-warn'],
205
+ },
199
206
  'code:context': {
200
207
  domain: 'code',
201
208
  desc: 'Pacote de contexto mínimo de um domínio: o mapa (context.md), + código com --code (ADR-0009)',
@@ -187,6 +187,12 @@ export declare function defaultEnv(overrides?: {}): {
187
187
  node: string;
188
188
  args: string[];
189
189
  };
190
+ 'graph:sync': {
191
+ domain: string;
192
+ desc: string;
193
+ capability: string;
194
+ gates: string[];
195
+ };
190
196
  'code:context': {
191
197
  domain: string;
192
198
  desc: string;
@@ -1,8 +1,20 @@
1
+ import type { DeterministicDocument, GraphDocumentSource } from '../../graph/src/index.ts';
2
+ import type { ISO8601 } from '../../contracts/src/index.ts';
1
3
  import type { SandboxBackend, SandboxCommandResult, SandboxDiffData, SandboxValidation } from '../../sandbox/src/index.ts';
2
4
  import type { SandboxCommand, SandboxSession } from '../../contracts/src/index.ts';
3
5
  export interface CommandRunner {
4
6
  run(command: SandboxCommand): SandboxCommandResult | Promise<SandboxCommandResult>;
5
7
  }
8
+ export declare class SpawnCommandRunner implements CommandRunner {
9
+ run(command: SandboxCommand): SandboxCommandResult;
10
+ }
11
+ export declare class GitGraphDocumentSource implements GraphDocumentSource {
12
+ private readonly root;
13
+ private readonly runner;
14
+ private readonly capturedAt;
15
+ constructor(root: string, runner: CommandRunner, capturedAt?: () => ISO8601);
16
+ listDocuments(): Promise<readonly DeterministicDocument[]>;
17
+ }
6
18
  export interface PatchApplier {
7
19
  apply(root: string, patch: string): void | Promise<void>;
8
20
  }
@@ -1,3 +1,48 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { graphDocumentId } from "../../graph/src/index.js";
5
+ export class SpawnCommandRunner {
6
+ run(command) {
7
+ const started = Date.now();
8
+ const result = spawnSync(command.executable, [...command.args], { cwd: command.cwd, env: command.env === undefined ? process.env : { ...process.env, ...command.env }, encoding: 'utf8' });
9
+ return { exitCode: result.status ?? 1, stdout: result.stdout ?? '', stderr: [result.stderr ?? '', result.error?.message ?? ''].filter(Boolean).join('\n'), durationMs: Date.now() - started };
10
+ }
11
+ }
12
+ export class GitGraphDocumentSource {
13
+ root;
14
+ runner;
15
+ capturedAt;
16
+ constructor(root, runner, capturedAt = () => new Date().toISOString()) {
17
+ this.root = path.resolve(root);
18
+ this.runner = runner;
19
+ this.capturedAt = capturedAt;
20
+ }
21
+ async listDocuments() {
22
+ const result = await this.runner.run({ executable: 'git', args: ['-C', this.root, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'] });
23
+ if (result.exitCode !== 0)
24
+ throw new Error(`Git file listing failed: ${result.stderr}`);
25
+ const documents = [];
26
+ for (const relative of result.stdout.split('\0').map((item) => item.trim()).filter(Boolean)) {
27
+ if (!isIndexable(relative))
28
+ continue;
29
+ const absolute = path.join(this.root, relative);
30
+ try {
31
+ const content = fs.readFileSync(absolute, 'utf8');
32
+ if (content.includes('\0') || Buffer.byteLength(content, 'utf8') > 1_000_000)
33
+ continue;
34
+ documents.push({ nodeId: graphDocumentId(relative), locator: relative, content, capturedAt: this.capturedAt() });
35
+ }
36
+ catch { /* unreadable/deleted files are skipped and remain auditable in Git status */ }
37
+ }
38
+ return documents;
39
+ }
40
+ }
41
+ function isIndexable(relative) {
42
+ if (relative.split('/').some((part) => part === 'node_modules' || part === '.git' || part === 'dist' || part === 'coverage'))
43
+ return false;
44
+ return /\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|yaml|yml)$/.test(relative);
45
+ }
1
46
  export class GitWorktreeBackend {
2
47
  runner;
3
48
  options;
@@ -1,9 +1,14 @@
1
- import type { AuditRecord, Checkpoint, DomainEvent, EntityId, Handoff, Observation, RuntimeRun, SandboxSession, Sprint, Task, RunId } from '../../contracts/src/index.ts';
1
+ import type { AuditRecord, Checkpoint, DomainEvent, EntityId, ExecutionResult, Handoff, Observation, RuntimeRun, SandboxSession, Sprint, Task, RunId } from '../../contracts/src/index.ts';
2
2
  import type { EventStore } from '../../events/src/index.ts';
3
- import type { CheckpointStore } from '../../runtime/src/index.ts';
3
+ import type { ApprovalStore } from '../../policy/src/index.ts';
4
+ import type { CheckpointStore, RuntimePersistence, RuntimePlanStep } from '../../runtime/src/index.ts';
5
+ import type { McpAuditEvent, McpAuditSink } from '../../mcp/src/index.ts';
4
6
  import type { OrchestrationStore } from '../../orchestration/src/index.ts';
5
7
  import type { SandboxStore } from '../../sandbox/src/index.ts';
6
8
  import type { ObservationStore } from '../../observability/src/index.ts';
9
+ import type { GraphStore } from '../../graph/src/index.ts';
10
+ import type { Evidence, GraphEdge, GraphNode } from '../../contracts/src/index.ts';
11
+ import type { ContextCache } from '../../context/src/index.ts';
7
12
  export interface SqliteStatement {
8
13
  run(...parameters: readonly unknown[]): {
9
14
  readonly changes?: number;
@@ -71,12 +76,64 @@ export declare class SqliteEventStore implements EventStore {
71
76
  list(): readonly DomainEvent[];
72
77
  private eventFrom;
73
78
  }
79
+ export declare class SqliteGraphStore implements GraphStore {
80
+ private readonly db;
81
+ constructor(db: SqliteConnection);
82
+ getNode(id: EntityId): GraphNode | undefined;
83
+ listNodes(): readonly GraphNode[];
84
+ saveNode(node: GraphNode): void;
85
+ getEdge(key: string): GraphEdge | undefined;
86
+ listEdges(): readonly GraphEdge[];
87
+ saveEdge(key: string, edge: GraphEdge): void;
88
+ getEvidence(id: EntityId): Evidence | undefined;
89
+ saveEvidence(item: Evidence): void;
90
+ getSourceChecksum(sourceKey: string): string | undefined;
91
+ saveSourceChecksum(sourceKey: string, checksum: string): void;
92
+ private payload;
93
+ private listPayload;
94
+ }
95
+ export declare class SqliteContextCache implements ContextCache {
96
+ private readonly db;
97
+ constructor(db: SqliteConnection);
98
+ get(checksum: string): string | undefined;
99
+ set(checksum: string, content: string): void;
100
+ }
74
101
  export declare class SqliteRuntimeRunStore {
75
102
  private readonly repository;
76
103
  constructor(db: SqliteConnection);
77
104
  save(value: RuntimeRun): void;
78
105
  get(runId: RunId): RuntimeRun | undefined;
79
106
  }
107
+ export declare class SqliteRuntimePersistence implements RuntimePersistence {
108
+ private readonly db;
109
+ constructor(db: SqliteConnection);
110
+ saveRun(value: RuntimeRun): void;
111
+ getRun(runId: RunId): RuntimeRun | undefined;
112
+ savePlan(runId: RunId, plan: readonly RuntimePlanStep[]): void;
113
+ getPlan(runId: RunId): readonly RuntimePlanStep[] | undefined;
114
+ saveResults(runId: RunId, results: readonly ExecutionResult[]): void;
115
+ getResults(runId: RunId): readonly ExecutionResult[] | undefined;
116
+ saveCursor(runId: RunId, nextStep: number, startedAt: number): void;
117
+ getCursor(runId: RunId): {
118
+ readonly nextStep: number;
119
+ readonly startedAt: number;
120
+ } | undefined;
121
+ private put;
122
+ private payload;
123
+ }
124
+ export declare class SqliteApprovalStore implements ApprovalStore {
125
+ private readonly db;
126
+ constructor(db: SqliteConnection);
127
+ save(value: import('../../contracts/src/index.ts').ApprovalRequest): void;
128
+ get(id: EntityId): import('../../contracts/src/index.ts').ApprovalRequest | undefined;
129
+ list(): readonly import('../../contracts/src/index.ts').ApprovalRequest[];
130
+ private payload;
131
+ }
132
+ export declare class SqliteMcpAuditSink implements McpAuditSink {
133
+ private readonly audit;
134
+ constructor(db: SqliteConnection);
135
+ append(event: McpAuditEvent): void;
136
+ }
80
137
  export declare class SqliteObservationStore implements ObservationStore {
81
138
  private readonly repository;
82
139
  constructor(db: SqliteConnection);
@@ -7,6 +7,36 @@ export const MIGRATIONS = [
7
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
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
9
  },
10
+ {
11
+ version: 2,
12
+ name: 'runtime-persistence',
13
+ sql: `CREATE TABLE IF NOT EXISTS runtime_runs (run_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
14
+ CREATE TABLE IF NOT EXISTS runtime_plans (run_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
15
+ CREATE TABLE IF NOT EXISTS runtime_results (run_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
16
+ CREATE TABLE IF NOT EXISTS runtime_state (run_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);`,
17
+ },
18
+ {
19
+ version: 3,
20
+ name: 'policy-approvals',
21
+ sql: `CREATE TABLE IF NOT EXISTS policy_approvals (approval_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);`,
22
+ },
23
+ {
24
+ version: 4,
25
+ name: 'graphloop-persistence',
26
+ sql: `CREATE TABLE IF NOT EXISTS graph_nodes (node_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
27
+ CREATE TABLE IF NOT EXISTS graph_edges (edge_key TEXT PRIMARY KEY, from_id TEXT NOT NULL, to_id TEXT NOT NULL, edge_type TEXT NOT NULL, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
28
+ CREATE TABLE IF NOT EXISTS graph_evidence (evidence_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
29
+ CREATE TABLE IF NOT EXISTS graph_sources (source_key TEXT PRIMARY KEY, checksum TEXT NOT NULL, updated_at TEXT NOT NULL);
30
+ CREATE TABLE IF NOT EXISTS graph_claims (claim_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS graph_contradictions (contradiction_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
32
+ CREATE TABLE IF NOT EXISTS graph_agenda (agenda_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);
33
+ CREATE TABLE IF NOT EXISTS graph_extraction_runs (run_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at TEXT NOT NULL);`,
34
+ },
35
+ {
36
+ version: 5,
37
+ name: 'context-cache',
38
+ sql: `CREATE TABLE IF NOT EXISTS context_cache (checksum TEXT PRIMARY KEY, content TEXT NOT NULL, updated_at TEXT NOT NULL);`,
39
+ },
10
40
  ];
11
41
  export class SqliteAdapterError extends Error {
12
42
  constructor(message) { super(message); this.name = 'SqliteAdapterError'; }
@@ -83,12 +113,118 @@ export class SqliteEventStore {
83
113
  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
114
  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
115
  }
116
+ export class SqliteGraphStore {
117
+ db;
118
+ constructor(db) { this.db = db; }
119
+ getNode(id) { return this.payload('SELECT payload FROM graph_nodes WHERE node_id = ?', id); }
120
+ listNodes() { return this.listPayload('SELECT payload FROM graph_nodes ORDER BY node_id'); }
121
+ saveNode(node) { this.db.prepare('INSERT INTO graph_nodes (node_id, payload, updated_at) VALUES (?, ?, ?) ON CONFLICT(node_id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at').run(node.id, JSON.stringify(node), node.updatedAt); }
122
+ getEdge(key) { return this.payload('SELECT payload FROM graph_edges WHERE edge_key = ?', key); }
123
+ listEdges() { return this.listPayload('SELECT payload FROM graph_edges ORDER BY edge_key'); }
124
+ saveEdge(key, edge) { this.db.prepare('INSERT INTO graph_edges (edge_key, from_id, to_id, edge_type, payload, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(edge_key) DO UPDATE SET from_id = excluded.from_id, to_id = excluded.to_id, edge_type = excluded.edge_type, payload = excluded.payload, updated_at = excluded.updated_at').run(key, edge.from, edge.to, edge.type, JSON.stringify(edge), edge.updatedAt); }
125
+ getEvidence(id) { return this.payload('SELECT payload FROM graph_evidence WHERE evidence_id = ?', id); }
126
+ saveEvidence(item) { this.db.prepare('INSERT INTO graph_evidence (evidence_id, payload, updated_at) VALUES (?, ?, ?) ON CONFLICT(evidence_id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at').run(item.id, JSON.stringify(item), item.capturedAt); }
127
+ getSourceChecksum(sourceKey) {
128
+ const row = this.db.prepare('SELECT checksum FROM graph_sources WHERE source_key = ?').get(sourceKey);
129
+ return isRecord(row) && typeof row.checksum === 'string' ? row.checksum : undefined;
130
+ }
131
+ saveSourceChecksum(sourceKey, checksum) { this.db.prepare('INSERT INTO graph_sources (source_key, checksum, updated_at) VALUES (?, ?, ?) ON CONFLICT(source_key) DO UPDATE SET checksum = excluded.checksum, updated_at = excluded.updated_at').run(sourceKey, checksum, new Date().toISOString()); }
132
+ payload(sql, id) {
133
+ const row = this.db.prepare(sql).get(id);
134
+ return isRecord(row) && typeof row.payload === 'string' ? JSON.parse(row.payload) : undefined;
135
+ }
136
+ listPayload(sql) {
137
+ return this.db.prepare(sql).all().flatMap((row) => isRecord(row) && typeof row.payload === 'string' ? [JSON.parse(row.payload)] : []);
138
+ }
139
+ }
140
+ export class SqliteContextCache {
141
+ db;
142
+ constructor(db) { this.db = db; }
143
+ get(checksum) {
144
+ const row = this.db.prepare('SELECT content FROM context_cache WHERE checksum = ?').get(checksum);
145
+ return isRecord(row) && typeof row.content === 'string' ? row.content : undefined;
146
+ }
147
+ set(checksum, content) {
148
+ this.db.prepare('INSERT INTO context_cache (checksum, content, updated_at) VALUES (?, ?, ?) ON CONFLICT(checksum) DO UPDATE SET content = excluded.content, updated_at = excluded.updated_at').run(checksum, content, new Date().toISOString());
149
+ }
150
+ }
86
151
  export class SqliteRuntimeRunStore {
87
152
  repository;
88
153
  constructor(db) { this.repository = new SqliteJsonRepository(db); }
89
154
  save(value) { this.repository.put('runtime_run', value.runId, value, value.updatedAt); }
90
155
  get(runId) { return this.repository.get('runtime_run', runId); }
91
156
  }
157
+ export class SqliteRuntimePersistence {
158
+ db;
159
+ constructor(db) { this.db = db; }
160
+ saveRun(value) {
161
+ this.db.prepare('INSERT INTO runtime_runs (run_id, payload, updated_at) VALUES (?, ?, ?) ON CONFLICT(run_id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at').run(value.runId, JSON.stringify(value), value.updatedAt);
162
+ }
163
+ getRun(runId) {
164
+ return this.payload('runtime_runs', 'run_id', runId);
165
+ }
166
+ savePlan(runId, plan) {
167
+ this.put('runtime_plans', runId, plan);
168
+ }
169
+ getPlan(runId) {
170
+ return this.payload('runtime_plans', 'run_id', runId);
171
+ }
172
+ saveResults(runId, results) {
173
+ this.put('runtime_results', runId, results);
174
+ }
175
+ getResults(runId) {
176
+ return this.payload('runtime_results', 'run_id', runId);
177
+ }
178
+ saveCursor(runId, nextStep, startedAt) {
179
+ this.put('runtime_state', runId, { nextStep, startedAt });
180
+ }
181
+ getCursor(runId) {
182
+ const value = this.payload('runtime_state', 'run_id', runId);
183
+ if (!isRecord(value) || typeof value.nextStep !== 'number' || typeof value.startedAt !== 'number')
184
+ return undefined;
185
+ return { nextStep: value.nextStep, startedAt: value.startedAt };
186
+ }
187
+ put(table, runId, value) {
188
+ this.db.prepare(`INSERT INTO ${table} (run_id, payload, updated_at) VALUES (?, ?, ?) ON CONFLICT(run_id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at`).run(runId, JSON.stringify(value), new Date().toISOString());
189
+ }
190
+ payload(table, key, value) {
191
+ const row = this.db.prepare(`SELECT payload FROM ${table} WHERE ${key} = ?`).get(value);
192
+ if (!isRecord(row) || typeof row.payload !== 'string')
193
+ return undefined;
194
+ return JSON.parse(row.payload);
195
+ }
196
+ }
197
+ export class SqliteApprovalStore {
198
+ db;
199
+ constructor(db) { this.db = db; }
200
+ save(value) {
201
+ this.db.prepare('INSERT INTO policy_approvals (approval_id, payload, updated_at) VALUES (?, ?, ?) ON CONFLICT(approval_id) DO UPDATE SET payload = excluded.payload, updated_at = excluded.updated_at').run(value.id, JSON.stringify(value), value.updatedAt);
202
+ }
203
+ get(id) {
204
+ return this.payload(id);
205
+ }
206
+ list() {
207
+ return this.db.prepare('SELECT payload FROM policy_approvals ORDER BY updated_at, approval_id').all().flatMap((row) => isRecord(row) && typeof row.payload === 'string' ? [JSON.parse(row.payload)] : []);
208
+ }
209
+ payload(id) {
210
+ const row = this.db.prepare('SELECT payload FROM policy_approvals WHERE approval_id = ?').get(id);
211
+ return isRecord(row) && typeof row.payload === 'string' ? JSON.parse(row.payload) : undefined;
212
+ }
213
+ }
214
+ export class SqliteMcpAuditSink {
215
+ audit;
216
+ constructor(db) { this.audit = new SqliteAuditStore(db); }
217
+ append(event) {
218
+ this.audit.append(createAuditRecord({
219
+ action: event.action,
220
+ aggregateId: event.agentId,
221
+ outcome: event.outcome,
222
+ evidenceIds: [],
223
+ correlationId: event.correlationId,
224
+ details: { tool: event.tool, agentId: event.agentId, ...event.details },
225
+ }));
226
+ }
227
+ }
92
228
  export class SqliteObservationStore {
93
229
  repository;
94
230
  constructor(db) { this.repository = new SqliteJsonRepository(db); }
@@ -30,6 +30,14 @@ export interface ContextDependencies {
30
30
  readonly graph?: ContextSource;
31
31
  readonly cache?: ContextCache;
32
32
  }
33
+ export interface GraphContextProvider {
34
+ searchContext(objective: string): readonly Omit<ContextCandidate, 'source'>[] | Promise<readonly Omit<ContextCandidate, 'source'>[]>;
35
+ }
36
+ export declare class GraphContextSource implements ContextSource {
37
+ private readonly provider;
38
+ constructor(provider: GraphContextProvider);
39
+ search(objective: string): Promise<readonly ContextCandidate[]>;
40
+ }
33
41
  export declare class ContextEngineError extends Error {
34
42
  readonly code: 'INVALID_REQUEST' | 'INSUFFICIENT_EVIDENCE' | 'CONTEXT_BUDGET_EXCEEDED' | 'CONTENT_NOT_CACHED';
35
43
  constructor(code: ContextEngineError['code'], message: string);
@@ -1,5 +1,12 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { CONTRACT_VERSION, validateTokenBudget, } from "../../contracts/src/index.js";
3
+ export class GraphContextSource {
4
+ provider;
5
+ constructor(provider) { this.provider = provider; }
6
+ async search(objective) {
7
+ return (await this.provider.searchContext(objective)).map((candidate) => ({ ...candidate, source: 'graph' }));
8
+ }
9
+ }
3
10
  export class ContextEngineError extends Error {
4
11
  code;
5
12
  constructor(code, message) {