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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
// Channels CLI tests cover channel command registration and option parsing.
import { Command } from "commander";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChannelPluginCatalogEntry } from "../channels/plugins/catalog.js";
import type { PluginPackageChannel } from "../plugins/manifest.js";
import { mockProcessPlatform } from "../test-utils/vitest-spies.js";
import {
  resolveChannelsAddChannelFromArgv,
  resolveChannelsAddOptions,
} from "./channels-cli-add-args.js";
import { registerChannelsCli } from "./channels-cli.js";

const listBundledPackageChannelMetadataMock = vi.hoisted(() =>
  vi.fn<() => readonly PluginPackageChannel[]>(() => []),
);
const listRawChannelPluginCatalogEntriesMock = vi.hoisted(() =>
  vi.fn<() => ChannelPluginCatalogEntry[]>(() => []),
);
const channelsAddCommandMock = vi.hoisted(() =>
  vi.fn<typeof import("../commands/channels.js").channelsAddCommand>(async () => undefined),
);
const channelsLogsCommandMock = vi.hoisted(() =>
  vi.fn(async (_options: { channel?: string }, _runtime: unknown) => undefined),
);
const channelsDeadLettersMocks = vi.hoisted(() => ({
  channelsDeadLettersListCommand: vi.fn(
    async (_options: { account?: string }, _runtime: unknown) => undefined,
  ),
  channelsDeadLettersResubmitCommand: vi.fn(
    async (_eventId: string, _options: { account?: string }, _runtime: unknown) => undefined,
  ),
}));
const channelsResolveCommandMock = vi.hoisted(() => vi.fn(async () => undefined));
const channelsCapabilitiesCommandMock = vi.hoisted(() => vi.fn(async () => undefined));
const channelsRemoveCommandMock = vi.hoisted(() => vi.fn(async () => undefined));
const channelAuthMocks = vi.hoisted(() => ({
  runChannelLogin: vi.fn(async () => undefined),
  runChannelLogout: vi.fn(async () => undefined),
}));
const runtimeMock = vi.hoisted(() => ({
  log: vi.fn(),
  error: vi.fn(),
  exit: vi.fn(),
}));

vi.mock("../plugins/bundled-package-channel-metadata.js", () => ({
  listBundledPackageChannelMetadata: listBundledPackageChannelMetadataMock,
}));

vi.mock("../channels/plugins/catalog.js", () => ({
  listRawChannelPluginCatalogEntries: listRawChannelPluginCatalogEntriesMock,
}));

vi.mock("../commands/channels.js", () => ({
  channelsAddCommand: channelsAddCommandMock,
  channelsLogsCommand: channelsLogsCommandMock,
  channelsResolveCommand: channelsResolveCommandMock,
  channelsCapabilitiesCommand: channelsCapabilitiesCommandMock,
  channelsRemoveCommand: channelsRemoveCommandMock,
}));

vi.mock("../commands/channels/dead-letters.js", () => channelsDeadLettersMocks);

vi.mock("./channel-auth.js", () => channelAuthMocks);

vi.mock("../runtime.js", () => ({
  defaultRuntime: runtimeMock,
}));

function getChannelAddOptionFlags(program: Command): string[] {
  const channels = program.commands.find((command) => command.name() === "channels");
  const add = channels?.commands.find((command) => command.name() === "add");
  return add?.options.map((option) => option.flags) ?? [];
}

function getChannelSubcommandNames(program: Command, parentName: string): string[] {
  const channels = program.commands.find((command) => command.name() === "channels");
  const parent = channels?.commands.find((command) => command.name() === parentName);
  return parent?.commands.map((command) => command.name()) ?? [];
}

async function runChannelsAddCli(args: string[]) {
  const program = new Command().name("openclaw");
  await registerChannelsCli(program, ["node", "openclaw", ...args]);
  await program.parseAsync(args, { from: "user" });
  return program;
}

