forjajs 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +22 -0
  3. package/README.pt-BR.md +22 -0
  4. package/dist/apps/cli/src/index.d.ts +44 -0
  5. package/dist/apps/cli/src/index.js +304 -0
  6. package/dist/apps/server/src/main.d.ts +9 -3
  7. package/dist/apps/server/src/main.js +70 -19
  8. package/dist/bin/forja.js +213 -0
  9. package/dist/lib/core/health.js +2 -1
  10. package/dist/lib/core/registry.d.ts +17 -0
  11. package/dist/lib/core/registry.js +17 -0
  12. package/dist/lib/core/release.d.ts +16 -0
  13. package/dist/packages/adapter-git/src/index.d.ts +14 -0
  14. package/dist/packages/adapter-git/src/index.js +66 -0
  15. package/dist/packages/adapter-sqlite/src/index.d.ts +59 -2
  16. package/dist/packages/adapter-sqlite/src/index.js +136 -0
  17. package/dist/packages/context/src/index.d.ts +8 -0
  18. package/dist/packages/context/src/index.js +7 -0
  19. package/dist/packages/contracts/src/index.d.ts +1 -1
  20. package/dist/packages/events/src/index.d.ts +2 -0
  21. package/dist/packages/events/src/index.js +16 -0
  22. package/dist/packages/graph/src/index.d.ts +59 -3
  23. package/dist/packages/graph/src/index.js +139 -21
  24. package/dist/packages/mcp/src/index.d.ts +14 -0
  25. package/dist/packages/mcp/src/index.js +39 -5
  26. package/dist/packages/plugin-docker/src/index.d.ts +3 -0
  27. package/dist/packages/plugin-docker/src/index.js +13 -0
  28. package/dist/packages/plugin-github/src/index.d.ts +3 -0
  29. package/dist/packages/plugin-github/src/index.js +13 -0
  30. package/dist/packages/policy/src/index.d.ts +7 -0
  31. package/dist/packages/policy/src/index.js +17 -1
  32. package/dist/packages/runtime/src/index.d.ts +20 -1
  33. package/dist/packages/runtime/src/index.js +34 -1
  34. package/dist/packages/sandbox/src/index.d.ts +2 -0
  35. package/dist/packages/sandbox/src/index.js +10 -0
  36. package/dist/scripts/context-benchmark.d.ts +2 -0
  37. package/dist/scripts/context-benchmark.js +39 -0
  38. package/dist/scripts/demo-autonomy.d.ts +15 -0
  39. package/dist/scripts/demo-autonomy.js +200 -0
  40. package/dist/scripts/server-persistence-probe.d.mts +1 -0
  41. package/dist/scripts/server-persistence-probe.d.ts +1 -0
  42. package/dist/scripts/server-persistence-probe.js +52 -0
  43. package/dist/scripts/server-persistence-probe.mjs +52 -0
  44. package/docs/2x/CLI-CAPABILITIES.md +35 -0
  45. package/docs/2x/IMPLEMENTATION-AUDIT.md +40 -0
  46. package/docs/2x/SPRINT-1-CLI-CAPABILITY-PLAN.md +53 -0
  47. package/docs/2x/SPRINT-10-GRAPH-SYNC-PLAN.md +54 -0
  48. package/docs/2x/SPRINT-11-GRAPH-SYNC-CLI-MCP-PLAN.md +38 -0
  49. package/docs/2x/SPRINT-12-REAL-AUTONOMY-PLAN.md +40 -0
  50. package/docs/2x/SPRINT-13-MCP-STDIO-PLAN.md +26 -0
  51. package/docs/2x/SPRINT-14-SERVER-RESTART-PLAN.md +28 -0
  52. package/docs/2x/SPRINT-15-CHAOS-SECURITY-PLAN.md +22 -0
  53. package/docs/2x/SPRINT-16-LAST-MILE-PLAN.md +25 -0
  54. package/docs/2x/SPRINT-2-CLI-CAPABILITY-PLAN.md +39 -0
  55. package/docs/2x/SPRINT-3-RUNTIME-PERSISTENCE-PLAN.md +42 -0
  56. package/docs/2x/SPRINT-4-MCP-REGISTRY-PLAN.md +35 -0
  57. package/docs/2x/SPRINT-5-SERVER-APPROVALS-AUDIT-PLAN.md +31 -0
  58. package/docs/2x/SPRINT-6-EVENTS-E2E-PLAN.md +55 -0
  59. package/docs/2x/SPRINT-7-GRAPHLOOP-PERSISTENCE-PLAN.md +60 -0
  60. package/docs/2x/SPRINT-8-CONTEXT-GRAPH-PLAN.md +64 -0
  61. package/docs/2x/SPRINT-9-DETERMINISTIC-EXTRACTORS-PLAN.md +51 -0
  62. package/memory/50-orchestration/handoffs/2026-08-01_sprint-1-cli-capabilities.md +41 -0
  63. package/memory/50-orchestration/handoffs/2026-08-01_sprint-10-graph-sync.md +23 -0
  64. package/memory/50-orchestration/handoffs/2026-08-01_sprint-11-graph-sync-cli-mcp.md +22 -0
  65. package/memory/50-orchestration/handoffs/2026-08-01_sprint-12-real-autonomy.md +16 -0
  66. package/memory/50-orchestration/handoffs/2026-08-01_sprint-2-cli-capabilities.md +30 -0
  67. package/memory/50-orchestration/handoffs/2026-08-01_sprint-3-runtime-persistence.md +29 -0
  68. package/memory/50-orchestration/handoffs/2026-08-01_sprint-4-mcp.md +29 -0
  69. package/memory/50-orchestration/handoffs/2026-08-01_sprint-5-server-approvals-audit.md +22 -0
  70. package/memory/50-orchestration/handoffs/2026-08-01_sprint-6-events-e2e.md +25 -0
  71. package/memory/50-orchestration/handoffs/2026-08-01_sprint-7-graphloop.md +23 -0
  72. package/memory/50-orchestration/handoffs/2026-08-01_sprint-8-context-graph.md +23 -0
  73. package/memory/50-orchestration/handoffs/2026-08-01_sprint-9-extractors.md +21 -0
  74. package/memory/50-orchestration/handoffs/2026-08-02_sprint-13-mcp-stdio.md +14 -0
  75. package/memory/50-orchestration/handoffs/2026-08-02_sprint-14-server-restart.md +15 -0
  76. package/memory/50-orchestration/handoffs/2026-08-02_sprint-15-chaos-security.md +13 -0
  77. package/memory/50-orchestration/handoffs/2026-08-02_sprint-16-last-mile.md +11 -0
  78. package/memory/90-decisions/0059-cli-adapter-capability-registry.md +17 -0
  79. package/memory/90-decisions/0060-runtime-persistence-port.md +17 -0
  80. package/memory/90-decisions/0061-mcp-dynamic-registry-stdio.md +16 -0
  81. package/memory/90-decisions/0062-server-catalog-approval-audit.md +17 -0
  82. package/memory/90-decisions/0063-events-persistent-e2e.md +19 -0
  83. package/memory/90-decisions/0064-graphloop-sqlite-store.md +20 -0
  84. package/memory/90-decisions/0065-context-graph-source-cache.md +20 -0
  85. package/memory/90-decisions/0066-graph-deterministic-extractors.md +16 -0
  86. package/memory/90-decisions/0067-graph-sync-capability.md +17 -0
  87. package/memory/90-decisions/0068-graph-sync-cli-mcp.md +17 -0
  88. package/memory/90-decisions/0069-real-autonomy-demo.md +16 -0
  89. package/memory/90-decisions/0070-mcp-stdio-real.md +11 -0
  90. package/memory/90-decisions/0071-server-persistence-composition.md +12 -0
  91. package/memory/90-decisions/0072-sandbox-security-boundaries.md +9 -0
  92. package/memory/90-decisions/0073-last-mile-rollback-benchmark-plugins.md +17 -0
  93. package/package.json +13 -3
