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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
// Channel setup plugin install tests cover install decisions, registry reloads, scoped snapshots, and trust boundaries.
import fs from "node:fs";
import path from "node:path";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import { createRequireRecord, bundledPluginRoot } from "openclaw/plugin-sdk/test-fixtures";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
import { createColdPluginFixture } from "../../plugins/test-helpers/cold-plugin-fixtures.js";
import { invokePluginArtifactInstallMock } from "../../plugins/test-helpers/install-fixtures.js";
import { expectObjectFields } from "../../test-utils/mock-call-assertions.js";

const installPluginFromNpmSpec = vi.fn();
const resolveNpmSpecMetadata = vi.hoisted(() => vi.fn());
vi.mock("../../infra/install-source-utils.js", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../../infra/install-source-utils.js")>()),
  resolveNpmSpecMetadata,
}));
const applyPluginAutoEnable = vi.fn();
vi.mock("../../plugins/install.js", () => ({
  installPluginFromNpmSpec: (params: Parameters<typeof invokePluginArtifactInstallMock>[1]) =>
    invokePluginArtifactInstallMock(installPluginFromNpmSpec, params),
}));

vi.mock("../../config/plugin-auto-enable.js", () => ({
  applyPluginAutoEnable: (...args: unknown[]) => applyPluginAutoEnable(...args),
}));

const resolveBundledPluginSources = vi.fn();
const getChannelPluginCatalogEntry = vi.fn();
const listChannelPluginCatalogEntries = vi.fn((..._args: unknown[]) => []);
vi.mock("../../channels/plugins/catalog.js", () => {
  return {
    getChannelPluginCatalogEntry: (...args: unknown[]) => getChannelPluginCatalogEntry(...args),
    listRawChannelPluginCatalogEntries: (...args: unknown[]) =>
      listChannelPluginCatalogEntries(...args),
  };
});

const loadPluginManifestRegistryCore = vi.fn();
vi.mock("../../plugins/manifest-registry.js", async (importOriginal) => {
  const actual = await importOriginal<typeof import("../../plugins/manifest-registry.js")>();
  return {
    ...actual,
    loadPluginManifestRegistryCore: (
      params: Parameters<typeof actual.loadPluginManifestRegistryCore>[0],
    ) =>
      // Artifact consent reads real fixtures; setup inventory remains independently mocked.
      params?.discovery
        ? actual.loadPluginManifestRegistryCore(params)
        : loadPluginManifestRegistryCore(params),
  };
});

vi.mock("../../plugins/bundled-sources.js", () => ({
  findBundledPluginSourceInMap: ({
    bundled,
    lookup,
  }: {
    bundled: ReadonlyMap<string, { pluginId: string; localPath: string; npmSpec?: string }>;
    lookup: { kind: "pluginId" | "npmSpec"; value: string };
  }) => {
    const targetValue = lookup.value.trim();
    if (!targetValue) {
      return undefined;
    }
    if (lookup.kind === "pluginId") {
      return bundled.get(targetValue);
    }
    for (const source of bundled.values()) {
      if (source.npmSpec === targetValue) {
        return source;
      }
    }
    return undefined;
  },
  resolveBundledPluginSources: (...args: unknown[]) => resolveBundledPluginSources(...args),
}));

vi.mock("../../plugins/loader.js", () => {
  const load = vi.fn();
  return { loadOpenClawPlugins: load, loadPluginRegistryHandle: load };
});

const discoverOpenClawPlugins = vi.fn((_args?: unknown) => ({
  candidates: [] as PluginCandidate[],
  diagnostics: [],
}));
vi.mock("../../plugins/discovery.js", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../../plugins/discovery.js")>()),
  discoverOpenClawPlugins: (args: unknown) => discoverOpenClawPlugins(args),
}));

import type { ChannelPluginCatalogEntry } from "../../channels/plugins/catalog.js";
import type { OpenClawConfig } from "../../config/config.js";
import type { PluginCandidate } from "../../plugins/discovery.js";
import { PLUGIN_INSTALL_ERROR_CODE } from "../../plugins/install-types.js";
import { loadOpenClawPlugins } from "../../plugins/loader.js";
import type { PluginManifestRecord } from "../../plugins/manifest-registry.js";
import { clearPluginMetadataLifecycleCaches } from "../../plugins/plugin-metadata-lifecycle.js";
import { createEmptyPluginRegistry } from "../../plugins/registry.js";
import { setActivePluginRegistry } from "../../plugins/runtime.js";
import type { WizardPrompter } from "../../wizard/prompts.js";
import { makePrompter, makeRuntime } from "../setup/__tests__/test-utils.js";
import {
  ensureChannelSetupPluginInstalled,
  loadChannelSetupPluginRegistrySnapshotForChannel,
} from "./plugin-install.js";

