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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
/**
 * Tests for CLI commands using mock backend.
 */

import { describe, it, expect, vi, beforeEach } from "vitest";
import { createMockBackend } from "./setup.js";
import type { Backend } from "../src/backend/base.js";
import { setAgentMode } from "../src/state.js";

let mockBackend: Backend;

// Capture console.log and console.error output
let output: string;
let errOutput: string;
const originalLog = console.log;
const originalError = console.error;

beforeEach(() => {
  mockBackend = createMockBackend();
  output = "";
  errOutput = "";
  console.log = (...args: unknown[]) => {
    output += args.map(String).join(" ") + "\n";
  };
  console.error = (...args: unknown[]) => {
    errOutput += args.map(String).join(" ") + "\n";
  };
});

// Restore after each test
import { afterEach } from "vitest";
afterEach(() => {
  console.log = originalLog;
  console.error = originalError;
  setAgentMode(false);
});

describe("cmdAdd", () => {
  it("adds text memory", async () => {
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "I prefer dark mode", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "text",
    });
    expect(mockBackend.add).toHaveBeenCalledOnce();
  });

  it("adds from messages JSON", async () => {
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, undefined, {
      userId: "alice",
      messages: JSON.stringify([{ role: "user", content: "I love Python" }]),
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "text",
    });
    expect(mockBackend.add).toHaveBeenCalledOnce();
  });

  it("outputs json format", async () => {
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "json",
    });
    expect(output).toContain("results");
  });

  it("quiet mode produces no memory content", async () => {
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "quiet",
    });
    expect(output).not.toContain("dark mode");
  });
});

describe("cmdAdd deduplicates PENDING", () => {
  const DUPLICATE_PENDING = {
    results: [
      { status: "PENDING", event_id: "evt-dup" },
      { status: "PENDING", event_id: "evt-dup" },
    ],
  };

  it("text shows one pending block", async () => {
    (mockBackend.add as ReturnType<typeof vi.fn>).mockResolvedValue(DUPLICATE_PENDING);
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "text",
    });
    expect(output.match(/Queued/g)?.length).toBe(1);
  });

  it("json shows one pending entry", async () => {
    (mockBackend.add as ReturnType<typeof vi.fn>).mockResolvedValue(DUPLICATE_PENDING);
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "json",
    });
    const data = JSON.parse(output);
    const pending = data.results.filter((r: Record<string, unknown>) => r.status === "PENDING");
    expect(pending).toHaveLength(1);
  });

  it("agent shows one pending entry", async () => {
    (mockBackend.add as ReturnType<typeof vi.fn>).mockResolvedValue(DUPLICATE_PENDING);
    setAgentMode(true);
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "agent",
    });
    const data = JSON.parse(output);
    expect(data.count).toBe(1);
    expect(data.data).toHaveLength(1);
  });
});

describe("cmdSearch", () => {
  it("searches and shows results in text mode", async () => {
    const { cmdSearch } = await import("../src/commands/memory.js");
    await cmdSearch(mockBackend, "preferences", {
      userId: "alice",
      topK: 10,
      threshold: 0.3,
      rerank: false,
      keyword: false,
      enableGraph: false,
      output: "text",
    });
    expect(output).toContain("Found 2");
  });

  it("outputs json format", async () => {
    const { cmdSearch } = await import("../src/commands/memory.js");
    await cmdSearch(mockBackend, "preferences", {
      userId: "alice",
      topK: 10,
      threshold: 0.3,
      rerank: false,
      keyword: false,
      enableGraph: false,
      output: "json",
    });
    expect(output).toContain("memory");
  });

  it("shows no results message", async () => {
    (mockBackend.search as ReturnType<typeof vi.fn>).mockResolvedValue([]);
    const { cmdSearch } = await import("../src/commands/memory.js");
    await cmdSearch(mockBackend, "nonexistent", {
      userId: "alice",
      topK: 10,
      threshold: 0.3,
      rerank: false,
      keyword: false,
      enableGraph: false,
      output: "text",
    });
    expect(errOutput).toContain("No memories found");
  });
});

