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26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/** Selection helpers for filtering migration plan items before apply. */
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
import { markMigrationItemSkipped, summarizeMigrationItems } from "../../plugin-sdk/migration.js";
import type { MigrationItem, MigrationPlan } from "../../plugins/types.js";
import { MIGRATION_CONFLICT_REASON_PHRASES } from "./output.js";

// Selection tokens are shared with the command and prompt implementations.
const MIGRATION_NOT_SELECTED_REASON = "not selected for migration";
export const MIGRATION_SELECTION_ACCEPT = "__openclaw_migrate_accept_recommended__";
export const MIGRATION_SELECTION_TOGGLE_ALL_ON = "__openclaw_migrate_toggle_all_on__";
export const MIGRATION_SELECTION_TOGGLE_ALL_OFF = "__openclaw_migrate_toggle_all_off__";

type InteractiveMigrationSelection = { action: "select"; selectedItemIds: Set<string> };

function normalizeSelectionRef(value: string): string {
  return value.trim().toLowerCase();
}

function readMigrationSkillName(item: MigrationItem): string | undefined {
  return normalizeOptionalString(item.details?.skillName);
}

function readMigrationSkillSourceLabel(item: MigrationItem): string | undefined {
  return normalizeOptionalString(item.details?.sourceLabel);
}

function readMigrationPluginName(item: MigrationItem): string | undefined {
  return normalizeOptionalString(item.details?.pluginName);
}

function readMigrationPluginConfigKey(item: MigrationItem): string | undefined {
  return normalizeOptionalString(item.details?.configKey);
}

function readMigrationPluginMarketplaceName(item: MigrationItem): string | undefined {
  return normalizeOptionalString(item.details?.marketplaceName);
}

function migrationSkillRefs(item: MigrationItem): string[] {
  const skillName = readMigrationSkillName(item);
  const idSuffix = item.id.startsWith("skill:") ? item.id.slice("skill:".length) : undefined;
  const sourceBase = item.source ? path.basename(item.source) : undefined;
  const targetBase = item.target ? path.basename(item.target) : undefined;
  return [item.id, idSuffix, skillName, sourceBase, targetBase].filter(
    (value): value is string => typeof value === "string" && value.trim().length > 0,
  );
}

function migrationPluginRefs(item: MigrationItem): string[] {
  const pluginName = readMigrationPluginName(item);
  const configKey = readMigrationPluginConfigKey(item);
  const idSuffix = item.id.startsWith("plugin:") ? item.id.slice("plugin:".length) : undefined;
  const sourceBase = item.source ? path.basename(item.source) : undefined;
  const targetBase = item.target ? path.basename(item.target) : undefined;
  return [item.id, idSuffix, pluginName, configKey, sourceBase, targetBase].filter(
    (value): value is string => typeof value === "string" && value.trim().length > 0,
  );
}

function formatSelectionRefList(values: readonly string[]): string {
  if (values.length === 0) {
    return "none";
  }
  return values.map((value) => `"${value}"`).join(", ");
}

function buildSelectionIndex(
  items: readonly MigrationItem[],
  refsForItem: (item: MigrationItem) => readonly string[],
): Map<string, ReadonlySet<string>> {
  const index = new Map<string, Set<string>>();
  for (const item of items) {
    for (const ref of refsForItem(item)) {
      const normalized = normalizeSelectionRef(ref);
      if (!normalized) {
        continue;
      }
      const existing = index.get(normalized) ?? new Set<string>();
      existing.add(item.id);
      index.set(normalized, existing);
    }
  }
  return index;
}

function resolveSelectedMigrationItemIds(params: {
  items: readonly MigrationItem[];
  selectedRefs: readonly string[];
  refsForItem: (item: MigrationItem) => readonly string[];
  formatSelectionLabel: (item: MigrationItem) => string;
  kindLabel: "skill" | "plugin";
  availableLabel: "skills" | "plugins";
}): Set<string> {
  const index = buildSelectionIndex(params.items, params.refsForItem);
  const selectedIds = new Set<string>();
  const unknownRefs: string[] = [];
  const ambiguousRefs: string[] = [];
  for (const ref of params.selectedRefs) {
    const normalized = normalizeSelectionRef(ref);
    if (!normalized) {
      continue;
    }
    const matches = index.get(normalized);
    if (!matches) {
      unknownRefs.push(ref);
      continue;
    }
    if (matches.size > 1) {
      ambiguousRefs.push(ref);
      continue;
    }
    const [id] = matches;
    if (id) {
      selectedIds.add(id);
    }
  }

  if (unknownRefs.length > 0 || ambiguousRefs.length > 0) {
    const available = params.items
      .map(params.formatSelectionLabel)
      .toSorted((a, b) => a.localeCompare(b));
    const titleKind =
      expectDefined(params.kindLabel[0], "kind label entry at 0").toUpperCase() +
      params.kindLabel.slice(1);
    const parts: string[] = [];
    if (unknownRefs.length > 0) {
      parts.push(
        `No migratable ${params.kindLabel} matched ${formatSelectionRefList(unknownRefs)}.`,
      );
    }
    if (ambiguousRefs.length > 0) {
      parts.push(`${titleKind} selection ${formatSelectionRefList(ambiguousRefs)} was ambiguous.`);
    }
    parts.push(
      `Available ${params.availableLabel}: ${available.length > 0 ? available.join(", ") : "none"}.`,
    );
    throw new Error(parts.join(" "));
  }

  return selectedIds;
}

