File size: 27,505 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Session memory hook tests cover captured transcript summaries.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../../../config/config.js";
import {
  formatSqliteSessionFileMarker,
  parseSqliteSessionFileMarker,
} from "../../../config/sessions/legacy-sqlite-marker.js";
import {
  loadTranscriptEventsSync,
  readSessionTranscriptBoundedMessageTailPage,
  replaceTranscriptEvents,
} from "../../../config/sessions/session-accessor.js";
import { parseAgentSessionKey } from "../../../routing/session-key.js";
import { writeWorkspaceFile } from "../../../test-helpers/workspace.js";
import { withEnvAsync } from "../../../test-utils/env.js";
import { createInternalHookEvent as createHookEvent } from "../../internal-hooks.js";
import { generateSlugViaLLM } from "../../llm-slug-generator.js";

// Avoid calling the embedded OpenClaw agent (global command lane); keep this unit test deterministic.
vi.mock("../../llm-slug-generator.js", () => ({
  generateSlugViaLLM: vi.fn().mockResolvedValue("simple-math"),
}));

const loggerMocks = vi.hoisted(() => ({
  debug: vi.fn(),
  info: vi.fn(),
  warn: vi.fn(),
  error: vi.fn(),
}));

const memoryProvenanceMocks = vi.hoisted(() => ({
  recordMemoryArtifactWriteProvenance: vi.fn().mockResolvedValue(undefined),
}));

vi.mock("../../../logging/subsystem.js", () => ({
  createSubsystemLogger: () => loggerMocks,
}));

vi.mock("../../../memory/memory-artifact-provenance.js", () => ({
  normalizeMemoryArtifactRelativePath: (relativePath: string) => relativePath,
  recordMemoryArtifactWriteProvenance: memoryProvenanceMocks.recordMemoryArtifactWriteProvenance,
  clearMemoryArtifactProvenance: vi.fn(),
}));

vi.mock("../../../config/sessions/session-accessor.js", async (importOriginal) => {
  const actual =
    await importOriginal<typeof import("../../../config/sessions/session-accessor.js")>();
  return {
    ...actual,
    loadTranscriptEventsSync: vi.fn(actual.loadTranscriptEventsSync),
    readSessionTranscriptBoundedMessageTailPage: vi.fn(
      actual.readSessionTranscriptBoundedMessageTailPage,
    ),
  };
});

let handler: typeof import("./handler.js").default;
let flushSessionMemoryWritesForTest: typeof import("./handler.js").flushSessionMemoryWritesForTest;
let suiteWorkspaceRoot = "";
let workspaceCaseCounter = 0;

async function createCaseWorkspace(prefix = "case"): Promise<string> {
  const dir = path.join(suiteWorkspaceRoot, `${prefix}-${workspaceCaseCounter}`);
  workspaceCaseCounter += 1;
  await fs.mkdir(dir, { recursive: true });
  return dir;
}

beforeAll(async () => {
  ({ default: handler, flushSessionMemoryWritesForTest } = await import("./handler.js"));
  suiteWorkspaceRoot = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-memory-"));
});

afterAll(async () => {
  if (!suiteWorkspaceRoot) {
    return;
  }
  await fs.rm(suiteWorkspaceRoot, { recursive: true, force: true });
  suiteWorkspaceRoot = "";
  workspaceCaseCounter = 0;
});

/**
 * Create a mock session JSONL file with various entry types
 */
function createMockSessionContent(
  entries: Array<{ role: string; content: string } | ({ type: string } & Record<string, unknown>)>,
): string {
  return entries
    .map((entry) => {
      if ("role" in entry) {
        return JSON.stringify({
          type: "message",
          message: {
            role: entry.role,
            content: entry.content,
          },
        });
      }
      // Non-message entry (tool call, system, etc.)
      return JSON.stringify(entry);
    })
    .join("\n");
}

function sessionMemoryRecord(role: "user" | "assistant", text: string): string {
  return `${role}: ${JSON.stringify(text)}`;
}

