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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
// Tests CLI dispatch arguments and runtime selection for agent runner turns.
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
import { withTestAdmittedRunContext } from "../../agents/admitted-run-context.test-support.js";
import { createCliTimeoutError } from "../../agents/cli-runner/no-output-timeout-policy.js";
import { clearCliSessionInStore } from "../../agents/cli-session-store.js";
import type { EmbeddedAgentRunResult } from "../../agents/embedded-agent-runner/types.js";
import { createAgentRunRestartAbortError } from "../../agents/run-termination.js";
import { loadSessionEntry, replaceSessionEntry } from "../../config/sessions/session-accessor.js";
import {
  emitAgentEvent,
  getAgentEventLifecycleGeneration,
  onAgentEvent,
  resetAgentEventsForTest,
} from "../../infra/agent-events.js";
import {
  createCliToolSummaryTracker,
  keepCliSessionBindingOnlyWhenReused,
  runCliAgentWithLifecycle as runCliAgentWithLifecycleProduction,
} from "./agent-runner-cli-dispatch.js";

type ProductionLifecycleParams = Parameters<typeof runCliAgentWithLifecycleProduction>[0];
type RunCliAgentWithLifecycleParams = Omit<ProductionLifecycleParams, "runParams"> & {
  runParams: Omit<ProductionLifecycleParams["runParams"], "admittedRunContext">;
};
const runCliAgentWithLifecycle = (params: RunCliAgentWithLifecycleParams) =>
  runCliAgentWithLifecycleProduction({
    ...params,
    runParams: withTestAdmittedRunContext(params.runParams),
  });
type ReasoningTextPayload = Parameters<
  NonNullable<RunCliAgentWithLifecycleParams["onReasoningText"]>
>[0];
type ReasoningProgressPayload = Parameters<
  NonNullable<RunCliAgentWithLifecycleParams["onReasoningProgress"]>
>[0];

const cliDispatchState = vi.hoisted(() => ({
  runCliAgentMock: vi.fn(),
}));
const tempDirs = useAutoCleanupTempDirTracker(afterEach);

vi.mock("../../agents/cli-runner.js", () => ({
  runCliAgent: (...args: unknown[]) => cliDispatchState.runCliAgentMock(...args),
}));

afterEach(() => {
  vi.useRealTimers();
  resetAgentEventsForTest();
  cliDispatchState.runCliAgentMock.mockReset();
});