/** Returns skill copy items that can still be selected or deselected. */
export function getSelectableMigrationSkillItems(plan: MigrationPlan): MigrationItem[] {
  return plan.items.filter(
    (item) =>
      item.kind === "skill" &&
      item.action === "copy" &&
      (item.status === "planned" || item.status === "conflict"),
  );
}

/** Returns plugin install items that can still be selected or deselected. */
export function getSelectableMigrationPluginItems(plan: MigrationPlan): MigrationItem[] {
  // Only source-installed curated Codex plugins become selectable install items.
  // Cached/manual-review plugin bundles are emitted as manual items, the aggregate
  // Codex plugin config write is a config item, and already skipped/applied/error
  // items are no longer user-actionable in the selector. Conflicts stay selectable
  // so the user can explicitly choose or deselect them before apply.
  return plan.items.filter(
    (item) =>
      item.kind === "plugin" &&
      item.action === "install" &&
      (item.status === "planned" || item.status === "conflict"),
  );
}

/** Formats the visible label for a plugin migration checkbox. */
export function formatMigrationPluginSelectionLabel(item: MigrationItem): string {
  return readMigrationPluginName(item) ?? item.id.replace(/^plugin:/u, "");
}

/** Defaults migration checkboxes to planned item ids in plan order. */
export function getDefaultMigrationSelectionValues(items: readonly MigrationItem[]): string[] {
  return items.filter((item) => item.status === "planned").map((item) => item.id);
}

/** Formats the visible label for a skill migration checkbox. */
export function formatMigrationSkillSelectionLabel(item: MigrationItem): string {
  return readMigrationSkillName(item) ?? item.id.replace(/^skill:/u, "");
}

function humanizeMigrationConflictReason(reason: string | undefined): string {
  if (!reason) {
    return "conflict";
  }
  return MIGRATION_CONFLICT_REASON_PHRASES[reason] ?? reason;
}

/** Formats conflict helper text for a skill migration checkbox. */
export function formatMigrationSkillSelectionHint(item: MigrationItem): string | undefined {
  if (item.status !== "conflict") {
    return undefined;
  }
  const sourceLabel = readMigrationSkillSourceLabel(item);
  const reason = humanizeMigrationConflictReason(item.reason);
  return sourceLabel ? `${sourceLabel} ${reason}` : reason;
}

/** Formats conflict helper text for a plugin migration checkbox. */
export function formatMigrationPluginSelectionHint(item: MigrationItem): string | undefined {
  if (item.status !== "conflict") {
    return undefined;
  }
  const marketplace = readMigrationPluginMarketplaceName(item);
  const reason = humanizeMigrationConflictReason(item.reason);
  return marketplace ? `${marketplace} plugin ${reason}` : reason;
}

/** Keeps skill copies and their per-skill config patches inside the same selection. */
export function applyMigrationSelectedSkillItemIds(
  plan: MigrationPlan,
  selectedItemIds: ReadonlySet<string>,
): MigrationPlan {
  const selectable = getSelectableMigrationSkillItems(plan);
  const selectableIds = new Set(selectable.map((item) => item.id));
  const selectedSkillNames = new Set(
    selectable
      .filter((item) => selectedItemIds.has(item.id))
      .map(
        (item) =>
          readMigrationSkillName(item) ?? (item.source ? path.basename(item.source) : undefined),
      )
      .filter((name) => name !== undefined),
  );
  const items = plan.items.map((item) => {
    const configPath = item.kind === "config" ? item.details?.path : undefined;
    // Per-skill patches keep conflicts independent, so a deselected skill's
    // policy cannot mutate the target or block an otherwise valid import.
    if (
      Array.isArray(configPath) &&
      configPath.length === 3 &&
      configPath[0] === "skills" &&
      configPath[1] === "entries" &&
      !selectedSkillNames.has(configPath[2]) &&
      (item.status === "planned" || item.status === "conflict")
    ) {
      return markMigrationItemSkipped(item, MIGRATION_NOT_SELECTED_REASON);
    }
    if (!selectableIds.has(item.id) || selectedItemIds.has(item.id)) {
      return item;
    }
    return markMigrationItemSkipped(item, MIGRATION_NOT_SELECTED_REASON);
  });
  return {
    ...plan,
    items,
    summary: summarizeMigrationItems(items),
  };
}

