@mycadet/assistant 0.12.11 → 0.13.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 (176) hide show
  1. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  2. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  3. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  4. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  5. package/node_modules/@mycadet/gateway-client/src/gateway-ipc-contracts.ts +0 -20
  6. package/node_modules/@mycadet/service-contracts/src/__tests__/ingress.test.ts +2 -2
  7. package/node_modules/@mycadet/service-contracts/src/ingress.ts +2 -2
  8. package/openapi.yaml +2 -708
  9. package/package.json +2 -3
  10. package/scripts/sync-web-search-catalog.ts +1 -2
  11. package/src/__tests__/cloud-profile-guard.test.ts +2 -2
  12. package/src/__tests__/config-schema.test.ts +6 -38
  13. package/src/__tests__/conversation-queue.test.ts +45 -6
  14. package/src/__tests__/db-readiness-http-gate.test.ts +0 -6
  15. package/src/__tests__/persist-onboarding-artifacts.test.ts +0 -1
  16. package/src/__tests__/persona-resolver.test.ts +0 -51
  17. package/src/__tests__/provider-cloud-proxy-integration.test.ts +2 -110
  18. package/src/__tests__/run-due-schedules.test.ts +0 -4
  19. package/src/__tests__/schedule-store.test.ts +0 -12
  20. package/src/__tests__/stt-stream-session.test.ts +4 -4
  21. package/src/__tests__/telephony-tts-guard.test.ts +2 -50
  22. package/src/__tests__/voice-config-update.test.ts +12 -167
  23. package/src/__tests__/web-search-catalog-parity.test.ts +0 -2
  24. package/src/__tests__/workspace-migration-130-speech-mode-to-provider.test.ts +9 -7
  25. package/src/__tests__/workspace-migration-132-web-search-mode-to-provider.test.ts +6 -6
  26. package/src/calls/__tests__/voice-session-bridge.test.ts +1 -4
  27. package/src/calls/resolve-call-tts-provider.ts +6 -25
  28. package/src/calls/telephony-credential-preflight.ts +0 -10
  29. package/src/calls/telephony-tts-capability.ts +1 -17
  30. package/src/cli/commands/tts.ts +1 -2
  31. package/src/cli/index.help.ts +0 -2
  32. package/src/cli/program.ts +0 -2
  33. package/src/config/bundled-skills/settings/tools/voice-config-update.ts +4 -42
  34. package/src/config/schemas/__tests__/stt.test.ts +10 -14
  35. package/src/config/schemas/services.ts +5 -6
  36. package/src/config/schemas/stt.ts +1 -3
  37. package/src/config/schemas/tts.ts +1 -30
  38. package/src/daemon/daemon-readiness.ts +4 -29
  39. package/src/daemon/lifecycle.ts +0 -31
  40. package/src/daemon/providers-setup.ts +0 -8
  41. package/src/heartbeat/__tests__/heartbeat-service.test.ts +0 -1
  42. package/src/heartbeat/heartbeat-service.ts +1 -66
  43. package/src/ipc/__tests__/db-readiness-ipc-gate.test.ts +1 -9
  44. package/src/live-voice/__tests__/live-voice-credential-preflight.test.ts +0 -44
  45. package/src/live-voice/__tests__/live-voice-flux-turn-end.test.ts +4 -6
  46. package/src/live-voice/__tests__/live-voice-stt.test.ts +1 -1
  47. package/src/live-voice/live-voice-credential-preflight.ts +9 -33
  48. package/src/live-voice/live-voice-session.ts +10 -6
  49. package/src/live-voice/live-voice-tts.ts +1 -8
  50. package/src/plugins/defaults/memory/worker.ts +3 -3
  51. package/src/prompts/persona-resolver.ts +0 -35
  52. package/src/providers/__tests__/search-provider-catalog.test.ts +5 -8
  53. package/src/providers/__tests__/voice-error-copy.test.ts +9 -10
  54. package/src/providers/search-provider-catalog.ts +7 -39
  55. package/src/providers/speech-to-text/__tests__/provider-catalog.test.ts +3 -47
  56. package/src/providers/speech-to-text/__tests__/resolve.test.ts +6 -372
  57. package/src/providers/speech-to-text/provider-catalog.ts +2 -73
  58. package/src/providers/speech-to-text/resolve.ts +3 -120
  59. package/src/runtime/http-router-types.ts +1 -3
  60. package/src/runtime/http-server.ts +1 -1
  61. package/src/runtime/routes/__tests__/tts-routes.test.ts +2 -6
  62. package/src/runtime/routes/inbound-stages/transcribe-audio.test.ts +7 -7
  63. package/src/runtime/routes/index.ts +0 -4
  64. package/src/runtime/routes/live-voice-routes.test.ts +4 -11
  65. package/src/runtime/routes/live-voice-routes.ts +8 -11
  66. package/src/runtime/routes/secret-routes.ts +0 -6
  67. package/src/runtime/routes/tts-routes.ts +0 -38
  68. package/src/schedule/__tests__/plugin-schedule-reconciler.test.ts +1 -7
  69. package/src/schedule/__tests__/worker-mcp-readiness.test.ts +0 -4
  70. package/src/schedule/schedule-store.ts +0 -7
  71. package/src/schedule/scheduler.ts +0 -5
  72. package/src/schedule/worker.ts +1 -1
  73. package/src/stt/__tests__/daemon-batch-transcriber.test.ts +2 -10
  74. package/src/stt/daemon-batch-transcriber.ts +4 -38
  75. package/src/stt/types.ts +1 -9
  76. package/src/tools/network/__tests__/web-search.test.ts +3 -250
  77. package/src/tools/network/web-search.ts +4 -165
  78. package/src/tts/__tests__/provider-resolution.test.ts +0 -5
  79. package/src/tts/provider-catalog.ts +0 -4
  80. package/src/tts/types.ts +0 -1
  81. package/src/__tests__/cloud-speech-defaults.test.ts +0 -330
  82. package/src/__tests__/migration-cross-version-compatibility.test.ts +0 -1708
  83. package/src/__tests__/migration-export-http.test.ts +0 -557
  84. package/src/__tests__/migration-export-streaming.test.ts +0 -350
  85. package/src/__tests__/migration-export-to-gcs.test.ts +0 -706
  86. package/src/__tests__/migration-import-commit-http.test.ts +0 -1176
  87. package/src/__tests__/migration-import-from-gcs.test.ts +0 -534
  88. package/src/__tests__/migration-import-from-path.test.ts +0 -324
  89. package/src/__tests__/migration-import-from-url.test.ts +0 -588
  90. package/src/__tests__/migration-import-preflight-http.test.ts +0 -739
  91. package/src/__tests__/migration-jobs-status.test.ts +0 -139
  92. package/src/__tests__/migration-parity-persistence.test.ts +0 -1891
  93. package/src/__tests__/migration-transport.test.ts +0 -1089
  94. package/src/__tests__/migration-validate-http.test.ts +0 -634
  95. package/src/__tests__/migration-wizard.test.ts +0 -1395
  96. package/src/__tests__/rebind-secrets-screen.test.ts +0 -876
  97. package/src/__tests__/sanitize-config-for-transfer.test.ts +0 -259
  98. package/src/__tests__/transfer-progress-screen.test.ts +0 -1217
  99. package/src/__tests__/validation-results-screen.test.ts +0 -1130
  100. package/src/__tests__/vbundle-pax-and-symlink.test.ts +0 -147
  101. package/src/background-wake/background-wake-routes.test.ts +0 -906
  102. package/src/background-wake/cloud-client.test.ts +0 -328
  103. package/src/background-wake/cloud-client.ts +0 -196
  104. package/src/background-wake/next-wake.test.ts +0 -335
  105. package/src/background-wake/next-wake.ts +0 -188
  106. package/src/background-wake/publisher.ts +0 -93
  107. package/src/background-wake/wake-intent-hooks.test.ts +0 -234
  108. package/src/cli/commands/__tests__/backup.test.ts +0 -363
  109. package/src/cli/commands/backup.help.ts +0 -180
  110. package/src/cli/commands/backup.ts +0 -398
  111. package/src/cloud/cloud-speech.test.ts +0 -335
  112. package/src/cloud/cloud-speech.ts +0 -300
  113. package/src/config/cloud-speech-defaults.ts +0 -300
  114. package/src/config/sanitize-for-transfer.ts +0 -111
  115. package/src/live-voice/__tests__/live-voice-cloud-speech-fallback.test.ts +0 -250
  116. package/src/providers/speech-to-text/__tests__/cadet-cloud-realtime.test.ts +0 -457
  117. package/src/providers/speech-to-text/__tests__/cadet-cloud.test.ts +0 -271
  118. package/src/providers/speech-to-text/__tests__/cadet-speech-relay-connection.test.ts +0 -126
  119. package/src/providers/speech-to-text/cadet-cloud-flux-realtime.ts +0 -309
  120. package/src/providers/speech-to-text/cadet-cloud-realtime.ts +0 -315
  121. package/src/providers/speech-to-text/cadet-cloud.ts +0 -108
  122. package/src/providers/speech-to-text/cadet-speech-relay-connection.ts +0 -176
  123. package/src/runtime/migrations/__tests__/gcs-signed-url.test.ts +0 -254
  124. package/src/runtime/migrations/__tests__/job-registry.test.ts +0 -346
  125. package/src/runtime/migrations/__tests__/origin-mode.test.ts +0 -62
  126. package/src/runtime/migrations/__tests__/rebind-secrets-credentials.test.ts +0 -184
  127. package/src/runtime/migrations/__tests__/staged-import-path.test.ts +0 -110
  128. package/src/runtime/migrations/__tests__/v1-test-helpers.ts +0 -112
  129. package/src/runtime/migrations/__tests__/vbundle-builder-credentials.test.ts +0 -285
  130. package/src/runtime/migrations/__tests__/vbundle-builder-fd-leak.test.ts +0 -126
  131. package/src/runtime/migrations/__tests__/vbundle-builder-v1-shape.test.ts +0 -253
  132. package/src/runtime/migrations/__tests__/vbundle-import-credentials.test.ts +0 -208
  133. package/src/runtime/migrations/__tests__/vbundle-import-parity.test.ts +0 -485
  134. package/src/runtime/migrations/__tests__/vbundle-import-policy.test.ts +0 -349
  135. package/src/runtime/migrations/__tests__/vbundle-import-version-compat.test.ts +0 -196
  136. package/src/runtime/migrations/__tests__/vbundle-legacy-user-md.test.ts +0 -551
  137. package/src/runtime/migrations/__tests__/vbundle-metadata-merge-integration.test.ts +0 -428
  138. package/src/runtime/migrations/__tests__/vbundle-metadata-merge.test.ts +0 -220
  139. package/src/runtime/migrations/__tests__/vbundle-streaming-importer.test.ts +0 -1823
  140. package/src/runtime/migrations/__tests__/vbundle-streaming-validator.test.ts +0 -598
  141. package/src/runtime/migrations/__tests__/vbundle-symlink-importer.test.ts +0 -463
  142. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming-importer.test.ts +0 -538
  143. package/src/runtime/migrations/__tests__/vbundle-symlink-streaming.test.ts +0 -515
  144. package/src/runtime/migrations/__tests__/vbundle-symlink-tar.test.ts +0 -453
  145. package/src/runtime/migrations/__tests__/vbundle-symlink-walker.test.ts +0 -319
  146. package/src/runtime/migrations/__tests__/vbundle-tar-stream.test.ts +0 -240
  147. package/src/runtime/migrations/__tests__/vbundle-validator-v1-schema.test.ts +0 -473
  148. package/src/runtime/migrations/gcs-signed-url.ts +0 -190
  149. package/src/runtime/migrations/job-registry.ts +0 -297
  150. package/src/runtime/migrations/migration-transport.ts +0 -612
  151. package/src/runtime/migrations/migration-wizard.ts +0 -747
  152. package/src/runtime/migrations/origin-mode.ts +0 -42
  153. package/src/runtime/migrations/rebind-secrets-screen.ts +0 -412
  154. package/src/runtime/migrations/staged-import-path.ts +0 -116
  155. package/src/runtime/migrations/transfer-progress-screen.ts +0 -323
  156. package/src/runtime/migrations/validation-results-screen.ts +0 -469
  157. package/src/runtime/migrations/vbundle-builder.ts +0 -1382
  158. package/src/runtime/migrations/vbundle-import-analyzer.ts +0 -405
  159. package/src/runtime/migrations/vbundle-import-policy.ts +0 -241
  160. package/src/runtime/migrations/vbundle-importer.ts +0 -826
  161. package/src/runtime/migrations/vbundle-metadata-merge.ts +0 -113
  162. package/src/runtime/migrations/vbundle-streaming-importer.ts +0 -2844
  163. package/src/runtime/migrations/vbundle-streaming-validator.ts +0 -426
  164. package/src/runtime/migrations/vbundle-tar-stream.ts +0 -244
  165. package/src/runtime/migrations/vbundle-validator.ts +0 -724
  166. package/src/runtime/routes/__tests__/migration-cadet-metadata-reconcile.test.ts +0 -227
  167. package/src/runtime/routes/__tests__/migration-export-secrets-redacted.test.ts +0 -54
  168. package/src/runtime/routes/__tests__/migration-import-allowed-hosts-env.test.ts +0 -70
  169. package/src/runtime/routes/__tests__/migration-import-credential-filter.test.ts +0 -257
  170. package/src/runtime/routes/background-wake-routes.ts +0 -387
  171. package/src/runtime/routes/migration-routes.ts +0 -2584
  172. package/src/tools/network/__tests__/cloud-search-proxy.test.ts +0 -282
  173. package/src/tools/network/cloud-search-proxy.ts +0 -211
  174. package/src/tts/__tests__/cadet-provider.test.ts +0 -253
  175. package/src/tts/providers/cadet-provider.ts +0 -244
  176. package/src/types/tar-stream.d.ts +0 -66
