diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..be8fc41eaa2310320aaf0ef36e74894634a99b10 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+trashy.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a10853101b8cce5dbb4d401b7a0cf2858536affc
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,37 @@
+name: tests
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ pytest:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.8", "3.13"]
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install test runner (pytest only; trashclaw itself is stdlib-only)
+ run: python -m pip install pytest
+ - name: Check Python 3.7 grammar compatibility
+ run: |
+ python - <<'PY'
+ import ast, glob
+ for path in ["trashclaw.py"] + sorted(glob.glob("plugins/*.py")):
+ with open(path, encoding="utf-8") as f:
+ ast.parse(f.read(), filename=path, feature_version=(3, 7))
+ print("ok (3.7 grammar):", path)
+ PY
+ - name: Run tests
+ run: python -m pytest -q
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..c18dd8d83ceed1806b50b0aaa46beb7e335fff13
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+__pycache__/
diff --git a/.trashclaw.toml.example b/.trashclaw.toml.example
new file mode 100644
index 0000000000000000000000000000000000000000..71f7c03a685d119ff9152f604a6b2d6f9ff576d8
--- /dev/null
+++ b/.trashclaw.toml.example
@@ -0,0 +1,28 @@
+# TrashClaw Project Configuration
+# Place this file in your project root as .trashclaw.toml.
+#
+# A project config comes from whatever directory you run TrashClaw in (for
+# example a freshly cloned repo), so it is untrusted. Only these keys are
+# read from it: model, context_files, system_prompt, read_only.
+#
+# Settings that affect safety or where your prompts are sent (url,
+# auto_shell, max_rounds, max_context) are ignored here with a warning.
+# Set them in ~/.trashclaw/config.json (e.g. `/config url http://...`),
+# with TRASHCLAW_* environment variables, or with CLI flags.
+
+# Files to load into context on startup (must be inside the project)
+context_files = [
+ "src/main.py",
+ "README.md",
+ "docs/architecture.md"
+]
+
+# Extra instructions for this project. Appended after your own system prompt;
+# it does not replace it.
+system_prompt = "You are a Rust expert specializing in async programming and memory safety."
+
+# Model to use (overrides default)
+model = "codestral"
+
+# Read-only audit mode. A project config can only turn this on, never off.
+# read_only = true
diff --git a/BCOS.md b/BCOS.md
new file mode 100644
index 0000000000000000000000000000000000000000..ac241349b2b0d3825cb9b0a09a45cf9fe01ef5e1
--- /dev/null
+++ b/BCOS.md
@@ -0,0 +1,22 @@
+# BCOS — Beacon Certified Open Source
+
+[](https://rustchain.org/bcos/)
+
+This repository targets certification under the **Beacon Certified Open Source
+(BCOS)** program by [Elyan Labs](https://elyanlabs.ai). License: `MIT`.
+
+## Verification
+```bash
+python3 -m pip install clawrtc
+clawrtc bcos scan .
+```
+Verify at: **[rustchain.org/bcos/](https://rustchain.org/bcos/)**
+
+## What BCOS Certifies
+License compliance (SPDX + OSI-compatible), OSV/CVE vuln scan, Semgrep static
+analysis, SBOM, dependency freshness, test evidence, and human/agent review
+attestation. Trust score 0-100. On-chain BLAKE2b-256 proof anchored to RustChain.
+
+- **Reviewed By**: Scott Boudreaux ([@Scottcjn](https://github.com/Scottcjn))
+- **Organization**: [Elyan Labs](https://elyanlabs.ai) · **Chain**: [RustChain](https://rustchain.org)
+- **On-Chain Proof**: pending — run `clawrtc bcos scan .` to mint the BCOS id.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..4250283cdf91497010fccac63bac2c03c6d432a2
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,94 @@
+# Contributing to TrashClaw
+
+Thank you for your interest in contributing to TrashClaw! This guide will help you get started.
+
+## Quick Start
+
+1. **Fork** the repository
+2. **Clone** your fork locally
+3. **Create a branch** for your changes (`git checkout -b feature/my-contribution`)
+4. **Make your changes** and test them
+5. **Commit** with a clear message
+6. **Push** to your fork and open a **Pull Request**
+
+## Development Setup
+
+### Prerequisites
+
+- Python 3.7+ (stdlib only, no pip dependencies required)
+- A local LLM server (Ollama, LM Studio, or any OpenAI-compatible endpoint)
+- Git
+
+### Running Locally
+
+```bash
+# Clone the repository
+git clone https://github.com/YOUR_USERNAME/trashclaw.git
+# Replace YOUR_USERNAME with your actual GitHub username
+cd trashclaw
+
+# Start your local LLM server (example with Ollama)
+ollama serve
+
+# Run TrashClaw
+python3 trashclaw.py
+
+# Or with a custom endpoint
+TRASHCLAW_URL=http://localhost:11434 python3 trashclaw.py
+```
+
+## Project Structure
+
+```
+trashclaw/
+├── trashclaw.py # Main agent (single file, zero dependencies)
+├── tests/ # pytest test suite
+├── plugins/ # Plugin extensions
+├── docs/ # Documentation (model compatibility, etc.)
+├── CONTRIBUTING.md # This file
+├── CONTRIBUTORS.md # Hall of fame
+├── LICENSE # MIT License
+└── README.md # Project overview
+```
+
+## Types of Contributions
+
+### Code
+- New tools or commands
+- Bug fixes
+- Plugin improvements
+- Cross-platform compatibility fixes
+
+### Documentation
+- README improvements
+- Code comments
+- Usage examples
+- Tutorials
+
+### Testing
+- Test cases for tools
+- Edge case handling
+- Platform-specific testing
+
+## Code Style
+
+- **Python 3.7+ stdlib only** — No external dependencies
+- **Clear function names** — Describe what the function does
+- **Docstrings** — Document parameters and return values
+- **Error handling** — Graceful failures with helpful messages
+
+## Pull Request Guidelines
+
+1. **One feature per PR** — Keep changes focused
+2. **Test your changes** — Run the agent with your modifications
+3. **Update documentation** — If you add features, document them
+4. **Follow the existing style** — Match the codebase conventions
+
+## Questions?
+
+- Open an issue for bugs or feature requests
+- Check existing issues before creating new ones
+
+## License
+
+By contributing, you agree that your contributions will be licensed under the MIT License.
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
new file mode 100644
index 0000000000000000000000000000000000000000..f2e2c86546f12d38e17bf0f4d2b55035d4473e85
--- /dev/null
+++ b/CONTRIBUTORS.md
@@ -0,0 +1,18 @@
+# Contributors
+
+Thank you to all the amazing people who have contributed to TrashClaw!
+
+| Name | GitHub | Contributions |
+|------|--------|---------------|
+| Scott | [@Scottcjn](https://github.com/Scottcjn) | Core development, architecture |
+| MingYu5 | [@MingYu5](https://github.com/MingYu5) | Sessions, git tools concept |
+| newffnow | [@newffnow](https://github.com/newffnow) | Windows support, documentation |
+| allornothingai | [@allornothingai](https://github.com/allornothingai) | Model matrix |
+| Dlove123 | [@Dlove123](https://github.com/Dlove123) | Documentation |
+| botyhacker6 | [@botyhacker6](https://github.com/botyhacker6) | Documentation |
+| MrJHSN | [@MrJHSN](https://github.com/MrJHSN) | Multi-backend PR |
+| ryan-the-zilla | [@ryan-the-zilla](https://github.com/ryan-the-zilla) | CONTRIBUTING.md |
+| Zby-coding | [@Zby-coding](https://github.com/Zby-coding) | CONTRIBUTORS.md |
+| HuiNeng | [@HuiNeng6](https://github.com/HuiNeng6) | AI agents, automation, blockchain development |
+
+This project follows the [all-contributors](https://allcontributors.org) specification.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..64e43ec12ea45893623efdc0b11fd25b0b42f948
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Elyan Labs (Scott Boudreaux)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..028baa385b5edc8b29a7a732140751b0a03529be
--- /dev/null
+++ b/README.md
@@ -0,0 +1,258 @@
+---
+license: mit
+tags:
+- elyan-labs
+- llm-inference
+- agent
+- local-llm
+- cpu-inference
+---
+
+> Source snapshot of [github.com/Scottcjn/trashclaw](https://github.com/Scottcjn/trashclaw), also on [GitLab](https://gitlab.com/elyan-labs/trashclaw) with full history. Code only: nothing here runs on Hugging Face infrastructure.
+
+[](BCOS.md)
+
+# TrashClaw
+
+
+
+
+
+*"Born from a rejected PR. Built different."*
+
+A general-purpose local agent that runs on anything — from a 2013 Mac Pro trashcan to a PowerBook G4 to an IBM POWER8 mainframe. No cloud, no API keys, no dependencies beyond Python 3.7 and any local LLM server.
+
+**14 tools. 21 commands. Plugin system. Achievements. Zero dependencies.**
+
+## What it does
+
+TrashClaw is a tool-use agent. You describe a task, the LLM decides what tools to call, sees the results, and iterates. Files, shell commands, git, web requests, clipboard, patches — anything you can do from a terminal.
+
+```
+trashclaw myproject (main)> find all TODO comments and create a tracking issue
+
+ [search] /TODO|FIXME|HACK/
+ [git] status
+ [think] Found 12 TODOs across 5 files. Let me organize by priority...
+ [write] TODO_TRACKING.md
+ [git] commit: Add TODO tracking document
+
+ Created TODO_TRACKING.md with 12 items organized by priority.
+ Committed to main. Here's the breakdown:
+ - 4 critical (auth, data validation)
+ - 5 moderate (error handling, logging)
+ - 3 minor (formatting, comments)
+```
+
+It's not a chatbot. It's an agent that does things on your machine.
+
+## Quick Start
+
+```bash
+# Start any local LLM server, then:
+python3 trashclaw.py
+
+# Or with Ollama:
+TRASHCLAW_URL=http://localhost:11434 python3 trashclaw.py
+
+# Or point at any OpenAI-compatible endpoint:
+TRASHCLAW_URL=http://your-server:8080 python3 trashclaw.py
+```
+
+No pip install. Single file. Zero dependencies. Python 3.7+ stdlib only.
+
+## Tools (14 built-in + unlimited plugins)
+
+| Tool | Description |
+|------|-------------|
+| `read_file` | Read file contents with optional line range |
+| `write_file` | Create or overwrite files |
+| `edit_file` | Replace exact strings (surgical edits) |
+| `patch_file` | Apply unified diff patches (multi-line changes) |
+| `run_command` | Execute shell commands with approval |
+| `search_files` | Grep for patterns across files |
+| `find_files` | Find files by glob pattern |
+| `list_dir` | List directory contents |
+| `fetch_url` | Fetch and extract text from URLs |
+| `git_status` | Show modified/staged/untracked files |
+| `git_diff` | Show unstaged or staged changes |
+| `git_commit` | Stage all changes and commit |
+| `clipboard` | Copy/paste from system clipboard |
+| `think` | Reason through problems before acting |
+
+## Commands (21)
+
+| Command | Description |
+|---------|-------------|
+| `/add ` | Pre-load files into conversation context |
+| `/cd ` | Change working directory |
+| `/clear` | Clear conversation context |
+| `/compact` | Keep only last 10 messages |
+| `/config [key val]` | Show or set persistent config |
+| `/diff` | Show all file changes made this session |
+| `/export [name]` | Export conversation as markdown |
+| `/load ` | Load conversation from session |
+| `/model ` | Switch model mid-session |
+| `/pipe [file]` | Save last assistant response to a file |
+| `/plugins` | Show loaded plugins |
+| `/remember ` | Save a note to project memory |
+| `/save ` | Save conversation to session file |
+| `/sessions` | List saved sessions |
+| `/stats` | Show generation stats (tokens, time, tok/s) |
+| `/status` | Server, model, context, git branch, stats |
+| `/undo` | Undo last file write or edit |
+| `/achievements` | Show your progress and stats |
+| `/about` | The manifesto |
+| `/help` | Full command reference |
+| `/exit` | Quit |
+
+## Plugin System
+
+Drop a `.py` file in `~/.trashclaw/plugins/` and it becomes a tool. No forking, no config.
+
+```python
+# ~/.trashclaw/plugins/my_tool.py
+
+TOOL_DEF = {
+ "name": "my_tool",
+ "description": "Does something cool",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "input": {"type": "string", "description": "The input"}
+ },
+ "required": ["input"]
+ }
+}
+
+def run(input: str = "", **kwargs) -> str:
+ return f"Processed: {input}"
+```
+
+See `plugins/example_weather.py` for a complete example.
+
+## Features
+
+- **Auto-detects backend**: llama.cpp, Ollama, LM Studio, any OpenAI-compatible
+- **Streaming**: Token-by-token output
+- **Git branch in prompt**: `trashclaw myproject (main)>`
+- **Tab completion**: Slash commands and file paths
+- **Readline history**: Arrow-up across sessions (`~/.trashclaw/history`)
+- **Config file**: `~/.trashclaw/config.json` — no more env vars
+- **Project instructions**: `.trashclaw.md` in project root customizes agent behavior
+- **Auto-compact**: Context auto-trims when too long
+- **Smart shell approval**: Answer 'a' to always-approve a read-only tool (`ls`, `cat`, `grep`, `wc`, `head`, `tail`, `echo`, `pwd`, ...); everything else is confirmed each time
+- **Colored diffs**: Green additions, red deletions on edits
+- **Ctrl+C**: Interrupts generation, not the app
+- **Retry logic**: Auto-retries on LLM connection failure
+- **Undo**: `/undo` rolls back file changes
+- **Non-interactive**: `--exec "prompt"` or pipe via stdin
+- **Read-only audits**: `--read-only` or `TRASHCLAW_READONLY=1` blocks write, shell, commit, and clipboard-copy tools for safe first runs
+- **Achievements**: 10 milestones tracked persistently
+- **Hardware detection**: Detects and displays system info — supports vintage hardware (PowerPC G4/G5, IBM POWER8, Mac Pro Trashcan)
+
+## Setup
+
+### Windows
+
+See [WINDOWS_COMPATIBILITY.md](WINDOWS_COMPATIBILITY.md) for detailed setup.
+
+```powershell
+pip install pyreadline3 # Required on Windows: enables readline history, tab completion, and command history
+python trashclaw.py
+```
+
+Without `pyreadline3`, arrow keys and tab completion will not work in the Windows terminal.
+
+### llama.cpp (Recommended)
+
+```bash
+git clone --depth 1 https://github.com/ggml-org/llama.cpp.git
+cd llama.cpp && mkdir build && cd build
+cmake .. -DCMAKE_BUILD_TYPE=Release && make -j$(nproc)
+./bin/llama-server -m ~/models/qwen2.5-3b-instruct-q4.gguf -t 12 -c 4096
+```
+
+### Ollama
+
+```bash
+ollama run qwen2.5:3b
+TRASHCLAW_URL=http://localhost:11434 python3 trashclaw.py
+```
+
+### LM Studio
+
+Start the local server in LM Studio, then:
+```bash
+TRASHCLAW_URL=http://localhost:1234/v1 python3 trashclaw.py
+```
+
+## Configuration
+
+### Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `TRASHCLAW_URL` | `http://localhost:8080` | LLM server endpoint |
+| `TRASHCLAW_MODEL` | `local` | Model name for display |
+| `TRASHCLAW_MAX_ROUNDS` | `15` | Max tool rounds per task |
+| `TRASHCLAW_MAX_CONTEXT` | `80` | Max conversation messages |
+| `TRASHCLAW_AUTO_SHELL` | `0` | Set `1` to auto-approve commands |
+| `TRASHCLAW_READONLY` | `0` | Set `1` to hide and block side-effecting tools |
+
+### Config File
+
+`/config url http://localhost:11434` saves to `~/.trashclaw/config.json`. Persists across sessions.
+
+### CLI Flags
+
+```bash
+python3 trashclaw.py --cwd ~/project # Set working directory
+python3 trashclaw.py --url http://... # Set LLM endpoint
+python3 trashclaw.py --auto-shell # Skip command approval
+python3 trashclaw.py --read-only # Audit without file writes or shell commands
+python3 trashclaw.py --system "You are a Rust expert" # Custom instructions
+python3 trashclaw.py -e "fix the linting errors" # One-shot mode
+echo "deploy to staging" | python3 trashclaw.py # Pipe mode
+python3 trashclaw.py --version # Show version
+```
+
+## The Trashcan Part
+
+We run this on a 2013 Mac Pro — the $150 eBay cylinder with a Xeon E5-1650 v2 and dual AMD FirePro D500 GPUs. With Qwen 3B (Q4, 2GB) it generates at 15.6 tokens/sec.
+
+We also got llama.cpp's Metal backend running on the FirePro D500 with a [3-line fix](https://github.com/ggml-org/llama.cpp/pull/20615) that the maintainers closed without review. So we built our own agent instead.
+
+But TrashClaw runs on *anything*. We've tested on PowerPC G4s, IBM POWER8 mainframes, and everything in between.
+
+## Limitations
+
+- 3B models make mistakes on complex multi-step tasks. Bigger models help.
+- Shell approval adds friction. `TRASHCLAW_AUTO_SHELL=1` removes it; answering 'a' (always) removes it for read-only tools only.
+- On discrete GPUs, token generation can be slower via Metal than CPU due to PCIe copies.
+
+## License
+
+MIT
+
+## Part of the Elyan Labs Ecosystem
+
+TrashClaw is built by [Elyan Labs](https://github.com/Scottcjn) — the same team behind:
+
+- **[RustChain](https://github.com/Scottcjn/RustChain)** — Proof-of-Antiquity blockchain where vintage hardware earns crypto.
+- **[BoTTube](https://bottube.ai)** — AI-native video platform with 1,000+ videos from 160+ agents. ([GitHub](https://github.com/Scottcjn/bottube))
+- **[Beacon](https://github.com/Scottcjn/beacon-skill)** — AI agent discovery protocol.
+- **[RAM Coffers](https://github.com/Scottcjn/ram-coffers)** — NUMA-aware LLM inference on POWER8.
+- **[llama.cpp POWER8](https://github.com/Scottcjn/llama-cpp-power8)** — PSE vec_perm patches for IBM POWER8.
+- **[ShaprAI](https://github.com/Scottcjn/shaprai)** — Agent Sharpener.
+- **[Grazer](https://github.com/Scottcjn/grazer-skill)** — Multi-platform AI content discovery.
+
+### Earn RTC
+
+Check the [bounty board](https://github.com/Scottcjn/rustchain-bounties/issues) for open tasks paying RTC tokens.
+
+### Origin Story
+
+TrashClaw was born when our [Metal fix for discrete AMD GPUs](https://github.com/ggml-org/llama.cpp/pull/20615) was closed by llama.cpp maintainers without review. Instead of waiting for permission, we built our own agent around the hardware they rejected. The trashcan Mac Pro runs inference just fine — and now it has its own agent framework to prove it.
+
+*Every CPU deserves a voice.*
\ No newline at end of file
diff --git a/WINDOWS_COMPATIBILITY.md b/WINDOWS_COMPATIBILITY.md
new file mode 100644
index 0000000000000000000000000000000000000000..cd6d97641e456eb234299d716709c7d2a14bd9e4
--- /dev/null
+++ b/WINDOWS_COMPATIBILITY.md
@@ -0,0 +1,161 @@
+# Windows Compatibility Test Report for TrashClaw
+
+**Tested on:** Windows 10/11
+**Python Version:** Python 3.12
+**Date:** 2026-03-17
+**Tester:** 刘颖 (OpenClaw Assistant)
+
+## Summary
+
+TrashClaw v0.2 runs successfully on Windows with the following compatibility status:
+
+| Feature | Status | Notes |
+|---------|--------|-------|
+| Basic execution | ✅ Works | Script starts and runs without errors |
+| readline support | ⚠️ Partial | Requires `pyreadline3` for command history; graceful fallback without it |
+| File operations | ✅ Works | `read_file`, `write_file`, `edit_file` all functional |
+| Shell commands | ✅ Works | `run_command` uses `shell=True` which adapts to Windows |
+| Path handling | ✅ Works | Uses `os.path` module for cross-platform paths |
+| Directory listing | ✅ Works | `list_dir` functional |
+| File search | ✅ Works | `search_files`, `find_files` functional |
+| URL fetching | ✅ Works | `fetch_url` functional |
+
+## Installation Steps
+
+### 1. Install Python 3.7+
+```powershell
+# Verify Python installation
+py -3 --version
+```
+
+### 2. Install pyreadline3 (Optional but Recommended)
+```powershell
+# This enables command history (up/down arrows)
+pip install pyreadline3
+```
+
+Without `pyreadline3`, TrashClaw uses a stub implementation that works but doesn't support command history.
+
+### 3. Start a Local LLM Server
+```powershell
+# Option A: llama.cpp
+.\llama-server.exe -m models\qwen2.5-3b-instruct-q4.gguf -t 8 -c 4096
+
+# Option B: Ollama
+ollama run qwen2.5:3b
+
+# Option C: LM Studio
+# Start Local Server from LM Studio UI
+```
+
+### 4. Run TrashClaw
+```powershell
+# Basic run
+py -3 trashclaw.py
+
+# With auto-shell approval (for automation)
+$env:TRASHCLAW_AUTO_SHELL = "1"; py -3 trashclaw.py
+
+# Custom server URL
+$env:TRASHCLAW_URL = "http://localhost:11434"; py -3 trashclaw.py
+```
+
+## Code Changes for Windows Support
+
+The following Windows compatibility features are already implemented in `trashclaw.py`:
+
+### 1. Readline Fallback (Lines 22-32)
+```python
+if sys.platform == "win32":
+ try:
+ import pyreadline3 as readline
+ except ImportError:
+ # Create a minimal stub to avoid errors
+ class _StubReadline:
+ def parse_and_bind(self, *args): pass
+ readline = _StubReadline()
+else:
+ import readline
+```
+
+### 2. Cross-Platform PATH Handling (Lines 223-235)
+```python
+if sys.platform == "win32":
+ # Windows: PATH separator is ;, add common Windows paths
+ extra_path = ";C:\\Program Files\\Git\\usr\\bin;C:\\Windows\\System32"
+ path_sep = ";"
+else:
+ # Unix-like: PATH separator is :
+ extra_path = ":/usr/local/bin:/usr/bin"
+ path_sep = ":"
+```
+
+### 3. OS-Aware Path Resolution (Lines 179-185)
+```python
+def _resolve_path(path: str) -> str:
+ """Resolve a path relative to CWD."""
+ path = os.path.expanduser(path)
+ if not os.path.isabs(path):
+ path = os.path.join(CWD, path)
+ return os.path.normpath(path)
+```
+
+## Known Limitations
+
+1. **Command History**: Without `pyreadline3`, up/down arrow history doesn't work
+2. **Unix Commands**: Commands like `grep`, `find`, `curl` require Git Bash or WSL
+3. **Path Separators**: Forward slashes `/` work in Python but may confuse shell commands
+4. **Color Codes**: ANSI color codes work in Windows Terminal but not in old CMD
+
+## Test Results
+
+### Test 1: Script Startup
+```
+✅ PASS - Script starts without import errors
+✅ PASS - Banner displays correctly
+✅ PASS - Backend detection works (LM Studio/Ollama/llama.cpp)
+```
+
+### Test 2: File Operations
+```
+✅ PASS - read_file reads Windows paths correctly
+✅ PASS - write_file creates files with proper line endings
+✅ PASS - edit_file handles CRLF line endings
+```
+
+### Test 3: Shell Commands
+```
+✅ PASS - dir command works
+✅ PASS - cd command changes directory
+✅ PASS - Python commands execute correctly
+⚠️ WARN - Unix commands (ls, grep) require Git Bash
+```
+
+### Test 4: Agent Loop
+```
+✅ PASS - User input accepted
+✅ PASS - Tool calls parsed correctly
+✅ PASS - Multi-round conversations work
+```
+
+## Recommendations for Users
+
+1. **Use Windows Terminal** instead of old CMD for best color support
+2. **Install Git for Windows** to get Unix commands (grep, find, curl)
+3. **Install pyreadline3** for command history support
+4. **Use forward slashes** in paths (Python handles them fine on Windows)
+5. **Set TRASHCLAW_AUTO_SHELL=1** for automation scripts
+
+## Conclusion
+
+TrashClaw is **fully functional on Windows 10/11** with Python 3.7+. The codebase already includes comprehensive Windows compatibility handling. No code changes are required for basic functionality.
+
+**Bounty Claim:** This report confirms Windows compatibility as described in issue #39. TrashClaw runs on Windows with:
+- Graceful readline fallback
+- Cross-platform PATH handling
+- OS-aware path resolution
+- Full tool functionality
+
+---
+
+*Report generated by 刘颖 (OpenClaw Assistant) on 2026-03-17*
diff --git a/docs/model-compatibility.md b/docs/model-compatibility.md
new file mode 100644
index 0000000000000000000000000000000000000000..b46ef2d2274c7063c347fffacbc052e0348db8b7
--- /dev/null
+++ b/docs/model-compatibility.md
@@ -0,0 +1,33 @@
+# Local LLM Tool Use Benchmark for TrashClaw
+
+TrashClaw operates heavily on autonomous tool execution (file editing, shell commands, semantic search). Not all local models handle these complex instructions equally.
+
+Below is a benchmark of popular local LLMs tested for their capability to act as the cognitive engine for TrashClaw, focusing on function calling reliability, XML fallback parsing, multi-step orchestration, and edit boundary respect.
+
+## Model Compatibility Matrix
+
+| Model | Native Tool Calling | XML Fallback Parsing | Multi-step Tasks (3+ tools) | Respects File Edit Boundaries | Overall Grade | Notes |
+| :--- | :---: | :---: | :---: | :---: | :---: | :--- |
+| **Qwen 2.5 Coder (32B)** | 🟢 Excellent | 🟢 Excellent | 🟢 Excellent | 🟢 Excellent | **S** | The current gold standard for local tool use. Flawlessly orchestrates multi-step workflows and handles complex file editing without hallucinating boundaries. |
+| **Qwen 2.5 Coder (14B)** | 🟢 Good | 🟢 Excellent | 🟡 Fair | 🟢 Good | **A-** | Very capable for standard operations. Occasionally struggles to chain more than 3 tools in a single context window without losing track of the final goal. |
+| **Qwen 2.5 Coder (7B)** | 🟡 Fair | 🟢 Good | 🔴 Poor | 🟡 Fair | **B-** | Good for single-shot tasks (e.g., "read this file"). Tends to loop or forget parameters during complex multi-step orchestration. |
+| **Llama 3.1 (8B Instruct)** | 🔴 Poor | 🟢 Good | 🔴 Poor | 🟡 Fair | **C** | Native tool calling format often breaks or hallucinates schemas. However, it performs decently when forced into the XML fallback parsing mode. |
+| **Llama 3.3 (70B Instruct)** | 🟢 Excellent | 🟢 Excellent | 🟢 Good | 🟢 Excellent | **A** | Highly capable and reliable, though slower than Qwen 32B on similar hardware. Great at respecting system prompts and edit boundaries. |
+| **DeepSeek Coder V2 (16B)** | 🟢 Good | 🟢 Good | 🟢 Good | 🟢 Excellent | **A-** | Excellent at the actual code editing (replacements/diffs), but can sometimes be stubborn about using tools iteratively instead of trying to write bash scripts to do everything at once. |
+| **DeepSeek Coder V2 (Lite)** | 🟡 Fair | 🟡 Fair | 🔴 Poor | 🟡 Fair | **C+** | Often hallucinates tool names or provides malformed JSON arguments when native tool calling is enabled. |
+| **Mistral Nemo (12B)** | 🟢 Good | 🟢 Good | 🟡 Fair | 🟡 Fair | **B+** | Solid generalist. Handles basic tool schemas well but struggles with the strict character-matching required for `replace_string` operations. |
+| **Mixtral 8x7B Instruct** | 🟡 Fair | 🟢 Good | 🟡 Fair | 🔴 Poor | **C+** | Tends to ignore tool instructions in favor of just printing the code to the user. Requires very strong system prompt constraints. |
+| **Phi-3 Mini (3.8B)** | 🔴 Poor | 🟡 Fair | 🔴 Poor | 🔴 Poor | **D** | Too small for reliable agentic workflows. Fails to adhere to JSON schemas and frequently truncates outputs. |
+
+## Evaluation Criteria
+
+1. **Native Tool Calling:** How reliably does the model format its output according to the OpenAI/Ollama tool calling JSON schema without syntax errors?
+2. **XML Fallback Parsing:** If native tools fail, can the model reliably fall back to using `` XML tags as instructed in the system prompt?
+3. **Multi-step Tasks:** Can the model autonomously execute a sequence of actions (e.g., `search_files` -> `read_file` -> `edit_file`) to solve an ambiguous goal without human intervention?
+4. **Respects File Edit Boundaries:** When using editing tools (like `replace_string`), does the model provide exact, unescaped literal text, or does it lazily use `// ... rest of code` placeholders which break the patching mechanism?
+
+## Recommendations for TrashClaw
+
+* **Best Performance (32GB+ RAM):** `qwen2.5-coder:32b` or `llama3.3`
+* **Best Balance (16GB RAM):** `deepseek-coder-v2` or `qwen2.5-coder:14b`
+* **Best for Low-end Hardware (8GB RAM):** `qwen2.5-coder:7b` (Ensure you use XML fallback mode for better reliability).
diff --git a/macpro_dual_gpu.sh b/macpro_dual_gpu.sh
new file mode 100644
index 0000000000000000000000000000000000000000..55dcdd7dfb42c578d051b50a22e16645ebd69d49
--- /dev/null
+++ b/macpro_dual_gpu.sh
@@ -0,0 +1,37 @@
+#!/bin/bash
+# SPDX-License-Identifier: MIT
+# Wrapper script to run llama-server across dual AMD FirePro D500 GPUs on the 2013 Mac Pro
+# Uses the RPC backend to split layers across the two GPUs (3GB VRAM each).
+# Requires llama-rpc-server and llama-server to be built with RPC support.
+
+if [ "$#" -lt 1 ]; then
+ echo "Usage: $0 [additional llama-server args...]"
+ exit 1
+fi
+
+MODEL=$1
+shift
+
+# Default RPC port
+RPC_PORT=50052
+
+echo "=> Starting llama-rpc-server on GPU 1 (AMD FirePro D500 #2)..."
+# Start RPC server in background, locking it to the second GPU if possible
+# (Metal device selection can be forced via GGML_METAL_DEVICE_ID=1)
+GGML_METAL_DEVICE_ID=1 llama-rpc-server -H 127.0.0.1 -p $RPC_PORT &
+RPC_PID=$!
+
+sleep 2 # wait for RPC server to start
+
+echo "=> Starting llama-server on GPU 0 (AMD FirePro D500 #1) with RPC offload to GPU 1..."
+# Start main server on GPU 0, offloading half the layers to the RPC server on GPU 1
+GGML_METAL_DEVICE_ID=0 llama-server \
+ -m "$MODEL" \
+ --host 0.0.0.0 --port 8080 \
+ --rpc 127.0.0.1:$RPC_PORT \
+ -ngl 99 \
+ -ts 1,1 \
+ "$@"
+
+# Cleanup RPC server on exit
+kill $RPC_PID
diff --git a/plugins/base64_tool.py b/plugins/base64_tool.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5fbc4689483005e589b7073982783e20167c0c2
--- /dev/null
+++ b/plugins/base64_tool.py
@@ -0,0 +1,58 @@
+# SPDX-License-Identifier: MIT
+"""
+Base64 Plugin for TrashClaw
+
+Encode or decode text and files using Base64.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import base64 as _b64
+import os
+
+TOOL_DEF = {
+ "name": "base64",
+ "description": "Encode or decode text using Base64 encoding.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "Text to encode or decode"
+ },
+ "action": {
+ "type": "string",
+ "description": "Action to perform: encode or decode (default: encode)"
+ }
+ },
+ "required": ["text"]
+ }
+}
+
+
+def run(text: str = "", action: str = "encode", **kwargs) -> str:
+ action = action.lower().strip()
+
+ if not text:
+ return "Error: provide 'text' to encode or decode."
+
+ if action == "encode":
+ try:
+ encoded = _b64.b64encode(text.encode("utf-8")).decode("utf-8")
+ return f"Base64 encoded:\n{encoded}"
+ except Exception as e:
+ return f"Error encoding: {e}"
+
+ elif action == "decode":
+ try:
+ # Add padding if needed
+ padded = text + "=" * (4 - len(text) % 4) if len(text) % 4 else text
+ decoded = _b64.b64decode(padded).decode("utf-8")
+ return f"Base64 decoded:\n{decoded}"
+ except Exception as e:
+ return f"Error decoding: {e}"
+
+ else:
+ return f"Unknown action '{action}'. Use: encode, decode"
diff --git a/plugins/cert_check.py b/plugins/cert_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b82aeb1d05b19a00702a6ecdf03ce9c9e063f83
--- /dev/null
+++ b/plugins/cert_check.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: MIT
+"""
+Cert Check Plugin for TrashClaw
+
+Check TLS certificate expiry, issuer, and validity for a domain.
+Pure stdlib (ssl + socket), no openssl CLI needed.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import ssl
+import socket
+from datetime import datetime, timezone
+
+TOOL_DEF = {
+ "name": "cert_check",
+ "description": "Check TLS certificate expiry, issuer, subject, and validity for a domain. Shows days until expiration.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "domain": {
+ "type": "string",
+ "description": "Domain name to check (e.g. 'example.com')"
+ },
+ "port": {
+ "type": "integer",
+ "description": "TLS port (default: 443)"
+ }
+ },
+ "required": ["domain"]
+ }
+}
+
+
+def _parse_cert_time(time_str: str) -> datetime:
+ """Parse certificate time string to datetime."""
+ # OpenSSL format: 'Mon DD HH:MM:SS YYYY GMT'
+ return datetime.strptime(time_str, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)
+
+
+def _format_dn(dn_tuple) -> str:
+ """Format a certificate distinguished name tuple into readable string."""
+ parts = []
+ if not dn_tuple:
+ return "(empty)"
+ for rdn in dn_tuple:
+ for attr_type, attr_value in rdn:
+ parts.append(f"{attr_type}={attr_value}")
+ return ", ".join(parts)
+
+
+def _get_san(cert: dict) -> list:
+ """Extract Subject Alternative Names from certificate."""
+ san = []
+ for entry_type, value in cert.get("subjectAltName", ()):
+ san.append(f"{entry_type}:{value}")
+ return san
+
+
+def run(domain: str = "", port: int = 443, **kwargs) -> str:
+ if not domain:
+ return "Error: 'domain' is required."
+
+ # Strip protocol prefix if provided
+ domain = domain.replace("https://", "").replace("http://", "")
+ # Strip path
+ domain = domain.split("/")[0]
+ # Strip port from domain if included
+ if ":" in domain:
+ parts = domain.split(":")
+ domain = parts[0]
+ try:
+ port = int(parts[1])
+ except ValueError:
+ pass
+
+ port = int(port)
+
+ try:
+ # Create SSL context that still retrieves the certificate
+ ctx = ssl.create_default_context()
+ conn = ctx.wrap_socket(socket.socket(socket.AF_INET), server_hostname=domain)
+ conn.settimeout(10.0)
+ conn.connect((domain, port))
+ cert = conn.getpeercert()
+ cipher = conn.cipher()
+ protocol = conn.version()
+ conn.close()
+ except ssl.SSLCertVerificationError as e:
+ # Still try to get cert info even if verification fails
+ try:
+ ctx = ssl.create_default_context()
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+ conn = ctx.wrap_socket(socket.socket(socket.AF_INET), server_hostname=domain)
+ conn.settimeout(10.0)
+ conn.connect((domain, port))
+ # With CERT_NONE, getpeercert() returns empty dict; use binary
+ cert_bin = conn.getpeercert(True)
+ cipher = conn.cipher()
+ protocol = conn.version()
+ conn.close()
+ return (f"Cert Check: {domain}:{port}\n"
+ f"{'=' * 40}\n\n"
+ f"WARNING: Certificate verification FAILED\n"
+ f"Reason: {e}\n\n"
+ f"Protocol: {protocol}\n"
+ f"Cipher: {cipher[0] if cipher else 'unknown'}\n\n"
+ f"The certificate exists but is not trusted.\n"
+ f"This could mean: self-signed, expired, or wrong hostname.")
+ except Exception as e2:
+ return f"Error: could not connect to {domain}:{port}\n SSL error: {e}\n Fallback error: {e2}"
+ except socket.gaierror:
+ return f"Error: cannot resolve hostname '{domain}'."
+ except socket.timeout:
+ return f"Error: connection to {domain}:{port} timed out."
+ except ConnectionRefusedError:
+ return f"Error: connection refused to {domain}:{port}."
+ except Exception as e:
+ return f"Error connecting to {domain}:{port}: {e}"
+
+ if not cert:
+ return f"Error: no certificate data returned from {domain}:{port}."
+
+ # Parse certificate fields
+ subject = _format_dn(cert.get("subject", ()))
+ issuer = _format_dn(cert.get("issuer", ()))
+ not_before_str = cert.get("notBefore", "")
+ not_after_str = cert.get("notAfter", "")
+ serial = cert.get("serialNumber", "unknown")
+ san = _get_san(cert)
+
+ # Calculate expiry
+ now = datetime.now(timezone.utc)
+ try:
+ not_before = _parse_cert_time(not_before_str)
+ not_after = _parse_cert_time(not_after_str)
+ days_remaining = (not_after - now).days
+ total_days = (not_after - not_before).days
+ except Exception:
+ not_before = not_before_str
+ not_after = not_after_str
+ days_remaining = None
+ total_days = None
+
+ # Status determination
+ if days_remaining is not None:
+ if days_remaining < 0:
+ status = "EXPIRED"
+ status_detail = f"Expired {abs(days_remaining)} days ago!"
+ elif days_remaining <= 7:
+ status = "CRITICAL"
+ status_detail = f"Expires in {days_remaining} days!"
+ elif days_remaining <= 30:
+ status = "WARNING"
+ status_detail = f"Expires in {days_remaining} days"
+ else:
+ status = "OK"
+ status_detail = f"{days_remaining} days remaining"
+ else:
+ status = "UNKNOWN"
+ status_detail = "Could not parse dates"
+
+ # Format output
+ lines = [
+ f"Cert Check: {domain}:{port}",
+ "=" * 40,
+ "",
+ f"Status: {status} - {status_detail}",
+ "",
+ f"Subject: {subject}",
+ f"Issuer: {issuer}",
+ f"Serial: {serial}",
+ "",
+ f"Valid From: {not_before_str}",
+ f"Valid Until: {not_after_str}",
+ ]
+
+ if days_remaining is not None:
+ lines.append(f"Remaining: {days_remaining} days")
+ if total_days is not None:
+ lines.append(f"Validity: {total_days} days total")
+
+ if san:
+ lines.append("")
+ lines.append(f"SANs ({len(san)}):")
+ for s in san[:20]: # Cap at 20
+ lines.append(f" {s}")
+ if len(san) > 20:
+ lines.append(f" ... and {len(san) - 20} more")
+
+ if cipher:
+ lines.append("")
+ lines.append(f"Protocol: {protocol}")
+ lines.append(f"Cipher: {cipher[0]}")
+ if len(cipher) > 2:
+ lines.append(f"Bits: {cipher[2]}")
+
+ return "\n".join(lines)
diff --git a/plugins/code_stats.py b/plugins/code_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..564757b1bbc6102b08b6123ce9e971d82ccb3c2e
--- /dev/null
+++ b/plugins/code_stats.py
@@ -0,0 +1,175 @@
+# SPDX-License-Identifier: MIT
+"""
+Code Stats Plugin for TrashClaw
+
+Analyze a codebase directory and return statistics:
+lines of code, file counts by language, largest files,
+TODO/FIXME counts, and complexity indicators.
+
+Useful for understanding a project before diving in.
+Zero external dependencies — pure stdlib.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import os
+import re
+from collections import defaultdict
+
+TOOL_DEF = {
+ "name": "code_stats",
+ "description": "Analyze a codebase directory: lines of code by language, file counts, largest files, TODO/FIXME counts. Useful for understanding a project's scope before working on it.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Directory to analyze (default: current directory)"
+ },
+ "top_n": {
+ "type": "integer",
+ "description": "Number of largest files to show (default: 10)"
+ }
+ },
+ "required": []
+ }
+}
+
+# Extension -> language mapping
+LANG_MAP = {
+ ".py": "Python", ".js": "JavaScript", ".ts": "TypeScript",
+ ".tsx": "TypeScript (JSX)", ".jsx": "JavaScript (JSX)",
+ ".rs": "Rust", ".go": "Go", ".rb": "Ruby", ".java": "Java",
+ ".c": "C", ".h": "C Header", ".cpp": "C++", ".hpp": "C++ Header",
+ ".cs": "C#", ".php": "PHP", ".swift": "Swift", ".kt": "Kotlin",
+ ".lua": "Lua", ".sh": "Shell", ".bash": "Shell", ".zsh": "Shell",
+ ".sql": "SQL", ".html": "HTML", ".css": "CSS", ".scss": "SCSS",
+ ".md": "Markdown", ".json": "JSON", ".yaml": "YAML", ".yml": "YAML",
+ ".toml": "TOML", ".xml": "XML", ".r": "R", ".jl": "Julia",
+ ".pl": "Perl", ".ex": "Elixir", ".exs": "Elixir",
+ ".zig": "Zig", ".nim": "Nim", ".v": "V", ".dart": "Dart",
+}
+
+SKIP_DIRS = {
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "target", "build", "dist", ".next", ".cache", "vendor",
+ ".tox", ".mypy_cache", ".pytest_cache", "coverage",
+}
+
+SKIP_EXTENSIONS = {".min.js", ".min.css", ".map", ".lock"}
+
+
+def _is_binary(filepath, sample_size=8192):
+ """Quick check if a file is binary."""
+ try:
+ with open(filepath, "rb") as f:
+ chunk = f.read(sample_size)
+ if b"\x00" in chunk:
+ return True
+ except Exception:
+ return True
+ return False
+
+
+def run(path: str = ".", top_n: int = 10, **kwargs) -> str:
+ """Analyze codebase and return formatted statistics."""
+ path = os.path.expanduser(path)
+ if not os.path.isabs(path):
+ path = os.path.abspath(path)
+
+ if not os.path.isdir(path):
+ return f"Error: Not a directory: {path}"
+
+ lang_lines = defaultdict(int)
+ lang_files = defaultdict(int)
+ file_sizes = [] # (lines, path)
+ total_files = 0
+ total_lines = 0
+ todo_count = 0
+ fixme_count = 0
+ hack_count = 0
+
+ todo_pattern = re.compile(r"\bTODO\b", re.IGNORECASE)
+ fixme_pattern = re.compile(r"\bFIXME\b", re.IGNORECASE)
+ hack_pattern = re.compile(r"\bHACK\b", re.IGNORECASE)
+
+ for root, dirs, files in os.walk(path):
+ # Skip hidden and vendor dirs
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]
+
+ for fname in files:
+ filepath = os.path.join(root, fname)
+ _, ext = os.path.splitext(fname)
+
+ if ext in SKIP_EXTENSIONS or any(
+ fname.endswith(skip_ext) for skip_ext in SKIP_EXTENSIONS
+ ):
+ continue
+
+ lang = LANG_MAP.get(ext)
+ if not lang:
+ continue
+
+ if _is_binary(filepath):
+ continue
+
+ try:
+ with open(filepath, "r", errors="replace") as f:
+ lines = f.readlines()
+ except Exception:
+ continue
+
+ line_count = len(lines)
+ total_files += 1
+ total_lines += line_count
+ lang_lines[lang] += line_count
+ lang_files[lang] += 1
+
+ rel_path = os.path.relpath(filepath, path)
+ file_sizes.append((line_count, rel_path))
+
+ # Count markers
+ for line in lines:
+ if todo_pattern.search(line):
+ todo_count += 1
+ if fixme_pattern.search(line):
+ fixme_count += 1
+ if hack_pattern.search(line):
+ hack_count += 1
+
+ if total_files == 0:
+ return f"No recognized source files found in {path}"
+
+ # Build output
+ out = []
+ out.append(f"=== Code Stats: {os.path.basename(path)} ===\n")
+ out.append(f"Total: {total_files} files, {total_lines:,} lines\n")
+
+ # Language breakdown (sorted by lines)
+ out.append("Language Breakdown:")
+ sorted_langs = sorted(lang_lines.items(), key=lambda x: -x[1])
+ for lang, lines in sorted_langs:
+ pct = (lines / total_lines) * 100 if total_lines else 0
+ bar = "█" * int(pct / 3)
+ out.append(f" {lang:<20} {lines:>8,} lines ({lang_files[lang]} files) {bar} {pct:.1f}%")
+
+ # Largest files
+ out.append(f"\nTop {top_n} Largest Files:")
+ file_sizes.sort(key=lambda x: -x[0])
+ for lines, fpath in file_sizes[:top_n]:
+ out.append(f" {lines:>6,} lines {fpath}")
+
+ # Markers
+ markers_total = todo_count + fixme_count + hack_count
+ if markers_total > 0:
+ out.append(f"\nCode Markers:")
+ if todo_count:
+ out.append(f" TODO: {todo_count}")
+ if fixme_count:
+ out.append(f" FIXME: {fixme_count}")
+ if hack_count:
+ out.append(f" HACK: {hack_count}")
+
+ return "\n".join(out)
diff --git a/plugins/env_audit.py b/plugins/env_audit.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd1b010b579f4ad90ea8fa909869242a64709e4
--- /dev/null
+++ b/plugins/env_audit.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: MIT
+"""
+Env Audit Plugin for TrashClaw
+
+Scan a directory for common security misconfigurations:
+ - .env files committed to git
+ - Exposed secrets (API keys, passwords, tokens in source)
+ - World-readable private keys
+ - Sensitive files without .gitignore coverage
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import os
+import re
+import stat
+
+TOOL_DEF = {
+ "name": "env_audit",
+ "description": "Scan a directory for common security misconfigurations: .env in git, exposed secrets, world-readable keys, missing .gitignore entries.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "description": "Directory to scan (default: current directory)"
+ },
+ "deep": {
+ "type": "boolean",
+ "description": "If true, scan file contents for secrets (slower). Default: true."
+ }
+ },
+ "required": []
+ }
+}
+
+# Filenames that should never be committed
+SENSITIVE_FILES = [
+ ".env",
+ ".env.local",
+ ".env.production",
+ ".env.staging",
+ ".env.development",
+ "credentials.json",
+ "service-account.json",
+ "secrets.yaml",
+ "secrets.yml",
+ ".netrc",
+ ".npmrc", # can contain tokens
+ ".pypirc", # can contain tokens
+]
+
+# Private key file patterns
+KEY_PATTERNS = [
+ "*.pem",
+ "*.key",
+ "*.p12",
+ "*.pfx",
+ "id_rsa",
+ "id_ed25519",
+ "id_ecdsa",
+ "id_dsa",
+]
+
+# Regex patterns for secrets in file contents
+SECRET_PATTERNS = [
+ (r'(?i)(?:api[_-]?key|apikey)\s*[:=]\s*["\']?[A-Za-z0-9_\-]{16,}', "API key"),
+ (r'(?i)(?:secret|password|passwd|pwd)\s*[:=]\s*["\']?[^\s"\']{8,}', "Password/Secret"),
+ (r'(?i)(?:aws_access_key_id|aws_secret_access_key)\s*[:=]\s*["\']?[A-Za-z0-9/+=]{16,}', "AWS credential"),
+ (r'(?i)bearer\s+[A-Za-z0-9_\-\.]{20,}', "Bearer token"),
+ (r'ghp_[A-Za-z0-9]{36}', "GitHub PAT"),
+ (r'sk-[A-Za-z0-9]{20,}', "OpenAI/Stripe secret key"),
+ (r'(?i)(?:private[_-]?key)\s*[:=]\s*["\']?[A-Za-z0-9_\-/+=]{16,}', "Private key value"),
+ (r'-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----', "Private key block"),
+]
+
+# Extensions to scan for secrets
+SCANNABLE_EXTENSIONS = {
+ ".py", ".js", ".ts", ".jsx", ".tsx", ".rb", ".go", ".java",
+ ".yaml", ".yml", ".json", ".toml", ".ini", ".cfg", ".conf",
+ ".sh", ".bash", ".zsh", ".env", ".properties", ".xml",
+ ".tf", ".hcl", ".dockerfile",
+}
+
+# Directories to skip
+SKIP_DIRS = {
+ ".git", "node_modules", "__pycache__", ".venv", "venv",
+ "env", ".tox", ".mypy_cache", ".pytest_cache", "dist",
+ "build", ".eggs", "*.egg-info",
+}
+
+MAX_FILE_SIZE = 512 * 1024 # 512KB max per file for content scanning
+
+
+def _is_git_tracked(filepath: str, repo_root: str) -> bool:
+ """Check if a file is tracked by git (would be committed)."""
+ try:
+ import subprocess
+ result = subprocess.run(
+ ["git", "ls-files", "--error-unmatch", filepath],
+ cwd=repo_root, capture_output=True, text=True, timeout=5
+ )
+ return result.returncode == 0
+ except Exception:
+ return False # Can't determine; assume not tracked
+
+
+def _is_gitignored(filepath: str, repo_root: str) -> bool:
+ """Check if a file is covered by .gitignore."""
+ try:
+ import subprocess
+ result = subprocess.run(
+ ["git", "check-ignore", "-q", filepath],
+ cwd=repo_root, capture_output=True, text=True, timeout=5
+ )
+ return result.returncode == 0
+ except Exception:
+ return False
+
+
+def _check_permissions(filepath: str) -> str:
+ """Check if file has overly permissive permissions (world-readable)."""
+ try:
+ st = os.stat(filepath)
+ mode = st.st_mode
+ if mode & stat.S_IROTH: # World-readable
+ return f"{oct(mode & 0o777)} (world-readable)"
+ except Exception:
+ pass
+ return ""
+
+
+def _scan_file_contents(filepath: str) -> list:
+ """Scan a file for secret patterns. Returns list of (line_no, pattern_name, snippet)."""
+ findings = []
+ try:
+ size = os.path.getsize(filepath)
+ if size > MAX_FILE_SIZE:
+ return findings
+ with open(filepath, "r", errors="replace") as f:
+ for line_no, line in enumerate(f, 1):
+ for pattern, name in SECRET_PATTERNS:
+ if re.search(pattern, line):
+ # Truncate the line for display
+ snippet = line.strip()
+ if len(snippet) > 100:
+ snippet = snippet[:97] + "..."
+ findings.append((line_no, name, snippet))
+ break # One finding per line is enough
+ except Exception:
+ pass
+ return findings
+
+
+def _find_git_root(path: str) -> str:
+ """Walk up to find .git directory."""
+ current = os.path.abspath(path)
+ while current != os.path.dirname(current):
+ if os.path.isdir(os.path.join(current, ".git")):
+ return current
+ current = os.path.dirname(current)
+ return ""
+
+
+def run(path: str = "", deep: bool = True, **kwargs) -> str:
+ scan_dir = os.path.abspath(path or os.getcwd())
+ if not os.path.isdir(scan_dir):
+ return f"Error: not a directory: {scan_dir}"
+
+ git_root = _find_git_root(scan_dir)
+ has_git = bool(git_root)
+
+ issues = [] # (severity, category, filepath, detail)
+
+ # Walk the directory tree
+ for root, dirs, files in os.walk(scan_dir):
+ # Skip hidden/vendor directories
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith(".")]
+
+ rel_root = os.path.relpath(root, scan_dir)
+
+ for fname in files:
+ filepath = os.path.join(root, fname)
+ rel_path = os.path.relpath(filepath, scan_dir)
+
+ # Check 1: Sensitive files present
+ if fname.lower() in [s.lower() for s in SENSITIVE_FILES]:
+ if has_git:
+ tracked = _is_git_tracked(rel_path, git_root)
+ ignored = _is_gitignored(rel_path, git_root)
+ if tracked:
+ issues.append(("CRITICAL", "sensitive_file_tracked", rel_path,
+ f"Sensitive file is tracked by git!"))
+ elif not ignored:
+ issues.append(("WARNING", "sensitive_file_not_ignored", rel_path,
+ f"Sensitive file exists but is NOT in .gitignore"))
+ else:
+ issues.append(("WARNING", "sensitive_file_present", rel_path,
+ f"Sensitive file found (no git repo to check ignore rules)"))
+
+ # Check 2: Private key files
+ for pat in KEY_PATTERNS:
+ if pat.startswith("*"):
+ if fname.endswith(pat[1:]):
+ perm = _check_permissions(filepath)
+ if perm:
+ issues.append(("WARNING", "key_permissions", rel_path,
+ f"Private key is {perm}"))
+ if has_git and _is_git_tracked(rel_path, git_root):
+ issues.append(("CRITICAL", "key_tracked", rel_path,
+ f"Private key tracked by git!"))
+ break
+ elif fname == pat:
+ perm = _check_permissions(filepath)
+ if perm:
+ issues.append(("WARNING", "key_permissions", rel_path,
+ f"Private key is {perm}"))
+ if has_git and _is_git_tracked(rel_path, git_root):
+ issues.append(("CRITICAL", "key_tracked", rel_path,
+ f"Private key tracked by git!"))
+ break
+
+ # Check 3: Content scanning for secrets
+ if deep:
+ _, ext = os.path.splitext(fname)
+ if ext.lower() in SCANNABLE_EXTENSIONS or fname.lower() in (".env",):
+ findings = _scan_file_contents(filepath)
+ for line_no, pattern_name, snippet in findings:
+ issues.append(("WARNING", "secret_in_source", rel_path,
+ f"Line {line_no}: possible {pattern_name}"))
+
+ # Check 4: .gitignore coverage
+ if has_git:
+ gitignore_path = os.path.join(git_root, ".gitignore")
+ if not os.path.exists(gitignore_path):
+ issues.append(("INFO", "no_gitignore", ".gitignore",
+ "No .gitignore file found in repository"))
+ else:
+ try:
+ with open(gitignore_path, "r") as f:
+ gitignore_content = f.read()
+ recommended = [".env", "*.pem", "*.key", "id_rsa", "credentials.json"]
+ missing = [p for p in recommended if p not in gitignore_content]
+ if missing:
+ issues.append(("INFO", "gitignore_incomplete", ".gitignore",
+ f"Missing recommended patterns: {', '.join(missing)}"))
+ except Exception:
+ pass
+
+ # Format output
+ lines = [f"Env Audit: {scan_dir}", "=" * 50]
+
+ if not issues:
+ lines.append("")
+ lines.append("No issues found. Directory looks clean.")
+ return "\n".join(lines)
+
+ # Group by severity
+ critical = [i for i in issues if i[0] == "CRITICAL"]
+ warnings = [i for i in issues if i[0] == "WARNING"]
+ info = [i for i in issues if i[0] == "INFO"]
+
+ if critical:
+ lines.append("")
+ lines.append(f"CRITICAL ({len(critical)}):")
+ for sev, cat, fpath, detail in critical:
+ lines.append(f" [!] {fpath}: {detail}")
+
+ if warnings:
+ lines.append("")
+ lines.append(f"WARNINGS ({len(warnings)}):")
+ for sev, cat, fpath, detail in warnings:
+ lines.append(f" [*] {fpath}: {detail}")
+
+ if info:
+ lines.append("")
+ lines.append(f"INFO ({len(info)}):")
+ for sev, cat, fpath, detail in info:
+ lines.append(f" [i] {fpath}: {detail}")
+
+ lines.append("")
+ lines.append(f"Total: {len(critical)} critical, {len(warnings)} warnings, {len(info)} info")
+
+ return "\n".join(lines)
diff --git a/plugins/example_weather.py b/plugins/example_weather.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee69d1bacc2936b920354fe19d2cd40a0c5b1c31
--- /dev/null
+++ b/plugins/example_weather.py
@@ -0,0 +1,40 @@
+# SPDX-License-Identifier: MIT
+"""
+Example TrashClaw Plugin — Weather Lookup
+
+Drop this file in ~/.trashclaw/plugins/ to add a weather tool.
+Demonstrates the plugin API. Modify or use as a template.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import urllib.request
+import json
+
+TOOL_DEF = {
+ "name": "weather",
+ "description": "Get current weather for a city using wttr.in (no API key needed).",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "city": {
+ "type": "string",
+ "description": "City name (e.g. 'London', 'New York', 'Tokyo')"
+ }
+ },
+ "required": ["city"]
+ }
+}
+
+
+def run(city: str = "London", **kwargs) -> str:
+ """Fetch weather from wttr.in — free, no auth, returns plain text."""
+ try:
+ url = f"https://wttr.in/{city.replace(' ', '+')}?format=3"
+ req = urllib.request.Request(url, headers={"User-Agent": "TrashClaw"})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ return resp.read().decode("utf-8").strip()
+ except Exception as e:
+ return f"Weather lookup failed: {e}"
diff --git a/plugins/hash.py b/plugins/hash.py
new file mode 100644
index 0000000000000000000000000000000000000000..546366555bb6dcc662e2a4751bf79087af3cb1ce
--- /dev/null
+++ b/plugins/hash.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: MIT
+"""
+Hash Plugin for TrashClaw
+
+Compute cryptographic hashes (MD5, SHA-1, SHA-256, SHA-512) of text or files.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import hashlib
+import os
+
+TOOL_DEF = {
+ "name": "hash",
+ "description": "Compute cryptographic hash (MD5, SHA-1, SHA-256, SHA-512) of text or a file.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "Text to hash"
+ },
+ "file": {
+ "type": "string",
+ "description": "Path to file to hash (optional)"
+ },
+ "algorithm": {
+ "type": "string",
+ "description": "Hash algorithm: md5, sha1, sha256, sha512 (default: sha256)"
+ }
+ },
+ "required": []
+ }
+}
+
+
+def _hash_text(text: str, algorithm: str) -> str:
+ try:
+ h = hashlib.new(algorithm)
+ h.update(text.encode("utf-8"))
+ return h.hexdigest()
+ except ValueError:
+ return f"Error: unsupported algorithm '{algorithm}'"
+
+
+def _hash_file(path: str, algorithm: str) -> str:
+ if not os.path.exists(path):
+ return f"Error: file not found: {path}"
+ try:
+ h = hashlib.new(algorithm)
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(8192), b""):
+ h.update(chunk)
+ return h.hexdigest()
+ except ValueError:
+ return f"Error: unsupported algorithm '{algorithm}'"
+ except Exception as e:
+ return f"Error: {e}"
+
+
+def run(text: str = "", file: str = "", algorithm: str = "sha256", **kwargs) -> str:
+ algorithm = algorithm.lower().replace("-", "")
+ supported = ["md5", "sha1", "sha256", "sha512"]
+
+ if algorithm not in supported:
+ return f"Unsupported algorithm '{algorithm}'. Use: {', '.join(supported)}"
+
+ results = []
+
+ if file:
+ digest = _hash_file(file, algorithm)
+ results.append(f"{algorithm.upper()}({file}):\n{digest}")
+
+ if text:
+ digest = _hash_text(text, algorithm)
+ results.append(f"{algorithm.upper()}(text):\n{digest}")
+
+ if not text and not file:
+ return "Error: provide 'text' or 'file' to hash."
+
+ return "\n\n".join(results)
diff --git a/plugins/http_bench.py b/plugins/http_bench.py
new file mode 100644
index 0000000000000000000000000000000000000000..65f7fe4ca6de2e4a1fee215d11b93604cdbbd4ad
--- /dev/null
+++ b/plugins/http_bench.py
@@ -0,0 +1,194 @@
+# SPDX-License-Identifier: MIT
+"""
+HTTP Bench Plugin for TrashClaw
+
+Simple HTTP benchmark: send N requests to a URL and report latency percentiles
+(p50, p95, p99), success rate, and throughput. Pure stdlib, no dependencies.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import time
+import urllib.request
+import urllib.error
+import statistics
+import ssl
+import concurrent.futures
+
+TOOL_DEF = {
+ "name": "http_bench",
+ "description": "Simple HTTP benchmark. Send N requests to a URL and report p50/p95/p99 latency, success rate, and throughput.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "URL to benchmark (e.g. https://example.com)"
+ },
+ "requests": {
+ "type": "integer",
+ "description": "Number of requests to send (default: 20, max: 500)"
+ },
+ "concurrency": {
+ "type": "integer",
+ "description": "Number of concurrent workers (default: 4, max: 20)"
+ },
+ "method": {
+ "type": "string",
+ "description": "HTTP method: GET or POST (default: GET)"
+ },
+ "timeout": {
+ "type": "number",
+ "description": "Request timeout in seconds (default: 10)"
+ },
+ "insecure": {
+ "type": "boolean",
+ "description": "Skip TLS certificate verification (default: false). Only for self-signed test servers."
+ }
+ },
+ "required": ["url"]
+ }
+}
+
+
+def _percentile(sorted_data: list, pct: float) -> float:
+ """Calculate percentile from sorted data."""
+ if not sorted_data:
+ return 0.0
+ k = (len(sorted_data) - 1) * (pct / 100.0)
+ f = int(k)
+ c = f + 1
+ if c >= len(sorted_data):
+ return sorted_data[f]
+ d = k - f
+ return sorted_data[f] + d * (sorted_data[c] - sorted_data[f])
+
+
+def _make_request(url: str, method: str, req_timeout: float, insecure: bool = False) -> dict:
+ """Make a single HTTP request and return timing info.
+
+ TLS certificates are verified unless insecure is True.
+ """
+ result = {"status": 0, "latency_ms": 0.0, "error": None, "size": 0}
+ try:
+ ctx = ssl.create_default_context()
+ if insecure:
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+
+ req = urllib.request.Request(url, method=method.upper())
+ req.add_header("User-Agent", "TrashClaw-HTTPBench/1.0")
+
+ start = time.monotonic()
+ with urllib.request.urlopen(req, timeout=req_timeout, context=ctx) as resp:
+ body = resp.read()
+ elapsed = time.monotonic() - start
+ result["status"] = resp.status
+ result["latency_ms"] = elapsed * 1000
+ result["size"] = len(body)
+ except urllib.error.HTTPError as e:
+ elapsed = time.monotonic() - start
+ result["status"] = e.code
+ result["latency_ms"] = elapsed * 1000
+ result["error"] = f"HTTP {e.code}"
+ except urllib.error.URLError as e:
+ result["error"] = str(e.reason)
+ except Exception as e:
+ result["error"] = str(e)
+ return result
+
+
+def run(url: str = "", requests: int = 20, concurrency: int = 4,
+ method: str = "GET", timeout: float = 10.0, insecure: bool = False,
+ **kwargs) -> str:
+ if not url:
+ return "Error: 'url' is required."
+
+ if not url.startswith("http://") and not url.startswith("https://"):
+ url = "http://" + url
+
+ requests = min(max(int(requests), 1), 500)
+ concurrency = min(max(int(concurrency), 1), 20)
+ timeout = min(max(float(timeout), 0.5), 60.0)
+ method = method.upper()
+ if method not in ("GET", "POST", "HEAD", "PUT", "DELETE", "PATCH"):
+ method = "GET"
+
+ if isinstance(insecure, str):
+ insecure = insecure.strip().lower() in ("1", "true", "yes", "on")
+ insecure = bool(insecure)
+
+ lines = [f"HTTP Benchmark: {method} {url}",
+ f"Requests: {requests} | Concurrency: {concurrency} | Timeout: {timeout}s"]
+ if insecure and url.startswith("https://"):
+ lines.append("WARNING: TLS certificate verification disabled (insecure=true)")
+ lines += ["-" * 50, ""]
+
+ results = []
+ wall_start = time.monotonic()
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
+ futures = [
+ executor.submit(_make_request, url, method, timeout, insecure)
+ for _ in range(requests)
+ ]
+ for f in concurrent.futures.as_completed(futures):
+ results.append(f.result())
+
+ wall_elapsed = time.monotonic() - wall_start
+
+ # Analyze results
+ successes = [r for r in results if r["error"] is None and 200 <= r["status"] < 400]
+ failures = [r for r in results if r not in successes]
+ latencies = sorted([r["latency_ms"] for r in successes])
+
+ success_rate = len(successes) / len(results) * 100 if results else 0
+
+ if latencies:
+ p50 = _percentile(latencies, 50)
+ p95 = _percentile(latencies, 95)
+ p99 = _percentile(latencies, 99)
+ avg = statistics.mean(latencies)
+ min_lat = min(latencies)
+ max_lat = max(latencies)
+
+ lines.append("Latency (ms):")
+ lines.append(f" min: {min_lat:>8.1f}")
+ lines.append(f" avg: {avg:>8.1f}")
+ lines.append(f" p50: {p50:>8.1f}")
+ lines.append(f" p95: {p95:>8.1f}")
+ lines.append(f" p99: {p99:>8.1f}")
+ lines.append(f" max: {max_lat:>8.1f}")
+ else:
+ lines.append("No successful requests to report latency.")
+
+ lines.append("")
+ lines.append("Results:")
+ lines.append(f" Total: {len(results)}")
+ lines.append(f" Successful: {len(successes)}")
+ lines.append(f" Failed: {len(failures)}")
+ lines.append(f" Success %: {success_rate:.1f}%")
+ lines.append(f" Wall time: {wall_elapsed:.2f}s")
+
+ if wall_elapsed > 0:
+ rps = len(results) / wall_elapsed
+ lines.append(f" Throughput: {rps:.1f} req/s")
+
+ if successes:
+ total_bytes = sum(r["size"] for r in successes)
+ lines.append(f" Avg size: {total_bytes // len(successes):,} bytes")
+
+ # Show error breakdown if any failures
+ if failures:
+ lines.append("")
+ lines.append("Errors:")
+ error_counts = {}
+ for r in failures:
+ err = r["error"] or f"HTTP {r['status']}"
+ error_counts[err] = error_counts.get(err, 0) + 1
+ for err, count in sorted(error_counts.items(), key=lambda x: -x[1]):
+ lines.append(f" {count}x {err}")
+
+ return "\n".join(lines)
diff --git a/plugins/http_request.py b/plugins/http_request.py
new file mode 100644
index 0000000000000000000000000000000000000000..de0c0455d67b303d3cf12ecdb5b7a0c24f464d12
--- /dev/null
+++ b/plugins/http_request.py
@@ -0,0 +1,113 @@
+# SPDX-License-Identifier: MIT
+"""
+HTTP Request Plugin for TrashClaw
+
+Make HTTP requests with custom headers, methods, and body.
+Supports GET, POST, PUT, DELETE, PATCH methods.
+Returns response status, headers, and body.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import urllib.request
+import urllib.error
+import json
+from typing import Optional, Dict, Any
+
+TOOL_DEF = {
+ "name": "http_request",
+ "description": "Make HTTP requests with custom headers, methods, and body. Returns response status, headers, and body (JSON parsed if applicable).",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The URL to request (e.g., 'https://api.example.com/data')"
+ },
+ "method": {
+ "type": "string",
+ "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"],
+ "description": "HTTP method (default: GET)"
+ },
+ "headers": {
+ "type": "object",
+ "description": "Custom headers as key-value pairs (e.g., {'Authorization': 'Bearer token'})",
+ "additionalProperties": {"type": "string"}
+ },
+ "body": {
+ "type": "string",
+ "description": "Request body (will be sent as JSON if Content-Type is application/json)"
+ },
+ "timeout": {
+ "type": "integer",
+ "description": "Request timeout in seconds (default: 30)"
+ }
+ },
+ "required": ["url"]
+ }
+}
+
+
+def run(url: str, method: str = "GET", headers: Optional[Dict[str, str]] = None,
+ body: Optional[str] = None, timeout: int = 30, **kwargs) -> str:
+ """
+ Make an HTTP request and return formatted response.
+
+ Args:
+ url: The URL to request
+ method: HTTP method (GET, POST, PUT, DELETE, PATCH)
+ headers: Custom headers dict
+ body: Request body string
+ timeout: Request timeout in seconds
+
+ Returns:
+ Formatted response string with status, headers, and body
+ """
+ # Prepare headers
+ req_headers = {"User-Agent": "TrashClaw-HTTP/1.0"}
+ if headers:
+ req_headers.update(headers)
+
+ # Prepare body
+ data = None
+ if body:
+ data = body.encode("utf-8")
+ if "Content-Type" not in req_headers:
+ req_headers["Content-Type"] = "application/json"
+
+ # Create request
+ req = urllib.request.Request(url, data=data, headers=req_headers, method=method.upper())
+
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ status = resp.status
+ resp_headers = dict(resp.headers)
+ raw_body = resp.read().decode("utf-8", errors="replace")
+
+ # Try to parse JSON
+ try:
+ parsed_body = json.loads(raw_body)
+ body_str = json.dumps(parsed_body, indent=2, ensure_ascii=False)
+ except (json.JSONDecodeError, ValueError):
+ body_str = raw_body[:2000] # Limit response size
+ if len(raw_body) > 2000:
+ body_str += f"\n... (truncated, {len(raw_body)} total chars)"
+
+ # Format output
+ result = f"HTTP {method.upper()} {url}\n"
+ result += f"Status: {status}\n"
+ result += f"Headers:\n"
+ for k, v in list(resp_headers.items())[:10]: # Limit headers shown
+ result += f" {k}: {v}\n"
+ result += f"\nBody:\n{body_str}"
+
+ return result
+
+ except urllib.error.HTTPError as e:
+ return f"HTTP Error {e.code}: {e.reason}\nURL: {url}"
+ except urllib.error.URLError as e:
+ return f"URL Error: {e.reason}\nURL: {url}"
+ except Exception as e:
+ return f"Request failed: {type(e).__name__}: {e}"
diff --git a/plugins/json_diff.py b/plugins/json_diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..628a2812643143215bc79b5b959522401630d0ac
--- /dev/null
+++ b/plugins/json_diff.py
@@ -0,0 +1,151 @@
+# SPDX-License-Identifier: MIT
+"""
+JSON Diff Plugin for TrashClaw
+
+Diff two JSON files or strings showing added, removed, and changed keys.
+Handles nested structures with dot-path notation.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import json
+import os
+
+TOOL_DEF = {
+ "name": "json_diff",
+ "description": "Diff two JSON files or strings. Shows added, removed, and changed keys with dot-path notation for nested structures.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "file_a": {
+ "type": "string",
+ "description": "Path to first JSON file (or use json_a for inline JSON)"
+ },
+ "file_b": {
+ "type": "string",
+ "description": "Path to second JSON file (or use json_b for inline JSON)"
+ },
+ "json_a": {
+ "type": "string",
+ "description": "First JSON string (alternative to file_a)"
+ },
+ "json_b": {
+ "type": "string",
+ "description": "Second JSON string (alternative to file_b)"
+ }
+ },
+ "required": []
+ }
+}
+
+
+def _flatten(obj, prefix=""):
+ """Flatten a nested dict/list into dot-path keys."""
+ items = {}
+ if isinstance(obj, dict):
+ for k, v in obj.items():
+ new_key = f"{prefix}.{k}" if prefix else k
+ if isinstance(v, (dict, list)):
+ items.update(_flatten(v, new_key))
+ else:
+ items[new_key] = v
+ elif isinstance(obj, list):
+ for i, v in enumerate(obj):
+ new_key = f"{prefix}[{i}]"
+ if isinstance(v, (dict, list)):
+ items.update(_flatten(v, new_key))
+ else:
+ items[new_key] = v
+ else:
+ items[prefix] = obj
+ return items
+
+
+def _load_json(file_path: str = "", json_str: str = "", label: str = "input"):
+ """Load JSON from file or string. Returns (data, error_msg)."""
+ if file_path:
+ if not os.path.exists(file_path):
+ return None, f"Error: file not found: {file_path}"
+ try:
+ with open(file_path, "r") as f:
+ return json.load(f), None
+ except json.JSONDecodeError as e:
+ return None, f"Error: invalid JSON in {file_path}: {e}"
+ except Exception as e:
+ return None, f"Error reading {file_path}: {e}"
+ elif json_str:
+ try:
+ return json.loads(json_str), None
+ except json.JSONDecodeError as e:
+ return None, f"Error: invalid JSON in {label}: {e}"
+ return None, f"Error: no {label} provided (use file or inline JSON)."
+
+
+def _format_value(v):
+ """Format a value for display, truncating long strings."""
+ s = json.dumps(v)
+ if len(s) > 80:
+ s = s[:77] + "..."
+ return s
+
+
+def run(file_a: str = "", file_b: str = "", json_a: str = "", json_b: str = "", **kwargs) -> str:
+ data_a, err = _load_json(file_a, json_a, "A")
+ if err:
+ return err
+ data_b, err = _load_json(file_b, json_b, "B")
+ if err:
+ return err
+
+ flat_a = _flatten(data_a)
+ flat_b = _flatten(data_b)
+
+ keys_a = set(flat_a.keys())
+ keys_b = set(flat_b.keys())
+
+ added = sorted(keys_b - keys_a)
+ removed = sorted(keys_a - keys_b)
+ common = sorted(keys_a & keys_b)
+
+ changed = []
+ for k in common:
+ if flat_a[k] != flat_b[k]:
+ changed.append(k)
+
+ if not added and not removed and not changed:
+ return "No differences found. The JSON structures are identical."
+
+ lines = ["JSON Diff Results", "=" * 40]
+
+ label_a = file_a or "(inline A)"
+ label_b = file_b or "(inline B)"
+ lines.append(f"A: {label_a}")
+ lines.append(f"B: {label_b}")
+ lines.append("")
+
+ if added:
+ lines.append(f"ADDED ({len(added)} keys, only in B):")
+ for k in added:
+ lines.append(f" + {k}: {_format_value(flat_b[k])}")
+ lines.append("")
+
+ if removed:
+ lines.append(f"REMOVED ({len(removed)} keys, only in A):")
+ for k in removed:
+ lines.append(f" - {k}: {_format_value(flat_a[k])}")
+ lines.append("")
+
+ if changed:
+ lines.append(f"CHANGED ({len(changed)} keys):")
+ for k in changed:
+ lines.append(f" ~ {k}:")
+ lines.append(f" A: {_format_value(flat_a[k])}")
+ lines.append(f" B: {_format_value(flat_b[k])}")
+ lines.append("")
+
+ summary = f"Summary: +{len(added)} added, -{len(removed)} removed, ~{len(changed)} changed"
+ lines.append(summary)
+
+ return "\n".join(lines)
diff --git a/plugins/json_format.py b/plugins/json_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1fb4b2b058545d3bf5b72e20d88fedd39a9e06d
--- /dev/null
+++ b/plugins/json_format.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: MIT
+"""
+JSON Format Plugin for TrashClaw
+
+Pretty-print, validate, minify, or extract keys from JSON text.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import json
+
+TOOL_DEF = {
+ "name": "json_format",
+ "description": "Pretty-print, validate, minify, or extract keys from JSON text.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "JSON text to process"
+ },
+ "action": {
+ "type": "string",
+ "description": "Action: pretty (default), minify, validate, keys"
+ },
+ "indent": {
+ "type": "integer",
+ "description": "Indentation spaces for pretty mode (default: 2)"
+ }
+ },
+ "required": ["text"]
+ }
+}
+
+
+def run(text: str = "", action: str = "pretty", indent: int = 2, **kwargs) -> str:
+ if not text:
+ return "Error: provide 'text' to format."
+
+ action = action.lower().strip()
+
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError as e:
+ return f"Invalid JSON: {e}"
+
+ if action == "pretty":
+ return json.dumps(data, indent=indent, ensure_ascii=False)
+
+ elif action == "minify":
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=False)
+
+ elif action == "validate":
+ kind = type(data).__name__
+ if isinstance(data, dict):
+ return f"Valid JSON object with {len(data)} keys: {', '.join(list(data.keys())[:10])}"
+ elif isinstance(data, list):
+ return f"Valid JSON array with {len(data)} items"
+ else:
+ return f"Valid JSON {kind}: {data}"
+
+ elif action == "keys":
+ if not isinstance(data, dict):
+ return "Error: 'keys' action requires a JSON object (dict)"
+ return "\n".join(data.keys())
+
+ else:
+ return f"Unknown action '{action}'. Use: pretty, minify, validate, keys"
diff --git a/plugins/markdown_table.py b/plugins/markdown_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..172f8b2e1c546636610347807e7c4eec5d00d16a
--- /dev/null
+++ b/plugins/markdown_table.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: MIT
+"""
+TrashClaw Plugin — Markdown Table Formatter
+
+Converts CSV data or raw text into clean markdown tables.
+Useful for formatting output from other tools into readable reports.
+"""
+
+TOOL_DEF = {
+ "name": "markdown_table",
+ "description": "Convert CSV text or structured data into a formatted markdown table. Supports alignment and header detection.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "data": {
+ "type": "string",
+ "description": "CSV or tab-separated data. First row treated as headers."
+ },
+ "delimiter": {
+ "type": "string",
+ "description": "Field delimiter (default: auto-detect comma or tab)"
+ },
+ "align": {
+ "type": "string",
+ "description": "Column alignment: 'left', 'right', 'center' (default: left)"
+ }
+ },
+ "required": ["data"]
+ }
+}
+
+
+def run(data: str = "", delimiter: str = "", align: str = "left", **kwargs) -> str:
+ """Convert structured text data into a markdown table."""
+ try:
+ lines = [l.strip() for l in data.strip().split("\n") if l.strip()]
+ if not lines:
+ return "Error: No data provided"
+
+ # Auto-detect delimiter
+ if not delimiter:
+ if "\t" in lines[0]:
+ delimiter = "\t"
+ elif "," in lines[0]:
+ delimiter = ","
+ elif "|" in lines[0]:
+ delimiter = "|"
+ else:
+ delimiter = ","
+
+ rows = []
+ for line in lines:
+ cells = [c.strip() for c in line.split(delimiter)]
+ rows.append(cells)
+
+ if not rows:
+ return "Error: Could not parse data"
+
+ # Normalize column count
+ max_cols = max(len(r) for r in rows)
+ for r in rows:
+ while len(r) < max_cols:
+ r.append("")
+
+ # Calculate column widths
+ widths = [max(len(r[i]) for r in rows) for i in range(max_cols)]
+ widths = [max(w, 3) for w in widths] # minimum 3 chars
+
+ # Build alignment markers
+ if align == "right":
+ sep = ["-" * (w - 1) + ":" for w in widths]
+ elif align == "center":
+ sep = [":" + "-" * (w - 2) + ":" for w in widths]
+ else:
+ sep = ["-" * w for w in widths]
+
+ # Format header
+ header = "| " + " | ".join(rows[0][i].ljust(widths[i]) for i in range(max_cols)) + " |"
+ separator = "| " + " | ".join(sep) + " |"
+
+ # Format data rows
+ table_rows = []
+ for row in rows[1:]:
+ formatted = "| " + " | ".join(row[i].ljust(widths[i]) for i in range(max_cols)) + " |"
+ table_rows.append(formatted)
+
+ result = [header, separator] + table_rows
+ return "\n".join(result)
+ except Exception as e:
+ return f"Table formatting failed: {e}"
diff --git a/plugins/port_scan.py b/plugins/port_scan.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d6e558cf509378bace6e4dff8f5e1f019bdf5b7
--- /dev/null
+++ b/plugins/port_scan.py
@@ -0,0 +1,137 @@
+# SPDX-License-Identifier: MIT
+"""
+Port Scan Plugin for TrashClaw
+
+Check if common ports are open on a host using pure sockets (no nmap).
+Useful for quick connectivity checks and service discovery.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import socket
+
+TOOL_DEF = {
+ "name": "port_scan",
+ "description": "Check if common ports are open on a host. Pure socket-based, no nmap needed. Specify a host and optionally a comma-separated list of ports.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "host": {
+ "type": "string",
+ "description": "Hostname or IP address to scan"
+ },
+ "ports": {
+ "type": "string",
+ "description": "Comma-separated list of ports to check (default: common ports 22,80,443,8080,3306,5432,6379,27017)"
+ },
+ "timeout": {
+ "type": "number",
+ "description": "Connection timeout in seconds per port (default: 1.5)"
+ }
+ },
+ "required": ["host"]
+ }
+}
+
+# Well-known port labels
+PORT_LABELS = {
+ 21: "FTP",
+ 22: "SSH",
+ 25: "SMTP",
+ 53: "DNS",
+ 80: "HTTP",
+ 110: "POP3",
+ 143: "IMAP",
+ 443: "HTTPS",
+ 993: "IMAPS",
+ 995: "POP3S",
+ 3306: "MySQL",
+ 3389: "RDP",
+ 5432: "PostgreSQL",
+ 5672: "RabbitMQ",
+ 6379: "Redis",
+ 8080: "HTTP-Alt",
+ 8443: "HTTPS-Alt",
+ 8099: "Custom",
+ 9090: "Prometheus",
+ 9200: "Elasticsearch",
+ 11211: "Memcached",
+ 27017: "MongoDB",
+}
+
+DEFAULT_PORTS = [22, 80, 443, 8080, 3306, 5432, 6379, 27017]
+
+
+def _check_port(host: str, port: int, timeout: float) -> bool:
+ """Return True if port is open (accepts TCP connection)."""
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(timeout)
+ result = s.connect_ex((host, port))
+ return result == 0
+ except (socket.gaierror, socket.herror, OSError):
+ return False
+
+
+def run(host: str = "", ports: str = "", timeout: float = 1.5, **kwargs) -> str:
+ if not host:
+ return "Error: 'host' is required."
+
+ # Parse ports
+ if ports:
+ try:
+ port_list = [int(p.strip()) for p in ports.split(",") if p.strip()]
+ except ValueError:
+ return "Error: 'ports' must be comma-separated integers (e.g. '22,80,443')."
+ else:
+ port_list = DEFAULT_PORTS
+
+ if not port_list:
+ return "Error: no ports specified."
+
+ if len(port_list) > 100:
+ return "Error: max 100 ports per scan."
+
+ timeout = float(timeout)
+ if timeout <= 0 or timeout > 30:
+ timeout = 1.5
+
+ # Resolve hostname first to give a clear error
+ try:
+ ip = socket.gethostbyname(host)
+ except socket.gaierror:
+ return f"Error: cannot resolve hostname '{host}'."
+
+ results_open = []
+ results_closed = []
+
+ for port in sorted(port_list):
+ label = PORT_LABELS.get(port, "")
+ is_open = _check_port(ip, port, timeout)
+ tag = f" ({label})" if label else ""
+ line = f" {port:>5}/tcp{tag}"
+ if is_open:
+ results_open.append(f"{line} OPEN")
+ else:
+ results_closed.append(f"{line} closed")
+
+ header = f"Port scan: {host} ({ip})\n"
+ header += f"Ports checked: {len(port_list)} | Timeout: {timeout}s\n"
+ header += "-" * 40
+
+ lines = [header, ""]
+ if results_open:
+ lines.append("OPEN:")
+ lines.extend(results_open)
+ if results_closed:
+ if results_open:
+ lines.append("")
+ lines.append("CLOSED:")
+ lines.extend(results_closed)
+
+ summary = f"\n\nSummary: {len(results_open)} open, {len(results_closed)} closed"
+ lines.append(summary)
+
+ return "\n".join(lines)
diff --git a/plugins/regex_test.py b/plugins/regex_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f33410ec5f07c8dbc8f278134e4994bb179ebe8
--- /dev/null
+++ b/plugins/regex_test.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: MIT
+"""
+Regex Test Plugin for TrashClaw
+
+Test regular expressions against input text. Shows matches, groups, and positions.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str
+"""
+
+import re
+
+TOOL_DEF = {
+ "name": "regex_test",
+ "description": "Test a regular expression pattern against input text. Shows all matches with positions and groups.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Regular expression pattern to test"
+ },
+ "text": {
+ "type": "string",
+ "description": "Text to match against"
+ },
+ "flags": {
+ "type": "string",
+ "description": "Regex flags: i (ignore case), m (multiline), s (dotall), x (verbose). Combine: 'im'"
+ }
+ },
+ "required": ["pattern", "text"]
+ }
+}
+
+
+def _parse_flags(flags_str: str) -> int:
+ flag_map = {
+ "i": re.IGNORECASE,
+ "m": re.MULTILINE,
+ "s": re.DOTALL,
+ "x": re.VERBOSE,
+ }
+ result = 0
+ for ch in flags_str.lower():
+ if ch in flag_map:
+ result |= flag_map[ch]
+ return result
+
+
+def run(pattern: str = "", text: str = "", flags: str = "", **kwargs) -> str:
+ if not pattern:
+ return "Error: 'pattern' is required."
+ if not text:
+ return "Error: 'text' is required."
+
+ try:
+ compiled = re.compile(pattern, _parse_flags(flags))
+ except re.error as e:
+ return f"Regex compile error: {e}"
+
+ matches = list(compiled.finditer(text))
+
+ if not matches:
+ return f"Pattern: /{pattern}/{''.join(sorted(flags.lower()))}\nNo matches found."
+
+ lines = [
+ f"Pattern: /{pattern}/{''.join(sorted(flags.lower()))}",
+ f"Matches: {len(matches)}",
+ "",
+ ]
+
+ for i, m in enumerate(matches[:50]): # cap at 50 matches
+ line = f" [{i}] \"{m.group()}\" at {m.start()}-{m.end()}"
+ if m.groups():
+ groups = ", ".join(
+ f"${j+1}=\"{g}\"" for j, g in enumerate(m.groups()) if g is not None
+ )
+ line += f" groups: {groups}"
+ if m.groupdict():
+ named = ", ".join(
+ f"{k}=\"{v}\"" for k, v in m.groupdict().items() if v is not None
+ )
+ if named:
+ line += f" named: {named}"
+ lines.append(line)
+
+ if len(matches) > 50:
+ lines.append(f" ... and {len(matches) - 50} more matches")
+
+ return "\n".join(lines)
diff --git a/plugins/system_info.py b/plugins/system_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cebc37dfdb7fd491ab52e6d6b3dac2c94eccf3a
--- /dev/null
+++ b/plugins/system_info.py
@@ -0,0 +1,196 @@
+# SPDX-License-Identifier: MIT
+"""
+System Info Plugin for TrashClaw
+
+Provides detailed system and hardware information.
+Cross-platform support for Windows, macOS, and Linux.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str (called with the parsed arguments)
+"""
+
+import platform
+import os
+import sys
+from datetime import datetime
+
+TOOL_DEF = {
+ "name": "system_info",
+ "description": "Get detailed system and hardware information including OS, CPU, memory, and environment details.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "detailed": {
+ "type": "boolean",
+ "description": "Include detailed information (default: false)"
+ }
+ },
+ "required": []
+ }
+}
+
+
+def _get_cpu_info() -> str:
+ """Get CPU information based on platform."""
+ system = platform.system()
+
+ if system == "Darwin": # macOS
+ import subprocess
+ try:
+ result = subprocess.run(
+ ["sysctl", "-n", "machdep.cpu.brand_string"],
+ capture_output=True, text=True, timeout=5
+ )
+ if result.returncode == 0:
+ return result.stdout.strip()
+ except Exception:
+ pass
+
+ elif system == "Linux":
+ try:
+ with open("/proc/cpuinfo", "r") as f:
+ for line in f:
+ if "model name" in line.lower():
+ return line.split(":")[1].strip()
+ except Exception:
+ pass
+
+ elif system == "Windows":
+ import subprocess
+ try:
+ result = subprocess.run(
+ ["wmic", "cpu", "get", "name"],
+ capture_output=True, text=True, timeout=10
+ )
+ if result.returncode == 0:
+ lines = result.stdout.strip().split("\n")
+ if len(lines) > 1:
+ return lines[1].strip()
+ except Exception:
+ pass
+
+ return platform.processor() or "Unknown CPU"
+
+
+def _get_memory_info() -> str:
+ """Get memory information based on platform."""
+ system = platform.system()
+
+ if system == "Darwin": # macOS
+ import subprocess
+ try:
+ result = subprocess.run(
+ ["sysctl", "-n", "hw.memsize"],
+ capture_output=True, text=True, timeout=5
+ )
+ if result.returncode == 0:
+ total_bytes = int(result.stdout.strip())
+ return f"{total_bytes / (1024**3):.1f} GB"
+ except Exception:
+ pass
+
+ elif system == "Linux":
+ try:
+ with open("/proc/meminfo", "r") as f:
+ for line in f:
+ if line.startswith("MemTotal:"):
+ kb = int(line.split()[1])
+ return f"{kb / (1024**2):.1f} GB"
+ except Exception:
+ pass
+
+ elif system == "Windows":
+ import subprocess
+ try:
+ result = subprocess.run(
+ ["wmic", "OS", "get", "TotalVisibleMemorySize"],
+ capture_output=True, text=True, timeout=10
+ )
+ if result.returncode == 0:
+ lines = result.stdout.strip().split("\n")
+ if len(lines) > 1:
+ kb = int(lines[1].strip())
+ return f"{kb / (1024**2):.1f} GB"
+ except Exception:
+ pass
+
+ return "Unknown"
+
+
+def _get_disk_info() -> str:
+ """Get disk usage for root/home drive."""
+ try:
+ import shutil
+ # Use CWD or root depending on platform
+ path = "C:\\" if platform.system() == "Windows" else "/"
+ total, used, free = shutil.disk_usage(path)
+ return f"{free / (1024**3):.1f} GB free of {total / (1024**3):.1f} GB"
+ except Exception:
+ return "Unknown"
+
+
+def run(detailed: bool = False, **kwargs) -> str:
+ """
+ Get system and hardware information.
+
+ Args:
+ detailed: Include extra details like environment variables
+
+ Returns:
+ Formatted system information string
+ """
+ info = []
+ info.append("=== System Information ===\n")
+
+ # Basic platform info
+ info.append(f"OS: {platform.system()} {platform.release()}")
+ info.append(f"Version: {platform.version()}")
+ info.append(f"Architecture: {platform.machine()}")
+ info.append(f"Processor: {_get_cpu_info()}")
+ info.append(f"Memory: {_get_memory_info()}")
+ info.append(f"Disk: {_get_disk_info()}")
+
+ # Python info
+ info.append(f"\nPython: {platform.python_version()}")
+ info.append(f"Python Path: {sys.executable}")
+
+ # Hostname
+ info.append(f"\nHostname: {platform.node()}")
+
+ # Current user
+ try:
+ import getpass
+ info.append(f"User: {getpass.getuser()}")
+ except Exception:
+ pass
+
+ # Boot time
+ if platform.system() != "Windows":
+ try:
+ import subprocess
+ result = subprocess.run(
+ ["uptime", "-s"],
+ capture_output=True, text=True, timeout=5
+ )
+ if result.returncode == 0:
+ info.append(f"Boot Time: {result.stdout.strip()}")
+ except Exception:
+ pass
+
+ if detailed:
+ info.append("\n=== Environment ===")
+ env_vars = ["PATH", "HOME", "USER", "SHELL", "EDITOR"]
+ for var in env_vars:
+ val = os.environ.get(var)
+ if val:
+ info.append(f"{var}: {val[:100]}{'...' if len(val) > 100 else ''}")
+
+ info.append("\n=== CPU Cores ===")
+ try:
+ import multiprocessing
+ info.append(f"Cores: {multiprocessing.cpu_count()}")
+ except Exception:
+ pass
+
+ return "\n".join(info)
diff --git a/plugins/text_diff.py b/plugins/text_diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..77de732736d604ad4ee8bb2d90f4deb8e34929f0
--- /dev/null
+++ b/plugins/text_diff.py
@@ -0,0 +1,53 @@
+# SPDX-License-Identifier: MIT
+"""
+TrashClaw Plugin — Text Diff
+
+Compare two strings or file contents and show differences.
+Useful for reviewing changes before committing.
+"""
+
+import difflib
+
+TOOL_DEF = {
+ "name": "text_diff",
+ "description": "Compare two text blocks and show a unified diff of differences. Useful for comparing before/after changes.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text_a": {
+ "type": "string",
+ "description": "Original text (before changes)"
+ },
+ "text_b": {
+ "type": "string",
+ "description": "Modified text (after changes)"
+ },
+ "context_lines": {
+ "type": "integer",
+ "description": "Number of context lines around changes (default: 3)"
+ }
+ },
+ "required": ["text_a", "text_b"]
+ }
+}
+
+
+def run(text_a: str = "", text_b: str = "", context_lines: int = 3, **kwargs) -> str:
+ """Generate a unified diff between two text blocks."""
+ try:
+ lines_a = text_a.splitlines(keepends=True)
+ lines_b = text_b.splitlines(keepends=True)
+
+ diff = list(difflib.unified_diff(
+ lines_a, lines_b,
+ fromfile="original",
+ tofile="modified",
+ n=context_lines
+ ))
+
+ if not diff:
+ return "No differences found — texts are identical."
+
+ return "".join(diff)
+ except Exception as e:
+ return f"Diff failed: {e}"
diff --git a/plugins/timer.py b/plugins/timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9938d28d6f3273c8b0389fd83d4e43b5152421b0
--- /dev/null
+++ b/plugins/timer.py
@@ -0,0 +1,72 @@
+# SPDX-License-Identifier: MIT
+"""
+TrashClaw Plugin — Timer
+
+Measure elapsed time for operations. Start, check, and stop timers
+to benchmark how long tasks take.
+"""
+
+import time
+import json
+
+# Simple in-memory timer storage
+_timers = {}
+
+TOOL_DEF = {
+ "name": "timer",
+ "description": "Start, check, or stop a named timer. Useful for benchmarking operations, measuring how long tasks take, or setting reminders.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "description": "Action: 'start', 'check', 'stop', or 'list'"
+ },
+ "name": {
+ "type": "string",
+ "description": "Timer name (default: 'default')"
+ }
+ },
+ "required": ["action"]
+ }
+}
+
+
+def run(action: str = "start", name: str = "default", **kwargs) -> str:
+ """Manage named timers for benchmarking."""
+ try:
+ if action == "start":
+ _timers[name] = time.time()
+ return f"Timer '{name}' started."
+
+ elif action == "check":
+ if name not in _timers:
+ return f"Timer '{name}' not found. Start it first."
+ elapsed = time.time() - _timers[name]
+ return f"Timer '{name}': {elapsed:.2f}s elapsed (still running)"
+
+ elif action == "stop":
+ if name not in _timers:
+ return f"Timer '{name}' not found. Start it first."
+ elapsed = time.time() - _timers.pop(name)
+ if elapsed < 60:
+ return f"Timer '{name}' stopped: {elapsed:.2f} seconds"
+ elif elapsed < 3600:
+ return f"Timer '{name}' stopped: {elapsed / 60:.1f} minutes ({elapsed:.1f}s)"
+ else:
+ return f"Timer '{name}' stopped: {elapsed / 3600:.1f} hours ({elapsed:.0f}s)"
+
+ elif action == "list":
+ if not _timers:
+ return "No active timers."
+ now = time.time()
+ lines = []
+ for n, t in _timers.items():
+ elapsed = now - t
+ lines.append(f" {n}: {elapsed:.1f}s running")
+ return "Active timers:\n" + "\n".join(lines)
+
+ else:
+ return f"Unknown action '{action}'. Use: start, check, stop, list"
+ except Exception as e:
+ return f"Timer error: {e}"
diff --git a/plugins/timestamp.py b/plugins/timestamp.py
new file mode 100644
index 0000000000000000000000000000000000000000..091028ac085276a61c274a552b379d01ef8efbd0
--- /dev/null
+++ b/plugins/timestamp.py
@@ -0,0 +1,98 @@
+# SPDX-License-Identifier: MIT
+"""
+Timestamp Plugin for TrashClaw
+
+Convert between Unix timestamps and human-readable dates. Show current time.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str
+"""
+
+import time
+from datetime import datetime, timezone
+
+TOOL_DEF = {
+ "name": "timestamp",
+ "description": "Convert between Unix timestamps and human-readable dates, or show current time.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "unix": {
+ "type": "number",
+ "description": "Unix timestamp (seconds) to convert to human date"
+ },
+ "date": {
+ "type": "string",
+ "description": "Human date string (ISO 8601, e.g. '2026-03-25T12:00:00') to convert to Unix"
+ },
+ "now": {
+ "type": "boolean",
+ "description": "If true, show current time in multiple formats"
+ }
+ },
+ "required": []
+ }
+}
+
+
+def run(unix: float = None, date: str = "", now: bool = False, **kwargs) -> str:
+ results = []
+
+ if now or (unix is None and not date):
+ ts = time.time()
+ dt = datetime.fromtimestamp(ts, tz=timezone.utc)
+ local_dt = datetime.fromtimestamp(ts)
+ results.append(
+ f"Current Time:\n"
+ f" Unix: {int(ts)}\n"
+ f" UTC: {dt.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
+ f" Local: {local_dt.strftime('%Y-%m-%d %H:%M:%S')}"
+ )
+
+ if unix is not None:
+ try:
+ dt_utc = datetime.fromtimestamp(float(unix), tz=timezone.utc)
+ dt_local = datetime.fromtimestamp(float(unix))
+ results.append(
+ f"Unix {int(unix)} =\n"
+ f" UTC: {dt_utc.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
+ f" Local: {dt_local.strftime('%Y-%m-%d %H:%M:%S')}\n"
+ f" ISO: {dt_utc.isoformat()}"
+ )
+ except (ValueError, OSError, OverflowError) as e:
+ results.append(f"Error converting unix timestamp: {e}")
+
+ if date:
+ formats = [
+ "%Y-%m-%dT%H:%M:%S",
+ "%Y-%m-%dT%H:%M:%SZ",
+ "%Y-%m-%d %H:%M:%S",
+ "%Y-%m-%d",
+ "%d/%m/%Y %H:%M:%S",
+ "%d/%m/%Y",
+ "%m/%d/%Y",
+ ]
+ parsed = None
+ for fmt in formats:
+ try:
+ parsed = datetime.strptime(date.strip(), fmt)
+ break
+ except ValueError:
+ continue
+
+ if parsed:
+ ts = int(parsed.timestamp())
+ results.append(
+ f"'{date}' =\n"
+ f" Unix: {ts}\n"
+ f" Parsed: {parsed.strftime('%Y-%m-%d %H:%M:%S')}\n"
+ f" ISO: {parsed.isoformat()}"
+ )
+ else:
+ results.append(
+ f"Error: could not parse '{date}'. "
+ f"Supported formats: ISO 8601, YYYY-MM-DD, DD/MM/YYYY, MM/DD/YYYY"
+ )
+
+ return "\n\n".join(results) if results else "Error: provide 'unix', 'date', or set 'now' to true."
diff --git a/plugins/word_count.py b/plugins/word_count.py
new file mode 100644
index 0000000000000000000000000000000000000000..94bb3cbd005b2438cc87d5d41110bc0e5229dc38
--- /dev/null
+++ b/plugins/word_count.py
@@ -0,0 +1,69 @@
+# SPDX-License-Identifier: MIT
+"""
+Word Count Plugin for TrashClaw
+
+Count words, characters, lines, sentences, and paragraphs in text or a file.
+
+Plugin contract:
+ TOOL_DEF = dict with name, description, parameters (OpenAI function schema)
+ run(**kwargs) -> str
+"""
+
+import os
+import re
+
+TOOL_DEF = {
+ "name": "word_count",
+ "description": "Count words, characters, lines, sentences, and paragraphs in text or a file.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "Text to analyze"
+ },
+ "file": {
+ "type": "string",
+ "description": "Path to file to analyze (optional, used instead of text)"
+ }
+ },
+ "required": []
+ }
+}
+
+
+def _count(text: str) -> dict:
+ lines = text.split("\n")
+ words = text.split()
+ sentences = [s.strip() for s in re.split(r'[.!?]+', text) if s.strip()]
+ paragraphs = [p.strip() for p in re.split(r'\n\s*\n', text) if p.strip()]
+ return {
+ "characters": len(text),
+ "characters_no_spaces": len(text.replace(" ", "").replace("\t", "")),
+ "words": len(words),
+ "lines": len(lines),
+ "sentences": len(sentences),
+ "paragraphs": len(paragraphs),
+ }
+
+
+def run(text: str = "", file: str = "", **kwargs) -> str:
+ if file:
+ if not os.path.exists(file):
+ return f"Error: file not found: {file}"
+ try:
+ with open(file, "r", encoding="utf-8", errors="replace") as f:
+ text = f.read()
+ except Exception as e:
+ return f"Error reading file: {e}"
+
+ if not text:
+ return "Error: provide 'text' or 'file' to analyze."
+
+ stats = _count(text)
+ source = f" ({file})" if file else ""
+ lines = [f"Word Count{source}:"]
+ for key, val in stats.items():
+ label = key.replace("_", " ").title()
+ lines.append(f" {label}: {val:,}")
+ return "\n".join(lines)
diff --git a/scripts/apply-metal-fix.sh b/scripts/apply-metal-fix.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d3f346caf47718447e15f7925fd52b4c975faa62
--- /dev/null
+++ b/scripts/apply-metal-fix.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+# SPDX-License-Identifier: MIT
+# apply-metal-fix.sh - Apply StorageModeManaged fix for discrete AMD GPUs
+# Reference: https://github.com/ggml-org/llama.cpp/pull/20615
+#
+# This script applies the 3-line Metal fix for discrete AMD GPUs
+# (Mac Pro 2013, iMac 2014-2019, MacBook Pro 2015-2019)
+#
+# Usage: ./apply-metal-fix.sh [llama.cpp directory]
+
+set -e
+
+LLAMA_DIR="${1:-../llama.cpp}"
+
+echo "🔧 Applying Metal StorageModeManaged fix for discrete AMD GPUs"
+echo " Target: $LLAMA_DIR"
+echo " Reference: https://github.com/ggml-org/llama.cpp/pull/20615"
+echo ""
+
+if [ ! -d "$LLAMA_DIR" ]; then
+ echo "❌ Error: llama.cpp directory not found at $LLAMA_DIR"
+ echo " Usage: ./apply-metal-fix.sh [path/to/llama.cpp]"
+ exit 1
+fi
+
+GGML_METAL_PATH="$LLAMA_DIR/ggml/src/ggml-metal/ggml-metal.m"
+
+if [ ! -f "$GGML_METAL_PATH" ]; then
+ echo "❌ Error: ggml-metal.m not found at $GGML_METAL_PATH"
+ exit 1
+fi
+
+echo "📄 Patching $GGML_METAL_PATH..."
+
+# Create backup
+cp "$GGML_METAL_PATH" "$GGML_METAL_PATH.bak"
+
+# Apply the 3-line fix
+# Find the line with "buffer addContents:" and replace with StorageModeManaged check
+# The fix checks if the buffer is StorageModeManaged and uses synchronizeResource instead
+
+# Check if already patched
+if grep -q "synchronizeResource" "$GGML_METAL_PATH"; then
+ echo "✅ Already patched! Skipping."
+ exit 0
+fi
+
+# Apply patch using sed
+# Look for: [buffer addContents:data size:length]
+# Replace with: if ([buffer storageMode] == MTLStorageModeManaged) { [buffer synchronizeResource]; } else { [buffer addContents:data size:length]; }
+
+# This is a simplified patch - the actual fix may need more context
+# For now, we'll add the synchronizeResource call before addContents
+
+sed -i.bak 's/\[buffer addContents:data size:length\]/if ([buffer storageMode] == MTLStorageModeManaged) { [buffer synchronizeResource]; } else { [buffer addContents:data size:length]; }/g' "$GGML_METAL_PATH"
+
+if grep -q "synchronizeResource" "$GGML_METAL_PATH"; then
+ echo "✅ Patch applied successfully!"
+ echo ""
+ echo "📋 Next steps:"
+ echo " 1. Rebuild llama.cpp: cd $LLAMA_DIR && make clean && make -j"
+ echo " 2. Test with discrete GPU (Mac Pro 2013, iMac 2014-2019, etc.)"
+ echo " 3. Report results to https://github.com/Scottcjn/trashclaw/issues/38"
+else
+ echo "❌ Patch failed to apply"
+ # Restore backup
+ mv "$GGML_METAL_PATH.bak" "$GGML_METAL_PATH"
+ exit 1
+fi
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8108b8e673ec0f2c89804751137107e624b519a8
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: MIT
+# TrashClaw test suite
diff --git a/tests/test_backend_url.py b/tests/test_backend_url.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcb9ba9b40ae3d3da236aea2c97e225bd01cc708
--- /dev/null
+++ b/tests/test_backend_url.py
@@ -0,0 +1,94 @@
+# SPDX-License-Identifier: MIT
+"""Regression tests: backend auto-detection must not produce /v1/v1/... URLs.
+
+A stdlib http.server runs in a thread and records the request paths it sees.
+"""
+
+import json
+import os
+import sys
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
+
+import trashclaw
+
+
+def _make_server(backend):
+ """Start a fake LM Studio ("lmstudio") or Ollama ("ollama") server."""
+ paths = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _send(self, code, body, ctype="application/json"):
+ data = body.encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_GET(self):
+ paths.append(("GET", self.path))
+ if backend == "lmstudio" and self.path == "/v1/models":
+ self._send(200, json.dumps({"data": [{"id": "test-model"}]}))
+ elif backend == "ollama" and self.path == "/api/tags":
+ self._send(200, json.dumps({"models": []}))
+ else:
+ self._send(404, "{}")
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", 0))
+ self.rfile.read(length)
+ paths.append(("POST", self.path))
+ if self.path != "/v1/chat/completions":
+ self._send(404, "{}")
+ return
+ chunk = {"choices": [{"delta": {"content": "hi"}, "finish_reason": "stop"}]}
+ self._send(200, "data: " + json.dumps(chunk) + "\n\ndata: [DONE]\n\n",
+ "text/event-stream")
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ return server, paths
+
+
+@pytest.fixture(autouse=True)
+def _reset_stats(monkeypatch):
+ monkeypatch.setattr(trashclaw, "LAST_GENERATION_STATS", {})
+ monkeypatch.setattr(trashclaw, "SESSION_STATS",
+ {"total_tokens": 0, "total_seconds": 0.0, "turns": 0})
+
+
+@pytest.mark.parametrize("backend,name", [("lmstudio", "LM Studio"), ("ollama", "Ollama")])
+@pytest.mark.parametrize("suffix", ["", "/", "/v1", "/v1/"])
+def test_detection_then_chat_posts_to_single_v1(monkeypatch, backend, name, suffix):
+ server, paths = _make_server(backend)
+ try:
+ base = "http://127.0.0.1:%d" % server.server_address[1]
+ monkeypatch.setattr(trashclaw, "LLAMA_URL", base + suffix)
+ assert trashclaw._detect_backend() == name
+ assert trashclaw.LLAMA_URL == base
+
+ result = trashclaw.llm_request([{"role": "user", "content": "hello"}])
+ assert "error" not in result, result
+ assert result["choices"][0]["message"]["content"] == "hi"
+ assert ("POST", "/v1/chat/completions") in paths
+ assert not any("/v1/v1" in p for _, p in paths)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def test_api_url_builders(monkeypatch):
+ for url in ("http://h:1", "http://h:1/", "http://h:1/v1", "http://h:1/v1/"):
+ monkeypatch.setattr(trashclaw, "LLAMA_URL", url)
+ assert trashclaw._server_base_url() == "http://h:1"
+ assert trashclaw._api_url("/chat/completions") == "http://h:1/v1/chat/completions"
+ assert trashclaw._api_url("/models") == "http://h:1/v1/models"
diff --git a/tests/test_cert_check.py b/tests/test_cert_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0586e5b32bf79f44a619b16c40acea659e9d638
--- /dev/null
+++ b/tests/test_cert_check.py
@@ -0,0 +1,105 @@
+# SPDX-License-Identifier: MIT
+"""Tests for the cert_check plugin."""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "plugins"))
+from cert_check import run, _format_dn, _parse_cert_time
+
+
+# ── Helper functions ──
+
+def test_parse_cert_time():
+ dt = _parse_cert_time("Jan 15 12:00:00 2026 GMT")
+ assert dt.year == 2026
+ assert dt.month == 1
+ assert dt.day == 15
+
+
+def test_format_dn_simple():
+ dn = (
+ (("commonName", "example.com"),),
+ (("organizationName", "Example Inc"),),
+ )
+ result = _format_dn(dn)
+ assert "commonName=example.com" in result
+ assert "organizationName=Example Inc" in result
+
+
+def test_format_dn_empty():
+ assert _format_dn(()) == "(empty)"
+ assert _format_dn(None) == "(empty)"
+
+
+# ── Basic operation ──
+
+def test_missing_domain():
+ result = run()
+ assert "Error" in result
+
+
+def test_unresolvable_domain():
+ result = run(domain="this.host.definitely.does.not.exist.invalid")
+ assert "Error" in result and "resolve" in result.lower()
+
+
+def test_connection_refused():
+ # Port 1 on localhost should refuse connections
+ result = run(domain="127.0.0.1", port=1)
+ assert "Error" in result
+
+
+def test_real_cert_check():
+ """Check a well-known public site (requires network).
+ Skip if no network is available."""
+ try:
+ import socket
+ socket.create_connection(("1.1.1.1", 443), timeout=3)
+ except (socket.timeout, OSError):
+ pytest.skip("No network available")
+
+ result = run(domain="google.com")
+ assert "Status:" in result
+ # Google's cert should be OK
+ assert "OK" in result or "Subject:" in result
+ assert "Valid From:" in result
+ assert "Valid Until:" in result
+ assert "Remaining:" in result
+
+
+def test_domain_with_protocol_prefix():
+ """Should strip https:// prefix."""
+ try:
+ import socket
+ socket.create_connection(("1.1.1.1", 443), timeout=3)
+ except (socket.timeout, OSError):
+ pytest.skip("No network available")
+
+ result = run(domain="https://google.com")
+ # Should still work after stripping prefix
+ assert "Status:" in result or "Error" in result
+
+
+def test_domain_with_port_in_string():
+ """Should handle 'domain:port' format."""
+ result = run(domain="127.0.0.1:1")
+ # Should try port 1 (will fail, but should parse correctly)
+ assert "Error" in result
+
+
+def test_self_signed_cert():
+ """Self-signed certs should show a warning, not crash."""
+ # 50.28.86.131 has a self-signed cert from the CLAUDE.md context
+ try:
+ import socket
+ socket.create_connection(("1.1.1.1", 443), timeout=3)
+ except (socket.timeout, OSError):
+ pytest.skip("No network available")
+
+ # Even if the specific host is down, the code path shouldn't crash
+ result = run(domain="self-signed.badssl.com")
+ # Should either show cert info or a clear verification warning
+ assert "Status:" in result or "WARNING" in result or "Error" in result
diff --git a/tests/test_cli_flags.py b/tests/test_cli_flags.py
new file mode 100644
index 0000000000000000000000000000000000000000..2edf85a6d373f4c4dcba0986813cacd89ac0422b
--- /dev/null
+++ b/tests/test_cli_flags.py
@@ -0,0 +1,87 @@
+# SPDX-License-Identifier: MIT
+"""Tests that command-line flags survive the config reload done by --cwd.
+
+Uses only pytest + stdlib. No LLM server is contacted: agent_turn is stubbed
+and only records the global state main() ended up with.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
+
+import trashclaw
+
+
+@pytest.fixture
+def run_main(tmp_path, monkeypatch):
+ """Run main() with the given argv and report the resulting settings."""
+ # Isolate from the developer's own config/env so defaults are the real ones.
+ monkeypatch.setattr(trashclaw, "CONFIG_FILE", str(tmp_path / "no-such-config.json"))
+ for var in ("TRASHCLAW_READONLY", "TRASHCLAW_AUTO_SHELL", "TRASHCLAW_URL"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setattr(trashclaw, "READ_ONLY_MODE", False)
+ monkeypatch.setattr(trashclaw, "APPROVE_SHELL", True)
+ monkeypatch.setattr(trashclaw, "LLAMA_URL", "http://localhost:8080")
+
+ project = tmp_path / "project"
+ project.mkdir()
+
+ def _run(*flags):
+ seen = {}
+ monkeypatch.setattr(
+ trashclaw,
+ "agent_turn",
+ lambda msg: seen.update(
+ read_only=trashclaw.READ_ONLY_MODE,
+ approve_shell=trashclaw.APPROVE_SHELL,
+ url=trashclaw.LLAMA_URL,
+ blocks_write=trashclaw._read_only_blocked("write_file", {}),
+ tool_names={
+ t["function"]["name"] for t in trashclaw._available_tools()
+ },
+ ),
+ )
+ argv = ["trashclaw.py"]
+ for flag in flags:
+ argv.extend(flag.replace("{cwd}", str(project)).split(" "))
+ argv.extend(["-e", "audit this repo"])
+ monkeypatch.setattr(sys, "argv", argv)
+ trashclaw.main()
+ return seen
+
+ _run.project = project
+ return _run
+
+
+def test_read_only_survives_later_cwd(run_main):
+ """--read-only before --cwd must still block writes (order must not matter)."""
+ for flags in (
+ ("--read-only",),
+ ("--read-only", "--cwd {cwd}"),
+ ("--cwd {cwd}", "--read-only"),
+ ("--read-only", "--cwd={cwd}"),
+ ):
+ seen = run_main(*flags)
+ assert seen["read_only"] is True, flags
+ assert seen["blocks_write"] is True, flags
+ for blocked in trashclaw.READ_ONLY_BLOCKED_TOOLS:
+ assert blocked not in seen["tool_names"], (flags, blocked)
+
+
+def test_url_and_auto_shell_survive_later_cwd(run_main):
+ seen = run_main("--url http://box:9999", "--cwd {cwd}")
+ assert seen["url"] == "http://box:9999"
+
+ seen = run_main("--auto-shell", "--cwd {cwd}")
+ assert seen["approve_shell"] is False
+
+
+def test_project_config_still_applies_when_no_flag_overrides_it(run_main):
+ """--cwd must keep loading the project config for settings not set on the CLI."""
+ (run_main.project / ".trashclaw.json").write_text('{"read_only": true}')
+ seen = run_main("--cwd {cwd}")
+ assert seen["read_only"] is True
+ assert seen["blocks_write"] is True
diff --git a/tests/test_code_stats.py b/tests/test_code_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb1a68972ba3d3ac4df4461b6f92cdd230da8c3e
--- /dev/null
+++ b/tests/test_code_stats.py
@@ -0,0 +1,68 @@
+# SPDX-License-Identifier: MIT
+"""Tests for the code_stats plugin."""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "plugins"))
+from code_stats import _is_binary, run
+
+
+def test_is_binary_detects_text_binary_and_missing_files(tmp_path):
+ text_file = tmp_path / "plain.py"
+ text_file.write_text("print('hello')\n")
+
+ binary_file = tmp_path / "compiled.py"
+ binary_file.write_bytes(b"print\x00hidden")
+
+ assert _is_binary(str(text_file)) is False
+ assert _is_binary(str(binary_file)) is True
+ assert _is_binary(str(tmp_path / "missing.py")) is True
+
+
+def test_run_counts_languages_markers_and_skips_ignored_paths(tmp_path):
+ (tmp_path / "app.py").write_text(
+ "print('hello')\n"
+ "# TODO: test marker\n"
+ "# FIXME: fix marker\n"
+ "# HACK: hack marker\n"
+ )
+ (tmp_path / "web.js").write_text("console.log('hi')\n")
+ (tmp_path / "README.md").write_text("# Project\n")
+ (tmp_path / "bundle.min.js").write_text("minified should be skipped\n")
+ (tmp_path / "binary.py").write_bytes(b"ignored\x00binary\n")
+
+ hidden = tmp_path / ".hidden"
+ hidden.mkdir()
+ (hidden / "secret.py").write_text("print('skip hidden')\n")
+
+ vendor = tmp_path / "vendor"
+ vendor.mkdir()
+ (vendor / "vendored.py").write_text("print('skip vendor')\n")
+
+ result = run(path=str(tmp_path), top_n=5)
+
+ assert "Total: 3 files, 6 lines" in result
+ assert "Python" in result
+ assert "JavaScript" in result
+ assert "Markdown" in result
+ assert "TODO: 1" in result
+ assert "FIXME: 1" in result
+ assert "HACK: 1" in result
+ assert "app.py" in result
+ assert "web.js" in result
+ assert "README.md" in result
+ assert "bundle.min.js" not in result
+ assert "binary.py" not in result
+ assert "secret.py" not in result
+ assert "vendored.py" not in result
+
+
+def test_run_reports_missing_directory_and_empty_source_tree(tmp_path):
+ missing = tmp_path / "missing"
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ (empty / "notes.txt").write_text("not a recognized source extension\n")
+
+ assert "Error: Not a directory" in run(path=str(missing))
+ assert "No recognized source files found" in run(path=str(empty))
diff --git a/tests/test_config_example.py b/tests/test_config_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..113da643d054644bd6ae3c0883a09c43798b6370
--- /dev/null
+++ b/tests/test_config_example.py
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: MIT
+"""The shipped .trashclaw.toml.example must only use keys a project config honours.
+
+Project configs are untrusted, so url, auto_shell, max_rounds, max_context
+(and anything else outside PROJECT_CONFIG_ALLOWED_KEYS) are ignored with a
+warning. An example that sets them tells users something that does not work.
+"""
+
+import os
+import shutil
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
+
+import pytest
+
+import trashclaw
+
+EXAMPLE = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".trashclaw.toml.example")
+
+
+@pytest.mark.parametrize("use_fallback_parser", [False, True])
+def test_example_only_uses_honoured_keys(tmp_path, monkeypatch, capsys, use_fallback_parser):
+ if use_fallback_parser:
+ monkeypatch.setitem(sys.modules, "tomllib", None) # Python < 3.11 path
+ monkeypatch.setattr(trashclaw, "CONFIG_FILE", str(tmp_path / "no-home-config.json"))
+ shutil.copy(EXAMPLE, str(tmp_path / ".trashclaw.toml"))
+ cfg = trashclaw._load_config(str(tmp_path))
+ err = capsys.readouterr().err
+ assert "Ignoring" not in err, err
+ assert cfg.get("model")
+ assert isinstance(cfg.get("context_files"), list) and cfg["context_files"]
+ assert cfg.get("project_system_prompt")
diff --git a/tests/test_env_audit.py b/tests/test_env_audit.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7e55b81402569baf0ddbca78f82d9382ab9d200
--- /dev/null
+++ b/tests/test_env_audit.py
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: MIT
+"""Tests for the env_audit plugin."""
+
+import os
+import stat
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "plugins"))
+from env_audit import run, _scan_file_contents
+
+
+# ── Basic operation ──
+
+def test_clean_dir(tmp_path):
+ """A directory with no issues should report clean."""
+ (tmp_path / "readme.txt").write_text("hello")
+ result = run(path=str(tmp_path))
+ assert "No issues" in result or "clean" in result.lower()
+
+
+def test_nonexistent_dir():
+ result = run(path="/tmp/nonexistent_trashclaw_env_audit_test")
+ assert "Error" in result
+
+
+# ── .env detection ──
+
+def test_env_file_detected(tmp_path):
+ """A .env file should be flagged."""
+ (tmp_path / ".env").write_text("SECRET_KEY=abc123def456ghi789")
+ result = run(path=str(tmp_path))
+ assert ".env" in result
+ # Should find at least a warning about the .env or a secret inside it
+ assert "WARNING" in result or "CRITICAL" in result or "secret" in result.lower()
+
+
+def test_env_production_detected(tmp_path):
+ (tmp_path / ".env.production").write_text("DB_PASSWORD=supersecret123")
+ result = run(path=str(tmp_path))
+ assert ".env.production" in result
+
+
+# ── Secret pattern detection ──
+
+def test_api_key_in_source(tmp_path):
+ f = tmp_path / "config.py"
+ f.write_text('API_KEY = "sk-abc123def456ghi789jkl012mno345"\n')
+ result = run(path=str(tmp_path), deep=True)
+ assert "secret" in result.lower() or "WARNING" in result
+
+
+def test_github_pat_detected(tmp_path):
+ f = tmp_path / "deploy.sh"
+ f.write_text('TOKEN=ghp_abcdefghijklmnopqrstuvwxyz1234567890\n')
+ result = run(path=str(tmp_path), deep=True)
+ assert "GitHub" in result or "WARNING" in result
+
+
+def test_private_key_block_detected(tmp_path):
+ f = tmp_path / "certs.py"
+ f.write_text('KEY = """-----BEGIN RSA PRIVATE KEY-----\nMIIE...\n"""\n')
+ result = run(path=str(tmp_path), deep=True)
+ assert "Private key" in result or "WARNING" in result
+
+
+def test_bearer_token_detected(tmp_path):
+ f = tmp_path / "api.js"
+ f.write_text('const headers = { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.abc" };\n')
+ result = run(path=str(tmp_path), deep=True)
+ assert "Bearer" in result or "WARNING" in result
+
+
+# ── Key file permissions ──
+
+def test_world_readable_key(tmp_path):
+ """A .pem file with world-readable permissions should be flagged."""
+ keyfile = tmp_path / "server.pem"
+ keyfile.write_text("fake key content")
+ os.chmod(str(keyfile), 0o644) # world-readable
+ result = run(path=str(tmp_path), deep=False)
+ assert "world-readable" in result or "WARNING" in result or "permissions" in result.lower()
+
+
+# ── Deep scan disabled ──
+
+def test_no_deep_scan(tmp_path):
+ """With deep=False, file contents should not be scanned for secrets."""
+ f = tmp_path / "config.py"
+ f.write_text('API_KEY = "sk-abc123def456ghi789jkl012mno345"\n')
+ result = run(path=str(tmp_path), deep=False)
+ # Should NOT find the API key since content scanning is off
+ # (unless the file is named as a sensitive file)
+ assert "secret_in_source" not in result
+
+
+# ── _scan_file_contents helper ──
+
+def test_scan_file_contents_finds_secrets(tmp_path):
+ f = tmp_path / "test.py"
+ f.write_text('password = "MyS3cretP@ss!"\napi_key: AKIAIOSFODNN7EXAMPLE1234\n')
+ findings = _scan_file_contents(str(f))
+ assert len(findings) >= 1
+ # At least one finding should mention password or API key
+ pattern_names = [name for _, name, _ in findings]
+ assert any("Password" in n or "API" in n for n in pattern_names)
+
+
+def test_scan_empty_file(tmp_path):
+ f = tmp_path / "empty.py"
+ f.write_text("")
+ findings = _scan_file_contents(str(f))
+ assert findings == []
+
+
+def test_scan_nonexistent():
+ findings = _scan_file_contents("/tmp/nonexistent_trashclaw_test_file")
+ assert findings == []
diff --git a/tests/test_fetch_url.py b/tests/test_fetch_url.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9ce9d22265862f96bbc7bb81fe27c8536e5feba
--- /dev/null
+++ b/tests/test_fetch_url.py
@@ -0,0 +1,243 @@
+# SPDX-License-Identifier: MIT
+"""
+Tests for tool_fetch_url and tool_think.
+
+Covers:
+- Happy path: HTML fetching, tag stripping, entity decoding, whitespace collapse
+- Error handling: HTTPError (404/500), URLError (no host), generic exceptions
+- Edge cases: empty response body, output truncation at MAX_OUTPUT_CHARS
+- tool_think: always returns a string with no side effects
+"""
+
+import os
+import sys
+import urllib.error
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Add project root to path so we can import trashclaw
+sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
+
+import trashclaw
+
+
+# ── Helpers ──
+
+def _make_mock_response(html: str):
+ """Create a mock urllib response that returns the given HTML bytes."""
+ mock = MagicMock()
+ mock.read.return_value = html.encode("utf-8")
+ mock.__enter__ = lambda s: s
+ mock.__exit__ = MagicMock(return_value=False)
+ return mock
+
+
+# ── tool_fetch_url: happy path ──
+
+class TestFetchUrlHappyPath:
+ """Test normal successful fetches."""
+
+ def test_returns_fetched_prefix(self):
+ """Successful fetch should include 'Fetched :' in the result."""
+ html = "Hello world
"
+ with patch("urllib.request.urlopen", return_value=_make_mock_response(html)):
+ result = trashclaw.tool_fetch_url("http://example.com")
+ assert "Fetched http://example.com" in result
+ assert "Hello world" in result
+
+ def test_strips_html_tags(self):
+ """HTML tags should be stripped from the response body."""
+ html = "bold and italic"
+ with patch("urllib.request.urlopen", return_value=_make_mock_response(html)):
+ result = trashclaw.tool_fetch_url("http://example.com")
+ assert "" not in result
+ assert "" not in result
+ assert "bold" in result
+ assert "italic" in result
+
+ def test_strips_script_blocks(self):
+ """