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.
Files changed (119) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +52 -4
  3. package/README.pt-BR.md +54 -4
  4. package/dist/apps/cli/src/index.d.ts +0 -1
  5. package/dist/apps/cli/src/index.js +43 -32
  6. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
  7. package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
  8. package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
  9. package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
  10. package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
  11. package/dist/apps/server/src/forja-nest.module.js +55 -0
  12. package/dist/apps/server/src/main.d.ts +21 -4
  13. package/dist/apps/server/src/main.js +79 -57
  14. package/dist/apps/server/src/task-planning-service.d.ts +29 -0
  15. package/dist/apps/server/src/task-planning-service.js +195 -0
  16. package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
  17. package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
  18. package/dist/bin/forja.js +3 -2
  19. package/dist/lib/agent-evals.d.ts +138 -0
  20. package/dist/lib/agent-evals.js +365 -0
  21. package/dist/lib/cli-output.js +14 -2
  22. package/dist/lib/code-context.d.ts +33 -5
  23. package/dist/lib/code-context.js +70 -5
  24. package/dist/lib/context-builder.d.ts +49 -4
  25. package/dist/lib/context-builder.js +114 -47
  26. package/dist/lib/core/coverage-gate.d.ts +59 -0
  27. package/dist/lib/core/coverage-gate.js +58 -0
  28. package/dist/lib/core/doc-graph.d.ts +38 -0
  29. package/dist/lib/core/doc-graph.js +83 -0
  30. package/dist/lib/core/health.js +286 -5
  31. package/dist/lib/core/journey.js +26 -0
  32. package/dist/lib/core/registry.js +81 -6
  33. package/dist/lib/docs-reference.d.ts +35 -0
  34. package/dist/lib/docs-reference.js +57 -0
  35. package/dist/lib/exec.d.ts +55 -0
  36. package/dist/lib/exec.js +141 -0
  37. package/dist/lib/project-wiring.js +6 -2
  38. package/dist/lib/session-memory.d.ts +38 -0
  39. package/dist/lib/session-memory.js +206 -0
  40. package/dist/lib/spec-trace.d.ts +46 -0
  41. package/dist/lib/spec-trace.js +184 -0
  42. package/dist/packages/adapter-git/src/index.js +13 -4
  43. package/dist/packages/adapter-nest/src/index.d.ts +2 -1
  44. package/dist/packages/adapter-nest/src/index.js +59 -1
  45. package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
  46. package/dist/packages/adapter-sqlite/src/index.js +61 -1
  47. package/dist/packages/context/src/index.d.ts +2 -0
  48. package/dist/packages/context/src/index.js +36 -15
  49. package/dist/packages/contracts/src/index.d.ts +64 -0
  50. package/dist/packages/core/src/index.d.ts +9 -1
  51. package/dist/packages/core/src/index.js +28 -3
  52. package/dist/packages/graph/src/index.js +14 -5
  53. package/dist/packages/llm/src/index.js +7 -24
  54. package/dist/packages/mcp/src/index.d.ts +8 -0
  55. package/dist/packages/mcp/src/index.js +12 -1
  56. package/dist/packages/observability/src/index.d.ts +11 -0
  57. package/dist/packages/observability/src/index.js +3 -0
  58. package/dist/packages/orchestration/src/index.d.ts +15 -1
  59. package/dist/packages/orchestration/src/index.js +127 -21
  60. package/dist/packages/planner/src/index.d.ts +7 -1
  61. package/dist/packages/planner/src/index.js +67 -10
  62. package/dist/packages/planner/src/proposal-store.d.ts +30 -0
  63. package/dist/packages/planner/src/proposal-store.js +109 -0
  64. package/dist/packages/policy/src/index.d.ts +9 -16
  65. package/dist/packages/policy/src/index.js +114 -31
  66. package/dist/packages/runtime/src/index.d.ts +16 -2
  67. package/dist/packages/runtime/src/index.js +176 -61
  68. package/dist/scripts/build-smart-context.d.ts +2 -0
  69. package/dist/scripts/build-smart-context.js +12 -3
  70. package/dist/scripts/code-context.d.ts +3 -1
  71. package/dist/scripts/code-context.js +13 -3
  72. package/dist/scripts/coverage-gate.d.ts +2 -0
  73. package/dist/scripts/coverage-gate.js +101 -0
  74. package/dist/scripts/eval-agents.d.ts +11 -0
  75. package/dist/scripts/eval-agents.js +96 -0
  76. package/dist/scripts/gen-commands-doc.d.ts +2 -0
  77. package/dist/scripts/gen-commands-doc.js +18 -0
  78. package/dist/scripts/hook-session-memory.d.ts +9 -0
  79. package/dist/scripts/hook-session-memory.js +20 -0
  80. package/dist/scripts/hook-session-start.js +34 -0
  81. package/dist/scripts/llm-fit.js +15 -6
  82. package/dist/scripts/simulate.js +16 -4
  83. package/dist/scripts/spec-trace.d.ts +10 -0
  84. package/dist/scripts/spec-trace.js +73 -0
  85. package/dist/scripts/sync-universal-memory.js +69 -4
  86. package/dist/scripts/token-benchmark.d.ts +33 -1
  87. package/dist/scripts/token-benchmark.js +179 -5
  88. package/dist/scripts/token-economy.js +3 -1
  89. package/dist/scripts/tools-doctor.d.ts +16 -1
  90. package/dist/scripts/tools-doctor.js +58 -17
  91. package/docs/commands.md +155 -0
  92. package/docs/fluxo.md +11 -7
  93. package/docs/init-project.md +3 -1
  94. package/docs/llm-fit-loop.md +20 -0
  95. package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
  96. package/docs/produto/factsheet-marketing.md +7 -5
  97. package/docs/produto/roteiro-demo.md +14 -5
  98. package/docs/quick-reference.md +3 -3
  99. package/docs/token-optimization.md +10 -6
  100. package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
  101. package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
  102. package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
  103. package/package.json +4 -2
  104. package/specs/avaliacoes-de-agentes/spec.md +52 -0
  105. package/specs/criterios-ligados-a-testes/spec.md +42 -0
  106. package/specs/memoria-de-sessao/spec.md +48 -0
  107. package/specs/v6-agent-runtime-portable/spec.md +83 -0
  108. package/specs/v6-core-consolidation/spec.md +70 -0
  109. package/specs/v6-docs-drift/spec.md +85 -0
  110. package/specs/v6-quality-gates/spec.md +104 -0
  111. package/specs/v6-token-economy/spec.md +84 -0
  112. package/templates/evals/agents/adr.json +25 -0
  113. package/templates/evals/agents/memoria.json +32 -0
  114. package/templates/evals/agents/proxima-acao.json +29 -0
  115. package/templates/evals/agents/spec-nova.json +26 -0
  116. package/templates/evals/agents/teste-do-criterio.json +29 -0
  117. package/templates/project/AGENTS.md +7 -0
  118. package/templates/project/CLAUDE.md +3 -2
  119. package/templates/project/skills/testing/SKILL.md +1 -1
