Skip to content

perf(memory): serve the memory browser from an incremental catalog - #433

Open
Lumea-art wants to merge 1 commit into
simplexai-labs:mainfrom
Lumea-art:perf/memory-browser-catalog
Open

Lumea-art wants to merge 1 commit into
simplexai-labs:mainfrom
Lumea-art:perf/memory-browser-catalog

Conversation

@Lumea-art

@Lumea-art Lumea-art commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What and why

listMemoryEntries and getMemoryEntry walked timeline/daily and timeline/weekly, read every Markdown page, parsed its frontmatter and stat'ed it, on every request. One page per day plus weekly pages means the cost grows with the Agent's history, and getMemoryEntry paid the whole walk to find a single page.

This adds apps/node-services/src/memory/memory-catalog.ts: one in-process catalog per Agent workspace that keeps each page's metadata and re-reads a page only when its size or modification time changed. It keys off memory.revision, the token markMemoryChanged already writes after every batch of Memory writes, so a service write invalidates the list immediately. A write that skipped the token is still caught by a 5-second staleness scan and by a forced rescan when get misses.

memory-browser.ts now maps catalog pages to the API response, and getMemoryEntry reads only the requested page. A page deleted outside the service inside the window answers not-found instead of failing on the read.

Cursors move from an array offset to the sort key of the last item (updated_at + path), so a page inserted between two requests cannot shift or repeat items; numeric cursors from older servers are still accepted.