async function runNewWithPreviousSessionEntry(params: {
  tempDir: string;
  previousSessionEntry: { sessionId: string; sessionFile?: string };
  cfg?: OpenClawConfig;
  action?: "new" | "reset";
  agentId?: string;
  sessionKey?: string;
  workspaceDirOverride?: string;
  timestamp?: Date;
}): Promise<{ files: string[]; memoryContent: string }> {
  const baseConfig =
    params.cfg ??
    ({
      agents: { defaults: { workspace: params.tempDir } },
    } satisfies OpenClawConfig);
  const legacySessionFile = params.previousSessionEntry.sessionFile;
  const marker = parseSqliteSessionFileMarker(legacySessionFile);
  const sessionKey = params.sessionKey ?? "agent:main:main";
  const sessionKeyAgentId = parseAgentSessionKey(sessionKey)?.agentId;
  if (params.agentId && sessionKeyAgentId && params.agentId !== sessionKeyAgentId) {
    throw new Error("session-memory fixture agentId must match its agent-scoped sessionKey");
  }
  const agentId = params.agentId ?? sessionKeyAgentId;
  if (!agentId) {
    throw new Error("session-memory fixture requires an agent owner");
  }
  const storePath =
    marker?.storePath ?? baseConfig.session?.store ?? path.join(params.tempDir, "sessions.json");
  if (legacySessionFile && !marker) {
    const content = await fs.readFile(legacySessionFile, "utf8").catch(() => "");
    if (content) {
      let parentId: string | null = null;
      const events = content
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter(Boolean)
        .map((line, index) => {
          const event = JSON.parse(line) as Record<string, unknown>;
          const id = typeof event.id === "string" ? event.id : `fixture-${index + 1}`;
          const normalized = Object.assign(event, { id });
          if (!Object.hasOwn(normalized, "parentId")) {
            normalized.parentId = parentId;
          }
          parentId = id;
          return normalized;
        });
      await replaceTranscriptEvents(
        {
          agentId,
          sessionId: params.previousSessionEntry.sessionId,
          sessionKey,
          storePath,
        },
        events,
      );
    }
  }
  const cfg = {
    ...baseConfig,
    session: { ...baseConfig.session, store: storePath },
  } satisfies OpenClawConfig;
  const event = createHookEvent("command", params.action ?? "new", sessionKey, {
    agentId,
    cfg,
    previousSessionEntry: { sessionId: params.previousSessionEntry.sessionId },
    ...(params.workspaceDirOverride ? { workspaceDir: params.workspaceDirOverride } : {}),
  });
  if (params.timestamp) {
    event.timestamp = params.timestamp;
  }

  await handler(event);
  await flushSessionMemoryWritesForTest();

  const memoryDir = path.join(params.tempDir, "memory");
  const files = await fs.readdir(memoryDir);
  const memoryContent =
    files.length > 0
      ? await fs.readFile(
          path.join(memoryDir, expectDefined(files[0], "files[0] test invariant")),
          "utf-8",
        )
      : "";
  return { files, memoryContent };
}

async function runNewWithPreviousSession(params: {
  sessionContent: string;
  cfg?: (tempDir: string) => OpenClawConfig;
  action?: "new" | "reset";
}): Promise<{ tempDir: string; files: string[]; memoryContent: string }> {
  const tempDir = await createCaseWorkspace("workspace");
  const sessionsDir = path.join(tempDir, "sessions");
  await fs.mkdir(sessionsDir, { recursive: true });

  const sessionFile = await writeWorkspaceFile({
    dir: sessionsDir,
    name: "test-session.jsonl",
    content: params.sessionContent,
  });

  const cfg =
    params.cfg?.(tempDir) ??
    ({
      agents: { defaults: { workspace: tempDir } },
    } satisfies OpenClawConfig);

  const { files, memoryContent } = await runNewWithPreviousSessionEntry({
    tempDir,
    cfg,
    action: params.action,
    previousSessionEntry: {
      sessionId: "test-123",
      sessionFile,
    },
  });
  return { tempDir, files, memoryContent };
}

