diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.md index 1cd407934..573aefed9 100644 --- a/apps/node-services/src/memory/README.md +++ b/apps/node-services/src/memory/README.md @@ -17,6 +17,13 @@ and then the repair for unquoted colon-bearing values. If neither parses, the reader uses the body heading and summary with empty metadata. A damaged report therefore remains readable without blocking other reports in the Memory browser; the reader does not rewrite the file. Publication validation remains strict. +The browser keeps that metadata in a per-process catalog: while +`memory.revision` is unchanged it answers from the catalog and re-reads only +pages whose size or modification time changed, so a page edited outside the +service can lag by up to five seconds. The published entry IDs and sort order +are unchanged. The cursor is now an opaque keyset (the last page's +`updated_at` and path), stable across inserts; a numeric offset cursor from an +older server is still accepted. ## Search diff --git a/apps/node-services/src/memory/memory-browser.ts b/apps/node-services/src/memory/memory-browser.ts index 55f622475..6cd29161e 100644 --- a/apps/node-services/src/memory/memory-browser.ts +++ b/apps/node-services/src/memory/memory-browser.ts @@ -1,19 +1,11 @@ -import crypto from "node:crypto"; -import fs from "node:fs/promises"; -import path from "node:path"; - import type { components } from "@linger/wire-contracts/node-services-internal/types"; import { loadWikiGraphSubjectsForActor } from "./collector.js"; -import { walkFiles } from "./fs-utils.js"; -import { parseMemoryMarkdown, stringValue } from "./markdown.js"; -import { agentMemoryRoot } from "./paths.js"; +import { memoryCatalogFor, type MemoryCatalogFile } from "./memory-catalog.js"; import { browseMeetings } from "./meeting-browser.js"; const maxContentChars = 200_000; -const defaultLimit = 50; -export type MemoryEntryKind = "daily" | "weekly"; type MemoryEntry = components["schemas"]["MemoryEntry"]; type MemoryEntryPage = components["schemas"]["MemoryEntryPage"]; @@ -24,17 +16,6 @@ interface BrowserRequest { ownerActorId: string; } -interface MemoryFile { - id: string; - kind: MemoryEntryKind; - relativePath: string; - absolutePath: string; - title: string; - summary: string; - updatedAt: string; - date?: string; -} - export async function listMemoryEntries(input: { dataRoot: string; tenantId: string; @@ -45,26 +26,20 @@ export async function listMemoryEntries(input: { }): Promise { if (input.kind === "meeting") return browseMeetings(input); const subject = await resolveSubject(input); - const files = await collectMemoryFiles( + const page = await memoryCatalogFor( input.dataRoot, subject.agentManagementId, - ); - const filtered = input.kind - ? files.filter((file) => file.kind === input.kind) - : files; - const offset = parseCursor(input.cursor); - const limit = input.limit ?? defaultLimit; - const page = filtered.slice(offset, offset + limit); - const nextOffset = offset + page.length; - + ).list({ + ...(input.kind ? { kind: input.kind } : {}), + ...(input.cursor ? { cursor: input.cursor } : {}), + ...(input.limit === undefined ? {} : { limit: input.limit }), + }); return { - items: page.map((file) => ({ + items: page.items.map((file) => ({ ...toEntry(file, ""), content: "", })), - ...(nextOffset < filtered.length - ? { next_cursor: String(nextOffset) } - : {}), + ...(page.nextCursor ? { next_cursor: page.nextCursor } : {}), }; } @@ -80,16 +55,19 @@ export async function getMemoryEntry(input: { return meeting; } const subject = await resolveSubject(input); - const files = await collectMemoryFiles( - input.dataRoot, - subject.agentManagementId, - ); - const file = files.find((candidate) => candidate.id === input.entryId); + const catalog = memoryCatalogFor(input.dataRoot, subject.agentManagementId); + const file = await catalog.get(input.entryId); if (!file) throw new MemoryBrowserNotFoundError("Memory entry was not found"); - const content = await fs.readFile(file.absolutePath, "utf8"); - return { - ...toEntry(file, content.slice(0, maxContentChars)), - }; + let content: string; + try { + content = await catalog.read(file); + } catch (error) { + // A page deleted outside the service inside the metadata window. + if ((error as NodeJS.ErrnoException).code === "ENOENT") + throw new MemoryBrowserNotFoundError("Memory entry was not found"); + throw error; + } + return toEntry(file, content.slice(0, maxContentChars)); } async function resolveSubject(input: BrowserRequest) { @@ -103,68 +81,7 @@ async function resolveSubject(input: BrowserRequest) { return subject; } -async function collectMemoryFiles( - dataRoot: string, - agentId: string, -): Promise { - const root = agentMemoryRoot(dataRoot, agentId); - const files: MemoryFile[] = []; - for (const directory of ["timeline/daily", "timeline/weekly"]) { - for await (const absolutePath of walkFiles(path.join(root, directory))) { - const relativePath = path - .relative(root, absolutePath) - .split(path.sep) - .join("/"); - const category = classifyPath(relativePath); - if (!category) continue; - const content = await fs.readFile(absolutePath, "utf8"); - const parsed = parseMemoryMarkdown(content); - const stat = await fs.stat(absolutePath); - const date = metadataDate(parsed.metadata.date) ?? pathDate(relativePath); - files.push({ - id: entryId(agentId, relativePath), - kind: category, - relativePath, - absolutePath, - title: parsed.title, - summary: parsed.summary, - updatedAt: stat.mtime.toISOString(), - ...(date ? { date } : {}), - }); - } - } - return files.sort( - (left, right) => - right.updatedAt.localeCompare(left.updatedAt) || - left.relativePath.localeCompare(right.relativePath), - ); -} - -function classifyPath(relativePath: string): MemoryEntryKind | undefined { - if ( - !relativePath.endsWith(".md") || - path.posix.basename(relativePath) === "index.md" - ) { - return undefined; - } - if (/^timeline\/daily\/[^/]+\.md$/u.test(relativePath)) { - return "daily"; - } - if (/^timeline\/weekly\/[^/]+\.md$/u.test(relativePath)) { - return "weekly"; - } - return undefined; -} - -function entryId(agentId: string, relativePath: string): string { - return `memory_${crypto - .createHash("sha256") - .update(`${agentId}\0${relativePath}`) - .digest("hex") - .slice(0, 24)}`; -} - -function toEntry(file: MemoryFile, content: string): MemoryEntry { +function toEntry(file: MemoryCatalogFile, content: string): MemoryEntry { return { content, id: file.id, @@ -176,23 +93,3 @@ function toEntry(file: MemoryFile, content: string): MemoryEntry { ...(file.date ? { date: file.date } : {}), }; } - -function parseCursor(value: string | undefined): number { - if (!value) return 0; - if (!/^[0-9]{1,9}$/u.test(value)) - throw new TypeError("Memory cursor is invalid"); - return Number(value); -} - -function metadataDate(value: unknown): string | undefined { - if (value instanceof Date && !Number.isNaN(value.valueOf())) { - return value.toISOString().slice(0, 10); - } - const string = stringValue(value); - return string && /^\d{4}-\d{2}-\d{2}$/u.test(string) ? string : undefined; -} - -function pathDate(relativePath: string): string | undefined { - const match = relativePath.match(/(?:^|\/)(\d{4}-\d{2}-\d{2})(?:\.md)?$/u); - return match?.[1]; -} diff --git a/apps/node-services/src/memory/memory-catalog.ts b/apps/node-services/src/memory/memory-catalog.ts new file mode 100644 index 000000000..04d69553d --- /dev/null +++ b/apps/node-services/src/memory/memory-catalog.ts @@ -0,0 +1,323 @@ +import crypto from "node:crypto"; +import fs from "node:fs/promises"; +import path from "node:path"; + +import { MEMORY_REVISION_FILE, walkFiles } from "./fs-utils.js"; +import { parseMemoryMarkdown, stringValue } from "./markdown.js"; +import { agentMemoryRoot, agentWorkspaceRoot } from "./paths.js"; + +const defaultLimit = 50; +const maximumCatalogs = 32; +/** Metadata may lag an external edit this long when nothing bumped the revision. */ +const defaultMaxStalenessMs = 5_000; + +export type MemoryEntryKind = "daily" | "weekly"; + +export interface MemoryCatalogFile { + readonly id: string; + readonly kind: MemoryEntryKind; + readonly relativePath: string; + readonly absolutePath: string; + readonly title: string; + readonly summary: string; + readonly updatedAt: string; + readonly date?: string; + readonly size: number; + readonly mtimeMs: number; +} + +export interface MemoryCatalogPage { + readonly items: readonly MemoryCatalogFile[]; + readonly nextCursor?: string; +} + +interface CatalogOptions { + readonly root: string; + readonly workspaceRoot: string; + /** The subject key the published entry IDs hash with. */ + readonly agentId: string; + readonly readFile?: typeof fs.readFile; + readonly stat?: typeof fs.stat; + readonly now?: () => number; + readonly maxStalenessMs?: number; +} + +/** + * The metadata of one Agent's daily and weekly Memory pages, kept between + * requests. A page is re-read only when its size or modification time changed, + * and the whole tree is walked only when `memory.revision` changed or the + * cached metadata is older than `maxStalenessMs`. + */ +export class MemoryCatalog { + readonly #root: string; + readonly #workspaceRoot: string; + readonly #agentId: string; + readonly #readFile: typeof fs.readFile; + readonly #stat: typeof fs.stat; + readonly #now: () => number; + readonly #maxStalenessMs: number; + readonly #entries = new Map(); + readonly #byId = new Map(); + #sorted: readonly MemoryCatalogFile[] | undefined; + #revision: string | undefined; + #refreshedAt = Number.NEGATIVE_INFINITY; + #refreshing: Promise | undefined; + + constructor(options: CatalogOptions) { + this.#root = options.root; + this.#workspaceRoot = options.workspaceRoot; + this.#agentId = options.agentId; + this.#readFile = options.readFile ?? fs.readFile; + this.#stat = options.stat ?? fs.stat; + this.#now = options.now ?? Date.now; + this.#maxStalenessMs = options.maxStalenessMs ?? defaultMaxStalenessMs; + } + + async list(input: { + kind?: string; + cursor?: string; + limit?: number; + }): Promise { + await this.#refresh(); + const files = input.kind + ? this.#snapshot().filter((file) => file.kind === input.kind) + : this.#snapshot(); + const start = cursorStart(files, input.cursor); + const limit = input.limit ?? defaultLimit; + const page = files.slice(start, start + limit); + const next = start + page.length; + const last = page.at(-1); + return { + items: page, + ...(last && next < files.length + ? { nextCursor: encodeCursor(last) } + : {}), + }; + } + + /** The entry of `id`, refreshing once more when the cached tree misses it. */ + async get(id: string): Promise { + if (await this.#refresh()) { + // The refresh just scanned the tree, so a miss is authoritative. + const cached = this.#byId.get(id); + if (cached) return cached; + return undefined; + } + const cached = this.#byId.get(id); + if (cached) return cached; + // A write that skipped `markMemoryChanged` must not hide a new page. + await this.#rescan(await this.#readRevision()); + return this.#byId.get(id); + } + + async read(file: MemoryCatalogFile): Promise { + return await this.#readFile(file.absolutePath, "utf8"); + } + + #snapshot(): readonly MemoryCatalogFile[] { + return this.#sorted ?? []; + } + + /** Reports whether this refresh scanned; an in-flight scan counts. */ + async #refresh(): Promise { + if (this.#refreshing) { + await this.#refreshing; + return true; + } + const revision = await this.#readRevision(); + const unchanged = + revision !== undefined && + revision === this.#revision && + this.#sorted !== undefined; + if (unchanged && this.#now() - this.#refreshedAt < this.#maxStalenessMs) { + return false; + } + await this.#rescan(revision); + return true; + } + + /** One scan at a time, whether a read missed or the revision changed. */ + async #rescan(revision: string | undefined): Promise { + if (this.#refreshing) return await this.#refreshing; + this.#refreshing = this.#scan(revision).finally(() => { + this.#refreshing = undefined; + }); + return await this.#refreshing; + } + + async #scan(revision: string | undefined): Promise { + const seen = new Set(); + for (const directory of ["timeline/daily", "timeline/weekly"]) { + for await (const absolutePath of walkFiles( + path.join(this.#root, directory), + )) { + const relativePath = path + .relative(this.#root, absolutePath) + .split(path.sep) + .join("/"); + const kind = classifyPath(relativePath); + if (!kind) continue; + seen.add(relativePath); + let metadata: Awaited>; + try { + metadata = await this.#stat(absolutePath); + } catch (error) { + // A page removed between the walk and the stat is simply absent. + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + const cached = this.#entries.get(relativePath); + if ( + cached && + cached.size === metadata.size && + cached.mtimeMs === metadata.mtimeMs + ) { + continue; + } + let content: string; + try { + content = await this.#readFile(absolutePath, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + throw error; + } + const parsed = parseMemoryMarkdown(content); + const date = + metadataDate(parsed.metadata.date) ?? pathDate(relativePath); + this.#entries.set(relativePath, { + id: entryId(this.#agentId, relativePath), + kind, + relativePath, + absolutePath, + title: parsed.title, + summary: parsed.summary, + updatedAt: metadata.mtime.toISOString(), + ...(date ? { date } : {}), + size: metadata.size, + mtimeMs: metadata.mtimeMs, + }); + } + } + for (const relativePath of this.#entries.keys()) + if (!seen.has(relativePath)) this.#entries.delete(relativePath); + this.#byId.clear(); + for (const entry of this.#entries.values()) this.#byId.set(entry.id, entry); + this.#sorted = [...this.#entries.values()].sort( + (left, right) => + right.updatedAt.localeCompare(left.updatedAt) || + left.relativePath.localeCompare(right.relativePath), + ); + this.#revision = revision; + this.#refreshedAt = this.#now(); + } + + async #readRevision(): Promise { + try { + return ( + await this.#readFile( + path.join(this.#workspaceRoot, MEMORY_REVISION_FILE), + "utf8", + ) + ).trim(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } + } +} + +const catalogs = new Map(); + +/** The catalog of one Agent, evicting the least recently used one past the cap. */ +export function memoryCatalogFor( + dataRoot: string, + agentId: string, +): MemoryCatalog { + const workspaceRoot = agentWorkspaceRoot(dataRoot, agentId); + const cached = catalogs.get(workspaceRoot); + if (cached) { + catalogs.delete(workspaceRoot); + catalogs.set(workspaceRoot, cached); + return cached; + } + const catalog = new MemoryCatalog({ + agentId, + root: agentMemoryRoot(dataRoot, agentId), + workspaceRoot, + }); + catalogs.set(workspaceRoot, catalog); + for (const key of catalogs.keys()) { + if (catalogs.size <= maximumCatalogs) break; + catalogs.delete(key); + } + return catalog; +} + +/** A stable page cursor: the sort key of the last item already read. */ +function encodeCursor(file: MemoryCatalogFile | undefined): string { + if (!file) throw new TypeError("Memory cursor needs a page item"); + return Buffer.from( + JSON.stringify({ p: file.relativePath, u: file.updatedAt }), + "utf8", + ).toString("base64url"); +} + +/** The index of the first item after `cursor`, or 0 without one. */ +function cursorStart( + files: readonly MemoryCatalogFile[], + cursor: string | undefined, +): number { + if (!cursor) return 0; + // Older servers paged by array offset; keep answering their cursors. + if (/^[0-9]{1,9}$/u.test(cursor)) + return Math.min(Number(cursor), files.length); + let key: { p?: unknown; u?: unknown }; + try { + key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as { + p?: unknown; + u?: unknown; + }; + } catch { + throw new TypeError("Memory cursor is invalid"); + } + const { p, u } = key; + if (typeof p !== "string" || typeof u !== "string") + throw new TypeError("Memory cursor is invalid"); + const index = files.findIndex( + (file) => + file.updatedAt < u || + (file.updatedAt === u && file.relativePath.localeCompare(p) > 0), + ); + return index === -1 ? files.length : index; +} + +function classifyPath(relativePath: string): MemoryEntryKind | undefined { + if ( + !relativePath.endsWith(".md") || + path.posix.basename(relativePath) === "index.md" + ) + return undefined; + if (/^timeline\/daily\/[^/]+\.md$/u.test(relativePath)) return "daily"; + if (/^timeline\/weekly\/[^/]+\.md$/u.test(relativePath)) return "weekly"; + return undefined; +} + +function entryId(agentId: string, relativePath: string): string { + return `memory_${crypto + .createHash("sha256") + .update(`${agentId}\0${relativePath}`) + .digest("hex") + .slice(0, 24)}`; +} + +function metadataDate(value: unknown): string | undefined { + if (value instanceof Date && !Number.isNaN(value.valueOf())) + return value.toISOString().slice(0, 10); + const string = stringValue(value); + return string && /^\d{4}-\d{2}-\d{2}$/u.test(string) ? string : undefined; +} + +function pathDate(relativePath: string): string | undefined { + const match = relativePath.match(/(?:^|\/)(\d{4}-\d{2}-\d{2})(?:\.md)?$/u); + return match?.[1]; +} diff --git a/apps/node-services/src/memory/server.ts b/apps/node-services/src/memory/server.ts index fd8e59634..2168349b6 100644 --- a/apps/node-services/src/memory/server.ts +++ b/apps/node-services/src/memory/server.ts @@ -714,7 +714,7 @@ function parseMemoryEntryListRequest(search: URLSearchParams): { !isId(tenantId) || !isId(ownerActorId) || (kind !== undefined && !/^[A-Za-z][A-Za-z0-9_-]{0,31}$/u.test(kind)) || - (cursor !== undefined && !/^[0-9]{1,9}$/u.test(cursor)) + (cursor !== undefined && !/^[A-Za-z0-9_-]{1,1024}$/u.test(cursor)) ) { throw new TypeError("Memory entry list request is invalid"); } diff --git a/apps/node-services/tests/memory/memory-browser.test.ts b/apps/node-services/tests/memory/memory-browser.test.ts index 8ed89aca4..2d348b906 100644 --- a/apps/node-services/tests/memory/memory-browser.test.ts +++ b/apps/node-services/tests/memory/memory-browser.test.ts @@ -2,42 +2,158 @@ import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ subjects: vi.fn() })); + +vi.mock("../../src/memory/collector.js", () => ({ + loadWikiGraphSubjectsForActor: mocks.subjects, +})); import { getMemoryEntry, listMemoryEntries, + MemoryBrowserNotFoundError, } from "../../src/memory/memory-browser.js"; +import { agentMemoryRoot, agentWorkspaceRoot } from "../../src/memory/paths.js"; -vi.mock("../../src/memory/collector.js", () => ({ - loadWikiGraphSubjectsForActor: async () => [ - { tenantId: "tenant_1", agentManagementId: "agent_alice" }, - ], -})); +const tenantId = "tenant-1"; +const ownerActorId = "actor-1"; +const agentId = "agent-1"; +let dataRoot: string; + +beforeEach(async () => { + dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), "memory-browser-")); + mocks.subjects.mockResolvedValue([{ tenantId, agentManagementId: agentId }]); +}); + +afterEach(async () => { + await fs.rm(dataRoot, { force: true, recursive: true }); +}); + +async function writePage(relativePath: string, title: string, modified?: Date) { + const target = path.join(agentMemoryRoot(dataRoot, agentId), relativePath); + await fs.mkdir(path.dirname(target), { recursive: true }); + await fs.writeFile(target, `---\ntitle: ${title}\n---\n${title} body\n`); + if (modified) await fs.utimes(target, modified, modified); + return target; +} + +async function writeReport( + relativePath: string, + content: string, + modified?: Date, +) { + const target = path.join(agentMemoryRoot(dataRoot, agentId), relativePath); + await fs.mkdir(path.dirname(target), { recursive: true }); + await fs.writeFile(target, content); + if (modified) await fs.utimes(target, modified, modified); + return target; +} + +async function bump(token: string) { + await fs.mkdir(agentWorkspaceRoot(dataRoot, agentId), { recursive: true }); + await fs.writeFile( + path.join(agentWorkspaceRoot(dataRoot, agentId), "memory.revision"), + `${token}\n`, + ); +} + +describe("memory browser", () => { + it("lists pages without their content and reads one by id", async () => { + await writePage( + "timeline/daily/2026-01-01.md", + "First", + new Date("2026-01-01T00:00:00Z"), + ); + await writePage( + "timeline/weekly/2026-W01.md", + "Week one", + new Date("2026-01-02T00:00:00Z"), + ); + await bump("revision-1"); + + const page = await listMemoryEntries({ + dataRoot, + tenantId, + ownerActorId, + }); + expect(page.items.map((item) => item.title)).toEqual(["Week one", "First"]); + expect(page.items.every((item) => item.content === "")).toBe(true); -it("lists and reads reports beside a file with malformed metadata", async () => { - const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), "memory-browser-")); - try { - const daily = path.join( + const entry = await getMemoryEntry({ dataRoot, - "agent_alice", - "memory", - "timeline", - "daily", + tenantId, + ownerActorId, + entryId: page.items[0]!.id, + }); + expect(entry.path).toBe("timeline/weekly/2026-W01.md"); + expect(entry.content).toContain("Week one body"); + }); + + it("pages with a cursor that a newer page cannot shift", async () => { + await writePage( + "timeline/daily/2026-01-01.md", + "A", + new Date("2026-01-01T00:00:00Z"), + ); + await writePage( + "timeline/daily/2026-01-02.md", + "B", + new Date("2026-01-02T00:00:00Z"), + ); + await writePage( + "timeline/daily/2026-01-03.md", + "C", + new Date("2026-01-03T00:00:00Z"), ); - await fs.mkdir(daily, { recursive: true }); + await bump("revision-1"); + + const first = await listMemoryEntries({ + dataRoot, + tenantId, + ownerActorId, + limit: 2, + }); + expect(first.items.map((item) => item.title)).toEqual(["C", "B"]); + + await writePage( + "timeline/daily/2026-01-04.md", + "D", + new Date("2026-01-04T00:00:00Z"), + ); + await bump("revision-2"); + const second = await listMemoryEntries({ + dataRoot, + tenantId, + ownerActorId, + cursor: first.next_cursor, + }); + expect(second.items.map((item) => item.title)).toEqual(["A"]); + }); + + it("lists and reads reports beside a file with malformed metadata", async () => { const broken = "---\nsources: [unfinished\n---\n\n# Recovered report\n\nThe body remains readable.\n"; const healthy = "---\ntitle: Healthy report\n---\n\n# Daily\n\nA separate report is intact.\n"; - await fs.writeFile(path.join(daily, "2026-11-18.md"), broken); - await fs.writeFile(path.join(daily, "2026-11-19.md"), healthy); - const input = { + const brokenPath = await writeReport( + "timeline/daily/2026-11-18.md", + broken, + new Date("2026-11-18T00:00:00Z"), + ); + await writeReport( + "timeline/daily/2026-11-19.md", + healthy, + new Date("2026-11-19T00:00:00Z"), + ); + await bump("revision-374"); + + const page = await listMemoryEntries({ dataRoot, - tenantId: "tenant_1", - ownerActorId: "actor_alice", - }; - const page = await listMemoryEntries(input); + tenantId, + ownerActorId, + }); expect(page.items).toHaveLength(2); expect(page.items).toEqual( expect.arrayContaining([ @@ -52,17 +168,43 @@ it("lists and reads reports beside a file with malformed metadata", async () => for (const [title, content] of [ ["Recovered report", broken], ["Healthy report", healthy], - ]) { + ] as const) { const entryId = page.items.find((item) => item.title === title)!.id; - expect(await getMemoryEntry({ ...input, entryId })).toMatchObject({ - title, - content, - }); + expect( + await getMemoryEntry({ dataRoot, tenantId, ownerActorId, entryId }), + ).toMatchObject({ title, content }); } - expect(await fs.readFile(path.join(daily, "2026-11-18.md"), "utf8")).toBe( - broken, + expect(await fs.readFile(brokenPath, "utf8")).toBe(broken); + }); + + it("reports a page deleted outside the service as not found", async () => { + const target = await writePage( + "timeline/daily/2026-02-01.md", + "Gone soon", + new Date("2026-02-01T00:00:00Z"), ); - } finally { - await fs.rm(dataRoot, { recursive: true, force: true }); - } + await bump("revision-2"); + const page = await listMemoryEntries({ + dataRoot, + tenantId, + ownerActorId, + }); + const entryId = page.items[0]!.id; + await fs.rm(target); + await expect( + getMemoryEntry({ dataRoot, tenantId, ownerActorId, entryId }), + ).rejects.toBeInstanceOf(MemoryBrowserNotFoundError); + }); + + it("reports a missing page as not found", async () => { + await bump("revision-1"); + await expect( + getMemoryEntry({ + dataRoot, + tenantId, + ownerActorId, + entryId: "memory_missing", + }), + ).rejects.toBeInstanceOf(MemoryBrowserNotFoundError); + }); }); diff --git a/apps/node-services/tests/memory/memory-catalog.test.ts b/apps/node-services/tests/memory/memory-catalog.test.ts new file mode 100644 index 000000000..70f142b4d --- /dev/null +++ b/apps/node-services/tests/memory/memory-catalog.test.ts @@ -0,0 +1,367 @@ +import { createHash } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { MemoryCatalog } from "../../src/memory/memory-catalog.js"; + +const roots: string[] = []; + +afterEach(async () => { + await Promise.all( + roots + .splice(0) + .map((root) => fs.rm(root, { force: true, recursive: true })), + ); +}); + +async function workspace() { + const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), "memory-catalog-")); + roots.push(dataRoot); + const agentId = "agent-1"; + return { + agentId, + memoryRoot: path.join(dataRoot, agentId, "memory"), + workspaceRoot: path.join(dataRoot, agentId), + }; +} + +async function page( + memoryRoot: string, + relativePath: string, + title: string, + modified?: Date, +) { + const target = path.join(memoryRoot, relativePath); + await fs.mkdir(path.dirname(target), { recursive: true }); + // A distinct size per title keeps size-based change detection honest even + // when two writes land in the same millisecond. + await fs.writeFile(target, `---\ntitle: ${title}\n---\n${title}\n`); + if (modified) await fs.utimes(target, modified, modified); + return target; +} + +async function bump(workspaceRoot: string, token: string) { + await fs.mkdir(workspaceRoot, { recursive: true }); + await fs.writeFile(path.join(workspaceRoot, "memory.revision"), `${token}\n`); +} + +function open(options: { + agentId: string; + memoryRoot: string; + workspaceRoot: string; + maxStalenessMs?: number; +}) { + const reads: string[] = []; + const readFile = (async (target: string, encoding: BufferEncoding) => { + reads.push(target); + return await fs.readFile(target, encoding); + }) as typeof fs.readFile; + const catalog = new MemoryCatalog({ + agentId: options.agentId, + root: options.memoryRoot, + workspaceRoot: options.workspaceRoot, + readFile, + maxStalenessMs: options.maxStalenessMs ?? 60_000, + }); + return { + catalog, + pageReads: () => reads.filter((target) => target.endsWith(".md")).length, + }; +} + +describe("MemoryCatalog", () => { + it("serves the cached index without reading pages again", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "First", + new Date("2026-01-01T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-02.md", + "Second", + new Date("2026-01-02T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-1"); + const { catalog, pageReads } = open({ agentId, memoryRoot, workspaceRoot }); + + const first = await catalog.list({}); + expect(first.items.map((item) => item.title)).toEqual(["Second", "First"]); + expect(pageReads()).toBe(2); + + const second = await catalog.list({ kind: "daily" }); + expect(second.items).toHaveLength(2); + expect(pageReads()).toBe(2); + }); + + it("does not scan twice when get misses after a refresh", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page(memoryRoot, "timeline/daily/2026-01-01.md", "First"); + await bump(workspaceRoot, "revision-1"); + let stats = 0; + const stat = (async (target: string) => { + stats += 1; + return await fs.stat(target); + }) as typeof fs.stat; + const readFile = (async (target: string, encoding: BufferEncoding) => + await fs.readFile(target, encoding)) as typeof fs.readFile; + const catalog = new MemoryCatalog({ + agentId, + root: memoryRoot, + workspaceRoot, + readFile, + stat, + maxStalenessMs: 60_000, + }); + + await expect(catalog.get("memory_missing")).resolves.toBeUndefined(); + expect(stats).toBe(1); + }); + + it("returns an empty page without a cursor when the limit is zero", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page(memoryRoot, "timeline/daily/2026-01-01.md", "First"); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + const listed = await catalog.list({ limit: 0 }); + expect(listed.items).toEqual([]); + expect(listed.nextCursor).toBeUndefined(); + }); + + it("reads only the page whose size or modification time changed", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "First", + new Date("2026-01-01T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-02.md", + "Second", + new Date("2026-01-02T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-1"); + const { catalog, pageReads } = open({ agentId, memoryRoot, workspaceRoot }); + await catalog.list({}); + expect(pageReads()).toBe(2); + + // Same modification time, a longer body: only the size tells them apart. + await page( + memoryRoot, + "timeline/daily/2026-01-02.md", + "Second, revised", + new Date("2026-01-02T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-2"); + const revised = await catalog.list({}); + expect(revised.items.map((item) => item.title)).toEqual([ + "Second, revised", + "First", + ]); + expect(pageReads()).toBe(3); + }); + + it("adds and removes pages after a revision bump", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + const first = await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "First", + ); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + expect((await catalog.list({})).items).toHaveLength(1); + + await page(memoryRoot, "timeline/weekly/2026-W01.md", "Week one"); + await bump(workspaceRoot, "revision-2"); + expect((await catalog.list({})).items).toHaveLength(2); + + await fs.rm(first); + await bump(workspaceRoot, "revision-3"); + const afterRemoval = await catalog.list({}); + expect(afterRemoval.items.map((item) => item.title)).toEqual(["Week one"]); + }); + + it("finds a page written without a revision bump", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ + agentId, + memoryRoot, + workspaceRoot, + maxStalenessMs: 0, + }); + expect((await catalog.list({})).items).toHaveLength(0); + + await page(memoryRoot, "timeline/daily/2026-01-03.md", "Unannounced"); + const listed = await catalog.list({}); + expect(listed.items.map((item) => item.title)).toEqual(["Unannounced"]); + }); + + it("keeps a stable cursor when a newer page arrives", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "A", + new Date("2026-01-01T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-02.md", + "B", + new Date("2026-01-02T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-03.md", + "C", + new Date("2026-01-03T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-04.md", + "D", + new Date("2026-01-04T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + + const first = await catalog.list({ limit: 2 }); + expect(first.items.map((item) => item.title)).toEqual(["D", "C"]); + expect(first.nextCursor).toBeDefined(); + + await page( + memoryRoot, + "timeline/daily/2026-01-05.md", + "E", + new Date("2026-01-05T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-2"); + const second = await catalog.list({ + cursor: first.nextCursor, + limit: 2, + }); + expect(second.items.map((item) => item.title)).toEqual(["B", "A"]); + expect(second.nextCursor).toBeUndefined(); + }); + + it("answers a legacy offset cursor", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "A", + new Date("2026-01-01T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-02.md", + "B", + new Date("2026-01-02T00:00:00Z"), + ); + await page( + memoryRoot, + "timeline/daily/2026-01-03.md", + "C", + new Date("2026-01-03T00:00:00Z"), + ); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + expect((await catalog.list({ cursor: "2" })).items[0]?.title).toBe("A"); + }); + + it("rejects an unreadable cursor", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + await expect(catalog.list({ cursor: "not-a-cursor" })).rejects.toThrow( + /cursor/i, + ); + }); + + it("reads page content fresh for an open entry", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + const target = await page( + memoryRoot, + "timeline/daily/2026-01-01.md", + "First", + ); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + const file = (await catalog.list({})).items[0]!; + expect(await catalog.read(file)).toContain("First"); + + await fs.writeFile(target, "---\ntitle: First\n---\nchanged body\n"); + expect(await catalog.read(file)).toContain("changed body"); + }); + + it("pages across paths that localeCompare orders differently from code units", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + const same = new Date("2026-03-01T00:00:00Z"); + await page(memoryRoot, "timeline/daily/a.md", "Lower", same); + await page(memoryRoot, "timeline/daily/B.md", "Upper", same); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + + const first = await catalog.list({ limit: 1 }); + expect(first.items.map((item) => item.title)).toEqual(["Lower"]); + const second = await catalog.list({ cursor: first.nextCursor }); + expect(second.items.map((item) => item.title)).toEqual(["Upper"]); + }); + + it("stats pages again only after the metadata window", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page(memoryRoot, "timeline/daily/2026-01-01.md", "First"); + await page(memoryRoot, "timeline/daily/2026-01-02.md", "Second"); + await bump(workspaceRoot, "revision-1"); + const stats: string[] = []; + let now = 1_000; + const stat = (async (target: string) => { + stats.push(target); + return await fs.stat(target); + }) as typeof fs.stat; + const readFile = (async (target: string, encoding: BufferEncoding) => + await fs.readFile(target, encoding)) as typeof fs.readFile; + const catalog = new MemoryCatalog({ + agentId, + root: memoryRoot, + workspaceRoot, + readFile, + stat, + now: () => now, + maxStalenessMs: 1_000, + }); + + await catalog.list({}); + expect(stats).toHaveLength(2); + stats.length = 0; + + now += 999; + await catalog.list({}); + expect(stats).toHaveLength(0); + + now += 1; + await catalog.list({}); + expect(stats).toHaveLength(2); + }); + + it("keeps the published entry id for a page path", async () => { + const { agentId, memoryRoot, workspaceRoot } = await workspace(); + await page(memoryRoot, "timeline/daily/2026-01-01.md", "First"); + await bump(workspaceRoot, "revision-1"); + const { catalog } = open({ agentId, memoryRoot, workspaceRoot }); + const file = (await catalog.list({})).items[0]!; + const expected = `memory_${createHash("sha256") + .update(`${agentId}\0timeline/daily/2026-01-01.md`) + .digest("hex") + .slice(0, 24)}`; + expect(file.id).toBe(expected); + }); +}); diff --git a/apps/node-services/tests/memory/memory-http-cursor.test.ts b/apps/node-services/tests/memory/memory-http-cursor.test.ts new file mode 100644 index 000000000..ff19e4b6b --- /dev/null +++ b/apps/node-services/tests/memory/memory-http-cursor.test.ts @@ -0,0 +1,119 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../../src/memory/collector.js", () => ({ + loadWikiGraphSubjectsForActor: async () => [ + { tenantId: "tenant_1", agentManagementId: "agent_alice" }, + ], +})); + +import type { MemoryScheduleConfig } from "../../src/memory/config.js"; +import { MemoryScheduler } from "../../src/memory/scheduler.js"; +import { startMemoryServer } from "../../src/memory/server.js"; + +const schedule: MemoryScheduleConfig = { + concurrency: 1, + timeZone: "Asia/Shanghai", + weeklyDay: 1, +}; +const token = "memory-http-token"; +const quarantine: string[] = []; +const closers: Array<() => Promise> = []; + +afterEach(async () => { + await Promise.all(closers.splice(0).map((close) => close())); + await Promise.all( + quarantine + .splice(0) + .map((root) => fs.rm(root, { force: true, recursive: true })), + ); +}); + +async function start(): Promise<{ dataRoot: string; url: string }> { + const dataRoot = await fs.mkdtemp(path.join(os.tmpdir(), "memory-http-")); + quarantine.push(dataRoot); + const server = await startMemoryServer({ + dataRoot, + host: "127.0.0.1", + port: 0, + scheduler: new MemoryScheduler(schedule, async () => {}), + serviceToken: token, + }); + closers.push(() => server.close()); + return { dataRoot, url: server.url }; +} + +async function page(dataRoot: string, date: string, title: string) { + const directory = path.join( + dataRoot, + "agent_alice", + "memory", + "timeline", + "daily", + ); + await fs.mkdir(directory, { recursive: true }); + const target = path.join(directory, `${date}.md`); + await fs.writeFile(target, `---\ntitle: ${title}\n---\n${title}\n`); + const modified = new Date(`${date}T00:00:00Z`); + await fs.utimes(target, modified, modified); +} + +async function bump(dataRoot: string) { + await fs.writeFile( + path.join(dataRoot, "agent_alice", "memory.revision"), + "revision-http\n", + ); +} + +async function entries( + url: string, + query: Record, +): Promise { + const search = new URLSearchParams({ + owner_actor_id: "actor_alice", + tenant_id: "tenant_1", + ...query, + }); + return await fetch(`${url}/internal/v1/memory/entries?${search}`, { + headers: { authorization: `Bearer ${token}` }, + }); +} + +describe("Memory entries HTTP paging", () => { + it("pages with the catalog cursor the response returned", async () => { + const { dataRoot, url } = await start(); + await page(dataRoot, "2026-04-01", "A"); + await page(dataRoot, "2026-04-02", "B"); + await page(dataRoot, "2026-04-03", "C"); + await bump(dataRoot); + + const first = await entries(url, { limit: "2" }); + expect(first.status).toBe(200); + const firstPage = (await first.json()) as { + items: Array<{ title: string }>; + next_cursor?: string; + }; + expect(firstPage.items.map((item) => item.title)).toEqual(["C", "B"]); + expect(firstPage.next_cursor).toBeDefined(); + + const second = await entries(url, { + cursor: firstPage.next_cursor!, + limit: "2", + }); + expect(second.status).toBe(200); + const secondPage = (await second.json()) as { + items: Array<{ title: string }>; + next_cursor?: string; + }; + expect(secondPage.items.map((item) => item.title)).toEqual(["A"]); + expect(secondPage.next_cursor).toBeUndefined(); + }); + + it("rejects a cursor that is not opaque page data", async () => { + const { url } = await start(); + expect((await entries(url, { cursor: "not a cursor!" })).status).toBe(400); + }); +}); diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.go index e84e576be..5acde1f33 100644 --- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go +++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go @@ -1708,6 +1708,9 @@ type ConflictedDocumentChangeResult struct { // ConflictedDocumentChangeResultReason defines model for ConflictedDocumentChangeResult.Reason. type ConflictedDocumentChangeResultReason string +// Cursor Opaque pagination cursor. Clients must not parse or modify it. +type Cursor = string + // DeleteDocumentBlocksSemanticOperation defines model for DeleteDocumentBlocksSemanticOperation. type DeleteDocumentBlocksSemanticOperation struct { Kind string `json:"kind"` @@ -2102,8 +2105,10 @@ type MemoryEntryKind string // MemoryEntryPage defines model for MemoryEntryPage. type MemoryEntryPage struct { - Items []MemoryEntry `json:"items"` - NextCursor *string `json:"next_cursor,omitempty"` + Items []MemoryEntry `json:"items"` + + // NextCursor Opaque pagination cursor. Clients must not parse or modify it. + NextCursor *Cursor `json:"next_cursor,omitempty"` } // MemoryErrorResponse defines model for MemoryErrorResponse. diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts index a239b1e2b..7e14235f8 100644 --- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts +++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts @@ -832,7 +832,7 @@ export interface components { }; MemoryEntryPage: { items: components["schemas"]["MemoryEntry"][]; - next_cursor?: string; + next_cursor?: components["schemas"]["Cursor"]; }; PocketNoteTrackingRefreshRequest: { tenant_id: components["schemas"]["AgentId"]; @@ -1759,6 +1759,8 @@ export interface components { /** @enum {string} */ status: "cancel_requested" | "canceled" | "already_terminal"; }; + /** @description Opaque pagination cursor. Clients must not parse or modify it. */ + Cursor: string; /** @description Opaque, case-sensitive TeamHub identifier. */ DocumentInternalId: string; SchemaVersion: number; diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml index 567f2e5e9..29a0fa2b3 100644 --- a/contracts/openapi/node-services-internal/openapi.yaml +++ b/contracts/openapi/node-services-internal/openapi.yaml @@ -653,7 +653,7 @@ paths: required: false schema: type: string - pattern: ^[0-9]{1,9}$ + pattern: ^[A-Za-z0-9_-]{1,1024}$ - name: limit in: query required: false @@ -1737,8 +1737,7 @@ components: items: $ref: "#/components/schemas/MemoryEntry" next_cursor: - type: string - pattern: ^[0-9]{1,9}$ + $ref: ../components/common.yaml#/components/schemas/Cursor PocketNoteTrackingRefreshRequest: type: object additionalProperties: false