describe("runCliAgentWithLifecycle", () => {
  it("bridges completed CLI compaction lifecycles to reply callbacks", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "compaction",
        data: { phase: "start", backend: "claude-cli" },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "compaction",
        data: { phase: "end", backend: "claude-cli", completed: false },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "compaction",
        data: { phase: "start", backend: "claude-cli" },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "compaction",
        data: { phase: "end", backend: "claude-cli", completed: true },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });
    const callbacks: string[] = [];

    await runCliAgentWithLifecycle({
      runId: "run-compaction-bridge",
      provider: "claude-cli",
      onCompactionStart: async () => {
        callbacks.push("start");
      },
      onCompactionEnd: async (payload) => {
        callbacks.push(payload?.completed === false ? "incomplete" : "end");
      },
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude-opus-4-8",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-compaction-bridge",
      },
    });

    expect(callbacks).toEqual(["start", "incomplete", "start", "end"]);
  });

  it("bridges typed CLI plan events", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "plan",
        data: {
          phase: "update",
          title: "Plan updated",
          source: "codex-exec",
          steps: [
            { step: "Inspect", status: "completed" },
            { step: "Patch", status: "pending" },
          ],
        },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });
    const onPlanUpdate = vi.fn(async () => undefined);

    await runCliAgentWithLifecycle({
      runId: "run-plan-bridge",
      provider: "codex-cli",
      onPlanUpdate,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "codex-cli",
        model: "codex",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-plan-bridge",
      },
    });

    expect(onPlanUpdate).toHaveBeenCalledWith({
      phase: "update",
      title: "Plan updated",
      explanation: undefined,
      source: "codex-exec",
      steps: [
        { step: "Inspect", status: "completed" },
        { step: "Patch", status: "pending" },
      ],
    });
  });

  it("normalizes shipped string-step plan events to pending typed steps", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "plan",
        data: {
          phase: "update",
          title: "Plan updated",
          source: "codex-exec",
          steps: ["Inspect", "  ", "Patch"],
        },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });
    const onPlanUpdate = vi.fn(async () => undefined);

    await runCliAgentWithLifecycle({
      runId: "run-plan-legacy",
      provider: "codex-cli",
      onPlanUpdate,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "codex-cli",
        model: "codex",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-plan-legacy",
      },
    });

    expect(onPlanUpdate).toHaveBeenCalledWith(
      expect.objectContaining({
        steps: [
          { step: "Inspect", status: "pending" },
          { step: "Patch", status: "pending" },
        ],
      }),
    );
  });

  it("bridges thinking events to reasoning text and dedupes identical snapshots", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Thinking", delta: "Thinking", isReasoningSnapshot: true },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Thinking", delta: "", isReasoningSnapshot: true },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Thinking more", delta: " more", isReasoningSnapshot: true },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "assistant",
        data: { text: "Visible answer", delta: "Visible answer" },
      });
      return { payloads: [{ text: "Visible answer" }], meta: { durationMs: 1 } };
    });
    const onReasoningText = vi.fn<(payload: ReasoningTextPayload) => Promise<void>>(
      async () => undefined,
    );

    const result = await runCliAgentWithLifecycle({
      runId: "run-thinking-bridge",
      provider: "claude-cli",
      onReasoningText,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-thinking-bridge",
      },
    });

    expect(onReasoningText).toHaveBeenCalledTimes(2);
    expect(onReasoningText.mock.calls.map((call) => call[0])).toEqual([
      { text: "Thinking", isReasoningSnapshot: true },
      { text: "Thinking more", isReasoningSnapshot: true },
    ]);
    expect(result.payloads).toEqual([
      { text: "Thinking more", isReasoning: true },
      { text: "Visible answer" },
    ]);
  });

  it("keeps durable reasoning when the CLI has no visible final answer", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Only thinking", delta: "Only thinking", isReasoningSnapshot: true },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Only thinking more", delta: " more", isReasoningSnapshot: true },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });

    const result = await runCliAgentWithLifecycle({
      runId: "run-thinking-without-answer",
      provider: "claude-cli",
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-thinking-without-answer",
      },
    });

    expect(result.payloads).toEqual([{ text: "Only thinking more", isReasoning: true }]);
  });

  it("bridges thinking token progress without adding durable reasoning", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 50 },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 50 },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 200 },
      });
      return { payloads: [{ text: "Visible answer" }], meta: { durationMs: 1 } };
    });
    const onReasoningProgress = vi.fn<(payload: ReasoningProgressPayload) => Promise<void>>(
      async () => undefined,
    );

    const result = await runCliAgentWithLifecycle({
      runId: "run-thinking-progress",
      provider: "claude-cli",
      onReasoningProgress,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-thinking-progress",
      },
    });

    expect(onReasoningProgress.mock.calls.map((call) => call[0])).toEqual([
      { progressTokens: 50 },
      { progressTokens: 200 },
    ]);
    expect(result.payloads).toEqual([{ text: "Visible answer" }]);
  });

  it("stamps onActivity for every delivered bridge event, including reasoning-only progress", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 50 },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 50 },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 200 },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });
    const onActivity = vi.fn();
    const onReasoningProgress = vi.fn<(payload: ReasoningProgressPayload) => Promise<void>>(
      async () => undefined,
    );

    await runCliAgentWithLifecycle({
      runId: "run-activity-reasoning-progress",
      provider: "claude-cli",
      onActivity,
      onReasoningProgress,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-activity-reasoning-progress",
      },
    });

    // A run in a long pure-reasoning stretch must keep stamping activity, or
    // stale-takeover reclaims it while it is visibly thinking. Stamps are
    // per-event (delivery-independent), so dedupe downstream does not matter.
    expect(onReasoningProgress).toHaveBeenCalledTimes(2);
    expect(onActivity).toHaveBeenCalledTimes(3);
  });

  it("keeps stamping onActivity when bridges are suppressed for silent runs", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { progressTokens: 50 },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "assistant",
        data: { text: "Silent answer", delta: "Silent answer" },
      });
      return { payloads: [], meta: { durationMs: 1 } };
    });
    const onActivity = vi.fn();
    const onAssistantText = vi.fn<(text: string) => Promise<void>>(async () => undefined);
    const onReasoningProgress = vi.fn<(payload: ReasoningProgressPayload) => Promise<void>>(
      async () => undefined,
    );

    await runCliAgentWithLifecycle({
      runId: "run-activity-suppressed",
      provider: "claude-cli",
      suppressAssistantBridge: true,
      onActivity,
      onAssistantText,
      onReasoningProgress,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-activity-suppressed",
      },
    });

    // silentExpected runs suppress deliveries, but their events are still real
    // liveness evidence — without these stamps a healthy silent run would be
    // reclaimed as run_stalled at the takeover window.
    expect(onAssistantText).not.toHaveBeenCalled();
    expect(onReasoningProgress).not.toHaveBeenCalled();
    expect(onActivity).toHaveBeenCalledTimes(2);
  });

  it("stamps onActivity for assistant text without caller callbacks for that stream", async () => {
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async (params: { runId: string }) => {
      emitAgentEvent({
        runId: params.runId,
        stream: "thinking",
        data: { text: "Deep thought", delta: "Deep thought", isReasoningSnapshot: true },
      });
      emitAgentEvent({
        runId: params.runId,
        stream: "assistant",
        data: { text: "Visible answer", delta: "Visible answer" },
      });
      return { payloads: [{ text: "Visible answer" }], meta: { durationMs: 1 } };
    });
    const onActivity = vi.fn();
    const onAssistantText = vi.fn<(text: string) => Promise<void>>(async () => undefined);

    await runCliAgentWithLifecycle({
      runId: "run-activity-assistant",
      provider: "claude-cli",
      onActivity,
      onAssistantText,
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-activity-assistant",
      },
    });

    // Every real event stamps, independent of which callbacks are registered.
    expect(onAssistantText).toHaveBeenCalledTimes(1);
    expect(onActivity).toHaveBeenCalledTimes(2);
  });

  it("does not add a durable reasoning payload when the CLI emits no thinking", async () => {
    cliDispatchState.runCliAgentMock.mockResolvedValueOnce({
      payloads: [{ text: "Visible answer" }],
      meta: { durationMs: 1 },
    } satisfies EmbeddedAgentRunResult);

    const result = await runCliAgentWithLifecycle({
      runId: "run-no-thinking",
      provider: "claude-cli",
      runParams: {
        sessionId: "session-1",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "hello",
        provider: "claude-cli",
        model: "claude",
        thinkLevel: "high",
        timeoutMs: 1_000,
        runId: "run-no-thinking",
      },
    });

    expect(result.payloads).toEqual([{ text: "Visible answer" }]);
  });

  it("keeps the captured lifecycle generation on start and terminal events", async () => {
    const events: Array<{
      stream?: string;
      lifecycleGeneration?: string;
      agentId?: string;
      data?: Record<string, unknown>;
    }> = [];
    const lifecycleGeneration = getAgentEventLifecycleGeneration();
    const stop = onAgentEvent((event) => {
      if (event.runId === "run-before-restart") {
        events.push(event);
      }
    });
    cliDispatchState.runCliAgentMock.mockResolvedValueOnce({
      payloads: [],
      meta: { durationMs: 1 },
    } satisfies EmbeddedAgentRunResult);

    try {
      await runCliAgentWithLifecycle({
        runId: "run-before-restart",
        lifecycleGeneration,
        startedAt: 1_000,
        provider: "claude-cli",
        runParams: {
          sessionId: "session-1",
          agentId: "support",
          sessionFile: "/tmp/session.jsonl",
          workspaceDir: "/tmp/workspace",
          prompt: "hello",
          provider: "claude-cli",
          model: "claude",
          thinkLevel: "off",
          timeoutMs: 1_000,
          runId: "run-before-restart",
        },
      });
    } finally {
      stop();
    }

    const lifecycleEvents = events.filter((event) => event.stream === "lifecycle");
    expect(lifecycleEvents).toHaveLength(2);
    expect(
      lifecycleEvents.every((event) => event.lifecycleGeneration === lifecycleGeneration),
    ).toBe(true);
    expect(lifecycleEvents.every((event) => event.agentId === "support")).toBe(true);
    expect(lifecycleEvents.every((event) => event.data?.startedAt === 1_000)).toBe(true);
  });

  it("preserves restart ownership when the CLI resolves after cancellation", async () => {
    const events: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
    const stop = onAgentEvent((event) => {
      if (event.runId === "run-restart") {
        events.push(event);
      }
    });
    const controller = new AbortController();
    cliDispatchState.runCliAgentMock.mockImplementationOnce(async () => {
      controller.abort(createAgentRunRestartAbortError());
      return {
        payloads: [{ text: "stale result" }],
        meta: { durationMs: 1 },
      } satisfies EmbeddedAgentRunResult;
    });

    await expect(
      runCliAgentWithLifecycle({
        runId: "run-restart",
        provider: "claude-cli",
        runParams: {
          sessionId: "session-1",
          sessionFile: "/tmp/session.jsonl",
          workspaceDir: "/tmp/workspace",
          prompt: "hello",
          provider: "claude-cli",
          model: "claude",
          thinkLevel: "off",
          timeoutMs: 1_000,
          runId: "run-restart",
          abortSignal: controller.signal,
        },
      }),
    ).rejects.toThrow("agent run aborted for restart");
    stop();

    const terminal = events.find(
      (event) => event.stream === "lifecycle" && event.data?.phase === "error",
    );
    expect(terminal?.data).toMatchObject({
      aborted: true,
      stopReason: "restart",
    });
    expect(events.some((event) => event.stream === "assistant")).toBe(false);
  });

  it("attributes a structured CLI watchdog timeout on the terminal event", async () => {
    const events: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
    const stop = onAgentEvent((event) => {
      if (event.runId === "run-timeout") {
        events.push(event);
      }
    });
    cliDispatchState.runCliAgentMock.mockRejectedValueOnce(
      createCliTimeoutError(
        { provider: "claude-cli", model: "claude", sessionId: "session-1" },
        {
          mode: "no-output",
          timeoutSeconds: 1,
          observedActivity: false,
          activeToolCount: 0,
          backgroundTaskCount: 0,
        },
      ),
    );

    await expect(
      runCliAgentWithLifecycle({
        runId: "run-timeout",
        provider: "claude-cli",
        runParams: {
          sessionId: "session-1",
          sessionFile: "/tmp/session.jsonl",
          workspaceDir: "/tmp/workspace",
          prompt: "hello",
          provider: "claude-cli",
          model: "claude",
          thinkLevel: "off",
          timeoutMs: 1_000,
          runId: "run-timeout",
        },
      }),
    ).rejects.toThrow("CLI produced no output");
    stop();

    expect(
      events.find((event) => event.stream === "lifecycle" && event.data?.phase === "error")?.data,
    ).toMatchObject({
      stopReason: "timeout",
      timeoutPhase: "provider",
    });
  });

  it("propagates yielded result metadata on lifecycle end", async () => {
    const events: Array<{ stream?: string; data?: Record<string, unknown> }> = [];
    const stop = onAgentEvent((event) => {
      if (event.runId === "run-yielded") {
        events.push(event);
      }
    });
    cliDispatchState.runCliAgentMock.mockResolvedValueOnce({
      payloads: [],
      meta: {
        durationMs: 1,
        yielded: true,
        livenessState: "paused",
        stopReason: "end_turn",
      },
    } satisfies EmbeddedAgentRunResult);

    try {
      await runCliAgentWithLifecycle({
        runId: "run-yielded",
        provider: "claude-cli",
        runParams: {
          sessionId: "session-1",
          sessionFile: "/tmp/session.jsonl",
          workspaceDir: "/tmp/workspace",
          prompt: "hello",
          provider: "claude-cli",
          model: "claude",
          thinkLevel: "off",
          timeoutMs: 1_000,
          runId: "run-yielded",
        },
      });
    } finally {
      stop();
    }

    const terminal = events.find(
      (event) => event.stream === "lifecycle" && event.data?.phase === "end",
    );
    expect(terminal?.data).toMatchObject({
      yielded: true,
      livenessState: "paused",
      stopReason: "end_turn",
    });
  });
});

