@agentic-sdlc-kit/cli 0.0.0-stage → 0.8.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 (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/dist/application/agent/execution-store.d.ts +55 -0
  4. package/dist/application/agent/execution-store.d.ts.map +1 -0
  5. package/dist/application/agent/execution-store.js +90 -0
  6. package/dist/application/agent/execution-store.js.map +1 -0
  7. package/dist/application/agent/gateway.d.ts +74 -0
  8. package/dist/application/agent/gateway.d.ts.map +1 -0
  9. package/dist/application/agent/gateway.js +580 -0
  10. package/dist/application/agent/gateway.js.map +1 -0
  11. package/dist/application/agent/index.d.ts +6 -0
  12. package/dist/application/agent/index.d.ts.map +1 -0
  13. package/dist/application/agent/index.js +18 -0
  14. package/dist/application/agent/index.js.map +1 -0
  15. package/dist/application/agent/orchestrator.d.ts +76 -0
  16. package/dist/application/agent/orchestrator.d.ts.map +1 -0
  17. package/dist/application/agent/orchestrator.js +422 -0
  18. package/dist/application/agent/orchestrator.js.map +1 -0
  19. package/dist/application/agent/providers/claude-code/claude-argv.d.ts +15 -0
  20. package/dist/application/agent/providers/claude-code/claude-argv.d.ts.map +1 -0
  21. package/dist/application/agent/providers/claude-code/claude-argv.js +98 -0
  22. package/dist/application/agent/providers/claude-code/claude-argv.js.map +1 -0
  23. package/dist/application/agent/providers/claude-code/index.d.ts +7 -0
  24. package/dist/application/agent/providers/claude-code/index.d.ts.map +1 -0
  25. package/dist/application/agent/providers/claude-code/index.js +13 -0
  26. package/dist/application/agent/providers/claude-code/index.js.map +1 -0
  27. package/dist/application/agent/providers/claude-code/mod-parity.d.ts +15 -0
  28. package/dist/application/agent/providers/claude-code/mod-parity.d.ts.map +1 -0
  29. package/dist/application/agent/providers/claude-code/mod-parity.js +41 -0
  30. package/dist/application/agent/providers/claude-code/mod-parity.js.map +1 -0
  31. package/dist/application/agent/providers/claude-code/permission-config.d.ts +59 -0
  32. package/dist/application/agent/providers/claude-code/permission-config.d.ts.map +1 -0
  33. package/dist/application/agent/providers/claude-code/permission-config.js +189 -0
  34. package/dist/application/agent/providers/claude-code/permission-config.js.map +1 -0
  35. package/dist/application/agent/providers/claude-code/provider.d.ts +38 -0
  36. package/dist/application/agent/providers/claude-code/provider.d.ts.map +1 -0
  37. package/dist/application/agent/providers/claude-code/provider.js +577 -0
  38. package/dist/application/agent/providers/claude-code/provider.js.map +1 -0
  39. package/dist/application/agent/providers/claude-code/resume-store.d.ts +25 -0
  40. package/dist/application/agent/providers/claude-code/resume-store.d.ts.map +1 -0
  41. package/dist/application/agent/providers/claude-code/resume-store.js +120 -0
  42. package/dist/application/agent/providers/claude-code/resume-store.js.map +1 -0
  43. package/dist/application/agent/providers/claude-code/stream-parser.d.ts +50 -0
  44. package/dist/application/agent/providers/claude-code/stream-parser.d.ts.map +1 -0
  45. package/dist/application/agent/providers/claude-code/stream-parser.js +129 -0
  46. package/dist/application/agent/providers/claude-code/stream-parser.js.map +1 -0
  47. package/dist/application/agent/test-fixture.d.ts +15 -0
  48. package/dist/application/agent/test-fixture.d.ts.map +1 -0
  49. package/dist/application/agent/test-fixture.js +93 -0
  50. package/dist/application/agent/test-fixture.js.map +1 -0
  51. package/dist/application/agent/workspace.d.ts +24 -0
  52. package/dist/application/agent/workspace.d.ts.map +1 -0
  53. package/dist/application/agent/workspace.js +139 -0
  54. package/dist/application/agent/workspace.js.map +1 -0
  55. package/dist/application/dispatcher.d.ts +13 -0
  56. package/dist/application/dispatcher.d.ts.map +1 -0
  57. package/dist/application/dispatcher.js +104 -0
  58. package/dist/application/dispatcher.js.map +1 -0
  59. package/dist/application/index.d.ts +5 -0
  60. package/dist/application/index.d.ts.map +1 -0
  61. package/dist/application/index.js +6 -0
  62. package/dist/application/index.js.map +1 -0
  63. package/dist/application/registry.d.ts +8 -0
  64. package/dist/application/registry.d.ts.map +1 -0
  65. package/dist/application/registry.js +17 -0
  66. package/dist/application/registry.js.map +1 -0
  67. package/dist/application/version.d.ts +2 -0
  68. package/dist/application/version.d.ts.map +1 -0
  69. package/dist/application/version.js +7 -0
  70. package/dist/application/version.js.map +1 -0
  71. package/dist/commands/doctor.d.ts +3 -0
  72. package/dist/commands/doctor.d.ts.map +1 -0
  73. package/dist/commands/doctor.js +68 -0
  74. package/dist/commands/doctor.js.map +1 -0
  75. package/dist/commands/elicit.d.ts +3 -0
  76. package/dist/commands/elicit.d.ts.map +1 -0
  77. package/dist/commands/elicit.js +163 -0
  78. package/dist/commands/elicit.js.map +1 -0
  79. package/dist/commands/evolve.d.ts +3 -0
  80. package/dist/commands/evolve.d.ts.map +1 -0
  81. package/dist/commands/evolve.js +165 -0
  82. package/dist/commands/evolve.js.map +1 -0
  83. package/dist/commands/feature.d.ts +13 -0
  84. package/dist/commands/feature.d.ts.map +1 -0
  85. package/dist/commands/feature.js +326 -0
  86. package/dist/commands/feature.js.map +1 -0
  87. package/dist/commands/fix.d.ts +3 -0
  88. package/dist/commands/fix.d.ts.map +1 -0
  89. package/dist/commands/fix.js +61 -0
  90. package/dist/commands/fix.js.map +1 -0
  91. package/dist/commands/help.d.ts +4 -0
  92. package/dist/commands/help.d.ts.map +1 -0
  93. package/dist/commands/help.js +32 -0
  94. package/dist/commands/help.js.map +1 -0
  95. package/dist/commands/index.d.ts +21 -0
  96. package/dist/commands/index.d.ts.map +1 -0
  97. package/dist/commands/index.js +22 -0
  98. package/dist/commands/index.js.map +1 -0
  99. package/dist/commands/init.d.ts +3 -0
  100. package/dist/commands/init.d.ts.map +1 -0
  101. package/dist/commands/init.js +90 -0
  102. package/dist/commands/init.js.map +1 -0
  103. package/dist/commands/inspect.d.ts +3 -0
  104. package/dist/commands/inspect.d.ts.map +1 -0
  105. package/dist/commands/inspect.js +64 -0
  106. package/dist/commands/inspect.js.map +1 -0
  107. package/dist/commands/install.d.ts +3 -0
  108. package/dist/commands/install.d.ts.map +1 -0
  109. package/dist/commands/install.js +329 -0
  110. package/dist/commands/install.js.map +1 -0
  111. package/dist/commands/journal.d.ts +3 -0
  112. package/dist/commands/journal.d.ts.map +1 -0
  113. package/dist/commands/journal.js +107 -0
  114. package/dist/commands/journal.js.map +1 -0
  115. package/dist/commands/memory.d.ts +3 -0
  116. package/dist/commands/memory.d.ts.map +1 -0
  117. package/dist/commands/memory.js +85 -0
  118. package/dist/commands/memory.js.map +1 -0
  119. package/dist/commands/new.d.ts +3 -0
  120. package/dist/commands/new.d.ts.map +1 -0
  121. package/dist/commands/new.js +68 -0
  122. package/dist/commands/new.js.map +1 -0
  123. package/dist/commands/next.d.ts +3 -0
  124. package/dist/commands/next.d.ts.map +1 -0
  125. package/dist/commands/next.js +107 -0
  126. package/dist/commands/next.js.map +1 -0
  127. package/dist/commands/optimize.d.ts +3 -0
  128. package/dist/commands/optimize.d.ts.map +1 -0
  129. package/dist/commands/optimize.js +28 -0
  130. package/dist/commands/optimize.js.map +1 -0
  131. package/dist/commands/plugin-linker.d.ts +34 -0
  132. package/dist/commands/plugin-linker.d.ts.map +1 -0
  133. package/dist/commands/plugin-linker.js +177 -0
  134. package/dist/commands/plugin-linker.js.map +1 -0
  135. package/dist/commands/refactor.d.ts +3 -0
  136. package/dist/commands/refactor.d.ts.map +1 -0
  137. package/dist/commands/refactor.js +32 -0
  138. package/dist/commands/refactor.js.map +1 -0
  139. package/dist/commands/types.d.ts +19 -0
  140. package/dist/commands/types.d.ts.map +1 -0
  141. package/dist/commands/types.js +7 -0
  142. package/dist/commands/types.js.map +1 -0
  143. package/dist/commands/validate-plan.d.ts +3 -0
  144. package/dist/commands/validate-plan.d.ts.map +1 -0
  145. package/dist/commands/validate-plan.js +62 -0
  146. package/dist/commands/validate-plan.js.map +1 -0
  147. package/dist/commands/validate-spec.d.ts +3 -0
  148. package/dist/commands/validate-spec.d.ts.map +1 -0
  149. package/dist/commands/validate-spec.js +62 -0
  150. package/dist/commands/validate-spec.js.map +1 -0
  151. package/dist/commands/verify.d.ts +3 -0
  152. package/dist/commands/verify.d.ts.map +1 -0
  153. package/dist/commands/verify.js +103 -0
  154. package/dist/commands/verify.js.map +1 -0
  155. package/dist/commands/version.d.ts +3 -0
  156. package/dist/commands/version.d.ts.map +1 -0
  157. package/dist/commands/version.js +12 -0
  158. package/dist/commands/version.js.map +1 -0
  159. package/dist/index.d.ts +3 -0
  160. package/dist/index.d.ts.map +1 -0
  161. package/dist/index.js +27 -0
  162. package/dist/index.js.map +1 -0
  163. package/dist/output/formatter.d.ts +2 -0
  164. package/dist/output/formatter.d.ts.map +1 -0
  165. package/dist/output/formatter.js +10 -0
  166. package/dist/output/formatter.js.map +1 -0
  167. package/dist/output/index.d.ts +2 -0
  168. package/dist/output/index.d.ts.map +1 -0
  169. package/dist/output/index.js +3 -0
  170. package/dist/output/index.js.map +1 -0
  171. package/package.json +37 -3
  172. package/src/application/agent/execution-store.ts +162 -0
  173. package/src/application/agent/gateway.test.ts +529 -0
  174. package/src/application/agent/gateway.ts +744 -0
  175. package/src/application/agent/index.ts +18 -0
  176. package/src/application/agent/orchestrator.test.ts +341 -0
  177. package/src/application/agent/orchestrator.ts +628 -0
  178. package/src/application/agent/providers/claude-code/claude-argv.ts +119 -0
  179. package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +139 -0
  180. package/src/application/agent/providers/claude-code/fixtures/fake-claude.mjs +125 -0
  181. package/src/application/agent/providers/claude-code/index.ts +28 -0
  182. package/src/application/agent/providers/claude-code/mod-parity.ts +50 -0
  183. package/src/application/agent/providers/claude-code/permission-config.test.ts +221 -0
  184. package/src/application/agent/providers/claude-code/permission-config.ts +242 -0
  185. package/src/application/agent/providers/claude-code/provider.test.ts +378 -0
  186. package/src/application/agent/providers/claude-code/provider.ts +717 -0
  187. package/src/application/agent/providers/claude-code/resume-store.test.ts +161 -0
  188. package/src/application/agent/providers/claude-code/resume-store.ts +157 -0
  189. package/src/application/agent/providers/claude-code/stream-parser.ts +166 -0
  190. package/src/application/agent/test-fixture.ts +131 -0
  191. package/src/application/agent/workspace.test.ts +104 -0
  192. package/src/application/agent/workspace.ts +156 -0
  193. package/src/application/dispatcher.test.ts +89 -0
  194. package/src/application/dispatcher.ts +98 -0
  195. package/src/application/index.ts +5 -0
  196. package/src/application/registry.ts +24 -0
  197. package/src/application/version.ts +7 -0
  198. package/src/commands/clse.test.ts +181 -0
  199. package/src/commands/doctor.test.ts +29 -0
  200. package/src/commands/doctor.ts +78 -0
  201. package/src/commands/elicit.test.ts +111 -0
  202. package/src/commands/elicit.ts +188 -0
  203. package/src/commands/evolve.ts +209 -0
  204. package/src/commands/feature.test.ts +323 -0
  205. package/src/commands/feature.ts +405 -0
  206. package/src/commands/fix.test.ts +36 -0
  207. package/src/commands/fix.ts +69 -0
  208. package/src/commands/help.test.ts +33 -0
  209. package/src/commands/help.ts +35 -0
  210. package/src/commands/index.ts +21 -0
  211. package/src/commands/init.test.ts +65 -0
  212. package/src/commands/init.ts +103 -0
  213. package/src/commands/inspect.test.ts +57 -0
  214. package/src/commands/inspect.ts +73 -0
  215. package/src/commands/install.test.ts +61 -0
  216. package/src/commands/install.ts +375 -0
  217. package/src/commands/journal.ts +118 -0
  218. package/src/commands/memory.ts +96 -0
  219. package/src/commands/new.test.ts +44 -0
  220. package/src/commands/new.ts +77 -0
  221. package/src/commands/next.test.ts +241 -0
  222. package/src/commands/next.ts +124 -0
  223. package/src/commands/optimize.ts +30 -0
  224. package/src/commands/plugin-linker.test.ts +139 -0
  225. package/src/commands/plugin-linker.ts +196 -0
  226. package/src/commands/refactor.ts +34 -0
  227. package/src/commands/stack-commands.test.ts +67 -0
  228. package/src/commands/tier-c-conformance.test.ts +194 -0
  229. package/src/commands/types.ts +26 -0
  230. package/src/commands/validate-plan.test.ts +107 -0
  231. package/src/commands/validate-plan.ts +67 -0
  232. package/src/commands/validate-spec.test.ts +59 -0
  233. package/src/commands/validate-spec.ts +68 -0
  234. package/src/commands/verify.test.ts +117 -0
  235. package/src/commands/verify.ts +112 -0
  236. package/src/commands/version.test.ts +11 -0
  237. package/src/commands/version.ts +14 -0
  238. package/src/index.ts +30 -0
  239. package/src/output/formatter.ts +10 -0
  240. package/src/output/index.ts +2 -0
@@ -0,0 +1,529 @@
1
+ // packages/cli/src/application/agent/gateway.test.ts
2
+ //
3
+ // Gateway unit tests (PR3, ADR-0019 v2 revisions A/C/D): the frozen
4
+ // request, the policy chain, capability/budget honesty cross-checks,
5
+ // gateway-enforced duration, idempotent event persistence with a
6
+ // fail-closed policyHash check, sequence auditing, result correlation,
7
+ // cancellation, resume — and the proof that resume tokens never reach
8
+ // disk.
9
+
10
+ import { promises as fs } from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { describe, expect, it } from 'vitest';
14
+ import {
15
+ AGENT_EVENT_SCHEMA_VERSION,
16
+ AGENT_EXECUTION_SCHEMA_VERSION,
17
+ AGENT_POLICY_SNAPSHOT_SCHEMA_VERSION,
18
+ type AgentEventSink,
19
+ type AgentExecutionEvent,
20
+ type AgentExecutionHandle,
21
+ type AgentExecutionRequest,
22
+ type AgentExecutionResult,
23
+ type AgentPolicySnapshot,
24
+ type AgentProvider,
25
+ type AgentProviderCapabilities,
26
+ type AgentProviderId,
27
+ computePolicyHash,
28
+ } from '@agentic-sdlc-kit/contracts';
29
+ import { MockAgentProvider, sampleAgentExecutionRequest } from '@agentic-sdlc-kit/testing';
30
+ import { findInExecutionRecords } from './execution-store.js';
31
+ import { AgentGateway } from './gateway.js';
32
+
33
+ function tempProjectRoot(): Promise<string> {
34
+ return fs.mkdtemp(path.join(os.tmpdir(), 'kit-gateway-'));
35
+ }
36
+
37
+ /** Build a consistent request+snapshot pair from the shared fixture. */
38
+ function buildRequest(overrides: Partial<AgentExecutionRequest> = {}): {
39
+ request: AgentExecutionRequest;
40
+ snapshot: AgentPolicySnapshot;
41
+ } {
42
+ const base = structuredClone(
43
+ sampleAgentExecutionRequest,
44
+ ) as unknown as AgentExecutionRequest;
45
+ const snapshot: AgentPolicySnapshot = {
46
+ schemaVersion: AGENT_POLICY_SNAPSHOT_SCHEMA_VERSION,
47
+ permissions: base.permissions,
48
+ budget: base.budget,
49
+ approvalPolicy: base.approvalPolicy,
50
+ };
51
+ const request: AgentExecutionRequest = {
52
+ ...base,
53
+ policyHash: computePolicyHash(snapshot),
54
+ ...overrides,
55
+ };
56
+ return { request, snapshot };
57
+ }
58
+
59
+ /**
60
+ * Minimal scripted provider for gateway edge cases: replays a fixed event
61
+ * list on subscribe and resolves/rejects result() as configured. It never
62
+ * touches the filesystem — the assertions are about what the GATEWAY
63
+ * persists.
64
+ */
65
+ class ScriptedProvider implements AgentProvider {
66
+ readonly id: AgentProviderId;
67
+ private readonly events: readonly AgentExecutionEvent[];
68
+ private readonly result: (request: AgentExecutionRequest) => Promise<AgentExecutionResult>;
69
+ readonly started: AgentExecutionRequest[] = [];
70
+
71
+ constructor(opts: {
72
+ id?: string;
73
+ events?: readonly AgentExecutionEvent[];
74
+ result?: (request: AgentExecutionRequest) => Promise<AgentExecutionResult>;
75
+ }) {
76
+ // Default 'mock': the shared sample request's providerId is 'mock', so
77
+ // the gateway's registry lookup succeeds without request surgery.
78
+ this.id = (opts.id ?? 'mock') as AgentProviderId;
79
+ this.events = opts.events ?? [];
80
+ this.result =
81
+ opts.result ?? ((request) => Promise.resolve(buildScriptedResult(request.executionId)));
82
+ }
83
+
84
+ async capabilities(): Promise<AgentProviderCapabilities> {
85
+ return {
86
+ capabilities: ['repository.read', 'repository.write', 'process.test'],
87
+ budgetEnforcement: {
88
+ maxDurationMs: 'gateway-enforced',
89
+ maxToolCalls: 'gateway-enforced',
90
+ maxInputTokens: 'best-effort',
91
+ maxOutputTokens: 'best-effort',
92
+ maxTotalTokens: 'best-effort',
93
+ maxEstimatedCost: 'best-effort',
94
+ },
95
+ };
96
+ }
97
+
98
+ async healthCheck(): Promise<{ available: boolean }> {
99
+ return { available: true };
100
+ }
101
+
102
+ async start(
103
+ request: AgentExecutionRequest,
104
+ _signal: AbortSignal,
105
+ ): Promise<AgentExecutionHandle> {
106
+ this.started.push(request);
107
+ const listeners = new Set<AgentEventSink>();
108
+ // Events replay synchronously to every subscriber (the gateway
109
+ // subscribes before awaiting result()).
110
+ return {
111
+ executionId: request.executionId,
112
+ result: () => this.result(request),
113
+ events: (onEvent: AgentEventSink): (() => void) => {
114
+ for (const e of this.events) onEvent(e);
115
+ listeners.add(onEvent);
116
+ return () => listeners.delete(onEvent);
117
+ },
118
+ };
119
+ }
120
+
121
+ async resume(): Promise<AgentExecutionHandle> {
122
+ throw new Error('scripted provider does not resume');
123
+ }
124
+
125
+ async cancel(): Promise<void> {
126
+ /* no-op */
127
+ }
128
+ }
129
+
130
+ function buildScriptedResult(executionId: string): AgentExecutionResult {
131
+ return {
132
+ schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
133
+ executionId,
134
+ workflowRunId: 'run-fixture-001',
135
+ taskId: 'TASK-001',
136
+ providerId: 'mock',
137
+ status: 'completed',
138
+ summary: 'scripted completion',
139
+ proposedArtifacts: [],
140
+ requestedApprovals: [],
141
+ usage: { durationMs: 1 },
142
+ errors: [],
143
+ };
144
+ }
145
+
146
+ function scriptedEvent(
147
+ executionId: string,
148
+ policyHash: string,
149
+ sequence: number,
150
+ eventId = `evt-${executionId}-${sequence}`,
151
+ ): AgentExecutionEvent {
152
+ return {
153
+ schemaVersion: AGENT_EVENT_SCHEMA_VERSION,
154
+ eventId,
155
+ executionId,
156
+ sequence,
157
+ policyHash,
158
+ occurredAt: new Date().toISOString(),
159
+ type: 'execution.started',
160
+ };
161
+ }
162
+
163
+ describe('AgentGateway start: validation and cross-checks', () => {
164
+ it('rejects a request that fails contract validation (nothing persisted)', async () => {
165
+ const root = await tempProjectRoot();
166
+ const gateway = new AgentGateway({ providers: [], projectRoot: root });
167
+ const { request, snapshot } = buildRequest();
168
+ const bad = { ...request, schemaVersion: 99 } as AgentExecutionRequest;
169
+ const res = await gateway.start(bad, { policySnapshot: snapshot });
170
+ expect(res.ok).toBe(false);
171
+ if (!res.ok) expect(res.error.code).toBe('CONTRACT_INVALID');
172
+ expect(await gateway.listExecutions()).toEqual([]);
173
+ });
174
+
175
+ it('fails with AGENT_PROVIDER_NOT_CONFIGURED when the provider is not registered', async () => {
176
+ const root = await tempProjectRoot();
177
+ const gateway = new AgentGateway({ providers: [], projectRoot: root });
178
+ const { request, snapshot } = buildRequest();
179
+ const res = await gateway.start(request, { policySnapshot: snapshot });
180
+ expect(res.ok).toBe(false);
181
+ if (!res.ok) {
182
+ expect(res.error.code).toBe('AGENT_PROVIDER_NOT_CONFIGURED');
183
+ expect(res.error.message).toContain(request.providerId);
184
+ }
185
+ });
186
+
187
+ it('rejects a snapshot that diverges from the request policy fields', async () => {
188
+ const root = await tempProjectRoot();
189
+ const provider = new MockAgentProvider();
190
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
191
+ const { request, snapshot } = buildRequest();
192
+ const diverged: AgentPolicySnapshot = {
193
+ ...snapshot,
194
+ permissions: { ...snapshot.permissions, networkAllowed: true },
195
+ };
196
+ // request.policyHash still hashes the ORIGINAL snapshot — chain broken.
197
+ const res = await gateway.start(request, { policySnapshot: diverged });
198
+ expect(res.ok).toBe(false);
199
+ if (!res.ok) expect(res.error.code).toBe('POLICY_VIOLATION');
200
+ });
201
+
202
+ it('rejects a policyHash that does not match the snapshot', async () => {
203
+ const root = await tempProjectRoot();
204
+ const provider = new MockAgentProvider();
205
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
206
+ const { request, snapshot } = buildRequest({ policyHash: 'sha256:not-the-snapshot' });
207
+ const res = await gateway.start(request, { policySnapshot: snapshot });
208
+ expect(res.ok).toBe(false);
209
+ if (!res.ok) expect(res.error.code).toBe('POLICY_VIOLATION');
210
+ });
211
+
212
+ it('rejects capabilities the provider does not support (honest grant)', async () => {
213
+ const root = await tempProjectRoot();
214
+ const provider = new MockAgentProvider(); // supports no git.write
215
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
216
+ const { request, snapshot } = buildRequest();
217
+ const extended: AgentPolicySnapshot = {
218
+ ...snapshot,
219
+ permissions: {
220
+ ...snapshot.permissions,
221
+ capabilities: [...snapshot.permissions.capabilities, 'git.write'],
222
+ },
223
+ };
224
+ const res = await gateway.start(
225
+ { ...request, permissions: extended.permissions, policyHash: computePolicyHash(extended) },
226
+ { policySnapshot: extended },
227
+ );
228
+ expect(res.ok).toBe(false);
229
+ if (!res.ok) {
230
+ expect(res.error.code).toBe('POLICY_VIOLATION');
231
+ expect(res.error.message).toContain('git.write');
232
+ }
233
+ });
234
+
235
+ it('rejects a cost budget the provider can only enforce best-effort (rev C)', async () => {
236
+ const root = await tempProjectRoot();
237
+ const provider = new MockAgentProvider(); // cost: best-effort
238
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
239
+ const { request, snapshot } = buildRequest();
240
+ const costly: AgentPolicySnapshot = {
241
+ ...snapshot,
242
+ budget: { ...snapshot.budget, maxEstimatedCost: { amount: 1, currency: 'USD' } },
243
+ };
244
+ const res = await gateway.start(
245
+ { ...request, budget: costly.budget, policyHash: computePolicyHash(costly) },
246
+ { policySnapshot: costly },
247
+ );
248
+ expect(res.ok).toBe(false);
249
+ if (!res.ok) expect(res.error.message).toContain('maxEstimatedCost');
250
+ });
251
+ });
252
+
253
+ describe('AgentGateway start: happy path and persistence', () => {
254
+ it('persists the original request BEFORE the provider sees it, then the terminal state', async () => {
255
+ const root = await tempProjectRoot();
256
+ const provider = new MockAgentProvider();
257
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
258
+ const { request, snapshot } = buildRequest();
259
+ const res = await gateway.start(request, { policySnapshot: snapshot });
260
+ expect(res.ok).toBe(true);
261
+ if (!res.ok) return;
262
+ expect(res.value.status).toBe('completed');
263
+ expect(res.value.request).toEqual(request); // frozen verbatim (rev A)
264
+ expect(res.value.policySnapshot).toEqual(snapshot);
265
+ expect(res.value.attempts).toBe(1);
266
+ // Events: started, tool.requested, tool.result, completed — all accepted.
267
+ expect(res.value.events.map((e) => e.type)).toEqual([
268
+ 'execution.started',
269
+ 'tool.requested',
270
+ 'tool.result',
271
+ 'execution.completed',
272
+ ]);
273
+ // Sequences are monotonic from 1.
274
+ expect(res.value.events.map((e) => e.sequence)).toEqual([1, 2, 3, 4]);
275
+ // Every event echoes the frozen policyHash.
276
+ for (const e of res.value.events) expect(e.policyHash).toBe(request.policyHash);
277
+ // Replay is idempotent: a fresh read returns the same durable record.
278
+ const again = await gateway.getExecution(request.executionId);
279
+ expect(again?.events).toHaveLength(4);
280
+ expect(again?.status).toBe('completed');
281
+ });
282
+
283
+ it('is reachable through listExecutions', async () => {
284
+ const root = await tempProjectRoot();
285
+ const provider = new MockAgentProvider();
286
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
287
+ const { request, snapshot } = buildRequest();
288
+ await gateway.start(request, { policySnapshot: snapshot });
289
+ expect((await gateway.listExecutions()).map((e) => e.executionId)).toEqual([
290
+ request.executionId,
291
+ ]);
292
+ });
293
+ });
294
+
295
+ describe('AgentGateway event pipeline (rev D): fail closed, idempotent', () => {
296
+ it('rejects events whose policyHash echo does not match the frozen policy', async () => {
297
+ const root = await tempProjectRoot();
298
+ const { request, snapshot } = buildRequest();
299
+ const provider = new ScriptedProvider({
300
+ events: [
301
+ scriptedEvent(request.executionId, 'sha256:wrong-policy', 1),
302
+ scriptedEvent(request.executionId, request.policyHash, 2),
303
+ ],
304
+ });
305
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
306
+ const res = await gateway.start(request, { policySnapshot: snapshot });
307
+ expect(res.ok).toBe(true);
308
+ if (!res.ok) return;
309
+ // Only the matching event was accepted...
310
+ expect(res.value.events.map((e) => e.sequence)).toEqual([2]);
311
+ // ...and the rejection is audited, not silent.
312
+ expect(res.value.eventAudit.map((a) => a.kind)).toContain('policy-hash-mismatch');
313
+ });
314
+
315
+ it('skips duplicate eventIds idempotently and audits them', async () => {
316
+ const root = await tempProjectRoot();
317
+ const { request, snapshot } = buildRequest();
318
+ const dup = scriptedEvent(request.executionId, request.policyHash, 1);
319
+ const provider = new ScriptedProvider({
320
+ events: [dup, { ...dup, sequence: 2 }],
321
+ });
322
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
323
+ const res = await gateway.start(request, { policySnapshot: snapshot });
324
+ expect(res.ok).toBe(true);
325
+ if (!res.ok) return;
326
+ expect(res.value.events).toHaveLength(1);
327
+ expect(res.value.eventAudit.map((a) => a.kind)).toContain('duplicate-event-id');
328
+ });
329
+
330
+ it('flags non-monotonic sequences and gaps, but stores the events (detectable)', async () => {
331
+ const root = await tempProjectRoot();
332
+ const { request, snapshot } = buildRequest();
333
+ const provider = new ScriptedProvider({
334
+ events: [
335
+ scriptedEvent(request.executionId, request.policyHash, 1),
336
+ scriptedEvent(request.executionId, request.policyHash, 1, 'evt-sequence-regression'),
337
+ scriptedEvent(request.executionId, request.policyHash, 5),
338
+ ],
339
+ });
340
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
341
+ const res = await gateway.start(request, { policySnapshot: snapshot });
342
+ expect(res.ok).toBe(true);
343
+ if (!res.ok) return;
344
+ expect(res.value.events).toHaveLength(3);
345
+ const anomalies = res.value.eventAudit.filter((a) => a.kind === 'sequence-anomaly');
346
+ expect(anomalies).toHaveLength(2);
347
+ });
348
+
349
+ it('rejects events for a different executionId', async () => {
350
+ const root = await tempProjectRoot();
351
+ const { request, snapshot } = buildRequest();
352
+ const provider = new ScriptedProvider({
353
+ events: [scriptedEvent('someone-else', request.policyHash, 1)],
354
+ });
355
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
356
+ const res = await gateway.start(request, { policySnapshot: snapshot });
357
+ expect(res.ok).toBe(true);
358
+ if (!res.ok) return;
359
+ expect(res.value.events).toHaveLength(0);
360
+ expect(res.value.eventAudit.map((a) => a.kind)).toContain('wrong-execution-id');
361
+ });
362
+ });
363
+
364
+ describe('AgentGateway results and enforced bounds', () => {
365
+ it('refuses a result that fails contract validation (interrupted, never completed)', async () => {
366
+ const root = await tempProjectRoot();
367
+ const { request, snapshot } = buildRequest();
368
+ const provider = new ScriptedProvider({
369
+ result: () =>
370
+ Promise.resolve({ bogus: true } as unknown as AgentExecutionResult),
371
+ });
372
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
373
+ const res = await gateway.start(request, { policySnapshot: snapshot });
374
+ expect(res.ok).toBe(false);
375
+ if (!res.ok) expect(res.error.code).toBe('CONTRACT_INVALID');
376
+ const stored = await gateway.getExecution(request.executionId);
377
+ expect(stored?.status).toBe('interrupted');
378
+ });
379
+
380
+ it('refuses a result correlated to a different executionId', async () => {
381
+ const root = await tempProjectRoot();
382
+ const { request, snapshot } = buildRequest();
383
+ const provider = new ScriptedProvider({
384
+ result: () => Promise.resolve(buildScriptedResult('not-my-execution')),
385
+ });
386
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
387
+ const res = await gateway.start(request, { policySnapshot: snapshot });
388
+ expect(res.ok).toBe(false);
389
+ const stored = await gateway.getExecution(request.executionId);
390
+ expect(stored?.status).toBe('interrupted');
391
+ expect(stored?.gatewayNotes.join(' ')).toContain('correlation refused');
392
+ });
393
+
394
+ it('treats a transport-level rejection as interrupted with an INTERNAL error', async () => {
395
+ const root = await tempProjectRoot();
396
+ const { request, snapshot } = buildRequest();
397
+ const provider = new ScriptedProvider({
398
+ result: () => Promise.reject(new Error('provider unreachable')),
399
+ });
400
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
401
+ const res = await gateway.start(request, { policySnapshot: snapshot });
402
+ expect(res.ok).toBe(false);
403
+ if (!res.ok) expect(res.error.code).toBe('INTERNAL');
404
+ const stored = await gateway.getExecution(request.executionId);
405
+ expect(stored?.status).toBe('interrupted');
406
+ });
407
+
408
+ it('enforces the duration budget itself: breach ends timed_out with the provider report kept', async () => {
409
+ const root = await tempProjectRoot();
410
+ const provider = new MockAgentProvider({ delayMs: 2_000 });
411
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
412
+ const { request, snapshot } = buildRequest();
413
+ const tight: AgentPolicySnapshot = {
414
+ ...snapshot,
415
+ budget: { ...snapshot.budget, maxDurationMs: 100 },
416
+ };
417
+ const res = await gateway.start(
418
+ { ...request, budget: tight.budget, policyHash: computePolicyHash(tight) },
419
+ { policySnapshot: tight },
420
+ );
421
+ expect(res.ok).toBe(true);
422
+ if (!res.ok) return;
423
+ expect(res.value.status).toBe('timed_out');
424
+ expect(res.value.providerReportedStatus).toBe('cancelled'); // mock reports cancelled after the gateway's abort
425
+ expect(res.value.gatewayNotes.join(' ')).toContain('duration budget');
426
+ });
427
+
428
+ it('propagates an external abort as cancelled', async () => {
429
+ const root = await tempProjectRoot();
430
+ const provider = new MockAgentProvider({ delayMs: 2_000 });
431
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
432
+ const { request, snapshot } = buildRequest();
433
+ const controller = new AbortController();
434
+ setTimeout(() => controller.abort(), 50);
435
+ const res = await gateway.start(request, { policySnapshot: snapshot, signal: controller.signal });
436
+ expect(res.ok).toBe(true);
437
+ if (!res.ok) return;
438
+ expect(res.value.status).toBe('cancelled');
439
+ });
440
+
441
+ it('an already-aborted signal yields cancelled without executing work', async () => {
442
+ const root = await tempProjectRoot();
443
+ let workRan = false;
444
+ const provider = new MockAgentProvider({
445
+ delayMs: 0,
446
+ performWork: () => {
447
+ workRan = true;
448
+ },
449
+ });
450
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
451
+ const { request, snapshot } = buildRequest();
452
+ const controller = new AbortController();
453
+ controller.abort();
454
+ const res = await gateway.start(request, { policySnapshot: snapshot, signal: controller.signal });
455
+ expect(res.ok).toBe(true);
456
+ if (!res.ok) return;
457
+ expect(res.value.status).toBe('cancelled');
458
+ expect(workRan).toBe(false);
459
+ });
460
+ });
461
+
462
+ describe('AgentGateway resume and cancel', () => {
463
+ it('resume reuses the persisted execution and increments attempts; token never persists', async () => {
464
+ const root = await tempProjectRoot();
465
+ const { request, snapshot } = buildRequest();
466
+ const provider = new MockAgentProvider({
467
+ resumePolicyHash: request.policyHash,
468
+ });
469
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root });
470
+ const first = await gateway.start(request, { policySnapshot: snapshot });
471
+ expect(first.ok).toBe(true);
472
+
473
+ const SECRET_TOKEN = 'tok-NEVER-PERSIST-abc123';
474
+ const second = await gateway.resume(request.executionId, SECRET_TOKEN);
475
+ expect(second.ok).toBe(true);
476
+ if (!second.ok) return;
477
+ expect(second.value.attempts).toBe(2);
478
+ expect(second.value.status).toBe('completed');
479
+ // The mock's resume replays the same eventIds — idempotent skip.
480
+ expect(second.value.eventAudit.map((a) => a.kind)).toContain('duplicate-event-id');
481
+ // SECURITY (ADR-0020 §6): the credential never reached disk.
482
+ expect(await findInExecutionRecords(root, SECRET_TOKEN)).toEqual([]);
483
+ expect(provider.wasResumedWith(request.executionId)).toBe(SECRET_TOKEN);
484
+ });
485
+
486
+ it('resume of an unknown execution is an error', async () => {
487
+ const root = await tempProjectRoot();
488
+ const gateway = new AgentGateway({
489
+ providers: [new MockAgentProvider()],
490
+ projectRoot: root,
491
+ });
492
+ const res = await gateway.resume('never-started', 'tok');
493
+ expect(res.ok).toBe(false);
494
+ if (!res.ok) expect(res.error.code).toBe('CONTRACT_INVALID');
495
+ });
496
+
497
+ it('cancel of an unknown execution is an error, not a guess', async () => {
498
+ const root = await tempProjectRoot();
499
+ const gateway = new AgentGateway({
500
+ providers: [new MockAgentProvider()],
501
+ projectRoot: root,
502
+ });
503
+ const res = await gateway.cancel('never-started');
504
+ expect(res.ok).toBe(false);
505
+ });
506
+
507
+ it('cancel marks a non-terminal execution cancelled and is idempotent', async () => {
508
+ const root = await tempProjectRoot();
509
+ const { request, snapshot } = buildRequest();
510
+ const provider = new ScriptedProvider({
511
+ // Never settles on its own: only the gateway's cancel path can end it.
512
+ result: () => new Promise<AgentExecutionResult>(() => undefined),
513
+ });
514
+ const gateway = new AgentGateway({ providers: [provider], projectRoot: root, drainMs: 200 });
515
+ const startPromise = gateway.start(request, { policySnapshot: snapshot });
516
+ // Give the start path a tick to persist the record, then cancel.
517
+ await new Promise((r) => setTimeout(r, 20));
518
+ await gateway.cancel(request.executionId);
519
+ const res = await startPromise;
520
+ // The scripted provider never lands a result; after the drain window
521
+ // the gateway concludes the execution ended by its own cancellation.
522
+ expect(res.ok).toBe(true);
523
+ if (res.ok) expect(res.value.status).toBe('cancelled');
524
+ const stored = await gateway.getExecution(request.executionId);
525
+ expect(stored?.status).toBe('cancelled');
526
+ const again = await gateway.cancel(request.executionId);
527
+ expect(again.ok).toBe(true);
528
+ });
529
+ });