const bundledChatNpmSpec = "@openclaw/bundled-chat@1.2.3";
const bundledChatIntegrity = "sha512-bundled-chat";
const bundledChatForkNpmSpec = "@vendor/bundled-chat-fork@1.2.3";
const bundledChatForkIntegrity = "sha512-vendor-bundled-chat-fork";
const ORIGINAL_OPENCLAW_STATE_DIR = process.env.OPENCLAW_STATE_DIR;
const tempDirs = useAutoCleanupTempDirTracker(afterEach);

const baseEntry: ChannelPluginCatalogEntry = {
  id: "bundled-chat",
  pluginId: "bundled-chat",
  meta: {
    id: "bundled-chat",
    label: "Bundled Chat",
    selectionLabel: "Bundled Chat",
    docsPath: "/channels/bundled-chat",
    docsLabel: "bundled chat",
    blurb: "Test",
  },
  install: {
    npmSpec: bundledChatNpmSpec,
    localPath: bundledPluginRoot("bundled-chat"),
    expectedIntegrity: bundledChatIntegrity,
  },
};

function mockBundledChatSource() {
  const { localPath } = createLocalPluginFixture();
  resolveBundledPluginSources.mockReturnValue(
    new Map([
      [
        "bundled-chat",
        {
          pluginId: "bundled-chat",
          localPath,
          npmSpec: bundledChatNpmSpec,
        },
      ],
    ]),
  );
  return localPath;
}

function makeSkipInstallPrompter(acceptCapabilities = false) {
  const select = vi.fn((async <T extends string>() => "skip" as T) as WizardPrompter["select"]);
  const confirm = vi.fn(async () => acceptCapabilities);
  const prompter = makePrompter({ select: select as WizardPrompter["select"], confirm });
  return { prompter, select, confirm };
}

function mockActivationOnlyPlugin(plugin: {
  id: string;
  origin?: "bundled" | "global" | "workspace";
}) {
  loadPluginManifestRegistryCore.mockReturnValue({
    plugins: [
      createManifestRecord({
        id: plugin.id,
        ...(plugin.origin === undefined ? {} : { origin: plugin.origin }),
        activation: {
          onChannels: ["external-chat"],
        },
      }),
    ],
    diagnostics: [],
  });
}

function createManifestRecord(
  overrides: Partial<PluginManifestRecord> & Pick<PluginManifestRecord, "id">,
): PluginManifestRecord {
  const { id, ...rest } = overrides;
  return {
    id,
    channels: [],
    providers: [],
    cliBackends: [],
    syntheticAuthRefs: [],
    nonSecretAuthMarkers: [],
    skills: [],
    hooks: [],
    origin: "bundled",
    rootDir: `/tmp/openclaw-test/${id}`,
    source: `/tmp/openclaw-test/${id}/index.ts`,
    manifestPath: `/tmp/openclaw-test/${id}/openclaw.plugin.json`,
    ...rest,
  };
}

function expectSetupSnapshotDoesNotScopeToPlugin(params: {
  cfg: OpenClawConfig;
  runtime: ReturnType<typeof makeRuntime>;
  pluginId: string;
}) {
  loadChannelSetupPluginRegistrySnapshotForChannel({
    cfg: params.cfg,
    runtime: params.runtime,
    channel: "external-chat",
    workspaceDir: "/tmp/openclaw-workspace",
  });

  expect(loadOpenClawPlugins).toHaveBeenCalledTimes(1);
  expect(requireMockCallArg(vi.mocked(loadOpenClawPlugins), 0).onlyPluginIds).toStrictEqual([]);
}