describe("keepCliSessionBindingOnlyWhenReused", () => {
  it("keeps the first room-event CLI binding when no binding exists yet", () => {
    const result = {
      payloads: [],
      meta: {
        durationMs: 1,
        agentMeta: {
          sessionId: "new-cli-session",
          provider: "claude-cli",
          model: "claude-opus-4-8",
          cliSessionBinding: {
            sessionId: "new-cli-session",
            authProfileId: "profile",
          },
        },
      },
    } satisfies EmbeddedAgentRunResult;

    expect(keepCliSessionBindingOnlyWhenReused({ result })).toBe(result);
  });

  it("drops a replacement room-event CLI binding when an existing binding was reused", () => {
    const onDroppedReplacement = vi.fn();
    const result = keepCliSessionBindingOnlyWhenReused({
      existingSessionId: "existing-cli-session",
      onDroppedReplacement,
      result: {
        payloads: [],
        meta: {
          durationMs: 1,
          agentMeta: {
            sessionId: "replacement-cli-session",
            provider: "claude-cli",
            model: "claude-opus-4-8",
            cliSessionBinding: {
              sessionId: "replacement-cli-session",
              authProfileId: "profile",
            },
          },
        },
      } satisfies EmbeddedAgentRunResult,
    });

    expect(onDroppedReplacement).toHaveBeenCalledOnce();
    expect(result.meta.agentMeta?.sessionId).toBe("");
    expect(result.meta.agentMeta?.cliSessionBinding).toBeUndefined();
  });
});