describe("cmdGet", () => {
  it("gets memory in text mode", async () => {
    const { cmdGet } = await import("../src/commands/memory.js");
    await cmdGet(mockBackend, "abc-123-def-456", { output: "text" });
    expect(output).toContain("dark mode");
  });

  it("gets memory in json mode", async () => {
    const { cmdGet } = await import("../src/commands/memory.js");
    await cmdGet(mockBackend, "abc-123-def-456", { output: "json" });
    expect(output).toContain("memory");
  });
});

describe("cmdList", () => {
  it("lists in table mode", async () => {
    const { cmdList } = await import("../src/commands/memory.js");
    await cmdList(mockBackend, {
      userId: "alice",
      page: 1,
      pageSize: 100,
      enableGraph: false,
      output: "table",
    });
    expect(output).toContain("dark mode");
  });

  it("shows empty message", async () => {
    (mockBackend.listMemories as ReturnType<typeof vi.fn>).mockResolvedValue([]);
    const { cmdList } = await import("../src/commands/memory.js");
    await cmdList(mockBackend, {
      userId: "alice",
      page: 1,
      pageSize: 100,
      enableGraph: false,
      output: "text",
    });
    expect(errOutput).toContain("No memories found");
  });
});

describe("cmdUpdate", () => {
  it("updates memory", async () => {
    const { cmdUpdate } = await import("../src/commands/memory.js");
    await cmdUpdate(mockBackend, "abc-123", "New text", { output: "text" });
    expect(output.toLowerCase()).toContain("updated");
  });
});

describe("cmdDelete", () => {
  it("deletes memory", async () => {
    const { cmdDelete } = await import("../src/commands/memory.js");
    await cmdDelete(mockBackend, "abc-123", { output: "text" });
    expect(output.toLowerCase()).toContain("deleted");
  });
});

describe("cmdDeleteAll", () => {
  it("deletes all with force", async () => {
    const { cmdDeleteAll } = await import("../src/commands/memory.js");
    await cmdDeleteAll(mockBackend, {
      force: true,
      userId: "alice",
      output: "text",
    });
    expect(output.toLowerCase()).toContain("deleted");
  });
});


describe("cmdEntitiesList", () => {
  it("lists users in table mode", async () => {
    const { cmdEntitiesList } = await import("../src/commands/entities.js");
    await cmdEntitiesList(mockBackend, "users", { output: "table" });
    expect(output).toContain("alice");
  });

  it("lists in json mode", async () => {
    const { cmdEntitiesList } = await import("../src/commands/entities.js");
    await cmdEntitiesList(mockBackend, "users", { output: "json" });
    expect(output).toContain("alice");
  });
});

describe("cmdEventList", () => {
  it("lists events in table mode", async () => {
    const { cmdEventList } = await import("../src/commands/events.js");
    await cmdEventList(mockBackend, { output: "table" });
    expect(output).toContain("evt-abc-");
    expect(output).toContain("ADD");
    expect(output).toContain("SUCCEEDED");
  });

  it("lists events in json mode", async () => {
    const { cmdEventList } = await import("../src/commands/events.js");
    await cmdEventList(mockBackend, { output: "json" });
    expect(output).toContain("evt-abc-123-def-456");
    expect(output).toContain("evt-def-456-ghi-789");
  });

  it("shows empty message when no events", async () => {
    (mockBackend.listEvents as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]);
    const { cmdEventList } = await import("../src/commands/events.js");
    await cmdEventList(mockBackend, { output: "table" });
    expect((output + errOutput).toLowerCase()).toContain("no events");
  });
});

describe("cmdEventStatus", () => {
  it("shows event details in text mode", async () => {
    const { cmdEventStatus } = await import("../src/commands/events.js");
    await cmdEventStatus(mockBackend, "evt-abc-123-def-456", { output: "text" });
    expect(output).toContain("evt-abc-123-def-456");
    expect(output).toContain("SUCCEEDED");
  });

  it("shows event details in json mode", async () => {
    const { cmdEventStatus } = await import("../src/commands/events.js");
    await cmdEventStatus(mockBackend, "evt-abc-123-def-456", { output: "json" });
    expect(output).toContain("evt-abc-123-def-456");
    expect(output).toContain("ADD");
  });
});

describe("agent mode", () => {
  it("cmdAdd outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdAdd } = await import("../src/commands/memory.js");
    await cmdAdd(mockBackend, "test preference", {
      userId: "alice",
      immutable: false,
      noInfer: false,
      enableGraph: false,
      output: "agent",
    });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("add");
    expect(parsed.data).toBeDefined();
    expect(parsed.scope).toMatchObject({ user_id: "alice" });
    expect(Object.keys(parsed.data[0]).sort()).toEqual(["event", "id", "memory"].sort());
  });

  it("cmdSearch outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdSearch } = await import("../src/commands/memory.js");
    await cmdSearch(mockBackend, "preferences", {
      userId: "alice",
      topK: 10,
      threshold: 0.3,
      rerank: false,
      keyword: false,
      enableGraph: false,
      output: "agent",
    });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("search");
    expect(Array.isArray(parsed.data)).toBe(true);
    expect(parsed.count).toBe(2);
    const keys = Object.keys(parsed.data[0]);
    expect(keys).toContain("id");
    expect(keys).toContain("memory");
    expect(keys).toContain("score");
    expect(keys).toContain("created_at");
    expect(keys).toContain("categories");
    expect(keys).not.toContain("user_id");
    expect(keys).not.toContain("agent_id");
  });

  it("cmdList outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdList } = await import("../src/commands/memory.js");
    await cmdList(mockBackend, {
      userId: "alice",
      page: 1,
      pageSize: 100,
      enableGraph: false,
      output: "agent",
    });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("list");
    expect(Array.isArray(parsed.data)).toBe(true);
    expect(parsed.count).toBe(2);
    expect(Object.keys(parsed.data[0]).sort()).toEqual(["categories", "created_at", "id", "memory"]);
  });

  it("cmdGet outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdGet } = await import("../src/commands/memory.js");
    await cmdGet(mockBackend, "abc-123-def-456", { output: "agent" });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("get");
    expect(parsed.data).toBeDefined();
    expect(parsed.data).toMatchObject({ id: "abc-123-def-456" });
    expect(Object.keys(parsed.data)).not.toContain("user_id");
  });

  it("cmdUpdate outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdUpdate } = await import("../src/commands/memory.js");
    await cmdUpdate(mockBackend, "abc-123", "Updated text", { output: "agent" });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("update");
    expect(parsed.data).toBeDefined();
  });

  it("cmdDelete outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdDelete } = await import("../src/commands/memory.js");
    await cmdDelete(mockBackend, "abc-123", { output: "agent" });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("delete");
    expect(parsed.data).toBeDefined();
  });

  it("cmdEventList outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdEventList } = await import("../src/commands/events.js");
    await cmdEventList(mockBackend, { output: "agent" });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("event list");
    expect(Array.isArray(parsed.data)).toBe(true);
    expect(parsed.count).toBe(2);
    expect(Object.keys(parsed.data[0]).sort()).toEqual(
      ["created_at", "event_type", "id", "latency", "status"],
    );
    expect(Object.keys(parsed.data[0])).not.toContain("updated_at");
  });

  it("cmdEventStatus outputs JSON envelope", async () => {
    setAgentMode(true);
    const { cmdEventStatus } = await import("../src/commands/events.js");
    await cmdEventStatus(mockBackend, "evt-abc-123-def-456", { output: "agent" });
    const parsed = JSON.parse(output.trim());
    expect(parsed.status).toBe("success");
    expect(parsed.command).toBe("event status");
    expect(parsed.data).toBeDefined();
    expect(parsed.data).toMatchObject({ id: "evt-abc-123-def-456" });
    expect(parsed.data.results[0]).toHaveProperty("memory");
    expect(parsed.data.results[0]).not.toHaveProperty("data");
  });
});