惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
The Register - Security
The Register - Security
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The GitHub Blog
The GitHub Blog
博客园 - 司徒正美
罗磊的独立博客
U
Unit 42
S
SegmentFault 最新的问题
Y
Y Combinator Blog
博客园_首页
Hugging Face - Blog
Hugging Face - Blog
J
Java Code Geeks
Schneier on Security
Schneier on Security
Know Your Adversary
Know Your Adversary
C
Check Point Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Simon Willison's Weblog
Simon Willison's Weblog
V
Vulnerabilities – Threatpost
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
博客园 - 叶小钗
C
Cybersecurity and Infrastructure Security Agency CISA
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Latest news
Latest news
L
Lohrmann on Cybersecurity
A
About on SuperTechFans
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
S
Securelist
A
Arctic Wolf
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threatpost
Scott Helme
Scott Helme
博客园 - 聂微东
博客园 - 【当耐特】
T
Tenable Blog
I
Intezer
D
DataBreaches.Net
B
Blog RSS Feed
Security Latest
Security Latest
C
Cisco Blogs
T
Tor Project blog
N
Netflix TechBlog - Medium

Recent Commits to openclaw:main

test: merge chat side-result checks · openclaw/openclaw@ddd2c2a test: merge cron history checks · openclaw/openclaw@f7eb746 test: merge responsive navigation shell checks · openclaw/openclaw@c2e4b47 docs(changelog): add codex oauth fixes · openclaw/openclaw@628e6cd test: merge navigation routing cases · openclaw/openclaw@5d8cecb Tests: mock channel registry bundled fallback · openclaw/openclaw@2b08233 Secrets: avoid broad web search discovery for single plugin config · openclaw/openclaw@a464f59 test: merge config view browser checks · openclaw/openclaw@20cf511 fix(status): align oauth health with runtime · openclaw/openclaw@eed7116 feat: add macOS screen snapshots for monitor preview (#67954) thanks … · openclaw/openclaw@f377db1 fix: report shared auth scopes in hello-ok (#67810) thanks @BunsDev · openclaw/openclaw@0b6c39b Auto-reply: avoid eager bundled route fallback · openclaw/openclaw@3ea1bf4 Tests: narrow session binding contract setup · openclaw/openclaw@54e4e16 fix(macOS): enable undo/redo in webchat composer text input (#34962) · openclaw/openclaw@00951dc Tests: speed up channel setup promotion · openclaw/openclaw@82b529a Docs: refresh agent instructions · openclaw/openclaw@5775fe2 fix(auth): serialize OAuth refresh across agents to fix #26322 (#67876) · openclaw/openclaw@8e79080 test: allow ollama public surface boundary test · openclaw/openclaw@7d4f1a6 Docs: add test performance guardrails · openclaw/openclaw@89706d3 Tests: restore context-engine usage proof · openclaw/openclaw@e4c4f95 Tests: slim context engine runtime coverage · openclaw/openclaw@74c198f ci: retry failed custom checkouts · openclaw/openclaw@0ee5baf test: trim duplicate provider auth onboarding cases · openclaw/openclaw@1ffc02e matrix: fix sessions_spawn --thread subagent session spawning (#67643) · openclaw/openclaw@1ce2596 test: reduce auth choice fixture churn · openclaw/openclaw@857b9cd test: mock health status config boundaries · openclaw/openclaw@9d5ab4a test: mock onboard config io boundary · openclaw/openclaw@299694d test: mock legacy state plugin boundaries · openclaw/openclaw@2713089 test: mock channel install boundaries · openclaw/openclaw@b945248 test: mock doctor preview channel boundaries · openclaw/openclaw@b1a3ad4 test: trim doctor command hotspots · openclaw/openclaw@c66f16a test: isolate agent auth and spawn hotspots · openclaw/openclaw@9285935 test: stabilize MCP startup disposal race · openclaw/openclaw@dd9d2eb test: merge browser contract server suites · openclaw/openclaw@5817a76 test: narrow ollama provider discovery setup · openclaw/openclaw@a0d9598 build: declare qa-lab aimock runtime dependency · openclaw/openclaw@24431e5 test: speed up safe-bins exec harness · openclaw/openclaw@ee856ab test: preserve tool helpers in embedded runner mocks · openclaw/openclaw@acd86a0 refactor: move memory embeddings into provider plugins · openclaw/openclaw@77e6e4c test: reuse system-run temp fixtures · openclaw/openclaw@7e9ff0f test: trim hotspot wait overhead · openclaw/openclaw@12a59b0 Check: avoid duplicate boundary prep · openclaw/openclaw@baf11b8 test: reduce hotspot fixture overhead · openclaw/openclaw@3a59edd feat(ui): overhaul settings and slash command UX (#67819) thanks @Bun… · openclaw/openclaw@2cfb660 QA Matrix: exit cleanly on failure · openclaw/openclaw@42805d2 QA Matrix: isolate scenario coverage · openclaw/openclaw@7e659e1 Matrix: refresh crypto bootstrap state · openclaw/openclaw@94081d8 QA Lab: add provider registry · openclaw/openclaw@bb7e982 Matrix: add plugin changelog · openclaw/openclaw@4acab55 test: trim more hotspot overhead · openclaw/openclaw@f485311 test: trim remaining hotspot tests · openclaw/openclaw@6ba8626 test: narrow hotspot mocks · openclaw/openclaw@dbc8179 test: isolate gemini embedding request helpers · openclaw/openclaw@cd330f5 test: trim memory and mcp hotspots · openclaw/openclaw@fd48dfa test: slim provider registry mocks · openclaw/openclaw@2e08c77 test: harden Parallels update smoke · openclaw/openclaw@1a98090 feat: default Anthropic to Opus 4.7 · openclaw/openclaw@628b454 fix: harden node-host shell payload mutability checks · openclaw/openclaw@75c551e fix: land node-host approval binding for native binaries (#66731) (th… · openclaw/openclaw@29919bb CI: add daily schedule to CodeQL workflow (#67645) · openclaw/openclaw@69d25f5 fix(gateway): capture config hash after plugin auto-enable to prevent… · openclaw/openclaw@8c11210 fix: repair sanitized replay tool results before send (#67620) (thank… · openclaw/openclaw@c3c7a99 fix: restrict HTML timeout short-circuit to transient statuses · openclaw/openclaw@de129a6 fix: keep TUI watchdog bound to active run (#67401) (thanks @xantorres) · openclaw/openclaw@3525273 Gateway/skills: dedupe skills prefix-match + drop dead fallback on log · openclaw/openclaw@d7f489f Extensions/lmstudio: back off inference preload after consecutive fai… · openclaw/openclaw@b555214 TUI/streaming: add watchdog that resets the activity indicator after … · openclaw/openclaw@f44ab20 Agents/tool-loop: enable unknown-tool stream guard by default · openclaw/openclaw@36ed367 Gateway/skills: invalidate session skills snapshot on config write · openclaw/openclaw@b23d59a fix: classify HTML provider error pages correctly (#67642) (thanks @s… · openclaw/openclaw@e588e90 fix(skills): remove unused model-usage import (#67641) · openclaw/openclaw@55f05df docs(changelog): credit codex fix superseded PRs · openclaw/openclaw@e485f24 fix(openai-codex): normalize stale transport metadata in resolution a… · openclaw/openclaw@90801ba CI: pin Docker-related GitHub Actions (#67632) · openclaw/openclaw@f697b01 Android: modernize WebView and discovery API usage (#67627) · openclaw/openclaw@44a6e50 fix(deps): bump hono to 4.12.14 and @hono/node-server to 1.19.14 (GHS… · openclaw/openclaw@fbccc18 fix(deps): bump dompurify to 3.4.0 (#67614) · openclaw/openclaw@2c2dc00 CI: add explicit permissions to all workflow jobs (fixes code-scannin… · openclaw/openclaw@01b7516 fix: register bundled TTS providers and route overrides correctly (#6… · openclaw/openclaw@6ea3cdd fix: align host tilde paths with OS home (#62804) (thanks @stainlu) · openclaw/openclaw@ecfaf64 fix: flush creds queue before reconnect socket open (#67464) (thanks … · openclaw/openclaw@405c63f fix: strip standalone <function> tool call tags from visible text (#6… · openclaw/openclaw@78df859 fix(agents): preserve cli session metadata before transcript persist … · openclaw/openclaw@898fd04 docs(changelog): move cli transcript entry · openclaw/openclaw@c1817c6 fix(agents): normalize cli transcript api field · openclaw/openclaw@3a3fae0 docs(changelog): note cli transcript persistence · openclaw/openclaw@6c343f1 fix(agents): persist cli transcript turns · openclaw/openclaw@b8ef507 fix(msteams): harden security-sensitive flows (#65841) · openclaw/openclaw@c56b56e [Dashboard] Fix exec approval modal overflow for long command content… · openclaw/openclaw@053c5b0 Docs: remove QA changelog entry · openclaw/openclaw@7fd5771 QA: fix private runtime source loading (#67428) · openclaw/openclaw@d5933af docs(gateway): correct protocol.md schema path, hello-ok example, aut… · openclaw/openclaw@489404d CI: pin Node 22 runners to 22.18.0 · openclaw/openclaw@4ffa621 models.authStatus: normalize provider ids + tighten env-backed escape… · openclaw/openclaw@f2fdb9d Update CHANGELOG.md · openclaw/openclaw@7694a92 test(parallels): clean up npm update guard jobs · openclaw/openclaw@045ea7b Plugins: prefer scanDir override paths · openclaw/openclaw@b2974da fix(dreaming): default storage.mode to "separate" so phase blocks sto… · openclaw/openclaw@8c392f0 fix(memory-core): skip dreaming transcript ingestion via session stor… · openclaw/openclaw@a1b01f0 fix: dedupe replayed exec.finished node events (#67281) · openclaw/openclaw@5dcf526
fix(memory-core): avoid per-file watcher FD fan-out for memory direct… · openclaw/openclaw@9e43d03
lukeboyett · 2026-05-27 · via Recent Commits to openclaw:main

@@ -109,6 +109,13 @@ const IGNORED_MEMORY_WATCH_DIR_NAMES = new Set([

109109110110

const log = createSubsystemLogger("memory");

111111

const TEST_MEMORY_WATCH_FACTORY_KEY = Symbol.for("openclaw.test.memoryWatchFactory");

112+

const TEST_MEMORY_NATIVE_WATCH_FACTORY_KEY = Symbol.for("openclaw.test.memoryNativeWatchFactory");

113+114+

type NativeMemoryWatchPair = {

115+

dir: string;

116+

main: fsSync.FSWatcher;

117+

parent: fsSync.FSWatcher | null;

118+

};

112119113120

function resolveMemoryWatchFactory(): typeof chokidar.watch {

114121

if (process.env.VITEST === "true" || process.env.NODE_ENV === "test") {

@@ -120,6 +127,18 @@ function resolveMemoryWatchFactory(): typeof chokidar.watch {

120127

return chokidar.watch.bind(chokidar);

121128

}

122129130+

function resolveMemoryNativeWatchFactory(): typeof fsSync.watch {

131+

if (process.env.VITEST === "true" || process.env.NODE_ENV === "test") {

132+

const override = (globalThis as Record<PropertyKey, unknown>)[

133+

TEST_MEMORY_NATIVE_WATCH_FACTORY_KEY

134+

];

135+

if (typeof override === "function") {

136+

return override as typeof fsSync.watch;

137+

}

138+

}

139+

return fsSync.watch.bind(fsSync);

140+

}

141+123142

function shouldIgnoreMemoryWatchPath(

124143

watchPath: string,

125144

stats?: { isDirectory?: () => boolean },

@@ -200,6 +219,7 @@ export abstract class MemoryManagerSyncOps {

200219

} = { enabled: false, available: false };

201220

protected vectorReady: Promise<boolean> | null = null;

202221

protected watcher: FSWatcher | null = null;

222+

private nativeMemoryWatchPairs: NativeMemoryWatchPair[] = [];

203223

protected watchTimer: NodeJS.Timeout | null = null;

204224

protected sessionWatchTimer: NodeJS.Timeout | null = null;

205225

protected sessionUnsubscribe: (() => void) | null = null;

@@ -434,13 +454,18 @@ export abstract class MemoryManagerSyncOps {

434454

}

435455436456

protected ensureWatcher() {

437-

if (!this.sources.has("memory") || !this.settings.sync.watch || this.watcher) {

457+

if (!this.sources.has("memory") || !this.settings.sync.watch) {

438458

return;

439459

}

440-

const watchPaths = new Set<string>([

441-

path.join(this.workspaceDir, "MEMORY.md"),

442-

path.join(this.workspaceDir, "memory"),

443-

]);

460+

if (this.watcher || this.nativeMemoryWatchPairs.length > 0) {

461+

// Already initialized — preserve idempotence.

462+

return;

463+

}

464+

// Core paths preserve original symlink-follow behavior (chokidar/fs.watch

465+

// resolve through symlinks by default); extraPaths preserves the original

466+

// explicit symlink-skip policy.

467+

const fileWatchPaths = new Set<string>([path.join(this.workspaceDir, "MEMORY.md")]);

468+

const dirWatchPaths = new Set<string>([path.join(this.workspaceDir, "memory")]);

444469

const additionalPaths = normalizeExtraMemoryPaths(this.workspaceDir, this.settings.extraPaths);

445470

for (const entry of additionalPaths) {

446471

try {

@@ -449,40 +474,301 @@ export abstract class MemoryManagerSyncOps {

449474

continue;

450475

}

451476

if (stat.isDirectory()) {

452-

watchPaths.add(entry);

477+

dirWatchPaths.add(entry);

453478

continue;

454479

}

455480

if (

456481

stat.isFile() &&

457482

(normalizeLowercaseStringOrEmpty(entry).endsWith(".md") ||

458483

classifyMemoryMultimodalPath(entry, this.settings.multimodal) !== null)

459484

) {

460-

watchPaths.add(entry);

485+

fileWatchPaths.add(entry);

461486

}

462487

} catch {

463488

// Skip missing/unreadable additional paths.

464489

}

465490

}

466-

this.watcher = resolveMemoryWatchFactory()(Array.from(watchPaths), {

467-

ignoreInitial: true,

468-

ignored: (watchPath, stats) =>

469-

shouldIgnoreMemoryWatchPath(watchPath, stats, this.settings.multimodal),

470-

});

471491

const markDirty = (watchPath?: string, stats?: MemoryWatchEventStats) => {

472492

recordMemoryWatchEventPath(this.pendingWatchPaths, watchPath, stats);

473493

this.dirty = true;

474494

this.scheduleWatchSync();

475495

};

476-

this.watcher.on("add", markDirty);

477-

this.watcher.on("change", markDirty);

478-

this.watcher.on("unlink", markDirty);

479-

this.watcher.on("unlinkDir", markDirty);

480-

this.watcher.on("error", (err) => {

481-

// File watcher errors (e.g., ENOSPC) should not crash the gateway.

482-

// Log the error and continue - memory search still works without auto-sync.

496+

// Native recursive fs.watch for directory paths — one watcher per

497+

// directory on macOS (FSEvents) and Windows (ReadDirectoryChangesW).

498+

// Avoids chokidar's per-file fs.watch fan-out that opened ~12k REG FDs

499+

// on multi-thousand-`.md` memory trees (issue #86613).

500+

//

501+

// Linux is intentionally NOT in the native set: Node's

502+

// `fs.watch(dir, { recursive: true })` on non-macOS/non-Windows routes

503+

// through `internal/fs/recursive_watch`, which walks the tree and

504+

// attaches one watcher per entry under the hood. That defeats the

505+

// constant-watcher-profile goal of this fix without throwing (so the

506+

// creation-failure fallback below would not catch it). Linux paths

507+

// therefore go straight to chokidar, matching pre-PR behavior on that

508+

// platform.

509+

//

510+

// On any other native creation failure (e.g. unsupported filesystem,

511+

// ERR_FEATURE_UNAVAILABLE_ON_PLATFORM) the directory also falls back to

512+

// chokidar so freshness is preserved on the degraded path.

513+

const nativeRecursiveSupported = process.platform === "darwin" || process.platform === "win32";

514+

for (const dir of dirWatchPaths) {

515+

if (!nativeRecursiveSupported) {

516+

fileWatchPaths.add(dir);

517+

continue;

518+

}

519+

if (!this.attachNativeMemoryWatchForDir(dir, markDirty)) {

520+

// Native creation failed (dir missing, unsupported FS, throw) —

521+

// fall back to chokidar so directory coverage isn't dropped.

522+

fileWatchPaths.add(dir);

523+

}

524+

}

525+

if (fileWatchPaths.size > 0) {

526+

this.watcher = resolveMemoryWatchFactory()(Array.from(fileWatchPaths), {

527+

ignoreInitial: true,

528+

ignored: (watchPath, stats) =>

529+

shouldIgnoreMemoryWatchPath(watchPath, stats, this.settings.multimodal),

530+

});

531+

this.watcher.on("add", markDirty);

532+

this.watcher.on("change", markDirty);

533+

this.watcher.on("unlink", markDirty);

534+

this.watcher.on("unlinkDir", markDirty);

535+

this.watcher.on("error", (err) => {

536+

// File watcher errors (e.g., ENOSPC) should not crash the gateway.

537+

// Log the error and continue - memory search still works without auto-sync.

538+

const message = err instanceof Error ? err.message : String(err);

539+

log.warn(`memory watcher error: ${message}`);

540+

});

541+

}

542+

}

543+544+

// Attach a native recursive `fs.watch` to `dir` plus a non-recursive

545+

// parent-directory watch that detects root-replacement

546+

// (`rm -rf memory && mkdir memory`) by inode comparison. Returns true if

547+

// the main native watcher attached. Called from ensureWatcher(); also

548+

// re-entered from the parent-watch handler on detected replacement.

549+

protected attachNativeMemoryWatchForDir(

550+

dir: string,

551+

markDirty: (watchPath?: string, stats?: MemoryWatchEventStats) => void,

552+

): boolean {

553+

if (this.closed) {

554+

return false;

555+

}

556+

let recordedInode: number | null;

557+

try {

558+

recordedInode = fsSync.statSync(dir).ino;

559+

} catch {

560+

// Dir doesn't exist; caller will fall back to chokidar.

561+

return false;

562+

}

563+

let mainWatcher: fsSync.FSWatcher;

564+

try {

565+

mainWatcher = resolveMemoryNativeWatchFactory()(

566+

dir,

567+

{ recursive: true },

568+

(_eventType, filename) => {

569+

if (filename == null) {

570+

// Node docs: filename may be null on some platforms even when

571+

// recursive watching is otherwise supported. Be conservative

572+

// and mark broadly dirty rather than dropping the event.

573+

markDirty();

574+

return;

575+

}

576+

const full = path.join(dir, filename);

577+

let stats: fsSync.Stats | undefined;

578+

try {

579+

const s = fsSync.lstatSync(full, { throwIfNoEntry: false });

580+

stats = s ?? undefined;

581+

} catch {

582+

stats = undefined;

583+

}

584+

if (shouldIgnoreMemoryWatchPath(full, stats, this.settings.multimodal)) {

585+

return;

586+

}

587+

// Pass stats so the watch-settle queue can debounce rapid

588+

// writes; without a snapshot the queue cannot detect stability.

589+

markDirty(full, stats);

590+

},

591+

);

592+

} catch (err) {

593+

log.warn(

594+

`failed to start native recursive watcher on ${dir}: ${String(err)}; falling back to chokidar`,

595+

);

596+

return false;

597+

}

598+

const pair: NativeMemoryWatchPair = { dir, main: mainWatcher, parent: null };

599+

mainWatcher.on("error", (err) => {

483600

const message = err instanceof Error ? err.message : String(err);

484-

log.warn(`memory watcher error: ${message}`);

601+

log.warn(`memory native watcher error on ${dir}: ${message}`);

602+

// Per Node docs the FSWatcher is no longer usable after an error.

603+

this.closeNativeMemoryWatchPair(pair);

604+

if (this.closed) {

605+

return;

606+

}

607+

// Force a broad re-sync to cover the gap, then restore directory

608+

// coverage by reattaching to chokidar so subsequent file changes

609+

// still drive watch sync (intervalMinutes defaults to 0; without

610+

// a watcher the directory would stop being indexed).

611+

markDirty();

612+

this.attachMemoryChokidarFallback(dir, markDirty);

485613

});

614+

this.nativeMemoryWatchPairs.push(pair);

615+

// Non-recursive parent watcher: catches root-directory replacement so

616+

// we can reattach the main watcher on the new inode. Without this,

617+

// `rm -rf memory && mkdir memory` would leave the main watcher bound

618+

// to the dead inode and silently miss subsequent file changes.

619+

try {

620+

const parentDir = path.dirname(dir);

621+

const baseName = path.basename(dir);

622+

const parentWatcher = resolveMemoryNativeWatchFactory()(

623+

parentDir,

624+

{ recursive: false },

625+

(_eventType, filename) => {

626+

// Per Node docs `filename` can be null on some platforms even

627+

// when the parent watcher is otherwise supported. Treat null

628+

// as an unknown event and re-check the watched directory's

629+

// inode (clawsweeper review [P2] 5df68c…); otherwise filter

630+

// by basename so sibling events don't trigger reattach.

631+

if (filename !== null && filename !== baseName) {

632+

return;

633+

}

634+

let currentInode: number | null;

635+

try {

636+

currentInode = fsSync.statSync(dir).ino;

637+

} catch {

638+

currentInode = null;

639+

}

640+

if (currentInode === recordedInode) {

641+

return;

642+

}

643+

// Root was replaced (or removed). Tear down the existing pair

644+

// and either reattach (if dir still exists) or fall back to

645+

// chokidar (if dir is gone).

646+

this.closeNativeMemoryWatchPair(pair);

647+

if (this.closed) {

648+

return;

649+

}

650+

markDirty();

651+

if (currentInode !== null) {

652+

// Re-attach on the new inode (this also installs a fresh

653+

// parent watcher closed over the new recordedInode). If the

654+

// helper's own statSync races with the dir disappearing

655+

// between our inode check and its own check, it returns

656+

// false — fall back to chokidar so coverage isn't lost.

657+

if (!this.attachNativeMemoryWatchForDir(dir, markDirty)) {

658+

this.attachMemoryChokidarFallback(dir, markDirty);

659+

}

660+

} else {

661+

this.attachMemoryChokidarFallback(dir, markDirty);

662+

}

663+

},

664+

);

665+

parentWatcher.on("error", (err) => {

666+

const message = err instanceof Error ? err.message : String(err);

667+

log.warn(`memory native parent watcher error on ${path.dirname(dir)}: ${message}`);

668+

try {

669+

parentWatcher.close();

670+

} catch {

671+

// ignore

672+

}

673+

this.removeNativeMemoryParentWatch(parentWatcher);

674+

if (pair.parent === parentWatcher) {

675+

pair.parent = null;

676+

}

677+

// Main watcher still alive — root-replacement detection is lost

678+

// but normal events still flow. No fallback needed.

679+

});

680+

pair.parent = parentWatcher;

681+

} catch (err) {

682+

// Parent watcher couldn't start (e.g. parentDir not accessible).

683+

// The main watcher still works for non-replacement events; just

684+

// log and continue.

685+

log.warn(

686+

`memory native parent watcher could not start on ${path.dirname(dir)}: ${String(err)}`,

687+

);

688+

}

689+

return true;

690+

}

691+692+

private closeNativeMemoryWatchPair(pair: NativeMemoryWatchPair): void {

693+

try {

694+

pair.main.close();

695+

} catch {

696+

// ignore close failures

697+

}

698+

if (pair.parent) {

699+

try {

700+

pair.parent.close();

701+

} catch {

702+

// ignore close failures

703+

}

704+

pair.parent = null;

705+

}

706+

this.removeNativeMemoryWatchPair(pair);

707+

}

708+709+

protected closeNativeMemoryWatchPairs(): void {

710+

while (this.nativeMemoryWatchPairs.length > 0) {

711+

const pair = this.nativeMemoryWatchPairs[0];

712+

if (!pair) {

713+

return;

714+

}

715+

this.closeNativeMemoryWatchPair(pair);

716+

}

717+

}

718+719+

private removeNativeMemoryParentWatch(w: fsSync.FSWatcher): void {

720+

for (const pair of this.nativeMemoryWatchPairs) {

721+

if (pair.parent === w) {

722+

pair.parent = null;

723+

return;

724+

}

725+

}

726+

}

727+728+

private removeNativeMemoryWatchPair(pair: NativeMemoryWatchPair): void {

729+

const idx = this.nativeMemoryWatchPairs.indexOf(pair);

730+

if (idx >= 0) {

731+

this.nativeMemoryWatchPairs.splice(idx, 1);

732+

}

733+

}

734+735+

// Reattach `dir` to chokidar after a native recursive watcher dies, so

736+

// subsequent memory changes under `dir` continue to drive watch sync.

737+

// Called from the native watcher `error` handler in ensureWatcher();

738+

// factored out so the fallback shape can be unit-tested in isolation.

739+

protected attachMemoryChokidarFallback(

740+

dir: string,

741+

markDirty: (watchPath?: string, stats?: MemoryWatchEventStats) => void,

742+

): void {

743+

if (this.closed) {

744+

// Manager teardown started — don't create new watcher resources.

745+

return;

746+

}

747+

try {

748+

if (this.watcher) {

749+

// Existing chokidar watcher (handling MEMORY.md and/or other file

750+

// paths) — extend it to cover this directory too.

751+

this.watcher.add(dir);

752+

return;

753+

}

754+

// No chokidar watcher exists yet. Spin one up just for this directory

755+

// so the periodic-sync gap is closed.

756+

this.watcher = resolveMemoryWatchFactory()([dir], {

757+

ignoreInitial: true,

758+

ignored: (watchPath, stats) =>

759+

shouldIgnoreMemoryWatchPath(watchPath, stats, this.settings.multimodal),

760+

});

761+

this.watcher.on("add", markDirty);

762+

this.watcher.on("change", markDirty);

763+

this.watcher.on("unlink", markDirty);

764+

this.watcher.on("unlinkDir", markDirty);

765+

this.watcher.on("error", (err) => {

766+

const message = err instanceof Error ? err.message : String(err);

767+

log.warn(`memory watcher error: ${message}`);

768+

});

769+

} catch (err) {

770+

log.warn(`failed to attach chokidar fallback for ${dir}: ${String(err)}`);

771+

}

486772

}

487773488774

protected ensureSessionListener() {