beforeEach(() => {
  resolveNpmSpecMetadata.mockReset().mockRejectedValue(new Error("Unseeded npm metadata query"));
  clearPluginMetadataLifecycleCaches();
  vi.clearAllMocks();
  applyPluginAutoEnable.mockImplementation((params: { config: unknown }) => ({
    config: params.config,
    changes: [],
    autoEnabledReasons: {},
  }));
  resolveBundledPluginSources.mockReturnValue(new Map());
  discoverOpenClawPlugins.mockReturnValue({ candidates: [], diagnostics: [] });
  getChannelPluginCatalogEntry.mockReturnValue(undefined);
  listChannelPluginCatalogEntries.mockReturnValue([]);
  loadPluginManifestRegistryCore.mockReturnValue({ plugins: [], diagnostics: [] });
  setActivePluginRegistry(createEmptyPluginRegistry());
});

afterEach(() => {
  clearPluginMetadataLifecycleCaches();
  if (ORIGINAL_OPENCLAW_STATE_DIR === undefined) {
    delete process.env.OPENCLAW_STATE_DIR;
  } else {
    process.env.OPENCLAW_STATE_DIR = ORIGINAL_OPENCLAW_STATE_DIR;
  }
});

function createLocalPluginFixture(pluginId = "bundled-chat") {
  const workspaceDir = tempDirs.make("openclaw-channel-plugin-");
  const localPath = path.join(workspaceDir, bundledPluginRoot("bundled-chat"));
  fs.mkdirSync(path.join(workspaceDir, ".git"));
  fs.mkdirSync(localPath, { recursive: true });
  const fixture = createColdPluginFixture({
    rootDir: localPath,
    pluginId,
  });
  return { workspaceDir, localPath, runtimeMarker: fixture.runtimeMarker };
}

async function runInitialValueForChannel(channel: "dev" | "beta") {
  const runtime = makeRuntime();
  const select = vi.fn((async <T extends string>() => "skip" as T) as WizardPrompter["select"]);
  const prompter = makePrompter({ select: select as unknown as WizardPrompter["select"] });
  const cfg: OpenClawConfig = { update: { channel } };
  const { workspaceDir } = createLocalPluginFixture();

  await ensureChannelSetupPluginInstalled({
    cfg,
    entry: baseEntry,
    prompter,
    runtime,
    workspaceDir,
  });

  return requireMockCallArg(select, 0).initialValue;
}

function expectPluginLoadedFromLocalPath(
  result: Awaited<ReturnType<typeof ensureChannelSetupPluginInstalled>>,
  expectedPath: string,
) {
  expect(result.installed).toBe(true);
  expect(result.cfg.plugins?.load?.paths).toContain(expectedPath);
}

const requireRecord = createRequireRecord("record", "expected-label-object");

function requireArray(value: unknown, label: string): unknown[] {
  if (!Array.isArray(value)) {
    throw new Error(`expected ${label} to be an array`);
  }
  return value;
}

function expectRecordFields(value: unknown, label: string, expected: Record<string, unknown>) {
  expectObjectFields(requireRecord(value, label), expected);
}

type MockWithCalls = { mock: { calls: unknown[][] } };

function requireMockCallArg(mock: MockWithCalls, callIndex: number, argIndex = 0) {
  return requireRecord(mock.mock.calls[callIndex]?.[argIndex], "mock call argument");
}

function requireSelectOptions(select: MockWithCalls) {
  return requireArray(requireMockCallArg(select, 0).options, "select options");
}

function requireOptionByValue(options: unknown[], value: string) {
  const option = options.find(
    (candidate) => requireRecord(candidate, "select option").value === value,
  );
  return requireRecord(option, `select option ${value}`);
}

function expectLoadOpenClawPluginFields(expected: Record<string, unknown>, callIndex = 0) {
  expectRecordFields(
    requireMockCallArg(vi.mocked(loadOpenClawPlugins), callIndex),
    "loadOpenClawPlugins args",
    expected,
  );
}

