Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

feat: add WireMock HTTP mock server CLI harness

fabio.mantelmacher2e685e1b16ea
diff --git a/.gitignore b/.gitignore
index d4bdbcde3..b46234974 100644
--- a/.gitignore
+++ b/.gitignore
@@ -118,6 +118,8 @@
/renderdoc/.*
/cloudcompare/*
/cloudcompare/.*
+/wiremock/*
+/wiremock/.*
# Step 6: ...except agent-harness/
!/gimp/agent-harness/
@@ -149,6 +151,8 @@
!/rms/agent-harness/
!/renderdoc/agent-harness/
!/cloudcompare/agent-harness/
+!/wiremock/
+!/wiremock/agent-harness/
# Step 7: Ignore build artifacts within allowed dirs
**/__pycache__/
diff --git a/README.md b/README.md
index 6bc7e6a5e..157785385 100644
--- a/README.md
+++ b/README.md
@@ -475,6 +475,7 @@ The catalog auto-updates whenever `registry.json` changes โ€” new community CLIs
| **๐Ÿ“ž Communication & Collaboration** | Automate meeting scheduling, participant management, recording retrieval, and reporting through structured CLI | Zoom, Jitsi Meet, BigBlueButton, Mattermost |
| **๐Ÿ“ Diagramming & Visualization** | Create and manipulate diagrams, flowcharts, architecture diagrams, and visual documentation programmatically | Draw.io (diagrams.net), Mermaid, PlantUML, Excalidraw, yEd |
| **๐ŸŒ Network & Infrastructure** | Manage network services, DNS, ad-blocking, and infrastructure through structured CLI commands | AdGuardHome |
+| **๐Ÿงช Testing & Mocking** | Control HTTP mock servers, manage test stubs, record and replay API traffic for integration testing | **[WireMock](https://wiremock.org)** |
| **๐Ÿ”ฌ Graphics & GPU Debugging** | Analyze GPU frame captures, inspect pipeline state, export shaders, and diff rendering state | RenderDoc |
| **๐ŸŽฌ Video & Subtitles** | Transcribe speech, translate subtitles, burn styled captions into video โ€” full captioning pipeline | VideoCaptioner |
| **โœจ AI Content Generation** | Generate professional deliverables (slides, docs, diagrams, websites, research reports) through AI-powered cloud APIs | [AnyGen](https://www.anygen.io), Gamma, Beautiful.ai, Tome |
diff --git a/registry.json b/registry.json
index b20c870f7..a69bb4335 100644
--- a/registry.json
+++ b/registry.json
@@ -2,9 +2,23 @@
"meta": {
"repo": "https://github.com/HKUDS/CLI-Anything",
"description": "CLI-Hub โ€” Agent-native stateful CLI interfaces for softwares, codebases, and Web Services",
- "updated": "2026-03-26"
+ "updated": "2026-03-31"
},
"clis": [
+ {
+ "name": "wiremock",
+ "display_name": "WireMock",
+ "version": "0.1.0",
+ "description": "HTTP mock server management โ€” create stubs, inspect requests, record traffic, and manage scenarios via WireMock REST API",
+ "requires": "WireMock server running (java -jar wiremock-standalone.jar)",
+ "homepage": "https://wiremock.org",
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=wiremock/agent-harness",
+ "entry_point": "cli-anything-wiremock",
+ "skill_md": "wiremock/agent-harness/cli_anything/wiremock/skills/SKILL.md",
+ "category": "testing",
+ "contributor": "fabiomantel",
+ "contributor_url": "https://github.com/fabiomantel"
+ },
{
"name": "anygen",
"display_name": "AnyGen",
diff --git a/wiremock/agent-harness/WIREMOCK.md b/wiremock/agent-harness/WIREMOCK.md
new file mode 100644
index 000000000..5850b7b65
--- /dev/null
+++ b/wiremock/agent-harness/WIREMOCK.md
@@ -0,0 +1,237 @@
+# WireMock CLI Harness โ€” Standard Operating Procedure
+
+## What is WireMock?
+
+WireMock is a flexible HTTP mock server used to stub and record HTTP interactions. It exposes a REST Admin API at `/__admin/` for managing stubs, inspecting requests, controlling stateful scenarios, and recording traffic from real backends.
+
+This CLI harness wraps those admin endpoints so agents and developers can control WireMock from the terminal or scripts without needing to craft raw HTTP calls.
+
+---
+
+## Starting WireMock Standalone
+
+### Download
+
+```bash
+curl -fsSL https://repo1.maven.org/maven2/org/wiremock/wiremock-standalone/3.3.1/wiremock-standalone-3.3.1.jar \
+ -o wiremock-standalone.jar
+```
+
+### Start (default port 8080)
+
+```bash
+java -jar wiremock-standalone.jar --port 8080 --verbose
+```
+
+### Start with persistent mappings directory
+
+```bash
+java -jar wiremock-standalone.jar \
+ --port 8080 \
+ --root-dir ./wiremock-data \
+ --verbose
+```
+
+### Start with HTTPS
+
+```bash
+java -jar wiremock-standalone.jar \
+ --port 8443 \
+ --https-port 8443 \
+ --verbose
+```
+
+### Docker (alternative)
+
+```bash
+docker run -d --name wiremock \
+ -p 8080:8080 \
+ wiremock/wiremock:latest
+```
+
+---
+
+## Installing the CLI
+
+```bash
+cd /path/to/agent-harness
+pip install -e .
+cli-anything-wiremock --help
+```
+
+---
+
+## Connection Configuration
+
+All connection parameters can be set via environment variables or CLI flags.
+
+| Environment Variable | CLI Flag | Default | Description |
+|----------------------|--------------|-------------|----------------------|
+| `WIREMOCK_HOST` | `--host` | `localhost` | WireMock host |
+| `WIREMOCK_PORT` | `--port` | `8080` | WireMock port |
+| `WIREMOCK_SCHEME` | `--scheme` | `http` | `http` or `https` |
+| `WIREMOCK_USER` | `--user` | (none) | Basic auth username |
+| `WIREMOCK_PASSWORD` | `--password` | (none) | Basic auth password |
+| `WIREMOCK_JSON` | `--json` | false | JSON output mode |
+
+**Example โ€” connect to a remote WireMock instance:**
+
+```bash
+export WIREMOCK_HOST=wiremock.internal
+export WIREMOCK_PORT=9090
+cli-anything-wiremock status
+```
+
+---
+
+## Common Workflows
+
+### 1. Verify the server is running
+
+```bash
+cli-anything-wiremock status
+```
+
+### 2. Create a simple stub
+
+```bash
+# Quick form: METHOD URL STATUS_CODE [--body JSON]
+cli-anything-wiremock stub quick GET /api/users 200 --body '{"users":[]}'
+
+# Full JSON form
+cli-anything-wiremock stub create '{
+ "request": { "method": "POST", "url": "/api/orders" },
+ "response": { "status": 201, "body": "{\"id\":42}", "headers": { "Content-Type": "application/json" } }
+}'
+```
+
+### 3. List all stubs
+
+```bash
+cli-anything-wiremock stub list
+cli-anything-wiremock stub list --json # machine-readable
+```
+
+### 4. Get a specific stub
+
+```bash
+cli-anything-wiremock stub get <stub-id>
+```
+
+### 5. Delete a stub
+
+```bash
+cli-anything-wiremock stub delete <stub-id>
+```
+
+### 6. Reset all stubs to defaults
+
+```bash
+cli-anything-wiremock stub reset
+```
+
+### 7. Persist stubs to disk
+
+```bash
+cli-anything-wiremock stub save
+```
+
+### 8. Import stubs from a file
+
+```bash
+cli-anything-wiremock stub import ./my-stubs.json
+```
+
+---
+
+### Request Verification
+
+```bash
+# List recent requests
+cli-anything-wiremock request list
+cli-anything-wiremock request list --limit 10
+
+# Find requests matching a pattern
+cli-anything-wiremock request find '{"method": "GET", "url": "/api/users"}'
+
+# Count matching requests (useful for assertion)
+cli-anything-wiremock request count '{"method": "POST", "urlPath": "/api/orders"}'
+
+# List unmatched requests (404s)
+cli-anything-wiremock request unmatched
+
+# Clear the request journal
+cli-anything-wiremock request reset
+```
+
+---
+
+### Stateful Scenario Testing
+
+WireMock supports state machines (scenarios) to simulate multi-step workflows.
+
+```bash
+# List all scenarios and their current state
+cli-anything-wiremock scenario list
+
+# Set a specific scenario to a state
+cli-anything-wiremock scenario set "login-flow" "logged-in"
+
+# Reset all scenarios to initial state
+cli-anything-wiremock scenario reset
+```
+
+---
+
+### Recording Traffic from a Real Backend
+
+Use recording to auto-generate stubs from real API traffic.
+
+```bash
+# Start recording โ€” proxy traffic to a real backend
+cli-anything-wiremock record start https://api.example.com
+
+# ... make requests to http://localhost:8080 โ€” they are proxied and captured ...
+
+# Stop recording and inspect captured stubs
+cli-anything-wiremock record stop
+
+# Check if currently recording
+cli-anything-wiremock record status
+
+# Take a snapshot of in-memory requests as stubs
+cli-anything-wiremock record snapshot
+```
+
+---
+
+### Server Management
+
+```bash
+# Check WireMock version
+cli-anything-wiremock settings version
+
+# Get global settings
+cli-anything-wiremock settings get
+
+# Full reset (stubs + requests + scenarios)
+cli-anything-wiremock reset
+
+# Shutdown the server
+cli-anything-wiremock shutdown
+```
+
+---
+
+## JSON Output Mode
+
+All commands support `--json` for machine-readable output suitable for scripting or agent use:
+
+```bash
+cli-anything-wiremock --json stub list
+cli-anything-wiremock --json request count '{"method":"GET","url":"/health"}'
+```
+
+Output envelope:
+- Success: `{ "status": "ok", "message": "...", "data": {...} }`
+- Error: `{ "status": "error", "message": "..." }`
diff --git a/wiremock/agent-harness/cli_anything/wiremock/README.md b/wiremock/agent-harness/cli_anything/wiremock/README.md
new file mode 100644
index 000000000..da8f2b032
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/README.md
@@ -0,0 +1,47 @@
+# cli-anything-wiremock
+
+Python CLI harness for the [WireMock](https://wiremock.org/) HTTP mock server admin API.
+
+## Installation
+
+```bash
+pip install -e /path/to/agent-harness
+```
+
+## Quick Start
+
+```bash
+# Check server status
+cli-anything-wiremock status
+
+# Create a stub
+cli-anything-wiremock stub quick GET /api/hello 200 --body '{"hello":"world"}'
+
+# List stubs
+cli-anything-wiremock stub list
+
+# Verify a request was made
+cli-anything-wiremock request count '{"method":"GET","url":"/api/hello"}'
+```
+
+## Command Groups
+
+| Group | Purpose |
+|------------|------------------------------------------------|
+| `stub` | Create, read, update, delete stub mappings |
+| `request` | Inspect served requests and verify invocations |
+| `scenario` | Manage stateful scenario state machines |
+| `record` | Record real backend traffic as stubs |
+| `settings` | Read global settings and server version |
+
+## Configuration
+
+Set via environment variables or `--option` flags:
+
+```bash
+export WIREMOCK_HOST=localhost
+export WIREMOCK_PORT=8080
+export WIREMOCK_SCHEME=http
+```
+
+See `WIREMOCK.md` at the repository root for the full SOP.
diff --git a/wiremock/agent-harness/cli_anything/wiremock/__init__.py b/wiremock/agent-harness/cli_anything/wiremock/__init__.py
new file mode 100644
index 000000000..47227626c
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/__init__.py
@@ -0,0 +1 @@
+# cli_anything.wiremock โ€” WireMock admin CLI
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/__init__.py b/wiremock/agent-harness/cli_anything/wiremock/core/__init__.py
new file mode 100644
index 000000000..97daee7e9
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/__init__.py
@@ -0,0 +1 @@
+# core package
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/recording.py b/wiremock/agent-harness/cli_anything/wiremock/core/recording.py
new file mode 100644
index 000000000..1f817a26b
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/recording.py
@@ -0,0 +1,31 @@
+from cli_anything.wiremock.utils.client import WireMockClient
+
+
+class RecordingManager:
+ def __init__(self, client: WireMockClient):
+ self.client = client
+
+ def start(self, target_url: str, headers_to_match: list = None) -> dict:
+ spec = {"targetBaseUrl": target_url}
+ if headers_to_match:
+ spec["captureHeaders"] = {
+ h: {"caseInsensitive": True} for h in headers_to_match
+ }
+ r = self.client.post("/recordings/start", json=spec)
+ r.raise_for_status()
+ return r.json()
+
+ def stop(self) -> dict:
+ r = self.client.post("/recordings/stop")
+ r.raise_for_status()
+ return r.json()
+
+ def status(self) -> dict:
+ r = self.client.get("/recordings/status")
+ r.raise_for_status()
+ return r.json()
+
+ def snapshot(self, spec: dict = None) -> dict:
+ r = self.client.post("/recordings/snapshot", json=spec or {})
+ r.raise_for_status()
+ return r.json()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/requests_log.py b/wiremock/agent-harness/cli_anything/wiremock/core/requests_log.py
new file mode 100644
index 000000000..6f42322e1
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/requests_log.py
@@ -0,0 +1,45 @@
+from cli_anything.wiremock.utils.client import WireMockClient
+
+
+class RequestsLog:
+ def __init__(self, client: WireMockClient):
+ self.client = client
+
+ def list(self, limit: int = None, since: str = None) -> dict:
+ params = {}
+ if limit:
+ params["limit"] = limit
+ if since:
+ params["since"] = since
+ r = self.client.get("/requests", params=params)
+ r.raise_for_status()
+ return r.json()
+
+ def get(self, request_id: str) -> dict:
+ r = self.client.get(f"/requests/{request_id}")
+ r.raise_for_status()
+ return r.json()
+
+ def reset(self) -> None:
+ r = self.client.delete("/requests")
+ r.raise_for_status()
+
+ def find(self, pattern: dict) -> dict:
+ r = self.client.post("/requests/find", json=pattern)
+ r.raise_for_status()
+ return r.json()
+
+ def count(self, pattern: dict) -> dict:
+ r = self.client.post("/requests/count", json=pattern)
+ r.raise_for_status()
+ return r.json()
+
+ def unmatched(self) -> dict:
+ r = self.client.get("/requests/unmatched")
+ r.raise_for_status()
+ return r.json()
+
+ def near_misses_unmatched(self) -> dict:
+ r = self.client.get("/requests/unmatched/near-misses")
+ r.raise_for_status()
+ return r.json()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/scenarios.py b/wiremock/agent-harness/cli_anything/wiremock/core/scenarios.py
new file mode 100644
index 000000000..b05824cca
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/scenarios.py
@@ -0,0 +1,19 @@
+from cli_anything.wiremock.utils.client import WireMockClient
+
+
+class ScenariosManager:
+ def __init__(self, client: WireMockClient):
+ self.client = client
+
+ def list(self) -> dict:
+ r = self.client.get("/scenarios")
+ r.raise_for_status()
+ return r.json()
+
+ def reset_all(self) -> None:
+ r = self.client.post("/scenarios/reset")
+ r.raise_for_status()
+
+ def set_state(self, name: str, state: str) -> None:
+ r = self.client.put(f"/scenarios/{name}/state", json={"state": state})
+ r.raise_for_status()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/session.py b/wiremock/agent-harness/cli_anything/wiremock/core/session.py
new file mode 100644
index 000000000..b12ee48bc
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/session.py
@@ -0,0 +1,28 @@
+"""Session state: stores connection parameters, loaded from env or CLI options."""
+import os
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class Session:
+ host: str = "localhost"
+ port: int = 8080
+ scheme: str = "http"
+ username: Optional[str] = None
+ password: Optional[str] = None
+
+ @classmethod
+ def from_env(cls) -> "Session":
+ return cls(
+ host=os.environ.get("WIREMOCK_HOST", "localhost"),
+ port=int(os.environ.get("WIREMOCK_PORT", "8080")),
+ scheme=os.environ.get("WIREMOCK_SCHEME", "http"),
+ username=os.environ.get("WIREMOCK_USER"),
+ password=os.environ.get("WIREMOCK_PASSWORD"),
+ )
+
+ def auth(self):
+ if self.username and self.password:
+ return (self.username, self.password)
+ return None
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/settings.py b/wiremock/agent-harness/cli_anything/wiremock/core/settings.py
new file mode 100644
index 000000000..4b40f1cac
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/settings.py
@@ -0,0 +1,21 @@
+from cli_anything.wiremock.utils.client import WireMockClient
+
+
+class SettingsManager:
+ def __init__(self, client: WireMockClient):
+ self.client = client
+
+ def get(self) -> dict:
+ r = self.client.get("/settings")
+ r.raise_for_status()
+ return r.json()
+
+ def update(self, settings: dict) -> dict:
+ r = self.client.put("/settings", json=settings)
+ r.raise_for_status()
+ return r.json()
+
+ def get_version(self) -> dict:
+ r = self.client.get("/version")
+ r.raise_for_status()
+ return r.json()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/core/stubs.py b/wiremock/agent-harness/cli_anything/wiremock/core/stubs.py
new file mode 100644
index 000000000..6a75cb0ac
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/core/stubs.py
@@ -0,0 +1,73 @@
+from cli_anything.wiremock.utils.client import WireMockClient
+from typing import Optional
+
+
+class StubsManager:
+ def __init__(self, client: WireMockClient):
+ self.client = client
+
+ def list(self, limit: int = None, offset: int = None) -> dict:
+ params = {}
+ if limit:
+ params["limit"] = limit
+ if offset:
+ params["offset"] = offset
+ r = self.client.get("/mappings", params=params)
+ r.raise_for_status()
+ return r.json()
+
+ def get(self, stub_id: str) -> dict:
+ r = self.client.get(f"/mappings/{stub_id}")
+ r.raise_for_status()
+ return r.json()
+
+ def create(self, mapping: dict) -> dict:
+ r = self.client.post("/mappings", json=mapping)
+ r.raise_for_status()
+ return r.json()
+
+ def update(self, stub_id: str, mapping: dict) -> dict:
+ r = self.client.put(f"/mappings/{stub_id}", json=mapping)
+ r.raise_for_status()
+ return r.json()
+
+ def delete(self, stub_id: str) -> None:
+ r = self.client.delete(f"/mappings/{stub_id}")
+ r.raise_for_status()
+
+ def reset(self) -> None:
+ r = self.client.post("/mappings/reset")
+ r.raise_for_status()
+
+ def save(self) -> None:
+ r = self.client.post("/mappings/save")
+ r.raise_for_status()
+
+ def import_stubs(self, stubs: dict) -> dict:
+ r = self.client.post("/mappings/import", json=stubs)
+ r.raise_for_status()
+ return r.json()
+
+ def find_by_metadata(self, pattern: dict) -> dict:
+ r = self.client.post("/mappings/find-by-metadata", json=pattern)
+ r.raise_for_status()
+ return r.json()
+
+ def quick_stub(
+ self,
+ method: str,
+ url: str,
+ status: int,
+ body: str = None,
+ content_type: str = "application/json",
+ ) -> dict:
+ """Helper: create a simple stub quickly."""
+ response = {"status": status}
+ if body:
+ response["body"] = body
+ response["headers"] = {"Content-Type": content_type}
+ mapping = {
+ "request": {"method": method.upper(), "url": url},
+ "response": response,
+ }
+ return self.create(mapping)
diff --git a/wiremock/agent-harness/cli_anything/wiremock/skills/SKILL.md b/wiremock/agent-harness/cli_anything/wiremock/skills/SKILL.md
new file mode 100644
index 000000000..e3c8c328b
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/skills/SKILL.md
@@ -0,0 +1,137 @@
+---
+name: cli-anything-wiremock
+description: Python CLI harness for WireMock HTTP mock server administration
+version: 0.1.0
+entrypoint: cli-anything-wiremock
+---
+
+## Overview
+
+`cli-anything-wiremock` is a command-line interface that wraps the WireMock Admin REST API (`/__admin/`). It allows agents and developers to manage HTTP stub mappings, inspect served requests, control stateful scenarios, and record real backend traffic โ€” all from the terminal or from agent tool calls.
+
+WireMock is commonly used in integration testing environments to replace real HTTP backends with controllable mock responses.
+
+## Command Groups
+
+### `stub` โ€” Manage HTTP stub mappings
+
+| Command | Description |
+|----------------------|-------------------------------------------------------|
+| `stub list` | List all registered stubs |
+| `stub get <id>` | Get details of a specific stub by UUID |
+| `stub create <json>` | Create a stub from a JSON string |
+| `stub quick M URL S` | Quickly create a stub: METHOD URL STATUS_CODE |
+| `stub delete <id>` | Delete a stub by UUID |
+| `stub reset` | Reset all stubs to the defaults on disk |
+| `stub save` | Persist in-memory stubs to disk |
+| `stub import <file>` | Import stubs from a JSON file |
+
+### `request` โ€” Inspect served requests
+
+| Command | Description |
+|----------------------------|--------------------------------------------------|
+| `request list` | List recent served requests |
+| `request find <pattern>` | Find requests matching a JSON pattern |
+| `request count <pattern>` | Count requests matching a JSON pattern |
+| `request unmatched` | List requests that matched no stub (404s) |
+| `request reset` | Clear the request journal |
+
+### `scenario` โ€” Stateful scenario management
+
+| Command | Description |
+|-----------------------|---------------------------------------------------|
+| `scenario list` | List all scenarios and current states |
+| `scenario set N S` | Set scenario NAME to STATE |
+| `scenario reset` | Reset all scenarios to their initial state |
+
+### `record` โ€” Record traffic from a real backend
+
+| Command | Description |
+|----------------------------|--------------------------------------------------|
+| `record start <url>` | Start proxying + recording to TARGET_URL |
+| `record stop` | Stop recording, return captured stubs |
+| `record status` | Check if currently recording |
+| `record snapshot` | Snapshot in-memory requests as stubs |
+
+### `settings` โ€” Global server settings
+
+| Command | Description |
+|--------------------|----------------------------------------|
+| `settings get` | Get current global WireMock settings |
+| `settings version` | Show WireMock server version |
+
+### Top-level commands
+
+| Command | Description |
+|------------|--------------------------------------------------|
+| `status` | Check if WireMock is running |
+| `reset` | Full reset: stubs + requests + scenarios |
+| `shutdown` | Gracefully shut down the WireMock server |
+
+## Key Examples
+
+```bash
+# Check connectivity
+cli-anything-wiremock status
+
+# Create a stub using quick form
+cli-anything-wiremock stub quick GET /api/users 200 --body '[{"id":1}]'
+
+# Create a stub using full JSON
+cli-anything-wiremock stub create '{
+ "request": {"method": "POST", "url": "/api/orders"},
+ "response": {"status": 201, "body": "{\"id\":99}"}
+}'
+
+# Verify a POST was made exactly once
+cli-anything-wiremock --json request count '{"method":"POST","url":"/api/orders"}'
+# โ†’ {"status":"ok","message":"...","data":{"count":1}}
+
+# Scenario: advance state
+cli-anything-wiremock scenario set "cart-flow" "item-added"
+
+# Record a real backend
+cli-anything-wiremock record start https://api.example.com
+# ... make requests ...
+cli-anything-wiremock record stop
+```
+
+## Agent Guidance
+
+### Always use `--json` in agent contexts
+
+Use `--json` for all invocations in scripts or agent tool calls. This produces a stable, parseable envelope:
+
+```json
+{ "status": "ok", "message": "Created stub abc-123", "data": { ... } }
+{ "status": "error", "message": "Connection refused" }
+```
+
+### Connection via environment
+
+Set connection params via environment variables before calling any command:
+
+```bash
+export WIREMOCK_HOST=localhost
+export WIREMOCK_PORT=8080
+```
+
+### Workflow pattern for test verification
+
+1. Set up stubs before running the system under test:
+ ```bash
+ cli-anything-wiremock --json stub quick POST /api/payment 200 --body '{"success":true}'
+ ```
+2. Run the system under test.
+3. Verify interactions:
+ ```bash
+ cli-anything-wiremock --json request count '{"method":"POST","url":"/api/payment"}'
+ ```
+4. Clean up:
+ ```bash
+ cli-anything-wiremock reset
+ ```
+
+### Error handling
+
+Non-zero exit code on all errors. Check `status` field in JSON output. The `data` field is `null` on errors.
diff --git a/wiremock/agent-harness/cli_anything/wiremock/tests/TEST.md b/wiremock/agent-harness/cli_anything/wiremock/tests/TEST.md
new file mode 100644
index 000000000..386f4baee
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/tests/TEST.md
@@ -0,0 +1,79 @@
+# WireMock CLI Harness โ€” Test Plan
+
+## Overview
+
+This document describes the testing strategy for the `cli-anything-wiremock` package. Tests live in this directory and cover both unit-level logic and end-to-end CLI invocation.
+
+---
+
+## Test Files
+
+| File | Type | Description |
+|--------------------|-------------|-----------------------------------------------------------|
+| `test_core.py` | Unit | Tests all core modules with mocked HTTP responses |
+| `test_full_e2e.py` | E2E / CLI | Tests CLI subcommands via subprocess against a live server |
+
+---
+
+## Unit Tests (`test_core.py`)
+
+Tests run entirely offline using `unittest.mock` to intercept `requests` calls.
+
+### Coverage targets
+
+| Module | Tests |
+|--------------------------------|-----------------------------------------------------------------------|
+| `utils/client.py` | `base_url()` construction, all HTTP verbs, `is_alive()` true/false |
+| `utils/output.py` | `success()` JSON mode, `success()` human mode, `error()` exits |
+| `core/session.py` | `from_env()` reads env vars, falls back to defaults |
+| `core/stubs.py` | `list()`, `get()`, `create()`, `delete()`, `reset()`, `quick_stub()` |
+| `core/requests_log.py` | `list()`, `find()`, `count()`, `unmatched()`, `reset()` |
+| `core/scenarios.py` | `list()`, `set_state()`, `reset_all()` |
+| `core/recording.py` | `start()` with and without headers, `stop()`, `status()`, `snapshot()`|
+| `core/settings.py` | `get()`, `get_version()` |
+
+### Running unit tests
+
+```bash
+cd /tmp/wiremock-src/agent-harness
+pip install -e . pytest
+pytest cli_anything/wiremock/tests/test_core.py -v
+```
+
+---
+
+## E2E Tests (`test_full_e2e.py`)
+
+CLI subcommand tests run via `subprocess`. They test argument parsing, flag handling, and output formatting.
+
+Tests that require a live WireMock server are gated on the `WIREMOCK_URL` environment variable โ€” they skip automatically when no server is available.
+
+Tests that only invoke `--help` or check argument parsing do not require a live server.
+
+### Running E2E tests (no server required for basic checks)
+
+```bash
+pytest cli_anything/wiremock/tests/test_full_e2e.py -v
+```
+
+### Running E2E tests with a live WireMock server
+
+```bash
+# Start WireMock first
+java -jar wiremock-standalone.jar --port 8080 &
+
+export WIREMOCK_URL=http://localhost:8080
+pytest cli_anything/wiremock/tests/test_full_e2e.py -v
+```
+
+---
+
+## Coverage Requirements
+
+- Minimum 80% overall coverage
+- All public methods in `core/` must have at least one unit test
+- All CLI command groups must have at least one invocation test
+
+```bash
+pytest --cov=cli_anything.wiremock --cov-report=term-missing cli_anything/wiremock/tests/
+```
diff --git a/wiremock/agent-harness/cli_anything/wiremock/tests/__init__.py b/wiremock/agent-harness/cli_anything/wiremock/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/wiremock/agent-harness/cli_anything/wiremock/tests/test_core.py b/wiremock/agent-harness/cli_anything/wiremock/tests/test_core.py
new file mode 100644
index 000000000..c0217717b
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/tests/test_core.py
@@ -0,0 +1,506 @@
+"""Unit tests for cli_anything.wiremock core modules.
+
+All tests use unittest.mock to intercept HTTP calls โ€” no live server required.
+"""
+import json
+import os
+import sys
+import unittest
+from unittest.mock import MagicMock, patch
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _mock_response(status_code: int = 200, json_data: dict = None):
+ """Return a mock requests.Response with configurable status and JSON."""
+ mock = MagicMock()
+ mock.status_code = status_code
+ mock.json.return_value = json_data or {}
+ mock.raise_for_status = MagicMock()
+ if status_code >= 400:
+ from requests.exceptions import HTTPError
+ mock.raise_for_status.side_effect = HTTPError(f"{status_code}")
+ return mock
+
+
+# ---------------------------------------------------------------------------
+# WireMockClient tests
+# ---------------------------------------------------------------------------
+
+
+class TestWireMockClient(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ self.client = WireMockClient(host="testhost", port=9090, scheme="https")
+
+ def test_base_url_construction(self):
+ self.assertEqual(self.client.base_url(), "https://testhost:9090/__admin")
+
+ def test_base_url_defaults(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ c = WireMockClient()
+ self.assertEqual(c.base_url(), "http://localhost:8080/__admin")
+
+ @patch("requests.get")
+ def test_get_passes_auth_and_timeout(self, mock_get):
+ mock_get.return_value = _mock_response(200, {})
+ self.client.auth = ("user", "pass")
+ self.client.get("/mappings")
+ mock_get.assert_called_once_with(
+ "https://testhost:9090/__admin/mappings",
+ auth=("user", "pass"),
+ timeout=30,
+ )
+
+ @patch("requests.post")
+ def test_post_sends_json(self, mock_post):
+ mock_post.return_value = _mock_response(200, {})
+ self.client.post("/mappings", json={"key": "value"})
+ mock_post.assert_called_once_with(
+ "https://testhost:9090/__admin/mappings",
+ json={"key": "value"},
+ auth=None,
+ timeout=30,
+ )
+
+ @patch("requests.put")
+ def test_put_sends_json(self, mock_put):
+ mock_put.return_value = _mock_response(200, {})
+ self.client.put("/mappings/abc", json={"id": "abc"})
+ mock_put.assert_called_once()
+
+ @patch("requests.delete")
+ def test_delete(self, mock_delete):
+ mock_delete.return_value = _mock_response(200, {})
+ self.client.delete("/mappings/abc")
+ mock_delete.assert_called_once()
+
+ @patch("requests.patch")
+ def test_patch(self, mock_patch):
+ mock_patch.return_value = _mock_response(200, {})
+ self.client.patch("/mappings/abc", json={"name": "x"})
+ mock_patch.assert_called_once()
+
+ @patch("requests.get")
+ def test_is_alive_true(self, mock_get):
+ mock_get.return_value = _mock_response(200, {})
+ self.assertTrue(self.client.is_alive())
+
+ @patch("requests.get")
+ def test_is_alive_false_on_non_200(self, mock_get):
+ mock_get.return_value = _mock_response(503, {})
+ self.assertFalse(self.client.is_alive())
+
+ @patch("requests.get")
+ def test_is_alive_false_on_exception(self, mock_get):
+ mock_get.side_effect = ConnectionError("refused")
+ self.assertFalse(self.client.is_alive())
+
+
+# ---------------------------------------------------------------------------
+# Session tests
+# ---------------------------------------------------------------------------
+
+
+class TestSession(unittest.TestCase):
+ def test_from_env_defaults(self):
+ from cli_anything.wiremock.core.session import Session
+ env = {}
+ with patch.dict(os.environ, env, clear=False):
+ # Remove keys if they exist so defaults are used
+ for k in ["WIREMOCK_HOST", "WIREMOCK_PORT", "WIREMOCK_SCHEME",
+ "WIREMOCK_USER", "WIREMOCK_PASSWORD"]:
+ os.environ.pop(k, None)
+ s = Session.from_env()
+ self.assertEqual(s.host, "localhost")
+ self.assertEqual(s.port, 8080)
+ self.assertEqual(s.scheme, "http")
+ self.assertIsNone(s.username)
+ self.assertIsNone(s.password)
+
+ def test_from_env_reads_env_vars(self):
+ from cli_anything.wiremock.core.session import Session
+ with patch.dict(os.environ, {
+ "WIREMOCK_HOST": "myhost",
+ "WIREMOCK_PORT": "9999",
+ "WIREMOCK_SCHEME": "https",
+ "WIREMOCK_USER": "admin",
+ "WIREMOCK_PASSWORD": "secret",
+ }):
+ s = Session.from_env()
+ self.assertEqual(s.host, "myhost")
+ self.assertEqual(s.port, 9999)
+ self.assertEqual(s.scheme, "https")
+ self.assertEqual(s.username, "admin")
+ self.assertEqual(s.password, "secret")
+
+ def test_auth_returns_tuple_when_both_set(self):
+ from cli_anything.wiremock.core.session import Session
+ s = Session(username="u", password="p")
+ self.assertEqual(s.auth(), ("u", "p"))
+
+ def test_auth_returns_none_when_partial(self):
+ from cli_anything.wiremock.core.session import Session
+ s = Session(username="u") # no password
+ self.assertIsNone(s.auth())
+
+ def test_auth_returns_none_when_empty(self):
+ from cli_anything.wiremock.core.session import Session
+ s = Session()
+ self.assertIsNone(s.auth())
+
+
+# ---------------------------------------------------------------------------
+# StubsManager tests
+# ---------------------------------------------------------------------------
+
+
+class TestStubsManager(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ from cli_anything.wiremock.core.stubs import StubsManager
+ self.client = WireMockClient()
+ self.mgr = StubsManager(self.client)
+
+ @patch("requests.get")
+ def test_list_no_params(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"mappings": [], "total": 0})
+ result = self.mgr.list()
+ self.assertEqual(result["total"], 0)
+ call_kwargs = mock_get.call_args
+ # params should not include limit/offset when not provided
+ self.assertNotIn("limit", call_kwargs.kwargs.get("params", {}))
+
+ @patch("requests.get")
+ def test_list_with_limit_and_offset(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"mappings": [], "total": 0})
+ self.mgr.list(limit=10, offset=5)
+ params = mock_get.call_args.kwargs.get("params", {})
+ self.assertEqual(params["limit"], 10)
+ self.assertEqual(params["offset"], 5)
+
+ @patch("requests.get")
+ def test_get_stub(self, mock_get):
+ stub_data = {"id": "abc-123", "request": {"method": "GET"}}
+ mock_get.return_value = _mock_response(200, stub_data)
+ result = self.mgr.get("abc-123")
+ self.assertEqual(result["id"], "abc-123")
+ mock_get.assert_called_once()
+ assert "/mappings/abc-123" in mock_get.call_args.args[0]
+
+ @patch("requests.post")
+ def test_create_stub(self, mock_post):
+ created = {"id": "new-id", "request": {"method": "GET", "url": "/foo"}}
+ mock_post.return_value = _mock_response(201, created)
+ mapping = {"request": {"method": "GET", "url": "/foo"}, "response": {"status": 200}}
+ result = self.mgr.create(mapping)
+ self.assertEqual(result["id"], "new-id")
+ posted_json = mock_post.call_args.kwargs["json"]
+ self.assertEqual(posted_json["request"]["url"], "/foo")
+
+ @patch("requests.delete")
+ def test_delete_stub(self, mock_delete):
+ mock_delete.return_value = _mock_response(200, {})
+ self.mgr.delete("abc-123")
+ mock_delete.assert_called_once()
+ assert "/mappings/abc-123" in mock_delete.call_args.args[0]
+
+ @patch("requests.post")
+ def test_reset(self, mock_post):
+ mock_post.return_value = _mock_response(200, {})
+ self.mgr.reset()
+ assert "/mappings/reset" in mock_post.call_args.args[0]
+
+ @patch("requests.post")
+ def test_save(self, mock_post):
+ mock_post.return_value = _mock_response(200, {})
+ self.mgr.save()
+ assert "/mappings/save" in mock_post.call_args.args[0]
+
+ @patch("requests.post")
+ def test_quick_stub_no_body(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"id": "q1"})
+ self.mgr.quick_stub("GET", "/ping", 200)
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertEqual(sent["request"]["method"], "GET")
+ self.assertEqual(sent["request"]["url"], "/ping")
+ self.assertEqual(sent["response"]["status"], 200)
+ self.assertNotIn("body", sent["response"])
+
+ @patch("requests.post")
+ def test_quick_stub_with_body(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"id": "q2"})
+ self.mgr.quick_stub("POST", "/data", 201, body='{"ok":true}')
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertEqual(sent["response"]["body"], '{"ok":true}')
+ self.assertIn("Content-Type", sent["response"]["headers"])
+
+ @patch("requests.post")
+ def test_quick_stub_method_uppercased(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"id": "q3"})
+ self.mgr.quick_stub("get", "/health", 200)
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertEqual(sent["request"]["method"], "GET")
+
+ @patch("requests.post")
+ def test_import_stubs(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"mappings": []})
+ result = self.mgr.import_stubs({"mappings": []})
+ assert "/mappings/import" in mock_post.call_args.args[0]
+ self.assertIn("mappings", result)
+
+ @patch("requests.post")
+ def test_find_by_metadata(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"mappings": []})
+ pattern = {"matchesJsonPath": {"expression": "$.name", "equalTo": "x"}}
+ self.mgr.find_by_metadata(pattern)
+ assert "/mappings/find-by-metadata" in mock_post.call_args.args[0]
+
+
+# ---------------------------------------------------------------------------
+# RequestsLog tests
+# ---------------------------------------------------------------------------
+
+
+class TestRequestsLog(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ from cli_anything.wiremock.core.requests_log import RequestsLog
+ self.client = WireMockClient()
+ self.log = RequestsLog(self.client)
+
+ @patch("requests.get")
+ def test_list(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"serveEvents": [], "total": 0})
+ result = self.log.list()
+ self.assertIn("serveEvents", result)
+
+ @patch("requests.get")
+ def test_list_with_limit(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"serveEvents": [], "total": 0})
+ self.log.list(limit=5)
+ params = mock_get.call_args.kwargs.get("params", {})
+ self.assertEqual(params["limit"], 5)
+
+ @patch("requests.post")
+ def test_find(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"requests": []})
+ pattern = {"method": "GET", "url": "/foo"}
+ result = self.log.find(pattern)
+ assert "/requests/find" in mock_post.call_args.args[0]
+ self.assertIn("requests", result)
+
+ @patch("requests.post")
+ def test_count(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"count": 3})
+ pattern = {"method": "POST"}
+ result = self.log.count(pattern)
+ self.assertEqual(result["count"], 3)
+ assert "/requests/count" in mock_post.call_args.args[0]
+
+ @patch("requests.get")
+ def test_unmatched(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"requests": []})
+ result = self.log.unmatched()
+ assert "/requests/unmatched" in mock_get.call_args.args[0]
+
+ @patch("requests.get")
+ def test_near_misses_unmatched(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"nearMisses": []})
+ result = self.log.near_misses_unmatched()
+ assert "/requests/unmatched/near-misses" in mock_get.call_args.args[0]
+
+ @patch("requests.delete")
+ def test_reset(self, mock_delete):
+ mock_delete.return_value = _mock_response(200, {})
+ self.log.reset()
+ assert "/requests" in mock_delete.call_args.args[0]
+
+
+# ---------------------------------------------------------------------------
+# ScenariosManager tests
+# ---------------------------------------------------------------------------
+
+
+class TestScenariosManager(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ from cli_anything.wiremock.core.scenarios import ScenariosManager
+ self.client = WireMockClient()
+ self.mgr = ScenariosManager(self.client)
+
+ @patch("requests.get")
+ def test_list(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"scenarios": []})
+ result = self.mgr.list()
+ self.assertIn("scenarios", result)
+ assert "/scenarios" in mock_get.call_args.args[0]
+
+ @patch("requests.put")
+ def test_set_state(self, mock_put):
+ mock_put.return_value = _mock_response(200, {})
+ self.mgr.set_state("login-flow", "logged-in")
+ assert "/scenarios/login-flow/state" in mock_put.call_args.args[0]
+ sent = mock_put.call_args.kwargs["json"]
+ self.assertEqual(sent["state"], "logged-in")
+
+ @patch("requests.post")
+ def test_reset_all(self, mock_post):
+ mock_post.return_value = _mock_response(200, {})
+ self.mgr.reset_all()
+ assert "/scenarios/reset" in mock_post.call_args.args[0]
+
+
+# ---------------------------------------------------------------------------
+# RecordingManager tests
+# ---------------------------------------------------------------------------
+
+
+class TestRecordingManager(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ from cli_anything.wiremock.core.recording import RecordingManager
+ self.client = WireMockClient()
+ self.mgr = RecordingManager(self.client)
+
+ @patch("requests.post")
+ def test_start_no_headers(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"status": "Recording"})
+ result = self.mgr.start("https://api.example.com")
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertEqual(sent["targetBaseUrl"], "https://api.example.com")
+ self.assertNotIn("captureHeaders", sent)
+
+ @patch("requests.post")
+ def test_start_with_headers(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"status": "Recording"})
+ self.mgr.start("https://api.example.com", headers_to_match=["Authorization", "X-Api-Key"])
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertIn("captureHeaders", sent)
+ self.assertIn("Authorization", sent["captureHeaders"])
+ self.assertIn("X-Api-Key", sent["captureHeaders"])
+ self.assertTrue(sent["captureHeaders"]["Authorization"]["caseInsensitive"])
+
+ @patch("requests.post")
+ def test_stop(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"mappings": [{"id": "x"}]})
+ result = self.mgr.stop()
+ assert "/recordings/stop" in mock_post.call_args.args[0]
+ self.assertIn("mappings", result)
+
+ @patch("requests.get")
+ def test_status(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"status": "Recording"})
+ result = self.mgr.status()
+ assert "/recordings/status" in mock_get.call_args.args[0]
+ self.assertEqual(result["status"], "Recording")
+
+ @patch("requests.post")
+ def test_snapshot(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"mappings": []})
+ result = self.mgr.snapshot()
+ assert "/recordings/snapshot" in mock_post.call_args.args[0]
+ self.assertIn("mappings", result)
+
+ @patch("requests.post")
+ def test_snapshot_with_spec(self, mock_post):
+ mock_post.return_value = _mock_response(200, {"mappings": []})
+ self.mgr.snapshot(spec={"persist": False})
+ sent = mock_post.call_args.kwargs["json"]
+ self.assertFalse(sent["persist"])
+
+
+# ---------------------------------------------------------------------------
+# SettingsManager tests
+# ---------------------------------------------------------------------------
+
+
+class TestSettingsManager(unittest.TestCase):
+ def setUp(self):
+ from cli_anything.wiremock.utils.client import WireMockClient
+ from cli_anything.wiremock.core.settings import SettingsManager
+ self.client = WireMockClient()
+ self.mgr = SettingsManager(self.client)
+
+ @patch("requests.get")
+ def test_get(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"fixedDelay": 0})
+ result = self.mgr.get()
+ assert "/settings" in mock_get.call_args.args[0]
+ self.assertIn("fixedDelay", result)
+
+ @patch("requests.put")
+ def test_update(self, mock_put):
+ mock_put.return_value = _mock_response(200, {"fixedDelay": 500})
+ result = self.mgr.update({"fixedDelay": 500})
+ sent = mock_put.call_args.kwargs["json"]
+ self.assertEqual(sent["fixedDelay"], 500)
+
+ @patch("requests.get")
+ def test_get_version(self, mock_get):
+ mock_get.return_value = _mock_response(200, {"version": "3.3.1"})
+ result = self.mgr.get_version()
+ assert "/version" in mock_get.call_args.args[0]
+ self.assertEqual(result["version"], "3.3.1")
+
+
+# ---------------------------------------------------------------------------
+# Output utility tests
+# ---------------------------------------------------------------------------
+
+
+class TestOutputFunctions(unittest.TestCase):
+ def test_print_json(self):
+ from cli_anything.wiremock.utils.output import print_json
+ import io
+ with patch("builtins.print") as mock_print:
+ print_json({"key": "value"})
+ mock_print.assert_called_once()
+ output = mock_print.call_args.args[0]
+ parsed = json.loads(output)
+ self.assertEqual(parsed["key"], "value")
+
+ def test_success_json_mode(self):
+ from cli_anything.wiremock.utils.output import success
+ with patch("builtins.print") as mock_print:
+ success("All good", data={"result": 1}, json_mode=True)
+ mock_print.assert_called_once()
+ output = mock_print.call_args.args[0]
+ parsed = json.loads(output)
+ self.assertEqual(parsed["status"], "ok")
+ self.assertEqual(parsed["message"], "All good")
+ self.assertEqual(parsed["data"]["result"], 1)
+
+ def test_success_human_mode(self):
+ from cli_anything.wiremock.utils.output import success
+ with patch("builtins.print") as mock_print:
+ success("Done", json_mode=False)
+ first_call = mock_print.call_args_list[0].args[0]
+ self.assertIn("Done", first_call)
+
+ def test_error_json_mode(self):
+ from cli_anything.wiremock.utils.output import error
+ with patch("builtins.print") as mock_print:
+ with self.assertRaises(SystemExit) as cm:
+ error("Something broke", json_mode=True)
+ self.assertEqual(cm.exception.code, 1)
+ output = mock_print.call_args.args[0]
+ parsed = json.loads(output)
+ self.assertEqual(parsed["status"], "error")
+ self.assertEqual(parsed["message"], "Something broke")
+
+ def test_error_human_mode_exits_1(self):
+ from cli_anything.wiremock.utils.output import error
+ with self.assertRaises(SystemExit) as cm:
+ error("Oops", json_mode=False)
+ self.assertEqual(cm.exception.code, 1)
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/tests/test_full_e2e.py b/wiremock/agent-harness/cli_anything/wiremock/tests/test_full_e2e.py
new file mode 100644
index 000000000..78a854573
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/tests/test_full_e2e.py
@@ -0,0 +1,374 @@
+"""E2E / subprocess tests for the cli-anything-wiremock CLI.
+
+Tests that require a live WireMock server are automatically skipped unless
+the WIREMOCK_URL environment variable is set (e.g. WIREMOCK_URL=http://localhost:8080).
+
+Tests for --help and argument parsing work without a server.
+"""
+import json
+import os
+import subprocess
+import sys
+import unittest
+
+# ---------------------------------------------------------------------------
+# CLI resolution
+# ---------------------------------------------------------------------------
+
+CLI_ENV_KEY = "CLI_ANYTHING_FORCE_INSTALLED"
+
+
+def _resolve_cli(name: str) -> list:
+ """Resolve CLI name to a command list, supporting installed and dev modes.
+
+ Returns a list suitable for use as the first argument to subprocess.run().
+ """
+ if os.environ.get(CLI_ENV_KEY):
+ return [name]
+ result = subprocess.run(["which", name], capture_output=True, text=True)
+ if result.returncode == 0:
+ return [result.stdout.strip()]
+ # Fall back to running the module directly
+ return [sys.executable, "-m", "cli_anything.wiremock.wiremock_cli"]
+
+
+CLI_CMD = _resolve_cli("cli-anything-wiremock")
+
+# ---------------------------------------------------------------------------
+# Live-server guard
+# ---------------------------------------------------------------------------
+
+WIREMOCK_URL = os.environ.get("WIREMOCK_URL", "")
+LIVE_SERVER_AVAILABLE = bool(WIREMOCK_URL)
+
+skip_no_server = unittest.skipUnless(
+ LIVE_SERVER_AVAILABLE,
+ "WIREMOCK_URL not set โ€” skipping live server tests",
+)
+
+
+def _run(*args, env_extras: dict = None, input_text: str = None) -> subprocess.CompletedProcess:
+ """Run the CLI with the given arguments and return the CompletedProcess."""
+ env = os.environ.copy()
+ if WIREMOCK_URL:
+ from urllib.parse import urlparse
+ parsed = urlparse(WIREMOCK_URL)
+ env["WIREMOCK_HOST"] = parsed.hostname or "localhost"
+ env["WIREMOCK_PORT"] = str(parsed.port or 8080)
+ env["WIREMOCK_SCHEME"] = parsed.scheme or "http"
+ if env_extras:
+ env.update(env_extras)
+ return subprocess.run(
+ CLI_CMD + list(args),
+ capture_output=True,
+ text=True,
+ env=env,
+ input=input_text,
+ )
+
+
+# ---------------------------------------------------------------------------
+# TestCLISubprocess โ€” argument parsing and --help (no server needed)
+# ---------------------------------------------------------------------------
+
+
+class TestCLISubprocess(unittest.TestCase):
+ """Tests that exercise CLI argument parsing without a live WireMock server."""
+
+ def test_top_level_help(self):
+ result = _run("--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("stub", result.stdout)
+ self.assertIn("request", result.stdout)
+ self.assertIn("scenario", result.stdout)
+ self.assertIn("record", result.stdout)
+ self.assertIn("settings", result.stdout)
+
+ def test_stub_group_help(self):
+ result = _run("stub", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("list", result.stdout)
+ self.assertIn("create", result.stdout)
+ self.assertIn("quick", result.stdout)
+ self.assertIn("delete", result.stdout)
+
+ def test_stub_list_help(self):
+ result = _run("stub", "list", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("--limit", result.stdout)
+ self.assertIn("--offset", result.stdout)
+
+ def test_stub_quick_help(self):
+ result = _run("stub", "quick", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("METHOD", result.stdout)
+ self.assertIn("URL", result.stdout)
+ self.assertIn("STATUS", result.stdout)
+ self.assertIn("--body", result.stdout)
+
+ def test_request_group_help(self):
+ result = _run("request", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("list", result.stdout)
+ self.assertIn("find", result.stdout)
+ self.assertIn("count", result.stdout)
+ self.assertIn("unmatched", result.stdout)
+ self.assertIn("reset", result.stdout)
+
+ def test_scenario_group_help(self):
+ result = _run("scenario", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("list", result.stdout)
+ self.assertIn("set", result.stdout)
+ self.assertIn("reset", result.stdout)
+
+ def test_record_group_help(self):
+ result = _run("record", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("start", result.stdout)
+ self.assertIn("stop", result.stdout)
+ self.assertIn("status", result.stdout)
+ self.assertIn("snapshot", result.stdout)
+
+ def test_settings_group_help(self):
+ result = _run("settings", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("get", result.stdout)
+ self.assertIn("version", result.stdout)
+
+ def test_status_help(self):
+ result = _run("status", "--help")
+ self.assertEqual(result.returncode, 0)
+
+ def test_global_json_flag_in_help(self):
+ result = _run("--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("--json", result.stdout)
+
+ def test_global_host_flag_in_help(self):
+ result = _run("--help")
+ self.assertIn("--host", result.stdout)
+
+ def test_global_port_flag_in_help(self):
+ result = _run("--help")
+ self.assertIn("--port", result.stdout)
+
+ def test_record_start_help_shows_match_header(self):
+ result = _run("record", "start", "--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("--match-header", result.stdout)
+
+ def test_status_fails_gracefully_when_no_server(self):
+ """status should exit non-zero or print 'stopped' โ€” not crash."""
+ result = _run(
+ "status",
+ env_extras={
+ "WIREMOCK_HOST": "127.0.0.1",
+ "WIREMOCK_PORT": "19999", # nothing listening here
+ },
+ )
+ # Either it prints "stopped" (exit 0) or exits with 1 โ€” both are acceptable
+ # It must NOT raise an unhandled exception
+ self.assertNotIn("Traceback", result.stdout)
+ self.assertNotIn("Traceback", result.stderr)
+ if result.returncode == 0:
+ self.assertIn("stopped", result.stdout)
+
+ def test_status_json_fails_gracefully_when_no_server(self):
+ """--json status should output valid JSON even when server is unreachable."""
+ result = _run(
+ "--json", "status",
+ env_extras={
+ "WIREMOCK_HOST": "127.0.0.1",
+ "WIREMOCK_PORT": "19999",
+ },
+ )
+ self.assertNotIn("Traceback", result.stdout)
+ if result.returncode == 0:
+ data = json.loads(result.stdout)
+ self.assertIn("status", data)
+
+
+# ---------------------------------------------------------------------------
+# TestLiveServer โ€” tests that require WIREMOCK_URL
+# ---------------------------------------------------------------------------
+
+
+class TestLiveServer(unittest.TestCase):
+ """Tests against a live WireMock instance.
+
+ Set WIREMOCK_URL=http://localhost:8080 before running.
+ """
+
+ @skip_no_server
+ def setUp(self):
+ """Reset WireMock state before each test."""
+ _run("reset", input_text="y\n") # confirm the prompt if any
+ # Also try a clean reset via the full-reset command
+ result = subprocess.run(
+ CLI_CMD + ["reset"],
+ capture_output=True, text=True,
+ env={**os.environ, **self._env()},
+ )
+ # Ignore reset errors โ€” server might already be clean
+
+ def _env(self):
+ from urllib.parse import urlparse
+ parsed = urlparse(WIREMOCK_URL)
+ return {
+ "WIREMOCK_HOST": parsed.hostname or "localhost",
+ "WIREMOCK_PORT": str(parsed.port or 8080),
+ "WIREMOCK_SCHEME": parsed.scheme or "http",
+ }
+
+ @skip_no_server
+ def test_status_running(self):
+ result = _run("--json", "status")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "running")
+
+ @skip_no_server
+ def test_stub_list_empty(self):
+ result = _run("--json", "stub", "list")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ # WireMock may have default stubs; just check the structure
+ self.assertIn("mappings", data)
+
+ @skip_no_server
+ def test_stub_quick_create_and_list(self):
+ # Create a stub
+ result = _run("--json", "stub", "quick", "GET", "/test-endpoint", "200",
+ "--body", '{"hello":"world"}')
+ self.assertEqual(result.returncode, 0)
+ created = json.loads(result.stdout)
+ self.assertEqual(created["status"], "ok")
+ stub_id = created["data"]["id"]
+ self.assertIsNotNone(stub_id)
+
+ # List and find it
+ result = _run("--json", "stub", "list")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ ids = [m["id"] for m in data.get("mappings", [])]
+ self.assertIn(stub_id, ids)
+
+ @skip_no_server
+ def test_stub_create_full_json(self):
+ mapping = {
+ "request": {"method": "POST", "url": "/api/orders"},
+ "response": {"status": 201, "body": '{"id":42}',
+ "headers": {"Content-Type": "application/json"}},
+ }
+ result = _run("--json", "stub", "create", json.dumps(mapping))
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "ok")
+
+ @skip_no_server
+ def test_stub_get(self):
+ # Create a stub first
+ r = _run("--json", "stub", "quick", "GET", "/get-test", "200")
+ stub_id = json.loads(r.stdout)["data"]["id"]
+
+ result = _run("--json", "stub", "get", stub_id)
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["id"], stub_id)
+
+ @skip_no_server
+ def test_stub_delete(self):
+ # Create then delete
+ r = _run("--json", "stub", "quick", "GET", "/delete-me", "200")
+ stub_id = json.loads(r.stdout)["data"]["id"]
+
+ result = _run("--json", "stub", "delete", stub_id)
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "ok")
+
+ @skip_no_server
+ def test_stub_reset(self):
+ # Create a stub, then reset
+ _run("stub", "quick", "GET", "/ephemeral", "200")
+ result = _run("--json", "stub", "reset")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "ok")
+
+ @skip_no_server
+ def test_request_list_and_reset(self):
+ # List requests
+ result = _run("--json", "request", "list")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertIn("serveEvents", data)
+
+ # Reset
+ result = _run("--json", "request", "reset")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "ok")
+
+ @skip_no_server
+ def test_request_count(self):
+ pattern = json.dumps({"method": "GET", "url": "/nonexistent"})
+ result = _run("--json", "request", "count", pattern)
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertIn("count", data)
+
+ @skip_no_server
+ def test_scenario_list(self):
+ result = _run("--json", "scenario", "list")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertIn("scenarios", data)
+
+ @skip_no_server
+ def test_scenario_reset(self):
+ result = _run("--json", "scenario", "reset")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertEqual(data["status"], "ok")
+
+ @skip_no_server
+ def test_record_status(self):
+ result = _run("--json", "record", "status")
+ self.assertEqual(result.returncode, 0)
+ # WireMock returns {"status": "NeverStarted"} or "Recording" or "Stopped"
+ # just verify we got a valid response
+ data = json.loads(result.stdout)
+ self.assertIn("status", data)
+
+ @skip_no_server
+ def test_settings_version(self):
+ result = _run("--json", "settings", "version")
+ self.assertEqual(result.returncode, 0)
+ data = json.loads(result.stdout)
+ self.assertIn("version", data)
+
+ @skip_no_server
+ def test_settings_get(self):
+ result = _run("--json", "settings", "get")
+ self.assertEqual(result.returncode, 0)
+ # Should return a JSON object (no crash)
+ data = json.loads(result.stdout)
+ self.assertIsInstance(data, dict)
+
+ @skip_no_server
+ def test_request_unmatched(self):
+ result = _run("--json", "request", "unmatched")
+ self.assertEqual(result.returncode, 0)
+ # Just verify it returns valid JSON
+ data = json.loads(result.stdout)
+ self.assertIsInstance(data, dict)
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/wiremock/agent-harness/cli_anything/wiremock/utils/__init__.py b/wiremock/agent-harness/cli_anything/wiremock/utils/__init__.py
new file mode 100644
index 000000000..db3e3278d
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/utils/__init__.py
@@ -0,0 +1 @@
+# utils package
diff --git a/wiremock/agent-harness/cli_anything/wiremock/utils/client.py b/wiremock/agent-harness/cli_anything/wiremock/utils/client.py
new file mode 100644
index 000000000..886b763a5
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/utils/client.py
@@ -0,0 +1,61 @@
+"""Thin wrapper around requests for WireMock admin API calls."""
+import requests
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class WireMockClient:
+ host: str = "localhost"
+ port: int = 8080
+ scheme: str = "http"
+ admin_prefix: str = "/__admin"
+ auth: Optional[tuple] = None
+ timeout: int = 30
+
+ def base_url(self) -> str:
+ return f"{self.scheme}://{self.host}:{self.port}{self.admin_prefix}"
+
+ def get(self, path: str, **kwargs) -> requests.Response:
+ return requests.get(
+ f"{self.base_url()}{path}", auth=self.auth, timeout=self.timeout, **kwargs
+ )
+
+ def post(self, path: str, json=None, **kwargs) -> requests.Response:
+ return requests.post(
+ f"{self.base_url()}{path}",
+ json=json,
+ auth=self.auth,
+ timeout=self.timeout,
+ **kwargs,
+ )
+
+ def put(self, path: str, json=None, **kwargs) -> requests.Response:
+ return requests.put(
+ f"{self.base_url()}{path}",
+ json=json,
+ auth=self.auth,
+ timeout=self.timeout,
+ **kwargs,
+ )
+
+ def delete(self, path: str, **kwargs) -> requests.Response:
+ return requests.delete(
+ f"{self.base_url()}{path}", auth=self.auth, timeout=self.timeout, **kwargs
+ )
+
+ def patch(self, path: str, json=None, **kwargs) -> requests.Response:
+ return requests.patch(
+ f"{self.base_url()}{path}",
+ json=json,
+ auth=self.auth,
+ timeout=self.timeout,
+ **kwargs,
+ )
+
+ def is_alive(self) -> bool:
+ try:
+ r = requests.get(f"{self.base_url()}/health", timeout=3)
+ return r.status_code == 200
+ except Exception:
+ return False
diff --git a/wiremock/agent-harness/cli_anything/wiremock/utils/output.py b/wiremock/agent-harness/cli_anything/wiremock/utils/output.py
new file mode 100644
index 000000000..8b350817d
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/utils/output.py
@@ -0,0 +1,48 @@
+import json
+import sys
+from typing import Any
+
+
+def print_json(data: Any) -> None:
+ """Print data as formatted JSON."""
+ print(json.dumps(data, indent=2))
+
+
+def print_table(headers: list, rows: list, title: str = None) -> None:
+ """Print data as a simple ASCII table using rich if available."""
+ try:
+ from rich.console import Console
+ from rich.table import Table
+
+ table = Table(title=title, show_header=True)
+ for h in headers:
+ table.add_column(h)
+ for row in rows:
+ table.add_row(*[str(c) for c in row])
+ Console().print(table)
+ except ImportError:
+ if title:
+ print(f"\n{title}")
+ print(" | ".join(headers))
+ print("-" * 40)
+ for row in rows:
+ print(" | ".join(str(c) for c in row))
+
+
+def success(message: str, data: Any = None, json_mode: bool = False) -> None:
+ """Output a success result."""
+ if json_mode:
+ print_json({"status": "ok", "message": message, "data": data})
+ else:
+ print(f"โœ“ {message}")
+ if data is not None:
+ print_json(data)
+
+
+def error(message: str, json_mode: bool = False) -> None:
+ """Output an error result and exit."""
+ if json_mode:
+ print_json({"status": "error", "message": message})
+ else:
+ print(f"โœ— {message}", file=sys.stderr)
+ sys.exit(1)
diff --git a/wiremock/agent-harness/cli_anything/wiremock/utils/repl_skin.py b/wiremock/agent-harness/cli_anything/wiremock/utils/repl_skin.py
new file mode 100644
index 000000000..c7312348a
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/utils/repl_skin.py
@@ -0,0 +1,521 @@
+"""cli-anything REPL Skin โ€” Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects skills/SKILL.md inside the package
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# โ”€โ”€ ANSI color codes (no external deps for core styling) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors โ€” each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# โ”€โ”€ Brand icon โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}โ—†{_RESET}"
+_ICON_SMALL = f"{_CYAN}โ–ธ{_RESET}"
+
+# โ”€โ”€ Box drawing characters โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_H_LINE = "โ”€"
+_V_LINE = "โ”‚"
+_TL = "โ•ญ"
+_TR = "โ•ฎ"
+_BL = "โ•ฐ"
+_BR = "โ•ฏ"
+_T_DOWN = "โ”ฌ"
+_T_UP = "โ”ด"
+_T_RIGHT = "โ”œ"
+_T_LEFT = "โ”ค"
+_CROSS = "โ”ผ"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the package's skills/ directory if not provided.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+
+ # Auto-detect skill path from package layout:
+ # cli_anything/<software>/utils/repl_skin.py (this file)
+ # cli_anything/<software>/skills/SKILL.md (target)
+ if skill_path is None:
+ from pathlib import Path
+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ if _auto.is_file():
+ skill_path = str(_auto)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # โ”€โ”€ Banner โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: โ—† cli-anything ยท Shotcut
+ icon = self._c(_CYAN + _BOLD, "โ—†")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "ยท")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ # Skill path for agent discovery
+ skill_line = None
+ if self.skill_path:
+ skill_icon = self._c(_MAGENTA, "โ—‡")
+ skill_label = self._c(_DARK_GRAY, " Skill:")
+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)
+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ if skill_line:
+ print(_box_line(skill_line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # โ”€โ”€ Prompt โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}โ—†{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " โฏ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "โ—† "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " โฏ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # โ”€โ”€ Messages โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "โœ“")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "โœ—")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "โš ")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "โ—")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # โ”€โ”€ Status display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "โ–ˆ" * filled + "โ–‘" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # โ”€โ”€ Table display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'โ”€โ”€โ”€'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # โ”€โ”€ Help display โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # โ”€โ”€ Goodbye โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # โ”€โ”€ Prompt toolkit session factory โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # โ”€โ”€ Toolbar builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " โ”‚ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# โ”€โ”€ ANSI 256-color to hex mapping (for prompt_toolkit styles) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/wiremock/agent-harness/cli_anything/wiremock/wiremock_cli.py b/wiremock/agent-harness/cli_anything/wiremock/wiremock_cli.py
new file mode 100644
index 000000000..44461e226
--- /dev/null
+++ b/wiremock/agent-harness/cli_anything/wiremock/wiremock_cli.py
@@ -0,0 +1,562 @@
+import json
+import sys
+import click
+from cli_anything.wiremock.utils.client import WireMockClient
+from cli_anything.wiremock.utils.output import error, print_json, print_table, success
+from cli_anything.wiremock.core.recording import RecordingManager
+from cli_anything.wiremock.core.requests_log import RequestsLog
+from cli_anything.wiremock.core.scenarios import ScenariosManager
+from cli_anything.wiremock.core.session import Session
+from cli_anything.wiremock.core.settings import SettingsManager
+from cli_anything.wiremock.core.stubs import StubsManager
+
+pass_client = click.make_pass_decorator(WireMockClient)
+
+
+ "--host",
+ default=None,
+ envvar="WIREMOCK_HOST",
+ help="WireMock host (default: localhost)",
+)
+ "--port",
+ default=None,
+ type=int,
+ envvar="WIREMOCK_PORT",
+ help="WireMock port (default: 8080)",
+)
+ "--scheme",
+ default=None,
+ envvar="WIREMOCK_SCHEME",
+ help="http or https (default: http)",
+)
+ "--user", default=None, envvar="WIREMOCK_USER", help="Admin basic auth username"
+)
+ "--password",
+ default=None,
+ envvar="WIREMOCK_PASSWORD",
+ help="Admin basic auth password",
+)
+ "--json",
+ "json_mode",
+ is_flag=True,
+ envvar="WIREMOCK_JSON",
+ help="Output as JSON",
+)
+def cli(ctx, host, port, scheme, user, password, json_mode):
+ """WireMock CLI โ€” manage stubs, requests, scenarios, and recordings."""
+ session = Session.from_env()
+ if host:
+ session.host = host
+ if port:
+ session.port = port
+ if scheme:
+ session.scheme = scheme
+ if user:
+ session.username = user
+ if password:
+ session.password = password
+ client = WireMockClient(
+ host=session.host,
+ port=session.port,
+ scheme=session.scheme,
+ auth=session.auth(),
+ )
+ ctx.obj = client
+ ctx.meta["json_mode"] = json_mode
+
+
+# ---------------------------------------------------------------------------
+# STUB COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def stub():
+ """Manage HTTP stub mappings."""
+
+
[email protected]("--limit", type=int, default=None)
[email protected]("--offset", type=int, default=None)
+def stub_list(ctx, limit, offset):
+ """List all stub mappings."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ mgr = StubsManager(client)
+ try:
+ data = mgr.list(limit=limit, offset=offset)
+ if json_mode:
+ print_json(data)
+ else:
+ mappings = data.get("mappings", [])
+ rows = [
+ (
+ m.get("id", "")[:8] + "...",
+ m.get("name", ""),
+ m.get("request", {}).get("method", ""),
+ m.get("request", {}).get("url", ""),
+ m.get("response", {}).get("status", ""),
+ )
+ for m in mappings
+ ]
+ print_table(
+ ["ID", "Name", "Method", "URL", "Status"],
+ rows,
+ title=f"Stubs ({data.get('total', 0)} total)",
+ )
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def stub_get(ctx, stub_id):
+ """Get a stub mapping by ID."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = StubsManager(client).get(stub_id)
+ print_json(data)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("mapping_json")
+def stub_create(ctx, mapping_json):
+ """Create a stub mapping from JSON string or @file."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ mapping = json.loads(mapping_json)
+ data = StubsManager(client).create(mapping)
+ success(f"Created stub {data.get('id')}", data, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("status", type=int)
[email protected]("--body", default=None, help="Response body")
[email protected]("--content-type", default="application/json")
+def stub_quick(ctx, method, url, status, body, content_type):
+ """Quickly create a stub: METHOD URL STATUS [--body TEXT]."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = StubsManager(client).quick_stub(method, url, status, body, content_type)
+ success(f"Created stub {data.get('id')}", data, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def stub_delete(ctx, stub_id):
+ """Delete a stub mapping by ID."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ StubsManager(client).delete(stub_id)
+ success(f"Deleted stub {stub_id}", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def stub_reset(ctx):
+ """Reset all stubs to defaults."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ StubsManager(client).reset()
+ success("Stubs reset to default mappings", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def stub_save(ctx):
+ """Persist stubs to disk."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ StubsManager(client).save()
+ success("Mappings saved to disk", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("file_path")
+def stub_import(ctx, file_path):
+ """Import stubs from a JSON file."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ with open(file_path) as f:
+ data = json.load(f)
+ result = StubsManager(client).import_stubs(data)
+ success("Stubs imported", result, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+# ---------------------------------------------------------------------------
+# REQUEST COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def request():
+ """Inspect and verify served requests."""
+
+
[email protected]("--limit", type=int, default=None)
+def request_list(ctx, limit):
+ """List recent served requests."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RequestsLog(client).list(limit=limit)
+ if json_mode:
+ print_json(data)
+ else:
+ events = data.get("serveEvents", [])
+ rows = [
+ (
+ e.get("id", "")[:8] + "...",
+ e.get("request", {}).get("method", ""),
+ e.get("request", {}).get("url", ""),
+ e.get("responseDefinition", {}).get("status", ""),
+ e.get("wasMatched", ""),
+ )
+ for e in events
+ ]
+ print_table(
+ ["ID", "Method", "URL", "Status", "Matched"],
+ rows,
+ title=f"Requests ({data.get('total', 0)} total)",
+ )
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("pattern_json")
+def request_find(ctx, pattern_json):
+ """Find requests matching a pattern JSON."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ pattern = json.loads(pattern_json)
+ data = RequestsLog(client).find(pattern)
+ print_json(data)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("pattern_json")
+def request_count(ctx, pattern_json):
+ """Count requests matching a pattern JSON."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ pattern = json.loads(pattern_json)
+ data = RequestsLog(client).count(pattern)
+ if json_mode:
+ print_json(data)
+ else:
+ click.echo(f"Count: {data.get('count', 0)}")
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("unmatched")
+def request_unmatched(ctx):
+ """List unmatched requests."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RequestsLog(client).unmatched()
+ print_json(data)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def request_reset(ctx):
+ """Clear the request journal."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ RequestsLog(client).reset()
+ success("Request journal cleared", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+# ---------------------------------------------------------------------------
+# SCENARIO COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def scenario():
+ """Manage state machine scenarios."""
+
+
+def scenario_list(ctx):
+ """List all scenarios."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = ScenariosManager(client).list()
+ if json_mode:
+ print_json(data)
+ else:
+ scenarios = data.get("scenarios", [])
+ rows = [
+ (
+ s.get("name", ""),
+ s.get("state", ""),
+ s.get("possibleStates", ""),
+ )
+ for s in scenarios
+ ]
+ print_table(
+ ["Name", "Current State", "Possible States"],
+ rows,
+ title="Scenarios",
+ )
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def scenario_set(ctx, name, state):
+ """Set a scenario state."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ ScenariosManager(client).set_state(name, state)
+ success(f"Scenario '{name}' set to state '{state}'", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def scenario_reset(ctx):
+ """Reset all scenarios."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ ScenariosManager(client).reset_all()
+ success("All scenarios reset", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+# ---------------------------------------------------------------------------
+# RECORD COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def record():
+ """Record traffic from a real backend."""
+
+
[email protected]("target_url")
+ "--match-header", multiple=True, help="Headers to capture (can repeat)"
+)
+def record_start(ctx, target_url, match_header):
+ """Start recording traffic proxied to TARGET_URL."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RecordingManager(client).start(
+ target_url, list(match_header) or None
+ )
+ success(f"Recording started โ†’ {target_url}", data, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def record_stop(ctx):
+ """Stop recording and return captured stubs."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RecordingManager(client).stop()
+ if json_mode:
+ print_json(data)
+ else:
+ count = len(data.get("mappings", []))
+ success(f"Recording stopped. {count} stubs captured.", data, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def record_status(ctx):
+ """Check recording status."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RecordingManager(client).status()
+ if json_mode:
+ print_json(data)
+ else:
+ click.echo(f"Status: {data.get('status', 'unknown')}")
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("snapshot")
+def record_snapshot(ctx):
+ """Take a snapshot of current traffic as stubs."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = RecordingManager(client).snapshot()
+ count = len(data.get("mappings", []))
+ success(f"Snapshot: {count} stubs captured", data, json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+# ---------------------------------------------------------------------------
+# SETTINGS COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def settings():
+ """Manage global WireMock settings."""
+
+
+def settings_get(ctx):
+ """Get current global settings."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = SettingsManager(client).get()
+ print_json(data)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+def settings_version(ctx):
+ """Show WireMock server version."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ data = SettingsManager(client).get_version()
+ if json_mode:
+ print_json(data)
+ else:
+ click.echo(f"WireMock version: {data.get('version', 'unknown')}")
+ except Exception as e:
+ error(str(e), json_mode)
+
+
+# ---------------------------------------------------------------------------
+# TOP-LEVEL COMMANDS
+# ---------------------------------------------------------------------------
+
+
+def status(ctx):
+ """Check if WireMock server is running."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ alive = client.is_alive()
+ if json_mode:
+ print_json(
+ {
+ "status": "running" if alive else "stopped",
+ "host": client.host,
+ "port": client.port,
+ }
+ )
+ else:
+ icon = "โœ“" if alive else "โœ—"
+ state = "running" if alive else "stopped"
+ click.echo(f"{icon} WireMock at {client.host}:{client.port} is {state}")
+
+
+def reset_all(ctx):
+ """Full reset: stubs + requests + scenarios."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ r = client.post("/reset")
+ r.raise_for_status()
+ success("Full reset complete", json_mode=json_mode)
+ except Exception as e:
+ error(str(e), json_mode)
+
+
[email protected]("shutdown")
[email protected]_option(prompt="Shutdown the WireMock server?")
+def shutdown(ctx):
+ """Shutdown the WireMock server."""
+ client = ctx.obj
+ json_mode = ctx.meta.get("json_mode", False)
+ try:
+ client.post("/shutdown")
+ success("Shutdown signal sent", json_mode=json_mode)
+ except Exception as e:
+ # Server may drop connection before responding
+ click.echo("Shutdown signal sent (connection may have closed)")
+
+
+if __name__ == "__main__":
+ cli()
diff --git a/wiremock/agent-harness/setup.py b/wiremock/agent-harness/setup.py
new file mode 100644
index 000000000..b292268d0
--- /dev/null
+++ b/wiremock/agent-harness/setup.py
@@ -0,0 +1,14 @@
+from setuptools import setup, find_namespace_packages
+
+setup(
+ name="cli-anything-wiremock",
+ version="0.1.0",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ install_requires=["click>=8.0", "requests>=2.28", "rich>=13.0"],
+ entry_points={
+ "console_scripts": [
+ "cli-anything-wiremock=cli_anything.wiremock.wiremock_cli:cli"
+ ]
+ },
+ python_requires=">=3.9",
+)