describe("registerChannelsCli", () => {
  const originalArgv = [...process.argv];

  afterEach(() => {
    process.argv = [...originalArgv];
    vi.restoreAllMocks();
    vi.clearAllMocks();
  });

  it("loads channel-specific add options only for channels add invocations", async () => {
    process.argv = ["node", "openclaw", "channels"];
    await registerChannelsCli(new Command().name("openclaw"));

    expect(listBundledPackageChannelMetadataMock).not.toHaveBeenCalled();
    expect(listRawChannelPluginCatalogEntriesMock).not.toHaveBeenCalled();

    process.argv = ["node", "openclaw", "channels", "add", "clickclack", "--help"];
    await registerChannelsCli(new Command().name("openclaw"));

    expect(listBundledPackageChannelMetadataMock).toHaveBeenCalledTimes(1);
    expect(listRawChannelPluginCatalogEntriesMock).toHaveBeenCalledTimes(1);
  });

  it("registers dead-letter inspection and resubmission commands", async () => {
    const program = new Command().name("openclaw");

    await registerChannelsCli(program);

    expect(getChannelSubcommandNames(program, "dead-letters")).toEqual(["list", "resubmit"]);
  });

  it.each(
    [
      { expected: "ops", label: "parent", leafAccount: undefined, parentAccount: "ops" },
      { expected: "ops", label: "leaf", leafAccount: "ops", parentAccount: undefined },
      { expected: "leaf", label: "leaf precedence", leafAccount: "leaf", parentAccount: "parent" },
      { expected: "", label: "blank parent", leafAccount: undefined, parentAccount: "" },
      { expected: "", label: "blank leaf", leafAccount: "", parentAccount: undefined },
    ].flatMap((accountCase) => [
      { ...accountCase, leaf: "list" as const },
      { ...accountCase, leaf: "resubmit" as const },
    ]),
  )(
    "passes a $label --account to dead-letters $leaf",
    async ({ expected, leaf, leafAccount, parentAccount }) => {
      const args = ["channels", "dead-letters"];
      if (parentAccount !== undefined) {
        args.push("--account", parentAccount);
      }
      args.push(leaf);
      if (leaf === "resubmit") {
        args.push("event-1");
      }
      args.push("--channel", "telegram");
      if (leafAccount !== undefined) {
        args.push("--account", leafAccount);
      }
      const program = new Command().name("openclaw").enablePositionalOptions().exitOverride();

      await registerChannelsCli(program, ["node", "openclaw", ...args]);
      await program.parseAsync(args, { from: "user" });

      const options =
        leaf === "list"
          ? channelsDeadLettersMocks.channelsDeadLettersListCommand.mock.calls[0]?.[0]
          : channelsDeadLettersMocks.channelsDeadLettersResubmitCommand.mock.calls[0]?.[1];
      expect(options?.account).toBe(expected);
    },
  );

  it.each([
    ["omitted", ["channels", "logs"], undefined],
    ["explicit all", ["channels", "logs", "--channel", "all"], "all"],
  ])("distinguishes an %s channels logs filter", async (_label, args, expectedChannel) => {
    const program = new Command().name("openclaw").exitOverride();

    await registerChannelsCli(program, ["node", "openclaw", ...args]);
    await program.parseAsync(args, { from: "user" });

    const optionsCall = channelsLogsCommandMock.mock.calls[0];
    expect(optionsCall).toBeDefined();
    const options = optionsCall![0];
    expect(options?.channel).toBe(expectedChannel);
  });

  it.each(["auto", "user", "group", "channel"])(
    "forwards the supported %s resolve target kind",
    async (kind) => {
      const program = new Command().name("openclaw").exitOverride();
      const args = ["channels", "resolve", "--kind", kind, "room"];

      await registerChannelsCli(program, ["node", "openclaw", ...args]);
      await program.parseAsync(args, { from: "user" });

      expect(channelsResolveCommandMock).toHaveBeenCalledWith(
        expect.objectContaining({ kind, entries: ["room"] }),
        runtimeMock,
      );
    },
  );

  it.each(
    ["add", "capabilities", "login", "logout", "remove", "resolve"].flatMap((leaf) =>
      ["parent", "leaf", "both"].map((position) => ({ leaf, position })),
    ),
  )("forwards the $position --agent option to channels $leaf", async ({ leaf, position }) => {
    const parentArgs =
      position === "leaf" ? [] : ["--agent", position === "both" ? "research" : "ops"];
    const leafArgs = position === "parent" ? [] : ["--agent", "ops"];
    const args = ["channels", ...parentArgs, leaf, ...leafArgs, "--channel", "telegram"];
    if (leaf === "resolve") {
      args.push("room");
    }
    const program = new Command().name("openclaw").enablePositionalOptions().exitOverride();

    await registerChannelsCli(program, ["node", "openclaw", ...args]);
    await program.parseAsync(args, { from: "user" });

    const command = {
      add: channelsAddCommandMock,
      capabilities: channelsCapabilitiesCommandMock,
      login: channelAuthMocks.runChannelLogin,
      logout: channelAuthMocks.runChannelLogout,
      remove: channelsRemoveCommandMock,
      resolve: channelsResolveCommandMock,
    }[leaf];
    expect(command).toHaveBeenCalledWith(
      expect.objectContaining({ agent: "ops" }),
      runtimeMock,
      ...(leaf === "add" ? [{ hasFlags: false }] : leaf === "remove" ? [{ hasFlags: true }] : []),
    );
  });

  it("rejects unsupported resolve target kinds before dispatching", async () => {
    const writeErr = vi.fn();
    const program = new Command().name("openclaw").exitOverride().configureOutput({ writeErr });
    const args = ["channels", "resolve", "--kind", "person", "room"];

    await registerChannelsCli(program, ["node", "openclaw", ...args]);

    await expect(program.parseAsync(args, { from: "user" })).rejects.toMatchObject({
      code: "commander.invalidArgument",
    });
    expect(writeErr).toHaveBeenCalledWith(
      expect.stringContaining("Allowed choices are auto, user, group, channel."),
    );
    expect(channelsResolveCommandMock).not.toHaveBeenCalled();
  });

  it("registers ClickClack setup options before an external channel plugin is installed", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "clickclack",
        cliAddOptions: [
          {
            flags: "--code <code>",
            description: "ClickClack one-time setup code or setup URL",
          },
          {
            flags: "--workspace <workspace>",
            description: "ClickClack workspace id, slug, or name",
          },
        ],
      },
    ]);
    process.argv = ["node", "openclaw", "channels", "add", "clickclack", "--help"];
    const program = new Command().name("openclaw");

    await registerChannelsCli(program);

    expect(getChannelAddOptionFlags(program)).toContain("--code <code>");
    expect(getChannelAddOptionFlags(program)).toContain("--workspace <workspace>");
  });

  it("registers setup options from a non-bundled catalog channel", async () => {
    listRawChannelPluginCatalogEntriesMock.mockReturnValueOnce([
      {
        id: "installed-chat",
        pluginId: "installed-chat",
        origin: "global",
        channel: {
          id: "installed-chat",
          label: "Installed Chat",
          cliAddOptions: [{ flags: "--installed-key <key>", description: "Installed chat key" }],
        },
        meta: {
          id: "installed-chat",
          label: "Installed Chat",
          selectionLabel: "Installed Chat",
          docsPath: "/channels/installed-chat",
          blurb: "Installed test channel.",
        },
        install: { npmSpec: "@openclaw/installed-chat" },
      },
    ]);
    const program = new Command().name("openclaw");

    await registerChannelsCli(program, [
      "node",
      "openclaw",
      "channels",
      "add",
      "--channel",
      "installed-chat",
      "--help",
    ]);

    expect(getChannelAddOptionFlags(program)).toContain("--installed-key <key>");
  });

  it("dedupes options by switch identity across differing value placeholders", async () => {
    listRawChannelPluginCatalogEntriesMock.mockReturnValueOnce([
      {
        id: "chat-a",
        pluginId: "chat-a",
        origin: "global",
        channel: {
          id: "chat-a",
          label: "Chat A",
          cliAddOptions: [
            { flags: "--url <url>", description: "Chat A URL" },
            { flags: "--token <payload>", description: "Chat A token" },
          ],
        },
        meta: {
          id: "chat-a",
          label: "Chat A",
          selectionLabel: "Chat A",
          docsPath: "/channels/chat-a",
          blurb: "Chat A test channel.",
        },
        install: { npmSpec: "@openclaw/chat-a" },
      },
      {
        id: "chat-b",
        pluginId: "chat-b",
        origin: "global",
        channel: {
          id: "chat-b",
          label: "Chat B",
          cliAddOptions: [{ flags: "--url <server>", description: "Chat B server URL" }],
        },
        meta: {
          id: "chat-b",
          label: "Chat B",
          selectionLabel: "Chat B",
          docsPath: "/channels/chat-b",
          blurb: "Chat B test channel.",
        },
        install: { npmSpec: "@openclaw/chat-b" },
      },
    ]);
    const program = new Command().name("openclaw");

    // Commander throws on conflicting switches; registration must survive a
    // plugin redeclaring `--url` with a different placeholder or the static
    // `--token` with a different value name.
    await registerChannelsCli(program, [
      "node",
      "openclaw",
      "channels",
      "add",
      "--channel",
      "chat-a",
      "--help",
    ]);

    const flags = getChannelAddOptionFlags(program);
    expect(flags).toContain("--url <url>");
    expect(flags).not.toContain("--url <server>");
    expect(flags).toContain("--token <payload>");
    expect(flags).not.toContain("--token <token>");
  });

  it("prefers the selected channel's declaration for a shared switch", async () => {
    listRawChannelPluginCatalogEntriesMock.mockReturnValueOnce([
      {
        id: "chat-a",
        pluginId: "chat-a",
        origin: "global",
        channel: {
          id: "chat-a",
          label: "Chat A",
          cliAddOptions: [{ flags: "--url <url>", description: "Chat A URL" }],
        },
        meta: {
          id: "chat-a",
          label: "Chat A",
          selectionLabel: "Chat A",
          docsPath: "/channels/chat-a",
          blurb: "Chat A test channel.",
        },
        install: { npmSpec: "@openclaw/chat-a" },
      },
      {
        id: "chat-b",
        pluginId: "chat-b",
        origin: "global",
        channel: {
          id: "chat-b",
          label: "Chat B",
          cliAddOptions: [{ flags: "--url <server>", description: "Chat B server URL" }],
        },
        meta: {
          id: "chat-b",
          label: "Chat B",
          selectionLabel: "Chat B",
          docsPath: "/channels/chat-b",
          blurb: "Chat B test channel.",
        },
        install: { npmSpec: "@openclaw/chat-b" },
      },
    ]);
    const program = new Command().name("openclaw");

    await registerChannelsCli(program, [
      "node",
      "openclaw",
      "channels",
      "add",
      "--channel",
      "chat-b",
    ]);

    const flags = getChannelAddOptionFlags(program);
    expect(flags).toContain("--url <server>");
    expect(flags).not.toContain("--url <url>");
  });

  it("projects channel-owned setup fields into Commander options", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "signal",
        setup: {
          fields: [
            {
              key: "signalTransport",
              kind: "choice",
              choices: ["external-native", "container"],
              cli: {
                flags: "--signal-transport <kind>",
                description: "Signal transport kind",
              },
            },
            {
              key: "autoDiscover",
              kind: "boolean",
              cli: {
                flags: "--auto-discover",
                negatedFlags: "--no-auto-discover",
                description: "Discover channels automatically",
              },
            },
          ],
        },
      },
    ]);
    process.argv = ["node", "openclaw", "channels", "add", "--channel", "signal", "--help"];
    const program = new Command().name("openclaw");

    await registerChannelsCli(program);

    expect(getChannelAddOptionFlags(program)).toContain("--signal-transport <kind>");
    expect(getChannelAddOptionFlags(program)).toContain("--no-auto-discover");
  });

  it("registers only the positional channel setup options", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--telegram-token <token>", description: "Telegram bot token" },
            },
          ],
        },
      },
      {
        id: "signal",
        setup: {
          fields: [
            {
              key: "signalNumber",
              kind: "string",
              cli: { flags: "--signal-number <e164>", description: "Signal account number" },
            },
          ],
        },
      },
    ]);
    const program = new Command().name("openclaw");

    await registerChannelsCli(program, [
      "node",
      "openclaw",
      "channels",
      "add",
      "telegram",
      "--help",
    ]);

    expect(getChannelAddOptionFlags(program)).toEqual(
      expect.arrayContaining(["--telegram-token <token>"]),
    );
    expect(getChannelAddOptionFlags(program)).not.toEqual(
      expect.arrayContaining(["--signal-number <e164>"]),
    );
  });

  it.each(["--help", "-h"])(
    "keeps generic add help via %s limited to the shared control envelope",
    async (helpFlag) => {
      const program = new Command().name("openclaw");

      await registerChannelsCli(program, ["node", "openclaw", "channels", "add", helpFlag]);

      expect(getChannelAddOptionFlags(program)).toEqual([
        "--channel <name>",
        "--agent <id>",
        "--account <id>",
        "--name <name>",
      ]);
      expect(listBundledPackageChannelMetadataMock).not.toHaveBeenCalled();
    },
  );

  it("registers add help when channels reuse a long flag with different placeholders", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "example",
        setup: {
          fields: [
            {
              key: "apiKey",
              kind: "string",
              cli: { flags: "--api-key <token>", description: "Example API key" },
            },
            {
              key: "apiKeyJson",
              kind: "string",
              cli: { flags: "--api-key <json>", description: "Example API key JSON" },
            },
          ],
        },
      },
    ]);
    process.argv = ["node", "openclaw", "channels", "add", "example", "--help"];
    const program = new Command().name("openclaw");

    await registerChannelsCli(program);

    expect(
      getChannelAddOptionFlags(program).filter((flags) => flags.startsWith("--api-key ")),
    ).toHaveLength(1);
  });

  it("forwards only explicitly supplied setup options", () => {
    const sources = new Map<string, "cli" | "default">([
      ["channel", "cli"],
      ["signalTransport", "cli"],
      ["useEnv", "default"],
    ]);

    expect(
      resolveChannelsAddOptions(
        undefined,
        { channel: "signal", signalTransport: "container", useEnv: false },
        {
          getOptionValueSource: (key) => sources.get(key),
        } as Pick<Command, "getOptionValueSource">,
      ),
    ).toEqual({ channel: "signal", signalTransport: "container" });
  });

  it("preserves selected legacy channel defaults", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "legacy-chat",
        cliAddOptions: [
          {
            flags: "--legacy-mode <mode>",
            description: "Legacy transport mode",
            defaultValue: "socket",
          },
        ],
      },
    ]);

    const program = await runChannelsAddCli([
      "channels",
      "add",
      "--channel",
      "legacy-chat",
      "--token",
      "test-token",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({
        channel: "legacy-chat",
        legacyMode: "socket",
        token: "test-token",
        useEnv: false,
      }),
      runtimeMock,
      { hasFlags: true },
    );
    expect(getChannelAddOptionFlags(program)).not.toContain("--secret-file <path>");
    expect(getChannelAddOptionFlags(program)).not.toContain("--workspace <workspace>");
  });

  it("omits empty legacy integer defaults while still rejecting explicit blanks", async () => {
    const legacyIntChannel = [
      {
        id: "legacy-chat",
        cliAddOptions: [
          {
            flags: "--limit <n>",
            description: "Legacy integer limit",
            defaultValue: "",
            valueType: "int" as const,
          },
        ],
      },
    ];
    listBundledPackageChannelMetadataMock.mockReturnValueOnce(legacyIntChannel);
    listBundledPackageChannelMetadataMock.mockReturnValueOnce(legacyIntChannel);

    await runChannelsAddCli([
      "channels",
      "add",
      "--channel",
      "legacy-chat",
      "--token",
      "test-token",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({
        channel: "legacy-chat",
        token: "test-token",
      }),
      runtimeMock,
      { hasFlags: true },
    );
    const omittedLimitCall = channelsAddCommandMock.mock.calls[0];
    expect(omittedLimitCall).toBeDefined();
    const omittedLimitOpts = omittedLimitCall![0];
    expect(omittedLimitOpts).not.toHaveProperty("limit");

    channelsAddCommandMock.mockClear();
    await runChannelsAddCli([
      "channels",
      "add",
      "--channel",
      "legacy-chat",
      "--token",
      "test-token",
      "--limit",
      "",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({
        channel: "legacy-chat",
        token: "test-token",
        limit: "",
      }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("preserves empty legacy text defaults when the flag is omitted", async () => {
    const legacyTextChannel = [
      {
        id: "legacy-chat",
        cliAddOptions: [
          {
            flags: "--note <text>",
            description: "Legacy optional note",
            defaultValue: "",
          },
        ],
      },
    ];
    listBundledPackageChannelMetadataMock.mockReturnValueOnce(legacyTextChannel);

    await runChannelsAddCli([
      "channels",
      "add",
      "--channel",
      "legacy-chat",
      "--token",
      "test-token",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({
        channel: "legacy-chat",
        token: "test-token",
        note: "",
      }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("uses caller argv instead of raw process argv for channel-specific add options", async () => {
    process.argv = ["node", "openclaw", "channels"];

    await registerChannelsCli(new Command().name("openclaw"), [
      "node",
      "openclaw",
      "channels",
      "add",
      "telegram",
      "--help",
    ]);

    expect(listBundledPackageChannelMetadataMock).toHaveBeenCalledTimes(1);
  });

  it("can force channel-specific add options for completion generation", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "matrix",
        cliAddOptions: [{ flags: "--homeserver <url>", description: "Matrix homeserver URL" }],
      },
    ]);
    process.argv = ["node", "openclaw", "completion", "--write-state"];
    const program = new Command().name("openclaw");

    await registerChannelsCli(program, process.argv, { includeSetupOptions: true });

    expect(listBundledPackageChannelMetadataMock).toHaveBeenCalledTimes(1);
    expect(getChannelAddOptionFlags(program)).toContain("--homeserver <url>");
  });

  it("normalizes Windows launcher argv before channel-specific add option gating", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "matrix",
        cliAddOptions: [{ flags: "--homeserver <url>", description: "Matrix homeserver URL" }],
      },
    ]);
    mockProcessPlatform("win32");
    process.argv = [
      "C:\\Program Files\\nodejs\\node.exe",
      "C:\\Program Files\\nodejs\\node.exe",
      "C:\\repo\\openclaw.js",
      "channels",
      "add",
      "--channel",
      "matrix",
      "--homeserver",
      "https://matrix.example.org",
    ];
    const program = new Command().name("openclaw");

    await registerChannelsCli(program);

    expect(listBundledPackageChannelMetadataMock).toHaveBeenCalledTimes(1);
    expect(getChannelAddOptionFlags(program)).toContain("--homeserver <url>");
  });

  it.each([
    ["positional", ["channels", "add", "telegram"]],
    ["--channel", ["channels", "add", "--channel", "telegram"]],
  ])("keeps selection-only %s channel adds on the guided path", async (_label, args) => {
    await runChannelsAddCli(args);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram" }),
      runtimeMock,
      { hasFlags: false },
    );
  });

  it.each([
    ["token", ["--token", "test-token"]],
    ["token file", ["--token-file", "/tmp/test-token"]],
    ["environment", ["--use-env"]],
    ["account", ["--account", "work"]],
  ])("keeps explicit %s inputs on the direct path", async (_label, extraArgs) => {
    await runChannelsAddCli(["channels", "add", "--channel", "telegram", ...extraArgs]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("registers selected-channel options before Commander parses option-first argv", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--token <token>", description: "Telegram bot token" },
            },
          ],
        },
      },
    ]);

    await runChannelsAddCli(["channels", "add", "--token", "test-token", "--channel", "telegram"]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram", token: "test-token" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it.each([{ parentArgs: ["--agent", "add"] }, { parentArgs: ["--agent=add"] }])(
    "registers setup flags after parent owner options $parentArgs",
    async ({ parentArgs }) => {
      await runChannelsAddCli([
        "channels",
        ...parentArgs,
        "add",
        "--channel",
        "telegram",
        "--token",
        "fixture-token",
      ]);

      expect(channelsAddCommandMock).toHaveBeenCalledWith(
        expect.objectContaining({ agent: "add", channel: "telegram", token: "fixture-token" }),
        runtimeMock,
        { hasFlags: true },
      );
    },
  );

  it("prefers modern contract options when a channel also publishes cliAddOptions", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValue([
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--token <token>", description: "Telegram bot token" },
            },
          ],
        },
        cliAddOptions: [{ flags: "--legacy-token <token>", description: "Retained legacy switch" }],
      },
    ]);

    const program = new Command().name("openclaw");
    const argv = ["channels", "add", "telegram", "--token", "test-token"];
    await registerChannelsCli(program, ["node", "openclaw", ...argv]);
    const flags = getChannelAddOptionFlags(program);
    expect(flags).toContain("--token <token>");
    expect(flags).not.toContain("--legacy-token <token>");

    await program.parseAsync(argv, { from: "user" });
    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram", token: "test-token" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("resolves a positional channel after a value-taking channel option", async () => {
    const metadata: PluginPackageChannel[] = [
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--token <token>", description: "Telegram bot token" },
            },
          ],
        },
      },
    ];
    listBundledPackageChannelMetadataMock
      .mockReturnValueOnce(metadata)
      .mockReturnValueOnce(metadata);

    await runChannelsAddCli(["channels", "add", "--token", "tok", "telegram"]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram", token: "tok" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("resolves a positional channel after a boolean channel option", async () => {
    const metadata: PluginPackageChannel[] = [
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "useEnv",
              kind: "boolean",
              cli: { flags: "--use-env", description: "Use Telegram environment credentials" },
            },
          ],
        },
      },
    ];
    listBundledPackageChannelMetadataMock
      .mockReturnValueOnce(metadata)
      .mockReturnValueOnce(metadata);

    await runChannelsAddCli(["channels", "add", "--use-env", "telegram"]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram", useEnv: true }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("keeps an all-channel-unknown flag before a positional channel ambiguous", async () => {
    await expect(
      resolveChannelsAddChannelFromArgv([
        "node",
        "openclaw",
        "channels",
        "add",
        "--unknown-option",
        "value",
        "telegram",
      ]),
    ).resolves.toBeUndefined();
  });

  it("keeps conflicting all-channel flag arities before a positional channel ambiguous", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "chat-a",
        setup: {
          fields: [
            {
              key: "mode",
              kind: "string",
              cli: { flags: "--mode <mode>", description: "Chat A mode" },
            },
          ],
        },
      },
      {
        id: "chat-b",
        setup: {
          fields: [
            {
              key: "mode",
              kind: "boolean",
              cli: { flags: "--mode", description: "Enable Chat B mode" },
            },
          ],
        },
      },
    ]);

    await expect(
      resolveChannelsAddChannelFromArgv([
        "node",
        "openclaw",
        "channels",
        "add",
        "--mode",
        "telegram",
      ]),
    ).resolves.toBeUndefined();
  });

  it("finds a positional channel after shared option-value pairs", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--token <token>", description: "Telegram bot token" },
            },
          ],
        },
      },
    ]);

    await runChannelsAddCli(["channels", "add", "--account", "work", "telegram", "--token", "tok"]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "telegram", account: "work", token: "tok" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("lets an explicit channel override the positional channel during option registration", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "telegram",
        setup: {
          fields: [
            {
              key: "token",
              kind: "string",
              cli: { flags: "--token <token>", description: "Telegram bot token" },
            },
          ],
        },
      },
      {
        id: "signal",
        setup: {
          fields: [
            {
              key: "signalNumber",
              kind: "string",
              cli: { flags: "--signal-number <e164>", description: "Signal account number" },
            },
          ],
        },
      },
    ]);

    await runChannelsAddCli([
      "channels",
      "add",
      "telegram",
      "--channel",
      "signal",
      "--signal-number",
      "+15555550123",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "signal", signalNumber: "+15555550123" }),
      runtimeMock,
      { hasFlags: true },
    );
  });

  it("treats plugin-provided config flags as direct automation inputs", async () => {
    listBundledPackageChannelMetadataMock.mockReturnValueOnce([
      {
        id: "matrix",
        cliAddOptions: [{ flags: "--homeserver <url>", description: "Matrix homeserver URL" }],
      },
    ]);

    await runChannelsAddCli([
      "channels",
      "add",
      "--channel",
      "matrix",
      "--homeserver",
      "https://matrix.example.org",
    ]);

    expect(channelsAddCommandMock).toHaveBeenCalledWith(
      expect.objectContaining({ channel: "matrix", homeserver: "https://matrix.example.org" }),
      runtimeMock,
      { hasFlags: true },
    );
  });
});