forjajs 5.1.0 → 5.3.1
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.
- package/CHANGELOG.md +108 -0
- package/README.md +52 -4
- package/README.pt-BR.md +54 -4
- package/dist/apps/cli/src/index.d.ts +0 -1
- package/dist/apps/cli/src/index.js +43 -32
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
- package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
- package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
- package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
- package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
- package/dist/apps/server/src/forja-nest.module.js +55 -0
- package/dist/apps/server/src/main.d.ts +21 -4
- package/dist/apps/server/src/main.js +79 -57
- package/dist/apps/server/src/task-planning-service.d.ts +29 -0
- package/dist/apps/server/src/task-planning-service.js +195 -0
- package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
- package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
- package/dist/bin/forja.js +3 -2
- package/dist/lib/agent-evals.d.ts +138 -0
- package/dist/lib/agent-evals.js +365 -0
- package/dist/lib/cli-output.js +14 -2
- package/dist/lib/code-context.d.ts +33 -5
- package/dist/lib/code-context.js +70 -5
- package/dist/lib/context-builder.d.ts +49 -4
- package/dist/lib/context-builder.js +114 -47
- package/dist/lib/core/coverage-gate.d.ts +59 -0
- package/dist/lib/core/coverage-gate.js +58 -0
- package/dist/lib/core/doc-graph.d.ts +38 -0
- package/dist/lib/core/doc-graph.js +83 -0
- package/dist/lib/core/health.js +286 -5
- package/dist/lib/core/journey.js +26 -0
- package/dist/lib/core/registry.js +81 -6
- package/dist/lib/docs-reference.d.ts +35 -0
- package/dist/lib/docs-reference.js +57 -0
- package/dist/lib/exec.d.ts +55 -0
- package/dist/lib/exec.js +141 -0
- package/dist/lib/project-wiring.js +6 -2
- package/dist/lib/session-memory.d.ts +38 -0
- package/dist/lib/session-memory.js +206 -0
- package/dist/lib/spec-trace.d.ts +46 -0
- package/dist/lib/spec-trace.js +184 -0
- package/dist/packages/adapter-git/src/index.js +13 -4
- package/dist/packages/adapter-nest/src/index.d.ts +2 -1
- package/dist/packages/adapter-nest/src/index.js +59 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
- package/dist/packages/adapter-sqlite/src/index.js +61 -1
- package/dist/packages/context/src/index.d.ts +2 -0
- package/dist/packages/context/src/index.js +36 -15
- package/dist/packages/contracts/src/index.d.ts +64 -0
- package/dist/packages/core/src/index.d.ts +9 -1
- package/dist/packages/core/src/index.js +28 -3
- package/dist/packages/graph/src/index.js +14 -5
- package/dist/packages/llm/src/index.js +7 -24
- package/dist/packages/mcp/src/index.d.ts +8 -0
- package/dist/packages/mcp/src/index.js +12 -1
- package/dist/packages/observability/src/index.d.ts +11 -0
- package/dist/packages/observability/src/index.js +3 -0
- package/dist/packages/orchestration/src/index.d.ts +15 -1
- package/dist/packages/orchestration/src/index.js +127 -21
- package/dist/packages/planner/src/index.d.ts +7 -1
- package/dist/packages/planner/src/index.js +67 -10
- package/dist/packages/planner/src/proposal-store.d.ts +30 -0
- package/dist/packages/planner/src/proposal-store.js +109 -0
- package/dist/packages/policy/src/index.d.ts +9 -16
- package/dist/packages/policy/src/index.js +114 -31
- package/dist/packages/runtime/src/index.d.ts +16 -2
- package/dist/packages/runtime/src/index.js +176 -61
- package/dist/scripts/build-smart-context.d.ts +2 -0
- package/dist/scripts/build-smart-context.js +12 -3
- package/dist/scripts/code-context.d.ts +3 -1
- package/dist/scripts/code-context.js +13 -3
- package/dist/scripts/coverage-gate.d.ts +2 -0
- package/dist/scripts/coverage-gate.js +101 -0
- package/dist/scripts/eval-agents.d.ts +11 -0
- package/dist/scripts/eval-agents.js +96 -0
- package/dist/scripts/gen-commands-doc.d.ts +2 -0
- package/dist/scripts/gen-commands-doc.js +18 -0
- package/dist/scripts/hook-session-memory.d.ts +9 -0
- package/dist/scripts/hook-session-memory.js +20 -0
- package/dist/scripts/hook-session-start.js +34 -0
- package/dist/scripts/llm-fit.js +15 -6
- package/dist/scripts/simulate.js +16 -4
- package/dist/scripts/spec-trace.d.ts +10 -0
- package/dist/scripts/spec-trace.js +73 -0
- package/dist/scripts/sync-universal-memory.js +69 -4
- package/dist/scripts/token-benchmark.d.ts +33 -1
- package/dist/scripts/token-benchmark.js +179 -5
- package/dist/scripts/token-economy.js +3 -1
- package/dist/scripts/tools-doctor.d.ts +16 -1
- package/dist/scripts/tools-doctor.js +58 -17
- package/docs/commands.md +155 -0
- package/docs/fluxo.md +11 -7
- package/docs/init-project.md +3 -1
- package/docs/llm-fit-loop.md +20 -0
- package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
- package/docs/produto/factsheet-marketing.md +7 -5
- package/docs/produto/roteiro-demo.md +14 -5
- package/docs/quick-reference.md +3 -3
- package/docs/token-optimization.md +10 -6
- package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
- package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
- package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
- package/package.json +4 -2
- package/specs/avaliacoes-de-agentes/spec.md +52 -0
- package/specs/criterios-ligados-a-testes/spec.md +42 -0
- package/specs/memoria-de-sessao/spec.md +48 -0
- package/specs/v6-agent-runtime-portable/spec.md +83 -0
- package/specs/v6-core-consolidation/spec.md +70 -0
- package/specs/v6-docs-drift/spec.md +85 -0
- package/specs/v6-quality-gates/spec.md +104 -0
- package/specs/v6-token-economy/spec.md +84 -0
- package/templates/evals/agents/adr.json +25 -0
- package/templates/evals/agents/memoria.json +32 -0
- package/templates/evals/agents/proxima-acao.json +29 -0
- package/templates/evals/agents/spec-nova.json +26 -0
- package/templates/evals/agents/teste-do-criterio.json +29 -0
- package/templates/project/AGENTS.md +7 -0
- package/templates/project/CLAUDE.md +3 -2
- package/templates/project/skills/testing/SKILL.md +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { CONTRACT_VERSION, isPathWithinRoot, } from '../../contracts/src/index.js';
|
|
3
3
|
export class PolicyError extends Error {
|
|
4
4
|
constructor(message) {
|
|
@@ -6,6 +6,72 @@ export class PolicyError extends Error {
|
|
|
6
6
|
this.name = 'PolicyError';
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
+
// Round-trip the calendar to reject Date.parse's normalization of impossible dates.
|
|
10
|
+
function approvalInstant(value) {
|
|
11
|
+
const parts = typeof value === 'string' ? /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value) : null;
|
|
12
|
+
if (parts === null)
|
|
13
|
+
throw new PolicyError('Approval date must be an unambiguous ISO timestamp');
|
|
14
|
+
const calendar = `${parts[1]}.${(parts[2] ?? '').padEnd(3, '0')}Z`;
|
|
15
|
+
const local = Date.parse(calendar);
|
|
16
|
+
const instant = Date.parse(value);
|
|
17
|
+
if (!Number.isFinite(local) || !Number.isFinite(instant) || new Date(local).toISOString() !== calendar) {
|
|
18
|
+
throw new PolicyError('Invalid approval date');
|
|
19
|
+
}
|
|
20
|
+
return instant;
|
|
21
|
+
}
|
|
22
|
+
// Tags distinguish absent/undefined/null; descriptors prevent executing getters or toJSON.
|
|
23
|
+
function canonicalApprovalValue(value, ancestors = new Set()) {
|
|
24
|
+
if (value === undefined)
|
|
25
|
+
return '["undefined"]';
|
|
26
|
+
if (value === null)
|
|
27
|
+
return '["null"]';
|
|
28
|
+
if (typeof value === 'string' || typeof value === 'boolean')
|
|
29
|
+
return JSON.stringify([typeof value, value]);
|
|
30
|
+
if (typeof value === 'number') {
|
|
31
|
+
if (!Number.isFinite(value))
|
|
32
|
+
throw new PolicyError('Non-finite approval value');
|
|
33
|
+
return JSON.stringify(['number', Object.is(value, -0) ? '-0' : value]);
|
|
34
|
+
}
|
|
35
|
+
if (typeof value !== 'object')
|
|
36
|
+
throw new PolicyError('Unsupported approval value');
|
|
37
|
+
if (ancestors.has(value))
|
|
38
|
+
throw new PolicyError('Cyclic approval value');
|
|
39
|
+
const array = Array.isArray(value);
|
|
40
|
+
const prototype = Object.getPrototypeOf(value);
|
|
41
|
+
if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
|
|
42
|
+
throw new PolicyError('Approval values must be plain objects or arrays');
|
|
43
|
+
}
|
|
44
|
+
ancestors.add(value);
|
|
45
|
+
try {
|
|
46
|
+
const keys = Reflect.ownKeys(value);
|
|
47
|
+
for (const key of keys) {
|
|
48
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
49
|
+
if (typeof key !== 'string' || descriptor === undefined || !('value' in descriptor) || (!descriptor.enumerable && !(array && key === 'length'))) {
|
|
50
|
+
throw new PolicyError('Ambiguous approval property');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (array) {
|
|
54
|
+
if (keys.length !== value.length + 1)
|
|
55
|
+
throw new PolicyError('Sparse or extended approval array');
|
|
56
|
+
const entries = [];
|
|
57
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
58
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
59
|
+
if (descriptor === undefined)
|
|
60
|
+
throw new PolicyError('Sparse approval array');
|
|
61
|
+
entries.push(canonicalApprovalValue(descriptor.value, ancestors));
|
|
62
|
+
}
|
|
63
|
+
return `["array",[${entries.join(',')}]]`;
|
|
64
|
+
}
|
|
65
|
+
const entries = Object.keys(value).sort().map((key) => {
|
|
66
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
67
|
+
return `[${JSON.stringify(key)},${canonicalApprovalValue(descriptor?.value, ancestors)}]`;
|
|
68
|
+
});
|
|
69
|
+
return `["object",[${entries.join(',')}]]`;
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
ancestors.delete(value);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
9
75
|
export class ApprovalLedger {
|
|
10
76
|
requests = new Map();
|
|
11
77
|
store;
|
|
@@ -17,6 +83,8 @@ export class ApprovalLedger {
|
|
|
17
83
|
throw new PolicyError('Approval justification is required');
|
|
18
84
|
if (input.impact.trim().length === 0)
|
|
19
85
|
throw new PolicyError('Approval impact is required');
|
|
86
|
+
if (approvalInstant(input.expiresAt) <= approvalInstant(now))
|
|
87
|
+
throw new PolicyError('Approval expiry must be in the future');
|
|
20
88
|
const request = {
|
|
21
89
|
schemaVersion: CONTRACT_VERSION,
|
|
22
90
|
id: randomUUID(),
|
|
@@ -26,6 +94,8 @@ export class ApprovalLedger {
|
|
|
26
94
|
expectedDiff: input.expectedDiff,
|
|
27
95
|
expiresAt: input.expiresAt,
|
|
28
96
|
correlationId: input.correlationId,
|
|
97
|
+
operationId: input.operationId,
|
|
98
|
+
fingerprint: input.fingerprint,
|
|
29
99
|
createdAt: now,
|
|
30
100
|
updatedAt: now,
|
|
31
101
|
};
|
|
@@ -42,7 +112,7 @@ export class ApprovalLedger {
|
|
|
42
112
|
const current = this.get(id);
|
|
43
113
|
if (current.decision !== undefined)
|
|
44
114
|
throw new PolicyError(`Approval already decided: ${id}`);
|
|
45
|
-
if (current.expiresAt <= decision.decidedAt)
|
|
115
|
+
if (approvalInstant(current.expiresAt) <= approvalInstant(decision.decidedAt))
|
|
46
116
|
throw new PolicyError(`Approval expired: ${id}`);
|
|
47
117
|
const updated = { ...current, decision: decision.decision, approverId: decision.approverId, updatedAt: decision.decidedAt };
|
|
48
118
|
this.requests.set(id, updated);
|
|
@@ -50,9 +120,10 @@ export class ApprovalLedger {
|
|
|
50
120
|
return updated;
|
|
51
121
|
}
|
|
52
122
|
expire(now) {
|
|
123
|
+
const instant = approvalInstant(now);
|
|
53
124
|
const expired = [];
|
|
54
|
-
for (const current of this.
|
|
55
|
-
if (current.decision === undefined && current.expiresAt <=
|
|
125
|
+
for (const current of this.list()) {
|
|
126
|
+
if ((current.decision === undefined || current.decision === 'approved') && approvalInstant(current.expiresAt) <= instant) {
|
|
56
127
|
const updated = { ...current, decision: 'expired', updatedAt: now };
|
|
57
128
|
this.requests.set(current.id, updated);
|
|
58
129
|
void this.store?.save(updated);
|
|
@@ -61,20 +132,14 @@ export class ApprovalLedger {
|
|
|
61
132
|
}
|
|
62
133
|
return expired;
|
|
63
134
|
}
|
|
64
|
-
/**
|
|
65
|
-
|
|
66
|
-
const matches = this.list().filter((request) => request.
|
|
135
|
+
/** Descriptive/historical records without both binding fields cannot authorize execution. */
|
|
136
|
+
findByOperation(operationId, fingerprint) {
|
|
137
|
+
const matches = this.list().filter((request) => request.operationId === operationId && request.fingerprint === fingerprint && request.decision !== 'expired');
|
|
67
138
|
return matches.at(-1);
|
|
68
139
|
}
|
|
69
140
|
get(id) {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const persisted = this.store.get(id);
|
|
73
|
-
if (persisted !== undefined) {
|
|
74
|
-
this.requests.set(id, persisted);
|
|
75
|
-
return persisted;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
141
|
+
// A persistent store is authoritative, including deletion and decisions by another ledger.
|
|
142
|
+
const request = this.store === undefined ? this.requests.get(id) : this.store.get(id);
|
|
78
143
|
if (request === undefined)
|
|
79
144
|
throw new PolicyError(`Approval not found: ${id}`);
|
|
80
145
|
return request;
|
|
@@ -99,25 +164,44 @@ export class PolicyEngine {
|
|
|
99
164
|
// approval just because a rule chose to bound it with limits instead of an unconditional ALLOW.
|
|
100
165
|
const isGranting = decision.effect === 'ALLOW' || decision.effect === 'ALLOW_WITH_LIMITS';
|
|
101
166
|
if (this.approvalRequiredRisks.includes(request.definition.risk) && isGranting) {
|
|
102
|
-
return this.withApproval(request, decision, 'Risk requires explicit approval');
|
|
167
|
+
return this.withApproval(request, decision, 'Risk requires explicit approval', match);
|
|
103
168
|
}
|
|
104
169
|
if (decision.effect === 'REQUIRE_APPROVAL')
|
|
105
|
-
return this.withApproval(request, decision, decision.reason);
|
|
170
|
+
return this.withApproval(request, decision, decision.reason, match);
|
|
106
171
|
return decision;
|
|
107
172
|
}
|
|
108
173
|
get approvals() {
|
|
109
174
|
return this.approvalLedger;
|
|
110
175
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
176
|
+
withApproval(request, decision, reason, rule) {
|
|
177
|
+
const now = approvalInstant(request.now);
|
|
178
|
+
if (request.approval !== undefined)
|
|
179
|
+
approvalInstant(request.approval.expiresAt);
|
|
180
|
+
const operationId = request.operationId ?? request.correlationId ?? randomUUID();
|
|
181
|
+
const correlationId = request.correlationId ?? operationId;
|
|
182
|
+
const { definition, agent, budget, approval } = request;
|
|
183
|
+
const fingerprint = `v1:${createHash('sha256').update(canonicalApprovalValue({
|
|
184
|
+
operationId,
|
|
185
|
+
agent: { id: agent.id, role: agent.role, autonomy: agent.autonomy },
|
|
186
|
+
capability: { id: definition.id, version: definition.version, risk: definition.risk, permissions: definition.permissions, sideEffects: definition.sideEffects },
|
|
187
|
+
payload: request.input?.payload,
|
|
188
|
+
projectId: request.projectId,
|
|
189
|
+
environment: request.environment,
|
|
190
|
+
files: [...new Set(request.files)].sort(),
|
|
191
|
+
categories: [...new Set(request.categories)].sort(),
|
|
192
|
+
approval: approval === undefined ? undefined : {
|
|
193
|
+
action: approval.action, justification: approval.justification, impact: approval.impact,
|
|
194
|
+
expectedDiff: approval.expectedDiff, expiresAt: approval.expiresAt,
|
|
195
|
+
},
|
|
196
|
+
decision,
|
|
197
|
+
rule,
|
|
198
|
+
approvalRequiredRisks: this.approvalRequiredRisks,
|
|
199
|
+
riskScore: request.riskScore,
|
|
200
|
+
anomalyScore: request.anomalyScore,
|
|
201
|
+
budget: budget === undefined ? undefined : { inputTokens: budget.inputTokens, outputTokens: budget.outputTokens, totalTokens: budget.totalTokens },
|
|
202
|
+
})).digest('hex')}`;
|
|
203
|
+
const existing = this.approvalLedger.findByOperation(operationId, fingerprint);
|
|
204
|
+
if (existing !== undefined && approvalInstant(existing.expiresAt) > now) {
|
|
121
205
|
if (existing.decision === 'approved') {
|
|
122
206
|
// `decision.effect` may already be ALLOW/ALLOW_WITH_LIMITS (gated only by the risk-level
|
|
123
207
|
// approval requirement) — keep it as-is. But when the *rule itself* is REQUIRE_APPROVAL,
|
|
@@ -130,12 +214,11 @@ export class PolicyEngine {
|
|
|
130
214
|
return { ...decision, effect: 'DENY', reason: `Approval rejected: ${existing.id}`, approvalRequestId: existing.id };
|
|
131
215
|
if (existing.decision === undefined)
|
|
132
216
|
return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: existing.id };
|
|
133
|
-
// existing.decision === 'expired': falls through to issue a fresh request below.
|
|
134
217
|
}
|
|
135
|
-
if (
|
|
218
|
+
if (approval === undefined)
|
|
136
219
|
return { ...decision, effect: 'REQUIRE_APPROVAL', reason };
|
|
137
|
-
const
|
|
138
|
-
return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId:
|
|
220
|
+
const created = this.approvalLedger.create({ ...approval, correlationId, operationId, fingerprint }, request.now);
|
|
221
|
+
return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: created.id };
|
|
139
222
|
}
|
|
140
223
|
matches(scope, request) {
|
|
141
224
|
if (scope.agentIds !== undefined && !scope.agentIds.includes(request.agent.id))
|
|
@@ -51,6 +51,9 @@ export interface RuntimeMemory {
|
|
|
51
51
|
remember(run: RuntimeRun, result: ExecutionResult): void | Promise<void>;
|
|
52
52
|
}
|
|
53
53
|
export interface RuntimeStartRequest {
|
|
54
|
+
readonly runId?: RunId;
|
|
55
|
+
readonly handoffId?: EntityId;
|
|
56
|
+
readonly context?: unknown;
|
|
54
57
|
readonly objective: string;
|
|
55
58
|
readonly agent: AgentIdentity;
|
|
56
59
|
readonly budget: TokenBudget;
|
|
@@ -68,9 +71,11 @@ export interface RuntimeDependencies {
|
|
|
68
71
|
readonly checkpointStore?: CheckpointStore;
|
|
69
72
|
readonly persistence?: RuntimePersistence;
|
|
70
73
|
readonly memory?: RuntimeMemory;
|
|
74
|
+
readonly beforeExecution?: (run: RuntimeRun) => void | Promise<void>;
|
|
71
75
|
}
|
|
72
76
|
export declare class RuntimeError extends Error {
|
|
73
|
-
|
|
77
|
+
readonly code: string;
|
|
78
|
+
constructor(message: string, code?: string);
|
|
74
79
|
}
|
|
75
80
|
export declare class InMemoryCheckpointStore implements CheckpointStore {
|
|
76
81
|
private readonly checkpoints;
|
|
@@ -87,18 +92,27 @@ export declare class RuntimeEngine {
|
|
|
87
92
|
private readonly policies;
|
|
88
93
|
private readonly requestedPauses;
|
|
89
94
|
private readonly startedAt;
|
|
95
|
+
private readonly starts;
|
|
96
|
+
private readonly executions;
|
|
97
|
+
private readonly recoveries;
|
|
98
|
+
private readonly requestedCancels;
|
|
99
|
+
private readonly executionErrors;
|
|
90
100
|
constructor(dependencies: RuntimeDependencies, limits?: Partial<RuntimeLimits>);
|
|
91
101
|
start(request: RuntimeStartRequest): Promise<RuntimeRun>;
|
|
102
|
+
private prepare;
|
|
92
103
|
execute(runId: RunId): Promise<RuntimeRun>;
|
|
104
|
+
private singleFlight;
|
|
105
|
+
private executeRun;
|
|
93
106
|
recover(runId: RunId, policy: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
|
|
107
|
+
private load;
|
|
94
108
|
resume(runId: RunId, policy?: CapabilityExecutionRequest['policy']): Promise<RuntimeRun>;
|
|
95
109
|
pause(runId: RunId): RuntimeRun;
|
|
96
110
|
cancel(runId: RunId): Promise<RuntimeRun>;
|
|
111
|
+
has(runId: RunId): boolean;
|
|
97
112
|
get(runId: RunId): RuntimeRun;
|
|
98
113
|
private validateAndFinish;
|
|
99
114
|
private stop;
|
|
100
115
|
private update;
|
|
101
|
-
private persist;
|
|
102
116
|
private saveCheckpoint;
|
|
103
117
|
private metrics;
|
|
104
118
|
private auditFields;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
3
|
import { CONTRACT_VERSION, validateTokenBudget, } from '../../contracts/src/index.js';
|
|
3
4
|
const DEFAULT_LIMITS = {
|
|
4
5
|
maxSteps: 20,
|
|
@@ -9,9 +10,11 @@ const DEFAULT_LIMITS = {
|
|
|
9
10
|
maxParallel: 1,
|
|
10
11
|
};
|
|
11
12
|
export class RuntimeError extends Error {
|
|
12
|
-
|
|
13
|
+
code;
|
|
14
|
+
constructor(message, code = 'RUNTIME_ERROR') {
|
|
13
15
|
super(message);
|
|
14
16
|
this.name = 'RuntimeError';
|
|
17
|
+
this.code = code;
|
|
15
18
|
}
|
|
16
19
|
}
|
|
17
20
|
export class InMemoryCheckpointStore {
|
|
@@ -33,16 +36,39 @@ export class RuntimeEngine {
|
|
|
33
36
|
policies = new Map();
|
|
34
37
|
requestedPauses = new Set();
|
|
35
38
|
startedAt = new Map();
|
|
39
|
+
starts = new Map();
|
|
40
|
+
executions = new Map();
|
|
41
|
+
recoveries = new Map();
|
|
42
|
+
requestedCancels = new Set();
|
|
43
|
+
// An interrupted write leaves execution ambiguous; retrying must not replay effects.
|
|
44
|
+
executionErrors = new Map();
|
|
36
45
|
constructor(dependencies, limits = {}) {
|
|
37
46
|
this.dependencies = dependencies;
|
|
38
47
|
this.limits = { ...DEFAULT_LIMITS, ...limits };
|
|
39
48
|
this.validateLimits(this.limits);
|
|
40
49
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
if (
|
|
44
|
-
|
|
45
|
-
|
|
50
|
+
start(request) {
|
|
51
|
+
const runId = request.runId ?? randomUUID();
|
|
52
|
+
if (this.has(runId) || this.starts.has(runId) || this.recoveries.has(runId)) {
|
|
53
|
+
return Promise.reject(new RuntimeError(`Run already exists: ${runId}`, 'RUN_ID_COLLISION'));
|
|
54
|
+
}
|
|
55
|
+
const starting = Promise.resolve().then(async () => {
|
|
56
|
+
validateTokenBudget(request.budget);
|
|
57
|
+
if (request.objective.trim().length === 0)
|
|
58
|
+
throw new RuntimeError('Runtime objective is required');
|
|
59
|
+
if (await this.dependencies.persistence?.getRun(runId) !== undefined) {
|
|
60
|
+
throw new RuntimeError(`Run already exists: ${runId}`, 'RUN_ID_COLLISION');
|
|
61
|
+
}
|
|
62
|
+
return this.prepare(runId, request);
|
|
63
|
+
}).catch((error) => {
|
|
64
|
+
if (this.has(runId))
|
|
65
|
+
this.executionErrors.set(runId, error);
|
|
66
|
+
throw error;
|
|
67
|
+
}).finally(() => { this.starts.delete(runId); });
|
|
68
|
+
this.starts.set(runId, starting);
|
|
69
|
+
return starting;
|
|
70
|
+
}
|
|
71
|
+
async prepare(runId, request) {
|
|
46
72
|
const fields = this.auditFields(request.correlationId ?? runId);
|
|
47
73
|
const run = {
|
|
48
74
|
...fields,
|
|
@@ -51,6 +77,7 @@ export class RuntimeEngine {
|
|
|
51
77
|
agent: request.agent,
|
|
52
78
|
sprintId: request.sprintId,
|
|
53
79
|
taskId: request.taskId,
|
|
80
|
+
handoffId: request.handoffId,
|
|
54
81
|
policy: { effect: 'ALLOW_WITH_LIMITS', reason: 'Policy is evaluated per capability', policyId: 'runtime-per-capability', limits: { maxTokens: this.limits.maxTokens, maxFiles: this.limits.maxFiles, maxRetries: this.limits.maxRetries } },
|
|
55
82
|
budget: request.budget,
|
|
56
83
|
state: 'created',
|
|
@@ -66,32 +93,65 @@ export class RuntimeEngine {
|
|
|
66
93
|
this.startedAt.set(runId, Date.now());
|
|
67
94
|
await this.dependencies.persistence?.saveRun(run);
|
|
68
95
|
await this.dependencies.persistence?.saveCursor(runId, 0, this.startedAt.get(runId));
|
|
96
|
+
await this.update(runId, { state: 'planning' });
|
|
97
|
+
let plan;
|
|
69
98
|
try {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
99
|
+
const context = Object.hasOwn(request, 'context') ? request.context : await this.dependencies.contextBuilder?.build(request.objective);
|
|
100
|
+
plan = [...await this.dependencies.planner.plan(request.objective, context)];
|
|
101
|
+
if (this.dependencies.persistence !== undefined) {
|
|
102
|
+
// JSON persistence must not change the input bound to an approval on recovery.
|
|
103
|
+
for (const step of plan) {
|
|
104
|
+
if (step.payload !== undefined && !isDeepStrictEqual(step.payload, JSON.parse(JSON.stringify(step.payload)))) {
|
|
105
|
+
throw new RuntimeError('Persisted step payload must round-trip through JSON without changes');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
80
109
|
}
|
|
81
110
|
catch (error) {
|
|
82
111
|
return this.stop(runId, 'failed', this.error('PLANNING_FAILED', this.message(error), false));
|
|
83
112
|
}
|
|
113
|
+
if (this.requestedCancels.has(runId))
|
|
114
|
+
return this.stop(runId, 'cancelled');
|
|
115
|
+
if (plan.length > this.limits.maxSteps)
|
|
116
|
+
return this.stop(runId, 'blocked', this.error('MAX_STEPS_EXCEEDED', 'Plan exceeds maximum steps', false));
|
|
117
|
+
await this.dependencies.persistence?.savePlan(runId, plan);
|
|
118
|
+
this.plans.set(runId, plan);
|
|
119
|
+
await this.saveCheckpoint(runId, 'planning', 0);
|
|
120
|
+
return this.get(runId);
|
|
121
|
+
}
|
|
122
|
+
execute(runId) {
|
|
123
|
+
return this.singleFlight(runId, async () => {
|
|
124
|
+
await this.starts.get(runId);
|
|
125
|
+
return this.executeRun(runId);
|
|
126
|
+
});
|
|
84
127
|
}
|
|
85
|
-
|
|
128
|
+
singleFlight(runId, work) {
|
|
129
|
+
const existing = this.executions.get(runId);
|
|
130
|
+
if (existing !== undefined)
|
|
131
|
+
return existing;
|
|
132
|
+
if (this.executionErrors.has(runId))
|
|
133
|
+
return Promise.reject(this.executionErrors.get(runId));
|
|
134
|
+
const executing = Promise.resolve().then(work).catch((error) => {
|
|
135
|
+
if (this.has(runId) && !(error instanceof RuntimeError && error.code === 'RUN_NOT_RESUMABLE'))
|
|
136
|
+
this.executionErrors.set(runId, error);
|
|
137
|
+
throw error;
|
|
138
|
+
}).finally(() => { this.executions.delete(runId); });
|
|
139
|
+
this.executions.set(runId, executing);
|
|
140
|
+
return executing;
|
|
141
|
+
}
|
|
142
|
+
async executeRun(runId) {
|
|
86
143
|
const current = this.get(runId);
|
|
87
144
|
if (this.isTerminal(current.state))
|
|
88
145
|
return current;
|
|
89
146
|
const plan = this.plans.get(runId);
|
|
90
147
|
if (plan === undefined)
|
|
91
148
|
return this.stop(runId, 'failed', this.error('PLAN_NOT_FOUND', 'Runtime plan is missing', false));
|
|
92
|
-
this.update(runId, { state: 'running' });
|
|
149
|
+
await this.update(runId, { state: 'running' });
|
|
150
|
+
await this.dependencies.beforeExecution?.(this.get(runId));
|
|
93
151
|
while (true) {
|
|
94
152
|
const run = this.get(runId);
|
|
153
|
+
if (this.requestedCancels.has(runId))
|
|
154
|
+
return this.stop(runId, 'cancelled');
|
|
95
155
|
if (this.requestedPauses.has(runId)) {
|
|
96
156
|
this.requestedPauses.delete(runId);
|
|
97
157
|
return this.stop(runId, 'paused');
|
|
@@ -118,14 +178,15 @@ export class RuntimeEngine {
|
|
|
118
178
|
const projectedTokens = beforeAttempt.budget.usedTokens + estimatedTokens;
|
|
119
179
|
if (projectedTokens > beforeAttempt.budget.totalTokens || projectedTokens > this.limits.maxTokens)
|
|
120
180
|
return this.stop(runId, 'blocked', this.error('TOKEN_BUDGET_EXCEEDED', 'Runtime token budget reached', false));
|
|
121
|
-
this.update(runId, { steps: beforeAttempt.steps + 1, budget: { ...beforeAttempt.budget, usedTokens: projectedTokens }, metrics: this.metrics(beforeAttempt, { attempts: beforeAttempt.metrics.attempts + 1, inputTokens: beforeAttempt.metrics.inputTokens + estimatedTokens }) });
|
|
181
|
+
await this.update(runId, { steps: beforeAttempt.steps + 1, budget: { ...beforeAttempt.budget, usedTokens: projectedTokens }, metrics: this.metrics(beforeAttempt, { attempts: beforeAttempt.metrics.attempts + 1, inputTokens: beforeAttempt.metrics.inputTokens + estimatedTokens }) });
|
|
182
|
+
if (this.requestedCancels.has(runId))
|
|
183
|
+
return this.stop(runId, 'cancelled');
|
|
122
184
|
result = await this.dependencies.registry.execute({
|
|
123
185
|
input: { capabilityId: step.capabilityId, payload: step.payload },
|
|
124
186
|
agent: run.agent,
|
|
125
187
|
policy: this.policies.get(runId) ?? (() => { throw new RuntimeError('Runtime policy is missing'); })(),
|
|
126
|
-
// Stable across retries/resume of the same run — without it every attempt looks like a
|
|
127
|
-
// brand-new approval request and a human's decision can never be recognized on retry.
|
|
128
188
|
correlationId: runId,
|
|
189
|
+
operationId: `${runId}:${index}`,
|
|
129
190
|
projectId: step.projectId,
|
|
130
191
|
environment: step.environment,
|
|
131
192
|
categories: step.categories,
|
|
@@ -135,49 +196,78 @@ export class RuntimeEngine {
|
|
|
135
196
|
});
|
|
136
197
|
this.results.get(runId)?.push(result);
|
|
137
198
|
await this.dependencies.persistence?.saveResults(runId, this.results.get(runId) ?? []);
|
|
199
|
+
if (this.requestedCancels.has(runId))
|
|
200
|
+
return this.stop(runId, 'cancelled');
|
|
138
201
|
if (result.status === 'succeeded')
|
|
139
202
|
break;
|
|
140
203
|
if (!result.error?.retryable || attempt > this.limits.maxRetries)
|
|
141
204
|
break;
|
|
142
205
|
const afterAttempt = this.get(runId);
|
|
143
|
-
this.update(runId, { metrics: this.metrics(afterAttempt, { retries: afterAttempt.metrics.retries + 1 }) });
|
|
206
|
+
await this.update(runId, { metrics: this.metrics(afterAttempt, { retries: afterAttempt.metrics.retries + 1 }) });
|
|
144
207
|
} while (attempt <= this.limits.maxRetries);
|
|
145
208
|
if (result.status !== 'succeeded') {
|
|
146
209
|
const state = result.error?.code === 'APPROVAL_REQUIRED' ? 'awaiting_approval' : result.error?.code === 'POLICY_DENIED' ? 'blocked' : 'failed';
|
|
147
210
|
return this.stop(runId, state, result.error);
|
|
148
211
|
}
|
|
149
|
-
this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
|
|
212
|
+
await this.update(runId, { evidence: [...this.get(runId).evidence, ...result.evidence], changedFiles: files });
|
|
150
213
|
await this.dependencies.memory?.remember(this.get(runId), result);
|
|
151
|
-
this.nextSteps.set(runId, index + 1);
|
|
152
214
|
await this.dependencies.persistence?.saveCursor(runId, index + 1, this.startedAt.get(runId) ?? Date.now());
|
|
215
|
+
this.nextSteps.set(runId, index + 1);
|
|
153
216
|
await this.saveCheckpoint(runId, 'running', index + 1);
|
|
154
217
|
}
|
|
155
218
|
}
|
|
156
|
-
|
|
219
|
+
recover(runId, policy) {
|
|
220
|
+
const starting = this.starts.get(runId);
|
|
221
|
+
if (starting !== undefined)
|
|
222
|
+
return starting;
|
|
223
|
+
if (this.has(runId))
|
|
224
|
+
return Promise.resolve(this.get(runId));
|
|
225
|
+
const existing = this.recoveries.get(runId);
|
|
226
|
+
if (existing !== undefined)
|
|
227
|
+
return existing;
|
|
228
|
+
const recovering = this.load(runId, policy).finally(() => { this.recoveries.delete(runId); });
|
|
229
|
+
this.recoveries.set(runId, recovering);
|
|
230
|
+
return recovering;
|
|
231
|
+
}
|
|
232
|
+
async load(runId, policy) {
|
|
157
233
|
const persistence = this.dependencies.persistence;
|
|
158
234
|
if (persistence === undefined)
|
|
159
235
|
throw new RuntimeError('Runtime persistence is not configured');
|
|
160
236
|
const run = await persistence.getRun(runId);
|
|
237
|
+
if (run === undefined)
|
|
238
|
+
throw new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND');
|
|
239
|
+
if (this.isTerminal(run.state)) {
|
|
240
|
+
if (this.has(runId))
|
|
241
|
+
return this.get(runId);
|
|
242
|
+
this.runs.set(runId, run);
|
|
243
|
+
return run;
|
|
244
|
+
}
|
|
161
245
|
const plan = await persistence.getPlan(runId);
|
|
162
|
-
if (run === undefined || plan === undefined)
|
|
163
|
-
throw new RuntimeError(`Persisted runtime is incomplete: ${runId}`);
|
|
164
246
|
const results = await persistence.getResults(runId);
|
|
165
247
|
const cursor = await persistence.getCursor(runId);
|
|
248
|
+
if (this.has(runId))
|
|
249
|
+
return this.get(runId);
|
|
250
|
+
if (plan === undefined || cursor === undefined || !Number.isInteger(cursor.nextStep) || cursor.nextStep < 0 || cursor.nextStep > plan.length || !Number.isFinite(cursor.startedAt)) {
|
|
251
|
+
throw new RuntimeError(`Persisted runtime is incomplete: ${runId}`, 'RECOVERY_INCOMPLETE');
|
|
252
|
+
}
|
|
166
253
|
this.runs.set(runId, run);
|
|
167
254
|
this.plans.set(runId, plan);
|
|
168
255
|
this.results.set(runId, [...(results ?? [])]);
|
|
169
|
-
this.nextSteps.set(runId, cursor
|
|
256
|
+
this.nextSteps.set(runId, cursor.nextStep);
|
|
170
257
|
this.policies.set(runId, policy);
|
|
171
|
-
this.startedAt.set(runId, cursor
|
|
258
|
+
this.startedAt.set(runId, cursor.startedAt);
|
|
172
259
|
return run;
|
|
173
260
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
await this.
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
261
|
+
resume(runId, policy) {
|
|
262
|
+
return this.singleFlight(runId, async () => {
|
|
263
|
+
await this.starts.get(runId);
|
|
264
|
+
if (!this.has(runId) && policy !== undefined)
|
|
265
|
+
await this.recover(runId, policy);
|
|
266
|
+
const run = this.get(runId);
|
|
267
|
+
if (run.state !== 'paused' && run.state !== 'awaiting_approval')
|
|
268
|
+
throw new RuntimeError(`Run is not resumable: ${run.state}`, 'RUN_NOT_RESUMABLE');
|
|
269
|
+
return this.executeRun(runId);
|
|
270
|
+
});
|
|
181
271
|
}
|
|
182
272
|
pause(runId) {
|
|
183
273
|
const run = this.get(runId);
|
|
@@ -185,53 +275,78 @@ export class RuntimeEngine {
|
|
|
185
275
|
this.requestedPauses.add(runId);
|
|
186
276
|
return run;
|
|
187
277
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
278
|
+
cancel(runId) {
|
|
279
|
+
if (!this.has(runId) && !this.starts.has(runId))
|
|
280
|
+
return Promise.reject(new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND'));
|
|
281
|
+
const run = this.runs.get(runId);
|
|
282
|
+
if (run !== undefined && this.isTerminal(run.state))
|
|
283
|
+
return Promise.resolve(run);
|
|
192
284
|
this.requestedPauses.delete(runId);
|
|
193
|
-
|
|
285
|
+
this.requestedCancels.add(runId);
|
|
286
|
+
return this.singleFlight(runId, async () => {
|
|
287
|
+
await this.starts.get(runId);
|
|
288
|
+
return this.stop(runId, 'cancelled');
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
has(runId) {
|
|
292
|
+
return this.runs.has(runId);
|
|
194
293
|
}
|
|
195
294
|
get(runId) {
|
|
196
295
|
const run = this.runs.get(runId);
|
|
197
296
|
if (run === undefined)
|
|
198
|
-
throw new RuntimeError(`Run not found: ${runId}
|
|
297
|
+
throw new RuntimeError(`Run not found: ${runId}`, 'RUN_NOT_FOUND');
|
|
199
298
|
return run;
|
|
200
299
|
}
|
|
201
300
|
async validateAndFinish(runId) {
|
|
202
|
-
this.update(runId, { state: 'validating' });
|
|
301
|
+
await this.update(runId, { state: 'validating' });
|
|
302
|
+
if (this.requestedCancels.has(runId))
|
|
303
|
+
return this.stop(runId, 'cancelled');
|
|
304
|
+
let validation;
|
|
203
305
|
try {
|
|
204
306
|
const run = this.get(runId);
|
|
205
|
-
const
|
|
206
|
-
const
|
|
207
|
-
|
|
307
|
+
const plan = this.plans.get(runId) ?? [];
|
|
308
|
+
const history = this.results.get(runId) ?? [];
|
|
309
|
+
const operationIds = new Set(plan.map((_, index) => `${runId}:${index}`));
|
|
310
|
+
const latest = new Map(history.map((result) => [result.operationId, result]));
|
|
311
|
+
const results = [...operationIds].flatMap((id) => { const result = latest.get(id); return result === undefined ? [] : [result]; });
|
|
312
|
+
const complete = plan.length > 0 && results.length === plan.length && history.every((result) => result.operationId !== undefined && operationIds.has(result.operationId));
|
|
313
|
+
const consistent = results.every((result) => result.status === 'succeeded' && !result.evidence.some((item) => item.status === 'contradicted'));
|
|
314
|
+
validation = !complete || !consistent
|
|
315
|
+
? { ...this.auditFields(run.correlationId), status: !complete ? 'inconclusive' : 'rejected', checks: [{ name: 'final-step-results', passed: complete && consistent, evidenceIds: results.flatMap((result) => result.evidence.map((item) => item.id)) }], summary: !complete ? 'Final step results cannot be established' : 'Final step results failed or contain contradicted evidence' }
|
|
316
|
+
: await this.dependencies.validator.validate(run, results);
|
|
208
317
|
}
|
|
209
318
|
catch (error) {
|
|
210
319
|
return this.stop(runId, 'failed', this.error('VALIDATION_FAILED', this.message(error), false));
|
|
211
320
|
}
|
|
321
|
+
const state = validation.status === 'accepted' ? 'completed' : validation.status === 'blocked' ? 'blocked' : 'failed';
|
|
322
|
+
return this.stop(runId, state, undefined, validation);
|
|
212
323
|
}
|
|
213
|
-
stop(runId, state, error, validation) {
|
|
324
|
+
async stop(runId, state, error, validation) {
|
|
325
|
+
if (this.requestedCancels.has(runId)) {
|
|
326
|
+
state = 'cancelled';
|
|
327
|
+
error = undefined;
|
|
328
|
+
validation = undefined;
|
|
329
|
+
}
|
|
214
330
|
const run = this.get(runId);
|
|
215
331
|
const durationMs = Date.now() - (this.startedAt.get(runId) ?? Date.now());
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
332
|
+
const stopped = { ...run, state, error, validation, metrics: this.metrics(run, { durationMs }), updatedAt: new Date().toISOString() };
|
|
333
|
+
await this.dependencies.persistence?.saveRun(stopped);
|
|
334
|
+
await this.saveCheckpoint(runId, state, this.nextSteps.get(runId) ?? 0, stopped);
|
|
335
|
+
if (state !== 'cancelled' && this.requestedCancels.has(runId))
|
|
336
|
+
return this.stop(runId, 'cancelled');
|
|
337
|
+
this.runs.set(runId, stopped);
|
|
338
|
+
this.requestedCancels.delete(runId);
|
|
339
|
+
return stopped;
|
|
219
340
|
}
|
|
220
|
-
update(runId, patch) {
|
|
221
|
-
|
|
222
|
-
|
|
341
|
+
async update(runId, patch) {
|
|
342
|
+
const updated = { ...this.get(runId), ...patch, updatedAt: new Date().toISOString() };
|
|
343
|
+
await this.dependencies.persistence?.saveRun(updated);
|
|
344
|
+
this.runs.set(runId, updated);
|
|
223
345
|
}
|
|
224
|
-
async
|
|
225
|
-
const persistence = this.dependencies.persistence;
|
|
226
|
-
if (persistence === undefined)
|
|
227
|
-
return;
|
|
228
|
-
await persistence.saveRun(this.get(runId));
|
|
229
|
-
}
|
|
230
|
-
async saveCheckpoint(runId, state, step) {
|
|
346
|
+
async saveCheckpoint(runId, state, step, run = this.get(runId)) {
|
|
231
347
|
const store = this.dependencies.checkpointStore;
|
|
232
348
|
if (store === undefined)
|
|
233
349
|
return;
|
|
234
|
-
const run = this.get(runId);
|
|
235
350
|
const checkpoint = { ...this.auditFields(run.correlationId), id: randomUUID(), runId, step, state, checksum: createHash('sha256').update(JSON.stringify({ runId, step, state, files: run.changedFiles })).digest('hex'), resumable: state === 'paused' || state === 'awaiting_approval' || state === 'running' };
|
|
236
351
|
await store.save(checkpoint);
|
|
237
352
|
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* forja context:smart global (missão, padrões, ADRs)
|
|
5
5
|
* forja context:smart --mode domain + visão/design/regras do projeto
|
|
6
6
|
* forja context:smart --mode task --task pix + nós do projeto que casam com a tarefa (FTS5)
|
|
7
|
+
* forja context:smart --full-context nós inteiros, sem trecho (opt-out da SPEC-057)
|
|
7
8
|
* forja context:smart <projeto> [keyword] forma posicional antiga (studio) — ainda aceita
|
|
8
9
|
*
|
|
9
10
|
* O projeto é inferido de onde o comando roda: no modo embedded é o próprio projeto; no studio,
|
|
@@ -15,5 +16,6 @@ export declare function parseArgs(argv: readonly string[]): {
|
|
|
15
16
|
mode?: string;
|
|
16
17
|
task?: string;
|
|
17
18
|
project?: string;
|
|
19
|
+
full?: boolean;
|
|
18
20
|
positional: string[];
|
|
19
21
|
};
|