@dailephd/my-centcom 0.2.0 → 0.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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,892 @@
1
+ import {
2
+ BrowserRequestV1Schema,
3
+ LoopbackHttpRequestV1Schema,
4
+ LoopbackHttpResponseV1Schema,
5
+ ContractErrorV1Schema,
6
+ NormalizedResultSchema,
7
+ NormalizedEventV1Schema,
8
+ RunLifecycleRecordV1Schema,
9
+ createProjectId,
10
+ createPluginId,
11
+ createOperationId,
12
+ createBrowserRequestId,
13
+ createIdempotencyKey,
14
+ BoundedFileResponseV1Schema,
15
+ ArtifactRecordV1Schema,
16
+ ShipmentSelectionV1Schema,
17
+ ReturnCargoV1Schema,
18
+ verifyShipmentProvenance,
19
+ createShipmentId,
20
+ createRunId,
21
+ } from '../../../../packages/contracts/dist/index.js';
22
+
23
+ /**
24
+ * Manifest V3 Extension Service Worker for the M03/M04 fixture path.
25
+ * Bridges probe-page user actions -> content script selection -> daemon loopback HTTP.
26
+ *
27
+ * Scope: fixture-only. Nothing here establishes compatibility with the real ChatGPT Web DOM.
28
+ */
29
+
30
+ const FIXTURE_PROJECT_ID = 'project.m03-fixture';
31
+ const FIXTURE_PLUGIN_ID = 'plugin.m03-fake';
32
+ const FIXTURE_OPERATION_ID = 'run-sentinel';
33
+ const DEFAULT_CONVERSATION_ID = 'conversation.m03-fixture';
34
+ const FETCH_TIMEOUT_MS = 15000;
35
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
36
+ const MAX_ID_LENGTH = 256;
37
+
38
+ // In-memory count of in-flight dispatches (diagnostics only).
39
+ const activeRequests = new Set<string>();
40
+
41
+ interface SelectionSnapshot {
42
+ tabId: number;
43
+ sourceUrl: string;
44
+ conversationId: string;
45
+ text: string;
46
+ fingerprint: string;
47
+ }
48
+
49
+ interface Failure {
50
+ success: false;
51
+ errorType: string;
52
+ errorCode?: string;
53
+ statusCode?: number;
54
+ requestId?: string;
55
+ idempotencyKey?: string;
56
+ error: string;
57
+ }
58
+
59
+ function failure(
60
+ errorType: string,
61
+ error: string,
62
+ extra: Partial<Failure> = {}
63
+ ): Failure {
64
+ return { success: false, errorType, error, ...extra };
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Sender validation
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /**
72
+ * Only the extension-owned probe page may issue preview/dispatch instructions.
73
+ * An absent id/url, a content script (page URL) or another extension page is rejected.
74
+ */
75
+ function isProbePageSender(sender: chrome.runtime.MessageSender): boolean {
76
+ if (sender.id !== chrome.runtime.id) {
77
+ return false;
78
+ }
79
+ if (typeof sender.url !== 'string') {
80
+ return false;
81
+ }
82
+ const probeUrl = chrome.runtime.getURL('probe/index.html');
83
+ if (sender.url !== probeUrl && !sender.url.startsWith(`${probeUrl}?`)) {
84
+ return false;
85
+ }
86
+ return sender.frameId === undefined || sender.frameId === 0;
87
+ }
88
+
89
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
90
+ if (!isProbePageSender(sender)) {
91
+ sendResponse(
92
+ failure(
93
+ 'UNAUTHORIZED_SENDER',
94
+ 'Message rejected: sender is not the extension probe page'
95
+ )
96
+ );
97
+ return true;
98
+ }
99
+
100
+ const action = (message as { action?: unknown } | null)?.action;
101
+
102
+ if (action === 'GET_WORKER_INFO') {
103
+ const isServiceWorkerGlobalScope =
104
+ typeof (globalThis as unknown as { ServiceWorkerGlobalScope?: unknown }).ServiceWorkerGlobalScope !== 'undefined';
105
+ sendResponse({
106
+ extensionId: chrome.runtime.id,
107
+ isServiceWorkerGlobalScope,
108
+ hasWindowObject: typeof window === 'undefined',
109
+ activeRequestsCount: activeRequests.size,
110
+ });
111
+ return true;
112
+ }
113
+
114
+ if (action === 'PREVIEW_FIXTURE_SELECTION') {
115
+ handlePreview(message as Record<string, unknown>)
116
+ .then((res) => sendResponse(res))
117
+ .catch(() => sendResponse(failure('UNHANDLED_EXCEPTION', 'Preview failed unexpectedly')));
118
+ return true;
119
+ }
120
+
121
+ if (action === 'DISPATCH_FIXTURE_PROMPT') {
122
+ handleDispatch(message as Record<string, unknown>)
123
+ .then((res) => sendResponse(res))
124
+ .catch(() => sendResponse(failure('UNHANDLED_EXCEPTION', 'Dispatch failed unexpectedly')));
125
+ return true; // Keep channel open for async response
126
+ }
127
+
128
+ if (action === 'FETCH_FIXTURE_EVIDENCE') {
129
+ handleFetchEvidence(message as Record<string, unknown>)
130
+ .then((res) => sendResponse(res))
131
+ .catch(() => sendResponse(failure('UNHANDLED_EXCEPTION', 'Evidence fetch failed unexpectedly')));
132
+ return true;
133
+ }
134
+
135
+ if (action === 'PREPARE_FIXTURE_RETURN') {
136
+ handlePrepareReturn(message as Record<string, unknown>)
137
+ .then((res) => sendResponse(res))
138
+ .catch(() => sendResponse(failure('UNHANDLED_EXCEPTION', 'Return preparation failed unexpectedly')));
139
+ return true;
140
+ }
141
+
142
+ return false;
143
+ });
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // Fixture URL / daemon URL validation
147
+ // ---------------------------------------------------------------------------
148
+
149
+ function isLoopbackFixtureUrl(url: unknown): url is string {
150
+ if (typeof url !== 'string') {
151
+ return false;
152
+ }
153
+ try {
154
+ const parsed = new URL(url);
155
+ return (
156
+ parsed.protocol === 'http:' &&
157
+ (parsed.hostname === '127.0.0.1' || parsed.hostname === 'localhost') &&
158
+ parsed.username === '' &&
159
+ parsed.password === ''
160
+ );
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Accepts only canonical `http://127.0.0.1:<port>` (one optional trailing slash).
168
+ * Rejects other hosts, schemes, credentials, paths, queries, fragments and invalid ports.
169
+ */
170
+ function canonicalDaemonUrl(raw: unknown): string | undefined {
171
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 64) {
172
+ return undefined;
173
+ }
174
+ let parsed: URL;
175
+ try {
176
+ parsed = new URL(raw);
177
+ } catch {
178
+ return undefined;
179
+ }
180
+ if (
181
+ parsed.protocol !== 'http:' ||
182
+ parsed.hostname !== '127.0.0.1' ||
183
+ parsed.username !== '' ||
184
+ parsed.password !== '' ||
185
+ parsed.search !== '' ||
186
+ parsed.hash !== '' ||
187
+ parsed.pathname !== '/'
188
+ ) {
189
+ return undefined;
190
+ }
191
+ if (!/^[0-9]{1,5}$/.test(parsed.port)) {
192
+ return undefined;
193
+ }
194
+ const port = Number(parsed.port);
195
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
196
+ return undefined;
197
+ }
198
+ const canonical = `http://127.0.0.1:${port}`;
199
+ if (raw !== canonical && raw !== `${canonical}/`) {
200
+ return undefined;
201
+ }
202
+ return canonical;
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Selection capture and fingerprint
207
+ // ---------------------------------------------------------------------------
208
+
209
+ async function computeSelectionFingerprint(
210
+ tabId: number,
211
+ sourceUrl: string,
212
+ conversationId: string,
213
+ capturedText: string
214
+ ): Promise<string> {
215
+ const bytes = new TextEncoder().encode(
216
+ JSON.stringify([tabId, sourceUrl, conversationId, capturedText])
217
+ );
218
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
219
+ return Array.from(new Uint8Array(digest))
220
+ .map((b) => b.toString(16).padStart(2, '0'))
221
+ .join('');
222
+ }
223
+
224
+ type TabResolution = { ok: true; tabId: number } | { ok: false; failure: Failure };
225
+
226
+ async function resolveTargetTab(targetTabId: unknown): Promise<TabResolution> {
227
+ if (targetTabId !== undefined && targetTabId !== null) {
228
+ if (typeof targetTabId !== 'number' || !Number.isInteger(targetTabId) || targetTabId < 0) {
229
+ return {
230
+ ok: false,
231
+ failure: failure('INVALID_TARGET_TAB', 'targetTabId must be a non-negative integer'),
232
+ };
233
+ }
234
+ return { ok: true, tabId: targetTabId };
235
+ }
236
+
237
+ const tabs = await chrome.tabs.query({ url: ['http://127.0.0.1/*', 'http://localhost/*'] });
238
+ const candidates = tabs.filter(
239
+ (tab) => typeof tab.id === 'number' && isLoopbackFixtureUrl(tab.url)
240
+ );
241
+ if (candidates.length === 0) {
242
+ return {
243
+ ok: false,
244
+ failure: failure(
245
+ 'TARGET_TAB_NOT_FOUND',
246
+ 'No loopback fixture tab found with the fixture content script'
247
+ ),
248
+ };
249
+ }
250
+ if (candidates.length > 1) {
251
+ return {
252
+ ok: false,
253
+ failure: failure(
254
+ 'AMBIGUOUS_TARGET_TAB',
255
+ `Multiple fixture tabs open (${candidates.length}); an explicit target tab is required`
256
+ ),
257
+ };
258
+ }
259
+ return { ok: true, tabId: candidates[0].id as number };
260
+ }
261
+
262
+ type SnapshotResult = { ok: true; snapshot: SelectionSnapshot } | { ok: false; failure: Failure };
263
+
264
+ async function readSelection(tabId: number): Promise<SnapshotResult> {
265
+ let tab: chrome.tabs.Tab;
266
+ try {
267
+ tab = await chrome.tabs.get(tabId);
268
+ } catch {
269
+ return {
270
+ ok: false,
271
+ failure: failure('TARGET_TAB_NOT_FOUND', 'Target tab no longer exists'),
272
+ };
273
+ }
274
+
275
+ if (!isLoopbackFixtureUrl(tab.url)) {
276
+ return {
277
+ ok: false,
278
+ failure: failure(
279
+ 'INVALID_TARGET_TAB',
280
+ 'Target tab is not a loopback fixture page'
281
+ ),
282
+ };
283
+ }
284
+ const sourceUrl = tab.url;
285
+
286
+ let capture: {
287
+ success?: boolean;
288
+ text?: unknown;
289
+ conversationId?: unknown;
290
+ sourceUrl?: unknown;
291
+ error?: unknown;
292
+ };
293
+ try {
294
+ capture = await chrome.tabs.sendMessage(tabId, { action: 'CAPTURE_SELECTION' });
295
+ } catch {
296
+ return {
297
+ ok: false,
298
+ failure: failure(
299
+ 'CONTENT_SCRIPT_COMMUNICATION_ERROR',
300
+ 'Failed to communicate with the fixture content script'
301
+ ),
302
+ };
303
+ }
304
+
305
+ if (
306
+ !capture ||
307
+ capture.success !== true ||
308
+ typeof capture.text !== 'string' ||
309
+ capture.text.length === 0
310
+ ) {
311
+ return {
312
+ ok: false,
313
+ failure: failure('SELECTION_CAPTURE_FAILED', 'Content script did not return a fixture selection'),
314
+ };
315
+ }
316
+ if (capture.sourceUrl !== sourceUrl) {
317
+ return {
318
+ ok: false,
319
+ failure: failure('SELECTION_CAPTURE_FAILED', 'Content script source does not match the target tab'),
320
+ };
321
+ }
322
+
323
+ const conversationId =
324
+ typeof capture.conversationId === 'string' && capture.conversationId.length > 0
325
+ ? capture.conversationId
326
+ : DEFAULT_CONVERSATION_ID;
327
+
328
+ const fingerprint = await computeSelectionFingerprint(tabId, sourceUrl, conversationId, capture.text);
329
+ return {
330
+ ok: true,
331
+ snapshot: { tabId, sourceUrl, conversationId, text: capture.text, fingerprint },
332
+ };
333
+ }
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // Preview (read-only; never contacts the daemon)
337
+ // ---------------------------------------------------------------------------
338
+
339
+ async function handlePreview(msg: Record<string, unknown>) {
340
+ const target = await resolveTargetTab(msg.targetTabId);
341
+ if (!target.ok) {
342
+ return target.failure;
343
+ }
344
+ const read = await readSelection(target.tabId);
345
+ if (!read.ok) {
346
+ return read.failure;
347
+ }
348
+ return { success: true as const, preview: read.snapshot };
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // Response validation
353
+ // ---------------------------------------------------------------------------
354
+
355
+ interface SentRequest {
356
+ requestId: string;
357
+ idempotencyKey: string;
358
+ projectId: string;
359
+ }
360
+
361
+ type ValidatedResponse =
362
+ | { kind: 'success'; runId: string; outputSummary: string; lifecycleState: string }
363
+ | { kind: 'rejected'; errorCode: string }
364
+ | { kind: 'malformed'; reason: string };
365
+
366
+ function malformed(reason: string): ValidatedResponse {
367
+ return { kind: 'malformed', reason };
368
+ }
369
+
370
+ function validateDaemonResponse(
371
+ httpStatus: number,
372
+ body: unknown,
373
+ sent: SentRequest
374
+ ): ValidatedResponse {
375
+ const envelope = LoopbackHttpResponseV1Schema.safeParse(body);
376
+ if (!envelope.success) {
377
+ return malformed('ENVELOPE_SCHEMA_INVALID');
378
+ }
379
+ const response = envelope.data;
380
+ if (response.requestId !== sent.requestId) {
381
+ return malformed('REQUEST_ID_MISMATCH');
382
+ }
383
+ if (response.statusCode !== httpStatus) {
384
+ return malformed('STATUS_CODE_MISMATCH');
385
+ }
386
+ const topLevel = body as Record<string, unknown>;
387
+
388
+ if (httpStatus >= 400) {
389
+ if (response.data !== undefined) {
390
+ return malformed('ERROR_RESPONSE_CARRIES_DATA');
391
+ }
392
+ const error = ContractErrorV1Schema.safeParse(response.error);
393
+ if (!error.success) {
394
+ return malformed('ERROR_SCHEMA_INVALID');
395
+ }
396
+ if (error.data.correlationId !== sent.requestId) {
397
+ return malformed('ERROR_CORRELATION_MISMATCH');
398
+ }
399
+ if (topLevel.errorCode !== undefined && topLevel.errorCode !== error.data.errorCode) {
400
+ return malformed('ERROR_CODE_CONTRADICTION');
401
+ }
402
+ return { kind: 'rejected', errorCode: error.data.errorCode };
403
+ }
404
+
405
+ if (httpStatus !== 200) {
406
+ return malformed('UNEXPECTED_SUCCESS_STATUS');
407
+ }
408
+ if (response.error !== undefined || topLevel.errorCode !== undefined) {
409
+ return malformed('SUCCESS_RESPONSE_CARRIES_ERROR');
410
+ }
411
+ const data = response.data;
412
+ if (!data) {
413
+ return malformed('SUCCESS_DATA_MISSING');
414
+ }
415
+
416
+ const runId = data.runId;
417
+ if (typeof runId !== 'string' || runId.length === 0) {
418
+ return malformed('RUN_ID_MISSING');
419
+ }
420
+
421
+ const result = NormalizedResultSchema.safeParse(data.result);
422
+ if (!result.success || result.data.runId !== runId) {
423
+ return malformed('RESULT_RUN_ID_MISMATCH');
424
+ }
425
+ if (result.data.exitCode !== 0) {
426
+ return malformed('RESULT_NOT_SUCCESSFUL');
427
+ }
428
+
429
+ if (!Array.isArray(data.events)) {
430
+ return malformed('EVENTS_MISSING');
431
+ }
432
+ for (const rawEvent of data.events) {
433
+ const event = NormalizedEventV1Schema.safeParse(rawEvent);
434
+ if (!event.success || event.data.runId !== runId) {
435
+ return malformed('EVENT_RUN_ID_MISMATCH');
436
+ }
437
+ }
438
+
439
+ const lifecycle = RunLifecycleRecordV1Schema.safeParse(data.lifecycleRecord);
440
+ if (
441
+ !lifecycle.success ||
442
+ lifecycle.data.runId !== runId ||
443
+ lifecycle.data.projectId !== sent.projectId ||
444
+ lifecycle.data.idempotencyKey !== sent.idempotencyKey
445
+ ) {
446
+ return malformed('LIFECYCLE_RECORD_MISMATCH');
447
+ }
448
+ if (lifecycle.data.currentState !== 'COMPLETED' || data.status !== 'COMPLETED') {
449
+ return malformed('TERMINAL_STATE_MISMATCH');
450
+ }
451
+ if (data.outputSummary !== result.data.outputSummary) {
452
+ return malformed('OUTPUT_SUMMARY_MISMATCH');
453
+ }
454
+
455
+ return {
456
+ kind: 'success',
457
+ runId,
458
+ outputSummary: result.data.outputSummary,
459
+ lifecycleState: lifecycle.data.currentState,
460
+ };
461
+ }
462
+
463
+ // ---------------------------------------------------------------------------
464
+ // Dispatch
465
+ // ---------------------------------------------------------------------------
466
+
467
+ function optionalId(value: unknown, prefix: string): string | Failure {
468
+ if (value === undefined || value === null || value === '') {
469
+ return `${prefix}${crypto.randomUUID()}`;
470
+ }
471
+ if (typeof value !== 'string' || value.length > MAX_ID_LENGTH) {
472
+ return failure('INVALID_REQUEST_IDENTITY', 'requestId/idempotencyKey must be bounded strings');
473
+ }
474
+ return value;
475
+ }
476
+
477
+ async function handleDispatch(msg: Record<string, unknown>): Promise<object> {
478
+ // 1. The destination is validated before anything is captured or any credential is touched.
479
+ const daemonUrl = canonicalDaemonUrl(msg.daemonUrl);
480
+ if (!daemonUrl) {
481
+ return failure(
482
+ 'INVALID_DAEMON_URL',
483
+ 'Daemon URL must be canonical http://127.0.0.1:<port>'
484
+ );
485
+ }
486
+
487
+ const authToken = typeof msg.token === 'string' ? msg.token : '';
488
+ if (authToken.length === 0) {
489
+ return failure('MISSING_TOKEN', 'No authorization token supplied', {
490
+ errorCode: 'MISSING_OR_INVALID_AUTHORIZATION',
491
+ });
492
+ }
493
+
494
+ // 2. A prior explicit preview is mandatory.
495
+ const rawPreview = msg.preview as Partial<SelectionSnapshot> | undefined;
496
+ if (
497
+ !rawPreview ||
498
+ typeof rawPreview.tabId !== 'number' ||
499
+ typeof rawPreview.fingerprint !== 'string' ||
500
+ rawPreview.fingerprint.length === 0
501
+ ) {
502
+ return failure('PREVIEW_REQUIRED', 'Dispatch requires a successful prior preview');
503
+ }
504
+
505
+ // 3. Re-read the exact selection; the preview never authorizes changed content.
506
+ const fresh = await readSelection(rawPreview.tabId);
507
+ if (!fresh.ok) {
508
+ return failure('STALE_REQUEST_OR_SELECTION', 'Previewed selection can no longer be read', {
509
+ errorCode: 'STALE_REQUEST_OR_SELECTION',
510
+ });
511
+ }
512
+ if (fresh.snapshot.fingerprint !== rawPreview.fingerprint) {
513
+ return failure(
514
+ 'STALE_REQUEST_OR_SELECTION',
515
+ 'Selection, source, conversation or tab changed since preview',
516
+ { errorCode: 'STALE_REQUEST_OR_SELECTION' }
517
+ );
518
+ }
519
+
520
+ // 4. Build correlated requests.
521
+ const requestIdValue = optionalId(msg.requestId, 'req.m04-');
522
+ if (typeof requestIdValue !== 'string') {
523
+ return requestIdValue;
524
+ }
525
+ const idempotencyValue = optionalId(msg.idempotencyKey, 'idem.m04-');
526
+ if (typeof idempotencyValue !== 'string') {
527
+ return idempotencyValue;
528
+ }
529
+
530
+ const browserRequest = BrowserRequestV1Schema.parse({
531
+ schemaVersion: 1,
532
+ requestId: createBrowserRequestId(requestIdValue),
533
+ action: 'DISPATCH_PROMPT',
534
+ projectId: createProjectId(FIXTURE_PROJECT_ID),
535
+ pluginId: createPluginId(FIXTURE_PLUGIN_ID),
536
+ operationId: createOperationId(FIXTURE_OPERATION_ID),
537
+ payload: { prompt: fresh.snapshot.text },
538
+ conversationId: fresh.snapshot.conversationId,
539
+ timestamp: new Date().toISOString(),
540
+ });
541
+
542
+ const loopbackRequest = LoopbackHttpRequestV1Schema.parse({
543
+ schemaVersion: 1,
544
+ requestId: browserRequest.requestId,
545
+ authToken,
546
+ action: browserRequest.action,
547
+ projectId: browserRequest.projectId,
548
+ pluginId: browserRequest.pluginId,
549
+ operationId: browserRequest.operationId,
550
+ payload: browserRequest.payload,
551
+ idempotencyKey: createIdempotencyKey(idempotencyValue),
552
+ });
553
+ const sent: SentRequest = {
554
+ requestId: loopbackRequest.requestId,
555
+ idempotencyKey: loopbackRequest.idempotencyKey as string,
556
+ projectId: loopbackRequest.projectId,
557
+ };
558
+
559
+ // 5. Send to the validated loopback daemon only. No redirects: a 3xx must never replay the token.
560
+ activeRequests.add(sent.requestId);
561
+ try {
562
+ let httpResponse: Response;
563
+ try {
564
+ httpResponse = await fetch(`${daemonUrl}/v1/dispatch`, {
565
+ method: 'POST',
566
+ headers: { 'Content-Type': 'application/json' },
567
+ body: JSON.stringify(loopbackRequest),
568
+ redirect: 'error',
569
+ credentials: 'omit',
570
+ cache: 'no-store',
571
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
572
+ });
573
+ } catch (err: unknown) {
574
+ const timedOut = err instanceof Error && err.name === 'TimeoutError';
575
+ return failure('TRANSPORT_ERROR', 'Daemon unreachable or request failed', {
576
+ errorCode: timedOut ? 'TIMEOUT' : 'OFFLINE_OR_UNAVAILABLE_SERVICE',
577
+ requestId: sent.requestId,
578
+ idempotencyKey: sent.idempotencyKey,
579
+ });
580
+ }
581
+
582
+ // 6. Parse and strictly correlate the response.
583
+ let parsedBody: unknown;
584
+ try {
585
+ const text = await httpResponse.text();
586
+ if (text.length > MAX_RESPONSE_BYTES) {
587
+ throw new Error('response too large');
588
+ }
589
+ parsedBody = JSON.parse(text);
590
+ } catch {
591
+ return failure('INVALID_JSON_RESPONSE', 'Daemon returned an unusable response body', {
592
+ statusCode: httpResponse.status,
593
+ requestId: sent.requestId,
594
+ idempotencyKey: sent.idempotencyKey,
595
+ });
596
+ }
597
+
598
+ const validated = validateDaemonResponse(httpResponse.status, parsedBody, sent);
599
+ if (validated.kind === 'success') {
600
+ return {
601
+ success: true,
602
+ statusCode: httpResponse.status,
603
+ requestId: sent.requestId,
604
+ idempotencyKey: sent.idempotencyKey,
605
+ runId: validated.runId,
606
+ lifecycleState: validated.lifecycleState,
607
+ outputSummary: validated.outputSummary,
608
+ };
609
+ }
610
+ if (validated.kind === 'rejected') {
611
+ return failure('DAEMON_REJECTED', 'Daemon rejected the request', {
612
+ errorCode: validated.errorCode,
613
+ statusCode: httpResponse.status,
614
+ requestId: sent.requestId,
615
+ idempotencyKey: sent.idempotencyKey,
616
+ });
617
+ }
618
+ return failure('MALFORMED_RESPONSE', `Daemon response failed validation: ${validated.reason}`, {
619
+ statusCode: httpResponse.status,
620
+ requestId: sent.requestId,
621
+ idempotencyKey: sent.idempotencyKey,
622
+ });
623
+ } finally {
624
+ activeRequests.delete(sent.requestId);
625
+ }
626
+ }
627
+
628
+ // ---------------------------------------------------------------------------
629
+ // Read-only fixture evidence (M04) and test-only "Prepare Return"
630
+ // ---------------------------------------------------------------------------
631
+
632
+ const EVIDENCE_PATH = 'reports/m04-evidence.txt';
633
+
634
+ interface ValidatedEvidence {
635
+ requestId: string;
636
+ file: ReturnType<typeof BoundedFileResponseV1Schema.parse>;
637
+ artifacts: Array<ReturnType<typeof ArtifactRecordV1Schema.parse>>;
638
+ selection?: ReturnType<typeof ShipmentSelectionV1Schema.parse>;
639
+ conversationId?: string;
640
+ }
641
+
642
+ /** Last validated evidence per request; in-memory fixture state only. */
643
+ const validatedEvidence = new Map<string, ValidatedEvidence>();
644
+
645
+ async function sha256Hex(text: string): Promise<string> {
646
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
647
+ return Array.from(new Uint8Array(digest))
648
+ .map((b) => b.toString(16).padStart(2, '0'))
649
+ .join('');
650
+ }
651
+
652
+ /** Strictly validates a GET_CONTEXT success body; the worker never trusts daemon-supplied digests. */
653
+ async function validateEvidenceData(
654
+ data: Record<string, unknown>,
655
+ sent: SentRequest,
656
+ relativePath: string
657
+ ): Promise<{ ok: true; evidence: ValidatedEvidence } | { ok: false; reason: string }> {
658
+ if (data.kind !== 'READ_ONLY_FIXTURE_EVIDENCE' || data.readOnly !== true) {
659
+ return { ok: false, reason: 'EVIDENCE_KIND_INVALID' };
660
+ }
661
+ const prov = data.provenance as Record<string, unknown> | undefined;
662
+ if (
663
+ !prov ||
664
+ prov.sourceKind !== 'FIXTURE_IN_MEMORY' ||
665
+ prov.realProjectFile !== false ||
666
+ prov.durableArtifactService !== false ||
667
+ prov.composerCapability !== false ||
668
+ prov.pluginDriverInvoked !== false
669
+ ) {
670
+ return { ok: false, reason: 'PROVENANCE_INVALID' };
671
+ }
672
+ const file = BoundedFileResponseV1Schema.safeParse(data.file);
673
+ if (!file.success) return { ok: false, reason: 'FILE_SCHEMA_INVALID' };
674
+ if (file.data.projectId !== sent.projectId || file.data.relativePath !== relativePath) {
675
+ return { ok: false, reason: 'FILE_IDENTITY_MISMATCH' };
676
+ }
677
+ if (
678
+ file.data.sizeBytes !== new TextEncoder().encode(file.data.content).length ||
679
+ file.data.sha256.toLowerCase() !== (await sha256Hex(file.data.content))
680
+ ) {
681
+ return { ok: false, reason: 'FILE_DIGEST_MISMATCH' };
682
+ }
683
+
684
+ const artifacts: ValidatedEvidence['artifacts'] = [];
685
+ const rawArtifacts = data.artifacts === undefined ? [] : data.artifacts;
686
+ if (!Array.isArray(rawArtifacts)) return { ok: false, reason: 'ARTIFACTS_INVALID' };
687
+ for (const raw of rawArtifacts) {
688
+ const artifact = ArtifactRecordV1Schema.safeParse(raw);
689
+ if (!artifact.success) return { ok: false, reason: 'ARTIFACT_SCHEMA_INVALID' };
690
+ if (
691
+ artifact.data.projectId !== sent.projectId ||
692
+ artifact.data.immutableSnapshotSha256.toLowerCase() !== (await sha256Hex(artifact.data.contentSnapshot))
693
+ ) {
694
+ return { ok: false, reason: 'ARTIFACT_DIGEST_MISMATCH' };
695
+ }
696
+ artifacts.push(artifact.data);
697
+ }
698
+
699
+ let selection: ValidatedEvidence['selection'];
700
+ if (data.selection !== undefined) {
701
+ const parsed = ShipmentSelectionV1Schema.safeParse(data.selection);
702
+ if (!parsed.success) return { ok: false, reason: 'SELECTION_SCHEMA_INVALID' };
703
+ try {
704
+ verifyShipmentProvenance(
705
+ parsed.data,
706
+ new Map(artifacts.map((a) => [a.artifactId as string, a]))
707
+ );
708
+ } catch {
709
+ return { ok: false, reason: 'SELECTION_PROVENANCE_INVALID' };
710
+ }
711
+ if (
712
+ parsed.data.selectedItems.length !== artifacts.length ||
713
+ parsed.data.selectionApprovedByUser !== false
714
+ ) {
715
+ return { ok: false, reason: 'SELECTION_SET_MISMATCH' };
716
+ }
717
+ selection = parsed.data;
718
+ } else if (artifacts.length > 0) {
719
+ return { ok: false, reason: 'SELECTION_MISSING' };
720
+ }
721
+
722
+ const conversationId = typeof data.conversationId === 'string' ? data.conversationId : undefined;
723
+ return {
724
+ ok: true,
725
+ evidence: { requestId: sent.requestId, file: file.data, artifacts, selection, conversationId },
726
+ };
727
+ }
728
+
729
+ async function handleFetchEvidence(msg: Record<string, unknown>): Promise<object> {
730
+ const daemonUrl = canonicalDaemonUrl(msg.daemonUrl);
731
+ if (!daemonUrl) {
732
+ return failure('INVALID_DAEMON_URL', 'Daemon URL must be canonical http://127.0.0.1:<port>');
733
+ }
734
+ const authToken = typeof msg.token === 'string' ? msg.token : '';
735
+ if (authToken.length === 0) {
736
+ return failure('MISSING_TOKEN', 'No authorization token supplied', {
737
+ errorCode: 'MISSING_OR_INVALID_AUTHORIZATION',
738
+ });
739
+ }
740
+ const requestIdValue = optionalId(msg.requestId, 'req.m04-ev-');
741
+ if (typeof requestIdValue !== 'string') return requestIdValue;
742
+
743
+ const relativePath = typeof msg.relativePath === 'string' ? msg.relativePath : EVIDENCE_PATH;
744
+ const maxBytes = typeof msg.maxBytes === 'number' ? msg.maxBytes : 128;
745
+ const maxLines = typeof msg.maxLines === 'number' ? msg.maxLines : 8;
746
+
747
+ const browserRequest = BrowserRequestV1Schema.parse({
748
+ schemaVersion: 1,
749
+ requestId: createBrowserRequestId(requestIdValue),
750
+ action: 'GET_CONTEXT',
751
+ projectId: createProjectId(FIXTURE_PROJECT_ID),
752
+ payload: { relativePath, maxBytes, maxLines },
753
+ conversationId: DEFAULT_CONVERSATION_ID,
754
+ timestamp: new Date().toISOString(),
755
+ });
756
+ const loopbackRequest = LoopbackHttpRequestV1Schema.parse({
757
+ schemaVersion: 1,
758
+ requestId: browserRequest.requestId,
759
+ authToken,
760
+ action: browserRequest.action,
761
+ projectId: browserRequest.projectId,
762
+ payload: browserRequest.payload,
763
+ });
764
+ const sent: SentRequest = {
765
+ requestId: loopbackRequest.requestId,
766
+ idempotencyKey: '',
767
+ projectId: loopbackRequest.projectId,
768
+ };
769
+
770
+ let httpResponse: Response;
771
+ try {
772
+ httpResponse = await fetch(`${daemonUrl}/v1/dispatch`, {
773
+ method: 'POST',
774
+ headers: { 'Content-Type': 'application/json' },
775
+ body: JSON.stringify(loopbackRequest),
776
+ redirect: 'error',
777
+ credentials: 'omit',
778
+ cache: 'no-store',
779
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
780
+ });
781
+ } catch (err: unknown) {
782
+ const timedOut = err instanceof Error && err.name === 'TimeoutError';
783
+ return failure('TRANSPORT_ERROR', 'Daemon unreachable or request failed', {
784
+ errorCode: timedOut ? 'TIMEOUT' : 'OFFLINE_OR_UNAVAILABLE_SERVICE',
785
+ requestId: sent.requestId,
786
+ });
787
+ }
788
+
789
+ let parsedBody: unknown;
790
+ try {
791
+ const text = await httpResponse.text();
792
+ if (text.length > MAX_RESPONSE_BYTES) throw new Error('response too large');
793
+ parsedBody = JSON.parse(text);
794
+ } catch {
795
+ return failure('INVALID_JSON_RESPONSE', 'Daemon returned an unusable response body', {
796
+ statusCode: httpResponse.status,
797
+ requestId: sent.requestId,
798
+ });
799
+ }
800
+
801
+ const envelope = LoopbackHttpResponseV1Schema.safeParse(parsedBody);
802
+ if (!envelope.success) {
803
+ return failure('MALFORMED_RESPONSE', 'Daemon response failed validation: ENVELOPE_SCHEMA_INVALID', {
804
+ statusCode: httpResponse.status,
805
+ requestId: sent.requestId,
806
+ });
807
+ }
808
+ const response = envelope.data;
809
+ if (response.requestId !== sent.requestId || response.statusCode !== httpResponse.status) {
810
+ return failure('MALFORMED_RESPONSE', 'Daemon response failed validation: CORRELATION_MISMATCH', {
811
+ statusCode: httpResponse.status,
812
+ requestId: sent.requestId,
813
+ });
814
+ }
815
+ if (httpResponse.status >= 400) {
816
+ const error = ContractErrorV1Schema.safeParse(response.error);
817
+ if (response.data !== undefined || !error.success || error.data.correlationId !== sent.requestId) {
818
+ return failure('MALFORMED_RESPONSE', 'Daemon response failed validation: ERROR_INVALID', {
819
+ statusCode: httpResponse.status,
820
+ requestId: sent.requestId,
821
+ });
822
+ }
823
+ return failure('DAEMON_REJECTED', 'Daemon rejected the request', {
824
+ errorCode: error.data.errorCode,
825
+ statusCode: httpResponse.status,
826
+ requestId: sent.requestId,
827
+ });
828
+ }
829
+ if (httpResponse.status !== 200 || response.error !== undefined || !response.data) {
830
+ return failure('MALFORMED_RESPONSE', 'Daemon response failed validation: SUCCESS_SHAPE_INVALID', {
831
+ statusCode: httpResponse.status,
832
+ requestId: sent.requestId,
833
+ });
834
+ }
835
+
836
+ const checked = await validateEvidenceData(response.data, sent, relativePath);
837
+ if (!checked.ok) {
838
+ return failure('MALFORMED_RESPONSE', `Daemon response failed validation: ${checked.reason}`, {
839
+ statusCode: httpResponse.status,
840
+ requestId: sent.requestId,
841
+ });
842
+ }
843
+ validatedEvidence.set(sent.requestId, checked.evidence);
844
+ return {
845
+ success: true,
846
+ statusCode: httpResponse.status,
847
+ requestId: sent.requestId,
848
+ file: checked.evidence.file,
849
+ artifactIds: checked.evidence.artifacts.map((a) => a.artifactId),
850
+ hasSelection: checked.evidence.selection !== undefined,
851
+ };
852
+ }
853
+
854
+ /**
855
+ * TEST-ONLY. Builds a ReturnCargoV1 from already-validated evidence after an explicit user click.
856
+ * It performs NO composer insertion, attaches nothing and submits nothing (K12 is not exercised).
857
+ */
858
+ async function handlePrepareReturn(msg: Record<string, unknown>): Promise<object> {
859
+ const requestId = typeof msg.requestId === 'string' ? msg.requestId : '';
860
+ const evidence = validatedEvidence.get(requestId);
861
+ if (!evidence || !evidence.selection || !evidence.conversationId || evidence.artifacts.length === 0) {
862
+ return failure('EVIDENCE_REQUIRED', 'Prepare Return requires previously validated evidence with a selection');
863
+ }
864
+ const selection = evidence.selection;
865
+ const selectedIds = new Set(selection.selectedItems.map((i) => i.artifactId as string));
866
+ const selectedArtifacts = evidence.artifacts.filter((a) => selectedIds.has(a.artifactId as string));
867
+ if (selectedArtifacts.length !== selectedIds.size) {
868
+ return failure('EVIDENCE_REQUIRED', 'Selected artifacts are not all present');
869
+ }
870
+ const approvedSelection = ShipmentSelectionV1Schema.parse({ ...selection, selectionApprovedByUser: true });
871
+ const cargo = ReturnCargoV1Schema.parse({
872
+ schemaVersion: 1,
873
+ shipmentId: createShipmentId(selection.shipmentId),
874
+ runId: createRunId(selection.runId),
875
+ conversationId: evidence.conversationId,
876
+ userApproved: true,
877
+ markdownSnippet: selection.markdownPresentation,
878
+ selectedArtifactIds: selection.selectedItems.map((i) => i.artifactId),
879
+ generatedAt: new Date().toISOString(),
880
+ });
881
+ return {
882
+ success: true,
883
+ requestId,
884
+ cargo,
885
+ selection: approvedSelection,
886
+ artifacts: selectedArtifacts,
887
+ // Prepared cargo is data only; no browser delivery happened.
888
+ deliveryStatus: 'PREPARED_NOT_DELIVERED',
889
+ composerInsertion: 'NOT_PERFORMED',
890
+ submitted: false,
891
+ };
892
+ }