/** Applies skill refs passed by CLI flags to a migration plan. */
export function applyMigrationSkillSelection(
  plan: MigrationPlan,
  selectedSkillRefs: readonly string[] | undefined,
): MigrationPlan {
  if (selectedSkillRefs === undefined) {
    return plan;
  }
  const selectable = getSelectableMigrationSkillItems(plan);
  const selectedIds = resolveSelectedMigrationItemIds({
    items: selectable,
    selectedRefs: selectedSkillRefs,
    refsForItem: migrationSkillRefs,
    formatSelectionLabel: formatMigrationSkillSelectionLabel,
    kindLabel: "skill",
    availableLabel: "skills",
  });
  return applyMigrationSelectedSkillItemIds(plan, selectedIds);
}

/** Applies plugin refs passed by CLI flags to a migration plan. */
export function applyMigrationPluginSelection(
  plan: MigrationPlan,
  selectedPluginRefs: readonly string[] | undefined,
): MigrationPlan {
  if (selectedPluginRefs === undefined) {
    return plan;
  }
  const selectable = getSelectableMigrationPluginItems(plan);
  const selectedIds = resolveSelectedMigrationItemIds({
    items: selectable,
    selectedRefs: selectedPluginRefs,
    refsForItem: migrationPluginRefs,
    formatSelectionLabel: formatMigrationPluginSelectionLabel,
    kindLabel: "plugin",
    availableLabel: "plugins",
  });
  return applyMigrationSelectedPluginItemIds(plan, selectedIds);
}

/** Marks unselected plugin items skipped and filters matching Codex plugin config writes. */
export function applyMigrationSelectedPluginItemIds(
  plan: MigrationPlan,
  selectedItemIds: ReadonlySet<string>,
): MigrationPlan {
  const selectable = getSelectableMigrationPluginItems(plan);
  const selectableIds = new Set(selectable.map((item) => item.id));
  const selectedConfigKeys = new Set(
    selectable
      .filter((item) => selectedItemIds.has(item.id))
      .map(readMigrationPluginConfigKey)
      .filter((value): value is string => value !== undefined),
  );
  const items = plan.items.map((item) => {
    const selectedConfigItem = applyCodexPluginConfigSelection(item, selectedConfigKeys);
    if (selectedConfigItem) {
      return selectedConfigItem;
    }
    if (!selectableIds.has(item.id) || selectedItemIds.has(item.id)) {
      return item;
    }
    return markMigrationItemSkipped(item, MIGRATION_NOT_SELECTED_REASON);
  });
  return {
    ...plan,
    items,
    summary: summarizeMigrationItems(items),
  };
}

function applyCodexPluginConfigSelection(
  item: MigrationItem,
  selectedConfigKeys: ReadonlySet<string>,
): MigrationItem | undefined {
  // Nonmatching config shapes still pass through ordinary item-id selection.
  if (item.kind !== "config" || item.action !== "merge") {
    return undefined;
  }
  const value = item.details?.value;
  if (!isRecord(value)) {
    return undefined;
  }
  const config = value.config;
  if (!isRecord(config)) {
    return undefined;
  }
  const codexPlugins = config.codexPlugins;
  if (!isRecord(codexPlugins) || !isRecord(codexPlugins.plugins)) {
    return undefined;
  }
  const plugins = Object.fromEntries(
    Object.entries(codexPlugins.plugins).filter(([configKey]) => selectedConfigKeys.has(configKey)),
  );
  if (Object.keys(plugins).length === 0) {
    return markMigrationItemSkipped(item, MIGRATION_NOT_SELECTED_REASON);
  }
  return {
    ...item,
    details: {
      ...item.details,
      value: {
        ...value,
        config: {
          ...config,
          codexPlugins: {
            ...codexPlugins,
            plugins,
          },
        },
      },
    },
  };
}

