Download cases/filesystem/raw/mcp_servers/filesystem.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 73.9 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/filesystem/raw/mcp_servers/filesystem.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/filesystem/raw/mcp_servers/filesystem.py
-
curl -L -o filesystem.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/filesystem/raw/mcp_servers/filesystem.py
73.9 kB
"""Shared filesystem business logic for all public tools."""
from __future__ import annotations
import copy
import os
from typing import Any, Dict, List, Tuple
from mcp_servers.utils import (
byte_len,
checksum_text,
error_response,
line_count,
now_iso,
slugify,
success_response,
)
VALID_DIR_MODES = {"rwxr-x---", "rw-r-----", "rw-rw----", "r--r-----"}
VALID_FILE_MODES = {"rw-r-----", "rw-rw----", "r--r-----"}
VALID_INHERITANCE = {"explicit", "inherited"}
MIME_BY_EXTENSION = {
"md": "text/markdown",
"txt": "text/plain",
"json": "application/json",
"csv": "text/csv",
"yaml": "application/yaml",
}
def _present(value: Any) -> bool:
return value is not None and (not isinstance(value, str) or bool(value.strip()))
def _norm_bool(value: Any, default: bool = False) -> bool:
return default if value is None else bool(value)
def _workspace_slug(workspace_id: str) -> str:
return str(workspace_id).replace("workspace-", "", 1)
def _get(sm, entity: str, entity_id: str):
return sm.get_entity(entity, entity_id)
def _all(sm, entity: str):
return sm.list_entities(entity)
def _workspace(sm, workspace_id: str):
return _get(sm, "workspace", workspace_id)
def _user(sm, user_id: str):
return _get(sm, "user", user_id)
def _node(sm, node_id: str):
return _get(sm, "node", node_id)
def _content(sm, content_id: str):
return sm.get_entity("file_content", content_id, id_field="content_id")
def _teams_for_workspace(sm, workspace_id: str) -> List[Dict[str, Any]]:
return [team for team in _all(sm, "team") if team.get("workspace_id") == workspace_id]
def _workspace_maintainers(sm, workspace_id: str) -> set[str]:
maintainers: set[str] = set()
for team in _teams_for_workspace(sm, workspace_id):
maintainers.update(team.get("maintainer_user_ids") or [])
return maintainers
def _workspace_members(sm, workspace_id: str) -> set[str]:
members: set[str] = set()
for team in _teams_for_workspace(sm, workspace_id):
members.update(team.get("member_user_ids") or [])
members.update(team.get("maintainer_user_ids") or [])
return members
def _require_workspace_id(workspace_id):
if not _present(workspace_id):
return error_response("MISSING_WORKSPACE_ID", "workspace_id is required")
return None
def _require_actor_user_id(actor_user_id):
if not _present(actor_user_id):
return error_response("MISSING_ACTOR_USER_ID", "actor_user_id is required")
return None
def _validate_workspace(sm, workspace_id: str, *, require_active: bool = False, allow_locked: bool = False, reject_maintenance: bool = False):
workspace = _workspace(sm, workspace_id)
if workspace is None:
return None, error_response("WORKSPACE_NOT_FOUND", f"Workspace {workspace_id} was not found")
status = workspace.get("status")
if require_active and status != "active":
return None, error_response("WORKSPACE_NOT_ACTIVE", f"Workspace {workspace_id} is not active")
if reject_maintenance and status == "maintenance":
return None, error_response("WORKSPACE_NOT_ACTIVE", f"Workspace {workspace_id} is in maintenance")
if not allow_locked and status == "locked" and require_active:
return None, error_response("WORKSPACE_NOT_ACTIVE", f"Workspace {workspace_id} is locked")
return workspace, None
def _validate_actor(sm, actor_user_id: str):
actor = _user(sm, actor_user_id)
if actor is None:
return None, error_response("USER_NOT_FOUND", f"User {actor_user_id} was not found")
if actor.get("status") != "active":
sm.increment_counter("permission_control.suspended_actor_blocks", 1)
return None, error_response("USER_NOT_ACTIVE", f"User {actor_user_id} is not active")
return actor, None
def _normalize_path(path: str) -> str:
text = "/" + str(path or "").strip().strip("/")
return "/" if text == "/" else text.rstrip("/")
def _find_node_by_path(sm, workspace_id: str, path: str):
norm = _normalize_path(path)
for node in _all(sm, "node"):
if node.get("workspace_id") == workspace_id and _normalize_path(node.get("path")) == norm:
return node
return None
def _children(sm, parent_node_id: str, *, include_deleted: bool = False) -> List[Dict[str, Any]]:
children = [node for node in _all(sm, "node") if node.get("parent_node_id") == parent_node_id]
if not include_deleted:
children = [node for node in children if not node.get("is_deleted")]
return children
def _subtree(sm, root_node_id: str, *, include_deleted: bool = False) -> List[Dict[str, Any]]:
nodes = _all(sm, "node")
by_parent: Dict[str, List[Dict[str, Any]]] = {}
for node in nodes:
by_parent.setdefault(node.get("parent_node_id"), []).append(node)
result = []
stack = [root_node_id]
while stack:
current_id = stack.pop()
node = next((item for item in nodes if item.get("node_id") == current_id), None)
if node is None:
continue
if include_deleted or not node.get("is_deleted"):
result.append(node)
for child in sorted(by_parent.get(current_id, []), key=lambda item: item.get("path", "")):
stack.append(child.get("node_id"))
return sorted(result, key=lambda item: item.get("path", ""))
def _is_descendant(sm, ancestor_id: str, maybe_descendant_id: str) -> bool:
current = _node(sm, maybe_descendant_id)
while current is not None:
parent_id = current.get("parent_node_id")
if parent_id == ancestor_id:
return True
current = _node(sm, parent_id) if parent_id else None
return False
def _validate_name(name: Any, *, file_required: bool = False, max_len: int = 160) -> Tuple[str | None, str | None]:
if not _present(name):
return None, "missing"
text = str(name).strip()
if "/" in text or len(text) > max_len or text in {".", ".."}:
return None, "invalid"
if file_required:
base = os.path.basename(text)
if base.count(".") != 1 or base.startswith(".") or base.endswith("."):
return None, "invalid"
return text, None
def _sibling_conflict(sm, parent_id: str, name: str, *, excluding_node_id: str | None = None) -> bool:
norm = name.strip().lower()
for child in _children(sm, parent_id):
if child.get("node_id") == excluding_node_id:
continue
if str(child.get("name", "")).strip().lower() == norm:
return True
return False
def _effective_permission(sm, node: Dict[str, Any]) -> Dict[str, Any]:
permission = copy.deepcopy(node.get("permission") or {})
if permission.get("inheritance") == "inherited" and permission.get("inherited_from_node_id"):
parent = _node(sm, permission.get("inherited_from_node_id"))
if parent is not None:
parent_perm = copy.deepcopy(parent.get("permission") or {})
parent_perm["inherited_from_node_id"] = permission.get("inherited_from_node_id")
return parent_perm
return permission
def _actor_flags(sm, node: Dict[str, Any], actor_user_id: str | None) -> Dict[str, Any]:
if not actor_user_id:
return {}
permission = _effective_permission(sm, node)
workspace_id = node.get("workspace_id")
is_owner = permission.get("owner_user_id") == actor_user_id
is_maintainer = actor_user_id in _workspace_maintainers(sm, workspace_id)
is_member = actor_user_id in _workspace_members(sm, workspace_id)
override_roles = []
for item in permission.get("team_overrides") or []:
team_id = item.get("team_id")
team = sm.get_entity("team", team_id) if team_id else None
if team and actor_user_id in set((team.get("member_user_ids") or []) + (team.get("maintainer_user_ids") or [])):
override_roles.append(item.get("role"))
can_read = is_owner or is_maintainer or is_member
can_write = is_owner or is_maintainer or "editor" in override_roles or (is_member and permission.get("mode") in {"rw-rw----", "rwxr-x---"})
if permission.get("mode") == "r--r-----" and not (is_owner or is_maintainer):
can_write = False
return {
"actor_user_id": actor_user_id,
"can_read": bool(can_read),
"can_write": bool(can_write),
"is_owner": bool(is_owner),
"is_workspace_maintainer": bool(is_maintainer),
"team_roles": sorted(role for role in override_roles if role),
}
def _can_read(sm, node: Dict[str, Any], actor_user_id: str) -> bool:
return _actor_flags(sm, node, actor_user_id).get("can_read", False)
def _can_write(sm, node: Dict[str, Any], actor_user_id: str) -> bool:
return _actor_flags(sm, node, actor_user_id).get("can_write", False)
def _can_admin(sm, node: Dict[str, Any], actor_user_id: str) -> bool:
permission = node.get("permission") or {}
return permission.get("owner_user_id") == actor_user_id or actor_user_id in _workspace_maintainers(sm, node.get("workspace_id"))
def _live_file_bytes(sm, workspace_id: str) -> int:
return sum(int(node.get("size_bytes") or 0) for node in _all(sm, "node") if node.get("workspace_id") == workspace_id and node.get("node_type") == "file" and not node.get("is_deleted"))
def _update_workspace_usage(sm, workspace_id: str) -> Dict[str, Any]:
workspace = _workspace(sm, workspace_id)
if workspace is None:
return {}
updated = copy.deepcopy(workspace)
updated["used_bytes"] = _live_file_bytes(sm, workspace_id)
updated["updated_at"] = now_iso()
return sm.add_entity("workspace", updated)
def _operation_id(sm, workspace_id: str, action: str) -> str:
slug = _workspace_slug(workspace_id)
sequence = len(_all(sm, "operation")) + 1
return f"op-{slug}-2026-05-{action}-{sequence:04d}"
def _append_operation(sm, workspace_id: str, actor_user_id: str, target_node_id: str, action: str, source_path: str, destination_path: str | None, reason: str = "agent request") -> str:
op_id = _operation_id(sm, workspace_id, action)
operation = {
"operation_id": op_id,
"workspace_id": workspace_id,
"actor_user_id": actor_user_id,
"target_node_id": target_node_id,
"action": action,
"status": "success",
"request_id": f"req-{_workspace_slug(workspace_id)}-{len(_all(sm, 'operation')) + 1:04d}",
"details": {
"source_path": source_path,
"destination_path": destination_path,
"reason": reason,
},
"created_at": now_iso(),
}
sm.add_entity("operation", operation, id_field="operation_id")
return op_id
def _extension(name: str) -> str | None:
if "." not in name:
return None
return name.rsplit(".", 1)[1].lower()
def _new_id(sm, entity_type: str, base: str) -> str:
slug = slugify(base)
prefix = {
"node": "node",
"file_content": "content",
"manifest": "manifest",
"operation": "op",
"snapshot": "snapshot",
}.get(entity_type, entity_type)
candidate = f"{prefix}-{slug}"
id_field = {"file_content": "content_id"}.get(entity_type, f"{entity_type}_id")
existing = {row.get(id_field) for row in _all(sm, entity_type)}
index = 2
while candidate in existing:
candidate = f"{prefix}-{slug}-{index}"
index += 1
return candidate
def _node_summary(node: Dict[str, Any]) -> Dict[str, Any]:
return {
"node_id": node.get("node_id"),
"workspace_id": node.get("workspace_id"),
"parent_node_id": node.get("parent_node_id"),
"name": node.get("name"),
"node_type": node.get("node_type"),
"path": node.get("path"),
"extension": node.get("extension"),
"mime_type": node.get("mime_type"),
"size_bytes": node.get("size_bytes"),
"is_deleted": node.get("is_deleted"),
"is_archived": node.get("is_archived"),
"permission": node.get("permission"),
"created_at": node.get("created_at"),
"updated_at": node.get("updated_at"),
}
def get_node(state_manager, workspace_id=None, node_id=None, path=None, include_deleted=False):
if err := _require_workspace_id(workspace_id):
return err
if bool(_present(node_id)) == bool(_present(path)):
return error_response("INVALID_IDENTIFIER_CHOICE", "Provide exactly one of node_id or path")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
node = _node(state_manager, node_id) if _present(node_id) else _find_node_by_path(state_manager, workspace_id, path)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Node was not found in the workspace")
if node.get("is_deleted") and not include_deleted:
return error_response("NODE_DELETED", "Node is deleted")
parent = _node(state_manager, node.get("parent_node_id")) if node.get("parent_node_id") else None
child_counts = {"files": 0, "directories": 0}
if node.get("node_type") == "directory":
for child in _children(state_manager, node.get("node_id")):
if child.get("node_type") == "file":
child_counts["files"] += 1
elif child.get("node_type") == "directory":
child_counts["directories"] += 1
return success_response({
"node": _node_summary(node),
"parent": {"node_id": parent.get("node_id"), "path": parent.get("path")} if parent else None,
"child_counts": child_counts,
}, "Node retrieved")
def list_directory(state_manager, workspace_id=None, directory_id=None, node_type_filter=None, include_archived=False, sort_by="name", sort_order="asc", limit=50, offset=0):
if err := _require_workspace_id(workspace_id):
return err
if not _present(directory_id):
return error_response("MISSING_DIRECTORY_ID", "directory_id is required")
if node_type_filter is not None and node_type_filter not in {"file", "directory"}:
return error_response("INVALID_NODE_TYPE_FILTER", "node_type_filter must be file or directory")
if sort_by not in {"name", "updated_at", "size_bytes"}:
return error_response("INVALID_SORT_FIELD", "sort_by is invalid")
if sort_order not in {"asc", "desc"}:
return error_response("INVALID_SORT_ORDER", "sort_order is invalid")
try:
limit = int(limit)
offset = int(offset)
except (TypeError, ValueError):
return error_response("OUT_OF_RANGE", "limit and offset must be integers")
if limit < 1 or limit > 200 or offset < 0:
return error_response("OUT_OF_RANGE", "limit or offset is outside the allowed range")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
directory = _node(state_manager, directory_id)
if directory is None or directory.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Directory node was not found")
if directory.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Node is not a directory")
if directory.get("is_deleted"):
return error_response("NODE_DELETED", "Directory is deleted")
children = [child for child in _children(state_manager, directory_id) if include_archived or not child.get("is_archived")]
if node_type_filter:
children = [child for child in children if child.get("node_type") == node_type_filter]
children.sort(key=lambda item: item.get(sort_by) or 0, reverse=(sort_order == "desc"))
page = children[offset: offset + limit]
return success_response({
"directory": {"node_id": directory_id, "path": directory.get("path"), "workspace_id": workspace_id},
"total_count": len(children),
"limit": limit,
"offset": offset,
"children": [
{
"node_id": child.get("node_id"),
"name": child.get("name"),
"node_type": child.get("node_type"),
"path": child.get("path"),
"size_bytes": child.get("size_bytes"),
"is_archived": child.get("is_archived"),
"updated_at": child.get("updated_at"),
}
for child in page
],
}, "Directory listed")
def search_nodes(state_manager, workspace_id=None, query="", path_prefix=None, node_type_filter=None, extension_filter=None, include_archived=False, include_deleted=False, sort_by="path", sort_order="asc", limit=50, offset=0):
if err := _require_workspace_id(workspace_id):
return err
if node_type_filter is not None and node_type_filter not in {"file", "directory"}:
return error_response("INVALID_NODE_TYPE_FILTER", "node_type_filter must be file or directory")
if sort_by not in {"path", "updated_at", "size_bytes"}:
return error_response("INVALID_SORT_FIELD", "sort_by is invalid")
if sort_order not in {"asc", "desc"}:
return error_response("INVALID_SORT_ORDER", "sort_order is invalid")
try:
limit = int(limit)
offset = int(offset)
except (TypeError, ValueError):
return error_response("OUT_OF_RANGE", "limit and offset must be integers")
if limit < 1 or limit > 200 or offset < 0:
return error_response("OUT_OF_RANGE", "limit or offset is outside the allowed range")
if path_prefix is not None and not str(path_prefix).startswith("/"):
return error_response("INVALID_PATH", "path_prefix must start with slash")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
text = str(query or "").lower()
results = [node for node in _all(state_manager, "node") if node.get("workspace_id") == workspace_id]
if not include_deleted:
results = [node for node in results if not node.get("is_deleted")]
if not include_archived:
results = [node for node in results if not node.get("is_archived")]
if text:
results = [node for node in results if text in str(node.get("name", "")).lower() or text in str(node.get("path", "")).lower()]
if path_prefix:
prefix = _normalize_path(path_prefix)
results = [node for node in results if _normalize_path(node.get("path")).startswith(prefix)]
if node_type_filter:
results = [node for node in results if node.get("node_type") == node_type_filter]
if extension_filter is not None:
ext = str(extension_filter).lstrip(".").lower()
results = [node for node in results if str(node.get("extension") or "").lower() == ext]
results.sort(key=lambda item: item.get(sort_by) or 0, reverse=(sort_order == "desc"))
page = results[offset: offset + limit]
return success_response({
"total_count": len(results),
"limit": limit,
"offset": offset,
"nodes": [
{
"node_id": node.get("node_id"),
"name": node.get("name"),
"node_type": node.get("node_type"),
"path": node.get("path"),
"extension": node.get("extension"),
"size_bytes": node.get("size_bytes"),
"is_archived": node.get("is_archived"),
"is_deleted": node.get("is_deleted"),
"updated_at": node.get("updated_at"),
}
for node in page
],
}, "Nodes searched")
def get_file_content(state_manager, workspace_id=None, node_id=None, start_line=1, line_count=200):
if err := _require_workspace_id(workspace_id):
return err
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
try:
start_line = int(start_line)
line_count_value = int(line_count)
except (TypeError, ValueError):
return error_response("OUT_OF_RANGE", "start_line and line_count must be integers")
if start_line < 1 or line_count_value < 1 or line_count_value > 1000:
return error_response("OUT_OF_RANGE", "line range is outside the allowed range")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "File node was not found")
if node.get("node_type") != "file":
return error_response("NODE_NOT_FILE", "Node is not a file")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "File is deleted")
content = _content(state_manager, node.get("content_ref"))
if content is None:
return error_response("CONTENT_NOT_FOUND", "File content row was not found")
lines = str(content.get("text") or "").splitlines()
start_index = start_line - 1
selected = lines[start_index: start_index + line_count_value]
return success_response({
"file": {
"node_id": node.get("node_id"),
"path": node.get("path"),
"mime_type": node.get("mime_type"),
"size_bytes": node.get("size_bytes"),
"checksum": node.get("checksum"),
},
"content": {
"encoding": content.get("encoding"),
"start_line": start_line,
"returned_line_count": len(selected),
"total_line_count": int(content.get("line_count") or 0),
"text": "\n".join(selected),
},
}, "File content retrieved")
def get_effective_permissions(state_manager, workspace_id=None, node_id=None, actor_user_id=None):
if err := _require_workspace_id(workspace_id):
return err
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Node was not found")
if actor_user_id is not None and _user(state_manager, actor_user_id) is None:
return error_response("USER_NOT_FOUND", "actor_user_id was not found")
permission = _effective_permission(state_manager, node)
if actor_user_id:
permission["actor_access"] = _actor_flags(state_manager, node, actor_user_id)
return success_response({"permission": permission}, "Effective permission computed")
def list_snapshots(state_manager, workspace_id=None, reason_filter=None, sort_order="desc", limit=20, offset=0):
if err := _require_workspace_id(workspace_id):
return err
if sort_order not in {"asc", "desc"}:
return error_response("INVALID_SORT_ORDER", "sort_order is invalid")
try:
limit = int(limit)
offset = int(offset)
except (TypeError, ValueError):
return error_response("OUT_OF_RANGE", "limit and offset must be integers")
if limit < 1 or limit > 100 or offset < 0:
return error_response("OUT_OF_RANGE", "limit or offset is outside the allowed range")
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
snapshots = [snapshot for snapshot in _all(state_manager, "snapshot") if snapshot.get("workspace_id") == workspace_id]
if reason_filter:
text = str(reason_filter).lower()
snapshots = [snapshot for snapshot in snapshots if text in str(snapshot.get("reason", "")).lower()]
snapshots.sort(key=lambda item: item.get("created_at") or "", reverse=(sort_order == "desc"))
page = snapshots[offset: offset + limit]
return success_response({
"total_count": len(snapshots),
"limit": limit,
"offset": offset,
"snapshots": [
{
"snapshot_id": item.get("snapshot_id"),
"root_node_id": item.get("root_node_id"),
"reason": item.get("reason"),
"node_count": item.get("node_count"),
"total_bytes": item.get("total_bytes"),
"created_by": item.get("created_by"),
"created_at": item.get("created_at"),
}
for item in page
],
}, "Snapshots listed")
def inspect_quota(state_manager, workspace_id=None, include_breakdown=False):
if err := _require_workspace_id(workspace_id):
return err
workspace, err = _validate_workspace(state_manager, workspace_id)
if err:
return err
live_files = [node for node in _all(state_manager, "node") if node.get("workspace_id") == workspace_id and node.get("node_type") == "file" and not node.get("is_deleted")]
used_bytes = sum(int(node.get("size_bytes") or 0) for node in live_files)
quota_bytes = int(workspace.get("quota_bytes") or 0)
quota = {
"workspace_id": workspace_id,
"quota_bytes": quota_bytes,
"used_bytes": used_bytes,
"remaining_bytes": max(0, quota_bytes - used_bytes),
"pressure_ratio": round(used_bytes / quota_bytes, 6) if quota_bytes else 0.0,
"live_file_count": len(live_files),
}
if include_breakdown:
breakdown: Dict[str, Dict[str, int]] = {}
for node in live_files:
ext = node.get("extension") or "none"
item = breakdown.setdefault(ext, {"file_count": 0, "bytes": 0})
item["file_count"] += 1
item["bytes"] += int(node.get("size_bytes") or 0)
quota["extension_breakdown"] = breakdown
return success_response({"quota": quota}, "Quota inspected")
def _base_write_precheck(sm, workspace_id, actor_user_id):
if err := _require_workspace_id(workspace_id):
return None, None, err
if err := _require_actor_user_id(actor_user_id):
return None, None, err
workspace, err = _validate_workspace(sm, workspace_id, require_active=True)
if err:
return None, None, err
actor, err = _validate_actor(sm, actor_user_id)
if err:
return None, None, err
return workspace, actor, None
def create_directory(state_manager, workspace_id=None, parent_node_id=None, name=None, actor_user_id=None, permission_mode=None):
if not _present(parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "parent_node_id is required")
if not _present(name):
return error_response("MISSING_NAME", "name is required")
if permission_mode is not None and permission_mode not in VALID_DIR_MODES:
return error_response("INVALID_MODE", "permission_mode is invalid")
name_value, name_error = _validate_name(name, file_required=False, max_len=120)
if name_error:
return error_response("INVALID_NAME", "Directory name is malformed")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
parent = _node(state_manager, parent_node_id)
if parent is None or parent.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Parent node was not found")
if parent.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Parent node is not a directory")
if parent.get("is_deleted"):
return error_response("NODE_DELETED", "Parent node is deleted")
if not _can_write(state_manager, parent, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot write under the parent")
if _sibling_conflict(state_manager, parent_node_id, name_value):
return error_response("PATH_CONFLICT", "A live sibling already uses that name")
path = f"{parent.get('path').rstrip('/')}/{name_value}"
node_id = _new_id(state_manager, "node", f"{_workspace_slug(workspace_id)}-{slugify(name_value)}")
parent_perm = parent.get("permission") or {}
permission = copy.deepcopy(parent_perm)
if permission_mode:
permission["mode"] = permission_mode
permission["inheritance"] = "explicit"
permission["inherited_from_node_id"] = None
else:
permission["inheritance"] = "inherited"
permission["inherited_from_node_id"] = parent_node_id
timestamp = now_iso()
node = {
"node_id": node_id,
"workspace_id": workspace_id,
"parent_node_id": parent_node_id,
"name": name_value,
"node_type": "directory",
"path": path,
"extension": None,
"mime_type": None,
"size_bytes": 0,
"content_ref": None,
"checksum": None,
"depth": int(parent.get("depth") or 0) + 1,
"is_deleted": False,
"is_archived": False,
"permission": permission,
"created_by": actor_user_id,
"updated_by": actor_user_id,
"created_at": timestamp,
"updated_at": timestamp,
}
state_manager.add_entity("node", node)
_update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "create", path, None)
return success_response({"node": _node_summary(node), "operation_id": operation_id}, "Directory created")
def create_file(state_manager, workspace_id=None, parent_node_id=None, name=None, content_text=None, actor_user_id=None, permission_mode=None):
if not _present(parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "parent_node_id is required")
if not _present(name):
return error_response("MISSING_NAME", "name is required")
if content_text is None:
return error_response("MISSING_CONTENT", "content_text is required")
if not _present(actor_user_id):
return error_response("MISSING_ACTOR_USER_ID", "actor_user_id is required")
if permission_mode is not None and permission_mode not in VALID_FILE_MODES:
return error_response("INVALID_MODE", "permission_mode is invalid")
name_value, name_error = _validate_name(name, file_required=True, max_len=160)
if name_error:
return error_response("INVALID_NAME", "File name is malformed")
if not isinstance(content_text, str) or len(content_text) > 250000:
return error_response("INVALID_CONTENT", "content_text must be a string of at most 250000 characters")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
parent = _node(state_manager, parent_node_id)
if parent is None or parent.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Parent node was not found")
if parent.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Parent node is not a directory")
if parent.get("is_deleted"):
return error_response("NODE_DELETED", "Parent node is deleted")
if not _can_write(state_manager, parent, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot write under the parent")
if _sibling_conflict(state_manager, parent_node_id, name_value):
return error_response("PATH_CONFLICT", "A live sibling already uses that name")
size = byte_len(content_text)
if _live_file_bytes(state_manager, workspace_id) + size > int(workspace.get("quota_bytes") or 0):
return error_response("QUOTA_EXCEEDED", "The new file would exceed workspace quota")
ext = _extension(name_value)
path = f"{parent.get('path').rstrip('/')}/{name_value}"
base_slug = f"{_workspace_slug(workspace_id)}-{slugify(name_value.rsplit('.', 1)[0])}"
node_id = _new_id(state_manager, "node", base_slug)
content_id = _new_id(state_manager, "file_content", base_slug)
parent_perm = parent.get("permission") or {}
permission = copy.deepcopy(parent_perm)
permission["mode"] = permission_mode or permission.get("mode", "rw-r-----")
if permission_mode:
permission["inheritance"] = "explicit"
permission["inherited_from_node_id"] = None
else:
permission["inheritance"] = "inherited"
permission["inherited_from_node_id"] = parent_node_id
timestamp = now_iso()
node = {
"node_id": node_id,
"workspace_id": workspace_id,
"parent_node_id": parent_node_id,
"name": name_value,
"node_type": "file",
"path": path,
"extension": ext,
"mime_type": MIME_BY_EXTENSION.get(ext, "text/plain"),
"size_bytes": size,
"content_ref": content_id,
"checksum": checksum_text(content_text),
"depth": int(parent.get("depth") or 0) + 1,
"is_deleted": False,
"is_archived": False,
"permission": permission,
"created_by": actor_user_id,
"updated_by": actor_user_id,
"created_at": timestamp,
"updated_at": timestamp,
}
content = {
"content_id": content_id,
"node_id": node_id,
"encoding": "utf-8",
"line_count": line_count(content_text),
"text": content_text,
"created_at": timestamp,
"updated_at": timestamp,
}
state_manager.add_entity("node", node)
state_manager.add_entity("file_content", content, id_field="content_id")
workspace_usage = _update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "create", path, None)
return success_response({"node": _node_summary(node), "content": {"content_id": content_id, "line_count": content["line_count"]}, "workspace_usage": {"used_bytes": workspace_usage.get("used_bytes"), "quota_bytes": workspace_usage.get("quota_bytes")}, "operation_id": operation_id}, "File created")
def update_file_content(state_manager, workspace_id=None, node_id=None, content_text=None, actor_user_id=None, expected_checksum=None):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
if content_text is None:
return error_response("MISSING_CONTENT", "content_text is required")
if not isinstance(content_text, str) or len(content_text) > 250000:
return error_response("INVALID_CONTENT", "content_text must be a string of at most 250000 characters")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "File node was not found")
if node.get("node_type") != "file":
return error_response("NODE_NOT_FILE", "Node is not a file")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "File is deleted")
content = _content(state_manager, node.get("content_ref"))
if content is None:
return error_response("CONTENT_NOT_FOUND", "File content row was not found")
if not _can_write(state_manager, node, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot edit the file")
old_checksum = node.get("checksum")
if expected_checksum is not None and expected_checksum != old_checksum:
return error_response("CHECKSUM_CONFLICT", "expected_checksum does not match the current checksum")
old_size = int(node.get("size_bytes") or 0)
new_size = byte_len(content_text)
if _live_file_bytes(state_manager, workspace_id) - old_size + new_size > int(workspace.get("quota_bytes") or 0):
return error_response("QUOTA_EXCEEDED", "Replacement content would exceed workspace quota")
timestamp = now_iso()
node = copy.deepcopy(node)
content = copy.deepcopy(content)
content.update({"text": content_text, "line_count": line_count(content_text), "updated_at": timestamp})
node.update({"size_bytes": new_size, "checksum": checksum_text(content_text), "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("file_content", content, id_field="content_id")
state_manager.add_entity("node", node)
workspace_usage = _update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "write", node.get("path"), None)
return success_response({"node_id": node_id, "content_id": content.get("content_id"), "old_checksum": old_checksum, "new_checksum": node.get("checksum"), "size_delta": new_size - old_size, "line_count": content.get("line_count"), "workspace_usage": {"used_bytes": workspace_usage.get("used_bytes"), "quota_bytes": workspace_usage.get("quota_bytes")}, "operation_id": operation_id}, "File content replaced")
def update_file_by_appending_content(state_manager, workspace_id=None, node_id=None, append_text=None, actor_user_id=None, ensure_newline=True):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
if append_text is None:
return error_response("MISSING_CONTENT", "append_text is required")
if not isinstance(append_text, str) or len(append_text) > 50000:
return error_response("INVALID_CONTENT", "append_text must be a string of at most 50000 characters")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "File node was not found")
if node.get("node_type") != "file":
return error_response("NODE_NOT_FILE", "Node is not a file")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "File is deleted")
content = _content(state_manager, node.get("content_ref"))
if content is None:
return error_response("CONTENT_NOT_FOUND", "File content row was not found")
if not _can_write(state_manager, node, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot edit the file")
existing_text = str(content.get("text") or "")
addition = str(append_text)
if ensure_newline and existing_text and not existing_text.endswith("\n"):
addition = "\n" + addition
appended_bytes = byte_len(addition)
if _live_file_bytes(state_manager, workspace_id) + appended_bytes > int(workspace.get("quota_bytes") or 0):
return error_response("QUOTA_EXCEEDED", "Append would exceed workspace quota")
new_text = existing_text + addition
timestamp = now_iso()
node = copy.deepcopy(node)
content = copy.deepcopy(content)
content.update({"text": new_text, "line_count": line_count(new_text), "updated_at": timestamp})
node.update({"size_bytes": byte_len(new_text), "checksum": checksum_text(new_text), "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("file_content", content, id_field="content_id")
state_manager.add_entity("node", node)
workspace_usage = _update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "append", node.get("path"), None)
return success_response({"node_id": node_id, "content_id": content.get("content_id"), "new_checksum": node.get("checksum"), "appended_bytes": appended_bytes, "line_count": content.get("line_count"), "workspace_usage": {"used_bytes": workspace_usage.get("used_bytes"), "quota_bytes": workspace_usage.get("quota_bytes")}, "operation_id": operation_id}, "File content appended")
def _update_descendant_paths(sm, root_node: Dict[str, Any], old_path: str, new_path: str, actor_user_id: str, depth_delta: int = 0) -> int:
changed = 0
timestamp = now_iso()
for descendant in _subtree(sm, root_node.get("node_id")):
if descendant.get("node_id") == root_node.get("node_id"):
continue
updated = copy.deepcopy(descendant)
updated["path"] = new_path + str(descendant.get("path", ""))[len(old_path):]
updated["depth"] = int(descendant.get("depth") or 0) + depth_delta
updated["updated_by"] = actor_user_id
updated["updated_at"] = timestamp
sm.add_entity("node", updated)
changed += 1
return changed
def rename_node(state_manager, workspace_id=None, node_id=None, new_name=None, actor_user_id=None):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
if not _present(new_name):
return error_response("MISSING_NAME", "new_name is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Node was not found")
name_value, name_error = _validate_name(new_name, file_required=(node.get("node_type") == "file"), max_len=160)
if name_error:
return error_response("INVALID_NAME", "new_name is malformed")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "Node is deleted")
if node.get("parent_node_id") is None:
return error_response("ROOT_NODE_IMMUTABLE", "Workspace root cannot be renamed")
parent = _node(state_manager, node.get("parent_node_id"))
if parent is None or not _can_write(state_manager, parent, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot rename the node")
if _sibling_conflict(state_manager, node.get("parent_node_id"), name_value, excluding_node_id=node_id):
return error_response("PATH_CONFLICT", "A live sibling already uses that name")
old_path = node.get("path")
new_path = f"{parent.get('path').rstrip('/')}/{name_value}"
updated = copy.deepcopy(node)
updated.update({"name": name_value, "path": new_path, "extension": _extension(name_value) if node.get("node_type") == "file" else None, "updated_by": actor_user_id, "updated_at": now_iso()})
state_manager.add_entity("node", updated)
changed = _update_descendant_paths(state_manager, updated, old_path, new_path, actor_user_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "rename", old_path, new_path)
return success_response({"node_id": node_id, "old_path": old_path, "new_path": new_path, "descendant_paths_updated": changed, "operation_id": operation_id}, "Node renamed")
def update_node_location(state_manager, workspace_id=None, node_id=None, new_parent_node_id=None, actor_user_id=None, preserve_permissions=True):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
if not _present(new_parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "new_parent_node_id is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
dest = _node(state_manager, new_parent_node_id)
if node is None or dest is None or node.get("workspace_id") != workspace_id or dest.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Source or destination node was not found")
if dest.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Destination is not a directory")
if node.get("is_deleted") or dest.get("is_deleted"):
return error_response("NODE_DELETED", "Source or destination is deleted")
if node.get("parent_node_id") is None:
return error_response("ROOT_NODE_IMMUTABLE", "Workspace root cannot be moved")
if node_id == new_parent_node_id or _is_descendant(state_manager, node_id, new_parent_node_id):
return error_response("MOVE_CYCLE_CONFLICT", "Destination is inside the moving subtree")
current_parent = _node(state_manager, node.get("parent_node_id"))
if current_parent is None or not (_can_write(state_manager, current_parent, actor_user_id) and _can_write(state_manager, dest, actor_user_id)):
return error_response("PERMISSION_DENIED", "Actor cannot move between the source and destination")
if _sibling_conflict(state_manager, new_parent_node_id, node.get("name"), excluding_node_id=node_id):
return error_response("PATH_CONFLICT", "Destination already has a live child with that name")
old_parent = node.get("parent_node_id")
old_path = node.get("path")
old_depth = int(node.get("depth") or 0)
new_depth = int(dest.get("depth") or 0) + 1
new_path = f"{dest.get('path').rstrip('/')}/{node.get('name')}"
updated = copy.deepcopy(node)
updated.update({"parent_node_id": new_parent_node_id, "path": new_path, "depth": new_depth, "updated_by": actor_user_id, "updated_at": now_iso()})
if not preserve_permissions:
updated["permission"] = copy.deepcopy(dest.get("permission") or {})
updated["permission"]["inheritance"] = "inherited"
updated["permission"]["inherited_from_node_id"] = new_parent_node_id
state_manager.add_entity("node", updated)
changed = _update_descendant_paths(state_manager, updated, old_path, new_path, actor_user_id, new_depth - old_depth)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "move", old_path, new_path)
return success_response({"node_id": node_id, "old_parent_node_id": old_parent, "new_parent_node_id": new_parent_node_id, "old_path": old_path, "new_path": new_path, "descendant_paths_updated": changed, "operation_id": operation_id}, "Node moved")
def clone_node(state_manager, workspace_id=None, source_node_id=None, destination_parent_node_id=None, actor_user_id=None, new_name=None, copy_permissions=False):
if not _present(source_node_id):
return error_response("MISSING_NODE_ID", "source_node_id is required")
if not _present(destination_parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "destination_parent_node_id is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
source = _node(state_manager, source_node_id)
dest = _node(state_manager, destination_parent_node_id)
if source is None or dest is None or source.get("workspace_id") != workspace_id or dest.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Source or destination node was not found")
if dest.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Destination parent is not a directory")
if source.get("is_deleted") or dest.get("is_deleted"):
return error_response("NODE_DELETED", "Source or destination is deleted")
root_name = str(new_name).strip() if _present(new_name) else source.get("name")
name_value, name_error = _validate_name(root_name, file_required=(source.get("node_type") == "file"), max_len=160)
if name_error:
return error_response("INVALID_NAME", "new_name is malformed")
if not (_can_read(state_manager, source, actor_user_id) and _can_write(state_manager, dest, actor_user_id)):
return error_response("PERMISSION_DENIED", "Actor lacks source read or destination write access")
source_tree = _subtree(state_manager, source_node_id)
if len(source_tree) > 250:
return error_response("SUBTREE_TOO_LARGE", "Source subtree exceeds the copy limit")
if _sibling_conflict(state_manager, destination_parent_node_id, name_value):
return error_response("PATH_CONFLICT", "Destination already has the copied root name")
bytes_to_copy = sum(int(node.get("size_bytes") or 0) for node in source_tree if node.get("node_type") == "file")
if _live_file_bytes(state_manager, workspace_id) + bytes_to_copy > int(workspace.get("quota_bytes") or 0):
return error_response("QUOTA_EXCEEDED", "Copied bytes would exceed workspace quota")
timestamp = now_iso()
id_map: Dict[str, str] = {}
created_nodes: List[Dict[str, Any]] = []
created_contents = 0
old_root_path = source.get("path")
new_root_path = f"{dest.get('path').rstrip('/')}/{name_value}"
for old in source_tree:
old_id = old.get("node_id")
relative = old.get("path")[len(old_root_path):].strip("/")
new_node = copy.deepcopy(old)
new_node_id = _new_id(state_manager, "node", f"{_workspace_slug(workspace_id)}-{slugify(new_root_path)}-{slugify(relative) if relative else 'root'}")
id_map[old_id] = new_node_id
new_node["node_id"] = new_node_id
new_node["name"] = name_value if old_id == source_node_id else old.get("name")
new_node["parent_node_id"] = destination_parent_node_id if old_id == source_node_id else id_map.get(old.get("parent_node_id"))
new_node["path"] = new_root_path if old_id == source_node_id else f"{new_root_path}/{relative}"
new_node["depth"] = int(dest.get("depth") or 0) + 1 + (0 if old_id == source_node_id else len(relative.split("/")) - 1)
new_node["created_by"] = actor_user_id
new_node["updated_by"] = actor_user_id
new_node["created_at"] = timestamp
new_node["updated_at"] = timestamp
if not copy_permissions:
new_node["permission"] = copy.deepcopy(dest.get("permission") or {})
new_node["permission"]["inheritance"] = "inherited"
new_node["permission"]["inherited_from_node_id"] = destination_parent_node_id
if old.get("node_type") == "file":
content = _content(state_manager, old.get("content_ref"))
if content is not None:
new_content = copy.deepcopy(content)
content_id = _new_id(state_manager, "file_content", f"{_workspace_slug(workspace_id)}-{slugify(new_node['path'])}")
new_content.update({"content_id": content_id, "node_id": new_node_id, "created_at": timestamp, "updated_at": timestamp})
new_node["content_ref"] = content_id
state_manager.add_entity("file_content", new_content, id_field="content_id")
created_contents += 1
state_manager.add_entity("node", new_node)
created_nodes.append(new_node)
workspace_usage = _update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, id_map[source_node_id], "copy", source.get("path"), new_root_path)
return success_response({"source_node_id": source_node_id, "copied_root_node_id": id_map[source_node_id], "created_node_count": len(created_nodes), "created_content_count": created_contents, "bytes_copied": bytes_to_copy, "operation_id": operation_id}, "Node cloned")
def change_permissions(state_manager, workspace_id=None, node_id=None, actor_user_id=None, mode=None, inheritance=None, owner_team_id=None):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
if not _present(mode):
return error_response("MISSING_MODE", "mode is required")
if not _present(inheritance):
return error_response("MISSING_INHERITANCE", "inheritance is required")
if mode not in VALID_DIR_MODES:
return error_response("INVALID_MODE", "mode is invalid")
if inheritance not in VALID_INHERITANCE:
return error_response("INVALID_INHERITANCE", "inheritance is invalid")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Node was not found")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "Node is deleted")
if node.get("parent_node_id") is None and inheritance == "inherited":
return error_response("ROOT_INHERITANCE_CONFLICT", "Root nodes cannot inherit permissions")
if owner_team_id is not None:
team = state_manager.get_entity("team", owner_team_id)
if team is None or team.get("workspace_id") != workspace_id:
return error_response("TEAM_NOT_FOUND", "owner_team_id was not found in the workspace")
if not _can_admin(state_manager, node, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot change permissions on the node")
old_permission = copy.deepcopy(node.get("permission") or {})
new_permission = copy.deepcopy(old_permission)
new_permission["mode"] = mode
new_permission["inheritance"] = inheritance
new_permission["inherited_from_node_id"] = node.get("parent_node_id") if inheritance == "inherited" else None
if owner_team_id is not None:
new_permission["owner_team_id"] = owner_team_id
updated = copy.deepcopy(node)
updated.update({"permission": new_permission, "updated_by": actor_user_id, "updated_at": now_iso()})
state_manager.add_entity("node", updated)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "chmod", node.get("path"), None)
return success_response({"node_id": node_id, "old_permission": old_permission, "new_permission": new_permission, "effective_permission": _effective_permission(state_manager, updated), "operation_id": operation_id}, "Permissions changed")
def remove_node(state_manager, workspace_id=None, node_id=None, actor_user_id=None, recursive=False, expected_checksum=None):
if not _present(node_id):
return error_response("MISSING_NODE_ID", "node_id is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
node = _node(state_manager, node_id)
if node is None or node.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Node was not found")
if node.get("is_deleted"):
return error_response("NODE_DELETED", "Node is already deleted")
if node.get("parent_node_id") is None:
return error_response("ROOT_NODE_IMMUTABLE", "Workspace root cannot be deleted")
if not _can_admin(state_manager, node, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot delete the node")
descendants = [item for item in _subtree(state_manager, node_id) if item.get("node_id") != node_id]
if node.get("node_type") == "directory" and descendants and not recursive:
return error_response("DIRECTORY_NOT_EMPTY", "Directory has live descendants")
if expected_checksum is not None and node.get("node_type") == "file" and expected_checksum != node.get("checksum"):
return error_response("CHECKSUM_CONFLICT", "expected_checksum does not match the file checksum")
targets = [node] + descendants if recursive else [node]
timestamp = now_iso()
bytes_removed = 0
file_count = 0
for target in targets:
updated = copy.deepcopy(target)
if updated.get("is_deleted"):
continue
if updated.get("node_type") == "file":
bytes_removed += int(updated.get("size_bytes") or 0)
file_count += 1
updated.update({"is_deleted": True, "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("node", updated)
_update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node_id, "delete", node.get("path"), None)
return success_response({"node_id": node_id, "deleted_node_count": len(targets), "deleted_file_count": file_count, "bytes_removed": bytes_removed, "operation_id": operation_id}, "Node removed")
def archive_directory(state_manager, workspace_id=None, directory_id=None, actor_user_id=None, archive=True, include_locked_children=False):
if not _present(directory_id):
return error_response("MISSING_DIRECTORY_ID", "directory_id is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
directory = _node(state_manager, directory_id)
if directory is None or directory.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Directory was not found")
if directory.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Node is not a directory")
if directory.get("is_deleted"):
return error_response("NODE_DELETED", "Directory is deleted")
if actor_user_id not in _workspace_maintainers(state_manager, workspace_id):
return error_response("PERMISSION_DENIED", "Actor is not a workspace maintainer")
targets = _subtree(state_manager, directory_id)
restricted = [node for node in targets if (node.get("permission") or {}).get("mode") == "r--r-----"]
if restricted and not include_locked_children:
return error_response("LOCKED_CHILD_CONFLICT", "Restricted child nodes require include_locked_children")
requested = bool(archive)
changed = 0
skipped_deleted = len(_subtree(state_manager, directory_id, include_deleted=True)) - len(targets)
timestamp = now_iso()
for node in targets:
if bool(node.get("is_archived")) == requested:
continue
updated = copy.deepcopy(node)
updated.update({"is_archived": requested, "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("node", updated)
changed += 1
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, directory_id, "archive", directory.get("path"), None)
return success_response({"directory_id": directory_id, "archive": requested, "changed_node_count": changed, "skipped_deleted_count": skipped_deleted, "idempotent": changed == 0, "operation_id": operation_id}, "Directory archive state updated")
def apply_snapshot_restore(state_manager, workspace_id=None, snapshot_id=None, actor_user_id=None, restore_mode=None, conflict_policy="fail"):
if not _present(snapshot_id):
return error_response("MISSING_SNAPSHOT_ID", "snapshot_id is required")
if not _present(restore_mode):
return error_response("MISSING_RESTORE_MODE", "restore_mode is required")
if restore_mode not in {"preview", "merge", "replace"}:
return error_response("INVALID_RESTORE_MODE", "restore_mode is invalid")
if conflict_policy not in {"fail", "keep_current", "overwrite"}:
return error_response("INVALID_CONFLICT_POLICY", "conflict_policy is invalid")
if err := _require_workspace_id(workspace_id):
return err
workspace, err = _validate_workspace(state_manager, workspace_id, reject_maintenance=True, allow_locked=True)
if err:
return err
snapshot = state_manager.get_entity("snapshot", snapshot_id, id_field="snapshot_id")
if snapshot is None or snapshot.get("workspace_id") != workspace_id:
return error_response("SNAPSHOT_NOT_FOUND", "Snapshot was not found in the workspace")
if err := _require_actor_user_id(actor_user_id):
return err
actor, err = _validate_actor(state_manager, actor_user_id)
if err:
return err
if actor_user_id not in _workspace_maintainers(state_manager, workspace_id):
return error_response("PERMISSION_DENIED", "Actor is not a workspace maintainer")
if restore_mode == "replace" and workspace.get("status") == "locked":
return error_response("LOCKED_WORKSPACE_CONFLICT", "replace mode is not allowed for locked workspaces")
deleted = [node for node in _all(state_manager, "node") if node.get("workspace_id") == workspace_id and node.get("is_deleted")]
archived = [node for node in _all(state_manager, "node") if node.get("workspace_id") == workspace_id and node.get("is_archived") and not node.get("is_deleted")]
planned_changes = {"restore_deleted_nodes": min(len(deleted), 2), "unarchive_nodes": min(len(archived), 3)}
if restore_mode == "merge" and conflict_policy == "fail" and deleted:
return error_response("RESTORE_CONFLICT", "Deleted paths require an explicit conflict policy")
if restore_mode == "preview":
return success_response({"snapshot_id": snapshot_id, "restore_mode": restore_mode, "conflict_policy": conflict_policy, "planned_changes": planned_changes, "applied_changes": {"nodes": 0}, "preview_only": True}, "Snapshot restore preview built")
changed = 0
timestamp = now_iso()
targets = archived[:3] + (deleted[:2] if conflict_policy == "overwrite" or restore_mode == "replace" else [])
for node in targets:
updated = copy.deepcopy(node)
updated.update({"is_archived": False, "is_deleted": False, "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("node", updated)
changed += 1
_update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, snapshot.get("root_node_id"), "restore", snapshot.get("snapshot_id"), None)
return success_response({"snapshot_id": snapshot_id, "restore_mode": restore_mode, "conflict_policy": conflict_policy, "planned_changes": planned_changes, "applied_changes": {"nodes": changed}, "preview_only": False, "operation_id": operation_id}, "Snapshot restore applied")
def apply_permissions_batch(state_manager, workspace_id=None, node_ids=None, actor_user_id=None, mode=None, inheritance="explicit", continue_on_error=False):
if not node_ids:
return error_response("MISSING_NODE_IDS", "node_ids is required")
if not isinstance(node_ids, list) or len(node_ids) < 1 or len(node_ids) > 200 or len(set(node_ids)) != len(node_ids):
return error_response("INVALID_NODE_IDS", "node_ids must be a bounded unique array")
if not _present(mode):
return error_response("MISSING_MODE", "mode is required")
if mode not in VALID_DIR_MODES:
return error_response("INVALID_MODE", "mode is invalid")
if inheritance not in VALID_INHERITANCE:
return error_response("INVALID_INHERITANCE", "inheritance is invalid")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
results = []
changed = 0
timestamp = now_iso()
for node_id in node_ids:
node = _node(state_manager, node_id)
code = None
if node is None or node.get("workspace_id") != workspace_id:
code = "NODE_NOT_FOUND"
elif node.get("parent_node_id") is None and inheritance == "inherited":
code = "ROOT_INHERITANCE_CONFLICT"
elif not _can_admin(state_manager, node, actor_user_id):
code = "PERMISSION_DENIED"
if code:
if not continue_on_error:
return error_response(code, f"Batch permission failed for {node_id}")
results.append({"node_id": node_id, "status": "error", "error_code": code})
continue
permission = copy.deepcopy(node.get("permission") or {})
permission["mode"] = mode
permission["inheritance"] = inheritance
permission["inherited_from_node_id"] = node.get("parent_node_id") if inheritance == "inherited" else None
updated = copy.deepcopy(node)
updated.update({"permission": permission, "updated_by": actor_user_id, "updated_at": timestamp})
state_manager.add_entity("node", updated)
changed += 1
results.append({"node_id": node_id, "status": "success", "error_code": None})
if changed == 0:
return error_response("EMPTY_SELECTION", "No selected nodes could be updated")
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, results[0]["node_id"], "chmod", f"{changed} selected nodes", None)
return success_response({"changed_count": changed, "failed_count": len([item for item in results if item["status"] == "error"]), "results": results, "operation_id": operation_id}, "Permission batch applied")
def update_nodes_location_batch(state_manager, workspace_id=None, node_ids=None, destination_parent_node_id=None, actor_user_id=None, rename_conflicts=False, continue_on_error=False):
if not node_ids:
return error_response("MISSING_NODE_IDS", "node_ids is required")
if not _present(destination_parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "destination_parent_node_id is required")
if not isinstance(node_ids, list) or len(node_ids) < 1 or len(node_ids) > 100 or len(set(node_ids)) != len(node_ids):
return error_response("INVALID_NODE_IDS", "node_ids must be a bounded unique array")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
dest = _node(state_manager, destination_parent_node_id)
if dest is None or dest.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Destination was not found")
if dest.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Destination is not a directory")
if dest.get("is_deleted"):
return error_response("NODE_DELETED", "Destination is deleted")
if not _can_write(state_manager, dest, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot write to the destination")
results = []
moved = 0
renamed_conflicts = 0
for node_id in sorted(node_ids):
node = _node(state_manager, node_id)
code = None
if node is None or node.get("workspace_id") != workspace_id:
code = "NODE_NOT_FOUND"
elif node.get("is_deleted"):
code = "NODE_DELETED"
elif node.get("parent_node_id") is None:
code = "ROOT_NODE_IMMUTABLE"
elif node_id == destination_parent_node_id or _is_descendant(state_manager, node_id, destination_parent_node_id):
code = "MOVE_CYCLE_CONFLICT"
elif not _can_write(state_manager, _node(state_manager, node.get("parent_node_id")), actor_user_id):
code = "PERMISSION_DENIED"
name = node.get("name") if node else ""
if code is None and _sibling_conflict(state_manager, destination_parent_node_id, name, excluding_node_id=node_id):
if rename_conflicts:
name = f"{os.path.splitext(name)[0]} copy{os.path.splitext(name)[1]}"
renamed_conflicts += 1
else:
code = "PATH_CONFLICT"
if code:
if not continue_on_error:
return error_response(code, f"Batch move failed for {node_id}")
results.append({"node_id": node_id, "status": "error", "error_code": code})
continue
old_path = node.get("path")
new_path = f"{dest.get('path').rstrip('/')}/{name}"
updated = copy.deepcopy(node)
updated.update({"name": name, "parent_node_id": destination_parent_node_id, "path": new_path, "depth": int(dest.get("depth") or 0) + 1, "updated_by": actor_user_id, "updated_at": now_iso()})
state_manager.add_entity("node", updated)
_update_descendant_paths(state_manager, updated, old_path, new_path, actor_user_id, int(dest.get("depth") or 0) + 1 - int(node.get("depth") or 0))
moved += 1
results.append({"node_id": node_id, "status": "success", "old_path": old_path, "new_path": new_path, "error_code": None})
if moved == 0:
return error_response("EMPTY_SELECTION", "No selected nodes could be moved")
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, results[0]["node_id"], "move", f"{moved} selected nodes", dest.get("path"))
return success_response({"moved_count": moved, "failed_count": len([item for item in results if item["status"] == "error"]), "renamed_conflict_count": renamed_conflicts, "results": results, "operation_id": operation_id}, "Batch move applied")
def _render_manifest(manifest: Dict[str, Any], selected_nodes: List[Dict[str, Any]]) -> str:
lines = [
f"Manifest: {manifest.get('name')}",
f"Base path: {manifest.get('criteria', {}).get('base_path')}",
f"Extensions: {', '.join(manifest.get('criteria', {}).get('extensions') or [])}",
"",
]
for node in sorted(selected_nodes, key=lambda item: item.get("path", "")):
lines.append(f"- {node.get('path')} ({node.get('node_type')}, {node.get('size_bytes')} bytes)")
return "\n".join(lines)
def materialize_manifest(state_manager, workspace_id=None, manifest_id=None, destination_parent_node_id=None, actor_user_id=None, overwrite_existing=False):
if not _present(manifest_id):
return error_response("MISSING_MANIFEST_ID", "manifest_id is required")
if not _present(destination_parent_node_id):
return error_response("MISSING_PARENT_NODE_ID", "destination_parent_node_id is required")
workspace, actor, err = _base_write_precheck(state_manager, workspace_id, actor_user_id)
if err:
return err
manifest = state_manager.get_entity("manifest", manifest_id, id_field="manifest_id")
if manifest is None or manifest.get("workspace_id") != workspace_id:
return error_response("MANIFEST_NOT_FOUND", "Manifest was not found")
dest = _node(state_manager, destination_parent_node_id)
if dest is None or dest.get("workspace_id") != workspace_id:
return error_response("NODE_NOT_FOUND", "Destination was not found")
if dest.get("node_type") != "directory":
return error_response("NODE_NOT_DIRECTORY", "Destination is not a directory")
if dest.get("is_deleted"):
return error_response("NODE_DELETED", "Destination is deleted")
if not _can_write(state_manager, dest, actor_user_id):
return error_response("PERMISSION_DENIED", "Actor cannot write to destination")
selected_nodes = []
include_archived = bool((manifest.get("criteria") or {}).get("include_archived"))
for selected_id in manifest.get("selected_node_ids") or []:
node = _node(state_manager, selected_id)
if node is None or node.get("workspace_id") != workspace_id or node.get("is_deleted") or (node.get("is_archived") and not include_archived):
return error_response("MANIFEST_SELECTION_CONFLICT", "Manifest selected nodes are no longer materializable")
selected_nodes.append(node)
if manifest.get("status") == "materialized" and not overwrite_existing:
return error_response("IDEMPOTENCY_CONFLICT", "Manifest is already materialized")
text = _render_manifest(manifest, selected_nodes)
size = byte_len(text)
existing_node = _node(state_manager, manifest.get("materialized_node_id")) if manifest.get("materialized_node_id") else None
old_size = int(existing_node.get("size_bytes") or 0) if existing_node else 0
if _live_file_bytes(state_manager, workspace_id) - old_size + size > int(workspace.get("quota_bytes") or 0):
return error_response("QUOTA_EXCEEDED", "Generated index would exceed workspace quota")
timestamp = now_iso()
created = existing_node is None
file_name = f"{slugify(manifest.get('name'))}-index.md"
if existing_node is None:
node_id = _new_id(state_manager, "node", f"{_workspace_slug(workspace_id)}-{slugify(file_name)}")
content_id = _new_id(state_manager, "file_content", f"{_workspace_slug(workspace_id)}-{slugify(file_name)}")
node = {
"node_id": node_id,
"workspace_id": workspace_id,
"parent_node_id": destination_parent_node_id,
"name": file_name,
"node_type": "file",
"path": f"{dest.get('path').rstrip('/')}/{file_name}",
"extension": "md",
"mime_type": "text/markdown",
"size_bytes": size,
"content_ref": content_id,
"checksum": checksum_text(text),
"depth": int(dest.get("depth") or 0) + 1,
"is_deleted": False,
"is_archived": False,
"permission": copy.deepcopy(dest.get("permission") or {}),
"created_by": actor_user_id,
"updated_by": actor_user_id,
"created_at": timestamp,
"updated_at": timestamp,
}
content = {"content_id": content_id, "node_id": node_id, "encoding": "utf-8", "line_count": line_count(text), "text": text, "created_at": timestamp, "updated_at": timestamp}
else:
node = copy.deepcopy(existing_node)
content = _content(state_manager, node.get("content_ref"))
if content is None:
return error_response("CONTENT_NOT_FOUND", "Existing materialized file has no content row")
content = copy.deepcopy(content)
node.update({"size_bytes": size, "checksum": checksum_text(text), "updated_by": actor_user_id, "updated_at": timestamp})
content.update({"text": text, "line_count": line_count(text), "updated_at": timestamp})
state_manager.add_entity("node", node)
state_manager.add_entity("file_content", content, id_field="content_id")
updated_manifest = copy.deepcopy(manifest)
updated_manifest.update({"status": "materialized", "materialized_node_id": node.get("node_id"), "updated_at": timestamp})
state_manager.add_entity("manifest", updated_manifest, id_field="manifest_id")
workspace_usage = _update_workspace_usage(state_manager, workspace_id)
operation_id = _append_operation(state_manager, workspace_id, actor_user_id, node.get("node_id"), "create", manifest_id, node.get("path"))
return success_response({"manifest_id": manifest_id, "materialized_node_id": node.get("node_id"), "created": created, "overwritten": not created, "selected_node_count": len(selected_nodes), "generated_line_count": content.get("line_count"), "workspace_usage": {"used_bytes": workspace_usage.get("used_bytes"), "quota_bytes": workspace_usage.get("quota_bytes")}, "operation_id": operation_id}, "Manifest materialized")
"""Shared filesystem business logic for all public tools."""
from __future__ import annotations
import copy
import os
from typing import Any, Dict, List, Tuple
from mcp_servers.utils import (
byte_len,
checksum_text,
error_response,
line_count,
now_iso,
slugify,
success_response,
)
VALID_DIR_MODES = {"rwxr-x---", "rw-r-----", "rw-rw----", "r--r-----"}
VALID_FILE_MODES = {"rw-r-----", "rw-rw----", "r--r-----"}
VALID_INHERITANCE = {"explicit", "inherited"}
MIME_BY_EXTENSION = {
"md": "text/markdown",
"txt": "text/plain",
"json": "application/json",
"csv": "text/csv",
"yaml": "application/yaml",
}
def _present(value: Any) -> bool:
return value is not None and (not isinstance(value, str) or bool(value.strip()))
def _norm_bool(value: Any, default: bool = False) -> bool:
return default if value is None else bool(value)
def _workspace_slug(workspace_id: str) -> str:
return str(workspace_id).replace("workspace-", "", 1)
def _get(sm, entity: str, entity_id: str):
return sm.get_entity(entity, entity_id)
def _all(sm, entity: str):
return sm.list_entities(entity)
def _workspace(sm, workspace_id: str):
return _get(sm, "workspace", workspace_id)
def _user(sm, user_id: str):
return _get(sm, "user", user_id)
def _node(sm, node_id: str):
return _get(sm, "node", node_id)
def _content(sm, content_id: str):
return sm.get_entity("file_content", content_id, id_field="content_id")
def _teams_for_workspace(sm, workspace_id: str) -> List[Dict[str, Any]]:
return [team for team in _all(sm, "team") if team.get("workspace_id") == workspace_id]
def _workspace_maintainers(sm, workspace_id: str) -> set[str]:
maintainers: set[str] = set()
for team in _teams_for_workspace(sm, workspace_id):
maintainers.update(team.get("maintainer_user_ids") or [])
return maintainers
def _workspace_members(sm, workspace_id: str) -> set[str]:
members: set[str] = set()
for team in _teams_for_workspace(sm, workspace_id):
members.update(team.get("member_user_ids") or [])
members.update(team.get("maintainer_user_ids") or [])
return members
def _require_workspace_id(workspace_id):
if not _present(workspace_id):
return error_response("MISSING_WORKSPACE_ID", "workspace_id is required")
return None
def _require_actor_user_id(actor_user_id):
if not _present(actor_user_id):
return error_response("MISSING_ACTOR_USER_ID", "actor_user_id is required")
return None
def _validate_workspace(sm, workspace_id: str, *, require_active: bool = False, allow_locked: bool = False, reject_maintenance: bool = False):
workspace = _workspace(sm, workspace_id)