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.
Files changed (113) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +37 -4
  3. package/README.pt-BR.md +39 -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 +349 -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/project-wiring.js +6 -2
  36. package/dist/lib/session-memory.d.ts +38 -0
  37. package/dist/lib/session-memory.js +206 -0
  38. package/dist/lib/spec-trace.d.ts +46 -0
  39. package/dist/lib/spec-trace.js +184 -0
  40. package/dist/packages/adapter-nest/src/index.d.ts +2 -1
  41. package/dist/packages/adapter-nest/src/index.js +59 -1
  42. package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
  43. package/dist/packages/adapter-sqlite/src/index.js +61 -1
  44. package/dist/packages/context/src/index.d.ts +2 -0
  45. package/dist/packages/context/src/index.js +36 -15
  46. package/dist/packages/contracts/src/index.d.ts +64 -0
  47. package/dist/packages/core/src/index.d.ts +9 -1
  48. package/dist/packages/core/src/index.js +28 -3
  49. package/dist/packages/graph/src/index.js +14 -5
  50. package/dist/packages/mcp/src/index.d.ts +8 -0
  51. package/dist/packages/mcp/src/index.js +12 -1
  52. package/dist/packages/observability/src/index.d.ts +11 -0
  53. package/dist/packages/observability/src/index.js +3 -0
  54. package/dist/packages/orchestration/src/index.d.ts +15 -1
  55. package/dist/packages/orchestration/src/index.js +127 -21
  56. package/dist/packages/planner/src/index.d.ts +7 -1
  57. package/dist/packages/planner/src/index.js +67 -10
  58. package/dist/packages/planner/src/proposal-store.d.ts +30 -0
  59. package/dist/packages/planner/src/proposal-store.js +109 -0
  60. package/dist/packages/policy/src/index.d.ts +9 -16
  61. package/dist/packages/policy/src/index.js +114 -31
  62. package/dist/packages/runtime/src/index.d.ts +16 -2
  63. package/dist/packages/runtime/src/index.js +176 -61
  64. package/dist/scripts/build-smart-context.d.ts +2 -0
  65. package/dist/scripts/build-smart-context.js +12 -3
  66. package/dist/scripts/code-context.d.ts +3 -1
  67. package/dist/scripts/code-context.js +13 -3
  68. package/dist/scripts/coverage-gate.d.ts +2 -0
  69. package/dist/scripts/coverage-gate.js +101 -0
  70. package/dist/scripts/eval-agents.d.ts +11 -0
  71. package/dist/scripts/eval-agents.js +96 -0
  72. package/dist/scripts/gen-commands-doc.d.ts +2 -0
  73. package/dist/scripts/gen-commands-doc.js +18 -0
  74. package/dist/scripts/hook-session-memory.d.ts +9 -0
  75. package/dist/scripts/hook-session-memory.js +20 -0
  76. package/dist/scripts/hook-session-start.js +34 -0
  77. package/dist/scripts/spec-trace.d.ts +10 -0
  78. package/dist/scripts/spec-trace.js +73 -0
  79. package/dist/scripts/sync-universal-memory.js +69 -4
  80. package/dist/scripts/token-benchmark.d.ts +33 -1
  81. package/dist/scripts/token-benchmark.js +179 -5
  82. package/dist/scripts/token-economy.js +3 -1
  83. package/dist/scripts/tools-doctor.d.ts +16 -1
  84. package/dist/scripts/tools-doctor.js +58 -17
  85. package/docs/commands.md +155 -0
  86. package/docs/fluxo.md +11 -7
  87. package/docs/init-project.md +3 -1
  88. package/docs/llm-fit-loop.md +20 -0
  89. package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
  90. package/docs/produto/factsheet-marketing.md +7 -5
  91. package/docs/produto/roteiro-demo.md +14 -5
  92. package/docs/quick-reference.md +3 -3
  93. package/docs/token-optimization.md +10 -6
  94. package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
  95. package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
  96. package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
  97. package/package.json +4 -2
  98. package/specs/avaliacoes-de-agentes/spec.md +52 -0
  99. package/specs/criterios-ligados-a-testes/spec.md +42 -0
  100. package/specs/memoria-de-sessao/spec.md +48 -0
  101. package/specs/v6-agent-runtime-portable/spec.md +83 -0
  102. package/specs/v6-core-consolidation/spec.md +70 -0
  103. package/specs/v6-docs-drift/spec.md +85 -0
  104. package/specs/v6-quality-gates/spec.md +99 -0
  105. package/specs/v6-token-economy/spec.md +84 -0
  106. package/templates/evals/agents/adr.json +25 -0
  107. package/templates/evals/agents/memoria.json +32 -0
  108. package/templates/evals/agents/proxima-acao.json +29 -0
  109. package/templates/evals/agents/spec-nova.json +26 -0
  110. package/templates/evals/agents/teste-do-criterio.json +29 -0
  111. package/templates/project/AGENTS.md +7 -0
  112. package/templates/project/CLAUDE.md +3 -2
  113. package/templates/project/skills/testing/SKILL.md +1 -1
