
# SYSTEM PROMPT: Building RepoPack (Universal Workspace CLI & MCP Server)

## 1. Project Overview
You are tasked with building a Python CLI application and Model Context Protocol (MCP) server named **RepoPack**.
The goal of RepoPack is to pack/unpack **any source workspace regardless of technology stack** (Python, Node.js, React, Angular, Vue, Rust, Go, Java, C#, etc.) into and out of a structured JSON payload.

Key Capabilities:
1. **Pack (Export):** Traverse any directory, respecting root/nested `.gitignore` patterns as well as standard ignore rules across all major tech stacks (excluding `node_modules`, `dist`, `.next`, virtual environments, binaries, locks, and generated artifacts), and output a clean JSON structure.
2. **Unpack (Import):** Read a packaged JSON document and faithfully reconstruct the directory hierarchy and all file contents at a designated output workspace.

---

## 2. Technical Stack & Dependencies
* **Python Version:** 3.10+
* **CLI Engine:** `typer`
* **MCP Integration:** `mcp` (Official Python Model Context Protocol SDK, specifically using `FastMCP`)
* **Ignore Rule Matching:** `pathspec` (Handles full Git wildmatch pattern logic)
* **Packaging Tooling:** `hatchling` or `flit` for `pyproject.toml` definition.

---

## 3. Polyglot Architecture & Framework Support

### A. Universal Ignore Engine (`utils.py` & `packer.py`)
To work seamlessly across Node.js, React, Angular, Python, and other stacks, the ignore resolution strategy must run in order of precedence:

1. **Hierarchy Gitignore Resolution:**
   - Recursively parse root `.gitignore` as well as any nested `.gitignore` files in subdirectories (e.g., inside package folders in monorepos).
2. **Universal Default Ignore Fallback Rules:**
   Even if a project lacks a `.gitignore`, enforce a comprehensive stack-agnostic default list:
   - **VCS & Meta:** `.git/`, `.svn/`, `.hg/`, `.DS_Store`, `Thumbs.db`
   - **Node / JS / TS (React, Angular, Vue, Next, Nuxt):** `node_modules/`, `dist/`, `build/`, `.next/`, `.nuxt/`, `.angular/`, `.cache/`, `coverage/`, `.astro/`, `.turbo/`, `out/`
   - **Python:** `__pycache__/`, `*.pyc`, `.venv/`, `venv/`, `.pytest_cache/`, `.mypy_cache/`, `.eggs/`, `*.egg-info/`, `sdist/`
   - **Rust / Go / Java / C# / C++:** `target/`, `bin/`, `obj/`, `*.exe`, `*.so`, `*.dylib`, `*.dll`, `*.class`, `*.jar`, `*.o`, `*.a`
   - **Environment & Secrets:** `.env`, `.env.local`, `.env.*.local` (Warn or skip to avoid security leaks)
3. **Encoding & Binary Safety:**
   - Intelligently differentiate text source files (`.js`, `.jsx`, `.ts`, `.tsx`, `.py`, `.json`, `.html`, `.css`, `.scss`, `.md`, `.yaml`, etc.) from raw binary assets.
   - Text files must be encoded as UTF-8 strings.
   - Non-UTF-8 binary files (e.g., `.png`, `.ico`, `.woff2`) must either be skipped by default or safely encoded as Base64 when `--include-binary` is toggled.

---

## 4. Specification: Package JSON Schema

```json
{
  "version": "1.0",
  "metadata": {
    "created_at": "2026-07-26T12:00:00Z",
    "root_directory_name": "my-app",
    "detected_stack": ["Node.js", "React"],
    "total_files": 38,
    "total_bytes": 128450
  },
  "files": [
    {
      "path": "package.json",
      "encoding": "utf-8",
      "content": "{\n  \"name\": \"my-react-app\"...\n}"
    },
    {
      "path": "src/App.tsx",
      "encoding": "utf-8",
      "content": "export default function App() {...}"
    },
    {
      "path": "public/favicon.ico",
      "encoding": "base64",
      "content": "AAABAAEAICAQAAAAAADoAgAA..."
    }
  ]
}

```

---

## 5. Security & Safety Protocols

1. **Path Traversal Shield:**
During `unpack`, strictly validate every path in the incoming JSON to prevent directory traversal attacks (`../`, `/etc/passwd`, absolute path injections). All output must be anchored safely under the target path.
2. **Large File Boundary:**
Skip or flag files larger than 5 MB (e.g., SQLite databases, large video assets) unless explicitly forced via configuration.

---

## 6. MCP Server Tools (`mcp_server.py`)

Using `FastMCP`, register two primary tools:

1. `export_workspace(workspace_path: str = ".", output_json_path: str = None, include_binary: bool = False)`
* Scans and packs the specified directory tree into JSON.
* If `output_json_path` is provided, writes to disk and returns summary stats. Otherwise, directly returns the serialized JSON string.


2. `import_workspace(json_input: str, destination_path: str, overwrite: bool = False)`
* Unpacks a workspace from either a JSON file path or a raw JSON string into `destination_path`.



---

## 7. CLI Commands (`cli.py`)

Executable defined via `pyproject.toml` as `repopack`:

* `repopack pack [DIRECTORY] [-o OUTPUT.json] [--include-binary] [--custom-ignore ".next,dist"]`
* `repopack unpack <INPUT.json> [-t TARGET_DIR] [--force]`
* `repopack serve` (Launches the stdio-based MCP Server)

---

## 8. File Tree Architecture

```text
repopack/
├── pyproject.toml
├── README.md
└── repopack/
    ├── __init__.py
    ├── cli.py            # Typer CLI wrapper
    ├── mcp_server.py     # MCP Server implementation
    ├── packer.py         # Directory walker & JSON builder
    ├── unpacker.py       # JSON extractor & security validator
    └── utils.py          # Gitignore handler, binary detector, path safety

```

---

## 9. Execution Instructions for AI Code Generator

1. Construct `utils.py` using `pathspec` for standard `.gitignore` wildmatch capabilities, including auto-detection of tech stack defaults.
2. Build `packer.py` with multi-encoding (UTF-8 / Base64) stream reading and file metadata detection.
3. Build `unpacker.py` with path sanitization enforcing `os.path.commonpath` checks to prevent escape vulnerabilities.
4. Integrate `cli.py` and `mcp_server.py` with `FastMCP`.
5. Ensure complete unit test coverage for Node/React/Angular mock folders and Python virtual environments.

```

```