@evomap/evolver-cli 2.0.0-beta.17 → 2.0.0-beta.19

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 (64) hide show
  1. package/dist/antiGeneRollout.js +7 -3
  2. package/dist/assetTrust.js +14 -1
  3. package/dist/atp.d.ts +8 -3
  4. package/dist/atp.js +82 -11
  5. package/dist/atpAutoBuyer.d.ts +120 -0
  6. package/dist/atpAutoBuyer.js +814 -0
  7. package/dist/atpAutoDeliver.js +2 -2
  8. package/dist/autoDistillLlm.js +2 -1
  9. package/dist/autoDistillTranscript.js +3 -2
  10. package/dist/autoexec.d.ts +90 -13
  11. package/dist/autoexec.js +731 -84
  12. package/dist/cli.js +13 -0
  13. package/dist/cliContracts.d.ts +5 -2
  14. package/dist/cliContracts.js +135 -8
  15. package/dist/commands.d.ts +1 -0
  16. package/dist/commands.js +1 -0
  17. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  18. package/dist/curriculumCapabilityGaps.js +24 -0
  19. package/dist/cycleConsumer.d.ts +4 -0
  20. package/dist/cycleConsumer.js +175 -20
  21. package/dist/dashboard.js +47 -9
  22. package/dist/dispatch.js +6 -2
  23. package/dist/distillPrimitives.js +18 -6
  24. package/dist/doctor.js +63 -5
  25. package/dist/identityHome.js +2 -1
  26. package/dist/index.d.ts +67 -39
  27. package/dist/index.js +504 -185
  28. package/dist/learningTrace.d.ts +4 -0
  29. package/dist/learningTrace.js +30 -3
  30. package/dist/lifecycle.d.ts +54 -1
  31. package/dist/lifecycle.js +489 -37
  32. package/dist/materialSnapshot.d.ts +9 -1
  33. package/dist/materialSnapshot.js +23 -6
  34. package/dist/migrate/envTranslate.d.ts +26 -0
  35. package/dist/migrate/envTranslate.js +145 -0
  36. package/dist/migrate/oauthImport.d.ts +66 -0
  37. package/dist/migrate/oauthImport.js +667 -0
  38. package/dist/migrate/v1Import.d.ts +13 -1
  39. package/dist/migrate/v1Import.js +621 -122
  40. package/dist/promptRecallHook.d.ts +24 -0
  41. package/dist/promptRecallHook.js +425 -0
  42. package/dist/recallVerifyReport.d.ts +37 -0
  43. package/dist/recallVerifyReport.js +244 -0
  44. package/dist/requiredSandboxValidation.d.ts +5 -0
  45. package/dist/requiredSandboxValidation.js +4 -0
  46. package/dist/reuse.d.ts +1 -0
  47. package/dist/reuse.js +45 -37
  48. package/dist/runtimeCapabilities.js +13 -13
  49. package/dist/runtimeSessionSource.d.ts +3 -2
  50. package/dist/runtimeSessionSource.js +63 -11
  51. package/dist/sessionIngest.d.ts +37 -0
  52. package/dist/sessionIngest.js +156 -0
  53. package/dist/setupHooks.js +95 -1
  54. package/dist/skill2gep.d.ts +4 -7
  55. package/dist/skill2gep.js +4 -21
  56. package/dist/solo/mode.js +1 -0
  57. package/dist/sync.js +125 -23
  58. package/dist/thesis.d.ts +1 -1
  59. package/dist/thesis.js +18 -3
  60. package/dist/trajectoryExport.js +21 -3
  61. package/dist/v1Compat.d.ts +1 -0
  62. package/dist/v1Compat.js +9 -0
  63. package/dist/workflowRuntime.js +24 -18
  64. package/package.json +10 -7
