@geminixiang/mikan 1.0.0-beta.83 → 1.0.0-beta.85

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 (159) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +2 -2
  3. package/dist/adapters/slack/bot.d.ts +1 -0
  4. package/dist/adapters/slack/bot.d.ts.map +1 -1
  5. package/dist/adapters/slack/bot.js +8 -2
  6. package/dist/adapters/slack/bot.js.map +1 -1
  7. package/dist/adapters/slack/response-lifecycle.js +2 -2
  8. package/dist/adapters/slack/response-lifecycle.js.map +1 -1
  9. package/dist/cli/boot.d.ts.map +1 -1
  10. package/dist/cli/boot.js +4 -6
  11. package/dist/cli/boot.js.map +1 -1
  12. package/dist/cli/migrate.d.ts +3 -0
  13. package/dist/cli/migrate.d.ts.map +1 -0
  14. package/dist/cli/migrate.js +75 -0
  15. package/dist/cli/migrate.js.map +1 -0
  16. package/dist/cli/office.d.ts.map +1 -1
  17. package/dist/cli/office.js +8 -129
  18. package/dist/cli/office.js.map +1 -1
  19. package/dist/cli/onboard.d.ts.map +1 -1
  20. package/dist/cli/onboard.js +3 -0
  21. package/dist/cli/onboard.js.map +1 -1
  22. package/dist/cli/types.d.ts +2 -3
  23. package/dist/cli/types.d.ts.map +1 -1
  24. package/dist/cli/types.js.map +1 -1
  25. package/dist/events/index.d.ts +2 -13
  26. package/dist/events/index.d.ts.map +1 -1
  27. package/dist/events/index.js +1 -58
  28. package/dist/events/index.js.map +1 -1
  29. package/dist/harness/budget-stop.d.ts +3 -0
  30. package/dist/harness/budget-stop.d.ts.map +1 -0
  31. package/dist/harness/budget-stop.js +36 -0
  32. package/dist/harness/budget-stop.js.map +1 -0
  33. package/dist/harness/execution-resolver.d.ts.map +1 -1
  34. package/dist/harness/execution-resolver.js +5 -9
  35. package/dist/harness/execution-resolver.js.map +1 -1
  36. package/dist/harness/open-connector.d.ts +0 -9
  37. package/dist/harness/open-connector.d.ts.map +1 -1
  38. package/dist/harness/open-connector.js +1 -62
  39. package/dist/harness/open-connector.js.map +1 -1
  40. package/dist/harness/presenter.d.ts.map +1 -1
  41. package/dist/harness/presenter.js +31 -2
  42. package/dist/harness/presenter.js.map +1 -1
  43. package/dist/harness/prompt.js +1 -1
  44. package/dist/harness/prompt.js.map +1 -1
  45. package/dist/harness/run-events.d.ts.map +1 -1
  46. package/dist/harness/run-events.js +6 -1
  47. package/dist/harness/run-events.js.map +1 -1
  48. package/dist/harness/skills.d.ts.map +1 -1
  49. package/dist/harness/skills.js +19 -14
  50. package/dist/harness/skills.js.map +1 -1
  51. package/dist/harness/tools/jev-browser.d.ts.map +1 -1
  52. package/dist/harness/tools/jev-browser.js +13 -15
  53. package/dist/harness/tools/jev-browser.js.map +1 -1
  54. package/dist/harness/types.d.ts +16 -0
  55. package/dist/harness/types.d.ts.map +1 -1
  56. package/dist/harness/types.js.map +1 -1
  57. package/dist/index.d.ts +0 -1
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +0 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/main.js +8 -50
  62. package/dist/main.js.map +1 -1
  63. package/dist/migrations/actor-vaults.d.ts +3 -0
  64. package/dist/migrations/actor-vaults.d.ts.map +1 -0
  65. package/dist/migrations/actor-vaults.js +43 -0
  66. package/dist/migrations/actor-vaults.js.map +1 -0
  67. package/dist/migrations/conversation-settings.d.ts +3 -0
  68. package/dist/migrations/conversation-settings.d.ts.map +1 -0
  69. package/dist/migrations/conversation-settings.js +31 -0
  70. package/dist/migrations/conversation-settings.js.map +1 -0
  71. package/dist/migrations/index.d.ts +14 -0
  72. package/dist/migrations/index.d.ts.map +1 -0
  73. package/dist/migrations/index.js +97 -0
  74. package/dist/migrations/index.js.map +1 -0
  75. package/dist/migrations/models-json.d.ts +3 -0
  76. package/dist/migrations/models-json.d.ts.map +1 -0
  77. package/dist/migrations/models-json.js +18 -0
  78. package/dist/migrations/models-json.js.map +1 -0
  79. package/dist/migrations/office-layout.d.ts +4 -0
  80. package/dist/migrations/office-layout.d.ts.map +1 -0
  81. package/dist/migrations/office-layout.js +94 -0
  82. package/dist/migrations/office-layout.js.map +1 -0
  83. package/dist/migrations/sandbox-containers.d.ts +3 -0
  84. package/dist/migrations/sandbox-containers.d.ts.map +1 -0
  85. package/dist/migrations/sandbox-containers.js +36 -0
  86. package/dist/migrations/sandbox-containers.js.map +1 -0
  87. package/dist/{sessions/migrate-common.d.ts → migrations/session-files.d.ts} +1 -2
  88. package/dist/migrations/session-files.d.ts.map +1 -0
  89. package/dist/{sessions/migrate-common.js → migrations/session-files.js} +2 -2
  90. package/dist/migrations/session-files.js.map +1 -0
  91. package/dist/{sessions/migrate-v3.d.ts → migrations/sessions-v3.d.ts} +4 -3
  92. package/dist/migrations/sessions-v3.d.ts.map +1 -0
  93. package/dist/{sessions/migrate-v3.js → migrations/sessions-v3.js} +14 -4
  94. package/dist/migrations/sessions-v3.js.map +1 -0
  95. package/dist/migrations/types.d.ts +30 -0
  96. package/dist/migrations/types.d.ts.map +1 -0
  97. package/dist/migrations/types.js +2 -0
  98. package/dist/migrations/types.js.map +1 -0
  99. package/dist/migrations/workspace-events.d.ts +3 -0
  100. package/dist/migrations/workspace-events.d.ts.map +1 -0
  101. package/dist/migrations/workspace-events.js +43 -0
  102. package/dist/migrations/workspace-events.js.map +1 -0
  103. package/dist/office/index.d.ts +2 -23
  104. package/dist/office/index.d.ts.map +1 -1
  105. package/dist/office/index.js +12 -574
  106. package/dist/office/index.js.map +1 -1
  107. package/dist/office/types.d.ts +0 -10
  108. package/dist/office/types.d.ts.map +1 -1
  109. package/dist/office/types.js.map +1 -1
  110. package/dist/sandbox/identity.d.ts +2 -3
  111. package/dist/sandbox/identity.d.ts.map +1 -1
  112. package/dist/sandbox/identity.js +6 -13
  113. package/dist/sandbox/identity.js.map +1 -1
  114. package/dist/sandbox/layout.d.ts +0 -2
  115. package/dist/sandbox/layout.d.ts.map +1 -1
  116. package/dist/sandbox/layout.js +2 -2
  117. package/dist/sandbox/layout.js.map +1 -1
  118. package/dist/sandbox/provisioner.d.ts +3 -37
  119. package/dist/sandbox/provisioner.d.ts.map +1 -1
  120. package/dist/sandbox/provisioner.js +13 -452
  121. package/dist/sandbox/provisioner.js.map +1 -1
  122. package/dist/sessions/session-store.d.ts.map +1 -1
  123. package/dist/sessions/session-store.js +1 -8
  124. package/dist/sessions/session-store.js.map +1 -1
  125. package/dist/sessions/types.d.ts +0 -10
  126. package/dist/sessions/types.d.ts.map +1 -1
  127. package/dist/sessions/types.js.map +1 -1
  128. package/dist/settings/index.d.ts +0 -48
  129. package/dist/settings/index.d.ts.map +1 -1
  130. package/dist/settings/index.js +6 -37
  131. package/dist/settings/index.js.map +1 -1
  132. package/dist/types.d.ts +0 -28
  133. package/dist/types.d.ts.map +1 -1
  134. package/dist/types.js.map +1 -1
  135. package/dist/vault/index.d.ts +0 -7
  136. package/dist/vault/index.d.ts.map +1 -1
  137. package/dist/vault/index.js +1 -36
  138. package/dist/vault/index.js.map +1 -1
  139. package/package.json +1 -1
  140. package/dist/cli/sandbox.d.ts +0 -3
  141. package/dist/cli/sandbox.d.ts.map +0 -1
  142. package/dist/cli/sandbox.js +0 -80
  143. package/dist/cli/sandbox.js.map +0 -1
  144. package/dist/cli/sessions.d.ts +0 -2
  145. package/dist/cli/sessions.d.ts.map +0 -1
  146. package/dist/cli/sessions.js +0 -78
  147. package/dist/cli/sessions.js.map +0 -1
  148. package/dist/sessions/migrate-common.d.ts.map +0 -1
  149. package/dist/sessions/migrate-common.js.map +0 -1
  150. package/dist/sessions/migrate-pi-084.d.ts +0 -7
  151. package/dist/sessions/migrate-pi-084.d.ts.map +0 -1
  152. package/dist/sessions/migrate-pi-084.js +0 -293
  153. package/dist/sessions/migrate-pi-084.js.map +0 -1
  154. package/dist/sessions/migrate-v3.d.ts.map +0 -1
  155. package/dist/sessions/migrate-v3.js.map +0 -1
  156. package/dist/settings/migrate.d.ts +0 -16
  157. package/dist/settings/migrate.d.ts.map +0 -1
  158. package/dist/settings/migrate.js +0 -70
  159. package/dist/settings/migrate.js.map +0 -1