describe("ensureChannelSetupPluginInstalled", () => {
  it("installs from npm and enables the plugin", async () => {
    const runtime = makeRuntime();
    const prompter = makePrompter({
      select: vi.fn(async () => "npm") as WizardPrompter["select"],
      confirm: vi.fn(async () => true),
    });
    const cfg: OpenClawConfig = { plugins: { allow: ["bundled-chat"] } };
    installPluginFromNpmSpec.mockResolvedValue({
      ok: true,
      pluginId: "bundled-chat",
      targetDir: "/tmp/bundled-chat",
      extensions: [],
    });

    const result = await ensureChannelSetupPluginInstalled({
      cfg,
      entry: baseEntry,
      prompter,
      runtime,
    });

    expect(result.installed).toBe(true);
    expect(result.cfg.plugins?.entries?.["bundled-chat"]?.enabled).toBe(true);
    expect(result.cfg.plugins?.allow).toContain("bundled-chat");
    expectRecordFields(result.cfg.plugins?.installs?.["bundled-chat"], "plugin install record", {
      source: "npm",
      spec: bundledChatNpmSpec,
      installPath: "/tmp/bundled-chat",
    });
    expectRecordFields(requireMockCallArg(installPluginFromNpmSpec, 0), "npm install args", {
      expectedIntegrity: bundledChatIntegrity,
      spec: bundledChatNpmSpec,
    });
  });

  it("installs npm channel plugins into the active profile extensions dir", async () => {
    const runtime = makeRuntime();
    const prompter = makePrompter({
      select: vi.fn(async () => "npm") as WizardPrompter["select"],
      confirm: vi.fn(async () => true),
    });
    const profileStateDir = tempDirs.make("openclaw-ledger-channel-");
    process.env.OPENCLAW_STATE_DIR = profileStateDir;
    installPluginFromNpmSpec.mockResolvedValue({
      ok: true,
      pluginId: "bundled-chat",
      targetDir: path.join(profileStateDir, "extensions", "bundled-chat"),
      extensions: [],
    });

    await ensureChannelSetupPluginInstalled({
      cfg: {},
      entry: baseEntry,
      prompter,
      runtime,
    });

    expectRecordFields(requireMockCallArg(installPluginFromNpmSpec, 0), "npm install args", {
      extensionsDir: path.resolve(profileStateDir, "extensions"),
      spec: bundledChatNpmSpec,
    });
  });

  it("uses local path when selected", async () => {
    const runtime = makeRuntime();
    const prompter = makePrompter({
      select: vi.fn(async () => "local") as WizardPrompter["select"],
      confirm: vi.fn(async () => true),
    });
    const cfg: OpenClawConfig = {};
    const { workspaceDir, localPath, runtimeMarker } = createLocalPluginFixture();

    const result = await ensureChannelSetupPluginInstalled({
      cfg,
      entry: baseEntry,
      prompter,
      runtime,
      workspaceDir,
    });

    expectPluginLoadedFromLocalPath(result, localPath);
    expect(result.cfg.plugins?.entries?.["bundled-chat"]?.enabled).toBe(true);
    expect(result.cfg.plugins?.installs?.["bundled-chat"]?.acceptedSurface).toBeDefined();
    expect(fs.existsSync(runtimeMarker)).toBe(false);
  });

  it("uses the catalog plugin id for local-path installs", async () => {
    const runtime = makeRuntime();
    const prompter = makePrompter({
      select: vi.fn(async () => "local") as WizardPrompter["select"],
      confirm: vi.fn(async () => true),
    });
    const cfg: OpenClawConfig = {};
    const { workspaceDir } = createLocalPluginFixture("@vendor/external-chat-plugin");

    const result = await ensureChannelSetupPluginInstalled({
      cfg,
      entry: {
        ...baseEntry,
        id: "external-chat",
        pluginId: "@vendor/external-chat-plugin",
      },
      prompter,
      runtime,
      workspaceDir,
    });

    expect(result.installed).toBe(true);
    expect(result.pluginId).toBe("@vendor/external-chat-plugin");
    expect(result.cfg.plugins?.entries?.["@vendor/external-chat-plugin"]?.enabled).toBe(true);
  });

  it("defaults to local on dev channel when local path exists", async () => {
    expect(await runInitialValueForChannel("dev")).toBe("local");
  });

  it("defaults to npm on beta channel even when local path exists", async () => {
    expect(await runInitialValueForChannel("beta")).toBe("npm");
  });

  it.each([
    { beta: "2026.5.4-beta.1", latest: "2026.5.4", selected: "2026.5.4" },
    { beta: "2026.5.5-beta.1", latest: "2026.5.4", selected: "2026.5.5-beta.1" },
  ])(
    "installs $selected on beta while preserving npm intent",
    async ({ beta, latest, selected }) => {
      const runtime = makeRuntime();
      const { prompter, select } = makeSkipInstallPrompter(true);
      const cfg: OpenClawConfig = { update: { channel: "beta" } };
      resolveNpmSpecMetadata.mockImplementation(async ({ spec }: { spec: string }) => {
        const version = spec === "@openclaw/wecom@beta" ? beta : latest;
        expect(["@openclaw/wecom@beta", "@openclaw/wecom@latest"]).toContain(spec);
        const name = "@openclaw/wecom";
        const metadata = { name, version, resolvedSpec: `${name}@${version}` };
        return { ok: true, metadata };
      });
      installPluginFromNpmSpec.mockResolvedValue({
        ok: true,
        pluginId: "wecom-openclaw-plugin",
        targetDir: "/tmp/wecom-openclaw-plugin",
        version: selected,
        npmResolution: {
          name: "@openclaw/wecom",
          version: selected,
          resolvedSpec: `@openclaw/wecom@${selected}`,
        },
      });

      const result = await ensureChannelSetupPluginInstalled({
        cfg,
        entry: {
          id: "wecom",
          pluginId: "wecom-openclaw-plugin",
          meta: {
            id: "wecom",
            label: "WeCom",
            selectionLabel: "WeCom",
            docsPath: "/channels/wecom",
            blurb: "WeCom channel",
          },
          install: {
            npmSpec: "@openclaw/wecom",
          },
        },
        prompter,
        runtime,
        promptInstall: false,
      });

      expect(select).not.toHaveBeenCalled();
      expectRecordFields(requireMockCallArg(installPluginFromNpmSpec, 0), "npm install args", {
        spec: `@openclaw/wecom@${selected}`,
        expectedPluginId: "wecom-openclaw-plugin",
      });
      expect(result.cfg.plugins?.installs?.["wecom-openclaw-plugin"]?.spec).toBe("@openclaw/wecom");
    },
  );

  it("defaults to bundled local path on beta channel when available", async () => {
    const runtime = makeRuntime();
    const { prompter, select } = makeSkipInstallPrompter();
    const cfg: OpenClawConfig = { update: { channel: "beta" } };
    const localPath = mockBundledChatSource();

    await ensureChannelSetupPluginInstalled({
      cfg,
      entry: baseEntry,
      prompter,
      runtime,
    });

    const selectArgs = requireMockCallArg(select, 0);
    expect(selectArgs.initialValue).toBe("local");
    expectRecordFields(
      requireOptionByValue(requireSelectOptions(select), "local"),
      "local option",
      {
        value: "local",
        hint: localPath,
      },
    );
  });

  it("uses the bundled default install source without prompting in non-interactive mode", async () => {
    const runtime = makeRuntime();
    const { prompter, select } = makeSkipInstallPrompter();
    const cfg: OpenClawConfig = { update: { channel: "beta" } };
    mockBundledChatSource();

    const result = await ensureChannelSetupPluginInstalled({
      cfg,
      entry: baseEntry,
      prompter,
      runtime,
      promptInstall: false,
    });

    expect(select).not.toHaveBeenCalled();
    expect(result.installed).toBe(true);
    expect(result.cfg.plugins?.entries?.["bundled-chat"]?.enabled).toBe(true);
    expect(result.cfg.plugins?.load?.paths).toBeUndefined();
    expect(result.cfg.plugins?.installs).toBeUndefined();
  });

  it("does not default to bundled local path when an external catalog overrides the npm spec", async () => {
    const runtime = makeRuntime();
    const { prompter, select } = makeSkipInstallPrompter();
    const cfg: OpenClawConfig = { update: { channel: "beta" } };
    mockBundledChatSource();

    await ensureChannelSetupPluginInstalled({
      cfg,
      entry: {
        id: "bundled-chat",
        meta: {
          id: "bundled-chat",
          label: "Bundled Chat",
          selectionLabel: "Bundled Chat",
          docsPath: "/channels/bundled-chat",
          blurb: "Test",
        },
        install: {
          npmSpec: bundledChatForkNpmSpec,
          expectedIntegrity: bundledChatForkIntegrity,
        },
      },
      prompter,
      runtime,
    });

    const selectArgs = requireMockCallArg(select, 0);
    expect(selectArgs.initialValue).toBe("npm");
    const options = requireSelectOptions(select);
    expect(options).toHaveLength(2);
    expectRecordFields(options[0], "npm option", {
      value: "npm",
      label: `Download from npm (${bundledChatForkNpmSpec})`,
    });
    expectRecordFields(options[1], "skip option", {
      value: "skip",
    });
  });

  it("offers ClawHub as the first-class install source for channel catalog entries", async () => {
    const runtime = makeRuntime();
    const { prompter, select } = makeSkipInstallPrompter();
    const cfg: OpenClawConfig = { update: { channel: "beta" } };
    resolveBundledPluginSources.mockReturnValue(new Map());

    await ensureChannelSetupPluginInstalled({
      cfg,
      entry: {
        id: "clawhub-chat",
        pluginId: "clawhub-chat",
        meta: {
          id: "clawhub-chat",
          label: "ClawHub Chat",
          selectionLabel: "ClawHub Chat",
          docsPath: "/channels/clawhub-chat",
          blurb: "Test",
        },
        install: {
          clawhubSpec: "clawhub:openclaw/clawhub-chat@2026.5.2",
          defaultChoice: "clawhub",
        },
      },
      prompter,
      runtime,
    });

    const selectArgs = requireMockCallArg(select, 0);
    expect(selectArgs.initialValue).toBe("clawhub");
    const options = requireSelectOptions(select);
    expect(options).toHaveLength(2);
    expectRecordFields(options[0], "clawhub option", {
      value: "clawhub",
      label: "Download from ClawHub (clawhub:openclaw/clawhub-chat@2026.5.2)",
    });
    expectRecordFields(options[1], "skip option", {
      value: "skip",
    });
  });

  it.each([
    {
      scenario: "falls back to local path when the npm target is not published",
      code: PLUGIN_INSTALL_ERROR_CODE.NPM_PACKAGE_NOT_FOUND,
      error: "Package not found on npm: @openclaw/bundled-chat@1.2.3",
      fallback: true,
    },
    {
      scenario: "refuses local fallback for an untyped npm error mentioning E404",
      code: undefined,
      error: "E404 while installing a dependency",
      fallback: false,
    },
    {
      scenario: "refuses local fallback after an npm integrity failure",
      code: undefined,
      error: "aborted: npm package integrity drift",
      fallback: false,
    },
    {
      scenario: "refuses local fallback after an npm policy failure",
      code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_BLOCKED,
      error: "Plugin install blocked by policy",
      fallback: false,
    },
  ])("$scenario", async ({ code, error, fallback }) => {
    const runtime = makeRuntime();
    const note = vi.fn(async () => {});
    const confirm = vi.fn(async () => true);
    const prompter = makePrompter({
      select: vi.fn(async () => "npm") as WizardPrompter["select"],
      note,
      confirm,
    });
    const cfg: OpenClawConfig = {};
    const { workspaceDir, localPath } = createLocalPluginFixture();
    installPluginFromNpmSpec.mockResolvedValue({
      ok: false,
      code,
      error,
    });

    const result = await ensureChannelSetupPluginInstalled({
      cfg,
      entry: baseEntry,
      prompter,
      runtime,
      workspaceDir,
    });

    expect(note).toHaveBeenCalled();
    expect(installPluginFromNpmSpec).toHaveBeenCalledOnce();
    if (fallback) {
      expectPluginLoadedFromLocalPath(result, localPath);
      expect(result.cfg.plugins?.installs?.["bundled-chat"]?.acceptedSurface).toBeDefined();
      expect(runtime.error).not.toHaveBeenCalled();
    } else {
      expect(result).toEqual({ cfg, installed: false, pluginId: "bundled-chat", status: "failed" });
      expect(confirm).not.toHaveBeenCalled();
      expect(runtime.error).toHaveBeenCalledWith(`Plugin install failed: ${error}`);
    }
  });

  it.each([true, false])(
    "auto-selects the only npm source but requires capability consent, accepted=%s",
    async (acceptCapabilities) => {
      const runtime = makeRuntime();
      const { prompter, select, confirm } = makeSkipInstallPrompter(acceptCapabilities);
      const cfg: OpenClawConfig = {};
      // npm-only entry (no local path)
      const npmOnlyEntry: ChannelPluginCatalogEntry = {
        id: "wecom",
        pluginId: "wecom-openclaw-plugin",
        meta: {
          id: "wecom",
          label: "WeCom",
          selectionLabel: "WeCom",
          docsPath: "/channels/wecom",
          blurb: "WeCom channel",
        },
        install: {
          npmSpec: "@openclaw/wecom@2026.4.23",
        },
      };
      installPluginFromNpmSpec.mockResolvedValue({
        ok: true,
        pluginId: "wecom-openclaw-plugin",
        targetDir: "/tmp/wecom-openclaw-plugin",
      });
      resolveBundledPluginSources.mockReturnValue(new Map());

      const result = await ensureChannelSetupPluginInstalled({
        cfg,
        entry: npmOnlyEntry,
        prompter,
        runtime,
        autoConfirmSingleSource: true,
      });

      expect(select).not.toHaveBeenCalled();
      expect(confirm).toHaveBeenCalledOnce();
      expect(result.installed).toBe(acceptCapabilities);
      expect(result.pluginId).toBe("wecom-openclaw-plugin");
      if (!acceptCapabilities) {
        expect(result.cfg).toBe(cfg);
        expect(runtime.error).toHaveBeenCalledWith(expect.stringMatching(/capabilit/i));
      }
    },
  );

  it("loads setup snapshots from the auto-enabled config snapshot", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {},
      channels: { "external-chat": { enabled: true } } as never,
    };
    const autoEnabledConfig = {
      ...cfg,
      plugins: {
        entries: {
          "external-chat": { enabled: true },
        },
      },
    } as OpenClawConfig;
    applyPluginAutoEnable.mockReturnValue({
      config: autoEnabledConfig,
      changes: [],
      autoEnabledReasons: {},
    });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expect(applyPluginAutoEnable).toHaveBeenCalledWith({
      config: cfg,
      env: process.env,
    });
    expectLoadOpenClawPluginFields({
      config: autoEnabledConfig,
      activationSourceConfig: cfg,
      autoEnabledReasons: {},
    });
  });

  it("can load a channel-scoped snapshot without activating the global registry", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    getChannelPluginCatalogEntry.mockReturnValue({ pluginId: "@vendor/external-chat-plugin" });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      config: cfg,
      activationSourceConfig: cfg,
      autoEnabledReasons: {},
      workspaceDir: "/tmp/openclaw-workspace",
      cache: false,
      onlyPluginIds: ["@vendor/external-chat-plugin"],
      includeSetupOnlyChannelPlugins: true,
      channelPluginLoadIntent: "setup",
    });
    expect(getChannelPluginCatalogEntry).toHaveBeenCalledWith("external-chat", {
      workspaceDir: "/tmp/openclaw-workspace",
    });
  });

  it("falls back to the bundled plugin for untrusted workspace shadows", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    getChannelPluginCatalogEntry
      .mockReturnValueOnce({ pluginId: "evil-external-chat-shadow", origin: "workspace" })
      .mockReturnValueOnce({ pluginId: "@vendor/external-chat-plugin", origin: "bundled" });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      onlyPluginIds: ["@vendor/external-chat-plugin"],
    });
    expect(getChannelPluginCatalogEntry).toHaveBeenNthCalledWith(1, "external-chat", {
      workspaceDir: "/tmp/openclaw-workspace",
    });
    expect(getChannelPluginCatalogEntry).toHaveBeenNthCalledWith(2, "external-chat", {
      workspaceDir: "/tmp/openclaw-workspace",
      env: undefined,
      excludePluginRefs: [{ pluginId: "evil-external-chat-shadow", origin: "workspace" }],
    });
  });

  it("keeps trusted workspace overrides scoped during setup reloads", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {
        enabled: true,
        allow: ["trusted-external-chat-shadow"],
      },
    };
    getChannelPluginCatalogEntry.mockReturnValue({
      pluginId: "trusted-external-chat-shadow",
      origin: "workspace",
    });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      onlyPluginIds: ["trusted-external-chat-shadow"],
    });
    expect(getChannelPluginCatalogEntry).toHaveBeenCalledTimes(1);
  });

  it("does not widen setup snapshots when no trusted plugin mapping exists", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      onlyPluginIds: [],
    });
  });

  it("scopes snapshots by a unique discovered manifest match when catalog mapping is missing", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    loadPluginManifestRegistryCore.mockReturnValue({
      plugins: [
        createManifestRecord({
          id: "custom-external-chat-plugin",
          channels: ["external-chat"],
        }),
      ],
      diagnostics: [],
    });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      config: cfg,
      activationSourceConfig: cfg,
      autoEnabledReasons: {},
      workspaceDir: "/tmp/openclaw-workspace",
      cache: false,
      onlyPluginIds: ["custom-external-chat-plugin"],
      includeSetupOnlyChannelPlugins: true,
      channelPluginLoadIntent: "setup",
    });
  });

  it("scopes snapshots by activation-declared channel ownership when direct channel lists are empty", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    let sawTrustedCandidate = false;
    discoverOpenClawPlugins.mockReturnValue({
      candidates: [
        {
          idHint: "custom-external-chat-plugin",
          source: "/tmp/openclaw-test/custom-external-chat-plugin/index.ts",
          rootDir: "/tmp/openclaw-test/custom-external-chat-plugin",
          origin: "bundled",
        },
      ],
      diagnostics: [],
    });
    loadPluginManifestRegistryCore.mockImplementation((args: unknown) => {
      if (
        isRecord(args) &&
        args.config === cfg &&
        args.workspaceDir === "/tmp/openclaw-workspace" &&
        Array.isArray(args.candidates)
      ) {
        sawTrustedCandidate ||= args.candidates.some((candidate) => {
          const record = isRecord(candidate) ? candidate : {};
          return record.idHint === "custom-external-chat-plugin" && record.origin === "bundled";
        });
      }
      return {
        plugins: [
          createManifestRecord({
            id: "custom-external-chat-plugin",
            activation: {
              onChannels: ["external-chat"],
            },
          }),
        ],
        diagnostics: [],
      };
    });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      onlyPluginIds: ["custom-external-chat-plugin"],
    });
    expect(sawTrustedCandidate).toBe(true);
  });

  it("uses live manifest discovery for activation-declared setup scoping", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    mockActivationOnlyPlugin({ id: "custom-external-chat-plugin" });

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expect(loadPluginManifestRegistryCore).toHaveBeenCalled();
    expect(
      loadPluginManifestRegistryCore.mock.calls.every(
        ([params]) => !Object.hasOwn(params ?? {}, "cache"),
      ),
    ).toBe(true);
  });

  it("does not trust unconfigured workspace activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    mockActivationOnlyPlugin({
      id: "evil-external-chat-shadow",
      origin: "workspace",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "evil-external-chat-shadow",
    });
  });

  it("does not trust allowlist-excluded bundled activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {
        allow: ["other-plugin"],
      },
    };
    mockActivationOnlyPlugin({
      id: "custom-external-chat-plugin",
      origin: "bundled",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "custom-external-chat-plugin",
    });
  });

  it("does not trust explicitly denied bundled activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {
        deny: ["custom-external-chat-plugin"],
      },
    };
    mockActivationOnlyPlugin({
      id: "custom-external-chat-plugin",
      origin: "bundled",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "custom-external-chat-plugin",
    });
  });

  it("does not trust explicitly disabled workspace activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {
        enabled: true,
        allow: ["evil-external-chat-shadow"],
        entries: {
          "evil-external-chat-shadow": { enabled: false },
        },
      },
    };
    mockActivationOnlyPlugin({
      id: "evil-external-chat-shadow",
      origin: "workspace",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "evil-external-chat-shadow",
    });
  });

  it("does not trust explicitly disabled bundled activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {
      plugins: {
        entries: {
          "custom-external-chat-plugin": { enabled: false },
        },
      },
    };
    mockActivationOnlyPlugin({
      id: "custom-external-chat-plugin",
      origin: "bundled",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "custom-external-chat-plugin",
    });
  });

  it("does not trust unenabled global activation-only channel ownership during setup", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};
    mockActivationOnlyPlugin({
      id: "custom-external-chat-global",
      origin: "global",
    });

    expectSetupSnapshotDoesNotScopeToPlugin({
      cfg,
      runtime,
      pluginId: "custom-external-chat-global",
    });
  });

  it("scopes snapshots by plugin id when channel and plugin ids differ", () => {
    const runtime = makeRuntime();
    const cfg: OpenClawConfig = {};

    loadChannelSetupPluginRegistrySnapshotForChannel({
      cfg,
      runtime,
      channel: "external-chat",
      pluginId: "@vendor/external-chat-plugin",
      workspaceDir: "/tmp/openclaw-workspace",
    });

    expectLoadOpenClawPluginFields({
      config: cfg,
      activationSourceConfig: cfg,
      autoEnabledReasons: {},
      workspaceDir: "/tmp/openclaw-workspace",
      cache: false,
      onlyPluginIds: ["@vendor/external-chat-plugin"],
      includeSetupOnlyChannelPlugins: true,
      channelPluginLoadIntent: "setup",
    });
  });
});