File size: 5,418 Bytes
eb3f11e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
import type { CliBackendPlugin } from "../../plugins/cli-backend.types.js";
import type { PreparedAgentRunAdmission } from "../admitted-run-context.js";
import { testing as cliBackendsTesting } from "../cli-backends.test-support.js";

const tempDirs = useAutoCleanupTempDirTracker(afterEach);

const { runCliAgentMock } = vi.hoisted(() => ({
  runCliAgentMock: vi.fn(async (_params: { preparedRunAdmission?: PreparedAgentRunAdmission }) => ({
    meta: {
      durationMs: 1,
      agentMeta: { sessionId: "native-session", provider: "claude-cli", model: "opus" },
    },
  })),
}));

vi.mock("../cli-runner.js", () => ({ runCliAgent: runCliAgentMock }));

const { testing } = await import("./compact.js");

function registerBackend(overrides: Partial<CliBackendPlugin> = {}) {
  cliBackendsTesting.setDepsForTest({
    resolveRuntimeCliBackends: () =>
      [
        {
          id: "claude-cli",
          modelProvider: "anthropic",
          config: {
            command: "claude",
            args: ["-p"],
            resumeArgs: ["-p", "--resume", "{sessionId}"],
            input: "stdin",
            output: "jsonl",
            sessionMode: "existing",
          },
          bundleMcp: false,
          pluginId: "anthropic",
          ownsNativeCompaction: true,
          manualCompaction: {
            buildPrompt: (instructions?: string) =>
              instructions ? `/compact ${instructions}` : "/compact",
            input: "arg",
            validateOutput: () => ({ ok: true }),
          },
          ...overrides,
        },
      ] as never,
    resolvePluginSetupCliBackend: () => undefined,
  });
}

function compactParams(overrides: Record<string, unknown> = {}) {
  const dir = tempDirs.make("openclaw-compact-native-cli-");
  const cliSessionBinding = {
    sessionId: "native-session",
    authProfileId: "anthropic:subscription",
  };
  const sessionEntry = { execHost: "node", execNode: "paired-node" };
  return {
    sessionId: "openclaw-session",
    sessionKey: "agent:main:main",
    sessionTarget: {
      agentId: "main",
      sessionId: "openclaw-session",
      sessionKey: "agent:main:main",
      storePath: join(dir, "openclaw.sqlite"),
    },
    sessionFile: "agent:main:main",
    agentId: "main",
    workspaceDir: join(dir, "workspace"),
    agentDir: join(dir, "agent"),
    config: {},
    provider: "anthropic",
    model: "opus",
    trigger: "manual",
    cliSessionId: "native-session",
    cliSessionBinding,
    sessionEntry,
    customInstructions: "keep decisions",
    preparedModelRuntime: {},
    ...overrides,
  } as never;
}

afterEach(() => {
  cliBackendsTesting.resetDepsForTest();
  runCliAgentMock.mockClear();
});

describe("native CLI manual compaction", () => {
  it("resumes the bound backend session with the backend-owned command", async () => {
    registerBackend();

    const result = await testing.compactNativeCliSession({
      runtime: "claude-cli",
      compactParams: compactParams(),
    });

    expect(result).toEqual({
      ok: true,
      compacted: true,
      reason: 'CLI backend "claude-cli" compacted its native session.',
    });
    expect(runCliAgentMock).toHaveBeenCalledWith(
      expect.objectContaining({
        preparedRunAdmission: expect.objectContaining({
          operationalRunInstance: expect.objectContaining({
            runId: "openclaw-session:native-compact",
          }),
        }),
        prompt: "/compact keep decisions",
        provider: "claude-cli",
        modelProvider: "anthropic",
        cliSessionId: "native-session",
        cliSessionBinding: {
          sessionId: "native-session",
          authProfileId: "anthropic:subscription",
        },
        authProfileId: "anthropic:subscription",
        sessionEntry: { execHost: "node", execNode: "paired-node" },
        controlOperation: "compact",
        disableCliLiveSession: true,
        cleanupCliLiveSessionOnRunEnd: true,
        allowEmptyAssistantReplyAsSilent: true,
      }),
    );
    const preparedRunAdmission = runCliAgentMock.mock.calls[0]?.[0]?.preparedRunAdmission;
    if (!preparedRunAdmission) {
      throw new Error("native compaction did not prepare run admission");
    }
    await expect(preparedRunAdmission.admit("embedded")).rejects.toThrow(
      "prepared execution context is already closed",
    );
  });

  it("fails explicitly when an owning backend has no resumable session", async () => {
    registerBackend();

    const result = await testing.compactNativeCliSession({
      runtime: "claude-cli",
      compactParams: compactParams({
        cliSessionId: undefined,
        cliSessionBinding: undefined,
      }),
    });

    expect(result).toMatchObject({ ok: false, compacted: false });
    expect(result?.reason).toContain("without a resumable native session");
    expect(runCliAgentMock).not.toHaveBeenCalled();
  });

  it("leaves non-owning runtimes on the existing compaction path", async () => {
    registerBackend({ ownsNativeCompaction: false });

    await expect(
      testing.compactNativeCliSession({
        runtime: "claude-cli",
        compactParams: compactParams(),
      }),
    ).resolves.toBeUndefined();
    expect(runCliAgentMock).not.toHaveBeenCalled();
  });
});