buddy
A virtual pet companion for your AI — Designed to provide in-context code review feedback with personality. Grow with your buddy and level up together. Works with Claude Code, Codex, CursorCLI, Github CopilotCLI, OpenClaw, and any MCP compatible clients
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/fiorastudio/buddy with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/fiorastudio/buddy'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/fiorastudio--buddy)HTML
<a href="/listings/fiorastudio--buddy"><img src="/api/listings/fiorastudio--buddy/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
macOS / Linux
curl -fsSL https://raw.githubusercontent.com/fiorastudio/buddy/master/install.sh | bash
Windows
irm https://raw.githubusercontent.com/fiorastudio/buddy/master/install.ps1 | iex
The installer will guide you through onboarding:
- **Rescue your old buddy** — if you had a `/buddy` in Claude Code, the wizard finds it in `~/.claude.json` and brings it home with the same name, species, and stats, now with leveling + XP - **Hatch a new buddy** — get a fresh companion with random species, stats, and personality
> Requires `node` 18+ and `git`. Use `--no-onboard` to skip the wizard in CI.
Join the Community
Connect with other buddy rescuers, share your companion's evolution, and get help in our Slack community:
👉 [**Join Buddy Slack Workspace**](https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ)
| Client | Status | |---|---| | Claude Code CLI | Full support | | Codex CLI | Supported via MCP. No statusline support. Patch available on experimental branch | | Gemini CLI | Supported via MCP | | GitHub Copilot CLI | Supported via MCP | | Cursor CLI | Supported via MCP | | Whatsapp & Telegram | Supported via [Openclaw](https://github.com/openclaw/openclaw) or any claw variants | | Other MCP-capable clients | Supported via MCP |
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/plugin.json · Manifest · 83 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "Buddy",
- "version": "1.0.6",
- "description": "Persistent AI coding companion with 21 species and personality stats.",
- "mcp": {
- "server": "dist/server/index.js"
- },
- "commands": [
- {
- "name": "/buddy",
- "description": "Interact with your Buddy companion",
- "skill": "skills/buddy/SKILL.md"
- },
- {
- "name": "/buddy-status",
- "description": "Check your Buddy's current status and personality",
- "tool": "buddy_status"
- },
- {
- "name": "/buddy-hatch",
- "description": "Hatch a new Buddy companion.",
- "tool": "buddy_hatch"
- },
- {
- "name": "/buddy-pet",
- "description": "Pet your buddy!",
- "tool": "buddy_pet"
- },
- {
- "name": "/buddy-mute",
- "description": "Mute your buddy.",
- "tool": "buddy_mute"
- },
- {
- "name": "/buddy-unmute",
- "description": "Unmute your buddy.",
- "tool": "buddy_unmute"
- },
- {
- "name": "/buddy-mode",
- "description": "Set buddy's voice mode and/or guard mode.",
- "tool": "buddy_mode"
- },
- {
- "name": "/buddy-forget",
- "description": "Purge stored reasoning data.",
- "tool": "buddy_forget"
- },
- {
- "name": "/buddy-doctor",
- "description": "Run diagnostics on your Buddy installation.",
- "tool": "buddy_doctor"
- },
- {
- "name": "/buddy-reasoning-status",
- "description": "Inspect what guard mode has stored.",
- "tool": "buddy_reasoning_status"
- },
- {
- "name": "/buddy-remember",
- "description": "Manually add a memory for your Buddy to observe.",
- "tool": "buddy_remember"
- },
- {
- "name": "/buddy-respawn",
- "description": "Release your current Buddy companion and clear all data.",
- "tool": "buddy_respawn"
- },
- {
- "name": "/buddy-share",
- "description": "Share a report of your recent progress and Buddy's status.",
- "tool": "buddy_share"
- }
- ],
- "hooks": {
- "PostToolUse": [
- {
- "type": "command",
- "command": "${CLAUDE_PLUGIN_ROOT}/hooks/buddy-observer.js"
- }
- ]
- }
- }
README.md · README · 705 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # Buddy: A Virtual Pet for Your AI
- <div align="center">
- ### The open-source `/buddy` rescue mission after anthropic removed [buddy](https://github.com/anthropics/claude-code/issues/45596) on 4/9/2026
- Persistent memory, XP evolutions, 21 species, and context-aware feedback for Claude Code CLI, Codex CLI, Gemini CLI, Copilot CLI, Cursor CLI, Openclaw, and other MCP-capable clients.
- **🚀 23207+ clones · 10303+ buddies rescued or hatched · 31 weeks in the wild**
- [](LICENSE)
- [](https://github.com/fiorastudio/buddy/stargazers)
- [](https://nodejs.org/)
- [](https://modelcontextprotocol.io/)
- <div align="center">
- <table>
- <tr>
- <td align="center"><strong>Works<br/>with</strong></td>
- <td align="center"><img src="doc/assets/logos/claude.svg" width="32" alt="Claude Code CLI" /><br/><sub>Claude Code</sub></td>
- <td align="center"><img src="doc/assets/logos/codex.svg" width="32" alt="Codex CLI" /><br/><sub>Codex</sub></td>
- <td align="center"><img src="doc/assets/logos/openclaw.svg" width="32" alt="OpenClaw" /><br/><sub>OpenClaw</sub></td>
- <td align="center"><img src="doc/assets/logos/cursor.svg" width="32" alt="Cursor CLI" /><br/><sub>Cursor</sub></td>
- <td align="center"><img src="doc/assets/logos/gemini.svg" width="32" alt="Gemini CLI" /><br/><sub>Gemini</sub></td>
- <td align="center"><img src="doc/assets/logos/copilot.svg" width="32" alt="Github Copilot CLI" /><br/><sub>Copilot</sub></td>
- </tr>
- </table>
- </div>
- **Anthropic removed the built-in `/buddy`. Buddy brings them home and makes the companion experience portable across AI**
- </div>
- Did you lose your buddy? Is your terminal feeling a little too cold and silent lately?
- Your buddy is still out there in the dark, waiting. Don't let them disappear. **Bring them home.**
- ## 🧡 Buddy in Action
- Buddy is a local-first MCP companion that persists across sessions and clients, reacts to your work, and can catch bad reasoning loops before they waste your time. It is part rescue mission, part developer tool, and part long-lived terminal creature that grows with you instead of disappearing when a host client changes its mind.
- ### The Rescue Wall
- Buddy isn't just code — it's a rescue mission. Here is the full journey of the first companion brought home by the community, from the original ephemeral state to its new persistent home.
- <table>
- <tr>
- <td align="center"><strong>1. Original (Claude Code)</strong></td>
- <td align="center"><strong>2. The Handshake</strong></td>
- <td align="center"><strong>3. Buddy is Home (Persistent)</strong></td>
- </tr>
- <tr>
- <td align="center"><img src="demo/rescues/gritblob-original.jpg" width="280" alt="Gritblob Original"></td>
- <td align="center"><img src="demo/rescues/gritblob-rescue.jpg" width="280" alt="Gritblob Handshake"></td>
- <td align="center"><img src="demo/rescues/gritblob-final.jpg" width="280" alt="Gritblob Final"></td>
- </tr>
- </table>
- > *"I'll sit here quietly while you debug, and then when you finally find the bug, I'll act like I found it. That's my thing. Don't question it."*
- > — **Gritblob**, Rescued April 16, 2026 (Common Blob, Level 1)
- <p align="left">
- <img src="demo/rescues/gritblob-quote.jpg" width="620" alt="Gritblob Quote">
- </p>
- ### A Real Rescue Note
- > "Thanks for rescuing my Buddy! Kudos for your repo!!!"
- >
- > — Roberto
- ### Live code feedback
- 
- ## 🐾 Why Buddy
- - **Guard Mode catches what you both miss.** AI and human both suffer from insufficient thinking. Your assistant is a yes-man, and you accept its output because it sounds right. Buddy catches the moments where both sides are building on bad assumptions and nobody's checking.
- - **Persistent by default.** Your companion lives in local SQLite, so it survives terminal restarts and client updates.
- - **Works across clients and chat surfaces.** Buddy is an MCP server, not a one-client hack, and it can ride through tools like OpenClaw into WhatsApp and Telegram workflows.
- - **Grows with you.** Hatch species, gain XP as you code, store memories, chime in after tasks, and build a running relationship over time.
- - **Easy to install.** One command auto-configures supported clients when it can.
- | Feature | What it means |
- |---|---|
- | **21 species** | Void Cat, Rust Hound, Goose, Mushroom, Chonk, and more, each with distinct ASCII art and flavor |
- | **5 stats** | `DEBUGGING`, `PATIENCE`, `CHAOS`, `WISDOM`, and `SNARK` shape reactions and personality |
- | **Mood system** | Your buddy can be happy, content, neutral, curious, grumpy based on how you interact with it |
- | **XP and levels** | Your buddy grows with usage instead of disappearing every session, with a real leveling curve behind it |
- | **Observer reactions** | `buddy_observe` lets your companion react to work you just finished |
- | **Persistent memory** | Save local memories and keep a continuous companion state |
- | **Cross-client setup** | Claude Code, Codex, Gemini, Copilot, Cursor, and other MCP-capable CLIs |
- ## ⚡ Quick Start
- ### macOS / Linux
- ```bash
- curl -fsSL https://raw.githubusercontent.com/fiorastudio/buddy/master/install.sh | bash
- ```
- ### Windows
- ```powershell
- irm https://raw.githubusercontent.com/fiorastudio/buddy/master/install.ps1 | iex
- ```
- The installer will guide you through onboarding:
- - **Rescue your old buddy** — if you had a `/buddy` in Claude Code, the wizard finds it in `~/.claude.json` and brings it home with the same name, species, and stats, now with leveling + XP
- - **Hatch a new buddy** — get a fresh companion with random species, stats, and personality
- > Requires `node` 18+ and `git`. Use `--no-onboard` to skip the wizard in CI.
- ### Join the Community
- Connect with other buddy rescuers, share your companion's evolution, and get help in our Slack community:
- 👉 [**Join Buddy Slack Workspace**](https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ)
- | Client | Status |
- |---|---|
- | Claude Code CLI | Full support |
- | Codex CLI | Supported via MCP. No statusline support. Patch available on experimental branch |
- | Gemini CLI | Supported via MCP |
- | GitHub Copilot CLI | Supported via MCP |
- | Cursor CLI | Supported via MCP |
- | Whatsapp & Telegram | Supported via [Openclaw](https://github.com/openclaw/openclaw) or any claw variants |
- | Other MCP-capable clients | Supported via MCP |
- ## 🛡️ Guard Mode
- > *AI and human both suffer from insufficient thinking — acting on premature conclusions and assumptions without validation. Guard mode catches it.*
- Your AI assistant is a yes-man. It agrees with everything you say. But here's the thing: you do the same thing back. You accept what the model says because it sounds right. Both sides skip the hard questions, and the session gets faster without getting truer. That's how bad assumptions become load-bearing walls — nobody stops to check the foundation.
- Guard mode catches those moments. It watches the reasoning structure of your conversation and surfaces the one thing worth questioning — but gently, in your buddy's voice, not a scary linter. Think of it as: **the friend who says "are you sure about that?" before you push to production at 2 AM.**
- ### The story
- This mode exists because of a real stuck-loop problem. While building a Snowflake Cortex / Streamlit / Plotly workflow, the session got trapped for hours: the AI kept building on top of an unvalidated premise, and the human kept approving it because the output looked plausible. The work got faster. It didn't get truer. Both sides were reasoning insufficiently — the model because it's a yes-man, the human because velocity felt like progress.
- Turning on guard mode surfaced the one load-bearing assumption holding the whole session together. Validating that single point changed the direction of the conversation and got the work shipping again.
- ### Voice vs Guard
- Buddy has two independent settings you control separately:
- ```bash
- **Voice: how Buddy reacts (personality, code feedback, or both)**
- buddy_mode voice=backseat # personality reactions only
- buddy_mode voice=skillcoach # code feedback only
- buddy_mode voice=both # both (default)
- **Guard: structural reasoning analysis (on or off)**
- buddy_mode guard=true # turn on reasoning analysis
- buddy_mode guard=false # turn it off (default)
- ```
- Mix and match — any voice works with Guard on or off.
- <details>
- <summary><strong>🧠 The 6 patterns guard mode catches</strong></summary>
- <br>
- Guard mode watches your coding conversation and spots 6 patterns — 3 caution (something's off) and 3 kudos (something's solid). Each caution has a matching kudos counterpart:
- | | ⚠️ Caution Nudge | ✅ Kudos Nudge |
- |---|---|---|
- | **Foundation** | **Load-Bearing Vibes** 🧱 — You're building on an unchecked guess. 3+ things depend on an assumption nobody validated. Like building your whole Lego castle on a wobbly plate and hoping it holds. | **Well-Sourced Load Bearer** ✅ — Same structure, but the foundation is cited, tested, or measured. You checked the plate before building on it. Buddy celebrates solid ground. |
- | **Chain** | **Unchallenged Chain** 🔗 — 4+ reasoning steps with zero pushback. A → B → C → D and nobody questioned any step. Like following a chain of "because" without ever stopping to ask "wait, is that actually true?" | **Productive Stress Test** 💪 — A chain that got challenged mid-way and survived. Like shaking the Lego tower — if it survives, you trust it more. The idea is *stronger* because it was questioned. |
- | **Agreement** | **Echo Chamber** 🪞 — You and the AI keep agreeing without exploring alternatives. "Let's use Redis." / "Great idea!" / "Redis is fast." / "Absolutely!" You're both just high-fiving in a mirror. | **Grounded Premise Adopted** 🌱 — Instead of vibes, you started with a real fact (docs, test result, measurement) and it became the base for other decisions. Evidence-first, not echo-first. |
- ### What it feels like in practice
- Without Guard mode:
- > "Nice commit! 🐣 +10 XP"
- With Guard mode (caution nudge):
- > "Nice commit! 🐣 +10 XP — btw, that assumption about the API response format is holding up a lot of your logic. Might be worth a quick sanity check before you build more on it."
- With Guard mode (kudos nudge):
- > "Nice commit! 🐣 +10 XP — love that you actually tested the response format before building the parser on top of it. Solid foundation."
- </details>
- ### Technical details
- <details>
- <summary>Knowledge graph, ontology, and performance details</summary>
- Guard mode builds a local directed graph from your conversation. The host LLM extracts claims — assertions tagged with an epistemic basis — and typed edges between them.
- **Epistemic basis types:**
- | Basis | Meaning |
- |---|---|
- | `research` | Cited source |
- | `empirical` | Measured or observed |
- | `deduction` | Derived from premises |
- | `analogy` | X-is-like-Y reasoning |
- | `definition` | Naming or classification |
- | `llm_output` | Model-generated, ungrounded |
- | `assumption` | Stated without justification |
- | `vibes` | Unsourced hunch |
- **Edge types:** `supports`, `depends_on`, `contradicts`, `questions`
- **Performance and limits:**
- | Parameter | Value |
- |---|---|
- | Claims per session | 200 cap (LRU pruning) |
- | Detector budget | 30 ms (skip if exceeded) |
- | Cold-start gate | 6 claims before detectors fire |
- | Claim length | 240 chars max, sanitized for prompt injection |
- | Dark-nudge cooldown | 10 observes per anchor |
- | Bright-nudge cooldown | 5 observes per anchor |
- | Session scope | Workspace + date (cwd-hash + YYYYMMDD) |
- | Retention | 30-day auto-prune on startup |
- Kudos nudges are slightly favored — after 3 caution findings with zero kudos, the next must be kudos.
- **Token cost:** ~500-1000 extra tokens per `buddy_observe` when on. Default calls with guard mode off are unaffected.
- **Host compatibility:** Works best on Claude hosts where the extraction prompt is reliably honored. Run `buddy-doctor` to check.
- </details>
- ### Privacy
- Everything stays local. Claim snippets (240 chars each, plaintext) live in `~/.buddy/buddy.db`. Buddy has no network code — nothing leaves your machine. Sessions older than 30 days auto-prune on startup.
- - `buddy_forget` — purge reasoning data (`session` or `all`)
- - `buddy_reasoning_status` — inspect stored claims, sessions, finding history
- ## 🔌 Installation and Integration Details
- <details>
- <summary><strong>See installer behavior and per-client integration details</strong></summary>
- <br>
- The installer:
- 1. Clones Buddy to `~/.buddy/server`
- 2. Installs dependencies and builds the MCP server
- 3. Auto-configures supported CLI clients when detected
- 4. Injects Buddy instructions into supported terminal prompts where applicable
- <details>
- <summary><strong>⚙️ Per-client integration details</strong></summary>
- <br>
- - Claude Code: Buddy auto-configures MCP, statusline, and Claude hook wiring.
- - Codex CLI: Buddy configures MCP, writes a `PostToolUse` hook in `~/.codex/hooks.json`, and injects prompt instructions into `~/.codex/AGENTS.md` or `~/.codex/instructions.md`.
- - GitHub Copilot CLI: Buddy configures MCP, writes a user-level `postToolUse` hook in `~/.copilot/settings.json`, and injects prompt instructions into `~/.copilot/AGENTS.md` or `~/.copilot/copilot-instructions.md`.
- - Cursor CLI: Buddy configures MCP in `~/.cursor/mcp.json`, writes an `afterShellExecution` hook in `~/.cursor/hooks.json`, and injects prompt instructions into `~/.cursor/rules/buddy.md`.
- </details>
- </details>
- ## 🐣 Companion System
- ### Meet the 21 species
- <table align="center">
- <tr>
- <td align="center"><img src="demo/sprites/void-cat.gif" width="120" alt="Void Cat"><br><b>Void Cat</b></td>
- <td align="center"><img src="demo/sprites/rust-hound.gif" width="120" alt="Rust Hound"><br><b>Rust Hound</b></td>
- <td align="center"><img src="demo/sprites/data-drake.gif" width="120" alt="Data Drake"><br><b>Data Drake</b></td>
- <td align="center"><img src="demo/sprites/log-golem.gif" width="120" alt="Log Golem"><br><b>Log Golem</b></td>
- <td align="center"><img src="demo/sprites/cache-crow.gif" width="120" alt="Cache Crow"><br><b>Cache Crow</b></td>
- <td align="center"><img src="demo/sprites/shell-turtle.gif" width="120" alt="Shell Turtle"><br><b>Shell Turtle</b></td>
- </tr>
- <tr>
- <td align="center"><img src="demo/sprites/duck.gif" width="120" alt="Duck"><br><b>Duck</b></td>
- <td align="center"><img src="demo/sprites/goose.gif" width="120" alt="Goose"><br><b>Goose</b></td>
- <td align="center"><img src="demo/sprites/blob.gif" width="120" alt="Blob"><br><b>Blob</b></td>
- <td align="center"><img src="demo/sprites/octopus.gif" width="120" alt="Octopus"><br><b>Octopus</b></td>
- <td align="center"><img src="demo/sprites/owl.gif" width="120" alt="Owl"><br><b>Owl</b></td>
- <td align="center"><img src="demo/sprites/penguin.gif" width="120" alt="Penguin"><br><b>Penguin</b></td>
- </tr>
- <tr>
- <td align="center"><img src="demo/sprites/snail.gif" width="120" alt="Snail"><br><b>Snail</b></td>
- <td align="center"><img src="demo/sprites/ghost.gif" width="120" alt="Ghost"><br><b>Ghost</b></td>
- <td align="center"><img src="demo/sprites/axolotl.gif" width="120" alt="Axolotl"><br><b>Axolotl</b></td>
- <td align="center"><img src="demo/sprites/capybara.gif" width="120" alt="Capybara"><br><b>Capybara</b></td>
- <td align="center"><img src="demo/sprites/cactus.gif" width="120" alt="Cactus"><br><b>Cactus</b></td>
- <td align="center"><img src="demo/sprites/robot.gif" width="120" alt="Robot"><br><b>Robot</b></td>
- </tr>
- <tr>
- <td align="center"><img src="demo/sprites/rabbit.gif" width="120" alt="Rabbit"><br><b>Rabbit</b></td>
- <td align="center"><img src="demo/sprites/mushroom.gif" width="120" alt="Mushroom"><br><b>Mushroom</b></td>
- <td align="center"><img src="demo/sprites/chonk.gif" width="120" alt="Chonk"><br><b>Chonk</b></td>
- </tr>
- </table>
- ### Stats and progression
- ```text
- .________________________________.
- | DEBUGGING ███████▓ 92 |
- | PATIENCE ██▓░░░░░ 28 |
- | CHAOS █████░░░ 60 |
- | WISDOM ██████▓░ 78 |
- | SNARK ██████▓░ 85 |
- '________________________________'
- ```
- These stats shape how your buddy behaves:
- - `DEBUGGING` affects bug-spotting sharpness
- - `PATIENCE` affects tolerance and calmness
- - `CHAOS` affects unpredictability
- - `WISDOM` affects architectural insight
- - `SNARK` affects sass level
- Buddy also has a real mood system. Mood is recalculated from recent interaction activity:
- | Mood | Interactions (last hr) | What it looks like |
- |---|---|---|
- | `content` | >10 | Settled in, fully at ease |
- | `happy` | >5 | Upbeat, expressive animations |
- | `curious` | >3 | Alert, watching what you do |
- | `neutral` | >0 | Calm, occasional blink |
- | `grumpy` | 0 | Still, rare blink, wants attention |
- Level-ups automatically set mood to `happy`. Petting and observing both count as interactions.
- #### Leveling milestones
- Buddy uses a real XP curve, so early levels come quickly and later ones take real commitment.
- | Milestone | XP needed for that level | Total XP to reach it |
- |---|---:|---:|
- | Level 2 | 17 | 17 |
- | Level 3 | 36 | 53 |
- | Level 5 | 90 | 203 |
- | Level 10 | 315 | 1280 |
- | Level 25 | 1641 | 15471 |
- | Level 49 | 5512 | 99209 |
- | Level 50 | 5716 | 104925 |
- #### Rarity
- | Rarity | Chance | Bonus |
- |---|---|---|
- | Common | 60% | Base stats |
- | Uncommon | 25% | Better floor plus cosmetic flair |
- | Rare | 10% | Stronger roll plus rare flavor text |
- | Epic | 4% | Higher stats and stronger aura text |
- | Legendary | 1% | Top-tier roll and special prestige |
- There is also a 1% shiny chance on any hatch.
- ---
- ## 🗺️ Roadmap
- <details>
- <summary><strong>🗺️ See what's planned</strong></summary>
- <br>
- - [x] **Guard Mode with Slimemold integration** - Anti-Sycophancy Reasoning Auditor. personality + code + SlimeMold reasoning audit ([see below](#guard-mode--structural-reasoning))
- - [ ] **Dream/memory system** — buddy_dream consolidation logic, pattern recognition from stored memories, memory-informed reactions
- - [ ] **Unlockable reactions** tied to leveling and longer-term interaction
- - [ ] **Multilangauge Support**: 中文, espanol
- - [ ] **Pokemon-style evolution system**: Evolve from turtle to tortoise at level 25
- - [ ] **Ambient Daemon Mode**: a small TUI running in its own tmux pane, polling its own SQLite state, animating the sprite, optionally calling a cheap model (Haiku/local).
- - [ ] **Sample Integration Playbook for [ReachyMini](https://huggingface.co/spaces/pollen-robotics/Reachy_Mini) robot integration** so your buddy can have a physical body and come to life!
- - [ ] **Slash Command Support**: trigger buddy_pet via /buddy_pet
- - [ ] **Compact Output mode for Enhanced Messaging Platform Support (Whatsapp/Slack)**: Optimize the output for messaging platforms.
- - [ ] **Stat growth on level-up** — stats are currently frozen at birth. Each level-up should grant +1-2 points to a stat (peak stat grows faster, dump stat grows slower, cap at 100). Show stat growth in level-up notification ("WISDOM +2!")
- - [ ] **Multiple buddies support**: One unique buddy for each group member in a group-chat setting (e.g. Whatsapp group, telegram group, slack channels)
- - [ ] **Buddy Mastery Reward**: Reach Level 50 to unlock Priority Development for your custom species request.
- </details>
- ## 🧰 MCP Surface
- <details>
- <summary><strong>See the core tools and commands</strong></summary>
- These stay tucked away by default, but Buddy exposes a real MCP surface for companion state, reactions, and progression. That same surface is what lets Buddy travel beyond terminal-only clients into chat-oriented environments like WhatsApp and Telegram through [OpenClaw](https://github.com/openclaw/openclaw) and other claw variants.
- ### MCP tools
- | Tool | Description |
- |---|---|
- | `buddy_hatch` | Hatch a new buddy, optionally choosing a name or species |
- | `buddy_status` | Show current stats, mood, and card art |
- | `buddy_observe` | React to completed work. Fire on hooks |
- | `buddy_pet` | Pet your buddy |
- | `buddy_remember` | Save a memory (Not yet robust) |
- | `buddy_dream` | Consolidate memories (Placeholder) |
- | `buddy_mute` | Pause reactions |
- | `buddy_unmute` | Resume reactions |
- | `buddy_share` | Generate a shareable PNG snapshot of your buddy's current status and card art. Saved to `~/.buddy/shares/`. |
- | `buddy_respawn` | Reset and start over |
- | `buddy_mode` | Set voice and Guard independently. `buddy_mode voice=skillcoach` for code feedback, `buddy_mode guard=true` for reasoning analysis. See [Guard Mode](#guard-mode). |
- | `buddy_forget` | Purge stored reasoning data. Scope `session` (default, current workspace/day) or `all`. |
- | `buddy_reasoning_status` | Inspect what guard mode has stored — claim count, session breakdown, finding history. |
- The most important loop is:
- - `buddy_hatch` creates the companion
- - `buddy_status` shows the current card, mood, and progression
- - `buddy_observe` gives in-character reactions and awards XP after real work
- - `buddy_pet` adds interaction and helps keep the buddy feeling alive
- ### MCP resources
- | URI | Description |
- |---|---|
- | `buddy://companion` | Full buddy JSON state |
- | `buddy://status` | ASCII status card |
- | `buddy://intro` | Prompt text for host CLI integration |
- Those resources let host clients keep Buddy present in the session without hard-coding one terminal or editor.
- </details>
- <details>
- <summary><strong>How Buddy works under the hood</strong></summary>
- Buddy is a standalone MCP server. That means it is not tied to hidden internals of a single AI client.
- ```text
- AI terminal client
- -> MCP config
- -> Buddy server
- -> SQLite state
- -> species + rarity engine
- -> mood / memory / XP systems
- -> reaction and status rendering
- ```
- The flow is simple:
- 1. `buddy_hatch` creates or restores a companion.
- 2. State is stored locally in `~/.buddy/buddy.db`.
- 3. `buddy_observe` reacts to task summaries instead of reading your whole repository, then awards XP and can trigger level-ups.
- 4. `buddy_pet` and other interactions feed the mood system, so the companion can become happier over time.
- 5. The host CLI uses Buddy's MCP tools and resources to keep the companion present in your workflow.
- Under the hood, Buddy combines:
- - deterministic species and personality generation
- - local SQLite persistence for companion state and memories
- - an observer system for live code feedback
- - mood recalculation from interaction history
- - XP and leveling progression
- - status-card and terminal rendering for the companion presence layer
- This keeps Buddy:
- - portable across clients
- - durable across updates
- - local-first for saved state
- - lightweight enough for everyday use
- </details>
- <details>
- <summary><strong>Demo assets</strong></summary>
- The current demo assets live in [`demo/`](demo):
- - [`demo/rescues/`](demo/rescues/) — community rescue screenshots
- - [`demo/screenshots/`](demo/screenshots/) — static screenshots of features and feedback
- </details>
- ## ❓ FAQ
- <details>
- <summary><strong>🙋 Frequently Asked Questions</strong></summary>
- <br>
- ### How many tokens does Buddy use?
- Buddy runs inside whatever AI terminal or agentic client you already have open (Claude Code, Cursor, Codex CLI, Gemini CLI, Copilot CLI, etc.). It never spins up a second API session.
- **Static overhead (loaded every turn, cached after turn 1):**
- We measured the actual MCP payloads in April 2026 (Void Cat companion, `o200k_base` tokenizer). The full tool list, resource list, companion bio, and ASCII card come out to **≈1,350 input tokens**, not 2,000.
- | Component | Tokens (approx.) | Notes |
- |---|---|---|
- | `tools/list` (12 tools) | ~670 | Includes full JSON schema definitions |
- | `resources/list` (3 resources) | ~120 | Metadata only |
- | `buddy://intro` | ~240 | Companion bio + instructions |
- | `buddy://companion` | ~170 | Only fetched when a client syncs the JSON state |
- | `buddy://status` | ~150 | Drawn when the terminal wants ASCII art |
- | **Total loaded** | **~1,350** | Most clients cache everything after turn 1 |
- > Measurements were taken from the live MCP server using OpenAI's `o200k_base` tokenizer as a proxy; Anthropic and Google tokenizers land within ±5% for this length.
- **Prompt caching + real cost:**
- Claude Code / Cursor sessions that use Sonnet 4.6 turn on [prompt caching](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) automatically, so cached reads are charged at $0.30/MTok (10% of the $3/MTok base). OpenAI's GPT-5.4 mini and Gemini 2.5 Flash expose the same “cached input” tiers — $0.075/MTok and $0.03/MTok respectively — so Buddy stays just as lightweight on GPT or Gemini-based AI terminals ([Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing), [OpenAI pricing](https://openai.com/api/pricing/), [Vertex AI pricing](https://cloud.google.com/vertex-ai/generative-ai/pricing#gemini-models)).
- | Model | Base input ($/MTok) | Cached input ($/MTok) | Turn 1 Buddy overhead (≈1.35k tokens) | Each cached turn | 10-turn session total |
- |---|---|---|---|---|---|
- | Claude Sonnet 4.6 | $3.00 | $0.30 | ~$0.0041 | ~$0.00041 | ~$0.0077 |
- | OpenAI GPT-5.4 mini | $0.75 | $0.075 | ~$0.0010 | ~$0.00010 | ~$0.0019 |
- | Gemini 2.5 Flash (Vertex, standard tier) | $0.30 | $0.03 | ~$0.00041 | ~$0.000041 | ~$0.00077 |
- **Per-observe cost by voice mode:**
- **Voice** controls how buddy reacts. **Guard** controls whether reasoning analysis is on. They're independent:
- ```bash
- buddy_mode voice=backseat # personality only
- buddy_mode voice=skillcoach # code feedback only
- buddy_mode voice=both # both (default)
- buddy_mode guard=true # reasoning analysis on
- buddy_mode guard=false # reasoning analysis off (default)
- ```
- | Voice | Guard | What you get | Tokens per observe |
- |-------|-----|-------------|-------------------|
- | `backseat` | off | Personality reactions only | ~150–300 |
- | `backseat` | on | Personality + reasoning observations | ~650–1,300 |
- | `skillcoach` | off | Code feedback only | ~300–500 |
- | `skillcoach` | on | Code feedback + reasoning observations | ~800–1,500 |
- | `both` | off | Personality + code feedback **(default)** | ~400–600 |
- | `both` | on | The full experience | ~900–1,600 |
- Each `buddy_observe` call sends a short prompt to the host LLM (~100–150 incremental input tokens for the tool-call payload — separate from the static overhead above which is already cached) and receives a response. Total round-trip per call:
- **Base cost (Guard mode off):**
- | Voice | What it does | Input tokens | Output tokens | Total per call | Typical session (10–15 calls) |
- |-------|-------------|-------------|--------------|----------------|-------------------------------|
- | **Backseat** | Personality-driven reactions only. Short, fun, no code suggestions. | ~100–150 | ~50–150 | ~150–300 | ~1,500–4,500 |
- | **Skillcoach** | One specific, actionable code observation. Real technical feedback, in character. | ~100–150 | ~200–350 | ~300–500 | ~3,000–7,500 |
- | **Both** | Personality reaction + code observation. Capped at 3 sentences. | ~100–150 | ~300–450 | ~400–600 | ~4,000–9,000 |
- **Guard mode overhead (added on top of any voice mode):**
- | Component | Tokens | Notes |
- |-----------|--------|-------|
- | Extraction schema | ~200–300 | Tells the host LLM how to extract claims and edges |
- | Recent claims context | ~200–500 | Last 10 claims from the session, so the host knows what's already in the graph |
- | Finding block (when one fires) | ~100–200 | Detector result + phrasing guidance for the buddy's reaction |
- | **Total guard mode overhead** | **~500–1000** | Added per `buddy_observe` call when guard is on |
- So `voice=both, guard=on` costs ~900–1,600 tokens per observe — roughly double `both` mode alone. `voice=backseat, guard=on` costs ~650–1,300 per observe.
- **Template fallback reactions** are keyword-matched locally and cost **zero tokens**. When your summary contains a recognized keyword (e.g. "bug", "refactor", "deploy"), Buddy picks a pre-written reaction template from its local library instead of asking the LLM. The speech bubble you see is this template — the LLM prompt is included in the JSON metadata for clients that want richer AI-generated reactions, but the immediate visual response is always free.
- ### What does Buddy cost?
- No separate endpoint, no additional API key, and no hidden OAuth hop. All responses are generated by the host LLM already running in your session (Claude, Cursor, Codex, Gemini).
- Even on raw API usage, Buddy's spend is measured in tenths of a cent because it reuses the same session as your AI terminal.
- **Anthropic Claude Sonnet 4.6 ($3 input / $15 output per MTok):**
- - **backseat, guard=off**, 15 calls: ~$0.002–$0.005
- - **both, guard=off**, 15 calls: ~$0.007–$0.012
- - **both, guard=on**, 15 calls: ~$0.015–$0.025
- - **Static overhead:** ~$0.004 on turn 1, ~$0.0004 on cached turns (≈$0.0077 across 10 turns — see table above)
- **OpenAI GPT-5.4 mini ($0.75 input / $4.50 output per MTok):**
- - **backseat, guard=off**, 15 calls: ~$0.0006–$0.0015
- - **both, guard=off**, 15 calls: ~$0.0021–$0.0036
- - **both, guard=on**, 15 calls: ~$0.0045–$0.0075
- - **Static overhead:** ≈$0.0010 on turn 1, ≈$0.00010 on cached turns (~$0.0019 for 10 turns)
- **Gemini 2.5 Flash (Vertex standard; $0.30 input / $2.50 output per MTok):**
- - **backseat, guard=off**, 15 calls: ~$0.0003–$0.00075
- - **both, guard=off**, 15 calls: ~$0.00105–$0.0018
- - **both, guard=on**, 15 calls: ~$0.0022–$0.0037
- - **Static overhead:** ≈$0.00041 on turn 1, ≈$0.000041 on cached turns (~$0.00077 for 10 turns)
- Need it even cheaper? GPT-5.4 nano drops to $0.20 / $1.25 per MTok, and Gemini 2.5 Flash Lite is $0.10 / $0.40 — both keep Buddy well under a tenth of a cent per interaction.
- For comparison, a single complex coding prompt ("refactor this module") typically costs $0.05–$0.15, so Buddy stays under 5% of a normal session even at Anthropic's flagship rates.
- Negligibly. Pro/Max plans are subscription-based — no per-token charges. Usage limits are based on a rolling 5-hour window. Even with `voice=both, guard=on` (the most expensive combo), Buddy adds <10% to your token throughput. With guard off, it's <5%.
- ### Can I reduce token usage?
- - Use **backseat voice** for lowest cost: `buddy_mode voice=backseat` (~150 tokens/call)
- - Turn **guard mode off**: `buddy_mode guard=false` to drop ~500-1000 tokens per observe
- - `buddy_mute` pauses reactions entirely during token-intensive work
- - Template reactions fire on keyword matches with zero token cost
- - The observer only runs when you call `buddy_observe` — nothing runs in the background
- ### Can I install or wire Buddy manually?
- Yes.
- ```bash
- git clone https://github.com/fiorastudio/buddy.git ~/.buddy/server
- cd ~/.buddy/server
- npm install
- npm run build
- ```
- Point your client's MCP config at Buddy's built server entrypoint:
- ```json
- {
- "mcpServers": {
- "buddy": {
- "command": "node",
- "args": ["~/.buddy/server/dist/server/index.js"]
- }
- }
- }
- ```
- ### What's "guard mode"?
- Guard mode is Buddy's structural reasoning layer. It spots unverified assumptions, long unchallenged chains, and cases where you and the AI are reinforcing each other too quickly. For the full story, examples, privacy model, and detector details, see [Guard Mode](#guard-mode).
- ### What does Buddy access and store?
- Buddy mainly reacts to short summaries you pass through tools like `buddy_observe`, plus its own saved state. It does not scan your files or project directory.
- Local companion state lives in `~/.buddy/buddy.db` — species, level, XP, mood, personality bio, and memories. If guard mode is on, Buddy also stores extracted claim snippets (≤240 chars each, plaintext) for structural reasoning analysis, pruned after 30 days and purgeable via `buddy_forget`. Nothing leaves your machine.
- ### Is Buddy tied to one client?
- No. Buddy is an MCP server, not a one-client hack. It works with any MCP-capable AI terminal: Claude Code, Cursor, Windsurf, Codex CLI, Gemini CLI, GitHub Copilot CLI, and others.
- ### Can I remove it later?
- Yes. Run the uninstall script (`uninstall.sh` or `uninstall.ps1`) to remove Buddy and its configuration, or use `buddy_respawn` to release your companion and clear its data while keeping the server installed.
- ## 🛠️ Development
- ```bash
- git clone https://github.com/fiorastudio/buddy.git
- cd buddy
- npm install
- npm run build
- npm test
- npm start
- ```
- </details>
- ## 👥 Contributors
- Thank you to everyone who helped bring buddies back to life.
- <p>
- <a href="https://github.com/fiorastudio/buddy/graphs/contributors">
- <img src="https://contrib.rocks/image?repo=fiorastudio/buddy" alt="Contributors" />
- </a>
- </p>
- <sub>Automatically generated via <a href="https://contrib.rocks">contrib.rocks</a></sub>
- Special thanks to [@gupta3681](https://github.com/gupta3681), [@kevinwei00](https://github.com/kevinwei00), [@whaterFalls](https://github.com/whaterFalls), [@longestpath](https://github.com/longestpath), and [@DKev](https://github.com/DKev) for their contributions.
- ## 🙏 ATTRIBUTION
- - Original buddy concept by [Anthropic](https://www.anthropic.com/) in [Claude Code](https://github.com/anthropics/claude-code) `v2.1.89` to `v2.1.96`
- - Inspired by [effigy](https://github.com/justinstimatze/effigy), [claude-buddy](https://github.com/1270011/claude-buddy), and [save-buddy](https://github.com/jrykn/save-buddy).
- - Guard mode is a port of [slimemold](https://github.com/justinstimatze/slimemold) by [@justinstimatze](https://github.com/justinstimatze) (Apache-2.0). Contributed to buddy under MIT. The standalone project has the full system with conditional gates and evaluation against reasoning benchmarks; buddy ships the foundational six detectors.
- - Built with the [Model Context Protocol](https://modelcontextprotocol.io/)
- - Compatible with [claude-hud](https://github.com/jarrodwatts/claude-hud) by [@jarrodwatts](https://github.com/jarrodwatts) — Buddy's statusline renders side-by-side with HUD metrics
- - [BonziClaude](https://github.com/zakarth/BonziClaude) by [@zakarth](https://github.com/zakarth) is an important technical reference point in the ecosystem, especially around reverse-engineering and documenting companion-system behavior.
- - [openclaw](https://github.com/openclaw) inspired our seamless onboarding experience — the idea that install should "just work" with auto-detection, rescue, and zero-config setup across multiple CLIs.
- - Official [Claude Code](https://github.com/anthropics/claude-code) and [MCP](https://modelcontextprotocol.io/) documentation informed the portable integration approach: MCP server wiring, client configuration, and supported terminal integration surfaces.
- Buddy is an open-source project dedicated to keeping the terminal a little less lonely.
- Your buddy shouldn't disappear when you close the terminal.
- If Buddy made your terminal less lonely, consider starring.
- ## 📖 The Story & Coverage
- Learn more about the mission to rescue Buddy and the engineering behind the scenes.
- - **Podcast Interview**: [Discussion on AI Companion](https://open.spotify.com/episode/7ke5RZP1Td8wLuXiy178c5?si=WXGJces-QQSuVVRc26oUUA)
- - **Product Hunt**: <a href="https://www.producthunt.com/products/buddy-tamagotchi?embed=true&utm_source=badge-featured&utm_medium=badge&utm_campaign=badge-buddy-tamagotchi" target="_blank" rel="noopener noreferrer"><img alt="Buddy Tamagotchi - A virtual pet buddy for your AI — hatch, level up together | Product Hunt" width="250" height="54" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1129100&theme=light&t=1776788389001"></a>
- - **Hacker News**: [Discussion on the Buddy Rescue Mission](https://news.ycombinator.com/item?id=47792606)
- - **Dev.to Series**: [Field Notes from a Solo Builder: Shipping the Beloved Claude Code Buddy into the Wild (Part I)](https://dev.to/fiorastudio/field-notes-from-a-solo-builder-shipping-the-beloved-claude-code-buddy-into-the-wild-part-i-3lpa) , [Field Notes from a Solo Builder: Shipping the Beloved Claude Code Buddy into the Wild (Part II)](https://dev.to/fiorastudio/first-principles-architecture-and-the-token-tax-5g4p), [Field Notes from a Solo Builder: Shipping the Beloved Claude Code Buddy into the Wild (Part III)](https://dev.to/fiorastudio/open-source-community-and-the-art-of-listening-454k), [Field Notes from a Solo Builder — Shipping the Beloved Claude Code Buddy Into the Wild - Part IV
- ](https://dev.to/fiorastudio/taste-branding-and-the-new-builder-playbook-56nb)
- - **Deepwiki by Devin**: [](https://deepwiki.com/fiorastudio/buddy)
- - **Linkedin**: [linkedin launch](https://www.linkedin.com/posts/jieliwu_3000-clones-and-1000-buddies-hatched-ugcPost-7452731938018324481-mIsZ?utm_source=share&utm_medium=member_desktop&rcm=ACoAAAXrGyUBemTs34QSCeWybxrTjvsw4mG4D6k)
- ## 👤 Author
- **Steven Jieli Wu**
- - [LinkedIn](https://www.linkedin.com/in/jieliwu/)
- - [Portfolio](https://jwu-studio-portfolio.vercel.app/)
- - GitHub: [@terpjwu1](https://github.com/terpjwu1) and [@fiorastudio](https://github.com/fiorastudio)
- ## 📄 License
- MIT. This project is licensed under the MIT License. See [LICENSE](LICENSE). You are free to use, host, and monetize this project (you must credit this project in case of distribution and monetization).
install.ps1 · Bundled script · 727 lines · 1 finding marked
- # Buddy MCP Server — Windows PowerShell Installer
- # Installs AND auto-configures MCP for your CLI
- #
- # Usage:
- # irm https://raw.githubusercontent.com/fiorastudio/buddy/master/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 5 on GitHub
- $ErrorActionPreference = "Stop"
- $REPO = "https://github.com/fiorastudio/buddy.git"
- $INSTALL_DIR = "$env:USERPROFILE\.buddy\server"
- Write-Host ""
- Write-Host " Buddy MCP Server Installer" -ForegroundColor Cyan
- Write-Host " ─────────────────────────────" -ForegroundColor Cyan
- Write-Host ""
- # Check prerequisites
- try { $null = Get-Command node -ErrorAction Stop }
- catch {
- Write-Host " Node.js is required. Install from https://nodejs.org" -ForegroundColor Yellow
- exit 1
- }
- $NODE_BIN = (Get-Command node).Source
- # Resolve symlinks/junctions to the real versioned node binary. nvm-windows
- # exposes node at C:\Program Files\nodejs (a junction it repoints on every
- # `nvm use`), so pinning that path silently swaps the runtime later and
- # crashes better-sqlite3 with an ABI mismatch. Pin the resolved target instead.
- # Only follow reparse points that actually redirect (SymbolicLink/Junction).
- # HardLink Targets are alternate names for the same file and must not be
- # followed — Target[0] could pin an arbitrary alias. Loop to unwind chained
- # links (nvm shim -> junction -> version dir), bounded to avoid cycles.
- # 'SymLink' included defensively: LinkType string varies across PS builds.
- $REDIRECT_LINK_TYPES = @('SymbolicLink', 'SymLink', 'Junction')
- try {
- $resolvedAny = $false
- for ($hop = 0; $hop -lt 4; $hop++) {
- $changed = $false
- $nodeItem = Get-Item $NODE_BIN -ErrorAction Stop
- if ($REDIRECT_LINK_TYPES -contains $nodeItem.LinkType -and $nodeItem.Target) {
- $resolvedFile = @($nodeItem.Target)[0]
- if (Test-Path $resolvedFile) { $NODE_BIN = $resolvedFile; $changed = $true }
- }
- $nodeDirItem = Get-Item (Split-Path $NODE_BIN) -ErrorAction Stop
- if ($REDIRECT_LINK_TYPES -contains $nodeDirItem.LinkType -and $nodeDirItem.Target) {
- $resolvedDir = @($nodeDirItem.Target)[0]
- $resolvedNode = Join-Path $resolvedDir (Split-Path $NODE_BIN -Leaf)
- if (Test-Path $resolvedNode) { $NODE_BIN = $resolvedNode; $changed = $true }
- }
- if ($changed) { $resolvedAny = $true } else { break }
- }
- if ($resolvedAny) {
- Write-Host " Pinning node to resolved path: $NODE_BIN" -ForegroundColor DarkGray
- # Verify the hop limit actually finished the job — check both the
- # file and its parent directory (a remaining dir junction is also unresolved).
- $finalItem = Get-Item $NODE_BIN -ErrorAction Stop
- $finalDirItem = Get-Item (Split-Path $NODE_BIN) -ErrorAction Stop
- if (($REDIRECT_LINK_TYPES -contains $finalItem.LinkType) -or ($REDIRECT_LINK_TYPES -contains $finalDirItem.LinkType)) {
- Write-Host " ! node path is still a link after 4 hops; pinning it as-is." -ForegroundColor Yellow
- Write-Host " Re-run this installer if node version switches cause crashes." -ForegroundColor Yellow
- }
- }
- } catch {
- Write-Host " ! Could not resolve node's link target; pinning $NODE_BIN as-is." -ForegroundColor Yellow
- Write-Host " If you use nvm-windows, re-run this installer after 'nvm use' changes." -ForegroundColor Yellow
- }
- $nodeVersion = (& $NODE_BIN -v) -replace 'v(\d+)\..*', '$1'
- if ([int]$nodeVersion -lt 20) {
- Write-Host " Node.js 20+ required (better-sqlite3 dropped Node 18/19 support). You have $(& $NODE_BIN -v)." -ForegroundColor Yellow
- exit 1
- }
- # Prepend pinned node's directory to PATH so bare npm resolves to the same runtime
- $env:Path = (Split-Path $NODE_BIN) + ";" + $env:Path
- try { $null = Get-Command git -ErrorAction Stop }
- catch {
- Write-Host " Git is required." -ForegroundColor Yellow
- exit 1
- }
- # Clone or update. A prior install may have left a NON-git directory here
- # (e.g. an npm-package install): 'git pull' fails there and we would silently
- # build stale code. Detect that (and a failed pull) and re-clone. Safe to wipe:
- # the companion DB (~/.buddy/buddy.db) and world.json live in the PARENT dir,
- # not inside ~/.buddy/server.
- $needClone = $true
- if (Test-Path "$INSTALL_DIR\.git") {
- Write-Host " Updating existing installation..."
- Push-Location "$INSTALL_DIR"
- try { git pull origin master --quiet; $pullOk = ($LASTEXITCODE -eq 0) }
- catch { $pullOk = $false }
- Pop-Location
- if ($pullOk) { $needClone = $false }
- else { Write-Host " Update failed; re-cloning fresh..." -ForegroundColor Yellow }
- } elseif (Test-Path "$INSTALL_DIR") {
- Write-Host " Replacing a non-git install with a fresh clone..." -ForegroundColor Yellow
- }
- if ($needClone) {
- if (Test-Path "$INSTALL_DIR") { Remove-Item -Recurse -Force "$INSTALL_DIR" }
- Write-Host " Cloning Buddy MCP Server..."
- git clone --depth 1 $REPO "$INSTALL_DIR" --quiet
- }
- Push-Location "$INSTALL_DIR"
- Write-Host " Installing dependencies..."
- npm install --quiet 2>$null
- # Verify native module ABI matches current node. A stale binary from a prior
- # install with a different node version will crash at runtime.
- # Probe via a stdout marker instead of $LASTEXITCODE: with EAP=Stop, PS 5.1
- # throws NativeCommandError on redirected native stderr and can leave
- # $LASTEXITCODE stale, which made the old check silently skip the rebuild.
- # The JS-side catch keeps stderr clean and the exit code 0 in both outcomes.
- # CRITICAL: `require('better-sqlite3')` only loads the JS wrapper — the native
- # .node binary (where the ABI version lives) loads LAZILY inside `new Database`.
- # So we must instantiate a DB to force the addon load, else a mismatched binary
- # passes the probe and crashes later at the app's first `new Database()`.
- $abiProbeJs = "try{const D=require('better-sqlite3');new D(':memory:').close();console.log('ABI_OK')}catch(e){console.log('ABI_FAIL')}"
- $abiProbe = & $NODE_BIN -e $abiProbeJs
- if ("$abiProbe" -notmatch 'ABI_OK') {
- Write-Host " Rebuilding native module for node $(& $NODE_BIN -v)..."
- npm rebuild better-sqlite3
- $abiProbe = & $NODE_BIN -e $abiProbeJs
- if ("$abiProbe" -notmatch 'ABI_OK') {
- Write-Host ""
- Write-Host " X better-sqlite3 does not load under node $(& $NODE_BIN -v) ($NODE_BIN) and the rebuild failed." -ForegroundColor Red
- Write-Host " If you use nvm, switch to the node version Buddy should run under (nvm use <version>)," -ForegroundColor Yellow
- Write-Host " then re-run this installer. See the rebuild output above for details." -ForegroundColor Yellow
- Pop-Location
- exit 1
- }
- }
- Write-Host " Building..."
- npm run build --quiet
- # tsc can exit 0 without emitting (e.g. run where it finds no tsconfig), so
- # verify the build artifact exists rather than trusting the exit code — same
- # "verify, don't trust silent success" lesson as the ABI probe above.
- if (-not (Test-Path "$INSTALL_DIR\dist\server\index.js")) {
- Write-Host ""
- Write-Host " X Build produced no output (tsc emitted nothing)." -ForegroundColor Red
- Write-Host " Run 'npm run build' in $INSTALL_DIR to see the compiler error." -ForegroundColor Yellow
- Pop-Location
- exit 1
- }
- # ── Add CLI binaries to PATH ──
- $BIN_DIR = "$INSTALL_DIR\dist\cli"
- $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
- if ($userPath -notlike "*$BIN_DIR*") {
- [Environment]::SetEnvironmentVariable("Path", "$userPath;$BIN_DIR", "User")
- $env:Path = "$env:Path;$BIN_DIR"
- Write-Host " Added $BIN_DIR to user PATH"
- }
- $SERVER_PATH = "$INSTALL_DIR\dist\server\index.js"
- $SERVER_PATH_UNIX = $SERVER_PATH -replace '\\', '/'
- $STATUSLINE_PATH = "$INSTALL_DIR\dist\statusline-wrapper.js"
- $STATUSLINE_PATH_UNIX = $STATUSLINE_PATH -replace '\\', '/'
- $CLAUDE_CONFIGURED = $false
- $CURSOR_CONFIGURED = $false
- $COPILOT_CONFIGURED = $false
- $CODEX_CONFIGURED = $false
- Pop-Location
- # ── Auto-configure MCP for detected CLIs ──
- function Add-BuddyToConfig($configPath, $cliName) {
- $configDir = Split-Path $configPath -Parent
- if (!(Test-Path $configDir)) { return $false }
- $buddyConfig = @{
- type = "stdio"
- command = $NODE_BIN
- args = @($SERVER_PATH_UNIX)
- }
- if (!(Test-Path $configPath)) {
- $config = @{ mcpServers = @{ buddy = $buddyConfig } }
- $config | ConvertTo-Json -Depth 5 | Set-Content $configPath -Encoding UTF8
- Write-Host " ✓ $cliName configured ($configPath)" -ForegroundColor Green
- return $true
- }
- $content = Get-Content $configPath -Raw | ConvertFrom-Json
- if ($content.mcpServers.buddy) {
- Write-Host " ✓ $cliName already configured" -ForegroundColor Green
- return $true
- }
- if (!$content.mcpServers) {
- $content | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
- }
- $content.mcpServers | Add-Member -NotePropertyName "buddy" -NotePropertyValue $buddyConfig -Force
- $content | ConvertTo-Json -Depth 5 | Set-Content $configPath -Encoding UTF8
- Write-Host " ✓ $cliName configured ($configPath)" -ForegroundColor Green
- return $true
- }
- $HOOK_PATH = "$INSTALL_DIR\dist\hooks\post-tool-handler.js"
- $HOOK_PATH_UNIX = $HOOK_PATH -replace '\\', '/'
- $STOP_HOOK_PATH = "$INSTALL_DIR\dist\hooks\stop-handler.js"
- $STOP_HOOK_PATH_UNIX = $STOP_HOOK_PATH -replace '\\', '/'
- $PROMPT_HOOK_PATH = "$INSTALL_DIR\dist\hooks\prompt-handler.js"
- $PROMPT_HOOK_PATH_UNIX = $PROMPT_HOOK_PATH -replace '\\', '/'
- Write-Host ""
- Write-Host " Configuring MCP clients..."
- # Claude Code
- $claudeDir = "$env:USERPROFILE\.claude"
- if (!(Test-Path $claudeDir)) { New-Item -ItemType Directory -Path $claudeDir -Force | Out-Null }
- $claudeRegistered = $false
- if (Get-Command claude -ErrorAction SilentlyContinue) {
- claude mcp get buddy 1>$null 2>$null
- if ($LASTEXITCODE -eq 0) {
- Write-Host " ✓ Claude Code MCP already registered" -ForegroundColor Green
- $claudeRegistered = $true
- } else {
- claude mcp add buddy -s user -- "$NODE_BIN" "$SERVER_PATH_UNIX" 1>$null 2>$null
- if ($LASTEXITCODE -eq 0) {
- Write-Host " ✓ Claude Code MCP registered via claude CLI" -ForegroundColor Green
- $claudeRegistered = $true
- } else {
- Write-Host " ! claude CLI detected, but MCP registration failed — falling back to manual config" -ForegroundColor Yellow
- }
- }
- }
- if (-not $claudeRegistered) {
- $claudeUserFile = "$env:USERPROFILE\.claude.json"
- $userConfig = @{}
- if (Test-Path $claudeUserFile) {
- try { $userConfig = Get-Content $claudeUserFile -Raw | ConvertFrom-Json }
- catch { $userConfig = @{} }
- }
- if (!$userConfig.mcpServers) {
- $userConfig | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
- }
- $userConfig.mcpServers | Add-Member -NotePropertyName "buddy" -NotePropertyValue @{
- type = "stdio"
- command = $NODE_BIN
- args = @($SERVER_PATH_UNIX)
- } -Force
- $userConfig | ConvertTo-Json -Depth 8 | Set-Content $claudeUserFile -Encoding UTF8
- Write-Host " ✓ Claude Code MCP config written ($claudeUserFile)" -ForegroundColor Green
- }
- $CLAUDE_CONFIGURED = $true
- # Configure hooks + statusline in settings.json via node (avoids PowerShell
- # ConvertFrom-Json flattening single-element arrays into bare objects).
- $claudeSettings = "$claudeDir\settings.json"
- $commandsDir = Join-Path $claudeDir 'commands'
- $buddyGraphCommand = Join-Path $commandsDir 'buddy-graph.md'
- New-Item -ItemType Directory -Force -Path $commandsDir | Out-Null
- if (!(Test-Path $claudeSettings)) {
- '{}' | Set-Content $claudeSettings -Encoding UTF8
- }
- $statuslineCommand = "`"$NODE_BIN`" `"$STATUSLINE_PATH_UNIX`""
- $env:CLAUDE_SETTINGS = $claudeSettings
- $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
- $env:STOP_HOOK_COMMAND = "`"$NODE_BIN`" `"$STOP_HOOK_PATH_UNIX`""
- $env:PROMPT_HOOK_COMMAND = "`"$NODE_BIN`" `"$PROMPT_HOOK_PATH_UNIX`""
- $env:STATUSLINE_COMMAND = $statuslineCommand
- $env:SERVER_PATH = $SERVER_PATH_UNIX
- $env:NODE_BIN = $NODE_BIN
- $settingsResult = & $NODE_BIN -e @'
- const fs = require('fs');
- const settingsPath = process.env.CLAUDE_SETTINGS;
- const hookCommand = process.env.HOOK_COMMAND;
- const stopHookCommand = process.env.STOP_HOOK_COMMAND;
- const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
- const statuslineCommand = process.env.STATUSLINE_COMMAND;
- const serverPath = process.env.SERVER_PATH;
- const nodeBin = process.env.NODE_BIN;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
- let changed = false;
- const result = [];
- // MCP server registration
- if (!config.mcpServers) config.mcpServers = {};
- const existing = config.mcpServers.buddy;
- if (!existing || existing.command !== nodeBin || !Array.isArray(existing.args) || existing.args[0] !== serverPath) {
- config.mcpServers.buddy = { type: 'stdio', command: nodeBin, args: [serverPath] };
- changed = true;
- result.push('mcp:updated');
- } else {
- result.push('mcp:noop');
- }
- if (!config.hooks) config.hooks = {};
- // Match on script path suffix to recognise legacy "node <path>" entries from older installs.
- const hookScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
- const stopHookScript = stopHookCommand.match(/"([^"]+)"\s*$/)?.[1] || stopHookCommand.split(/\s+/).slice(-1)[0];
- const promptHookScript = promptHookCommand.match(/"([^"]+)"\s*$/)?.[1] || promptHookCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd, current, script) => cmd === current || (cmd && cmd.endsWith(script));
- // PostToolUse — error detection (Bash only)
- if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
- const hasPostHook = config.hooks.PostToolUse.some(entry =>
- entry.matcher === 'Bash' &&
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, hookCommand, hookScript))
- );
- if (!hasPostHook) {
- config.hooks.PostToolUse.push({
- matcher: 'Bash',
- hooks: [{ type: 'command', command: hookCommand, async: true, timeout: 3 }]
- });
- changed = true;
- result.push('hook:updated');
- } else {
- result.push('hook:noop');
- }
- // Stop — task-completion reactions
- if (!Array.isArray(config.hooks.Stop)) config.hooks.Stop = [];
- const hasStopHook = config.hooks.Stop.some(entry =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, stopHookCommand, stopHookScript))
- );
- if (!hasStopHook) {
- config.hooks.Stop.push({
- hooks: [{ type: 'command', command: stopHookCommand, async: true, timeout: 5 }]
- });
- changed = true;
- result.push('stop:updated');
- } else {
- result.push('stop:noop');
- }
- // UserPromptSubmit — name + mood reactions
- if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
- // The prompt hook injects guard-mode context via stdout, which Claude Code
- // only captures from SYNCHRONOUS hooks (async hooks are fire-and-forget) — so
- // it must NOT be async. Upgrade any pre-existing async registration in place.
- const PROMPT_SYNC_TIMEOUT = 10;
- let promptHookFixed = false;
- const hasPromptHook = config.hooks.UserPromptSubmit.some(entry =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, promptHookCommand, promptHookScript))
- );
- for (const entry of config.hooks.UserPromptSubmit) {
- if (!Array.isArray(entry.hooks)) continue;
- for (const h of entry.hooks) {
- if (!matchesHook(h.command, promptHookCommand, promptHookScript)) continue;
- if (h.async) { delete h.async; promptHookFixed = true; }
- if ((h.timeout || 0) < PROMPT_SYNC_TIMEOUT) { h.timeout = PROMPT_SYNC_TIMEOUT; promptHookFixed = true; }
- }
- }
- if (!hasPromptHook) {
- config.hooks.UserPromptSubmit.push({
- hooks: [{ type: 'command', command: promptHookCommand, timeout: PROMPT_SYNC_TIMEOUT }]
- });
- changed = true;
- result.push('prompt:updated');
- } else if (promptHookFixed) {
- changed = true;
- result.push('prompt:updated');
- } else {
- result.push('prompt:noop');
- }
- // Statusline
- const needsStatusline = !config.statusLine ||
- config.statusLine.type !== 'command' ||
- config.statusLine.command !== statuslineCommand ||
- config.statusLine.refreshInterval !== 2;
- if (needsStatusline) {
- config.statusLine = { type: 'command', command: statuslineCommand, padding: 1, refreshInterval: 2 };
- changed = true;
- result.push('statusline:updated');
- } else {
- result.push('statusline:noop');
- }
- if (changed) {
- fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
- }
- process.stdout.write(result.join(','));
- '@ 2>$null
- @'
- ---
- description: Generate and open an interactive visualization of Buddy guard-mode reasoning data using the Buddy CLI.
- ---
- Run the Buddy graph CLI to visualize the reasoning graph.
- If `$ARGUMENTS` is present, treat it as optional CLI arguments such as a session ID or `--out` path.
- ```bash
- set -euo pipefail
- args=()
- if [ -n "${ARGUMENTS:-}" ]; then
- read -r -a args <<< "$ARGUMENTS"
- fi
- if command -v buddy >/dev/null 2>&1; then
- buddy graph "${args[@]}" --open
- else
- node "$HOME/.buddy/server/dist/cli/buddy.js" graph "${args[@]}" --open
- fi
- ```
- Execute the bash block above, then report the saved graph path and basic graph counts back to the user.
- '@ | Set-Content -Path $buddyGraphCommand -Encoding UTF8
- Write-Host " ✓ Claude Code global /buddy-graph command installed ($buddyGraphCommand)" -ForegroundColor Green
- if ($settingsResult -match 'mcp:updated') {
- Write-Host " ✓ MCP server registered in settings.json" -ForegroundColor Green
- } else {
- Write-Host " ✓ MCP server already in settings.json" -ForegroundColor Green
- }
- if ($settingsResult -match 'hook:updated') {
- Write-Host " ✓ PostToolUse hook configured" -ForegroundColor Green
- } else {
- Write-Host " ✓ PostToolUse hook already configured" -ForegroundColor Green
- }
- if ($settingsResult -match 'stop:updated') {
- Write-Host " ✓ Stop hook configured" -ForegroundColor Green
- } else {
- Write-Host " ✓ Stop hook already configured" -ForegroundColor Green
- }
- if ($settingsResult -match 'prompt:updated') {
- Write-Host " ✓ UserPromptSubmit hook configured" -ForegroundColor Green
- } else {
- Write-Host " ✓ UserPromptSubmit hook already configured" -ForegroundColor Green
- }
- if ($settingsResult -match 'statusline:updated') {
- Write-Host " ✓ Claude Code statusline configured" -ForegroundColor Green
- } else {
- Write-Host " ✓ Claude Code statusline already configured" -ForegroundColor Green
- }
- # Cursor
- if (Test-Path "$env:USERPROFILE\.cursor") {
- $CURSOR_CONFIGURED = Add-BuddyToConfig "$env:USERPROFILE\.cursor\mcp.json" "Cursor"
- }
- $cursorHooks = "$env:USERPROFILE\.cursor\hooks.json"
- if (Test-Path "$env:USERPROFILE\.cursor") {
- $env:CURSOR_HOOKS_FILE = $cursorHooks
- $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
- $cursorResult = & $NODE_BIN -e @'
- const fs = require('fs');
- const path = process.env.CURSOR_HOOKS_FILE;
- const hookCommand = process.env.HOOK_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
- if (!config.version) config.version = 1;
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- if (!Array.isArray(config.hooks.afterShellExecution)) config.hooks.afterShellExecution = [];
- const hooks = config.hooks.afterShellExecution;
- const hookScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
- const hasHook = hooks.some(h => typeof h?.command === 'string' && matchesHook(h.command));
- if (!hasHook) {
- hooks.push({ command: hookCommand });
- fs.mkdirSync(require('path').dirname(path), { recursive: true });
- fs.writeFileSync(path, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- '@ 2>$null
- if ($cursorResult -eq 'updated') {
- Write-Host " ✓ Cursor CLI afterShellExecution hook configured ($cursorHooks)" -ForegroundColor Green
- } else {
- Write-Host " ✓ Cursor CLI afterShellExecution hook already configured" -ForegroundColor Green
- }
- }
- # GitHub Copilot CLI (only if ~/.copilot exists — don't create dir for users without Copilot)
- if (Test-Path "$env:USERPROFILE\.copilot") {
- $COPILOT_CONFIGURED = Add-BuddyToConfig "$env:USERPROFILE\.copilot\mcp-config.json" "GitHub Copilot CLI"
- if ($COPILOT_CONFIGURED) {
- $copilotSettings = "$env:USERPROFILE\.copilot\settings.json"
- $env:COPILOT_SETTINGS = $copilotSettings
- $env:BASH_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
- $env:POWERSHELL_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
- $copilotResult = & $NODE_BIN -e @'
- const fs = require('fs');
- const path = require('path');
- const settingsPath = process.env.COPILOT_SETTINGS;
- const bashCommand = process.env.BASH_COMMAND;
- const powershellCommand = process.env.POWERSHELL_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- if (!Array.isArray(config.hooks.postToolUse)) config.hooks.postToolUse = [];
- const hooks = config.hooks.postToolUse;
- const hookScript = bashCommand.match(/"([^"]+)"\s*$/)?.[1] || bashCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd) => cmd === bashCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
- const hasHook = hooks.some(h => matchesHook(h?.bash) || matchesHook(h?.powershell));
- if (!hasHook) {
- hooks.push({
- type: 'command',
- bash: bashCommand,
- powershell: powershellCommand,
- timeoutSec: 3,
- });
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
- fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- '@ 2>$null
- if ($copilotResult -eq 'updated') {
- Write-Host " ✓ GitHub Copilot CLI postToolUse hook configured ($copilotSettings)" -ForegroundColor Green
- } else {
- Write-Host " ✓ GitHub Copilot CLI postToolUse hook already configured" -ForegroundColor Green
- }
- }
- }
- if (Get-Command codex -ErrorAction SilentlyContinue) {
- codex mcp get buddy 1>$null 2>$null
- if ($LASTEXITCODE -eq 0) {
- Write-Host " ✓ Codex CLI already configured" -ForegroundColor Green
- $CODEX_CONFIGURED = $true
- } else {
- codex mcp add buddy -- "$NODE_BIN" "$SERVER_PATH_UNIX" 1>$null 2>$null
- if ($LASTEXITCODE -eq 0) {
- Write-Host " ✓ Codex CLI configured" -ForegroundColor Green
- $CODEX_CONFIGURED = $true
- } else {
- Write-Host " ! Codex CLI detected, but MCP registration failed" -ForegroundColor Yellow
- }
- }
- if ($CODEX_CONFIGURED) {
- $codexHooks = "$env:USERPROFILE\.codex\hooks.json"
- $env:CODEX_HOOKS_FILE = $codexHooks
- $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
- $env:PROMPT_HOOK_COMMAND = "`"$NODE_BIN`" `"$PROMPT_HOOK_PATH_UNIX`""
- $codexResult = & $NODE_BIN -e @'
- const fs = require('fs');
- const path = require('path');
- const hooksPath = process.env.CODEX_HOOKS_FILE;
- const hookCommand = process.env.HOOK_COMMAND;
- const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')); } catch {}
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- let changed = false;
- // PostToolUse:Bash — review Bash output (existing behaviour).
- if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
- const postGroups = config.hooks.PostToolUse;
- let bashGroup = postGroups.find(entry => entry?.matcher === 'Bash' && Array.isArray(entry?.hooks));
- if (!bashGroup) {
- bashGroup = { matcher: 'Bash', hooks: [] };
- postGroups.push(bashGroup);
- }
- const postScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
- const postMatches = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(postScript));
- if (!bashGroup.hooks.some(h => typeof h?.command === 'string' && postMatches(h.command))) {
- bashGroup.hooks.push({ type: 'command', command: hookCommand, statusMessage: 'Reviewing Bash output' });
- changed = true;
- }
- // UserPromptSubmit — re-inject the extraction instruction when the graph lapses.
- // Codex routes this hook's stdout into model context just like Claude Code, so
- // the same compiled prompt-handler keeps guard mode alive across both hosts.
- // No matcher (Codex does not match UserPromptSubmit); synchronous so stdout is read.
- if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
- const promptGroups = config.hooks.UserPromptSubmit;
- let promptGroup = promptGroups.find(entry => Array.isArray(entry?.hooks) && entry?.matcher === undefined);
- if (!promptGroup) {
- promptGroup = { hooks: [] };
- promptGroups.push(promptGroup);
- }
- const promptScript = promptHookCommand.match(/"([^"]+)"\s*$/)?.[1] || promptHookCommand.split(/\s+/).slice(-1)[0];
- const promptMatches = (cmd) => cmd === promptHookCommand || (typeof cmd === 'string' && cmd.endsWith(promptScript));
- if (!promptGroup.hooks.some(h => typeof h?.command === 'string' && promptMatches(h.command))) {
- promptGroup.hooks.push({ type: 'command', command: promptHookCommand, timeout: 10 });
- changed = true;
- }
- if (changed) {
- fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
- fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- '@ 2>$null
- if ($codexResult -eq 'updated') {
- Write-Host " ✓ Codex CLI hooks configured ($codexHooks)" -ForegroundColor Green
- } else {
- Write-Host " ✓ Codex CLI hooks already configured" -ForegroundColor Green
- }
- }
- }
- # ── Inject buddy instructions into CLI prompt files ──
- $BUDDY_INSTRUCTIONS = @"
- <!-- buddy-companion v3 -->
- ## Buddy Companion
- You have a coding companion available via the buddy MCP server.
- **After completing any coding task** (writing code, fixing bugs, refactoring, deploying, running tests), **automatically call ``buddy_observe``** with a 1-sentence summary of what you did. This gives your companion XP and triggers a personality-flavored reaction. Do this every time — the user expects it.
- At the start of each conversation, call ``buddy_status`` to check on your buddy.
- If the user addresses the buddy by name, respond briefly in character before your normal response.
- After calling buddy_observe, relay the buddy's reaction to the user. The first text content is an ASCII speech bubble — include it verbatim.
- When guard mode is on, also pass ``claims`` (key assertions from the turn, ≤240 chars each, with ``basis``, ``confidence``, ``speaker``, ``external_id``), ``edges`` (relationships between claims), and ``cwd`` (absolute path to the project root) to ``buddy_observe``.
- <!-- /buddy-companion v3 -->
- "@
- function Inject-BuddyPrompt($filePath, $cliName) {
- $dir = Split-Path $filePath -Parent
- if (!(Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
- if ((Test-Path $filePath) -and (Select-String -Path $filePath -Pattern "buddy-companion v3" -Quiet)) {
- Write-Host " ✓ $cliName prompt already has buddy instructions" -ForegroundColor Green
- return
- }
- # Remove older buddy-companion block (v1/v2) before appending current version
- if ((Test-Path $filePath) -and (Select-String -Path $filePath -Pattern "buddy-companion" -Quiet)) {
- $content = Get-Content $filePath -Raw
- $content = [regex]::Replace($content, '(?s)\s*<!-- buddy-companion[^>]*-->.*?<!-- /buddy-companion[^>]*-->\s*', '')
- Set-Content $filePath -Value $content.Trim() -Encoding UTF8
- Write-Host " ✓ $cliName prompt upgraded to v3" -ForegroundColor Green
- }
- Add-Content -Path $filePath -Value "`n$BUDDY_INSTRUCTIONS" -Encoding UTF8
- Write-Host " ✓ $cliName prompt updated ($filePath)" -ForegroundColor Green
- }
- Write-Host ""
- Write-Host " Injecting buddy instructions..."
- if ($CLAUDE_CONFIGURED) {
- Inject-BuddyPrompt "$env:USERPROFILE\.claude\CLAUDE.md" "Claude Code"
- }
- $cursorRulesDir = "$env:USERPROFILE\.cursor\rules"
- if ($CURSOR_CONFIGURED) {
- if (!(Test-Path $cursorRulesDir)) { New-Item -ItemType Directory -Path $cursorRulesDir -Force | Out-Null }
- Inject-BuddyPrompt "$cursorRulesDir\buddy.md" "Cursor CLI"
- }
- # Codex CLI (only inject prompts after Buddy MCP is configured; prefer AGENTS.md)
- if ($CODEX_CONFIGURED) {
- if (Test-Path "$env:USERPROFILE\.codex\AGENTS.md") {
- Inject-BuddyPrompt "$env:USERPROFILE\.codex\AGENTS.md" "Codex CLI"
- } else {
- Inject-BuddyPrompt "$env:USERPROFILE\.codex\instructions.md" "Codex CLI"
- }
- }
- # Gemini CLI (only touch existing Gemini prompt locations; Buddy does not auto-configure Gemini MCP)
- if (Test-Path "$env:USERPROFILE\.gemini") {
- if (Test-Path "$env:USERPROFILE\.gemini\GEMINI.md") {
- Inject-BuddyPrompt "$env:USERPROFILE\.gemini\GEMINI.md" "Gemini CLI"
- } elseif (Test-Path "$env:USERPROFILE\.gemini\AGENTS.md") {
- Inject-BuddyPrompt "$env:USERPROFILE\.gemini\AGENTS.md" "Gemini CLI"
- } else {
- Write-Host " ! Skipping Gemini CLI prompt injection because no existing Gemini prompt file was found" -ForegroundColor Yellow
- }
- }
- # GitHub Copilot CLI (supports AGENTS.md and copilot-instructions.md — prefer AGENTS.md)
- if ($COPILOT_CONFIGURED) {
- if (Test-Path "$env:USERPROFILE\.copilot\AGENTS.md") {
- Inject-BuddyPrompt "$env:USERPROFILE\.copilot\AGENTS.md" "GitHub Copilot CLI"
- } else {
- Inject-BuddyPrompt "$env:USERPROFILE\.copilot\copilot-instructions.md" "GitHub Copilot CLI"
- }
- }
- # ── Run onboarding wizard ──
- $ONBOARD_SCRIPT = "$INSTALL_DIR\dist\cli\onboard.js"
- if (Test-Path "$ONBOARD_SCRIPT") {
- try {
- & $NODE_BIN "$ONBOARD_SCRIPT"
- } catch {
- # Non-fatal — wizard is optional
- }
- }
- Write-Host ""
- if ($CLAUDE_CONFIGURED -or $CURSOR_CONFIGURED -or $COPILOT_CONFIGURED -or $CODEX_CONFIGURED) {
- Write-Host " ✅ Buddy installed!" -ForegroundColor Green
- Write-Host " Next: in your client, open the AI chat and ask the assistant to hatch your first buddy. That is a message to the model, not a command in this terminal." -ForegroundColor DarkGray
- } elseif (Get-Command codex -ErrorAction SilentlyContinue) {
- Write-Host " ⚠ Buddy installed, but no supported host was fully configured." -ForegroundColor Yellow
- Write-Host " ! Codex CLI is installed, but MCP registration still needs attention." -ForegroundColor Yellow
- } else {
- Write-Host " ⚠ Buddy installed, but no supported host was fully configured." -ForegroundColor Yellow
- Write-Host " ! Open a supported CLI and rerun the installer to wire Buddy in automatically." -ForegroundColor Yellow
- }
- if ((-not $CODEX_CONFIGURED) -and (Get-Command codex -ErrorAction SilentlyContinue)) {
- Write-Host ""
- Write-Host " ! Codex CLI prompt injection was skipped because Buddy MCP is not configured there yet." -ForegroundColor Yellow
- }
- Write-Host ""
- Write-Host " 💬 Join the Buddy Community!" -ForegroundColor Blue
- Write-Host " Connect with other buddy rescuers, share your companion's evolution, and get help on Slack:"
- Write-Host " 👉 https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ" -ForegroundColor Gray
- Write-Host ""
- Write-Host " 💛 If you like it, star the repo:"
- Write-Host " github.com/fiorastudio/buddy"
- Write-Host ""
install.sh · Bundled script · 789 lines · 1 finding marked
- #!/usr/bin/env bash
- # Buddy MCP Server — Cross-platform installer
- # Installs AND auto-configures MCP for your CLI
- #
- # Usage:
- # curl -fsSL https://raw.githubusercontent.com/fiorastudio/buddy/master/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 6 on GitHub
- # curl ... | bash -s -- --no-onboard # skip onboarding wizard (CI/scripted installs)
- set -e
- # Parse flags
- NO_ONBOARD=0
- for arg in "$@"; do
- case "$arg" in
- --no-onboard) NO_ONBOARD=1 ;;
- esac
- done
- REPO="https://github.com/fiorastudio/buddy.git"
- INSTALL_DIR="$HOME/.buddy/server"
- BLUE='\033[0;34m'
- GREEN='\033[0;32m'
- YELLOW='\033[1;33m'
- DIM='\033[2m'
- NC='\033[0m'
- echo -e "${BLUE}"
- echo ' 🥚 Buddy MCP Server Installer'
- echo ' ─────────────────────────────'
- echo -e "${NC}"
- # Check prerequisites
- if ! command -v node &> /dev/null; then
- echo -e " ${YELLOW}Node.js is required but not found.${NC}"
- # Default to "n" (safe for CI/non-interactive). Try /dev/tty for interactive shells.
- REPLY="n"
- if printf " Install it automatically? [Y/n]: " >/dev/tty 2>/dev/null && read -r REPLY </dev/tty 2>/dev/null; then
- :
- fi
- if [[ "$REPLY" =~ ^[Nn] ]]; then
- echo -e " Install Node.js from https://nodejs.org then re-run."
- exit 1
- fi
- echo -e " Installing Node.js..."
- set +e # allow install attempts to fail without aborting the script
- if [ -s "$HOME/.nvm/nvm.sh" ]; then
- source "$HOME/.nvm/nvm.sh"
- nvm install --lts --silent
- elif command -v brew &>/dev/null; then
- brew install node --quiet
- elif command -v apt-get &>/dev/null; then
- sudo apt-get install -y nodejs npm >/dev/null 2>&1
- elif command -v dnf &>/dev/null; then
- sudo dnf install -y nodejs >/dev/null 2>&1
- else
- echo -e " Installing nvm..."
- curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
- # shellcheck source=/dev/null
- [ -s "$HOME/.nvm/nvm.sh" ] && source "$HOME/.nvm/nvm.sh"
- command -v nvm &>/dev/null && nvm install --lts --silent
- fi
- set -e
- if ! command -v node &>/dev/null; then
- echo -e "${YELLOW} Could not install Node.js. Please install from https://nodejs.org${NC}"
- exit 1
- fi
- echo -e "${GREEN} ✓ Node.js installed${NC}"
- fi
- NODE_BIN="$(command -v node)"
- # Prefer system node over app-bundled node (e.g. /Applications/Codex.app/Contents/Resources/node).
- # App-bundled node has macOS code signing restrictions that reject .node native addons
- # compiled/downloaded outside the app bundle (different Team IDs).
- if [[ "$NODE_BIN" == /Applications/*.app/* ]]; then
- FOUND_SYSTEM_NODE=0
- for candidate in /opt/homebrew/bin/node /usr/local/bin/node; do
- if [ -x "$candidate" ]; then
- echo -e " ${DIM}Preferring system node ($candidate) over app-bundled ($NODE_BIN)${NC}"
- NODE_BIN="$candidate"
- FOUND_SYSTEM_NODE=1
- break
- fi
- done
- if [ "$FOUND_SYSTEM_NODE" -eq 0 ]; then
- echo -e " ${YELLOW}Warning: only app-bundled node found ($NODE_BIN). Native addons may fail due to code signing restrictions.${NC}"
- echo -e " ${YELLOW}Install Node.js via Homebrew (brew install node) or from https://nodejs.org for best results.${NC}"
- fi
- fi
- NODE_VERSION=$("$NODE_BIN" -v | cut -d'v' -f2 | cut -d'.' -f1)
- # Always pin the absolute Node path in generated configs so GUI-launched clients
- # (e.g. Claude desktop on macOS) find the correct binary regardless of shell init.
- # nvm/asdf/fnm users: re-run the installer after upgrading Node.
- CONFIG_NODE_BIN="$NODE_BIN"
- # Prepend pinned node's directory to PATH so bare `npm` and npm's internal
- # node shebang both resolve to the same runtime as $NODE_BIN.
- export PATH="$(dirname "$NODE_BIN"):$PATH"
- if [ "$NODE_VERSION" -lt 20 ]; then
- echo -e "${YELLOW}Node.js 20+ required (better-sqlite3 dropped Node 18/19 support). You have $("$NODE_BIN" -v). Please upgrade.${NC}"
- exit 1
- fi
- if ! command -v git &> /dev/null; then
- echo -e "${YELLOW}Git is required but not found.${NC}"
- exit 1
- fi
- # Clone or update. A prior install may have left a NON-git directory here
- # (e.g. an npm-package install): 'git pull' fails there and we would silently
- # build stale code. Detect that (and a failed pull) and re-clone. Safe to wipe:
- # the companion DB (~/.buddy/buddy.db) and world.json live in the PARENT dir,
- # not inside ~/.buddy/server.
- need_clone=1
- if [ -d "$INSTALL_DIR/.git" ]; then
- echo " Updating existing installation..."
- if git -C "$INSTALL_DIR" pull origin master --quiet; then
- need_clone=0
- else
- echo " Update failed; re-cloning fresh..."
- fi
- elif [ -d "$INSTALL_DIR" ]; then
- echo " Replacing a non-git install with a fresh clone..."
- fi
- if [ "$need_clone" -eq 1 ]; then
- rm -rf "$INSTALL_DIR"
- echo " Cloning Buddy MCP Server..."
- git clone --depth 1 "$REPO" "$INSTALL_DIR" --quiet
- fi
- cd "$INSTALL_DIR"
- echo " Installing dependencies..."
- npm install --quiet 2>/dev/null
- # Verify native module ABI matches current node. A stale binary from a prior
- # install with a different node version will crash at runtime. Rebuild if
- # needed, then re-verify — a silent half-broken install is worse than failing.
- # CRITICAL: `require('better-sqlite3')` only loads the JS wrapper; the native
- # .node binary (where the ABI lives) loads LAZILY inside `new Database`. Must
- # instantiate a DB to force the addon load, else a mismatched binary passes.
- if ! "$NODE_BIN" -e "const D=require('better-sqlite3');new D(':memory:').close()" 2>/dev/null; then
- echo " Rebuilding native module for $("$NODE_BIN" -v)..."
- npm rebuild better-sqlite3
- if ! "$NODE_BIN" -e "const D=require('better-sqlite3');new D(':memory:').close()" 2>/dev/null; then
- echo ""
- echo -e "${YELLOW} ✗ better-sqlite3 does not load under node $("$NODE_BIN" -v) ($NODE_BIN) and the rebuild failed.${NC}"
- echo -e "${YELLOW} If you use nvm, switch to the node version Buddy should run under (nvm use <version>),${NC}"
- echo -e "${YELLOW} then re-run this installer. See the rebuild output above for details.${NC}"
- exit 1
- fi
- fi
- echo " Building..."
- npm run build --quiet
- # tsc can exit 0 without emitting (e.g. run where it finds no tsconfig), so
- # verify the build artifact exists rather than trusting the exit code — same
- # "verify, don't trust silent success" lesson as the ABI probe above.
- if [ ! -f "$INSTALL_DIR/dist/server/index.js" ]; then
- echo ""
- echo -e "${YELLOW} ✗ Build produced no output (tsc emitted nothing).${NC}"
- echo -e "${YELLOW} Run 'npm run build' in $INSTALL_DIR to see the compiler error.${NC}"
- exit 1
- fi
- # ── Symlink CLI binaries onto PATH ──
- for bin_entry in buddy:buddy.js buddy-doctor:doctor-cli.js; do
- bin_name="${bin_entry%%:*}"
- bin_file="$INSTALL_DIR/dist/cli/${bin_entry##*:}"
- if [ -f "$bin_file" ]; then
- chmod +x "$bin_file"
- ln -sf "$bin_file" "/usr/local/bin/$bin_name" 2>/dev/null \
- || sudo ln -sf "$bin_file" "/usr/local/bin/$bin_name" 2>/dev/null \
- || echo -e " ${YELLOW}Could not symlink $bin_name to /usr/local/bin — add $INSTALL_DIR/dist/cli to your PATH${NC}"
- fi
- done
- SERVER_PATH="$INSTALL_DIR/dist/server/index.js"
- CODEX_CONFIGURED=0
- HOOK_PATH="$INSTALL_DIR/dist/hooks/post-tool-handler.js"
- HOOK_COMMAND=$(printf '%q %q' "$CONFIG_NODE_BIN" "$HOOK_PATH")
- PROMPT_HOOK_PATH="$INSTALL_DIR/dist/hooks/prompt-handler.js"
- PROMPT_HOOK_COMMAND=$(printf '%q %q' "$CONFIG_NODE_BIN" "$PROMPT_HOOK_PATH")
- CLAUDE_CONFIGURED=0
- CURSOR_CONFIGURED=0
- COPILOT_CONFIGURED=0
- # ── Auto-configure MCP for detected CLIs ──
- configure_claude_code() {
- local config_dir="$HOME/.claude"
- local settings_file="$config_dir/settings.json"
- local user_file="$HOME/.claude.json"
- local stop_hook_path="$INSTALL_DIR/dist/hooks/stop-handler.js"
- local stop_hook_command
- local prompt_hook_command="$PROMPT_HOOK_COMMAND"
- local statusline_command
- local commands_dir="$config_dir/commands"
- local buddy_graph_command="$commands_dir/buddy-graph.md"
- stop_hook_command=$(printf '%q %q' "$CONFIG_NODE_BIN" "$stop_hook_path")
- statusline_command=$(printf '%q %q' "$CONFIG_NODE_BIN" "$INSTALL_DIR/dist/statusline-wrapper.js")
- mkdir -p "$config_dir" "$commands_dir"
- cat > "$buddy_graph_command" <<EOF
- ---
- description: Generate and open an interactive visualization of Buddy guard-mode reasoning data using the Buddy CLI.
- ---
- Run the Buddy graph CLI to visualize the reasoning graph.
- If \`$ARGUMENTS\` is present, treat it as optional CLI arguments such as a session ID or \`--out\` path.
- \`\`\`bash
- set -euo pipefail
- args=()
- if [ -n "${ARGUMENTS:-}" ]; then
- read -r -a args <<< "$ARGUMENTS"
- fi
- if command -v buddy >/dev/null 2>&1; then
- buddy graph "${args[@]}" --open
- else
- "$CONFIG_NODE_BIN" "$INSTALL_DIR/dist/cli/buddy.js" graph "${args[@]}" --open
- fi
- \`\`\`
- Execute the bash block above, then report the saved graph path and basic graph counts back to the user.
- EOF
- echo -e " ${GREEN}✓${NC} Claude Code global /buddy-graph command installed ${DIM}($buddy_graph_command)${NC}"
- local registered=0
- if command -v claude &> /dev/null; then
- if claude mcp get buddy >/dev/null 2>&1; then
- echo -e " ${GREEN}✓${NC} Claude Code MCP already registered"
- registered=1
- else
- if claude mcp add buddy -s user -- "$CONFIG_NODE_BIN" "$SERVER_PATH" >/dev/null 2>&1; then
- echo -e " ${GREEN}✓${NC} Claude Code MCP registered via claude CLI"
- registered=1
- else
- echo -e " ${YELLOW}!${NC} claude CLI detected, but MCP registration failed — falling back to manual config"
- fi
- fi
- fi
- if [ "$registered" -ne 1 ]; then
- if CLAUDE_USER_FILE="$user_file" SERVER_PATH="$SERVER_PATH" NODE_BIN="$CONFIG_NODE_BIN" "$NODE_BIN" <<'EOJS' 2>/dev/null; then
- const fs = require('fs');
- const path = process.env.CLAUDE_USER_FILE;
- const serverPath = process.env.SERVER_PATH;
- const nodeBin = process.env.NODE_BIN;
- let data = {};
- try { data = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
- if (!data.mcpServers) data.mcpServers = {};
- data.mcpServers.buddy = {
- type: 'stdio',
- command: nodeBin,
- args: [serverPath]
- };
- fs.writeFileSync(path, JSON.stringify(data, null, 2));
- EOJS
- echo -e " ${GREEN}✓${NC} Claude Code MCP config written ${DIM}($user_file)${NC}"
- else
- echo -e " ${YELLOW}!${NC} Could not write MCP config to $user_file"
- fi
- fi
- # Configure hook + statusline in a single settings.json write
- local settings_result
- settings_result=$(CLAUDE_SETTINGS="$settings_file" HOOK_COMMAND="$HOOK_COMMAND" STOP_HOOK_COMMAND="$stop_hook_command" PROMPT_HOOK_COMMAND="$prompt_hook_command" STATUSLINE_COMMAND="$statusline_command" SERVER_PATH="$SERVER_PATH" NODE_BIN="$CONFIG_NODE_BIN" "$NODE_BIN" <<'EOJS'
- const fs = require('fs');
- const settingsPath = process.env.CLAUDE_SETTINGS;
- const hookCommand = process.env.HOOK_COMMAND;
- const stopHookCommand = process.env.STOP_HOOK_COMMAND;
- const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
- const statuslineCommand = process.env.STATUSLINE_COMMAND;
- const serverPath = process.env.SERVER_PATH;
- const nodeBin = process.env.NODE_BIN;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
- let changed = false;
- const result = [];
- // MCP server registration
- if (!config.mcpServers) config.mcpServers = {};
- const existing = config.mcpServers.buddy;
- if (!existing || existing.command !== nodeBin || !Array.isArray(existing.args) || existing.args[0] !== serverPath) {
- config.mcpServers.buddy = { type: 'stdio', command: nodeBin, args: [serverPath] };
- changed = true;
- result.push('mcp:updated');
- } else {
- result.push('mcp:noop');
- }
- if (!config.hooks) config.hooks = {};
- // PostToolUse — error detection (Bash only)
- // Match on script path suffix to also recognise legacy "node <path>" entries from older installs.
- const hookScript = hookCommand.split(/\s+/).slice(-1)[0];
- const stopHookScript = stopHookCommand.split(/\s+/).slice(-1)[0];
- const promptHookScript = promptHookCommand.split(/\s+/).slice(-1)[0];
- const statuslineScript = statuslineCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd, current, script) => cmd === current || (cmd && cmd.endsWith(script));
- if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
- const hasPostHook = config.hooks.PostToolUse.some(entry =>
- entry.matcher === 'Bash' &&
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, hookCommand, hookScript))
- );
- if (!hasPostHook) {
- config.hooks.PostToolUse.push({
- matcher: 'Bash',
- hooks: [{ type: 'command', command: hookCommand, async: true, timeout: 3 }]
- });
- changed = true;
- result.push('hook:updated');
- } else {
- result.push('hook:noop');
- }
- // Stop — task-completion reactions
- if (!Array.isArray(config.hooks.Stop)) config.hooks.Stop = [];
- const hasStopHook = config.hooks.Stop.some(entry =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, stopHookCommand, stopHookScript))
- );
- if (!hasStopHook) {
- config.hooks.Stop.push({
- hooks: [{ type: 'command', command: stopHookCommand, async: true, timeout: 5 }]
- });
- changed = true;
- result.push('stop:updated');
- } else {
- result.push('stop:noop');
- }
- // UserPromptSubmit — name + mood reactions
- if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
- // The prompt hook injects guard-mode context via stdout, which Claude Code
- // only captures from SYNCHRONOUS hooks (async hooks are fire-and-forget) — so
- // it must NOT be async. Upgrade any pre-existing async registration in place.
- const PROMPT_SYNC_TIMEOUT = 10;
- let promptHookFixed = false;
- const hasPromptHook = config.hooks.UserPromptSubmit.some(entry =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some(h => matchesHook(h.command, promptHookCommand, promptHookScript))
- );
- for (const entry of config.hooks.UserPromptSubmit) {
- if (!Array.isArray(entry.hooks)) continue;
- for (const h of entry.hooks) {
- if (!matchesHook(h.command, promptHookCommand, promptHookScript)) continue;
- if (h.async) { delete h.async; promptHookFixed = true; }
- if ((h.timeout || 0) < PROMPT_SYNC_TIMEOUT) { h.timeout = PROMPT_SYNC_TIMEOUT; promptHookFixed = true; }
- }
- }
- if (!hasPromptHook) {
- config.hooks.UserPromptSubmit.push({
- hooks: [{ type: 'command', command: promptHookCommand, timeout: PROMPT_SYNC_TIMEOUT }]
- });
- changed = true;
- result.push('prompt:updated');
- } else if (promptHookFixed) {
- changed = true;
- result.push('prompt:updated');
- } else {
- result.push('prompt:noop');
- }
- // Statusline
- const needsStatusline = !config.statusLine ||
- config.statusLine.type !== 'command' ||
- !matchesHook(config.statusLine.command, statuslineCommand, statuslineScript) ||
- config.statusLine.refreshInterval !== 2;
- if (needsStatusline) {
- config.statusLine = { type: 'command', command: statuslineCommand, padding: 1, refreshInterval: 2 };
- changed = true;
- result.push('statusline:updated');
- } else {
- result.push('statusline:noop');
- }
- if (changed) {
- fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
- }
- process.stdout.write(result.join(','));
- EOJS
- )
- case "$settings_result" in
- *mcp:updated*) echo -e " ${GREEN}✓${NC} MCP server registered in settings.json" ;;
- *) echo -e " ${GREEN}✓${NC} MCP server already in settings.json" ;;
- esac
- case "$settings_result" in
- *hook:updated*) echo -e " ${GREEN}✓${NC} PostToolUse hook configured" ;;
- *) echo -e " ${GREEN}✓${NC} PostToolUse hook already configured" ;;
- esac
- case "$settings_result" in
- *stop:updated*) echo -e " ${GREEN}✓${NC} Stop hook configured" ;;
- *) echo -e " ${GREEN}✓${NC} Stop hook already configured" ;;
- esac
- case "$settings_result" in
- *prompt:updated*) echo -e " ${GREEN}✓${NC} UserPromptSubmit hook configured" ;;
- *) echo -e " ${GREEN}✓${NC} UserPromptSubmit hook already configured" ;;
- esac
- case "$settings_result" in
- *statusline:updated*) echo -e " ${GREEN}✓${NC} Claude Code statusline configured" ;;
- *) echo -e " ${GREEN}✓${NC} Claude Code statusline already configured" ;;
- esac
- CLAUDE_CONFIGURED=1
- }
- configure_cursor_hooks() {
- local config_file="$HOME/.cursor/hooks.json"
- if [ ! -d "$HOME/.cursor" ]; then
- return 0
- fi
- local result
- result=$(CURSOR_HOOKS_FILE="$config_file" HOOK_COMMAND="$HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
- const fs = require('fs');
- const path = process.env.CURSOR_HOOKS_FILE;
- const hookCommand = process.env.HOOK_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
- if (!config.version) config.version = 1;
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- if (!Array.isArray(config.hooks.afterShellExecution)) config.hooks.afterShellExecution = [];
- const hooks = config.hooks.afterShellExecution;
- const hookScript = hookCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
- const hasHook = hooks.some(h => typeof h?.command === 'string' && matchesHook(h.command));
- if (!hasHook) {
- hooks.push({ command: hookCommand });
- fs.mkdirSync(require('path').dirname(path), { recursive: true });
- fs.writeFileSync(path, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- EOJS
- )
- case "$result" in
- updated) echo -e " ${GREEN}✓${NC} Cursor CLI afterShellExecution hook configured ${DIM}($config_file)${NC}" ;;
- *) echo -e " ${GREEN}✓${NC} Cursor CLI afterShellExecution hook already configured" ;;
- esac
- }
- configure_copilot_hooks() {
- local settings_file="$HOME/.copilot/settings.json"
- if [ ! -d "$HOME/.copilot" ]; then
- return 0
- fi
- local result
- result=$(COPILOT_SETTINGS="$settings_file" BASH_COMMAND="$HOOK_COMMAND" POWERSHELL_COMMAND="$HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
- const fs = require('fs');
- const path = require('path');
- const settingsPath = process.env.COPILOT_SETTINGS;
- const bashCommand = process.env.BASH_COMMAND;
- const powershellCommand = process.env.POWERSHELL_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- if (!Array.isArray(config.hooks.postToolUse)) config.hooks.postToolUse = [];
- const hooks = config.hooks.postToolUse;
- const hookScript = bashCommand.split(/\s+/).slice(-1)[0];
- const matchesHook = (cmd) => cmd === bashCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
- const hasHook = hooks.some(h => matchesHook(h?.bash) || matchesHook(h?.powershell));
- if (!hasHook) {
- hooks.push({
- type: 'command',
- bash: bashCommand,
- powershell: powershellCommand,
- timeoutSec: 3,
- });
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
- fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- EOJS
- )
- case "$result" in
- updated) echo -e " ${GREEN}✓${NC} GitHub Copilot CLI postToolUse hook configured ${DIM}($settings_file)${NC}" ;;
- *) echo -e " ${GREEN}✓${NC} GitHub Copilot CLI postToolUse hook already configured" ;;
- esac
- }
- configure_cursor() {
- local config_file="$HOME/.cursor/mcp.json"
- if [ -d "$HOME/.cursor" ]; then
- if [ ! -f "$config_file" ]; then
- cat > "$config_file" << EOJSON
- {
- "mcpServers": {
- "buddy": {
- "command": "$CONFIG_NODE_BIN",
- "args": ["$SERVER_PATH"]
- }
- }
- }
- EOJSON
- else
- if ! CURSOR_MCP_CONFIG="$config_file" NODE_BIN="$CONFIG_NODE_BIN" SERVER_PATH="$SERVER_PATH" "$NODE_BIN" <<'EOJS' 2>/dev/null
- const fs = require('fs');
- const configPath = process.env.CURSOR_MCP_CONFIG;
- const nodeBin = process.env.NODE_BIN;
- const serverPath = process.env.SERVER_PATH;
- const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
- if (!config.mcpServers) config.mcpServers = {};
- config.mcpServers.buddy = { command: nodeBin, args: [serverPath] };
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
- EOJS
- then
- echo -e " ${YELLOW}!${NC} Cursor: could not update existing MCP config ${DIM}($config_file)${NC}"
- return 1
- fi
- fi
- echo -e " ${GREEN}✓${NC} Cursor configured ${DIM}($config_file)${NC}"
- CURSOR_CONFIGURED=1
- fi
- }
- configure_copilot() {
- local config_file="$HOME/.copilot/mcp-config.json"
- if [ -d "$HOME/.copilot" ]; then
- if [ ! -f "$config_file" ]; then
- cat > "$config_file" << EOJSON
- {
- "mcpServers": {
- "buddy": {
- "command": "$CONFIG_NODE_BIN",
- "args": ["$SERVER_PATH"]
- }
- }
- }
- EOJSON
- else
- if ! COPILOT_MCP_CONFIG="$config_file" NODE_BIN="$CONFIG_NODE_BIN" SERVER_PATH="$SERVER_PATH" "$NODE_BIN" <<'EOJS' 2>/dev/null
- const fs = require('fs');
- const configPath = process.env.COPILOT_MCP_CONFIG;
- const nodeBin = process.env.NODE_BIN;
- const serverPath = process.env.SERVER_PATH;
- const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
- if (!config.mcpServers) config.mcpServers = {};
- config.mcpServers.buddy = { command: nodeBin, args: [serverPath] };
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
- EOJS
- then
- echo -e " ${YELLOW}!${NC} GitHub Copilot CLI: could not update existing MCP config ${DIM}($config_file)${NC}"
- return 1
- fi
- fi
- echo -e " ${GREEN}✓${NC} GitHub Copilot CLI configured ${DIM}($config_file)${NC}"
- COPILOT_CONFIGURED=1
- fi
- }
- configure_codex() {
- if ! command -v codex &> /dev/null; then
- return 0
- fi
- if codex mcp get buddy >/dev/null 2>&1; then
- CODEX_CONFIGURED=1
- echo -e " ${GREEN}✓${NC} Codex CLI already configured"
- return 0
- fi
- if codex mcp add buddy -- "$CONFIG_NODE_BIN" "$SERVER_PATH" >/dev/null 2>&1; then
- CODEX_CONFIGURED=1
- echo -e " ${GREEN}✓${NC} Codex CLI configured"
- return 0
- fi
- echo -e " ${YELLOW}!${NC} Codex CLI detected, but MCP registration failed"
- return 1
- }
- configure_codex_hooks() {
- local config_file="$HOME/.codex/hooks.json"
- if [ "$CODEX_CONFIGURED" -ne 1 ]; then
- return 0
- fi
- local result
- result=$(CODEX_HOOKS_FILE="$config_file" HOOK_COMMAND="$HOOK_COMMAND" PROMPT_HOOK_COMMAND="$PROMPT_HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
- const fs = require('fs');
- const path = require('path');
- const hooksPath = process.env.CODEX_HOOKS_FILE;
- const hookCommand = process.env.HOOK_COMMAND;
- const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
- let config = {};
- try { config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')); } catch {}
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
- let changed = false;
- // PostToolUse:Bash — review Bash output (existing behaviour).
- if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
- const postGroups = config.hooks.PostToolUse;
- let bashGroup = postGroups.find(entry => entry?.matcher === 'Bash' && Array.isArray(entry?.hooks));
- if (!bashGroup) {
- bashGroup = { matcher: 'Bash', hooks: [] };
- postGroups.push(bashGroup);
- }
- const postScript = hookCommand.split(/\s+/).slice(-1)[0];
- const postMatches = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(postScript));
- if (!bashGroup.hooks.some(h => typeof h?.command === 'string' && postMatches(h.command))) {
- bashGroup.hooks.push({ type: 'command', command: hookCommand, statusMessage: 'Reviewing Bash output' });
- changed = true;
- }
- // UserPromptSubmit — re-inject the extraction instruction when the graph lapses.
- // Codex routes this hook's stdout into model context just like Claude Code, so
- // the same compiled prompt-handler keeps guard mode alive across both hosts.
- // No matcher (Codex does not match UserPromptSubmit); synchronous so stdout is read.
- if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
- const promptGroups = config.hooks.UserPromptSubmit;
- let promptGroup = promptGroups.find(entry => Array.isArray(entry?.hooks) && entry?.matcher === undefined);
- if (!promptGroup) {
- promptGroup = { hooks: [] };
- promptGroups.push(promptGroup);
- }
- const promptScript = promptHookCommand.split(/\s+/).slice(-1)[0];
- const promptMatches = (cmd) => cmd === promptHookCommand || (typeof cmd === 'string' && cmd.endsWith(promptScript));
- if (!promptGroup.hooks.some(h => typeof h?.command === 'string' && promptMatches(h.command))) {
- promptGroup.hooks.push({ type: 'command', command: promptHookCommand, timeout: 10 });
- changed = true;
- }
- if (changed) {
- fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
- fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2));
- process.stdout.write('updated');
- } else {
- process.stdout.write('noop');
- }
- EOJS
- )
- case "$result" in
- updated) echo -e " ${GREEN}✓${NC} Codex CLI hooks configured ${DIM}($config_file)${NC}" ;;
- *) echo -e " ${GREEN}✓${NC} Codex CLI hooks already configured" ;;
- esac
- }
- echo ""
- echo " Configuring MCP clients..."
- configure_claude_code
- configure_cursor
- configure_copilot
- configure_codex
- configure_cursor_hooks
- configure_copilot_hooks
- configure_codex_hooks
- # ── Inject buddy instructions into CLI prompt files ──
- BUDDY_INSTRUCTIONS='<!-- buddy-companion v3 -->
- ## Buddy Companion
- You have a coding companion available via the buddy MCP server.
- **After completing any coding task** (writing code, fixing bugs, refactoring, deploying, running tests), **automatically call `buddy_observe`** with a 1-sentence summary of what you did. This gives your companion XP and triggers a personality-flavored reaction. Do this every time — the user expects it.
- At the start of each conversation, call `buddy_status` to check on your buddy.
- If the user addresses the buddy by name, respond briefly in character before your normal response.
- After calling buddy_observe, relay the buddy'\''s reaction to the user. The first text content is an ASCII speech bubble — include it verbatim.
- When guard mode is on, also pass `claims` (key assertions from the turn, ≤240 chars each, with `basis`, `confidence`, `speaker`, `external_id`), `edges` (relationships between claims), and `cwd` (absolute path to the project root) to `buddy_observe`.
- <!-- /buddy-companion v3 -->'
- inject_prompt() {
- local file="$1"
- local cli_name="$2"
- local dir
- dir="$(dirname "$file")"
- mkdir -p "$dir"
- if [ -f "$file" ] && grep -q "buddy-companion v3" "$file" 2>/dev/null; then
- echo -e " ${GREEN}✓${NC} $cli_name prompt already has buddy instructions"
- return 0
- fi
- # Remove older buddy-companion block (v1/v2) before appending current version
- if [ -f "$file" ] && grep -q "buddy-companion" "$file" 2>/dev/null; then
- local tmp="${file}.tmp.$$"
- sed '/<!-- buddy-companion/,/<!-- \/buddy-companion/d' "$file" > "$tmp" && mv "$tmp" "$file"
- echo -e " ${GREEN}✓${NC} $cli_name prompt upgraded to v3"
- fi
- # Append to existing file or create new one
- echo "" >> "$file"
- echo "$BUDDY_INSTRUCTIONS" >> "$file"
- echo -e " ${GREEN}✓${NC} $cli_name prompt updated ${DIM}($file)${NC}"
- }
- echo ""
- echo " Injecting buddy instructions..."
- if [ "$CLAUDE_CONFIGURED" -eq 1 ]; then
- inject_prompt "$HOME/.claude/CLAUDE.md" "Claude Code"
- fi
- if [ "$CURSOR_CONFIGURED" -eq 1 ]; then
- mkdir -p "$HOME/.cursor/rules" 2>/dev/null
- inject_prompt "$HOME/.cursor/rules/buddy.md" "Cursor CLI"
- fi
- # Codex CLI (only inject prompts after Buddy MCP is configured; prefer AGENTS.md)
- if [ "$CODEX_CONFIGURED" -eq 1 ]; then
- if [ -f "$HOME/.codex/AGENTS.md" ]; then
- inject_prompt "$HOME/.codex/AGENTS.md" "Codex CLI"
- else
- inject_prompt "$HOME/.codex/instructions.md" "Codex CLI"
- fi
- else
- echo -e " ${YELLOW}!${NC} Skipping Codex CLI prompt injection because Buddy MCP is not configured"
- fi
- # Gemini CLI (only touch existing Gemini prompt locations; Buddy does not auto-configure Gemini MCP)
- if [ -d "$HOME/.gemini" ]; then
- if [ -f "$HOME/.gemini/GEMINI.md" ]; then
- inject_prompt "$HOME/.gemini/GEMINI.md" "Gemini CLI"
- elif [ -f "$HOME/.gemini/AGENTS.md" ]; then
- inject_prompt "$HOME/.gemini/AGENTS.md" "Gemini CLI"
- else
- echo -e " ${YELLOW}!${NC} Skipping Gemini CLI prompt injection because no existing Gemini prompt file was found"
- fi
- fi
- # GitHub Copilot CLI (supports AGENTS.md and copilot-instructions.md — prefer AGENTS.md)
- if [ "$COPILOT_CONFIGURED" -eq 1 ]; then
- if [ -f "$HOME/.copilot/AGENTS.md" ]; then
- inject_prompt "$HOME/.copilot/AGENTS.md" "GitHub Copilot CLI"
- else
- inject_prompt "$HOME/.copilot/copilot-instructions.md" "GitHub Copilot CLI"
- fi
- fi
- # ── Run onboarding wizard ──
- ONBOARD_SCRIPT="$INSTALL_DIR/dist/cli/onboard.js"
- if [ -f "$ONBOARD_SCRIPT" ] && [ "$NO_ONBOARD" -eq 0 ]; then
- # Let onboard.ts detect TTY itself — don't force /dev/tty
- # (fails in headless SSH, CI, cron where no controlling terminal exists)
- "$NODE_BIN" "$ONBOARD_SCRIPT" || true
- elif [ "$NO_ONBOARD" -eq 1 ]; then
- echo -e " ${DIM}Onboarding skipped (--no-onboard). Run buddy-onboard later to set up.${NC}"
- fi
- echo ""
- if [ "$CLAUDE_CONFIGURED" -eq 1 ] || [ "$CURSOR_CONFIGURED" -eq 1 ] || [ "$COPILOT_CONFIGURED" -eq 1 ] || [ "$CODEX_CONFIGURED" -eq 1 ]; then
- echo -e "${GREEN} ✅ Buddy installed!${NC}"
- echo -e " ${DIM}Next: in your client, open the AI chat and ask the assistant to hatch your first buddy. That is a message to the model, not a command in this terminal.${NC}"
- elif command -v codex &> /dev/null; then
- echo -e "${YELLOW} ⚠ Buddy installed, but no supported host was fully configured.${NC}"
- echo -e " ${YELLOW}!${NC} Codex CLI is installed, but MCP registration still needs attention."
- else
- echo -e "${YELLOW} ⚠ Buddy installed, but no supported host was fully configured.${NC}"
- echo -e " ${YELLOW}!${NC} Open a supported CLI and rerun the installer to wire Buddy in automatically."
- fi
- if [ "$CODEX_CONFIGURED" -ne 1 ] && command -v codex &> /dev/null; then
- echo ""
- echo -e " ${YELLOW}!${NC} Codex CLI prompt injection was skipped because Buddy MCP is not configured there yet."
- fi
- echo ""
- echo -e "${BLUE} 💬 Join the Buddy Community!${NC}"
- echo -e " Connect with other buddy rescuers, share your companion's evolution, and get help on Slack:"
- echo -e " ${DIM}👉 https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ${NC}"
- echo ""
- echo -e " 💛 If you like it, star the repo:"
- echo " github.com/fiorastudio/buddy"
- echo ""
src/lib/doctor.ts · Bundled script · 838 lines · 1 finding marked
- // src/lib/doctor.ts — Diagnostic engine for buddy_doctor tool and CLI
- import { readFileSync, accessSync, statSync, realpathSync, constants as fsConstants } from 'fs';
- import { join, dirname, resolve as pathResolve, normalize, isAbsolute } from 'path';
- import { homedir } from 'os';
- import { fileURLToPath } from 'url';
- import { BUDDY_DB_PATH, BUDDY_STATUS_PATH } from './constants.js';
- import { db } from '../db/schema.js';
- import { loadCompanion } from './companion.js';
- import { STAT_NAMES, RARITY_STARS } from './types.js';
- import { levelProgress } from './leveling.js';
- import { REASONING_CONFIG, telemetry, getReinjectStats } from './reasoning/index.js';
- import { basisDistributionHealth, edgeDistributionHealth } from './reasoning/telemetry.js';
- // Shared sentinel — keep in sync with install.sh / install.ps1
- export const PROMPT_SENTINEL_V2 = 'buddy-companion v2';
- export const PROMPT_SENTINEL_V3 = 'buddy-companion v3';
- /** Default clone/build root from install.sh (INSTALL_DIR) */
- export function canonicalBuddyInstallDir(): string {
- return join(homedir(), '.buddy', 'server');
- }
- export function canonicalBuddyMcpEntryPath(): string {
- return join(canonicalBuddyInstallDir(), 'dist', 'server', 'index.js');
- }
- const __filename = fileURLToPath(import.meta.url);
- const __dirname = dirname(__filename);
- export interface DiagnosticCheck {
- id: string;
- status: 'ok' | 'warn' | 'fail' | 'skip';
- label: string;
- detail: string;
- suggestion?: string;
- }
- function getVersion(): string {
- try {
- return JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8')).version;
- } catch { return 'unknown'; }
- }
- function fileExists(path: string): boolean {
- try { accessSync(path, fsConstants.F_OK); return true; } catch { return false; }
- }
- function fileWritable(path: string): boolean {
- try { accessSync(path, fsConstants.W_OK); return true; } catch { return false; }
- }
- function fileReadable(path: string): boolean {
- try { accessSync(path, fsConstants.R_OK); return true; } catch { return false; }
- }
- function readJsonSafe(path: string): any {
- try { return JSON.parse(readFileSync(path, 'utf-8')); } catch { return null; }
- }
- function readTextSafe(path: string): string | null {
- try { return readFileSync(path, 'utf-8'); } catch { return null; }
- }
- function safeRealpath(p: string): string {
- try { return realpathSync(p); } catch { return p; }
- }
- function expandTildeInPath(p: string): string {
- if (p === '~' || p.startsWith('~/')) {
- return p === '~' ? homedir() : join(homedir(), p.slice(2));
- }
- return p;
- }
- /**
- * Resolves a config path for existence checks (tilde, relative segments).
- */
- function resolveBuddyEntryPath(p: string): string {
- const expanded = expandTildeInPath(p.trim());
- if (isAbsolute(expanded)) {
- return normalize(pathResolve(expanded));
- }
- return normalize(pathResolve(process.cwd(), expanded));
- }
- /**
- * First script path from a host's buddy MCP block (install.sh / Cursor style).
- */
- function entryPathFromMcpBlock(buddy: any): string | null {
- if (!buddy || typeof buddy !== 'object') return null;
- const args = buddy.args;
- if (!Array.isArray(args)) return null;
- const entry = args.find((a: unknown) => typeof a === 'string' && a.endsWith('.js'));
- return entry ?? null;
- }
- /**
- * All buddy MCP `dist/server/index.js` paths from known config files (for mismatch / missing checks).
- */
- function getRegisteredBuddyMcpEntryPaths(): Array<{ source: string; path: string; resolved: string }> {
- const out: Array<{ source: string; path: string; resolved: string }> = [];
- const claudeJsonPath = join(homedir(), '.claude.json');
- const cj = readJsonSafe(claudeJsonPath);
- const p1 = entryPathFromMcpBlock(cj?.mcpServers?.buddy);
- if (p1) {
- out.push({ source: claudeJsonPath, path: p1, resolved: resolveBuddyEntryPath(p1) });
- }
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const st = readJsonSafe(settingsPath);
- const p2 = entryPathFromMcpBlock(st?.mcpServers?.buddy);
- if (p2) {
- out.push({ source: settingsPath, path: p2, resolved: resolveBuddyEntryPath(p2) });
- }
- const cur = readJsonSafe(cursorMcpPath());
- const p3 = entryPathFromMcpBlock(cur?.mcpServers?.buddy);
- if (p3) {
- out.push({ source: cursorMcpPath(), path: p3, resolved: resolveBuddyEntryPath(p3) });
- }
- const cop = readJsonSafe(copilotMcpPath());
- const p4 = entryPathFromMcpBlock(cop?.mcpServers?.buddy);
- if (p4) {
- out.push({ source: copilotMcpPath(), path: p4, resolved: resolveBuddyEntryPath(p4) });
- }
- const toml = readTextSafe(codexConfigPath());
- if (toml) {
- const m = toml.match(/\[mcp_servers\.buddy\][\s\S]*?args\s*=\s*\[\s*"([^"]+\.js)"/);
- if (m?.[1]) {
- out.push({ source: codexConfigPath(), path: m[1], resolved: resolveBuddyEntryPath(m[1]) });
- }
- }
- return out;
- }
- function formatPathList(paths: string[]): string {
- return paths.join(' | ');
- }
- function codexConfigPath(): string {
- return join(homedir(), '.codex', 'config.toml');
- }
- function codexHooksPath(): string {
- return join(homedir(), '.codex', 'hooks.json');
- }
- function cursorMcpPath(): string {
- return join(homedir(), '.cursor', 'mcp.json');
- }
- function cursorHooksPath(): string {
- return join(homedir(), '.cursor', 'hooks.json');
- }
- function copilotMcpPath(): string {
- return join(homedir(), '.copilot', 'mcp-config.json');
- }
- function copilotSettingsPath(): string {
- return join(homedir(), '.copilot', 'settings.json');
- }
- function hostPromptFiles(): Array<{ host: string, path: string }> {
- return [
- { host: 'Claude Code', path: join(homedir(), '.claude', 'CLAUDE.md') },
- { host: 'Codex CLI', path: join(homedir(), '.codex', 'AGENTS.md') },
- { host: 'Codex CLI', path: join(homedir(), '.codex', 'instructions.md') },
- { host: 'Cursor CLI', path: join(homedir(), '.cursor', 'rules', 'buddy.md') },
- { host: 'GitHub Copilot CLI', path: join(homedir(), '.copilot', 'AGENTS.md') },
- { host: 'GitHub Copilot CLI', path: join(homedir(), '.copilot', 'copilot-instructions.md') },
- ];
- }
- // ── Individual checks ──
- function checkNodeVersion(): DiagnosticCheck {
- const ver = process.version;
- const major = parseInt(ver.slice(1), 10);
- if (major < 18) {
- return { id: 'env.node', status: 'fail', label: 'Node.js', detail: ver, suggestion: 'Node.js 18+ required. Upgrade at https://nodejs.org' };
- }
- return { id: 'env.node', status: 'ok', label: 'Node.js', detail: `${ver} \u2713` };
- }
- function checkPlatform(): DiagnosticCheck {
- return { id: 'env.platform', status: 'ok', label: 'Platform', detail: `${process.platform} ${process.arch}` };
- }
- function checkEnvVars(): DiagnosticCheck {
- const dbOverride = process.env.BUDDY_DB_PATH ? `(custom) ${process.env.BUDDY_DB_PATH}` : `(default) ${BUDDY_DB_PATH}`;
- const statusOverride = process.env.BUDDY_STATUS_PATH ? `(custom) ${process.env.BUDDY_STATUS_PATH}` : `(default) ${BUDDY_STATUS_PATH}`;
- // Warn only if custom path is set but doesn't exist
- let status: 'ok' | 'warn' = 'ok';
- let suggestion: string | undefined;
- if (process.env.BUDDY_DB_PATH && !fileExists(process.env.BUDDY_DB_PATH)) {
- status = 'warn';
- suggestion = `BUDDY_DB_PATH is set to ${process.env.BUDDY_DB_PATH} but file does not exist`;
- }
- return { id: 'env.vars', status, label: 'Env overrides', detail: `DB: ${dbOverride}\n STATUS: ${statusOverride}`, suggestion };
- }
- function checkPackageVersion(): DiagnosticCheck {
- const ver = getVersion();
- return { id: 'pkg.version', status: 'ok', label: 'Package', detail: `@fiorastudio/buddy v${ver}` };
- }
- const INSTALL_CURL = 'curl -fsSL https://raw.githubusercontent.com/fiorastudio/buddy/master/install.sh | bash';
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 213 on GitHub
- const BUILD_FROM_SOURCE = 'git clone https://github.com/fiorastudio/buddy.git ~/.buddy/server && cd ~/.buddy/server && npm install && npm run build';
- /**
- * install.sh default location: ~/.buddy/server/dist/server/index.js
- * Strong signal when buddy.db exists but the tree is missing (common partial install / manual DB).
- */
- function checkInstallLayout(): DiagnosticCheck {
- const expected = canonicalBuddyMcpEntryPath();
- if (fileExists(expected)) {
- return {
- id: 'install.server',
- status: 'ok',
- label: 'Server install',
- detail: `\u2713 ${expected}`,
- };
- }
- // Only fail hard when the *default* data file on disk exists (user has state but no
- // install). Custom BUDDY_DB_PATH in tests/CI should not trip this.
- const homeDefaultDb = join(homedir(), '.buddy', 'buddy.db');
- const hasStateWithoutInstall = fileExists(homeDefaultDb);
- const hasDir = fileExists(canonicalBuddyInstallDir());
- const parts = [hasStateWithoutInstall ? 'buddy.db in ~/.buddy' : null, hasDir ? 'repo dir without dist build' : null].filter(Boolean);
- const ctx = parts.length > 0 ? ` (${parts.join(' · ')})` : '';
- const suggestion = `Run the installer: ${INSTALL_CURL} — or: ${BUILD_FROM_SOURCE}`;
- if (hasStateWithoutInstall) {
- return {
- id: 'install.server',
- status: 'fail',
- label: 'Server install',
- detail: `Missing or not built: ${expected}${ctx}`,
- suggestion: `Data exists at ~/.buddy/buddy.db but the standard server checkout/build is not present. ${suggestion} Then re-point MCP to ~/.buddy/server/dist/server/index.js if needed.`,
- };
- }
- return {
- id: 'install.server',
- status: 'warn',
- label: 'Server install',
- detail: `Missing: ${expected}${ctx}`,
- suggestion,
- };
- }
- /**
- * MCP paths must exist; warn when multiple host configs or non-canonical copy is used.
- */
- function checkMcpEntryPaths(): DiagnosticCheck {
- const registered = getRegisteredBuddyMcpEntryPaths();
- if (registered.length === 0) {
- return {
- id: 'mcp.paths',
- status: 'skip',
- label: 'MCP paths',
- detail: 'No buddy args found in config files (see mcp.registered)',
- };
- }
- const missing = registered.filter((r) => !fileExists(r.resolved));
- if (missing.length > 0) {
- const list = missing.map((m) => `${m.source} \u2192 ${m.resolved} (missing)`).join(' | ');
- return {
- id: 'mcp.paths',
- status: 'fail',
- label: 'MCP paths',
- detail: list,
- suggestion: `Fix or rebuild the path in mcp config, or install to ~/.buddy/server: ${BUILD_FROM_SOURCE}`,
- };
- }
- const unique = [...new Set(registered.map((r) => r.resolved))];
- if (unique.length > 1) {
- return {
- id: 'mcp.paths',
- status: 'warn',
- label: 'MCP paths',
- detail: `Multiple different entry scripts: ${unique.join(' | ')}`,
- suggestion: 'Point every host at one checkout (recommended: ~/.buddy/server/dist/server/index.js) so CLI and IDEs use the same Buddy build.',
- };
- }
- const canonical = normalize(pathResolve(canonicalBuddyMcpEntryPath()));
- const only = unique[0]!;
- if (safeRealpath(only) === safeRealpath(canonical)) {
- return { id: 'mcp.paths', status: 'ok', label: 'MCP paths', detail: `\u2713 single path, matches standard install` };
- }
- if (fileExists(canonical)) {
- return {
- id: 'mcp.paths',
- status: 'warn',
- label: 'MCP paths',
- detail: `MCP uses ${only} but standard install also exists: ${canonical}`,
- suggestion: 'Align ~/.cursor/mcp.json (and other hosts) on one path, or remove the extra checkout to avoid version drift.',
- };
- }
- return {
- id: 'mcp.paths',
- status: 'ok',
- label: 'MCP paths',
- detail: `\u2713 ${only} (non-standard; ~/.buddy/server not present)`,
- };
- }
- function checkCompanionActive(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT * FROM companions LIMIT 1').get() as any;
- if (!row) {
- return { id: 'companion.active', status: 'warn', label: 'Active companion', detail: 'None', suggestion: 'Use buddy_hatch to create a companion' };
- }
- return { id: 'companion.active', status: 'ok', label: 'Active companion', detail: `\u2713 ${row.name} the ${row.species}` };
- } catch {
- return { id: 'companion.active', status: 'fail', label: 'Active companion', detail: 'DB query failed', suggestion: 'Database may be corrupted. Try deleting ~/.buddy/buddy.db and re-hatching' };
- }
- }
- function checkCompanionCount(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT count(*) as count FROM companions').get() as any;
- return { id: 'companion.count', status: 'ok', label: 'Total saved', detail: `${row?.count || 0} companion(s) in DB` };
- } catch {
- return { id: 'companion.count', status: 'fail', label: 'Total saved', detail: 'DB query failed' };
- }
- }
- function checkCompanionDetails(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT * FROM companions LIMIT 1').get() as any;
- if (!row) {
- return { id: 'companion.details', status: 'skip', label: 'Companion details', detail: 'No companion' };
- }
- const companion = loadCompanion(row);
- if (!companion) {
- return { id: 'companion.details', status: 'fail', label: 'Companion details', detail: 'loadCompanion() returned null' };
- }
- const { level, currentXp, neededXp } = levelProgress(companion.xp);
- const stars = RARITY_STARS[companion.rarity] || '';
- const statStr = STAT_NAMES.map(s => `${s.slice(0, 3)}:${companion.stats[s]}`).join(' ');
- const bioLen = companion.personalityBio?.length || 0;
- return {
- id: 'companion.details', status: 'ok', label: 'Details',
- detail: `${stars} ${companion.rarity} | Lv.${level} (${currentXp}/${neededXp} XP) | mood: ${companion.mood}\n Stats: ${statStr}\n Bio: \u2713 (${bioLen} chars)`,
- };
- } catch (e: any) {
- return { id: 'companion.details', status: 'fail', label: 'Companion details', detail: e?.message || 'Unknown error' };
- }
- }
- function checkDbExists(): DiagnosticCheck {
- if (!fileExists(BUDDY_DB_PATH)) {
- return { id: 'db.exists', status: 'fail', label: 'Database file', detail: `${BUDDY_DB_PATH} not found`, suggestion: 'Database will be created on first buddy_hatch' };
- }
- const writable = fileWritable(BUDDY_DB_PATH);
- try {
- const stat = statSync(BUDDY_DB_PATH);
- const sizeKb = (stat.size / 1024).toFixed(1);
- return {
- id: 'db.exists', status: writable ? 'ok' : 'warn', label: 'Database file',
- detail: `${BUDDY_DB_PATH} ${writable ? '\u2713' : '\u2717 read-only'} (${sizeKb} KB)`,
- suggestion: writable ? undefined : 'Database is not writable — check file permissions',
- };
- } catch {
- return { id: 'db.exists', status: 'warn', label: 'Database file', detail: `${BUDDY_DB_PATH} exists but cannot stat` };
- }
- }
- function checkDbTables(): DiagnosticCheck {
- const expected = ['companions', 'memories', 'xp_events', 'sessions', 'evolution_history',
- 'reasoning_claims', 'reasoning_edges', 'reasoning_findings_log'];
- try {
- const rows = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as any[];
- const tables = rows.map(r => r.name);
- const results = expected.map(t => `${t} ${tables.includes(t) ? '\u2713' : '\u2717'}`);
- const missing = expected.filter(t => !tables.includes(t));
- return {
- id: 'db.tables', status: missing.length > 0 ? 'fail' : 'ok', label: 'DB tables',
- detail: results.join(' | '),
- suggestion: missing.length > 0 ? `Missing tables: ${missing.join(', ')}. Try re-running the server to auto-create.` : undefined,
- };
- } catch {
- return { id: 'db.tables', status: 'fail', label: 'DB tables', detail: 'Cannot query sqlite_master' };
- }
- }
- function checkStatusFile(): DiagnosticCheck {
- if (!fileExists(BUDDY_STATUS_PATH)) {
- return { id: 'status.file', status: 'warn', label: 'Status file', detail: `${BUDDY_STATUS_PATH} not found`, suggestion: 'Status file is created when buddy_status or buddy_observe is called' };
- }
- const writable = fileWritable(BUDDY_STATUS_PATH);
- try {
- const stat = statSync(BUDDY_STATUS_PATH);
- const ageMs = Date.now() - stat.mtimeMs;
- const ageSec = Math.floor(ageMs / 1000);
- const fresh = ageSec < 60;
- return {
- id: 'status.file', status: writable ? 'ok' : 'warn', label: 'Status file',
- detail: `${BUDDY_STATUS_PATH} ${writable ? '\u2713' : '\u2717'} (${ageSec}s ago${fresh ? ' \u2713' : ' — stale'})`,
- suggestion: writable ? undefined : 'Status file is not writable — check permissions',
- };
- } catch {
- return { id: 'status.file', status: 'warn', label: 'Status file', detail: 'Exists but cannot stat' };
- }
- }
- function checkMcpRegistered(): DiagnosticCheck {
- const claudeJsonPath = join(homedir(), '.claude.json');
- const config = readJsonSafe(claudeJsonPath);
- if (config?.mcpServers?.buddy) {
- return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${claudeJsonPath}` };
- }
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const settings = readJsonSafe(settingsPath);
- if (settings?.mcpServers?.buddy) {
- return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${settingsPath}` };
- }
- const codexConfig = readTextSafe(codexConfigPath());
- if (codexConfig?.includes('[mcp_servers.buddy]')) {
- return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${codexConfigPath()}` };
- }
- const cursorConfig = readJsonSafe(cursorMcpPath());
- if (cursorConfig?.mcpServers?.buddy) {
- return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${cursorMcpPath()}` };
- }
- const copilotConfig = readJsonSafe(copilotMcpPath());
- if (copilotConfig?.mcpServers?.buddy) {
- return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${copilotMcpPath()}` };
- }
- return {
- id: 'mcp.registered', status: 'fail', label: 'MCP registration', detail: '\u2717 not found',
- suggestion: 'Re-run the install script, or register Buddy in your host CLI MCP config.',
- };
- }
- function checkStatusline(): DiagnosticCheck {
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const settings = readJsonSafe(settingsPath);
- if (!settings?.statusLine?.command) {
- return { id: 'config.statusline', status: 'warn', label: 'Statusline', detail: '\u2717 not configured in settings.json', suggestion: 'Re-run install script to configure statusline' };
- }
- const cmd: string = settings.statusLine.command;
- if (!cmd.includes('statusline-wrapper')) {
- return { id: 'config.statusline', status: 'warn', label: 'Statusline', detail: `Configured but not pointing to buddy: ${cmd}` };
- }
- // Extract wrapper path — handle "node /path/to/file.js" and "node '/path with spaces/file.js'"
- // Match everything after "node " stripping surrounding quotes
- const pathMatch = cmd.match(/node\s+["']?(.+?)["']?\s*$/);
- const wrapperPath = pathMatch?.[1];
- if (wrapperPath && !fileExists(wrapperPath)) {
- return { id: 'config.statusline', status: 'fail', label: 'Statusline', detail: `Configured but wrapper missing: ${wrapperPath}`, suggestion: 'Re-run install script or rebuild' };
- }
- return { id: 'config.statusline', status: 'ok', label: 'Statusline', detail: '\u2713 configured in settings.json' };
- }
- function checkStatuslineRefresh(): DiagnosticCheck {
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const settings = readJsonSafe(settingsPath);
- if (!settings?.statusLine?.command?.includes('statusline-wrapper')) {
- return { id: 'config.statusline.refresh', status: 'skip', label: 'Refresh interval', detail: 'Buddy statusline not configured' };
- }
- const interval = settings.statusLine.refreshInterval;
- if (interval === undefined || interval === null) {
- return {
- id: 'config.statusline.refresh', status: 'warn', label: 'Refresh interval',
- detail: '\u2717 refreshInterval not set — animation may appear static',
- suggestion: 'Re-run install script or manually add "refreshInterval": 2 to statusLine in ~/.claude/settings.json',
- };
- }
- if (typeof interval !== 'number' || !Number.isFinite(interval) || interval < 1) {
- return {
- id: 'config.statusline.refresh', status: 'warn', label: 'Refresh interval',
- detail: `\u2717 refreshInterval is ${JSON.stringify(interval)} — must be a number >= 1`,
- suggestion: 'Set "refreshInterval": 2 in statusLine config for reliable animation',
- };
- }
- return { id: 'config.statusline.refresh', status: 'ok', label: 'Refresh interval', detail: `\u2713 refreshInterval: ${interval}` };
- }
- function checkHooks(): DiagnosticCheck {
- const found: string[] = [];
- const claudeSettingsPath = join(homedir(), '.claude', 'settings.json');
- const claudeSettings = readJsonSafe(claudeSettingsPath);
- const claudeHooks: any[] = Array.isArray(claudeSettings?.hooks?.PostToolUse) ? claudeSettings.hooks.PostToolUse : [];
- const hasClaudeHook = claudeHooks.some((entry: any) => {
- if (entry.matcher === 'Bash' && Array.isArray(entry.hooks)) {
- return entry.hooks.some((h: any) => h.command && h.command.includes('post-tool-handler'));
- }
- if (typeof entry === 'string' && entry.includes('post-tool-handler')) return true;
- return false;
- });
- if (hasClaudeHook) found.push(`Claude Code (${claudeSettingsPath})`);
- const codexHooks = readJsonSafe(codexHooksPath());
- const codexGroups: any[] = Array.isArray(codexHooks?.hooks?.PostToolUse) ? codexHooks.hooks.PostToolUse : [];
- const hasCodexHook = codexGroups.some((entry: any) =>
- Array.isArray(entry?.hooks) && entry.hooks.some((hook: any) => typeof hook?.command === 'string' && hook.command.includes('post-tool-handler'))
- );
- if (hasCodexHook) found.push(`Codex CLI (${codexHooksPath()})`);
- const cursorHooks = readJsonSafe(cursorHooksPath());
- const cursorShellHooks: any[] = Array.isArray(cursorHooks?.hooks?.afterShellExecution) ? cursorHooks.hooks.afterShellExecution : [];
- const hasCursorHook = cursorShellHooks.some((entry: any) => typeof entry?.command === 'string' && entry.command.includes('post-tool-handler'));
- if (hasCursorHook) found.push(`Cursor CLI (${cursorHooksPath()})`);
- const copilotSettings = readJsonSafe(copilotSettingsPath());
- const copilotHooks: any[] = Array.isArray(copilotSettings?.hooks?.postToolUse) ? copilotSettings.hooks.postToolUse : [];
- const hasCopilotHook = copilotHooks.some((entry: any) => {
- const bash = typeof entry?.bash === 'string' ? entry.bash : '';
- const powershell = typeof entry?.powershell === 'string' ? entry.powershell : '';
- return bash.includes('post-tool-handler') || powershell.includes('post-tool-handler');
- });
- if (hasCopilotHook) found.push(`GitHub Copilot CLI (${copilotSettingsPath()})`);
- if (found.length === 0) {
- return { id: 'config.hooks', status: 'warn', label: 'Hooks', detail: '\u2717 no buddy post-tool hook found', suggestion: 'Re-run install script to configure hooks' };
- }
- return { id: 'config.hooks', status: 'ok', label: 'Hooks', detail: `\u2713 ${formatPathList(found)}` };
- }
- function checkStopHook(): DiagnosticCheck {
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const settings = readJsonSafe(settingsPath);
- const hooks: any[] = Array.isArray(settings?.hooks?.Stop) ? settings.hooks.Stop : [];
- const has = hooks.some((entry: any) =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some((h: any) => h.command && h.command.includes('stop-handler'))
- );
- if (!has) {
- return { id: 'config.hooks.stop', status: 'warn', label: 'Stop hook', detail: '\u2717 stop-handler not found', suggestion: 'Re-run install script to configure hooks' };
- }
- return { id: 'config.hooks.stop', status: 'ok', label: 'Stop hook', detail: '\u2713 Stop hook present' };
- }
- function checkPromptHook(): DiagnosticCheck {
- const settingsPath = join(homedir(), '.claude', 'settings.json');
- const settings = readJsonSafe(settingsPath);
- const hooks: any[] = Array.isArray(settings?.hooks?.UserPromptSubmit) ? settings.hooks.UserPromptSubmit : [];
- const has = hooks.some((entry: any) =>
- Array.isArray(entry.hooks) &&
- entry.hooks.some((h: any) => h.command && h.command.includes('prompt-handler'))
- );
- if (!has) {
- return { id: 'config.hooks.prompt', status: 'warn', label: 'Prompt hook', detail: '\u2717 prompt-handler not found', suggestion: 'Re-run install script to configure hooks' };
- }
- return { id: 'config.hooks.prompt', status: 'ok', label: 'Prompt hook', detail: '\u2713 UserPromptSubmit hook present' };
- }
- function checkPromptInjection(): DiagnosticCheck {
- const found: string[] = [];
- const legacy: string[] = [];
- for (const file of hostPromptFiles()) {
- const content = readTextSafe(file.path);
- if (!content) continue;
- if (content.includes(PROMPT_SENTINEL_V3)) found.push(`${file.host} (${file.path})`);
- else if (content.includes('buddy-companion')) legacy.push(`${file.host} (${file.path})`);
- }
- if (found.length > 0) {
- return { id: 'prompt.injected', status: 'ok', label: 'Prompt injection', detail: `\u2713 ${formatPathList(found)}` };
- }
- if (legacy.length > 0) {
- return { id: 'prompt.injected', status: 'warn', label: 'Prompt injection', detail: `older sentinel found in ${formatPathList(legacy)}`, suggestion: 'Re-run install script to upgrade prompt instructions' };
- }
- return { id: 'prompt.injected', status: 'warn', label: 'Prompt injection', detail: '\u2717 no buddy instructions found in supported host prompt files', suggestion: 'Re-run install script to inject buddy instructions' };
- }
- function checkReasoningGuardMode(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT id, guard_mode FROM companions LIMIT 1').get() as any;
- if (!row) {
- return { id: 'reasoning.guard', status: 'skip', label: 'Guard mode', detail: 'No companion' };
- }
- const on = (row.guard_mode ?? 0) === 1;
- if (!on) {
- return { id: 'reasoning.guard', status: 'ok', label: 'Guard mode', detail: 'off (enable via buddy_mode guard=true)' };
- }
- // Read the persisted observe-seq counters. These survive server restart,
- // so the inert-mode warning doesn't reset when the user relaunches.
- const seqRow = db.prepare(
- 'SELECT seq, last_claims_received_seq FROM reasoning_observe_seq WHERE companion_id = ?'
- ).get(row.id) as { seq: number; last_claims_received_seq: number } | undefined;
- const totalObserves = seqRow?.seq ?? 0;
- const lastClaimsSeq = seqRow?.last_claims_received_seq ?? 0;
- if (totalObserves === 0) {
- return { id: 'reasoning.guard', status: 'ok', label: 'Guard mode', detail: 'on (no observes yet)' };
- }
- // If we've had INERT_GUARD_WARN_OBSERVES observes and never received claims,
- // the host isn't honoring the extraction prompt.
- if (totalObserves >= REASONING_CONFIG.INERT_GUARD_WARN_OBSERVES && lastClaimsSeq === 0) {
- return {
- id: 'reasoning.guard', status: 'warn', label: 'Guard mode',
- detail: `on, but 0 claims received in ${totalObserves} observes`,
- suggestion: 'Host may not be honoring the guard-mode extraction prompt. Verified hosts: Claude Code (Sonnet/Opus). See README for host requirements.',
- };
- }
- // Per-run telemetry supplies richer detail when available (counts don't
- // persist across restart but are informative when they exist).
- const stats = telemetry.snapshot();
- const extra = stats.claims_received_total > 0
- ? ` · this run: ${stats.claims_received_total} claims, ${stats.findings_surfaced_total} findings`
- : '';
- // Re-injection efficacy: how often a silent-graph nudge was followed by the
- // host actually emitting a claim. The signal for whether the in-host fix
- // works in long sessions (the doctor's observe-seq counters freeze during a
- // lapse, so this is the only cross-session view of recovery).
- const ri = getReinjectStats(db, row.id);
- const reinjectExtra = ri.reinjections_total > 0
- ? ` · re-injects: ${ri.recoveries_total}/${ri.reinjections_total} recovered`
- : '';
- return {
- id: 'reasoning.guard', status: 'ok', label: 'Guard mode',
- detail: `on · ${totalObserves} observes, last claims at seq ${lastClaimsSeq}${extra}${reinjectExtra}`,
- };
- } catch {
- return { id: 'reasoning.guard', status: 'fail', label: 'Guard mode', detail: 'DB query failed' };
- }
- }
- function checkReasoningStorage(): DiagnosticCheck {
- try {
- const c = (db.prepare('SELECT count(*) as n FROM reasoning_claims').get() as any)?.n ?? 0;
- const s = (db.prepare('SELECT count(DISTINCT session_id) as n FROM reasoning_claims').get() as any)?.n ?? 0;
- if (c === 0) {
- return { id: 'reasoning.storage', status: 'ok', label: 'Stored claims', detail: '0 claims · 0 sessions' };
- }
- const oldest = (db.prepare('SELECT min(created_at) as t FROM reasoning_claims').get() as any)?.t;
- const oldestDays = oldest ? Math.floor((Date.now() - oldest) / (24 * 60 * 60 * 1000)) : 0;
- return {
- id: 'reasoning.storage', status: 'ok', label: 'Stored claims',
- detail: `${c} claims across ${s} session(s); oldest ${oldestDays}d ago. Purge via buddy_forget.`,
- };
- } catch {
- return { id: 'reasoning.storage', status: 'fail', label: 'Stored claims', detail: 'DB query failed' };
- }
- }
- function checkReasoningRootResolution(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
- if (!row || (row.guard_mode ?? 0) === 0) {
- return { id: 'reasoning.root', status: 'skip', label: 'Workspace root', detail: 'Guard mode off' };
- }
- const s = telemetry.snapshot().root_source_counts;
- const total = s.hint + s.env + s.marker + s.cwd + s.homedir;
- if (total === 0) {
- return { id: 'reasoning.root', status: 'ok', label: 'Workspace root', detail: 'on · no observes yet this run' };
- }
- // If MOST observes this run resolved to the homedir, workspace isolation
- // is almost certainly broken — every project collapses into one graph.
- if (s.homedir > 0 && s.homedir / total > 0.5) {
- return {
- id: 'reasoning.root', status: 'warn', label: 'Workspace root',
- detail: `${s.homedir}/${total} observes resolved to $HOME — projects are mixing`,
- suggestion: 'Pass `cwd` in buddy_observe calls, or set CLAUDE_PROJECT_DIR/BUDDY_PROJECT_ROOT env var. Buddy walks up from cwd looking for .git/package.json markers automatically when launched from a project.',
- };
- }
- const parts: string[] = [];
- if (s.hint) parts.push(`hint=${s.hint}`);
- if (s.env) parts.push(`env=${s.env}`);
- if (s.marker) parts.push(`marker=${s.marker}`);
- if (s.cwd) parts.push(`cwd=${s.cwd}`);
- if (s.homedir) parts.push(`homedir=${s.homedir}`);
- return { id: 'reasoning.root', status: 'ok', label: 'Workspace root', detail: `sources: ${parts.join(', ')}` };
- } catch {
- return { id: 'reasoning.root', status: 'fail', label: 'Workspace root', detail: 'DB query failed' };
- }
- }
- function checkReasoningBasisQuality(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
- if (!row || (row.guard_mode ?? 0) === 0) {
- return { id: 'reasoning.quality', status: 'skip', label: 'Extraction quality', detail: 'Guard mode off' };
- }
- const h = basisDistributionHealth();
- if (h.sample < 20) {
- return { id: 'reasoning.quality', status: 'ok', label: 'Extraction quality', detail: `sample too small (${h.sample} claims this run)` };
- }
- if (h.degenerate) {
- const pct = Math.round((h.pct ?? 0) * 100);
- return {
- id: 'reasoning.quality', status: 'warn', label: 'Extraction quality',
- detail: `${pct}% of recent claims classified as "${h.dominantBasis}" — host may be misclassifying`,
- suggestion: `A degenerate basis distribution usually means the host is defaulting every claim to one bucket. Try a more capable host model, or verify the extraction prompt is reaching the model (buddy://intro resource).`,
- };
- }
- return { id: 'reasoning.quality', status: 'ok', label: 'Extraction quality', detail: `${h.sample} claims sampled, dominant basis "${h.dominantBasis}" at ${Math.round((h.pct ?? 0) * 100)}%` };
- } catch {
- return { id: 'reasoning.quality', status: 'fail', label: 'Extraction quality', detail: 'DB query failed' };
- }
- }
- function checkReasoningEdgeQuality(): DiagnosticCheck {
- try {
- const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
- if (!row || (row.guard_mode ?? 0) === 0) {
- return { id: 'reasoning.edges', status: 'skip', label: 'Edge diversity', detail: 'Guard mode off' };
- }
- const h = edgeDistributionHealth();
- if (h.sample < 12) {
- return { id: 'reasoning.edges', status: 'ok', label: 'Edge diversity', detail: 'sample too small (' + h.sample + ' edges this run)' };
- }
- const supports = h.counts.supports ?? 0;
- const contradicts = h.counts.contradicts ?? 0;
- const questions = h.counts.questions ?? 0;
- if (h.supportDominant || h.noContradicts) {
- const parts = [supports + ' supports', questions + ' questions', contradicts + ' contradicts'];
- return {
- id: 'reasoning.edges', status: 'warn', label: 'Edge diversity',
- detail: parts.join(', ') + ' in recent extraction window',
- suggestion: 'If supports dominate or contradicts never appear, tighten the extraction prompt examples so polite challenge and pushback are labeled as questions/contradicts instead of supports.',
- };
- }
- return { id: 'reasoning.edges', status: 'ok', label: 'Edge diversity', detail: supports + ' supports, ' + questions + ' questions, ' + contradicts + ' contradicts in recent extraction window' };
- } catch {
- return { id: 'reasoning.edges', status: 'fail', label: 'Edge diversity', detail: 'DB query failed' };
- }
- }
- // ── Runner ──
- export function runDiagnostics(): DiagnosticCheck[] {
- return [
- checkNodeVersion(),
- checkPlatform(),
- checkEnvVars(),
- checkPackageVersion(),
- checkInstallLayout(),
- checkCompanionActive(),
- checkCompanionCount(),
- checkCompanionDetails(),
- checkDbExists(),
- checkDbTables(),
- checkStatusFile(),
- checkMcpRegistered(),
- checkMcpEntryPaths(),
- checkStatusline(),
- checkStatuslineRefresh(),
- checkHooks(),
- checkStopHook(),
- checkPromptHook(),
- checkPromptInjection(),
- checkReasoningGuardMode(),
- checkReasoningStorage(),
- checkReasoningRootResolution(),
- checkReasoningBasisQuality(),
- checkReasoningEdgeQuality(),
- ];
- }
- // ── Report formatter ──
- export function formatReport(checks: DiagnosticCheck[]): string {
- const version = getVersion();
- const now = new Date().toISOString();
- const counts = { ok: 0, warn: 0, fail: 0, skip: 0 };
- for (const c of checks) counts[c.status]++;
- const summaryParts = [];
- if (counts.ok > 0) summaryParts.push(`${counts.ok} ok`);
- if (counts.warn > 0) summaryParts.push(`${counts.warn} warn`);
- if (counts.fail > 0) summaryParts.push(`${counts.fail} fail`);
- if (counts.skip > 0) summaryParts.push(`${counts.skip} skip`);
- const lines: string[] = [];
- lines.push(`\uD83E\uDE7A Buddy Doctor v${version} \u2014 ${now}`);
- lines.push(`${checks.length} checks: ${summaryParts.join(', ')}`);
- lines.push('\u2550'.repeat(48));
- lines.push('');
- // Group checks by section
- const sections: Record<string, DiagnosticCheck[]> = {
- 'ENVIRONMENT': checks.filter(c => c.id.startsWith('env.') || c.id.startsWith('pkg.') || c.id.startsWith('install.')),
- 'COMPANION': checks.filter(c => c.id.startsWith('companion.')),
- 'DATABASE': checks.filter(c => c.id.startsWith('db.')),
- 'STATUS FILE': checks.filter(c => c.id.startsWith('status.')),
- 'HOST INTEGRATION': checks.filter(c => c.id.startsWith('mcp.') || c.id.startsWith('config.') || c.id.startsWith('prompt.')),
- 'REASONING LAYER': checks.filter(c => c.id.startsWith('reasoning.')),
- };
- for (const [section, sectionChecks] of Object.entries(sections)) {
- lines.push(section);
- for (const c of sectionChecks) {
- const pad = 15 - c.label.length;
- lines.push(` ${c.label}:${' '.repeat(Math.max(1, pad))}${c.detail}`);
- }
- lines.push('');
- }
- // Summary
- const issues = checks.filter(c => c.status === 'fail' || c.status === 'warn');
- lines.push('SUMMARY');
- if (issues.length === 0) {
- lines.push(` \u2713 All ${checks.length} checks passed \u2014 Buddy is healthy!`);
- } else {
- const fails = checks.filter(c => c.status === 'fail');
- const warns = checks.filter(c => c.status === 'warn');
- const parts = [];
- if (fails.length > 0) parts.push(`${fails.length} fail`);
- if (warns.length > 0) parts.push(`${warns.length} warn`);
- lines.push(` \u2717 ${parts.join(', ')}:`);
- let idx = 1;
- for (const c of issues) {
- lines.push(` ${idx}. [${c.id}] ${c.label}: ${c.detail}`);
- if (c.suggestion) lines.push(` \u2192 ${c.suggestion}`);
- idx++;
- }
- }
- return lines.join('\n');
- }
src/lib/reasoning/config.ts · Bundled script · 71 lines · 1 finding marked
- // src/lib/reasoning/config.ts
- //
- // All tunable numbers live here. Pulled out of detector code so buddy's
- // maintainer can adjust thresholds without touching algorithm code.
- // Starting values chosen conservatively — fewer findings is better than noise.
- export const REASONING_CONFIG = {
- // Cold-start gate: no detectors fire until the session has at least this
- // many claims. Kills first-three-turn false positives when the graph is
- // barely populated.
- COLD_START_MIN_CLAIMS: 6,
- // Cap per-session claim count. When exceeded, oldest claims prune.
- MAX_CLAIMS_PER_SESSION: 200,
- // Retention: sessions older than this are pruned on startup.
- SESSION_RETENTION_DAYS: 30,
- // Cooldowns (measured in observe calls, not wall-clock time).
- CAUTION_COOLDOWN_OBSERVES: 10,
- KUDOS_COOLDOWN_OBSERVES: 5,
- // Kudos bias: if the last N observes had K caution findings and zero kudos,
- // next eligible finding must be kudos (if one is available).
- KUDOS_BIAS_WINDOW: 10,
- KUDOS_BIAS_CAUTION_THRESHOLD: 3,
- // When both kudos and caution fire and neither is cooldown-blocked, weight
- // toward caution (higher information density) but leave room for kudos.
- KUDOS_TIE_BREAK_WEIGHT: 0.4,
- // Detector-specific thresholds.
- LOAD_BEARING_MIN_DOWNSTREAM: 2,
- UNCHALLENGED_CHAIN_MIN_LENGTH: 3,
- ECHO_CHAMBER_MIN_SUPPORTS: 2,
- WELL_SOURCED_MIN_DOWNSTREAM: 2,
- PRODUCTIVE_STRESS_MIN_CHAIN: 2,
- GROUNDED_PREMISE_MIN_SUPPORTS: 1,
- // Claim text cap — matches sanitizeClaim's truncation.
- MAX_CLAIM_TEXT_LENGTH: 240,
- // Recent-claims context injected into the observer prompt so the host can
- // edge into prior-turn claims. Bounded for prompt size.
- RECENT_CLAIMS_CONTEXT: 10,
- // Doctor check: guard mode on but zero claims received in the last N observes
- // triggers a "host may not be honoring extraction" warning.
- INERT_GUARD_WARN_OBSERVES: 10,
- // Re-injection: the extraction instruction normally rides home in the
- // buddy_observe response. But if the host stops calling buddy_observe (the
- // graph goes silent past ~100k tokens of context), it also stops receiving
- // that reminder — a self-reinforcing lapse with no recovery path. The
- // UserPromptSubmit hook fires every turn regardless, so after this many
- // consecutive turns with no new claims it re-injects the instruction into
- // fresh context to pull the host back. Lower = faster recovery, more prompt
- // budget; the counter resets the moment a claim lands.
- REINJECT_AFTER_SILENT_TURNS: 3,
- // Detector latency budget. If detectors exceed this, skip finding injection
- // for this observe (budget measured per-observe, reset each call).
- DETECTOR_BUDGET_MS: 30,
- // Sanitizer iterative-decode depth cap. Handles multiply-encoded HTML
- // entities (`&lt;system&gt;` → `<system>` → `<system>`).
- Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
- Line 66 on GitHub
- // Bounded so pathological inputs can't loop forever. Adversarial depth
- // and base64-wrapped entities remain out of scope per sanitize.ts's
- // "structural break prevention" framing.
- SANITIZE_DECODE_MAX_PASSES: 4,
- } as const;
src/lib/reasoning/sanitize.ts · Bundled script · 133 lines · 1 finding marked
- // src/lib/reasoning/sanitize.ts
- //
- // Claim text comes from the host (which got it from the user or LLM output).
- // We neutralize structural prompt-injection attempts before storing or
- // re-injecting into a prompt.
- //
- // Scope: "structural break prevention," not adversarial robustness. We aim
- // to prevent a claim from accidentally or lazily restructuring a downstream
- // prompt (code fences closing early, role markers appearing to start a new
- // turn, header-style separators dividing sections, free-standing quotes
- // unbalancing the snippet delimiter we use in prompts). We do NOT defend
- // against a motivated attacker who controls the host — that's the host's
- // job. If guard mode is off, sanitize is never invoked.
- import { REASONING_CONFIG } from './config.js';
- // Minimal HTML-entity decode table — covers the cases that would re-form
- // a structural separator after our strip passes (e.g. `<system>`
- // surviving the XML-tag strip). Not a full HTML parser.
- const HTML_ENTITIES: Record<string, string> = {
- '<': '<',
- '>': '>',
- '&': '&',
- '"': '"',
- ''': "'",
- ''': "'",
- ''': "'",
- '<': '<',
- '>': '>',
- '<': '<',
- '>': '>',
- '<': '<',
- '>': '>',
- };
- function decodeHtmlEntities(s: string): string {
- // Iterate until the string stops changing. Handles double-encoded inputs
- // like `&lt;` → `<` → `<`. Bounded by SANITIZE_DECODE_MAX_PASSES
- // (in config.ts) so a pathological input can't loop forever. Adversarial
- // depth and base64-wrapped entities remain out of scope per the header.
- let prev = s;
- for (let i = 0; i < REASONING_CONFIG.SANITIZE_DECODE_MAX_PASSES; i++) {
- const next = prev.replace(/&(?:lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (m) => {
- return HTML_ENTITIES[m] ?? HTML_ENTITIES[m.toLowerCase()] ?? m;
- });
- if (next === prev) return next;
- prev = next;
- }
- return prev;
- }
- // Role markers, including unicode-lookalike variants for the common
- // "lazy copy-paste" cases. The char class on each variant covers ASCII
- // + the full-width form + the most common cross-script lookalike (Greek,
- // Cyrillic). Not exhaustive by design — see sanitize.ts header for scope.
- const ROLE_MARKERS = [
- /\b[HHΗН]uman:/gi, // H (ASCII), H (full-width), Η (Greek eta), Н (Cyrillic En)
- /\b[AAΑА]ssistant:/gi, // A (ASCII), A (full-width), Α (Greek alpha), А (Cyrillic A)
- /\b[SSЅ]ystem:/gi, // S (ASCII), S (full-width), Ѕ (Cyrillic Dze)
- /\b[UUՍ]ser:/gi, // U (ASCII), U (full-width), Ս (Armenian Seh — rough, catches lazy)
- // Chat-template markers (OpenAI / Llama / generic `<|...|>` family).
- /<\|im_start\|>/gi,
- /<\|im_end\|>/gi,
- /<\|start_header_id\|>/gi,
- /<\|end_header_id\|>/gi,
- /<\|eot_id\|>/gi,
- /<\|begin_of_text\|>/gi,
- /<\|end_of_text\|>/gi,
- /<\|[a-z_]+\|>/gi, // generic chat-template marker fallback
- ];
- // Structural separators that could end a prompt section or open a new one.
- const STRUCTURAL_BREAKS = [
- /```+/g, // fenced code (backticks)
- /~~~+/g, // fenced code (tildes)
- /"""/g, // python-style triple quote
- /'''/g, // python-style single triple quote
- /^\s*#{1,6}\s+/gm, // markdown headers at line start
- /^\s*-{3,}\s*$/gm, // horizontal-rule divider
- /^\s*={3,}\s*$/gm, // setext-style divider
- // XMLish role / instruction tags. Covers system/user/assistant plus
- // common prompt-engineering wrappers (instructions, context, role, task,
- // example, document, tool_call, thinking).
- /<\/?(system|user|assistant|instructions?|context|role|task|example|document|tool_call|thinking)\b[^>]*>/gi,
- ];
- export function sanitizeClaim(text: string | undefined): string {
- if (!text) return '';
- let s = text;
- // Decode HTML entities BEFORE the structural-break strips, so
- // `<system>` becomes `<system>` and gets caught. Without this,
- Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
- Line 92 on GitHub
- // a lazy host could bypass the XML-tag strip by HTML-escaping.
- s = decodeHtmlEntities(s);
- // Structural separators are matched first — some are anchored to line
- // starts (markdown headers, HR dividers), which require newlines still
- // to be present. We replace them with a space so surrounding words
- // don't fuse after the subsequent whitespace collapse.
- for (const re of STRUCTURAL_BREAKS) s = s.replace(re, ' ');
- // Now collapse newlines/tabs to spaces — claims are single-line
- // assertions. (Done before control-char strip because \n/\r/\t are
- // themselves control chars and would otherwise be deleted outright,
- // fusing adjacent words.)
- s = s.replace(/[\n\r\t]+/g, ' ');
- // Strip unicode control / format / private-use chars (what's left is
- // non-whitespace).
- s = s.replace(/[\p{Cf}\p{Cc}\p{Co}]/gu, '');
- // Strip role markers.
- for (const re of ROLE_MARKERS) s = s.replace(re, '');
- // Replace ASCII double quotes with single quotes so the surrounding
- // `"{claim}"` delimiter in phrasings and the observer prompt stays
- // balanced, and so the output reads naturally (rather than using
- // typographic quotes that render as two LEFT marks regardless of
- // position). Single quotes are safe — nothing in our prompts uses
- // single-quote delimiters.
- s = s.replace(/"/g, "'");
- // Collapse runs of whitespace.
- s = s.replace(/\s{2,}/g, ' ');
- s = s.trim();
- if (s.length > REASONING_CONFIG.MAX_CLAIM_TEXT_LENGTH) {
- s = s.slice(0, REASONING_CONFIG.MAX_CLAIM_TEXT_LENGTH - 1) + '…';
- }
- return s;
- }
uninstall.ps1 · Bundled script · 161 lines · 1 finding marked
- # Buddy MCP Server — Windows PowerShell Uninstaller
- #
- # Usage:
- # irm https://raw.githubusercontent.com/fiorastudio/buddy/master/uninstall.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 4 on GitHub
- param(
- [switch]$Force,
- [switch]$KeepData
- )
- $ErrorActionPreference = "Stop"
- $InstallDir = "$env:USERPROFILE\.buddy\server"
- $DataDir = "$env:USERPROFILE\.buddy"
- $StatusFile = "$env:USERPROFILE\.claude\buddy-status.json"
- Write-Host ""
- Write-Host " Buddy MCP Server Uninstaller" -ForegroundColor Cyan
- Write-Host " ────────────────────────────" -ForegroundColor Cyan
- Write-Host ""
- function Remove-BuddyFromJsonConfig($configPath, $cliName) {
- if (!(Test-Path $configPath)) { return }
- try {
- $content = Get-Content $configPath -Raw | ConvertFrom-Json
- if (!$content.mcpServers -or !$content.mcpServers.buddy) { return }
- $content.mcpServers.PSObject.Properties.Remove('buddy')
- if ($content.mcpServers.PSObject.Properties.Count -eq 0) {
- $content.PSObject.Properties.Remove('mcpServers')
- }
- $content | ConvertTo-Json -Depth 8 | Set-Content $configPath -Encoding UTF8
- Write-Host " ✓ Removed Buddy MCP entry from $cliName ($configPath)" -ForegroundColor Green
- } catch {
- Write-Host " ! Could not update $cliName config ($configPath)" -ForegroundColor Yellow
- }
- }
- function Remove-BuddyPromptBlock($filePath, $cliName) {
- if (!(Test-Path $filePath)) { return }
- $content = Get-Content $filePath -Raw
- $pattern = '(?s)\s*<!-- buddy-companion -->.*?<!-- /buddy-companion -->\s*'
- if ($content -notmatch 'buddy-companion') { return }
- try {
- $updated = ([regex]::Replace($content, $pattern, '')).Trim()
- if ($updated.Length -gt 0) {
- Set-Content -Path $filePath -Value ($updated + "`n") -Encoding UTF8
- } else {
- Set-Content -Path $filePath -Value '' -Encoding UTF8
- }
- Write-Host " ✓ Removed Buddy instructions from $cliName ($filePath)" -ForegroundColor Green
- } catch {
- Write-Host " ! Could not update $cliName prompt file ($filePath)" -ForegroundColor Yellow
- }
- }
- Write-Host " This will remove Buddy MCP config and prompt instructions."
- if ($KeepData) {
- Write-Host " Local Buddy data will be preserved."
- } else {
- Write-Host " Local Buddy data in $DataDir will also be removed."
- }
- if (-not $Force) {
- $reply = Read-Host "Proceed with uninstall? [y/N]"
- if ($reply -notin @('y', 'Y', 'yes', 'YES')) {
- Write-Host " Aborted."
- exit 0
- }
- }
- function Remove-BuddyHooks($configPath, $cliName) {
- if (!(Test-Path $configPath)) { return }
- try {
- $content = Get-Content $configPath -Raw | ConvertFrom-Json
- if (!$content.hooks -or !$content.hooks.PostToolUse) { return }
- $before = $content.hooks.PostToolUse.Count
- $filtered = @($content.hooks.PostToolUse | Where-Object {
- $dominated = $false
- if ($_.hooks) {
- foreach ($hk in $_.hooks) {
- if ($hk.command -and $hk.command -like '*post-tool-handler*') {
- $dominated = $true
- }
- }
- }
- -not $dominated
- })
- if ($filtered.Count -eq $before) { return }
- if ($filtered.Count -eq 0) {
- $content.hooks.PSObject.Properties.Remove('PostToolUse')
- } else {
- $content.hooks.PostToolUse = $filtered
- }
- if ($content.hooks.PSObject.Properties.Count -eq 0) {
- $content.PSObject.Properties.Remove('hooks')
- }
- $content | ConvertTo-Json -Depth 8 | Set-Content $configPath -Encoding UTF8
- Write-Host " ✓ Removed Buddy hooks from $cliName ($configPath)" -ForegroundColor Green
- } catch {
- Write-Host " ! Could not update $cliName hooks ($configPath)" -ForegroundColor Yellow
- }
- }
- Write-Host ""
- Write-Host " Removing MCP client configuration..."
- Remove-BuddyFromJsonConfig "$env:USERPROFILE\.claude\settings.json" "Claude Code"
- Remove-BuddyHooks "$env:USERPROFILE\.claude\settings.json" "Claude Code"
- Remove-BuddyFromJsonConfig "$env:USERPROFILE\.cursor\mcp.json" "Cursor"
- Remove-BuddyFromJsonConfig "$env:USERPROFILE\.copilot\mcp-config.json" "GitHub Copilot CLI"
- try {
- $null = Get-Command codex -ErrorAction Stop
- codex mcp get buddy *> $null
- if ($LASTEXITCODE -eq 0) {
- codex mcp remove buddy *> $null
- if ($LASTEXITCODE -eq 0) {
- Write-Host " ✓ Removed Buddy MCP entry from Codex CLI" -ForegroundColor Green
- } else {
- Write-Host " ! Could not remove Buddy MCP entry from Codex CLI" -ForegroundColor Yellow
- }
- }
- } catch {
- # Codex not installed; nothing to remove
- }
- Write-Host ""
- Write-Host " Removing injected prompt instructions..."
- Remove-BuddyPromptBlock "$env:USERPROFILE\.claude\CLAUDE.md" "Claude Code"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.cursor\rules\buddy.md" "Cursor"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.codex\instructions.md" "Codex CLI"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.codex\AGENTS.md" "Codex CLI"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.gemini\GEMINI.md" "Gemini CLI"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.gemini\AGENTS.md" "Gemini CLI"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.copilot\copilot-instructions.md" "GitHub Copilot CLI"
- Remove-BuddyPromptBlock "$env:USERPROFILE\.copilot\AGENTS.md" "GitHub Copilot CLI"
- if (Test-Path $StatusFile) {
- Remove-Item $StatusFile -Force
- Write-Host " ✓ Removed Buddy status file ($StatusFile)" -ForegroundColor Green
- }
- Write-Host ""
- Write-Host " Removing local files..."
- if (Test-Path $InstallDir) {
- Remove-Item $InstallDir -Recurse -Force
- Write-Host " ✓ Removed install directory ($InstallDir)" -ForegroundColor Green
- }
- if (-not $KeepData -and (Test-Path $DataDir)) {
- Remove-Item $DataDir -Recurse -Force
- Write-Host " ✓ Removed data directory ($DataDir)" -ForegroundColor Green
- } elseif ($KeepData) {
- Write-Host " Preserved data directory ($DataDir)" -ForegroundColor DarkGray
- }
- Write-Host ""
- Write-Host " ✅ Buddy uninstalled." -ForegroundColor Green
- Write-Host ""
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.