workspace-storage-guard 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ # Workspace Storage Guard
2
+
3
+ - `storage_guard.py` owns scanning, cleanup, and the CLI used by agent hooks and the macOS LaunchAgent.
4
+ - `mcp_server.py` exposes `storage_status`, `scan_storage`, and `restore_storage` over stdio and delegates to the CLI. Checkout-based MCP registrations, hooks, and the LaunchAgent use absolute script paths. Update those callers if you move either entry point.
5
+ - Keep setup and usage instructions in `docs/`, generic config and LaunchAgent templates in `examples/`, and tests in `tests/`.
6
+
7
+ ## Verify changes
8
+
9
+ From the repository root, run `python3 -m unittest -v`. Use the Python from the [MCP virtual environment](docs/setup.md#run-from-a-checkout) and have `lsof` and Cargo on `PATH` to exercise the full suite. Use `storage_status` to check the live MCP connection and temporary workspaces to test cleanup.
10
+
11
+ For packaging changes, run `uv build` and check the MCP handshake from the wheel with `uvx --from /path/to/wheel workspace-storage-guard`.
12
+
13
+ ## Cleanup and privacy
14
+
15
+ - Preserve the cleanup allowlists, Git and filesystem eligibility checks, active-build checks, and cleanup lock. Forced cleanup bypasses free-space thresholds and still enforces eligibility. Invoke it on the live workspace only when the user explicitly requests forced cleanup.
16
+ - Keep installed config, local paths, private project names, and credentials out of commits. Use generic fixtures and examples in this public repository.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chanwit Piromplad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include AGENTS.md docs/setup.md docs/usage.md
2
+ include examples/config.json examples/io.github.workspace-storage-guard.plist
3
+ include tests/__init__.py
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: workspace-storage-guard
3
+ Version: 0.1.0
4
+ Summary: Local MCP server for checking workspace storage and reclaiming generated files
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/TonPC64/workspace-storage-guard
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: mcp==2.3.0
11
+ Dynamic: license-file
12
+
13
+ # Workspace Storage Guard
14
+
15
+ Workspace Storage Guard is a local MCP server and command-line tool for software developers on macOS and Linux. It reports free space on your workspace volume, ranks directories by disk usage, and reclaims generated files you explicitly allowlist, including Cargo debug output, build caches, and `node_modules`.
16
+
17
+ ## Connect your agent
18
+
19
+ Install `uv`, then create a local config from `examples/config.json` and set your workspace, free-space thresholds, and cleanup allowlists. Register the server with Hermes Agent, Claude Code, GitHub Copilot CLI, or Codex. [Setup guide](docs/setup.md)
20
+
21
+ For example, register it in Codex using the GitHub release.
22
+
23
+ ```sh
24
+ codex mcp add workspace-storage-guard -- "$(command -v uvx)" \
25
+ --from git+https://github.com/TonPC64/workspace-storage-guard.git@v0.1.0 \
26
+ workspace-storage-guard
27
+ ```
28
+
29
+ Start a fresh agent session and ask it to call `storage_status`.
30
+
31
+ ## Check and reclaim space
32
+
33
+ - `storage_status` reports free space and your cleanup thresholds.
34
+ - `scan_storage` ranks the largest directories in your workspace.
35
+ - `restore_storage` reclaims eligible generated output when free space drops below your minimum. Pass `{"force": true}` to clean eligible output regardless of free space.
36
+
37
+ Your workspace path and allowlists live in a per-user local config. Scan results include local paths and may be shared with your agent’s model provider. [Usage guide](docs/usage.md)
38
+
39
+ ## Automate checks
40
+
41
+ Run Storage Guard from the terminal, add a hook to your agent, or schedule it with a macOS LaunchAgent. The example LaunchAgent runs at sign-in and every five minutes. [Hook and LaunchAgent setup](docs/setup.md#connect-agent-hooks)
@@ -0,0 +1,29 @@
1
+ # Workspace Storage Guard
2
+
3
+ Workspace Storage Guard is a local MCP server and command-line tool for software developers on macOS and Linux. It reports free space on your workspace volume, ranks directories by disk usage, and reclaims generated files you explicitly allowlist, including Cargo debug output, build caches, and `node_modules`.
4
+
5
+ ## Connect your agent
6
+
7
+ Install `uv`, then create a local config from `examples/config.json` and set your workspace, free-space thresholds, and cleanup allowlists. Register the server with Hermes Agent, Claude Code, GitHub Copilot CLI, or Codex. [Setup guide](docs/setup.md)
8
+
9
+ For example, register it in Codex using the GitHub release.
10
+
11
+ ```sh
12
+ codex mcp add workspace-storage-guard -- "$(command -v uvx)" \
13
+ --from git+https://github.com/TonPC64/workspace-storage-guard.git@v0.1.0 \
14
+ workspace-storage-guard
15
+ ```
16
+
17
+ Start a fresh agent session and ask it to call `storage_status`.
18
+
19
+ ## Check and reclaim space
20
+
21
+ - `storage_status` reports free space and your cleanup thresholds.
22
+ - `scan_storage` ranks the largest directories in your workspace.
23
+ - `restore_storage` reclaims eligible generated output when free space drops below your minimum. Pass `{"force": true}` to clean eligible output regardless of free space.
24
+
25
+ Your workspace path and allowlists live in a per-user local config. Scan results include local paths and may be shared with your agent’s model provider. [Usage guide](docs/usage.md)
26
+
27
+ ## Automate checks
28
+
29
+ Run Storage Guard from the terminal, add a hook to your agent, or schedule it with a macOS LaunchAgent. The example LaunchAgent runs at sign-in and every five minutes. [Hook and LaunchAgent setup](docs/setup.md#connect-agent-hooks)
@@ -0,0 +1,167 @@
1
+ # Set up Workspace Storage Guard
2
+
3
+ The CLI runs on macOS or Linux with Python 3.9+ and Git. For `disposable_paths` cleanup, install `lsof` and `find`. Cargo cleanup requires `pgrep` and a Cargo version that supports `cargo clean --profile dev` and `build.build-dir`. MCP requires Python 3.10+.
4
+
5
+ ## Create a local config
6
+
7
+ Clone the repository to a directory where you can keep it. Run the setup commands from that checkout.
8
+
9
+ ```sh
10
+ guard_config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/workspace-storage-guard"
11
+ guard_config="$guard_config_dir/config.json"
12
+ mkdir -p "$guard_config_dir"
13
+ if [ ! -e "$guard_config" ]; then
14
+ cp examples/config.json "$guard_config"
15
+ fi
16
+ ```
17
+
18
+ Edit the local `config.json`. Set `workspace` to the directory to scan. Set `min_free_gib` and `target_free_gib` to positive integers, with the target equal to or higher than the minimum. The minimum starts cleanup, and the target tells the guard when to stop trying new candidates.
19
+
20
+ Add exact paths relative to `workspace` to either cleanup allowlist. Each allowlist is optional.
21
+
22
+ - `cargo_projects` lists Cargo project directories whose `target/debug` trees you can rebuild. Set `cargo` to an absolute executable path if the scheduler or clients need a custom Cargo binary.
23
+ - `disposable_paths` lists directories you can recreate in full, such as Next.js `.next`, Swift `.build`, or `node_modules` in a project with a lockfile.
24
+
25
+ Verify that the guard reads your config and reports the volume's free space.
26
+
27
+ ```sh
28
+ python3 storage_guard.py --config "$guard_config" status
29
+ ```
30
+
31
+ ## Register the local MCP server
32
+
33
+ ### Run with uvx
34
+
35
+ Install [uv](https://docs.astral.sh/uv/getting-started/installation/) and create the local config above. Each client starts the server from the same GitHub release using `uvx`. Run the command for each client you use. In Hermes, enable all three tools when prompted.
36
+
37
+ ```sh
38
+ uvx_bin="$(command -v uvx)"
39
+ guard_source='git+https://github.com/TonPC64/workspace-storage-guard.git@v0.1.0'
40
+ guard_config="${XDG_CONFIG_HOME:-$HOME/.config}/workspace-storage-guard/config.json"
41
+
42
+ hermes mcp add workspace-storage-guard --command "$uvx_bin" --args --from "$guard_source" workspace-storage-guard --config "$guard_config"
43
+ claude mcp add --scope user --transport stdio workspace-storage-guard -- "$uvx_bin" --from "$guard_source" workspace-storage-guard --config "$guard_config"
44
+ copilot mcp add --timeout 300000 workspace-storage-guard -- "$uvx_bin" --from "$guard_source" workspace-storage-guard --config "$guard_config"
45
+ codex mcp add workspace-storage-guard -- "$uvx_bin" --from "$guard_source" workspace-storage-guard --config "$guard_config"
46
+ ```
47
+
48
+ If the server is already registered, update its command and arguments in the client settings. The first launch needs access to GitHub and PyPI to install the server and its dependencies. Hooks and the LaunchAgent use `storage_guard.py` from a checkout.
49
+
50
+ ### Run from a checkout
51
+
52
+ Install the MCP dependency in a virtual environment. Run these commands from the repository root.
53
+
54
+ ```sh
55
+ mcp_venv="$HOME/.local/share/workspace-storage-guard/mcp-venv"
56
+ python3 -m venv "$mcp_venv"
57
+ mcp_python="$mcp_venv/bin/python"
58
+ "$mcp_python" -m pip install -r requirements-mcp.txt
59
+ mcp_server="$PWD/mcp_server.py"
60
+ guard_config="${XDG_CONFIG_HOME:-$HOME/.config}/workspace-storage-guard/config.json"
61
+ ```
62
+
63
+ Run the command for each client you use. In Hermes, enable all three tools when prompted.
64
+
65
+ ```sh
66
+ hermes mcp add workspace-storage-guard --command "$mcp_python" --args "$mcp_server" --config "$guard_config"
67
+ claude mcp add --scope user --transport stdio workspace-storage-guard -- "$mcp_python" "$mcp_server" --config "$guard_config"
68
+ copilot mcp add --timeout 300000 workspace-storage-guard -- "$mcp_python" "$mcp_server" --config "$guard_config"
69
+ codex mcp add workspace-storage-guard -- "$mcp_python" "$mcp_server" --config "$guard_config"
70
+ ```
71
+
72
+ Keep the checkout and virtual environment at the registered paths.
73
+
74
+ ### Verify the connection
75
+
76
+ For Codex, add `tool_timeout_sec = 300` under the generated `[mcp_servers.workspace-storage-guard]` section in your Codex config.
77
+
78
+ Start a fresh agent session and ask the agent to call `storage_status` on `workspace-storage-guard`. Look for the free-space reading and thresholds from the CLI status check. Each client launches its MCP server over stdio.
79
+
80
+ ## Connect agent hooks
81
+
82
+ Replace `/absolute/path/to/python3` and `/absolute/path/to/storage_guard.py` with your actual paths. Quote each path in the command if it contains spaces. Add `--config /absolute/path/to/config.json` before `hook` if the agent runs with a different config home. Merge the entries into existing settings and retain any current hooks.
83
+
84
+ ### Hermes Agent
85
+
86
+ Add the following to `~/.hermes/config.yaml`. Launch Hermes interactively and approve the displayed command. Run `hermes hooks test pre_tool_call --for-tool terminal` to exercise the hook.
87
+
88
+ ```yaml
89
+ hooks:
90
+ pre_tool_call:
91
+ - command: '/absolute/path/to/python3 /absolute/path/to/storage_guard.py hook hermes'
92
+ timeout: 300
93
+ fail_closed: true
94
+ ```
95
+
96
+ ### Claude Code
97
+
98
+ Merge into `~/.claude/settings.json` and start a fresh session. [Claude Code hooks](https://code.claude.com/docs/en/hooks)
99
+
100
+ ```json
101
+ {
102
+ "hooks": {
103
+ "PreToolUse": [{
104
+ "hooks": [{"type": "command", "command": "/absolute/path/to/python3 /absolute/path/to/storage_guard.py hook claude", "timeout": 300}]
105
+ }]
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### GitHub Copilot CLI
111
+
112
+ Save as `~/.copilot/hooks/workspace-storage-guard.json` and start a fresh session. Run `copilot help hooks` to check the hook format for your version.
113
+
114
+ ```json
115
+ {
116
+ "version": 1,
117
+ "hooks": {
118
+ "preToolUse": [{"type": "command", "bash": "/absolute/path/to/python3 /absolute/path/to/storage_guard.py hook copilot", "timeoutSec": 300}]
119
+ }
120
+ }
121
+ ```
122
+
123
+ ### Codex
124
+
125
+ Merge into `~/.codex/hooks.json`. In a new Codex session, open `/hooks`, review the command, and trust it. Codex dispatches `PreToolUse` for supported calls such as shell execution and `apply_patch`. [Codex hooks](https://learn.chatgpt.com/docs/hooks)
126
+
127
+ ```json
128
+ {
129
+ "hooks": {
130
+ "PreToolUse": [{
131
+ "hooks": [{"type": "command", "command": "/absolute/path/to/python3 /absolute/path/to/storage_guard.py hook codex", "timeout": 300}]
132
+ }]
133
+ }
134
+ }
135
+ ```
136
+
137
+ ## Schedule background checks on macOS
138
+
139
+ Copy the example [LaunchAgent plist](../examples/io.github.workspace-storage-guard.plist) into `~/Library/LaunchAgents`. If you already installed the LaunchAgent, edit your installed copy.
140
+
141
+ ```sh
142
+ guard_plist="$HOME/Library/LaunchAgents/io.github.workspace-storage-guard.plist"
143
+ mkdir -p "$HOME/Library/LaunchAgents"
144
+ if [ ! -e "$guard_plist" ]; then
145
+ cp examples/io.github.workspace-storage-guard.plist "$guard_plist"
146
+ fi
147
+ ```
148
+
149
+ Edit the installed plist and replace the Python and script paths with absolute paths. If your config lives outside the default location, add `--config` and the absolute config path as two items before `background` in `ProgramArguments`.
150
+
151
+ Validate and load the LaunchAgent from your macOS login session. To reload an existing job after editing the plist, run `launchctl bootout "gui/$(id -u)/io.github.workspace-storage-guard"` before `bootstrap`.
152
+
153
+ ```sh
154
+ plutil -lint "$guard_plist"
155
+ launchctl bootstrap "gui/$(id -u)" "$guard_plist"
156
+ launchctl print "gui/$(id -u)/io.github.workspace-storage-guard"
157
+ ```
158
+
159
+ The sample runs at sign-in and every five minutes while you are signed in. The `background` command skips a run when another guard holds the cleanup lock. On Linux, schedule `python3 /absolute/path/to/storage_guard.py background` with your user scheduler.
160
+
161
+ ## Uninstall
162
+
163
+ Remove the MCP server entry and guard hook from each client you configured. On macOS, unload the LaunchAgent before deleting its plist.
164
+
165
+ ```sh
166
+ launchctl bootout "gui/$(id -u)/io.github.workspace-storage-guard"
167
+ ```
@@ -0,0 +1,45 @@
1
+ # Use Workspace Storage Guard
2
+
3
+ Follow the [setup guide](setup.md) to configure the guard and register the MCP server.
4
+
5
+ ## Check free space
6
+
7
+ In Hermes Agent, Claude Code, GitHub Copilot CLI, or Codex, ask the agent to call `storage_status` on `workspace-storage-guard`. It reports free space on the volume that holds your workspace, the threshold that starts cleanup, and the cleanup target.
8
+
9
+ From the repository root, run the equivalent terminal command.
10
+
11
+ ```sh
12
+ python3 storage_guard.py status
13
+ ```
14
+
15
+ ## Find large directories
16
+
17
+ Ask the agent to run `scan_storage`. The tool reports up to 20 directories, ranked by disk usage, at most two levels below the workspace root. Totals include descendants. The output includes local paths, which your client may include in its history or send to its model provider. Use the terminal command to view those paths locally.
18
+
19
+ ```sh
20
+ python3 storage_guard.py scan
21
+ ```
22
+
23
+ ## Reclaim storage
24
+
25
+ Ask the agent to run `restore_storage` on `workspace-storage-guard`. When free space is below `min_free_gib`, the guard tries the Cargo allowlist first and then `disposable_paths`. It stops when it reaches `target_free_gib` or runs out of candidates. The terminal command is `python3 storage_guard.py guard`.
26
+
27
+ Before forcing cleanup, review your allowlists. The guard can remove every eligible directory on them, so you may need to rebuild outputs or reinstall dependencies afterward. Ask the agent to call `restore_storage` with `{"force": true}` to clean up regardless of free space.
28
+
29
+ ```sh
30
+ python3 storage_guard.py guard --force
31
+ ```
32
+
33
+ Forced cleanup still uses the cleanup lock and the same eligibility checks. Scheduled runs and hooks use the configured thresholds. If the guard hook blocks regular agent calls because the volume is still below the minimum, use the three MCP storage tools to inspect or reclaim space.
34
+
35
+ ## Check why a directory was skipped
36
+
37
+ - Check that the directory is on an allowlist and on the workspace volume. Cleanup requires a Git-ignored directory with zero tracked files inside and a path free of symlinks.
38
+ - For Cargo cleanup, check for a Cargo manifest and cache marker. Let running Cargo, `rustc`, and `rustdoc` processes finish. Cargo cleanup targets `target/debug` and preserves release, documentation, and cross-compiled outputs.
39
+ - For `disposable_paths`, wait until the directory and its contents have gone 24 hours without changes. The guard skips directories with nested Git metadata or a process owned by you whose working directory is inside the checkout. To clean a listed checkout, leave that checkout in your shells and agent sessions before retrying. Use the absolute script path if you run the CLI from elsewhere.
40
+
41
+ A process can reopen generated files after the guard checks them or use them from another directory. Add directories to your allowlist only if you can recreate their entire contents.
42
+
43
+ ## Check the MCP connection
44
+
45
+ Start a fresh session after adding the server. In Hermes, run `hermes mcp test workspace-storage-guard`. In Claude Code, run `claude mcp get workspace-storage-guard` and look for **Connected**. In Copilot CLI, run `/mcp get workspace-storage-guard` inside the session to see the live state. In Codex, run `codex mcp get workspace-storage-guard` to check the saved entry, then ask the agent to call `storage_status`.
@@ -0,0 +1,7 @@
1
+ {
2
+ "workspace": "~/workspace",
3
+ "min_free_gib": 40,
4
+ "target_free_gib": 60,
5
+ "cargo_projects": ["my-rust-project"],
6
+ "disposable_paths": ["my-web-app/.next", "my-web-app/node_modules", "my-swift-project/.build"]
7
+ }
@@ -0,0 +1,18 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>Label</key>
6
+ <string>io.github.workspace-storage-guard</string>
7
+ <key>ProgramArguments</key>
8
+ <array>
9
+ <string>/absolute/path/to/python3</string>
10
+ <string>/absolute/path/to/storage_guard.py</string>
11
+ <string>background</string>
12
+ </array>
13
+ <key>RunAtLoad</key>
14
+ <true/>
15
+ <key>StartInterval</key>
16
+ <integer>300</integer>
17
+ </dict>
18
+ </plist>
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env python3
2
+ """Serve Workspace Storage Guard tools over local MCP stdio."""
3
+
4
+ import argparse
5
+ import asyncio
6
+ from contextlib import suppress
7
+ import os
8
+ from pathlib import Path
9
+ import signal
10
+ import subprocess
11
+ import sys
12
+
13
+ from mcp.server.lowlevel import Server
14
+ from mcp.server.stdio import stdio_server
15
+ from mcp_types import CallToolResult, ListToolsResult, TextContent, Tool, ToolAnnotations
16
+
17
+ from storage_guard import DEFAULT_CONFIG, MCP_SERVER, MCP_TOOLS
18
+
19
+
20
+ GUARD = Path(__file__).resolve().with_name("storage_guard.py")
21
+ TOOL_DESCRIPTIONS = {
22
+ "storage_status": "Report free space and cleanup thresholds for the workspace volume.",
23
+ "scan_storage": "Report the largest workspace directories, including their local paths.",
24
+ "restore_storage": "Clean configured generated files if space is low. Set force to true "
25
+ "only when the user explicitly requests cleanup regardless of free space.",
26
+ }
27
+
28
+
29
+ def run_guard(config, mode, force):
30
+ command = [sys.executable, str(GUARD), "--config", str(config), mode]
31
+ if force:
32
+ command.append("--force")
33
+ with subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
34
+ text=True, errors="replace", start_new_session=True) as process:
35
+ try:
36
+ stdout, stderr = process.communicate(timeout=285)
37
+ except subprocess.TimeoutExpired:
38
+ # Stop child commands such as du as well as the guard.
39
+ with suppress(ProcessLookupError):
40
+ os.killpg(process.pid, signal.SIGKILL)
41
+ process.communicate()
42
+ raise
43
+ if process.returncode:
44
+ return stderr.strip() or f"Storage guard exited with status {process.returncode}.", True
45
+ return stdout.strip() or "Free space meets the minimum. Cleanup skipped.", False
46
+
47
+
48
+ async def serve(config):
49
+ async def list_tools(_context, _params):
50
+ return ListToolsResult(tools=[
51
+ Tool(
52
+ name=name, description=TOOL_DESCRIPTIONS[name],
53
+ input_schema={
54
+ "type": "object", "additionalProperties": False,
55
+ "properties": {"force": {"type": "boolean", "default": False}} if mode == "guard" else {},
56
+ },
57
+ annotations=ToolAnnotations(read_only_hint=mode != "guard", destructive_hint=mode == "guard",
58
+ open_world_hint=False),
59
+ ) for name, mode in MCP_TOOLS.items()
60
+ ])
61
+
62
+ async def call_tool(_context, params):
63
+ args = params.arguments or {}
64
+ force = args.get("force", False)
65
+ if params.name not in MCP_TOOLS:
66
+ message, error = "Unknown storage tool.", True
67
+ elif args and (params.name != "restore_storage" or set(args) != {"force"} or type(force) is not bool):
68
+ message, error = "Only restore_storage accepts an argument, the boolean force.", True
69
+ else:
70
+ try:
71
+ message, error = await asyncio.to_thread(run_guard, config, MCP_TOOLS[params.name], force)
72
+ except subprocess.TimeoutExpired:
73
+ message, error = "Storage operation timed out. Check free space before retrying.", True
74
+ except OSError as exc:
75
+ message, error = f"Workspace storage guard: {exc}", True
76
+ return CallToolResult(content=[TextContent(type="text", text=message)], is_error=error)
77
+
78
+ server = Server(MCP_SERVER, on_list_tools=list_tools, on_call_tool=call_tool)
79
+ async with stdio_server() as (read_stream, write_stream):
80
+ await server.run(read_stream, write_stream, server.create_initialization_options())
81
+
82
+
83
+ def main():
84
+ parser = argparse.ArgumentParser(description=__doc__)
85
+ parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
86
+ config = parser.parse_args().config.expanduser().absolute()
87
+ os.chdir("/") # Starting in a Git checkout would make the guard treat it as in use.
88
+ asyncio.run(serve(config))
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "workspace-storage-guard"
7
+ version = "0.1.0"
8
+ description = "Local MCP server for checking workspace storage and reclaiming generated files"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ dynamic = ["dependencies"]
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/TonPC64/workspace-storage-guard"
16
+
17
+ [project.scripts]
18
+ workspace-storage-guard = "mcp_server:main"
19
+
20
+ [tool.setuptools]
21
+ py-modules = ["storage_guard", "mcp_server"]
22
+
23
+ [tool.setuptools.dynamic]
24
+ dependencies = {file = ["requirements-mcp.txt"]}
@@ -0,0 +1 @@
1
+ mcp==2.3.0
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env python3
2
+ """Scan workspace storage and reclaim allowlisted generated output when disk space is low."""
3
+
4
+ import argparse
5
+ import fcntl
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import time
13
+
14
+
15
+ GIB = 1024 ** 3
16
+ RECOVERY_TIMEOUT = 240
17
+ DEFAULT_CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / (
18
+ "workspace-storage-guard/config.json"
19
+ )
20
+ MCP_SERVER = "workspace-storage-guard"
21
+ MCP_TOOLS = {
22
+ "storage_status": "status",
23
+ "scan_storage": "scan",
24
+ "restore_storage": "guard",
25
+ }
26
+
27
+
28
+ class GuardError(Exception):
29
+ pass
30
+
31
+
32
+ def relative_paths(data, key):
33
+ entries = data.get(key, [])
34
+ if not isinstance(entries, list) or any(not isinstance(entry, str) or not entry for entry in entries):
35
+ raise GuardError(f"List {key} in a JSON array of paths.")
36
+ paths = [Path(entry) for entry in entries]
37
+ for path in paths:
38
+ if path.is_absolute() or any(part.casefold() in ("..", ".git") for part in path.parts):
39
+ raise GuardError(f"Use workspace-relative paths outside Git metadata in {key}.")
40
+ return paths
41
+
42
+
43
+ def read_config(path):
44
+ data = json.loads(path.read_text())
45
+ workspace = Path(data["workspace"]).expanduser().resolve(strict=True)
46
+ minimum = data["min_free_gib"]
47
+ target = data["target_free_gib"]
48
+ projects = relative_paths(data, "cargo_projects")
49
+ generated = relative_paths(data, "disposable_paths")
50
+ if not workspace.is_dir() or type(minimum) is not int or type(target) is not int:
51
+ raise GuardError("Use a workspace directory and integer GiB thresholds.")
52
+ if not 0 < minimum <= target:
53
+ raise GuardError("Set thresholds such that 0 < min_free_gib <= target_free_gib.")
54
+ for directory in generated:
55
+ if not directory.parts:
56
+ raise GuardError("disposable_paths cannot include the workspace root.")
57
+ parts = tuple(part.casefold() for part in directory.parts)
58
+ for project in projects:
59
+ cargo_target = tuple(part.casefold() for part in (project / "target").parts)
60
+ common = min(len(parts), len(cargo_target))
61
+ if parts[:common] == cargo_target[:common]:
62
+ raise GuardError(f"disposable_paths overlaps a Cargo target: {directory}")
63
+ cargo = Path(data["cargo"]).expanduser() if "cargo" in data else None
64
+ if cargo is not None and not cargo.is_absolute():
65
+ raise GuardError("Set cargo to an absolute executable path.")
66
+ return workspace, minimum * GIB, target * GIB, projects, cargo, generated
67
+
68
+
69
+ def free_bytes(workspace):
70
+ volume = os.statvfs(workspace)
71
+ return volume.f_bavail * volume.f_frsize
72
+
73
+
74
+ def cargo_busy():
75
+ result = subprocess.run(
76
+ ["pgrep", "-x", "cargo|rustc|rustdoc"], stdout=subprocess.DEVNULL, timeout=5
77
+ )
78
+ if result.returncode not in (0, 1):
79
+ raise GuardError("Could not check for running Cargo or Rust compiler processes.")
80
+ return result.returncode == 0
81
+
82
+
83
+ def disposable_worktree(directory, filesystem):
84
+ if not directory.is_dir() or directory.resolve() != directory or directory.stat().st_dev != filesystem:
85
+ return None
86
+ git = ["git", "--no-optional-locks"]
87
+ env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
88
+ ignored = subprocess.run(
89
+ [*git, "check-ignore", "-q", "--", f"./{directory.name}/"],
90
+ cwd=directory.parent, env=env, stderr=subprocess.DEVNULL, timeout=5,
91
+ )
92
+ if ignored.returncode != 0:
93
+ return None
94
+ tracked = subprocess.check_output(
95
+ [*git, "ls-files", "-z", "--", f":(icase,literal){directory.name}"],
96
+ cwd=directory.parent, env=env, timeout=5,
97
+ )
98
+ if tracked:
99
+ return None
100
+ root = subprocess.check_output(
101
+ [*git, "rev-parse", "--show-toplevel"], cwd=directory.parent, env=env, timeout=5,
102
+ )
103
+ return Path(os.fsdecode(root.removesuffix(b"\n"))).resolve()
104
+
105
+
106
+ def eligible(project, filesystem):
107
+ if disposable_worktree(project / "target/debug", filesystem) is None:
108
+ return False
109
+ manifest = project / "Cargo.toml"
110
+ tag = project / "target/CACHEDIR.TAG"
111
+ if not manifest.is_file() or manifest.is_symlink() or not tag.is_file() or tag.is_symlink():
112
+ return False
113
+ with tag.open("rb") as file:
114
+ return file.readline(64).rstrip() == b"Signature: 8a477f597d28d172789f06886806bc55"
115
+
116
+
117
+ def scan(workspace):
118
+ output = subprocess.check_output(["du", "-kx", "-d", "2", str(workspace)], text=True)
119
+ sizes = []
120
+ for line in output.splitlines():
121
+ blocks, separator, path = line.partition("\t")
122
+ if separator and blocks.isdecimal():
123
+ sizes.append((int(blocks), path))
124
+ return "\n".join(f"{blocks / 1024 ** 2:8.2f} GiB {path}"
125
+ for blocks, path in sorted(sizes, reverse=True)[:20])
126
+
127
+
128
+ def clean_generated(directory, filesystem, deadline):
129
+ root = disposable_worktree(directory, filesystem)
130
+ if root is None:
131
+ return
132
+ cwd_fields = subprocess.check_output(
133
+ ["lsof", "-a", "-u", str(os.getuid()), "-d", "cwd", "-F0n"], timeout=5,
134
+ ).split(b"\0")
135
+ for field in cwd_fields:
136
+ field = field.lstrip(b"\n")
137
+ if field.startswith(b"n/") and Path(os.fsdecode(field[1:])).is_relative_to(root):
138
+ raise GuardError("A process is working in this Git checkout.")
139
+ find = ["find", "-P", str(directory), "-xdev"]
140
+ keep = subprocess.check_output(
141
+ [*find, "(", "-iname", ".git", "-o", "-mmin", "-1440", ")", "-print", "-quit"],
142
+ timeout=max(0, deadline - time.monotonic()),
143
+ )
144
+ if keep:
145
+ raise GuardError("Contains Git metadata or files modified in the past 24 hours.")
146
+ # shortcut: an independent process can reopen this cache after the check, coordinate if needed.
147
+ subprocess.run([*find, "-depth", "-delete"], check=True, capture_output=True, text=True,
148
+ timeout=max(0, deadline - time.monotonic()))
149
+
150
+
151
+ def recover(path, workspace, minimum, target, projects, cargo, background, generated=(), *, force=False):
152
+ if background and free_bytes(workspace) >= minimum:
153
+ return ""
154
+
155
+ deadline = time.monotonic() + RECOVERY_TIMEOUT
156
+ lock = path.with_name("cleanup.lock")
157
+ fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
158
+ with os.fdopen(fd, "r+b") as file:
159
+ while True:
160
+ try:
161
+ fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
162
+ break
163
+ except BlockingIOError:
164
+ if background:
165
+ return ""
166
+ if time.monotonic() >= deadline:
167
+ raise GuardError("Another storage cleanup is still running. Retry shortly.")
168
+ time.sleep(0.25)
169
+
170
+ before = free_bytes(workspace)
171
+ if not force and before >= minimum:
172
+ return ""
173
+ failures = []
174
+ filesystem = workspace.stat().st_dev
175
+ for relative in projects:
176
+ project = workspace / relative
177
+ if not force and free_bytes(workspace) >= target:
178
+ break
179
+ if time.monotonic() >= deadline:
180
+ failures.append("Cleanup reached its time limit. Retry to continue.")
181
+ break
182
+ try:
183
+ if not eligible(project, filesystem):
184
+ continue
185
+ executable = str(cargo) if cargo else shutil.which("cargo")
186
+ if executable is None or not os.access(executable, os.X_OK):
187
+ failures.append("Cargo is unavailable. Set its executable path in the guard config.")
188
+ break
189
+ cargo_env = dict(os.environ, PATH=os.pathsep.join([
190
+ str(Path(executable).parent), *os.get_exec_path()
191
+ ]))
192
+ # shortcut: external builds can start after pgrep, coordinate builds if this becomes frequent.
193
+ if cargo_busy():
194
+ failures.append("A Cargo or Rust compiler process is running. Retry when it finishes.")
195
+ break
196
+ remaining = deadline - time.monotonic()
197
+ if remaining <= 0:
198
+ failures.append("Cleanup reached its time limit. Retry to continue.")
199
+ break
200
+ subprocess.run(
201
+ [executable, "clean", "--frozen", "--profile", "dev",
202
+ "--target-dir", str(project / "target"), "--config",
203
+ f"build.build-dir={json.dumps(str(project / 'target'), ensure_ascii=False)}"],
204
+ cwd=project, env=cargo_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
205
+ check=True, text=True, timeout=remaining,
206
+ )
207
+ except subprocess.CalledProcessError as error:
208
+ details = (error.stderr or str(error)).strip()[-400:]
209
+ failures.append(f"{relative}: {details}")
210
+ except (OSError, subprocess.SubprocessError) as error:
211
+ failures.append(f"{relative}: {error}")
212
+
213
+ for relative in generated:
214
+ if not force and free_bytes(workspace) >= target:
215
+ break
216
+ if time.monotonic() >= deadline:
217
+ failures.append("Cleanup reached its time limit. Retry to continue.")
218
+ break
219
+ try:
220
+ clean_generated(workspace / relative, filesystem, deadline)
221
+ except subprocess.CalledProcessError as error:
222
+ details = (error.stderr or str(error)).strip()[-400:]
223
+ failures.append(f"{relative}: {details}")
224
+ except (GuardError, OSError, subprocess.SubprocessError) as error:
225
+ failures.append(f"{relative}: {error}")
226
+
227
+ after = free_bytes(workspace)
228
+ if after < minimum:
229
+ details = " ".join(failures) or "Run storage_guard.py scan to review workspace usage."
230
+ raise GuardError(
231
+ f"{after / GIB:.1f} GiB free, below the {minimum // GIB} GiB minimum. {details}"
232
+ )
233
+ summary = f"Free space was {before / GIB:.1f} GiB before cleanup and {after / GIB:.1f} GiB afterward."
234
+ return " ".join([summary, *failures])
235
+
236
+
237
+ def reply(mode, client, error, message):
238
+ if mode == "hook":
239
+ if error and client == "copilot":
240
+ print(json.dumps({"permissionDecision": "deny", "permissionDecisionReason": message}))
241
+ return 0
242
+ if error:
243
+ print(message, file=sys.stderr)
244
+ return 2
245
+ return 0
246
+ if message:
247
+ print(message, file=sys.stderr if error else sys.stdout)
248
+ return 2 if error else 0
249
+
250
+
251
+ def storage_tool_call(client):
252
+ if sys.stdin.isatty():
253
+ return False
254
+ try:
255
+ event = json.load(sys.stdin)
256
+ except (ValueError, OSError, RecursionError):
257
+ return False
258
+ key = "toolName" if client == "copilot" else "tool_name"
259
+ name = event.get(key) if isinstance(event, dict) else None
260
+ if not isinstance(name, str):
261
+ return False
262
+ if client == "copilot":
263
+ server, _, tool = name.rpartition("-")
264
+ return server == MCP_SERVER and tool in MCP_TOOLS
265
+ server, _, tool = name.rpartition("__")
266
+ return tool in MCP_TOOLS and server in (f"mcp__{MCP_SERVER}", f"mcp__{MCP_SERVER.replace('-', '_')}")
267
+
268
+
269
+ def main():
270
+ parser = argparse.ArgumentParser(description=__doc__)
271
+ parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
272
+ commands = parser.add_subparsers(dest="mode", required=True)
273
+ for mode in ("status", "scan", "background"):
274
+ commands.add_parser(mode)
275
+ manual = commands.add_parser("guard")
276
+ manual.add_argument("--force", action="store_true", help="clean all eligible paths regardless of free space")
277
+ hook = commands.add_parser("hook")
278
+ hook.add_argument("client", choices=("claude", "codex", "copilot", "hermes"))
279
+ args = parser.parse_args()
280
+ client = getattr(args, "client", None)
281
+ if args.mode == "hook" and storage_tool_call(client):
282
+ return 0
283
+ try:
284
+ workspace, minimum, target, projects, cargo, generated = read_config(args.config)
285
+ if args.mode == "status":
286
+ message = (
287
+ f"{free_bytes(workspace) / GIB:.1f} GiB free. "
288
+ f"Cleanup starts below {minimum // GIB} GiB and aims for {target // GIB} GiB."
289
+ )
290
+ elif args.mode == "scan":
291
+ message = f"{free_bytes(workspace) / GIB:.1f} GiB free on the workspace volume.\n{scan(workspace)}"
292
+ else:
293
+ message = recover(
294
+ args.config, workspace, minimum, target, projects, cargo, args.mode == "background", generated,
295
+ force=getattr(args, "force", False),
296
+ )
297
+ except (GuardError, KeyError, OSError, TypeError, ValueError, subprocess.SubprocessError) as err:
298
+ return reply(args.mode, client, True, f"Workspace storage guard: {err}")
299
+ return reply(args.mode, client, False, message)
300
+
301
+
302
+ if __name__ == "__main__":
303
+ sys.exit(main())
File without changes
@@ -0,0 +1,66 @@
1
+ from importlib.util import find_spec
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ import unittest
11
+
12
+ from storage_guard import GIB, free_bytes
13
+
14
+
15
+ @unittest.skipUnless(find_spec("mcp_types") and shutil.which("lsof"), "MCP requirements and lsof required")
16
+ class StorageGuardMCPTest(unittest.IsolatedAsyncioTestCase):
17
+ async def test_stdio_tools_use_the_configured_workspace(self):
18
+ from mcp import ClientSession, StdioServerParameters
19
+ from mcp.client.stdio import stdio_client
20
+
21
+ with tempfile.TemporaryDirectory() as directory:
22
+ workspace = Path(directory).resolve()
23
+ if free_bytes(workspace) < GIB:
24
+ self.skipTest("Test needs 1 GiB free on the temporary volume")
25
+ subprocess.run(["git", "init", "-q", str(workspace)], check=True)
26
+ (workspace / ".gitignore").write_text("/.cache/\n")
27
+ cache = workspace / ".cache"
28
+ cache.mkdir()
29
+ old = time.time() - 2 * 86400
30
+ os.utime(cache, (old, old))
31
+ config = workspace / "config.json"
32
+ config.write_text(json.dumps({
33
+ "workspace": str(workspace), "min_free_gib": 1, "target_free_gib": 1,
34
+ "disposable_paths": [".cache"],
35
+ }))
36
+ server = StdioServerParameters(command=sys.executable, args=[
37
+ str(Path(__file__).resolve().parents[1] / "mcp_server.py"), "--config", str(config),
38
+ ], cwd=str(workspace))
39
+ async with stdio_client(server) as (read, write), ClientSession(read, write, 20) as session:
40
+ await session.initialize()
41
+ tools = {tool.name: tool for tool in (await session.list_tools()).tools}
42
+ self.assertEqual(set(tools), {"storage_status", "scan_storage", "restore_storage"})
43
+ self.assertTrue(tools["storage_status"].annotations.read_only_hint)
44
+ self.assertTrue(tools["scan_storage"].annotations.read_only_hint)
45
+ self.assertTrue(tools["restore_storage"].annotations.destructive_hint)
46
+
47
+ status = await session.call_tool("storage_status")
48
+ self.assertFalse(status.is_error)
49
+ self.assertIn("Cleanup starts below 1 GiB", status.content[0].text)
50
+ scan = await session.call_tool("scan_storage")
51
+ self.assertFalse(scan.is_error)
52
+ self.assertIn(str(cache), scan.content[0].text)
53
+ for args in ({"force": "true"}, {"force": True, "path": "/"}):
54
+ self.assertTrue((await session.call_tool("restore_storage", args)).is_error)
55
+ self.assertTrue(cache.exists())
56
+
57
+ skipped = await session.call_tool("restore_storage")
58
+ self.assertFalse(skipped.is_error)
59
+ self.assertIn("Cleanup skipped", skipped.content[0].text)
60
+ self.assertTrue(cache.exists())
61
+ restored = await session.call_tool("restore_storage", {"force": True})
62
+ self.assertFalse(restored.is_error)
63
+ self.assertFalse(cache.exists(), restored.content[0].text)
64
+
65
+ config.unlink()
66
+ self.assertTrue((await session.call_tool("storage_status")).is_error)
@@ -0,0 +1,195 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ import unittest
12
+ from unittest.mock import patch
13
+
14
+ import storage_guard as guard
15
+
16
+
17
+ class StorageGuardTest(unittest.TestCase):
18
+ def setUp(self):
19
+ temp = tempfile.TemporaryDirectory()
20
+ self.addCleanup(temp.cleanup)
21
+ self.root = Path(temp.name).resolve()
22
+ self.config = self.root / "config.json"
23
+ self.project = self.root / "example"
24
+ self.debug = self.project / "target/debug"
25
+ self.debug.mkdir(parents=True)
26
+ (self.project / "target/CACHEDIR.TAG").write_text(
27
+ "Signature: 8a477f597d28d172789f06886806bc55\n"
28
+ )
29
+ (self.project / "Cargo.toml").write_text(
30
+ '[package]\nname = "fixture"\nversion = "0.1.0"\nedition = "2021"\n'
31
+ )
32
+ (self.project / "src").mkdir()
33
+ (self.project / "src/lib.rs").write_text("pub fn fixture() {}\n")
34
+ (self.project / ".gitignore").write_text("/target/\n")
35
+ self.run_in_project("git", "init", "-q")
36
+
37
+ def run_in_project(self, *command, env=None):
38
+ return subprocess.run(command, cwd=self.project, env=env, check=True, capture_output=True)
39
+
40
+ def recover(self, cargo=None):
41
+ return guard.recover(self.config, self.root, 40 * guard.GIB, 60 * guard.GIB,
42
+ [Path("example")], cargo, False)
43
+
44
+ def test_healthy_disk_skips_cleanup(self):
45
+ with patch.object(guard, "free_bytes", return_value=60 * guard.GIB):
46
+ self.assertEqual(self.recover(Path("/missing/cargo")), "")
47
+ self.assertTrue(self.debug.is_dir())
48
+
49
+ def test_tracks_and_symlinks_are_ineligible(self):
50
+ device = self.root.stat().st_dev
51
+ self.assertTrue(guard.eligible(self.project, device))
52
+ (self.debug / "keep").touch()
53
+ self.run_in_project("git", "add", "-f", "target/debug/keep")
54
+ with patch.dict(os.environ, {"GIT_INDEX_FILE": str(self.root / "alternate-index")}):
55
+ self.assertFalse(guard.eligible(self.project, device))
56
+ self.debug.rename(self.root / "outside")
57
+ self.debug.symlink_to(self.root / "outside", target_is_directory=True)
58
+ self.assertFalse(guard.eligible(self.project, device))
59
+
60
+ def test_disposable_paths_cannot_overlap_cargo_targets(self):
61
+ self.config.write_text(json.dumps({
62
+ "workspace": str(self.root), "min_free_gib": 40, "target_free_gib": 60,
63
+ "cargo_projects": ["example"], "disposable_paths": ["example/TARGET/debug"],
64
+ }))
65
+ with self.assertRaisesRegex(guard.GuardError, "overlaps a Cargo target"):
66
+ guard.read_config(self.config)
67
+
68
+ @unittest.skipUnless(shutil.which("lsof"), "lsof unavailable")
69
+ def test_force_cli_cleans_all_eligible_output_above_target(self):
70
+ (self.project / ".gitignore").write_text("/.next/\n/.build/\n")
71
+ outputs = [self.project / name for name in (".next", ".build")]
72
+ old = time.time() - 2 * 86400
73
+ for output in outputs:
74
+ output.mkdir()
75
+ os.utime(output, (old, old))
76
+ self.config.write_text(json.dumps({
77
+ "workspace": str(self.root), "min_free_gib": 40, "target_free_gib": 60,
78
+ "disposable_paths": [str(output.relative_to(self.root)) for output in outputs],
79
+ }))
80
+ args = ["storage_guard.py", "--config", str(self.config), "guard"]
81
+ with patch.object(guard, "free_bytes", return_value=70 * guard.GIB):
82
+ with patch.object(sys, "argv", args):
83
+ self.assertEqual(guard.main(), 0)
84
+ self.assertTrue(all(output.exists() for output in outputs))
85
+ with patch.object(sys, "argv", [*args, "--force"]), contextlib.redirect_stdout(io.StringIO()):
86
+ self.assertEqual(guard.main(), 0)
87
+ self.assertFalse(any(output.exists() for output in outputs))
88
+
89
+ @unittest.skipUnless(shutil.which("lsof"), "lsof unavailable")
90
+ def test_reclaims_stale_ignored_output_without_cargo(self):
91
+ cache = self.project / "node_modules"
92
+ cache.mkdir()
93
+ (self.project / ".gitignore").write_text("/target/\n/node_modules/\n")
94
+ (cache / "contents").touch()
95
+ outside = self.root / "outside"
96
+ outside.mkdir()
97
+ (outside / "keep").touch()
98
+ (cache / "link").symlink_to(outside, target_is_directory=True)
99
+ deadline = time.monotonic() + 30
100
+ device = self.root.stat().st_dev
101
+ with self.assertRaisesRegex(guard.GuardError, "past 24 hours"):
102
+ guard.clean_generated(cache, device, deadline)
103
+ old = time.time() - 2 * 86400
104
+ (cache / ".git").touch()
105
+ for file in [cache, *cache.iterdir()]:
106
+ os.utime(file, (old, old), follow_symlinks=False)
107
+ with self.assertRaisesRegex(guard.GuardError, "Git metadata"):
108
+ guard.clean_generated(cache, device, deadline)
109
+ (cache / ".git").unlink()
110
+ os.utime(cache, (old, old))
111
+ with subprocess.Popen(["sleep", "10"], cwd=self.project) as running:
112
+ try:
113
+ with self.assertRaisesRegex(guard.GuardError, "process is working"):
114
+ guard.clean_generated(cache, device, deadline)
115
+ finally:
116
+ running.terminate()
117
+ with patch.object(guard, "free_bytes", side_effect=lambda _: (
118
+ 30 if cache.exists() else 65) * guard.GIB):
119
+ output = guard.recover(self.config, self.root, 40 * guard.GIB, 60 * guard.GIB,
120
+ [Path("example")], Path("/missing/cargo"), False,
121
+ [Path("example/node_modules")])
122
+ self.assertIn("65.0 GiB", output)
123
+ self.assertFalse(cache.exists())
124
+ self.assertTrue((outside / "keep").exists())
125
+ self.assertTrue(self.debug.exists())
126
+
127
+ @unittest.skipUnless(shutil.which("cargo"), "Cargo unavailable")
128
+ def test_active_build_defers_and_reports_low_space(self):
129
+ with patch.object(guard, "free_bytes", return_value=30 * guard.GIB), \
130
+ patch.object(guard, "cargo_busy", return_value=True):
131
+ with self.assertRaisesRegex(guard.GuardError, "30.0 GiB free.*compiler process"):
132
+ self.recover()
133
+ self.assertTrue(self.debug.is_dir())
134
+
135
+ @unittest.skipUnless(shutil.which("cargo"), "Cargo unavailable")
136
+ def test_reclaims_only_debug_artifacts(self):
137
+ self.run_in_project("cargo", "generate-lockfile", "--offline")
138
+ self.run_in_project("cargo", "build", "--frozen", "--target-dir", "target")
139
+ (self.debug / "discard").touch()
140
+ alternate = self.root / "other output"
141
+ (alternate / "debug").mkdir(parents=True)
142
+ (alternate / "debug/keep").touch()
143
+ for sibling in ("release", "doc", "x86_64-test/debug"):
144
+ directory = self.project / "target" / sibling
145
+ directory.mkdir(parents=True)
146
+ (directory / "keep").touch()
147
+ before = self.run_in_project("git", "status", "--porcelain").stdout
148
+ with patch.dict(os.environ, {"CARGO_TARGET_DIR": str(alternate),
149
+ "CARGO_BUILD_BUILD_DIR": str(alternate)}), \
150
+ patch.object(guard, "free_bytes", side_effect=lambda _: (
151
+ 30 if self.debug.exists() else 65) * guard.GIB), \
152
+ patch.object(guard, "cargo_busy", return_value=False):
153
+ self.assertIn("65.0 GiB", self.recover())
154
+ self.assertFalse(self.debug.exists())
155
+ self.assertTrue((alternate / "debug/keep").is_file())
156
+ for sibling in ("release", "doc", "x86_64-test/debug"):
157
+ self.assertTrue((self.project / "target" / sibling / "keep").is_file())
158
+ self.assertEqual(before, self.run_in_project("git", "status", "--porcelain").stdout)
159
+
160
+ def test_hook_denial_formats(self):
161
+ for client in ("claude", "codex", "hermes", "copilot"):
162
+ with self.subTest(client=client), contextlib.redirect_stdout(io.StringIO()) as out, \
163
+ contextlib.redirect_stderr(io.StringIO()) as err:
164
+ code = guard.reply("hook", client, True, "Low space")
165
+ if client == "copilot":
166
+ self.assertEqual(code, 0)
167
+ self.assertEqual(json.loads(out.getvalue())["permissionDecision"], "deny")
168
+ else:
169
+ self.assertEqual(code, 2)
170
+ self.assertEqual(err.getvalue().strip(), "Low space")
171
+
172
+ def test_hooks_let_storage_tools_run_when_guard_would_block(self):
173
+ for client, key, prefix in (
174
+ ("claude", "tool_name", "mcp__workspace-storage-guard__"),
175
+ ("codex", "tool_name", "mcp__workspace-storage-guard__"),
176
+ ("copilot", "toolName", "workspace-storage-guard-"),
177
+ ("hermes", "tool_name", "mcp__workspace_storage_guard__"),
178
+ ):
179
+ with self.subTest(client=client):
180
+ command = [sys.executable, str(Path(guard.__file__).resolve()),
181
+ "--config", str(self.config), "hook", client]
182
+ for tool in ("storage_status", "scan_storage", "restore_storage"):
183
+ reply = subprocess.run(command, input=json.dumps({key: prefix + tool}),
184
+ text=True, capture_output=True, check=True)
185
+ self.assertEqual((reply.stdout, reply.stderr), ("", ""))
186
+ reply = subprocess.run(command, input=json.dumps({key: prefix + "other_tool"}),
187
+ text=True, capture_output=True)
188
+ if client == "copilot":
189
+ self.assertEqual(json.loads(reply.stdout)["permissionDecision"], "deny")
190
+ else:
191
+ self.assertEqual(reply.returncode, 2)
192
+
193
+
194
+ if __name__ == "__main__":
195
+ unittest.main()
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: workspace-storage-guard
3
+ Version: 0.1.0
4
+ Summary: Local MCP server for checking workspace storage and reclaiming generated files
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/TonPC64/workspace-storage-guard
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: mcp==2.3.0
11
+ Dynamic: license-file
12
+
13
+ # Workspace Storage Guard
14
+
15
+ Workspace Storage Guard is a local MCP server and command-line tool for software developers on macOS and Linux. It reports free space on your workspace volume, ranks directories by disk usage, and reclaims generated files you explicitly allowlist, including Cargo debug output, build caches, and `node_modules`.
16
+
17
+ ## Connect your agent
18
+
19
+ Install `uv`, then create a local config from `examples/config.json` and set your workspace, free-space thresholds, and cleanup allowlists. Register the server with Hermes Agent, Claude Code, GitHub Copilot CLI, or Codex. [Setup guide](docs/setup.md)
20
+
21
+ For example, register it in Codex using the GitHub release.
22
+
23
+ ```sh
24
+ codex mcp add workspace-storage-guard -- "$(command -v uvx)" \
25
+ --from git+https://github.com/TonPC64/workspace-storage-guard.git@v0.1.0 \
26
+ workspace-storage-guard
27
+ ```
28
+
29
+ Start a fresh agent session and ask it to call `storage_status`.
30
+
31
+ ## Check and reclaim space
32
+
33
+ - `storage_status` reports free space and your cleanup thresholds.
34
+ - `scan_storage` ranks the largest directories in your workspace.
35
+ - `restore_storage` reclaims eligible generated output when free space drops below your minimum. Pass `{"force": true}` to clean eligible output regardless of free space.
36
+
37
+ Your workspace path and allowlists live in a per-user local config. Scan results include local paths and may be shared with your agent’s model provider. [Usage guide](docs/usage.md)
38
+
39
+ ## Automate checks
40
+
41
+ Run Storage Guard from the terminal, add a hook to your agent, or schedule it with a macOS LaunchAgent. The example LaunchAgent runs at sign-in and every five minutes. [Hook and LaunchAgent setup](docs/setup.md#connect-agent-hooks)
@@ -0,0 +1,21 @@
1
+ AGENTS.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ mcp_server.py
6
+ pyproject.toml
7
+ requirements-mcp.txt
8
+ storage_guard.py
9
+ docs/setup.md
10
+ docs/usage.md
11
+ examples/config.json
12
+ examples/io.github.workspace-storage-guard.plist
13
+ tests/__init__.py
14
+ tests/test_mcp_server.py
15
+ tests/test_storage_guard.py
16
+ workspace_storage_guard.egg-info/PKG-INFO
17
+ workspace_storage_guard.egg-info/SOURCES.txt
18
+ workspace_storage_guard.egg-info/dependency_links.txt
19
+ workspace_storage_guard.egg-info/entry_points.txt
20
+ workspace_storage_guard.egg-info/requires.txt
21
+ workspace_storage_guard.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ workspace-storage-guard = mcp_server:main
@@ -0,0 +1,2 @@
1
+ mcp_server
2
+ storage_guard