forjajs 5.1.0 → 5.3.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.
- package/CHANGELOG.md +76 -0
- package/README.md +37 -4
- package/README.pt-BR.md +39 -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 +349 -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/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-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/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/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 +99 -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,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
|
};
|
|
@@ -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,
|
|
@@ -14,12 +15,15 @@
|
|
|
14
15
|
import fs from 'node:fs';
|
|
15
16
|
import path from 'node:path';
|
|
16
17
|
import { ContextBuilder } from '../lib/context-builder.js';
|
|
18
|
+
import { COMMANDS } from '../lib/core/registry.js';
|
|
17
19
|
import { getDbPath, ensureSchema } from './memory-schema.js';
|
|
18
20
|
import { getForjaMode, getProjectsDir, getWorkspaceContextDir, getWorkspaceRoot, initWorkspace, resolveProject } from '../lib/workspace.js';
|
|
19
21
|
const MODES = ['global', 'domain', 'task'];
|
|
20
22
|
function fail(msg) {
|
|
21
23
|
console.error(msg);
|
|
22
|
-
|
|
24
|
+
// O usage do registro, não um texto à parte: foi assim que o help prometeu três modos que o comando
|
|
25
|
+
// ignorava — duas fontes da mesma frase, e só uma delas era verdade.
|
|
26
|
+
console.error(`Uso: ${COMMANDS['context:smart'].usage}`);
|
|
23
27
|
process.exit(1);
|
|
24
28
|
}
|
|
25
29
|
export function parseArgs(argv) {
|
|
@@ -34,6 +38,8 @@ export function parseArgs(argv) {
|
|
|
34
38
|
opts.task = val();
|
|
35
39
|
else if (a === '--project')
|
|
36
40
|
opts.project = val();
|
|
41
|
+
else if (a === '--full-context')
|
|
42
|
+
opts.full = true;
|
|
37
43
|
else if (a.startsWith('--'))
|
|
38
44
|
fail(`Opção desconhecida: ${a}`);
|
|
39
45
|
else
|
|
@@ -67,7 +73,7 @@ function main() {
|
|
|
67
73
|
ensureSchema({ silent: true });
|
|
68
74
|
const builder = new ContextBuilder(process.cwd(), getDbPath());
|
|
69
75
|
try {
|
|
70
|
-
const content = builder.build(mode, project ?? 'global', keyword);
|
|
76
|
+
const content = builder.build(mode, project ?? 'global', keyword, { full: opts.full === true });
|
|
71
77
|
const outDir = embedded
|
|
72
78
|
? path.join(getWorkspaceRoot(), '.context')
|
|
73
79
|
: project ? path.join(resolveProject(project), '.context') : getWorkspaceContextDir();
|
|
@@ -76,8 +82,11 @@ function main() {
|
|
|
76
82
|
const outFile = path.join(outDir, 'smart-context.md');
|
|
77
83
|
builder.save(content, outFile);
|
|
78
84
|
const files = (content.match(/^\*\*Path\*\*:/gm) || []).length;
|
|
85
|
+
const excerpts = /- \*\*Excerpts\*\*: (\d+)\/(\d+)/.exec(content);
|
|
86
|
+
const cortados = excerpts ? Number(excerpts[1]) : 0;
|
|
79
87
|
console.log(`✓ contexto ${mode}${keyword ? ` ("${keyword}")` : ''}${project ? ` de ${project}` : ''}: ${outFile}`);
|
|
80
|
-
console.log(` ${files} arquivo(s) · ~${Math.round(content.length / 4)} tokens`
|
|
88
|
+
console.log(` ${files} arquivo(s) · ~${Math.round(content.length / 4)} tokens` +
|
|
89
|
+
(cortados ? ` · ${cortados} nó(s) em trecho (--full-context injeta inteiro)` : ''));
|
|
81
90
|
if (files === 0)
|
|
82
91
|
console.log(' nada indexado ainda — rode: forja sync:universal');
|
|
83
92
|
}
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
* code:context — entrega o pacote de contexto mínimo de um domínio (SPEC-016, ADR-0009).
|
|
4
4
|
*
|
|
5
5
|
* forja code:context <domínio> só o mapa (context.md) — o contexto barato
|
|
6
|
-
* forja code:context <domínio> --code + o código da fatia (para editar)
|
|
6
|
+
* forja code:context <domínio> --code + o código da fatia (para editar), por relevância
|
|
7
|
+
* forja code:context <domínio> <termo> --code prioriza os arquivos que casam com o termo
|
|
8
|
+
* forja code:context <domínio> --code --full a fatia inteira, sem orçamento (SPEC-057)
|
|
7
9
|
* forja code:context <domínio> --project <path> aponta para outro projeto
|
|
8
10
|
*
|
|
9
11
|
* O −61% do `token:economy` virado ferramenta: o mapa que substitui a exploração, pronto para colar.
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
* code:context — entrega o pacote de contexto mínimo de um domínio (SPEC-016, ADR-0009).
|
|
4
4
|
*
|
|
5
5
|
* forja code:context <domínio> só o mapa (context.md) — o contexto barato
|
|
6
|
-
* forja code:context <domínio> --code + o código da fatia (para editar)
|
|
6
|
+
* forja code:context <domínio> --code + o código da fatia (para editar), por relevância
|
|
7
|
+
* forja code:context <domínio> <termo> --code prioriza os arquivos que casam com o termo
|
|
8
|
+
* forja code:context <domínio> --code --full a fatia inteira, sem orçamento (SPEC-057)
|
|
7
9
|
* forja code:context <domínio> --project <path> aponta para outro projeto
|
|
8
10
|
*
|
|
9
11
|
* O −61% do `token:economy` virado ferramenta: o mapa que substitui a exploração, pronto para colar.
|
|
@@ -29,8 +31,10 @@ function main() {
|
|
|
29
31
|
positional.push(argv[i]);
|
|
30
32
|
}
|
|
31
33
|
const domain = positional[0];
|
|
34
|
+
const query = positional.slice(1).join(' ');
|
|
32
35
|
const projectRoot = path.resolve(arg('--project') || process.cwd());
|
|
33
36
|
const includeCode = process.argv.includes('--code');
|
|
37
|
+
const full = process.argv.includes('--full');
|
|
34
38
|
const available = domainsOf(projectRoot);
|
|
35
39
|
if (!domain) {
|
|
36
40
|
if (!available.length) {
|
|
@@ -38,11 +42,11 @@ function main() {
|
|
|
38
42
|
console.error('Rode dentro de um projeto gerado, ou aponte com --project <path>.');
|
|
39
43
|
process.exit(1);
|
|
40
44
|
}
|
|
41
|
-
console.log('Uso: forja code:context <domínio> [--code] [--project <path>]\n');
|
|
45
|
+
console.log('Uso: forja code:context <domínio> [termo] [--code] [--full] [--project <path>]\n');
|
|
42
46
|
console.log(`Domínios disponíveis: ${available.join(', ')}`);
|
|
43
47
|
return;
|
|
44
48
|
}
|
|
45
|
-
const pack = buildContextPack({ projectRoot, domain, includeCode });
|
|
49
|
+
const pack = buildContextPack({ projectRoot, domain, includeCode, query, full });
|
|
46
50
|
if (!pack.found) {
|
|
47
51
|
console.error(`Domínio "${domain}" não tem context.md em ${projectRoot}.`);
|
|
48
52
|
if (available.length)
|
|
@@ -65,6 +69,12 @@ function main() {
|
|
|
65
69
|
console.error(''); // separa do stdout colável
|
|
66
70
|
if (includeCode) {
|
|
67
71
|
console.error(`— pacote completo: ${pack.totalTokens} tokens (mapa ${pack.mapTokens} + código ${pack.codeTokens}, ${pack.code.length} arquivos).`);
|
|
72
|
+
if (pack.codeOmitted.length) {
|
|
73
|
+
const omitidos = pack.codeOmitted.reduce((acc, c) => acc + c.tokens, 0);
|
|
74
|
+
console.error(`— fora do orçamento: ${pack.codeOmitted.length} arquivos (${omitidos} tokens) · --full traz a fatia inteira.`);
|
|
75
|
+
for (const c of pack.codeOmitted)
|
|
76
|
+
console.error(` ${c.path} (${c.tokens} tokens)`);
|
|
77
|
+
}
|
|
68
78
|
}
|
|
69
79
|
else {
|
|
70
80
|
console.error(`— só o mapa: ${pack.mapTokens} tokens. Para editar, adicione o código com --code, ou o blast radius com \`forja code:impact <símbolo>\`.`);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* quality:coverage — roda a suíte com a cobertura nativa do Node e cobra o piso versionado (SPEC-056).
|
|
4
|
+
*
|
|
5
|
+
* Sem c8/istanbul de propósito: `node --test --experimental-test-coverage` já produz a tabela, e o
|
|
6
|
+
* trabalho aqui é ler a linha "all files" e comparar com `coverageLineFloor` de
|
|
7
|
+
* `lib/core/quality-budget.json`. É o ratchet gêmeo do check `type-debt`: o piso só desce em commit
|
|
8
|
+
* explícito, e a suíte continua sendo a mesma — não há segunda máquina de teste.
|
|
9
|
+
*
|
|
10
|
+
* A saída do filho é capturada e reimpressa inteira: o CI precisa ver cada teste, e o parsing precisa
|
|
11
|
+
* da tabela. Piso abaixo do combinado → exit 2 (`emitRejected`): gate negativo, não falha operacional.
|
|
12
|
+
*
|
|
13
|
+
* Ler a tabela, ler o piso e decidir o código de saída vive em `lib/core/coverage-gate.ts` — aqui só
|
|
14
|
+
* a coleta e a emissão, porque um teste deste script rodaria a suíte dentro da suíte (AC-3).
|
|
15
|
+
*
|
|
16
|
+
* A régua só vale se se repetir: `test/isolate-workspace.mjs` retira `NODE_V8_COVERAGE` do ambiente para
|
|
17
|
+
* que os CLIs filhos não despejem blocos parciais na agregação do Node — antes disso o `all files`
|
|
18
|
+
* variava 1,6pp entre execuções idênticas e o piso era sorteio (ver Evidências da SPEC-056).
|
|
19
|
+
*/
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { spawnSync } from 'node:child_process';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { emitError, emitOk, emitRejected } from '../lib/cli-output.js';
|
|
25
|
+
import { asErrno } from '../lib/core/checks.js';
|
|
26
|
+
import { coverageFloorFrom, coverageSummary, decideCoverage, parseCoverageTotal } from '../lib/core/coverage-gate.js';
|
|
27
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
28
|
+
const BUDGET_LABEL = 'lib/core/quality-budget.json';
|
|
29
|
+
const BUDGET = path.join(ROOT, 'lib', 'core', 'quality-budget.json');
|
|
30
|
+
const asJson = process.argv.includes('--json');
|
|
31
|
+
function floor() {
|
|
32
|
+
let text;
|
|
33
|
+
try {
|
|
34
|
+
text = fs.readFileSync(BUDGET, 'utf8');
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
throw new Error(`orçamento ilegível (${BUDGET_LABEL}): ${asErrno(err).message}`);
|
|
38
|
+
}
|
|
39
|
+
return coverageFloorFrom(text, BUDGET_LABEL);
|
|
40
|
+
}
|
|
41
|
+
function testFiles() {
|
|
42
|
+
const dir = path.join(ROOT, 'test');
|
|
43
|
+
return fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => path.join('test', f));
|
|
44
|
+
}
|
|
45
|
+
let piso;
|
|
46
|
+
try {
|
|
47
|
+
piso = floor();
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
const mensagem = asErrno(err).message;
|
|
51
|
+
if (asJson)
|
|
52
|
+
emitError(mensagem, { code: 'EBUDGET' });
|
|
53
|
+
console.error(mensagem);
|
|
54
|
+
process.exit(1);
|
|
55
|
+
}
|
|
56
|
+
const files = testFiles();
|
|
57
|
+
if (files.length === 0) {
|
|
58
|
+
if (asJson)
|
|
59
|
+
emitError('nenhum test/*.test.js encontrado', { code: 'ENOTEST' });
|
|
60
|
+
console.error('nenhum test/*.test.js encontrado');
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
const run = spawnSync(process.execPath, ['--test', '--experimental-test-coverage', '--import', './test/isolate-workspace.mjs', ...files], { cwd: ROOT, encoding: 'utf8' });
|
|
64
|
+
process.stdout.write(run.stdout ?? '');
|
|
65
|
+
process.stderr.write(run.stderr ?? '');
|
|
66
|
+
const total = parseCoverageTotal(run.stdout ?? '');
|
|
67
|
+
const outcome = decideCoverage({
|
|
68
|
+
spawnError: run.error !== undefined ? run.error.message : null,
|
|
69
|
+
total,
|
|
70
|
+
suiteStatus: run.status,
|
|
71
|
+
floor: piso,
|
|
72
|
+
});
|
|
73
|
+
if (run.error !== undefined) {
|
|
74
|
+
if (asJson)
|
|
75
|
+
emitError(`suíte não rodou: ${run.error.message}`, { code: outcome.code });
|
|
76
|
+
process.exit(outcome.exitCode);
|
|
77
|
+
}
|
|
78
|
+
if (total === null) {
|
|
79
|
+
if (asJson)
|
|
80
|
+
emitError('tabela de cobertura não encontrada na saída da suíte', { code: outcome.code });
|
|
81
|
+
console.error('não achei a linha "all files" da cobertura — o formato do Node mudou?');
|
|
82
|
+
process.exit(outcome.exitCode);
|
|
83
|
+
}
|
|
84
|
+
const payload = { lines: total.lines, branches: total.branches, funcs: total.funcs, floor: piso };
|
|
85
|
+
const resumo = coverageSummary(total, piso);
|
|
86
|
+
if (outcome.kind === 'suite-failed') {
|
|
87
|
+
if (asJson)
|
|
88
|
+
emitRejected({ ...payload, suiteExitCode: run.status ?? 'sinal' });
|
|
89
|
+
console.error(`suíte falhou (exit ${run.status ?? 'sinal'}) — ${resumo}`);
|
|
90
|
+
process.exit(outcome.exitCode);
|
|
91
|
+
}
|
|
92
|
+
if (outcome.kind === 'below-floor') {
|
|
93
|
+
if (asJson)
|
|
94
|
+
emitRejected({ ...payload, gap: Number((piso - total.lines).toFixed(2)) });
|
|
95
|
+
console.error(`ABAIXO DO PISO: ${resumo}`);
|
|
96
|
+
console.error('cubra o que o PR descobriu, ou desça o piso num commit próprio e justificado.');
|
|
97
|
+
process.exit(outcome.exitCode);
|
|
98
|
+
}
|
|
99
|
+
if (asJson)
|
|
100
|
+
emitOk(payload);
|
|
101
|
+
console.log(`OK ${resumo}`);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* eval:agents — avaliações com agentes reais em projeto descartável (SPEC-054, ADR-0093).
|
|
4
|
+
*
|
|
5
|
+
* forja eval:agents --agent claude|codex [--case a,b] [--model m] [--budget-usd n]
|
|
6
|
+
* [--timeout s] [--keep] [--list] [--json]
|
|
7
|
+
*
|
|
8
|
+
* Custa: cada caso é uma sessão real do agente. Exit 0 = todos passaram, 2 = algum falhou,
|
|
9
|
+
* 1 = agente ausente, caso inexistente ou argumento inválido.
|
|
10
|
+
*/
|
|
11
|
+
export {};
|