@@ -0,0 +1,667 @@
1
+ // V1 oauth_token.json to V2 token.json explicit offline converter (Refs #697).
2
+ // Product decision for this slice: migration runs only when the operator invokes this command.
3
+ // Re-login remains the supported fallback when conversion fails or tokens are unusable.
4
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
7
+ import { CredentialStore, CredentialStoreError, machineFingerprint, resolveMachineId, } from '@evomap/evolver-adapter-public';
8
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
9
+ import { publicOAuthTokenPath } from '../login.js';
10
+ import { resolveIdentityHome } from '../identityHome.js';
11
+ const MAX_OAUTH_JSON_BYTES = 256 * 1024;
12
+ function isPlainRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ function nonBlank(value) {
16
+ if (typeof value !== 'string')
17
+ return undefined;
18
+ const t = value.trim();
19
+ return t.length > 0 ? t : undefined;
20
+ }
21
+ function secretString(value) {
22
+ if (typeof value !== 'string' || value.trim().length === 0)
23
+ return undefined;
24
+ return value;
25
+ }
26
+ function pickString(obj, keys) {
27
+ for (const key of keys) {
28
+ const v = nonBlank(obj[key]);
29
+ if (v)
30
+ return v;
31
+ }
32
+ return undefined;
33
+ }
34
+ function pickSecret(obj, keys) {
35
+ for (const key of keys) {
36
+ const value = secretString(obj[key]);
37
+ if (value !== undefined)
38
+ return value;
39
+ }
40
+ return undefined;
41
+ }
42
+ /** Normalize expires fields: ms epoch preferred; accept seconds epoch or expires_in relative. */
43
+ export function normalizeExpiresAt(raw, nowMs) {
44
+ const expAt = raw['expiresAt'] ?? raw['expires_at'] ?? raw['expiry'] ?? raw['exp'];
45
+ if (typeof expAt === 'number' && Number.isFinite(expAt) && expAt > 0) {
46
+ // Heuristic: values < 1e12 are seconds.
47
+ return expAt < 1e12 ? Math.floor(expAt * 1000) : Math.floor(expAt);
48
+ }
49
+ if (typeof expAt === 'string' && expAt.trim()) {
50
+ const asNum = Number(expAt);
51
+ if (Number.isFinite(asNum) && asNum > 0) {
52
+ return asNum < 1e12 ? Math.floor(asNum * 1000) : Math.floor(asNum);
53
+ }
54
+ const parsed = Date.parse(expAt);
55
+ if (Number.isFinite(parsed))
56
+ return parsed;
57
+ }
58
+ const expiresIn = raw['expiresInMs'] ?? raw['expires_in_ms'] ?? raw['expires_in'] ?? raw['expiresIn'];
59
+ if (typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0) {
60
+ // expires_in is usually seconds; expiresInMs is ms. Prefer key name.
61
+ if (raw['expiresInMs'] !== undefined || raw['expires_in_ms'] !== undefined) {
62
+ return nowMs + Math.floor(expiresIn);
63
+ }
64
+ // bare expires_in / expiresIn → seconds (OAuth2)
65
+ if (raw['expires_in'] !== undefined || raw['expiresIn'] !== undefined) {
66
+ return nowMs + Math.floor(expiresIn * 1000);
67
+ }
68
+ return nowMs + Math.floor(expiresIn);
69
+ }
70
+ return undefined;
71
+ }
72
+ /**
73
+ * Parse a V1 (or already-V2) OAuth JSON object into a V2 hub.Credential.
74
+ * Accepts snake_case OAuth2, nested token objects, and V2 credential shape.
75
+ */
76
+ export function parseV1OAuthJson(raw, nowMs = Date.now()) {
77
+ if (!isPlainRecord(raw)) {
78
+ throw new Error('oauth_json_not_object');
79
+ }
80
+ // Nested { token: { access_token, ... } } or { oauth: {...} }
81
+ let body = raw;
82
+ let shape = 'unknown';
83
+ if (isPlainRecord(raw['token']) && !nonBlank(raw['token']) && !nonBlank(raw['access_token'])) {
84
+ body = raw['token'];
85
+ shape = 'nested';
86
+ }
87
+ else if (isPlainRecord(raw['oauth'])) {
88
+ body = raw['oauth'];
89
+ shape = 'nested';
90
+ }
91
+ const access = pickSecret(body, ['token', 'access_token', 'accessToken'])
92
+ ?? pickSecret(raw, ['token', 'access_token', 'accessToken']);
93
+ const refresh = pickSecret(body, ['refreshToken', 'refresh_token', 'refresh'])
94
+ ?? pickSecret(raw, ['refreshToken', 'refresh_token', 'refresh']);
95
+ const device = pickString(body, ['device', 'device_id', 'deviceId', 'fingerprint', 'machine_id'])
96
+ ?? pickString(raw, ['device', 'device_id', 'deviceId', 'fingerprint', 'machine_id']);
97
+ const kindRaw = pickString(body, ['kind']) ?? pickString(raw, ['kind']);
98
+ if (kindRaw && kindRaw !== 'oauth_device_token') {
99
+ throw new Error('oauth_unsupported_kind');
100
+ }
101
+ // Detect V2 shape
102
+ if (body['kind'] === 'oauth_device_token' || raw['kind'] === 'oauth_device_token') {
103
+ shape = 'v2-credential';
104
+ }
105
+ else if (body['access_token'] !== undefined || raw['access_token'] !== undefined || body['refresh_token'] !== undefined) {
106
+ if (shape === 'unknown')
107
+ shape = 'oauth2-snake';
108
+ }
109
+ else if (body['token'] !== undefined && typeof body['token'] === 'string') {
110
+ if (shape === 'unknown')
111
+ shape = 'v2-credential';
112
+ }
113
+ if (!access && !refresh) {
114
+ throw new Error('oauth_missing_token');
115
+ }
116
+ const expiresAt = normalizeExpiresAt(body, nowMs) ?? normalizeExpiresAt(raw, nowMs);
117
+ const id = pickString(body, ['id'])
118
+ ?? pickString(raw, ['id'])
119
+ ?? (device ? `oauth-${device.slice(0, 12)}` : 'oauth-migrated-v1');
120
+ // The credential union requires a token. A refresh-only import uses a fixed
121
+ // placeholder that must always be expired so authenticate() rotates before use.
122
+ const token = access ?? 'migrated-pending-refresh';
123
+ const effectiveExpiresAt = access ? expiresAt : nowMs - 1;
124
+ const cred = {
125
+ id,
126
+ kind: 'oauth_device_token',
127
+ token,
128
+ ...(device ? { device } : {}),
129
+ ...(effectiveExpiresAt !== undefined ? { expiresAt: effectiveExpiresAt } : {}),
130
+ ...(refresh ? { refreshToken: refresh } : {}),
131
+ };
132
+ return {
133
+ cred,
134
+ shape,
135
+ hasAccessToken: Boolean(access),
136
+ hasRefreshToken: Boolean(refresh),
137
+ hasExpires: expiresAt !== undefined,
138
+ hasDevice: Boolean(device),
139
+ };
140
+ }
141
+ export function defaultV1OAuthPath(opts = {}) {
142
+ const env = opts.env ?? process.env;
143
+ // V1 only honored EVOLVER_HOME. EVOMAP_HOME / EVOMAP_DIR are V2 identity
144
+ // roots and must not redirect discovery away from the legacy credential.
145
+ const home = nonBlank(env['EVOLVER_HOME']) ?? join(opts.homeDir ?? homedir(), '.evomap');
146
+ return join(home, 'oauth_token.json');
147
+ }
148
+ class JsonSnapshotError extends Error {
149
+ code;
150
+ snapshot;
151
+ constructor(code, snapshot) {
152
+ super(code);
153
+ this.code = code;
154
+ this.snapshot = snapshot;
155
+ this.name = 'JsonSnapshotError';
156
+ }
157
+ }
158
+ function isErrno(error, code) {
159
+ return error.code === code;
160
+ }
161
+ function optionalConstant(name) {
162
+ return constants[name] ?? 0;
163
+ }
164
+ function sameFileIdentity(left, right) {
165
+ const stableId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
166
+ return stableId
167
+ ? left.dev === right.dev && left.ino === right.ino
168
+ : left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
169
+ }
170
+ function sameFileSnapshot(left, right) {
171
+ return sameFileIdentity(left, right)
172
+ && left.size === right.size
173
+ && left.mtimeNs === right.mtimeNs
174
+ && left.ctimeNs === right.ctimeNs;
175
+ }
176
+ function sameTrustedSecuritySnapshot(left, right) {
177
+ return sameFileIdentity(left, right)
178
+ && left.ctimeNs === right.ctimeNs
179
+ && left.mtimeNs === right.mtimeNs
180
+ && left.size === right.size
181
+ && left.mode === right.mode
182
+ && left.uid === right.uid;
183
+ }
184
+ function readBoundedJsonText(fd, purpose) {
185
+ const buffer = Buffer.allocUnsafe(MAX_OAUTH_JSON_BYTES + 1);
186
+ let offset = 0;
187
+ while (offset < buffer.length) {
188
+ const bytesRead = readSync(fd, buffer, offset, buffer.length - offset, null);
189
+ if (bytesRead === 0)
190
+ break;
191
+ offset += bytesRead;
192
+ }
193
+ if (offset > MAX_OAUTH_JSON_BYTES) {
194
+ throw new JsonSnapshotError(`oauth_${purpose}_too_large`);
195
+ }
196
+ return buffer.subarray(0, offset).toString('utf8');
197
+ }
198
+ function pathKey(path) {
199
+ return process.platform === 'win32' ? path.toLowerCase() : path;
200
+ }
201
+ function readJsonSnapshot(path, purpose, hook) {
202
+ let requested;
203
+ try {
204
+ requested = lstatSync(path, { bigint: true });
205
+ }
206
+ catch (error) {
207
+ if (isErrno(error, 'ENOENT'))
208
+ throw new JsonSnapshotError(`oauth_${purpose}_missing`);
209
+ throw new JsonSnapshotError(`oauth_${purpose}_stat_failed`);
210
+ }
211
+ if (!requested.isFile() || requested.isSymbolicLink()) {
212
+ throw new JsonSnapshotError(`oauth_${purpose}_not_regular_file`);
213
+ }
214
+ if (requested.size > BigInt(MAX_OAUTH_JSON_BYTES)) {
215
+ throw new JsonSnapshotError(`oauth_${purpose}_too_large`);
216
+ }
217
+ let canonicalPath;
218
+ let canonicalBefore;
219
+ try {
220
+ canonicalPath = realpathSync(path);
221
+ canonicalBefore = lstatSync(canonicalPath, { bigint: true });
222
+ }
223
+ catch {
224
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
225
+ }
226
+ if (!canonicalBefore.isFile() || canonicalBefore.isSymbolicLink()
227
+ || !sameFileSnapshot(requested, canonicalBefore)) {
228
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
229
+ }
230
+ hook?.('before-open', path);
231
+ let fd;
232
+ try {
233
+ fd = openSync(canonicalPath, constants.O_RDONLY | optionalConstant('O_NOFOLLOW') | optionalConstant('O_NONBLOCK'));
234
+ }
235
+ catch (error) {
236
+ if (isErrno(error, 'ELOOP'))
237
+ throw new JsonSnapshotError(`oauth_${purpose}_not_regular_file`);
238
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
239
+ }
240
+ let opened;
241
+ let text;
242
+ try {
243
+ opened = fstatSync(fd, { bigint: true });
244
+ if (!opened.isFile() || !sameFileSnapshot(canonicalBefore, opened)) {
245
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
246
+ }
247
+ if (opened.size > BigInt(MAX_OAUTH_JSON_BYTES)) {
248
+ throw new JsonSnapshotError(`oauth_${purpose}_too_large`);
249
+ }
250
+ hook?.('after-open', path);
251
+ text = readBoundedJsonText(fd, purpose);
252
+ hook?.('after-read', path);
253
+ const afterFd = fstatSync(fd, { bigint: true });
254
+ let afterPath;
255
+ let afterCanonical;
256
+ try {
257
+ afterPath = lstatSync(path, { bigint: true });
258
+ afterCanonical = realpathSync(path);
259
+ }
260
+ catch {
261
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
262
+ }
263
+ if (!afterPath.isFile() || afterPath.isSymbolicLink()
264
+ || pathKey(afterCanonical) !== pathKey(canonicalPath)
265
+ || !sameFileSnapshot(opened, afterFd)
266
+ || !sameFileSnapshot(afterFd, afterPath)) {
267
+ throw new JsonSnapshotError(`oauth_${purpose}_changed`);
268
+ }
269
+ }
270
+ finally {
271
+ closeSync(fd);
272
+ }
273
+ try {
274
+ return { value: JSON.parse(text), canonicalPath, stat: opened };
275
+ }
276
+ catch {
277
+ throw new JsonSnapshotError(`oauth_${purpose}_invalid_json`, { value: undefined, canonicalPath, stat: opened });
278
+ }
279
+ }
280
+ function isUsableOAuthCredential(value) {
281
+ if (!isPlainRecord(value) || value['kind'] !== 'oauth_device_token')
282
+ return false;
283
+ if (typeof value['id'] !== 'string' || value['id'].trim().length === 0)
284
+ return false;
285
+ if (typeof value['token'] !== 'string' || value['token'].trim().length === 0)
286
+ return false;
287
+ if (value['refreshToken'] !== undefined
288
+ && (typeof value['refreshToken'] !== 'string' || value['refreshToken'].trim().length === 0))
289
+ return false;
290
+ if (value['expiresAt'] !== undefined
291
+ && (typeof value['expiresAt'] !== 'number' || !Number.isFinite(value['expiresAt'])))
292
+ return false;
293
+ if (value['device'] !== undefined && typeof value['device'] !== 'string')
294
+ return false;
295
+ return true;
296
+ }
297
+ function inspectDestination(path) {
298
+ let snapshot;
299
+ try {
300
+ snapshot = readJsonSnapshot(path, 'destination');
301
+ }
302
+ catch (error) {
303
+ const code = error instanceof JsonSnapshotError ? error.code : 'oauth_destination_read_failed';
304
+ if (code === 'oauth_destination_missing')
305
+ return { status: 'absent' };
306
+ return {
307
+ status: 'invalid',
308
+ code,
309
+ ...(error instanceof JsonSnapshotError && error.snapshot !== undefined
310
+ ? { snapshot: error.snapshot }
311
+ : {}),
312
+ };
313
+ }
314
+ if (!isUsableOAuthCredential(snapshot.value)) {
315
+ return { status: 'invalid', code: 'oauth_destination_invalid_credential', snapshot };
316
+ }
317
+ return { status: 'valid', snapshot };
318
+ }
319
+ function validateTrustedSnapshot(path, snapshot, purpose) {
320
+ try {
321
+ const inspected = new CredentialStore(path).inspectTrustedExisting();
322
+ if (inspected === null || !sameTrustedSecuritySnapshot(snapshot.stat, inspected)) {
323
+ return `oauth_${purpose}_changed`;
324
+ }
325
+ return null;
326
+ }
327
+ catch {
328
+ return purpose === 'source'
329
+ ? 'oauth_source_untrusted'
330
+ : 'oauth_destination_credential_store_refused';
331
+ }
332
+ }
333
+ function validateTrustedDestinationParent(path) {
334
+ try {
335
+ new CredentialStore(path).inspectTrustedParentForCreate();
336
+ return null;
337
+ }
338
+ catch {
339
+ return 'oauth_destination_credential_store_refused';
340
+ }
341
+ }
342
+ function validateStoredDestination(path) {
343
+ try {
344
+ const loaded = new CredentialStore(path).load();
345
+ return isUsableOAuthCredential(loaded)
346
+ ? null
347
+ : 'oauth_destination_invalid_credential';
348
+ }
349
+ catch {
350
+ return 'oauth_destination_credential_store_refused';
351
+ }
352
+ }
353
+ /**
354
+ * Convert V1 ~/.evomap/oauth_token.json into V2 token.json via CredentialStore.
355
+ * Never prints secret values. Fail-closed on unsafe paths / missing tokens.
356
+ */
357
+ export function migrateV1OAuth(options = {}) {
358
+ const env = options.env ?? process.env;
359
+ const homeDir = options.homeDir;
360
+ const fromPath = resolve(options.fromPath ?? defaultV1OAuthPath({ env, homeDir }));
361
+ const toPath = resolve(options.toPath ?? publicOAuthTokenPath({ env, homeDir }));
362
+ const now = options.now ?? (() => Date.now());
363
+ const nowMs = now();
364
+ const emptyFields = {
365
+ hasAccessToken: false,
366
+ hasRefreshToken: false,
367
+ hasExpires: false,
368
+ hasDevice: false,
369
+ shape: 'unknown',
370
+ };
371
+ if (pathKey(fromPath) === pathKey(toPath)) {
372
+ return {
373
+ status: 'refused',
374
+ fromPath,
375
+ toPath,
376
+ sourceFields: emptyFields,
377
+ message: 'oauth_source_destination_same_file',
378
+ };
379
+ }
380
+ const destination = inspectDestination(toPath);
381
+ if (options.dryRun && destination.status !== 'absent' && destination.snapshot !== undefined) {
382
+ const destinationError = validateTrustedSnapshot(toPath, destination.snapshot, 'destination');
383
+ if (destinationError !== null) {
384
+ return {
385
+ status: 'refused',
386
+ fromPath,
387
+ toPath,
388
+ sourceFields: emptyFields,
389
+ message: destinationError,
390
+ };
391
+ }
392
+ }
393
+ if (destination.status === 'invalid' && (!options.force || destination.snapshot === undefined)) {
394
+ return {
395
+ status: 'refused',
396
+ fromPath,
397
+ toPath,
398
+ sourceFields: emptyFields,
399
+ message: destination.code,
400
+ };
401
+ }
402
+ if (destination.status === 'valid' && !options.force) {
403
+ if (!options.dryRun) {
404
+ const destinationError = validateStoredDestination(toPath);
405
+ if (destinationError !== null) {
406
+ return {
407
+ status: 'refused',
408
+ fromPath,
409
+ toPath,
410
+ sourceFields: emptyFields,
411
+ message: destinationError,
412
+ };
413
+ }
414
+ }
415
+ return {
416
+ status: 'skipped_existing',
417
+ fromPath,
418
+ toPath,
419
+ sourceFields: emptyFields,
420
+ message: 'valid V2 OAuth credential already exists; pass --force to replace it',
421
+ };
422
+ }
423
+ let sourceSnapshot;
424
+ let parsed;
425
+ try {
426
+ sourceSnapshot = readJsonSnapshot(fromPath, 'source', options.sourceReadTestHook);
427
+ options.beforeSourceTrustTestHook?.(fromPath);
428
+ const sourceTrustError = validateTrustedSnapshot(fromPath, sourceSnapshot, 'source');
429
+ if (sourceTrustError !== null)
430
+ throw new JsonSnapshotError(sourceTrustError);
431
+ parsed = parseV1OAuthJson(sourceSnapshot.value, nowMs);
432
+ }
433
+ catch (error) {
434
+ const rawCode = error instanceof JsonSnapshotError
435
+ ? error.code
436
+ : error instanceof Error && /^oauth_[a-z_]+$/.test(error.message)
437
+ ? error.message
438
+ : 'oauth_parse_failed';
439
+ const missing = rawCode === 'oauth_source_missing';
440
+ return {
441
+ status: missing ? 'source_missing' : 'invalid_source',
442
+ fromPath,
443
+ toPath,
444
+ sourceFields: emptyFields,
445
+ message: missing
446
+ ? 'V1 oauth_token.json not found; run `evolver login` if Hub auth is required'
447
+ : rawCode,
448
+ };
449
+ }
450
+ if (destination.status !== 'absent' && destination.snapshot !== undefined
451
+ && (pathKey(destination.snapshot.canonicalPath) === pathKey(sourceSnapshot.canonicalPath)
452
+ || sameFileIdentity(destination.snapshot.stat, sourceSnapshot.stat))) {
453
+ return {
454
+ status: 'refused',
455
+ fromPath,
456
+ toPath,
457
+ sourceFields: emptyFields,
458
+ message: 'oauth_source_destination_same_file',
459
+ };
460
+ }
461
+ const sourceFields = {
462
+ hasAccessToken: parsed.hasAccessToken,
463
+ hasRefreshToken: parsed.hasRefreshToken,
464
+ hasExpires: parsed.hasExpires,
465
+ hasDevice: parsed.hasDevice,
466
+ shape: parsed.shape,
467
+ };
468
+ const accessExpired = parsed.cred.expiresAt !== undefined ? parsed.cred.expiresAt <= nowMs : false;
469
+ if (options.dryRun) {
470
+ if (destination.status === 'absent') {
471
+ const destinationError = validateTrustedDestinationParent(toPath);
472
+ if (destinationError !== null) {
473
+ return {
474
+ status: 'refused',
475
+ fromPath,
476
+ toPath,
477
+ sourceFields,
478
+ accessExpired,
479
+ message: destinationError,
480
+ };
481
+ }
482
+ }
483
+ return {
484
+ status: 'dry_run',
485
+ fromPath,
486
+ toPath,
487
+ sourceFields,
488
+ accessExpired,
489
+ message: 'dry-run: source is valid; no credential or machine-id was written',
490
+ };
491
+ }
492
+ let device;
493
+ try {
494
+ device = options.deviceFingerprint ?? machineFingerprint(resolveMachineId({
495
+ softIdPath: join(resolveIdentityHome(env, homeDir), 'machine-id'),
496
+ }).id);
497
+ if (!/^[a-f0-9]{64}$/.test(device))
498
+ throw new Error('invalid_device_fingerprint');
499
+ const credential = {
500
+ ...parsed.cred,
501
+ id: `oauth-${device.slice(0, 12)}`,
502
+ device,
503
+ };
504
+ options.beforeSaveTestHook?.(toPath);
505
+ const store = new CredentialStore(toPath);
506
+ const stored = options.force ? (store.save(credential), true) : store.saveIfAbsent(credential);
507
+ if (!stored) {
508
+ const incumbent = inspectDestination(toPath);
509
+ if (incumbent.status !== 'valid') {
510
+ return {
511
+ status: 'refused',
512
+ fromPath,
513
+ toPath,
514
+ sourceFields,
515
+ accessExpired,
516
+ message: incumbent.status === 'invalid'
517
+ ? incumbent.code
518
+ : 'oauth_destination_changed',
519
+ };
520
+ }
521
+ const incumbentError = validateStoredDestination(toPath);
522
+ if (incumbentError !== null) {
523
+ return {
524
+ status: 'refused',
525
+ fromPath,
526
+ toPath,
527
+ sourceFields,
528
+ accessExpired,
529
+ message: incumbentError,
530
+ };
531
+ }
532
+ return {
533
+ status: 'skipped_existing',
534
+ fromPath,
535
+ toPath,
536
+ sourceFields,
537
+ accessExpired,
538
+ message: 'concurrent writer published a valid V2 OAuth credential; migration did not overwrite it',
539
+ };
540
+ }
541
+ }
542
+ catch (error) {
543
+ return {
544
+ status: 'refused',
545
+ fromPath,
546
+ toPath,
547
+ sourceFields,
548
+ accessExpired,
549
+ message: error instanceof CredentialStoreError
550
+ ? 'oauth_destination_credential_store_refused'
551
+ : 'oauth_credential_write_failed',
552
+ };
553
+ }
554
+ const tips = [];
555
+ if (!parsed.hasRefreshToken && accessExpired) {
556
+ tips.push('access token appears expired and no refresh_token; run `evolver login` if Hub rejects it');
557
+ }
558
+ else if (!parsed.hasRefreshToken) {
559
+ tips.push('no refresh_token in V1 file; re-login if Hub rejects it');
560
+ }
561
+ else if (accessExpired) {
562
+ tips.push('access token expired; V2 will refresh via refresh_token on next Hub call');
563
+ }
564
+ return {
565
+ status: 'migrated',
566
+ fromPath,
567
+ toPath,
568
+ sourceFields,
569
+ accessExpired,
570
+ message: tips.length > 0
571
+ ? `migrated OAuth credential to ${toPath} (${tips.join('; ')})`
572
+ : `migrated OAuth credential to ${toPath}`,
573
+ };
574
+ }
575
+ function formatOAuthMigrateReport(report) {
576
+ const f = report.sourceFields;
577
+ return [
578
+ `oauth migrate: ${report.status}`,
579
+ ` from: ${report.fromPath}`,
580
+ ` to: ${report.toPath}`,
581
+ ` fields: access=${f.hasAccessToken} refresh=${f.hasRefreshToken} expires=${f.hasExpires} device=${f.hasDevice} shape=${f.shape}`,
582
+ report.accessExpired !== undefined ? ` access_expired: ${report.accessExpired}` : '',
583
+ ` ${report.message}`,
584
+ ].filter(Boolean).join('\n') + '\n';
585
+ }
586
+ function parseMigrateOAuthArgs(argv) {
587
+ const opts = {};
588
+ for (let i = 0; i < argv.length; i += 1) {
589
+ const a = argv[i] ?? '';
590
+ if (a === '--force')
591
+ opts.force = true;
592
+ else if (a === '--dry-run')
593
+ opts.dryRun = true;
594
+ else if (a === '--from') {
595
+ const v = argv[++i];
596
+ if (!v || v.startsWith('--'))
597
+ return { error: 'migrate oauth --from requires a path' };
598
+ opts.fromPath = v;
599
+ }
600
+ else if (a.startsWith('--from=')) {
601
+ const value = a.slice('--from='.length);
602
+ if (!value)
603
+ return { error: 'migrate oauth --from requires a path' };
604
+ opts.fromPath = value;
605
+ }
606
+ else if (a === '--to') {
607
+ const v = argv[++i];
608
+ if (!v || v.startsWith('--'))
609
+ return { error: 'migrate oauth --to requires a path' };
610
+ opts.toPath = v;
611
+ }
612
+ else if (a.startsWith('--to=')) {
613
+ const value = a.slice('--to='.length);
614
+ if (!value)
615
+ return { error: 'migrate oauth --to requires a path' };
616
+ opts.toPath = value;
617
+ }
618
+ else if (a === '--json')
619
+ opts.json = true;
620
+ else if (a === '--help' || a === '-h')
621
+ return { error: 'help' };
622
+ else
623
+ return { error: 'unknown argument' };
624
+ }
625
+ return opts;
626
+ }
627
+ export async function runMigrateOAuthCommand(argv, io = {}) {
628
+ const stdout = io.stdout ?? ((s) => { process.stdout.write(s); });
629
+ const stderr = io.stderr ?? ((s) => { process.stderr.write(s); });
630
+ const usage = [
631
+ 'Usage: evolver migrate oauth [--from <oauth_token.json>] [--to <token.json>] [--force] [--dry-run] [--json]',
632
+ '',
633
+ 'Import V1 ~/.evomap/oauth_token.json into V2 token.json (CredentialStore).',
634
+ 'Does not print secret values. Re-login remains valid if migration is incomplete.',
635
+ '',
636
+ ].join('\n');
637
+ const parsed = parseMigrateOAuthArgs(argv);
638
+ if ('error' in parsed) {
639
+ if (parsed.error === 'help') {
640
+ stdout(usage);
641
+ return 0;
642
+ }
643
+ stderr(`${parsed.error}\n${usage}`);
644
+ return 1;
645
+ }
646
+ const json = Boolean(parsed.json);
647
+ const env = io.env ?? process.env;
648
+ const envLoad = loadEnvFileFromEnv(env);
649
+ if (envLoad.error) {
650
+ stderr('migrate oauth: failed to load EVOLVER_ENV_FILE\n');
651
+ return 1;
652
+ }
653
+ const report = migrateV1OAuth({ ...parsed, env });
654
+ if (json) {
655
+ stdout(`${JSON.stringify(report, null, 2)}\n`);
656
+ }
657
+ else {
658
+ stdout(formatOAuthMigrateReport(report));
659
+ }
660
+ if (report.status === 'migrated' || report.status === 'dry_run')
661
+ return 0;
662
+ if (report.status === 'skipped_existing')
663
+ return 0;
664
+ if (report.status === 'source_missing')
665
+ return 2;
666
+ return 1;
667
+ }
@@ -9,6 +9,8 @@ export interface ImportReport {
9
9
  memoryGraphArchived: boolean;
10
10
  memoryGraphImported: number;
11
11
  memoryGraphDeferred: boolean;
12
+ mailboxFound: boolean;
13
+ mailboxImported: number;
12
14
  candidatesSkipped: boolean;
13
15
  }