@@ -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) {
@@ -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;
@@ -38,10 +38,12 @@ export declare class EventBus {
38
38
  private readonly consumerIdempotency;
39
39
  private readonly sequences;
40
40
  private readonly deadLetters;
41
+ private initialized?;
41
42
  constructor(store?: EventStore);
42
43
  subscribe(subscription: EventSubscription, handler: EventHandler): () => void;
43
44
  append(input: EventInput): Promise<DomainEvent>;
44
45
  list(): Promise<readonly DomainEvent[]>;
45
46
  getDeadLetters(): readonly DeadLetterEvent[];
46
47
  private dispatch;
48
+ private ensureInitialized;
47
49
  }
@@ -22,6 +22,7 @@ export class EventBus {
22
22
  consumerIdempotency = new Set();
23
23
  sequences = new Map();
24
24
  deadLetters = [];
25
+ initialized;
25
26
  constructor(store = new InMemoryEventStore()) {
26
27
  this.store = store;
27
28
  }
@@ -36,6 +37,7 @@ export class EventBus {
36
37
  return () => this.subscriptions.delete(subscription.id);
37
38
  }
38
39
  async append(input) {
40
+ await this.ensureInitialized();
39
41
  if (input.type.trim().length === 0)
40
42
  throw new EventBusError('Event type is required');
41
43
  if (input.idempotencyKey.trim().length === 0)
@@ -62,6 +64,7 @@ export class EventBus {
62
64
  return event;
63
65
  }
64
66
  async list() {
67
+ await this.ensureInitialized();
65
68
  return this.store.list();
66
69
  }
67
70
  getDeadLetters() {
@@ -93,4 +96,17 @@ export class EventBus {
93
96
  }
94
97
  }
95
98
  }
99
+ async ensureInitialized() {
100
+ if (this.initialized === undefined) {
101
+ this.initialized = (async () => {
102
+ for (const event of await this.store.list()) {
103
+ this.idempotency.set(event.idempotencyKey, event);
104
+ const current = this.sequences.get(event.aggregateId) ?? 0;
105
+ if (event.sequence > current)
106
+ this.sequences.set(event.aggregateId, event.sequence);
107
+ }
108
+ })();
109
+ }
110
+ await this.initialized;
111
+ }
96
112
  }
@@ -1,4 +1,4 @@
1
- import { type Contradiction, type EntityId, type Evidence, type GraphEdge, type GraphNode, type ISO8601, type KnowledgeStatus, type SuggestedAction } from '../../contracts/src/index.ts';
1
+ import { type Contradiction, type EntityId, type Evidence, type GraphEdge, type GraphNode, type ISO8601, type KnowledgeStatus, type RuntimeRun, type ExecutionResult, type SuggestedAction } from '../../contracts/src/index.ts';
2
2
  export interface GraphNodeSpec {
3
3
  readonly id: EntityId;
4
4
  readonly type: string;
@@ -41,18 +41,49 @@ export interface GraphImpact {
41
41
  readonly edges: readonly GraphEdge[];
42
42
  readonly depth: number;
43
43
  }
44
+ export interface GraphContextRecord {
45
+ readonly id: EntityId;
46
+ readonly locator: string;
47
+ readonly content: string;
48
+ readonly relevance: number;
49
+ readonly status: KnowledgeStatus;
50
+ readonly evidence: readonly Evidence[];
51
+ readonly checksum: string;
52
+ }
53
+ export interface GraphStore {
54
+ getNode(id: EntityId): GraphNode | undefined;
55
+ listNodes(): readonly GraphNode[];
56
+ saveNode(node: GraphNode): void;
57
+ getEdge(key: string): GraphEdge | undefined;
58
+ listEdges(): readonly GraphEdge[];
59
+ saveEdge(key: string, edge: GraphEdge): void;
60
+ getEvidence(id: EntityId): Evidence | undefined;
61
+ saveEvidence(item: Evidence): void;
62
+ getSourceChecksum(sourceKey: string): string | undefined;
63
+ saveSourceChecksum(sourceKey: string, checksum: string): void;
64
+ }
44
65
  export declare class GraphError extends Error {
45
66
  constructor(message: string);
46
67
  }
47
- export declare class InMemoryGraphStore {
68
+ export declare class InMemoryGraphStore implements GraphStore {
48
69
  readonly nodes: Map<EntityId, GraphNode>;
49
70
  readonly edges: Map<string, GraphEdge>;
50
71
  readonly evidence: Map<EntityId, Evidence>;
51
72
  readonly sources: Map<string, string>;
73
+ getNode(id: EntityId): GraphNode | undefined;
74
+ listNodes(): readonly GraphNode[];
75
+ saveNode(node: GraphNode): void;
76
+ getEdge(key: string): GraphEdge | undefined;
77
+ listEdges(): readonly GraphEdge[];
78
+ saveEdge(key: string, edge: GraphEdge): void;
79
+ getEvidence(id: EntityId): Evidence | undefined;
80
+ saveEvidence(item: Evidence): void;
81
+ getSourceChecksum(sourceKey: string): string | undefined;
82
+ saveSourceChecksum(sourceKey: string, checksum: string): void;
52
83
  }
53
84
  export declare class GraphLoop {
54
85
  private readonly store;
55
- constructor(store?: InMemoryGraphStore);
86
+ constructor(store?: GraphStore);
56
87
  addEvidence(item: Evidence): void;
57
88
  upsertNode(spec: GraphNodeSpec): GraphNode;
58
89
  upsertEdge(spec: GraphEdgeSpec): GraphEdge;
@@ -66,15 +97,40 @@ export declare class GraphLoop {
66
97
  impact(origin: EntityId, depth?: number, direction?: 'outgoing' | 'incoming' | 'both', at?: ISO8601): GraphImpact;
67
98
  contradictions(at?: ISO8601): readonly Contradiction[];
68
99
  agenda(): readonly SuggestedAction[];
100
+ contextRecords(objective: string): readonly GraphContextRecord[];
69
101
  private activeEdges;
70
102
  private active;
71
103
  private edgeKey;
72
104
  private auditFields;
73
105
  }
106
+ /** Adapts runtime results into evidence-backed graph facts without importing runtime code. */
107
+ export declare class GraphExecutionMemory {
108
+ private readonly graph;
109
+ constructor(graph: GraphLoop);
110
+ remember(run: RuntimeRun, result: ExecutionResult): void;
111
+ }
74
112
  export interface DeterministicDocument {
75
113
  readonly nodeId: EntityId;
76
114
  readonly locator: string;
77
115
  readonly content: string;
78
116
  readonly capturedAt: ISO8601;
79
117
  }
118
+ export interface GraphDocumentSource {
119
+ listDocuments(): readonly DeterministicDocument[] | Promise<readonly DeterministicDocument[]>;
120
+ }
121
+ export interface GraphSyncResult {
122
+ readonly documents: number;
123
+ readonly indexed: number;
124
+ readonly skipped: number;
125
+ readonly nodes: number;
126
+ readonly edges: number;
127
+ readonly durationMs: number;
128
+ readonly files: readonly string[];
129
+ }
130
+ export declare class GraphIndexer {
131
+ private readonly graph;
132
+ constructor(graph: GraphLoop);
133
+ sync(source: GraphDocumentSource): Promise<GraphSyncResult>;
134
+ }
80
135
  export declare function extractDeterministicRelations(document: DeterministicDocument): GraphMutation;
136
+ export declare function graphDocumentId(locator: string): EntityId;
@@ -11,6 +11,16 @@ export class InMemoryGraphStore {
11
11
  edges = new Map();
12
12
  evidence = new Map();
13
13
  sources = new Map();
14
+ getNode(id) { return this.nodes.get(id); }
15
+ listNodes() { return [...this.nodes.values()]; }
16
+ saveNode(node) { this.nodes.set(node.id, node); }
17
+ getEdge(key) { return this.edges.get(key); }
18
+ listEdges() { return [...this.edges.values()]; }
19
+ saveEdge(key, edge) { this.edges.set(key, edge); }
20
+ getEvidence(id) { return this.evidence.get(id); }
21
+ saveEvidence(item) { this.evidence.set(item.id, item); }
22
+ getSourceChecksum(sourceKey) { return this.sources.get(sourceKey); }
23
+ saveSourceChecksum(sourceKey, checksum) { this.sources.set(sourceKey, checksum); }
14
24
  }
15
25
  export class GraphLoop {
16
26
  store;
@@ -18,34 +28,34 @@ export class GraphLoop {
18
28
  this.store = store;
19
29
  }
20
30
  addEvidence(item) {
21
- this.store.evidence.set(item.id, item);
31
+ this.store.saveEvidence(item);
22
32
  }
23
33
  upsertNode(spec) {
24
34
  if (spec.id.trim().length === 0 || spec.type.trim().length === 0 || spec.label.trim().length === 0)
25
35
  throw new GraphError('Graph node id, type and label are required');
26
- const current = this.store.nodes.get(spec.id);
36
+ const current = this.store.getNode(spec.id);
27
37
  const node = { ...this.auditFields(current?.correlationId ?? `node:${spec.id}`), ...spec };
28
- this.store.nodes.set(spec.id, node);
38
+ this.store.saveNode(node);
29
39
  return node;
30
40
  }
31
41
  upsertEdge(spec) {
32
- if (!this.store.nodes.has(spec.from) || !this.store.nodes.has(spec.to))
42
+ if (this.store.getNode(spec.from) === undefined || this.store.getNode(spec.to) === undefined)
33
43
  throw new GraphError('Graph edge endpoints must exist');
34
44
  if (spec.evidenceIds.length === 0)
35
45
  throw new GraphError('Graph edge requires at least one evidence id');
36
46
  for (const id of spec.evidenceIds)
37
- if (!this.store.evidence.has(id))
47
+ if (this.store.getEvidence(id) === undefined)
38
48
  throw new GraphError(`Graph edge evidence not found: ${id}`);
39
49
  if (!Number.isFinite(spec.confidence) || spec.confidence < 0 || spec.confidence > 1)
40
50
  throw new GraphError('Graph edge confidence must be between 0 and 1');
41
51
  const key = this.edgeKey(spec);
42
- const current = this.store.edges.get(key);
52
+ const current = this.store.getEdge(key);
43
53
  const edge = { ...this.auditFields(current?.correlationId ?? `edge:${key}`), ...spec, id: current?.id ?? spec.id ?? randomUUID() };
44
- this.store.edges.set(key, edge);
54
+ this.store.saveEdge(key, edge);
45
55
  return edge;
46
56
  }
47
57
  apply(mutation) {
48
- if (this.store.sources.get(mutation.sourceKey) === mutation.sourceChecksum)
58
+ if (this.store.getSourceChecksum(mutation.sourceKey) === mutation.sourceChecksum)
49
59
  return { nodes: 0, edges: 0, skipped: true };
50
60
  for (const item of mutation.evidence)
51
61
  this.addEvidence(item);
@@ -53,11 +63,11 @@ export class GraphLoop {
53
63
  this.upsertNode(item);
54
64
  for (const item of mutation.edges)
55
65
  this.upsertEdge(item);
56
- this.store.sources.set(mutation.sourceKey, mutation.sourceChecksum);
66
+ this.store.saveSourceChecksum(mutation.sourceKey, mutation.sourceChecksum);
57
67
  return { nodes: mutation.nodes.length, edges: mutation.edges.length, skipped: false };
58
68
  }
59
69
  query(query = {}) {
60
- return [...this.store.nodes.values()]
70
+ return [...this.store.listNodes()]
61
71
  .filter((node) => query.type === undefined || node.type === query.type)
62
72
  .filter((node) => query.status === undefined || node.status === query.status)
63
73
  .filter((node) => query.labelIncludes === undefined || node.label.toLowerCase().includes(query.labelIncludes.toLowerCase()))
@@ -65,7 +75,7 @@ export class GraphLoop {
65
75
  .sort((left, right) => left.id.localeCompare(right.id));
66
76
  }
67
77
  path(from, to, maxDepth = 5, at) {
68
- if (!this.store.nodes.has(from) || !this.store.nodes.has(to))
78
+ if (this.store.getNode(from) === undefined || this.store.getNode(to) === undefined)
69
79
  return undefined;
70
80
  const queue = [{ id: from, nodePath: [from], edgePath: [] }];
71
81
  const visited = new Set([from]);
@@ -74,7 +84,7 @@ export class GraphLoop {
74
84
  if (current === undefined)
75
85
  break;
76
86
  if (current.id === to)
77
- return { nodes: current.nodePath.map((id) => this.store.nodes.get(id)).filter((node) => node !== undefined), edges: current.edgePath };
87
+ return { nodes: current.nodePath.map((id) => this.store.getNode(id)).filter((node) => node !== undefined), edges: current.edgePath };
78
88
  if (current.edgePath.length >= maxDepth)
79
89
  continue;
80
90
  for (const edge of this.activeEdges(at)) {
@@ -87,7 +97,7 @@ export class GraphLoop {
87
97
  return undefined;
88
98
  }
89
99
  impact(origin, depth = 2, direction = 'outgoing', at) {
90
- const root = this.store.nodes.get(origin);
100
+ const root = this.store.getNode(origin);
91
101
  if (root === undefined)
92
102
  throw new GraphError(`Graph node not found: ${origin}`);
93
103
  const nodes = new Map([[origin, root]]);
@@ -101,7 +111,7 @@ export class GraphLoop {
101
111
  if (!forward && !backward)
102
112
  continue;
103
113
  const target = forward ? edge.to : edge.from;
104
- const node = this.store.nodes.get(target);
114
+ const node = this.store.getNode(target);
105
115
  if (node !== undefined) {
106
116
  nodes.set(target, node);
107
117
  next.add(target);
@@ -116,12 +126,34 @@ export class GraphLoop {
116
126
  return this.activeEdges(at, true).filter((edge) => edge.type === 'CONTRADICTS').map((edge) => ({ id: edge.id, claimIds: [edge.from, edge.to], reason: 'Contradictory relation recorded in GraphLoop', evidenceIds: edge.evidenceIds }));
117
127
  }
118
128
  agenda() {
119
- return [...this.store.nodes.values()]
129
+ return [...this.store.listNodes()]
120
130
  .filter((node) => !this.activeEdges().some((edge) => edge.from === node.id || edge.to === node.id))
121
131
  .map((node) => ({ id: randomUUID(), reason: `Graph node has no relation: ${node.label}`, priority: 50, risk: 'low', dependencyIds: [], evidenceIds: [], approvalRequired: false }));
122
132
  }
133
+ contextRecords(objective) {
134
+ const terms = objective.toLowerCase().split(/[^a-z0-9_./-]+/).filter((term) => term.length > 1);
135
+ const records = this.activeEdges()
136
+ .map((edge) => {
137
+ const from = this.store.getNode(edge.from);
138
+ const to = this.store.getNode(edge.to);
139
+ if (from === undefined || to === undefined)
140
+ return undefined;
141
+ const content = `${from.label} ${edge.type} ${to.label}`;
142
+ const haystack = content.toLowerCase();
143
+ const matches = terms.filter((term) => haystack.includes(term)).length;
144
+ if (matches === 0)
145
+ return undefined;
146
+ const evidence = edge.evidenceIds.map((id) => this.store.getEvidence(id)).filter((item) => item !== undefined);
147
+ if (evidence.length === 0)
148
+ return undefined;
149
+ return { id: edge.id, locator: `graph:${edge.id}`, content, relevance: matches / Math.max(1, terms.length), status: edge.status, evidence: evidence, checksum: createHash('sha256').update(`${edge.id}:${edge.updatedAt}:${content}`).digest('hex') };
150
+ });
151
+ return records
152
+ .filter((record) => record !== undefined)
153
+ .sort((left, right) => right.relevance - left.relevance || left.locator.localeCompare(right.locator));
154
+ }
123
155
  activeEdges(at, includeContradicted = false) {
124
- return [...this.store.edges.values()].filter((edge) => (includeContradicted || edge.status !== 'contradicted') && this.active(edge.validFrom, edge.validTo, at));
156
+ return [...this.store.listEdges()].filter((edge) => (includeContradicted || edge.status !== 'contradicted') && this.active(edge.validFrom, edge.validTo, at));
125
157
  }
126
158
  active(validFrom, validTo, at) {
127
159
  const point = at ?? new Date().toISOString();
@@ -135,14 +167,57 @@ export class GraphLoop {
135
167
  return { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId };
136
168
  }
137
169
  }
170
+ /** Adapts runtime results into evidence-backed graph facts without importing runtime code. */
171
+ export class GraphExecutionMemory {
172
+ graph;
173
+ constructor(graph) { this.graph = graph; }
174
+ remember(run, result) {
175
+ const executionId = `execution:${run.runId}`;
176
+ const capability = result.output?.capabilityId ?? 'unknown';
177
+ const capabilityId = `capability:${capability}`;
178
+ this.graph.upsertNode({ id: executionId, type: 'Execution', label: run.objective, status: result.status === 'succeeded' ? 'verified' : 'unknown' });
179
+ this.graph.upsertNode({ id: capabilityId, type: 'Capability', label: capability, status: 'verified' });
180
+ for (const item of result.evidence)
181
+ this.graph.addEvidence(item);
182
+ if (result.evidence.length > 0)
183
+ this.graph.upsertEdge({ from: executionId, to: capabilityId, type: 'PRODUCES', status: result.status === 'succeeded' ? 'verified' : 'unknown', confidence: result.status === 'succeeded' ? 1 : 0.5, evidenceIds: result.evidence.map((item) => item.id) });
184
+ }
185
+ }
186
+ export class GraphIndexer {
187
+ graph;
188
+ constructor(graph) { this.graph = graph; }
189
+ async sync(source) {
190
+ const started = Date.now();
191
+ const documents = await source.listDocuments();
192
+ let indexed = 0;
193
+ let skipped = 0;
194
+ let nodes = 0;
195
+ let edges = 0;
196
+ for (const document of documents) {
197
+ const result = this.graph.apply(extractDeterministicRelations(document));
198
+ if (result.skipped)
199
+ skipped += 1;
200
+ else {
201
+ indexed += 1;
202
+ nodes += result.nodes;
203
+ edges += result.edges;
204
+ }
205
+ }
206
+ return { documents: documents.length, indexed, skipped, nodes, edges, durationMs: Date.now() - started, files: documents.map((document) => document.locator) };
207
+ }
208
+ }
138
209
  export function extractDeterministicRelations(document) {
139
210
  const evidence = [];
140
211
  const nodes = new Map();
141
212
  const edges = [];
142
- const addRelation = (target, type, line) => {
143
- const targetId = stableId(`${type}:${target}`);
144
- const evidenceId = stableId(`evidence:${document.locator}:${line}:${type}:${target}`);
145
- nodes.set(targetId, { id: targetId, type: type === 'DEPENDS_ON' ? 'File' : 'Document', label: target, status: 'verified' });
213
+ nodes.set(document.nodeId, { id: document.nodeId, type: document.locator.endsWith('package.json') ? 'Project' : document.locator.endsWith('.md') ? 'Document' : 'File', label: document.locator, status: 'verified' });
214
+ const addRelation = (target, type, line, targetType = 'Document') => {
215
+ const normalizedTarget = target.trim();
216
+ if (normalizedTarget.length === 0)
217
+ return;
218
+ const targetId = stableId(`${type}:${normalizedTarget}`);
219
+ const evidenceId = stableId(`evidence:${document.locator}:${line}:${type}:${normalizedTarget}`);
220
+ nodes.set(targetId, { id: targetId, type: targetType, label: normalizedTarget, status: 'verified' });
146
221
  evidence.push({ id: evidenceId, source: 'deterministic-extractor', locator: `${document.locator}:${line}`, capturedAt: document.capturedAt, status: 'verified' });
147
222
  edges.push({ from: document.nodeId, to: targetId, type, status: 'verified', confidence: 1, evidenceIds: [evidenceId] });
148
223
  };
@@ -150,14 +225,57 @@ export function extractDeterministicRelations(document) {
150
225
  lines.forEach((line, index) => {
151
226
  const importMatch = line.match(/(?:from\s*|import\s*\()(['"])([^'"]+)\1/);
152
227
  if (importMatch?.[2] !== undefined)
153
- addRelation(importMatch[2], 'DEPENDS_ON', index + 1);
228
+ addRelation(importMatch[2], 'DEPENDS_ON', index + 1, 'File');
154
229
  const linkMatch = line.match(/\[[^\]]+\]\(([^)#]+)(?:#[^)]*)?\)/);
155
230
  if (linkMatch?.[1] !== undefined)
156
231
  addRelation(linkMatch[1], 'DERIVED_FROM', index + 1);
232
+ const exportMatch = line.match(/\bexport\s+(?:default\s+)?(?:declare\s+)?(?:class|function|const|let|var|interface|type|enum)\s+([A-Za-z_$][\w$]*)/);
233
+ if (exportMatch?.[1] !== undefined)
234
+ addRelation(exportMatch[1], 'DEFINES', index + 1, 'Symbol');
235
+ const implementsMatch = line.match(/\bimplements\s+([A-Za-z_$][\w$]*)/);
236
+ if (implementsMatch?.[1] !== undefined)
237
+ addRelation(implementsMatch[1], 'IMPLEMENTS', index + 1, 'Symbol');
238
+ const adrMatches = line.match(/\bADR-\d{4}\b/g) ?? [];
239
+ for (const adr of adrMatches)
240
+ addRelation(adr, 'DERIVED_FROM', index + 1, 'ADR');
241
+ const taskMatch = line.match(/^\s*-\s*\[[ xX]\]\s+(.+)$/);
242
+ if (taskMatch?.[1] !== undefined)
243
+ addRelation(taskMatch[1], 'CONTAINS', index + 1, 'Task');
244
+ const handoffAgentMatch = line.match(/^\s*-\s*\*\*(?:to|next agent)\*\*:\s*(.+)$/i);
245
+ if (handoffAgentMatch?.[1] !== undefined)
246
+ addRelation(handoffAgentMatch[1], 'ASSIGNED_TO', index + 1, 'Agent');
247
+ const testMatch = line.match(/\b(?:describe|it|test)\s*\(\s*['"]([^'"]+)['"]/);
248
+ if (testMatch?.[1] !== undefined)
249
+ addRelation(testMatch[1], 'VALIDATES', index + 1, 'Test');
250
+ const callMatches = [...line.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)];
251
+ for (const match of callMatches) {
252
+ const name = match[1];
253
+ if (name !== undefined && !new Set(['if', 'for', 'while', 'switch', 'catch', 'function', 'describe', 'it', 'test']).has(name))
254
+ addRelation(name, 'CALLS', index + 1, 'Symbol');
255
+ }
157
256
  });
257
+ if (document.locator.endsWith('package.json')) {
258
+ try {
259
+ const manifest = JSON.parse(document.content);
260
+ if (isRecord(manifest))
261
+ for (const field of ['dependencies', 'devDependencies', 'peerDependencies']) {
262
+ const dependencies = manifest[field];
263
+ if (isRecord(dependencies))
264
+ for (const name of Object.keys(dependencies))
265
+ addRelation(name, 'DEPENDS_ON', 1, 'Technology');
266
+ }
267
+ }
268
+ catch { /* Invalid manifests are handled by their own validator. */ }
269
+ }
158
270
  const sourceChecksum = createHash('sha256').update(document.content).digest('hex');
159
271
  return { sourceKey: document.locator, sourceChecksum, nodes: [...nodes.values()], evidence, edges };
160
272
  }
273
+ function isRecord(value) {
274
+ return typeof value === 'object' && value !== null;
275
+ }
161
276
  function stableId(value) {
162
277
  return createHash('sha256').update(value).digest('hex');
163
278
  }
279
+ export function graphDocumentId(locator) {
280
+ return stableId(`document:${locator}`);
281
+ }
@@ -58,6 +58,17 @@ export interface McpResource {
58
58
  readonly mimeType: string;
59
59
  readonly read: () => unknown | Promise<unknown>;
60
60
  }
61
+ export interface McpAuditEvent {
62
+ readonly action: 'mcp.tool';
63
+ readonly tool: string;
64
+ readonly agentId: EntityId;
65
+ readonly correlationId: string;
66
+ readonly outcome: 'success' | 'failure' | 'blocked';
67
+ readonly details: Readonly<Record<string, string>>;
68
+ }
69
+ export interface McpAuditSink {
70
+ append(event: McpAuditEvent): void | Promise<void>;
71
+ }
61
72
  export declare const MCP_RESOURCE_URIS: readonly ["forja://workspace/current", "forja://project/current", "forja://specs", "forja://decisions", "forja://graph", "forja://agent/agenda", "forja://executions"];
62
73
  export type McpResourceUri = typeof MCP_RESOURCE_URIS[number];
63
74
  export interface McpServerDependencies {
@@ -75,6 +86,7 @@ export interface McpServerDependencies {
75
86
  readonly mcpPolicy?: McpPolicy;
76
87
  readonly resources?: readonly McpResource[];
77
88
  readonly resourceData?: Readonly<Partial<Record<McpResourceUri, unknown>>>;
89
+ readonly audit?: McpAuditSink;
78
90
  }
79
91
  export declare class McpAdapterError extends Error {
80
92
  constructor(message: string);
@@ -90,6 +102,7 @@ export declare class McpServer {
90
102
  callTool(name: string, input?: unknown): Promise<McpToolResult>;
91
103
  readResource(uri: string): Promise<McpToolResult>;
92
104
  private dispatch;
105
+ private executeDynamicCapability;
93
106
  private createHandoff;
94
107
  private executeCapability;
95
108
  private authorize;
@@ -116,4 +129,5 @@ export declare class McpServer {
116
129
  private requireExecutionValidator;
117
130
  private success;
118
131
  private error;
132
+ private audit;
119
133
  }