describe("clearCliSessionInStore", () => {
  it.each(["current", "closed"])(
    "clears active and stored entries only for a %s owner",
    async (owner) => {
      const activeEntry = {
        sessionId: "openclaw-active",
        updatedAt: 1,
        cliSessionBindings: { "claude-cli": { sessionId: "stale-session" } },
        cliSessionIds: { "claude-cli": "stale-session" },
        claudeCliSessionId: "stale-session",
      };
      const storedEntry = structuredClone(activeEntry);
      const storePath = path.join(tempDirs.make("cli-session-cleanup-"), "sessions.json");
      await replaceSessionEntry({ storePath, sessionKey: "main" }, structuredClone(activeEntry));

      let open = true;
      const clear = clearCliSessionInStore({
        provider: "claude-cli",
        expectedCliSessionId: "stale-session",
        expectedSessionId: activeEntry.sessionId,
        sessionKey: "main",
        sessionStore: { main: storedEntry },
        storePath,
        activeSessionEntry: activeEntry,
        assertCommitAllowed: () => {
          if (!open) {
            throw new Error("owner closed");
          }
        },
      });
      if (owner === "closed") {
        open = false;
        await expect(clear).rejects.toThrow("owner closed");
        for (const entry of [
          activeEntry,
          storedEntry,
          loadSessionEntry({ storePath, sessionKey: "main" }),
        ]) {
          expect(entry?.cliSessionBindings?.["claude-cli"]?.sessionId).toBe("stale-session");
        }
        return;
      }
      await clear;

      for (const entry of [activeEntry, storedEntry]) {
        expect(entry.cliSessionBindings?.["claude-cli"]).toBeUndefined();
        expect(entry.cliSessionIds?.["claude-cli"]).toBeUndefined();
        expect(entry.claudeCliSessionId).toBeUndefined();
        expect(entry.updatedAt).toBeGreaterThan(1);
      }
      const persisted = loadSessionEntry({ storePath, sessionKey: "main" });
      expect(persisted?.cliSessionBindings?.["claude-cli"]).toBeUndefined();
      expect(persisted?.cliSessionIds?.["claude-cli"]).toBeUndefined();
      expect(persisted?.claudeCliSessionId).toBeUndefined();
    },
  );

  it("does not clear a replacement binding adopted by another turn", async () => {
    const entry = {
      sessionId: "openclaw-active",
      updatedAt: 1,
      cliSessionBindings: { "claude-cli": { sessionId: "replacement-session" } },
      cliSessionIds: { "claude-cli": "replacement-session" },
      claudeCliSessionId: "replacement-session",
    };

    await clearCliSessionInStore({
      provider: "claude-cli",
      expectedCliSessionId: "stale-session",
      activeSessionEntry: entry,
    });

    expect(entry.cliSessionBindings["claude-cli"].sessionId).toBe("replacement-session");
    expect(entry.cliSessionIds["claude-cli"]).toBe("replacement-session");
    expect(entry.claudeCliSessionId).toBe("replacement-session");
    expect(entry.updatedAt).toBe(1);
  });
});

