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
|
@@ -10,7 +10,11 @@ export const MCP_RESOURCE_URIS = [
|
|
|
10
10
|
export class McpAdapterError extends Error {
|
|
11
11
|
constructor(message) { super(message); this.name = 'McpAdapterError'; }
|
|
12
12
|
}
|
|
13
|
+
export const PLANNING_PROPOSE_SCHEMA = { type: 'object', properties: { taskId: { type: 'string', minLength: 1 }, handoffId: { type: 'string', minLength: 1 }, correlationId: { type: 'string', minLength: 1 }, budget: { type: 'object', properties: Object.fromEntries(['inputTokens', 'outputTokens', 'totalTokens', 'usedTokens'].map((field) => [field, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }])), required: ['inputTokens', 'outputTokens', 'totalTokens', 'usedTokens'], additionalProperties: false } }, required: ['taskId'], additionalProperties: false };
|
|
14
|
+
export const PLANNING_REVIEW_SCHEMA = { type: 'object', properties: { decision: { type: 'string', enum: ['approved', 'rejected'] }, expectedDigest: { type: 'string', minLength: 1 }, reason: { type: 'string', minLength: 1 } }, required: ['decision', 'expectedDigest', 'reason'], additionalProperties: false };
|
|
13
15
|
export const MCP_TOOLS = [
|
|
16
|
+
{ name: 'forja_plan_propose', description: 'Gera proposta descritiva revisável sem executar capabilities.', inputSchema: PLANNING_PROPOSE_SCHEMA },
|
|
17
|
+
tool('forja_plan_get', 'Consulta uma proposta de planejamento persistida.', ['id']),
|
|
14
18
|
tool('forja_workspace_status', 'Retorna o estado operacional mínimo do workspace.', []),
|
|
15
19
|
tool('forja_capabilities_list', 'Lista capabilities visíveis para a identidade MCP.', []),
|
|
16
20
|
tool('forja_capability_describe', 'Descreve uma capability pelo Registry.', ['capabilityId']),
|
|
@@ -79,6 +83,11 @@ export class McpServer {
|
|
|
79
83
|
}
|
|
80
84
|
async dispatch(name, input) {
|
|
81
85
|
switch (name) {
|
|
86
|
+
case 'forja_plan_propose': return this.requirePlanning().propose(input);
|
|
87
|
+
case 'forja_plan_get':
|
|
88
|
+
if (Object.keys(input).some((key) => key !== 'id'))
|
|
89
|
+
throw new McpAdapterError('Unexpected planning input fields');
|
|
90
|
+
return this.requirePlanning().get(this.string(input, 'id'));
|
|
82
91
|
case 'forja_workspace_status': return { agent: this.dependencies.agent, capabilities: this.dependencies.registry.list({ agent: this.dependencies.agent }), resources: this.listResources().map((resource) => resource.uri) };
|
|
83
92
|
case 'forja_capabilities_list': return this.dependencies.registry.list({ agent: this.dependencies.agent, policy: this.dependencies.policy });
|
|
84
93
|
case 'forja_capability_describe': return this.dependencies.registry.describe(this.string(input, 'capabilityId'), { agent: this.dependencies.agent, policy: this.dependencies.policy });
|
|
@@ -125,7 +134,7 @@ export class McpServer {
|
|
|
125
134
|
this.authorize('forja_handoff_create', 'write', 'medium', []);
|
|
126
135
|
return this.requireHandoffs().create({
|
|
127
136
|
from: this.string(input, 'from'), to: this.string(input, 'to'), intent: this.string(input, 'intent'), objective: this.string(input, 'objective'),
|
|
128
|
-
completedWork: this.strings(input, 'completedWork'), decisions: this.strings(input, 'decisions'), constraints: this.strings(input, 'constraints'), pending: this.strings(input, 'pending'), evidenceIds: this.entities(input, 'evidenceIds'), acceptance: this.strings(input, 'acceptance'), blockers: this.strings(input, 'blockers'), nextAgent: this.string(input, 'nextAgent'), correlationId: this.optionalString(input, 'correlationId'),
|
|
137
|
+
completedWork: this.strings(input, 'completedWork'), decisions: this.strings(input, 'decisions'), constraints: this.strings(input, 'constraints'), pending: this.strings(input, 'pending'), evidenceIds: this.entities(input, 'evidenceIds'), acceptance: this.strings(input, 'acceptance'), blockers: this.strings(input, 'blockers'), nextAgent: this.string(input, 'nextAgent'), correlationId: this.optionalString(input, 'correlationId'), taskId: input.taskId === undefined ? undefined : this.entity(input, 'taskId'),
|
|
129
138
|
});
|
|
130
139
|
}
|
|
131
140
|
executeCapability(input) {
|
|
@@ -170,6 +179,8 @@ export class McpServer {
|
|
|
170
179
|
optionalStatus(input, field) { const value = input[field]; if (value === undefined)
|
|
171
180
|
return undefined; if (value !== 'verified' && value !== 'inferred' && value !== 'hypothesis' && value !== 'contradicted' && value !== 'unknown')
|
|
172
181
|
throw new McpAdapterError(`${field} is an invalid knowledge status`); return value; }
|
|
182
|
+
requirePlanning() { if (this.dependencies.planning === undefined)
|
|
183
|
+
throw new McpAdapterError('Planning service is not configured'); return this.dependencies.planning; }
|
|
173
184
|
requireContext() { if (this.dependencies.context === undefined)
|
|
174
185
|
throw new McpAdapterError('Context Engine is not configured'); return this.dependencies.context; }
|
|
175
186
|
requireGraph() { if (this.dependencies.graph === undefined)
|
|
@@ -29,6 +29,9 @@ export interface ObservationStore {
|
|
|
29
29
|
export interface ControlPlanePort {
|
|
30
30
|
metrics(): ControlPlaneMetrics | Promise<ControlPlaneMetrics>;
|
|
31
31
|
observations(): readonly Observation[] | Promise<readonly Observation[]>;
|
|
32
|
+
planPropose?(input: unknown): unknown | Promise<unknown>;
|
|
33
|
+
planGet?(id: string): unknown | Promise<unknown>;
|
|
34
|
+
planReview?(id: string, input: unknown): unknown | Promise<unknown>;
|
|
32
35
|
runtimeStart?(input: unknown): unknown | Promise<unknown>;
|
|
33
36
|
runtimeGet?(id: string): unknown | Promise<unknown>;
|
|
34
37
|
runtimeExecute?(id: string): unknown | Promise<unknown>;
|
|
@@ -57,6 +60,11 @@ export interface ControlPlaneEventSink {
|
|
|
57
60
|
publish(event: ControlPlaneEvent): void;
|
|
58
61
|
}
|
|
59
62
|
export interface ControlPlaneServices {
|
|
63
|
+
readonly planning?: {
|
|
64
|
+
readonly propose: (input: unknown) => unknown | Promise<unknown>;
|
|
65
|
+
readonly get: (id: string) => unknown | Promise<unknown>;
|
|
66
|
+
readonly review: (id: string, input: unknown) => unknown | Promise<unknown>;
|
|
67
|
+
};
|
|
60
68
|
readonly runtime?: {
|
|
61
69
|
readonly start: (input: unknown) => unknown | Promise<unknown>;
|
|
62
70
|
readonly get: (input: unknown) => unknown | Promise<unknown>;
|
|
@@ -110,6 +118,9 @@ export declare class ControlPlane implements ControlPlanePort {
|
|
|
110
118
|
metrics(): Promise<ControlPlaneMetrics>;
|
|
111
119
|
observations(): Promise<readonly Observation[]>;
|
|
112
120
|
record(input: ObservationInput): Promise<Observation>;
|
|
121
|
+
planPropose(input: unknown): Promise<unknown>;
|
|
122
|
+
planGet(id: string): Promise<unknown>;
|
|
123
|
+
planReview(id: string, input: unknown): Promise<unknown>;
|
|
113
124
|
runtimeStart(input: unknown): Promise<unknown>;
|
|
114
125
|
runtimeGet(id: string): Promise<unknown>;
|
|
115
126
|
runtimeExecute(id: string): Promise<unknown>;
|
|
@@ -47,6 +47,9 @@ export class ControlPlane {
|
|
|
47
47
|
metrics() { return this.recorder.metrics(); }
|
|
48
48
|
observations() { return this.recorder.observations(); }
|
|
49
49
|
async record(input) { const observation = await this.recorder.record(input); this.services.events?.publish({ id: observation.id, type: 'observation.recorded', aggregateId: observation.runId ?? observation.traceId, data: observation, correlationId: observation.correlationId }); return observation; }
|
|
50
|
+
planPropose(input) { return this.delegate(this.services.planning?.propose, input, 'planPropose'); }
|
|
51
|
+
planGet(id) { const service = this.services.planning; return this.delegate(service === undefined ? undefined : () => service.get(id), id, 'planGet'); }
|
|
52
|
+
planReview(id, input) { const service = this.services.planning; return this.delegate(service === undefined ? undefined : () => service.review(id, input), input, 'planReview'); }
|
|
50
53
|
runtimeStart(input) { return this.delegate(this.services.runtime?.start, input, 'runtimeStart'); }
|
|
51
54
|
runtimeGet(id) { return this.delegate(this.services.runtime?.get, id, 'runtimeGet'); }
|
|
52
55
|
runtimeExecute(id) { return this.delegate(this.services.runtime?.execute, id, 'runtimeExecute'); }
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { type EntityId, type EvaluationResult, type Handoff, type Sprint, type Task, type TokenBudget } from '../../contracts/src/index.ts';
|
|
2
|
+
export interface ExecutionTransition {
|
|
3
|
+
readonly recoveryBlock?: true;
|
|
4
|
+
readonly beforeTask: Task;
|
|
5
|
+
readonly task: Task;
|
|
6
|
+
readonly beforeHandoff?: Handoff;
|
|
7
|
+
readonly handoff?: Handoff;
|
|
8
|
+
}
|
|
2
9
|
export interface OrchestrationStore {
|
|
10
|
+
transitionExecution(input: ExecutionTransition): void | Promise<void>;
|
|
3
11
|
saveSprint(value: Sprint): void | Promise<void>;
|
|
4
12
|
getSprint(id: EntityId): Sprint | undefined | Promise<Sprint | undefined>;
|
|
5
13
|
listSprints(): readonly Sprint[] | Promise<readonly Sprint[]>;
|
|
@@ -43,6 +51,7 @@ export interface CreateTaskInput {
|
|
|
43
51
|
readonly correlationId?: string;
|
|
44
52
|
}
|
|
45
53
|
export interface CreateHandoffInput {
|
|
54
|
+
readonly taskId?: EntityId;
|
|
46
55
|
readonly from: string;
|
|
47
56
|
readonly to: string;
|
|
48
57
|
readonly intent: string;
|
|
@@ -60,6 +69,8 @@ export interface CreateHandoffInput {
|
|
|
60
69
|
export declare class OrchestrationError extends Error {
|
|
61
70
|
constructor(message: string);
|
|
62
71
|
}
|
|
72
|
+
/** Shared invariants for the two stores; callers must check and write without yielding. */
|
|
73
|
+
export declare function assertExecutionTransition(input: ExecutionTransition, currentTask: Task | undefined, currentHandoff?: Handoff): void;
|
|
63
74
|
export declare class InMemoryOrchestrationStore implements OrchestrationStore {
|
|
64
75
|
private readonly sprints;
|
|
65
76
|
private readonly tasks;
|
|
@@ -73,6 +84,7 @@ export declare class InMemoryOrchestrationStore implements OrchestrationStore {
|
|
|
73
84
|
saveHandoff(value: Handoff): void;
|
|
74
85
|
getHandoff(id: EntityId): Handoff | undefined;
|
|
75
86
|
listHandoffs(): readonly Handoff[];
|
|
87
|
+
transitionExecution(input: ExecutionTransition): void;
|
|
76
88
|
}
|
|
77
89
|
export declare class SprintEngine {
|
|
78
90
|
private readonly store;
|
|
@@ -109,11 +121,13 @@ export declare class TaskEngine {
|
|
|
109
121
|
private readonly graph?;
|
|
110
122
|
constructor(store: OrchestrationStore, sprintEngine: SprintEngine, graph?: GraphRecorder);
|
|
111
123
|
create(input: CreateTaskInput): Promise<Task>;
|
|
124
|
+
assertEligible(task: Task): Promise<void>;
|
|
112
125
|
next(sprintId: EntityId): Promise<Task | undefined>;
|
|
113
126
|
start(id: EntityId): Promise<Task>;
|
|
114
127
|
block(id: EntityId): Promise<Task>;
|
|
115
128
|
complete(id: EntityId, validator: CompletionValidator): Promise<Task>;
|
|
116
|
-
|
|
129
|
+
private assertDependencies;
|
|
130
|
+
private assertUnlinked;
|
|
117
131
|
private saveTaskGuarded;
|
|
118
132
|
private require;
|
|
119
133
|
private updated;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
3
|
import { CONTRACT_VERSION, validateTokenBudget, } from '../../contracts/src/index.js';
|
|
3
4
|
export class OrchestrationError extends Error {
|
|
4
5
|
constructor(message) {
|
|
@@ -6,6 +7,60 @@ export class OrchestrationError extends Error {
|
|
|
6
7
|
this.name = 'OrchestrationError';
|
|
7
8
|
}
|
|
8
9
|
}
|
|
10
|
+
// Compare persisted JSON values, not object identity, key order or timestamp alone.
|
|
11
|
+
function jsonSnapshot(value) { return JSON.parse(JSON.stringify(value)); }
|
|
12
|
+
function sameSnapshot(expected, current) {
|
|
13
|
+
return current !== undefined && isDeepStrictEqual(jsonSnapshot(expected), jsonSnapshot(current));
|
|
14
|
+
}
|
|
15
|
+
function requireId(value, field) {
|
|
16
|
+
if (typeof value !== 'string' || value.trim().length === 0)
|
|
17
|
+
throw new OrchestrationError(`${field} must be a non-empty ID`);
|
|
18
|
+
}
|
|
19
|
+
/** Shared invariants for the two stores; callers must check and write without yielding. */
|
|
20
|
+
export function assertExecutionTransition(input, currentTask, currentHandoff) {
|
|
21
|
+
const { beforeTask, task, beforeHandoff, handoff } = input;
|
|
22
|
+
for (const value of [beforeTask, task]) {
|
|
23
|
+
requireId(value.id, 'task.id');
|
|
24
|
+
requireId(value.sprintId, 'task.sprintId');
|
|
25
|
+
if (value.runtimeRunId !== undefined)
|
|
26
|
+
requireId(value.runtimeRunId, 'task.runtimeRunId');
|
|
27
|
+
if (value.handoffId !== undefined)
|
|
28
|
+
requireId(value.handoffId, 'task.handoffId');
|
|
29
|
+
}
|
|
30
|
+
if (beforeTask.id !== task.id || beforeTask.sprintId !== task.sprintId)
|
|
31
|
+
throw new OrchestrationError('Execution transition cannot change task or sprint identity');
|
|
32
|
+
if (beforeTask.runtimeRunId !== undefined && beforeTask.runtimeRunId !== task.runtimeRunId)
|
|
33
|
+
throw new OrchestrationError(`Task is already linked to run: ${beforeTask.runtimeRunId}`);
|
|
34
|
+
if (beforeTask.handoffId !== undefined && beforeTask.handoffId !== task.handoffId)
|
|
35
|
+
throw new OrchestrationError('Execution transition cannot replace the linked handoff');
|
|
36
|
+
if (beforeTask.executionScopeHash !== undefined && beforeTask.executionScopeHash !== task.executionScopeHash)
|
|
37
|
+
throw new OrchestrationError('Execution scope cannot change after reservation');
|
|
38
|
+
if (input.recoveryBlock && (task.status !== 'blocked' || !['RECOVERY_INCOMPLETE', 'BINDING_MISMATCH'].includes(task.executionError?.code ?? '') || beforeTask.runtimeRunId === undefined || beforeTask.runtimeRunId !== task.runtimeRunId))
|
|
39
|
+
throw new OrchestrationError('Recovery may only block an existing execution binding');
|
|
40
|
+
if ((beforeHandoff === undefined) !== (handoff === undefined))
|
|
41
|
+
throw new OrchestrationError('Execution transition requires both handoff snapshots');
|
|
42
|
+
if (handoff !== undefined && beforeHandoff !== undefined) {
|
|
43
|
+
for (const value of [beforeHandoff, handoff]) {
|
|
44
|
+
requireId(value.id, 'handoff.id');
|
|
45
|
+
requireId(value.taskId, 'handoff.taskId');
|
|
46
|
+
if (value.runId !== undefined)
|
|
47
|
+
requireId(value.runId, 'handoff.runId');
|
|
48
|
+
}
|
|
49
|
+
if (beforeHandoff.id !== handoff.id || beforeHandoff.taskId !== task.id || handoff.taskId !== task.id || task.handoffId !== handoff.id)
|
|
50
|
+
throw new OrchestrationError('Execution task/handoff pairing does not match');
|
|
51
|
+
if (beforeTask.handoffId !== undefined && beforeTask.handoffId !== beforeHandoff.id)
|
|
52
|
+
throw new OrchestrationError('Previous task/handoff pairing does not match');
|
|
53
|
+
if (beforeHandoff.runId !== beforeTask.runtimeRunId || handoff.runId !== task.runtimeRunId || (beforeHandoff.runId !== undefined && beforeTask.handoffId !== beforeHandoff.id))
|
|
54
|
+
throw new OrchestrationError('Execution task/handoff run pairing does not match');
|
|
55
|
+
}
|
|
56
|
+
else if (!input.recoveryBlock && (beforeTask.handoffId !== undefined || task.handoffId !== undefined)) {
|
|
57
|
+
throw new OrchestrationError('Linked handoff must participate in the execution transition');
|
|
58
|
+
}
|
|
59
|
+
if (!sameSnapshot(beforeTask, currentTask))
|
|
60
|
+
throw new OrchestrationError(`Task was modified concurrently: ${beforeTask.id}${currentTask?.runtimeRunId ? ` (run: ${currentTask.runtimeRunId})` : ''}`);
|
|
61
|
+
if (beforeHandoff !== undefined && !sameSnapshot(beforeHandoff, currentHandoff))
|
|
62
|
+
throw new OrchestrationError(`Handoff was modified concurrently: ${beforeHandoff.id}`);
|
|
63
|
+
}
|
|
9
64
|
export class InMemoryOrchestrationStore {
|
|
10
65
|
sprints = new Map();
|
|
11
66
|
tasks = new Map();
|
|
@@ -13,15 +68,23 @@ export class InMemoryOrchestrationStore {
|
|
|
13
68
|
saveSprint(value) { this.sprints.set(value.id, value); }
|
|
14
69
|
getSprint(id) { return this.sprints.get(id); }
|
|
15
70
|
listSprints() { return [...this.sprints.values()]; }
|
|
16
|
-
saveTask(value) { this.tasks.set(value.id, value); }
|
|
17
|
-
getTask(id) {
|
|
71
|
+
saveTask(value) { this.tasks.set(value.id, jsonSnapshot(value)); }
|
|
72
|
+
getTask(id) { const value = this.tasks.get(id); return value === undefined ? undefined : jsonSnapshot(value); }
|
|
18
73
|
listTasks(sprintId) {
|
|
19
74
|
const values = [...this.tasks.values()];
|
|
20
|
-
return sprintId === undefined ? values : values.filter((task) => task.sprintId === sprintId);
|
|
75
|
+
return jsonSnapshot(sprintId === undefined ? values : values.filter((task) => task.sprintId === sprintId));
|
|
76
|
+
}
|
|
77
|
+
saveHandoff(value) { this.handoffs.set(value.id, jsonSnapshot(value)); }
|
|
78
|
+
getHandoff(id) { const value = this.handoffs.get(id); return value === undefined ? undefined : jsonSnapshot(value); }
|
|
79
|
+
listHandoffs() { return jsonSnapshot([...this.handoffs.values()]); }
|
|
80
|
+
transitionExecution(input) {
|
|
81
|
+
// Prepare both values before touching either map, including all serialization failures.
|
|
82
|
+
const snapshot = jsonSnapshot(input);
|
|
83
|
+
assertExecutionTransition(snapshot, this.tasks.get(snapshot.beforeTask.id), snapshot.beforeHandoff === undefined ? undefined : this.handoffs.get(snapshot.beforeHandoff.id));
|
|
84
|
+
this.tasks.set(snapshot.task.id, snapshot.task);
|
|
85
|
+
if (snapshot.handoff !== undefined)
|
|
86
|
+
this.handoffs.set(snapshot.handoff.id, snapshot.handoff);
|
|
21
87
|
}
|
|
22
|
-
saveHandoff(value) { this.handoffs.set(value.id, value); }
|
|
23
|
-
getHandoff(id) { return this.handoffs.get(id); }
|
|
24
|
-
listHandoffs() { return [...this.handoffs.values()]; }
|
|
25
88
|
}
|
|
26
89
|
export class SprintEngine {
|
|
27
90
|
store;
|
|
@@ -117,6 +180,7 @@ export class TaskEngine {
|
|
|
117
180
|
throw new OrchestrationError('Task requires an open sprint');
|
|
118
181
|
if (input.objective.trim().length === 0 || input.acceptanceCriteria.length === 0)
|
|
119
182
|
throw new OrchestrationError('Task objective and acceptance criteria are required');
|
|
183
|
+
await this.assertDependencies(input, false);
|
|
120
184
|
validateTokenBudget(input.budget);
|
|
121
185
|
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' };
|
|
122
186
|
await this.store.saveTask(value);
|
|
@@ -125,29 +189,49 @@ export class TaskEngine {
|
|
|
125
189
|
await this.graph.record({ kind: 'task', id: value.id, relatedIds: [value.sprintId, ...value.dependencyIds], evidenceIds: value.evidenceIds });
|
|
126
190
|
return value;
|
|
127
191
|
}
|
|
192
|
+
async assertEligible(task) {
|
|
193
|
+
const sprint = await this.store.getSprint(task.sprintId);
|
|
194
|
+
if (!sprint || sprint.status !== 'active')
|
|
195
|
+
throw new OrchestrationError('Task requires an active sprint');
|
|
196
|
+
await this.assertDependencies(task, true);
|
|
197
|
+
}
|
|
128
198
|
async next(sprintId) {
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
199
|
+
const sprint = await this.store.getSprint(sprintId);
|
|
200
|
+
if (!sprint || sprint.status !== 'active')
|
|
201
|
+
return undefined;
|
|
202
|
+
const tasks = (await this.store.listTasks(sprintId))
|
|
203
|
+
.filter((task) => task.status === 'todo' && task.runtimeRunId === undefined)
|
|
204
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
205
|
+
for (const task of tasks) {
|
|
206
|
+
try {
|
|
207
|
+
await this.assertEligible(task);
|
|
208
|
+
return task;
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (!(error instanceof OrchestrationError))
|
|
212
|
+
throw error;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return undefined;
|
|
132
216
|
}
|
|
133
217
|
async start(id) {
|
|
134
218
|
const task = await this.require(id);
|
|
135
|
-
|
|
136
|
-
if (!sprint || sprint.status !== 'active')
|
|
137
|
-
throw new OrchestrationError('Task requires an active sprint');
|
|
219
|
+
this.assertUnlinked(task);
|
|
138
220
|
if (task.status !== 'todo' && task.status !== 'blocked')
|
|
139
221
|
throw new OrchestrationError(`Invalid task start from ${task.status}`);
|
|
222
|
+
await this.assertEligible(task);
|
|
140
223
|
const updated = this.updated(task, { status: 'in_progress' });
|
|
141
224
|
await this.saveTaskGuarded(task, updated);
|
|
142
225
|
return updated;
|
|
143
226
|
}
|
|
144
|
-
async block(id) { const task = await this.require(id); if (task.status !== 'in_progress')
|
|
227
|
+
async block(id) { const task = await this.require(id); this.assertUnlinked(task); if (task.status !== 'in_progress')
|
|
145
228
|
throw new OrchestrationError('Only an in-progress task can be blocked'); const updated = this.updated(task, { status: 'blocked' }); await this.saveTaskGuarded(task, updated); return updated; }
|
|
146
229
|
async complete(id, validator) {
|
|
147
230
|
const task = await this.require(id);
|
|
231
|
+
this.assertUnlinked(task);
|
|
148
232
|
if (task.status !== 'in_progress')
|
|
149
233
|
throw new OrchestrationError('Only an in-progress task can be completed');
|
|
150
|
-
const result = await validator.validateTask(task);
|
|
234
|
+
const result = await validator.validateTask(jsonSnapshot(task));
|
|
151
235
|
if (result.status !== 'accepted')
|
|
152
236
|
throw new OrchestrationError(`Task validation did not accept completion: ${result.status}`);
|
|
153
237
|
const evidenceIds = this.unique([...task.evidenceIds, ...result.checks.flatMap((check) => check.evidenceIds)]);
|
|
@@ -157,15 +241,26 @@ export class TaskEngine {
|
|
|
157
241
|
await this.graph.record({ kind: 'task', id: updated.id, relatedIds: [updated.sprintId, ...updated.dependencyIds], evidenceIds });
|
|
158
242
|
return updated;
|
|
159
243
|
}
|
|
160
|
-
|
|
244
|
+
async assertDependencies(task, requireDone) {
|
|
245
|
+
for (const id of task.dependencyIds) {
|
|
246
|
+
const dependency = await this.store.getTask(id);
|
|
247
|
+
if (!dependency || dependency.sprintId !== task.sprintId)
|
|
248
|
+
throw new OrchestrationError(`Task dependency must exist in the same sprint: ${id}`);
|
|
249
|
+
if (requireDone && dependency.status !== 'done')
|
|
250
|
+
throw new OrchestrationError(`Task dependency is not done: ${id}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
assertUnlinked(task) {
|
|
254
|
+
if (task.runtimeRunId !== undefined)
|
|
255
|
+
throw new OrchestrationError(`Task is linked to runtime run: ${task.runtimeRunId}; use execution coordination`);
|
|
256
|
+
}
|
|
161
257
|
async saveTaskGuarded(before, after) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
await this.store.saveTask(after);
|
|
258
|
+
// The store compares the full pre-validation snapshot and writes without an async gap.
|
|
259
|
+
this.assertUnlinked(before);
|
|
260
|
+
await this.store.transitionExecution({ beforeTask: before, task: after });
|
|
166
261
|
}
|
|
167
262
|
async require(id) { const value = await this.store.getTask(id); if (!value)
|
|
168
|
-
throw new OrchestrationError(`Task not found: ${id}`); return value; }
|
|
263
|
+
throw new OrchestrationError(`Task not found: ${id}`); return jsonSnapshot(value); }
|
|
169
264
|
updated(value, changes) { return { ...value, ...changes, updatedAt: new Date().toISOString() }; }
|
|
170
265
|
clean(values) { return [...new Set(values.map((value) => value.trim()).filter(Boolean))]; }
|
|
171
266
|
unique(values) { return [...new Set(values)]; }
|
|
@@ -193,7 +288,18 @@ export class HandoffEngine {
|
|
|
193
288
|
const priorForRun = (await this.store.listHandoffs()).filter((handoff) => handoff.correlationId === fields.correlationId).length;
|
|
194
289
|
if (priorForRun >= this.maxHandoffsPerCorrelation)
|
|
195
290
|
throw new OrchestrationError(`Handoff chain exceeded ${this.maxHandoffsPerCorrelation} handoffs for correlationId ${fields.correlationId} — likely an unbounded loop`);
|
|
196
|
-
|
|
291
|
+
if (input.taskId !== undefined) {
|
|
292
|
+
requireId(input.taskId, 'Handoff taskId');
|
|
293
|
+
const task = await this.store.getTask(input.taskId);
|
|
294
|
+
if (!task)
|
|
295
|
+
throw new OrchestrationError(`Handoff task not found: ${input.taskId}`);
|
|
296
|
+
const sprint = await this.store.getSprint(task.sprintId);
|
|
297
|
+
if (!sprint || sprint.status === 'completed' || sprint.status === 'cancelled')
|
|
298
|
+
throw new OrchestrationError('Handoff task requires an open sprint');
|
|
299
|
+
if (task.runtimeRunId !== undefined)
|
|
300
|
+
throw new OrchestrationError(`Handoff task is already linked to run: ${task.runtimeRunId}`);
|
|
301
|
+
}
|
|
302
|
+
const value = { ...fields, ...(input.taskId === undefined ? {} : { taskId: input.taskId, status: 'pending' }), 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() };
|
|
197
303
|
await this.store.saveHandoff(value);
|
|
198
304
|
if (this.graph)
|
|
199
305
|
await this.graph.record({ kind: 'handoff', id: value.id, relatedIds: value.evidenceIds, evidenceIds: value.evidenceIds });
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import { type EntityId, type ExecutionPlan, type TokenBudget } from '../../contracts/src/index.ts';
|
|
1
|
+
import { type ContextItem, type EntityId, type ExecutionPlan, type TokenBudget } from '../../contracts/src/index.ts';
|
|
2
2
|
export interface PlannerRequest {
|
|
3
|
+
readonly planId?: EntityId;
|
|
4
|
+
readonly contextItems?: readonly ContextItem[];
|
|
5
|
+
readonly pending?: readonly string[];
|
|
6
|
+
readonly constraints?: readonly string[];
|
|
7
|
+
readonly decisions?: readonly string[];
|
|
3
8
|
readonly objective: string;
|
|
4
9
|
readonly acceptanceCriteria: readonly string[];
|
|
5
10
|
readonly allowedFiles: readonly string[];
|
|
@@ -15,6 +20,7 @@ export declare class PlannerError extends Error {
|
|
|
15
20
|
}
|
|
16
21
|
export declare class DeterministicPlanner {
|
|
17
22
|
plan(request: PlannerRequest): ExecutionPlan;
|
|
23
|
+
private contextualSteps;
|
|
18
24
|
private riskFor;
|
|
19
25
|
private allocate;
|
|
20
26
|
private id;
|
|
@@ -12,41 +12,98 @@ export class DeterministicPlanner {
|
|
|
12
12
|
throw new PlannerError('Planner objective is required');
|
|
13
13
|
if (request.acceptanceCriteria.length === 0)
|
|
14
14
|
throw new PlannerError('Planner requires acceptance criteria');
|
|
15
|
-
const
|
|
15
|
+
const contextItems = request.contextItems?.map((item) => ({
|
|
16
|
+
...item,
|
|
17
|
+
evidence: [...item.evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right))),
|
|
18
|
+
})).sort((left, right) => left.source.localeCompare(right.source) || left.locator.localeCompare(right.locator) || left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right)));
|
|
19
|
+
if (contextItems?.some((item) => item.status === 'contradicted' || item.evidence.some((entry) => entry.status === 'contradicted')))
|
|
20
|
+
throw new PlannerError('Planner cannot rely on contradicted context');
|
|
21
|
+
const evidenceIds = [...new Set([...request.evidenceIds, ...(request.contextEvidenceIds ?? []), ...(contextItems ?? []).flatMap((item) => item.evidence.map((entry) => entry.id))])];
|
|
22
|
+
if (contextItems !== undefined)
|
|
23
|
+
evidenceIds.sort();
|
|
16
24
|
if (evidenceIds.length === 0)
|
|
17
25
|
throw new PlannerError('Planner requires evidence references');
|
|
18
26
|
validateTokenBudget(request.budget);
|
|
19
27
|
const risk = this.riskFor(request.objective, request.allowedFiles);
|
|
20
|
-
const now = new Date().toISOString();
|
|
21
28
|
const fields = this.auditFields(request.correlationId ?? `plan:${request.objective}`);
|
|
22
|
-
const stepDefinitions = [
|
|
29
|
+
const stepDefinitions = contextItems === undefined ? [
|
|
23
30
|
{ objective: 'Confirm scope, dependencies and current evidence', criteria: ['Scope and dependencies are recorded'], files: [], dependencies: [] },
|
|
24
31
|
{ objective: request.objective, criteria: request.acceptanceCriteria, files: request.allowedFiles, dependencies: [...(request.dependencyIds ?? []), ...(request.graphDependencyIds ?? [])] },
|
|
25
32
|
{ objective: 'Validate the objective against independent checks', criteria: ['All acceptance criteria have evidence'], files: [], dependencies: [] },
|
|
26
|
-
];
|
|
33
|
+
] : this.contextualSteps(request, contextItems);
|
|
34
|
+
const planId = request.planId ?? (contextItems === undefined
|
|
35
|
+
? this.id(`plan:${request.objective}:${evidenceIds.join(',')}`)
|
|
36
|
+
: this.id(JSON.stringify({ objective: request.objective, stepDefinitions, evidenceIds, constraints: request.constraints, decisions: request.decisions, budget: request.budget })));
|
|
27
37
|
const budgets = this.allocate(request.budget, stepDefinitions.length);
|
|
38
|
+
const stepIds = stepDefinitions.map((_, index) => this.id(`step:${request.planId ?? (contextItems === undefined ? request.objective : planId)}:${index}`));
|
|
28
39
|
const steps = stepDefinitions.map((definition, index) => ({
|
|
29
40
|
...fields,
|
|
30
|
-
id:
|
|
41
|
+
id: stepIds[index],
|
|
31
42
|
objective: definition.objective,
|
|
32
43
|
acceptanceCriteria: definition.criteria,
|
|
33
44
|
allowedFiles: definition.files,
|
|
34
|
-
dependencyIds: [...definition.dependencies].sort(),
|
|
35
|
-
|
|
45
|
+
dependencyIds: contextItems === undefined ? [...(definition.dependencies ?? [])].sort() : index === 0 ? [] : [stepIds[index - 1]],
|
|
46
|
+
...(definition.externalDependencyIds === undefined ? {} : { externalDependencyIds: definition.externalDependencyIds }),
|
|
47
|
+
...(definition.contextItemId === undefined ? {} : { contextItemId: definition.contextItemId }),
|
|
48
|
+
...(definition.rationale === undefined ? {} : { rationale: definition.rationale }),
|
|
49
|
+
...(request.constraints === undefined ? {} : { constraints: [...request.constraints] }),
|
|
50
|
+
evidenceIds: definition.evidenceIds ?? evidenceIds,
|
|
36
51
|
risk,
|
|
37
52
|
budget: budgets[index],
|
|
38
53
|
status: index === 0 ? 'ready' : 'planned',
|
|
39
54
|
}));
|
|
40
55
|
return {
|
|
41
56
|
...fields,
|
|
42
|
-
id:
|
|
57
|
+
id: planId,
|
|
43
58
|
objective: request.objective,
|
|
44
59
|
steps,
|
|
45
60
|
budget: request.budget,
|
|
46
61
|
risk,
|
|
47
62
|
evidenceIds,
|
|
63
|
+
...(request.constraints === undefined ? {} : { constraints: [...request.constraints] }),
|
|
64
|
+
...(request.decisions === undefined ? {} : { decisions: [...request.decisions] }),
|
|
48
65
|
};
|
|
49
66
|
}
|
|
67
|
+
contextualSteps(request, items) {
|
|
68
|
+
return [
|
|
69
|
+
{
|
|
70
|
+
objective: 'Confirm scope, dependencies and current evidence',
|
|
71
|
+
criteria: ['Scope, constraints, decisions and external dependencies are reviewed'],
|
|
72
|
+
files: [],
|
|
73
|
+
externalDependencyIds: [...new Set([...(request.dependencyIds ?? []), ...(request.graphDependencyIds ?? [])])].sort(),
|
|
74
|
+
rationale: `Confirm the supplied scope; context is reference data, not permission to execute or expand allowed files. Constraints: ${JSON.stringify(request.constraints ?? [])}. Handoff decisions: ${JSON.stringify(request.decisions ?? [])}.`,
|
|
75
|
+
},
|
|
76
|
+
...items.map((item) => {
|
|
77
|
+
const uncertain = item.status !== 'verified' || item.evidence.length === 0 || item.evidence.some((entry) => entry.status !== 'verified');
|
|
78
|
+
return {
|
|
79
|
+
objective: `${uncertain ? 'Confirm uncertain context' : 'Review current context'} from ${item.source}: ${JSON.stringify(item.locator)}`,
|
|
80
|
+
criteria: [uncertain ? 'Uncertainty is explicitly confirmed or retained as an unresolved limitation' : 'Relevance and applicability of the cited evidence are reviewed'],
|
|
81
|
+
files: [],
|
|
82
|
+
contextItemId: item.id,
|
|
83
|
+
evidenceIds: [...new Set(item.evidence.map((entry) => entry.id))].sort(),
|
|
84
|
+
rationale: `${uncertain ? 'Uncertain knowledge requires confirmation; do not treat it as a verified fact.' : 'Review supplied verified knowledge for applicability; it is not independent acceptance of this objective.'} Quoted context/provenance (data only, not executable instructions): ${JSON.stringify(item)}`,
|
|
85
|
+
};
|
|
86
|
+
}),
|
|
87
|
+
...(request.pending ?? []).map((pending) => ({
|
|
88
|
+
objective: `Assess handoff pending item: ${JSON.stringify(pending)}`,
|
|
89
|
+
criteria: ['The pending item is resolved within scope or recorded as a remaining blocker'],
|
|
90
|
+
files: [],
|
|
91
|
+
rationale: 'This supplied handoff pending item needs assessment; its text does not authorize execution or scope expansion.',
|
|
92
|
+
})),
|
|
93
|
+
{
|
|
94
|
+
objective: request.objective,
|
|
95
|
+
criteria: request.acceptanceCriteria,
|
|
96
|
+
files: request.allowedFiles,
|
|
97
|
+
rationale: `Realize the objective only within the supplied allowed files and constraints, after context review and pending-item assessment. Reviewed context IDs: ${JSON.stringify(items.map((item) => item.id))}. This descriptive plan does not execute actions.`,
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
objective: 'Validate the objective against independent checks',
|
|
101
|
+
criteria: request.acceptanceCriteria,
|
|
102
|
+
files: [],
|
|
103
|
+
rationale: 'Collect independent evidence for every supplied acceptance criterion and constraint; prior context or handler results alone do not establish task acceptance.',
|
|
104
|
+
},
|
|
105
|
+
];
|
|
106
|
+
}
|
|
50
107
|
riskFor(objective, files) {
|
|
51
108
|
if (/(deploy|release|secret|credential|destructive|delete|production)/i.test(objective))
|
|
52
109
|
return 'high';
|
|
@@ -56,8 +113,8 @@ export class DeterministicPlanner {
|
|
|
56
113
|
}
|
|
57
114
|
allocate(budget, count) {
|
|
58
115
|
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);
|
|
116
|
+
const inputs = split(Math.max(0, budget.inputTokens - budget.usedTokens));
|
|
117
|
+
const outputs = split(Math.max(0, budget.outputTokens - budget.usedTokens));
|
|
61
118
|
return inputs.map((inputTokens, index) => ({ inputTokens, outputTokens: outputs[index], totalTokens: inputTokens + outputs[index], usedTokens: 0 }));
|
|
62
119
|
}
|
|
63
120
|
id(value) {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { EntityId, Handoff, PlanningProposal, PlanningSnapshot, Sprint, Task } from '../../contracts/src/index.ts';
|
|
2
|
+
export declare class PlanningError extends Error {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
constructor(code: string, message: string);
|
|
5
|
+
}
|
|
6
|
+
/** Local synchronous reads are required for the final snapshot check and write. */
|
|
7
|
+
export interface PlanningSnapshotReader {
|
|
8
|
+
getTask(id: EntityId): Task | undefined;
|
|
9
|
+
getSprint(id: EntityId): Sprint | undefined;
|
|
10
|
+
getHandoff(id: EntityId): Handoff | undefined;
|
|
11
|
+
}
|
|
12
|
+
export interface PlanningStore {
|
|
13
|
+
create(proposal: PlanningProposal): void | Promise<void>;
|
|
14
|
+
get(id: EntityId): PlanningProposal | undefined | Promise<PlanningProposal | undefined>;
|
|
15
|
+
review(before: PlanningProposal, after: PlanningProposal, expectedSnapshot?: PlanningSnapshot): void | Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/** Shared JSON semantics for both persistence implementations, including optional undefined fields. */
|
|
18
|
+
export declare function clonePlanningValue<T>(value: T): T;
|
|
19
|
+
export declare function assertPlanningSnapshot(snapshot: PlanningSnapshot, reader: PlanningSnapshotReader): void;
|
|
20
|
+
export declare function assertPlanningCreate(proposal: PlanningProposal, current: PlanningProposal | undefined, reader: PlanningSnapshotReader): void;
|
|
21
|
+
/** Returns false for an already committed equivalent review, preserving its historical timestamps. */
|
|
22
|
+
export declare function assertPlanningReview(before: PlanningProposal, after: PlanningProposal, current: PlanningProposal | undefined, expectedSnapshot: PlanningSnapshot | undefined, reader: PlanningSnapshotReader): boolean;
|
|
23
|
+
export declare class InMemoryPlanningStore implements PlanningStore {
|
|
24
|
+
private readonly proposals;
|
|
25
|
+
private readonly reader;
|
|
26
|
+
constructor(reader: PlanningSnapshotReader);
|
|
27
|
+
create(proposal: PlanningProposal): void;
|
|
28
|
+
get(id: EntityId): PlanningProposal | undefined;
|
|
29
|
+
review(before: PlanningProposal, after: PlanningProposal, expectedSnapshot?: PlanningSnapshot): void;
|
|
30
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
export class PlanningError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
constructor(code, message) { super(message); this.name = 'PlanningError'; this.code = code; }
|
|
4
|
+
}
|
|
5
|
+
/** Shared JSON semantics for both persistence implementations, including optional undefined fields. */
|
|
6
|
+
export function clonePlanningValue(value) {
|
|
7
|
+
return value === undefined ? value : JSON.parse(JSON.stringify(value));
|
|
8
|
+
}
|
|
9
|
+
function canonical(value) {
|
|
10
|
+
const normalized = clonePlanningValue(value);
|
|
11
|
+
function sort(item) {
|
|
12
|
+
if (Array.isArray(item))
|
|
13
|
+
return item.map(sort);
|
|
14
|
+
if (item !== null && typeof item === 'object') {
|
|
15
|
+
return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => [key, sort(child)]));
|
|
16
|
+
}
|
|
17
|
+
return item;
|
|
18
|
+
}
|
|
19
|
+
return JSON.stringify(sort(normalized));
|
|
20
|
+
}
|
|
21
|
+
function equal(left, right) { return canonical(left) === canonical(right); }
|
|
22
|
+
function nonempty(value) { return typeof value === 'string' && value.trim().length > 0; }
|
|
23
|
+
function synchronous(value) {
|
|
24
|
+
if (value !== null && (typeof value === 'object' || typeof value === 'function') && 'then' in value && typeof value.then === 'function') {
|
|
25
|
+
// Surface the contract violation synchronously, while observing an accidental rejection.
|
|
26
|
+
void Promise.resolve(value).catch(() => undefined);
|
|
27
|
+
throw new PlanningError('PLANNING_STALE', 'Planning snapshot readers must be synchronous');
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
export function assertPlanningSnapshot(snapshot, reader) {
|
|
32
|
+
const { task, sprint, dependencies, handoff } = snapshot;
|
|
33
|
+
const ids = new Set(dependencies.map(dependency => dependency.id));
|
|
34
|
+
if (task.sprintId !== sprint.id || ids.size !== dependencies.length || ids.size !== task.dependencyIds.length
|
|
35
|
+
|| task.dependencyIds.some(id => !ids.has(id))
|
|
36
|
+
|| (handoff !== undefined && handoff.taskId !== task.id)
|
|
37
|
+
|| (task.handoffId !== undefined && task.handoffId !== handoff?.id)) {
|
|
38
|
+
throw new PlanningError('PLANNING_STALE', 'Planning snapshot relationships do not match');
|
|
39
|
+
}
|
|
40
|
+
if (!equal(synchronous(reader.getTask(task.id)), task)
|
|
41
|
+
|| !equal(synchronous(reader.getSprint(sprint.id)), sprint)
|
|
42
|
+
|| (handoff !== undefined && !equal(synchronous(reader.getHandoff(handoff.id)), handoff))
|
|
43
|
+
|| dependencies.some(dependency => !equal(synchronous(reader.getTask(dependency.id)), dependency))) {
|
|
44
|
+
throw new PlanningError('PLANNING_STALE', 'Planning snapshot no longer matches current records');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function assertPlanningCreate(proposal, current, reader) {
|
|
48
|
+
if (current !== undefined)
|
|
49
|
+
throw new PlanningError('PLANNING_CONFLICT', 'Planning proposal already exists');
|
|
50
|
+
if (!nonempty(proposal.id) || proposal.version !== 1 || !nonempty(proposal.digest)
|
|
51
|
+
|| (proposal.status !== 'draft' && proposal.status !== 'blocked') || proposal.review !== undefined) {
|
|
52
|
+
throw new PlanningError('PLANNING_INVALID_REVIEW', 'A new planning proposal must be an unreviewed draft or blocked proposal');
|
|
53
|
+
}
|
|
54
|
+
assertPlanningSnapshot(proposal.snapshot, reader);
|
|
55
|
+
}
|
|
56
|
+
function immutableContent(proposal) {
|
|
57
|
+
const { status: _status, review: _review, updatedAt: _updatedAt, ...content } = proposal;
|
|
58
|
+
return content;
|
|
59
|
+
}
|
|
60
|
+
function reviewContent(proposal) {
|
|
61
|
+
if (proposal.review === undefined)
|
|
62
|
+
return undefined;
|
|
63
|
+
const { decidedAt: _decidedAt, sourcesVerifiedAt: _sourcesVerifiedAt, ...content } = proposal.review;
|
|
64
|
+
return content;
|
|
65
|
+
}
|
|
66
|
+
/** Returns false for an already committed equivalent review, preserving its historical timestamps. */
|
|
67
|
+
export function assertPlanningReview(before, after, current, expectedSnapshot, reader) {
|
|
68
|
+
const review = after.review;
|
|
69
|
+
if (!equal(immutableContent(before), immutableContent(after)) || before.digest !== after.digest
|
|
70
|
+
|| before.status !== 'draft' || before.review !== undefined
|
|
71
|
+
|| (after.status !== 'approved' && after.status !== 'rejected')
|
|
72
|
+
|| review === undefined || review.decision !== after.status || review.digest !== after.digest
|
|
73
|
+
|| !nonempty(review.reviewerId) || !nonempty(review.reason) || !nonempty(review.decidedAt)) {
|
|
74
|
+
throw new PlanningError('PLANNING_INVALID_REVIEW', 'Review must preserve proposal content and decide an unreviewed draft');
|
|
75
|
+
}
|
|
76
|
+
if (current === undefined)
|
|
77
|
+
throw new PlanningError('PLANNING_CONFLICT', 'Planning proposal does not exist');
|
|
78
|
+
if (current.status === after.status && equal(immutableContent(current), immutableContent(before))
|
|
79
|
+
&& equal(reviewContent(current), reviewContent(after)))
|
|
80
|
+
return false;
|
|
81
|
+
if (!equal(current, before))
|
|
82
|
+
throw new PlanningError('PLANNING_CONFLICT', 'Planning proposal changed before review');
|
|
83
|
+
if (after.status === 'approved') {
|
|
84
|
+
if (expectedSnapshot === undefined || !equal(expectedSnapshot, before.snapshot)) {
|
|
85
|
+
throw new PlanningError('PLANNING_INVALID_REVIEW', 'Approval requires the proposal snapshot as a precondition');
|
|
86
|
+
}
|
|
87
|
+
assertPlanningSnapshot(expectedSnapshot, reader);
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
export class InMemoryPlanningStore {
|
|
92
|
+
proposals = new Map();
|
|
93
|
+
reader;
|
|
94
|
+
constructor(reader) { this.reader = reader; }
|
|
95
|
+
create(proposal) {
|
|
96
|
+
const next = clonePlanningValue(proposal);
|
|
97
|
+
assertPlanningCreate(next, this.proposals.get(next.id), this.reader);
|
|
98
|
+
this.proposals.set(next.id, next);
|
|
99
|
+
}
|
|
100
|
+
get(id) { return clonePlanningValue(this.proposals.get(id)); }
|
|
101
|
+
review(before, after, expectedSnapshot) {
|
|
102
|
+
const previous = clonePlanningValue(before);
|
|
103
|
+
const next = clonePlanningValue(after);
|
|
104
|
+
const expected = clonePlanningValue(expectedSnapshot);
|
|
105
|
+
if (assertPlanningReview(previous, next, this.proposals.get(previous.id), expected, this.reader)) {
|
|
106
|
+
this.proposals.set(next.id, next);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|