@@ -1,739 +0,0 @@
1
- /**
2
- * HTTP-layer integration tests for POST /v1/migrations/import-preflight.
3
- *
4
- * Tests cover:
5
- * - Success: valid .vbundle returns dry-run report with file analysis
6
- * - Validation failures: invalid bundle returns can_import: false with validation errors
7
- * - Request errors: empty body, invalid multipart
8
- * - File comparison: detects creates, overwrites, and unchanged files
9
- * - Conflicts: unknown archive paths are flagged
10
- * - Auth: route policy enforcement (settings.write scope required)
11
- * - Integration: existing routes are unaffected by the new endpoint
12
- */
13
- import { createHash } from "node:crypto";
14
- import { mkdirSync, writeFileSync } from "node:fs";
15
- import { join } from "node:path";
16
- import { gzipSync } from "node:zlib";
17
- import { beforeAll, describe, expect, test } from "bun:test";
18
-
19
- /** Convert a Uint8Array to an ArrayBuffer for BodyInit compatibility. */
20
- function toArrayBuffer(data: Uint8Array): ArrayBuffer {
21
- return data.buffer.slice(
22
- data.byteOffset,
23
- data.byteOffset + data.byteLength,
24
- ) as ArrayBuffer;
25
- }
26
-
27
- const testDir = process.env.CADET_WORKSPACE_DIR!;
28
- const testDbDir = join(testDir, "data", "db");
29
- const testDbPath = join(testDbDir, "assistant.db");
30
- const testConfigPath = join(testDir, "config.json");
31
-
32
- process.env.DISABLE_HTTP_AUTH = "true";
33
-
34
- import {
35
- analyzeImport,
36
- DefaultPathResolver,
37
- } from "../runtime/migrations/vbundle-import-analyzer.js";
38
- import type { ManifestType } from "../runtime/migrations/vbundle-validator.js";
39
- import { handleMigrationImportPreflight } from "../runtime/routes/migration-routes.js";
40
- import { callHandler } from "./helpers/call-route-handler.js";
41
-
42
- /** Build a v1-compliant manifest with the given file entries. */
43
- function v1Manifest(
44
- contents: Array<{ path: string; sha256: string; size_bytes: number }>,
45
- ): ManifestType {
46
- return {
47
- schema_version: 1,
48
- bundle_id: "00000000-0000-4000-8000-000000000000",
49
- created_at: new Date().toISOString(),
50
- assistant: { id: "self", name: "Test", runtime_version: "0.0.0-test" },
51
- origin: { mode: "self-hosted-local" },
52
- compatibility: {
53
- min_runtime_version: "0.0.0-test",
54
- max_runtime_version: null,
55
- },
56
- contents,
57
- checksum:
58
- "0000000000000000000000000000000000000000000000000000000000000000",
59
- secrets_redacted: false,
60
- export_options: {
61
- include_logs: false,
62
- include_browser_state: false,
63
- include_memory_vectors: false,
64
- },
65
- } as ManifestType;
66
- }
67
-
68
- // Test fixture data
69
- const EXISTING_DB_DATA = new Uint8Array([
70
- 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74,
71
- 0x20, 0x33, 0x00,
72
- ]);
73
- const EXISTING_CONFIG = { provider: "anthropic", model: "test-model" };
74
-
75
- beforeAll(() => {
76
- mkdirSync(testDbDir, { recursive: true });
77
- writeFileSync(testDbPath, EXISTING_DB_DATA);
78
- writeFileSync(testConfigPath, JSON.stringify(EXISTING_CONFIG, null, 2));
79
- });
80
-
81
- // ---------------------------------------------------------------------------
82
- // Tar archive builder helpers (mirrors validate test)
83
- // ---------------------------------------------------------------------------
84
-
85
- const BLOCK_SIZE = 512;
86
-
87
- function padToBlock(data: Uint8Array): Uint8Array {
88
- const remainder = data.length % BLOCK_SIZE;
89
- if (remainder === 0) {
90
- return data;
91
- }
92
- const padded = new Uint8Array(data.length + (BLOCK_SIZE - remainder));
93
- padded.set(data);
94
- return padded;
95
- }
96
-
97
- function writeOctal(
98
- buf: Uint8Array,
99
- offset: number,
100
- length: number,
101
- value: number,
102
- ): void {
103
- const str = value.toString(8).padStart(length - 1, "0");
104
- for (let i = 0; i < str.length; i++) {
105
- buf[offset + i] = str.charCodeAt(i);
106
- }
107
- buf[offset + length - 1] = 0;
108
- }
109
-
110
- function computeHeaderChecksum(header: Uint8Array): number {
111
- let sum = 0;
112
- for (let i = 0; i < 512; i++) {
113
- if (i >= 148 && i < 156) {
114
- sum += 0x20;
115
- } else {
116
- sum += header[i];
117
- }
118
- }
119
- return sum;
120
- }
121
-
122
- function createTarEntry(name: string, data: Uint8Array): Uint8Array {
123
- const header = new Uint8Array(BLOCK_SIZE);
124
- const encoder = new TextEncoder();
125
-
126
- const nameBytes = encoder.encode(name);
127
- header.set(nameBytes.subarray(0, 100), 0);
128
-
129
- writeOctal(header, 100, 8, 0o644);
130
- writeOctal(header, 108, 8, 0);
131
- writeOctal(header, 116, 8, 0);
132
- writeOctal(header, 124, 12, data.length);
133
- writeOctal(header, 136, 12, Math.floor(Date.now() / 1000));
134
- header[156] = "0".charCodeAt(0);
135
-
136
- const magic = encoder.encode("ustar\0");
137
- header.set(magic, 257);
138
- header[263] = "0".charCodeAt(0);
139
- header[264] = "0".charCodeAt(0);
140
-
141
- const checksum = computeHeaderChecksum(header);
142
- writeOctal(header, 148, 7, checksum);
143
- header[155] = 0x20;
144
-
145
- const paddedData = padToBlock(data);
146
- const result = new Uint8Array(header.length + paddedData.length);
147
- result.set(header, 0);
148
- result.set(paddedData, header.length);
149
- return result;
150
- }
151
-
152
- function createTarArchive(
153
- entries: Array<{ name: string; data: Uint8Array }>,
154
- ): Uint8Array {
155
- const parts: Uint8Array[] = [];
156
- for (const entry of entries) {
157
- parts.push(createTarEntry(entry.name, entry.data));
158
- }
159
- parts.push(new Uint8Array(BLOCK_SIZE * 2));
160
-
161
- const totalLength = parts.reduce((sum, p) => sum + p.length, 0);
162
- const result = new Uint8Array(totalLength);
163
- let offset = 0;
164
- for (const part of parts) {
165
- result.set(part, offset);
166
- offset += part.length;
167
- }
168
- return result;
169
- }
170
-
171
- function sha256Hex(data: Uint8Array | string): string {
172
- return createHash("sha256").update(data).digest("hex");
173
- }
174
-
175
- function canonicalizeJson(obj: unknown): string {
176
- return JSON.stringify(obj, (_key, value) => {
177
- if (value && typeof value === "object" && !Array.isArray(value)) {
178
- const sorted: Record<string, unknown> = {};
179
- for (const k of Object.keys(value as Record<string, unknown>).sort()) {
180
- sorted[k] = (value as Record<string, unknown>)[k];
181
- }
182
- return sorted;
183
- }
184
- return value;
185
- });
186
- }
187
-
188
- interface VBundleFile {
189
- path: string;
190
- data: Uint8Array;
191
- }
192
-
193
- function createValidVBundle(files?: VBundleFile[]): Uint8Array {
194
- const dbData = new Uint8Array([0x53, 0x51, 0x4c, 0x69, 0x74, 0x65]);
195
- const bundleFiles = files ?? [{ path: "data/db/assistant.db", data: dbData }];
196
-
197
- const contents = bundleFiles.map((f) => ({
198
- path: f.path,
199
- sha256: sha256Hex(f.data),
200
- size_bytes: f.data.length,
201
- }));
202
-
203
- const manifestWithEmptyChecksum = {
204
- schema_version: 1,
205
- bundle_id: "00000000-0000-4000-8000-000000000000",
206
- created_at: new Date().toISOString(),
207
- assistant: { id: "self", name: "Test", runtime_version: "0.0.0-test" },
208
- origin: { mode: "self-hosted-local" },
209
- compatibility: {
210
- min_runtime_version: "0.0.0-test",
211
- max_runtime_version: null,
212
- },
213
- contents,
214
- checksum: "",
215
- secrets_redacted: false,
216
- export_options: {
217
- include_logs: false,
218
- include_browser_state: false,
219
- include_memory_vectors: false,
220
- },
221
- };
222
-
223
- const checksum = sha256Hex(canonicalizeJson(manifestWithEmptyChecksum));
224
- const manifest = { ...manifestWithEmptyChecksum, checksum };
225
- const manifestData = new TextEncoder().encode(JSON.stringify(manifest));
226
-
227
- const tarEntries = [
228
- { name: "manifest.json", data: manifestData },
229
- ...bundleFiles.map((f) => ({ name: f.path, data: f.data })),
230
- ];
231
-
232
- const tar = createTarArchive(tarEntries);
233
- return gzipSync(tar);
234
- }
235
-
236
- // ---------------------------------------------------------------------------
237
- // Import dry-run report types (for type-safe assertions)
238
- // ---------------------------------------------------------------------------
239
-
240
- interface ImportDryRunResponse {
241
- can_import: boolean;
242
- summary: {
243
- total_files: number;
244
- files_to_create: number;
245
- files_to_overwrite: number;
246
- files_unchanged: number;
247
- files_to_skip: number;
248
- };
249
- files: Array<{
250
- path: string;
251
- action: string;
252
- bundle_size: number;
253
- current_size: number | null;
254
- bundle_sha256: string;
255
- current_sha256: string | null;
256
- }>;
257
- conflicts: Array<{
258
- code: string;
259
- message: string;
260
- path?: string;
261
- }>;
262
- manifest: Record<string, unknown>;
263
- }
264
-
265
- interface ImportValidationFailureResponse {
266
- can_import: boolean;
267
- validation: {
268
- is_valid: boolean;
269
- errors: Array<{ code: string; message: string; path?: string }>;
270
- };
271
- }
272
-
273
- // ---------------------------------------------------------------------------
274
- // HTTP handler tests: success cases
275
- // ---------------------------------------------------------------------------
276
-
277
- describe("handleMigrationImportPreflight", () => {
278
- test("POST with valid vbundle returns 200 with dry-run report", async () => {
279
- const vbundle = createValidVBundle();
280
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
281
- method: "POST",
282
- headers: { "Content-Type": "application/octet-stream" },
283
- body: toArrayBuffer(vbundle),
284
- });
285
-
286
- const res = await callHandler(handleMigrationImportPreflight, req);
287
- const body = (await res.json()) as ImportDryRunResponse;
288
-
289
- expect(res.status).toBe(200);
290
- expect(body.can_import).toBe(true);
291
- expect(body.summary).toBeDefined();
292
- expect(body.summary.total_files).toBeGreaterThan(0);
293
- expect(body.files).toBeDefined();
294
- expect(body.files.length).toBeGreaterThan(0);
295
- expect(body.manifest).toBeDefined();
296
- });
297
-
298
- test("report summary counts match file details", async () => {
299
- // Bundle with a db file different from disk (overwrite) and config (overwrite)
300
- const newDbData = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
301
- const newConfigData = new TextEncoder().encode('{"provider":"openai"}');
302
- const vbundle = createValidVBundle([
303
- { path: "data/db/assistant.db", data: newDbData },
304
- { path: "config/settings.json", data: newConfigData },
305
- ]);
306
-
307
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
308
- method: "POST",
309
- headers: { "Content-Type": "application/octet-stream" },
310
- body: toArrayBuffer(vbundle),
311
- });
312
-
313
- const res = await callHandler(handleMigrationImportPreflight, req);
314
- const body = (await res.json()) as ImportDryRunResponse;
315
-
316
- expect(body.can_import).toBe(true);
317
- expect(body.summary.total_files).toBe(body.files.length);
318
-
319
- const creates = body.files.filter((f) => f.action === "create").length;
320
- const overwrites = body.files.filter(
321
- (f) => f.action === "overwrite",
322
- ).length;
323
- const unchanged = body.files.filter((f) => f.action === "unchanged").length;
324
- const skips = body.files.filter((f) => f.action === "skip").length;
325
-
326
- expect(body.summary.files_to_create).toBe(creates);
327
- expect(body.summary.files_to_overwrite).toBe(overwrites);
328
- expect(body.summary.files_unchanged).toBe(unchanged);
329
- expect(body.summary.files_to_skip).toBe(skips);
330
- });
331
-
332
- test("detects overwrite when bundle db differs from disk", async () => {
333
- const differentDbData = new Uint8Array([0xca, 0xfe, 0xba, 0xbe]);
334
- const vbundle = createValidVBundle([
335
- { path: "data/db/assistant.db", data: differentDbData },
336
- ]);
337
-
338
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
339
- method: "POST",
340
- headers: { "Content-Type": "application/octet-stream" },
341
- body: toArrayBuffer(vbundle),
342
- });
343
-
344
- const res = await callHandler(handleMigrationImportPreflight, req);
345
- const body = (await res.json()) as ImportDryRunResponse;
346
-
347
- expect(body.can_import).toBe(true);
348
- const dbFile = body.files.find((f) => f.path === "data/db/assistant.db");
349
- expect(dbFile).toBeDefined();
350
- expect(dbFile!.action).toBe("overwrite");
351
- expect(dbFile!.bundle_size).toBe(differentDbData.length);
352
- expect(dbFile!.current_size).toBe(EXISTING_DB_DATA.length);
353
- expect(dbFile!.bundle_sha256).toBe(sha256Hex(differentDbData));
354
- expect(dbFile!.current_sha256).toBe(sha256Hex(EXISTING_DB_DATA));
355
- });
356
-
357
- test("detects unchanged when bundle db matches disk", async () => {
358
- // Use the same data as what's on disk
359
- const vbundle = createValidVBundle([
360
- { path: "data/db/assistant.db", data: EXISTING_DB_DATA },
361
- ]);
362
-
363
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
364
- method: "POST",
365
- headers: { "Content-Type": "application/octet-stream" },
366
- body: toArrayBuffer(vbundle),
367
- });
368
-
369
- const res = await callHandler(handleMigrationImportPreflight, req);
370
- const body = (await res.json()) as ImportDryRunResponse;
371
-
372
- expect(body.can_import).toBe(true);
373
- const dbFile = body.files.find((f) => f.path === "data/db/assistant.db");
374
- expect(dbFile).toBeDefined();
375
- expect(dbFile!.action).toBe("unchanged");
376
- });
377
-
378
- test("includes manifest in response", async () => {
379
- const vbundle = createValidVBundle();
380
-
381
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
382
- method: "POST",
383
- headers: { "Content-Type": "application/octet-stream" },
384
- body: toArrayBuffer(vbundle),
385
- });
386
-
387
- const res = await callHandler(handleMigrationImportPreflight, req);
388
- const body = (await res.json()) as ImportDryRunResponse;
389
-
390
- expect(body.manifest).toBeDefined();
391
- expect(body.manifest.schema_version).toBe(1);
392
- expect(body.manifest.bundle_id).toBeDefined();
393
- expect(body.manifest.contents).toBeDefined();
394
- });
395
-
396
- test("POST with multipart form data works", async () => {
397
- const vbundle = createValidVBundle();
398
- const formData = new FormData();
399
- formData.append("file", new Blob([toArrayBuffer(vbundle)]), "test.vbundle");
400
-
401
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
402
- method: "POST",
403
- body: formData,
404
- });
405
-
406
- const res = await callHandler(handleMigrationImportPreflight, req);
407
- const body = (await res.json()) as ImportDryRunResponse;
408
-
409
- expect(res.status).toBe(200);
410
- expect(body.can_import).toBe(true);
411
- });
412
- });
413
-
414
- // ---------------------------------------------------------------------------
415
- // HTTP handler tests: validation failure cases
416
- // ---------------------------------------------------------------------------
417
-
418
- describe("handleMigrationImportPreflight — validation failures", () => {
419
- test("invalid gzip returns can_import: false with validation errors", async () => {
420
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
421
- method: "POST",
422
- headers: { "Content-Type": "application/octet-stream" },
423
- body: toArrayBuffer(new Uint8Array([0xde, 0xad, 0xbe, 0xef])),
424
- });
425
-
426
- const res = await callHandler(handleMigrationImportPreflight, req);
427
- const body = (await res.json()) as ImportValidationFailureResponse;
428
-
429
- expect(res.status).toBe(200);
430
- expect(body.can_import).toBe(false);
431
- expect(body.validation).toBeDefined();
432
- expect(body.validation.is_valid).toBe(false);
433
- expect(body.validation.errors.length).toBeGreaterThan(0);
434
- expect(body.validation.errors[0].code).toBe("INVALID_GZIP");
435
- });
436
-
437
- test("missing manifest returns can_import: false", async () => {
438
- const dbData = new Uint8Array([0x53, 0x51, 0x4c, 0x69, 0x74, 0x65]);
439
- const tar = createTarArchive([
440
- { name: "data/db/assistant.db", data: dbData },
441
- ]);
442
- const vbundle = gzipSync(tar);
443
-
444
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
445
- method: "POST",
446
- headers: { "Content-Type": "application/octet-stream" },
447
- body: toArrayBuffer(vbundle),
448
- });
449
-
450
- const res = await callHandler(handleMigrationImportPreflight, req);
451
- const body = (await res.json()) as ImportValidationFailureResponse;
452
-
453
- expect(res.status).toBe(200);
454
- expect(body.can_import).toBe(false);
455
- expect(body.validation.is_valid).toBe(false);
456
- });
457
-
458
- test("empty body returns 400", async () => {
459
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
460
- method: "POST",
461
- headers: { "Content-Type": "application/octet-stream" },
462
- body: toArrayBuffer(new Uint8Array(0)),
463
- });
464
-
465
- const res = await callHandler(handleMigrationImportPreflight, req);
466
- const body = (await res.json()) as {
467
- error: { code: string; message: string };
468
- };
469
-
470
- expect(res.status).toBe(400);
471
- expect(body.error.code).toBe("BAD_REQUEST");
472
- });
473
-
474
- test("multipart without file field returns 400", async () => {
475
- const formData = new FormData();
476
- formData.append("notfile", "some text");
477
-
478
- const req = new Request("http://localhost/v1/migrations/import-preflight", {
479
- method: "POST",
480
- body: formData,
481
- });
482
-
483
- const res = await callHandler(handleMigrationImportPreflight, req);
484
- const body = (await res.json()) as { error: { code: string } };
485
-
486
- expect(res.status).toBe(400);
487
- expect(body.error.code).toBe("BAD_REQUEST");
488
- });
489
- });
490
-
491
- // ---------------------------------------------------------------------------
492
- // Import analyzer unit tests
493
- // ---------------------------------------------------------------------------
494
-
495
- describe("analyzeImport", () => {
496
- test("detects create when file does not exist on disk", () => {
497
- const resolver = new DefaultPathResolver(
498
- join(testDir, "nonexistent-workspace"),
499
- );
500
-
501
- const report = analyzeImport({
502
- manifest: v1Manifest([
503
- {
504
- path: "data/db/assistant.db",
505
- sha256: sha256Hex(new Uint8Array([1, 2, 3])),
506
- size_bytes: 3,
507
- },
508
- ]),
509
- pathResolver: resolver,
510
- });
511
-
512
- expect(report.can_import).toBe(true);
513
- expect(report.files[0].action).toBe("create");
514
- expect(report.files[0].current_size).toBeNull();
515
- expect(report.files[0].current_sha256).toBeNull();
516
- expect(report.summary.files_to_create).toBe(1);
517
- });
518
-
519
- test("detects unchanged when file on disk matches bundle", () => {
520
- const resolver = new DefaultPathResolver(testDir);
521
-
522
- const report = analyzeImport({
523
- manifest: v1Manifest([
524
- {
525
- path: "data/db/assistant.db",
526
- sha256: sha256Hex(EXISTING_DB_DATA),
527
- size_bytes: EXISTING_DB_DATA.length,
528
- },
529
- ]),
530
- pathResolver: resolver,
531
- });
532
-
533
- expect(report.can_import).toBe(true);
534
- expect(report.files[0].action).toBe("unchanged");
535
- expect(report.summary.files_unchanged).toBe(1);
536
- });
537
-
538
- test("detects overwrite when file on disk differs from bundle", () => {
539
- const resolver = new DefaultPathResolver(testDir);
540
-
541
- const report = analyzeImport({
542
- manifest: v1Manifest([
543
- {
544
- path: "data/db/assistant.db",
545
- sha256: sha256Hex(new Uint8Array([0xca, 0xfe])),
546
- size_bytes: 2,
547
- },
548
- ]),
549
- pathResolver: resolver,
550
- });
551
-
552
- expect(report.can_import).toBe(true);
553
- expect(report.files[0].action).toBe("overwrite");
554
- expect(report.files[0].current_size).toBe(EXISTING_DB_DATA.length);
555
- expect(report.summary.files_to_overwrite).toBe(1);
556
- });
557
-
558
- test("flags unknown archive paths as conflicts with skip action", () => {
559
- const resolver = new DefaultPathResolver(testDir);
560
-
561
- const report = analyzeImport({
562
- manifest: v1Manifest([
563
- {
564
- path: "data/db/assistant.db",
565
- sha256: sha256Hex(EXISTING_DB_DATA),
566
- size_bytes: EXISTING_DB_DATA.length,
567
- },
568
- {
569
- path: "unknown/extra-file.bin",
570
- sha256: sha256Hex(new Uint8Array([1])),
571
- size_bytes: 1,
572
- },
573
- ]),
574
- pathResolver: resolver,
575
- });
576
-
577
- expect(report.can_import).toBe(false);
578
- expect(report.conflicts.length).toBe(1);
579
- expect(report.conflicts[0].code).toBe("UNKNOWN_ARCHIVE_PATH");
580
- expect(report.conflicts[0].path).toBe("unknown/extra-file.bin");
581
-
582
- const unknownFile = report.files.find(
583
- (f) => f.path === "unknown/extra-file.bin",
584
- );
585
- expect(unknownFile).toBeDefined();
586
- expect(unknownFile!.action).toBe("skip");
587
- expect(report.summary.files_to_skip).toBe(1);
588
- expect(report.summary.files_to_create).toBe(0);
589
- });
590
-
591
- test("includes manifest in report", () => {
592
- const resolver = new DefaultPathResolver(testDir);
593
- const manifest = v1Manifest([
594
- {
595
- path: "data/db/assistant.db",
596
- sha256: sha256Hex(EXISTING_DB_DATA),
597
- size_bytes: EXISTING_DB_DATA.length,
598
- },
599
- ]);
600
-
601
- const report = analyzeImport({ manifest, pathResolver: resolver });
602
-
603
- expect(report.manifest).toBe(manifest);
604
- expect(report.manifest.schema_version).toBe(1);
605
- expect(report.manifest.assistant.id).toBe("self");
606
- });
607
- });
608
-
609
- // ---------------------------------------------------------------------------
610
- // DefaultPathResolver unit tests
611
- // ---------------------------------------------------------------------------
612
-
613
- const WORKSPACE_DIR = "/home/user/.cadet/workspace";
614
-
615
- describe("DefaultPathResolver", () => {
616
- test("resolves data/db/assistant.db to workspace db path (backward compat)", () => {
617
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
618
- expect(resolver.resolve("data/db/assistant.db")).toBe(
619
- `${WORKSPACE_DIR}/data/db/assistant.db`,
620
- );
621
- });
622
-
623
- test("resolves config/settings.json to workspace config path (backward compat)", () => {
624
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
625
- expect(resolver.resolve("config/settings.json")).toBe(
626
- `${WORKSPACE_DIR}/config.json`,
627
- );
628
- });
629
-
630
- test("returns null for unknown paths", () => {
631
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
632
- expect(resolver.resolve("unknown/path.txt")).toBeNull();
633
- });
634
-
635
- test("resolves valid skills path via backward compat", () => {
636
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
637
- expect(resolver.resolve("skills/my-skill/SKILL.md")).toBe(
638
- `${WORKSPACE_DIR}/skills/my-skill/SKILL.md`,
639
- );
640
- });
641
-
642
- test("resolves workspace/ prefix paths", () => {
643
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
644
- expect(resolver.resolve("workspace/data/db/assistant.db")).toBe(
645
- `${WORKSPACE_DIR}/data/db/assistant.db`,
646
- );
647
- expect(resolver.resolve("workspace/config.json")).toBe(
648
- `${WORKSPACE_DIR}/config.json`,
649
- );
650
- expect(resolver.resolve("workspace/skills/my-skill/SKILL.md")).toBe(
651
- `${WORKSPACE_DIR}/skills/my-skill/SKILL.md`,
652
- );
653
- });
654
-
655
- test("returns null for workspace/ path traversal attempt", () => {
656
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
657
- expect(resolver.resolve("workspace/../../etc/passwd")).toBeNull();
658
- });
659
-
660
- test("returns null for skills path traversal attempt (../../etc/passwd)", () => {
661
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
662
- expect(resolver.resolve("skills/../../etc/passwd")).toBeNull();
663
- });
664
-
665
- test("returns null for skills path traversal attempt (../../../.ssh/authorized_keys)", () => {
666
- const resolver = new DefaultPathResolver(WORKSPACE_DIR);
667
- expect(resolver.resolve("skills/../../../.ssh/authorized_keys")).toBeNull();
668
- });
669
-
670
- test("returns null for skills paths when workspaceDir is not provided", () => {
671
- const resolver = new DefaultPathResolver();
672
- expect(resolver.resolve("skills/my-skill/SKILL.md")).toBeNull();
673
- });
674
- });
675
-
676
- // ---------------------------------------------------------------------------
677
- // Auth policy registration tests
678
- // ---------------------------------------------------------------------------
679
-
680
- describe("route policy registration", () => {
681
- test("migrations/import-preflight policy requires settings.write scope", async () => {
682
- const { ROUTES } = await import("../runtime/routes/index.js");
683
- const policy =
684
- ROUTES.find((r) => r.endpoint === "migrations/import-preflight")
685
- ?.policy ?? null;
686
-
687
- expect(policy).not.toBeNull();
688
- expect(policy?.requiredScopes).toContain("settings.write");
689
- expect(policy?.allowedPrincipalTypes).toContain("actor");
690
- expect(policy?.allowedPrincipalTypes).toContain("svc_gateway");
691
- expect(policy?.allowedPrincipalTypes).toContain("local");
692
- });
693
-
694
- test("import-preflight policy matches export but differs from validate on scopes", async () => {
695
- const { ROUTES } = await import("../runtime/routes/index.js");
696
- const preflightPolicy =
697
- ROUTES.find((r) => r.endpoint === "migrations/import-preflight")
698
- ?.policy ?? null;
699
- const validatePolicy =
700
- ROUTES.find((r) => r.endpoint === "migrations/validate")?.policy ?? null;
701
- const exportPolicy =
702
- ROUTES.find((r) => r.endpoint === "migrations/export")?.policy ?? null;
703
-
704
- // preflight and export both require settings.write
705
- expect(preflightPolicy!.requiredScopes).toEqual(
706
- exportPolicy!.requiredScopes,
707
- );
708
- // validate is read-only so requires settings.read
709
- expect(validatePolicy!.requiredScopes).toEqual(["settings.read"]);
710
- // all share the same principal types
711
- expect(preflightPolicy!.allowedPrincipalTypes).toEqual(
712
- validatePolicy!.allowedPrincipalTypes,
713
- );
714
- });
715
- });
716
-
717
- // ---------------------------------------------------------------------------
718
- // Integration: existing routes unaffected
719
- // ---------------------------------------------------------------------------
720
-
721
- describe("integration: existing routes unaffected", () => {
722
- test("GET /v1/health still works", async () => {
723
- const { handleDetailedHealth } =
724
- await import("../runtime/routes/identity-routes.js");
725
- const res = await handleDetailedHealth();
726
- const body = (await res.json()) as Record<string, unknown>;
727
-
728
- expect(res.status).toBe(200);
729
- expect(body.status).toBe("healthy");
730
- });
731
-
732
- test("validate and export handlers still importable", async () => {
733
- const { handleMigrationValidate, handleMigrationExport } =
734
- await import("../runtime/routes/migration-routes.js");
735
-
736
- expect(typeof handleMigrationValidate).toBe("function");
737
- expect(typeof handleMigrationExport).toBe("function");
738
- });
739
- });