@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
367 lines • 14.8 kB
JavaScript
import { createHash } from "node:crypto";
import { lstatSync, readdirSync, readFileSync } from "node:fs";
import { basename, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
export { createFsWatchEventSource } from "./watch-event-source.js";
const DEFAULT_DEBOUNCE_MS = 200;
const DEFAULT_CLOCK = {
setTimeout: (callback, delayMs) => setTimeout(callback, delayMs),
clearTimeout: (timer) => clearTimeout(timer),
};
/**
* Hash-gates filesystem events. Targets are directories by design: watching a
* file directly breaks when editors atomically rename a replacement over it.
*/
export class ConfigReloadWatchEngine {
#states;
#unsubscribes = [];
#closeCompletion;
#subscribe;
#onRealChange;
#onError;
#hashFile;
#clock;
#debounceMs;
#pending = new Map();
#timer;
#closed = false;
constructor(options) {
this.#subscribe = options.subscribe;
this.#onRealChange = options.onRealChange;
this.#onError = options.onError ?? (() => { });
this.#hashFile = options.hashFile ?? hashFile;
this.#clock = options.clock ?? DEFAULT_CLOCK;
this.#debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
this.#states = options.targets.map((target) => {
const resolvedTarget = { ...target, path: resolve(target.path) };
const scan = this.#scan(resolvedTarget);
return {
target: resolvedTarget,
hashes: scan.hashes,
allowedDirectories: scan.allowedDirectories,
watchedDirectories: new Map(),
scannedDirectories: scan.scannedDirectories,
};
});
for (const state of this.#states) {
this.#attach(state, state.scannedDirectories);
}
}
/**
* Subscribes to exactly the in-scope directories.
*
* A `dir-recursive` target used to hand its root to `fs.watch({recursive:true})`,
* which registers the entire subtree with the OS watcher (FSEvents on macOS).
* The target `filter` only discards events after delivery, so an extensions or
* skills directory containing `node_modules` still cost a full-subtree
* registration per session. The scan already knows which directories are in
* scope — it skips `node_modules`, `.git`, symlinks, and filtered paths — so
* watching that set directly gives identical coverage at a fraction of the
* OS-level cost.
*/
#attach(state, directories) {
const recursive = state.target.kind === "dir-recursive";
// The root is always watched so that creations directly beneath it are seen.
const wanted = recursive ? new Set([state.target.path, ...directories]) : new Set([state.target.path]);
for (const directory of wanted) {
if (state.watchedDirectories.has(directory)) {
continue;
}
try {
const unsubscribe = this.#subscribe(directory, (eventType, filename) => {
this.#onEvent(state, eventType, filename, directory);
}, { recursive: false });
state.watchedDirectories.set(directory, unsubscribe);
this.#unsubscribes.push(unsubscribe);
}
catch (error) {
this.#reportError(error, directory);
}
}
}
/** Drops subscriptions for directories that left scope (deleted or filtered out). */
#detachMissing(state, live) {
for (const [directory, unsubscribe] of [...state.watchedDirectories]) {
if (directory === state.target.path || live.has(directory)) {
continue;
}
state.watchedDirectories.delete(directory);
const index = this.#unsubscribes.indexOf(unsubscribe);
if (index >= 0) {
this.#unsubscribes.splice(index, 1);
}
try {
unsubscribe();
}
catch (error) {
this.#reportError(error, directory);
}
}
}
/**
* Marks the engine inert and cancels every subscription synchronously, then
* joins whatever native disposal those unsubscribers return. Repeated close()
* callers share that join. Dispatch already checks `#closed`, so stale events
* cannot start reload work while disposal is outstanding.
*/
close() {
if (this.#closed) {
return this.#closeCompletion ?? Promise.resolve();
}
this.#closed = true;
if (this.#timer) {
this.#clock.clearTimeout(this.#timer);
this.#timer = undefined;
}
const unsubscribes = this.#unsubscribes.splice(0);
this.#closeCompletion = Promise.allSettled(unsubscribes.map(async (unsubscribe) => unsubscribe())).then((results) => {
const errors = results
.filter((result) => result.status === "rejected")
.map((result) => result.reason);
if (errors.length > 0) {
throw new AggregateError(errors, "Config watcher teardown failed");
}
});
return this.#closeCompletion;
}
getBaselineSnapshot() {
const snapshot = new Map();
for (const state of this.#states) {
for (const [path, hash] of state.hashes) {
snapshot.set(path, hash);
}
}
return snapshot;
}
#onEvent(state, _eventType, filename, watchedDirectory) {
if (this.#closed) {
return;
}
if (filename === null) {
this.#pending.set(state, null);
}
else if (this.#pending.get(state) !== null) {
const affected = this.#pending.get(state) ?? new Set();
// Per-directory subscriptions report names relative to their own directory,
// so re-anchor them to the target root before matching.
const relPath = normalizeRelativePath(watchedDirectory && watchedDirectory !== state.target.path
? join(relative(state.target.path, watchedDirectory), filename)
: filename);
if (relPath && this.#matches(state.target, relPath)) {
affected.add(relPath);
this.#pending.set(state, affected);
}
}
this.#schedule();
}
#schedule() {
if (this.#timer) {
this.#clock.clearTimeout(this.#timer);
}
this.#timer = this.#clock.setTimeout(() => {
this.#timer = undefined;
this.#evaluatePending();
}, this.#debounceMs);
}
#evaluatePending() {
if (this.#closed) {
return;
}
const changes = new Map();
for (const [state, affected] of this.#pending) {
this.#evaluateState(state, affected, changes);
}
this.#pending.clear();
if (changes.size > 0) {
const changedPaths = [...changes.keys()].sort();
this.#onRealChange({
changedPaths,
created: changedPaths.filter((path) => changes.get(path)?.created),
deleted: changedPaths.filter((path) => changes.get(path)?.deleted),
});
}
}
#evaluateState(state, affected, changes) {
const previousHashes = new Map(state.hashes);
const previousDirectories = new Set(state.allowedDirectories);
const next = affected === null ? this.#scan(state.target) : this.#scanAffected(state.target, affected, state);
if (affected === null) {
state.hashes.clear();
for (const [path, hash] of next.hashes) {
state.hashes.set(path, hash);
}
state.allowedDirectories.clear();
for (const path of next.allowedDirectories) {
state.allowedDirectories.add(path);
}
state.scannedDirectories = next.scannedDirectories;
this.#detachMissing(state, state.scannedDirectories);
this.#attach(state, state.scannedDirectories);
this.#compare(previousHashes, previousDirectories, state.hashes, state.allowedDirectories, changes);
return;
}
const prefixes = [...affected].map((relPath) => join(state.target.path, relPath));
for (const path of [...state.hashes.keys()]) {
if (prefixes.some((prefix) => isWithin(path, prefix))) {
state.hashes.delete(path);
}
}
for (const path of [...state.allowedDirectories]) {
if (prefixes.some((prefix) => isWithin(path, prefix))) {
state.allowedDirectories.delete(path);
}
}
for (const path of [...state.scannedDirectories]) {
if (prefixes.some((prefix) => isWithin(path, prefix))) {
state.scannedDirectories.delete(path);
}
}
for (const [path, hash] of next.hashes) {
state.hashes.set(path, hash);
}
for (const path of next.allowedDirectories) {
state.allowedDirectories.add(path);
}
for (const path of next.scannedDirectories) {
state.scannedDirectories.add(path);
}
// A partial rescan can both create and remove directories in scope, so the
// subscription set is reconciled in both directions here too.
this.#detachMissing(state, state.scannedDirectories);
this.#attach(state, state.scannedDirectories);
this.#compare(previousHashes, previousDirectories, state.hashes, state.allowedDirectories, changes);
}
#scanAffected(target, affected, state) {
const result = { hashes: new Map(), allowedDirectories: new Set(), scannedDirectories: new Set() };
for (const relPath of affected) {
const absolutePath = join(target.path, relPath);
this.#scanPath(target, absolutePath, relPath, result, state);
}
return result;
}
#scan(target) {
const result = { hashes: new Map(), allowedDirectories: new Set(), scannedDirectories: new Set() };
this.#scanPath(target, target.path, "", result);
return result;
}
#scanPath(target, absolutePath, relPath, result, state) {
if (relPath && !this.#matches(target, relPath)) {
return;
}
let entry;
try {
entry = lstatSync(absolutePath);
}
catch (error) {
if (state && !isMissing(error)) {
this.#reportError(error, absolutePath);
}
return;
}
if (entry.isSymbolicLink()) {
return;
}
if (entry.isFile()) {
try {
result.hashes.set(absolutePath, this.#hashFile(absolutePath));
}
catch (error) {
this.#reportError(error, absolutePath);
}
return;
}
if (!entry.isDirectory()) {
return;
}
const dotDirectory = relPath !== "" && basename(relPath).startsWith(".");
const explicitlyAllowedDirectory = relPath !== "" && this.#isExplicitlyAllowedDirectory(target, relPath);
if (explicitlyAllowedDirectory) {
result.allowedDirectories.add(absolutePath);
}
if (relPath && target.kind === "dir") {
return;
}
if (dotDirectory && !explicitlyAllowedDirectory) {
return;
}
// Recorded before descending: this is the set the OS watcher subscribes to.
result.scannedDirectories.add(absolutePath);
try {
for (const child of readdirSync(absolutePath, { withFileTypes: true })) {
if (child.isSymbolicLink() || child.name === "node_modules" || child.name === ".git") {
continue;
}
const childRelPath = relPath ? join(relPath, child.name) : child.name;
if (child.isDirectory() &&
child.name.startsWith(".") &&
!this.#isExplicitlyAllowedDirectory(target, childRelPath)) {
continue;
}
this.#scanPath(target, join(absolutePath, child.name), childRelPath, result, state);
}
}
catch (error) {
this.#reportError(error, absolutePath);
}
}
#compare(previousHashes, previousDirectories, nextHashes, nextDirectories, changes) {
for (const [path, hash] of nextHashes) {
const oldHash = previousHashes.get(path);
if (oldHash !== hash) {
changes.set(path, { created: oldHash === undefined, deleted: false });
}
}
for (const path of previousHashes.keys()) {
if (!nextHashes.has(path)) {
changes.set(path, { created: false, deleted: true });
}
}
for (const path of nextDirectories) {
if (!previousDirectories.has(path)) {
changes.set(path, { created: true, deleted: false });
}
}
for (const path of previousDirectories) {
if (!nextDirectories.has(path)) {
changes.set(path, { created: false, deleted: true });
}
}
}
#matches(target, relPath) {
if (!target.kind.includes("recursive") && relPath.includes(sep)) {
return false;
}
if (target.allowList &&
!target.allowList.some((allowed) => relPath === allowed || relPath.startsWith(`${allowed}${sep}`))) {
return false;
}
return target.filter?.(relPath) ?? true;
}
#isExplicitlyAllowedDirectory(target, relPath) {
return (target.allowList?.some((allowed) => relPath === allowed || relPath.startsWith(`${allowed}${sep}`)) ?? false);
}
#reportError(error, path) {
try {
this.#onError(error, path);
}
catch {
// Error reporting must not take down the watcher.
}
}
}
function hashFile(path) {
return createHash("sha256").update(readFileSync(path)).digest("hex");
}
function normalizeRelativePath(filename) {
if (isAbsolute(filename)) {
return undefined;
}
const normalized = normalize(filename);
return normalized === "." || normalized === ".." || normalized.startsWith(`..${sep}`) ? undefined : normalized;
}
function isWithin(path, prefix) {
return path === prefix || path.startsWith(`${prefix}${sep}`);
}
function isMissing(error) {
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
}
//# sourceMappingURL=watch-engine.js.map