describe("createCliToolSummaryTracker", () => {
  const startEvent = {
    name: "exec",
    phase: "start" as const,
    args: { command: "date -u" },
    toolCallId: "tool-1",
  };
  const resultEvent = {
    name: "exec",
    phase: "result" as const,
    args: undefined,
    toolCallId: "tool-1",
    isError: false,
    result: { content: [{ type: "text", text: "Wed Jun 10 2026" }] },
  };

  it.each(["exec", "server.exec"])(
    "delivers a safe %s summary using metadata captured at start",
    async (name) => {
      const deliver = vi.fn();
      const tracker = createCliToolSummaryTracker({
        commandDetailsVisible: false,
        shouldEmitToolResult: () => true,
        shouldEmitToolOutput: () => false,
        deliver,
      });
      await tracker.noteToolEvent({ ...startEvent, name });
      const commandBearing = await tracker.noteToolEvent({ ...resultEvent, name });
      expect(commandBearing).toBe(true);
      expect(deliver).toHaveBeenCalledTimes(1);
      const payload = deliver.mock.calls[0]?.[0] as { text: string; isError?: boolean };
      expect(payload.text).toContain(name === "exec" ? "Exec" : "Server.exec");
      expect(payload.text).not.toContain("date -u");
      expect(payload.text).not.toContain("Wed Jun 10 2026");
      expect(payload.isError).toBeUndefined();
    },
  );

  it("appends the tool output block when full verbose output is enabled", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: true,
      shouldEmitToolResult: () => true,
      shouldEmitToolOutput: () => true,
      deliver,
    });
    await tracker.noteToolEvent(startEvent);
    await tracker.noteToolEvent(resultEvent);
    const payload = deliver.mock.calls[0]?.[0] as { text: string };
    expect(payload.text).toContain("```txt");
    expect(payload.text).toContain("Wed Jun 10 2026");
  });

  it("renders top-level structured CLI results in full verbose output", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: true,
      shouldEmitToolResult: () => true,
      shouldEmitToolOutput: () => true,
      deliver,
    });
    await tracker.noteToolEvent(startEvent);
    await tracker.noteToolEvent({
      ...resultEvent,
      result: [{ type: "web_search_result", title: "OpenClaw", url: "https://example.com" }],
    });

    const payload = deliver.mock.calls[0]?.[0] as { text: string };
    expect(payload.text).toContain('"type":"web_search_result"');
    expect(payload.text).toContain('"title":"OpenClaw"');
  });

  it("emits nothing while tool summaries are disabled", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: false,
      shouldEmitToolResult: () => false,
      shouldEmitToolOutput: () => false,
      deliver,
    });
    await tracker.noteToolEvent(startEvent);
    await tracker.noteToolEvent(resultEvent);
    expect(deliver).not.toHaveBeenCalled();
  });

  it("leaves plan tools to the authoritative plan event instead of summarizing arguments", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: true,
      shouldEmitToolResult: () => true,
      shouldEmitToolOutput: () => true,
      deliver,
    });
    await tracker.noteToolEvent({
      name: "progress_card",
      phase: "start",
      args: {
        markdown: '<progress aria-label="CI · 2/3" value="2" max="3"></progress>',
      },
      toolCallId: "plan-1",
    });
    await tracker.noteToolEvent({
      name: "progress_card",
      phase: "result",
      args: undefined,
      toolCallId: "plan-1",
      isError: false,
      result: { content: [{ type: "text", text: "Progress card updated" }] },
    });

    expect(deliver).not.toHaveBeenCalled();
  });

  it.each([false, true])(
    "keeps card errors visible without arguments (full output: %s)",
    async (fullOutput) => {
      const deliver = vi.fn();
      const tracker = createCliToolSummaryTracker({
        commandDetailsVisible: false,
        shouldEmitToolResult: () => true,
        shouldEmitToolOutput: () => fullOutput,
        deliver,
      });
      await tracker.noteToolEvent({
        name: "progress_card",
        phase: "start",
        args: { markdown: '<progress aria-label="private" value="1" max="2"></progress>' },
        toolCallId: "plan-error",
      });
      await tracker.noteToolEvent({
        name: undefined,
        phase: "result",
        args: undefined,
        toolCallId: "plan-error",
        isError: true,
        result: { content: [{ type: "text", text: "write failed" }] },
      });

      expect(deliver).toHaveBeenCalledWith({
        text: fullOutput ? "🗺️ Progress Card\n```txt\nwrite failed\n```" : "🗺️ Progress Card",
        isError: true,
      });
    },
  );

  it("propagates tool errors on the summary payload", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: false,
      shouldEmitToolResult: () => true,
      shouldEmitToolOutput: () => false,
      deliver,
    });
    await tracker.noteToolEvent(startEvent);
    await tracker.noteToolEvent({ ...resultEvent, isError: true });
    const payload = deliver.mock.calls[0]?.[0] as { isError?: boolean };
    expect(payload.isError).toBe(true);
  });

  it("summarizes results without a tracked start event", async () => {
    const deliver = vi.fn();
    const tracker = createCliToolSummaryTracker({
      commandDetailsVisible: false,
      shouldEmitToolResult: () => true,
      shouldEmitToolOutput: () => false,
      deliver,
    });
    await tracker.noteToolEvent({ ...resultEvent, toolCallId: "unseen" });
    expect(deliver).toHaveBeenCalledTimes(1);
  });
});