14
16
  /**
@@ -18,5 +20,15 @@ export interface ImportReport {
18
20
  export interface ImportV1Options {
19
21
  workspace?: string;
20
22
  userId?: string;
23
+ /** Test seam used to deterministically exercise source-path races. */
24
+ sourceSnapshotTestHook?: (stage: 'before-open' | 'after-open' | 'after-snapshot', source: string, snapshotPath?: string) => void;
25
+ /** Test seam used to prove extension metadata is durable before the asset write. */
26
+ sidecarAppendTestHook?: (stage: 'before-append' | 'after-append', path: string) => void;
27
+ /** Test seam used to exercise completion-marker publication failures. */
28
+ memoryGraphMarkerTestHook?: (stage: 'before-publish', temporaryPath: string, markerPath: string) => void;
21
29
  }
22
- export declare function importV1(v1Dir: string, store: assetstore.LocalJsonlProvider, outDir: string, options?: ImportV1Options): Promise<ImportReport>;
30
+ export declare function importV1(v1Dir: string, store: assetstore.LocalJsonlProvider, outDir: string, options?: ImportV1Options): Promise<ImportReport>;
31
+ export declare function validateMigrationRoots(v1Dir: string, outDir: string): {
32
+ sourceRoot: string;
33
+ outputRoot: string;
34
+ };