forjajs 1.7.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +223 -217
  3. package/README.pt-BR.md +323 -0
  4. package/dist/apps/dashboard/app/api/forja/[...path]/route.d.ts +10 -0
  5. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +36 -0
  6. package/dist/apps/dashboard/app/api/forja/approval.d.ts +1 -0
  7. package/dist/apps/dashboard/app/api/forja/approval.js +8 -0
  8. package/dist/apps/dashboard/app/dashboard-client.d.ts +1 -0
  9. package/dist/apps/dashboard/app/dashboard-client.jsx +62 -0
  10. package/dist/apps/dashboard/app/layout.d.ts +9 -0
  11. package/dist/apps/dashboard/app/layout.jsx +7 -0
  12. package/dist/apps/dashboard/app/page.d.ts +1 -0
  13. package/dist/apps/dashboard/app/page.jsx +5 -0
  14. package/dist/apps/dashboard/app/providers.d.ts +4 -0
  15. package/dist/apps/dashboard/app/providers.jsx +7 -0
  16. package/dist/apps/dashboard/next.config.d.mts +6 -0
  17. package/dist/apps/dashboard/next.config.mjs +8 -0
  18. package/dist/apps/dashboard/src/index.d.ts +14 -0
  19. package/dist/apps/dashboard/src/index.js +16 -0
  20. package/dist/apps/server/src/app.module.d.ts +5 -0
  21. package/dist/apps/server/src/app.module.js +16 -0
  22. package/dist/apps/server/src/forja-nest.module.d.ts +59 -0
  23. package/dist/apps/server/src/forja-nest.module.js +316 -0
  24. package/dist/apps/server/src/index.d.ts +15 -0
  25. package/dist/apps/server/src/index.js +7 -0
  26. package/dist/apps/server/src/main.d.ts +12 -0
  27. package/dist/apps/server/src/main.js +105 -0
  28. package/dist/apps/worker/src/main.d.ts +12 -0
  29. package/dist/apps/worker/src/main.js +18 -0
  30. package/dist/lib/core/health.js +26 -4
  31. package/dist/packages/adapter-git/src/index.d.ts +27 -0
  32. package/dist/packages/adapter-git/src/index.js +53 -0
  33. package/dist/packages/adapter-nest/src/index.d.ts +71 -0
  34. package/dist/packages/adapter-nest/src/index.js +142 -0
  35. package/dist/packages/adapter-sqlite/src/index.d.ts +99 -0
  36. package/dist/packages/adapter-sqlite/src/index.js +108 -0
  37. package/dist/packages/context/src/index.d.ts +52 -0
  38. package/dist/packages/context/src/index.js +108 -0
  39. package/dist/packages/contracts/src/index.d.ts +368 -0
  40. package/dist/packages/contracts/src/index.js +27 -0
  41. package/dist/packages/core/src/index.d.ts +68 -0
  42. package/dist/packages/core/src/index.js +141 -0
  43. package/dist/packages/evals/src/index.d.ts +22 -0
  44. package/dist/packages/evals/src/index.js +65 -0
  45. package/dist/packages/events/src/index.d.ts +47 -0
  46. package/dist/packages/events/src/index.js +96 -0
  47. package/dist/packages/graph/src/index.d.ts +80 -0
  48. package/dist/packages/graph/src/index.js +163 -0
  49. package/dist/packages/mcp/src/index.d.ts +119 -0
  50. package/dist/packages/mcp/src/index.js +153 -0
  51. package/dist/packages/observability/src/index.d.ts +132 -0
  52. package/dist/packages/observability/src/index.js +86 -0
  53. package/dist/packages/orchestration/src/index.d.ts +122 -0
  54. package/dist/packages/orchestration/src/index.js +178 -0
  55. package/dist/packages/planner/src/index.d.ts +22 -0
  56. package/dist/packages/planner/src/index.js +70 -0
  57. package/dist/packages/plugin-sdk/src/index.d.ts +56 -0
  58. package/dist/packages/plugin-sdk/src/index.js +55 -0
  59. package/dist/packages/policy/src/index.d.ts +80 -0
  60. package/dist/packages/policy/src/index.js +136 -0
  61. package/dist/packages/runtime/src/index.d.ts +91 -0
  62. package/dist/packages/runtime/src/index.js +217 -0
  63. package/dist/packages/sandbox/src/index.d.ts +64 -0
  64. package/dist/packages/sandbox/src/index.js +108 -0
  65. package/dist/packages/scheduler/src/index.d.ts +56 -0
  66. package/dist/packages/scheduler/src/index.js +123 -0
  67. package/dist/packages/sdk/src/index.d.ts +122 -0
  68. package/dist/packages/sdk/src/index.js +40 -0
  69. package/dist/packages/validator/src/index.d.ts +36 -0
  70. package/dist/packages/validator/src/index.js +60 -0
  71. package/docs/architecture/FORJA-2.0-ARCHITECTURE.md +109 -0
  72. package/docs/architecture/FORJA-2.0-IMPACT-FOUNDATION.md +273 -0
  73. package/docs/security/FORJA-2.0-RELEASE-AUDIT-2026-08-01.md +95 -0
  74. package/docs/vision/FORJA-2.0-VISION.md +72 -0
  75. package/memory/50-orchestration/handoffs/2026-07-31_architect_foundation-contracts.md +15 -0
  76. package/memory/50-orchestration/handoffs/2026-07-31_backend-nest.md +22 -0
  77. package/memory/50-orchestration/handoffs/2026-07-31_context-engine.md +16 -0
  78. package/memory/50-orchestration/handoffs/2026-07-31_control-plane.md +28 -0
  79. package/memory/50-orchestration/handoffs/2026-07-31_core-capability-registry.md +15 -0
  80. package/memory/50-orchestration/handoffs/2026-07-31_evals-plugin-sdk.md +22 -0
  81. package/memory/50-orchestration/handoffs/2026-07-31_events-scheduler.md +16 -0
  82. package/memory/50-orchestration/handoffs/2026-07-31_graphloop.md +16 -0
  83. package/memory/50-orchestration/handoffs/2026-07-31_mcp.md +21 -0
  84. package/memory/50-orchestration/handoffs/2026-07-31_nest-bootstrap.md +28 -0
  85. package/memory/50-orchestration/handoffs/2026-07-31_next-dashboard.md +22 -0
  86. package/memory/50-orchestration/handoffs/2026-07-31_observability.md +27 -0
  87. package/memory/50-orchestration/handoffs/2026-07-31_orchestration.md +21 -0
  88. package/memory/50-orchestration/handoffs/2026-07-31_planner-validator.md +16 -0
  89. package/memory/50-orchestration/handoffs/2026-07-31_policy-engine.md +14 -0
  90. package/memory/50-orchestration/handoffs/2026-07-31_runtime-control-plane.md +23 -0
  91. package/memory/50-orchestration/handoffs/2026-07-31_runtime-controlado.md +15 -0
  92. package/memory/50-orchestration/handoffs/2026-07-31_sandbox.md +21 -0
  93. package/memory/50-orchestration/handoffs/2026-07-31_sdk.md +27 -0
  94. package/memory/50-orchestration/handoffs/2026-07-31_sqlite-adapter.md +21 -0
  95. package/memory/50-orchestration/handoffs/2026-07-31_worker-dashboard-boundary.md +23 -0
  96. package/memory/50-orchestration/handoffs/2026-08-01_approval-server-identity.md +23 -0
  97. package/memory/50-orchestration/handoffs/2026-08-01_dashboard-auth-query.md +24 -0
  98. package/memory/50-orchestration/handoffs/2026-08-01_graphloop-approvals.md +23 -0
  99. package/memory/90-decisions/0033-doctor-distingue-permissao-de-corrupcao.md +64 -0
  100. package/memory/90-decisions/0034-forja-2-core-e-contratos.md +29 -0
  101. package/memory/90-decisions/0035-forja-2-local-first-e-autonomia.md +23 -0
  102. package/memory/90-decisions/0036-forja-2-capability-registry.md +30 -0
  103. package/memory/90-decisions/0037-forja-2-policy-engine-obrigatorio.md +28 -0
  104. package/memory/90-decisions/0038-forja-2-runtime-controlado.md +28 -0
  105. package/memory/90-decisions/0039-forja-2-event-bus-scheduler-local-first.md +31 -0
  106. package/memory/90-decisions/0040-forja-2-context-engine-budget-cache.md +32 -0
  107. package/memory/90-decisions/0041-forja-2-graphloop-separado-codegraph.md +32 -0
  108. package/memory/90-decisions/0042-forja-2-planner-validator-independentes.md +29 -0
  109. package/memory/90-decisions/0043-forja-2-orchestration-entities.md +16 -0
  110. package/memory/90-decisions/0044-forja-2-sandbox-worktree.md +19 -0
  111. package/memory/90-decisions/0045-forja-2-sqlite-adapter.md +19 -0
  112. package/memory/90-decisions/0046-forja-2-mcp-adapter.md +18 -0
  113. package/memory/90-decisions/0047-forja-2-backend-nest-adapter.md +19 -0
  114. package/memory/90-decisions/0048-forja-2-sdk-transport.md +18 -0
  115. package/memory/90-decisions/0049-forja-2-observability-control-plane.md +18 -0
  116. package/memory/90-decisions/0050-forja-2-control-plane-application-ports.md +18 -0
  117. package/memory/90-decisions/0051-forja-2-runtime-control-plane-composition.md +18 -0
  118. package/memory/90-decisions/0052-forja-2-deterministic-evaluation.md +15 -0
  119. package/memory/90-decisions/0053-forja-2-plugin-sdk-permissionado.md +16 -0
  120. package/memory/90-decisions/0054-forja-2-worker-dashboard-boundary.md +15 -0
  121. package/memory/90-decisions/0055-forja-2-next-dashboard-distribution.md +16 -0
  122. package/memory/90-decisions/0056-forja-2-dashboard-proxy-auth-query.md +16 -0
  123. package/memory/90-decisions/0057-forja-2-graphloop-approvals-dashboard.md +15 -0
  124. package/memory/90-decisions/0058-forja-2-approval-server-identity.md +15 -0
  125. package/package.json +28 -3
  126. package/README.en.md +0 -329