Review fixes (rebased onto 1c35212)

  • P2 — MemoryEntryPage.next_cursor now refs components/common.yaml#/components/schemas/Cursor instead of the digit-only pattern; regenerated Go and TypeScript contracts.
  • Double scan — #refresh() now reports whether it scanned. A get(id) miss right after a refresh no longer rescans the whole tree; only a miss with no fresh scan forces a rescan. Added a test that counts stat calls: one miss after the initial scan stats once.
  • Zero limit — list guards that the page is non-empty before encoding a cursor, so a programmatic limit: 0 returns an empty page instead of throwing. Added a test.
  • README — now says the cursor is an opaque keyset (last page's updated_at + path), stable across inserts, with numeric offset cursors still accepted.

Measurements

2000 daily pages, local ext4, median of 5 runs:

Request Before After
First list after start 282 ms 285 ms
List with no Memory change 282 ms under 1 ms
get by id full walk one page read

The "under 1 ms" row holds inside the five-second metadata window. After it, or after any memory.revision bump, list walks and stats every page but still reads none; the cold row covers that path. The tests assert the read and stat counts deterministically, so the gain does not depend on a benchmark machine.

How it was verified

  • memory-catalog.test.ts (13): cached index not re-read; only a changed page re-read; add/remove after a revision bump; a page written without a bump found; stable cursor across an insertion; legacy offset cursor; invalid cursor; fresh content; published entry IDs; stat-only refresh window; get miss scans once; limit: 0.
  • memory-browser.test.ts (5), memory-http-cursor.test.ts (2), server-http.test.ts (6): API mapping, HTTP paging with the returned cursor, not-found cases.
  • pnpm --filter @linger/node-services typecheck; pnpm contracts:generate and contracts:verify; eslint/prettier on the changed files. 26 tests pass across the four files.

Boundary

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes (1 P1, 1 P2, 1 P3)

Scope: base main, merge base 1ffbcd28; 1 commit and 4 files reviewed at 212f6279. Helper skills loaded: coderbook, ponytail-review, karpathy-guidelines. Ran in a separate session.

Findings

P1

1. The HTTP route rejects the new cursors, so page 2 always fails (apps/node-services/src/memory/server.ts:717)

  • parseMemoryEntryListRequest still requires cursor to match /^[0-9]{1,9}$/u and throws TypeError otherwise. onError (server.ts:85) turns that into HTTP 400.
  • MemoryCatalog.list now returns next_cursor from encodeCursor (memory-catalog.ts:256), which is base64url JSON and never all digits. When TeamHub sends that cursor back, Node Services answers 400. TeamHub treats it as an internal error (apps/teamhub/internal/memoryclient/client.go:196, handlers_personal_wiki.go:93).
  • Who is affected: listReports in apps/web/src/features/memory/wiki-period-reports.ts:33-50 loops over every page with limit: 100. Any Agent with more than 100 daily pages (about three months of history) gets an error for the whole Daily report list instead of a second page. Before this PR, the numeric offset cursor passed this check.
  • Why the tests miss it: memory-browser.test.ts calls listMemoryEntries directly and never goes through the HTTP parser.
  • Fix: drop the cursor format check from parseMemoryEntryListRequest, or relax it to the contract's opaque Cursor (1 to 1024 chars, contracts/openapi/components/common.yaml:40). cursorStart already throws TypeError on a malformed cursor. Add an HTTP-level test in server.test.ts that follows next_cursor to the second page.

P2

2. MEMORY_REVISION_FILE is defined a second time (apps/node-services/src/memory/memory-catalog.ts:10)

  • fs-utils.ts:8 already exports MEMORY_REVISION_FILE, and markMemoryChanged writes it. The catalog's whole invalidation scheme depends on both copies naming the same file. If one is renamed and the other is not, the catalog stops seeing writes and falls back to the 5-second staleness scan without any error.
  • Fix: import { MEMORY_REVISION_FILE, walkFiles } from "./fs-utils.js"; and delete the local constant.

P3

3. Unused injection options and exports (apps/node-services/src/memory/memory-catalog.ts:41-45, 246, 251, 261)

  • The stat, walk and now constructor options have no caller. The tests inject only readFile and maxStalenessMs (tests/memory/memory-catalog.test.ts:62-68).
  • resetMemoryCatalogs says "tests use it between cases", but nothing calls it.
  • encodeCursor and cursorStart are exported but used only inside this module.
  • Fix: delete the three options and resetMemoryCatalogs, and make the cursor helpers module-private. That removes about 15 lines.

Verified as fine

  • The revision token is the same file the writers bump. agentWorkspaceRoot(dataRoot, agentId)/memory.revision (memory-catalog.ts:208) matches markMemoryChanged (fs-utils.ts:18-20), which writes it through an atomic rename with a fresh UUID. Service writers call it after their writes (apply.ts:123, sync-runners.ts:153, published-memory-files.ts:201, rebuild.ts:171).
  • Entry IDs, kind classification, date extraction and sort order are moved unchanged from the old memory-browser.ts: same entryId hash input, same classifyPath regexes, same updatedAt desc, relativePath asc comparator (memory-catalog.ts:191-195). The published IDs stay stable.
  • Only one scan runs at a time. #refresh and #rescan both join #refreshing (memory-catalog.ts:119, 132). #sorted and #byId are swapped only at the end of #scan, so a scan that fails partway leaves the previous snapshot in place. #refreshing is cleared in finally.
  • A page that disappears between the walk and the stat/readFile is skipped on ENOENT, and any other error still propagates (memory-catalog.ts:153-171).
  • A missing timeline/* directory gives an empty walk (walkFiles checks pathExists, fs-utils.ts:97-100).
  • The cursor sort key compares the same updatedAt ISO strings and relativePath that the list is sorted by, so it skips correctly across an inserted page. A legacy numeric cursor is clamped to the list length (memory-catalog.ts:267-268).
  • The LRU cache is bounded at 32 workspaces, and its key is derived from agentWorkspaceRoot, which runs assertSafeAgentId first (paths.ts:7-9).
  • No CJK in the added lines. No contract, generated or env changes.

Process notes

  • The commit 212f6279 has only a subject. The repo's commit convention also asks for a body that says what changed and which problem it solves. No merge or fixup commits. The branch is up to date with main.

CI

The checks that ran passed (changes, repository-gate, check (web)); every other lane was skipped. The Node Services tests are not in PR CI, as the PR body notes, so the new catalog and browser tests and the HTTP path were not run in CI. I did not run tests myself: finding 1 is clear from the parser regex in server.ts:717 and the cursor format in memory-catalog.ts:256.

Automated review by Claude Code


Automated review of 212f627 by Claude Code.

@muterC

muterC commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Thanks for this one. The design looks right to me: entry IDs, sort order and the API shape are unchanged, legacy numeric cursors keep working, and the memory.revision path the catalog reads is the same one applyMemoryUpdate → markMemoryChanged bumps for Daily/Weekly writes.

I checked out the head (212f627) and ran it locally on macOS: node-services typecheck passes, and tests/memory gives 473 passed / 1 failed. PR CI does not run the node-services tests (only the fast gate), so the failure below was not caught there.

Blocking: one new test is flaky

MemoryCatalog > serves the cached index without reading pages again failed 3 of 5 runs:

pnpm --filter @linger/node-services exec vitest run tests/memory/memory-catalog.test.ts
- "Second", "First"
+ "First", "Second"

The two pages are written back to back without explicit times, so their mtimes often land in the same millisecond. The sort then falls back to relativePath ascending, and 2026-01-01.md comes first. The page() helper already takes a modified date; passing distinct dates for the two pages, as other cases in the file do, should make it deterministic.

Non-blocking

  1. The description's "under 1 ms with no Memory change" holds only within maxStalenessMs (5 s) of the last scan. After that, or after any memory.revision bump (including unrelated Memory writes), list walks and stats every page, though it still reads none. With an injected stat and 20 pages I saw 0 stats inside the window and 20 after it. That is still far cheaper than main, but the table could say so.
  2. If a page is deleted outside the service within the staleness window, get returns the cached entry and catalog.read then throws ENOENT, which getMemoryEntry surfaces as a 500 instead of MemoryBrowserNotFoundError. Mapping ENOENT from the read to not-found would close that.
  3. Merge order: a page with unrepairable YAML still makes parseMemoryMarkdown throw inside #scan, which fails the whole list, as it does on main today. fix(memory): retain readable reports with damaged metadata #374 fixes that, so landing fix(memory): retain readable reports with damaged metadata #374 first seems better. perf(memory): avoid reading unrelated report bodies for detail #376 looks superseded by this PR's single-page get.
  4. During a rolling deploy with old and new node-services side by side, an old process rejects the new base64url cursor with a 400. Node-services usually runs as one process, so this is probably fine; I am mentioning it only because the change touches cursor compatibility.

@muterC

muterC commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Follow-up now that #374 has merged (e777e3e). Two more things are needed before this can land, plus two smaller ones.

Needed

  1. Rebase and fold in the fix(memory): retain readable reports with damaged metadata #374 test. fix(memory): retain readable reports with damaged metadata #374 added apps/node-services/tests/memory/memory-browser.test.ts as a new file, and this PR adds a file at the same path, so the rebase hits an add/add conflict. Please keep this PR's version and move fix(memory): retain readable reports with damaged metadata #374's case ("lists and reads reports beside a file with malformed metadata") into it, using the existing writePage helper and mocks.subjects. That case is the only test showing that one damaged report cannot break the catalog. I merged both branches onto main locally: with fix(memory): retain readable reports with damaged metadata #374's parser change, the case passes through the catalog. Without it, #scan throws YAMLParseError and every list fails.
  2. Pin mtimes in two order-sensitive catalog tests. Besides serves the cached index without reading pages again (3 of 5 runs failed here), reads only the page whose size or modification time changed has the same exposure: it asserts ["Second, revised", "First"], but neither page is written with an explicit mtime. When two writes share a millisecond, the sort falls back to relativePath ascending and the order flips. Passing distinct modified dates to page(), as the other ordering tests already do, fixes both.

Smaller

  1. In getMemoryEntry, mapping an ENOENT from catalog.read to MemoryBrowserNotFoundError turns a page deleted outside the service within the staleness window into a 404 instead of a 500.
  2. The Memory README now describes the browser's damaged-metadata fallback (from fix(memory): retain readable reports with damaged metadata #374). One sentence beside it on the per-process catalog and the up-to-5-second lag for external edits would keep the owning docs aligned. The description's "under 1 ms" row could also note that it holds within the staleness window; after it, list stats every page but still reads none.

@Lumea-art
Lumea-art force-pushed the perf/memory-browser-catalog branch from 212f627 to bf6f37f Compare November 22, 2026 00:53
@Lumea-art

Copy link
Copy Markdown
Contributor Author

Thanks — all of it is in bf6f37f7, rebased on 2f03b64f (#374 merged).

Needed

  1. Rebased and folded fix(memory): retain readable reports with damaged metadata #374's case into this PR's memory-browser.test.ts, keeping this PR's version and using its writePage/mocks.subjects setup. tests/memory is 493 passed, 36 skipped; the folded case passes through #scan with fix(memory): retain readable reports with damaged metadata #374's parser fallback.
  2. Pinned mtimes on serves the cached index... and reads only the page whose size or modification time changed (the latter now rewrites with the same mtime so only size distinguishes it). Ran memory-catalog.test.ts ten times: 0 failures.

Smaller

  1. getMemoryEntry maps ENOENT from catalog.read to MemoryBrowserNotFoundError; added a test that deletes the page inside the window and expects not-found.
  2. The Memory README now has a sentence beside the damaged-metadata paragraph on the per-process catalog and the five-second external-edit lag; the description's under-1 ms row says it holds inside the window and that a later list stats every page but reads none.

Bot P3: dropped the unused walk option and resetMemoryCatalogs, and made the cursor helpers module-private. stat and now stay: a new catalog test drives the staleness window with them (2 stats on the first list, 0 inside, 2 after).

On merge order: with #374 in, the fallback runs before the catalog, so a damaged report cannot fail the whole list.

The only remaining trade-off is the mixed-version cursor note. If you would rather keep old processes working during a rollout, I can make list return the numeric cursor unless a page was inserted — but that reintroduces the offset shift, so I left it opaque.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes (1 P1, 1 P2, 1 P3)

Scope: follow-up on 212f627. Base main, merge base 2f03b64f, 1 commit (bf6f37f7), 5 files reviewed. The previous head was rebased onto a newer main, so I compared the memory files across both heads and re-read the full merge-base diff. Loaded coderbook, ponytail-review and karpathy-guidelines. Ran in a separate session.

Previous findings

  • P1 HTTP layer rejects the new base64url cursor: Not resolved. apps/node-services/src/memory/server.ts:717 still requires cursor to match ^[0-9]{1,9}$. The internal contract contracts/openapi/node-services-internal/openapi.yaml:656 also still declares that pattern. Every next_cursor the catalog now returns is base64url JSON (memory-catalog.ts:246-252), so fetching page 2 still returns 400 (Memory entry list request is invalid). TeamHub passes the cursor through unchanged: its public Cursor is an opaque string of up to 1024 chars (contracts/openapi/components/common.yaml:40-44). Once a Human has more than one page of reports (limit at most 100, default 50), "load more" in the Web Memory list fails. No test sends a catalog cursor through the HTTP route. The new tests call MemoryCatalog/listMemoryEntries directly.
  • P2 MEMORY_REVISION_FILE defined twice: Not resolved. memory-catalog.ts:10 still declares its own "memory.revision", while fs-utils.ts:8 exports the same constant that markMemoryChanged writes. These are two sources of truth for the invalidation token.
  • P3 unused injection points and exports: Resolved. The walk option and resetMemoryCatalogs are gone, and encodeCursor/cursorStart are now module-private. stat/now are used by the stat-only refresh test (memory-catalog.test.ts:284-291).

Findings

P1

  • apps/node-services/src/memory/server.ts:717: see the previous finding above. It still blocks merge. Fix: accept the opaque cursor here (for example ^[A-Za-z0-9_-]{1,1024}$, or just a length bound, since cursorStart already rejects malformed input with TypeError). Relax the cursor pattern in contracts/openapi/node-services-internal/openapi.yaml, run pnpm contracts:generate, and add an HTTP-level test that pages twice through /internal/v1/memory/entries.

P2

  • apps/node-services/src/memory/memory-catalog.ts:10: the duplicate MEMORY_REVISION_FILE (previous finding). Import it from ./fs-utils.js and delete the local constant.

P3

  • apps/node-services/src/memory/memory-catalog.ts:277: the cursor tie-break uses code-unit comparison (file.relativePath > p), but the list is sorted with localeCompare (:194-198). Example: timeline/daily/a.md and timeline/daily/B.md have the same mtime to the millisecond, and a page ends at a.md. localeCompare puts B.md after a.md, but "B.md" > "a.md" is false, so the next page silently skips B.md. Service-written date names don't hit this, but externally created pages can. Fix: compare paths with the same function in both places (plain </> in the sort, or localeCompare in cursorStart).

Verified as fine

  • Invalidation token location: the catalog reads <workspace>/memory.revision via agentWorkspaceRoot (memory-catalog.ts:207, :225). This is the same file markMemoryChanged renames into place (fs-utils.ts:18-30).
  • A cache miss in get forces one rescan, so a page written without a revision bump is still found (memory-catalog.ts:98-105). Concurrent refreshes share one in-flight scan (:115-135).
  • A page that disappears between walk, stat and read is skipped during the scan (:151-172). getMemoryEntry maps ENOENT on read to not-found (memory-browser.ts:61-69).
  • Entry IDs (sha256(agentId\0relativePath) truncated to 24 hex chars), path classification, date derivation and sort order match the deleted collectMemoryFiles logic. Published IDs are therefore unchanged.
  • Legacy numeric cursors are still honored inside the catalog (memory-catalog.ts:261-262).
  • The per-process LRU is capped at 32 workspaces (:238-241). Catalogs are keyed by workspace root, so tests that use separate temp data roots do not share state.
  • No CJK in added lines or the commit message. The commit is a single conventional commit.

Process notes

  • None. The branch is a single commit with no merge or fixup commits.

CI

  • changes, check (web) and repository-gate pass. Everything else was skipped. Node Services tests (check-node-services) are a heavy lane, so PR CI did not run the new catalog or browser tests or any HTTP-route test. I ran no tests myself: the P1 follows directly from the regex at server.ts:717 and the base64url cursor format.

Automated review by Claude Code


Automated review of bf6f37f by Claude Code.

@Lumea-art
Lumea-art force-pushed the perf/memory-browser-catalog branch from bf6f37f to b4694cc Compare November 22, 2026 11:13
@Lumea-art

Copy link
Copy Markdown
Contributor Author

Fixed in b4694cc8.

P1 (blocking) — server.ts now accepts the opaque cursor (^[A-Za-z0-9_-]{1,1024}$) and the internal contract pattern matches; pnpm contracts:generate and contracts:verify are clean. Added memory-http-cursor.test.ts: it starts the Memory server, pages twice through /internal/v1/memory/entries, and asserts page two is 200 with the remaining item; a malformed cursor still gets 400.

P2 — MEMORY_REVISION_FILE now comes from fs-utils.ts; the local constant is gone.

P3 — the cursor tie-break uses relativePath.localeCompare(p), the same comparison as the sort. Added a catalog test with a.md and B.md on the same millisecond: the first page ends at a.md, and the next page must return B.md (code-unit comparison skipped it).

Local: 24 tests across catalog/browser/HTTP/server-http pass; typecheck, eslint, prettier and contracts:verify are clean.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits (1 P2, 1 P3)

Scope: base main, merge base 2f03b64f, 1 commit, 8 files reviewed. Follow-up on bf6f37f. Loaded the review recipe's criteria (coderbook §二/三/五, ponytail-review §1–3, karpathy-guidelines §2–3); ran in a separate session.

Previous findings

  • Resolved: cursor comparison didn't match the sort order. apps/node-services/src/memory/memory-catalog.ts:274-276 now compares relativePath with localeCompare, the same comparator #scan sorts with (memory-catalog.ts:192-196). The new test pages across paths that localeCompare orders differently from code units (a.md/B.md with the same mtime) fails without the fix: the old > comparison returns an empty second page.

Since bf6f37f the commit also widened the server's cursor validation (server.ts:717) and the request-parameter pattern, and added memory-http-cursor.test.ts. That test pages through the real HTTP server with the cursor the response returned, so the new cursor format is now accepted end to end.

Findings

P2

  • contracts/openapi/node-services-internal/openapi.yaml:1741: the response schema MemoryEntryPage.next_cursor still says pattern: ^[0-9]{1,9}$, but the server now returns a base64url JSON key (memory-catalog.ts:248-254, e.g. eyJwIjoi...). The PR widened only the request parameter (line 656). The internal contract now describes a response the server can't produce. Any consumer or contract test that validates responses against it would reject every non-final page. Nothing validates this response at runtime today: the generated Go/TS code carries no pattern, and there's no embedded spec. Fix: give next_cursor the same ^[A-Za-z0-9_-]{1,1024}$ pattern, or $ref the shared common.yaml#/components/schemas/Cursor the public MemoryEntryPage already uses.

P3

  • apps/node-services/src/memory/README.md:24: "The published entry IDs, sort order and cursor semantics are unchanged." The cursor did change, from an array offset to an updated_at + path key, and older servers reject the new format. The PR body says the same in its Boundary section. Say what the cursor is now (an opaque sort key, stable across inserts, with numeric offsets still accepted) instead of calling it unchanged.

Verified as fine

  • Invalidation keys off the real token: markMemoryChanged writes agentWorkspaceRoot(dataRoot, agentId)/memory.revision (fs-utils.ts:18-30). The catalog reads the same path through the shared MEMORY_REVISION_FILE (memory-catalog.ts:5,205), with the same agentManagementId subject key the old walk used (memory-browser.ts:29-32).
  • Only one scan runs at a time: #rescan joins any in-flight #refreshing promise (memory-catalog.ts:127-133). #sorted and #byId are swapped only at the end of a scan, so a concurrent list never sees a half-built index. If a write lands mid-scan, the scan records the old revision and the next list rescans.
  • A page removed between walk and stat/read is skipped on ENOENT (memory-catalog.ts:149-153,165-168). A deleted page served from the cache answers not-found rather than 500 (memory-browser.ts:61-69).
  • Entry IDs are unchanged: entryId is moved verbatim (memory-catalog.ts:292-298), and so are classifyPath, metadataDate and pathDate. The old helpers are gone from memory-browser.ts, so nothing dead is left behind.
  • Cursors: numeric legacy cursors are still served (memory-catalog.ts:258-260). A base64url cursor of {"p":...} always starts with eyJ, so it can't be mistaken for a numeric one. Malformed cursors throw TypeError, which maps to 400 (covered by rejects a cursor that is not opaque page data). The worst-case cursor length (a 255-byte file name) is about 420 characters, well under the 1024 limit on both the internal and public (common.yaml:40-44) contracts.
  • TeamHub passes the cursor through as an opaque string (handlers_personal_wiki.go:78-88, memoryclient/client.go:175-177), and the public contract already types it as an opaque Cursor of at most 1024 characters. No TeamHub or Web change is needed.
  • The LRU cap of 32 workspaces is enforced on insert (memory-catalog.ts:237-240).
  • No CJK in added lines or the commit message, and no merge or fixup commits.

Process notes

  • main is 8 commits ahead of the merge base. The branch needs a rebase before it can merge.

CI

  • changes and check (web) pass; check (contracts), check (teamhub-cli) and repository-gate were still pending at review time. Node Services tests run in the heavy lane, so PR CI doesn't run them.
  • Ran locally: vitest run tests/memory/memory-catalog.test.ts tests/memory/memory-http-cursor.test.ts tests/memory/memory-browser.test.ts: 3 files, 18 tests passed.

Automated review by Claude Code


Automated review of b4694cc by Claude Code.

@DolphinMiner

Copy link
Copy Markdown
Contributor

Thanks for the thorough work on this — the design is clean and directly addresses the full-walk overhead by building on memory.revision, (size, mtimeMs) incremental refreshes, single-page get, and keyset pagination with legacy numeric cursor fallback.

Just a few small things to tidy up before we merge:

  1. Relax MemoryEntryPage.next_cursor in the internal OpenAPI contract (contracts/openapi/node-services-internal/openapi.yaml): the request cursor query parameter was updated, but the response MemoryEntryPage.next_cursor still has pattern: ^[0-9]{1,9}$, which doesn't match the base64url cursor the server now returns. Please update it to match (or $ref ../components/common.yaml#/components/schemas/Cursor) and run pnpm contracts:generate && pnpm contracts:verify.
  2. Avoid a double full scan on get(id) misses (apps/node-services/src/memory/memory-catalog.ts): get(id) currently runs await this.#refresh() and then unconditionally runs await this.#rescan(...) on a cache miss, even when #refresh() just completed a full scan. Having #refresh() report whether it actually scanned (and skipping #rescan if it already did) avoids walking and stat'ing the whole tree twice on every missing ID.
  3. Two small nits:
    • In MemoryCatalog.list, guard next < files.length && page.length > 0 before calling encodeCursor(page.at(-1)) so a programmatic limit: 0 call can't throw.
    • In apps/node-services/src/memory/README.md, update "cursor semantics are unchanged" to describe the opaque keyset cursor (stable across inserts, with legacy numeric offsets still accepted).

Once these are in and the branch is rebased on main, this is ready to merge!

Memory browsing walked and parsed every daily and weekly page per request. This keeps one per-Agent catalog keyed by memory.revision and re-reads only pages whose size or mtime changed.

The internal response cursor now refs the shared opaque Cursor; get() does not scan twice after a refresh; list guards a zero limit; the README describes the keyset cursor. Rejected drafts and published entry IDs are unchanged.
@Lumea-art
Lumea-art force-pushed the perf/memory-browser-catalog branch from b4694cc to de8f651 Compare November 26, 2026 15:34
@Lumea-art

Copy link
Copy Markdown
Contributor Author

Thanks — all four are in, rebased onto 1c35212b:

  1. MemoryEntryPage.next_cursor now $refs ../components/common.yaml#/components/schemas/Cursor, and contracts:generate/verify are clean.
  2. #refresh() returns whether it scanned. get() returns a miss directly when the refresh just scanned, and only forces a rescan when no fresh scan happened. Added does not scan twice when get misses after a refresh, which counts stat calls (1 for one missing get).
  3. list only encodes a cursor when the page is non-empty; added a limit: 0 test.
  4. README now describes the opaque keyset cursor (stable across inserts, legacy numeric offsets accepted).

Local: 13 catalog + 5 browser + 2 HTTP-cursor + 6 server-HTTP tests pass; typecheck, contracts generate/verify, eslint and prettier are clean.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve (0 findings)

Follow-up on b4694cc. Merge base 1c35212b (current main tip), 1 commit, 10 files reviewed.

  • Resolved: response next_cursor declared digit-only (contracts/openapi/node-services-internal/openapi.yaml:1740 now refs common.yaml#/components/schemas/Cursor, generated Go/TS regenerated)
  • Resolved: README claimed cursor semantics unchanged (apps/node-services/src/memory/README.md:21-26 now describes the opaque keyset cursor and numeric fallback)

Verified as fine

  • The catalog reads the same memory.revision that every writer bumps: memoryCatalogFor uses agentWorkspaceRoot(dataRoot, agentManagementId) (apps/node-services/src/memory/memory-catalog.ts:236), and writers call markMemoryChanged(root, memorySubjectKey) where memorySubjectKey === agentManagementId (apps/node-services/src/memory/subject.ts:11-12, fs-utils.ts:14-20).
  • Keyset cursor matches the sort order (updated_at desc, path asc): cursorStart (memory-catalog.ts:286-290) vs. the sort at memory-catalog.ts:205-209. A base64url cursor of {"… can never collide with the legacy numeric form, and it fits the 1024-char Cursor limit that TeamHub passes through unchanged (apps/teamhub/internal/app/handlers_personal_wiki.go:79-88).
  • #refresh()/get() scan at most once per miss, and list swaps #sorted atomically, so readers never see a half-built index (memory-catalog.ts:99-146, 201-209).

CI: all required checks pass. check-node-services is a heavy check that CI does not run. I ran vitest run tests/memory/memory-catalog.test.ts tests/memory/memory-browser.test.ts tests/memory/memory-http-cursor.test.ts myself: 20/20 passed.

Automated review by Claude Code


Automated review of de8f651 by Claude Code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants