The two poll loops were ~15 % of a core at idle: the watcher re-stat'd every source transcript each 2 s tick, and the indexer re-walked the workspace (~8 000 dirs / 120 000 files, a Path + relative_to per file) every 2 min. fswatch.TreeWatch (ctypes onto libc, nothing to install) watches every dir of a tree, picks up new dirs as they appear, skips pruned names and reports queue overflows. The watcher drains it each tick and stats only the reported paths — a full re-walk every WATCH_RESCAN_SECS (60 s) and after an overflow stay as the safety net. WorkspaceWatch (its own thread) marks the indexer's cached walk dirty when a context file appears or goes, so the walk runs on that, on save, and every WALK_SAFETY_SECS (30 min); the walk itself now filters on strings before building any path. Without inotify (WATCH_INOTIFY=0, not Linux, the watch limit) both keep the old cadence. Side by side on the live mounts (threads running, a client polling the list every 5 s): 28–40 % → ~4 % of a core, list p90 1.3–2.6 s → ~150–180 ms. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
153 lines
5.7 KiB
Python
153 lines
5.7 KiB
Python
"""Which workspace files the editor exposes (CLAUDE.md, .claude/, data/)."""
|
|
|
|
import os
|
|
import pathlib
|
|
import threading
|
|
|
|
import fswatch
|
|
from core.config import DATA_TEXT_EXTS, IGNORE_DIRS, MD_EXTS, WORKSPACE
|
|
|
|
|
|
# ── file discovery ──────────────────────────────────────────────────────────
|
|
def _is_data_file(rel: pathlib.PurePosixPath) -> bool:
|
|
"""A text file under the repo's root `data/` tree (plans/logs/notes/etc.).
|
|
|
|
Surfaced read-only for visibility; binaries and the ignored `data/tmp/`
|
|
(scratch + secrets) are filtered out via DATA_TEXT_EXTS + IGNORE_DIRS."""
|
|
return (
|
|
len(rel.parts) > 1
|
|
and rel.parts[0] == "data"
|
|
and rel.suffix.lower() in DATA_TEXT_EXTS
|
|
)
|
|
|
|
|
|
def _is_context_file(rel: pathlib.PurePosixPath) -> bool:
|
|
"""A file we expose: any CLAUDE.md, anything under a `.claude/` tree, or a
|
|
text file under the repo's root `data/` tree."""
|
|
if rel.name == "CLAUDE.md":
|
|
return True
|
|
if ".claude" in rel.parts:
|
|
return True
|
|
return _is_data_file(rel)
|
|
|
|
|
|
def _is_editable(rel: pathlib.PurePosixPath) -> bool:
|
|
"""Text files we allow editing. Binary/lock files stay read-only, and the
|
|
`data/` tree is read-only (mounted :ro — surfaced for viewing only)."""
|
|
if _is_data_file(rel):
|
|
return False
|
|
return rel.suffix.lower() in {
|
|
".md", ".markdown", ".sh", ".py", ".js", ".mjs", ".ts", ".tsx",
|
|
".json", ".yml", ".yaml", ".txt", ".toml", ".cfg", ".ini", "",
|
|
}
|
|
|
|
|
|
def _kind(rel: pathlib.PurePosixPath) -> str:
|
|
name = rel.name
|
|
if name == "CLAUDE.md":
|
|
return "claude-md"
|
|
if name == "SKILL.md":
|
|
return "skill-md"
|
|
if rel.suffix in MD_EXTS:
|
|
return "markdown"
|
|
if rel.suffix in {".sh", ".py", ".js", ".mjs", ".ts", ".tsx"}:
|
|
return "script"
|
|
if rel.suffix in {".json", ".yml", ".yaml", ".toml", ".ini", ".cfg"}:
|
|
return "config"
|
|
return "other"
|
|
|
|
|
|
def _iter_files():
|
|
"""Yield (abs_path, rel_posix) for every exposed context file.
|
|
|
|
The walk visits every project dir (~120 000 files) to find a few hundred,
|
|
so a file is only turned into paths once its name or dir can make it a
|
|
context file — a `Path` + `relative_to` per file was most of the walk."""
|
|
base = str(WORKSPACE)
|
|
for dirpath, dirnames, filenames in os.walk(WORKSPACE):
|
|
dirnames[:] = [d for d in dirnames if d not in IGNORE_DIRS]
|
|
reldir = "" if dirpath == base else dirpath[len(base.rstrip("/")) + 1:]
|
|
parts = reldir.split("/") if reldir else []
|
|
whole_dir = ".claude" in parts or (parts and parts[0] == "data")
|
|
for fn in filenames:
|
|
if not (whole_dir or fn == "CLAUDE.md" or fn == ".claude"):
|
|
continue
|
|
rel = pathlib.PurePosixPath(f"{reldir}/{fn}" if reldir else fn)
|
|
if _is_context_file(rel):
|
|
yield pathlib.Path(dirpath) / fn, rel
|
|
|
|
|
|
class WorkspaceWatch:
|
|
"""Tells the indexer when its cached walk (`_iter_files`) may be stale.
|
|
|
|
An inotify watch (fswatch) on every dir the walk visits: a context file
|
|
appearing / going / moving, or a dir that held one going, marks the list
|
|
dirty — so the indexer re-walks on that instead of every couple of
|
|
minutes. Content edits aren't its business: the indexer re-stats the
|
|
cached files each pass. A daemon thread drains the events as they come,
|
|
so a build churning files in a project can't overflow the queue between
|
|
two indexer passes. ``active`` is False until the watch is up, and for
|
|
good where inotify isn't available or the watch limit was hit — the
|
|
indexer then keeps its timed walk."""
|
|
|
|
def __init__(self, root: pathlib.Path = WORKSPACE):
|
|
self.root = str(root)
|
|
self._tw: fswatch.TreeWatch | None = None
|
|
self._dirty = False
|
|
# Rel dirs holding an exposed file, and their ancestors: one of these
|
|
# going away takes exposed files with it.
|
|
self._dirs: frozenset[str] = frozenset()
|
|
|
|
@property
|
|
def active(self) -> bool:
|
|
tw = self._tw
|
|
return tw is not None and tw.ok
|
|
|
|
def start(self) -> None:
|
|
threading.Thread(target=self._run, daemon=True,
|
|
name="workspace-watch").start()
|
|
|
|
def take(self) -> bool:
|
|
"""True (once) when something changed since the last ``take``."""
|
|
d, self._dirty = self._dirty, False
|
|
return d
|
|
|
|
def known(self, files) -> None:
|
|
"""The walk's result — which dirs hold exposed files."""
|
|
dirs = set()
|
|
for _ap, rel in files:
|
|
for parent in rel.parents:
|
|
dirs.add(str(parent))
|
|
dirs.discard(".")
|
|
self._dirs = frozenset(dirs)
|
|
|
|
def _relevant(self, path: str) -> bool:
|
|
if not path.startswith(self.root + "/"):
|
|
return False
|
|
rel = path[len(self.root.rstrip("/")) + 1:]
|
|
return rel in self._dirs or _is_context_file(pathlib.PurePosixPath(rel))
|
|
|
|
def _run(self) -> None:
|
|
tw = fswatch.TreeWatch.open([self.root], prune=lambda n: n in IGNORE_DIRS)
|
|
if tw is None:
|
|
return
|
|
self._tw = tw
|
|
self._dirty = True # anything that moved before the watch was up
|
|
while tw.ok:
|
|
if not tw.wait(None):
|
|
if tw.fileno() < 0:
|
|
break
|
|
continue
|
|
paths, lost = tw.changes()
|
|
if lost or any(self._relevant(p) for p in paths):
|
|
self._dirty = True
|
|
self._dirty = True # watch limit: back to the timed walk
|
|
tw.close()
|
|
|
|
|
|
def _read_text(ap: pathlib.Path) -> str:
|
|
try:
|
|
return ap.read_text(encoding="utf-8")
|
|
except (UnicodeDecodeError, OSError):
|
|
return ""
|