@@ -1,4 +1,6 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
+ import { PLANNING_PROPOSE_SCHEMA, PLANNING_REVIEW_SCHEMA } from '../../mcp/src/index.js';
3
+ import { PlanningError } from '../../planner/src/proposal-store.js';
2
4
  /**
3
5
  * True for 127.0.0.0/8 and ::1 (with the common ::ffff:-mapped IPv4 form normalized first).
4
6
  * `address === undefined` returns false — "unknown" is not "trusted" — but callers that only have
@@ -26,6 +28,7 @@ export const FORJA_NEST_MODULES = [
26
28
  { name: 'WorkspaceModule', routes: ['/health', '/api/workspace/status'] },
27
29
  { name: 'CapabilityModule', routes: ['/api/capabilities', '/api/capabilities/:id/execute'] },
28
30
  { name: 'RuntimeModule', routes: ['/api/executions/:id'] },
31
+ { name: 'PlanningModule', routes: ['/api/plans', '/api/plans/:id', '/api/plans/:id/review'] },
29
32
  { name: 'GraphModule', routes: ['/api/graph/query', '/api/graph/impact'] },
30
33
  { name: 'ContextModule', routes: ['/api/context/build'] },
31
34
  { name: 'PolicyModule', routes: ['/api/policies'] },
@@ -38,6 +41,44 @@ export const FORJA_NEST_MODULES = [
38
41
  { name: 'ControlPlaneModule', routes: ['/api/control-plane/metrics'] },
39
42
  { name: 'McpModule', routes: ['/mcp/tools', '/mcp/resources'] },
40
43
  ];
44
+ export function planningOpenApiPaths() {
45
+ const string = { type: 'string' };
46
+ const strings = { type: 'array', items: string };
47
+ const timestamp = { type: 'string', format: 'date-time' };
48
+ const tokens = { type: 'integer', minimum: 0 };
49
+ const tokenBudget = PLANNING_PROPOSE_SCHEMA.properties.budget;
50
+ const knowledge = { type: 'string', enum: ['verified', 'inferred', 'hypothesis', 'contradicted', 'unknown'] };
51
+ const evidence = { type: 'object', required: ['id', 'source', 'locator', 'capturedAt', 'status'], properties: { id: string, source: string, locator: string, capturedAt: timestamp, status: knowledge, checksum: string } };
52
+ const evidenceItems = { type: 'array', items: evidence };
53
+ const contextItem = { type: 'object', required: ['id', 'source', 'locator', 'checksum', 'status', 'evidence'], properties: { id: string, source: { enum: ['memory', 'graph'] }, locator: string, content: string, checksum: string, status: knowledge, evidence: evidenceItems } };
54
+ const task = { type: 'object', required: ['id', 'sprintId', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'budget', 'status'], properties: { id: string, sprintId: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, evidenceIds: strings, budget: tokenBudget, status: string } };
55
+ const step = { type: 'object', required: ['id', 'objective', 'acceptanceCriteria', 'allowedFiles', 'dependencyIds', 'evidenceIds', 'budget', 'status'], properties: { id: string, objective: string, acceptanceCriteria: strings, allowedFiles: strings, dependencyIds: strings, externalDependencyIds: strings, contextItemId: string, rationale: string, constraints: strings, evidenceIds: strings, risk: string, budget: tokenBudget, status: string } };
56
+ const proposal = {
57
+ type: 'object', required: ['id', 'version', 'digest', 'status', 'snapshot', 'budget', 'blockers'],
58
+ properties: {
59
+ id: string, version: { const: 1 }, digest: string, status: { type: 'string', enum: ['draft', 'blocked', 'approved', 'rejected'] },
60
+ schemaVersion: string, createdAt: timestamp, updatedAt: timestamp, correlationId: string, declaredEvidenceIds: strings,
61
+ executor: { type: 'object', required: ['id', 'name', 'role', 'autonomy'], properties: { id: string, name: string, role: string, autonomy: string } },
62
+ snapshot: { type: 'object', required: ['task', 'sprint', 'dependencies'], properties: {
63
+ task, dependencies: { type: 'array', items: task },
64
+ sprint: { type: 'object', properties: { id: string, objective: string, status: string, budget: tokenBudget, includedScope: strings, excludedScope: strings, completionCriteria: strings, taskIds: strings } },
65
+ handoff: { type: 'object', properties: { id: string, taskId: string, from: string, to: string, nextAgent: string, intent: string, objective: string, completedWork: strings, decisions: strings, constraints: strings, pending: strings, acceptance: strings, blockers: strings, evidenceIds: strings, status: string } },
66
+ } },
67
+ plan: { type: 'object', properties: { id: string, objective: string, steps: { type: 'array', items: step }, budget: tokenBudget, constraints: strings, decisions: strings, evidenceIds: strings } },
68
+ context: { type: 'object', properties: { id: string, checksum: string, references: evidenceItems, content: strings, items: { type: 'array', items: contextItem }, budget: tokenBudget } },
69
+ budget: { type: 'object', description: 'Conservative token estimates, not billed usage', required: ['limit', 'briefingTokens', 'contextTokens', 'allocation'], properties: { limit: tokenBudget, briefingTokens: tokens, contextTokens: tokens, allocation: tokenBudget } },
70
+ blockers: { type: 'array', items: { type: 'object', required: ['code', 'message'], properties: { code: string, message: string } } },
71
+ review: { type: 'object', required: ['decision', 'reviewerId', 'reason', 'digest', 'decidedAt'], properties: { decision: { enum: ['approved', 'rejected'] }, reviewerId: string, reason: string, digest: string, decidedAt: timestamp, sourcesVerifiedAt: timestamp } },
72
+ },
73
+ };
74
+ const responses = { '200': { description: 'Persisted planning proposal; never an execution', content: { 'application/json': { schema: proposal } } }, ...Object.fromEntries([400, 401, 403, 404, 409, 500, 503].map((status) => [String(status), { description: 'Planning error', content: { 'application/json': { schema: { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string' }, message: { type: 'string' } } } } } } } }])) };
75
+ const parameters = [{ name: 'id', in: 'path', required: true, schema: { type: 'string', minLength: 1 } }];
76
+ return {
77
+ '/api/plans': { post: { operationId: 'planPropose', requestBody: { required: true, content: { 'application/json': { schema: PLANNING_PROPOSE_SCHEMA } } }, responses } },
78
+ '/api/plans/{id}': { get: { operationId: 'planGet', parameters, responses } },
79
+ '/api/plans/{id}/review': { post: { operationId: 'planReview', parameters, requestBody: { required: true, content: { 'application/json': { schema: PLANNING_REVIEW_SCHEMA } } }, responses } },
80
+ };
81
+ }
41
82
  export class NestAdapterError extends Error {
42
83
  constructor(message) { super(message); this.name = 'NestAdapterError'; }
43
84
  }
@@ -56,6 +97,10 @@ export class ForjaNestAdapter {
56
97
  return this.result(correlationId, result);
57
98
  }
58
99
  catch (error) {
100
+ if (request.path === '/api/plans' || request.path.startsWith('/api/plans/')) {
101
+ const status = error instanceof PlanningError ? { PLANNING_INVALID_INPUT: 400, PLANNING_NOT_FOUND: 404, PLANNING_DENIED: 403, PLANNING_CONFLICT: 409, PLANNING_STALE: 409, PLANNING_INVALID_SCOPE: 409, PLANNING_INVALID_REVIEW: 409, PLANNING_REVIEWER_UNAVAILABLE: 503 }[error.code] ?? 500 : 500;
102
+ return { status, headers: { 'content-type': 'application/json; charset=utf-8', 'x-correlation-id': correlationId }, body: { error: { code: status === 500 ? 'PLANNING_UNAVAILABLE' : error.code, message: status === 500 ? 'Planning service unavailable' : error.message } }, correlationId };
103
+ }
59
104
  return this.error(correlationId, error instanceof Error ? error.message : 'Unknown HTTP adapter error');
60
105
  }
61
106
  }
@@ -79,10 +124,23 @@ export class ForjaNestAdapter {
79
124
  }
80
125
  modules() { return FORJA_NEST_MODULES; }
81
126
  openApi() {
82
- const paths = Object.fromEntries(FORJA_NEST_MODULES.flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }])));
127
+ const paths = { ...Object.fromEntries(FORJA_NEST_MODULES.filter((module) => module.name !== 'PlanningModule').flatMap((module) => module.routes.map((route) => [route, { description: `${module.name} route` }]))), ...planningOpenApiPaths() };
83
128
  return { openapi: '3.1.0', info: { title: 'ForjaJS 2.0 API', version: '2.0.0' }, paths };
84
129
  }
85
130
  async dispatch(request) {
131
+ if (request.method === 'POST' && request.path === '/api/plans') {
132
+ if (typeof request.body !== 'object' || request.body === null || Array.isArray(request.body))
133
+ throw new PlanningError('PLANNING_INVALID_INPUT', 'Planning body must be an object');
134
+ const body = request.body;
135
+ return this.requireControlPlane().planPropose?.({ ...body, correlationId: request.correlationId ?? request.headers['x-correlation-id'] ?? body.correlationId }) ?? this.missing('planPropose');
136
+ }
137
+ const planRoute = /^\/api\/plans\/([^/]+)(\/review)?$/.exec(request.path);
138
+ if (planRoute !== null && request.method === 'GET' && planRoute[2] === undefined)
139
+ return this.requireControlPlane().planGet?.(planRoute[1]) ?? this.missing('planGet');
140
+ if (planRoute !== null && request.method === 'POST' && planRoute[2] !== undefined)
141
+ return this.requireControlPlane().planReview?.(planRoute[1], request.body) ?? this.missing('planReview');
142
+ if (request.path === '/api/plans' || request.path.startsWith('/api/plans/'))
143
+ throw new PlanningError('PLANNING_NOT_FOUND', 'Planning route not found');
86
144
  if (request.method === 'GET' && request.path === '/health')
87
145
  return { status: 'ok', service: 'forja-server', offline: true };
88
146
  if (request.method === 'GET' && request.path === '/api/workspace/status')
@@ -4,12 +4,14 @@ import type { ProvenanceRecord } from '../../engineering/provenance/src/index.ts
4
4
  import type { ApprovalStore } from '../../policy/src/index.ts';
5
5
  import type { CheckpointStore, RuntimePersistence, RuntimePlanStep } from '../../runtime/src/index.ts';
6
6
  import type { McpAuditEvent, McpAuditSink } from '../../mcp/src/index.ts';
7
- import type { OrchestrationStore } from '../../orchestration/src/index.ts';
7
+ import { type ExecutionTransition, type OrchestrationStore } from '../../orchestration/src/index.ts';
8
8
  import type { SandboxStore } from '../../sandbox/src/index.ts';
9
9
  import type { ObservationStore } from '../../observability/src/index.ts';
10
10
  import type { GraphStore } from '../../graph/src/index.ts';
11
11
  import type { Evidence, GraphEdge, GraphNode } from '../../contracts/src/index.ts';
12
12
  import type { ContextCache } from '../../context/src/index.ts';
13
+ import type { PlanningProposal, PlanningSnapshot } from '../../contracts/src/index.ts';
14
+ import { type PlanningStore } from '../../planner/src/proposal-store.ts';
13
15
  export interface SqliteStatement {
14
16
  run(...parameters: readonly unknown[]): {
15
17
  readonly changes?: number;
@@ -47,7 +49,9 @@ export declare class SqliteJsonRepository {
47
49
  }
48
50
  export declare class SqliteOrchestrationStore implements OrchestrationStore {
49
51
  private readonly repository;
52
+ private readonly db;
50
53
  constructor(db: SqliteConnection);
54
+ transitionExecution(input: ExecutionTransition): void;
51
55
  saveSprint(value: Sprint): void;
52
56
  getSprint(id: EntityId): Sprint | undefined;
53
57
  listSprints(): readonly Sprint[];
@@ -58,6 +62,16 @@ export declare class SqliteOrchestrationStore implements OrchestrationStore {
58
62
  getHandoff(id: EntityId): Handoff | undefined;
59
63
  listHandoffs(): readonly Handoff[];
60
64
  }
65
+ export declare class SqlitePlanningStore implements PlanningStore {
66
+ private readonly db;
67
+ private readonly repository;
68
+ private readonly reader;
69
+ constructor(db: SqliteConnection);
70
+ create(proposal: PlanningProposal): void;
71
+ get(id: EntityId): PlanningProposal | undefined;
72
+ review(before: PlanningProposal, after: PlanningProposal, expectedSnapshot?: PlanningSnapshot): void;
73
+ private transaction;
74
+ }
61
75
  export declare class SqliteSandboxStore implements SandboxStore {
62
76
  private readonly repository;
63
77
  constructor(db: SqliteConnection);
@@ -1,4 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { assertExecutionTransition } from '../../orchestration/src/index.js';
3
+ import { assertPlanningCreate, assertPlanningReview, clonePlanningValue } from '../../planner/src/proposal-store.js';
2
4
  export const MIGRATIONS = [
3
5
  {
4
6
  version: 1,
@@ -82,7 +84,24 @@ export class SqliteJsonRepository {
82
84
  }
83
85
  export class SqliteOrchestrationStore {
84
86
  repository;
85
- constructor(db) { this.repository = new SqliteJsonRepository(db); }
87
+ db;
88
+ constructor(db) { this.db = db; this.repository = new SqliteJsonRepository(db); }
89
+ transitionExecution(input) {
90
+ // A savepoint also works inside an existing transaction. No handlers or awaits here.
91
+ this.db.exec('SAVEPOINT forja_execution_transition');
92
+ try {
93
+ assertExecutionTransition(input, this.getTask(input.beforeTask.id), input.beforeHandoff === undefined ? undefined : this.getHandoff(input.beforeHandoff.id));
94
+ this.saveTask(input.task);
95
+ if (input.handoff !== undefined)
96
+ this.saveHandoff(input.handoff);
97
+ this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
98
+ }
99
+ catch (error) {
100
+ this.db.exec('ROLLBACK TO SAVEPOINT forja_execution_transition');
101
+ this.db.exec('RELEASE SAVEPOINT forja_execution_transition');
102
+ throw error;
103
+ }
104
+ }
86
105
  saveSprint(value) { this.repository.put('sprint', value.id, value, value.updatedAt); }
87
106
  getSprint(id) { return this.repository.get('sprint', id); }
88
107
  listSprints() { return this.repository.list('sprint'); }
@@ -93,6 +112,47 @@ export class SqliteOrchestrationStore {
93
112
  getHandoff(id) { return this.repository.get('handoff', id); }
94
113
  listHandoffs() { return this.repository.list('handoff'); }
95
114
  }
115
+ export class SqlitePlanningStore {
116
+ db;
117
+ repository;
118
+ reader;
119
+ constructor(db) {
120
+ this.db = db;
121
+ this.repository = new SqliteJsonRepository(db);
122
+ this.reader = new SqliteOrchestrationStore(db);
123
+ }
124
+ create(proposal) {
125
+ const next = clonePlanningValue(proposal);
126
+ this.transaction(() => {
127
+ assertPlanningCreate(next, this.get(next.id), this.reader);
128
+ this.repository.put('planning_proposal', next.id, next, next.updatedAt);
129
+ });
130
+ }
131
+ get(id) { return this.repository.get('planning_proposal', id); }
132
+ review(before, after, expectedSnapshot) {
133
+ const previous = clonePlanningValue(before);
134
+ const next = clonePlanningValue(after);
135
+ const expected = clonePlanningValue(expectedSnapshot);
136
+ this.transaction(() => {
137
+ if (assertPlanningReview(previous, next, this.get(previous.id), expected, this.reader)) {
138
+ this.repository.put('planning_proposal', next.id, next, next.updatedAt);
139
+ }
140
+ });
141
+ }
142
+ transaction(write) {
143
+ // Snapshot reads, CAS and proposal write share the same short, synchronous transaction.
144
+ this.db.exec('SAVEPOINT forja_planning_proposal');
145
+ try {
146
+ write();
147
+ this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
148
+ }
149
+ catch (error) {
150
+ this.db.exec('ROLLBACK TO SAVEPOINT forja_planning_proposal');
151
+ this.db.exec('RELEASE SAVEPOINT forja_planning_proposal');
152
+ throw error;
153
+ }
154
+ }
155
+ }
96
156
  export class SqliteSandboxStore {
97
157
  repository;
98
158
  constructor(db) { this.repository = new SqliteJsonRepository(db); }
@@ -21,6 +21,7 @@ export interface ContextBuildRequest {
21
21
  readonly objective: string;
22
22
  readonly budget: TokenBudget;
23
23
  readonly includeContent?: boolean;
24
+ readonly includeProvenanceInBudget?: boolean;
24
25
  readonly maxItems?: number;
25
26
  readonly requireEvidence?: boolean;
26
27
  readonly correlationId?: string;
@@ -53,6 +54,7 @@ export declare class ContextEngine {
53
54
  build(request: ContextBuildRequest): Promise<ContextPackage>;
54
55
  expand(checksum: string): string;
55
56
  private isUsable;
57
+ private contextItem;
56
58
  private estimateTokens;
57
59
  private checksum;
58
60
  private uniqueEvidence;
@@ -42,30 +42,38 @@ export class ContextEngine {
42
42
  if (candidates.length === 0 && (request.requireEvidence ?? true))
43
43
  throw new ContextEngineError('INSUFFICIENT_EVIDENCE', 'No current evidence matches the context objective');
44
44
  const ranked = candidates
45
- .map((candidate) => ({ candidate, checksum: candidate.checksum ?? this.checksum(candidate.content) }))
46
- .sort((left, right) => right.candidate.relevance - left.candidate.relevance || left.candidate.locator.localeCompare(right.candidate.locator) || left.checksum.localeCompare(right.checksum));
45
+ .map((candidate) => ({ candidate, item: this.contextItem(candidate, request.includeContent !== false) }))
46
+ .sort((left, right) => right.candidate.relevance - left.candidate.relevance
47
+ || left.item.locator.localeCompare(right.item.locator)
48
+ || left.item.checksum.localeCompare(right.item.checksum)
49
+ || JSON.stringify(left.item).localeCompare(JSON.stringify(right.item)));
47
50
  const unique = new Map();
48
- for (const item of ranked)
49
- if (!unique.has(item.checksum))
50
- unique.set(item.checksum, item);
51
+ for (const entry of ranked)
52
+ if (!unique.has(entry.item.checksum))
53
+ unique.set(entry.item.checksum, entry);
51
54
  const availableTokens = request.budget.totalTokens - request.budget.usedTokens;
52
55
  let usedTokens = 0;
53
56
  let cacheHits = 0;
54
57
  const selected = [];
55
- for (const item of [...unique.values()].slice(0, maxItems)) {
56
- const tokens = this.estimateTokens(item.candidate.content);
58
+ for (const entry of [...unique.values()].slice(0, maxItems)) {
59
+ const { candidate, item } = entry;
60
+ const tokens = this.estimateTokens(request.includeProvenanceInBudget ? JSON.stringify(item) : candidate.content);
57
61
  if (usedTokens + tokens > availableTokens)
58
62
  continue;
59
- if (this.dependencies.cache?.get(item.checksum) !== undefined)
63
+ // Supplied keys remain valid for expand(), but never establish content freshness.
64
+ const cacheKey = candidate.checksum ?? item.checksum;
65
+ if (this.dependencies.cache?.get(cacheKey) === candidate.content)
60
66
  cacheHits += 1;
61
- else
62
- this.dependencies.cache?.set(item.checksum, item.candidate.content);
63
- selected.push({ ...item, tokens });
67
+ this.dependencies.cache?.set(cacheKey, candidate.content);
68
+ if (cacheKey !== item.checksum)
69
+ this.dependencies.cache?.set(item.checksum, candidate.content);
70
+ selected.push(entry);
64
71
  usedTokens += tokens;
65
72
  }
66
73
  if (selected.length === 0 && (request.requireEvidence ?? true))
67
74
  throw new ContextEngineError('CONTEXT_BUDGET_EXCEEDED', 'Context budget cannot fit any evidence');
68
- const references = this.uniqueEvidence(selected.flatMap((item) => item.candidate.evidence));
75
+ const items = selected.map((entry) => entry.item);
76
+ const references = this.uniqueEvidence(items.flatMap((item) => item.evidence));
69
77
  const content = request.includeContent === false ? [] : selected.map((item) => item.candidate.content);
70
78
  const metrics = {
71
79
  candidateCount: candidates.length,
@@ -81,8 +89,9 @@ export class ContextEngine {
81
89
  id: randomUUID(),
82
90
  references,
83
91
  content,
92
+ items,
84
93
  budget: { ...request.budget, usedTokens: request.budget.usedTokens + usedTokens },
85
- checksum: this.checksum(JSON.stringify({ objective: request.objective, refs: selected.map((item) => item.checksum), includeContent: request.includeContent !== false })),
94
+ checksum: this.checksum(JSON.stringify({ objective: request.objective, items, includeContent: request.includeContent !== false })),
86
95
  metrics,
87
96
  };
88
97
  }
@@ -93,7 +102,18 @@ export class ContextEngine {
93
102
  return content;
94
103
  }
95
104
  isUsable(candidate) {
96
- return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0;
105
+ return !candidate.obsolete && candidate.status !== 'contradicted' && candidate.content.trim().length > 0 && Number.isFinite(candidate.relevance) && candidate.evidence.length > 0 && candidate.evidence.every((item) => item.status !== 'contradicted');
106
+ }
107
+ contextItem(candidate, includeContent) {
108
+ return {
109
+ id: candidate.id,
110
+ source: candidate.source,
111
+ locator: candidate.locator,
112
+ ...(includeContent ? { content: candidate.content } : {}),
113
+ checksum: this.checksum(candidate.content),
114
+ status: candidate.status,
115
+ evidence: [...candidate.evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right))),
116
+ };
97
117
  }
98
118
  estimateTokens(content) {
99
119
  return Math.max(1, Math.ceil(Buffer.byteLength(content, 'utf8') / 4));
@@ -103,7 +123,8 @@ export class ContextEngine {
103
123
  }
104
124
  uniqueEvidence(evidence) {
105
125
  const unique = new Map();
106
- for (const item of evidence)
126
+ const sorted = [...evidence].sort((left, right) => left.id.localeCompare(right.id) || JSON.stringify(left).localeCompare(JSON.stringify(right)));
127
+ for (const item of sorted)
107
128
  if (!unique.has(item.id))
108
129
  unique.set(item.id, item);
109
130
  return [...unique.values()];
@@ -72,6 +72,7 @@ export interface ExecutionError {
72
72
  readonly details?: Readonly<Record<string, string>>;
73
73
  }
74
74
  export interface ExecutionResult extends AuditFields {
75
+ readonly operationId?: string;
75
76
  readonly runId: RunId;
76
77
  readonly status: 'succeeded' | 'failed' | 'blocked' | 'cancelled';
77
78
  readonly output?: CapabilityOutput;
@@ -118,6 +119,8 @@ export interface PolicyDecision {
118
119
  readonly approvalRequestId?: EntityId;
119
120
  }
120
121
  export interface ApprovalRequest extends AuditFields {
122
+ readonly operationId?: string;
123
+ readonly fingerprint?: string;
121
124
  readonly id: EntityId;
122
125
  readonly action: string;
123
126
  readonly justification: string;
@@ -147,6 +150,10 @@ export interface Sprint extends AuditFields {
147
150
  }
148
151
  export interface Task extends AuditFields {
149
152
  readonly id: EntityId;
153
+ readonly runtimeRunId?: RunId;
154
+ readonly handoffId?: EntityId;
155
+ readonly executionScopeHash?: string;
156
+ readonly executionError?: ExecutionError;
150
157
  readonly sprintId: EntityId;
151
158
  readonly objective: string;
152
159
  readonly acceptanceCriteria: readonly string[];
@@ -158,6 +165,9 @@ export interface Task extends AuditFields {
158
165
  }
159
166
  export interface Handoff extends AuditFields {
160
167
  readonly id: EntityId;
168
+ readonly taskId?: EntityId;
169
+ readonly runId?: RunId;
170
+ readonly status?: 'pending' | 'in_progress' | 'blocked' | 'completed' | 'cancelled';
161
171
  readonly from: string;
162
172
  readonly to: string;
163
173
  readonly intent: string;
@@ -192,6 +202,7 @@ export interface RuntimeRun extends AuditFields {
192
202
  readonly agent: AgentIdentity;
193
203
  readonly sprintId?: EntityId;
194
204
  readonly taskId?: EntityId;
205
+ readonly handoffId?: EntityId;
195
206
  readonly policy: PolicyDecision;
196
207
  readonly budget: TokenBudget;
197
208
  readonly state: ExecutionState;
@@ -251,10 +262,20 @@ export interface ContextMetrics {
251
262
  readonly selectedTokens: number;
252
263
  readonly unusedTokens: number;
253
264
  }
265
+ export interface ContextItem {
266
+ readonly id: EntityId;
267
+ readonly source: 'memory' | 'graph';
268
+ readonly locator: string;
269
+ readonly content?: string;
270
+ readonly checksum: string;
271
+ readonly status: KnowledgeStatus;
272
+ readonly evidence: readonly Evidence[];
273
+ }
254
274
  export interface ContextPackage extends AuditFields {
255
275
  readonly id: EntityId;
256
276
  readonly references: readonly Evidence[];
257
277
  readonly content: readonly string[];
278
+ readonly items?: readonly ContextItem[];
258
279
  readonly budget: TokenBudget;
259
280
  readonly checksum: string;
260
281
  readonly metrics: ContextMetrics;
@@ -275,6 +296,10 @@ export interface PlanStep extends AuditFields {
275
296
  readonly acceptanceCriteria: readonly string[];
276
297
  readonly allowedFiles: readonly string[];
277
298
  readonly dependencyIds: readonly EntityId[];
299
+ readonly externalDependencyIds?: readonly EntityId[];
300
+ readonly contextItemId?: EntityId;
301
+ readonly rationale?: string;
302
+ readonly constraints?: readonly string[];
278
303
  readonly evidenceIds: readonly EntityId[];
279
304
  readonly risk: RiskLevel;
280
305
  readonly budget: TokenBudget;
@@ -286,8 +311,47 @@ export interface ExecutionPlan extends AuditFields {
286
311
  readonly steps: readonly PlanStep[];
287
312
  readonly budget: TokenBudget;
288
313
  readonly risk: RiskLevel;
314
+ readonly constraints?: readonly string[];
315
+ readonly decisions?: readonly string[];
289
316
  readonly evidenceIds: readonly EntityId[];
290
317
  }
318
+ export interface PlanningSnapshot {
319
+ readonly task: Task;
320
+ readonly sprint: Sprint;
321
+ readonly dependencies: readonly Task[];
322
+ readonly handoff?: Handoff;
323
+ }
324
+ export interface PlanningBudget {
325
+ readonly limit: TokenBudget;
326
+ readonly briefingTokens: number;
327
+ readonly contextTokens: number;
328
+ readonly allocation: TokenBudget;
329
+ }
330
+ export interface PlanningReview {
331
+ readonly decision: 'approved' | 'rejected';
332
+ readonly reviewerId: EntityId;
333
+ readonly reason: string;
334
+ readonly digest: string;
335
+ readonly decidedAt: ISO8601;
336
+ readonly sourcesVerifiedAt?: ISO8601;
337
+ }
338
+ export interface PlanningProposal extends AuditFields {
339
+ readonly id: EntityId;
340
+ readonly version: 1;
341
+ readonly digest: string;
342
+ readonly executor: AgentIdentity;
343
+ readonly snapshot: PlanningSnapshot;
344
+ readonly plan?: ExecutionPlan;
345
+ readonly context?: ContextPackage;
346
+ readonly status: 'draft' | 'approved' | 'rejected' | 'blocked';
347
+ readonly blockers: readonly {
348
+ readonly code: string;
349
+ readonly message: string;
350
+ }[];
351
+ readonly budget: PlanningBudget;
352
+ readonly declaredEvidenceIds: readonly EntityId[];
353
+ readonly review?: PlanningReview;
354
+ }
291
355
  export interface EvaluationResult extends AuditFields {
292
356
  readonly status: 'accepted' | 'rejected' | 'inconclusive' | 'blocked';
293
357
  readonly checks: readonly {
@@ -1,4 +1,4 @@
1
- import { type AgentIdentity, type AgentProfile, type CapabilityDefinition, type CapabilityInput, type CapabilityOutput, type ExecutionResult, type PolicyDecision, type RunId, type ISO8601, type TokenBudget } from '../../contracts/src/index.ts';
1
+ import { type AgentIdentity, type AgentProfile, type CapabilityDefinition, type CapabilityInput, type CapabilityOutput, type ExecutionError, type ExecutionResult, type PolicyDecision, type RunId, type ISO8601, type TokenBudget } from '../../contracts/src/index.ts';
2
2
  export interface CapabilityExecutionContext {
3
3
  readonly runId: RunId;
4
4
  readonly agent: AgentIdentity;
@@ -6,6 +6,7 @@ export interface CapabilityExecutionContext {
6
6
  }
7
7
  export interface CapabilityRegistration<Input, Output> {
8
8
  readonly definition: CapabilityDefinition;
9
+ readonly categories?: readonly string[];
9
10
  readonly validateInput: (value: unknown) => Input;
10
11
  readonly validateOutput: (value: unknown) => Output;
11
12
  readonly handler: (input: Input, context: CapabilityExecutionContext) => CapabilityOutput | Promise<CapabilityOutput>;
@@ -15,6 +16,7 @@ export interface CapabilityAuthorizationRequest {
15
16
  readonly input: CapabilityInput;
16
17
  readonly agent: AgentIdentity;
17
18
  readonly correlationId?: string;
19
+ readonly operationId?: string;
18
20
  readonly projectId?: string;
19
21
  readonly environment: string;
20
22
  readonly categories: readonly string[];
@@ -42,6 +44,7 @@ export interface CapabilityExecutionRequest {
42
44
  readonly agent: AgentIdentity;
43
45
  readonly policy: CapabilityPolicy;
44
46
  readonly correlationId?: string;
47
+ readonly operationId?: string;
45
48
  readonly projectId?: string;
46
49
  readonly environment?: string;
47
50
  readonly categories?: readonly string[];
@@ -62,6 +65,11 @@ export interface CapabilityExecutionRequest {
62
65
  export declare class CapabilityRegistryError extends Error {
63
66
  constructor(message: string);
64
67
  }
68
+ export declare class CapabilityExecutionFailure extends Error {
69
+ readonly executionError: ExecutionError;
70
+ readonly output?: CapabilityOutput;
71
+ constructor(error: ExecutionError, output?: CapabilityOutput);
72
+ }
65
73
  export declare class CapabilityRegistry {
66
74
  private readonly registrations;
67
75
  private readonly aliases;
@@ -6,6 +6,16 @@ export class CapabilityRegistryError extends Error {
6
6
  this.name = 'CapabilityRegistryError';
7
7
  }
8
8
  }
9
+ export class CapabilityExecutionFailure extends Error {
10
+ executionError;
11
+ output;
12
+ constructor(error, output) {
13
+ super(error.message);
14
+ this.name = 'CapabilityExecutionFailure';
15
+ this.executionError = error;
16
+ this.output = output;
17
+ }
18
+ }
9
19
  export class CapabilityRegistry {
10
20
  registrations = new Map();
11
21
  aliases = new Map();
@@ -24,6 +34,7 @@ export class CapabilityRegistry {
24
34
  }
25
35
  const stored = {
26
36
  definition,
37
+ categories: [...(registration.categories ?? definition.permissions)],
27
38
  validateInput: registration.validateInput,
28
39
  validateOutput: registration.validateOutput,
29
40
  handler: registration.handler,
@@ -47,7 +58,7 @@ export class CapabilityRegistry {
47
58
  }
48
59
  async execute(request) {
49
60
  const runId = this.createRunId();
50
- const timestamps = this.auditFields(request.correlationId ?? runId);
61
+ const timestamps = { ...this.auditFields(request.correlationId ?? runId), operationId: request.operationId ?? request.correlationId ?? runId };
51
62
  const resolved = this.tryResolve(request.input.capabilityId);
52
63
  if (resolved.error !== undefined) {
53
64
  return this.failure(runId, timestamps, resolved.error);
@@ -64,12 +75,13 @@ export class CapabilityRegistry {
64
75
  try {
65
76
  decision = request.policy.authorize({
66
77
  definition: registration.definition,
67
- input: request.input,
78
+ input: { capabilityId: registration.definition.id, payload: input },
68
79
  agent: request.agent,
69
80
  correlationId: request.correlationId ?? runId,
81
+ operationId: timestamps.operationId,
70
82
  projectId: request.projectId,
71
83
  environment: request.environment ?? 'local',
72
- categories: request.categories ?? [],
84
+ categories: registration.categories ?? registration.definition.permissions,
73
85
  files: request.files ?? [],
74
86
  budget: request.budget,
75
87
  now: timestamps.createdAt,
@@ -108,6 +120,19 @@ export class CapabilityRegistry {
108
120
  return { ...timestamps, runId, status: 'succeeded', output, evidence: output.evidence };
109
121
  }
110
122
  catch (error) {
123
+ if (error instanceof CapabilityExecutionFailure) {
124
+ if (error.output !== undefined) {
125
+ try {
126
+ registration.validateOutput(error.output.payload);
127
+ if (error.output.capabilityId !== registration.definition.id)
128
+ throw new Error('Handler output capabilityId does not match definition');
129
+ }
130
+ catch (invalidOutput) {
131
+ return this.failure(runId, timestamps, this.toExecutionError('HANDLER_FAILED', invalidOutput, false));
132
+ }
133
+ }
134
+ return { ...timestamps, runId, status: 'failed', error: error.executionError, output: error.output, evidence: error.output?.evidence ?? [] };
135
+ }
111
136
  return this.failure(runId, timestamps, this.toExecutionError('HANDLER_FAILED', error, true));
112
137
  }
113
138
  }
@@ -169,21 +169,30 @@ export class GraphLoop {
169
169
  }
170
170
  contextRecords(objective) {
171
171
  const terms = objective.toLowerCase().split(/[^a-z0-9_./-]+/).filter((term) => term.length > 1);
172
- const records = this.activeEdges()
172
+ const at = new Date().toISOString();
173
+ const records = this.activeEdges(at)
173
174
  .map((edge) => {
174
175
  const from = this.store.getNode(edge.from);
175
176
  const to = this.store.getNode(edge.to);
176
177
  if (from === undefined || to === undefined)
177
178
  return undefined;
178
- const content = `${from.label} ${edge.type} ${to.label}`;
179
- const haystack = content.toLowerCase();
179
+ if ([from, to].some((node) => node.status === 'contradicted' || !this.active(node.validFrom, node.validTo, at)))
180
+ return undefined;
181
+ const relation = `${from.label} ${edge.type} ${to.label}`;
182
+ const haystack = relation.toLowerCase();
180
183
  const matches = terms.filter((term) => haystack.includes(term)).length;
181
184
  if (matches === 0)
182
185
  return undefined;
183
186
  const evidence = edge.evidenceIds.map((id) => this.store.getEvidence(id)).filter((item) => item !== undefined);
184
- if (evidence.length === 0)
187
+ if (evidence.length !== edge.evidenceIds.length || evidence.length === 0 || evidence.some((item) => item.status === 'contradicted'))
185
188
  return undefined;
186
- return { id: edge.id, locator: `graph:${edge.id}`, content, relevance: matches / Math.max(1, terms.length), status: edge.status, evidence: evidence, checksum: createHash('sha256').update(`${edge.id}:${edge.updatedAt}:${content}`).digest('hex') };
189
+ evidence.sort((left, right) => left.id.localeCompare(right.id));
190
+ const content = from.type === 'Execution' || to.type === 'Execution'
191
+ ? `${relation} [Execution memory: handler attempt/result, not independent acceptance of the task.]`
192
+ : relation;
193
+ const statuses = [edge.status, from.status, to.status, ...evidence.map((item) => item.status)];
194
+ const status = ['unknown', 'hypothesis', 'inferred'].find((value) => statuses.includes(value)) ?? 'verified';
195
+ return { id: edge.id, locator: `graph:${edge.id}`, content, relevance: matches / Math.max(1, terms.length), status, evidence, checksum: createHash('sha256').update(`${edge.id}:${edge.updatedAt}:${content}`).digest('hex') };
187
196
  });
188
197
  return records
189
198
  .filter((record) => record !== undefined)
@@ -39,6 +39,10 @@ export interface McpAgentContext {
39
39
  readonly permissions: readonly string[];
40
40
  readonly capabilities: readonly CapabilityId[];
41
41
  }
42
+ export interface McpPlanning {
43
+ propose(input: unknown): unknown | Promise<unknown>;
44
+ get(id: string): unknown | Promise<unknown>;
45
+ }
42
46
  export interface McpMemoryQuery {
43
47
  query(objective: string): unknown | Promise<unknown>;
44
48
  }
@@ -76,6 +80,7 @@ export interface McpServerDependencies {
76
80
  readonly policy: CapabilityPolicy;
77
81
  readonly agent: McpAgentContext;
78
82
  readonly context?: ContextEngine;
83
+ readonly planning?: McpPlanning;
79
84
  readonly graph?: GraphLoop;
80
85
  readonly memory?: McpMemoryQuery;
81
86
  readonly taskEngine?: TaskEngine;
@@ -91,6 +96,8 @@ export interface McpServerDependencies {
91
96
  export declare class McpAdapterError extends Error {
92
97
  constructor(message: string);
93
98
  }
99
+ export declare const PLANNING_PROPOSE_SCHEMA: McpInputSchema;
100
+ export declare const PLANNING_REVIEW_SCHEMA: McpInputSchema;
94
101
  export declare const MCP_TOOLS: readonly McpToolDefinition[];
95
102
  export declare class McpServer {
96
103
  private readonly dependencies;
@@ -119,6 +126,7 @@ export declare class McpServer {
119
126
  private entities;
120
127
  private number;
121
128
  private optionalStatus;
129
+ private requirePlanning;
122
130
  private requireContext;
123
131
  private requireGraph;
124
132
  private requireMemory;