mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-10-01 02:04:21 +00:00
* refactor(components): extract shared component state into mixin - Introduce ComponentMixin class with shared state for components and steps - Move identity, config, and vault path functionality to ComponentMixin - Update BaseComponent to inherit from ComponentMixin - Update BaseStep to inherit from ComponentMixin - Consolidate vault path helper methods in ComponentMixin - Remove duplicate vault path implementations from BaseComponent and BaseStep - Add ComponentMixin to components module exports * refactor(file_io): implement path locks cache eviction mechanism - Add _PATH_LOCKS_MAX constant set to 1024 for cache size limit - Implement cache eviction logic when locks exceed maximum capacity - Remove half of unlocked entries when cache limit is reached - Use list comprehension to identify unlocked locks for removal - Maintain existing path normalization and locking behavior fix(edit): correct method call from public to private fail method - Change self.fail to self._fail for internal error handling - Maintain consistent private method usage within class fix(mcp_client): change pop to get for optional command and args - Replace kwargs.pop with kwargs.get to avoid removing keys - Preserve original kwargs dictionary contents - Maintain default empty string and list values feat(reme): add client backend validation with error raising - Check if client_cls is None before instantiation - Raise ValueError with descriptive message for unknown backends - Provide clear error feedback for invalid backend configurations * fix(components): move directory creation to start method - Moved component_metadata_path.mkdir call from __init__ to _start in base_keyword_index - Moved component_metadata_path.mkdir call from __init__ to _start in local_file_graph - Moved component_metadata_path.mkdir call from __init__ to _start in local_file_store - Ensures directory creation happens after component initialization - Prevents potential issues with path creation during object construction * fix(steps): replace assertions with runtime errors for app_context validation - Replace assert statements with explicit RuntimeError exceptions when app_context is None - Add descriptive error messages for better debugging when resolving components - Replace assert in resolve_component method with proper exception handling - Replace assert in get_file_parser method with proper exception handling - Maintain same functionality while improving error reporting clarity * refactor(file_io): split file IO utilities into modular components - Move daily note helpers to separate _daily_index module - Extract path validation and resolution to new _path module - Remove unused code and imports from _file_io module - Update import statements across affected modules - Introduce WikilinkHandler utility for link parsing - Replace regex-based link extraction with WikilinkHandler - Add integration JSONL files to gitignore - Consolidate file locking mechanism in _file_io module * style(formatter): fix spacing issues in file IO and chunked file parser - Fixed whitespace around colon in slice notation in file_io.py - Corrected spacing around colon in slice notation in chunked_file_parser.py - Applied consistent formatting for array slicing operations - Improved code readability by standardizing space placement in ranges * refactor(steps): replace property-based component resolution with Ref descriptor - Introduce Ref descriptor class for lazy component dependency resolution - Replace _resolve method and individual properties with Ref descriptors - Add as_llm, as_llm_formatter, as_token_counter, file_store, and embedding Ref attributes - Remove legacy property methods and resolve logic from BaseStep - Add cache clearing mechanism for Ref values during step calls - Update UpdateCatalogStep to use Ref instead of property-based resolution
137 lines
5.5 KiB
Python
137 lines
5.5 KiB
Python
"""Pure-Python file-graph backend (no external deps)."""
|
|
|
|
from pathlib import Path
|
|
|
|
from .base_file_graph import BaseFileGraph
|
|
from ..component_registry import R
|
|
from ...enumeration import LinkScopeEnum
|
|
from ...schema import FileLink, FileNode
|
|
|
|
|
|
@R.register("local")
|
|
class LocalFileGraph(BaseFileGraph):
|
|
"""Dict-backed file graph; uses FileLink.target_path for adjacency."""
|
|
|
|
def __init__(self, **kwargs):
|
|
super().__init__(**kwargs)
|
|
self._nodes: dict[str, FileNode] = {}
|
|
self._inverse: dict[str, set[str]] = {} # real target → sources
|
|
self._pending: dict[str, set[str]] = {} # virtual target → sources
|
|
self._graph_file: Path = self.component_metadata_path / f"{self.name}.jsonl"
|
|
|
|
# -- Lifecycle ---------------------------------------------------------
|
|
|
|
async def _start(self) -> None:
|
|
self.component_metadata_path.mkdir(parents=True, exist_ok=True)
|
|
await super()._start() # base calls load()
|
|
await self.rebuild_links()
|
|
|
|
async def load(self) -> None:
|
|
if not self._graph_file.exists():
|
|
return
|
|
try:
|
|
with open(self._graph_file, "r", encoding="utf-8") as f:
|
|
for line in f:
|
|
if line.strip():
|
|
node = FileNode.model_validate_json(line)
|
|
self._nodes[node.path] = node
|
|
self.logger.info(f"Loaded {len(self._nodes)} nodes from {self._graph_file}")
|
|
except Exception as e:
|
|
self.logger.exception(f"Failed to load {self._graph_file}: {e}")
|
|
|
|
async def dump(self) -> None:
|
|
try:
|
|
tmp = self._graph_file.with_suffix(".tmp")
|
|
with open(tmp, "w", encoding="utf-8") as f:
|
|
f.writelines(f"{n.model_dump_json()}\n" for n in self._nodes.values())
|
|
tmp.replace(self._graph_file)
|
|
self.logger.info(f"Saved {len(self._nodes)} nodes to {self._graph_file}")
|
|
except Exception as e:
|
|
self.logger.exception(f"Failed to write {self._graph_file}: {e}")
|
|
|
|
# -- Internals ---------------------------------------------------------
|
|
|
|
@staticmethod
|
|
def _targets(node: FileNode) -> list[str]:
|
|
return [lnk.target_path for lnk in node.links if lnk.target_path]
|
|
|
|
def _add_edge(self, src: str, target: str) -> None:
|
|
bucket = self._inverse if target in self._nodes else self._pending
|
|
bucket.setdefault(target, set()).add(src)
|
|
|
|
def _remove_edge(self, src: str, target: str) -> None:
|
|
for bucket in (self._inverse, self._pending):
|
|
srcs = bucket.get(target)
|
|
if srcs and src in srcs:
|
|
srcs.discard(src)
|
|
if not srcs:
|
|
del bucket[target]
|
|
|
|
def _scope_match(self, target: str, scope: LinkScopeEnum) -> bool:
|
|
if scope is LinkScopeEnum.ALL:
|
|
return True
|
|
is_real = target in self._nodes
|
|
return is_real if scope is LinkScopeEnum.REAL else not is_real
|
|
|
|
# -- Node CRUD ---------------------------------------------------------
|
|
|
|
async def upsert_nodes(self, nodes: list[FileNode]) -> None:
|
|
for node in nodes:
|
|
path = node.path
|
|
old = self._nodes.get(path)
|
|
if old is not None:
|
|
for target in self._targets(old):
|
|
self._remove_edge(path, target)
|
|
self._nodes[path] = node
|
|
for target in self._targets(node):
|
|
self._add_edge(path, target)
|
|
promoted = self._pending.pop(path, None)
|
|
if promoted:
|
|
self._inverse.setdefault(path, set()).update(promoted)
|
|
|
|
async def delete_nodes(self, paths: list[str]) -> None:
|
|
for path in paths:
|
|
node = self._nodes.pop(path, None)
|
|
if node is None:
|
|
continue
|
|
for target in self._targets(node):
|
|
self._remove_edge(path, target)
|
|
demoted = self._inverse.pop(path, None)
|
|
if demoted:
|
|
self._pending.setdefault(path, set()).update(demoted)
|
|
|
|
async def get_nodes(self, paths: list[str] | None = None) -> list[FileNode]:
|
|
if paths is None:
|
|
return list(self._nodes.values())
|
|
return [self._nodes[p] for p in paths if p in self._nodes]
|
|
|
|
async def rebuild_links(self) -> None:
|
|
self._inverse.clear()
|
|
self._pending.clear()
|
|
for src, node in self._nodes.items():
|
|
for target in self._targets(node):
|
|
self._add_edge(src, target)
|
|
|
|
async def clear(self):
|
|
self._nodes.clear()
|
|
self._inverse.clear()
|
|
self._pending.clear()
|
|
self._graph_file.unlink(missing_ok=True)
|
|
|
|
# -- Link access -------------------------------------------------------
|
|
|
|
async def get_outlinks(self, path: str, scope: LinkScopeEnum = LinkScopeEnum.REAL) -> list[FileLink]:
|
|
node = self._nodes.get(path)
|
|
if node is None:
|
|
return []
|
|
return [lnk for lnk in node.links if lnk.target_path and self._scope_match(lnk.target_path, scope)]
|
|
|
|
async def get_inlinks(self, path: str, scope: LinkScopeEnum = LinkScopeEnum.REAL) -> list[FileLink]:
|
|
sources: set[str] = set()
|
|
if scope in (LinkScopeEnum.REAL, LinkScopeEnum.ALL):
|
|
sources |= self._inverse.get(path, set())
|
|
if scope in (LinkScopeEnum.VIRTUAL, LinkScopeEnum.ALL):
|
|
sources |= self._pending.get(path, set())
|
|
return [
|
|
link for src in sources if src in self._nodes for link in self._nodes[src].links if link.target_path == path
|
|
]
|