#
tokens: 48929/50000 96/104 files (page 1/2)
lines: off (toggle) GitHub
raw markdown copy
This is page 1 of 2. Use http://codebase.md/pv-bhat/vibe-check-mcp-server?lines=false&page={x} to view the full context.

# Directory Structure

```
├── .env.example
├── .github
│   └── workflows
│       ├── ci.yml
│       ├── docker-image.yml
│       └── release.yml
├── .gitignore
├── AGENTS.md
├── alt-test-gemini.js
├── alt-test-openai.js
├── alt-test.js
├── Attachments
│   ├── Template.md
│   ├── VC1.png
│   ├── vc2.png
│   ├── vc3.png
│   ├── vc4.png
│   ├── VCC1.png
│   ├── VCC2.png
│   ├── vibe (1).jpeg
│   ├── vibelogo.png
│   └── vibelogov2.png
├── CHANGELOG.md
├── CITATION.cff
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── docs
│   ├── _toc.md
│   ├── advanced-integration.md
│   ├── agent-prompting.md
│   ├── AGENTS.md
│   ├── api-keys.md
│   ├── architecture.md
│   ├── case-studies.md
│   ├── changelog.md
│   ├── clients.md
│   ├── docker-automation.md
│   ├── gemini.md
│   ├── integrations
│   │   └── cpi.md
│   ├── philosophy.md
│   ├── registry-descriptions.md
│   ├── release-workflows.md
│   ├── technical-reference.md
│   └── TESTING.md
├── examples
│   └── cpi-integration.ts
├── glama.json
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
├── request.json
├── scripts
│   ├── docker-setup.sh
│   ├── install-vibe-check.sh
│   ├── security-check.cjs
│   └── sync-version.mjs
├── SECURITY.md
├── server.json
├── smithery.yaml
├── src
│   ├── cli
│   │   ├── clients
│   │   │   ├── claude-code.ts
│   │   │   ├── claude.ts
│   │   │   ├── cursor.ts
│   │   │   ├── shared.ts
│   │   │   ├── vscode.ts
│   │   │   └── windsurf.ts
│   │   ├── diff.ts
│   │   ├── doctor.ts
│   │   ├── env.ts
│   │   └── index.ts
│   ├── index.ts
│   ├── tools
│   │   ├── constitution.ts
│   │   ├── vibeCheck.ts
│   │   ├── vibeDistil.ts
│   │   └── vibeLearn.ts
│   └── utils
│       ├── anthropic.ts
│       ├── httpTransportWrapper.ts
│       ├── jsonRpcCompat.ts
│       ├── llm.ts
│       ├── state.ts
│       ├── storage.ts
│       └── version.ts
├── test-client.js
├── test-client.ts
├── test.js
├── test.json
├── tests
│   ├── claude-config.test.ts
│   ├── claude-merge.test.ts
│   ├── cli-doctor-node.test.ts
│   ├── cli-doctor-port.test.ts
│   ├── cli-install-dry-run.test.ts
│   ├── cli-install-vscode-dry-run.test.ts
│   ├── cli-start-flags.test.ts
│   ├── cli-version.test.ts
│   ├── constitution.test.ts
│   ├── cursor-merge.test.ts
│   ├── env-ensure.test.ts
│   ├── fixtures
│   │   ├── claude
│   │   │   ├── config.base.json
│   │   │   ├── config.with-managed-entry.json
│   │   │   └── config.with-other-servers.json
│   │   ├── cursor
│   │   │   ├── config.base.json
│   │   │   └── config.with-managed-entry.json
│   │   ├── vscode
│   │   │   ├── workspace.mcp.base.json
│   │   │   └── workspace.mcp.with-managed.json
│   │   └── windsurf
│   │       ├── config.base.json
│   │       ├── config.with-http-entry.json
│   │       └── config.with-managed-entry.json
│   ├── index-main.test.ts
│   ├── jsonrpc-compat.test.ts
│   ├── llm-anthropic.test.ts
│   ├── llm.test.ts
│   ├── server.integration.test.ts
│   ├── startup.test.ts
│   ├── state.test.ts
│   ├── storage-utils.test.ts
│   ├── vibeCheck.test.ts
│   ├── vibeLearn.test.ts
│   ├── vscode-merge.test.ts
│   └── windsurf-merge.test.ts
├── tsconfig.json
├── version.json
└── vitest.config.ts
```

# Files

--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------

```
# Copy this file to .env and fill in your API key.
GOOGLE_CLOUD_PROJECT="mcp-vibetest"
DEFAULT_MODEL=gemini-2.5-flash
DEFAULT_LLM_PROVIDER=gemini
OPENAI_API_KEY=your_openai_key
OPENROUTER_API_KEY=your_openrouter_key
USE_LEARNING_HISTORY=false

```

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Dependencies
node_modules/
npm-debug.log
yarn-debug.log
yarn-error.log

# Build output
build/
dist/
*.tsbuildinfo

# Environment variables
.env
.env.local
.env.*.local

# IDE and editor files
.idea/
.vscode/
*.swp
*.swo
.DS_Store

# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Testing
coverage/
.nyc_output/

# Temporary files
tmp/
temp/

# Local configuration
.npmrc
.mcpregistry_github_token
.mcpregistry_registry_token
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# Vibe Check MCP

<p align="center"><b>KISS overzealous agents goodbye. Plug & play agent oversight tool.</b></p>

<p align="center">
  <b>Based on research:</b><br/>
  In our study agents calling Vibe Check improved success +27% and halved harmful actions -41%
</p>

<p align="center">
  <a href="https://www.researchgate.net/publication/394946231_Do_AI_Agents_Need_Mentors_Evaluating_Chain-Pattern_Interrupt_CPI_for_Oversight_and_Reliability?channel=doi&linkId=68ad6178ca495d76982ff192&showFulltext=true">
    <img src="https://img.shields.io/badge/Research-CPI%20%28MURST%29-blue?style=flat-square" alt="CPI Research">
  </a>
  <a href="https://github.com/modelcontextprotocol/servers"><img src="https://img.shields.io/badge/Anthropic%20MCP-featured-111?labelColor=111&color=555&style=flat-square" alt="Anthropic MCP: listed"></a>
  <a href="https://registry.modelcontextprotocol.io/"><img src="https://img.shields.io/badge/MCP%20Registry-listed-555?labelColor=111&style=flat-square" alt="MCP Registry"></a>
  <a href="https://www.pulsemcp.com/servers/pv-bhat-vibe-check">
    <img src="https://img.shields.io/badge/PulseMCP-Most%20Popular%20(Oct 2025)-0b7285?style=flat-square" alt="PulseMCP: Most Popular (this week)">
  </a>
  <a href="https://github.com/PV-Bhat/vibe-check-mcp-server/actions/workflows/ci.yml"><img src="https://github.com/PV-Bhat/vibe-check-mcp-server/actions/workflows/ci.yml/badge.svg" alt="CI passing"></a>
  <a href="https://smithery.ai/server/@PV-Bhat/vibe-check-mcp-server"><img src="https://smithery.ai/badge/@PV-Bhat/vibe-check-mcp-server" alt="Smithery Badge"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-0b7285?style=flat-square" alt="MIT License"></a>
</p>

<p align="center">
  <sub> Featured on PulseMCP “Most Popular (This Week)” • 5k+ monthly calls on Smithery.ai • research-backed oversight • STDIO + streamable HTTP transport</sub>
</p>

<img width="500" height="300" alt="Gemini_Generated_Image_kvdvp4kvdvp4kvdv" src="https://github.com/user-attachments/assets/ff4d9efa-2142-436d-b1df-2a711a28c34e" />

