@agentmemory/fs-watcher 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -0
- package/bin.mjs +28 -0
- package/package.json +22 -0
- package/watcher.mjs +229 -0
package/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# @agentmemory/fs-watcher
|
|
2
|
+
|
|
3
|
+
Filesystem connector for agentmemory. Watches one or more directories and emits an observation to the running agentmemory server every time a file changes.
|
|
4
|
+
|
|
5
|
+
Part of the data-source-connectors effort tracked in issue #62.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g @agentmemory/fs-watcher
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or run without installing:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npx @agentmemory/fs-watcher ~/work/my-repo
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
# CLI args win over env.
|
|
23
|
+
agentmemory-fs-watcher ~/work/my-repo ~/notes
|
|
24
|
+
|
|
25
|
+
# Or set env once in your shell.
|
|
26
|
+
export AGENTMEMORY_FS_WATCH_DIRS=~/work/my-repo,~/notes
|
|
27
|
+
export AGENTMEMORY_URL=http://localhost:3111
|
|
28
|
+
export AGENTMEMORY_SECRET=... # only if the server requires auth
|
|
29
|
+
agentmemory-fs-watcher
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
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).
|
|
33
|
+
|
|
34
|
+
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.
|
|
35
|
+
|
|
36
|
+
Requires Node.js **>=20 LTS**. Recursive `fs.watch` needs Node 19.1.0+ on Linux; Node 20 is the minimum supported LTS line.
|
|
37
|
+
|
|
38
|
+
## Configuration
|
|
39
|
+
|
|
40
|
+
| Variable | Default | Meaning |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `AGENTMEMORY_FS_WATCH_DIRS` | — | Comma-separated list of directories to watch |
|
|
43
|
+
| `AGENTMEMORY_FS_WATCH_IGNORE` | — | Comma-separated regex patterns to ignore (applied to relative paths) |
|
|
44
|
+
| `AGENTMEMORY_FS_WATCH_ALLOW_BINARY` | `0` | `1` to include binary files in the preview read |
|
|
45
|
+
| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL |
|
|
46
|
+
| `AGENTMEMORY_SECRET` | — | Bearer token, required if the server has `AGENTMEMORY_SECRET` set |
|
|
47
|
+
| `AGENTMEMORY_PROJECT` | — | Optional project label attached to each observation |
|
|
48
|
+
| `AGENTMEMORY_SESSION_ID` | — | Optional session id to attribute observations to |
|
|
49
|
+
|
|
50
|
+
## Defaults
|
|
51
|
+
|
|
52
|
+
Ignored out of the box: `.git/`, `node_modules/`, `dist/`, `build/`, `.next/`, `.turbo/`, `coverage/`, `.DS_Store`, `*.log`, `*.lock`. Extend with `AGENTMEMORY_FS_WATCH_IGNORE`.
|
|
53
|
+
|
|
54
|
+
Text extensions read for preview: common source, config, and docs (`.ts/.js/.py/.go/.rs/.md/.yaml/...`). Unknown extensions are recorded as a path-only observation without content.
|
|
55
|
+
|
|
56
|
+
Writes are debounced 500 ms per path so a stream of saves from your editor becomes a single observation.
|
|
57
|
+
|
|
58
|
+
## Notes
|
|
59
|
+
|
|
60
|
+
- Uses Node's built-in `fs.watch` with `{ recursive: true }`. Works natively on macOS, Linux, and Windows 10+. No native deps.
|
|
61
|
+
- If `fs.watch` errors on a specific root (permission, platform quirk), the watcher logs and continues on the others.
|
|
62
|
+
- The process must keep running. Use a process manager (`launchd`, `systemd`, `pm2`) to supervise it.
|
|
63
|
+
- This connector is intentionally one-way: it writes observations and never reads the agentmemory store.
|
package/bin.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { FilesystemWatcher, configFromEnv } from "./watcher.mjs";
|
|
3
|
+
|
|
4
|
+
const cliArgs = process.argv.slice(2);
|
|
5
|
+
const envCfg = configFromEnv(process.env);
|
|
6
|
+
|
|
7
|
+
const roots = cliArgs.length > 0 ? cliArgs : envCfg.roots;
|
|
8
|
+
if (!roots || roots.length === 0) {
|
|
9
|
+
process.stderr.write(
|
|
10
|
+
"agentmemory-fs-watcher: no directories to watch.\n" +
|
|
11
|
+
"Usage: agentmemory-fs-watcher <dir> [<dir>...]\n" +
|
|
12
|
+
"Or set AGENTMEMORY_FS_WATCH_DIRS=path1,path2\n",
|
|
13
|
+
);
|
|
14
|
+
process.exit(2);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const watcher = new FilesystemWatcher({ ...envCfg, roots });
|
|
18
|
+
watcher.start();
|
|
19
|
+
process.stderr.write(
|
|
20
|
+
`[fs-watcher] emitting to ${envCfg.baseUrl || "http://localhost:3111"}\n`,
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
const shutdown = () => {
|
|
24
|
+
watcher.stop();
|
|
25
|
+
process.exit(0);
|
|
26
|
+
};
|
|
27
|
+
process.on("SIGINT", shutdown);
|
|
28
|
+
process.on("SIGTERM", shutdown);
|
package/package.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentmemory/fs-watcher",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Filesystem connector for agentmemory — emits observations on file changes.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"agentmemory-fs-watcher": "./bin.mjs"
|
|
8
|
+
},
|
|
9
|
+
"main": "./watcher.mjs",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./watcher.mjs"
|
|
12
|
+
},
|
|
13
|
+
"files": ["watcher.mjs", "bin.mjs", "README.md"],
|
|
14
|
+
"engines": { "node": ">=20" },
|
|
15
|
+
"license": "Apache-2.0",
|
|
16
|
+
"homepage": "https://github.com/rohitg00/agentmemory/tree/main/integrations/filesystem-watcher",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/rohitg00/agentmemory.git",
|
|
20
|
+
"directory": "integrations/filesystem-watcher"
|
|
21
|
+
}
|
|
22
|
+
}
|
package/watcher.mjs
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { watch, promises as fsp, statSync } from "node:fs";
|
|
2
|
+
import { resolve, relative, join, extname, sep, basename } from "node:path";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
const TEXT_EXTENSIONS = new Set([
|
|
6
|
+
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
|
|
7
|
+
".py", ".rb", ".go", ".rs", ".java", ".kt", ".swift",
|
|
8
|
+
".c", ".cc", ".cpp", ".h", ".hpp",
|
|
9
|
+
".md", ".mdx", ".txt", ".rst",
|
|
10
|
+
".json", ".yaml", ".yml", ".toml", ".ini", ".env",
|
|
11
|
+
".html", ".css", ".scss", ".vue", ".svelte",
|
|
12
|
+
".sh", ".bash", ".zsh", ".fish",
|
|
13
|
+
".sql", ".graphql", ".proto",
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const DEFAULT_IGNORE = [
|
|
17
|
+
/(?:^|\/)\.git(?:\/|$)/,
|
|
18
|
+
/(?:^|\/)node_modules(?:\/|$)/,
|
|
19
|
+
/(?:^|\/)dist(?:\/|$)/,
|
|
20
|
+
/(?:^|\/)build(?:\/|$)/,
|
|
21
|
+
/(?:^|\/)\.next(?:\/|$)/,
|
|
22
|
+
/(?:^|\/)\.turbo(?:\/|$)/,
|
|
23
|
+
/(?:^|\/)coverage(?:\/|$)/,
|
|
24
|
+
/(?:^|\/)\.DS_Store$/,
|
|
25
|
+
/\.log$/,
|
|
26
|
+
/\.lock$/,
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
const MAX_PREVIEW_BYTES = 4096;
|
|
30
|
+
const DEBOUNCE_MS = 500;
|
|
31
|
+
|
|
32
|
+
export class FilesystemWatcher {
|
|
33
|
+
constructor(config = {}) {
|
|
34
|
+
this.roots = (config.roots || []).map((r) => resolve(r));
|
|
35
|
+
this.baseUrl = (config.baseUrl || "http://localhost:3111").replace(/\/+$/, "");
|
|
36
|
+
this.secret = config.secret;
|
|
37
|
+
this.project =
|
|
38
|
+
config.project ||
|
|
39
|
+
(this.roots[0] ? basename(this.roots[0]) : "filesystem-watcher");
|
|
40
|
+
this.sessionId =
|
|
41
|
+
config.sessionId ||
|
|
42
|
+
`fs-watcher-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`;
|
|
43
|
+
this.ignore = [...DEFAULT_IGNORE, ...(config.ignorePatterns || [])];
|
|
44
|
+
this.allowBinary = Boolean(config.allowBinary);
|
|
45
|
+
this.logger = config.logger || console;
|
|
46
|
+
this.watchers = [];
|
|
47
|
+
this.pendingByPath = new Map();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
isIgnored(path) {
|
|
51
|
+
return this.ignore.some((re) => re.test(path));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
isTextFile(path) {
|
|
55
|
+
if (this.allowBinary) return true;
|
|
56
|
+
const ext = extname(path).toLowerCase();
|
|
57
|
+
return TEXT_EXTENSIONS.has(ext);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async readPreview(path) {
|
|
61
|
+
try {
|
|
62
|
+
const fh = await fsp.open(path, "r");
|
|
63
|
+
try {
|
|
64
|
+
const buf = Buffer.alloc(MAX_PREVIEW_BYTES);
|
|
65
|
+
const { bytesRead } = await fh.read(buf, 0, MAX_PREVIEW_BYTES, 0);
|
|
66
|
+
return buf.slice(0, bytesRead).toString("utf-8");
|
|
67
|
+
} finally {
|
|
68
|
+
await fh.close();
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async emit(event) {
|
|
76
|
+
const headers = { "content-type": "application/json" };
|
|
77
|
+
if (this.secret) headers.authorization = `Bearer ${this.secret}`;
|
|
78
|
+
try {
|
|
79
|
+
const res = await fetch(`${this.baseUrl}/agentmemory/observe`, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers,
|
|
82
|
+
body: JSON.stringify(event),
|
|
83
|
+
signal: AbortSignal.timeout(5000),
|
|
84
|
+
});
|
|
85
|
+
if (!res.ok) {
|
|
86
|
+
this.logger.warn?.(
|
|
87
|
+
`[fs-watcher] observe ${res.status}: ${await res.text().catch(() => "")}`,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
} catch (err) {
|
|
91
|
+
this.logger.warn?.(`[fs-watcher] observe failed: ${err?.message || err}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
schedule(rootDir, relPath) {
|
|
96
|
+
const key = join(rootDir, relPath);
|
|
97
|
+
const existing = this.pendingByPath.get(key);
|
|
98
|
+
if (existing) clearTimeout(existing.timer);
|
|
99
|
+
const timer = setTimeout(() => {
|
|
100
|
+
this.pendingByPath.delete(key);
|
|
101
|
+
this.flush(rootDir, relPath).catch((err) =>
|
|
102
|
+
this.logger.warn?.(`[fs-watcher] flush failed: ${err?.message || err}`),
|
|
103
|
+
);
|
|
104
|
+
}, DEBOUNCE_MS);
|
|
105
|
+
this.pendingByPath.set(key, { timer });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async flush(rootDir, relPath) {
|
|
109
|
+
const absPath = join(rootDir, relPath);
|
|
110
|
+
if (this.isIgnored(relPath)) return;
|
|
111
|
+
let exists = true;
|
|
112
|
+
let size = 0;
|
|
113
|
+
try {
|
|
114
|
+
const st = statSync(absPath);
|
|
115
|
+
if (!st.isFile()) return;
|
|
116
|
+
size = st.size;
|
|
117
|
+
} catch {
|
|
118
|
+
exists = false;
|
|
119
|
+
}
|
|
120
|
+
const changeKind = exists ? "file_change" : "file_delete";
|
|
121
|
+
let preview = null;
|
|
122
|
+
if (exists && this.isTextFile(absPath)) {
|
|
123
|
+
preview = await this.readPreview(absPath);
|
|
124
|
+
}
|
|
125
|
+
const truncated = exists && size > MAX_PREVIEW_BYTES;
|
|
126
|
+
const payload = {
|
|
127
|
+
hookType: "post_tool_use",
|
|
128
|
+
sessionId: this.sessionId,
|
|
129
|
+
project: this.project,
|
|
130
|
+
cwd: rootDir,
|
|
131
|
+
timestamp: new Date().toISOString(),
|
|
132
|
+
data: {
|
|
133
|
+
source: "filesystem-watcher",
|
|
134
|
+
changeKind,
|
|
135
|
+
files: [relPath],
|
|
136
|
+
content: this.formatContent(relPath, changeKind, preview, {
|
|
137
|
+
size,
|
|
138
|
+
truncated,
|
|
139
|
+
}),
|
|
140
|
+
rootDir,
|
|
141
|
+
absPath,
|
|
142
|
+
size,
|
|
143
|
+
truncated,
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
await this.emit(payload);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
formatContent(relPath, changeKind, preview, { size, truncated }) {
|
|
150
|
+
if (changeKind === "file_delete") return `deleted: ${relPath}`;
|
|
151
|
+
const head = `${relPath} (${size} bytes${truncated ? ", truncated" : ""})`;
|
|
152
|
+
if (preview === null) return head;
|
|
153
|
+
return `${head}\n\n${preview}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
start() {
|
|
157
|
+
if (this.roots.length === 0) {
|
|
158
|
+
throw new Error("filesystem-watcher: at least one root directory is required");
|
|
159
|
+
}
|
|
160
|
+
const failures = [];
|
|
161
|
+
for (const root of this.roots) {
|
|
162
|
+
try {
|
|
163
|
+
const handle = watch(
|
|
164
|
+
root,
|
|
165
|
+
{ recursive: true, persistent: true },
|
|
166
|
+
(_eventType, filename) => {
|
|
167
|
+
if (!filename) return;
|
|
168
|
+
const rel = filename.split(sep).join("/");
|
|
169
|
+
if (this.isIgnored(rel)) return;
|
|
170
|
+
this.schedule(root, rel);
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
handle.on("error", (err) => {
|
|
174
|
+
this.logger.warn?.(`[fs-watcher] watch error on ${root}: ${err?.message || err}`);
|
|
175
|
+
});
|
|
176
|
+
this.watchers.push(handle);
|
|
177
|
+
this.logger.info?.(`[fs-watcher] watching ${root}`);
|
|
178
|
+
} catch (err) {
|
|
179
|
+
const msg = err?.message || String(err);
|
|
180
|
+
failures.push(`${root}: ${msg}`);
|
|
181
|
+
this.logger.error?.(`[fs-watcher] failed to watch ${root}: ${msg}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (this.watchers.length === 0) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
`filesystem-watcher: could not watch any of the configured roots. ` +
|
|
187
|
+
`If you are on Node 18 + Linux, recursive fs.watch requires Node >=19.1.0; upgrade to Node 20 LTS or newer. ` +
|
|
188
|
+
`Failures: ${failures.join("; ")}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
stop() {
|
|
194
|
+
for (const w of this.watchers) {
|
|
195
|
+
try {
|
|
196
|
+
w.close();
|
|
197
|
+
} catch {}
|
|
198
|
+
}
|
|
199
|
+
this.watchers = [];
|
|
200
|
+
for (const { timer } of this.pendingByPath.values()) {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
}
|
|
203
|
+
this.pendingByPath.clear();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Small helper used by tests and bin.mjs to parse env.
|
|
208
|
+
export function configFromEnv(env = process.env) {
|
|
209
|
+
const roots = (env.AGENTMEMORY_FS_WATCH_DIRS || "")
|
|
210
|
+
.split(",")
|
|
211
|
+
.map((s) => s.trim())
|
|
212
|
+
.filter(Boolean);
|
|
213
|
+
const extraIgnore = (env.AGENTMEMORY_FS_WATCH_IGNORE || "")
|
|
214
|
+
.split(",")
|
|
215
|
+
.map((s) => s.trim())
|
|
216
|
+
.filter(Boolean)
|
|
217
|
+
.map((s) => new RegExp(s));
|
|
218
|
+
return {
|
|
219
|
+
roots,
|
|
220
|
+
baseUrl: env.AGENTMEMORY_URL,
|
|
221
|
+
secret: env.AGENTMEMORY_SECRET,
|
|
222
|
+
project: env.AGENTMEMORY_PROJECT || null,
|
|
223
|
+
sessionId: env.AGENTMEMORY_SESSION_ID || null,
|
|
224
|
+
ignorePatterns: extraIgnore,
|
|
225
|
+
allowBinary: env.AGENTMEMORY_FS_WATCH_ALLOW_BINARY === "1",
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export { relative as _relativeForTests };
|