@@ -0,0 +1,65 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { CONTRACT_VERSION } from "../../contracts/src/index.js";
3
+ export class EvaluationError extends Error {
4
+ constructor(message) { super(message); this.name = 'EvaluationError'; }
5
+ }
6
+ export class EvaluationEngine {
7
+ source;
8
+ constructor(source) { this.source = source; }
9
+ async evaluate(input) {
10
+ const values = input.observations === undefined ? await this.source.list() : input.observations;
11
+ const selected = values.filter((value) => this.matches(value, input.scope, input.scopeId));
12
+ const metrics = this.metrics(selected);
13
+ const evidenceIds = selected.map((value) => value.id);
14
+ const now = new Date().toISOString();
15
+ return {
16
+ schemaVersion: CONTRACT_VERSION, id: randomUUID(), createdAt: now, updatedAt: now,
17
+ correlationId: input.correlationId ?? `evaluation:${input.scope}:${input.scopeId ?? 'all'}`,
18
+ scope: input.scope, scopeId: input.scopeId, observationIds: evidenceIds, metrics,
19
+ findings: Object.entries(metrics).map(([name, value]) => ({ name, value, evidenceIds })),
20
+ };
21
+ }
22
+ matches(value, scope, scopeId) {
23
+ if (scopeId === undefined || scope === 'workspace' || scope === 'strategy')
24
+ return true;
25
+ const candidate = scope === 'run' ? value.runId : scope === 'agent' ? value.agentId : scope === 'task' ? value.taskId : scope === 'sprint' ? value.sprintId : scope === 'capability' ? value.capabilityId : scope === 'model' ? value.model : undefined;
26
+ return candidate === scopeId;
27
+ }
28
+ metrics(values) {
29
+ const total = values.length;
30
+ const succeeded = values.filter((value) => value.outcome === 'succeeded').length;
31
+ const repeatedInputs = this.repeatedInputCount(values);
32
+ const taskIds = new Set(values.map((value) => value.taskId).filter((value) => value !== undefined));
33
+ const evidenceFree = values.filter((value) => value.contextRefs.length === 0 && value.inputHash === undefined).length;
34
+ const rollbacks = values.filter((value) => value.errorCode?.toUpperCase() === 'ROLLBACK').length;
35
+ const contextUsed = values.filter((value) => value.contextRefs.length > 0).length;
36
+ const useless = values.filter((value) => value.inputTokens === 0 && value.outputTokens === 0 && value.durationMs === 0).length;
37
+ return {
38
+ observationCount: total,
39
+ successRate: this.rate(succeeded, total),
40
+ reworkRate: this.rate(repeatedInputs, total),
41
+ tokensPerTask: taskIds.size === 0 ? 0 : values.reduce((sum, value) => sum + value.inputTokens + value.outputTokens, 0) / taskIds.size,
42
+ uselessStepRate: this.rate(useless, total),
43
+ cacheHitRate: this.rate(repeatedInputs, total),
44
+ assertionsWithoutEvidenceRate: this.rate(evidenceFree, total),
45
+ rollbackRate: this.rate(rollbacks, total),
46
+ contextUtilizationRate: this.rate(contextUsed, total),
47
+ totalInputTokens: values.reduce((sum, value) => sum + value.inputTokens, 0),
48
+ totalOutputTokens: values.reduce((sum, value) => sum + value.outputTokens, 0),
49
+ totalCost: values.reduce((sum, value) => sum + (value.cost ?? 0), 0),
50
+ };
51
+ }
52
+ repeatedInputCount(values) {
53
+ const seen = new Set();
54
+ let repeated = 0;
55
+ for (const value of values)
56
+ if (value.inputHash !== undefined) {
57
+ if (seen.has(value.inputHash))
58
+ repeated += 1;
59
+ else
60
+ seen.add(value.inputHash);
61
+ }
62
+ return repeated;
63
+ }
64
+ rate(value, total) { return total === 0 ? 0 : value / total; }
65
+ }
@@ -0,0 +1,47 @@
1
+ import { type DomainEvent, type EntityId, type ISO8601 } from '../../contracts/src/index.ts';
2
+ export interface EventInput {
3
+ readonly type: string;
4
+ readonly aggregateId: EntityId;
5
+ readonly payload: unknown;
6
+ readonly idempotencyKey: string;
7
+ readonly correlationId?: string;
8
+ }
9
+ export interface EventStore {
10
+ append(event: DomainEvent): void | Promise<void>;
11
+ list(): readonly DomainEvent[] | Promise<readonly DomainEvent[]>;
12
+ }
13
+ export interface EventSubscription {
14
+ readonly id: string;
15
+ readonly eventTypes: readonly string[];
16
+ readonly maxRetries: number;
17
+ }
18
+ export interface DeadLetterEvent {
19
+ readonly event: DomainEvent;
20
+ readonly consumerId: string;
21
+ readonly attempts: number;
22
+ readonly error: string;
23
+ readonly failedAt: ISO8601;
24
+ }
25
+ export type EventHandler = (event: DomainEvent) => void | Promise<void>;
26
+ export declare class EventBusError extends Error {
27
+ constructor(message: string);
28
+ }
29
+ export declare class InMemoryEventStore implements EventStore {
30
+ private readonly events;
31
+ append(event: DomainEvent): void;
32
+ list(): readonly DomainEvent[];
33
+ }
34
+ export declare class EventBus {
35
+ private readonly store;
36
+ private readonly subscriptions;
37
+ private readonly idempotency;
38
+ private readonly consumerIdempotency;
39
+ private readonly sequences;
40
+ private readonly deadLetters;
41
+ constructor(store?: EventStore);
42
+ subscribe(subscription: EventSubscription, handler: EventHandler): () => void;
43
+ append(input: EventInput): Promise<DomainEvent>;
44
+ list(): Promise<readonly DomainEvent[]>;
45
+ getDeadLetters(): readonly DeadLetterEvent[];
46
+ private dispatch;
47
+ }
@@ -0,0 +1,96 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { CONTRACT_VERSION, } from "../../contracts/src/index.js";
3
+ export class EventBusError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'EventBusError';
7
+ }
8
+ }
9
+ export class InMemoryEventStore {
10
+ events = [];
11
+ append(event) {
12
+ this.events.push(event);
13
+ }
14
+ list() {
15
+ return [...this.events];
16
+ }
17
+ }
18
+ export class EventBus {
19
+ store;
20
+ subscriptions = new Map();
21
+ idempotency = new Map();
22
+ consumerIdempotency = new Set();
23
+ sequences = new Map();
24
+ deadLetters = [];
25
+ constructor(store = new InMemoryEventStore()) {
26
+ this.store = store;
27
+ }
28
+ subscribe(subscription, handler) {
29
+ if (subscription.id.trim().length === 0)
30
+ throw new EventBusError('Subscription id is required');
31
+ if (subscription.maxRetries < 0 || !Number.isInteger(subscription.maxRetries))
32
+ throw new EventBusError('Subscription maxRetries must be a non-negative integer');
33
+ if (this.subscriptions.has(subscription.id))
34
+ throw new EventBusError(`Subscription already exists: ${subscription.id}`);
35
+ this.subscriptions.set(subscription.id, { subscription, handler });
36
+ return () => this.subscriptions.delete(subscription.id);
37
+ }
38
+ async append(input) {
39
+ if (input.type.trim().length === 0)
40
+ throw new EventBusError('Event type is required');
41
+ if (input.idempotencyKey.trim().length === 0)
42
+ throw new EventBusError('Event idempotencyKey is required');
43
+ const existing = this.idempotency.get(input.idempotencyKey);
44
+ if (existing !== undefined)
45
+ return existing;
46
+ const event = {
47
+ schemaVersion: CONTRACT_VERSION,
48
+ id: randomUUID(),
49
+ type: input.type,
50
+ aggregateId: input.aggregateId,
51
+ sequence: (this.sequences.get(input.aggregateId) ?? 0) + 1,
52
+ payload: input.payload,
53
+ idempotencyKey: input.idempotencyKey,
54
+ correlationId: input.correlationId ?? input.idempotencyKey,
55
+ createdAt: new Date().toISOString(),
56
+ updatedAt: new Date().toISOString(),
57
+ };
58
+ this.sequences.set(input.aggregateId, event.sequence);
59
+ this.idempotency.set(input.idempotencyKey, event);
60
+ await this.store.append(event);
61
+ await this.dispatch(event);
62
+ return event;
63
+ }
64
+ async list() {
65
+ return this.store.list();
66
+ }
67
+ getDeadLetters() {
68
+ return [...this.deadLetters];
69
+ }
70
+ async dispatch(event) {
71
+ for (const { subscription, handler } of this.subscriptions.values()) {
72
+ if (!subscription.eventTypes.includes('*') && !subscription.eventTypes.includes(event.type))
73
+ continue;
74
+ const consumerKey = `${subscription.id}:${event.idempotencyKey}`;
75
+ if (this.consumerIdempotency.has(consumerKey))
76
+ continue;
77
+ let attempts = 0;
78
+ let succeeded = false;
79
+ let lastError = 'Unknown consumer error';
80
+ while (!succeeded && attempts <= subscription.maxRetries) {
81
+ attempts += 1;
82
+ try {
83
+ await handler(event);
84
+ this.consumerIdempotency.add(consumerKey);
85
+ succeeded = true;
86
+ }
87
+ catch (error) {
88
+ lastError = error instanceof Error ? error.message : 'Unknown consumer error';
89
+ }
90
+ }
91
+ if (!succeeded) {
92
+ this.deadLetters.push({ event, consumerId: subscription.id, attempts, error: lastError, failedAt: new Date().toISOString() });
93
+ }
94
+ }
95
+ }
96
+ }
@@ -0,0 +1,80 @@
1
+ import { type Contradiction, type EntityId, type Evidence, type GraphEdge, type GraphNode, type ISO8601, type KnowledgeStatus, type SuggestedAction } from '../../contracts/src/index.ts';
2
+ export interface GraphNodeSpec {
3
+ readonly id: EntityId;
4
+ readonly type: string;
5
+ readonly label: string;
6
+ readonly status: KnowledgeStatus;
7
+ readonly validFrom?: ISO8601;
8
+ readonly validTo?: ISO8601;
9
+ }
10
+ export interface GraphEdgeSpec {
11
+ readonly id?: EntityId;
12
+ readonly from: EntityId;
13
+ readonly to: EntityId;
14
+ readonly type: string;
15
+ readonly status: KnowledgeStatus;
16
+ readonly confidence: number;
17
+ readonly evidenceIds: readonly EntityId[];
18
+ readonly validFrom?: ISO8601;
19
+ readonly validTo?: ISO8601;
20
+ }
21
+ export interface GraphMutation {
22
+ readonly sourceKey: string;
23
+ readonly sourceChecksum: string;
24
+ readonly nodes: readonly GraphNodeSpec[];
25
+ readonly evidence: readonly Evidence[];
26
+ readonly edges: readonly GraphEdgeSpec[];
27
+ }
28
+ export interface GraphQuery {
29
+ readonly type?: string;
30
+ readonly status?: KnowledgeStatus;
31
+ readonly labelIncludes?: string;
32
+ readonly at?: ISO8601;
33
+ }
34
+ export interface GraphPath {
35
+ readonly nodes: readonly GraphNode[];
36
+ readonly edges: readonly GraphEdge[];
37
+ }
38
+ export interface GraphImpact {
39
+ readonly origin: GraphNode;
40
+ readonly nodes: readonly GraphNode[];
41
+ readonly edges: readonly GraphEdge[];
42
+ readonly depth: number;
43
+ }
44
+ export declare class GraphError extends Error {
45
+ constructor(message: string);
46
+ }
47
+ export declare class InMemoryGraphStore {
48
+ readonly nodes: Map<EntityId, GraphNode>;
49
+ readonly edges: Map<string, GraphEdge>;
50
+ readonly evidence: Map<EntityId, Evidence>;
51
+ readonly sources: Map<string, string>;
52
+ }
53
+ export declare class GraphLoop {
54
+ private readonly store;
55
+ constructor(store?: InMemoryGraphStore);
56
+ addEvidence(item: Evidence): void;
57
+ upsertNode(spec: GraphNodeSpec): GraphNode;
58
+ upsertEdge(spec: GraphEdgeSpec): GraphEdge;
59
+ apply(mutation: GraphMutation): {
60
+ readonly nodes: number;
61
+ readonly edges: number;
62
+ readonly skipped: boolean;
63
+ };
64
+ query(query?: GraphQuery): readonly GraphNode[];
65
+ path(from: EntityId, to: EntityId, maxDepth?: number, at?: ISO8601): GraphPath | undefined;
66
+ impact(origin: EntityId, depth?: number, direction?: 'outgoing' | 'incoming' | 'both', at?: ISO8601): GraphImpact;
67
+ contradictions(at?: ISO8601): readonly Contradiction[];
68
+ agenda(): readonly SuggestedAction[];
69
+ private activeEdges;
70
+ private active;
71
+ private edgeKey;
72
+ private auditFields;
73
+ }
74
+ export interface DeterministicDocument {
75
+ readonly nodeId: EntityId;
76
+ readonly locator: string;
77
+ readonly content: string;
78
+ readonly capturedAt: ISO8601;
79
+ }
80
+ export declare function extractDeterministicRelations(document: DeterministicDocument): GraphMutation;
@@ -0,0 +1,163 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { CONTRACT_VERSION, } from "../../contracts/src/index.js";
3
+ export class GraphError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'GraphError';
7
+ }
8
+ }
9
+ export class InMemoryGraphStore {
10
+ nodes = new Map();
11
+ edges = new Map();
12
+ evidence = new Map();
13
+ sources = new Map();
14
+ }
15
+ export class GraphLoop {
16
+ store;
17
+ constructor(store = new InMemoryGraphStore()) {
18
+ this.store = store;
19
+ }
20
+ addEvidence(item) {
21
+ this.store.evidence.set(item.id, item);
22
+ }
23
+ upsertNode(spec) {
24
+ if (spec.id.trim().length === 0 || spec.type.trim().length === 0 || spec.label.trim().length === 0)
25
+ throw new GraphError('Graph node id, type and label are required');
26
+ const current = this.store.nodes.get(spec.id);
27
+ const node = { ...this.auditFields(current?.correlationId ?? `node:${spec.id}`), ...spec };
28
+ this.store.nodes.set(spec.id, node);
29
+ return node;
30
+ }
31
+ upsertEdge(spec) {
32
+ if (!this.store.nodes.has(spec.from) || !this.store.nodes.has(spec.to))
33
+ throw new GraphError('Graph edge endpoints must exist');
34
+ if (spec.evidenceIds.length === 0)
35
+ throw new GraphError('Graph edge requires at least one evidence id');
36
+ for (const id of spec.evidenceIds)
37
+ if (!this.store.evidence.has(id))
38
+ throw new GraphError(`Graph edge evidence not found: ${id}`);
39
+ if (!Number.isFinite(spec.confidence) || spec.confidence < 0 || spec.confidence > 1)
40
+ throw new GraphError('Graph edge confidence must be between 0 and 1');
41
+ const key = this.edgeKey(spec);
42
+ const current = this.store.edges.get(key);
43
+ const edge = { ...this.auditFields(current?.correlationId ?? `edge:${key}`), ...spec, id: current?.id ?? spec.id ?? randomUUID() };
44
+ this.store.edges.set(key, edge);
45
+ return edge;
46
+ }
47
+ apply(mutation) {
48
+ if (this.store.sources.get(mutation.sourceKey) === mutation.sourceChecksum)
49
+ return { nodes: 0, edges: 0, skipped: true };
50
+ for (const item of mutation.evidence)
51
+ this.addEvidence(item);
52
+ for (const item of mutation.nodes)
53
+ this.upsertNode(item);
54
+ for (const item of mutation.edges)
55
+ this.upsertEdge(item);
56
+ this.store.sources.set(mutation.sourceKey, mutation.sourceChecksum);
57
+ return { nodes: mutation.nodes.length, edges: mutation.edges.length, skipped: false };
58
+ }
59
+ query(query = {}) {
60
+ return [...this.store.nodes.values()]
61
+ .filter((node) => query.type === undefined || node.type === query.type)
62
+ .filter((node) => query.status === undefined || node.status === query.status)
63
+ .filter((node) => query.labelIncludes === undefined || node.label.toLowerCase().includes(query.labelIncludes.toLowerCase()))
64
+ .filter((node) => this.active(node.validFrom, node.validTo, query.at))
65
+ .sort((left, right) => left.id.localeCompare(right.id));
66
+ }
67
+ path(from, to, maxDepth = 5, at) {
68
+ if (!this.store.nodes.has(from) || !this.store.nodes.has(to))
69
+ return undefined;
70
+ const queue = [{ id: from, nodePath: [from], edgePath: [] }];
71
+ const visited = new Set([from]);
72
+ while (queue.length > 0) {
73
+ const current = queue.shift();
74
+ if (current === undefined)
75
+ break;
76
+ if (current.id === to)
77
+ return { nodes: current.nodePath.map((id) => this.store.nodes.get(id)).filter((node) => node !== undefined), edges: current.edgePath };
78
+ if (current.edgePath.length >= maxDepth)
79
+ continue;
80
+ for (const edge of this.activeEdges(at)) {
81
+ if (edge.from !== current.id || visited.has(edge.to))
82
+ continue;
83
+ visited.add(edge.to);
84
+ queue.push({ id: edge.to, nodePath: [...current.nodePath, edge.to], edgePath: [...current.edgePath, edge] });
85
+ }
86
+ }
87
+ return undefined;
88
+ }
89
+ impact(origin, depth = 2, direction = 'outgoing', at) {
90
+ const root = this.store.nodes.get(origin);
91
+ if (root === undefined)
92
+ throw new GraphError(`Graph node not found: ${origin}`);
93
+ const nodes = new Map([[origin, root]]);
94
+ const edges = new Map();
95
+ let frontier = new Set([origin]);
96
+ for (let level = 0; level < depth; level += 1) {
97
+ const next = new Set();
98
+ for (const edge of this.activeEdges(at)) {
99
+ const forward = (direction === 'outgoing' || direction === 'both') && frontier.has(edge.from);
100
+ const backward = (direction === 'incoming' || direction === 'both') && frontier.has(edge.to);
101
+ if (!forward && !backward)
102
+ continue;
103
+ const target = forward ? edge.to : edge.from;
104
+ const node = this.store.nodes.get(target);
105
+ if (node !== undefined) {
106
+ nodes.set(target, node);
107
+ next.add(target);
108
+ edges.set(this.edgeKey(edge), edge);
109
+ }
110
+ }
111
+ frontier = next;
112
+ }
113
+ return { origin: root, nodes: [...nodes.values()], edges: [...edges.values()], depth };
114
+ }
115
+ contradictions(at) {
116
+ 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
+ }
118
+ agenda() {
119
+ return [...this.store.nodes.values()]
120
+ .filter((node) => !this.activeEdges().some((edge) => edge.from === node.id || edge.to === node.id))
121
+ .map((node) => ({ id: randomUUID(), reason: `Graph node has no relation: ${node.label}`, priority: 50, risk: 'low', dependencyIds: [], evidenceIds: [], approvalRequired: false }));
122
+ }
123
+ activeEdges(at, includeContradicted = false) {
124
+ return [...this.store.edges.values()].filter((edge) => (includeContradicted || edge.status !== 'contradicted') && this.active(edge.validFrom, edge.validTo, at));
125
+ }
126
+ active(validFrom, validTo, at) {
127
+ const point = at ?? new Date().toISOString();
128
+ return (validFrom === undefined || validFrom <= point) && (validTo === undefined || point < validTo);
129
+ }
130
+ edgeKey(edge) {
131
+ return `${edge.from}|${edge.to}|${edge.type}|${edge.validFrom ?? ''}`;
132
+ }
133
+ auditFields(correlationId) {
134
+ const now = new Date().toISOString();
135
+ return { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId };
136
+ }
137
+ }
138
+ export function extractDeterministicRelations(document) {
139
+ const evidence = [];
140
+ const nodes = new Map();
141
+ 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' });
146
+ evidence.push({ id: evidenceId, source: 'deterministic-extractor', locator: `${document.locator}:${line}`, capturedAt: document.capturedAt, status: 'verified' });
147
+ edges.push({ from: document.nodeId, to: targetId, type, status: 'verified', confidence: 1, evidenceIds: [evidenceId] });
148
+ };
149
+ const lines = document.content.split('\n');
150
+ lines.forEach((line, index) => {
151
+ const importMatch = line.match(/(?:from\s*|import\s*\()(['"])([^'"]+)\1/);
152
+ if (importMatch?.[2] !== undefined)
153
+ addRelation(importMatch[2], 'DEPENDS_ON', index + 1);
154
+ const linkMatch = line.match(/\[[^\]]+\]\(([^)#]+)(?:#[^)]*)?\)/);
155
+ if (linkMatch?.[1] !== undefined)
156
+ addRelation(linkMatch[1], 'DERIVED_FROM', index + 1);
157
+ });
158
+ const sourceChecksum = createHash('sha256').update(document.content).digest('hex');
159
+ return { sourceKey: document.locator, sourceChecksum, nodes: [...nodes.values()], evidence, edges };
160
+ }
161
+ function stableId(value) {
162
+ return createHash('sha256').update(value).digest('hex');
163
+ }
@@ -0,0 +1,119 @@
1
+ import type { CapabilityId, EntityId, PolicyDecision } from '../../contracts/src/index.ts';
2
+ import type { CapabilityPolicy, CapabilityRegistry } from '../../core/src/index.ts';
3
+ import type { ContextEngine } from '../../context/src/index.ts';
4
+ import type { GraphLoop } from '../../graph/src/index.ts';
5
+ import type { HandoffEngine, TaskEngine } from '../../orchestration/src/index.ts';
6
+ export interface McpInputSchema {
7
+ readonly type: 'object';
8
+ readonly properties: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
9
+ readonly required?: readonly string[];
10
+ readonly additionalProperties: false;
11
+ }
12
+ export interface McpToolDefinition {
13
+ readonly name: string;
14
+ readonly description: string;
15
+ readonly inputSchema: McpInputSchema;
16
+ }
17
+ export interface McpTextContent {
18
+ readonly type: 'text';
19
+ readonly text: string;
20
+ }
21
+ export interface McpToolResult {
22
+ readonly isError: boolean;
23
+ readonly content: readonly McpTextContent[];
24
+ readonly structuredContent: unknown;
25
+ }
26
+ export interface McpPolicy {
27
+ authorize(input: {
28
+ readonly action: string;
29
+ readonly category: string;
30
+ readonly risk: 'low' | 'medium' | 'high' | 'critical';
31
+ readonly files: readonly string[];
32
+ }): PolicyDecision;
33
+ }
34
+ export interface McpAgentContext {
35
+ readonly id: EntityId;
36
+ readonly name: string;
37
+ readonly role: string;
38
+ readonly autonomy: 'consultive' | 'assisted' | 'supervised' | 'controlled_autonomous';
39
+ readonly permissions: readonly string[];
40
+ readonly capabilities: readonly CapabilityId[];
41
+ }
42
+ export interface McpMemoryQuery {
43
+ query(objective: string): unknown | Promise<unknown>;
44
+ }
45
+ export interface McpSpecChecker {
46
+ check(input: Record<string, unknown>): unknown | Promise<unknown>;
47
+ }
48
+ export interface McpTestRunner {
49
+ run(input: Record<string, unknown>): unknown | Promise<unknown>;
50
+ }
51
+ export interface McpExecutionValidator {
52
+ validate(input: Record<string, unknown>): unknown | Promise<unknown>;
53
+ }
54
+ export interface McpResource {
55
+ readonly uri: string;
56
+ readonly name: string;
57
+ readonly description: string;
58
+ readonly mimeType: string;
59
+ readonly read: () => unknown | Promise<unknown>;
60
+ }
61
+ 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
+ export type McpResourceUri = typeof MCP_RESOURCE_URIS[number];
63
+ export interface McpServerDependencies {
64
+ readonly registry: CapabilityRegistry;
65
+ readonly policy: CapabilityPolicy;
66
+ readonly agent: McpAgentContext;
67
+ readonly context?: ContextEngine;
68
+ readonly graph?: GraphLoop;
69
+ readonly memory?: McpMemoryQuery;
70
+ readonly taskEngine?: TaskEngine;
71
+ readonly handoffEngine?: HandoffEngine;
72
+ readonly specChecker?: McpSpecChecker;
73
+ readonly testRunner?: McpTestRunner;
74
+ readonly executionValidator?: McpExecutionValidator;
75
+ readonly mcpPolicy?: McpPolicy;
76
+ readonly resources?: readonly McpResource[];
77
+ readonly resourceData?: Readonly<Partial<Record<McpResourceUri, unknown>>>;
78
+ }
79
+ export declare class McpAdapterError extends Error {
80
+ constructor(message: string);
81
+ }
82
+ export declare const MCP_TOOLS: readonly McpToolDefinition[];
83
+ export declare class McpServer {
84
+ private readonly dependencies;
85
+ private readonly tools;
86
+ private readonly resources;
87
+ constructor(dependencies: McpServerDependencies);
88
+ listTools(): readonly McpToolDefinition[];
89
+ listResources(): readonly McpResource[];
90
+ callTool(name: string, input?: unknown): Promise<McpToolResult>;
91
+ readResource(uri: string): Promise<McpToolResult>;
92
+ private dispatch;
93
+ private createHandoff;
94
+ private executeCapability;
95
+ private authorize;
96
+ private contextRequest;
97
+ private graphQuery;
98
+ private direction;
99
+ private budget;
100
+ private objectInput;
101
+ private requireFields;
102
+ private string;
103
+ private optionalString;
104
+ private strings;
105
+ private entity;
106
+ private entities;
107
+ private number;
108
+ private optionalStatus;
109
+ private requireContext;
110
+ private requireGraph;
111
+ private requireMemory;
112
+ private requireTasks;
113
+ private requireHandoffs;
114
+ private requireSpecChecker;
115
+ private requireTestRunner;
116
+ private requireExecutionValidator;
117
+ private success;
118
+ private error;
119
+ }