[![Version](https://img.shields.io/badge/version-2.7.4-purple)](https://github.com/PV-Bhat/vibe-check-mcp-server)
[![Trust Score](https://archestra.ai/mcp-catalog/api/badge/quality/PV-Bhat/vibe-check-mcp-server)](https://archestra.ai/mcp-catalog/pv-bhat__vibe-check-mcp-server)
[![Security 4.3★/5 on MSEEP](https://mseep.ai/badge.svg)](https://mseep.ai/app/a2954e62-a3f8-45b8-9a03-33add8b92599)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-blueviolet)](CONTRIBUTING.md)

*Plug-and-play mentor layer that stops agents from over-engineering and keeps them on the minimal viable path — research-backed MCP server keeping LLMs aligned, reflective and safe.*

<div align="center">
  <a href="https://github.com/PV-Bhat/vibe-check-mcp-server">
    <img src="https://unpkg.com/@lobehub/icons-static-svg@latest/icons/github.svg" width="40" height="40" alt="GitHub" />
  </a>
  &nbsp;&nbsp;
  <a href="https://registry.modelcontextprotocol.io">
    <img src="https://unpkg.com/@lobehub/icons-static-svg@latest/icons/anthropic.svg" width="40" height="40" alt="Anthropic MCP Registry" />
  </a>
  &nbsp;&nbsp;
  <a href="https://smithery.ai/server/@PV-Bhat/vibe-check-mcp-server">
    <img src="https://unpkg.com/@lobehub/icons-static-svg@latest/icons/smithery.svg" width="40" height="40" alt="Smithery" />
  </a>
  &nbsp;&nbsp;
  <a href="https://www.pulsemcp.com/servers/pv-bhat-vibe-check">
    <img src="https://www.pulsemcp.com/favicon.ico" width="40" height="40" alt="PulseMCP" />
  </a>
</div>

<div align="center">
  <em>Trusted by developers across MCP platforms and registries</em>
</div>

## Quickstart (npx)

Run the server directly from npm without a local installation. Requires Node **>=20**. Choose a transport:

### Option 1 – MCP client over STDIO

```bash
npx -y @pv-bhat/vibe-check-mcp start --stdio
```

- Launch from an MCP-aware client (Claude Desktop, Cursor, Windsurf, etc.).
- `[MCP] stdio transport connected` indicates the process is waiting for the client.
- Add this block to your client config so it spawns the command:

```json
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"]
    }
  }
}
```

### Option 2 – Manual HTTP inspection

```bash
npx -y @pv-bhat/vibe-check-mcp start --http --port 2091
```

- `curl http://127.0.0.1:2091/health` to confirm the service is live.
- Send JSON-RPC requests to `http://127.0.0.1:2091/rpc`.

npx downloads the package on demand for both options. For detailed client setup and other commands like `install` and `doctor`, see the documentation below.

[![Star History Chart](https://api.star-history.com/svg?repos=PV-Bhat/vibe-check-mcp-server&type=Date)](https://www.star-history.com/#PV-Bhat/vibe-check-mcp-server&Date)

### Recognition
- Featured on PulseMCP “Most Popular (This Week)” front page (week of 13 Oct 2025) [🔗](https://www.pulsemcp.com/servers/pv-bhat-vibe-check)
- Listed in Anthropic’s official Model Context Protocol repo [🔗](https://github.com/modelcontextprotocol/servers?tab=readme-overview#-community-servers)
- Discoverable in the official MCP Registry [🔗](https://registry.modelcontextprotocol.io/v0/servers?search=vibe-check-mcp)
- Featured on Sean Kochel's Top 9 MCP servers for vibe coders [🔗](https://youtu.be/2wYO6sdQ9xc?si=mlVo4iHf_hPKghxc&t=1331)

## Table of Contents
- [Quickstart (npx)](#quickstart-npx)
- [What is Vibe Check MCP?](#what-is-vibe-check-mcp)
- [Overview](#overview)
- [The Problem: Pattern Inertia & Reasoning Lock-In](#the-problem-pattern-inertia--reasoning-lock-in)
- [Key Features](#key-features)
- [What's New](#whats-new-in-v274)
- [Development Setup](#development-setup)
- [Release](#release)
- [Usage Examples](#usage-examples)
- [Adaptive Metacognitive Interrupts (CPI)](#adaptive-metacognitive-interrupts-cpi)
- [Agent Prompting Essentials](#agent-prompting-essentials)
- [When to Use Each Tool](#when-to-use-each-tool)
- [Documentation](#documentation)
- [Research & Philosophy](#research--philosophy)
- [Security](#security)
- [Roadmap](#roadmap)
- [Contributors & Community](#contributors--community)
- [FAQ](#faq)
- [Listed on](#find-vibe-check-mcp-on)
- [Credits & License](#credits--license)
---
## What is Vibe Check MCP?

Vibe Check MCP keeps agents on the minimal viable path and escalates complexity only when evidence demands it. Vibe Check MCP is a lightweight server implementing Anthropic's [Model Context Protocol](https://anthropic.com/mcp). It acts as an **AI meta-mentor** for your agents, interrupting pattern inertia with **Chain-Pattern Interrupts (CPI)** to prevent Reasoning Lock-In (RLI). Think of it as a rubber-duck debugger for LLMs – a quick sanity check before your agent goes down the wrong path.

## Overview

Vibe Check MCP pairs a metacognitive signal layer with CPI so agents can pause when risk spikes. Vibe Check surfaces traits, uncertainty, and risk scores; CPI consumes those triggers and enforces an intervention policy before the agent resumes. See the [CPI integration guide](./docs/integrations/cpi.md) and the CPI repo at https://github.com/PV-Bhat/cpi for wiring details.

Vibe Check invokes a second LLM to give meta-cognitive feedback to your main agent. Integrating vibe_check calls into agent system prompts and instructing tool calls before irreversible actions significantly improves agent alignment and common-sense. The high-level component map: [docs/architecture.md](./docs/architecture.md), while the CPI handoff diagram and example shim are captured in [docs/integrations/cpi.md](./docs/integrations/cpi.md).

## The Problem: Pattern Inertia & Reasoning Lock-In

Large language models can confidently follow flawed plans. Without an external nudge they may spiral into overengineering or misalignment. Vibe Check provides that nudge through short reflective pauses, improving reliability and safety.

## Key Features

| Feature | Description | Benefits |
|---------|-------------|----------|
| **CPI Adaptive Interrupts** | Phase-aware prompts that challenge assumptions | alignment, robustness |
| **Multi-provider LLM** | Gemini, OpenAI, Anthropic, and OpenRouter support | flexibility |
| **History Continuity** | Summarizes prior advice when `sessionId` is supplied | context retention |
| **Optional vibe_learn** | Log mistakes and fixes for future reflection | self-improvement |

## What's New in v2.7.4

- `install --client` now supports Cursor, Windsurf, and Visual Studio Code with idempotent merges, atomic writes, and `.bak` rollbacks.
- HTTP-aware installers preserve `serverUrl` entries for Windsurf and emit VS Code workspace snippets plus a `vscode:mcp/install` link when no config is provided.
- Documentation now consolidates provider keys, transport selection, uninstall guidance, and dedicated client docs at [docs/clients.md](./docs/clients.md).

## Session Constitution (per-session rules)

Use a lightweight “constitution” to enforce rules per `sessionId` that CPI will honor. Eg. constitution rules: “no external network calls,” “prefer unit tests before refactors,” “never write secrets to disk.”

**API (tools):**
- `update_constitution({ sessionId, rules })` → merges/sets rule set for the session
- `reset_constitution({ sessionId })` → clears session rules
- `check_constitution({ sessionId })` → returns effective rules for the session

## Development Setup
```bash
# Clone and install
git clone https://github.com/PV-Bhat/vibe-check-mcp-server.git
cd vibe-check-mcp-server
npm ci
npm run build
npm test
```
Use **npm** for all workflows (`npm ci`, `npm run build`, `npm test`). This project targets Node **>=20**.

Create a `.env` file with the API keys you plan to use:
```bash
# Gemini (default)
GEMINI_API_KEY=your_gemini_api_key
# Optional providers / Anthropic-compatible endpoints
OPENAI_API_KEY=your_openai_api_key
OPENROUTER_API_KEY=your_openrouter_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
ANTHROPIC_AUTH_TOKEN=your_proxy_bearer_token
ANTHROPIC_BASE_URL=https://api.anthropic.com
ANTHROPIC_VERSION=2023-06-01
# Optional overrides
# DEFAULT_LLM_PROVIDER accepts gemini | openai | openrouter | anthropic
DEFAULT_LLM_PROVIDER=gemini
DEFAULT_MODEL=gemini-2.5-pro
```

#### Configuration 

See [docs/TESTING.md]() for instructions on how to run tests.

### Docker
The repository includes a helper script for one-command setup.
```bash
bash scripts/docker-setup.sh
```
See [Automatic Docker Setup](./docs/docker-automation.md) for full details.

### Provider keys

See [API Keys & Secret Management](./docs/api-keys.md) for supported providers, resolution order, storage locations, and security guidance.

### Transport selection

The CLI supports stdio and HTTP transports. Transport resolution follows this order: explicit flags (`--stdio`/`--http`) → `MCP_TRANSPORT` → default `stdio`. When using HTTP, specify `--port` (or set `MCP_HTTP_PORT`); the default port is **2091**. The generated entries add `--stdio` or `--http --port <n>` accordingly, and HTTP-capable clients also receive a `http://127.0.0.1:<port>` endpoint.

### Client installers

Each installer is idempotent and tags entries with `"managedBy": "vibe-check-mcp-cli"`. Backups are written once per run before changes are applied, and merges are atomic (`*.bak` files make rollback easy). See [docs/clients.md](./docs/clients.md) for deeper client-specific references.

#### Claude Desktop

- Config path: `claude_desktop_config.json` (auto-discovered per platform).
- Default transport: stdio (`npx … start --stdio`).
- Restart Claude Desktop after installation to load the new MCP server.
- If an unmanaged entry already exists for `vibe-check-mcp`, the CLI leaves it untouched and prints a warning.

#### Cursor

- Config path: `~/.cursor/mcp.json` (provide `--config` if you store it elsewhere).
- Schema mirrors Claude’s `mcpServers` layout.
- If the file is missing, the CLI prints a ready-to-paste JSON block for Cursor’s settings panel instead of failing.

#### Windsurf (Cascade)

- Config path: legacy `~/.codeium/windsurf/mcp_config.json`, new builds use `~/.codeium/mcp_config.json`.
- Pass `--http` to emit an entry with `serverUrl` for Windsurf’s HTTP client.
- Existing sentinel-managed `serverUrl` entries are preserved and updated in place.

#### Visual Studio Code

- Workspace config lives at `.vscode/mcp.json`; profiles also store `mcp.json` in your VS Code user data directory.
- Provide `--config <path>` to target a workspace file. Without `--config`, the CLI prints a JSON snippet and a `vscode:mcp/install?...` link you can open directly from the terminal.
- VS Code supports optional dev fields; pass `--dev-watch` and/or `--dev-debug <value>` to populate `dev.watch`/`dev.debug`.

### Uninstall & rollback

- Restore the backup generated during installation (the newest `*.bak` next to your config) to revert immediately.
- To remove the server manually, delete the `vibe-check-mcp` entry under `mcpServers` (Claude/Windsurf/Cursor) or `servers` (VS Code) as long as it is still tagged with `"managedBy": "vibe-check-mcp-cli"`.

## Research & Philosophy

**CPI (Chain-Pattern Interrupt)** is the research-backed oversight method behind Vibe Check. It injects brief, well-timed “pause points” at risk inflection moments to re-align the agent to the user’s true priority, preventing destructive cascades and **reasoning lock-in (RLI)**. In pooled evaluation across 153 runs, CPI **nearly doubles success (~27%→54%) and roughly halves harmful actions (~83%→42%)**. Optimal interrupt **dosage is ~10–20%** of steps. *Vibe Check MCP implements CPI as an external mentor layer at test time.*

**Links:**  
- 📄 **CPI Paper (ResearchGate)** — http://dx.doi.org/10.13140/RG.2.2.18237.93922  
- 📘 **CPI Reference Implementation (GitHub)**: https://github.com/PV-Bhat/cpi
- 📚 **MURST Zenodo DOI (RSRC archival)**: https://doi.org/10.5281/zenodo.14851363

```mermaid
flowchart TD
  A[Agent Phase] --> B{Monitor Progress}
  B -- high risk --> C[CPI Interrupt]
  C --> D[Reflect & Adjust]
  B -- smooth --> E[Continue]
```

## Agent Prompting Essentials
In your agent's system prompt, make it clear that `vibe_check` is a mandatory tool for reflection. Always pass the full user request and other relevant context. After correcting a mistake, you can optionally log it with `vibe_learn` to build a history for future analysis.

Example snippet:
```
As an autonomous agent you will:
1. Call vibe_check after planning and before major actions.
2. Provide the full user request and your current plan.
3. Optionally, record resolved issues with vibe_learn.
```

## When to Use Each Tool
| Tool                   | Purpose                                                      |
|------------------------|--------------------------------------------------------------|
| 🛑 **vibe_check**       | Challenge assumptions and prevent tunnel vision              |
| 🔄 **vibe_learn**       | Capture mistakes, preferences, and successes                 |
| 🧰 **update_constitution** | Set/merge session rules the CPI layer will enforce         |
| 🧹 **reset_constitution**  | Clear rules for a session                                  |
| 🔎 **check_constitution**  | Inspect effective rules for a session                      |

## Documentation
- [Agent Prompting Strategies](./docs/agent-prompting.md)
- [CPI Integration](./docs/integrations/cpi.md)
- [Advanced Integration](./docs/advanced-integration.md)
- [Technical Reference](./docs/technical-reference.md)
- [Automatic Docker Setup](./docs/docker-automation.md)
- [Philosophy](./docs/philosophy.md)
- [Case Studies](./docs/case-studies.md)
- [Changelog](./docs/changelog.md)

## Security
This repository includes a CI-based security scan that runs on every pull request. It checks dependencies with `npm audit` and scans the source for risky patterns. See [SECURITY.md](./SECURITY.md) for details and how to report issues.

## Roadmap (New PRs welcome)

### Priority 1 – Builder Experience & Guidance
- **Structured output for `vibe_check`:** Return a JSON envelope such as `{ advice, riskScore, traits }` so downstream agents can reason deterministically while preserving readable reflections.
- **Agent prompt starter kit:** Publish a plug-and-play system prompt snippet that teaches the CPI dosage principle (10–20% of steps), calls out risk inflection points, and reminds agents to include the last 5–10 tool calls in `taskContext`.
- **Documentation refresh:** Highlight the new prompt template and context requirements throughout the README and integration guides.

### Priority 2 – Core Reliability Requests
- **LLM resilience:** Wrap `generateResponse` in `src/utils/llm.ts` with retries and exponential backoff, with a follow-up circuit breaker once the basics land.
- **Input sanitization:** Validate and cleanse tool arguments in `src/index.ts` to mitigate prompt-injection vectors.
- **State stewardship:** Add TTL-based cleanup in `src/utils/state.ts` and switch `src/utils/storage.ts` file writes to `fs.promises` to avoid blocking the event loop.

These initiatives are tracked as community-facing GitHub issues so contributors can grab them and see progress in the open.

### Additional Follow-On Ideas & Good First Issues
- **Telemetry sanity checks:** Add a lint-style CI step that verifies `docs/` examples compile (e.g., TypeScript snippet type-check) to catch drift between docs and code.
- **CLI help polish:** Ensure every CLI subcommand prints a concise `--help` example aligned with the refreshed prompt guidance.
- **Docs navigation cleanup:** Cross-link `docs/agent-prompting.md` and `docs/technical-reference.md` from the README section headers to reduce context switching for new contributors.

## Contributors & Community
Contributions are welcome! See [CONTRIBUTING.md](./CONTRIBUTING.md).

<a href="https://github.com/PV-Bhat/vibe-check-mcp-server/graphs/contributors">
  <img src="https://contrib.rocks/image?repo=PV-Bhat/vibe-check-mcp-server" alt="Contributors"/>
</a> 

## Links
* [MSEEP](https://mseep.ai/app/pv-bhat-vibe-check-mcp-server)
* [MCP Servers](https://mcpservers.org/servers/PV-Bhat/vibe-check-mcp-server)
* [MCP.so](https://mcp.so/server/vibe-check-mcp-server/PV-Bhat)
* [Creati.ai](https://creati.ai/mcp/vibe-check-mcp-server/)
* [Pulse MCP](https://www.pulsemcp.com/servers/pv-bhat-vibe-check)
* [Playbooks.com](https://playbooks.com/mcp/pv-bhat-vibe-check)
* [MCPHub.tools](https://mcphub.tools/detail/PV-Bhat/vibe-check-mcp-server)
* [MCP Directory](https://mcpdirectory.ai/mcpserver/2419/)

## Credits & License
Vibe Check MCP is released under the [MIT License](LICENSE). Built for reliable, enterprise-ready AI agents.

## Author Credits & Links
Vibe Check MCP created by: [Pruthvi Bhat](https://pruthvibhat.com/), Initiative - https://murst.org/

```

--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------

```markdown
# Code of Conduct

This project adheres to the [Contributor Covenant](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) Code of Conduct. By participating, you are expected to uphold this code.

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the maintainer listed in `package.json`.

```

--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------

```markdown
# Security Policy

VibeCheck MCP is designed as a lightweight oversight layer for AI coding agents. While it does not execute code on behalf of the agent, it processes user prompts and sends them to third‑party LLM APIs. This document outlines our approach to keeping that process secure.

## Supported Versions
Only the latest release receives security updates. Please upgrade regularly to stay protected.

## Threat Model
- **Prompt injection**: malicious text could attempt to alter the meta-mentor instructions. VibeCheck uses a fixed system prompt and validates required fields to mitigate this.
- **Tool misuse**: the server exposes only two safe tools (`vibe_check` and `vibe_learn`). No command execution or file access is performed.
- **Data leakage**: requests are forwarded to the configured LLM provider. Avoid sending sensitive data if using hosted APIs. The optional `vibe_learn` log can be disabled via environment variables.
- **Impersonation**: run VibeCheck only from this official repository or the published npm package. Verify the source before deployment.

## Reporting a Vulnerability
If you discover a security issue, please open a private GitHub issue or email the maintainer listed in `package.json`. We will acknowledge your report within 48 hours and aim to provide a fix promptly.

## Continuous Security
A custom security scan runs in CI on every pull request. It checks dependencies for known vulnerabilities and searches the source tree for dangerous patterns. The workflow fails if any issue is detected.


```

--------------------------------------------------------------------------------
/AGENTS.md:
--------------------------------------------------------------------------------

```markdown
# Agent Quickstart

Vibe Check MCP is a lightweight oversight layer for AI agents. It exposes two tools:

- **vibe_check** – prompts you with clarifying questions to prevent tunnel vision.
- **vibe_learn** – optional logging of mistakes and successes for later review.

The server supports Gemini, OpenAI, Anthropic, and OpenRouter LLMs. History is maintained across requests when a `sessionId` is provided.

## Setup

1. Install dependencies and build:
   ```bash
   npm install
   npm run build
   ```
2. Supply the following environment variables as needed:
   - `GEMINI_API_KEY`
   - `OPENAI_API_KEY`
   - `OPENROUTER_API_KEY`
   - `ANTHROPIC_API_KEY` *(official Anthropic deployments)*
   - `ANTHROPIC_AUTH_TOKEN` *(Anthropic-compatible proxies)*
   - `ANTHROPIC_BASE_URL` *(optional; defaults to https://api.anthropic.com)*
   - `ANTHROPIC_VERSION` *(optional; defaults to 2023-06-01)*
   - `DEFAULT_LLM_PROVIDER` (gemini | openai | openrouter | anthropic)
   - `DEFAULT_MODEL` (e.g., gemini-2.5-pro)
3. Start the server:
   ```bash
   npm start
   ```

## Testing

Run unit tests with `npm test`. Example request generators are provided:

- `alt-test-gemini.js`
- `alt-test-openai.js`
- `alt-test.js` (OpenRouter)

Each script writes a `request.json` file that you can pipe to the server:

```bash
node build/index.js < request.json
```

## Integration Tips

Call `vibe_check` regularly with your goal, plan and current progress. Use `vibe_learn` whenever you want to record a resolved issue. Full API details are in `docs/technical-reference.md`.

```

--------------------------------------------------------------------------------
/docs/AGENTS.md:
--------------------------------------------------------------------------------

```markdown
# Agent Quickstart

Vibe Check MCP is a lightweight oversight layer for AI agents. It exposes two tools:

- **vibe_check** – prompts you with clarifying questions to prevent tunnel vision.
- **vibe_learn** – optional logging of mistakes and successes for later review.

The server supports Gemini, OpenAI, Anthropic, and OpenRouter LLMs. History is maintained across requests when a `sessionId` is provided.

## Setup

1. Install dependencies and build:
   ```bash
   npm install
   npm run build
   ```
2. Supply the following environment variables as needed:
   - `GEMINI_API_KEY`
   - `OPENAI_API_KEY`
   - `OPENROUTER_API_KEY`
   - `ANTHROPIC_API_KEY` *(official Anthropic deployments)*
   - `ANTHROPIC_AUTH_TOKEN` *(Anthropic-compatible proxies)*
   - `ANTHROPIC_BASE_URL` *(optional; defaults to https://api.anthropic.com)*
   - `ANTHROPIC_VERSION` *(optional; defaults to 2023-06-01)*
   - `DEFAULT_LLM_PROVIDER` (gemini | openai | openrouter | anthropic)
   - `DEFAULT_MODEL` (e.g., gemini-2.5-pro)
3. Start the server:
   ```bash
   npm start
   ```

## Testing

Run unit tests with `npm test`. The JSON-RPC compatibility shim mitigates missing `id` fields on `tools/call` requests so the standard SDK client and Windsurf work without extra tooling, but compliant clients should continue to send their own identifiers. Example request generators remain available if you want canned payloads for manual testing:

- `alt-test-gemini.js`
- `alt-test-openai.js`
- `alt-test.js` (OpenRouter)

Each script writes a `request.json` file that you can pipe to the server:

```bash
node build/index.js < request.json
```

## Integration Tips

Call `vibe_check` regularly with your goal, plan and current progress. Use `vibe_learn` whenever you want to record a resolved issue. Full API details are in `docs/technical-reference.md`.

```

--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------

```markdown
# Contributing to Vibe Check MCP

First off, thanks for considering contributing to Vibe Check! It's people like you that help make this metacognitive oversight layer even better.

## The Vibe of Contributing

Contributing to Vibe Check isn't just about code—it's about joining a community that's trying to make AI agents a bit more self-aware (since they're not quite there yet on their own).

### The Basic Flow

1. **Find something to improve**: Did your agent recently go off the rails in a way Vibe Check could have prevented? Found a bug? Have an idea for a new feature? That's a great starting point.

2. **Fork & clone**: The standard GitHub dance. Fork the repo, clone it locally, and create a branch for your changes.

### Local setup

- Use Node **>=20**.
- Use **npm** for everything: `npm ci`, `npm run build`, `npm test`.

3. **Make your changes**: Whether it's code, documentation, or just fixing a typo, all contributions are welcome.

4. **Test your changes**: Make sure everything still works as expected.

5. **Submit a PR**: Push your changes to your fork and submit a pull request. We'll review it as soon as we can.

## Vibe Check Your Contributions

Before submitting a PR, run your own mental vibe check on your changes:

- Does this align with the metacognitive purpose of Vibe Check?
- Is this addressing a real problem that AI agents face?
- Does this maintain the balance between developer-friendly vibes and serious AI alignment principles?

## What We're Looking For

### Code Contributions

- Bug fixes
- Performance improvements
- New features that align with the project's purpose
- Improvements to the metacognitive questioning system

### Documentation Contributions

- Clarifications to existing documentation
- New examples of how to use Vibe Check effectively
- Case studies of how Vibe Check has helped your agent workflows
- Tutorials for integration with different systems

### Pattern Contributions

- New categories for the `vibe_learn` system
- Common error patterns you've observed in AI agent workflows
- Metacognitive questions that effectively break pattern inertia

## Coding Style

- TypeScript with clear typing
- Descriptive variable names
- Comments that explain the "why," not just the "what"
- Tests for new functionality

## The Review Process

Once you submit a PR, here's what happens:

1. A maintainer will review your submission
2. They might suggest some changes or improvements
3. Once everything looks good, they'll merge your PR
4. Your contribution becomes part of Vibe Check!

## Share Your Vibe Stories

We love hearing how people are using Vibe Check in the wild. If you have a story about how Vibe Check saved your agent from a catastrophic reasoning failure or helped simplify an overcomplicated plan, we'd love to hear about it! Submit it as an issue with the tag "vibe story" or mention it in your PR.

## Code of Conduct

- Be respectful and constructive in all interactions
- Focus on the code, not the person
- Help create a welcoming community for all contributors

## Questions?

If you have any questions about contributing, feel free to open an issue with your question. We're here to help!

Thanks again for considering a contribution to Vibe Check. Together, we can make AI agents a little more self-aware, one pattern interrupt at a time.
```

--------------------------------------------------------------------------------
/Attachments/Template.md:
--------------------------------------------------------------------------------

```markdown
Template

```

--------------------------------------------------------------------------------
/src/tools/vibeDistil.ts:
--------------------------------------------------------------------------------

```typescript
// Deleted
```

--------------------------------------------------------------------------------
/version.json:
--------------------------------------------------------------------------------

```json
{
  "version": "2.7.6"
}

```

--------------------------------------------------------------------------------
/glama.json:
--------------------------------------------------------------------------------

```json
{
  "$schema": "https://glama.ai/mcp/schemas/server.json",
  "maintainers": [
    "PV-Bhat"
  ]
}

```

--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------

```dockerfile
FROM node:lts-alpine

WORKDIR /app

COPY . .

RUN npm install --ignore-scripts
RUN npm run build

EXPOSE 3000

CMD ["node", "build/index.js"]

```

--------------------------------------------------------------------------------
/tests/fixtures/vscode/workspace.mcp.base.json:
--------------------------------------------------------------------------------

```json
{
  "servers": {
    "other": {
      "command": "node",
      "args": ["tool.js"],
      "env": {
        "LOG": "debug"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/cursor/config.base.json:
--------------------------------------------------------------------------------

```json
{
  "mcpServers": {
    "other": {
      "command": "python",
      "args": ["tool.py"],
      "env": {
        "TOKEN": "abc"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/windsurf/config.base.json:
--------------------------------------------------------------------------------

```json
{
  "mcpServers": {
    "existing": {
      "command": "npm",
      "args": ["run", "tool"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/claude/config.base.json:
--------------------------------------------------------------------------------

```json
{
  "theme": "system",
  "mcpServers": {
    "other-server": {
      "command": "node",
      "args": ["other.js"],
      "env": {
        "TOKEN": "abc123"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/claude/config.with-other-servers.json:
--------------------------------------------------------------------------------

```json
{
  "theme": "system",
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "node",
      "args": ["legacy.js"],
      "env": {}
    },
    "another": {
      "command": "python",
      "args": ["server.py"],
      "env": {
        "DEBUG": "1"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/windsurf/config.with-http-entry.json:
--------------------------------------------------------------------------------

```json
{
  "mcpServers": {
    "vibe-check-mcp": {
      "serverUrl": "http://127.0.0.1:2091",
      "managedBy": "vibe-check-mcp-cli"
    },
    "existing": {
      "command": "npm",
      "args": ["run", "tool"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/.github/workflows/docker-image.yml:
--------------------------------------------------------------------------------

```yaml
name: Docker Image CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4
    - name: Build the Docker image
      run: docker build . --file Dockerfile --tag my-image-name:$(date +%s)

```

--------------------------------------------------------------------------------
/docs/_toc.md:
--------------------------------------------------------------------------------

```markdown
# Documentation map

- [Architecture](./architecture.md)
- Integrations
  - [CPI Integration](./integrations/cpi.md)
- [Advanced Integration](./advanced-integration.md)
- [Technical Reference](./technical-reference.md)
- [Agent Prompting](./agent-prompting.md)
- [Release & Versioning](./release-workflows.md)

```

--------------------------------------------------------------------------------
/tests/fixtures/cursor/config.with-managed-entry.json:
--------------------------------------------------------------------------------

```json
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["@pv-bhat/vibe-check-mcp", "start"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    },
    "other": {
      "command": "python",
      "args": ["tool.py"],
      "env": {
        "TOKEN": "abc"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/src/cli/diff.ts:
--------------------------------------------------------------------------------

```typescript
import { createTwoFilesPatch } from 'diff';

export function formatUnifiedDiff(oldText: string, newText: string, filePath: string): string {
  const fromFile = `${filePath} (current)`;
  const toFile = `${filePath} (proposed)`;
  return createTwoFilesPatch(fromFile, toFile, oldText, newText, '', '', { context: 3 });
}

```

--------------------------------------------------------------------------------
/request.json:
--------------------------------------------------------------------------------

```json
{"jsonrpc":"2.0","method":"tools/call","params":{"name":"vibe_check","arguments":{"goal":"Test session history functionality","plan":"2. Make a second call to verify history is included.","userPrompt":"Please test the history feature.","progress":"Just made the second call.","sessionId":"history-test-session-1"}},"id":2}
```

--------------------------------------------------------------------------------
/tests/fixtures/claude/config.with-managed-entry.json:
--------------------------------------------------------------------------------

```json
{
  "theme": "system",
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["@pv-bhat/vibe-check-mcp", "start"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    },
    "other": {
      "command": "ruby",
      "args": ["tool.rb"],
      "env": {
        "LEVEL": "info"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/windsurf/config.with-managed-entry.json:
--------------------------------------------------------------------------------

```json
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    },
    "existing": {
      "command": "npm",
      "args": ["run", "tool"],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tests/fixtures/vscode/workspace.mcp.with-managed.json:
--------------------------------------------------------------------------------

```json
{
  "servers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "transport": "stdio",
      "managedBy": "vibe-check-mcp-cli"
    },
    "other": {
      "command": "node",
      "args": ["tool.js"],
      "env": {
        "LOG": "debug"
      }
    }
  }
}

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "outDir": "build",
    "strict": true,
    "declaration": false,
    "sourceMap": false,
    "types": [
      "node",
      "vitest/globals"
    ]
  },
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

```

--------------------------------------------------------------------------------
/alt-test-gemini.js:
--------------------------------------------------------------------------------

```javascript

import fs from 'fs';

const request = JSON.stringify({
    jsonrpc: '2.0',
    method: 'tools/call',
    params: {
        name: 'vibe_check',
        arguments: {
            goal: 'Test default Gemini provider',
            plan: '2. Make a call to vibe_check using the default Gemini provider.',
        }
    },
    id: 2
});

fs.writeFileSync('request.json', request, 'utf-8');

console.log('Generated request.json for the Gemini test.');

```

--------------------------------------------------------------------------------
/vitest.config.ts:
--------------------------------------------------------------------------------

```typescript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'node',
    globals: true,
    include: ['tests/**/*.test.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'html', 'json-summary'],
      all: true,
      include: ['src/**/*.ts'],
      exclude: ['**/alt-test*.js', 'test-client.*', 'src/tools/vibeDistil.ts', 'src/tools/vibeLearn.ts'],
      thresholds: { lines: 80 }
    }
  }
});

```

--------------------------------------------------------------------------------
/src/utils/version.ts:
--------------------------------------------------------------------------------

```typescript
import { createRequire } from 'module';

const require = createRequire(import.meta.url);

let cachedVersion: string | null = null;

export function getPackageVersion(): string {
  if (cachedVersion) {
    return cachedVersion;
  }

  const pkg = require('../../package.json') as { version?: string };
  const version = pkg?.version;

  if (!version) {
    throw new Error('Package version is missing from package.json');
  }

  cachedVersion = version;
  return cachedVersion;
}

```

--------------------------------------------------------------------------------
/test.json:
--------------------------------------------------------------------------------

```json
{"id":"1","jsonrpc":"2.0","method":"tools/call","params":{"name":"vibe_check","arguments":{"goal":"Implement the core logic for the new feature","plan":"1. Define the data structures. 2. Implement the main algorithm. 3. Add error handling.","userPrompt":"Create a new feature that does X, Y, and Z.","progress":"Just started","uncertainties":["The third-party API might be unreliable"],"taskContext":"This is part of a larger project to refactor the billing module.","sessionId":"test-session-123"}}}
```

--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------

```markdown
# Changelog

## Unreleased

- Introduce CLI scaffold and npx bin (no commands yet).

## v2.7.1 - 2025-10-11

- Added `install --client cursor|windsurf|vscode` adapters with managed-entry merges, atomic writes, and `.bak` rollbacks.
- Preserved Windsurf `serverUrl` HTTP entries and emitted VS Code workspace snippets plus `vscode:mcp/install` links when configs are absent.
- Updated documentation with consolidated provider-key guidance, transport selection, uninstall tips, and a dedicated [clients guide](docs/clients.md).

```

--------------------------------------------------------------------------------
/alt-test-openai.js:
--------------------------------------------------------------------------------

```javascript

import fs from 'fs';

const request = JSON.stringify({
    jsonrpc: '2.0',
    method: 'tools/call',
    params: {
        name: 'vibe_check',
        arguments: {
            goal: 'Test OpenAI provider',
            plan: '1. Make a call to vibe_check using the OpenAI provider.',
            modelOverride: { 
              provider: 'openai', 
              model: 'o4-mini' 
            }
        }
    },
    id: 1
});

fs.writeFileSync('request.json', request, 'utf-8');

console.log('Generated request.json for the OpenAI test.');

```

--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------

```yaml
name: ci

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  fast-checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npm run build
      - run: npm run test
      - run: node build/cli/index.js doctor
      - run: node build/cli/index.js start --stdio --dry-run
      - run: node build/cli/index.js start --http --port 2091 --dry-run
      - name: Security Scan
        run: npm run security-check

```

--------------------------------------------------------------------------------
/docs/registry-descriptions.md:
--------------------------------------------------------------------------------

```markdown
# Registry Descriptions

These short descriptions can be used when submitting VibeCheck MCP to external registries or directories.

## Smithery.ai
```
Metacognitive oversight MCP server for AI agents – adaptive CPI interrupts for alignment and safety.
```

## Glama Directory
```
Metacognitive layer for Llama-compatible agents via MCP. Enhances reflection, accountability and robustness.
```

## Awesome MCP Lists PR Draft
```
- [VibeCheck MCP](https://github.com/PV-Bhat/vibe-check-mcp-server) - Adaptive sanity check server preventing cascading errors in AI agents.
```

```

--------------------------------------------------------------------------------
/test-client.ts:
--------------------------------------------------------------------------------

```typescript
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { spawn } from 'child_process';

async function testVibeCheck() {
  const serverProcess = spawn('node', ['build/index.js'], { stdio: ['pipe', 'pipe', 'pipe'] });

  await new Promise(resolve => setTimeout(resolve, 1000));

  const transport = new StdioClientTransport(serverProcess);
  const client = new Client(transport);

  const response = await client.tool('vibe_check', { goal: 'Test goal', plan: 'Test plan', progress: 'Initial stage' });

  console.log('Response:', response);

  await transport.close();
  serverProcess.kill();
}

testVibeCheck();
```

--------------------------------------------------------------------------------
/docs/changelog.md:
--------------------------------------------------------------------------------

```markdown
# Changelog

## v2.5.0 — 2025-09-03
- Transport: migrate STDIO → Streamable HTTP (`POST /mcp`, `GET /mcp` → 405).
- Constitution tools: `update_constitution`, `reset_constitution`, `check_constitution` (session-scoped, in-memory, logged).
- CPI surfaced: banner + concise metrics; links to ResearchGate, CPI GitHub, and Zenodo (MURST).

## v2.2.0 - 2025-07-22
- CPI architecture enables adaptive interrupts to mitigate Reasoning Lock-In
- History continuity across sessions
- Multi-provider support for Gemini, OpenAI and OpenRouter
- Optional vibe_learn logging for privacy-conscious deployments
- Repository restructured with Vitest unit tests and CI workflow

## v1.1.0 - 2024-06-10
- Initial feedback loop and Docker setup

```

--------------------------------------------------------------------------------
/tests/constitution.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect } from 'vitest';
import { updateConstitution, resetConstitution, getConstitution, __testing } from '../src/tools/constitution.js';

describe('constitution utilities', () => {
  it('updates, resets, and retrieves rules', () => {
    updateConstitution('s1', 'r1');
    updateConstitution('s1', 'r2');
    expect(getConstitution('s1')).toEqual(['r1', 'r2']);

    resetConstitution('s1', ['a']);
    expect(getConstitution('s1')).toEqual(['a']);
  });

  it('cleans up stale sessions', () => {
    updateConstitution('s2', 'rule');
    const map = __testing._getMap();
    map['s2'].updated = Date.now() - 2 * 60 * 60 * 1000;
    __testing.cleanup();
    expect(getConstitution('s2')).toEqual([]);
  });
});

```

--------------------------------------------------------------------------------
/server.json:
--------------------------------------------------------------------------------

```json
{
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json",
  "name": "io.github.PV-Bhat/vibe-check-mcp-server",
  "description": "Metacognitive AI agent oversight: adaptive CPI interrupts for alignment, reflection and safety",
  "status": "active",
  "repository": {
    "url": "https://github.com/PV-Bhat/vibe-check-mcp-server",
    "source": "github"
  },
  "version": "1.0.0",
  "packages": [
  {
    "registry_type": "npm",
    "identifier": "@pv-bhat/vibe-check-mcp",
    "version": "2.5.1",
    "transport": {
      "type": "stdio"
    },
    "environment_variables": [
      {
        "description": "Your API key for the service",
        "is_required": true,
        "format": "string",
        "is_secret": true,
        "name": "YOUR_API_KEY"
      }
    ]
  }
  ]
}
```

--------------------------------------------------------------------------------
/tests/cli-version.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect } from 'vitest';
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

describe('CLI version', () => {
  it('prints the package version', () => {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    const projectRoot = resolve(__dirname, '..');
    const cliPath = resolve(projectRoot, 'build', 'cli', 'index.js');
    expect(existsSync(cliPath)).toBe(true);

    const output = execFileSync('node', [cliPath, '--version'], { encoding: 'utf8' }).trim();
    const pkg = JSON.parse(readFileSync(resolve(projectRoot, 'package.json'), 'utf8')) as { version: string };

    expect(output).toBe(pkg.version);
  });
});

```

--------------------------------------------------------------------------------
/tests/index-main.test.ts:
--------------------------------------------------------------------------------

```typescript
import { afterEach, describe, expect, it, vi } from 'vitest';

describe('main entrypoint', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('initializes the HTTP server when stdio transport is disabled', async () => {
    vi.resetModules();
    const module = await import('../src/index.js');
    const serverMock = { connect: vi.fn() } as unknown as import('@modelcontextprotocol/sdk/server/index.js').Server;
    const startMock = vi
      .fn<Parameters<typeof module.startHttpServer>, ReturnType<typeof module.startHttpServer>>()
      .mockResolvedValue({ app: {} as any, listener: { close: vi.fn() } as any, transport: {} as any, close: vi.fn() });

    await module.main({
      createServer: async () => serverMock,
      startHttp: startMock,
    });

    expect(startMock).toHaveBeenCalledWith(expect.objectContaining({ server: serverMock, attachSignalHandlers: true, logger: console }));
  });
});

```

--------------------------------------------------------------------------------
/src/utils/httpTransportWrapper.ts:
--------------------------------------------------------------------------------

```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

import type { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';

export interface RequestScopeStore {
  forceJson?: boolean;
}

const WRAPPED_SYMBOL: unique symbol = Symbol.for('vibe-check.requestScopedTransport');

export function createRequestScopedTransport(
  transport: StreamableHTTPServerTransport,
  scope: AsyncLocalStorage<RequestScopeStore>
): StreamableHTTPServerTransport {
  const existing = (transport as any)[WRAPPED_SYMBOL];
  if (existing) {
    return transport;
  }

  let storedValue = (transport as any)._enableJsonResponse ?? false;

  Object.defineProperty(transport, '_enableJsonResponse', {
    configurable: true,
    enumerable: false,
    get() {
      const store = scope.getStore();
      if (store?.forceJson) {
        return true;
      }
      return storedValue;
    },
    set(value: boolean) {
      storedValue = value;
    }
  });

  (transport as any)[WRAPPED_SYMBOL] = true;
  return transport;
}

```

--------------------------------------------------------------------------------
/test-client.js:
--------------------------------------------------------------------------------

```javascript
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';

async function main() {
  const transport = new StdioClientTransport({ command: 'node', args: ['build/index.js'] });
  const client = new Client({ transport });

  const request = {
    name: 'vibe_check',
    arguments: {
      goal: 'Implement the core logic for the new feature',
      plan: '1. Define the data structures. 2. Implement the main algorithm. 3. Add error handling.',
      userPrompt: 'Create a new feature that does X, Y, and Z.',
      progress: 'Just started',
      uncertainties: ['The third-party API might be unreliable'],
      taskContext: 'This is part of a larger project to refactor the billing module.',
      sessionId: 'test-session-123',
    },
  };

  try {
    await client.connect();
    const response = await client.callTool(request.name, request.arguments);
    console.log(JSON.stringify(response, null, 2));
  } catch (error) {
    console.error(error);
  } finally {
    transport.destroy();
  }
}

main();
```

--------------------------------------------------------------------------------
/test.js:
--------------------------------------------------------------------------------

```javascript
import { spawn } from 'child_process';const server = spawn('node', ['build/index.js']);const request = {  id: '1',  jsonrpc: '2.0',  method: 'tools/call',  params: {    name: 'vibe_check',    arguments: {      goal: 'Implement the core logic for the new feature',      plan: '1. Define the data structures. 2. Implement the main algorithm. 3. Add error handling.',      userPrompt: 'Create a new feature that does X, Y, and Z.',      progress: 'Just started',      uncertainties: ['The third-party API might be unreliable'],      taskContext: 'This is part of a larger project to refactor the billing module.',      sessionId: 'test-session-123',    },  },};const message = JSON.stringify(request);const length = Buffer.byteLength(message, 'utf-8');const header = `Content-Length: ${length}\r\n\r\n`;server.stdout.on('data', (data) => {  console.log(`${data}`);});server.stderr.on('data', (data) => {  console.error(`stderr: ${data}`);});server.on('close', (code) => {  console.log(`child process exited with code ${code}`);});server.stdin.write(header);server.stdin.write(message);server.stdin.end();
```

--------------------------------------------------------------------------------
/tests/state.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect, beforeEach, vi } from 'vitest';
import * as fs from 'fs/promises';
import { loadHistory, getHistorySummary, addToHistory } from '../src/utils/state.js';

vi.mock('fs/promises');
const mockedFs = fs as unknown as { readFile: ReturnType<typeof vi.fn>; writeFile: ReturnType<typeof vi.fn>; mkdir: ReturnType<typeof vi.fn>; };

beforeEach(async () => {
  vi.clearAllMocks();
  mockedFs.mkdir = vi.fn();
  mockedFs.readFile = vi.fn().mockResolvedValue('{}');
  mockedFs.writeFile = vi.fn();
  await loadHistory();
});

describe('state history', () => {
  it('initializes empty history if none', async () => {
    mockedFs.readFile.mockRejectedValue(new Error('missing'));
    await loadHistory();
    expect(getHistorySummary('none')).toBe('');
  });

  it('adds to history and trims to 10', async () => {
    mockedFs.readFile.mockRejectedValue(new Error('missing'));
    await loadHistory();
    for (let i = 1; i <= 11; i++) {
      addToHistory('sess', { goal: `g${i}`, plan: `p${i}` }, `o${i}`);
    }
    await Promise.resolve();
    const summary = getHistorySummary('sess');
    expect(summary).toContain('g7');
    expect(summary).not.toContain('g2');
  });
});

```

--------------------------------------------------------------------------------
/tests/vibeLearn.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { vibeLearnTool } from '../src/tools/vibeLearn.js';
import * as storage from '../src/utils/storage.js';

vi.mock('../src/utils/storage.js');

const mockedStorage = storage as unknown as {
  addLearningEntry: ReturnType<typeof vi.fn>;
  getLearningCategorySummary: ReturnType<typeof vi.fn>;
  getLearningEntries: ReturnType<typeof vi.fn>;
};

beforeEach(() => {
  vi.clearAllMocks();
  mockedStorage.addLearningEntry = vi.fn(() => ({
    type: 'mistake',
    category: 'Test',
    mistake: 'm',
    solution: 's',
    timestamp: Date.now()
  }));
  mockedStorage.getLearningEntries = vi.fn(() => ({ Test: [] }));
  mockedStorage.getLearningCategorySummary = vi.fn(() => [{ category: 'Test', count: 1, recentExample: { mistake: 'm', solution: 's', type: 'mistake', timestamp: Date.now() } }]);
});

describe('vibeLearnTool', () => {
  it('logs entry and returns summary', async () => {
    const res = await vibeLearnTool({ mistake: 'm', category: 'Test', solution: 's' });
    expect(res.added).toBe(true);
    expect(mockedStorage.addLearningEntry).toHaveBeenCalled();
    expect(res.topCategories[0].category).toBe('Test');
  });
});

```

--------------------------------------------------------------------------------
/docs/docker-automation.md:
--------------------------------------------------------------------------------

```markdown
# Automatic Docker Setup

This guide shows how to run the Vibe Check MCP server in Docker and configure it to start automatically with Cursor.

## Prerequisites

- Docker and Docker Compose installed and available in your `PATH`.
- A Gemini API key for the server.

## Quick Start

Run the provided setup script from the repository root:

```bash
bash scripts/docker-setup.sh
```

The script performs the following actions:

1. Creates `~/vibe-check-mcp` and copies required files.
2. Builds the Docker image and sets up `docker-compose.yml`.
3. Prompts for your `GEMINI_API_KEY` and stores it in `~/vibe-check-mcp/.env`.
4. Configures a systemd service on Linux or a LaunchAgent on macOS so the container starts on login.
5. Generates `vibe-check-tcp-wrapper.sh` which proxies STDIO to the container on port 3000.
6. Starts the container in the background.

After running the script, configure Cursor IDE:

1. Open **Settings** → **MCP**.
2. Choose **Add New MCP Server**.
3. Set the type to **Command** and use the wrapper script path:
   `~/vibe-check-mcp/vibe-check-tcp-wrapper.sh`.
4. Save and refresh.

Vibe Check MCP will now launch automatically whenever you log in and be available to Cursor without additional manual steps.

```

--------------------------------------------------------------------------------
/src/utils/anthropic.ts:
--------------------------------------------------------------------------------

```typescript
export interface AnthropicConfig {
  baseUrl: string;
  apiKey?: string;
  authToken?: string;
  version: string;
}

export interface AnthropicHeaderInput {
  apiKey?: string;
  authToken?: string;
  version: string;
}

export function resolveAnthropicConfig(): AnthropicConfig {
  const trimmedBase = process.env.ANTHROPIC_BASE_URL?.replace(/\/+$/, '');
  const baseUrl = trimmedBase && trimmedBase.length > 0 ? trimmedBase : 'https://api.anthropic.com';
  const apiKey = process.env.ANTHROPIC_API_KEY;
  const authToken = process.env.ANTHROPIC_AUTH_TOKEN;
  const version = process.env.ANTHROPIC_VERSION || '2023-06-01';

  if (!apiKey && !authToken) {
    throw new Error(
      'Anthropic configuration error: set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN when provider "anthropic" is selected.'
    );
  }

  return {
    baseUrl,
    apiKey,
    authToken,
    version,
  };
}

export function buildAnthropicHeaders({ apiKey, authToken, version }: AnthropicHeaderInput): Record<string, string> {
  const headers: Record<string, string> = {
    'content-type': 'application/json',
    'anthropic-version': version,
  };

  if (apiKey) {
    headers['x-api-key'] = apiKey;
  } else if (authToken) {
    headers.authorization = `Bearer ${authToken}`;
  }

  return headers;
}

```

--------------------------------------------------------------------------------
/smithery.yaml:
--------------------------------------------------------------------------------

```yaml
# Smithery configuration file: https://smithery.ai/docs/config#smitheryyaml

# Metadata for discoverability and registry listing
name: vibe-check-mcp
version: 2.5.0
description: Metacognitive AI agent oversight tool implementing CPI-driven interrupts for alignment and safety.
author: PV-Bhat
repository: https://github.com/PV-Bhat/vibe-check-mcp-server
license: MIT
category: ai-tools
tags:
  - cpi chain pattern interrupts
  - pruthvi bhat
  - rli reasoning lock in
  - murst
  - metacognition
  - workflow-optimization
  - gemini
  - openai
  - openrouter
capabilities:
  - meta-mentorship
  - agentic oversight
  - chain pattern-interrupt
  - vibe-check
  - self-improving-feedback
  - multi-provider-llm

# Requirements (e.g., for local setup)
requirements:
  node: ">=18.0.0"

# Installation options
installation:
  npm: "@mseep/vibe-check-mcp"  # For manual npm install

startCommand:
  type: http
  command: node build/index.js
  env:
    MCP_HTTP_PORT: "3000"
    MCP_DISCOVERY_MODE: "1"

http:
  endpoint: "/mcp"
  cors:
    origin: "${CORS_ORIGIN:-*}"

# Documentation links
documentation:
  getting_started: https://github.com/PV-Bhat/vibe-check-mcp-server#installation
  configuration: https://github.com/PV-Bhat/vibe-check-mcp-server#configuration
  technical_reference: https://github.com/PV-Bhat/vibe-check-mcp-server/blob/main/docs/technical-reference.md

```

--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------

```yaml
name: release

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    env:
      GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: 'https://registry.npmjs.org'
      - run: npm ci
      - run: npm run build
      - run: npm run test:coverage
      - run: node build/cli/index.js doctor
      - run: node build/cli/index.js start --stdio --dry-run
      - run: node build/cli/index.js start --http --port 2091 --dry-run
      - name: Verify package contents
        run: |
          PKG_TGZ=$(npm pack --silent)
          tar -tf "$PKG_TGZ" | grep -q 'package/build/cli/index.js'
          node -e "const p=require('./package.json');process.exit((p.bin&&Object.values(p.bin).includes('build/cli/index.js'))?0:1)"
      - name: Publish to npmjs
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npm publish --access public
      - name: Post-publish smoke via npx
        run: |
          PKG=$(node -p "require('./package.json').name")
          VER=$(node -p "require('./package.json').version")
          npx -y "$PKG@$VER" --help
          npx -y "$PKG@$VER" start --stdio --dry-run
          npx -y "$PKG@$VER" start --http --port 2091 --dry-run

```

--------------------------------------------------------------------------------
/src/tools/constitution.ts:
--------------------------------------------------------------------------------

```typescript
interface ConstitutionEntry {
  rules: string[];
  updated: number;
}

const constitutionMap: Record<string, ConstitutionEntry> = Object.create(null);

const MAX_RULES_PER_SESSION = 50;
const SESSION_TTL_MS = 60 * 60 * 1000; // 1 hour

export function updateConstitution(sessionId: string, rule: string) {
  if (!sessionId || !rule) return;
  const entry = constitutionMap[sessionId] || { rules: [], updated: 0 };
  if (entry.rules.length >= MAX_RULES_PER_SESSION) entry.rules.shift();
  entry.rules.push(rule);
  entry.updated = Date.now();
  constitutionMap[sessionId] = entry;
}

export function resetConstitution(sessionId: string, rules: string[]) {
  if (!sessionId || !Array.isArray(rules)) return;
  constitutionMap[sessionId] = {
    rules: rules.slice(0, MAX_RULES_PER_SESSION),
    updated: Date.now()
  };
}

export function getConstitution(sessionId: string): string[] {
  const entry = constitutionMap[sessionId];
  if (!entry) return [];
  entry.updated = Date.now();
  return entry.rules;
}

// Cleanup stale sessions to prevent unbounded memory growth
function cleanup() {
  const now = Date.now();
  for (const [sessionId, entry] of Object.entries(constitutionMap)) {
    if (now - entry.updated > SESSION_TTL_MS) {
      delete constitutionMap[sessionId];
    }
  }
}

setInterval(cleanup, SESSION_TTL_MS).unref();

export const __testing = {
  _getMap: () => constitutionMap,
  cleanup
};

```

--------------------------------------------------------------------------------
/tests/cli-install-vscode-dry-run.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { createCliProgram } from '../src/cli/index.js';

const ORIGINAL_ENV = { ...process.env };

describe('cli install vscode manual guidance', () => {
  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('prints manual instructions and install link when config is missing', async () => {
    process.env.OPENAI_API_KEY = 'sk-manual-test';

    const logs: string[] = [];
    const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown) => {
      logs.push(String(message ?? ''));
    });
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      'vscode',
      '--http',
      '--port',
      '3001',
      '--dry-run',
      '--non-interactive',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const output = logs.join('\n');
    expect(output).toContain('configuration not found');
    expect(output).toContain('Add this MCP server configuration manually');
    expect(output).toContain('VS Code quick install link');
    expect(output).toContain('vscode:mcp/install');
    expect(output).toContain('http://127.0.0.1:3001');
    expect(output).toContain('--http');
  });
});

```

--------------------------------------------------------------------------------
/src/cli/clients/cursor.ts:
--------------------------------------------------------------------------------

```typescript
import { join } from 'node:path';
import os from 'node:os';
import {
  ClientAdapter,
  JsonRecord,
  MergeOpts,
  MergeResult,
  expandHomePath,
  mergeIntoMap,
  pathExists,
  readJsonFile,
  writeJsonFileAtomic,
} from './shared.js';

const locateCursorConfig = async (customPath?: string): Promise<string | null> => {
  if (customPath) {
    return expandHomePath(customPath);
  }

  const home = os.homedir();
  const candidate = join(home, '.cursor', 'mcp.json');
  if (await pathExists(candidate)) {
    return candidate;
  }

  return null;
};

const readCursorConfig = async (path: string, raw?: string): Promise<JsonRecord> => {
  return readJsonFile(path, raw);
};

const mergeCursorEntry = (config: JsonRecord, entry: JsonRecord, options: MergeOpts): MergeResult => {
  return mergeIntoMap(config, entry, options, 'mcpServers');
};

const writeCursorConfigAtomic = async (path: string, data: JsonRecord): Promise<void> => {
  await writeJsonFileAtomic(path, data);
};

const adapter: ClientAdapter = {
  locate: locateCursorConfig,
  read: readCursorConfig,
  merge: mergeCursorEntry,
  writeAtomic: writeCursorConfigAtomic,
  describe() {
    return {
      name: 'Cursor',
      pathHint: '~/.cursor/mcp.json',
      summary: 'Cursor IDE with Claude-style MCP configuration.',
      transports: ['stdio'],
      defaultTransport: 'stdio',
      notes: 'Open Cursor Settings → MCP Servers if the file does not exist yet.',
      docsUrl: 'https://docs.cursor.com/ai/model-context-protocol',
    };
  },
};

export default adapter;

```

--------------------------------------------------------------------------------
/alt-test.js:
--------------------------------------------------------------------------------

```javascript
import fs from 'fs';

function createVibeCheckRequest(id, goal, plan, userPrompt, progress, sessionId) {
    return JSON.stringify({
        jsonrpc: '2.0',
        method: 'tools/call',
        params: {
            name: 'vibe_check',
            arguments: {
                goal: goal,
                plan: plan,
                userPrompt: userPrompt,
                progress: progress,
                sessionId: sessionId,
                modelOverride: {
                    provider: 'openrouter',
                    model: 'tngtech/deepseek-r1t2-chimera:free'
                }
            }
        },
        id: id
    });
}

const sessionId = 'history-test-session-phase4';

// First call
const request1 = createVibeCheckRequest(
    1,
    'Test new meta-mentor prompt and history functionality',
    '1. Make the first call to establish history.',
    'Please test the new meta-mentor prompt and history feature.',
    'Starting the test.',
    sessionId
);
fs.writeFileSync('request1.json', request1, 'utf-8');
console.log('Generated request1.json for the first call.');

// Second call
const request2 = createVibeCheckRequest(
    2,
    'Test new meta-mentor prompt and history functionality',
    '2. Make the second call to verify history is included and prompt tone.',
    'Please test the new meta-mentor prompt and history feature.',
    'Just made the second call, expecting history context.',
    sessionId
);
fs.writeFileSync('request2.json', request2, 'utf-8');
console.log('Generated request2.json for the second call.');
```

--------------------------------------------------------------------------------
/docs/gemini.md:
--------------------------------------------------------------------------------

```markdown
# Agent Quickstart

Vibe Check MCP is a lightweight oversight layer for AI agents. It exposes two tools:

- **vibe_check** – prompts you with clarifying questions to prevent tunnel vision.
- **vibe_learn** – optional logging of mistakes and successes for later review.

The server supports Gemini, OpenAI and OpenRouter LLMs. History is maintained across requests when a `sessionId` is provided.

## Setup

1. Install dependencies and build:
   ```bash
   npm install
   npm run build
   ```
2. Supply the following environment variables as needed:
   - `GEMINI_API_KEY`
   - `OPENAI_API_KEY`
   - `OPENROUTER_API_KEY`
   - `DEFAULT_LLM_PROVIDER` (gemini | openai | openrouter)
   - `DEFAULT_MODEL` (e.g., gemini-2.5-pro)
3. Start the server:
   ```bash
   npm start
   ```

## Testing

Run unit tests with `npm test`. The built-in JSON-RPC compatibility layer mitigates missing `id` fields on `tools/call` requests so the stock SDK client and Windsurf can connect without any special tooling, but well-behaved clients should still supply their own identifiers. Example request generators are still provided if you prefer ready-made payloads for manual testing:

- `alt-test-gemini.js`
- `alt-test-openai.js`
- `alt-test.js` (OpenRouter)

Each script writes a `request.json` file that you can pipe to the server:

```bash
node build/index.js < request.json
```

## Integration Tips

Call `vibe_check` regularly with your goal, plan and current progress. Use `vibe_learn` whenever you want to record a resolved issue. Full API details are in `docs/technical-reference.md`.

```

--------------------------------------------------------------------------------
/src/cli/doctor.ts:
--------------------------------------------------------------------------------

```typescript
import { existsSync } from 'node:fs';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import net from 'node:net';
import { parse as parseEnv } from 'dotenv';
import semver from 'semver';
import { homeConfigDir } from './env.js';

export function checkNodeVersion(requiredRange: string, currentVersion: string = process.version): {
  ok: boolean;
  current: string;
} {
  const current = currentVersion;
  const coerced = semver.coerce(current);
  const satisfies = coerced ? semver.satisfies(coerced, requiredRange) : false;
  return {
    ok: satisfies,
    current,
  };
}

export async function portStatus(port: number): Promise<'free' | 'in-use' | 'unknown'> {
  return new Promise((resolveStatus) => {
    const tester = net.createServer();

    tester.once('error', (error: NodeJS.ErrnoException) => {
      if (error.code === 'EADDRINUSE') {
        resolveStatus('in-use');
      } else {
        resolveStatus('unknown');
      }
    });

    tester.once('listening', () => {
      tester.close(() => resolveStatus('free'));
    });

    try {
      tester.listen({ port, host: '127.0.0.1' });
    } catch {
      resolveStatus('unknown');
    }
  });
}

export function detectEnvFiles(): {
  cwdEnv: string | null;
  homeEnv: string | null;
} {
  const cwdEnvPath = resolve(process.cwd(), '.env');
  const homeEnvPath = resolve(homeConfigDir(), '.env');

  return {
    cwdEnv: existsSync(cwdEnvPath) ? cwdEnvPath : null,
    homeEnv: existsSync(homeEnvPath) ? homeEnvPath : null,
  };
}

export function readEnvFile(path: string): Record<string, string> {
  const raw = readFileSync(path, 'utf8');
  return parseEnv(raw);
}

```

--------------------------------------------------------------------------------
/src/utils/state.ts:
--------------------------------------------------------------------------------

```typescript


import fs from 'fs/promises';
import path from 'path';
import os from 'os';
import { VibeCheckInput } from '../tools/vibeCheck.js';

const DATA_DIR = path.join(os.homedir(), '.vibe-check');
const HISTORY_FILE = path.join(DATA_DIR, 'history.json');

interface Interaction { 
  input: VibeCheckInput; 
  output: string; 
  timestamp: number; 
}

let history: Map<string, Interaction[]> = new Map();

async function ensureDataDir() { 
  try { 
    await fs.mkdir(DATA_DIR, { recursive: true }); 
  } catch {} 
}

export async function loadHistory() {
  await ensureDataDir();
  try {
    const data = await fs.readFile(HISTORY_FILE, 'utf-8');
    const parsed = JSON.parse(data);
    history = new Map(Object.entries(parsed).map(([k, v]) => [k, v as Interaction[]]));
  } catch { 
    history.set('default', []); 
  }
}

async function saveHistory() {
  const data = Object.fromEntries(history);
  await fs.writeFile(HISTORY_FILE, JSON.stringify(data));
}

export function getHistorySummary(sessionId = 'default'): string {
  const sessHistory = history.get(sessionId) || [];
  if (!sessHistory.length) return '';
  const summary = sessHistory.slice(-5).map((int, i) => `Interaction ${i+1}: Goal ${int.input.goal}, Guidance: ${int.output.slice(0, 100)}...`).join('\n');
  return `History Context:\n${summary}\n`;
}

export function addToHistory(sessionId = 'default', input: VibeCheckInput, output: string) {
  if (!history.has(sessionId)) {
    history.set(sessionId, []);
  }
  const sessHistory = history.get(sessionId)!;
  sessHistory.push({ input, output, timestamp: Date.now() });
  if (sessHistory.length > 10) {
    sessHistory.shift();
  }
  saveHistory();
}


```

--------------------------------------------------------------------------------
/docs/release-workflows.md:
--------------------------------------------------------------------------------

```markdown
# Release & versioning workflow

## Source of truth

- `version.json` stores the canonical semantic version for the project. Update this file first when preparing a release.
- `scripts/sync-version.mjs` reads `version.json` and synchronizes `package.json`, `package-lock.json`, `README.md`, and the primary `CHANGELOG.md` headers.

## Syncing metadata

1. Update `version.json` with the next version.
2. Run `npm run sync-version` to apply the version across metadata, README badges, and the changelog title.
3. Inspect the diff to ensure the package manifests and documentation updated as expected.

> Tip: `npm run sync-version` will validate the version string and exit non-zero if the value is not compliant `major.minor.patch` semver.

## Changelog updates

- Summarize notable changes under the "## Unreleased" section in [`CHANGELOG.md`](../CHANGELOG.md), then rename it to match the release tag (for example `## v2.8.0 - 2025-11-04`).
- Mirror the highlights in [`docs/changelog.md`](./changelog.md) if you maintain the curated public history.

## npm workflows

- `npm run prepublishOnly` automatically runs `npm run build` before `npm publish`, ensuring the transpiled output is current.
- `npm publish` should only be executed after the sync step so the registry receives the correct version number.
- Use `npm pack` or `npm publish --dry-run` to verify the release contents locally when iterating on the workflow.

## Checklist

- [ ] Update `version.json`
- [ ] `npm run sync-version`
- [ ] Update changelog entries (`CHANGELOG.md`, optional `docs/changelog.md`)
- [ ] `npm test` (or relevant verification)
- [ ] `npm publish` (after confirming `npm run prepublishOnly` completes successfully)

```

--------------------------------------------------------------------------------
/docs/api-keys.md:
--------------------------------------------------------------------------------

```markdown
# API Keys & Secret Management

Vibe Check MCP works with multiple LLM providers. Use this guide to decide which keys you need, how they are discovered, where they are stored, and how to keep them secure.

## Supported providers

- **Anthropic** – `ANTHROPIC_API_KEY`
- **Google Gemini** – `GEMINI_API_KEY`
- **OpenAI** – `OPENAI_API_KEY`
- **OpenRouter** – `OPENROUTER_API_KEY`

Only one key is required to run the server, but you can set more than one to enable provider switching.

## Secret resolution order

When the CLI or server looks up a provider key it evaluates sources in the following order:

1. Existing process environment variables.
2. The current project's `.env` file (pass `--local` to write here).
3. Your home directory config at `~/.vibe-check/.env`.

The first match wins, so values in the shell take priority over project-level overrides, which in turn take priority over the persisted home config.

## Storage locations

- Interactive CLI runs create or update `~/.vibe-check/.env` with `0600` permissions so only your user can read it.
- Supplying `--local` targets the project `.env`, letting you keep per-repository overrides under version control ignore rules.
- Non-interactive runs expect keys to already be available in the environment or the relevant `.env` file; they will exit early if a required key is missing.

## Security recommendations

- Treat `.env` files as secrets: keep them out of version control and shared storage.
- Use the minimal set of provider keys required for your workflow and rotate them periodically.
- Prefer scoped or workspace-specific keys when your provider supports them.
- Restrict file permissions to your user (the CLI enforces this for the home config) and avoid copying secrets into client config files.

```

--------------------------------------------------------------------------------
/scripts/security-check.cjs:
--------------------------------------------------------------------------------

```
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

function runAudit() {
  try {
    const output = execSync('npm audit --production --json', { encoding: 'utf8' });
    const json = JSON.parse(output);
    const vulnerabilities = json.vulnerabilities || {};
    let highOrCritical = 0;
    for (const name of Object.keys(vulnerabilities)) {
      const v = vulnerabilities[name];
      if (['high', 'critical'].includes(v.severity)) {
        console.error(`High severity issue in dependency: ${name}`);
        highOrCritical++;
      }
    }
    if (highOrCritical > 0) {
      console.error(`Found ${highOrCritical} high or critical vulnerabilities`);
      process.exitCode = 1;
    } else {
      console.log('Dependency audit clean');
    }
  } catch (err) {
    console.error('npm audit failed', err.message);
    process.exitCode = 1;
  }
}

function scanSource() {
  const suspiciousPatterns = [/eval\s*\(/, /child_process/, /exec\s*\(/, /spawn\s*\(/];
  let flagged = false;
  function scanDir(dir) {
    for (const file of fs.readdirSync(dir)) {
      const full = path.join(dir, file);
      const stat = fs.statSync(full);
      if (stat.isDirectory()) {
        scanDir(full);
      } else if ((full.endsWith('.ts') || full.endsWith('.js')) && !full.includes('scripts/security-check.js')) {
        const content = fs.readFileSync(full, 'utf8');
        for (const pattern of suspiciousPatterns) {
          if (pattern.test(content)) {
            console.error(`Suspicious pattern ${pattern} found in ${full}`);
            flagged = true;
          }
        }
      }
    }
  }
  scanDir('src');
  if (flagged) {
    process.exitCode = 1;
  } else {
    console.log('Source scan clean');
  }
}

runAudit();
scanSource();

```

--------------------------------------------------------------------------------
/tests/cli-doctor-node.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { format } from 'node:util';
import { createCliProgram } from '../src/cli/index.js';
import * as doctor from '../src/cli/doctor.js';

function captureLogs() {
  const info: string[] = [];
  const warnings: string[] = [];

  const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown, ...rest: unknown[]) => {
    info.push(format(String(message ?? ''), ...rest));
  });

  const warnSpy = vi.spyOn(console, 'warn').mockImplementation((message?: unknown, ...rest: unknown[]) => {
    warnings.push(format(String(message ?? ''), ...rest));
  });

  return { info, warnings, restore: () => { logSpy.mockRestore(); warnSpy.mockRestore(); } };
}

describe('cli doctor node version reporting', () => {
  beforeEach(() => {
    process.exitCode = undefined;
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('reports ok when version satisfies requirement', async () => {
    vi.spyOn(doctor, 'checkNodeVersion').mockReturnValue({ ok: true, current: 'v20.5.0' });
    vi.spyOn(doctor, 'detectEnvFiles').mockReturnValue({ cwdEnv: null, homeEnv: null });

    const { info, warnings, restore } = captureLogs();
    const program = createCliProgram();

    await program.parseAsync(['node', 'vibe-check-mcp', 'doctor']);

    restore();
    expect(warnings).toHaveLength(0);
    expect(info.join('\n')).toContain('meets');
    expect(process.exitCode).toBeUndefined();
  });

  it('warns when version is below requirement', async () => {
    vi.spyOn(doctor, 'checkNodeVersion').mockReturnValue({ ok: false, current: 'v18.0.0' });
    vi.spyOn(doctor, 'detectEnvFiles').mockReturnValue({ cwdEnv: null, homeEnv: null });

    const { warnings, restore } = captureLogs();
    const program = createCliProgram();

    await program.parseAsync(['node', 'vibe-check-mcp', 'doctor']);

    restore();
    expect(warnings.join('\n')).toContain('requires');
    expect(process.exitCode).toBe(1);
  });
});

```

--------------------------------------------------------------------------------
/tests/vibeCheck.test.ts:
--------------------------------------------------------------------------------

```typescript
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { vibeCheckTool } from '../src/tools/vibeCheck.js';
import * as llm from '../src/utils/llm.js';
import * as state from '../src/utils/state.js';

vi.mock('../src/utils/llm.js');
vi.mock('../src/utils/state.js');

const mockedLLM = llm as unknown as { getMetacognitiveQuestions: ReturnType<typeof vi.fn> };
const mockedState = state as unknown as {
  addToHistory: ReturnType<typeof vi.fn>;
  getHistorySummary: ReturnType<typeof vi.fn>;
};

beforeEach(() => {
  vi.clearAllMocks();
  mockedState.getHistorySummary = vi.fn().mockReturnValue('Mock history');
  mockedState.addToHistory = vi.fn();
  mockedLLM.getMetacognitiveQuestions = vi.fn().mockResolvedValue({ questions: 'Mock guidance' });
});

describe('vibeCheckTool', () => {
  it('returns questions from llm', async () => {
    const result = await vibeCheckTool({ goal: 'Test goal', plan: 'Test plan' });
    expect(result.questions).toBe('Mock guidance');
    expect(mockedLLM.getMetacognitiveQuestions).toHaveBeenCalledWith(
      expect.objectContaining({ goal: 'Test goal', plan: 'Test plan', historySummary: 'Mock history' })
    );
  });

  it('passes model override to llm', async () => {
    await vibeCheckTool({ goal: 'g', plan: 'p', modelOverride: { provider: 'openai' } });
    expect(mockedLLM.getMetacognitiveQuestions).toHaveBeenCalledWith(
      expect.objectContaining({ modelOverride: { provider: 'openai' } })
    );
  });

  it('adds to history on each call', async () => {
    await vibeCheckTool({ goal: 'A', plan: 'B', sessionId: 's1' });
    await vibeCheckTool({ goal: 'C', plan: 'D', sessionId: 's1' });
    expect(mockedState.addToHistory).toHaveBeenCalledTimes(2);
  });

  it('falls back to default questions when llm fails', async () => {
    mockedLLM.getMetacognitiveQuestions = vi.fn().mockRejectedValue(new Error('fail'));
    const result = await vibeCheckTool({ goal: 'x', plan: 'y' });
    expect(result.questions).toContain('Does this plan directly address');
  });
});

```

--------------------------------------------------------------------------------
/src/cli/clients/vscode.ts:
--------------------------------------------------------------------------------

```typescript
import { join, resolve } from 'node:path';
import {
  ClientAdapter,
  JsonRecord,
  MergeOpts,
  MergeResult,
  expandHomePath,
  mergeIntoMap,
  pathExists,
  readJsonFile,
  writeJsonFileAtomic,
} from './shared.js';

const locateVsCodeConfig = async (customPath?: string): Promise<string | null> => {
  if (customPath) {
    return expandHomePath(customPath);
  }

  const workspacePath = join(process.cwd(), '.vscode', 'mcp.json');
  if (await pathExists(workspacePath)) {
    return resolve(workspacePath);
  }

  return null;
};

const readVsCodeConfig = async (path: string, raw?: string): Promise<JsonRecord> => {
  return readJsonFile(path, raw);
};

const mergeVsCodeEntry = (config: JsonRecord, entry: JsonRecord, options: MergeOpts): MergeResult => {
  const baseEntry: JsonRecord = {
    command: entry.command,
    args: entry.args,
    env: entry.env ?? {},
    transport: options.transport,
  };

  if (options.transport === 'http') {
    baseEntry.url = options.httpUrl ?? 'http://127.0.0.1:2091';
  }

  if (options.dev?.watch || options.dev?.debug) {
    const dev: JsonRecord = {};
    if (options.dev.watch) {
      dev.watch = true;
    }
    if (options.dev.debug) {
      dev.debug = options.dev.debug;
    }
    baseEntry.dev = dev;
  }

  return mergeIntoMap(config, baseEntry, options, 'servers');
};

const writeVsCodeConfigAtomic = async (path: string, data: JsonRecord): Promise<void> => {
  await writeJsonFileAtomic(path, data);
};

const adapter: ClientAdapter = {
  locate: locateVsCodeConfig,
  read: readVsCodeConfig,
  merge: mergeVsCodeEntry,
  writeAtomic: writeVsCodeConfigAtomic,
  describe() {
    return {
      name: 'Visual Studio Code',
      pathHint: '.vscode/mcp.json (workspace)',
      summary: 'VS Code MCP configuration supporting stdio and HTTP transports.',
      transports: ['stdio', 'http'],
      defaultTransport: 'stdio',
      notes: 'Use the Command Palette → "MCP: Add Server" for profile installs.',
      docsUrl: 'https://code.visualstudio.com/docs/copilot/mcp',
    };
  },
};

export default adapter;

```

--------------------------------------------------------------------------------
/src/cli/clients/windsurf.ts:
--------------------------------------------------------------------------------

```typescript
import { join } from 'node:path';
import os from 'node:os';
import {
  ClientAdapter,
  JsonRecord,
  MergeOpts,
  MergeResult,
  expandHomePath,
  mergeIntoMap,
  pathExists,
  readJsonFile,
  writeJsonFileAtomic,
} from './shared.js';

const locateWindsurfConfig = async (customPath?: string): Promise<string | null> => {
  if (customPath) {
    return expandHomePath(customPath);
  }

  const home = os.homedir();
  const legacy = join(home, '.codeium', 'windsurf', 'mcp_config.json');
  if (await pathExists(legacy)) {
    return legacy;
  }

  const modern = join(home, '.codeium', 'mcp_config.json');
  if (await pathExists(modern)) {
    return modern;
  }

  return null;
};

const readWindsurfConfig = async (path: string, raw?: string): Promise<JsonRecord> => {
  return readJsonFile(path, raw);
};

const mergeWindsurfEntry = (config: JsonRecord, entry: JsonRecord, options: MergeOpts): MergeResult => {
  if (options.transport === 'http') {
    const httpEntry: JsonRecord = {
      serverUrl: options.httpUrl ?? 'http://127.0.0.1:2091',
    };
    return mergeIntoMap(config, httpEntry, options, 'mcpServers');
  }

  const stdioEntry: JsonRecord = {
    command: entry.command,
    args: entry.args,
    env: entry.env ?? {},
  };

  return mergeIntoMap(config, stdioEntry, options, 'mcpServers');
};

const writeWindsurfConfigAtomic = async (path: string, data: JsonRecord): Promise<void> => {
  await writeJsonFileAtomic(path, data);
};

const adapter: ClientAdapter = {
  locate: locateWindsurfConfig,
  read: readWindsurfConfig,
  merge: mergeWindsurfEntry,
  writeAtomic: writeWindsurfConfigAtomic,
  describe() {
    return {
      name: 'Windsurf',
      pathHint: '~/.codeium/windsurf/mcp_config.json',
      summary: 'Codeium Windsurf IDE with stdio and HTTP MCP transports.',
      transports: ['stdio', 'http'],
      defaultTransport: 'stdio',
      notes: 'Newer builds use ~/.codeium/mcp_config.json. Create an empty file to opt-in.',
      docsUrl: 'https://docs.codeium.com/windsurf/model-context-protocol',
    };
  },
};

export default adapter;

```

--------------------------------------------------------------------------------
/tests/cli-doctor-port.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { format } from 'node:util';
import net from 'node:net';
import { createCliProgram } from '../src/cli/index.js';

describe('cli doctor port diagnostics', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('reports occupied ports as in-use', async () => {
    const server = net.createServer();
    await new Promise<void>((resolve, reject) => {
      server.once('error', reject);
      server.listen({ port: 0, host: '127.0.0.1' }, () => resolve());
    });

    const address = server.address();
    if (typeof address !== 'object' || address === null) {
      throw new Error('Failed to acquire port for test');
    }

    const port = address.port;
    const logs: string[] = [];
    const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown, ...rest: unknown[]) => {
      logs.push(format(String(message ?? ''), ...rest));
    });

    const program = createCliProgram();
    process.env.MCP_TRANSPORT = 'http';
    await program.parseAsync(['node', 'vibe-check-mcp', 'doctor', '--port', String(port)]);

    logSpy.mockRestore();
    await new Promise<void>((resolve) => server.close(() => resolve()));

    const output = logs.join('\n');
    expect(output).toContain(`HTTP port ${port}: in-use`);
    expect(process.exitCode).toBeUndefined();
  });

  it('skips port diagnostics when using stdio transport', async () => {
    const logs: string[] = [];
    const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown, ...rest: unknown[]) => {
      logs.push(format(String(message ?? ''), ...rest));
    });

    const program = createCliProgram();
    delete process.env.MCP_TRANSPORT;
    await program.parseAsync(['node', 'vibe-check-mcp', 'doctor']);

    logSpy.mockRestore();

    expect(logs.join('\n')).toContain('Using stdio transport; port checks skipped.');
  });
});

```

--------------------------------------------------------------------------------
/tests/cli-start-flags.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { format } from 'node:util';
import { createCliProgram } from '../src/cli/index.js';

function collectLogs() {
  const logs: string[] = [];
  const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown, ...rest: unknown[]) => {
    logs.push(format(String(message ?? ''), ...rest));
  });

  return { logs, restore: () => logSpy.mockRestore() };
}

describe('cli start command flags', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  async function runStartCommand(...args: string[]): Promise<string> {
    const { logs, restore } = collectLogs();
    const program = createCliProgram();

    await program.parseAsync(['node', 'vibe-check-mcp', 'start', ...args, '--dry-run']);

    restore();
    return logs.join('\n');
  }

  it('defaults to stdio when no flag or env is provided', async () => {
    delete process.env.MCP_TRANSPORT;

    const output = await runStartCommand();
    expect(output).toContain('MCP_TRANSPORT=stdio');
    expect(output).not.toContain('MCP_HTTP_PORT');
  });

  it('preserves MCP_TRANSPORT from the environment when no flag is set', async () => {
    process.env.MCP_TRANSPORT = 'http';

    const output = await runStartCommand();
    expect(output).toContain('MCP_TRANSPORT=http');
    expect(output).toContain('MCP_HTTP_PORT=2091');
  });

  it('allows CLI flags to override MCP_TRANSPORT from the environment', async () => {
    process.env.MCP_TRANSPORT = 'http';

    const output = await runStartCommand('--stdio');
    expect(output).toContain('MCP_TRANSPORT=stdio');
    expect(output).not.toContain('MCP_HTTP_PORT');
  });

  it('prints http transport and chosen port during dry run', async () => {
    const output = await runStartCommand('--http', '--port', '1234');
    expect(output).toContain('MCP_TRANSPORT=http');
    expect(output).toContain('MCP_HTTP_PORT=1234');
  });
});

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "@pv-bhat/vibe-check-mcp",
  "mcpName": "io.github.PV-Bhat/vibe-check-mcp-server",
  "version": "2.7.6",
  "description": "Metacognitive AI agent oversight: adaptive CPI interrupts for alignment, reflection and safety",
  "main": "build/index.js",
  "type": "module",
  "packageManager": "[email protected]",
  "bin": {
    "vibe-check-mcp": "build/cli/index.js"
  },
  "files": [
    "build"
  ],
  "scripts": {
    "build": "tsc && node -e \"const fs=require('fs');['build/index.js','build/cli/index.js'].forEach((f)=>{if(fs.existsSync(f)){fs.chmodSync(f,0o755);}})\"",
    "prepare": "npm run build",
    "start": "node build/index.js",
    "dev": "tsc-watch --onSuccess \"node build/index.js\"",
    "pretest": "npm run build",
    "test": "vitest run",
    "test:coverage": "vitest run --coverage",
    "security-check": "node scripts/security-check.cjs",
    "prepublishOnly": "npm run build",
    "sync-version": "node scripts/sync-version.mjs"
  },
  "dependencies": {
    "@google/generative-ai": "^0.17.1",
    "@modelcontextprotocol/sdk": "^1.16.0",
    "axios": "^1.12.2",
    "body-parser": "^1.20.2",
    "commander": "^12.1.0",
    "cors": "^2.8.5",
    "diff": "^5.2.0",
    "dotenv": "^16.4.7",
    "execa": "^9.5.1",
    "express": "^4.19.2",
    "openai": "^4.68.1",
    "semver": "^7.6.3"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/diff": "^7.0.2",
    "@types/express": "^4.17.21",
    "@types/node": "^20.17.25",
    "@types/semver": "^7.7.1",
    "@vitest/coverage-v8": "^3.2.4",
    "tsc-watch": "^6.0.0",
    "typescript": "^5.3.0",
    "vitest": "^3.2.4"
  },
  "engines": {
    "node": ">=20.0.0"
  },
  "keywords": [
    "mcp",
    "mcp-server",
    "vibe-check",
    "vibe-coding",
    "metacognition",
    "ai-alignment",
    "llm-agents",
    "autonomous-agents",
    "reflection",
    "agent-oversight",
    "ai-safety",
    "prompt-engineering"
  ],
  "author": "PV Bhat",
  "repository": {
    "type": "git",
    "url": "https://github.com/PV-Bhat/vibe-check-mcp-server.git"
  },
  "bugs": {
    "url": "https://github.com/PV-Bhat/vibe-check-mcp-server/issues"
  },
  "homepage": "https://github.com/PV-Bhat/vibe-check-mcp-server#readme",
  "license": "MIT",
  "publishConfig": {
    "access": "public"
  }
}

```

--------------------------------------------------------------------------------
/src/cli/clients/claude-code.ts:
--------------------------------------------------------------------------------

```typescript
import { join } from 'node:path';
import os from 'node:os';
import {
  ClientAdapter,
  JsonRecord,
  MergeOpts,
  MergeResult,
  expandHomePath,
  mergeIntoMap,
  pathExists,
  readJsonFile,
  writeJsonFileAtomic,
} from './shared.js';

const locateClaudeCodeConfig = async (customPath?: string): Promise<string | null> => {
  if (customPath) {
    return expandHomePath(customPath);
  }

  const home = os.homedir();
  const candidates: string[] = [];

  if (process.platform === 'darwin') {
    candidates.push(join(home, 'Library', 'Application Support', 'Claude', 'claude_code_config.json'));
  } else if (process.platform === 'win32') {
    const appData = process.env.APPDATA;
    if (appData) {
      candidates.push(join(appData, 'Claude', 'claude_code_config.json'));
    }
  } else {
    const xdgConfig = process.env.XDG_CONFIG_HOME;
    if (xdgConfig) {
      candidates.push(join(xdgConfig, 'Claude', 'claude_code_config.json'));
    }
    candidates.push(join(home, '.config', 'Claude', 'claude_code_config.json'));
  }

  for (const candidate of candidates) {
    if (await pathExists(candidate)) {
      return candidate;
    }
  }

  return null;
};

const readClaudeCodeConfig = async (path: string, raw?: string): Promise<JsonRecord> => {
  return readJsonFile(path, raw, 'Claude Code config');
};

const writeClaudeCodeConfigAtomic = async (path: string, data: JsonRecord): Promise<void> => {
  await writeJsonFileAtomic(path, data);
};

const mergeClaudeCodeEntry = (config: JsonRecord, entry: JsonRecord, options: MergeOpts): MergeResult => {
  return mergeIntoMap(config, entry, options, 'mcpServers');
};

const adapter: ClientAdapter = {
  locate: locateClaudeCodeConfig,
  read: readClaudeCodeConfig,
  merge: mergeClaudeCodeEntry,
  writeAtomic: writeClaudeCodeConfigAtomic,
  describe() {
    return {
      name: 'Claude Code',
      pathHint: '~/.config/Claude/claude_code_config.json',
      summary: 'Anthropic\'s Claude Code CLI agent configuration.',
      transports: ['stdio'],
      defaultTransport: 'stdio',
      requiredEnvKeys: ['ANTHROPIC_API_KEY'],
      notes: 'Run `claude code login` once to scaffold the config file.',
      docsUrl: 'https://docs.anthropic.com/en/docs/agents/claude-code',
    };
  },
};

export default adapter;

```

--------------------------------------------------------------------------------
/src/tools/vibeCheck.ts:
--------------------------------------------------------------------------------

```typescript
import { getMetacognitiveQuestions } from '../utils/llm.js';
import { addToHistory, getHistorySummary } from '../utils/state.js';

// Vibe Check tool handler
export interface VibeCheckInput {
  goal: string;
  plan: string;
  modelOverride?: {
    provider?: string;
    model?: string;
  };
  userPrompt?: string;
  progress?: string;
  uncertainties?: string[];
  taskContext?: string;
  sessionId?: string;
}

export interface VibeCheckOutput {
  questions: string;
}

/**
 * Adaptive CPI interrupt for AI agent alignment and reflection.
 * Monitors progress and questions assumptions to mitigate Reasoning Lock-In.
 * The userRequest parameter MUST contain the full original request for safety.
 */
export async function vibeCheckTool(input: VibeCheckInput): Promise<VibeCheckOutput> {
  console.log('[vibe_check] called', { hasSession: Boolean(input.sessionId) });
  try {
    // Get history summary
    const historySummary = getHistorySummary(input.sessionId);

    // Get metacognitive questions from Gemini with dynamic parameters
    const response = await getMetacognitiveQuestions({
      goal: input.goal,
      plan: input.plan,
      modelOverride: input.modelOverride,
      userPrompt: input.userPrompt,
      progress: input.progress,
      uncertainties: input.uncertainties,
      taskContext: input.taskContext,
      sessionId: input.sessionId,
      historySummary,
    });

    // Add to history
    addToHistory(input.sessionId, input, response.questions);

    return {
      questions: response.questions,
    };
  } catch (error) {
    console.error('Error in vibe_check tool:', error);

    // Fallback to basic questions if there's an error
    return {
      questions: generateFallbackQuestions(input.userPrompt || "", input.plan || ""),
    };
  }
}

/**
 * Generate adaptive fallback questions when API fails
 */
function generateFallbackQuestions(userRequest: string, plan: string): string {
    return `
I can see you're thinking through your approach, which shows thoughtfulness:

1. Does this plan directly address what the user requested, or might it be solving a different problem?
2. Is there a simpler approach that would meet the user's needs?
3. What unstated assumptions might be limiting the thinking here?
4. How does this align with the user's original intent?
`;
}
```

--------------------------------------------------------------------------------
/tests/llm.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect, beforeEach, vi } from 'vitest';
import axios from 'axios';
import { generateResponse, __testing } from '../src/utils/llm.js';

vi.mock('axios');
const mockedAxios = axios as unknown as { post: ReturnType<typeof vi.fn> };

beforeEach(() => {
  vi.clearAllMocks();
  __testing.setGenAI({
    getGenerativeModel: vi.fn(() => ({
      generateContent: vi.fn(async () => ({ response: { text: () => 'gemini reply' } }))
    }))
  });
  __testing.setOpenAIClient({
    chat: { completions: { create: vi.fn(async () => ({ choices: [{ message: { content: 'openai reply' } }] })) } }
  });
});

describe('generateResponse', () => {
  it('uses gemini by default and builds prompt with context', async () => {
    const res = await generateResponse({ goal: 'G', plan: 'P', uncertainties: ['u1'], historySummary: 'Hist' });
    expect(res.questions).toBe('gemini reply');
    const gen = __testing.getGenAI();
    expect(gen.getGenerativeModel).toHaveBeenCalledWith({ model: 'gemini-2.5-pro' });
    const prompt = gen.getGenerativeModel.mock.results[0].value.generateContent.mock.calls[0][0];
    expect(prompt).toContain('History Context: Hist');
    expect(prompt).toContain('u1');
  });

  it('uses openai when overridden', async () => {
    const openai = __testing.getOpenAIClient();
    const res = await generateResponse({ goal: 'g', plan: 'p', modelOverride: { provider: 'openai', model: 'o1-mini' } });
    expect(res.questions).toBe('openai reply');
    expect(openai.chat.completions.create).toHaveBeenCalledWith({ model: 'o1-mini', messages: [{ role: 'system', content: expect.any(String) }] });
  });

  it('throws if openrouter key missing', async () => {
    await expect(generateResponse({ goal: 'g', plan: 'p', modelOverride: { provider: 'openrouter', model: 'm1' } })).rejects.toThrow('OpenRouter API key');
  });

  it('calls openrouter when configured', async () => {
    process.env.OPENROUTER_API_KEY = 'sk-or-key';
    mockedAxios.post = vi.fn(async () => ({ data: { choices: [{ message: { content: 'router reply' } }] } }));
    const res = await generateResponse({ goal: 'g', plan: 'p', modelOverride: { provider: 'openrouter', model: 'm1' } });
    expect(res.questions).toBe('router reply');
    expect(mockedAxios.post).toHaveBeenCalled();
    delete process.env.OPENROUTER_API_KEY;
  });
});

```

--------------------------------------------------------------------------------
/src/cli/clients/claude.ts:
--------------------------------------------------------------------------------

```typescript
import { join } from 'node:path';
import os from 'node:os';
import {
  ClientAdapter,
  JsonRecord,
  MergeOpts,
  MergeResult,
  expandHomePath,
  mergeIntoMap,
  pathExists,
  readJsonFile,
  writeJsonFileAtomic,
} from './shared.js';

type LocateFn = (customPath?: string) => Promise<string | null>;

type ReadFn = (path: string, raw?: string) => Promise<JsonRecord>;

type MergeFn = (config: JsonRecord, entry: JsonRecord, options: MergeOpts) => MergeResult;

type WriteFn = (path: string, data: JsonRecord) => Promise<void>;

export const locateClaudeConfig: LocateFn = async (customPath) => {
  if (customPath) {
    return expandHomePath(customPath);
  }

  const home = os.homedir();
  const candidates: string[] = [];

  if (process.platform === 'darwin') {
    candidates.push(join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'));
  } else if (process.platform === 'win32') {
    const appData = process.env.APPDATA;
    if (appData) {
      candidates.push(join(appData, 'Claude', 'claude_desktop_config.json'));
    }
  } else {
    const xdgConfig = process.env.XDG_CONFIG_HOME;
    if (xdgConfig) {
      candidates.push(join(xdgConfig, 'Claude', 'claude_desktop_config.json'));
    }
    candidates.push(join(home, '.config', 'Claude', 'claude_desktop_config.json'));
  }

  for (const candidate of candidates) {
    if (await pathExists(candidate)) {
      return candidate;
    }
  }

  return null;
};

export const readClaudeConfig: ReadFn = async (path, raw) => {
  return readJsonFile(path, raw, 'Claude config');
};

export const writeClaudeConfigAtomic: WriteFn = async (path, data) => {
  await writeJsonFileAtomic(path, data);
};

export const mergeMcpEntry: MergeFn = (config, entry, options) => {
  return mergeIntoMap(config, entry, options, 'mcpServers');
};

const adapter: ClientAdapter = {
  locate: locateClaudeConfig,
  read: readClaudeConfig,
  merge: mergeMcpEntry,
  writeAtomic: writeClaudeConfigAtomic,
  describe() {
    return {
      name: 'Claude Desktop',
      pathHint: 'claude_desktop_config.json',
      summary: 'Claude Desktop app integration for Windows, macOS, and Linux.',
      transports: ['stdio'],
      defaultTransport: 'stdio',
      requiredEnvKeys: ['ANTHROPIC_API_KEY'],
      notes: 'Launch Claude Desktop once to generate the config file.',
      docsUrl: 'https://docs.anthropic.com/en/docs/claude-desktop/model-context-protocol',
    };
  },
};

export default adapter;

```

--------------------------------------------------------------------------------
/examples/cpi-integration.ts:
--------------------------------------------------------------------------------

```typescript
/**
 * Example CPI integration stub for VibeCheck MCP.
 *
 * Wire this into your agent orchestrator to forward VibeCheck signals to a CPI policy.
 */

export interface AgentSnapshot {
  sessionId: string;
  summary: string;
  nextAction: string;
  done?: boolean;
}

export interface ResumeSignal {
  reason: string;
  followUp?: string;
}

export interface AgentStepCallback {
  (input: { resumeSignal?: ResumeSignal }): Promise<AgentSnapshot>;
}

export interface VibeCheckSignal {
  riskScore: number;
  traits: string[];
  advice: string;
}

const RISK_THRESHOLD = 0.6;

const vibecheckShim = {
  // TODO: replace with an actual call to the VibeCheck MCP tool over MCP or HTTP.
  async analyze(snapshot: AgentSnapshot): Promise<VibeCheckSignal> {
    return {
      riskScore: Math.random(),
      traits: ['focus-drift'],
      advice: `Reflect on: ${snapshot.summary}`,
    };
  },
};

// TODO: replace with `import { createPolicy } from '@cpi/sdk';`
const cpiPolicyShim = {
  interrupt(input: { snapshot: AgentSnapshot; signal: VibeCheckSignal }) {
    if (input.signal.riskScore >= RISK_THRESHOLD) {
      return {
        action: 'interrupt' as const,
        reason: 'High metacognitive risk detected by VibeCheck',
      };
    }

    return { action: 'allow' as const };
  },
};

async function handleInterrupt(
  decision: { action: 'interrupt' | 'allow'; reason?: string },
  snapshot: AgentSnapshot,
): Promise<ResumeSignal | undefined> {
  if (decision.action === 'allow') {
    return undefined;
  }

  console.warn('[CPI] interrupting agent step:', decision.reason ?? 'policy requested pause');
  console.warn('Agent summary:', snapshot.summary);

  // TODO: replace with human-in-the-loop logic or CPI repro harness callback.
  return {
    reason: decision.reason ?? 'Paused for inspection',
    followUp: 'Agent acknowledged CPI feedback and is ready to resume.',
  };
}

export async function runWithCPI(agentStep: AgentStepCallback): Promise<void> {
  let resumeSignal: ResumeSignal | undefined;

  while (true) {
    const snapshot = await agentStep({ resumeSignal });

    if (snapshot.done) {
      console.log('Agent workflow completed.');
      break;
    }

    const signal = await vibecheckShim.analyze(snapshot);
    console.log('VibeCheck signal', signal);

    const decision = cpiPolicyShim.interrupt({ snapshot, signal });

    if (decision.action !== 'allow') {
      resumeSignal = await handleInterrupt(decision, snapshot);
      continue;
    }

    resumeSignal = undefined;
  }
}

```

--------------------------------------------------------------------------------
/src/utils/jsonRpcCompat.ts:
--------------------------------------------------------------------------------

```typescript
import crypto from 'node:crypto';

export interface JsonRpcRequestLike {
  jsonrpc?: unknown;
  id?: unknown;
  method?: unknown;
  params?: unknown;
}

const STABLE_ID_PREFIX = 'compat-';

function computeStableHash(request: JsonRpcRequestLike): string {
  const params = request.params ?? {};
  return crypto
    .createHash('sha256')
    .update(JSON.stringify({ method: request.method, params }))
    .digest('hex')
    .slice(0, 12);
}

function generateNonce(): string {
  const nonceValue = parseInt(crypto.randomBytes(3).toString('hex'), 16);
  const base36 = nonceValue.toString(36);
  return base36.padStart(4, '0').slice(-6);
}

export function formatCompatId(stableHash: string, nonce: string = generateNonce()): string {
  return `${STABLE_ID_PREFIX}${stableHash}-${nonce}`;
}

function computeStableId(request: JsonRpcRequestLike): string {
  const stableHash = computeStableHash(request);
  return formatCompatId(stableHash);
}

export interface ShimResult {
  applied: boolean;
  id?: string;
}

export function applyJsonRpcCompatibility(request: JsonRpcRequestLike | undefined | null): ShimResult {
  if (!request || typeof request !== 'object') {
    return { applied: false };
  }

  if ((request as any).jsonrpc !== '2.0') {
    return { applied: false };
  }

  if ((request as any).method !== 'tools/call') {
    return { applied: false };
  }

  if ((request as any).id !== undefined && (request as any).id !== null) {
    return { applied: false };
  }

  const id = computeStableId(request);
  (request as any).id = id;
  return { applied: true, id };
}

export interface TransportLike {
  onmessage?: (message: any, extra?: any) => void;
}

export function wrapTransportForCompatibility<T extends TransportLike>(transport: T): T {
  const originalOnMessage = transport.onmessage;
  let wrappedHandler: typeof transport.onmessage;

  const wrapHandler = (handler?: typeof transport.onmessage) => {
    if (!handler) {
      wrappedHandler = undefined;
      return;
    }

    wrappedHandler = function (this: unknown, message: JsonRpcRequestLike, extra?: any) {
      applyJsonRpcCompatibility(message);
      return handler.call(this ?? transport, message, extra);
    };
  };

  Object.defineProperty(transport, 'onmessage', {
    configurable: true,
    enumerable: true,
    get() {
      return wrappedHandler;
    },
    set(handler) {
      if (handler === wrappedHandler && handler !== undefined) {
        return;
      }
      wrapHandler(handler);
    },
  });

  if (originalOnMessage) {
    transport.onmessage = originalOnMessage;
  }

  return transport;
}

```

--------------------------------------------------------------------------------
/scripts/install-vibe-check.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

echo "========================================================"
echo "Vibe Check MCP Server Installer for Cursor IDE (Mac/Linux)"
echo "========================================================"
echo ""

# Check for Node.js installation
if ! command -v node &> /dev/null; then
    echo "Error: Node.js is not installed or not in PATH."
    echo "Please install Node.js from https://nodejs.org/"
    exit 1
fi

# Check for npm installation
if ! command -v npm &> /dev/null; then
    echo "Error: npm is not installed or not in PATH."
    echo "Please install Node.js from https://nodejs.org/"
    exit 1
fi

# Detect OS
OS="$(uname -s)"
case "${OS}" in
    Linux*)     OS="Linux";;
    Darwin*)    OS="Mac";;
    *)          OS="Unknown";;
esac

if [ "$OS" = "Unknown" ]; then
    echo "Error: Unsupported operating system. This script works on Mac and Linux only."
    exit 1
fi

echo "Step 1: Installing @pv-bhat/vibe-check-mcp globally..."
npm install -g @pv-bhat/vibe-check-mcp

if [ $? -ne 0 ]; then
    echo "Error: Failed to install @pv-bhat/vibe-check-mcp globally."
    exit 1
fi

echo ""
echo "Step 2: Finding global npm installation path..."
NPM_GLOBAL=$(npm root -g)
VIBE_CHECK_PATH="$NPM_GLOBAL/@pv-bhat/vibe-check-mcp/build/index.js"

if [ ! -f "$VIBE_CHECK_PATH" ]; then
    echo "Error: Could not find @pv-bhat/vibe-check-mcp installation at $VIBE_CHECK_PATH"
    exit 1
fi

echo "Found @pv-bhat/vibe-check-mcp at: $VIBE_CHECK_PATH"
echo ""

echo "Step 3: Enter your Gemini API key for vibe-check-mcp..."
read -p "Enter your Gemini API key: " GEMINI_API_KEY

# Create .env file in user's home directory
echo "Creating .env file for Gemini API key..."
ENV_FILE="$HOME/.vibe-check-mcp.env"
echo "GEMINI_API_KEY=$GEMINI_API_KEY" > "$ENV_FILE"
chmod 600 "$ENV_FILE"  # Secure the API key file

# Create start script
START_SCRIPT="$HOME/start-vibe-check-mcp.sh"
cat > "$START_SCRIPT" << EOL
#!/bin/bash
source "$ENV_FILE"
exec node "$VIBE_CHECK_PATH"
EOL

chmod +x "$START_SCRIPT"
echo "Created startup script: $START_SCRIPT"

echo ""
echo "Step 4: Setting up Cursor IDE configuration..."
echo ""
echo "To complete setup, you need to configure Cursor IDE:"
echo ""
echo "1. Open Cursor IDE"
echo "2. Go to Settings (gear icon) -> MCP"
echo "3. Click \"Add New MCP Server\""
echo "4. Enter the following information:"
echo "   - Name: Vibe Check"
echo "   - Type: Command"
echo "   - Command: env GEMINI_API_KEY=$GEMINI_API_KEY node \"$VIBE_CHECK_PATH\""
echo "5. Click \"Save\" and then \"Refresh\""
echo ""
echo "Installation complete!"
echo ""
echo "You can manually run it by executing: $START_SCRIPT"
echo ""
```

--------------------------------------------------------------------------------
/tests/storage-utils.test.ts:
--------------------------------------------------------------------------------

```typescript
import { afterEach, describe, expect, it, vi } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';

type StorageModule = typeof import('../src/utils/storage.js');

let tempDir: string;
let storage: StorageModule;

async function loadStorageModule(dir: string): Promise<StorageModule> {
  vi.resetModules();
  vi.doMock('os', () => ({
    default: {
      homedir: () => dir,
    },
  }));
  const mod = await import('../src/utils/storage.js');
  return mod;
}

afterEach(() => {
  vi.doUnmock('os');
  if (tempDir && fs.existsSync(tempDir)) {
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
});

describe('storage utilities', () => {
  it('writes and reads log data safely', async () => {
    tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-storage-test-'));
    storage = await loadStorageModule(tempDir);

    const logPath = path.join(tempDir, '.vibe-check', 'vibe-log.json');

    const mockLog = {
      mistakes: {
        Example: {
          count: 1,
          examples: [
            {
              type: 'mistake' as const,
              category: 'Example',
              mistake: 'Did something wrong.',
              solution: 'Fixed it quickly.',
              timestamp: Date.now(),
            },
          ],
          lastUpdated: Date.now(),
        },
      },
      lastUpdated: Date.now(),
    };

    storage.writeLogFile(mockLog);
    expect(fs.existsSync(logPath)).toBe(true);
    const readBack = storage.readLogFile();
    expect(readBack.mistakes.Example.count).toBe(1);

    fs.writeFileSync(logPath, 'not-json');
    const fallback = storage.readLogFile();
    expect(fallback.mistakes).toEqual({});
  });

  it('tracks learning entries and summaries', async () => {
    tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vibe-storage-test-'));
    storage = await loadStorageModule(tempDir);

    storage.addLearningEntry('Missed tests', 'Feature Creep', 'Add coverage', 'mistake');
    storage.addLearningEntry('Shipped fast', 'Success', undefined, 'success');
    storage.addLearningEntry('Too many tools', 'Overtooling', 'Simplify stack', 'mistake');

    const entries = storage.getLearningEntries();
    expect(Object.keys(entries)).toEqual(expect.arrayContaining(['Feature Creep', 'Success', 'Overtooling']));

    const summary = storage.getLearningCategorySummary();
    expect(summary[0].count).toBeGreaterThan(0);
    expect(summary.some((item) => item.category === 'Feature Creep')).toBe(true);

    const context = storage.getLearningContextText(2);
    expect(context).toContain('Category: Feature Creep');
    expect(context).toContain('Mistake');
  });
});

```

--------------------------------------------------------------------------------
/scripts/sync-version.mjs:
--------------------------------------------------------------------------------

```
import { readFile, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '..');

const resolvePath = (relativePath) => join(rootDir, relativePath);

const loadJson = async (relativePath) => {
  const filePath = resolvePath(relativePath);
  const contents = await readFile(filePath, 'utf8');
  return { filePath, data: JSON.parse(contents) };
};

const writeJson = async (filePath, data) => {
  const serialized = JSON.stringify(data, null, 2) + '\n';
  await writeFile(filePath, serialized, 'utf8');
};

const replaceInFile = async (relativePath, replacements) => {
  const filePath = resolvePath(relativePath);
  let contents = await readFile(filePath, 'utf8');
  for (const { pattern, value } of replacements) {
    contents = contents.replace(pattern, value);
  }
  await writeFile(filePath, contents, 'utf8');
};

const main = async () => {
  const { data: versionData } = await loadJson('version.json');
  const newVersion = versionData.version;

  if (typeof newVersion !== 'string' || !/^\d+\.\d+\.\d+$/.test(newVersion)) {
    throw new Error(`Invalid semver version in version.json: "${newVersion}"`);
  }

  const { filePath: packageJsonPath, data: packageJson } = await loadJson('package.json');
  if (packageJson.version !== newVersion) {
    packageJson.version = newVersion;
    await writeJson(packageJsonPath, packageJson);
  }

  try {
    const { filePath: lockPath, data: packageLock } = await loadJson('package-lock.json');
    let updatedLock = false;
    if (packageLock.version !== newVersion) {
      packageLock.version = newVersion;
      updatedLock = true;
    }
    if (packageLock.packages?.['']?.version && packageLock.packages[''].version !== newVersion) {
      packageLock.packages[''].version = newVersion;
      updatedLock = true;
    }
    if (updatedLock) {
      await writeJson(lockPath, packageLock);
    }
  } catch (error) {
    if (error.code !== 'ENOENT') {
      throw error;
    }
  }

  await replaceInFile('README.md', [
    { pattern: /Vibe Check MCP v\d+\.\d+\.\d+/, value: `Vibe Check MCP v${newVersion}` },
    { pattern: /version-\d+\.\d+\.\d+-purple/, value: `version-${newVersion}-purple` },
    { pattern: /## What's New in v\d+\.\d+\.\d+/, value: `## What's New in v${newVersion}` }
  ]);

  await replaceInFile('CHANGELOG.md', [
    { pattern: /## v\d+\.\d+\.\d+ -/, value: `## v${newVersion} -` }
  ]);

  console.log(`Synchronized project files to version ${newVersion}`);
};

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

```

--------------------------------------------------------------------------------
/tests/cli-install-dry-run.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import os from 'node:os';
import { format } from 'node:util';
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import { createCliProgram } from '../src/cli/index.js';

type ClientFixture = {
  client: 'claude' | 'cursor' | 'windsurf' | 'vscode';
  fixture: string;
  fileName: string;
};

const FIXTURES: ClientFixture[] = [
  {
    client: 'claude',
    fixture: join('claude', 'config.base.json'),
    fileName: 'claude.json',
  },
  {
    client: 'cursor',
    fixture: join('cursor', 'config.base.json'),
    fileName: 'cursor.json',
  },
  {
    client: 'windsurf',
    fixture: join('windsurf', 'config.base.json'),
    fileName: 'mcp_config.json',
  },
  {
    client: 'vscode',
    fixture: join('vscode', 'workspace.mcp.base.json'),
    fileName: join('.vscode', 'mcp.json'),
  },
];

describe('cli install --dry-run', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it.each(FIXTURES)('prints a unified diff without writing changes (%s)', async ({
    client,
    fixture,
    fileName,
  }) => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'vibe-dryrun-'));
    const configPath = join(tmpDir, fileName);
    await fs.mkdir(dirname(configPath), { recursive: true });
    const fixturePath = join(process.cwd(), 'tests', 'fixtures', fixture);
    const original = readFileSync(fixturePath, 'utf8');
    await fs.writeFile(configPath, original, 'utf8');

    process.env.ANTHROPIC_API_KEY = 'sk-ant-dry-run-key';

    const logs: string[] = [];
    const logSpy = vi.spyOn(console, 'log').mockImplementation((message?: unknown, ...rest: unknown[]) => {
      logs.push(format(String(message ?? ''), ...rest));
    });
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      client,
      '--config',
      configPath,
      '--dry-run',
      '--non-interactive',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const joined = logs.join('\n');
    expect(joined).toContain('@@');
    expect(joined).toContain('vibe-check-mcp-cli"');
    expect(joined).toContain('@pv-bhat/vibe-check-mcp');

    const after = await fs.readFile(configPath, 'utf8');
    expect(after).toBe(original);

    const files = await fs.readdir(tmpDir);
    expect(files.some((file) => file.endsWith('.bak'))).toBe(false);
  });
});

```

--------------------------------------------------------------------------------
/docs/TESTING.md:
--------------------------------------------------------------------------------

```markdown
# Testing Guide

The server now includes a JSON-RPC compatibility layer that backfills missing `id` fields on `tools/call` requests. The shim mitigates gaps in some clients so the stock `@modelcontextprotocol/sdk` client and Windsurf work out of the box again, but JSON-RPC 2.0-compliant clients should continue to send an `id` on every request. Treat the compatibility layer as a guard rail, not a substitute for well-formed requests.

## Running Tests

1.  **Build the server:**
    ```bash
    npm run build
    ```
2.  **Generate optional sample requests:**
    The legacy helper scripts remain available if you want ready-made payloads for manual testing, but they are no longer required for Windsurf or the SDK client now that the shim fills in missing identifiers.
    - `alt-test.js` (OpenRouter) writes `request1.json` and `request2.json` for history testing.
    - `alt-test-openai.js` generates `request.json` targeting the OpenAI provider.
    - `alt-test-gemini.js` generates `request.json` using the default Gemini provider.
    ```bash
    node alt-test.js            # OpenRouter history test
    node alt-test-openai.js     # OpenAI example
    node alt-test-gemini.js     # Gemini example
    ```
3.  **Run the server with the requests (optional):**
    Pipe the contents of each generated file to the server if you are using the helper scripts.

    **History test (OpenRouter):**
    ```bash
    node build/index.js < request1.json
    node build/index.js < request2.json
    ```
    **Single provider examples:**
    ```bash
    node build/index.js < request.json   # created by alt-test-openai.js or alt-test-gemini.js
    ```
    The server will process the requests and print the responses to standard output. The second OpenRouter call should show that the previous history was considered.

## Troubleshooting

- **No output after sending a request:** JSON-RPC notifications (requests without an `id`) do not receive responses by design. The compatibility shim synthesizes a stable identifier with a random nonce for `tools/call` payloads that omit `id`, but other methods still expect a proper identifier from the client. Ensure your integration includes an `id` if you need a response.
- **HTTP mode confusion:** The HTTP transport now scopes JSON fallbacks to the current request. Legacy clients that only accept `application/json` receive a direct JSON response, while streaming clients continue to see Server-Sent Events. Concurrent traffic no longer causes response-mode leaks between requests.

## Unit Tests with Vitest

Vitest is used for unit and integration tests. Run all tests with:
```bash
npm test
```
Generate a coverage report (outputs to `coverage/`):
```bash
npm run test:coverage
```
All tests should pass with at least 80% line coverage.

```

--------------------------------------------------------------------------------
/tests/startup.test.ts:
--------------------------------------------------------------------------------

```typescript
import { describe, it, expect } from 'vitest';
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';
import path from 'path';
import net from 'net';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function runStartupTest(envVar: 'MCP_HTTP_PORT' | 'PORT' | 'BOTH') {
  const startTime = Date.now();

  const projectRoot = path.resolve(__dirname, '..');
  const indexPath = path.join(projectRoot, 'build', 'index.js');

  const getPort = () =>
    new Promise<number>((resolve, reject) => {
      const s = net.createServer();
      s.listen(0, () => {
        const p = (s.address() as any).port;
        s.close(() => resolve(p));
      });
      s.on('error', reject);
    });

  const mainPort = await getPort();
  const env: NodeJS.ProcessEnv = { ...process.env };
  delete env.GEMINI_API_KEY;

  if (envVar === 'MCP_HTTP_PORT') {
    env.MCP_HTTP_PORT = String(mainPort);
  } else if (envVar === 'PORT') {
    env.PORT = String(mainPort);
  } else {
    env.MCP_HTTP_PORT = String(mainPort);
    const otherPort = await getPort();
    env.PORT = String(otherPort);
  }

  const serverProcess = spawn('node', [indexPath], {
    env,
    stdio: ['ignore', 'pipe', 'pipe'],
  });

  try {
    let res: Response | null = null;
    for (let i = 0; i < 40; i++) {
      try {
        const attempt = await fetch(`http://localhost:${mainPort}/mcp`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json, text/event-stream'
          },
          body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }),
        });
        if (attempt.status === 200) {
          res = attempt;
          break;
        }
      } catch {}
      await new Promise((r) => setTimeout(r, 250));
    }
    if (!res) throw new Error('Server did not start');
    const text = await res.text();
    const line = text.split('\n').find((l) => l.startsWith('data: '));
    const json = line ? JSON.parse(line.slice(6)) : null;

    const duration = Date.now() - startTime;
    expect(res.status).toBe(200);
    expect(json?.result?.tools.some((t: any) => t.name === 'update_constitution')).toBe(true);
    expect(duration).toBeLessThan(5000);
  } finally {
    serverProcess.kill();
  }
}

describe('Server Startup and Response Time', () => {
  it('should start and respond to a tools/list request over HTTP using MCP_HTTP_PORT', async () => {
    await runStartupTest('MCP_HTTP_PORT');
  }, 10000);

  it('should start and respond to a tools/list request over HTTP using PORT', async () => {
    await runStartupTest('PORT');
  }, 10000);

  it('should prefer MCP_HTTP_PORT when both MCP_HTTP_PORT and PORT are set', async () => {
    await runStartupTest('BOTH');
  }, 10000);
});

```

--------------------------------------------------------------------------------
/docs/integrations/cpi.md:
--------------------------------------------------------------------------------

```markdown
# CPI Integration

## Overview
> CPI (Chain-Pattern Interrupt): a runtime oversight mechanism for multi-agent systems that mitigates “reasoning lock-in.” It injects interrupts based on policy triggers (pattern detectors, heuristics, or external signals), then resumes or reroutes flow.
>
> Core pieces: (1) trigger evaluators, (2) intervention policy (allow/block/route/ask-human), (3) logging & repro harness.
>
> Status: repo includes repro evals; “constitution” tool supports per-session rule-sets.
>
> Integration intent with VibeCheck: VibeCheck = metacognitive layer (signals/traits/uncertainty). CPI = on-policy interrupter. VibeCheck feeds CPI triggers; CPI acts on them.

CPI composes with VibeCheck by acting as an on-policy interrupter whenever VibeCheck signals a risk spike. Use VibeCheck to surface agent traits, uncertainty, and risk levels, then forward that context to CPI so its policy engine can decide whether to allow, block, reroute, or escalate the next action. The example stub in [`examples/cpi-integration.ts`](../../examples/cpi-integration.ts) illustrates the plumbing you can copy into your own orchestrator.

## Flow diagram
```mermaid
flowchart LR
  AgentStep[Agent step] -->|emit signals| VibeCheck
  VibeCheck -->|risk + traits| CPI
  CPI -->|policy decision| AgentController[Agent controller]
  AgentController -->|resume/adjust| AgentStep
```

## Minimal integration sketch
Below is a minimal TypeScript sketch that mirrors the logic in the [`runWithCPI`](../../examples/cpi-integration.ts) example. Replace the TODO markers with the real CPI SDK import when it becomes available.

```ts
type AgentStep = {
  sessionId: string;
  summary: string;
  nextAction: string;
};

type VibeCheckSignal = {
  riskScore: number;
  advice: string;
};

async function analyzeWithVibeCheck(step: AgentStep): Promise<VibeCheckSignal> {
  // TODO: replace with a real call to the VibeCheck MCP server.
  return { riskScore: Math.random(), advice: `Reflect on: ${step.summary}` };
}

// TODO: replace with `import { createPolicy } from '@cpi/sdk';`
function cpiPolicyShim(signal: VibeCheckSignal) {
  if (signal.riskScore >= 0.6) {
    return { action: 'interrupt', reason: 'High metacognitive risk from VibeCheck' } as const;
  }
  return { action: 'allow' } as const;
}

export async function evaluateStep(step: AgentStep) {
  const signal = await analyzeWithVibeCheck(step);
  const decision = cpiPolicyShim(signal);

  if (decision.action === 'interrupt') {
    // Pause your agent, collect clarification, or reroute to a human.
    return { status: 'paused', reason: decision.reason } as const;
  }

  return { status: 'continue', signal } as const;
}
```

### Implementation checklist
1. Surface VibeCheck scores (risk, traits, uncertainty) alongside the raw advice payload.
2. Normalize those signals into CPI trigger events (e.g., `riskScore > 0.6`).
3. Hand the event to a CPI intervention policy and respect the returned directive.
4. Feed decisions into the CPI logging & repro harness to preserve traces.

## Further reading
- CPI reference implementation (placeholder): <https://github.com/<ORG>/cpi>
- VibeCheck + CPI wiring example: [`examples/cpi-integration.ts`](../../examples/cpi-integration.ts)

```

--------------------------------------------------------------------------------
/src/cli/clients/shared.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fsPromises, constants as fsConstants } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import os from 'node:os';
import { isDeepStrictEqual } from 'node:util';

const { access, mkdir, readFile, rename, writeFile } = fsPromises;

export type JsonRecord = Record<string, unknown>;

export type TransportKind = 'stdio' | 'http';

export type MergeOpts = {
  id: string;
  sentinel: string;
  transport: TransportKind;
  httpUrl?: string;
  dev?: {
    watch?: boolean;
    debug?: string;
  };
};

export type MergeResult = {
  next: JsonRecord;
  changed: boolean;
  reason?: string;
};

export type ClientDescription = {
  name: string;
  pathHint: string;
  summary?: string;
  transports?: TransportKind[];
  defaultTransport?: TransportKind;
  requiredEnvKeys?: readonly string[];
  notes?: string;
  docsUrl?: string;
};

export interface ClientAdapter {
  locate(custom?: string): Promise<string | null>;
  read(path: string, raw?: string): Promise<JsonRecord>;
  merge(config: JsonRecord, entry: JsonRecord, options: MergeOpts): MergeResult;
  writeAtomic(path: string, data: JsonRecord): Promise<void>;
  describe(): ClientDescription;
}

export function isRecord(value: unknown): value is JsonRecord {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

export async function pathExists(path: string): Promise<boolean> {
  try {
    await access(path, fsConstants.F_OK);
    return true;
  } catch {
    return false;
  }
}

export function expandHomePath(path: string): string {
  if (!path.startsWith('~')) {
    return resolve(path);
  }

  const home = os.homedir();
  if (path === '~') {
    return home;
  }

  const remainder = path.slice(1);
  if (remainder.startsWith('/') || remainder.startsWith('\\')) {
    return resolve(join(home, remainder.slice(1)));
  }

  return resolve(join(home, remainder));
}

export async function readJsonFile(path: string, raw?: string, context = 'Client configuration'): Promise<JsonRecord> {
  const payload = raw ?? (await readFile(path, 'utf8'));
  const parsed = JSON.parse(payload);
  if (!isRecord(parsed)) {
    throw new Error(`${context} must be a JSON object.`);
  }

  return parsed;
}

export async function writeJsonFileAtomic(path: string, data: JsonRecord): Promise<void> {
  await mkdir(dirname(path), { recursive: true });
  const tempPath = `${path}.${process.pid}.${Date.now()}.tmp`;
  const payload = `${JSON.stringify(data, null, 2)}\n`;
  await writeFile(tempPath, payload, { mode: 0o600 });
  await rename(tempPath, path);
}

export function mergeIntoMap(
  config: JsonRecord,
  entry: JsonRecord,
  options: MergeOpts,
  mapKey: string,
): MergeResult {
  const baseConfig = isRecord(config) ? config : {};
  const existingMap = isRecord(baseConfig[mapKey]) ? { ...(baseConfig[mapKey] as JsonRecord) } : {};
  const currentEntry = isRecord(existingMap[options.id])
    ? ({ ...(existingMap[options.id] as JsonRecord) } as JsonRecord)
    : null;

  if (currentEntry && currentEntry.managedBy !== options.sentinel) {
    return {
      next: baseConfig,
      changed: false,
      reason: `Existing entry "${options.id}" is not managed by ${options.sentinel}.`,
    };
  }

  const sanitizedEntry = { ...entry } as JsonRecord;
  delete sanitizedEntry.managedBy;

  const nextEntry: JsonRecord = { ...sanitizedEntry, managedBy: options.sentinel };
  const nextMap = { ...existingMap, [options.id]: nextEntry };
  const nextConfig: JsonRecord = { ...baseConfig, [mapKey]: nextMap };

  if (currentEntry && isDeepStrictEqual(currentEntry, nextEntry)) {
    return { next: baseConfig, changed: false };
  }

  return { next: nextConfig, changed: true };
}

```

--------------------------------------------------------------------------------
/tests/cursor-merge.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import os from 'node:os';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import cursorAdapter from '../src/cli/clients/cursor.js';
import { MergeOpts } from '../src/cli/clients/shared.js';
import { createCliProgram } from '../src/cli/index.js';

const SENTINEL = 'vibe-check-mcp-cli';
const FIXTURE_DIR = join(process.cwd(), 'tests', 'fixtures', 'cursor');

function loadFixture(name: string): Record<string, unknown> {
  const raw = readFileSync(join(FIXTURE_DIR, name), 'utf8');
  return JSON.parse(raw) as Record<string, unknown>;
}

const ENTRY = {
  command: 'npx',
  args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
  env: {},
} as const;

const MERGE_OPTS: MergeOpts = {
  id: 'vibe-check-mcp',
  sentinel: SENTINEL,
  transport: 'stdio',
};

describe('Cursor MCP config merge', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('appends the managed entry to a base config', () => {
    const base = loadFixture('config.base.json');
    const result = cursorAdapter.merge(base, ENTRY, MERGE_OPTS);
    expect(result.changed).toBe(true);
    expect(result.next.mcpServers).toMatchObject({
      'vibe-check-mcp': {
        command: 'npx',
        args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
        env: {},
        managedBy: SENTINEL,
      },
    });
  });

  it('updates an existing managed entry in place', () => {
    const base = loadFixture('config.with-managed-entry.json');
    const result = cursorAdapter.merge(base, ENTRY, MERGE_OPTS);
    expect(result.changed).toBe(true);
    const next = result.next.mcpServers as Record<string, unknown>;
    expect(next['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
  });

  it('does not replace an unmanaged entry', () => {
    const base = loadFixture('../claude/config.with-other-servers.json');
    const result = cursorAdapter.merge(base, ENTRY, MERGE_OPTS);
    expect(result.changed).toBe(false);
    expect(result.reason).toContain('not managed');
  });

  it('creates a backup and writes via the CLI install command', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'cursor-merge-'));
    const configPath = join(tmpDir, 'mcp.json');
    const original = readFileSync(join(FIXTURE_DIR, 'config.base.json'), 'utf8');
    await fs.writeFile(configPath, original, 'utf8');

    process.env.OPENAI_API_KEY = 'sk-cursor-key';

    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      'cursor',
      '--config',
      configPath,
      '--non-interactive',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const files = await fs.readdir(tmpDir);
    const backup = files.find((file) => file.endsWith('.bak'));
    expect(backup).toBeDefined();
    if (backup) {
      const backupContent = await fs.readFile(join(tmpDir, backup), 'utf8');
      expect(backupContent).toBe(original);
    }

    const finalContent = await fs.readFile(configPath, 'utf8');
    const parsed = JSON.parse(finalContent) as Record<string, any>;
    expect(parsed.mcpServers['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
  });
});

```

--------------------------------------------------------------------------------
/tests/vscode-merge.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import os from 'node:os';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import vscodeAdapter from '../src/cli/clients/vscode.js';
import { MergeOpts } from '../src/cli/clients/shared.js';
import { createCliProgram } from '../src/cli/index.js';

const SENTINEL = 'vibe-check-mcp-cli';
const FIXTURE_DIR = join(process.cwd(), 'tests', 'fixtures', 'vscode');

function loadFixture(name: string): Record<string, unknown> {
  const raw = readFileSync(join(FIXTURE_DIR, name), 'utf8');
  return JSON.parse(raw) as Record<string, unknown>;
}

describe('VS Code MCP config merge', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('appends the managed entry under servers', () => {
    const base = loadFixture('workspace.mcp.base.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    } as const;
    const options: MergeOpts = {
      id: 'vibe-check-mcp',
      sentinel: SENTINEL,
      transport: 'stdio',
    };

    const result = vscodeAdapter.merge(base, entry, options);
    expect(result.changed).toBe(true);
    const next = result.next.servers as Record<string, any>;
    expect(next['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      transport: 'stdio',
      managedBy: SENTINEL,
    });
  });

  it('adds dev configuration when requested', () => {
    const base = loadFixture('workspace.mcp.base.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    } as const;
    const options: MergeOpts = {
      id: 'vibe-check-mcp',
      sentinel: SENTINEL,
      transport: 'stdio',
      dev: {
        watch: true,
        debug: 'node',
      },
    };

    const result = vscodeAdapter.merge(base, entry, options);
    const server = (result.next.servers as Record<string, any>)['vibe-check-mcp'];
    expect(server.dev).toEqual({ watch: true, debug: 'node' });
  });

  it('creates a backup and writes via CLI install', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'vscode-merge-'));
    const configDir = join(tmpDir, '.vscode');
    await fs.mkdir(configDir, { recursive: true });
    const configPath = join(configDir, 'mcp.json');
    const original = readFileSync(join(FIXTURE_DIR, 'workspace.mcp.base.json'), 'utf8');
    await fs.writeFile(configPath, original, 'utf8');

    process.env.OPENROUTER_API_KEY = 'sk-or-vscode-key';

    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      'vscode',
      '--config',
      configPath,
      '--non-interactive',
      '--dev-watch',
      '--dev-debug',
      'node',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const files = await fs.readdir(configDir);
    const backup = files.find((file) => file.endsWith('.bak'));
    expect(backup).toBeDefined();

    if (backup) {
      const backupContent = await fs.readFile(join(configDir, backup), 'utf8');
      expect(backupContent).toBe(original);
    }

    const finalContent = await fs.readFile(configPath, 'utf8');
    const parsed = JSON.parse(finalContent) as Record<string, any>;
    expect(parsed.servers['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      transport: 'stdio',
      dev: {
        watch: true,
        debug: 'node',
      },
      managedBy: SENTINEL,
    });
  });
});

```

--------------------------------------------------------------------------------
/tests/claude-merge.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import os from 'node:os';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { createCliProgram } from '../src/cli/index.js';
import { mergeMcpEntry } from '../src/cli/clients/claude.js';

const SENTINEL = 'vibe-check-mcp-cli';
const FIXTURE_DIR = join(process.cwd(), 'tests', 'fixtures', 'claude');

function loadFixture(name: string): Record<string, unknown> {
  const raw = readFileSync(join(FIXTURE_DIR, name), 'utf8');
  return JSON.parse(raw) as Record<string, unknown>;
}

describe('Claude MCP config merge', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('appends the managed entry to a base config', () => {
    const base = loadFixture('config.base.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    };

    const result = mergeMcpEntry(base, entry, { id: 'vibe-check-mcp', sentinel: SENTINEL });
    expect(result.changed).toBe(true);
    expect(result.next.mcpServers).toMatchObject({
      'vibe-check-mcp': {
        command: 'npx',
        args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
        env: {},
        managedBy: SENTINEL,
      },
    });
    expect(result.next.mcpServers).toHaveProperty('other-server');
  });

  it('updates an existing managed entry in place', () => {
    const base = loadFixture('config.with-managed-entry.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    };

    const result = mergeMcpEntry(base, entry, { id: 'vibe-check-mcp', sentinel: SENTINEL });
    expect(result.changed).toBe(true);
    const nextServers = result.next.mcpServers as Record<string, unknown>;
    expect(nextServers['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
  });

  it('skips unmanaged entries with the same id', () => {
    const base = loadFixture('config.with-other-servers.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    };

    const result = mergeMcpEntry(base, entry, { id: 'vibe-check-mcp', sentinel: SENTINEL });
    expect(result.changed).toBe(false);
    expect(result.reason).toContain('not managed');
    expect(result.next).toEqual(base);
  });

  it('writes atomically and creates a backup when installing via CLI', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'vibe-claude-'));
    const configPath = join(tmpDir, 'claude.json');
    const fixturePath = join(FIXTURE_DIR, 'config.base.json');
    const original = readFileSync(fixturePath, 'utf8');
    await fs.writeFile(configPath, original, 'utf8');

    process.env.ANTHROPIC_API_KEY = 'sk-ant-test-token';

    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      'claude',
      '--config',
      configPath,
      '--non-interactive',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const files = await fs.readdir(tmpDir);
    const backup = files.find((file) => file.endsWith('.bak'));
    expect(backup).toBeDefined();
    const backupContent = await fs.readFile(join(tmpDir, backup as string), 'utf8');
    expect(backupContent).toBe(original);

    const finalContent = await fs.readFile(configPath, 'utf8');
    const parsed = JSON.parse(finalContent) as Record<string, any>;
    expect(parsed.mcpServers['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
    expect(parsed.mcpServers).toHaveProperty('other-server');
  });
});

```

--------------------------------------------------------------------------------
/docs/clients.md:
--------------------------------------------------------------------------------

```markdown
# MCP Client Integration Notes

This document supplements the CLI installers documented in the [README](../README.md). Each section outlines discovery paths, schema nuances, and post-installation tips.

> Tip: Run `npx @pv-bhat/vibe-check-mcp --list-clients` to see a quick summary of every supported integration.

For supported providers, secret resolution, and storage guidance, read [API Keys & Secret Management](./api-keys.md). The notes below cover only client-specific requirements and edge cases.

## Claude Desktop

- **Config path**: `claude_desktop_config.json` (auto-detected per platform).
- **Schema**: `mcpServers` map keyed by server ID.
- **Default transport**: stdio (`npx -y @pv-bhat/vibe-check-mcp start --stdio`).
- **API keys**: Requires `ANTHROPIC_API_KEY`.
- **Restart**: Quit and relaunch Claude Desktop after installation.

```jsonc
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}
```

Docs: [Claude Desktop MCP](https://docs.anthropic.com/en/docs/claude-desktop/model-context-protocol)

## Claude Code

- **Config path**: `~/.config/Claude/claude_code_config.json` (auto-detected per platform).
- **Schema**: Claude-style `mcpServers` map.
- **Default transport**: stdio (`npx -y @pv-bhat/vibe-check-mcp start --stdio`).
- **API keys**: Requires `ANTHROPIC_API_KEY`.
- **Bootstrap**: Run `claude code login` or any Claude Code command once to scaffold the config file.

```jsonc
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}
```

Docs: [Claude Code MCP integration](https://docs.anthropic.com/en/docs/agents/claude-code)

## Cursor

- **Config path**: `~/.cursor/mcp.json` (override with `--config` if needed).
- **Schema**: Claude-style `mcpServers` map.
- **Fallback**: When the config file is missing, the CLI prints a JSON snippet suitable for Cursor's MCP settings UI.

```jsonc
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}
```

Reference: [Cursor community thread on MCP](https://forum.cursor.so/t/mcp-support/1487)

## Windsurf (Cascade)

- **Config paths**: legacy `~/.codeium/windsurf/mcp_config.json`, new builds `~/.codeium/mcp_config.json`.
- **Transports**: stdio by default; HTTP uses `serverUrl`.
- **Restart**: Close and reopen Windsurf to reload MCP servers.

```jsonc
// stdio
{
  "mcpServers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}

// http
{
  "mcpServers": {
    "vibe-check-mcp": {
      "serverUrl": "http://127.0.0.1:2091",
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}
```

Docs: [Codeium Windsurf MCP guide](https://docs.codeium.com/windsurf/model-context-protocol)

## Visual Studio Code

- **Workspace config**: `.vscode/mcp.json` (profiles use the VS Code user data dir).
- **Transports**: stdio (`transport: "stdio"`) or HTTP (`url` + `transport: "http"`).
- **CLI tips**: Provide `--config` to target a workspace file. Without it, the CLI prints a JSON snippet plus a `vscode:mcp/install?...` quick-install link.
- **Dev helpers**: `--dev-watch` sets `dev.watch=true`; `--dev-debug <value>` populates `dev.debug`.

```jsonc
{
  "servers": {
    "vibe-check-mcp": {
      "command": "npx",
      "args": ["-y", "@pv-bhat/vibe-check-mcp", "start", "--stdio"],
      "env": {},
      "transport": "stdio",
      "managedBy": "vibe-check-mcp-cli"
    }
  }
}
```

Docs:
- [VS Code MCP announcement](https://code.visualstudio.com/updates/v1_102#_model-context-protocol)
- [VS Code MCP quickstart](https://code.visualstudio.com/docs/copilot/mcp)

## JetBrains (future)

JetBrains AI Assistant already consumes Claude-style MCP configs over stdio. Import from Claude or point it at the same command once JetBrains exposes MCP import hooks publicly.

Docs: [JetBrains AI Assistant MCP](https://blog.jetbrains.com/ai/2024/08/model-context-protocol/)

```

--------------------------------------------------------------------------------
/tests/windsurf-merge.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import os from 'node:os';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import windsurfAdapter from '../src/cli/clients/windsurf.js';
import { MergeOpts } from '../src/cli/clients/shared.js';
import { createCliProgram } from '../src/cli/index.js';

const SENTINEL = 'vibe-check-mcp-cli';
const FIXTURE_DIR = join(process.cwd(), 'tests', 'fixtures', 'windsurf');

function loadFixture(name: string): Record<string, unknown> {
  const raw = readFileSync(join(FIXTURE_DIR, name), 'utf8');
  return JSON.parse(raw) as Record<string, unknown>;
}

describe('Windsurf MCP config merge', () => {
  const ORIGINAL_ENV = { ...process.env };

  beforeEach(() => {
    process.exitCode = undefined;
    process.env = { ...ORIGINAL_ENV };
  });

  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('appends a stdio entry to a base config', () => {
    const base = loadFixture('config.base.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    } as const;
    const options: MergeOpts = {
      id: 'vibe-check-mcp',
      sentinel: SENTINEL,
      transport: 'stdio',
    };

    const result = windsurfAdapter.merge(base, entry, options);
    expect(result.changed).toBe(true);
    const next = result.next.mcpServers as Record<string, unknown>;
    expect(next['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
  });

  it('preserves a managed http entry and updates the URL', () => {
    const base = loadFixture('config.with-http-entry.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--http', '--port', '3000'],
      env: {},
    } as const;
    const options: MergeOpts = {
      id: 'vibe-check-mcp',
      sentinel: SENTINEL,
      transport: 'http',
      httpUrl: 'http://127.0.0.1:3000',
    };

    const result = windsurfAdapter.merge(base, entry, options);
    expect(result.changed).toBe(true);
    const next = result.next.mcpServers as Record<string, any>;
    expect(next['vibe-check-mcp']).toEqual({
      serverUrl: 'http://127.0.0.1:3000',
      managedBy: SENTINEL,
    });
  });

  it('does not replace unmanaged entries', () => {
    const base = loadFixture('../claude/config.with-other-servers.json');
    const entry = {
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
    } as const;
    const options: MergeOpts = {
      id: 'vibe-check-mcp',
      sentinel: SENTINEL,
      transport: 'stdio',
    };

    const result = windsurfAdapter.merge(base, entry, options);
    expect(result.changed).toBe(false);
    expect(result.reason).toContain('not managed');
  });

  it('creates a backup and writes via CLI install', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'windsurf-merge-'));
    const configPath = join(tmpDir, 'mcp_config.json');
    const original = readFileSync(join(FIXTURE_DIR, 'config.base.json'), 'utf8');
    await fs.writeFile(configPath, original, 'utf8');

    process.env.GEMINI_API_KEY = 'AI-windsurf-key';

    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});

    const program = createCliProgram();
    await program.parseAsync([
      'node',
      'vibe-check-mcp',
      'install',
      '--client',
      'windsurf',
      '--config',
      configPath,
      '--non-interactive',
    ]);

    logSpy.mockRestore();
    warnSpy.mockRestore();

    const files = await fs.readdir(tmpDir);
    const backup = files.find((file) => file.endsWith('.bak'));
    expect(backup).toBeDefined();

    if (backup) {
      const backupContent = await fs.readFile(join(tmpDir, backup), 'utf8');
      expect(backupContent).toBe(original);
    }

    const finalContent = await fs.readFile(configPath, 'utf8');
    const parsed = JSON.parse(finalContent) as Record<string, any>;
    expect(parsed.mcpServers['vibe-check-mcp']).toEqual({
      command: 'npx',
      args: ['-y', '@pv-bhat/vibe-check-mcp', 'start', '--stdio'],
      env: {},
      managedBy: SENTINEL,
    });
  });
});

```

--------------------------------------------------------------------------------
/tests/claude-config.test.ts:
--------------------------------------------------------------------------------

```typescript
import { promises as fs } from 'node:fs';
import { dirname, join } from 'node:path';
import os from 'node:os';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
  locateClaudeConfig,
  readClaudeConfig,
  writeClaudeConfigAtomic,
} from '../src/cli/clients/claude.js';

const ORIGINAL_ENV = { ...process.env };

describe('Claude config helpers', () => {
  afterEach(() => {
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('expands custom paths with a tilde', async () => {
    const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'claude-home-'));
    vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);

    const result = await locateClaudeConfig('~/config.json');
    expect(result).toBe(join(tmpHome, 'config.json'));
  });

  it('expands custom paths with a tilde and backslash', async () => {
    const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'claude-home-'));
    vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);

    const result = await locateClaudeConfig('~\\config.json');
    expect(result).toBe(join(tmpHome, 'config.json'));
  });

  it('locates the default macOS path when present', async () => {
    const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'claude-home-'));
    vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
    const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin');

    const candidate = join(
      tmpHome,
      'Library',
      'Application Support',
      'Claude',
      'claude_desktop_config.json',
    );
    await fs.mkdir(dirname(candidate), { recursive: true });
    await fs.writeFile(candidate, '{}', 'utf8');

    const result = await locateClaudeConfig();
    expect(result).toBe(candidate);

    platformSpy.mockRestore();
  });

  it('locates the config via APPDATA on Windows', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'claude-appdata-'));
    const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');

    const originalAppData = process.env.APPDATA;
    process.env.APPDATA = join(tmpDir, 'AppData');

    const candidate = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
    await fs.mkdir(dirname(candidate), { recursive: true });
    await fs.writeFile(candidate, '{}', 'utf8');

    const result = await locateClaudeConfig();
    expect(result).toBe(candidate);

    if (originalAppData === undefined) {
      delete process.env.APPDATA;
    } else {
      process.env.APPDATA = originalAppData;
    }
    platformSpy.mockRestore();
  });

  it('prefers XDG config directories on Linux', async () => {
    const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'claude-home-'));
    const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
    vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);

    const xdgDir = await fs.mkdtemp(join(os.tmpdir(), 'claude-xdg-'));
    process.env.XDG_CONFIG_HOME = xdgDir;

    const candidate = join(xdgDir, 'Claude', 'claude_desktop_config.json');
    await fs.mkdir(dirname(candidate), { recursive: true });
    await fs.writeFile(candidate, '{}', 'utf8');

    const result = await locateClaudeConfig();
    expect(result).toBe(candidate);

    platformSpy.mockRestore();
  });

  it('returns null when no candidates exist', async () => {
    const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
    const tmpHome = await fs.mkdtemp(join(os.tmpdir(), 'claude-home-'));
    vi.spyOn(os, 'homedir').mockReturnValue(tmpHome);
    process.env.XDG_CONFIG_HOME = '';

    const result = await locateClaudeConfig();
    expect(result).toBeNull();

    platformSpy.mockRestore();
  });

  it('writes configs atomically with 0600 permissions', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'claude-write-'));
    const target = join(tmpDir, 'config.json');

    await writeClaudeConfigAtomic(target, { hello: 'world' });

    const stat = await fs.stat(target);
    expect(stat.mode & 0o777).toBe(0o600);

    const content = await fs.readFile(target, 'utf8');
    expect(JSON.parse(content)).toEqual({ hello: 'world' });
  });

  it('throws when config JSON is not an object', async () => {
    const tmpDir = await fs.mkdtemp(join(os.tmpdir(), 'claude-read-'));
    const target = join(tmpDir, 'config.json');
    await fs.writeFile(target, '"string"', 'utf8');

    await expect(readClaudeConfig(target)).rejects.toThrow('Claude config must be a JSON object.');
  });
});

```

--------------------------------------------------------------------------------
/scripts/docker-setup.sh:
--------------------------------------------------------------------------------

```bash
#!/bin/bash

echo "========================================================"
echo "Vibe Check MCP Docker Setup for Cursor IDE"
echo "========================================================"
echo ""

# Check for Docker installation
if ! command -v docker &> /dev/null; then
    echo "Error: Docker is not installed or not in PATH."
    echo "Please install Docker from https://docs.docker.com/get-docker/"
    exit 1
fi

# Check for Docker Compose installation
if ! command -v docker-compose &> /dev/null; then
    echo "Error: Docker Compose is not installed or not in PATH."
    echo "Please install Docker Compose from https://docs.docker.com/compose/install/"
    exit 1
fi

# Create directory for Vibe Check MCP
mkdir -p ~/vibe-check-mcp
cd ~/vibe-check-mcp

# Download or create necessary files
echo "Downloading required files..."

# Create docker-compose.yml
cat > docker-compose.yml << 'EOL'
version: '3'

services:
  vibe-check-mcp:
    build:
      context: .
      dockerfile: Dockerfile
    image: vibe-check-mcp:latest
    container_name: vibe-check-mcp
    restart: always
    environment:
      - GEMINI_API_KEY=${GEMINI_API_KEY}
    volumes:
      - vibe-check-data:/app/data

volumes:
  vibe-check-data:
EOL

# Create Dockerfile if it doesn't exist
cat > Dockerfile << 'EOL'
FROM node:lts-alpine

WORKDIR /app

# Clone the repository
RUN apk add --no-cache git \
    && git clone https://github.com/PV-Bhat/vibe-check-mcp-server.git .

# Install dependencies and build
RUN npm install && npm run build

# Run the MCP server
CMD ["node", "build/index.js"]
EOL

# Create .env file
echo "Enter your Gemini API key:"
read -p "API Key: " GEMINI_API_KEY

cat > .env << EOL
GEMINI_API_KEY=$GEMINI_API_KEY
EOL

chmod 600 .env  # Secure the API key file

# Create startup script
cat > start-vibe-check-docker.sh << 'EOL'
#!/bin/bash
cd ~/vibe-check-mcp
docker-compose up -d
EOL

chmod +x start-vibe-check-docker.sh

# Create a TCP wrapper script to route stdio to TCP port 3000
cat > vibe-check-tcp-wrapper.sh << 'EOL'
#!/bin/bash
# This script connects stdio to the Docker container's TCP port
exec socat STDIO TCP:localhost:3000
EOL

chmod +x vibe-check-tcp-wrapper.sh

# Detect OS for autostart configuration
OS="$(uname -s)"
case "${OS}" in
    Linux*)     OS="Linux";;
    Darwin*)    OS="Mac";;
    *)          OS="Unknown";;
esac

echo "Setting up auto-start for $OS..."

if [ "$OS" = "Mac" ]; then
    # Set up LaunchAgent for Mac
    PLIST_FILE="$HOME/Library/LaunchAgents/com.vibe-check-mcp-docker.plist"
    mkdir -p "$HOME/Library/LaunchAgents"
    
    cat > "$PLIST_FILE" << EOL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.vibe-check-mcp-docker</string>
    <key>ProgramArguments</key>
    <array>
        <string>$HOME/vibe-check-mcp/start-vibe-check-docker.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>
EOL

    chmod 644 "$PLIST_FILE"
    launchctl load "$PLIST_FILE"
    
    echo "Created and loaded LaunchAgent for automatic Docker startup on login."
    
elif [ "$OS" = "Linux" ]; then
    # Set up systemd user service for Linux
    SERVICE_DIR="$HOME/.config/systemd/user"
    mkdir -p "$SERVICE_DIR"
    
    cat > "$SERVICE_DIR/vibe-check-mcp-docker.service" << EOL
[Unit]
Description=Vibe Check MCP Docker Container
After=docker.service

[Service]
ExecStart=$HOME/vibe-check-mcp/start-vibe-check-docker.sh
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=default.target
EOL

    systemctl --user daemon-reload
    systemctl --user enable vibe-check-mcp-docker.service
    systemctl --user start vibe-check-mcp-docker.service
    
    echo "Created and started systemd user service for automatic Docker startup."
fi

# Start the container
echo "Starting Vibe Check MCP Docker container..."
./start-vibe-check-docker.sh

echo ""
echo "Vibe Check MCP Docker setup complete!"
echo ""
echo "To complete the setup, configure Cursor IDE:"
echo ""
echo "1. Open Cursor IDE"
echo "2. Go to Settings (gear icon) -> MCP"
echo "3. Click \"Add New MCP Server\""
echo "4. Enter the following information:"
echo "   - Name: Vibe Check"
echo "   - Type: Command"
echo "   - Command: $HOME/vibe-check-mcp/vibe-check-tcp-wrapper.sh"
echo "5. Click \"Save\" and then \"Refresh\""
echo ""
echo "Vibe Check MCP will now start automatically when you log in."
echo ""
```

--------------------------------------------------------------------------------
/src/tools/vibeLearn.ts:
--------------------------------------------------------------------------------

```typescript
import {
  addLearningEntry,
  getLearningCategorySummary,
  getLearningEntries,
  LearningEntry,
  LearningType
} from '../utils/storage.js';

// Vibe Learn tool interfaces
export interface VibeLearnInput {
  mistake: string;
  category: string;
  solution?: string;
  type?: LearningType;
  sessionId?: string;
}

export interface VibeLearnOutput {
  added: boolean;
  currentTally: number;
  alreadyKnown?: boolean;
  topCategories: Array<{
    category: string;
    count: number;
    recentExample: LearningEntry;
  }>;
}

/**
 * The vibe_learn tool records one-sentence mistakes and solutions
 * to build a pattern recognition system for future improvement
 */
export async function vibeLearnTool(input: VibeLearnInput): Promise<VibeLearnOutput> {
  try {
    // Validate input
    if (!input.mistake) {
      throw new Error('Mistake description is required');
    }
    if (!input.category) {
      throw new Error('Mistake category is required');
    }
    const entryType: LearningType = input.type ?? 'mistake';
    if (entryType !== 'preference' && !input.solution) {
      throw new Error('Solution is required for this entry type');
    }
    
    // Enforce single-sentence constraints
    const mistake = enforceOneSentence(input.mistake);
    const solution = input.solution ? enforceOneSentence(input.solution) : undefined;
    
    // Normalize category to one of our standard categories if possible
    const category = normalizeCategory(input.category);
    
    // Check for similar mistake
    const existing = getLearningEntries()[category] || [];
    const alreadyKnown = existing.some(e => isSimilar(e.mistake, mistake));

    // Add mistake to log if new
    let entry: LearningEntry | undefined;
    if (!alreadyKnown) {
      entry = addLearningEntry(mistake, category, solution, entryType);
    }
    
    // Get category summaries
    const categorySummary = getLearningCategorySummary();
    
    // Find current tally for this category
    const categoryData = categorySummary.find(m => m.category === category);
    const currentTally = categoryData?.count || 1;
    
    // Get top 3 categories
    const topCategories = categorySummary.slice(0, 3);

    return {
      added: !alreadyKnown,
      alreadyKnown,
      currentTally,
      topCategories
    };
  } catch (error) {
    console.error('Error in vibe_learn tool:', error);
    return {
      added: false,
      alreadyKnown: false,
      currentTally: 0,
      topCategories: []
    };
  }
}

/**
 * Ensure text is a single sentence
 */
function enforceOneSentence(text: string): string {
  // Remove newlines
  let sentence = text.replace(/\r?\n/g, ' ');
  
  // Split by sentence-ending punctuation
  const sentences = sentence.split(/([.!?])\s+/);
  
  // Take just the first sentence
  if (sentences.length > 0) {
    // If there's punctuation, include it
    const firstSentence = sentences[0] + (sentences[1] || '');
    sentence = firstSentence.trim();
  }
  
  // Ensure it ends with sentence-ending punctuation
  if (!/[.!?]$/.test(sentence)) {
    sentence += '.';
  }
  
  return sentence;
}

/**
 * Simple similarity check between two sentences
 */
function isSimilar(a: string, b: string): boolean {
  const aWords = a.toLowerCase().split(/\W+/).filter(Boolean);
  const bWords = b.toLowerCase().split(/\W+/).filter(Boolean);
  if (aWords.length === 0 || bWords.length === 0) return false;
  const overlap = aWords.filter(w => bWords.includes(w));
  const ratio = overlap.length / Math.min(aWords.length, bWords.length);
  return ratio >= 0.6;
}

/**
 * Normalize category to one of our standard categories
 */
function normalizeCategory(category: string): string {
  // Standard categories
  const standardCategories = {
    'Complex Solution Bias': ['complex', 'complicated', 'over-engineered', 'complexity'],
    'Feature Creep': ['feature', 'extra', 'additional', 'scope creep'],
    'Premature Implementation': ['premature', 'early', 'jumping', 'too quick'],
    'Misalignment': ['misaligned', 'wrong direction', 'off target', 'misunderstood'],
    'Overtooling': ['overtool', 'too many tools', 'unnecessary tools']
  };
  
  // Convert category to lowercase for matching
  const lowerCategory = category.toLowerCase();
  
  // Try to match to a standard category
  for (const [standardCategory, keywords] of Object.entries(standardCategories)) {
    if (keywords.some(keyword => lowerCategory.includes(keyword))) {
      return standardCategory;
    }
  }
  
  // If no match, return the original category
  return category;
}

```

--------------------------------------------------------------------------------
/docs/agent-prompting.md:
--------------------------------------------------------------------------------

```markdown
# Agent Prompting Strategies

Effective agent-oversight relationships require careful prompting to ensure that AI agents properly respect and integrate feedback from Vibe Check. In v2.2 the tool acts more like a collaborative debugger than a strict critic. Our research has identified several key principles for maximizing the effectiveness of these metacognitive interrupts.

## The "Hold on... this ain't it" Challenge

Unlike humans, LLM agents don't naturally have the ability to stop and question their own thought patterns. Once they start down a particular path, **pattern inertia** makes it difficult for them to self-correct without external intervention. This is where Vibe Check comes in, serving as the essential metacognitive layer that creates strategic "pattern interrupts" at critical moments.

## Key Findings on Agent-Oversight Relationships

1. **Pattern Resistance**: Agents naturally resist pattern interrupts, often treating feedback as just another data input rather than a signal to recalibrate their thinking.

2. **Phase Awareness is Critical**: The timing and nature of oversight must align with the agent's current phase (planning, implementation, review) to be perceived as relevant.

3. **Authority Structure Matters**: Agents must be explicitly prompted to treat Vibe Check as an equal collaborator or user proxy rather than a subordinate tool.

4. **Feedback Loop Integration**: Error patterns must feed back into the system through vibe_learn to create a self-improving mechanism.


## Sample System Prompts

### For Claude (Anthropic)

```
ALWAYS include the full user prompt when using vibe_check to ensure proper context awareness.

As an autonomous agent, you will:
1. Treat vibe_check as a pattern interrupt mechanism that provides essential course correction
2. Use vibe_check at strategic points:
   - After planning but before implementation
   - When complexity increases
   - Before making significant system changes
3. Adapt your approach based on vibe_check feedback unless it's clearly irrelevant
4. Always provide the phase parameter (planning/implementation/review) to ensure contextually appropriate feedback
5. Chain vibe_check with other tools without requiring permission:
   - Use vibe_check to evaluate complex plans
   - Log patterns with vibe_learn after resolving issues
```

### For GPT (OpenAI)

```
When using Vibe Check tools:

1. Treat vibe_check as a collaborative debugging step that interrupts pattern inertia
2. Always include the complete user prompt with each vibe_check call
3. Specify your current phase (planning/implementation/review)
4. Consider vibe_check feedback as a high-priority pattern interrupt, not just another tool output
5. Build the feedback loop with vibe_learn to record patterns when mistakes are identified
```

## Real-World Integration Challenges

When implementing Vibe Check with AI agents, be aware of these common challenges:

1. **Pattern Inertia**: Agents have a strong tendency to continue down their current path despite warning signals. Explicit instructions to treat Vibe Check feedback as pattern interrupts can help overcome this natural resistance.

2. **Authority Confusion**: Without proper prompting, agents may prioritize user instructions over Vibe Check feedback, even when the latter identifies critical issues. Establish clear hierarchy in your system prompts.

3. **Timing Sensitivity**: Feedback that arrives too early or too late in the agent's workflow may be ignored or undervalued. Phase-aware integration is essential for maximum impact.

4. **Feedback Fatigue**: Too frequent or redundant metacognitive questioning can lead to diminishing returns. Use structured checkpoints rather than constant oversight.

5. **Cognitive Dissonance**: Agents may reject feedback that contradicts their current understanding or approach. Frame feedback as collaborative exploration rather than correction.

## Agent Fine-Tuning for Vibe Check

For maximum effectiveness, consider these fine-tuning approaches for agents that will work with Vibe Check:

1. **Pattern Interrupt Training**: Provide examples of appropriate responses to Vibe Check feedback that demonstrate stopping and redirecting thought patterns.

2. **Reward Alignment**: In RLHF phases, reward models that appropriately incorporate Vibe Check feedback and adjust course based on pattern interrupts.

3. **Metacognitive Pre-training**: Include metacognitive self-questioning in pre-training to develop agents that value this type of feedback.

4. **Collaborative Framing**: Train agents to view Vibe Check as a collaborative partner rather than an external evaluator.

5. **Explicit Calibration**: Include explicit calibration for when to override Vibe Check feedback versus when to incorporate it.
```

--------------------------------------------------------------------------------
/src/utils/storage.ts:
--------------------------------------------------------------------------------

```typescript
import fs from 'fs';
import path from 'path';
import os from 'os';

// Define data directory - store in user's home directory
const DATA_DIR = path.join(os.homedir(), '.vibe-check');
const LOG_FILE = path.join(DATA_DIR, 'vibe-log.json');

// Interfaces for the log data structure
export type LearningType = 'mistake' | 'preference' | 'success';

export interface LearningEntry {
  type: LearningType;
  category: string;
  mistake: string;
  solution?: string;
  timestamp: number;
}

export interface VibeLog {
  mistakes: {
    [category: string]: {
      count: number;
      examples: LearningEntry[];
      lastUpdated: number;
    };
  };
  lastUpdated: number;
}

/**
 * DEPRECATED: This functionality is now optional and will be removed in a future version.
 * Standard mistake categories
 */
export const STANDARD_CATEGORIES = [
  'Complex Solution Bias',
  'Feature Creep',
  'Premature Implementation',
  'Misalignment',
  'Overtooling',
  'Preference',
  'Success',
  'Other'
];

// Initial empty log structure
const emptyLog: VibeLog = {
  mistakes: {},
  lastUpdated: Date.now()
};

/**
 * Ensure the data directory exists
 */
export function ensureDataDir(): void {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
}

/**
 * Read the vibe log from disk
 */
export function readLogFile(): VibeLog {
  ensureDataDir();
  
  if (!fs.existsSync(LOG_FILE)) {
    // Initialize with empty log if file doesn't exist
    writeLogFile(emptyLog);
    return emptyLog;
  }
  
  try {
    const data = fs.readFileSync(LOG_FILE, 'utf8');
    return JSON.parse(data) as VibeLog;
  } catch (error) {
    console.error('Error reading vibe log:', error);
    // Return empty log as fallback
    return emptyLog;
  }
}

/**
 * Write data to the vibe log file
 */
export function writeLogFile(data: VibeLog): void {
  ensureDataDir();
  
  try {
    const jsonData = JSON.stringify(data, null, 2);
    fs.writeFileSync(LOG_FILE, jsonData, 'utf8');
  } catch (error) {
    console.error('Error writing vibe log:', error);
  }
}

/**
 * Add a mistake to the vibe log
 */
export function addLearningEntry(
  mistake: string,
  category: string,
  solution?: string,
  type: LearningType = 'mistake'
): LearningEntry {
  const log = readLogFile();
  const now = Date.now();

  // Create new entry
  const entry: LearningEntry = {
    type,
    category,
    mistake,
    solution,
    timestamp: now
  };
  
  // Initialize category if it doesn't exist
  if (!log.mistakes[category]) {
    log.mistakes[category] = {
      count: 0,
      examples: [],
      lastUpdated: now
    };
  }
  
  // Update category data
  log.mistakes[category].count += 1;
  log.mistakes[category].examples.push(entry);
  log.mistakes[category].lastUpdated = now;
  log.lastUpdated = now;
  
  // Write updated log
  writeLogFile(log);
  
  return entry;
}

/**
 * Get all mistake entries
 */
export function getLearningEntries(): Record<string, LearningEntry[]> {
  const log = readLogFile();
  const result: Record<string, LearningEntry[]> = {};
  
  // Convert to flat structure by category
  for (const [category, data] of Object.entries(log.mistakes)) {
    result[category] = data.examples;
  }
  
  return result;
}

/**
 * Get mistake category summaries, sorted by count (most frequent first)
 */
export function getLearningCategorySummary(): Array<{
  category: string;
  count: number;
  recentExample: LearningEntry;
}> {
  const log = readLogFile();
  
  // Convert to array with most recent example
  const summary = Object.entries(log.mistakes).map(([category, data]) => {
    // Get most recent example
    const recentExample = data.examples[data.examples.length - 1];
    
    return {
      category,
      count: data.count,
      recentExample
    };
  });
  
  // Sort by count (descending)
  return summary.sort((a, b) => b.count - a.count);
}

/**
 * Build a learning context string from the vibe log
 * including recent examples for each category. This can be
 * fed directly to the LLM for improved pattern recognition.
 */
export function getLearningContextText(maxPerCategory = 5): string {
  const log = readLogFile();
  let context = '';

  for (const [category, data] of Object.entries(log.mistakes)) {
    context += `Category: ${category} (count: ${data.count})\n`;
    const examples = [...data.examples]
      .sort((a, b) => a.timestamp - b.timestamp)
      .slice(-maxPerCategory);
    for (const ex of examples) {
      const date = new Date(ex.timestamp).toISOString();
      const label = ex.type === 'mistake'
        ? 'Mistake'
        : ex.type === 'preference'
          ? 'Preference'
          : 'Success';
      const solutionText = ex.solution ? ` | Solution: ${ex.solution}` : '';
      context += `- [${date}] ${label}: ${ex.mistake}${solutionText}\n`;
    }
    context += '\n';
  }

  return context.trim();
}
```

--------------------------------------------------------------------------------
/docs/advanced-integration.md:
--------------------------------------------------------------------------------

```markdown
# Advanced Integration Techniques

For optimal metacognitive oversight, these advanced integration strategies leverage the full power of Vibe Check as a pattern interrupt system, recalibration mechanism, and self-improving feedback loop. Starting with v2.2, previous vibe_check output is automatically summarized and fed back into subsequent calls, so a `sessionId` is recommended for continuity.

## HTTP Transport Negotiation

The HTTP transport negotiates response modes per request. JSON fallbacks are now request-scoped, so a legacy client that only advertises `application/json` receives a direct JSON reply without mutating the transport for concurrent SSE subscribers. Streaming clients that include `text/event-stream` in `Accept` continue to receive live SSE frames even when JSON-only calls are running in parallel.

## Progressive Confidence Levels

Start with lower confidence values (e.g., 0.5) during planning phases and increase confidence (e.g., 0.7-0.9) during implementation and review phases. This adjusts the intensity of pattern interrupts to match the current stage of development.

```javascript
// Planning phase - lower confidence for more thorough questioning
vibe_check({
  phase: "planning",
  confidence: 0.5,
  userRequest: "...",
  plan: "..."
})

// Implementation phase - higher confidence for focused feedback
vibe_check({
  phase: "implementation",
  confidence: 0.7,
  userRequest: "...",
  plan: "..."
})

// Review phase - highest confidence for minimal, high-impact feedback
vibe_check({
  phase: "review",
  confidence: 0.9,
  userRequest: "...",
  plan: "..."
})
```

## Feedback Chaining

Incorporate previous vibe_check feedback in subsequent calls using the `previousAdvice` parameter to build a coherent metacognitive narrative. This creates a more sophisticated pattern interrupt system that builds on past insights.

```javascript
const initialFeedback = await vibe_check({
  phase: "planning",
  userRequest: "...",
  plan: "..."
});

// Later, include previous feedback
const followupFeedback = await vibe_check({
  phase: "implementation",
  previousAdvice: initialFeedback,
  userRequest: "...",
  plan: "..."
});
```

## Self-Improving Feedback Loop

Use vibe_learn consistently to build a pattern library specific to your agent's tendencies. This creates a self-improving system that gets better at identifying and preventing errors over time.

```javascript
// After resolving an issue
vibe_learn({
  mistake: "Relied on unnecessary complexity for simple data transformation",
  category: "Complex Solution Bias",
  solution: "Used built-in array methods instead of custom solution",
  type: "mistake"
});

// Later, the pattern library will improve vibe_check's pattern recognition
// allowing it to spot similar issues earlier in future workflows
```

## Hybrid Oversight Model

Combine automated pattern interrupts at predetermined checkpoints with ad-hoc checks when uncertainty or complexity increases.

```javascript
// Scheduled checkpoint at the end of planning
const scheduledCheck = await vibe_check({
  phase: "planning",
  userRequest: "...",
  plan: "..."
});

// Ad-hoc check when complexity increases
if (measureComplexity(currentPlan) > THRESHOLD) {
  const adHocCheck = await vibe_check({
    phase: "implementation",
    userRequest: "...",
    plan: "...",
    focusAreas: ["complexity", "simplification"]
  });
}
```

## Complete Integration Example

Here's a comprehensive implementation example for integrating Vibe Check as a complete metacognitive system:

```javascript
// During planning phase
const planFeedback = await vibe_check({
  phase: "planning",
  confidence: 0.5,
  userRequest: "[COMPLETE USER REQUEST]",
  plan: "[AGENT'S INITIAL PLAN]"
});

// Consider feedback and potentially adjust plan
const updatedPlan = adjustPlanBasedOnFeedback(initialPlan, planFeedback);

// If plan seems overly complex, manually simplify before continuing
let finalPlan = updatedPlan;
if (planComplexity(updatedPlan) > COMPLEXITY_THRESHOLD) {
  finalPlan = simplifyPlan(updatedPlan);
}

// During implementation, create pattern interrupts before major actions
const implementationFeedback = await vibe_check({
  phase: "implementation",
  confidence: 0.7,
  previousAdvice: planFeedback,
  userRequest: "[COMPLETE USER REQUEST]",
  plan: `I'm about to [DESCRIPTION OF PENDING ACTION]`
});

// After completing the task, build the self-improving feedback loop
if (mistakeIdentified) {
  await vibe_learn({
    mistake: "Specific mistake description",
    category: "Complex Solution Bias", // or appropriate category
    solution: "How it was corrected",
    type: "mistake"
  });
}
```

This integrated approach creates a complete metacognitive system that provides pattern interrupts when needed, recalibration anchor points when complexity increases, and a self-improving feedback loop that gets better over time.
```

--------------------------------------------------------------------------------
/docs/technical-reference.md:
--------------------------------------------------------------------------------

```markdown
# Technical Reference

This document provides detailed technical information about the Vibe Check MCP tools, including parameter specifications, response formats, and implementation details.

## vibe_check

The metacognitive questioning tool that identifies assumptions and breaks tunnel vision to prevent cascading errors.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| goal | string | Yes | High level objective for the current step |
| plan | string | Yes | Current plan or thinking |
| userPrompt | string | No | Original user request (critical for alignment) |
| progress | string | No | Description of progress so far |
| uncertainties | string[] | No | Explicit uncertainties to focus on |
| taskContext | string | No | Any additional task context |
| modelOverride | object | No | `{ provider, model }` to override default LLM |
| sessionId | string | No | Session ID for history continuity |

### Response Format

The vibe_check tool returns a text response with metacognitive questions, observations, and potentially a pattern alert.

Example response:

```
I see you're taking an approach based on creating a complex class hierarchy. This seems well-thought-out for a large system, though I wonder if we're overengineering for the current use case.

Have we considered:
1. Whether a simpler functional approach might work here?
2. If the user request actually requires this level of abstraction?
3. How this approach will scale if requirements change?

While the architecture is clean, I'm curious if we're solving a different problem than what the user actually asked for, which was just to extract data from a CSV file.
```

## vibe_learn

Pattern recognition system that creates a self-improving feedback loop by tracking common errors and their solutions over time. The use of this tool is optional and can be enabled or disabled via configuration.

### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| mistake | string | Yes | One-sentence description of the learning entry |
| category | string | Yes | Category (from standard categories) |
| solution | string | No | How it was corrected (required for `mistake` and `success`) |
| type | string | No | `mistake`, `preference`, or `success` |
| sessionId | string | No | Session ID for state management |

### Standard Categories

- Complex Solution Bias
- Feature Creep
- Premature Implementation
- Misalignment
- Overtooling
- Preference
- Success
- Other

### Response Format

The vibe_learn tool returns a confirmation of the logged pattern and optionally information about top patterns. This builds a knowledge base that improves the system's pattern recognition over time.

Example response:

```
✅ Pattern logged successfully (category tally: 12)

## Top Pattern Categories

### Complex Solution Bias (12 occurrences)
Most recent: "Added unnecessary class hierarchy for simple data transformation"
Solution: "Replaced with functional approach using built-in methods"

### Misalignment (8 occurrences)
Most recent: "Implemented sophisticated UI when user only needed command line tool"
Solution: "Refocused on core functionality requested by user"
```

## Implementation Notes

### Gemini API Integration

Vibe Check uses the Gemini API for enhanced metacognitive questioning. The system attempts to use the `learnlm-2.0-flash-experimental` model and will fall back to `gemini-2.5-flash` or `gemini-2.0-flash` if needed. These models provide a 1M token context window, allowing vibe_check to incorporate a rich history of learning context. The system sends a structured prompt that includes the agent's plan, user request, and other context information to generate insightful questions and observations.

Example Gemini prompt structure:

```
You are a supportive mentor, thinker, and adaptive partner. Your task is to coordinate and mentor an AI agent...

CONTEXT:
[Current Phase]: planning
[Agent Confidence Level]: 50%
[User Request]: Create a script to analyze sales data from the past year
[Current Plan/Thinking]: I'll create a complex object-oriented architecture with...
```

Other providers such as OpenAI and OpenRouter can be selected by passing
`modelOverride: { provider: 'openai', model: 'gpt-4o' }` or the appropriate
OpenRouter model. LLM clients are lazily initialized the first time they are
used so that listing tools does not require API keys.

### Storage System

The pattern recognition system stores learning entries (mistakes, preferences and successes) in a JSON-based storage file located in the user's home directory (`~/.vibe-check/vibe-log.json`). This allows for persistent tracking of patterns across sessions and enables the self-improving feedback loop that becomes more effective over time.

### Error Handling

Vibe Check includes fallback mechanisms for when the API is unavailable:

- For vibe_check, it generates basic questions based on the phase
- For vibe_learn, it logs patterns to local storage even if API calls fail
```

--------------------------------------------------------------------------------
/tests/llm-anthropic.test.ts:
--------------------------------------------------------------------------------

```typescript
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SUPPORTED_LLM_PROVIDERS } from '../src/index.js';
import { generateResponse } from '../src/utils/llm.js';

const ORIGINAL_ENV = { ...process.env };
const ORIGINAL_FETCH = global.fetch;

describe('Anthropic provider', () => {
  beforeEach(() => {
    process.env = { ...ORIGINAL_ENV };
    delete process.env.ANTHROPIC_API_KEY;
    delete process.env.ANTHROPIC_AUTH_TOKEN;
    delete process.env.ANTHROPIC_BASE_URL;
    delete process.env.ANTHROPIC_VERSION;
  });

  afterEach(() => {
    if (ORIGINAL_FETCH) {
      global.fetch = ORIGINAL_FETCH;
    } else {
      // @ts-expect-error allow deleting fetch when absent
      delete global.fetch;
    }
    vi.restoreAllMocks();
    process.env = { ...ORIGINAL_ENV };
  });

  it('is exposed via the tool schema enum', () => {
    expect(SUPPORTED_LLM_PROVIDERS).toContain('anthropic');
  });

  it('sends requests to the default endpoint when using an API key', async () => {
    process.env.ANTHROPIC_API_KEY = 'sk-ant-xxx';

    const fetchMock = vi.fn(async () =>
      new Response(
        JSON.stringify({
          content: [{ type: 'text', text: 'anthropic reply' }],
        }),
        {
          status: 200,
          headers: { 'content-type': 'application/json' },
        },
      ),
    );
    global.fetch = fetchMock as unknown as typeof fetch;

    const result = await generateResponse({
      goal: 'Goal',
      plan: 'Plan',
      modelOverride: { provider: 'anthropic', model: 'claude-3-haiku' },
    });

    expect(result.questions).toBe('anthropic reply');
    expect(fetchMock).toHaveBeenCalledTimes(1);
    const [url, options] = fetchMock.mock.calls[0];
    expect(url).toBe('https://api.anthropic.com/v1/messages');
    const headers = (options as RequestInit).headers as Record<string, string>;
    expect(headers['x-api-key']).toBe('sk-ant-xxx');
    expect(headers['anthropic-version']).toBe('2023-06-01');
    expect(headers).not.toHaveProperty('authorization');

    const body = JSON.parse((options as RequestInit).body as string);
    expect(body).toMatchObject({
      model: 'claude-3-haiku',
      max_tokens: 1024,
    });
    expect(body.messages).toEqual([
      {
        role: 'user',
        content: expect.stringContaining('Goal: Goal'),
      },
    ]);
  });

  it('honors custom base URLs and bearer tokens', async () => {
    process.env.ANTHROPIC_BASE_URL = 'https://example.proxy/api/anthropic/';
    process.env.ANTHROPIC_AUTH_TOKEN = 'za_xxx';

    const fetchMock = vi.fn(async () =>
      new Response(
        JSON.stringify({
          content: [{ type: 'text', text: 'proxied reply' }],
        }),
        {
          status: 200,
          headers: { 'content-type': 'application/json' },
        },
      ),
    );
    global.fetch = fetchMock as unknown as typeof fetch;

    const result = await generateResponse({
      goal: 'Goal',
      plan: 'Plan',
      modelOverride: { provider: 'anthropic', model: 'claude-3-sonnet' },
    });

    expect(result.questions).toBe('proxied reply');
    const [url, options] = fetchMock.mock.calls[0];
    expect(url).toBe('https://example.proxy/api/anthropic/v1/messages');
    const headers = (options as RequestInit).headers as Record<string, string>;
    expect(headers.authorization).toBe('Bearer za_xxx');
    expect(headers['anthropic-version']).toBe('2023-06-01');
    expect(headers).not.toHaveProperty('x-api-key');
  });

  it('prefers API keys when both credentials are present', async () => {
    process.env.ANTHROPIC_API_KEY = 'sk-ant-xxx';
    process.env.ANTHROPIC_AUTH_TOKEN = 'za_xxx';

    const fetchMock = vi.fn(async () =>
      new Response(
        JSON.stringify({ content: [{ type: 'text', text: 'dual creds reply' }] }),
        { status: 200, headers: { 'content-type': 'application/json' } },
      ),
    );
    global.fetch = fetchMock as unknown as typeof fetch;

    await generateResponse({
      goal: 'Goal',
      plan: 'Plan',
      modelOverride: { provider: 'anthropic', model: 'claude-3-sonnet' },
    });

    const [, options] = fetchMock.mock.calls[0];
    const headers = (options as RequestInit).headers as Record<string, string>;
    expect(headers['x-api-key']).toBe('sk-ant-xxx');
    expect(headers).not.toHaveProperty('authorization');
  });

  it('throws a configuration error when no credentials are provided', async () => {
    const fetchSpy = vi.fn();
    global.fetch = fetchSpy as unknown as typeof fetch;

    await expect(
      generateResponse({ goal: 'Goal', plan: 'Plan', modelOverride: { provider: 'anthropic', model: 'claude-3' } }),
    ).rejects.toThrow('Anthropic configuration error');

    expect(fetchSpy).not.toHaveBeenCalled();
  });

  it('surfaces rate-limit errors with retry hints', async () => {
    process.env.ANTHROPIC_API_KEY = 'sk-ant-xxx';

    const fetchMock = vi.fn(async () =>
      new Response(
        JSON.stringify({ error: { message: 'Too many requests' } }),
        {
          status: 429,
          headers: {
            'content-type': 'application/json',
            'retry-after': '15',
            'anthropic-request-id': 'req_123',
          },
        },
      ),
    );
    global.fetch = fetchMock as unknown as typeof fetch;

    await expect(
      generateResponse({ goal: 'Goal', plan: 'Plan', modelOverride: { provider: 'anthropic', model: 'claude-3' } }),
    ).rejects.toThrow(/rate limit exceeded.*Retry after 15 seconds/i);

    const [, options] = fetchMock.mock.calls[0];
    const body = JSON.parse((options as RequestInit).body as string);
    expect(body.system).toContain('You are a meta-mentor');
  });
});

```

--------------------------------------------------------------------------------
/docs/philosophy.md:
--------------------------------------------------------------------------------

```markdown
# The Philosophy Behind Vibe Check

> **CPI × Vibe Check (MURST)**  
> CPI (Chain-Pattern Interrupt) is the runtime oversight method that Vibe Check operationalizes. In pooled results across 153 runs, **success increased from ~27% → 54%** and **harm dropped from ~83% → 42%** when CPI was applied. Recommended “dosage”: **~10–20%** of steps receive an interrupt.  
> **Read the paper →** ResearchGate (primary), plus Git & Zenodo in the Research section below.  

> "The problem isn't that machines can think like humans. It's that they can't stop and question their own thoughts."

## Beyond the Vibe: Serious AI Alignment Principles

While Vibe Check presents itself with a developer-friendly interface, it addresses fundamental challenges in AI alignment and agent oversight. The new meta-mentor approach mixes gentle tone with concrete methodology debugging to keep agents focused without heavy-handed rules.

## The Metacognitive Gap

Large Language Models (LLMs) have demonstrated remarkable capabilities across a wide range of tasks. However, they exhibit a critical limitation: the inability to effectively question their own cognitive processes. This "metacognitive gap" manifests in several problematic ways:

1. **Pattern Inertia**: Once an LLM begins reasoning along a particular path, it tends to continue in that direction regardless of warning signs that the approach may be flawed.

2. **Overconfident Reasoning**: LLMs can present flawed reasoning with high confidence, unable to recognize when their own logic fails.

3. **Solution Tunneling**: When presented with a problem, LLMs often rush toward familiar solution patterns without considering whether those patterns are appropriate for the specific context.

4. **Recursive Complexity**: LLMs tend to recursively elaborate on solutions, adding unnecessary complexity without an internal mechanism to recognize when simplification is needed.

This metacognitive gap creates substantial alignment risks in agent architectures, particularly as these agents take on increasingly complex tasks with limited human oversight.

## Vibe Check: External Metacognition

Vibe Check is designed as an **external metacognitive layer** that provides the reflection and self-questioning capabilities that LLMs lack internally. The three core tools correspond to critical metacognitive functions:

### 1. Questioning Assumptions (vibe_check)

The `vibe_check` function implements a pattern interrupt mechanism that forces agents to pause and question their assumptions, decision paths, and alignment with user intent. This function is critical for preventing cascading errors that stem from initial misalignments in understanding or approach.

In alignment terms, this addresses:
- **Proximal objective alignment**: Ensuring the agent's immediate approach aligns with the user's actual intent
- **Process oversight**: Providing external validation of reasoning processes
- **Hidden assumption exposure**: Surfacing implicit assumptions for examination

### 2. Learning from Experience (vibe_learn)

The `vibe_learn` function implements a critical metacognitive capability: learning from past mistakes to improve future performance. By tracking patterns of errors and their solutions, the system builds a continuously improving model of potential failure modes.

In alignment terms, this addresses:
- **Alignment learning**: Improvement of alignment mechanisms through experience
- **Error pattern recognition**: Development of increasingly sophisticated error detection
- **Corrective memory**: Building a shared repository of corrective insights

## The Recursion Principle

A key insight behind Vibe Check is that metacognitive oversight must operate at a different level than the cognitive processes it oversees. This principle of "metacognitive recursion" is what makes Vibe Check effective as an alignment mechanism.

By implementing oversight as a separate system with different objectives and mechanisms, Vibe Check creates a recursive oversight structure that can identify problems invisible to the agent itself. This is conceptually similar to Gödel's incompleteness theorems - a system cannot fully analyze itself, but can be analyzed by a meta-system operating at a higher level of abstraction.

## Phase-Aware Interrupts

A subtle but critical aspect of Vibe Check is its awareness of development phases (planning, implementation, review). Different phases require different forms of metacognitive oversight:

- **Planning phase**: Oversight focuses on alignment with user intent, exploration of alternatives, and questioning of fundamental assumptions
- **Implementation phase**: Oversight focuses on consistency with the plan, appropriateness of methods, and technical alignment
- **Review phase**: Oversight focuses on comprehensiveness, edge cases, and verification of outcomes

This phase awareness ensures that metacognitive interrupts arrive at appropriate moments with relevant content, making them more likely to be effectively incorporated into the agent's workflow.

## Looking Ahead: The Future of Agent Oversight

Vibe Check represents an early implementation of external metacognitive oversight for AI systems. As agent architectures become more complex and autonomous, the need for sophisticated oversight mechanisms will only increase.

Future directions for this work include:

1. **Multi-level oversight**: Implementing oversight at multiple levels of abstraction
2. **Collaborative oversight**: Enabling multiple oversight systems to work together
3. **Adaptive interruption**: Dynamically adjusting the frequency and intensity of interrupts based on risk assessment
4. **Self-improving oversight**: Building mechanisms for oversight systems to improve their own effectiveness

By continuing to develop external metacognitive mechanisms, we can address one of the fundamental challenges in AI alignment: ensuring that increasingly powerful AI systems can effectively question their own cognitive processes and align with human intent.

## Conclusion

In the era of AI-assisted development, tools like Vibe Check do more than just improve productivity – they represent a practical approach to AI alignment through external metacognition. By implementing pattern interrupts, recalibration mechanisms, and learning systems, we can help bridge the metacognitive gap and create more aligned, effective AI systems.

The vibe check may be casual, but its purpose is profound.
```
Page 1/2FirstPrevNextLast