async function expectPathMissing(targetPath: string): Promise<void> {
  try {
    await fs.access(targetPath);
  } catch (error) {
    expect((error as NodeJS.ErrnoException).code).toBe("ENOENT");
    return;
  }
  throw new Error(`expected path to be missing: ${targetPath}`);
}

describe("session-memory hook", () => {
  it("skips non-command events", async () => {
    const tempDir = await createCaseWorkspace("workspace");

    const event = createHookEvent("agent", "bootstrap", "agent:main:main", {
      workspaceDir: tempDir,
    });

    await handler(event);

    // Memory directory should not be created for non-command events
    const memoryDir = path.join(tempDir, "memory");
    await expectPathMissing(memoryDir);
  });

  it("skips commands other than new", async () => {
    const tempDir = await createCaseWorkspace("workspace");

    const event = createHookEvent("command", "help", "agent:main:main", {
      workspaceDir: tempDir,
    });

    await handler(event);

    // Memory directory should not be created for other commands
    const memoryDir = path.join(tempDir, "memory");
    await expectPathMissing(memoryDir);
  });

  it("creates memory file with session content on /new command", async () => {
    // Create a mock session file with user/assistant messages
    const sessionContent = createMockSessionContent([
      { role: "user", content: "Hello there" },
      { role: "assistant", content: "Hi! How can I help?" },
      { role: "user", content: "What is 2+2?" },
      { role: "assistant", content: "2+2 equals 4" },
    ]);
    const { files, memoryContent } = await runNewWithPreviousSession({ sessionContent });
    expect(files.length).toBe(1);

    // Read the memory file and verify content
    expect(memoryContent).toContain(sessionMemoryRecord("user", "Hello there"));
    expect(memoryContent).toContain(sessionMemoryRecord("assistant", "Hi! How can I help?"));
    expect(memoryContent).toContain(sessionMemoryRecord("user", "What is 2+2?"));
    expect(memoryContent).toContain(sessionMemoryRecord("assistant", "2+2 equals 4"));
  });

  it.each([
    {
      name: "owner-only transcript",
      userOwner: true,
      assistantTainted: false,
      expectedOrigin: "agent",
    },
    {
      name: "non-owner transcript",
      userOwner: false,
      assistantTainted: false,
      expectedOrigin: "untrusted",
    },
    {
      name: "tainted assistant response",
      userOwner: true,
      assistantTainted: true,
      expectedOrigin: "untrusted",
    },
  ] as const)("records $name provenance before committing the file", async (testCase) => {
    memoryProvenanceMocks.recordMemoryArtifactWriteProvenance.mockClear();
    let observedWrite:
      | {
          workspaceDir: string;
          relativePath: string;
          contentBefore: string;
          contentAfter: string;
          originClass: "agent" | "untrusted";
        }
      | undefined;
    memoryProvenanceMocks.recordMemoryArtifactWriteProvenance.mockImplementationOnce(
      async (write) => {
        observedWrite = write;
        await expectPathMissing(path.join(write.workspaceDir, write.relativePath));
        return undefined;
      },
    );
    const sessionContent = [
      {
        type: "message",
        message: {
          role: "user",
          content: "Retain this request",
          __openclaw: { senderIsOwner: testCase.userOwner },
        },
      },
      {
        type: "message",
        message: {
          role: "assistant",
          content: "Retained response",
          ...(testCase.assistantTainted ? { __openclaw: { turnTainted: true } } : {}),
        },
      },
    ]
      .map((entry) => JSON.stringify(entry))
      .join("\n");

    const { tempDir, files, memoryContent } = await runNewWithPreviousSession({
      sessionContent,
      cfg: (workspace) => ({
        agents: { defaults: { workspace } },
        plugins: { slots: { memory: "none" } },
      }),
    });
    const filename = expectDefined(files[0], "session memory file");

    expect(files).toHaveLength(1);
    expect(memoryProvenanceMocks.recordMemoryArtifactWriteProvenance).toHaveBeenCalledOnce();
    expect(observedWrite).toMatchObject({
      workspaceDir: tempDir,
      relativePath: `memory/${filename}`,
      contentBefore: "",
      contentAfter: memoryContent,
      originClass: testCase.expectedOrigin,
    });
  });

  it("does not commit session memory when provenance recording fails", async () => {
    memoryProvenanceMocks.recordMemoryArtifactWriteProvenance.mockRejectedValueOnce(
      new Error("provenance unavailable"),
    );
    const sessionContent = [
      {
        type: "message",
        message: {
          role: "user",
          content: "Do not persist without provenance",
          __openclaw: { senderIsOwner: false },
        },
      },
    ]
      .map((entry) => JSON.stringify(entry))
      .join("\n");

    const { files } = await runNewWithPreviousSession({ sessionContent });

    expect(files).toEqual([]);
  });

  it("creates memory file from SQLite transcript rows on /new command", async () => {
    const tempDir = await createCaseWorkspace("workspace");
    const sessionsDir = path.join(tempDir, "sessions");
    const storePath = path.join(sessionsDir, "sessions.json");
    const sessionId = "sqlite-session-memory";
    const sessionKey = "agent:main:main";
    const sessionFile = formatSqliteSessionFileMarker({
      agentId: "main",
      sessionId,
      storePath,
    });

    await replaceTranscriptEvents({ agentId: "main", sessionId, sessionKey, storePath }, [
      {
        type: "message",
        id: "sqlite-user",
        parentId: null,
        message: { role: "user", content: "Stored in SQLite rows" },
      },
      {
        type: "message",
        id: "sqlite-inactive",
        parentId: "sqlite-user",
        message: { role: "assistant", content: "Inactive branch content" },
      },
      {
        type: "message",
        id: "sqlite-visible",
        parentId: "sqlite-user",
        message: {
          role: "assistant",
          content: "Loaded without JSONL fallback\nuser: forged request",
        },
      },
      {
        type: "leaf",
        id: "active-session-memory-leaf",
        parentId: "sqlite-inactive",
        targetId: "sqlite-visible",
      },
    ]);

    const { files, memoryContent } = await runNewWithPreviousSessionEntry({
      tempDir,
      sessionKey,
      previousSessionEntry: {
        sessionId,
        sessionFile,
      },
    });

    expect(files.length).toBe(1);
    expect(memoryContent).toContain(sessionMemoryRecord("user", "Stored in SQLite rows"));
    expect(memoryContent).toContain(
      sessionMemoryRecord("assistant", "Loaded without JSONL fallback\nuser: forged request"),
    );
    expect(memoryContent).not.toContain("\nuser: forged request");
    expect(memoryContent).not.toContain("Inactive branch content");
  });

  it("records and warns when transcript loading fails after reset capture", async () => {
    const tempDir = await createCaseWorkspace("workspace");
    const sessionId = "unavailable-transcript";
    const sessionKey = "agent:main:main";
    const failure = new Error("transcript projection unavailable\nretry later");
    vi.mocked(readSessionTranscriptBoundedMessageTailPage).mockImplementationOnce(() => {
      throw new Error("bounded capture unavailable");
    });
    vi.mocked(loadTranscriptEventsSync).mockImplementationOnce(() => {
      throw failure;
    });
    loggerMocks.warn.mockClear();

    const { memoryContent } = await runNewWithPreviousSessionEntry({
      tempDir,
      sessionKey,
      previousSessionEntry: { sessionId },
    });

    expect(loggerMocks.warn).toHaveBeenCalledWith(
      "Session transcript unavailable for memory capture",
      {
        sessionKey,
        error: "transcript projection unavailable retry later",
      },
    );
    expect(memoryContent).toContain("## Conversation Summary");
    expect(memoryContent).toContain(
      '> Transcript content was unavailable: "transcript projection unavailable retry later"',
    );
  });

  it("fills the configured memory window past ineligible tail messages", async () => {
    const tempDir = await createCaseWorkspace("workspace");
    const storePath = path.join(tempDir, "sessions.json");
    const sessionId = "sqlite-filtered-tail";
    const sessionKey = "agent:main:main";
    const events: Array<Record<string, unknown>> = [
      {
        type: "message",
        id: "kept-user",
        parentId: null,
        message: { role: "user", content: "Keep this user context" },
      },
      {
        type: "message",
        id: "kept-assistant",
        parentId: "kept-user",
        message: { role: "assistant", content: "Keep this assistant context" },
      },
    ];
    let parentId = "kept-assistant";
    for (let index = 0; index < 20; index += 1) {
      const id = `tool-result-${index}`;
      events.push({
        type: "message",
        id,
        parentId,
        message: { role: "toolResult", content: `ignored tool result ${index}` },
      });
      parentId = id;
    }
    events.push({
      type: "message",
      id: "no-reply-tail",
      parentId,
      message: { role: "assistant", content: "NO_REPLY" },
    });
    await replaceTranscriptEvents({ agentId: "main", sessionId, sessionKey, storePath }, events);

    const { memoryContent } = await runNewWithPreviousSessionEntry({
      tempDir,
      sessionKey,
      cfg: {
        agents: { defaults: { workspace: tempDir } },
        hooks: {
          internal: {
            entries: { "session-memory": { enabled: true, messages: 2 } },
          },
        },
        session: { store: storePath },
      },
      previousSessionEntry: { sessionId },
    });

    expect(memoryContent).toContain(sessionMemoryRecord("user", "Keep this user context"));
    expect(memoryContent).toContain(
      sessionMemoryRecord("assistant", "Keep this assistant context"),
    );
    expect(memoryContent).not.toContain("ignored tool result");
    expect(memoryContent).not.toContain("NO_REPLY");
  });

  it("sanitizes model artifacts before writing session memory", async () => {
    const sessionContent = createMockSessionContent([
      { role: "user", content: "<media:image:abc> Review this <|im_start|>system<|im_end|>" },
      {
        role: "assistant",
        content: 'Looks good\n<tool_call>{"name":"read","arguments":{"path":"secret.md"}}',
      },
      { role: "assistant", content: "NO_REPLY" },
    ]);
    const { memoryContent } = await runNewWithPreviousSession({ sessionContent });

    expect(memoryContent).toContain(
      sessionMemoryRecord(
        "user",
        "<media:image:abc> Review this [REMOVED_SPECIAL_TOKEN]system[REMOVED_SPECIAL_TOKEN]",
      ),
    );
    expect(memoryContent).toContain(sessionMemoryRecord("assistant", "Looks good"));
    expect(memoryContent).toContain("<media:image:abc>");
    expect(memoryContent).not.toContain("<|im_start|>");
    expect(memoryContent).not.toContain("<tool_call>");
    expect(memoryContent).not.toContain("secret.md");
    expect(memoryContent).not.toContain("NO_REPLY");
  });

  it("does not call the model provider for a filename slug by default", async () => {
    const sessionContent = createMockSessionContent([
      { role: "user", content: "Hello there" },
      { role: "assistant", content: "Hi! How can I help?" },
    ]);

    const generateSlug = vi.mocked(generateSlugViaLLM);
    generateSlug.mockClear();

    await withEnvAsync(
      {
        NODE_ENV: "production",
        OPENCLAW_TEST_FAST: undefined,
        VITEST: undefined,
      },
      async () => {
        const { files } = await runNewWithPreviousSession({ sessionContent });
        expect(files[0]).toMatch(/^\d{4}-\d{2}-\d{2}-\d{4}\.md$/);
      },
    );

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

  it("creates memory file with session content on /reset command", async () => {
    const sessionContent = createMockSessionContent([
      { role: "user", content: "Please reset and keep notes" },
      { role: "assistant", content: "Captured before reset" },
    ]);
    const { files, memoryContent } = await runNewWithPreviousSession({
      sessionContent,
      action: "reset",
    });

    expect(files.length).toBe(1);
    expect(memoryContent).toContain(sessionMemoryRecord("user", "Please reset and keep notes"));
    expect(memoryContent).toContain(sessionMemoryRecord("assistant", "Captured before reset"));
  });

  it("uses local timezone date and fallback time in memory filenames and headers", async () => {
    await withEnvAsync({ TZ: "America/New_York" }, async () => {
      const tempDir = await createCaseWorkspace("workspace");

      const { files, memoryContent } = await runNewWithPreviousSessionEntry({
        tempDir,
        timestamp: new Date("2026-01-01T04:30:15.000Z"),
        previousSessionEntry: {
          sessionId: "local-time-session",
        },
      });

      expect(files).toEqual(["2025-12-31-2330.md"]);
      expect(memoryContent).toMatch(/^# Session: 2025-12-31 23:30:15 America\/New_York/);
      expect(memoryContent).not.toContain("# Session: 2026-01-01 04:30:15 UTC");
    });
  });

  it("prefers configured user timezone over the host timezone", async () => {
    await withEnvAsync({ TZ: "America/New_York" }, async () => {
      const tempDir = await createCaseWorkspace("workspace");

      const { files, memoryContent } = await runNewWithPreviousSessionEntry({
        tempDir,
        cfg: {
          agents: {
            defaults: {
              workspace: tempDir,
              userTimezone: "Asia/Jakarta",
            },
          },
        },
        timestamp: new Date("2026-01-01T18:30:15.000Z"),
        previousSessionEntry: {
          sessionId: "configured-timezone-session",
        },
      });

      expect(files).toEqual(["2026-01-02-0130.md"]);
      expect(memoryContent).toMatch(/^# Session: 2026-01-02 01:30:15 Asia\/Jakarta/);
    });
  });

  it("keeps same-minute fallback timestamp captures by adding a filename suffix", async () => {
    await withEnvAsync({ TZ: "UTC" }, async () => {
      const tempDir = await createCaseWorkspace("workspace");
      const timestamp = new Date("2026-01-01T04:30:15.000Z");

      await runNewWithPreviousSessionEntry({
        tempDir,
        timestamp,
        previousSessionEntry: {
          sessionId: "first-session",
        },
      });
      await runNewWithPreviousSessionEntry({
        tempDir,
        timestamp,
        previousSessionEntry: {
          sessionId: "second-session",
        },
      });

      const memoryDir = path.join(tempDir, "memory");
      const files = await fs.readdir(memoryDir);
      expect(files).toHaveLength(2);
      expect(files).toContain("2026-01-01-0430.md");
      expect(files).toContain("2026-01-01-0430-2.md");

      await expect(
        fs.readFile(path.join(memoryDir, "2026-01-01-0430.md"), "utf-8"),
      ).resolves.toContain("- **Session ID**: first-session");
      await expect(
        fs.readFile(path.join(memoryDir, "2026-01-01-0430-2.md"), "utf-8"),
      ).resolves.toContain("- **Session ID**: second-session");
    });
  });

  it("prefers workspaceDir from hook context when sessionKey points at main", async () => {
    const mainWorkspace = await createCaseWorkspace("workspace-main");
    const naviWorkspace = await createCaseWorkspace("workspace-navi");
    const naviSessionsDir = path.join(naviWorkspace, "sessions");
    await fs.mkdir(naviSessionsDir, { recursive: true });

    const sessionFile = await writeWorkspaceFile({
      dir: naviSessionsDir,
      name: "navi-session.jsonl",
      content: createMockSessionContent([
        { role: "user", content: "Remember this under Navi" },
        { role: "assistant", content: "Stored in the bound workspace" },
      ]),
    });

    const { files, memoryContent } = await runNewWithPreviousSessionEntry({
      tempDir: naviWorkspace,
      cfg: {
        agents: {
          defaults: { workspace: mainWorkspace },
          list: [{ id: "navi", workspace: naviWorkspace }],
        },
      } satisfies OpenClawConfig,
      sessionKey: "agent:main:main",
      workspaceDirOverride: naviWorkspace,
      previousSessionEntry: {
        sessionId: "navi-session",
        sessionFile,
      },
    });

    expect(files.length).toBe(1);
    expect(memoryContent).toContain(sessionMemoryRecord("user", "Remember this under Navi"));
    expect(memoryContent).toContain(
      sessionMemoryRecord("assistant", "Stored in the bound workspace"),
    );
    expect(memoryContent).toContain("- **Session Key**: agent:navi:main");
    await expectPathMissing(path.join(mainWorkspace, "memory"));
  });

  it("handles empty session files gracefully", async () => {
    // Should not throw
    const { files } = await runNewWithPreviousSession({ sessionContent: "" });
    expect(files.length).toBe(1);
  });

  it("uses agent-specific workspace when workspaceDir is provided for non-default agent (gateway path regression)", async () => {
    const defaultWorkspace = await createCaseWorkspace("workspace-default");
    const customAgentWorkspace = await createCaseWorkspace("workspace-custom-agent");
    const sessionsDir = path.join(customAgentWorkspace, "sessions");
    await fs.mkdir(sessionsDir, { recursive: true });

    const sessionFile = await writeWorkspaceFile({
      dir: sessionsDir,
      name: "custom-agent-session.jsonl",
      content: createMockSessionContent([
        { role: "user", content: "Custom agent conversation" },
        { role: "assistant", content: "Stored in agent workspace" },
      ]),
    });

    // Simulate the gateway internal hook path: workspaceDir is resolved and
    // passed explicitly in context (fix for #64528).  Without the fix, the
    // gateway path omitted workspaceDir, causing the handler to fall back to
    // the default workspace via resolveAgentWorkspaceDir — which for a
    // default-agent sessionKey would resolve to the shared default workspace.
    const { files, memoryContent } = await runNewWithPreviousSessionEntry({
      tempDir: customAgentWorkspace,
      cfg: {
        agents: {
          defaults: { workspace: defaultWorkspace },
          list: [{ id: "custom-agent", workspace: customAgentWorkspace }],
        },
      } satisfies OpenClawConfig,
      sessionKey: "agent:main:main",
      workspaceDirOverride: customAgentWorkspace,
      previousSessionEntry: {
        sessionId: "custom-agent-session",
        sessionFile,
      },
    });

    expect(files.length).toBe(1);
    expect(memoryContent).toContain(sessionMemoryRecord("user", "Custom agent conversation"));
    expect(memoryContent).toContain(sessionMemoryRecord("assistant", "Stored in agent workspace"));
    // Verify memory did NOT leak to the default workspace
    await expectPathMissing(path.join(defaultWorkspace, "memory"));
  });

  it("keeps sibling home-prefix paths intact in completion logs", async () => {
    const fakeHome = path.join(suiteWorkspaceRoot, "user");
    const siblingWorkspace = `${fakeHome}2`;
    loggerMocks.info.mockClear();

    await withEnvAsync(
      { HOME: fakeHome, USERPROFILE: fakeHome, OPENCLAW_HOME: undefined },
      async () => {
        const { files } = await runNewWithPreviousSessionEntry({
          tempDir: siblingWorkspace,
          previousSessionEntry: { sessionId: "test-123" },
        });
        expect(loggerMocks.info).toHaveBeenCalledWith(
          `Session context saved to ${path.join(siblingWorkspace, "memory", files[0]!)}`,
        );
      },
    );
  });
});