memory-dream.test.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import { mkdtemp, readFile, stat, utimes, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { readFileSync } from "node:fs";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import {
  7. acquireDreamLock,
  8. buildMemoryDreamPrompt,
  9. collectDreamTouchedPaths,
  10. evaluateAutoDreamTiming,
  11. restoreDreamLockAfterFailure,
  12. } from "../src/memory/dream.js";
  13. const temporaryDirectories: string[] = [];
  14. afterEach(async () => {
  15. const { rm } = await import("node:fs/promises");
  16. await Promise.all(
  17. temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })),
  18. );
  19. });
  20. describe("Memory Dream prompt", () => {
  21. it("matches the frozen provider-visible fixture", () => {
  22. const fixture = readFileSync(
  23. new URL("./fixtures/memory/dream-prompt.md", import.meta.url),
  24. "utf8",
  25. ).trimEnd();
  26. expect(
  27. buildMemoryDreamPrompt({
  28. memoryRoot: "<MEMORY_ROOT>",
  29. sessionIds: Array.from({ length: 7 }, () => "<SESSION_ID>"),
  30. transcriptRoot: "<SESSION_TRANSCRIPT_ROOT>",
  31. }),
  32. ).toBe(fixture);
  33. });
  34. });
  35. describe("auto Dream timing gate", () => {
  36. const day = 24 * 60 * 60 * 1000;
  37. const tenMinutes = 10 * 60 * 1000;
  38. const now = Date.parse("2026-07-16T12:00:00.000Z");
  39. it("checks the 24 hour gate before scan throttling", () => {
  40. expect(
  41. evaluateAutoDreamTiming({
  42. lastConsolidatedAtMs: now - day + 1,
  43. lastScanAtMs: now - tenMinutes - 1,
  44. nowMs: now,
  45. }),
  46. ).toEqual({ decision: "skip", reason: "minimum-interval" });
  47. });
  48. it("throttles scans only after the 24 hour gate passes", () => {
  49. expect(
  50. evaluateAutoDreamTiming({
  51. lastConsolidatedAtMs: now - day,
  52. lastScanAtMs: now - tenMinutes + 1,
  53. nowMs: now,
  54. }),
  55. ).toEqual({ decision: "skip", reason: "scan-throttled" });
  56. expect(
  57. evaluateAutoDreamTiming({
  58. lastConsolidatedAtMs: now - day,
  59. lastScanAtMs: now - tenMinutes,
  60. nowMs: now,
  61. }),
  62. ).toEqual({ decision: "scan" });
  63. });
  64. });
  65. describe("Dream consolidation lock", () => {
  66. it("acquires a missing lock and removes it when the run fails", async () => {
  67. const root = await temporaryDirectory();
  68. const priorMtime = await acquireDreamLock({ memoryRoot: root, pid: process.pid });
  69. expect(priorMtime).toBe(0);
  70. expect((await readFile(join(root, ".consolidate-lock"), "utf8")).trim()).toBe(
  71. String(process.pid),
  72. );
  73. await restoreDreamLockAfterFailure({ memoryRoot: root, priorMtimeMs: priorMtime! });
  74. await expect(stat(join(root, ".consolidate-lock"))).rejects.toMatchObject({ code: "ENOENT" });
  75. });
  76. it("does not take a fresh lock held by a live PID", async () => {
  77. const root = await temporaryDirectory();
  78. const lockPath = join(root, ".consolidate-lock");
  79. await writeFile(lockPath, String(process.pid), "utf8");
  80. await expect(acquireDreamLock({ memoryRoot: root, pid: process.pid })).resolves.toBeNull();
  81. expect((await readFile(lockPath, "utf8")).trim()).toBe(String(process.pid));
  82. });
  83. it("takes a stale lock and restores empty content with its original mtime after failure", async () => {
  84. const root = await temporaryDirectory();
  85. const lockPath = join(root, ".consolidate-lock");
  86. const oldMtime = Date.parse("2026-07-14T01:02:03.000Z");
  87. await writeFile(lockPath, "99999999", "utf8");
  88. await utimes(lockPath, oldMtime / 1000, oldMtime / 1000);
  89. const priorMtime = await acquireDreamLock({ memoryRoot: root, pid: process.pid });
  90. expect(priorMtime).toBe(oldMtime);
  91. await restoreDreamLockAfterFailure({ memoryRoot: root, priorMtimeMs: priorMtime! });
  92. expect(await readFile(lockPath, "utf8")).toBe("");
  93. expect((await stat(lockPath)).mtimeMs).toBeCloseTo(oldMtime, -1);
  94. });
  95. });
  96. describe("Dream touched paths", () => {
  97. const root = "/storage/memory";
  98. it("records canonical allowed Write/Edit and narrow rm targets in first-seen order", () => {
  99. const paths = new Set<string>();
  100. collectDreamTouchedPaths(paths, {
  101. rootDir: root,
  102. toolCall: {
  103. id: "write",
  104. name: "Write",
  105. input: { file_path: `${root}/fact.md` },
  106. },
  107. workingDirectory: "/workspace",
  108. workspaceRoot: "/workspace",
  109. });
  110. collectDreamTouchedPaths(paths, {
  111. rootDir: root,
  112. toolCall: {
  113. id: "remove",
  114. name: "Bash",
  115. input: { command: `rm -f ${root}/old.md ${root}/fact.md` },
  116. },
  117. workingDirectory: "/workspace",
  118. workspaceRoot: "/workspace",
  119. });
  120. expect([...paths]).toEqual([`${root}/fact.md`, `${root}/old.md`]);
  121. });
  122. });
  123. async function temporaryDirectory(): Promise<string> {
  124. const path = await mkdtemp(join(tmpdir(), "zcode-memory-dream-"));
  125. temporaryDirectories.push(path);
  126. return path;
  127. }