@@ -1,10 +1,6 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
3
- import { isAbsolute, join, resolve } from "node:path";
4
- import * as log from "../log.js";
5
- import { legacyConversationCredentialKey } from "../sandbox/identity.js";
6
- import { guestWorkspacePath } from "../sandbox/layout.js";
7
- import { migrateConversationVaultKeys } from "../vault/index.js";
2
+ import { lstatSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
8
4
  import { atomicWritePrivateFile, readTextFileIfExists } from "../file-guards.js";
9
5
  import { isRecord } from "../unknown-values.js";
10
6
  export const OFFICE_LOG_FILENAME = "log.jsonl";
@@ -193,13 +189,6 @@ function ensureRegularOfficeDirectory(dir) {
193
189
  }
194
190
  const REGISTRY_VERSION = 1;
195
191
  const REGISTRY_FILENAME = "office-registry.json";
196
- const MIGRATION_STATUSES = new Set([
197
- "needs-owner",
198
- "prepared",
199
- "moving",
200
- "committed",
201
- "failed",
202
- ]);
203
192
  const REGISTRY_LOCK_FILENAME = ".office-registry.lock";
204
193
  const REGISTRY_LOCK_RETRY_MS = 25;
205
194
  const REGISTRY_LOCK_TIMEOUT_MS = 5_000;
@@ -222,20 +211,6 @@ export class OfficeRegistry {
222
211
  getState() {
223
212
  return this.state;
224
213
  }
225
- getMigration(rawConversationId) {
226
- assertConversationId(rawConversationId);
227
- return this.state.migrations.find((record) => record.rawConversationId === rawConversationId);
228
- }
229
- enablePlatform(platform) {
230
- const validPlatform = assertPlatformName(platform);
231
- return this.withExclusiveLease(() => {
232
- if (this.state.enabledPlatforms.includes(validPlatform))
233
- return this.state;
234
- const enabledPlatforms = [...this.state.enabledPlatforms, validPlatform].toSorted();
235
- this.replaceState(enabledPlatforms, this.state.offices, this.state.migrations);
236
- return this.state;
237
- });
238
- }
239
214
  recordOffice(address) {
240
215
  const normalized = validateOfficeAddress(address);
241
216
  const existing = this.findOffice(normalized);
@@ -250,7 +225,7 @@ export class OfficeRegistry {
250
225
  conversationId: normalized.conversationId,
251
226
  recordedAt: new Date().toISOString(),
252
227
  });
253
- this.replaceState(this.state.enabledPlatforms, [...this.state.offices, record], this.state.migrations);
228
+ this.replaceState([...this.state.offices, record]);
254
229
  return record;
255
230
  });
256
231
  }
@@ -260,151 +235,8 @@ export class OfficeRegistry {
260
235
  findOffice(address) {
261
236
  return this.state.offices.find((record) => record.platform === address.platform && record.conversationId === address.conversationId);
262
237
  }
263
- prepareLegacyMigration(options) {
264
- const rawConversationId = assertConversationId(options.rawConversationId);
265
- const sourceDir = resolve(options.sourceDir);
266
- const workspaceRoot = resolve(options.workspaceRoot);
267
- return this.withExclusiveLease(() => {
268
- const existing = this.getMigration(rawConversationId);
269
- assertCanonicalSource(sourceDir, workspaceRoot, rawConversationId);
270
- if (existing) {
271
- assertSameMigrationInputs(existing, sourceDir, workspaceRoot);
272
- if (existing.status !== "needs-owner")
273
- return existing;
274
- }
275
- assertRegularDirectory(sourceDir, "Legacy office source");
276
- const ownerPlatform = this.resolveOwner(options.ownerPlatform, rawConversationId);
277
- if (!ownerPlatform) {
278
- const record = makeRecord({
279
- rawConversationId,
280
- sourceDir,
281
- workspaceRoot,
282
- status: "needs-owner",
283
- });
284
- this.replaceMigration(existing, record);
285
- return record;
286
- }
287
- const targetDir = officeDir(workspaceRoot, {
288
- platform: ownerPlatform,
289
- conversationId: rawConversationId,
290
- });
291
- if (pathExists(targetDir)) {
292
- const failed = makeRecord({
293
- rawConversationId,
294
- sourceDir,
295
- workspaceRoot,
296
- ownerPlatform,
297
- targetDir,
298
- status: "failed",
299
- error: "Target office directory already exists",
300
- });
301
- this.replaceMigration(existing, failed);
302
- throw new Error(`${failed.error}: ${targetDir}`);
303
- }
304
- const prepared = makeRecord({
305
- rawConversationId,
306
- sourceDir,
307
- workspaceRoot,
308
- ownerPlatform,
309
- targetDir,
310
- status: "prepared",
311
- });
312
- this.replaceMigration(existing, prepared);
313
- return prepared;
314
- });
315
- }
316
- markMoving(rawConversationId) {
317
- return this.withExclusiveLease(() => {
318
- const record = this.requireMigration(rawConversationId);
319
- if (record.status === "moving" ||
320
- record.status === "committed" ||
321
- record.status === "failed") {
322
- return record;
323
- }
324
- if (record.status === "needs-owner") {
325
- throw new Error(`Legacy office ${JSON.stringify(rawConversationId)} still needs an owner`);
326
- }
327
- assertRegularDirectory(record.sourceDir, "Legacy office source");
328
- const targetDir = migrationTarget(record);
329
- if (!targetDir)
330
- throw new Error("Prepared office migration has no target directory");
331
- if (pathExists(targetDir)) {
332
- const failed = this.failRecord(record, "Target office directory appeared before moving");
333
- throw new Error(`${failed.error}: ${targetDir}`);
334
- }
335
- const moving = transitionRecord(record, "moving");
336
- this.replaceMigration(record, moving);
337
- return moving;
338
- });
339
- }
340
- markCommitted(rawConversationId) {
341
- return this.withExclusiveLease(() => {
342
- const record = this.requireMigration(rawConversationId);
343
- if (record.status === "committed" || record.status === "failed")
344
- return record;
345
- if (record.status !== "moving") {
346
- throw new Error(`Cannot commit office migration from ${record.status}`);
347
- }
348
- const targetDir = migrationTarget(record);
349
- if (!targetDir)
350
- throw new Error("Moving office migration has no target directory");
351
- assertRegularDirectory(targetDir, "Migrated office target");
352
- assertPathAbsent(record.sourceDir, "Legacy office source");
353
- const committed = transitionRecord(record, "committed");
354
- this.replaceMigration(record, committed);
355
- return committed;
356
- });
357
- }
358
- markFailed(rawConversationId, error) {
359
- return this.withExclusiveLease(() => {
360
- const record = this.requireMigration(rawConversationId);
361
- if (record.status === "committed") {
362
- throw new Error("A committed office migration cannot be marked failed");
363
- }
364
- if (record.status === "failed")
365
- return record;
366
- return this.failRecord(record, error);
367
- });
368
- }
369
- resolveOwner(ownerPlatform, rawConversationId) {
370
- if (ownerPlatform !== undefined) {
371
- const validPlatform = assertPlatformName(ownerPlatform);
372
- if (!this.state.enabledPlatforms.includes(validPlatform)) {
373
- throw new Error(`Owner platform ${validPlatform} is not enabled`);
374
- }
375
- return validPlatform;
376
- }
377
- const candidates = platformsMatchingConversationIdFormat(rawConversationId, this.state.enabledPlatforms);
378
- return candidates.length === 1 ? candidates[0] : undefined;
379
- }
380
- requireMigration(rawConversationId) {
381
- assertConversationId(rawConversationId);
382
- const record = this.getMigration(rawConversationId);
383
- if (!record)
384
- throw new Error(`No office migration registered for ${rawConversationId}`);
385
- return record;
386
- }
387
- failRecord(record, error) {
388
- const message = error.trim();
389
- if (!message)
390
- throw new Error("Office migration failure reason must not be empty");
391
- const failed = transitionRecord(record, "failed", message);
392
- this.replaceMigration(record, failed);
393
- return failed;
394
- }
395
- replaceMigration(previous, next) {
396
- const migrations = [...this.state.migrations];
397
- const index = previous
398
- ? migrations.findIndex((record) => record.rawConversationId === previous.rawConversationId)
399
- : -1;
400
- if (index === -1)
401
- migrations.push(next);
402
- else
403
- migrations[index] = next;
404
- this.replaceState(this.state.enabledPlatforms, this.state.offices, migrations);
405
- }
406
- replaceState(enabledPlatforms, offices, migrations) {
407
- const candidate = freezeState({ enabledPlatforms, offices, migrations });
238
+ replaceState(offices) {
239
+ const candidate = freezeState(offices);
408
240
  this.writeState(this.registryPath, `${JSON.stringify(candidate, null, 2)}\n`);
409
241
  this.state = candidate;
410
242
  }
@@ -422,7 +254,7 @@ export class OfficeRegistry {
422
254
  assertRegistryFileSafe(this.registryPath);
423
255
  const raw = readTextFileIfExists(this.registryPath);
424
256
  if (raw === undefined) {
425
- return freezeState({ enabledPlatforms: [], offices: [], migrations: [] });
257
+ return freezeState([]);
426
258
  }
427
259
  let value;
428
260
  try {
@@ -434,71 +266,21 @@ export class OfficeRegistry {
434
266
  return parseState(value, this.registryPath);
435
267
  }
436
268
  }
437
- function makeRecord(fields) {
438
- const record = {
439
- rawConversationId: fields.rawConversationId,
440
- sourceDir: fields.sourceDir,
441
- workspaceRoot: fields.workspaceRoot,
442
- ownerPlatform: fields.ownerPlatform ? fields.ownerPlatform : undefined,
443
- targetDir: fields.targetDir ? fields.targetDir : undefined,
444
- status: fields.status,
445
- error: fields.error ? fields.error : undefined,
446
- updatedAt: fields.updatedAt ?? new Date().toISOString(),
447
- };
448
- return Object.freeze(record);
449
- }
450
- function transitionRecord(record, status, error) {
451
- const targetDir = migrationTarget(record);
452
- return makeRecord({
453
- rawConversationId: record.rawConversationId,
454
- sourceDir: record.sourceDir,
455
- workspaceRoot: record.workspaceRoot,
456
- ownerPlatform: record.ownerPlatform,
457
- targetDir,
458
- status,
459
- error,
460
- });
461
- }
462
- function migrationTarget(record) {
463
- return record.ownerPlatform
464
- ? officeDir(record.workspaceRoot, {
465
- platform: record.ownerPlatform,
466
- conversationId: record.rawConversationId,
467
- })
468
- : undefined;
469
- }
470
- function freezeState(input) {
269
+ function freezeState(offices) {
471
270
  return Object.freeze({
472
271
  version: REGISTRY_VERSION,
473
- enabledPlatforms: Object.freeze([...input.enabledPlatforms]),
474
- offices: Object.freeze(input.offices.map((record) => Object.freeze({ ...record }))),
475
- migrations: Object.freeze(input.migrations.map((record) => Object.freeze({ ...record }))),
272
+ offices: Object.freeze(offices.map((record) => Object.freeze({ ...record }))),
476
273
  });
477
274
  }
478
275
  function parseState(value, path) {
479
- if (!isRecord(value) || value.version !== REGISTRY_VERSION) {
480
- throw new Error(`Invalid office registry version at ${path}`);
481
- }
482
- if (!Array.isArray(value.enabledPlatforms) || !Array.isArray(value.migrations)) {
483
- throw new Error(`Invalid office registry shape at ${path}`);
484
- }
485
- const enabledPlatforms = value.enabledPlatforms.map((platform) => {
486
- if (typeof platform !== "string")
487
- throw new Error(`Invalid enabled platform in ${path}`);
488
- return assertPlatformName(platform);
489
- });
490
- if (new Set(enabledPlatforms).size !== enabledPlatforms.length) {
491
- throw new Error(`Duplicate enabled platform in ${path}`);
276
+ if (!isRecord(value) || value.version !== REGISTRY_VERSION || !Array.isArray(value.offices)) {
277
+ throw new Error(`Invalid office registry at ${path}`);
492
278
  }
493
- const offices = (Array.isArray(value.offices) ? value.offices : []).map((entry) => parseOfficeRecord(entry, path));
279
+ const offices = value.offices.map((entry) => parseOfficeRecord(entry, path));
494
280
  if (new Set(offices.map((record) => officeKey(record))).size !== offices.length) {
495
281
  throw new Error(`Duplicate office record in ${path}`);
496
282
  }
497
- const migrations = value.migrations.map((entry) => parseRecord(entry, path, enabledPlatforms));
498
- if (new Set(migrations.map((record) => record.rawConversationId)).size !== migrations.length) {
499
- throw new Error(`Duplicate office migration in ${path}`);
500
- }
501
- return freezeState({ enabledPlatforms, offices, migrations });
283
+ return freezeState(offices);
502
284
  }
503
285
  function parseOfficeRecord(value, path) {
504
286
  if (!isRecord(value))
@@ -514,113 +296,6 @@ function parseOfficeRecord(value, path) {
514
296
  recordedAt: value.recordedAt,
515
297
  });
516
298
  }
517
- function hasMigrationStrings(value) {
518
- return (typeof value.rawConversationId === "string" &&
519
- typeof value.sourceDir === "string" &&
520
- typeof value.workspaceRoot === "string" &&
521
- typeof value.status === "string" &&
522
- typeof value.updatedAt === "string");
523
- }
524
- function parseMigrationFields(value, path) {
525
- if (!hasMigrationStrings(value)) {
526
- throw new Error(`Invalid office migration fields in ${path}`);
527
- }
528
- assertConversationId(value.rawConversationId);
529
- if (!isAbsolute(value.sourceDir) || !isAbsolute(value.workspaceRoot)) {
530
- throw new Error(`Office migration paths must be absolute in ${path}`);
531
- }
532
- assertCanonicalSource(value.sourceDir, value.workspaceRoot, value.rawConversationId);
533
- if (!MIGRATION_STATUSES.has(value.status)) {
534
- throw new Error(`Invalid office migration status in ${path}`);
535
- }
536
- return {
537
- rawConversationId: value.rawConversationId,
538
- sourceDir: value.sourceDir,
539
- workspaceRoot: value.workspaceRoot,
540
- status: value.status,
541
- updatedAt: value.updatedAt,
542
- };
543
- }
544
- function assertOwnershipMatchesStatus(status, ownerPlatform, targetDir, path) {
545
- const owned = ownerPlatform !== undefined;
546
- const targeted = targetDir !== undefined;
547
- if (status === "needs-owner" && (owned || targeted)) {
548
- throw new Error(`Needs-owner migration cannot have an owner or target in ${path}`);
549
- }
550
- if (status !== "needs-owner" && status !== "failed" && !(owned && targeted)) {
551
- throw new Error(`Prepared office migration is missing ownership in ${path}`);
552
- }
553
- if (!owned && targeted) {
554
- throw new Error(`Office migration target has no owner in ${path}`);
555
- }
556
- }
557
- function parseRecord(value, path, enabledPlatforms) {
558
- if (!isRecord(value))
559
- throw new Error(`Invalid office migration record in ${path}`);
560
- const fields = parseMigrationFields(value, path);
561
- const ownerPlatform = optionalPlatform(value.ownerPlatform);
562
- const targetDir = optionalString(value.targetDir);
563
- const error = optionalString(value.error);
564
- if (ownerPlatform !== undefined && !enabledPlatforms.includes(ownerPlatform)) {
565
- throw new Error(`Office migration owner is not enabled in ${path}`);
566
- }
567
- assertOwnershipMatchesStatus(fields.status, ownerPlatform, targetDir, path);
568
- const expectedTargetDir = ownerPlatform
569
- ? officeDir(fields.workspaceRoot, {
570
- platform: ownerPlatform,
571
- conversationId: fields.rawConversationId,
572
- })
573
- : undefined;
574
- if (targetDir !== expectedTargetDir) {
575
- throw new Error(`Office migration target does not match its office address in ${path}`);
576
- }
577
- if (fields.status === "failed" && !error) {
578
- throw new Error(`Failed office migration is missing an error in ${path}`);
579
- }
580
- return buildMigrationRecord(fields, ownerPlatform, expectedTargetDir, error);
581
- }
582
- function buildMigrationRecord(fields, ownerPlatform, targetDir, error) {
583
- return makeRecord({
584
- rawConversationId: fields.rawConversationId,
585
- sourceDir: fields.sourceDir,
586
- workspaceRoot: fields.workspaceRoot,
587
- ownerPlatform,
588
- targetDir,
589
- status: fields.status,
590
- error,
591
- updatedAt: fields.updatedAt,
592
- });
593
- }
594
- function optionalPlatform(value) {
595
- return value === undefined
596
- ? undefined
597
- : typeof value === "string"
598
- ? assertPlatformName(value)
599
- : failOptional("platform");
600
- }
601
- function optionalString(value) {
602
- return value === undefined
603
- ? undefined
604
- : typeof value === "string"
605
- ? value
606
- : failOptional("string");
607
- }
608
- function failOptional(label) {
609
- throw new Error(`Invalid optional ${label} in office registry`);
610
- }
611
- function assertSameMigrationInputs(existing, sourceDir, workspaceRoot) {
612
- if (existing.sourceDir !== sourceDir || existing.workspaceRoot !== workspaceRoot) {
613
- throw new Error(`Legacy office migration inputs changed for ${existing.rawConversationId}`);
614
- }
615
- }
616
- function assertCanonicalSource(sourceDir, workspaceRoot, rawConversationId) {
617
- const expectedSourceDir = resolve(workspaceRoot, rawConversationId);
618
- if (sourceDir !== expectedSourceDir) {
619
- throw new Error(`Legacy office source must be ${expectedSourceDir}`);
620
- }
621
- assertRegularDirectory(workspaceRoot, "Workspace root");
622
- assertPathIfPresent(sourceDir, "Legacy office source");
623
- }
624
299
  function assertRegularDirectory(path, label) {
625
300
  let stat;
626
301
  try {
@@ -649,19 +324,6 @@ function assertRegistryFileSafe(path) {
649
324
  throw new Error(`Office registry must be a regular file: ${path}`);
650
325
  }
651
326
  }
652
- function assertPathIfPresent(path, label) {
653
- const stat = lstatIfExists(path);
654
- if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) {
655
- throw new Error(`${label} must be a regular directory: ${path}`);
656
- }
657
- }
658
- function assertPathAbsent(path, label) {
659
- if (lstatIfExists(path))
660
- throw new Error(`${label} must be absent: ${path}`);
661
- }
662
- function pathExists(path) {
663
- return lstatIfExists(path) !== undefined;
664
- }
665
327
  function claimRegistryLock(lockPath, token) {
666
328
  mkdirSync(lockPath, { mode: 0o700 });
667
329
  try {
@@ -741,231 +403,7 @@ function sleepSync(milliseconds) {
741
403
  export function listRegisteredOffices(stateDir) {
742
404
  return new OfficeRegistry(stateDir).getOffices();
743
405
  }
744
- function platformsMatchingConversationIdFormat(rawConversationId, enabledPlatforms) {
745
- return enabledPlatforms.filter((platform) => {
746
- switch (platform) {
747
- case "github":
748
- return isGithubConversationId(rawConversationId);
749
- case "telegram":
750
- return /^-?\d+$/.test(rawConversationId);
751
- case "discord":
752
- return /^\d+$/.test(rawConversationId);
753
- case "slack":
754
- return /^[A-Z][A-Z0-9]*$/.test(rawConversationId);
755
- }
756
- });
757
- }
758
- function isGithubConversationId(rawConversationId) {
759
- try {
760
- parseGithubConversationId(rawConversationId);
761
- return true;
762
- }
763
- catch {
764
- return false;
765
- }
766
- }
767
406
  function isErrno(error, code) {
768
407
  return error instanceof Error && "code" in error && error.code === code;
769
408
  }
770
- export function migrateLegacyOffices(options) {
771
- const registry = new OfficeRegistry(options.stateDir);
772
- for (const platform of options.enabledPlatforms)
773
- registry.enablePlatform(platform);
774
- const summary = {
775
- migrated: [],
776
- recovered: [],
777
- unowned: [],
778
- failed: [],
779
- vaultKeysMigrated: [],
780
- vaultConflicts: [],
781
- stateDirsMigrated: [],
782
- stateDirConflicts: [],
783
- };
784
- recoverInterruptedMoves(registry, summary);
785
- claimAndMoveLegacyDirs(registry, options.workspaceRoot, summary);
786
- const vaults = migrateConversationVaultKeys({
787
- stateDir: options.stateDir,
788
- offices: registry.getOffices(),
789
- });
790
- summary.vaultKeysMigrated = vaults.migrated;
791
- summary.vaultConflicts = vaults.conflicts;
792
- for (const rawConversationId of vaults.migrated) {
793
- log.logInfo(`[office] Migrated vault key to office key: ${rawConversationId}`);
794
- }
795
- migrateConversationStateDirs(registry, options.stateDir, summary);
796
- for (const record of registry.getState().migrations) {
797
- if (record.status === "needs-owner")
798
- summary.unowned.push(record.rawConversationId);
799
- else if (record.status === "failed")
800
- summary.failed.push(record.rawConversationId);
801
- }
802
- return summary;
803
- }
804
- function recoverInterruptedMoves(registry, summary) {
805
- for (const record of registry.getState().migrations) {
806
- if (record.status !== "moving")
807
- continue;
808
- const failure = finishInterruptedMove(record);
809
- if (failure) {
810
- registry.markFailed(record.rawConversationId, failure);
811
- continue;
812
- }
813
- registry.markCommitted(record.rawConversationId);
814
- recordMigratedOffice(registry, record);
815
- summary.recovered.push(record.rawConversationId);
816
- log.logInfo(`[office] Recovered interrupted migration: ${record.rawConversationId}`);
817
- }
818
- }
819
- function finishInterruptedMove(record) {
820
- const targetDir = record.targetDir;
821
- if (!targetDir)
822
- return "Moving record has no target directory";
823
- const sourceExists = pathExists(record.sourceDir);
824
- const targetExists = pathExists(targetDir);
825
- if (sourceExists && targetExists) {
826
- return "Both legacy source and office target exist; merge them manually";
827
- }
828
- if (!sourceExists && !targetExists)
829
- return "Neither legacy source nor office target exists";
830
- if (sourceExists)
831
- renameSync(record.sourceDir, targetDir);
832
- return undefined;
833
- }
834
- function isClaimableLegacyDir(registry, workspaceRoot, rawConversationId) {
835
- const existing = registry.getMigration(rawConversationId);
836
- if (existing?.status === "committed") {
837
- throw new Error(`Legacy office directory reappeared after migration: ${join(workspaceRoot, rawConversationId)}`);
838
- }
839
- return existing?.status !== "failed";
840
- }
841
- function claimAndMoveLegacyDirs(registry, workspaceRoot, summary) {
842
- for (const rawConversationId of listLegacyOfficeDirs(workspaceRoot)) {
843
- if (!isClaimableLegacyDir(registry, workspaceRoot, rawConversationId))
844
- continue;
845
- const record = registry.prepareLegacyMigration({
846
- rawConversationId,
847
- sourceDir: join(workspaceRoot, rawConversationId),
848
- workspaceRoot,
849
- });
850
- if (record.status === "needs-owner")
851
- continue;
852
- const moving = registry.markMoving(rawConversationId);
853
- const targetDir = moving.targetDir;
854
- if (!targetDir)
855
- throw new Error("Moving office migration has no target directory");
856
- renameSync(moving.sourceDir, targetDir);
857
- registry.markCommitted(rawConversationId);
858
- recordMigratedOffice(registry, moving);
859
- summary.migrated.push(rawConversationId);
860
- log.logInfo(`[office] Migrated office directory: ${rawConversationId} -> ${targetDir}`);
861
- }
862
- }
863
- function migrateConversationStateDirs(registry, stateDir, summary) {
864
- for (const office of registry.getOffices()) {
865
- const legacyDir = join(stateDir, "conversations", office.conversationId);
866
- if (!existsSync(legacyDir))
867
- continue;
868
- const targetDir = officeStateDir(stateDir, office);
869
- if (existsSync(targetDir)) {
870
- summary.stateDirConflicts.push(office.conversationId);
871
- continue;
872
- }
873
- renameSync(legacyDir, targetDir);
874
- summary.stateDirsMigrated.push(office.conversationId);
875
- log.logInfo(`[office] Migrated host state dir to office key: ${office.conversationId}`);
876
- }
877
- }
878
- function recordMigratedOffice(registry, record) {
879
- if (!record.ownerPlatform)
880
- return;
881
- registry.recordOffice({
882
- platform: record.ownerPlatform,
883
- conversationId: record.rawConversationId,
884
- });
885
- }
886
- function listLegacyOfficeDirs(workspaceRoot) {
887
- return readdirSync(workspaceRoot, { withFileTypes: true })
888
- .filter((entry) => isLegacyOfficeDir(workspaceRoot, entry))
889
- .map((entry) => entry.name)
890
- .toSorted();
891
- }
892
- function isLegacyOfficeDir(workspaceRoot, entry) {
893
- if (entry.name.startsWith("."))
894
- return false;
895
- if (RESERVED_WORKSPACE_NAMES.has(entry.name))
896
- return false;
897
- if (isOfficeKey(entry.name))
898
- return false;
899
- if (entry.isSymbolicLink()) {
900
- throw new Error(`Workspace entry must not be a symlink: ${join(workspaceRoot, entry.name)}`);
901
- }
902
- if (!entry.isDirectory())
903
- return false;
904
- if (looksLikeConversationOffice(join(workspaceRoot, entry.name)))
905
- return true;
906
- log.logInfo(`[office] Skipping non-office workspace directory (no ${OFFICE_LOG_FILENAME} or sessions/): ${entry.name}`);
907
- return false;
908
- }
909
- function looksLikeConversationOffice(dir) {
910
- return existsSync(join(dir, OFFICE_LOG_FILENAME)) || existsSync(join(dir, "sessions"));
911
- }
912
- export function formatUnmigratedOfficesError(summary) {
913
- const lines = ["Conversation office migration cannot complete:"];
914
- if (summary.unowned.length > 0) {
915
- lines.push("", "These legacy conversation directories have no owning platform (several", "platforms are enabled, so ownership cannot be inferred):", ...summary.unowned.map((id) => ` - ${id}`), "", "Assign each one with:", " mikan office claim <conversationId> <platform>");
916
- }
917
- lines.push(...conflictSection(summary.failed, [
918
- "These migrations previously failed and need manual repair (see",
919
- "office-registry.json in the state dir for each error):",
920
- ]), ...conflictSection(summary.vaultConflicts, [
921
- "These conversations have credentials under both the legacy and the",
922
- "office-key vault directory; merge them manually under <state-dir>/vaults:",
923
- ]), ...conflictSection(summary.stateDirConflicts, [
924
- "These conversations have host state under both the legacy and the",
925
- "office-key directory; merge them manually under <state-dir>/conversations:",
926
- ]));
927
- return lines.join("\n");
928
- }
929
- function conflictSection(ids, explanation) {
930
- if (ids.length === 0)
931
- return [];
932
- return ["", ...explanation, ...ids.map((id) => ` - ${id}`)];
933
- }
934
- function replacePrefix(path, pairs) {
935
- for (const [oldPrefix, newPrefix] of pairs) {
936
- if (path === oldPrefix)
937
- return newPrefix;
938
- if (path.startsWith(`${oldPrefix}/`))
939
- return newPrefix + path.slice(oldPrefix.length);
940
- }
941
- return path;
942
- }
943
- export function buildContainerBindTranslator(options) {
944
- const hostPairs = [];
945
- const guestPairs = [];
946
- for (const office of options.offices) {
947
- const key = officeKey(office);
948
- const rawId = office.conversationId;
949
- hostPairs.push([join(options.workspaceRoot, rawId), join(options.workspaceRoot, key)]);
950
- hostPairs.push([
951
- join(options.stateDir, "conversations", rawId),
952
- officeStateDir(options.stateDir, office),
953
- ]);
954
- hostPairs.push([
955
- join(options.stateDir, "vaults", legacyConversationCredentialKey(rawId)),
956
- join(options.stateDir, "vaults", key),
957
- ]);
958
- guestPairs.push([guestWorkspacePath(rawId), guestWorkspacePath(key)]);
959
- }
960
- return (bindSpec) => {
961
- const readOnly = bindSpec.endsWith(":ro");
962
- const spec = readOnly ? bindSpec.slice(0, -3) : bindSpec;
963
- const separator = spec.indexOf(":");
964
- if (separator === -1)
965
- return bindSpec;
966
- const source = replacePrefix(spec.slice(0, separator), hostPairs);
967
- const target = replacePrefix(spec.slice(separator + 1), guestPairs);
968
- return `${source}:${target}${readOnly ? ":ro" : ""}`;
969
- };
970
- }
971
409
  //# sourceMappingURL=index.js.map