forjajs 1.7.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +24 -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 +1 -1
  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/0034-forja-2-core-e-contratos.md +29 -0
  100. package/memory/90-decisions/0035-forja-2-local-first-e-autonomia.md +23 -0
  101. package/memory/90-decisions/0036-forja-2-capability-registry.md +30 -0
  102. package/memory/90-decisions/0037-forja-2-policy-engine-obrigatorio.md +28 -0
  103. package/memory/90-decisions/0038-forja-2-runtime-controlado.md +28 -0
  104. package/memory/90-decisions/0039-forja-2-event-bus-scheduler-local-first.md +31 -0
  105. package/memory/90-decisions/0040-forja-2-context-engine-budget-cache.md +32 -0
  106. package/memory/90-decisions/0041-forja-2-graphloop-separado-codegraph.md +32 -0
  107. package/memory/90-decisions/0042-forja-2-planner-validator-independentes.md +29 -0
  108. package/memory/90-decisions/0043-forja-2-orchestration-entities.md +16 -0
  109. package/memory/90-decisions/0044-forja-2-sandbox-worktree.md +19 -0
  110. package/memory/90-decisions/0045-forja-2-sqlite-adapter.md +19 -0
  111. package/memory/90-decisions/0046-forja-2-mcp-adapter.md +18 -0
  112. package/memory/90-decisions/0047-forja-2-backend-nest-adapter.md +19 -0
  113. package/memory/90-decisions/0048-forja-2-sdk-transport.md +18 -0
  114. package/memory/90-decisions/0049-forja-2-observability-control-plane.md +18 -0
  115. package/memory/90-decisions/0050-forja-2-control-plane-application-ports.md +18 -0
  116. package/memory/90-decisions/0051-forja-2-runtime-control-plane-composition.md +18 -0
  117. package/memory/90-decisions/0052-forja-2-deterministic-evaluation.md +15 -0
  118. package/memory/90-decisions/0053-forja-2-plugin-sdk-permissionado.md +16 -0
  119. package/memory/90-decisions/0054-forja-2-worker-dashboard-boundary.md +15 -0
  120. package/memory/90-decisions/0055-forja-2-next-dashboard-distribution.md +16 -0
  121. package/memory/90-decisions/0056-forja-2-dashboard-proxy-auth-query.md +16 -0
  122. package/memory/90-decisions/0057-forja-2-graphloop-approvals-dashboard.md +15 -0
  123. package/memory/90-decisions/0058-forja-2-approval-server-identity.md +15 -0
  124. package/package.json +28 -3
  125. package/README.en.md +0 -329