describe("runCliAgentWithLifecycle fast auto progress", () => {
  it("emits auto-off after the first CLI tool boundary past the threshold", async () => {
    vi.useFakeTimers();
    vi.setSystemTime(1_000);
    const events: Array<{ stream: string; data: Record<string, unknown> }> = [];
    const stop = onAgentEvent((evt) => {
      if (evt.runId === "run-fast-cli") {
        events.push({ stream: evt.stream, data: evt.data });
      }
    });
    const progressPayloads: string[] = [];
    cliDispatchState.runCliAgentMock.mockImplementation(async () => {
      emitAgentEvent({
        runId: "run-fast-cli",
        stream: "tool",
        data: { phase: "start", name: "bash", toolCallId: "call-1" },
      });
      vi.setSystemTime(7_100);
      emitAgentEvent({
        runId: "run-fast-cli",
        stream: "tool",
        data: { phase: "result", name: "bash", toolCallId: "call-1" },
      });
      return {
        payloads: [{ text: "done" }],
        meta: {
          durationMs: 7_100,
          agentMeta: { sessionId: "session-1", provider: "codex-cli", model: "gpt-5.5" },
        },
      } satisfies EmbeddedAgentRunResult;
    });

    await runCliAgentWithLifecycle({
      runId: "run-fast-cli",
      provider: "codex-cli",
      runParams: {
        sessionId: "session-1",
        sessionKey: "agent:main:cli-fast",
        sessionFile: "/tmp/session.jsonl",
        workspaceDir: "/tmp/workspace",
        prompt: "run one tool",
        provider: "codex-cli",
        model: "gpt-5.5",
        timeoutMs: 60_000,
        runId: "run-fast-cli",
        fastMode: "auto",
        fastModeStartedAtMs: 1_000,
        fastModeAutoOnSeconds: 5,
      },
      onFastModeAutoProgress: async (payload) => {
        if (payload.text) {
          progressPayloads.push(payload.text);
        }
      },
    });
    stop();

    const summaries = events
      .filter((event) => event.stream === "item")
      .map((event) => event.data.summary);
    expect(summaries).toContain("💨Fast: auto-off(6s>=5s)");
    expect(summaries).toContain("💨Fast: auto-on");
    expect(progressPayloads).toEqual(["💨Fast: auto-off(6s>=5s)", "💨Fast: auto-on"]);
  });
});