/** Resolves checkbox values into migration item ids for either selector. */
export function resolveInteractiveMigrationSelection(
  items: readonly MigrationItem[],
  selectedValues: readonly string[],
): InteractiveMigrationSelection {
  const selectableIds = new Set(items.map((item) => item.id));
  const selectedItemIds = new Set(selectedValues.filter((value) => selectableIds.has(value)));
  if (selectedItemIds.size > 0) {
    return { action: "select", selectedItemIds };
  }

  const selectedValueSet = new Set(selectedValues);
  if (selectedValueSet.has(MIGRATION_SELECTION_TOGGLE_ALL_OFF)) {
    return { action: "select", selectedItemIds: new Set() };
  }
  if (selectedValueSet.has(MIGRATION_SELECTION_TOGGLE_ALL_ON)) {
    return { action: "select", selectedItemIds: selectableIds };
  }

  return {
    action: "select",
    selectedItemIds,
  };
}

function isMigrationSelectionToggleValue(value: string): boolean {
  return (
    value === MIGRATION_SELECTION_TOGGLE_ALL_ON || value === MIGRATION_SELECTION_TOGGLE_ALL_OFF
  );
}

function selectedMigrationItemValues(selectedValues: readonly string[]): string[] {
  return selectedValues.filter((value) => !isMigrationSelectionToggleValue(value));
}

function resolveMigrationSelectionBulkToggleValues(
  activatedValue: string | undefined,
  selectableValues: readonly string[],
): string[] | undefined {
  if (activatedValue === MIGRATION_SELECTION_TOGGLE_ALL_ON) {
    return [MIGRATION_SELECTION_TOGGLE_ALL_ON, ...selectableValues];
  }
  if (activatedValue === MIGRATION_SELECTION_TOGGLE_ALL_OFF) {
    return [MIGRATION_SELECTION_TOGGLE_ALL_OFF];
  }
  return undefined;
}

/** Reconciles all/none checkbox toggles for the skill-selection prompt. */
export function reconcileInteractiveMigrationSkillToggleValues(
  selectedValues: readonly string[],
  activatedValue: string | undefined,
  selectableValues: readonly string[],
): string[] {
  const bulkValues = resolveMigrationSelectionBulkToggleValues(activatedValue, selectableValues);
  if (bulkValues !== undefined) {
    return bulkValues;
  }
  if (activatedValue !== undefined && selectableValues.includes(activatedValue)) {
    return selectedMigrationItemValues(selectedValues);
  }
  return selectedValues.filter(
    (value) =>
      value !== MIGRATION_SELECTION_TOGGLE_ALL_ON ||
      !selectedValues.includes(MIGRATION_SELECTION_TOGGLE_ALL_OFF),
  );
}

/** Reconciles Enter-key selection behavior for interactive migration prompts. */
export function reconcileInteractiveMigrationEnterValues(
  selectedValues: readonly string[],
  activatedValue: string | undefined,
  selectableValues: readonly string[],
  opts: { preserveDeselectedActivatedValue?: boolean } = {},
): string[] {
  const bulkValues = resolveMigrationSelectionBulkToggleValues(activatedValue, selectableValues);
  if (bulkValues !== undefined) {
    return bulkValues;
  }
  if (activatedValue !== undefined && selectableValues.includes(activatedValue)) {
    const selectedSelectableValues = selectedMigrationItemValues(selectedValues);
    if (opts.preserveDeselectedActivatedValue && !selectedValues.includes(activatedValue)) {
      return selectedSelectableValues;
    }
    return uniqueStrings([...selectedSelectableValues, activatedValue]);
  }
  return [...selectedValues];
}

/** Reconciles keyboard shortcuts for all/none migration prompt selections. */
export function reconcileInteractiveMigrationShortcutValues(
  previousValues: readonly string[],
  selectedValues: readonly string[],
  selectableValues: readonly string[],
  key: "a" | "i",
): string[] {
  const previousSelectable = previousValues.filter((value) => selectableValues.includes(value));
  if (key === "a" && previousSelectable.length === selectableValues.length) {
    return [MIGRATION_SELECTION_TOGGLE_ALL_OFF];
  }

  const selectedSelectable = selectedValues.filter((value) => selectableValues.includes(value));
  if (selectedSelectable.length === selectableValues.length) {
    return [MIGRATION_SELECTION_TOGGLE_ALL_ON, ...selectableValues];
  }
  if (selectedSelectable.length === 0) {
    return [MIGRATION_SELECTION_TOGGLE_ALL_OFF];
  }
  return selectedSelectable;
}