@@ -0,0 +1,178 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { CONTRACT_VERSION, validateTokenBudget, } from "../../contracts/src/index.js";
3
+ export class OrchestrationError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'OrchestrationError';
7
+ }
8
+ }
9
+ export class InMemoryOrchestrationStore {
10
+ sprints = new Map();
11
+ tasks = new Map();
12
+ handoffs = new Map();
13
+ saveSprint(value) { this.sprints.set(value.id, value); }
14
+ getSprint(id) { return this.sprints.get(id); }
15
+ listSprints() { return [...this.sprints.values()]; }
16
+ saveTask(value) { this.tasks.set(value.id, value); }
17
+ getTask(id) { return this.tasks.get(id); }
18
+ listTasks(sprintId) {
19
+ const values = [...this.tasks.values()];
20
+ return sprintId === undefined ? values : values.filter((task) => task.sprintId === sprintId);
21
+ }
22
+ saveHandoff(value) { this.handoffs.set(value.id, value); }
23
+ getHandoff(id) { return this.handoffs.get(id); }
24
+ listHandoffs() { return [...this.handoffs.values()]; }
25
+ }
26
+ export class SprintEngine {
27
+ store;
28
+ graph;
29
+ constructor(store, graph) { this.store = store; this.graph = graph; }
30
+ async create(input) {
31
+ this.requireText(input.objective, 'objective');
32
+ this.requireItems(input.completionCriteria, 'completionCriteria');
33
+ validateTokenBudget(input.budget);
34
+ const value = this.audit(input.correlationId ?? `sprint:${input.objective}`, {
35
+ id: this.id(), objective: input.objective.trim(), includedScope: this.clean(input.includedScope),
36
+ excludedScope: this.clean(input.excludedScope), budget: input.budget,
37
+ completionCriteria: this.clean(input.completionCriteria), risks: this.clean(input.risks),
38
+ taskIds: [], evidenceIds: this.unique(input.evidenceIds), status: 'planned',
39
+ });
40
+ await this.store.saveSprint(value);
41
+ await this.record('sprint', value.id, [], value.evidenceIds);
42
+ return value;
43
+ }
44
+ async start(id) { return this.transition(id, ['planned', 'paused'], 'active'); }
45
+ async pause(id) { return this.transition(id, ['active'], 'paused'); }
46
+ async attachTask(sprintId, taskId) {
47
+ const sprint = await this.requireSprint(sprintId);
48
+ if (sprint.status === 'completed' || sprint.status === 'cancelled')
49
+ throw new OrchestrationError('Cannot attach a task to a closed sprint');
50
+ if (sprint.taskIds.includes(taskId))
51
+ return sprint;
52
+ const updated = this.updated(sprint, { taskIds: [...sprint.taskIds, taskId] });
53
+ await this.store.saveSprint(updated);
54
+ await this.record('sprint', updated.id, [taskId], updated.evidenceIds);
55
+ return updated;
56
+ }
57
+ async complete(id, validator) {
58
+ const sprint = await this.requireSprint(id);
59
+ const tasks = await this.store.listTasks(id);
60
+ if (sprint.status !== 'active' && sprint.status !== 'paused')
61
+ throw new OrchestrationError('Only an active or paused sprint can be completed');
62
+ if (tasks.length !== sprint.taskIds.length || tasks.some((task) => task.status !== 'done'))
63
+ throw new OrchestrationError('Sprint cannot complete before every task is done');
64
+ const result = await validator.validateSprint(sprint, tasks);
65
+ if (result.status !== 'accepted')
66
+ throw new OrchestrationError(`Sprint validation did not accept completion: ${result.status}`);
67
+ const updated = this.updated(sprint, { status: 'completed', evidenceIds: this.unique([...sprint.evidenceIds, ...this.evidenceFrom(result)]) });
68
+ await this.store.saveSprint(updated);
69
+ await this.record('sprint', updated.id, updated.taskIds, updated.evidenceIds);
70
+ return updated;
71
+ }
72
+ async transition(id, allowed, status) {
73
+ const sprint = await this.requireSprint(id);
74
+ if (!allowed.includes(sprint.status))
75
+ throw new OrchestrationError(`Invalid sprint transition from ${sprint.status} to ${status}`);
76
+ const updated = this.updated(sprint, { status });
77
+ await this.store.saveSprint(updated);
78
+ await this.record('sprint', updated.id, updated.taskIds, updated.evidenceIds);
79
+ return updated;
80
+ }
81
+ async requireSprint(id) { const value = await this.store.getSprint(id); if (!value)
82
+ throw new OrchestrationError(`Sprint not found: ${id}`); return value; }
83
+ async record(kind, id, relatedIds, evidenceIds) { if (this.graph)
84
+ await this.graph.record({ kind, id, relatedIds, evidenceIds }); }
85
+ updated(value, changes) { return { ...value, ...changes, updatedAt: new Date().toISOString() }; }
86
+ audit(correlationId, value) { return { ...value, schemaVersion: CONTRACT_VERSION, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), correlationId }; }
87
+ auditFields() { return { schemaVersion: CONTRACT_VERSION, createdAt: '', updatedAt: '', correlationId: '' }; }
88
+ id() { return randomUUID(); }
89
+ clean(values) { return [...new Set(values.map((value) => value.trim()).filter(Boolean))]; }
90
+ unique(values) { return [...new Set(values)]; }
91
+ requireText(value, path) { if (value.trim().length === 0)
92
+ throw new OrchestrationError(`${path} is required`); }
93
+ requireItems(values, path) { if (this.clean(values).length === 0)
94
+ throw new OrchestrationError(`${path} must not be empty`); }
95
+ evidenceFrom(result) { return result.checks.flatMap((check) => check.evidenceIds); }
96
+ }
97
+ export class TaskEngine {
98
+ store;
99
+ sprintEngine;
100
+ graph;
101
+ constructor(store, sprintEngine, graph) { this.store = store; this.sprintEngine = sprintEngine; this.graph = graph; }
102
+ async create(input) {
103
+ const sprint = await this.store.getSprint(input.sprintId);
104
+ if (!sprint || sprint.status === 'completed' || sprint.status === 'cancelled')
105
+ throw new OrchestrationError('Task requires an open sprint');
106
+ if (input.objective.trim().length === 0 || input.acceptanceCriteria.length === 0)
107
+ throw new OrchestrationError('Task objective and acceptance criteria are required');
108
+ validateTokenBudget(input.budget);
109
+ const value = { schemaVersion: CONTRACT_VERSION, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), correlationId: input.correlationId ?? `task:${input.objective}`, id: randomUUID(), sprintId: input.sprintId, objective: input.objective.trim(), acceptanceCriteria: this.clean(input.acceptanceCriteria), allowedFiles: this.clean(input.allowedFiles), dependencyIds: this.unique(input.dependencyIds), evidenceIds: this.unique(input.evidenceIds), budget: input.budget, status: 'todo' };
110
+ await this.store.saveTask(value);
111
+ await this.sprintEngine.attachTask(input.sprintId, value.id);
112
+ if (this.graph)
113
+ await this.graph.record({ kind: 'task', id: value.id, relatedIds: [value.sprintId, ...value.dependencyIds], evidenceIds: value.evidenceIds });
114
+ return value;
115
+ }
116
+ async next(sprintId) {
117
+ const tasks = await this.store.listTasks(sprintId);
118
+ const done = new Set(tasks.filter((task) => task.status === 'done').map((task) => task.id));
119
+ return tasks.filter((task) => task.status === 'todo' && task.dependencyIds.every((dependency) => done.has(dependency))).sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
120
+ }
121
+ async start(id) {
122
+ const task = await this.require(id);
123
+ const sprint = await this.store.getSprint(task.sprintId);
124
+ if (!sprint || sprint.status !== 'active')
125
+ throw new OrchestrationError('Task requires an active sprint');
126
+ if (task.status !== 'todo' && task.status !== 'blocked')
127
+ throw new OrchestrationError(`Invalid task start from ${task.status}`);
128
+ const updated = this.updated(task, { status: 'in_progress' });
129
+ await this.store.saveTask(updated);
130
+ return updated;
131
+ }
132
+ async block(id) { const task = await this.require(id); if (task.status !== 'in_progress')
133
+ throw new OrchestrationError('Only an in-progress task can be blocked'); const updated = this.updated(task, { status: 'blocked' }); await this.store.saveTask(updated); return updated; }
134
+ async complete(id, validator) {
135
+ const task = await this.require(id);
136
+ if (task.status !== 'in_progress')
137
+ throw new OrchestrationError('Only an in-progress task can be completed');
138
+ const result = await validator.validateTask(task);
139
+ if (result.status !== 'accepted')
140
+ throw new OrchestrationError(`Task validation did not accept completion: ${result.status}`);
141
+ const evidenceIds = this.unique([...task.evidenceIds, ...result.checks.flatMap((check) => check.evidenceIds)]);
142
+ const updated = this.updated(task, { status: 'done', evidenceIds });
143
+ await this.store.saveTask(updated);
144
+ if (this.graph)
145
+ await this.graph.record({ kind: 'task', id: updated.id, relatedIds: [updated.sprintId, ...updated.dependencyIds], evidenceIds });
146
+ return updated;
147
+ }
148
+ async require(id) { const value = await this.store.getTask(id); if (!value)
149
+ throw new OrchestrationError(`Task not found: ${id}`); return value; }
150
+ updated(value, changes) { return { ...value, ...changes, updatedAt: new Date().toISOString() }; }
151
+ clean(values) { return [...new Set(values.map((value) => value.trim()).filter(Boolean))]; }
152
+ unique(values) { return [...new Set(values)]; }
153
+ }
154
+ export class HandoffEngine {
155
+ store;
156
+ graph;
157
+ maxItems;
158
+ maxItemLength;
159
+ constructor(store, graph, maxItems = 20, maxItemLength = 500) { this.store = store; this.graph = graph; this.maxItems = maxItems; this.maxItemLength = maxItemLength; }
160
+ async create(input) {
161
+ for (const [name, value] of Object.entries({ from: input.from, to: input.to, intent: input.intent, objective: input.objective, nextAgent: input.nextAgent }))
162
+ if (value.trim().length === 0)
163
+ throw new OrchestrationError(`Handoff ${name} is required`);
164
+ if (input.acceptance.length === 0)
165
+ throw new OrchestrationError('Handoff acceptance is required');
166
+ if (input.evidenceIds.length === 0)
167
+ throw new OrchestrationError('Handoff requires evidence references');
168
+ const fields = { schemaVersion: CONTRACT_VERSION, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), correlationId: input.correlationId ?? `handoff:${input.intent}` };
169
+ const value = { ...fields, id: randomUUID(), from: input.from.trim(), to: input.to.trim(), intent: input.intent.trim(), objective: input.objective.trim(), completedWork: this.compact(input.completedWork), decisions: this.compact(input.decisions), constraints: this.compact(input.constraints), pending: this.compact(input.pending), evidenceIds: [...new Set(input.evidenceIds)], acceptance: this.compact(input.acceptance), blockers: this.compact(input.blockers), nextAgent: input.nextAgent.trim() };
170
+ await this.store.saveHandoff(value);
171
+ if (this.graph)
172
+ await this.graph.record({ kind: 'handoff', id: value.id, relatedIds: value.evidenceIds, evidenceIds: value.evidenceIds });
173
+ return value;
174
+ }
175
+ compact(values) { if (values.length > this.maxItems)
176
+ throw new OrchestrationError(`Handoff section exceeds ${this.maxItems} items`); const result = [...new Set(values.map((value) => value.trim()).filter(Boolean))]; if (result.some((value) => value.length > this.maxItemLength))
177
+ throw new OrchestrationError(`Handoff item exceeds ${this.maxItemLength} characters`); return result; }
178
+ }
@@ -0,0 +1,22 @@
1
+ import { type EntityId, type ExecutionPlan, type TokenBudget } from '../../contracts/src/index.ts';
2
+ export interface PlannerRequest {
3
+ readonly objective: string;
4
+ readonly acceptanceCriteria: readonly string[];
5
+ readonly allowedFiles: readonly string[];
6
+ readonly dependencyIds?: readonly EntityId[];
7
+ readonly graphDependencyIds?: readonly EntityId[];
8
+ readonly contextEvidenceIds?: readonly EntityId[];
9
+ readonly evidenceIds: readonly EntityId[];
10
+ readonly budget: TokenBudget;
11
+ readonly correlationId?: string;
12
+ }
13
+ export declare class PlannerError extends Error {
14
+ constructor(message: string);
15
+ }
16
+ export declare class DeterministicPlanner {
17
+ plan(request: PlannerRequest): ExecutionPlan;
18
+ private riskFor;
19
+ private allocate;
20
+ private id;
21
+ private auditFields;
22
+ }
@@ -0,0 +1,70 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { CONTRACT_VERSION, validateTokenBudget, } from "../../contracts/src/index.js";
3
+ export class PlannerError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'PlannerError';
7
+ }
8
+ }
9
+ export class DeterministicPlanner {
10
+ plan(request) {
11
+ if (request.objective.trim().length === 0)
12
+ throw new PlannerError('Planner objective is required');
13
+ if (request.acceptanceCriteria.length === 0)
14
+ throw new PlannerError('Planner requires acceptance criteria');
15
+ const evidenceIds = [...new Set([...request.evidenceIds, ...(request.contextEvidenceIds ?? [])])];
16
+ if (evidenceIds.length === 0)
17
+ throw new PlannerError('Planner requires evidence references');
18
+ validateTokenBudget(request.budget);
19
+ const risk = this.riskFor(request.objective, request.allowedFiles);
20
+ const now = new Date().toISOString();
21
+ const fields = this.auditFields(request.correlationId ?? `plan:${request.objective}`);
22
+ const stepDefinitions = [
23
+ { objective: 'Confirm scope, dependencies and current evidence', criteria: ['Scope and dependencies are recorded'], files: [], dependencies: [] },
24
+ { objective: request.objective, criteria: request.acceptanceCriteria, files: request.allowedFiles, dependencies: [...(request.dependencyIds ?? []), ...(request.graphDependencyIds ?? [])] },
25
+ { objective: 'Validate the objective against independent checks', criteria: ['All acceptance criteria have evidence'], files: [], dependencies: [] },
26
+ ];
27
+ const budgets = this.allocate(request.budget, stepDefinitions.length);
28
+ const steps = stepDefinitions.map((definition, index) => ({
29
+ ...fields,
30
+ id: this.id(`step:${request.objective}:${index}`),
31
+ objective: definition.objective,
32
+ acceptanceCriteria: definition.criteria,
33
+ allowedFiles: definition.files,
34
+ dependencyIds: [...definition.dependencies].sort(),
35
+ evidenceIds,
36
+ risk,
37
+ budget: budgets[index],
38
+ status: index === 0 ? 'ready' : 'planned',
39
+ }));
40
+ return {
41
+ ...fields,
42
+ id: this.id(`plan:${request.objective}:${evidenceIds.join(',')}`),
43
+ objective: request.objective,
44
+ steps,
45
+ budget: request.budget,
46
+ risk,
47
+ evidenceIds,
48
+ };
49
+ }
50
+ riskFor(objective, files) {
51
+ if (/(deploy|release|secret|credential|destructive|delete|production)/i.test(objective))
52
+ return 'high';
53
+ if (files.length > 20 || files.some((file) => /(^|\/)(infra|migration|security)(\/|$)/i.test(file)))
54
+ return 'medium';
55
+ return 'low';
56
+ }
57
+ allocate(budget, count) {
58
+ const split = (total) => Array.from({ length: count }, (_, index) => Math.floor(total / count) + (index < total % count ? 1 : 0));
59
+ const inputs = split(budget.inputTokens);
60
+ const outputs = split(budget.outputTokens);
61
+ return inputs.map((inputTokens, index) => ({ inputTokens, outputTokens: outputs[index], totalTokens: inputTokens + outputs[index], usedTokens: 0 }));
62
+ }
63
+ id(value) {
64
+ return createHash('sha256').update(value).digest('hex');
65
+ }
66
+ auditFields(correlationId) {
67
+ const now = new Date().toISOString();
68
+ return { schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId };
69
+ }
70
+ }
@@ -0,0 +1,56 @@
1
+ import type { CapabilityId, DomainEvent, EntityId, ExecutionResult, Handoff, RuntimeRun, Sprint, Task } from '../../contracts/src/index.ts';
2
+ export type PluginPermission = 'workspace:read' | 'capabilities:list' | 'capability:execute' | 'runtime:start' | 'graph:read' | 'sprint:create' | 'task:create' | 'handoff:create' | 'events:subscribe' | 'approval:respond';
3
+ export type PluginEventHandler = (event: DomainEvent) => void;
4
+ export interface PluginManifest {
5
+ readonly id: string;
6
+ readonly version: string;
7
+ readonly capabilities: readonly CapabilityId[];
8
+ readonly permissions: readonly PluginPermission[];
9
+ readonly events: readonly string[];
10
+ readonly migrations: readonly string[];
11
+ readonly dashboardExtensions: readonly string[];
12
+ readonly compatibleCore: string;
13
+ readonly signature?: string;
14
+ }
15
+ export interface PluginServices {
16
+ readonly workspaceStatus?: () => unknown | Promise<unknown>;
17
+ readonly listCapabilities?: () => readonly unknown[] | Promise<readonly unknown[]>;
18
+ readonly executeCapability?: (id: CapabilityId, payload: unknown) => ExecutionResult | Promise<ExecutionResult>;
19
+ readonly startRuntime?: (input: unknown) => RuntimeRun | Promise<RuntimeRun>;
20
+ readonly queryGraph?: (query: unknown) => readonly unknown[] | Promise<readonly unknown[]>;
21
+ readonly createSprint?: (input: unknown) => Sprint | Promise<Sprint>;
22
+ readonly createTask?: (input: unknown) => Task | Promise<Task>;
23
+ readonly createHandoff?: (input: unknown) => Handoff | Promise<Handoff>;
24
+ readonly subscribeEvents?: (handler: PluginEventHandler) => () => void;
25
+ readonly respondApproval?: (requestId: EntityId, input: unknown) => unknown | Promise<unknown>;
26
+ }
27
+ export interface PluginContext {
28
+ readonly manifest: PluginManifest;
29
+ readonly workspaceStatus: () => Promise<unknown>;
30
+ readonly listCapabilities: () => Promise<readonly unknown[]>;
31
+ readonly executeCapability: (id: CapabilityId, payload: unknown) => Promise<ExecutionResult>;
32
+ readonly startRuntime: (input: unknown) => Promise<RuntimeRun>;
33
+ readonly queryGraph: (query: unknown) => Promise<readonly unknown[]>;
34
+ readonly createSprint: (input: unknown) => Promise<Sprint>;
35
+ readonly createTask: (input: unknown) => Promise<Task>;
36
+ readonly createHandoff: (input: unknown) => Promise<Handoff>;
37
+ readonly subscribeEvents: (handler: PluginEventHandler) => () => void;
38
+ readonly respondApproval: (requestId: EntityId, input: unknown) => Promise<unknown>;
39
+ }
40
+ export interface PluginDefinition {
41
+ readonly manifest: PluginManifest;
42
+ readonly setup?: (context: PluginContext) => void | Promise<void>;
43
+ }
44
+ export declare class PluginError extends Error {
45
+ constructor(message: string);
46
+ }
47
+ export declare class PluginRegistry {
48
+ private readonly plugins;
49
+ private readonly services;
50
+ constructor(services: PluginServices);
51
+ register(definition: PluginDefinition): Promise<PluginContext>;
52
+ list(): readonly PluginManifest[];
53
+ get(id: string): PluginManifest | undefined;
54
+ private context;
55
+ private validateManifest;
56
+ }
@@ -0,0 +1,55 @@
1
+ export class PluginError extends Error {
2
+ constructor(message) { super(message); this.name = 'PluginError'; }
3
+ }
4
+ export class PluginRegistry {
5
+ plugins = new Map();
6
+ services;
7
+ constructor(services) { this.services = services; }
8
+ async register(definition) {
9
+ this.validateManifest(definition.manifest);
10
+ if (this.plugins.has(definition.manifest.id))
11
+ throw new PluginError(`Plugin already registered: ${definition.manifest.id}`);
12
+ this.plugins.set(definition.manifest.id, definition.manifest);
13
+ const context = this.context(definition.manifest);
14
+ try {
15
+ if (definition.setup !== undefined)
16
+ await definition.setup(context);
17
+ return context;
18
+ }
19
+ catch (error) {
20
+ this.plugins.delete(definition.manifest.id);
21
+ throw error;
22
+ }
23
+ }
24
+ list() { return [...this.plugins.values()]; }
25
+ get(id) { return this.plugins.get(id); }
26
+ context(manifest) {
27
+ const requirePermission = (permission) => { if (!manifest.permissions.includes(permission))
28
+ throw new PluginError(`Plugin ${manifest.id} lacks permission ${permission}`); };
29
+ const service = (permission, value, name) => { requirePermission(permission); if (value === undefined)
30
+ throw new PluginError(`Plugin service is not configured: ${name}`); return value; };
31
+ return {
32
+ manifest,
33
+ workspaceStatus: async () => service('workspace:read', this.services.workspaceStatus, 'workspaceStatus')(),
34
+ listCapabilities: async () => service('capabilities:list', this.services.listCapabilities, 'listCapabilities')(),
35
+ executeCapability: async (id, payload) => service('capability:execute', this.services.executeCapability, 'executeCapability')(id, payload),
36
+ startRuntime: async (input) => service('runtime:start', this.services.startRuntime, 'startRuntime')(input),
37
+ queryGraph: async (query) => service('graph:read', this.services.queryGraph, 'queryGraph')(query),
38
+ createSprint: async (input) => service('sprint:create', this.services.createSprint, 'createSprint')(input),
39
+ createTask: async (input) => service('task:create', this.services.createTask, 'createTask')(input),
40
+ createHandoff: async (input) => service('handoff:create', this.services.createHandoff, 'createHandoff')(input),
41
+ subscribeEvents: (handler) => { requirePermission('events:subscribe'); const subscribe = service('events:subscribe', this.services.subscribeEvents, 'subscribeEvents'); return subscribe(handler); },
42
+ respondApproval: async (id, input) => service('approval:respond', this.services.respondApproval, 'respondApproval')(id, input),
43
+ };
44
+ }
45
+ validateManifest(manifest) {
46
+ if (!/^[a-z0-9]+(?:[-.][a-z0-9]+)*$/.test(manifest.id))
47
+ throw new PluginError('Plugin id must be lowercase and namespaced');
48
+ if (manifest.version.trim() === '' || manifest.compatibleCore.trim() === '')
49
+ throw new PluginError('Plugin version and compatibleCore are required');
50
+ if (new Set(manifest.permissions).size !== manifest.permissions.length)
51
+ throw new PluginError('Plugin permissions must be unique');
52
+ if (new Set(manifest.capabilities).size !== manifest.capabilities.length)
53
+ throw new PluginError('Plugin capabilities must be unique');
54
+ }
55
+ }
@@ -0,0 +1,80 @@
1
+ import { type AgentIdentity, type ApprovalRequest, type CapabilityDefinition, type EntityId, type ISO8601, type PolicyDecision, type RiskLevel, type TokenBudget } from '../../contracts/src/index.ts';
2
+ export type PolicyCategory = 'read' | 'write' | 'execution' | 'network' | 'repository' | 'secrets' | 'database' | 'deployment' | 'destructive';
3
+ export interface PolicyScope {
4
+ readonly agentIds?: readonly EntityId[];
5
+ readonly roles?: readonly string[];
6
+ readonly capabilityIds?: readonly string[];
7
+ readonly projects?: readonly string[];
8
+ readonly environments?: readonly string[];
9
+ readonly risks?: readonly RiskLevel[];
10
+ readonly categories?: readonly PolicyCategory[];
11
+ readonly pathPrefixes?: readonly string[];
12
+ }
13
+ export interface PolicyLimits {
14
+ readonly maxTokens?: number;
15
+ readonly maxFiles?: number;
16
+ readonly maxDurationMs?: number;
17
+ readonly maxRetries?: number;
18
+ }
19
+ export interface PolicyRule {
20
+ readonly id: string;
21
+ readonly priority: number;
22
+ readonly effect: PolicyDecision['effect'];
23
+ readonly reason: string;
24
+ readonly scope: PolicyScope;
25
+ readonly limits?: PolicyLimits;
26
+ }
27
+ export interface ApprovalDetails {
28
+ readonly action: string;
29
+ readonly justification: string;
30
+ readonly impact: string;
31
+ readonly expectedDiff?: string;
32
+ readonly expiresAt: ISO8601;
33
+ }
34
+ export interface PolicyRequest {
35
+ readonly definition: CapabilityDefinition;
36
+ readonly agent: AgentIdentity;
37
+ readonly projectId?: string;
38
+ readonly environment: string;
39
+ readonly categories: readonly string[];
40
+ readonly files: readonly string[];
41
+ readonly budget?: TokenBudget;
42
+ readonly now: ISO8601;
43
+ readonly approval?: ApprovalDetails;
44
+ }
45
+ export interface ApprovalDecision {
46
+ readonly decision: 'approved' | 'rejected';
47
+ readonly approverId: EntityId;
48
+ readonly decidedAt: ISO8601;
49
+ }
50
+ export interface ApprovalInput extends ApprovalDetails {
51
+ readonly correlationId: string;
52
+ }
53
+ export declare class PolicyError extends Error {
54
+ constructor(message: string);
55
+ }
56
+ export declare class ApprovalLedger {
57
+ private readonly requests;
58
+ create(input: ApprovalInput, now?: ISO8601): ApprovalRequest;
59
+ list(): readonly ApprovalRequest[];
60
+ decide(id: EntityId, decision: ApprovalDecision): ApprovalRequest;
61
+ expire(now: ISO8601): readonly ApprovalRequest[];
62
+ get(id: EntityId): ApprovalRequest;
63
+ }
64
+ export declare class PolicyEngine {
65
+ private readonly rules;
66
+ private readonly approvalRequiredRisks;
67
+ private readonly approvalLedger;
68
+ constructor(options?: {
69
+ readonly rules?: readonly PolicyRule[];
70
+ readonly approvalRequiredRisks?: readonly RiskLevel[];
71
+ readonly approvalLedger?: ApprovalLedger;
72
+ });
73
+ authorize(request: PolicyRequest): PolicyDecision;
74
+ get approvals(): ApprovalLedger;
75
+ private withApproval;
76
+ private matches;
77
+ private validateRules;
78
+ private effectRank;
79
+ private asNumericLimits;
80
+ }
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { CONTRACT_VERSION, } from "../../contracts/src/index.js";
3
+ export class PolicyError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'PolicyError';
7
+ }
8
+ }
9
+ export class ApprovalLedger {
10
+ requests = new Map();
11
+ create(input, now = new Date().toISOString()) {
12
+ if (input.action.trim().length === 0)
13
+ throw new PolicyError('Approval action is required');
14
+ if (input.justification.trim().length === 0)
15
+ throw new PolicyError('Approval justification is required');
16
+ if (input.impact.trim().length === 0)
17
+ throw new PolicyError('Approval impact is required');
18
+ const request = {
19
+ schemaVersion: CONTRACT_VERSION,
20
+ id: randomUUID(),
21
+ action: input.action,
22
+ justification: input.justification,
23
+ impact: input.impact,
24
+ expectedDiff: input.expectedDiff,
25
+ expiresAt: input.expiresAt,
26
+ correlationId: input.correlationId,
27
+ createdAt: now,
28
+ updatedAt: now,
29
+ };
30
+ this.requests.set(request.id, request);
31
+ return request;
32
+ }
33
+ list() { return [...this.requests.values()].sort((left, right) => left.createdAt.localeCompare(right.createdAt)); }
34
+ decide(id, decision) {
35
+ const current = this.get(id);
36
+ if (current.decision !== undefined)
37
+ throw new PolicyError(`Approval already decided: ${id}`);
38
+ if (current.expiresAt <= decision.decidedAt)
39
+ throw new PolicyError(`Approval expired: ${id}`);
40
+ const updated = { ...current, decision: decision.decision, approverId: decision.approverId, updatedAt: decision.decidedAt };
41
+ this.requests.set(id, updated);
42
+ return updated;
43
+ }
44
+ expire(now) {
45
+ const expired = [];
46
+ for (const current of this.requests.values()) {
47
+ if (current.decision === undefined && current.expiresAt <= now) {
48
+ const updated = { ...current, decision: 'expired', updatedAt: now };
49
+ this.requests.set(current.id, updated);
50
+ expired.push(updated);
51
+ }
52
+ }
53
+ return expired;
54
+ }
55
+ get(id) {
56
+ const request = this.requests.get(id);
57
+ if (request === undefined)
58
+ throw new PolicyError(`Approval not found: ${id}`);
59
+ return request;
60
+ }
61
+ }
62
+ export class PolicyEngine {
63
+ rules;
64
+ approvalRequiredRisks;
65
+ approvalLedger;
66
+ constructor(options = {}) {
67
+ this.rules = [...(options.rules ?? [])].sort((left, right) => right.priority - left.priority || this.effectRank(left.effect) - this.effectRank(right.effect) || left.id.localeCompare(right.id));
68
+ this.approvalRequiredRisks = options.approvalRequiredRisks ?? ['critical'];
69
+ this.approvalLedger = options.approvalLedger ?? new ApprovalLedger();
70
+ this.validateRules(this.rules);
71
+ }
72
+ authorize(request) {
73
+ const match = this.rules.find((rule) => this.matches(rule.scope, request));
74
+ const decision = match === undefined
75
+ ? { effect: 'DENY', reason: 'No matching policy rule', policyId: 'default-deny' }
76
+ : { effect: match.effect, reason: match.reason, policyId: match.id, ...(match.limits === undefined ? {} : { limits: this.asNumericLimits(match.limits) }) };
77
+ if (this.approvalRequiredRisks.includes(request.definition.risk) && decision.effect === 'ALLOW') {
78
+ return this.withApproval(request, decision, 'Risk requires explicit approval');
79
+ }
80
+ if (decision.effect === 'REQUIRE_APPROVAL')
81
+ return this.withApproval(request, decision, decision.reason);
82
+ return decision;
83
+ }
84
+ get approvals() {
85
+ return this.approvalLedger;
86
+ }
87
+ withApproval(request, decision, reason) {
88
+ if (request.approval === undefined)
89
+ return { ...decision, effect: 'REQUIRE_APPROVAL', reason };
90
+ const approval = this.approvalLedger.create({ ...request.approval, correlationId: request.agent.id }, request.now);
91
+ return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: approval.id };
92
+ }
93
+ matches(scope, request) {
94
+ if (scope.agentIds !== undefined && !scope.agentIds.includes(request.agent.id))
95
+ return false;
96
+ if (scope.roles !== undefined && !scope.roles.includes(request.agent.role))
97
+ return false;
98
+ if (scope.capabilityIds !== undefined && !scope.capabilityIds.includes(request.definition.id))
99
+ return false;
100
+ if (scope.projects !== undefined && (request.projectId === undefined || !scope.projects.includes(request.projectId)))
101
+ return false;
102
+ if (scope.environments !== undefined && !scope.environments.includes(request.environment))
103
+ return false;
104
+ if (scope.risks !== undefined && !scope.risks.includes(request.definition.risk))
105
+ return false;
106
+ if (scope.categories !== undefined && !scope.categories.some((category) => request.categories.includes(category)))
107
+ return false;
108
+ if (scope.pathPrefixes !== undefined && !request.files.every((file) => scope.pathPrefixes?.some((prefix) => file.startsWith(prefix))))
109
+ return false;
110
+ return true;
111
+ }
112
+ validateRules(rules) {
113
+ const ids = new Set();
114
+ for (const rule of rules) {
115
+ if (rule.id.trim().length === 0)
116
+ throw new PolicyError('Policy rule id is required');
117
+ if (ids.has(rule.id))
118
+ throw new PolicyError(`Duplicate policy rule: ${rule.id}`);
119
+ if (!Number.isInteger(rule.priority))
120
+ throw new PolicyError(`Policy priority must be an integer: ${rule.id}`);
121
+ if (rule.reason.trim().length === 0)
122
+ throw new PolicyError(`Policy reason is required: ${rule.id}`);
123
+ ids.add(rule.id);
124
+ }
125
+ }
126
+ effectRank(effect) {
127
+ return effect === 'DENY' ? 0 : effect === 'REQUIRE_APPROVAL' ? 1 : effect === 'ALLOW_WITH_LIMITS' ? 2 : 3;
128
+ }
129
+ asNumericLimits(limits) {
130
+ const output = {};
131
+ for (const [key, value] of Object.entries(limits))
132
+ if (value !== undefined)
133
+ output[key] = value;
134
+ return output;
135
+ }
136
+ }