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
@@ -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
  }
@@ -13,6 +13,7 @@ export class McpAdapterError extends Error {
13
13
  export const MCP_TOOLS = [
14
14
  tool('forja_workspace_status', 'Retorna o estado operacional mínimo do workspace.', []),
15
15
  tool('forja_capabilities_list', 'Lista capabilities visíveis para a identidade MCP.', []),
16
+ tool('forja_capability_describe', 'Descreve uma capability pelo Registry.', ['capabilityId']),
16
17
  tool('forja_capability_execute', 'Executa uma capability pelo Registry com Policy e resultado auditável.', ['capabilityId']),
17
18
  tool('forja_context_build', 'Constrói contexto mínimo com orçamento e evidências.', ['objective', 'budget']),
18
19
  tool('forja_memory_query', 'Consulta memória por objetivo.', ['objective']),
@@ -32,6 +33,11 @@ export class McpServer {
32
33
  this.dependencies = dependencies;
33
34
  for (const definition of MCP_TOOLS)
34
35
  this.tools.set(definition.name, definition);
36
+ for (const definition of dependencies.registry.list({ agent: dependencies.agent, policy: dependencies.policy })) {
37
+ const name = capabilityToolName(definition.id);
38
+ if (!this.tools.has(name))
39
+ this.tools.set(name, capabilityTool(definition));
40
+ }
35
41
  for (const uri of MCP_RESOURCE_URIS)
36
42
  this.resources.set(uri, { uri, name: uri, description: `Forja resource ${uri}`, mimeType: 'application/json', read: () => dependencies.resourceData?.[uri] ?? { available: false, uri, reason: 'Resource provider is not configured' } });
37
43
  for (const resource of dependencies.resources ?? [])
@@ -41,16 +47,23 @@ export class McpServer {
41
47
  listResources() { return [...this.resources.values()]; }
42
48
  async callTool(name, input = {}) {
43
49
  const definition = this.tools.get(name);
44
- if (definition === undefined)
45
- return this.error('TOOL_NOT_FOUND', `MCP tool not found: ${name}`);
50
+ if (definition === undefined) {
51
+ const result = this.error('TOOL_NOT_FOUND', `MCP tool not found: ${name}`);
52
+ await this.audit(name, input, 'failure', result.structuredContent);
53
+ return result;
54
+ }
46
55
  try {
47
56
  const object = this.objectInput(input);
48
57
  this.requireFields(definition, object);
49
58
  const value = await this.dispatch(name, object);
50
- return this.success(value);
59
+ const result = this.success(value);
60
+ await this.audit(name, object, 'success');
61
+ return result;
51
62
  }
52
63
  catch (error) {
53
- return this.error('TOOL_FAILED', error instanceof Error ? error.message : 'Unknown MCP tool error');
64
+ const result = this.error('TOOL_FAILED', error instanceof Error ? error.message : 'Unknown MCP tool error');
65
+ await this.audit(name, input, 'failure', result.structuredContent);
66
+ return result;
54
67
  }
55
68
  }
56
69
  async readResource(uri) {
@@ -68,6 +81,7 @@ export class McpServer {
68
81
  switch (name) {
69
82
  case 'forja_workspace_status': return { agent: this.dependencies.agent, capabilities: this.dependencies.registry.list({ agent: this.dependencies.agent }), resources: this.listResources().map((resource) => resource.uri) };
70
83
  case 'forja_capabilities_list': return this.dependencies.registry.list({ agent: this.dependencies.agent, policy: this.dependencies.policy });
84
+ case 'forja_capability_describe': return this.dependencies.registry.describe(this.string(input, 'capabilityId'), { agent: this.dependencies.agent, policy: this.dependencies.policy });
71
85
  case 'forja_capability_execute': return this.executeCapability(input);
72
86
  case 'forja_context_build': return this.requireContext().build(this.contextRequest(input));
73
87
  case 'forja_memory_query': return this.requireMemory().query(this.string(input, 'objective'));
@@ -78,9 +92,16 @@ export class McpServer {
78
92
  case 'forja_spec_check': return this.requireSpecChecker().check(input);
79
93
  case 'forja_test_run': return this.requireTestRunner().run(input);
80
94
  case 'forja_execution_validate': return this.requireExecutionValidator().validate(input);
81
- default: throw new McpAdapterError(`MCP tool not implemented: ${name}`);
95
+ default:
96
+ if (name.startsWith('forja_capability_'))
97
+ return this.executeDynamicCapability(name, input);
98
+ throw new McpAdapterError(`MCP tool not implemented: ${name}`);
82
99
  }
83
100
  }
101
+ executeDynamicCapability(name, input) {
102
+ const capabilityId = name.slice('forja_capability_'.length).replace(/_/g, '.');
103
+ return this.executeCapability({ ...input, capabilityId });
104
+ }
84
105
  async createHandoff(input) {
85
106
  this.authorize('forja_handoff_create', 'write', 'medium', []);
86
107
  return this.requireHandoffs().create({
@@ -148,6 +169,19 @@ export class McpServer {
148
169
  throw new McpAdapterError('Execution validator is not configured'); return this.dependencies.executionValidator; }
149
170
  success(value) { return { isError: false, content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value }; }
150
171
  error(code, message) { const value = { code, message }; return { isError: true, content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value }; }
172
+ async audit(toolName, input, outcome, error) {
173
+ if (this.dependencies.audit === undefined)
174
+ return;
175
+ const correlationId = isRecord(input) && typeof input.correlationId === 'string' ? input.correlationId : `${this.dependencies.agent.id}:${toolName}`;
176
+ try {
177
+ await this.dependencies.audit.append({ action: 'mcp.tool', tool: toolName, agentId: this.dependencies.agent.id, correlationId, outcome, details: error === undefined ? {} : { error: JSON.stringify(error) } });
178
+ }
179
+ catch {
180
+ // Auditoria não pode derrubar o transporte MCP; o sink deve expor sua própria saúde.
181
+ }
182
+ }
151
183
  }
152
184
  function tool(name, description, required) { return { name, description, inputSchema: { type: 'object', properties: Object.fromEntries(required.map((field) => [field, { type: field === 'budget' ? 'object' : field.endsWith('Ids') ? 'array' : 'string' }])), required, additionalProperties: false } }; }
185
+ function capabilityToolName(id) { return `forja_capability_${id.replace(/[^a-zA-Z0-9_]/g, '_')}`; }
186
+ function capabilityTool(definition) { return { name: capabilityToolName(definition.id), description: `Executa ${definition.id}: ${definition.description}`, inputSchema: { type: 'object', properties: { payload: { type: 'object' }, correlationId: { type: 'string' }, files: { type: 'array' }, categories: { type: 'array' } }, additionalProperties: false } }; }
153
187
  function isRecord(value) { return typeof value === 'object' && value !== null; }
@@ -50,11 +50,18 @@ export interface ApprovalDecision {
50
50
  export interface ApprovalInput extends ApprovalDetails {
51
51
  readonly correlationId: string;
52
52
  }
53
+ export interface ApprovalStore {
54
+ save(request: ApprovalRequest): void;
55
+ get(id: EntityId): ApprovalRequest | undefined;
56
+ list(): readonly ApprovalRequest[];
57
+ }
53
58
  export declare class PolicyError extends Error {
54
59
  constructor(message: string);
55
60
  }
56
61
  export declare class ApprovalLedger {
57
62
  private readonly requests;
63
+ private readonly store?;
64
+ constructor(store?: ApprovalStore);
58
65
  create(input: ApprovalInput, now?: ISO8601): ApprovalRequest;
59
66
  list(): readonly ApprovalRequest[];
60
67
  decide(id: EntityId, decision: ApprovalDecision): ApprovalRequest;
@@ -8,6 +8,8 @@ export class PolicyError extends Error {
8
8
  }
9
9
  export class ApprovalLedger {
10
10
  requests = new Map();
11
+ store;
12
+ constructor(store) { this.store = store; }
11
13
  create(input, now = new Date().toISOString()) {
12
14
  if (input.action.trim().length === 0)
13
15
  throw new PolicyError('Approval action is required');
@@ -28,9 +30,14 @@ export class ApprovalLedger {
28
30
  updatedAt: now,
29
31
  };
30
32
  this.requests.set(request.id, request);
33
+ void this.store?.save(request);
31
34
  return request;
32
35
  }
33
- list() { return [...this.requests.values()].sort((left, right) => left.createdAt.localeCompare(right.createdAt)); }
36
+ list() {
37
+ if (this.store !== undefined)
38
+ return this.store.list();
39
+ return [...this.requests.values()].sort((left, right) => left.createdAt.localeCompare(right.createdAt));
40
+ }
34
41
  decide(id, decision) {
35
42
  const current = this.get(id);
36
43
  if (current.decision !== undefined)
@@ -39,6 +46,7 @@ export class ApprovalLedger {
39
46
  throw new PolicyError(`Approval expired: ${id}`);
40
47
  const updated = { ...current, decision: decision.decision, approverId: decision.approverId, updatedAt: decision.decidedAt };
41
48
  this.requests.set(id, updated);
49
+ void this.store?.save(updated);
42
50
  return updated;
43
51
  }
44
52
  expire(now) {
@@ -47,6 +55,7 @@ export class ApprovalLedger {
47
55
  if (current.decision === undefined && current.expiresAt <= now) {
48
56
  const updated = { ...current, decision: 'expired', updatedAt: now };
49
57
  this.requests.set(current.id, updated);
58
+ void this.store?.save(updated);
50
59
  expired.push(updated);
51
60
  }
52
61
  }
@@ -54,6 +63,13 @@ export class ApprovalLedger {
54
63
  }
55
64
  get(id) {
56
65
  const request = this.requests.get(id);
66
+ if (request === undefined && this.store !== undefined) {
67
+ const persisted = this.store.get(id);
68
+ if (persisted !== undefined) {
69
+ this.requests.set(id, persisted);
70
+ return persisted;
71
+ }
72
+ }
57
73
  if (request === undefined)
58
74
  throw new PolicyError(`Approval not found: ${id}`);
59
75
  return request;