#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(fs-watcher): address CodeRabbit review
Rohit Ghumare02ebc5f1fa4c
diff --git a/integrations/filesystem-watcher/README.md b/integrations/filesystem-watcher/README.mdindex 36b7e960..12b11de7 100644--- a/integrations/filesystem-watcher/README.md+++ b/integrations/filesystem-watcher/README.md@@ -29,7 +29,11 @@ export AGENTMEMORY_SECRET=... # only if the server requires authagentmemory-fs-watcher```-Every file change inside the watched roots becomes a `file_change` observation; deletions become `file_delete`. The first 4 KB of each text file is included as content preview so retrieval can match by substring; larger files are truncated with `truncated: true` in metadata. Binary files are not read (set `AGENTMEMORY_FS_WATCH_ALLOW_BINARY=1` to override).+Every file change inside the watched roots becomes a `post_tool_use` observation whose `data.changeKind` is `file_change` or `file_delete`. The first 4 KB of each text file is included as `data.content` so retrieval can match by substring; larger files are truncated with `data.truncated: true`. Binary files are not read (set `AGENTMEMORY_FS_WATCH_ALLOW_BINARY=1` to override).++Session id and project are required by the observe endpoint — set them via env, or the watcher generates a per-process `fs-watcher-<ts>-<rand>` session id and uses the first root's directory name as the project.++Requires Node.js **>=20 LTS**. Recursive `fs.watch` needs Node 19.1.0+ on Linux; Node 20 is the minimum supported LTS line.## Configurationdiff --git a/integrations/filesystem-watcher/package.json b/integrations/filesystem-watcher/package.jsonindex 4e049857..b260ab68 100644--- a/integrations/filesystem-watcher/package.json+++ b/integrations/filesystem-watcher/package.json@@ -11,7 +11,7 @@".": "./watcher.mjs"},"files": ["watcher.mjs", "bin.mjs", "README.md"],- "engines": { "node": ">=18" },+ "engines": { "node": ">=20" },"license": "Apache-2.0","homepage": "https://github.com/rohitg00/agentmemory/tree/main/integrations/filesystem-watcher","repository": {diff --git a/integrations/filesystem-watcher/watcher.mjs b/integrations/filesystem-watcher/watcher.mjsindex 40fc969f..a548142e 100644--- a/integrations/filesystem-watcher/watcher.mjs+++ b/integrations/filesystem-watcher/watcher.mjs@@ -1,5 +1,6 @@import { watch, promises as fsp, statSync } from "node:fs";-import { resolve, relative, join, extname, sep } from "node:path";+import { resolve, relative, join, extname, sep, basename } from "node:path";+import { randomBytes } from "node:crypto";const TEXT_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",@@ -33,8 +34,12 @@ export class FilesystemWatcher {this.roots = (config.roots || []).map((r) => resolve(r));this.baseUrl = (config.baseUrl || "http://localhost:3111").replace(/\/+$/, "");this.secret = config.secret;- this.project = config.project || null;- this.sessionId = config.sessionId || null;+ this.project =+ config.project ||+ (this.roots[0] ? basename(this.roots[0]) : "filesystem-watcher");+ this.sessionId =+ config.sessionId ||+ `fs-watcher-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`;this.ignore = [...DEFAULT_IGNORE, ...(config.ignorePatterns || [])];this.allowBinary = Boolean(config.allowBinary);this.logger = config.logger || console;@@ -112,20 +117,26 @@ export class FilesystemWatcher {} catch {exists = false;}- const hookType = exists ? "file_change" : "file_delete";+ const changeKind = exists ? "file_change" : "file_delete";let preview = null;if (exists && this.isTextFile(absPath)) {preview = await this.readPreview(absPath);}const truncated = exists && size > MAX_PREVIEW_BYTES;const payload = {- hookType,- project: this.project,+ hookType: "post_tool_use",sessionId: this.sessionId,- files: [relPath],- content: this.formatContent(relPath, hookType, preview, { size, truncated }),- metadata: {+ project: this.project,+ cwd: rootDir,+ timestamp: new Date().toISOString(),+ data: {source: "filesystem-watcher",+ changeKind,+ files: [relPath],+ content: this.formatContent(relPath, changeKind, preview, {+ size,+ truncated,+ }),rootDir,absPath,size,@@ -135,8 +146,8 @@ export class FilesystemWatcher {await this.emit(payload);}- formatContent(relPath, hookType, preview, { size, truncated }) {- if (hookType === "file_delete") return `deleted: ${relPath}`;+ formatContent(relPath, changeKind, preview, { size, truncated }) {+ if (changeKind === "file_delete") return `deleted: ${relPath}`;const head = `${relPath} (${size} bytes${truncated ? ", truncated" : ""})`;if (preview === null) return head;return `${head}\n\n${preview}`;@@ -146,6 +157,7 @@ export class FilesystemWatcher {if (this.roots.length === 0) {throw new Error("filesystem-watcher: at least one root directory is required");}+ const failures = [];for (const root of this.roots) {try {const handle = watch(@@ -164,11 +176,18 @@ export class FilesystemWatcher {this.watchers.push(handle);this.logger.info?.(`[fs-watcher] watching ${root}`);} catch (err) {- this.logger.error?.(- `[fs-watcher] failed to watch ${root}: ${err?.message || err}`,- );+ const msg = err?.message || String(err);+ failures.push(`${root}: ${msg}`);+ this.logger.error?.(`[fs-watcher] failed to watch ${root}: ${msg}`);}}+ if (this.watchers.length === 0) {+ throw new Error(+ `filesystem-watcher: could not watch any of the configured roots. ` ++ `If you are on Node 18 + Linux, recursive fs.watch requires Node >=19.1.0; upgrade to Node 20 LTS or newer. ` ++ `Failures: ${failures.join("; ")}`,+ );+ }}stop() {diff --git a/test/fs-watcher.test.ts b/test/fs-watcher.test.tsindex c50e6eda..21e260ee 100644--- a/test/fs-watcher.test.ts+++ b/test/fs-watcher.test.ts@@ -40,7 +40,7 @@ describe("FilesystemWatcher", () => {} catch {}});- it("emits a file_change observation when a watched file is written", async () => {+ it("emits a post_tool_use observation with HookPayload shape on write", async () => {const w = new FilesystemWatcher({roots: [root],baseUrl: "http://localhost:3111",@@ -53,16 +53,31 @@ describe("FilesystemWatcher", () => {expect(captured.length).toBeGreaterThanOrEqual(1);const obs = captured[captured.length - 1];expect(obs.url).toBe("http://localhost:3111/agentmemory/observe");- const body = obs.body as { hookType: string; files: string[]; content: string };- expect(body.hookType).toBe("file_change");- expect(body.files).toContain("notes.md");- expect(body.content).toContain("hello world");+ const body = obs.body as {+ hookType: string;+ sessionId: string;+ project: string;+ cwd: string;+ timestamp: string;+ data: { changeKind: string; files: string[]; content: string; source: string };+ };+ expect(body.hookType).toBe("post_tool_use");+ expect(typeof body.sessionId).toBe("string");+ expect(body.sessionId.length).toBeGreaterThan(0);+ expect(typeof body.project).toBe("string");+ expect(body.project.length).toBeGreaterThan(0);+ expect(body.cwd).toBe(root);+ expect(body.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ expect(body.data.source).toBe("filesystem-watcher");+ expect(body.data.changeKind).toBe("file_change");+ expect(body.data.files).toContain("notes.md");+ expect(body.data.content).toContain("hello world");} finally {w.stop();}});- it("emits a file_delete observation when a watched file is removed", async () => {+ it("emits changeKind=file_delete when a watched file is removed", async () => {writeFileSync(join(root, "old.md"), "bye\n");const w = new FilesystemWatcher({roots: [root],@@ -74,7 +89,7 @@ describe("FilesystemWatcher", () => {unlinkSync(join(root, "old.md"));await wait(800);const deletes = captured.filter(- (c) => (c.body as { hookType: string }).hookType === "file_delete",+ (c) => (c.body as { data: { changeKind: string } }).data?.changeKind === "file_delete",);expect(deletes.length).toBeGreaterThanOrEqual(1);} finally {@@ -82,6 +97,15 @@ describe("FilesystemWatcher", () => {}});+ it("throws if no watched roots could be attached", () => {+ const w = new FilesystemWatcher({+ roots: ["/definitely/does/not/exist/xyz123"],+ baseUrl: "http://localhost:3111",+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ });+ expect(() => w.start()).toThrow(/could not watch any of the configured roots/);+ });+it("ignores paths that match the default ignore set", async () => {mkdirSync(join(root, "node_modules"), { recursive: true });const w = new FilesystemWatcher({@@ -94,7 +118,7 @@ describe("FilesystemWatcher", () => {writeFileSync(join(root, "node_modules", "ignored.js"), "x");await wait(800);const matches = captured.filter((c) =>- (c.body as { files: string[] }).files?.some((f) => f.includes("ignored.js")),+ (c.body as { data: { files: string[] } }).data?.files?.some((f) => f.includes("ignored.js")),);expect(matches).toHaveLength(0);} finally {@@ -136,7 +160,7 @@ describe("FilesystemWatcher", () => {writeFileSync(target, "4\n");await wait(900);const hits = captured.filter((c) =>- (c.body as { files: string[] }).files?.[0] === "burst.md",+ (c.body as { data: { files: string[] } }).data?.files?.[0] === "burst.md",);expect(hits.length).toBeLessThanOrEqual(2);} finally {