@@ -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) { return this.tasks.get(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 tasks = await this.store.listTasks(sprintId);
130
- const done = new Set(tasks.filter((task) => task.status === 'done').map((task) => task.id));
131
- return tasks.filter((task) => task.status === 'todo' && task.dependencyIds.every((dependency) => done.has(dependency))).sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
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
- const sprint = await this.store.getSprint(task.sprintId);
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
- /** See SprintEngine.saveSprintGuarded — same lost-update race, same narrowing mitigation. */
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
- const current = await this.store.getTask(before.id);
163
- if (current === undefined || current.updatedAt !== before.updatedAt)
164
- throw new OrchestrationError(`Task was modified concurrently: ${before.id}`);
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
- const value = { ...fields, id: randomUUID(), from: input.from.trim(), to: input.to.trim(), intent: input.intent.trim(), objective: input.objective.trim(), completedWork: this.compact(input.completedWork), decisions: this.compact(input.decisions), constraints: this.compact(input.constraints), pending: this.compact(input.pending), evidenceIds: [...new Set(input.evidenceIds)], acceptance: this.compact(input.acceptance), blockers: this.compact(input.blockers), nextAgent: input.nextAgent.trim() };
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 evidenceIds = [...new Set([...request.evidenceIds, ...(request.contextEvidenceIds ?? [])])];
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: this.id(`step:${request.objective}:${index}`),
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
- evidenceIds,
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: this.id(`plan:${request.objective}:${evidenceIds.join(',')}`),
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
+ }
@@ -1,4 +1,4 @@
1
- import { type AgentIdentity, type ApprovalRequest, type CapabilityDefinition, type EntityId, type ISO8601, type PolicyDecision, type RiskLevel, type TokenBudget } from '../../contracts/src/index.ts';
1
+ import { type AgentIdentity, type ApprovalRequest, type CapabilityDefinition, type CapabilityInput, type EntityId, type ISO8601, type PolicyDecision, type RiskLevel, type TokenBudget } from '../../contracts/src/index.ts';
2
2
  export type PolicyCategory = 'read' | 'write' | 'execution' | 'network' | 'repository' | 'secrets' | 'database' | 'deployment' | 'destructive';
3
3
  export interface PolicyScope {
4
4
  readonly agentIds?: readonly EntityId[];
@@ -54,13 +54,10 @@ export interface ApprovalDetails {
54
54
  export interface PolicyRequest {
55
55
  readonly definition: CapabilityDefinition;
56
56
  readonly agent: AgentIdentity;
57
- /**
58
- * Identifies the run/action this decision belongs to. Required for approvals to actually
59
- * resolve: without a stable key, every retry of the same step looks like a brand-new request
60
- * and `authorize()` can never see that a human already approved it. Callers that omit this
61
- * fall back to `agent.id`, which only works correctly for an agent with a single in-flight
62
- * approval at a time.
63
- */
57
+ /** Validated, canonical input supplied by the capability registry. Only its digest is persisted. */
58
+ readonly input?: CapabilityInput;
59
+ /** Stable action/step identity; falls back to correlationId, never to agent identity. */
60
+ readonly operationId?: string;
64
61
  readonly correlationId?: string;
65
62
  readonly projectId?: string;
66
63
  readonly environment: string;
@@ -81,6 +78,8 @@ export interface ApprovalDecision {
81
78
  }
82
79
  export interface ApprovalInput extends ApprovalDetails {
83
80
  readonly correlationId: string;
81
+ readonly operationId?: string;
82
+ readonly fingerprint?: string;
84
83
  }
85
84
  export interface ApprovalStore {
86
85
  save(request: ApprovalRequest): void;
@@ -98,8 +97,8 @@ export declare class ApprovalLedger {
98
97
  list(): readonly ApprovalRequest[];
99
98
  decide(id: EntityId, decision: ApprovalDecision): ApprovalRequest;
100
99
  expire(now: ISO8601): readonly ApprovalRequest[];
101
- /** Most recent approval request recorded for this correlationId, if any. */
102
- findByCorrelationId(correlationId: string): ApprovalRequest | undefined;
100
+ /** Descriptive/historical records without both binding fields cannot authorize execution. */
101
+ findByOperation(operationId: string, fingerprint: string): ApprovalRequest | undefined;
103
102
  get(id: EntityId): ApprovalRequest;
104
103
  }
105
104
  export declare class PolicyEngine {
@@ -113,12 +112,6 @@ export declare class PolicyEngine {
113
112
  });
114
113
  authorize(request: PolicyRequest): PolicyDecision;
115
114
  get approvals(): ApprovalLedger;
116
- /**
117
- * Resolves approval state for `request` instead of unconditionally demanding a fresh one.
118
- * Keyed by `request.correlationId` (falling back to the agent id) so that resuming/retrying
119
- * the same run recognizes a decision a human already made, rather than re-issuing an
120
- * unresolvable `REQUIRE_APPROVAL` on every attempt — see ADR/finding on approval resume.
121
- */
122
115
  private withApproval;
123
116
  private matches;
124
117
  private validateRules;