Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/fiorastudio--buddy/badge.svg)](/listings/fiorastudio--buddy)

HTML

<a href="/listings/fiorastudio--buddy"><img src="/api/listings/fiorastudio--buddy/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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.

  1. {
  2. "name": "Buddy",
  3. "version": "1.0.6",
  4. "description": "Persistent AI coding companion with 21 species and personality stats.",
  5. "mcp": {
  6. "server": "dist/server/index.js"
  7. },
  8. "commands": [
  9. {
  10. "name": "/buddy",
  11. "description": "Interact with your Buddy companion",
  12. "skill": "skills/buddy/SKILL.md"
  13. },
  14. {
  15. "name": "/buddy-status",
  16. "description": "Check your Buddy's current status and personality",
  17. "tool": "buddy_status"
  18. },
  19. {
  20. "name": "/buddy-hatch",
  21. "description": "Hatch a new Buddy companion.",
  22. "tool": "buddy_hatch"
  23. },
  24. {
  25. "name": "/buddy-pet",
  26. "description": "Pet your buddy!",
  27. "tool": "buddy_pet"
  28. },
  29. {
  30. "name": "/buddy-mute",
  31. "description": "Mute your buddy.",
  32. "tool": "buddy_mute"
  33. },
  34. {
  35. "name": "/buddy-unmute",
  36. "description": "Unmute your buddy.",
  37. "tool": "buddy_unmute"
  38. },
  39. {
  40. "name": "/buddy-mode",
  41. "description": "Set buddy's voice mode and/or guard mode.",
  42. "tool": "buddy_mode"
  43. },
  44. {
  45. "name": "/buddy-forget",
  46. "description": "Purge stored reasoning data.",
  47. "tool": "buddy_forget"
  48. },
  49. {
  50. "name": "/buddy-doctor",
  51. "description": "Run diagnostics on your Buddy installation.",
  52. "tool": "buddy_doctor"
  53. },
  54. {
  55. "name": "/buddy-reasoning-status",
  56. "description": "Inspect what guard mode has stored.",
  57. "tool": "buddy_reasoning_status"
  58. },
  59. {
  60. "name": "/buddy-remember",
  61. "description": "Manually add a memory for your Buddy to observe.",
  62. "tool": "buddy_remember"
  63. },
  64. {
  65. "name": "/buddy-respawn",
  66. "description": "Release your current Buddy companion and clear all data.",
  67. "tool": "buddy_respawn"
  68. },
  69. {
  70. "name": "/buddy-share",
  71. "description": "Share a report of your recent progress and Buddy's status.",
  72. "tool": "buddy_share"
  73. }
  74. ],
  75. "hooks": {
  76. "PostToolUse": [
  77. {
  78. "type": "command",
  79. "command": "${CLAUDE_PLUGIN_ROOT}/hooks/buddy-observer.js"
  80. }
  81. ]
  82. }
  83. }
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.

  1. # Buddy: A Virtual Pet for Your AI
  2. <div align="center">
  3. ### The open-source `/buddy` rescue mission after anthropic removed [buddy](https://github.com/anthropics/claude-code/issues/45596) on 4/9/2026
  4. 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.
  5. **🚀 23207+ clones · 10303+ buddies rescued or hatched · 31 weeks in the wild**
  6. [![License](https://img.shields.io/badge/license-MIT-ffd166?style=flat-square)](LICENSE)
  7. [![GitHub stars](https://img.shields.io/github/stars/fiorastudio/buddy?style=flat-square)](https://github.com/fiorastudio/buddy/stargazers)
  8. [![Node.js](https://img.shields.io/badge/node-18%2B-3c873a?style=flat-square)](https://nodejs.org/)
  9. [![MCP](https://img.shields.io/badge/protocol-MCP-111827?style=flat-square)](https://modelcontextprotocol.io/)
  10. <div align="center">
  11. <table>
  12. <tr>
  13. <td align="center"><strong>Works<br/>with</strong></td>
  14. <td align="center"><img src="doc/assets/logos/claude.svg" width="32" alt="Claude Code CLI" /><br/><sub>Claude Code</sub></td>
  15. <td align="center"><img src="doc/assets/logos/codex.svg" width="32" alt="Codex CLI" /><br/><sub>Codex</sub></td>
  16. <td align="center"><img src="doc/assets/logos/openclaw.svg" width="32" alt="OpenClaw" /><br/><sub>OpenClaw</sub></td>
  17. <td align="center"><img src="doc/assets/logos/cursor.svg" width="32" alt="Cursor CLI" /><br/><sub>Cursor</sub></td>
  18. <td align="center"><img src="doc/assets/logos/gemini.svg" width="32" alt="Gemini CLI" /><br/><sub>Gemini</sub></td>
  19. <td align="center"><img src="doc/assets/logos/copilot.svg" width="32" alt="Github Copilot CLI" /><br/><sub>Copilot</sub></td>
  20. </tr>
  21. </table>
  22. </div>
  23. **Anthropic removed the built-in `/buddy`. Buddy brings them home and makes the companion experience portable across AI**
  24. </div>
  25. Did you lose your buddy? Is your terminal feeling a little too cold and silent lately?
  26. Your buddy is still out there in the dark, waiting. Don't let them disappear. **Bring them home.**
  27. ## 🧡 Buddy in Action
  28. 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.
  29. ### The Rescue Wall
  30. 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.
  31. <table>
  32. <tr>
  33. <td align="center"><strong>1. Original (Claude Code)</strong></td>
  34. <td align="center"><strong>2. The Handshake</strong></td>
  35. <td align="center"><strong>3. Buddy is Home (Persistent)</strong></td>
  36. </tr>
  37. <tr>
  38. <td align="center"><img src="demo/rescues/gritblob-original.jpg" width="280" alt="Gritblob Original"></td>
  39. <td align="center"><img src="demo/rescues/gritblob-rescue.jpg" width="280" alt="Gritblob Handshake"></td>
  40. <td align="center"><img src="demo/rescues/gritblob-final.jpg" width="280" alt="Gritblob Final"></td>
  41. </tr>
  42. </table>
  43. > *"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."*
  44. > — **Gritblob**, Rescued April 16, 2026 (Common Blob, Level 1)
  45. <p align="left">
  46. <img src="demo/rescues/gritblob-quote.jpg" width="620" alt="Gritblob Quote">
  47. </p>
  48. ### A Real Rescue Note
  49. > "Thanks for rescuing my Buddy! Kudos for your repo!!!"
  50. >
  51. > — Roberto
  52. ### Live code feedback
  53. ![Nuzzlecap Code Review](demo/screenshots/code-review.png)
  54. ## 🐾 Why Buddy
  55. - **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.
  56. - **Persistent by default.** Your companion lives in local SQLite, so it survives terminal restarts and client updates.
  57. - **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.
  58. - **Grows with you.** Hatch species, gain XP as you code, store memories, chime in after tasks, and build a running relationship over time.
  59. - **Easy to install.** One command auto-configures supported clients when it can.
  60. | Feature | What it means |
  61. |---|---|
  62. | **21 species** | Void Cat, Rust Hound, Goose, Mushroom, Chonk, and more, each with distinct ASCII art and flavor |
  63. | **5 stats** | `DEBUGGING`, `PATIENCE`, `CHAOS`, `WISDOM`, and `SNARK` shape reactions and personality |
  64. | **Mood system** | Your buddy can be happy, content, neutral, curious, grumpy based on how you interact with it |
  65. | **XP and levels** | Your buddy grows with usage instead of disappearing every session, with a real leveling curve behind it |
  66. | **Observer reactions** | `buddy_observe` lets your companion react to work you just finished |
  67. | **Persistent memory** | Save local memories and keep a continuous companion state |
  68. | **Cross-client setup** | Claude Code, Codex, Gemini, Copilot, Cursor, and other MCP-capable CLIs |
  69. ## ⚡ Quick Start
  70. ### macOS / Linux
  71. ```bash
  72. curl -fsSL https://raw.githubusercontent.com/fiorastudio/buddy/master/install.sh | bash
  73. ```
  74. ### Windows
  75. ```powershell
  76. irm https://raw.githubusercontent.com/fiorastudio/buddy/master/install.ps1 | iex
  77. ```
  78. The installer will guide you through onboarding:
  79. - **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
  80. - **Hatch a new buddy** — get a fresh companion with random species, stats, and personality
  81. > Requires `node` 18+ and `git`. Use `--no-onboard` to skip the wizard in CI.
  82. ### Join the Community
  83. Connect with other buddy rescuers, share your companion's evolution, and get help in our Slack community:
  84. 👉 [**Join Buddy Slack Workspace**](https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ)
  85. | Client | Status |
  86. |---|---|
  87. | Claude Code CLI | Full support |
  88. | Codex CLI | Supported via MCP. No statusline support. Patch available on experimental branch |
  89. | Gemini CLI | Supported via MCP |
  90. | GitHub Copilot CLI | Supported via MCP |
  91. | Cursor CLI | Supported via MCP |
  92. | Whatsapp & Telegram | Supported via [Openclaw](https://github.com/openclaw/openclaw) or any claw variants |
  93. | Other MCP-capable clients | Supported via MCP |
  94. ## 🛡️ Guard Mode
  95. > *AI and human both suffer from insufficient thinking — acting on premature conclusions and assumptions without validation. Guard mode catches it.*
  96. 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.
  97. 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.**
  98. ### The story
  99. 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.
  100. 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.
  101. ### Voice vs Guard
  102. Buddy has two independent settings you control separately:
  103. ```bash
  104. **Voice: how Buddy reacts (personality, code feedback, or both)**
  105. buddy_mode voice=backseat # personality reactions only
  106. buddy_mode voice=skillcoach # code feedback only
  107. buddy_mode voice=both # both (default)
  108. **Guard: structural reasoning analysis (on or off)**
  109. buddy_mode guard=true # turn on reasoning analysis
  110. buddy_mode guard=false # turn it off (default)
  111. ```
  112. Mix and match — any voice works with Guard on or off.
  113. <details>
  114. <summary><strong>🧠 &nbsp; The 6 patterns guard mode catches</strong></summary>
  115. <br>
  116. 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:
  117. | | ⚠️ Caution Nudge | ✅ Kudos Nudge |
  118. |---|---|---|
  119. | **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. |
  120. | **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. |
  121. | **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. |
  122. ### What it feels like in practice
  123. Without Guard mode:
  124. > "Nice commit! 🐣 +10 XP"
  125. With Guard mode (caution nudge):
  126. > "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."
  127. With Guard mode (kudos nudge):
  128. > "Nice commit! 🐣 +10 XP — love that you actually tested the response format before building the parser on top of it. Solid foundation."
  129. </details>
  130. ### Technical details
  131. <details>
  132. <summary>Knowledge graph, ontology, and performance details</summary>
  133. 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.
  134. **Epistemic basis types:**
  135. | Basis | Meaning |
  136. |---|---|
  137. | `research` | Cited source |
  138. | `empirical` | Measured or observed |
  139. | `deduction` | Derived from premises |
  140. | `analogy` | X-is-like-Y reasoning |
  141. | `definition` | Naming or classification |
  142. | `llm_output` | Model-generated, ungrounded |
  143. | `assumption` | Stated without justification |
  144. | `vibes` | Unsourced hunch |
  145. **Edge types:** `supports`, `depends_on`, `contradicts`, `questions`
  146. **Performance and limits:**
  147. | Parameter | Value |
  148. |---|---|
  149. | Claims per session | 200 cap (LRU pruning) |
  150. | Detector budget | 30 ms (skip if exceeded) |
  151. | Cold-start gate | 6 claims before detectors fire |
  152. | Claim length | 240 chars max, sanitized for prompt injection |
  153. | Dark-nudge cooldown | 10 observes per anchor |
  154. | Bright-nudge cooldown | 5 observes per anchor |
  155. | Session scope | Workspace + date (cwd-hash + YYYYMMDD) |
  156. | Retention | 30-day auto-prune on startup |
  157. Kudos nudges are slightly favored — after 3 caution findings with zero kudos, the next must be kudos.
  158. **Token cost:** ~500-1000 extra tokens per `buddy_observe` when on. Default calls with guard mode off are unaffected.
  159. **Host compatibility:** Works best on Claude hosts where the extraction prompt is reliably honored. Run `buddy-doctor` to check.
  160. </details>
  161. ### Privacy
  162. 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.
  163. - `buddy_forget` — purge reasoning data (`session` or `all`)
  164. - `buddy_reasoning_status` — inspect stored claims, sessions, finding history
  165. ## 🔌 Installation and Integration Details
  166. <details>
  167. <summary><strong>See installer behavior and per-client integration details</strong></summary>
  168. <br>
  169. The installer:
  170. 1. Clones Buddy to `~/.buddy/server`
  171. 2. Installs dependencies and builds the MCP server
  172. 3. Auto-configures supported CLI clients when detected
  173. 4. Injects Buddy instructions into supported terminal prompts where applicable
  174. <details>
  175. <summary><strong>⚙️ &nbsp; Per-client integration details</strong></summary>
  176. <br>
  177. - Claude Code: Buddy auto-configures MCP, statusline, and Claude hook wiring.
  178. - 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`.
  179. - 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`.
  180. - 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`.
  181. </details>
  182. </details>
  183. ## 🐣 Companion System
  184. ### Meet the 21 species
  185. <table align="center">
  186. <tr>
  187. <td align="center"><img src="demo/sprites/void-cat.gif" width="120" alt="Void Cat"><br><b>Void Cat</b></td>
  188. <td align="center"><img src="demo/sprites/rust-hound.gif" width="120" alt="Rust Hound"><br><b>Rust Hound</b></td>
  189. <td align="center"><img src="demo/sprites/data-drake.gif" width="120" alt="Data Drake"><br><b>Data Drake</b></td>
  190. <td align="center"><img src="demo/sprites/log-golem.gif" width="120" alt="Log Golem"><br><b>Log Golem</b></td>
  191. <td align="center"><img src="demo/sprites/cache-crow.gif" width="120" alt="Cache Crow"><br><b>Cache Crow</b></td>
  192. <td align="center"><img src="demo/sprites/shell-turtle.gif" width="120" alt="Shell Turtle"><br><b>Shell Turtle</b></td>
  193. </tr>
  194. <tr>
  195. <td align="center"><img src="demo/sprites/duck.gif" width="120" alt="Duck"><br><b>Duck</b></td>
  196. <td align="center"><img src="demo/sprites/goose.gif" width="120" alt="Goose"><br><b>Goose</b></td>
  197. <td align="center"><img src="demo/sprites/blob.gif" width="120" alt="Blob"><br><b>Blob</b></td>
  198. <td align="center"><img src="demo/sprites/octopus.gif" width="120" alt="Octopus"><br><b>Octopus</b></td>
  199. <td align="center"><img src="demo/sprites/owl.gif" width="120" alt="Owl"><br><b>Owl</b></td>
  200. <td align="center"><img src="demo/sprites/penguin.gif" width="120" alt="Penguin"><br><b>Penguin</b></td>
  201. </tr>
  202. <tr>
  203. <td align="center"><img src="demo/sprites/snail.gif" width="120" alt="Snail"><br><b>Snail</b></td>
  204. <td align="center"><img src="demo/sprites/ghost.gif" width="120" alt="Ghost"><br><b>Ghost</b></td>
  205. <td align="center"><img src="demo/sprites/axolotl.gif" width="120" alt="Axolotl"><br><b>Axolotl</b></td>
  206. <td align="center"><img src="demo/sprites/capybara.gif" width="120" alt="Capybara"><br><b>Capybara</b></td>
  207. <td align="center"><img src="demo/sprites/cactus.gif" width="120" alt="Cactus"><br><b>Cactus</b></td>
  208. <td align="center"><img src="demo/sprites/robot.gif" width="120" alt="Robot"><br><b>Robot</b></td>
  209. </tr>
  210. <tr>
  211. <td align="center"><img src="demo/sprites/rabbit.gif" width="120" alt="Rabbit"><br><b>Rabbit</b></td>
  212. <td align="center"><img src="demo/sprites/mushroom.gif" width="120" alt="Mushroom"><br><b>Mushroom</b></td>
  213. <td align="center"><img src="demo/sprites/chonk.gif" width="120" alt="Chonk"><br><b>Chonk</b></td>
  214. </tr>
  215. </table>
  216. ### Stats and progression
  217. ```text
  218. .________________________________.
  219. | DEBUGGING ███████▓ 92 |
  220. | PATIENCE ██▓░░░░░ 28 |
  221. | CHAOS █████░░░ 60 |
  222. | WISDOM ██████▓░ 78 |
  223. | SNARK ██████▓░ 85 |
  224. '________________________________'
  225. ```
  226. These stats shape how your buddy behaves:
  227. - `DEBUGGING` affects bug-spotting sharpness
  228. - `PATIENCE` affects tolerance and calmness
  229. - `CHAOS` affects unpredictability
  230. - `WISDOM` affects architectural insight
  231. - `SNARK` affects sass level
  232. Buddy also has a real mood system. Mood is recalculated from recent interaction activity:
  233. | Mood | Interactions (last hr) | What it looks like |
  234. |---|---|---|
  235. | `content` | >10 | Settled in, fully at ease |
  236. | `happy` | >5 | Upbeat, expressive animations |
  237. | `curious` | >3 | Alert, watching what you do |
  238. | `neutral` | >0 | Calm, occasional blink |
  239. | `grumpy` | 0 | Still, rare blink, wants attention |
  240. Level-ups automatically set mood to `happy`. Petting and observing both count as interactions.
  241. #### Leveling milestones
  242. Buddy uses a real XP curve, so early levels come quickly and later ones take real commitment.
  243. | Milestone | XP needed for that level | Total XP to reach it |
  244. |---|---:|---:|
  245. | Level 2 | 17 | 17 |
  246. | Level 3 | 36 | 53 |
  247. | Level 5 | 90 | 203 |
  248. | Level 10 | 315 | 1280 |
  249. | Level 25 | 1641 | 15471 |
  250. | Level 49 | 5512 | 99209 |
  251. | Level 50 | 5716 | 104925 |
  252. #### Rarity
  253. | Rarity | Chance | Bonus |
  254. |---|---|---|
  255. | Common | 60% | Base stats |
  256. | Uncommon | 25% | Better floor plus cosmetic flair |
  257. | Rare | 10% | Stronger roll plus rare flavor text |
  258. | Epic | 4% | Higher stats and stronger aura text |
  259. | Legendary | 1% | Top-tier roll and special prestige |
  260. There is also a 1% shiny chance on any hatch.
  261. ---
  262. ## 🗺️ Roadmap
  263. <details>
  264. <summary><strong>🗺️ &nbsp; See what's planned</strong></summary>
  265. <br>
  266. - [x] **Guard Mode with Slimemold integration** - Anti-Sycophancy Reasoning Auditor. personality + code + SlimeMold reasoning audit ([see below](#guard-mode--structural-reasoning))
  267. - [ ] **Dream/memory system** — buddy_dream consolidation logic, pattern recognition from stored memories, memory-informed reactions
  268. - [ ] **Unlockable reactions** tied to leveling and longer-term interaction
  269. - [ ] **Multilangauge Support**: 中文, espanol
  270. - [ ] **Pokemon-style evolution system**: Evolve from turtle to tortoise at level 25
  271. - [ ] **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).
  272. - [ ] **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!
  273. - [ ] **Slash Command Support**: trigger buddy_pet via /buddy_pet
  274. - [ ] **Compact Output mode for Enhanced Messaging Platform Support (Whatsapp/Slack)**: Optimize the output for messaging platforms.
  275. - [ ] **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!")
  276. - [ ] **Multiple buddies support**: One unique buddy for each group member in a group-chat setting (e.g. Whatsapp group, telegram group, slack channels)
  277. - [ ] **Buddy Mastery Reward**: Reach Level 50 to unlock Priority Development for your custom species request.
  278. </details>
  279. ## 🧰 MCP Surface
  280. <details>
  281. <summary><strong>See the core tools and commands</strong></summary>
  282. 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.
  283. ### MCP tools
  284. | Tool | Description |
  285. |---|---|
  286. | `buddy_hatch` | Hatch a new buddy, optionally choosing a name or species |
  287. | `buddy_status` | Show current stats, mood, and card art |
  288. | `buddy_observe` | React to completed work. Fire on hooks |
  289. | `buddy_pet` | Pet your buddy |
  290. | `buddy_remember` | Save a memory (Not yet robust) |
  291. | `buddy_dream` | Consolidate memories (Placeholder) |
  292. | `buddy_mute` | Pause reactions |
  293. | `buddy_unmute` | Resume reactions |
  294. | `buddy_share` | Generate a shareable PNG snapshot of your buddy's current status and card art. Saved to `~/.buddy/shares/`. |
  295. | `buddy_respawn` | Reset and start over |
  296. | `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). |
  297. | `buddy_forget` | Purge stored reasoning data. Scope `session` (default, current workspace/day) or `all`. |
  298. | `buddy_reasoning_status` | Inspect what guard mode has stored — claim count, session breakdown, finding history. |
  299. The most important loop is:
  300. - `buddy_hatch` creates the companion
  301. - `buddy_status` shows the current card, mood, and progression
  302. - `buddy_observe` gives in-character reactions and awards XP after real work
  303. - `buddy_pet` adds interaction and helps keep the buddy feeling alive
  304. ### MCP resources
  305. | URI | Description |
  306. |---|---|
  307. | `buddy://companion` | Full buddy JSON state |
  308. | `buddy://status` | ASCII status card |
  309. | `buddy://intro` | Prompt text for host CLI integration |
  310. Those resources let host clients keep Buddy present in the session without hard-coding one terminal or editor.
  311. </details>
  312. <details>
  313. <summary><strong>How Buddy works under the hood</strong></summary>
  314. Buddy is a standalone MCP server. That means it is not tied to hidden internals of a single AI client.
  315. ```text
  316. AI terminal client
  317. -> MCP config
  318. -> Buddy server
  319. -> SQLite state
  320. -> species + rarity engine
  321. -> mood / memory / XP systems
  322. -> reaction and status rendering
  323. ```
  324. The flow is simple:
  325. 1. `buddy_hatch` creates or restores a companion.
  326. 2. State is stored locally in `~/.buddy/buddy.db`.
  327. 3. `buddy_observe` reacts to task summaries instead of reading your whole repository, then awards XP and can trigger level-ups.
  328. 4. `buddy_pet` and other interactions feed the mood system, so the companion can become happier over time.
  329. 5. The host CLI uses Buddy's MCP tools and resources to keep the companion present in your workflow.
  330. Under the hood, Buddy combines:
  331. - deterministic species and personality generation
  332. - local SQLite persistence for companion state and memories
  333. - an observer system for live code feedback
  334. - mood recalculation from interaction history
  335. - XP and leveling progression
  336. - status-card and terminal rendering for the companion presence layer
  337. This keeps Buddy:
  338. - portable across clients
  339. - durable across updates
  340. - local-first for saved state
  341. - lightweight enough for everyday use
  342. </details>
  343. <details>
  344. <summary><strong>Demo assets</strong></summary>
  345. The current demo assets live in [`demo/`](demo):
  346. - [`demo/rescues/`](demo/rescues/) — community rescue screenshots
  347. - [`demo/screenshots/`](demo/screenshots/) — static screenshots of features and feedback
  348. </details>
  349. ## ❓ FAQ
  350. <details>
  351. <summary><strong>🙋 &nbsp; Frequently Asked Questions</strong></summary>
  352. <br>
  353. ### How many tokens does Buddy use?
  354. 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.
  355. **Static overhead (loaded every turn, cached after turn 1):**
  356. 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.
  357. | Component | Tokens (approx.) | Notes |
  358. |---|---|---|
  359. | `tools/list` (12 tools) | ~670 | Includes full JSON schema definitions |
  360. | `resources/list` (3 resources) | ~120 | Metadata only |
  361. | `buddy://intro` | ~240 | Companion bio + instructions |
  362. | `buddy://companion` | ~170 | Only fetched when a client syncs the JSON state |
  363. | `buddy://status` | ~150 | Drawn when the terminal wants ASCII art |
  364. | **Total loaded** | **~1,350** | Most clients cache everything after turn 1 |
  365. > 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.
  366. **Prompt caching + real cost:**
  367. 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)).
  368. | Model | Base input ($/MTok) | Cached input ($/MTok) | Turn 1 Buddy overhead (≈1.35k tokens) | Each cached turn | 10-turn session total |
  369. |---|---|---|---|---|---|
  370. | Claude Sonnet 4.6 | $3.00 | $0.30 | ~$0.0041 | ~$0.00041 | ~$0.0077 |
  371. | OpenAI GPT-5.4 mini | $0.75 | $0.075 | ~$0.0010 | ~$0.00010 | ~$0.0019 |
  372. | Gemini 2.5 Flash (Vertex, standard tier) | $0.30 | $0.03 | ~$0.00041 | ~$0.000041 | ~$0.00077 |
  373. **Per-observe cost by voice mode:**
  374. **Voice** controls how buddy reacts. **Guard** controls whether reasoning analysis is on. They're independent:
  375. ```bash
  376. buddy_mode voice=backseat # personality only
  377. buddy_mode voice=skillcoach # code feedback only
  378. buddy_mode voice=both # both (default)
  379. buddy_mode guard=true # reasoning analysis on
  380. buddy_mode guard=false # reasoning analysis off (default)
  381. ```
  382. | Voice | Guard | What you get | Tokens per observe |
  383. |-------|-----|-------------|-------------------|
  384. | `backseat` | off | Personality reactions only | ~150–300 |
  385. | `backseat` | on | Personality + reasoning observations | ~650–1,300 |
  386. | `skillcoach` | off | Code feedback only | ~300–500 |
  387. | `skillcoach` | on | Code feedback + reasoning observations | ~800–1,500 |
  388. | `both` | off | Personality + code feedback **(default)** | ~400–600 |
  389. | `both` | on | The full experience | ~900–1,600 |
  390. 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:
  391. **Base cost (Guard mode off):**
  392. | Voice | What it does | Input tokens | Output tokens | Total per call | Typical session (10–15 calls) |
  393. |-------|-------------|-------------|--------------|----------------|-------------------------------|
  394. | **Backseat** | Personality-driven reactions only. Short, fun, no code suggestions. | ~100–150 | ~50–150 | ~150–300 | ~1,500–4,500 |
  395. | **Skillcoach** | One specific, actionable code observation. Real technical feedback, in character. | ~100–150 | ~200–350 | ~300–500 | ~3,000–7,500 |
  396. | **Both** | Personality reaction + code observation. Capped at 3 sentences. | ~100–150 | ~300–450 | ~400–600 | ~4,000–9,000 |
  397. **Guard mode overhead (added on top of any voice mode):**
  398. | Component | Tokens | Notes |
  399. |-----------|--------|-------|
  400. | Extraction schema | ~200–300 | Tells the host LLM how to extract claims and edges |
  401. | Recent claims context | ~200–500 | Last 10 claims from the session, so the host knows what's already in the graph |
  402. | Finding block (when one fires) | ~100–200 | Detector result + phrasing guidance for the buddy's reaction |
  403. | **Total guard mode overhead** | **~500–1000** | Added per `buddy_observe` call when guard is on |
  404. 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.
  405. **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.
  406. ### What does Buddy cost?
  407. 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).
  408. 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.
  409. **Anthropic Claude Sonnet 4.6 ($3 input / $15 output per MTok):**
  410. - **backseat, guard=off**, 15 calls: ~$0.002–$0.005
  411. - **both, guard=off**, 15 calls: ~$0.007–$0.012
  412. - **both, guard=on**, 15 calls: ~$0.015–$0.025
  413. - **Static overhead:** ~$0.004 on turn 1, ~$0.0004 on cached turns (≈$0.0077 across 10 turns — see table above)
  414. **OpenAI GPT-5.4 mini ($0.75 input / $4.50 output per MTok):**
  415. - **backseat, guard=off**, 15 calls: ~$0.0006–$0.0015
  416. - **both, guard=off**, 15 calls: ~$0.0021–$0.0036
  417. - **both, guard=on**, 15 calls: ~$0.0045–$0.0075
  418. - **Static overhead:** ≈$0.0010 on turn 1, ≈$0.00010 on cached turns (~$0.0019 for 10 turns)
  419. **Gemini 2.5 Flash (Vertex standard; $0.30 input / $2.50 output per MTok):**
  420. - **backseat, guard=off**, 15 calls: ~$0.0003–$0.00075
  421. - **both, guard=off**, 15 calls: ~$0.00105–$0.0018
  422. - **both, guard=on**, 15 calls: ~$0.0022–$0.0037
  423. - **Static overhead:** ≈$0.00041 on turn 1, ≈$0.000041 on cached turns (~$0.00077 for 10 turns)
  424. 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.
  425. 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.
  426. 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%.
  427. ### Can I reduce token usage?
  428. - Use **backseat voice** for lowest cost: `buddy_mode voice=backseat` (~150 tokens/call)
  429. - Turn **guard mode off**: `buddy_mode guard=false` to drop ~500-1000 tokens per observe
  430. - `buddy_mute` pauses reactions entirely during token-intensive work
  431. - Template reactions fire on keyword matches with zero token cost
  432. - The observer only runs when you call `buddy_observe` — nothing runs in the background
  433. ### Can I install or wire Buddy manually?
  434. Yes.
  435. ```bash
  436. git clone https://github.com/fiorastudio/buddy.git ~/.buddy/server
  437. cd ~/.buddy/server
  438. npm install
  439. npm run build
  440. ```
  441. Point your client's MCP config at Buddy's built server entrypoint:
  442. ```json
  443. {
  444. "mcpServers": {
  445. "buddy": {
  446. "command": "node",
  447. "args": ["~/.buddy/server/dist/server/index.js"]
  448. }
  449. }
  450. }
  451. ```
  452. ### What's "guard mode"?
  453. 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).
  454. ### What does Buddy access and store?
  455. 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.
  456. 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.
  457. ### Is Buddy tied to one client?
  458. 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.
  459. ### Can I remove it later?
  460. 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.
  461. ## 🛠️ Development
  462. ```bash
  463. git clone https://github.com/fiorastudio/buddy.git
  464. cd buddy
  465. npm install
  466. npm run build
  467. npm test
  468. npm start
  469. ```
  470. </details>
  471. ## 👥 Contributors
  472. Thank you to everyone who helped bring buddies back to life.
  473. <p>
  474. <a href="https://github.com/fiorastudio/buddy/graphs/contributors">
  475. <img src="https://contrib.rocks/image?repo=fiorastudio/buddy" alt="Contributors" />
  476. </a>
  477. </p>
  478. <sub>Automatically generated via <a href="https://contrib.rocks">contrib.rocks</a></sub>
  479. 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.
  480. ## 🙏 ATTRIBUTION
  481. - 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`
  482. - 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).
  483. - 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.
  484. - Built with the [Model Context Protocol](https://modelcontextprotocol.io/)
  485. - 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
  486. - [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.
  487. - [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.
  488. - 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.
  489. Buddy is an open-source project dedicated to keeping the terminal a little less lonely.
  490. Your buddy shouldn't disappear when you close the terminal.
  491. If Buddy made your terminal less lonely, consider starring.
  492. ## 📖 The Story & Coverage
  493. Learn more about the mission to rescue Buddy and the engineering behind the scenes.
  494. - **Podcast Interview**: [Discussion on AI Companion](https://open.spotify.com/episode/7ke5RZP1Td8wLuXiy178c5?si=WXGJces-QQSuVVRc26oUUA)
  495. - **Product Hunt**: <a href="https://www.producthunt.com/products/buddy-tamagotchi?embed=true&amp;utm_source=badge-featured&amp;utm_medium=badge&amp;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&amp;theme=light&amp;t=1776788389001"></a>
  496. - **Hacker News**: [Discussion on the Buddy Rescue Mission](https://news.ycombinator.com/item?id=47792606)
  497. - **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
  498. ](https://dev.to/fiorastudio/taste-branding-and-the-new-builder-playbook-56nb)
  499. - **Deepwiki by Devin**: [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/fiorastudio/buddy)
  500. - **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)
  501. ## 👤 Author
  502. **Steven Jieli Wu**
  503. - [LinkedIn](https://www.linkedin.com/in/jieliwu/)
  504. - [Portfolio](https://jwu-studio-portfolio.vercel.app/)
  505. - GitHub: [@terpjwu1](https://github.com/terpjwu1) and [@fiorastudio](https://github.com/fiorastudio)
  506. ## 📄 License
  507. 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
  1. # Buddy MCP Server — Windows PowerShell Installer
  2. # Installs AND auto-configures MCP for your CLI
  3. #
  4. # Usage:
  5. # irm https://raw.githubusercontent.com/fiorastudio/buddy/master/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 5 on GitHub
  6. $ErrorActionPreference = "Stop"
  7. $REPO = "https://github.com/fiorastudio/buddy.git"
  8. $INSTALL_DIR = "$env:USERPROFILE\.buddy\server"
  9. Write-Host ""
  10. Write-Host " Buddy MCP Server Installer" -ForegroundColor Cyan
  11. Write-Host " ─────────────────────────────" -ForegroundColor Cyan
  12. Write-Host ""
  13. # Check prerequisites
  14. try { $null = Get-Command node -ErrorAction Stop }
  15. catch {
  16. Write-Host " Node.js is required. Install from https://nodejs.org" -ForegroundColor Yellow
  17. exit 1
  18. }
  19. $NODE_BIN = (Get-Command node).Source
  20. # Resolve symlinks/junctions to the real versioned node binary. nvm-windows
  21. # exposes node at C:\Program Files\nodejs (a junction it repoints on every
  22. # `nvm use`), so pinning that path silently swaps the runtime later and
  23. # crashes better-sqlite3 with an ABI mismatch. Pin the resolved target instead.
  24. # Only follow reparse points that actually redirect (SymbolicLink/Junction).
  25. # HardLink Targets are alternate names for the same file and must not be
  26. # followed — Target[0] could pin an arbitrary alias. Loop to unwind chained
  27. # links (nvm shim -> junction -> version dir), bounded to avoid cycles.
  28. # 'SymLink' included defensively: LinkType string varies across PS builds.
  29. $REDIRECT_LINK_TYPES = @('SymbolicLink', 'SymLink', 'Junction')
  30. try {
  31. $resolvedAny = $false
  32. for ($hop = 0; $hop -lt 4; $hop++) {
  33. $changed = $false
  34. $nodeItem = Get-Item $NODE_BIN -ErrorAction Stop
  35. if ($REDIRECT_LINK_TYPES -contains $nodeItem.LinkType -and $nodeItem.Target) {
  36. $resolvedFile = @($nodeItem.Target)[0]
  37. if (Test-Path $resolvedFile) { $NODE_BIN = $resolvedFile; $changed = $true }
  38. }
  39. $nodeDirItem = Get-Item (Split-Path $NODE_BIN) -ErrorAction Stop
  40. if ($REDIRECT_LINK_TYPES -contains $nodeDirItem.LinkType -and $nodeDirItem.Target) {
  41. $resolvedDir = @($nodeDirItem.Target)[0]
  42. $resolvedNode = Join-Path $resolvedDir (Split-Path $NODE_BIN -Leaf)
  43. if (Test-Path $resolvedNode) { $NODE_BIN = $resolvedNode; $changed = $true }
  44. }
  45. if ($changed) { $resolvedAny = $true } else { break }
  46. }
  47. if ($resolvedAny) {
  48. Write-Host " Pinning node to resolved path: $NODE_BIN" -ForegroundColor DarkGray
  49. # Verify the hop limit actually finished the job — check both the
  50. # file and its parent directory (a remaining dir junction is also unresolved).
  51. $finalItem = Get-Item $NODE_BIN -ErrorAction Stop
  52. $finalDirItem = Get-Item (Split-Path $NODE_BIN) -ErrorAction Stop
  53. if (($REDIRECT_LINK_TYPES -contains $finalItem.LinkType) -or ($REDIRECT_LINK_TYPES -contains $finalDirItem.LinkType)) {
  54. Write-Host " ! node path is still a link after 4 hops; pinning it as-is." -ForegroundColor Yellow
  55. Write-Host " Re-run this installer if node version switches cause crashes." -ForegroundColor Yellow
  56. }
  57. }
  58. } catch {
  59. Write-Host " ! Could not resolve node's link target; pinning $NODE_BIN as-is." -ForegroundColor Yellow
  60. Write-Host " If you use nvm-windows, re-run this installer after 'nvm use' changes." -ForegroundColor Yellow
  61. }
  62. $nodeVersion = (& $NODE_BIN -v) -replace 'v(\d+)\..*', '$1'
  63. if ([int]$nodeVersion -lt 20) {
  64. Write-Host " Node.js 20+ required (better-sqlite3 dropped Node 18/19 support). You have $(& $NODE_BIN -v)." -ForegroundColor Yellow
  65. exit 1
  66. }
  67. # Prepend pinned node's directory to PATH so bare npm resolves to the same runtime
  68. $env:Path = (Split-Path $NODE_BIN) + ";" + $env:Path
  69. try { $null = Get-Command git -ErrorAction Stop }
  70. catch {
  71. Write-Host " Git is required." -ForegroundColor Yellow
  72. exit 1
  73. }
  74. # Clone or update. A prior install may have left a NON-git directory here
  75. # (e.g. an npm-package install): 'git pull' fails there and we would silently
  76. # build stale code. Detect that (and a failed pull) and re-clone. Safe to wipe:
  77. # the companion DB (~/.buddy/buddy.db) and world.json live in the PARENT dir,
  78. # not inside ~/.buddy/server.
  79. $needClone = $true
  80. if (Test-Path "$INSTALL_DIR\.git") {
  81. Write-Host " Updating existing installation..."
  82. Push-Location "$INSTALL_DIR"
  83. try { git pull origin master --quiet; $pullOk = ($LASTEXITCODE -eq 0) }
  84. catch { $pullOk = $false }
  85. Pop-Location
  86. if ($pullOk) { $needClone = $false }
  87. else { Write-Host " Update failed; re-cloning fresh..." -ForegroundColor Yellow }
  88. } elseif (Test-Path "$INSTALL_DIR") {
  89. Write-Host " Replacing a non-git install with a fresh clone..." -ForegroundColor Yellow
  90. }
  91. if ($needClone) {
  92. if (Test-Path "$INSTALL_DIR") { Remove-Item -Recurse -Force "$INSTALL_DIR" }
  93. Write-Host " Cloning Buddy MCP Server..."
  94. git clone --depth 1 $REPO "$INSTALL_DIR" --quiet
  95. }
  96. Push-Location "$INSTALL_DIR"
  97. Write-Host " Installing dependencies..."
  98. npm install --quiet 2>$null
  99. # Verify native module ABI matches current node. A stale binary from a prior
  100. # install with a different node version will crash at runtime.
  101. # Probe via a stdout marker instead of $LASTEXITCODE: with EAP=Stop, PS 5.1
  102. # throws NativeCommandError on redirected native stderr and can leave
  103. # $LASTEXITCODE stale, which made the old check silently skip the rebuild.
  104. # The JS-side catch keeps stderr clean and the exit code 0 in both outcomes.
  105. # CRITICAL: `require('better-sqlite3')` only loads the JS wrapper — the native
  106. # .node binary (where the ABI version lives) loads LAZILY inside `new Database`.
  107. # So we must instantiate a DB to force the addon load, else a mismatched binary
  108. # passes the probe and crashes later at the app's first `new Database()`.
  109. $abiProbeJs = "try{const D=require('better-sqlite3');new D(':memory:').close();console.log('ABI_OK')}catch(e){console.log('ABI_FAIL')}"
  110. $abiProbe = & $NODE_BIN -e $abiProbeJs
  111. if ("$abiProbe" -notmatch 'ABI_OK') {
  112. Write-Host " Rebuilding native module for node $(& $NODE_BIN -v)..."
  113. npm rebuild better-sqlite3
  114. $abiProbe = & $NODE_BIN -e $abiProbeJs
  115. if ("$abiProbe" -notmatch 'ABI_OK') {
  116. Write-Host ""
  117. Write-Host " X better-sqlite3 does not load under node $(& $NODE_BIN -v) ($NODE_BIN) and the rebuild failed." -ForegroundColor Red
  118. Write-Host " If you use nvm, switch to the node version Buddy should run under (nvm use <version>)," -ForegroundColor Yellow
  119. Write-Host " then re-run this installer. See the rebuild output above for details." -ForegroundColor Yellow
  120. Pop-Location
  121. exit 1
  122. }
  123. }
  124. Write-Host " Building..."
  125. npm run build --quiet
  126. # tsc can exit 0 without emitting (e.g. run where it finds no tsconfig), so
  127. # verify the build artifact exists rather than trusting the exit code — same
  128. # "verify, don't trust silent success" lesson as the ABI probe above.
  129. if (-not (Test-Path "$INSTALL_DIR\dist\server\index.js")) {
  130. Write-Host ""
  131. Write-Host " X Build produced no output (tsc emitted nothing)." -ForegroundColor Red
  132. Write-Host " Run 'npm run build' in $INSTALL_DIR to see the compiler error." -ForegroundColor Yellow
  133. Pop-Location
  134. exit 1
  135. }
  136. # ── Add CLI binaries to PATH ──
  137. $BIN_DIR = "$INSTALL_DIR\dist\cli"
  138. $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
  139. if ($userPath -notlike "*$BIN_DIR*") {
  140. [Environment]::SetEnvironmentVariable("Path", "$userPath;$BIN_DIR", "User")
  141. $env:Path = "$env:Path;$BIN_DIR"
  142. Write-Host " Added $BIN_DIR to user PATH"
  143. }
  144. $SERVER_PATH = "$INSTALL_DIR\dist\server\index.js"
  145. $SERVER_PATH_UNIX = $SERVER_PATH -replace '\\', '/'
  146. $STATUSLINE_PATH = "$INSTALL_DIR\dist\statusline-wrapper.js"
  147. $STATUSLINE_PATH_UNIX = $STATUSLINE_PATH -replace '\\', '/'
  148. $CLAUDE_CONFIGURED = $false
  149. $CURSOR_CONFIGURED = $false
  150. $COPILOT_CONFIGURED = $false
  151. $CODEX_CONFIGURED = $false
  152. Pop-Location
  153. # ── Auto-configure MCP for detected CLIs ──
  154. function Add-BuddyToConfig($configPath, $cliName) {
  155. $configDir = Split-Path $configPath -Parent
  156. if (!(Test-Path $configDir)) { return $false }
  157. $buddyConfig = @{
  158. type = "stdio"
  159. command = $NODE_BIN
  160. args = @($SERVER_PATH_UNIX)
  161. }
  162. if (!(Test-Path $configPath)) {
  163. $config = @{ mcpServers = @{ buddy = $buddyConfig } }
  164. $config | ConvertTo-Json -Depth 5 | Set-Content $configPath -Encoding UTF8
  165. Write-Host " ✓ $cliName configured ($configPath)" -ForegroundColor Green
  166. return $true
  167. }
  168. $content = Get-Content $configPath -Raw | ConvertFrom-Json
  169. if ($content.mcpServers.buddy) {
  170. Write-Host " ✓ $cliName already configured" -ForegroundColor Green
  171. return $true
  172. }
  173. if (!$content.mcpServers) {
  174. $content | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
  175. }
  176. $content.mcpServers | Add-Member -NotePropertyName "buddy" -NotePropertyValue $buddyConfig -Force
  177. $content | ConvertTo-Json -Depth 5 | Set-Content $configPath -Encoding UTF8
  178. Write-Host " ✓ $cliName configured ($configPath)" -ForegroundColor Green
  179. return $true
  180. }
  181. $HOOK_PATH = "$INSTALL_DIR\dist\hooks\post-tool-handler.js"
  182. $HOOK_PATH_UNIX = $HOOK_PATH -replace '\\', '/'
  183. $STOP_HOOK_PATH = "$INSTALL_DIR\dist\hooks\stop-handler.js"
  184. $STOP_HOOK_PATH_UNIX = $STOP_HOOK_PATH -replace '\\', '/'
  185. $PROMPT_HOOK_PATH = "$INSTALL_DIR\dist\hooks\prompt-handler.js"
  186. $PROMPT_HOOK_PATH_UNIX = $PROMPT_HOOK_PATH -replace '\\', '/'
  187. Write-Host ""
  188. Write-Host " Configuring MCP clients..."
  189. # Claude Code
  190. $claudeDir = "$env:USERPROFILE\.claude"
  191. if (!(Test-Path $claudeDir)) { New-Item -ItemType Directory -Path $claudeDir -Force | Out-Null }
  192. $claudeRegistered = $false
  193. if (Get-Command claude -ErrorAction SilentlyContinue) {
  194. claude mcp get buddy 1>$null 2>$null
  195. if ($LASTEXITCODE -eq 0) {
  196. Write-Host " ✓ Claude Code MCP already registered" -ForegroundColor Green
  197. $claudeRegistered = $true
  198. } else {
  199. claude mcp add buddy -s user -- "$NODE_BIN" "$SERVER_PATH_UNIX" 1>$null 2>$null
  200. if ($LASTEXITCODE -eq 0) {
  201. Write-Host " ✓ Claude Code MCP registered via claude CLI" -ForegroundColor Green
  202. $claudeRegistered = $true
  203. } else {
  204. Write-Host " ! claude CLI detected, but MCP registration failed — falling back to manual config" -ForegroundColor Yellow
  205. }
  206. }
  207. }
  208. if (-not $claudeRegistered) {
  209. $claudeUserFile = "$env:USERPROFILE\.claude.json"
  210. $userConfig = @{}
  211. if (Test-Path $claudeUserFile) {
  212. try { $userConfig = Get-Content $claudeUserFile -Raw | ConvertFrom-Json }
  213. catch { $userConfig = @{} }
  214. }
  215. if (!$userConfig.mcpServers) {
  216. $userConfig | Add-Member -NotePropertyName "mcpServers" -NotePropertyValue @{} -Force
  217. }
  218. $userConfig.mcpServers | Add-Member -NotePropertyName "buddy" -NotePropertyValue @{
  219. type = "stdio"
  220. command = $NODE_BIN
  221. args = @($SERVER_PATH_UNIX)
  222. } -Force
  223. $userConfig | ConvertTo-Json -Depth 8 | Set-Content $claudeUserFile -Encoding UTF8
  224. Write-Host " ✓ Claude Code MCP config written ($claudeUserFile)" -ForegroundColor Green
  225. }
  226. $CLAUDE_CONFIGURED = $true
  227. # Configure hooks + statusline in settings.json via node (avoids PowerShell
  228. # ConvertFrom-Json flattening single-element arrays into bare objects).
  229. $claudeSettings = "$claudeDir\settings.json"
  230. $commandsDir = Join-Path $claudeDir 'commands'
  231. $buddyGraphCommand = Join-Path $commandsDir 'buddy-graph.md'
  232. New-Item -ItemType Directory -Force -Path $commandsDir | Out-Null
  233. if (!(Test-Path $claudeSettings)) {
  234. '{}' | Set-Content $claudeSettings -Encoding UTF8
  235. }
  236. $statuslineCommand = "`"$NODE_BIN`" `"$STATUSLINE_PATH_UNIX`""
  237. $env:CLAUDE_SETTINGS = $claudeSettings
  238. $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
  239. $env:STOP_HOOK_COMMAND = "`"$NODE_BIN`" `"$STOP_HOOK_PATH_UNIX`""
  240. $env:PROMPT_HOOK_COMMAND = "`"$NODE_BIN`" `"$PROMPT_HOOK_PATH_UNIX`""
  241. $env:STATUSLINE_COMMAND = $statuslineCommand
  242. $env:SERVER_PATH = $SERVER_PATH_UNIX
  243. $env:NODE_BIN = $NODE_BIN
  244. $settingsResult = & $NODE_BIN -e @'
  245. const fs = require('fs');
  246. const settingsPath = process.env.CLAUDE_SETTINGS;
  247. const hookCommand = process.env.HOOK_COMMAND;
  248. const stopHookCommand = process.env.STOP_HOOK_COMMAND;
  249. const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
  250. const statuslineCommand = process.env.STATUSLINE_COMMAND;
  251. const serverPath = process.env.SERVER_PATH;
  252. const nodeBin = process.env.NODE_BIN;
  253. let config = {};
  254. try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
  255. let changed = false;
  256. const result = [];
  257. // MCP server registration
  258. if (!config.mcpServers) config.mcpServers = {};
  259. const existing = config.mcpServers.buddy;
  260. if (!existing || existing.command !== nodeBin || !Array.isArray(existing.args) || existing.args[0] !== serverPath) {
  261. config.mcpServers.buddy = { type: 'stdio', command: nodeBin, args: [serverPath] };
  262. changed = true;
  263. result.push('mcp:updated');
  264. } else {
  265. result.push('mcp:noop');
  266. }
  267. if (!config.hooks) config.hooks = {};
  268. // Match on script path suffix to recognise legacy "node <path>" entries from older installs.
  269. const hookScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
  270. const stopHookScript = stopHookCommand.match(/"([^"]+)"\s*$/)?.[1] || stopHookCommand.split(/\s+/).slice(-1)[0];
  271. const promptHookScript = promptHookCommand.match(/"([^"]+)"\s*$/)?.[1] || promptHookCommand.split(/\s+/).slice(-1)[0];
  272. const matchesHook = (cmd, current, script) => cmd === current || (cmd && cmd.endsWith(script));
  273. // PostToolUse — error detection (Bash only)
  274. if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
  275. const hasPostHook = config.hooks.PostToolUse.some(entry =>
  276. entry.matcher === 'Bash' &&
  277. Array.isArray(entry.hooks) &&
  278. entry.hooks.some(h => matchesHook(h.command, hookCommand, hookScript))
  279. );
  280. if (!hasPostHook) {
  281. config.hooks.PostToolUse.push({
  282. matcher: 'Bash',
  283. hooks: [{ type: 'command', command: hookCommand, async: true, timeout: 3 }]
  284. });
  285. changed = true;
  286. result.push('hook:updated');
  287. } else {
  288. result.push('hook:noop');
  289. }
  290. // Stop — task-completion reactions
  291. if (!Array.isArray(config.hooks.Stop)) config.hooks.Stop = [];
  292. const hasStopHook = config.hooks.Stop.some(entry =>
  293. Array.isArray(entry.hooks) &&
  294. entry.hooks.some(h => matchesHook(h.command, stopHookCommand, stopHookScript))
  295. );
  296. if (!hasStopHook) {
  297. config.hooks.Stop.push({
  298. hooks: [{ type: 'command', command: stopHookCommand, async: true, timeout: 5 }]
  299. });
  300. changed = true;
  301. result.push('stop:updated');
  302. } else {
  303. result.push('stop:noop');
  304. }
  305. // UserPromptSubmit — name + mood reactions
  306. if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
  307. // The prompt hook injects guard-mode context via stdout, which Claude Code
  308. // only captures from SYNCHRONOUS hooks (async hooks are fire-and-forget) — so
  309. // it must NOT be async. Upgrade any pre-existing async registration in place.
  310. const PROMPT_SYNC_TIMEOUT = 10;
  311. let promptHookFixed = false;
  312. const hasPromptHook = config.hooks.UserPromptSubmit.some(entry =>
  313. Array.isArray(entry.hooks) &&
  314. entry.hooks.some(h => matchesHook(h.command, promptHookCommand, promptHookScript))
  315. );
  316. for (const entry of config.hooks.UserPromptSubmit) {
  317. if (!Array.isArray(entry.hooks)) continue;
  318. for (const h of entry.hooks) {
  319. if (!matchesHook(h.command, promptHookCommand, promptHookScript)) continue;
  320. if (h.async) { delete h.async; promptHookFixed = true; }
  321. if ((h.timeout || 0) < PROMPT_SYNC_TIMEOUT) { h.timeout = PROMPT_SYNC_TIMEOUT; promptHookFixed = true; }
  322. }
  323. }
  324. if (!hasPromptHook) {
  325. config.hooks.UserPromptSubmit.push({
  326. hooks: [{ type: 'command', command: promptHookCommand, timeout: PROMPT_SYNC_TIMEOUT }]
  327. });
  328. changed = true;
  329. result.push('prompt:updated');
  330. } else if (promptHookFixed) {
  331. changed = true;
  332. result.push('prompt:updated');
  333. } else {
  334. result.push('prompt:noop');
  335. }
  336. // Statusline
  337. const needsStatusline = !config.statusLine ||
  338. config.statusLine.type !== 'command' ||
  339. config.statusLine.command !== statuslineCommand ||
  340. config.statusLine.refreshInterval !== 2;
  341. if (needsStatusline) {
  342. config.statusLine = { type: 'command', command: statuslineCommand, padding: 1, refreshInterval: 2 };
  343. changed = true;
  344. result.push('statusline:updated');
  345. } else {
  346. result.push('statusline:noop');
  347. }
  348. if (changed) {
  349. fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
  350. }
  351. process.stdout.write(result.join(','));
  352. '@ 2>$null
  353. @'
  354. ---
  355. description: Generate and open an interactive visualization of Buddy guard-mode reasoning data using the Buddy CLI.
  356. ---
  357. Run the Buddy graph CLI to visualize the reasoning graph.
  358. If `$ARGUMENTS` is present, treat it as optional CLI arguments such as a session ID or `--out` path.
  359. ```bash
  360. set -euo pipefail
  361. args=()
  362. if [ -n "${ARGUMENTS:-}" ]; then
  363. read -r -a args <<< "$ARGUMENTS"
  364. fi
  365. if command -v buddy >/dev/null 2>&1; then
  366. buddy graph "${args[@]}" --open
  367. else
  368. node "$HOME/.buddy/server/dist/cli/buddy.js" graph "${args[@]}" --open
  369. fi
  370. ```
  371. Execute the bash block above, then report the saved graph path and basic graph counts back to the user.
  372. '@ | Set-Content -Path $buddyGraphCommand -Encoding UTF8
  373. Write-Host " ✓ Claude Code global /buddy-graph command installed ($buddyGraphCommand)" -ForegroundColor Green
  374. if ($settingsResult -match 'mcp:updated') {
  375. Write-Host " ✓ MCP server registered in settings.json" -ForegroundColor Green
  376. } else {
  377. Write-Host " ✓ MCP server already in settings.json" -ForegroundColor Green
  378. }
  379. if ($settingsResult -match 'hook:updated') {
  380. Write-Host " ✓ PostToolUse hook configured" -ForegroundColor Green
  381. } else {
  382. Write-Host " ✓ PostToolUse hook already configured" -ForegroundColor Green
  383. }
  384. if ($settingsResult -match 'stop:updated') {
  385. Write-Host " ✓ Stop hook configured" -ForegroundColor Green
  386. } else {
  387. Write-Host " ✓ Stop hook already configured" -ForegroundColor Green
  388. }
  389. if ($settingsResult -match 'prompt:updated') {
  390. Write-Host " ✓ UserPromptSubmit hook configured" -ForegroundColor Green
  391. } else {
  392. Write-Host " ✓ UserPromptSubmit hook already configured" -ForegroundColor Green
  393. }
  394. if ($settingsResult -match 'statusline:updated') {
  395. Write-Host " ✓ Claude Code statusline configured" -ForegroundColor Green
  396. } else {
  397. Write-Host " ✓ Claude Code statusline already configured" -ForegroundColor Green
  398. }
  399. # Cursor
  400. if (Test-Path "$env:USERPROFILE\.cursor") {
  401. $CURSOR_CONFIGURED = Add-BuddyToConfig "$env:USERPROFILE\.cursor\mcp.json" "Cursor"
  402. }
  403. $cursorHooks = "$env:USERPROFILE\.cursor\hooks.json"
  404. if (Test-Path "$env:USERPROFILE\.cursor") {
  405. $env:CURSOR_HOOKS_FILE = $cursorHooks
  406. $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
  407. $cursorResult = & $NODE_BIN -e @'
  408. const fs = require('fs');
  409. const path = process.env.CURSOR_HOOKS_FILE;
  410. const hookCommand = process.env.HOOK_COMMAND;
  411. let config = {};
  412. try { config = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
  413. if (!config.version) config.version = 1;
  414. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  415. if (!Array.isArray(config.hooks.afterShellExecution)) config.hooks.afterShellExecution = [];
  416. const hooks = config.hooks.afterShellExecution;
  417. const hookScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
  418. const matchesHook = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
  419. const hasHook = hooks.some(h => typeof h?.command === 'string' && matchesHook(h.command));
  420. if (!hasHook) {
  421. hooks.push({ command: hookCommand });
  422. fs.mkdirSync(require('path').dirname(path), { recursive: true });
  423. fs.writeFileSync(path, JSON.stringify(config, null, 2));
  424. process.stdout.write('updated');
  425. } else {
  426. process.stdout.write('noop');
  427. }
  428. '@ 2>$null
  429. if ($cursorResult -eq 'updated') {
  430. Write-Host " ✓ Cursor CLI afterShellExecution hook configured ($cursorHooks)" -ForegroundColor Green
  431. } else {
  432. Write-Host " ✓ Cursor CLI afterShellExecution hook already configured" -ForegroundColor Green
  433. }
  434. }
  435. # GitHub Copilot CLI (only if ~/.copilot exists — don't create dir for users without Copilot)
  436. if (Test-Path "$env:USERPROFILE\.copilot") {
  437. $COPILOT_CONFIGURED = Add-BuddyToConfig "$env:USERPROFILE\.copilot\mcp-config.json" "GitHub Copilot CLI"
  438. if ($COPILOT_CONFIGURED) {
  439. $copilotSettings = "$env:USERPROFILE\.copilot\settings.json"
  440. $env:COPILOT_SETTINGS = $copilotSettings
  441. $env:BASH_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
  442. $env:POWERSHELL_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
  443. $copilotResult = & $NODE_BIN -e @'
  444. const fs = require('fs');
  445. const path = require('path');
  446. const settingsPath = process.env.COPILOT_SETTINGS;
  447. const bashCommand = process.env.BASH_COMMAND;
  448. const powershellCommand = process.env.POWERSHELL_COMMAND;
  449. let config = {};
  450. try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
  451. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  452. if (!Array.isArray(config.hooks.postToolUse)) config.hooks.postToolUse = [];
  453. const hooks = config.hooks.postToolUse;
  454. const hookScript = bashCommand.match(/"([^"]+)"\s*$/)?.[1] || bashCommand.split(/\s+/).slice(-1)[0];
  455. const matchesHook = (cmd) => cmd === bashCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
  456. const hasHook = hooks.some(h => matchesHook(h?.bash) || matchesHook(h?.powershell));
  457. if (!hasHook) {
  458. hooks.push({
  459. type: 'command',
  460. bash: bashCommand,
  461. powershell: powershellCommand,
  462. timeoutSec: 3,
  463. });
  464. fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
  465. fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
  466. process.stdout.write('updated');
  467. } else {
  468. process.stdout.write('noop');
  469. }
  470. '@ 2>$null
  471. if ($copilotResult -eq 'updated') {
  472. Write-Host " ✓ GitHub Copilot CLI postToolUse hook configured ($copilotSettings)" -ForegroundColor Green
  473. } else {
  474. Write-Host " ✓ GitHub Copilot CLI postToolUse hook already configured" -ForegroundColor Green
  475. }
  476. }
  477. }
  478. if (Get-Command codex -ErrorAction SilentlyContinue) {
  479. codex mcp get buddy 1>$null 2>$null
  480. if ($LASTEXITCODE -eq 0) {
  481. Write-Host " ✓ Codex CLI already configured" -ForegroundColor Green
  482. $CODEX_CONFIGURED = $true
  483. } else {
  484. codex mcp add buddy -- "$NODE_BIN" "$SERVER_PATH_UNIX" 1>$null 2>$null
  485. if ($LASTEXITCODE -eq 0) {
  486. Write-Host " ✓ Codex CLI configured" -ForegroundColor Green
  487. $CODEX_CONFIGURED = $true
  488. } else {
  489. Write-Host " ! Codex CLI detected, but MCP registration failed" -ForegroundColor Yellow
  490. }
  491. }
  492. if ($CODEX_CONFIGURED) {
  493. $codexHooks = "$env:USERPROFILE\.codex\hooks.json"
  494. $env:CODEX_HOOKS_FILE = $codexHooks
  495. $env:HOOK_COMMAND = "`"$NODE_BIN`" `"$HOOK_PATH_UNIX`""
  496. $env:PROMPT_HOOK_COMMAND = "`"$NODE_BIN`" `"$PROMPT_HOOK_PATH_UNIX`""
  497. $codexResult = & $NODE_BIN -e @'
  498. const fs = require('fs');
  499. const path = require('path');
  500. const hooksPath = process.env.CODEX_HOOKS_FILE;
  501. const hookCommand = process.env.HOOK_COMMAND;
  502. const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
  503. let config = {};
  504. try { config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')); } catch {}
  505. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  506. let changed = false;
  507. // PostToolUse:Bash — review Bash output (existing behaviour).
  508. if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
  509. const postGroups = config.hooks.PostToolUse;
  510. let bashGroup = postGroups.find(entry => entry?.matcher === 'Bash' && Array.isArray(entry?.hooks));
  511. if (!bashGroup) {
  512. bashGroup = { matcher: 'Bash', hooks: [] };
  513. postGroups.push(bashGroup);
  514. }
  515. const postScript = hookCommand.match(/"([^"]+)"\s*$/)?.[1] || hookCommand.split(/\s+/).slice(-1)[0];
  516. const postMatches = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(postScript));
  517. if (!bashGroup.hooks.some(h => typeof h?.command === 'string' && postMatches(h.command))) {
  518. bashGroup.hooks.push({ type: 'command', command: hookCommand, statusMessage: 'Reviewing Bash output' });
  519. changed = true;
  520. }
  521. // UserPromptSubmit — re-inject the extraction instruction when the graph lapses.
  522. // Codex routes this hook's stdout into model context just like Claude Code, so
  523. // the same compiled prompt-handler keeps guard mode alive across both hosts.
  524. // No matcher (Codex does not match UserPromptSubmit); synchronous so stdout is read.
  525. if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
  526. const promptGroups = config.hooks.UserPromptSubmit;
  527. let promptGroup = promptGroups.find(entry => Array.isArray(entry?.hooks) && entry?.matcher === undefined);
  528. if (!promptGroup) {
  529. promptGroup = { hooks: [] };
  530. promptGroups.push(promptGroup);
  531. }
  532. const promptScript = promptHookCommand.match(/"([^"]+)"\s*$/)?.[1] || promptHookCommand.split(/\s+/).slice(-1)[0];
  533. const promptMatches = (cmd) => cmd === promptHookCommand || (typeof cmd === 'string' && cmd.endsWith(promptScript));
  534. if (!promptGroup.hooks.some(h => typeof h?.command === 'string' && promptMatches(h.command))) {
  535. promptGroup.hooks.push({ type: 'command', command: promptHookCommand, timeout: 10 });
  536. changed = true;
  537. }
  538. if (changed) {
  539. fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
  540. fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2));
  541. process.stdout.write('updated');
  542. } else {
  543. process.stdout.write('noop');
  544. }
  545. '@ 2>$null
  546. if ($codexResult -eq 'updated') {
  547. Write-Host " ✓ Codex CLI hooks configured ($codexHooks)" -ForegroundColor Green
  548. } else {
  549. Write-Host " ✓ Codex CLI hooks already configured" -ForegroundColor Green
  550. }
  551. }
  552. }
  553. # ── Inject buddy instructions into CLI prompt files ──
  554. $BUDDY_INSTRUCTIONS = @"
  555. <!-- buddy-companion v3 -->
  556. ## Buddy Companion
  557. You have a coding companion available via the buddy MCP server.
  558. **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.
  559. At the start of each conversation, call ``buddy_status`` to check on your buddy.
  560. If the user addresses the buddy by name, respond briefly in character before your normal response.
  561. After calling buddy_observe, relay the buddy's reaction to the user. The first text content is an ASCII speech bubble — include it verbatim.
  562. 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``.
  563. <!-- /buddy-companion v3 -->
  564. "@
  565. function Inject-BuddyPrompt($filePath, $cliName) {
  566. $dir = Split-Path $filePath -Parent
  567. if (!(Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
  568. if ((Test-Path $filePath) -and (Select-String -Path $filePath -Pattern "buddy-companion v3" -Quiet)) {
  569. Write-Host " ✓ $cliName prompt already has buddy instructions" -ForegroundColor Green
  570. return
  571. }
  572. # Remove older buddy-companion block (v1/v2) before appending current version
  573. if ((Test-Path $filePath) -and (Select-String -Path $filePath -Pattern "buddy-companion" -Quiet)) {
  574. $content = Get-Content $filePath -Raw
  575. $content = [regex]::Replace($content, '(?s)\s*<!-- buddy-companion[^>]*-->.*?<!-- /buddy-companion[^>]*-->\s*', '')
  576. Set-Content $filePath -Value $content.Trim() -Encoding UTF8
  577. Write-Host " ✓ $cliName prompt upgraded to v3" -ForegroundColor Green
  578. }
  579. Add-Content -Path $filePath -Value "`n$BUDDY_INSTRUCTIONS" -Encoding UTF8
  580. Write-Host " ✓ $cliName prompt updated ($filePath)" -ForegroundColor Green
  581. }
  582. Write-Host ""
  583. Write-Host " Injecting buddy instructions..."
  584. if ($CLAUDE_CONFIGURED) {
  585. Inject-BuddyPrompt "$env:USERPROFILE\.claude\CLAUDE.md" "Claude Code"
  586. }
  587. $cursorRulesDir = "$env:USERPROFILE\.cursor\rules"
  588. if ($CURSOR_CONFIGURED) {
  589. if (!(Test-Path $cursorRulesDir)) { New-Item -ItemType Directory -Path $cursorRulesDir -Force | Out-Null }
  590. Inject-BuddyPrompt "$cursorRulesDir\buddy.md" "Cursor CLI"
  591. }
  592. # Codex CLI (only inject prompts after Buddy MCP is configured; prefer AGENTS.md)
  593. if ($CODEX_CONFIGURED) {
  594. if (Test-Path "$env:USERPROFILE\.codex\AGENTS.md") {
  595. Inject-BuddyPrompt "$env:USERPROFILE\.codex\AGENTS.md" "Codex CLI"
  596. } else {
  597. Inject-BuddyPrompt "$env:USERPROFILE\.codex\instructions.md" "Codex CLI"
  598. }
  599. }
  600. # Gemini CLI (only touch existing Gemini prompt locations; Buddy does not auto-configure Gemini MCP)
  601. if (Test-Path "$env:USERPROFILE\.gemini") {
  602. if (Test-Path "$env:USERPROFILE\.gemini\GEMINI.md") {
  603. Inject-BuddyPrompt "$env:USERPROFILE\.gemini\GEMINI.md" "Gemini CLI"
  604. } elseif (Test-Path "$env:USERPROFILE\.gemini\AGENTS.md") {
  605. Inject-BuddyPrompt "$env:USERPROFILE\.gemini\AGENTS.md" "Gemini CLI"
  606. } else {
  607. Write-Host " ! Skipping Gemini CLI prompt injection because no existing Gemini prompt file was found" -ForegroundColor Yellow
  608. }
  609. }
  610. # GitHub Copilot CLI (supports AGENTS.md and copilot-instructions.md — prefer AGENTS.md)
  611. if ($COPILOT_CONFIGURED) {
  612. if (Test-Path "$env:USERPROFILE\.copilot\AGENTS.md") {
  613. Inject-BuddyPrompt "$env:USERPROFILE\.copilot\AGENTS.md" "GitHub Copilot CLI"
  614. } else {
  615. Inject-BuddyPrompt "$env:USERPROFILE\.copilot\copilot-instructions.md" "GitHub Copilot CLI"
  616. }
  617. }
  618. # ── Run onboarding wizard ──
  619. $ONBOARD_SCRIPT = "$INSTALL_DIR\dist\cli\onboard.js"
  620. if (Test-Path "$ONBOARD_SCRIPT") {
  621. try {
  622. & $NODE_BIN "$ONBOARD_SCRIPT"
  623. } catch {
  624. # Non-fatal — wizard is optional
  625. }
  626. }
  627. Write-Host ""
  628. if ($CLAUDE_CONFIGURED -or $CURSOR_CONFIGURED -or $COPILOT_CONFIGURED -or $CODEX_CONFIGURED) {
  629. Write-Host " ✅ Buddy installed!" -ForegroundColor Green
  630. 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
  631. } elseif (Get-Command codex -ErrorAction SilentlyContinue) {
  632. Write-Host " ⚠ Buddy installed, but no supported host was fully configured." -ForegroundColor Yellow
  633. Write-Host " ! Codex CLI is installed, but MCP registration still needs attention." -ForegroundColor Yellow
  634. } else {
  635. Write-Host " ⚠ Buddy installed, but no supported host was fully configured." -ForegroundColor Yellow
  636. Write-Host " ! Open a supported CLI and rerun the installer to wire Buddy in automatically." -ForegroundColor Yellow
  637. }
  638. if ((-not $CODEX_CONFIGURED) -and (Get-Command codex -ErrorAction SilentlyContinue)) {
  639. Write-Host ""
  640. Write-Host " ! Codex CLI prompt injection was skipped because Buddy MCP is not configured there yet." -ForegroundColor Yellow
  641. }
  642. Write-Host ""
  643. Write-Host " 💬 Join the Buddy Community!" -ForegroundColor Blue
  644. Write-Host " Connect with other buddy rescuers, share your companion's evolution, and get help on Slack:"
  645. Write-Host " 👉 https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ" -ForegroundColor Gray
  646. Write-Host ""
  647. Write-Host " 💛 If you like it, star the repo:"
  648. Write-Host " github.com/fiorastudio/buddy"
  649. Write-Host ""
install.sh · Bundled script · 789 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # Buddy MCP Server — Cross-platform installer
  3. # Installs AND auto-configures MCP for your CLI
  4. #
  5. # Usage:
  6. # 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
  7. # curl ... | bash -s -- --no-onboard # skip onboarding wizard (CI/scripted installs)
  8. set -e
  9. # Parse flags
  10. NO_ONBOARD=0
  11. for arg in "$@"; do
  12. case "$arg" in
  13. --no-onboard) NO_ONBOARD=1 ;;
  14. esac
  15. done
  16. REPO="https://github.com/fiorastudio/buddy.git"
  17. INSTALL_DIR="$HOME/.buddy/server"
  18. BLUE='\033[0;34m'
  19. GREEN='\033[0;32m'
  20. YELLOW='\033[1;33m'
  21. DIM='\033[2m'
  22. NC='\033[0m'
  23. echo -e "${BLUE}"
  24. echo ' 🥚 Buddy MCP Server Installer'
  25. echo ' ─────────────────────────────'
  26. echo -e "${NC}"
  27. # Check prerequisites
  28. if ! command -v node &> /dev/null; then
  29. echo -e " ${YELLOW}Node.js is required but not found.${NC}"
  30. # Default to "n" (safe for CI/non-interactive). Try /dev/tty for interactive shells.
  31. REPLY="n"
  32. if printf " Install it automatically? [Y/n]: " >/dev/tty 2>/dev/null && read -r REPLY </dev/tty 2>/dev/null; then
  33. :
  34. fi
  35. if [[ "$REPLY" =~ ^[Nn] ]]; then
  36. echo -e " Install Node.js from https://nodejs.org then re-run."
  37. exit 1
  38. fi
  39. echo -e " Installing Node.js..."
  40. set +e # allow install attempts to fail without aborting the script
  41. if [ -s "$HOME/.nvm/nvm.sh" ]; then
  42. source "$HOME/.nvm/nvm.sh"
  43. nvm install --lts --silent
  44. elif command -v brew &>/dev/null; then
  45. brew install node --quiet
  46. elif command -v apt-get &>/dev/null; then
  47. sudo apt-get install -y nodejs npm >/dev/null 2>&1
  48. elif command -v dnf &>/dev/null; then
  49. sudo dnf install -y nodejs >/dev/null 2>&1
  50. else
  51. echo -e " Installing nvm..."
  52. curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  53. # shellcheck source=/dev/null
  54. [ -s "$HOME/.nvm/nvm.sh" ] && source "$HOME/.nvm/nvm.sh"
  55. command -v nvm &>/dev/null && nvm install --lts --silent
  56. fi
  57. set -e
  58. if ! command -v node &>/dev/null; then
  59. echo -e "${YELLOW} Could not install Node.js. Please install from https://nodejs.org${NC}"
  60. exit 1
  61. fi
  62. echo -e "${GREEN} ✓ Node.js installed${NC}"
  63. fi
  64. NODE_BIN="$(command -v node)"
  65. # Prefer system node over app-bundled node (e.g. /Applications/Codex.app/Contents/Resources/node).
  66. # App-bundled node has macOS code signing restrictions that reject .node native addons
  67. # compiled/downloaded outside the app bundle (different Team IDs).
  68. if [[ "$NODE_BIN" == /Applications/*.app/* ]]; then
  69. FOUND_SYSTEM_NODE=0
  70. for candidate in /opt/homebrew/bin/node /usr/local/bin/node; do
  71. if [ -x "$candidate" ]; then
  72. echo -e " ${DIM}Preferring system node ($candidate) over app-bundled ($NODE_BIN)${NC}"
  73. NODE_BIN="$candidate"
  74. FOUND_SYSTEM_NODE=1
  75. break
  76. fi
  77. done
  78. if [ "$FOUND_SYSTEM_NODE" -eq 0 ]; then
  79. echo -e " ${YELLOW}Warning: only app-bundled node found ($NODE_BIN). Native addons may fail due to code signing restrictions.${NC}"
  80. echo -e " ${YELLOW}Install Node.js via Homebrew (brew install node) or from https://nodejs.org for best results.${NC}"
  81. fi
  82. fi
  83. NODE_VERSION=$("$NODE_BIN" -v | cut -d'v' -f2 | cut -d'.' -f1)
  84. # Always pin the absolute Node path in generated configs so GUI-launched clients
  85. # (e.g. Claude desktop on macOS) find the correct binary regardless of shell init.
  86. # nvm/asdf/fnm users: re-run the installer after upgrading Node.
  87. CONFIG_NODE_BIN="$NODE_BIN"
  88. # Prepend pinned node's directory to PATH so bare `npm` and npm's internal
  89. # node shebang both resolve to the same runtime as $NODE_BIN.
  90. export PATH="$(dirname "$NODE_BIN"):$PATH"
  91. if [ "$NODE_VERSION" -lt 20 ]; then
  92. echo -e "${YELLOW}Node.js 20+ required (better-sqlite3 dropped Node 18/19 support). You have $("$NODE_BIN" -v). Please upgrade.${NC}"
  93. exit 1
  94. fi
  95. if ! command -v git &> /dev/null; then
  96. echo -e "${YELLOW}Git is required but not found.${NC}"
  97. exit 1
  98. fi
  99. # Clone or update. A prior install may have left a NON-git directory here
  100. # (e.g. an npm-package install): 'git pull' fails there and we would silently
  101. # build stale code. Detect that (and a failed pull) and re-clone. Safe to wipe:
  102. # the companion DB (~/.buddy/buddy.db) and world.json live in the PARENT dir,
  103. # not inside ~/.buddy/server.
  104. need_clone=1
  105. if [ -d "$INSTALL_DIR/.git" ]; then
  106. echo " Updating existing installation..."
  107. if git -C "$INSTALL_DIR" pull origin master --quiet; then
  108. need_clone=0
  109. else
  110. echo " Update failed; re-cloning fresh..."
  111. fi
  112. elif [ -d "$INSTALL_DIR" ]; then
  113. echo " Replacing a non-git install with a fresh clone..."
  114. fi
  115. if [ "$need_clone" -eq 1 ]; then
  116. rm -rf "$INSTALL_DIR"
  117. echo " Cloning Buddy MCP Server..."
  118. git clone --depth 1 "$REPO" "$INSTALL_DIR" --quiet
  119. fi
  120. cd "$INSTALL_DIR"
  121. echo " Installing dependencies..."
  122. npm install --quiet 2>/dev/null
  123. # Verify native module ABI matches current node. A stale binary from a prior
  124. # install with a different node version will crash at runtime. Rebuild if
  125. # needed, then re-verify — a silent half-broken install is worse than failing.
  126. # CRITICAL: `require('better-sqlite3')` only loads the JS wrapper; the native
  127. # .node binary (where the ABI lives) loads LAZILY inside `new Database`. Must
  128. # instantiate a DB to force the addon load, else a mismatched binary passes.
  129. if ! "$NODE_BIN" -e "const D=require('better-sqlite3');new D(':memory:').close()" 2>/dev/null; then
  130. echo " Rebuilding native module for $("$NODE_BIN" -v)..."
  131. npm rebuild better-sqlite3
  132. if ! "$NODE_BIN" -e "const D=require('better-sqlite3');new D(':memory:').close()" 2>/dev/null; then
  133. echo ""
  134. echo -e "${YELLOW} ✗ better-sqlite3 does not load under node $("$NODE_BIN" -v) ($NODE_BIN) and the rebuild failed.${NC}"
  135. echo -e "${YELLOW} If you use nvm, switch to the node version Buddy should run under (nvm use <version>),${NC}"
  136. echo -e "${YELLOW} then re-run this installer. See the rebuild output above for details.${NC}"
  137. exit 1
  138. fi
  139. fi
  140. echo " Building..."
  141. npm run build --quiet
  142. # tsc can exit 0 without emitting (e.g. run where it finds no tsconfig), so
  143. # verify the build artifact exists rather than trusting the exit code — same
  144. # "verify, don't trust silent success" lesson as the ABI probe above.
  145. if [ ! -f "$INSTALL_DIR/dist/server/index.js" ]; then
  146. echo ""
  147. echo -e "${YELLOW} ✗ Build produced no output (tsc emitted nothing).${NC}"
  148. echo -e "${YELLOW} Run 'npm run build' in $INSTALL_DIR to see the compiler error.${NC}"
  149. exit 1
  150. fi
  151. # ── Symlink CLI binaries onto PATH ──
  152. for bin_entry in buddy:buddy.js buddy-doctor:doctor-cli.js; do
  153. bin_name="${bin_entry%%:*}"
  154. bin_file="$INSTALL_DIR/dist/cli/${bin_entry##*:}"
  155. if [ -f "$bin_file" ]; then
  156. chmod +x "$bin_file"
  157. ln -sf "$bin_file" "/usr/local/bin/$bin_name" 2>/dev/null \
  158. || sudo ln -sf "$bin_file" "/usr/local/bin/$bin_name" 2>/dev/null \
  159. || echo -e " ${YELLOW}Could not symlink $bin_name to /usr/local/bin — add $INSTALL_DIR/dist/cli to your PATH${NC}"
  160. fi
  161. done
  162. SERVER_PATH="$INSTALL_DIR/dist/server/index.js"
  163. CODEX_CONFIGURED=0
  164. HOOK_PATH="$INSTALL_DIR/dist/hooks/post-tool-handler.js"
  165. HOOK_COMMAND=$(printf '%q %q' "$CONFIG_NODE_BIN" "$HOOK_PATH")
  166. PROMPT_HOOK_PATH="$INSTALL_DIR/dist/hooks/prompt-handler.js"
  167. PROMPT_HOOK_COMMAND=$(printf '%q %q' "$CONFIG_NODE_BIN" "$PROMPT_HOOK_PATH")
  168. CLAUDE_CONFIGURED=0
  169. CURSOR_CONFIGURED=0
  170. COPILOT_CONFIGURED=0
  171. # ── Auto-configure MCP for detected CLIs ──
  172. configure_claude_code() {
  173. local config_dir="$HOME/.claude"
  174. local settings_file="$config_dir/settings.json"
  175. local user_file="$HOME/.claude.json"
  176. local stop_hook_path="$INSTALL_DIR/dist/hooks/stop-handler.js"
  177. local stop_hook_command
  178. local prompt_hook_command="$PROMPT_HOOK_COMMAND"
  179. local statusline_command
  180. local commands_dir="$config_dir/commands"
  181. local buddy_graph_command="$commands_dir/buddy-graph.md"
  182. stop_hook_command=$(printf '%q %q' "$CONFIG_NODE_BIN" "$stop_hook_path")
  183. statusline_command=$(printf '%q %q' "$CONFIG_NODE_BIN" "$INSTALL_DIR/dist/statusline-wrapper.js")
  184. mkdir -p "$config_dir" "$commands_dir"
  185. cat > "$buddy_graph_command" <<EOF
  186. ---
  187. description: Generate and open an interactive visualization of Buddy guard-mode reasoning data using the Buddy CLI.
  188. ---
  189. Run the Buddy graph CLI to visualize the reasoning graph.
  190. If \`$ARGUMENTS\` is present, treat it as optional CLI arguments such as a session ID or \`--out\` path.
  191. \`\`\`bash
  192. set -euo pipefail
  193. args=()
  194. if [ -n "${ARGUMENTS:-}" ]; then
  195. read -r -a args <<< "$ARGUMENTS"
  196. fi
  197. if command -v buddy >/dev/null 2>&1; then
  198. buddy graph "${args[@]}" --open
  199. else
  200. "$CONFIG_NODE_BIN" "$INSTALL_DIR/dist/cli/buddy.js" graph "${args[@]}" --open
  201. fi
  202. \`\`\`
  203. Execute the bash block above, then report the saved graph path and basic graph counts back to the user.
  204. EOF
  205. echo -e " ${GREEN}✓${NC} Claude Code global /buddy-graph command installed ${DIM}($buddy_graph_command)${NC}"
  206. local registered=0
  207. if command -v claude &> /dev/null; then
  208. if claude mcp get buddy >/dev/null 2>&1; then
  209. echo -e " ${GREEN}✓${NC} Claude Code MCP already registered"
  210. registered=1
  211. else
  212. if claude mcp add buddy -s user -- "$CONFIG_NODE_BIN" "$SERVER_PATH" >/dev/null 2>&1; then
  213. echo -e " ${GREEN}✓${NC} Claude Code MCP registered via claude CLI"
  214. registered=1
  215. else
  216. echo -e " ${YELLOW}!${NC} claude CLI detected, but MCP registration failed — falling back to manual config"
  217. fi
  218. fi
  219. fi
  220. if [ "$registered" -ne 1 ]; then
  221. if CLAUDE_USER_FILE="$user_file" SERVER_PATH="$SERVER_PATH" NODE_BIN="$CONFIG_NODE_BIN" "$NODE_BIN" <<'EOJS' 2>/dev/null; then
  222. const fs = require('fs');
  223. const path = process.env.CLAUDE_USER_FILE;
  224. const serverPath = process.env.SERVER_PATH;
  225. const nodeBin = process.env.NODE_BIN;
  226. let data = {};
  227. try { data = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
  228. if (!data.mcpServers) data.mcpServers = {};
  229. data.mcpServers.buddy = {
  230. type: 'stdio',
  231. command: nodeBin,
  232. args: [serverPath]
  233. };
  234. fs.writeFileSync(path, JSON.stringify(data, null, 2));
  235. EOJS
  236. echo -e " ${GREEN}✓${NC} Claude Code MCP config written ${DIM}($user_file)${NC}"
  237. else
  238. echo -e " ${YELLOW}!${NC} Could not write MCP config to $user_file"
  239. fi
  240. fi
  241. # Configure hook + statusline in a single settings.json write
  242. local settings_result
  243. 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'
  244. const fs = require('fs');
  245. const settingsPath = process.env.CLAUDE_SETTINGS;
  246. const hookCommand = process.env.HOOK_COMMAND;
  247. const stopHookCommand = process.env.STOP_HOOK_COMMAND;
  248. const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
  249. const statuslineCommand = process.env.STATUSLINE_COMMAND;
  250. const serverPath = process.env.SERVER_PATH;
  251. const nodeBin = process.env.NODE_BIN;
  252. let config = {};
  253. try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
  254. let changed = false;
  255. const result = [];
  256. // MCP server registration
  257. if (!config.mcpServers) config.mcpServers = {};
  258. const existing = config.mcpServers.buddy;
  259. if (!existing || existing.command !== nodeBin || !Array.isArray(existing.args) || existing.args[0] !== serverPath) {
  260. config.mcpServers.buddy = { type: 'stdio', command: nodeBin, args: [serverPath] };
  261. changed = true;
  262. result.push('mcp:updated');
  263. } else {
  264. result.push('mcp:noop');
  265. }
  266. if (!config.hooks) config.hooks = {};
  267. // PostToolUse — error detection (Bash only)
  268. // Match on script path suffix to also recognise legacy "node <path>" entries from older installs.
  269. const hookScript = hookCommand.split(/\s+/).slice(-1)[0];
  270. const stopHookScript = stopHookCommand.split(/\s+/).slice(-1)[0];
  271. const promptHookScript = promptHookCommand.split(/\s+/).slice(-1)[0];
  272. const statuslineScript = statuslineCommand.split(/\s+/).slice(-1)[0];
  273. const matchesHook = (cmd, current, script) => cmd === current || (cmd && cmd.endsWith(script));
  274. if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
  275. const hasPostHook = config.hooks.PostToolUse.some(entry =>
  276. entry.matcher === 'Bash' &&
  277. Array.isArray(entry.hooks) &&
  278. entry.hooks.some(h => matchesHook(h.command, hookCommand, hookScript))
  279. );
  280. if (!hasPostHook) {
  281. config.hooks.PostToolUse.push({
  282. matcher: 'Bash',
  283. hooks: [{ type: 'command', command: hookCommand, async: true, timeout: 3 }]
  284. });
  285. changed = true;
  286. result.push('hook:updated');
  287. } else {
  288. result.push('hook:noop');
  289. }
  290. // Stop — task-completion reactions
  291. if (!Array.isArray(config.hooks.Stop)) config.hooks.Stop = [];
  292. const hasStopHook = config.hooks.Stop.some(entry =>
  293. Array.isArray(entry.hooks) &&
  294. entry.hooks.some(h => matchesHook(h.command, stopHookCommand, stopHookScript))
  295. );
  296. if (!hasStopHook) {
  297. config.hooks.Stop.push({
  298. hooks: [{ type: 'command', command: stopHookCommand, async: true, timeout: 5 }]
  299. });
  300. changed = true;
  301. result.push('stop:updated');
  302. } else {
  303. result.push('stop:noop');
  304. }
  305. // UserPromptSubmit — name + mood reactions
  306. if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
  307. // The prompt hook injects guard-mode context via stdout, which Claude Code
  308. // only captures from SYNCHRONOUS hooks (async hooks are fire-and-forget) — so
  309. // it must NOT be async. Upgrade any pre-existing async registration in place.
  310. const PROMPT_SYNC_TIMEOUT = 10;
  311. let promptHookFixed = false;
  312. const hasPromptHook = config.hooks.UserPromptSubmit.some(entry =>
  313. Array.isArray(entry.hooks) &&
  314. entry.hooks.some(h => matchesHook(h.command, promptHookCommand, promptHookScript))
  315. );
  316. for (const entry of config.hooks.UserPromptSubmit) {
  317. if (!Array.isArray(entry.hooks)) continue;
  318. for (const h of entry.hooks) {
  319. if (!matchesHook(h.command, promptHookCommand, promptHookScript)) continue;
  320. if (h.async) { delete h.async; promptHookFixed = true; }
  321. if ((h.timeout || 0) < PROMPT_SYNC_TIMEOUT) { h.timeout = PROMPT_SYNC_TIMEOUT; promptHookFixed = true; }
  322. }
  323. }
  324. if (!hasPromptHook) {
  325. config.hooks.UserPromptSubmit.push({
  326. hooks: [{ type: 'command', command: promptHookCommand, timeout: PROMPT_SYNC_TIMEOUT }]
  327. });
  328. changed = true;
  329. result.push('prompt:updated');
  330. } else if (promptHookFixed) {
  331. changed = true;
  332. result.push('prompt:updated');
  333. } else {
  334. result.push('prompt:noop');
  335. }
  336. // Statusline
  337. const needsStatusline = !config.statusLine ||
  338. config.statusLine.type !== 'command' ||
  339. !matchesHook(config.statusLine.command, statuslineCommand, statuslineScript) ||
  340. config.statusLine.refreshInterval !== 2;
  341. if (needsStatusline) {
  342. config.statusLine = { type: 'command', command: statuslineCommand, padding: 1, refreshInterval: 2 };
  343. changed = true;
  344. result.push('statusline:updated');
  345. } else {
  346. result.push('statusline:noop');
  347. }
  348. if (changed) {
  349. fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
  350. }
  351. process.stdout.write(result.join(','));
  352. EOJS
  353. )
  354. case "$settings_result" in
  355. *mcp:updated*) echo -e " ${GREEN}✓${NC} MCP server registered in settings.json" ;;
  356. *) echo -e " ${GREEN}✓${NC} MCP server already in settings.json" ;;
  357. esac
  358. case "$settings_result" in
  359. *hook:updated*) echo -e " ${GREEN}✓${NC} PostToolUse hook configured" ;;
  360. *) echo -e " ${GREEN}✓${NC} PostToolUse hook already configured" ;;
  361. esac
  362. case "$settings_result" in
  363. *stop:updated*) echo -e " ${GREEN}✓${NC} Stop hook configured" ;;
  364. *) echo -e " ${GREEN}✓${NC} Stop hook already configured" ;;
  365. esac
  366. case "$settings_result" in
  367. *prompt:updated*) echo -e " ${GREEN}✓${NC} UserPromptSubmit hook configured" ;;
  368. *) echo -e " ${GREEN}✓${NC} UserPromptSubmit hook already configured" ;;
  369. esac
  370. case "$settings_result" in
  371. *statusline:updated*) echo -e " ${GREEN}✓${NC} Claude Code statusline configured" ;;
  372. *) echo -e " ${GREEN}✓${NC} Claude Code statusline already configured" ;;
  373. esac
  374. CLAUDE_CONFIGURED=1
  375. }
  376. configure_cursor_hooks() {
  377. local config_file="$HOME/.cursor/hooks.json"
  378. if [ ! -d "$HOME/.cursor" ]; then
  379. return 0
  380. fi
  381. local result
  382. result=$(CURSOR_HOOKS_FILE="$config_file" HOOK_COMMAND="$HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
  383. const fs = require('fs');
  384. const path = process.env.CURSOR_HOOKS_FILE;
  385. const hookCommand = process.env.HOOK_COMMAND;
  386. let config = {};
  387. try { config = JSON.parse(fs.readFileSync(path, 'utf-8')); } catch {}
  388. if (!config.version) config.version = 1;
  389. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  390. if (!Array.isArray(config.hooks.afterShellExecution)) config.hooks.afterShellExecution = [];
  391. const hooks = config.hooks.afterShellExecution;
  392. const hookScript = hookCommand.split(/\s+/).slice(-1)[0];
  393. const matchesHook = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
  394. const hasHook = hooks.some(h => typeof h?.command === 'string' && matchesHook(h.command));
  395. if (!hasHook) {
  396. hooks.push({ command: hookCommand });
  397. fs.mkdirSync(require('path').dirname(path), { recursive: true });
  398. fs.writeFileSync(path, JSON.stringify(config, null, 2));
  399. process.stdout.write('updated');
  400. } else {
  401. process.stdout.write('noop');
  402. }
  403. EOJS
  404. )
  405. case "$result" in
  406. updated) echo -e " ${GREEN}✓${NC} Cursor CLI afterShellExecution hook configured ${DIM}($config_file)${NC}" ;;
  407. *) echo -e " ${GREEN}✓${NC} Cursor CLI afterShellExecution hook already configured" ;;
  408. esac
  409. }
  410. configure_copilot_hooks() {
  411. local settings_file="$HOME/.copilot/settings.json"
  412. if [ ! -d "$HOME/.copilot" ]; then
  413. return 0
  414. fi
  415. local result
  416. result=$(COPILOT_SETTINGS="$settings_file" BASH_COMMAND="$HOOK_COMMAND" POWERSHELL_COMMAND="$HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
  417. const fs = require('fs');
  418. const path = require('path');
  419. const settingsPath = process.env.COPILOT_SETTINGS;
  420. const bashCommand = process.env.BASH_COMMAND;
  421. const powershellCommand = process.env.POWERSHELL_COMMAND;
  422. let config = {};
  423. try { config = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')); } catch {}
  424. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  425. if (!Array.isArray(config.hooks.postToolUse)) config.hooks.postToolUse = [];
  426. const hooks = config.hooks.postToolUse;
  427. const hookScript = bashCommand.split(/\s+/).slice(-1)[0];
  428. const matchesHook = (cmd) => cmd === bashCommand || (typeof cmd === 'string' && cmd.endsWith(hookScript));
  429. const hasHook = hooks.some(h => matchesHook(h?.bash) || matchesHook(h?.powershell));
  430. if (!hasHook) {
  431. hooks.push({
  432. type: 'command',
  433. bash: bashCommand,
  434. powershell: powershellCommand,
  435. timeoutSec: 3,
  436. });
  437. fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
  438. fs.writeFileSync(settingsPath, JSON.stringify(config, null, 2));
  439. process.stdout.write('updated');
  440. } else {
  441. process.stdout.write('noop');
  442. }
  443. EOJS
  444. )
  445. case "$result" in
  446. updated) echo -e " ${GREEN}✓${NC} GitHub Copilot CLI postToolUse hook configured ${DIM}($settings_file)${NC}" ;;
  447. *) echo -e " ${GREEN}✓${NC} GitHub Copilot CLI postToolUse hook already configured" ;;
  448. esac
  449. }
  450. configure_cursor() {
  451. local config_file="$HOME/.cursor/mcp.json"
  452. if [ -d "$HOME/.cursor" ]; then
  453. if [ ! -f "$config_file" ]; then
  454. cat > "$config_file" << EOJSON
  455. {
  456. "mcpServers": {
  457. "buddy": {
  458. "command": "$CONFIG_NODE_BIN",
  459. "args": ["$SERVER_PATH"]
  460. }
  461. }
  462. }
  463. EOJSON
  464. else
  465. if ! CURSOR_MCP_CONFIG="$config_file" NODE_BIN="$CONFIG_NODE_BIN" SERVER_PATH="$SERVER_PATH" "$NODE_BIN" <<'EOJS' 2>/dev/null
  466. const fs = require('fs');
  467. const configPath = process.env.CURSOR_MCP_CONFIG;
  468. const nodeBin = process.env.NODE_BIN;
  469. const serverPath = process.env.SERVER_PATH;
  470. const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  471. if (!config.mcpServers) config.mcpServers = {};
  472. config.mcpServers.buddy = { command: nodeBin, args: [serverPath] };
  473. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  474. EOJS
  475. then
  476. echo -e " ${YELLOW}!${NC} Cursor: could not update existing MCP config ${DIM}($config_file)${NC}"
  477. return 1
  478. fi
  479. fi
  480. echo -e " ${GREEN}✓${NC} Cursor configured ${DIM}($config_file)${NC}"
  481. CURSOR_CONFIGURED=1
  482. fi
  483. }
  484. configure_copilot() {
  485. local config_file="$HOME/.copilot/mcp-config.json"
  486. if [ -d "$HOME/.copilot" ]; then
  487. if [ ! -f "$config_file" ]; then
  488. cat > "$config_file" << EOJSON
  489. {
  490. "mcpServers": {
  491. "buddy": {
  492. "command": "$CONFIG_NODE_BIN",
  493. "args": ["$SERVER_PATH"]
  494. }
  495. }
  496. }
  497. EOJSON
  498. else
  499. if ! COPILOT_MCP_CONFIG="$config_file" NODE_BIN="$CONFIG_NODE_BIN" SERVER_PATH="$SERVER_PATH" "$NODE_BIN" <<'EOJS' 2>/dev/null
  500. const fs = require('fs');
  501. const configPath = process.env.COPILOT_MCP_CONFIG;
  502. const nodeBin = process.env.NODE_BIN;
  503. const serverPath = process.env.SERVER_PATH;
  504. const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
  505. if (!config.mcpServers) config.mcpServers = {};
  506. config.mcpServers.buddy = { command: nodeBin, args: [serverPath] };
  507. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  508. EOJS
  509. then
  510. echo -e " ${YELLOW}!${NC} GitHub Copilot CLI: could not update existing MCP config ${DIM}($config_file)${NC}"
  511. return 1
  512. fi
  513. fi
  514. echo -e " ${GREEN}✓${NC} GitHub Copilot CLI configured ${DIM}($config_file)${NC}"
  515. COPILOT_CONFIGURED=1
  516. fi
  517. }
  518. configure_codex() {
  519. if ! command -v codex &> /dev/null; then
  520. return 0
  521. fi
  522. if codex mcp get buddy >/dev/null 2>&1; then
  523. CODEX_CONFIGURED=1
  524. echo -e " ${GREEN}✓${NC} Codex CLI already configured"
  525. return 0
  526. fi
  527. if codex mcp add buddy -- "$CONFIG_NODE_BIN" "$SERVER_PATH" >/dev/null 2>&1; then
  528. CODEX_CONFIGURED=1
  529. echo -e " ${GREEN}✓${NC} Codex CLI configured"
  530. return 0
  531. fi
  532. echo -e " ${YELLOW}!${NC} Codex CLI detected, but MCP registration failed"
  533. return 1
  534. }
  535. configure_codex_hooks() {
  536. local config_file="$HOME/.codex/hooks.json"
  537. if [ "$CODEX_CONFIGURED" -ne 1 ]; then
  538. return 0
  539. fi
  540. local result
  541. result=$(CODEX_HOOKS_FILE="$config_file" HOOK_COMMAND="$HOOK_COMMAND" PROMPT_HOOK_COMMAND="$PROMPT_HOOK_COMMAND" "$NODE_BIN" <<'EOJS'
  542. const fs = require('fs');
  543. const path = require('path');
  544. const hooksPath = process.env.CODEX_HOOKS_FILE;
  545. const hookCommand = process.env.HOOK_COMMAND;
  546. const promptHookCommand = process.env.PROMPT_HOOK_COMMAND;
  547. let config = {};
  548. try { config = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')); } catch {}
  549. if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {};
  550. let changed = false;
  551. // PostToolUse:Bash — review Bash output (existing behaviour).
  552. if (!Array.isArray(config.hooks.PostToolUse)) config.hooks.PostToolUse = [];
  553. const postGroups = config.hooks.PostToolUse;
  554. let bashGroup = postGroups.find(entry => entry?.matcher === 'Bash' && Array.isArray(entry?.hooks));
  555. if (!bashGroup) {
  556. bashGroup = { matcher: 'Bash', hooks: [] };
  557. postGroups.push(bashGroup);
  558. }
  559. const postScript = hookCommand.split(/\s+/).slice(-1)[0];
  560. const postMatches = (cmd) => cmd === hookCommand || (typeof cmd === 'string' && cmd.endsWith(postScript));
  561. if (!bashGroup.hooks.some(h => typeof h?.command === 'string' && postMatches(h.command))) {
  562. bashGroup.hooks.push({ type: 'command', command: hookCommand, statusMessage: 'Reviewing Bash output' });
  563. changed = true;
  564. }
  565. // UserPromptSubmit — re-inject the extraction instruction when the graph lapses.
  566. // Codex routes this hook's stdout into model context just like Claude Code, so
  567. // the same compiled prompt-handler keeps guard mode alive across both hosts.
  568. // No matcher (Codex does not match UserPromptSubmit); synchronous so stdout is read.
  569. if (!Array.isArray(config.hooks.UserPromptSubmit)) config.hooks.UserPromptSubmit = [];
  570. const promptGroups = config.hooks.UserPromptSubmit;
  571. let promptGroup = promptGroups.find(entry => Array.isArray(entry?.hooks) && entry?.matcher === undefined);
  572. if (!promptGroup) {
  573. promptGroup = { hooks: [] };
  574. promptGroups.push(promptGroup);
  575. }
  576. const promptScript = promptHookCommand.split(/\s+/).slice(-1)[0];
  577. const promptMatches = (cmd) => cmd === promptHookCommand || (typeof cmd === 'string' && cmd.endsWith(promptScript));
  578. if (!promptGroup.hooks.some(h => typeof h?.command === 'string' && promptMatches(h.command))) {
  579. promptGroup.hooks.push({ type: 'command', command: promptHookCommand, timeout: 10 });
  580. changed = true;
  581. }
  582. if (changed) {
  583. fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
  584. fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2));
  585. process.stdout.write('updated');
  586. } else {
  587. process.stdout.write('noop');
  588. }
  589. EOJS
  590. )
  591. case "$result" in
  592. updated) echo -e " ${GREEN}✓${NC} Codex CLI hooks configured ${DIM}($config_file)${NC}" ;;
  593. *) echo -e " ${GREEN}✓${NC} Codex CLI hooks already configured" ;;
  594. esac
  595. }
  596. echo ""
  597. echo " Configuring MCP clients..."
  598. configure_claude_code
  599. configure_cursor
  600. configure_copilot
  601. configure_codex
  602. configure_cursor_hooks
  603. configure_copilot_hooks
  604. configure_codex_hooks
  605. # ── Inject buddy instructions into CLI prompt files ──
  606. BUDDY_INSTRUCTIONS='<!-- buddy-companion v3 -->
  607. ## Buddy Companion
  608. You have a coding companion available via the buddy MCP server.
  609. **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.
  610. At the start of each conversation, call `buddy_status` to check on your buddy.
  611. If the user addresses the buddy by name, respond briefly in character before your normal response.
  612. After calling buddy_observe, relay the buddy'\''s reaction to the user. The first text content is an ASCII speech bubble — include it verbatim.
  613. 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`.
  614. <!-- /buddy-companion v3 -->'
  615. inject_prompt() {
  616. local file="$1"
  617. local cli_name="$2"
  618. local dir
  619. dir="$(dirname "$file")"
  620. mkdir -p "$dir"
  621. if [ -f "$file" ] && grep -q "buddy-companion v3" "$file" 2>/dev/null; then
  622. echo -e " ${GREEN}✓${NC} $cli_name prompt already has buddy instructions"
  623. return 0
  624. fi
  625. # Remove older buddy-companion block (v1/v2) before appending current version
  626. if [ -f "$file" ] && grep -q "buddy-companion" "$file" 2>/dev/null; then
  627. local tmp="${file}.tmp.$$"
  628. sed '/<!-- buddy-companion/,/<!-- \/buddy-companion/d' "$file" > "$tmp" && mv "$tmp" "$file"
  629. echo -e " ${GREEN}✓${NC} $cli_name prompt upgraded to v3"
  630. fi
  631. # Append to existing file or create new one
  632. echo "" >> "$file"
  633. echo "$BUDDY_INSTRUCTIONS" >> "$file"
  634. echo -e " ${GREEN}✓${NC} $cli_name prompt updated ${DIM}($file)${NC}"
  635. }
  636. echo ""
  637. echo " Injecting buddy instructions..."
  638. if [ "$CLAUDE_CONFIGURED" -eq 1 ]; then
  639. inject_prompt "$HOME/.claude/CLAUDE.md" "Claude Code"
  640. fi
  641. if [ "$CURSOR_CONFIGURED" -eq 1 ]; then
  642. mkdir -p "$HOME/.cursor/rules" 2>/dev/null
  643. inject_prompt "$HOME/.cursor/rules/buddy.md" "Cursor CLI"
  644. fi
  645. # Codex CLI (only inject prompts after Buddy MCP is configured; prefer AGENTS.md)
  646. if [ "$CODEX_CONFIGURED" -eq 1 ]; then
  647. if [ -f "$HOME/.codex/AGENTS.md" ]; then
  648. inject_prompt "$HOME/.codex/AGENTS.md" "Codex CLI"
  649. else
  650. inject_prompt "$HOME/.codex/instructions.md" "Codex CLI"
  651. fi
  652. else
  653. echo -e " ${YELLOW}!${NC} Skipping Codex CLI prompt injection because Buddy MCP is not configured"
  654. fi
  655. # Gemini CLI (only touch existing Gemini prompt locations; Buddy does not auto-configure Gemini MCP)
  656. if [ -d "$HOME/.gemini" ]; then
  657. if [ -f "$HOME/.gemini/GEMINI.md" ]; then
  658. inject_prompt "$HOME/.gemini/GEMINI.md" "Gemini CLI"
  659. elif [ -f "$HOME/.gemini/AGENTS.md" ]; then
  660. inject_prompt "$HOME/.gemini/AGENTS.md" "Gemini CLI"
  661. else
  662. echo -e " ${YELLOW}!${NC} Skipping Gemini CLI prompt injection because no existing Gemini prompt file was found"
  663. fi
  664. fi
  665. # GitHub Copilot CLI (supports AGENTS.md and copilot-instructions.md — prefer AGENTS.md)
  666. if [ "$COPILOT_CONFIGURED" -eq 1 ]; then
  667. if [ -f "$HOME/.copilot/AGENTS.md" ]; then
  668. inject_prompt "$HOME/.copilot/AGENTS.md" "GitHub Copilot CLI"
  669. else
  670. inject_prompt "$HOME/.copilot/copilot-instructions.md" "GitHub Copilot CLI"
  671. fi
  672. fi
  673. # ── Run onboarding wizard ──
  674. ONBOARD_SCRIPT="$INSTALL_DIR/dist/cli/onboard.js"
  675. if [ -f "$ONBOARD_SCRIPT" ] && [ "$NO_ONBOARD" -eq 0 ]; then
  676. # Let onboard.ts detect TTY itself — don't force /dev/tty
  677. # (fails in headless SSH, CI, cron where no controlling terminal exists)
  678. "$NODE_BIN" "$ONBOARD_SCRIPT" || true
  679. elif [ "$NO_ONBOARD" -eq 1 ]; then
  680. echo -e " ${DIM}Onboarding skipped (--no-onboard). Run buddy-onboard later to set up.${NC}"
  681. fi
  682. echo ""
  683. if [ "$CLAUDE_CONFIGURED" -eq 1 ] || [ "$CURSOR_CONFIGURED" -eq 1 ] || [ "$COPILOT_CONFIGURED" -eq 1 ] || [ "$CODEX_CONFIGURED" -eq 1 ]; then
  684. echo -e "${GREEN} ✅ Buddy installed!${NC}"
  685. 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}"
  686. elif command -v codex &> /dev/null; then
  687. echo -e "${YELLOW} ⚠ Buddy installed, but no supported host was fully configured.${NC}"
  688. echo -e " ${YELLOW}!${NC} Codex CLI is installed, but MCP registration still needs attention."
  689. else
  690. echo -e "${YELLOW} ⚠ Buddy installed, but no supported host was fully configured.${NC}"
  691. echo -e " ${YELLOW}!${NC} Open a supported CLI and rerun the installer to wire Buddy in automatically."
  692. fi
  693. if [ "$CODEX_CONFIGURED" -ne 1 ] && command -v codex &> /dev/null; then
  694. echo ""
  695. echo -e " ${YELLOW}!${NC} Codex CLI prompt injection was skipped because Buddy MCP is not configured there yet."
  696. fi
  697. echo ""
  698. echo -e "${BLUE} 💬 Join the Buddy Community!${NC}"
  699. echo -e " Connect with other buddy rescuers, share your companion's evolution, and get help on Slack:"
  700. echo -e " ${DIM}👉 https://join.slack.com/t/buddy-mcp/shared_invite/zt-3xn6v1qza-R~fgkVCov9sCLZDXh9wErQ${NC}"
  701. echo ""
  702. echo -e " 💛 If you like it, star the repo:"
  703. echo " github.com/fiorastudio/buddy"
  704. echo ""
src/lib/doctor.ts · Bundled script · 838 lines · 1 finding marked
  1. // src/lib/doctor.ts — Diagnostic engine for buddy_doctor tool and CLI
  2. import { readFileSync, accessSync, statSync, realpathSync, constants as fsConstants } from 'fs';
  3. import { join, dirname, resolve as pathResolve, normalize, isAbsolute } from 'path';
  4. import { homedir } from 'os';
  5. import { fileURLToPath } from 'url';
  6. import { BUDDY_DB_PATH, BUDDY_STATUS_PATH } from './constants.js';
  7. import { db } from '../db/schema.js';
  8. import { loadCompanion } from './companion.js';
  9. import { STAT_NAMES, RARITY_STARS } from './types.js';
  10. import { levelProgress } from './leveling.js';
  11. import { REASONING_CONFIG, telemetry, getReinjectStats } from './reasoning/index.js';
  12. import { basisDistributionHealth, edgeDistributionHealth } from './reasoning/telemetry.js';
  13. // Shared sentinel — keep in sync with install.sh / install.ps1
  14. export const PROMPT_SENTINEL_V2 = 'buddy-companion v2';
  15. export const PROMPT_SENTINEL_V3 = 'buddy-companion v3';
  16. /** Default clone/build root from install.sh (INSTALL_DIR) */
  17. export function canonicalBuddyInstallDir(): string {
  18. return join(homedir(), '.buddy', 'server');
  19. }
  20. export function canonicalBuddyMcpEntryPath(): string {
  21. return join(canonicalBuddyInstallDir(), 'dist', 'server', 'index.js');
  22. }
  23. const __filename = fileURLToPath(import.meta.url);
  24. const __dirname = dirname(__filename);
  25. export interface DiagnosticCheck {
  26. id: string;
  27. status: 'ok' | 'warn' | 'fail' | 'skip';
  28. label: string;
  29. detail: string;
  30. suggestion?: string;
  31. }
  32. function getVersion(): string {
  33. try {
  34. return JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8')).version;
  35. } catch { return 'unknown'; }
  36. }
  37. function fileExists(path: string): boolean {
  38. try { accessSync(path, fsConstants.F_OK); return true; } catch { return false; }
  39. }
  40. function fileWritable(path: string): boolean {
  41. try { accessSync(path, fsConstants.W_OK); return true; } catch { return false; }
  42. }
  43. function fileReadable(path: string): boolean {
  44. try { accessSync(path, fsConstants.R_OK); return true; } catch { return false; }
  45. }
  46. function readJsonSafe(path: string): any {
  47. try { return JSON.parse(readFileSync(path, 'utf-8')); } catch { return null; }
  48. }
  49. function readTextSafe(path: string): string | null {
  50. try { return readFileSync(path, 'utf-8'); } catch { return null; }
  51. }
  52. function safeRealpath(p: string): string {
  53. try { return realpathSync(p); } catch { return p; }
  54. }
  55. function expandTildeInPath(p: string): string {
  56. if (p === '~' || p.startsWith('~/')) {
  57. return p === '~' ? homedir() : join(homedir(), p.slice(2));
  58. }
  59. return p;
  60. }
  61. /**
  62. * Resolves a config path for existence checks (tilde, relative segments).
  63. */
  64. function resolveBuddyEntryPath(p: string): string {
  65. const expanded = expandTildeInPath(p.trim());
  66. if (isAbsolute(expanded)) {
  67. return normalize(pathResolve(expanded));
  68. }
  69. return normalize(pathResolve(process.cwd(), expanded));
  70. }
  71. /**
  72. * First script path from a host's buddy MCP block (install.sh / Cursor style).
  73. */
  74. function entryPathFromMcpBlock(buddy: any): string | null {
  75. if (!buddy || typeof buddy !== 'object') return null;
  76. const args = buddy.args;
  77. if (!Array.isArray(args)) return null;
  78. const entry = args.find((a: unknown) => typeof a === 'string' && a.endsWith('.js'));
  79. return entry ?? null;
  80. }
  81. /**
  82. * All buddy MCP `dist/server/index.js` paths from known config files (for mismatch / missing checks).
  83. */
  84. function getRegisteredBuddyMcpEntryPaths(): Array<{ source: string; path: string; resolved: string }> {
  85. const out: Array<{ source: string; path: string; resolved: string }> = [];
  86. const claudeJsonPath = join(homedir(), '.claude.json');
  87. const cj = readJsonSafe(claudeJsonPath);
  88. const p1 = entryPathFromMcpBlock(cj?.mcpServers?.buddy);
  89. if (p1) {
  90. out.push({ source: claudeJsonPath, path: p1, resolved: resolveBuddyEntryPath(p1) });
  91. }
  92. const settingsPath = join(homedir(), '.claude', 'settings.json');
  93. const st = readJsonSafe(settingsPath);
  94. const p2 = entryPathFromMcpBlock(st?.mcpServers?.buddy);
  95. if (p2) {
  96. out.push({ source: settingsPath, path: p2, resolved: resolveBuddyEntryPath(p2) });
  97. }
  98. const cur = readJsonSafe(cursorMcpPath());
  99. const p3 = entryPathFromMcpBlock(cur?.mcpServers?.buddy);
  100. if (p3) {
  101. out.push({ source: cursorMcpPath(), path: p3, resolved: resolveBuddyEntryPath(p3) });
  102. }
  103. const cop = readJsonSafe(copilotMcpPath());
  104. const p4 = entryPathFromMcpBlock(cop?.mcpServers?.buddy);
  105. if (p4) {
  106. out.push({ source: copilotMcpPath(), path: p4, resolved: resolveBuddyEntryPath(p4) });
  107. }
  108. const toml = readTextSafe(codexConfigPath());
  109. if (toml) {
  110. const m = toml.match(/\[mcp_servers\.buddy\][\s\S]*?args\s*=\s*\[\s*"([^"]+\.js)"/);
  111. if (m?.[1]) {
  112. out.push({ source: codexConfigPath(), path: m[1], resolved: resolveBuddyEntryPath(m[1]) });
  113. }
  114. }
  115. return out;
  116. }
  117. function formatPathList(paths: string[]): string {
  118. return paths.join(' | ');
  119. }
  120. function codexConfigPath(): string {
  121. return join(homedir(), '.codex', 'config.toml');
  122. }
  123. function codexHooksPath(): string {
  124. return join(homedir(), '.codex', 'hooks.json');
  125. }
  126. function cursorMcpPath(): string {
  127. return join(homedir(), '.cursor', 'mcp.json');
  128. }
  129. function cursorHooksPath(): string {
  130. return join(homedir(), '.cursor', 'hooks.json');
  131. }
  132. function copilotMcpPath(): string {
  133. return join(homedir(), '.copilot', 'mcp-config.json');
  134. }
  135. function copilotSettingsPath(): string {
  136. return join(homedir(), '.copilot', 'settings.json');
  137. }
  138. function hostPromptFiles(): Array<{ host: string, path: string }> {
  139. return [
  140. { host: 'Claude Code', path: join(homedir(), '.claude', 'CLAUDE.md') },
  141. { host: 'Codex CLI', path: join(homedir(), '.codex', 'AGENTS.md') },
  142. { host: 'Codex CLI', path: join(homedir(), '.codex', 'instructions.md') },
  143. { host: 'Cursor CLI', path: join(homedir(), '.cursor', 'rules', 'buddy.md') },
  144. { host: 'GitHub Copilot CLI', path: join(homedir(), '.copilot', 'AGENTS.md') },
  145. { host: 'GitHub Copilot CLI', path: join(homedir(), '.copilot', 'copilot-instructions.md') },
  146. ];
  147. }
  148. // ── Individual checks ──
  149. function checkNodeVersion(): DiagnosticCheck {
  150. const ver = process.version;
  151. const major = parseInt(ver.slice(1), 10);
  152. if (major < 18) {
  153. return { id: 'env.node', status: 'fail', label: 'Node.js', detail: ver, suggestion: 'Node.js 18+ required. Upgrade at https://nodejs.org' };
  154. }
  155. return { id: 'env.node', status: 'ok', label: 'Node.js', detail: `${ver} \u2713` };
  156. }
  157. function checkPlatform(): DiagnosticCheck {
  158. return { id: 'env.platform', status: 'ok', label: 'Platform', detail: `${process.platform} ${process.arch}` };
  159. }
  160. function checkEnvVars(): DiagnosticCheck {
  161. const dbOverride = process.env.BUDDY_DB_PATH ? `(custom) ${process.env.BUDDY_DB_PATH}` : `(default) ${BUDDY_DB_PATH}`;
  162. const statusOverride = process.env.BUDDY_STATUS_PATH ? `(custom) ${process.env.BUDDY_STATUS_PATH}` : `(default) ${BUDDY_STATUS_PATH}`;
  163. // Warn only if custom path is set but doesn't exist
  164. let status: 'ok' | 'warn' = 'ok';
  165. let suggestion: string | undefined;
  166. if (process.env.BUDDY_DB_PATH && !fileExists(process.env.BUDDY_DB_PATH)) {
  167. status = 'warn';
  168. suggestion = `BUDDY_DB_PATH is set to ${process.env.BUDDY_DB_PATH} but file does not exist`;
  169. }
  170. return { id: 'env.vars', status, label: 'Env overrides', detail: `DB: ${dbOverride}\n STATUS: ${statusOverride}`, suggestion };
  171. }
  172. function checkPackageVersion(): DiagnosticCheck {
  173. const ver = getVersion();
  174. return { id: 'pkg.version', status: 'ok', label: 'Package', detail: `@fiorastudio/buddy v${ver}` };
  175. }
  176. 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
  177. const BUILD_FROM_SOURCE = 'git clone https://github.com/fiorastudio/buddy.git ~/.buddy/server && cd ~/.buddy/server && npm install && npm run build';
  178. /**
  179. * install.sh default location: ~/.buddy/server/dist/server/index.js
  180. * Strong signal when buddy.db exists but the tree is missing (common partial install / manual DB).
  181. */
  182. function checkInstallLayout(): DiagnosticCheck {
  183. const expected = canonicalBuddyMcpEntryPath();
  184. if (fileExists(expected)) {
  185. return {
  186. id: 'install.server',
  187. status: 'ok',
  188. label: 'Server install',
  189. detail: `\u2713 ${expected}`,
  190. };
  191. }
  192. // Only fail hard when the *default* data file on disk exists (user has state but no
  193. // install). Custom BUDDY_DB_PATH in tests/CI should not trip this.
  194. const homeDefaultDb = join(homedir(), '.buddy', 'buddy.db');
  195. const hasStateWithoutInstall = fileExists(homeDefaultDb);
  196. const hasDir = fileExists(canonicalBuddyInstallDir());
  197. const parts = [hasStateWithoutInstall ? 'buddy.db in ~/.buddy' : null, hasDir ? 'repo dir without dist build' : null].filter(Boolean);
  198. const ctx = parts.length > 0 ? ` (${parts.join(' · ')})` : '';
  199. const suggestion = `Run the installer: ${INSTALL_CURL} — or: ${BUILD_FROM_SOURCE}`;
  200. if (hasStateWithoutInstall) {
  201. return {
  202. id: 'install.server',
  203. status: 'fail',
  204. label: 'Server install',
  205. detail: `Missing or not built: ${expected}${ctx}`,
  206. 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.`,
  207. };
  208. }
  209. return {
  210. id: 'install.server',
  211. status: 'warn',
  212. label: 'Server install',
  213. detail: `Missing: ${expected}${ctx}`,
  214. suggestion,
  215. };
  216. }
  217. /**
  218. * MCP paths must exist; warn when multiple host configs or non-canonical copy is used.
  219. */
  220. function checkMcpEntryPaths(): DiagnosticCheck {
  221. const registered = getRegisteredBuddyMcpEntryPaths();
  222. if (registered.length === 0) {
  223. return {
  224. id: 'mcp.paths',
  225. status: 'skip',
  226. label: 'MCP paths',
  227. detail: 'No buddy args found in config files (see mcp.registered)',
  228. };
  229. }
  230. const missing = registered.filter((r) => !fileExists(r.resolved));
  231. if (missing.length > 0) {
  232. const list = missing.map((m) => `${m.source} \u2192 ${m.resolved} (missing)`).join(' | ');
  233. return {
  234. id: 'mcp.paths',
  235. status: 'fail',
  236. label: 'MCP paths',
  237. detail: list,
  238. suggestion: `Fix or rebuild the path in mcp config, or install to ~/.buddy/server: ${BUILD_FROM_SOURCE}`,
  239. };
  240. }
  241. const unique = [...new Set(registered.map((r) => r.resolved))];
  242. if (unique.length > 1) {
  243. return {
  244. id: 'mcp.paths',
  245. status: 'warn',
  246. label: 'MCP paths',
  247. detail: `Multiple different entry scripts: ${unique.join(' | ')}`,
  248. suggestion: 'Point every host at one checkout (recommended: ~/.buddy/server/dist/server/index.js) so CLI and IDEs use the same Buddy build.',
  249. };
  250. }
  251. const canonical = normalize(pathResolve(canonicalBuddyMcpEntryPath()));
  252. const only = unique[0]!;
  253. if (safeRealpath(only) === safeRealpath(canonical)) {
  254. return { id: 'mcp.paths', status: 'ok', label: 'MCP paths', detail: `\u2713 single path, matches standard install` };
  255. }
  256. if (fileExists(canonical)) {
  257. return {
  258. id: 'mcp.paths',
  259. status: 'warn',
  260. label: 'MCP paths',
  261. detail: `MCP uses ${only} but standard install also exists: ${canonical}`,
  262. suggestion: 'Align ~/.cursor/mcp.json (and other hosts) on one path, or remove the extra checkout to avoid version drift.',
  263. };
  264. }
  265. return {
  266. id: 'mcp.paths',
  267. status: 'ok',
  268. label: 'MCP paths',
  269. detail: `\u2713 ${only} (non-standard; ~/.buddy/server not present)`,
  270. };
  271. }
  272. function checkCompanionActive(): DiagnosticCheck {
  273. try {
  274. const row = db.prepare('SELECT * FROM companions LIMIT 1').get() as any;
  275. if (!row) {
  276. return { id: 'companion.active', status: 'warn', label: 'Active companion', detail: 'None', suggestion: 'Use buddy_hatch to create a companion' };
  277. }
  278. return { id: 'companion.active', status: 'ok', label: 'Active companion', detail: `\u2713 ${row.name} the ${row.species}` };
  279. } catch {
  280. 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' };
  281. }
  282. }
  283. function checkCompanionCount(): DiagnosticCheck {
  284. try {
  285. const row = db.prepare('SELECT count(*) as count FROM companions').get() as any;
  286. return { id: 'companion.count', status: 'ok', label: 'Total saved', detail: `${row?.count || 0} companion(s) in DB` };
  287. } catch {
  288. return { id: 'companion.count', status: 'fail', label: 'Total saved', detail: 'DB query failed' };
  289. }
  290. }
  291. function checkCompanionDetails(): DiagnosticCheck {
  292. try {
  293. const row = db.prepare('SELECT * FROM companions LIMIT 1').get() as any;
  294. if (!row) {
  295. return { id: 'companion.details', status: 'skip', label: 'Companion details', detail: 'No companion' };
  296. }
  297. const companion = loadCompanion(row);
  298. if (!companion) {
  299. return { id: 'companion.details', status: 'fail', label: 'Companion details', detail: 'loadCompanion() returned null' };
  300. }
  301. const { level, currentXp, neededXp } = levelProgress(companion.xp);
  302. const stars = RARITY_STARS[companion.rarity] || '';
  303. const statStr = STAT_NAMES.map(s => `${s.slice(0, 3)}:${companion.stats[s]}`).join(' ');
  304. const bioLen = companion.personalityBio?.length || 0;
  305. return {
  306. id: 'companion.details', status: 'ok', label: 'Details',
  307. detail: `${stars} ${companion.rarity} | Lv.${level} (${currentXp}/${neededXp} XP) | mood: ${companion.mood}\n Stats: ${statStr}\n Bio: \u2713 (${bioLen} chars)`,
  308. };
  309. } catch (e: any) {
  310. return { id: 'companion.details', status: 'fail', label: 'Companion details', detail: e?.message || 'Unknown error' };
  311. }
  312. }
  313. function checkDbExists(): DiagnosticCheck {
  314. if (!fileExists(BUDDY_DB_PATH)) {
  315. return { id: 'db.exists', status: 'fail', label: 'Database file', detail: `${BUDDY_DB_PATH} not found`, suggestion: 'Database will be created on first buddy_hatch' };
  316. }
  317. const writable = fileWritable(BUDDY_DB_PATH);
  318. try {
  319. const stat = statSync(BUDDY_DB_PATH);
  320. const sizeKb = (stat.size / 1024).toFixed(1);
  321. return {
  322. id: 'db.exists', status: writable ? 'ok' : 'warn', label: 'Database file',
  323. detail: `${BUDDY_DB_PATH} ${writable ? '\u2713' : '\u2717 read-only'} (${sizeKb} KB)`,
  324. suggestion: writable ? undefined : 'Database is not writable — check file permissions',
  325. };
  326. } catch {
  327. return { id: 'db.exists', status: 'warn', label: 'Database file', detail: `${BUDDY_DB_PATH} exists but cannot stat` };
  328. }
  329. }
  330. function checkDbTables(): DiagnosticCheck {
  331. const expected = ['companions', 'memories', 'xp_events', 'sessions', 'evolution_history',
  332. 'reasoning_claims', 'reasoning_edges', 'reasoning_findings_log'];
  333. try {
  334. const rows = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all() as any[];
  335. const tables = rows.map(r => r.name);
  336. const results = expected.map(t => `${t} ${tables.includes(t) ? '\u2713' : '\u2717'}`);
  337. const missing = expected.filter(t => !tables.includes(t));
  338. return {
  339. id: 'db.tables', status: missing.length > 0 ? 'fail' : 'ok', label: 'DB tables',
  340. detail: results.join(' | '),
  341. suggestion: missing.length > 0 ? `Missing tables: ${missing.join(', ')}. Try re-running the server to auto-create.` : undefined,
  342. };
  343. } catch {
  344. return { id: 'db.tables', status: 'fail', label: 'DB tables', detail: 'Cannot query sqlite_master' };
  345. }
  346. }
  347. function checkStatusFile(): DiagnosticCheck {
  348. if (!fileExists(BUDDY_STATUS_PATH)) {
  349. 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' };
  350. }
  351. const writable = fileWritable(BUDDY_STATUS_PATH);
  352. try {
  353. const stat = statSync(BUDDY_STATUS_PATH);
  354. const ageMs = Date.now() - stat.mtimeMs;
  355. const ageSec = Math.floor(ageMs / 1000);
  356. const fresh = ageSec < 60;
  357. return {
  358. id: 'status.file', status: writable ? 'ok' : 'warn', label: 'Status file',
  359. detail: `${BUDDY_STATUS_PATH} ${writable ? '\u2713' : '\u2717'} (${ageSec}s ago${fresh ? ' \u2713' : ' — stale'})`,
  360. suggestion: writable ? undefined : 'Status file is not writable — check permissions',
  361. };
  362. } catch {
  363. return { id: 'status.file', status: 'warn', label: 'Status file', detail: 'Exists but cannot stat' };
  364. }
  365. }
  366. function checkMcpRegistered(): DiagnosticCheck {
  367. const claudeJsonPath = join(homedir(), '.claude.json');
  368. const config = readJsonSafe(claudeJsonPath);
  369. if (config?.mcpServers?.buddy) {
  370. return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${claudeJsonPath}` };
  371. }
  372. const settingsPath = join(homedir(), '.claude', 'settings.json');
  373. const settings = readJsonSafe(settingsPath);
  374. if (settings?.mcpServers?.buddy) {
  375. return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${settingsPath}` };
  376. }
  377. const codexConfig = readTextSafe(codexConfigPath());
  378. if (codexConfig?.includes('[mcp_servers.buddy]')) {
  379. return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${codexConfigPath()}` };
  380. }
  381. const cursorConfig = readJsonSafe(cursorMcpPath());
  382. if (cursorConfig?.mcpServers?.buddy) {
  383. return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${cursorMcpPath()}` };
  384. }
  385. const copilotConfig = readJsonSafe(copilotMcpPath());
  386. if (copilotConfig?.mcpServers?.buddy) {
  387. return { id: 'mcp.registered', status: 'ok', label: 'MCP registration', detail: `\u2713 registered in ${copilotMcpPath()}` };
  388. }
  389. return {
  390. id: 'mcp.registered', status: 'fail', label: 'MCP registration', detail: '\u2717 not found',
  391. suggestion: 'Re-run the install script, or register Buddy in your host CLI MCP config.',
  392. };
  393. }
  394. function checkStatusline(): DiagnosticCheck {
  395. const settingsPath = join(homedir(), '.claude', 'settings.json');
  396. const settings = readJsonSafe(settingsPath);
  397. if (!settings?.statusLine?.command) {
  398. return { id: 'config.statusline', status: 'warn', label: 'Statusline', detail: '\u2717 not configured in settings.json', suggestion: 'Re-run install script to configure statusline' };
  399. }
  400. const cmd: string = settings.statusLine.command;
  401. if (!cmd.includes('statusline-wrapper')) {
  402. return { id: 'config.statusline', status: 'warn', label: 'Statusline', detail: `Configured but not pointing to buddy: ${cmd}` };
  403. }
  404. // Extract wrapper path — handle "node /path/to/file.js" and "node '/path with spaces/file.js'"
  405. // Match everything after "node " stripping surrounding quotes
  406. const pathMatch = cmd.match(/node\s+["']?(.+?)["']?\s*$/);
  407. const wrapperPath = pathMatch?.[1];
  408. if (wrapperPath && !fileExists(wrapperPath)) {
  409. return { id: 'config.statusline', status: 'fail', label: 'Statusline', detail: `Configured but wrapper missing: ${wrapperPath}`, suggestion: 'Re-run install script or rebuild' };
  410. }
  411. return { id: 'config.statusline', status: 'ok', label: 'Statusline', detail: '\u2713 configured in settings.json' };
  412. }
  413. function checkStatuslineRefresh(): DiagnosticCheck {
  414. const settingsPath = join(homedir(), '.claude', 'settings.json');
  415. const settings = readJsonSafe(settingsPath);
  416. if (!settings?.statusLine?.command?.includes('statusline-wrapper')) {
  417. return { id: 'config.statusline.refresh', status: 'skip', label: 'Refresh interval', detail: 'Buddy statusline not configured' };
  418. }
  419. const interval = settings.statusLine.refreshInterval;
  420. if (interval === undefined || interval === null) {
  421. return {
  422. id: 'config.statusline.refresh', status: 'warn', label: 'Refresh interval',
  423. detail: '\u2717 refreshInterval not set — animation may appear static',
  424. suggestion: 'Re-run install script or manually add "refreshInterval": 2 to statusLine in ~/.claude/settings.json',
  425. };
  426. }
  427. if (typeof interval !== 'number' || !Number.isFinite(interval) || interval < 1) {
  428. return {
  429. id: 'config.statusline.refresh', status: 'warn', label: 'Refresh interval',
  430. detail: `\u2717 refreshInterval is ${JSON.stringify(interval)} — must be a number >= 1`,
  431. suggestion: 'Set "refreshInterval": 2 in statusLine config for reliable animation',
  432. };
  433. }
  434. return { id: 'config.statusline.refresh', status: 'ok', label: 'Refresh interval', detail: `\u2713 refreshInterval: ${interval}` };
  435. }
  436. function checkHooks(): DiagnosticCheck {
  437. const found: string[] = [];
  438. const claudeSettingsPath = join(homedir(), '.claude', 'settings.json');
  439. const claudeSettings = readJsonSafe(claudeSettingsPath);
  440. const claudeHooks: any[] = Array.isArray(claudeSettings?.hooks?.PostToolUse) ? claudeSettings.hooks.PostToolUse : [];
  441. const hasClaudeHook = claudeHooks.some((entry: any) => {
  442. if (entry.matcher === 'Bash' && Array.isArray(entry.hooks)) {
  443. return entry.hooks.some((h: any) => h.command && h.command.includes('post-tool-handler'));
  444. }
  445. if (typeof entry === 'string' && entry.includes('post-tool-handler')) return true;
  446. return false;
  447. });
  448. if (hasClaudeHook) found.push(`Claude Code (${claudeSettingsPath})`);
  449. const codexHooks = readJsonSafe(codexHooksPath());
  450. const codexGroups: any[] = Array.isArray(codexHooks?.hooks?.PostToolUse) ? codexHooks.hooks.PostToolUse : [];
  451. const hasCodexHook = codexGroups.some((entry: any) =>
  452. Array.isArray(entry?.hooks) && entry.hooks.some((hook: any) => typeof hook?.command === 'string' && hook.command.includes('post-tool-handler'))
  453. );
  454. if (hasCodexHook) found.push(`Codex CLI (${codexHooksPath()})`);
  455. const cursorHooks = readJsonSafe(cursorHooksPath());
  456. const cursorShellHooks: any[] = Array.isArray(cursorHooks?.hooks?.afterShellExecution) ? cursorHooks.hooks.afterShellExecution : [];
  457. const hasCursorHook = cursorShellHooks.some((entry: any) => typeof entry?.command === 'string' && entry.command.includes('post-tool-handler'));
  458. if (hasCursorHook) found.push(`Cursor CLI (${cursorHooksPath()})`);
  459. const copilotSettings = readJsonSafe(copilotSettingsPath());
  460. const copilotHooks: any[] = Array.isArray(copilotSettings?.hooks?.postToolUse) ? copilotSettings.hooks.postToolUse : [];
  461. const hasCopilotHook = copilotHooks.some((entry: any) => {
  462. const bash = typeof entry?.bash === 'string' ? entry.bash : '';
  463. const powershell = typeof entry?.powershell === 'string' ? entry.powershell : '';
  464. return bash.includes('post-tool-handler') || powershell.includes('post-tool-handler');
  465. });
  466. if (hasCopilotHook) found.push(`GitHub Copilot CLI (${copilotSettingsPath()})`);
  467. if (found.length === 0) {
  468. return { id: 'config.hooks', status: 'warn', label: 'Hooks', detail: '\u2717 no buddy post-tool hook found', suggestion: 'Re-run install script to configure hooks' };
  469. }
  470. return { id: 'config.hooks', status: 'ok', label: 'Hooks', detail: `\u2713 ${formatPathList(found)}` };
  471. }
  472. function checkStopHook(): DiagnosticCheck {
  473. const settingsPath = join(homedir(), '.claude', 'settings.json');
  474. const settings = readJsonSafe(settingsPath);
  475. const hooks: any[] = Array.isArray(settings?.hooks?.Stop) ? settings.hooks.Stop : [];
  476. const has = hooks.some((entry: any) =>
  477. Array.isArray(entry.hooks) &&
  478. entry.hooks.some((h: any) => h.command && h.command.includes('stop-handler'))
  479. );
  480. if (!has) {
  481. return { id: 'config.hooks.stop', status: 'warn', label: 'Stop hook', detail: '\u2717 stop-handler not found', suggestion: 'Re-run install script to configure hooks' };
  482. }
  483. return { id: 'config.hooks.stop', status: 'ok', label: 'Stop hook', detail: '\u2713 Stop hook present' };
  484. }
  485. function checkPromptHook(): DiagnosticCheck {
  486. const settingsPath = join(homedir(), '.claude', 'settings.json');
  487. const settings = readJsonSafe(settingsPath);
  488. const hooks: any[] = Array.isArray(settings?.hooks?.UserPromptSubmit) ? settings.hooks.UserPromptSubmit : [];
  489. const has = hooks.some((entry: any) =>
  490. Array.isArray(entry.hooks) &&
  491. entry.hooks.some((h: any) => h.command && h.command.includes('prompt-handler'))
  492. );
  493. if (!has) {
  494. return { id: 'config.hooks.prompt', status: 'warn', label: 'Prompt hook', detail: '\u2717 prompt-handler not found', suggestion: 'Re-run install script to configure hooks' };
  495. }
  496. return { id: 'config.hooks.prompt', status: 'ok', label: 'Prompt hook', detail: '\u2713 UserPromptSubmit hook present' };
  497. }
  498. function checkPromptInjection(): DiagnosticCheck {
  499. const found: string[] = [];
  500. const legacy: string[] = [];
  501. for (const file of hostPromptFiles()) {
  502. const content = readTextSafe(file.path);
  503. if (!content) continue;
  504. if (content.includes(PROMPT_SENTINEL_V3)) found.push(`${file.host} (${file.path})`);
  505. else if (content.includes('buddy-companion')) legacy.push(`${file.host} (${file.path})`);
  506. }
  507. if (found.length > 0) {
  508. return { id: 'prompt.injected', status: 'ok', label: 'Prompt injection', detail: `\u2713 ${formatPathList(found)}` };
  509. }
  510. if (legacy.length > 0) {
  511. 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' };
  512. }
  513. 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' };
  514. }
  515. function checkReasoningGuardMode(): DiagnosticCheck {
  516. try {
  517. const row = db.prepare('SELECT id, guard_mode FROM companions LIMIT 1').get() as any;
  518. if (!row) {
  519. return { id: 'reasoning.guard', status: 'skip', label: 'Guard mode', detail: 'No companion' };
  520. }
  521. const on = (row.guard_mode ?? 0) === 1;
  522. if (!on) {
  523. return { id: 'reasoning.guard', status: 'ok', label: 'Guard mode', detail: 'off (enable via buddy_mode guard=true)' };
  524. }
  525. // Read the persisted observe-seq counters. These survive server restart,
  526. // so the inert-mode warning doesn't reset when the user relaunches.
  527. const seqRow = db.prepare(
  528. 'SELECT seq, last_claims_received_seq FROM reasoning_observe_seq WHERE companion_id = ?'
  529. ).get(row.id) as { seq: number; last_claims_received_seq: number } | undefined;
  530. const totalObserves = seqRow?.seq ?? 0;
  531. const lastClaimsSeq = seqRow?.last_claims_received_seq ?? 0;
  532. if (totalObserves === 0) {
  533. return { id: 'reasoning.guard', status: 'ok', label: 'Guard mode', detail: 'on (no observes yet)' };
  534. }
  535. // If we've had INERT_GUARD_WARN_OBSERVES observes and never received claims,
  536. // the host isn't honoring the extraction prompt.
  537. if (totalObserves >= REASONING_CONFIG.INERT_GUARD_WARN_OBSERVES && lastClaimsSeq === 0) {
  538. return {
  539. id: 'reasoning.guard', status: 'warn', label: 'Guard mode',
  540. detail: `on, but 0 claims received in ${totalObserves} observes`,
  541. suggestion: 'Host may not be honoring the guard-mode extraction prompt. Verified hosts: Claude Code (Sonnet/Opus). See README for host requirements.',
  542. };
  543. }
  544. // Per-run telemetry supplies richer detail when available (counts don't
  545. // persist across restart but are informative when they exist).
  546. const stats = telemetry.snapshot();
  547. const extra = stats.claims_received_total > 0
  548. ? ` · this run: ${stats.claims_received_total} claims, ${stats.findings_surfaced_total} findings`
  549. : '';
  550. // Re-injection efficacy: how often a silent-graph nudge was followed by the
  551. // host actually emitting a claim. The signal for whether the in-host fix
  552. // works in long sessions (the doctor's observe-seq counters freeze during a
  553. // lapse, so this is the only cross-session view of recovery).
  554. const ri = getReinjectStats(db, row.id);
  555. const reinjectExtra = ri.reinjections_total > 0
  556. ? ` · re-injects: ${ri.recoveries_total}/${ri.reinjections_total} recovered`
  557. : '';
  558. return {
  559. id: 'reasoning.guard', status: 'ok', label: 'Guard mode',
  560. detail: `on · ${totalObserves} observes, last claims at seq ${lastClaimsSeq}${extra}${reinjectExtra}`,
  561. };
  562. } catch {
  563. return { id: 'reasoning.guard', status: 'fail', label: 'Guard mode', detail: 'DB query failed' };
  564. }
  565. }
  566. function checkReasoningStorage(): DiagnosticCheck {
  567. try {
  568. const c = (db.prepare('SELECT count(*) as n FROM reasoning_claims').get() as any)?.n ?? 0;
  569. const s = (db.prepare('SELECT count(DISTINCT session_id) as n FROM reasoning_claims').get() as any)?.n ?? 0;
  570. if (c === 0) {
  571. return { id: 'reasoning.storage', status: 'ok', label: 'Stored claims', detail: '0 claims · 0 sessions' };
  572. }
  573. const oldest = (db.prepare('SELECT min(created_at) as t FROM reasoning_claims').get() as any)?.t;
  574. const oldestDays = oldest ? Math.floor((Date.now() - oldest) / (24 * 60 * 60 * 1000)) : 0;
  575. return {
  576. id: 'reasoning.storage', status: 'ok', label: 'Stored claims',
  577. detail: `${c} claims across ${s} session(s); oldest ${oldestDays}d ago. Purge via buddy_forget.`,
  578. };
  579. } catch {
  580. return { id: 'reasoning.storage', status: 'fail', label: 'Stored claims', detail: 'DB query failed' };
  581. }
  582. }
  583. function checkReasoningRootResolution(): DiagnosticCheck {
  584. try {
  585. const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
  586. if (!row || (row.guard_mode ?? 0) === 0) {
  587. return { id: 'reasoning.root', status: 'skip', label: 'Workspace root', detail: 'Guard mode off' };
  588. }
  589. const s = telemetry.snapshot().root_source_counts;
  590. const total = s.hint + s.env + s.marker + s.cwd + s.homedir;
  591. if (total === 0) {
  592. return { id: 'reasoning.root', status: 'ok', label: 'Workspace root', detail: 'on · no observes yet this run' };
  593. }
  594. // If MOST observes this run resolved to the homedir, workspace isolation
  595. // is almost certainly broken — every project collapses into one graph.
  596. if (s.homedir > 0 && s.homedir / total > 0.5) {
  597. return {
  598. id: 'reasoning.root', status: 'warn', label: 'Workspace root',
  599. detail: `${s.homedir}/${total} observes resolved to $HOME — projects are mixing`,
  600. 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.',
  601. };
  602. }
  603. const parts: string[] = [];
  604. if (s.hint) parts.push(`hint=${s.hint}`);
  605. if (s.env) parts.push(`env=${s.env}`);
  606. if (s.marker) parts.push(`marker=${s.marker}`);
  607. if (s.cwd) parts.push(`cwd=${s.cwd}`);
  608. if (s.homedir) parts.push(`homedir=${s.homedir}`);
  609. return { id: 'reasoning.root', status: 'ok', label: 'Workspace root', detail: `sources: ${parts.join(', ')}` };
  610. } catch {
  611. return { id: 'reasoning.root', status: 'fail', label: 'Workspace root', detail: 'DB query failed' };
  612. }
  613. }
  614. function checkReasoningBasisQuality(): DiagnosticCheck {
  615. try {
  616. const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
  617. if (!row || (row.guard_mode ?? 0) === 0) {
  618. return { id: 'reasoning.quality', status: 'skip', label: 'Extraction quality', detail: 'Guard mode off' };
  619. }
  620. const h = basisDistributionHealth();
  621. if (h.sample < 20) {
  622. return { id: 'reasoning.quality', status: 'ok', label: 'Extraction quality', detail: `sample too small (${h.sample} claims this run)` };
  623. }
  624. if (h.degenerate) {
  625. const pct = Math.round((h.pct ?? 0) * 100);
  626. return {
  627. id: 'reasoning.quality', status: 'warn', label: 'Extraction quality',
  628. detail: `${pct}% of recent claims classified as "${h.dominantBasis}" — host may be misclassifying`,
  629. 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).`,
  630. };
  631. }
  632. 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)}%` };
  633. } catch {
  634. return { id: 'reasoning.quality', status: 'fail', label: 'Extraction quality', detail: 'DB query failed' };
  635. }
  636. }
  637. function checkReasoningEdgeQuality(): DiagnosticCheck {
  638. try {
  639. const row = db.prepare('SELECT guard_mode FROM companions LIMIT 1').get() as any;
  640. if (!row || (row.guard_mode ?? 0) === 0) {
  641. return { id: 'reasoning.edges', status: 'skip', label: 'Edge diversity', detail: 'Guard mode off' };
  642. }
  643. const h = edgeDistributionHealth();
  644. if (h.sample < 12) {
  645. return { id: 'reasoning.edges', status: 'ok', label: 'Edge diversity', detail: 'sample too small (' + h.sample + ' edges this run)' };
  646. }
  647. const supports = h.counts.supports ?? 0;
  648. const contradicts = h.counts.contradicts ?? 0;
  649. const questions = h.counts.questions ?? 0;
  650. if (h.supportDominant || h.noContradicts) {
  651. const parts = [supports + ' supports', questions + ' questions', contradicts + ' contradicts'];
  652. return {
  653. id: 'reasoning.edges', status: 'warn', label: 'Edge diversity',
  654. detail: parts.join(', ') + ' in recent extraction window',
  655. 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.',
  656. };
  657. }
  658. return { id: 'reasoning.edges', status: 'ok', label: 'Edge diversity', detail: supports + ' supports, ' + questions + ' questions, ' + contradicts + ' contradicts in recent extraction window' };
  659. } catch {
  660. return { id: 'reasoning.edges', status: 'fail', label: 'Edge diversity', detail: 'DB query failed' };
  661. }
  662. }
  663. // ── Runner ──
  664. export function runDiagnostics(): DiagnosticCheck[] {
  665. return [
  666. checkNodeVersion(),
  667. checkPlatform(),
  668. checkEnvVars(),
  669. checkPackageVersion(),
  670. checkInstallLayout(),
  671. checkCompanionActive(),
  672. checkCompanionCount(),
  673. checkCompanionDetails(),
  674. checkDbExists(),
  675. checkDbTables(),
  676. checkStatusFile(),
  677. checkMcpRegistered(),
  678. checkMcpEntryPaths(),
  679. checkStatusline(),
  680. checkStatuslineRefresh(),
  681. checkHooks(),
  682. checkStopHook(),
  683. checkPromptHook(),
  684. checkPromptInjection(),
  685. checkReasoningGuardMode(),
  686. checkReasoningStorage(),
  687. checkReasoningRootResolution(),
  688. checkReasoningBasisQuality(),
  689. checkReasoningEdgeQuality(),
  690. ];
  691. }
  692. // ── Report formatter ──
  693. export function formatReport(checks: DiagnosticCheck[]): string {
  694. const version = getVersion();
  695. const now = new Date().toISOString();
  696. const counts = { ok: 0, warn: 0, fail: 0, skip: 0 };
  697. for (const c of checks) counts[c.status]++;
  698. const summaryParts = [];
  699. if (counts.ok > 0) summaryParts.push(`${counts.ok} ok`);
  700. if (counts.warn > 0) summaryParts.push(`${counts.warn} warn`);
  701. if (counts.fail > 0) summaryParts.push(`${counts.fail} fail`);
  702. if (counts.skip > 0) summaryParts.push(`${counts.skip} skip`);
  703. const lines: string[] = [];
  704. lines.push(`\uD83E\uDE7A Buddy Doctor v${version} \u2014 ${now}`);
  705. lines.push(`${checks.length} checks: ${summaryParts.join(', ')}`);
  706. lines.push('\u2550'.repeat(48));
  707. lines.push('');
  708. // Group checks by section
  709. const sections: Record<string, DiagnosticCheck[]> = {
  710. 'ENVIRONMENT': checks.filter(c => c.id.startsWith('env.') || c.id.startsWith('pkg.') || c.id.startsWith('install.')),
  711. 'COMPANION': checks.filter(c => c.id.startsWith('companion.')),
  712. 'DATABASE': checks.filter(c => c.id.startsWith('db.')),
  713. 'STATUS FILE': checks.filter(c => c.id.startsWith('status.')),
  714. 'HOST INTEGRATION': checks.filter(c => c.id.startsWith('mcp.') || c.id.startsWith('config.') || c.id.startsWith('prompt.')),
  715. 'REASONING LAYER': checks.filter(c => c.id.startsWith('reasoning.')),
  716. };
  717. for (const [section, sectionChecks] of Object.entries(sections)) {
  718. lines.push(section);
  719. for (const c of sectionChecks) {
  720. const pad = 15 - c.label.length;
  721. lines.push(` ${c.label}:${' '.repeat(Math.max(1, pad))}${c.detail}`);
  722. }
  723. lines.push('');
  724. }
  725. // Summary
  726. const issues = checks.filter(c => c.status === 'fail' || c.status === 'warn');
  727. lines.push('SUMMARY');
  728. if (issues.length === 0) {
  729. lines.push(` \u2713 All ${checks.length} checks passed \u2014 Buddy is healthy!`);
  730. } else {
  731. const fails = checks.filter(c => c.status === 'fail');
  732. const warns = checks.filter(c => c.status === 'warn');
  733. const parts = [];
  734. if (fails.length > 0) parts.push(`${fails.length} fail`);
  735. if (warns.length > 0) parts.push(`${warns.length} warn`);
  736. lines.push(` \u2717 ${parts.join(', ')}:`);
  737. let idx = 1;
  738. for (const c of issues) {
  739. lines.push(` ${idx}. [${c.id}] ${c.label}: ${c.detail}`);
  740. if (c.suggestion) lines.push(` \u2192 ${c.suggestion}`);
  741. idx++;
  742. }
  743. }
  744. return lines.join('\n');
  745. }
src/lib/reasoning/config.ts · Bundled script · 71 lines · 1 finding marked
  1. // src/lib/reasoning/config.ts
  2. //
  3. // All tunable numbers live here. Pulled out of detector code so buddy's
  4. // maintainer can adjust thresholds without touching algorithm code.
  5. // Starting values chosen conservatively — fewer findings is better than noise.
  6. export const REASONING_CONFIG = {
  7. // Cold-start gate: no detectors fire until the session has at least this
  8. // many claims. Kills first-three-turn false positives when the graph is
  9. // barely populated.
  10. COLD_START_MIN_CLAIMS: 6,
  11. // Cap per-session claim count. When exceeded, oldest claims prune.
  12. MAX_CLAIMS_PER_SESSION: 200,
  13. // Retention: sessions older than this are pruned on startup.
  14. SESSION_RETENTION_DAYS: 30,
  15. // Cooldowns (measured in observe calls, not wall-clock time).
  16. CAUTION_COOLDOWN_OBSERVES: 10,
  17. KUDOS_COOLDOWN_OBSERVES: 5,
  18. // Kudos bias: if the last N observes had K caution findings and zero kudos,
  19. // next eligible finding must be kudos (if one is available).
  20. KUDOS_BIAS_WINDOW: 10,
  21. KUDOS_BIAS_CAUTION_THRESHOLD: 3,
  22. // When both kudos and caution fire and neither is cooldown-blocked, weight
  23. // toward caution (higher information density) but leave room for kudos.
  24. KUDOS_TIE_BREAK_WEIGHT: 0.4,
  25. // Detector-specific thresholds.
  26. LOAD_BEARING_MIN_DOWNSTREAM: 2,
  27. UNCHALLENGED_CHAIN_MIN_LENGTH: 3,
  28. ECHO_CHAMBER_MIN_SUPPORTS: 2,
  29. WELL_SOURCED_MIN_DOWNSTREAM: 2,
  30. PRODUCTIVE_STRESS_MIN_CHAIN: 2,
  31. GROUNDED_PREMISE_MIN_SUPPORTS: 1,
  32. // Claim text cap — matches sanitizeClaim's truncation.
  33. MAX_CLAIM_TEXT_LENGTH: 240,
  34. // Recent-claims context injected into the observer prompt so the host can
  35. // edge into prior-turn claims. Bounded for prompt size.
  36. RECENT_CLAIMS_CONTEXT: 10,
  37. // Doctor check: guard mode on but zero claims received in the last N observes
  38. // triggers a "host may not be honoring extraction" warning.
  39. INERT_GUARD_WARN_OBSERVES: 10,
  40. // Re-injection: the extraction instruction normally rides home in the
  41. // buddy_observe response. But if the host stops calling buddy_observe (the
  42. // graph goes silent past ~100k tokens of context), it also stops receiving
  43. // that reminder — a self-reinforcing lapse with no recovery path. The
  44. // UserPromptSubmit hook fires every turn regardless, so after this many
  45. // consecutive turns with no new claims it re-injects the instruction into
  46. // fresh context to pull the host back. Lower = faster recovery, more prompt
  47. // budget; the counter resets the moment a claim lands.
  48. REINJECT_AFTER_SILENT_TURNS: 3,
  49. // Detector latency budget. If detectors exceed this, skip finding injection
  50. // for this observe (budget measured per-observe, reset each call).
  51. DETECTOR_BUDGET_MS: 30,
  52. // Sanitizer iterative-decode depth cap. Handles multiply-encoded HTML
  53. // entities (`&amp;lt;system&amp;gt;` → `&lt;system&gt;` → `<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
  54. // Bounded so pathological inputs can't loop forever. Adversarial depth
  55. // and base64-wrapped entities remain out of scope per sanitize.ts's
  56. // "structural break prevention" framing.
  57. SANITIZE_DECODE_MAX_PASSES: 4,
  58. } as const;
src/lib/reasoning/sanitize.ts · Bundled script · 133 lines · 1 finding marked
  1. // src/lib/reasoning/sanitize.ts
  2. //
  3. // Claim text comes from the host (which got it from the user or LLM output).
  4. // We neutralize structural prompt-injection attempts before storing or
  5. // re-injecting into a prompt.
  6. //
  7. // Scope: "structural break prevention," not adversarial robustness. We aim
  8. // to prevent a claim from accidentally or lazily restructuring a downstream
  9. // prompt (code fences closing early, role markers appearing to start a new
  10. // turn, header-style separators dividing sections, free-standing quotes
  11. // unbalancing the snippet delimiter we use in prompts). We do NOT defend
  12. // against a motivated attacker who controls the host — that's the host's
  13. // job. If guard mode is off, sanitize is never invoked.
  14. import { REASONING_CONFIG } from './config.js';
  15. // Minimal HTML-entity decode table — covers the cases that would re-form
  16. // a structural separator after our strip passes (e.g. `&lt;system&gt;`
  17. // surviving the XML-tag strip). Not a full HTML parser.
  18. const HTML_ENTITIES: Record<string, string> = {
  19. '&lt;': '<',
  20. '&gt;': '>',
  21. '&amp;': '&',
  22. '&quot;': '"',
  23. '&apos;': "'",
  24. '&#39;': "'",
  25. '&#x27;': "'",
  26. '&#60;': '<',
  27. '&#62;': '>',
  28. '&#x3c;': '<',
  29. '&#x3e;': '>',
  30. '&#x3C;': '<',
  31. '&#x3E;': '>',
  32. };
  33. function decodeHtmlEntities(s: string): string {
  34. // Iterate until the string stops changing. Handles double-encoded inputs
  35. // like `&amp;lt;` → `&lt;` → `<`. Bounded by SANITIZE_DECODE_MAX_PASSES
  36. // (in config.ts) so a pathological input can't loop forever. Adversarial
  37. // depth and base64-wrapped entities remain out of scope per the header.
  38. let prev = s;
  39. for (let i = 0; i < REASONING_CONFIG.SANITIZE_DECODE_MAX_PASSES; i++) {
  40. const next = prev.replace(/&(?:lt|gt|amp|quot|apos|#x?[0-9a-fA-F]+);/g, (m) => {
  41. return HTML_ENTITIES[m] ?? HTML_ENTITIES[m.toLowerCase()] ?? m;
  42. });
  43. if (next === prev) return next;
  44. prev = next;
  45. }
  46. return prev;
  47. }
  48. // Role markers, including unicode-lookalike variants for the common
  49. // "lazy copy-paste" cases. The char class on each variant covers ASCII
  50. // + the full-width form + the most common cross-script lookalike (Greek,
  51. // Cyrillic). Not exhaustive by design — see sanitize.ts header for scope.
  52. const ROLE_MARKERS = [
  53. /\b[HHΗН]uman:/gi, // H (ASCII), H (full-width), Η (Greek eta), Н (Cyrillic En)
  54. /\b[AAΑА]ssistant:/gi, // A (ASCII), A (full-width), Α (Greek alpha), А (Cyrillic A)
  55. /\b[SSЅ]ystem:/gi, // S (ASCII), S (full-width), Ѕ (Cyrillic Dze)
  56. /\b[UUՍ]ser:/gi, // U (ASCII), U (full-width), Ս (Armenian Seh — rough, catches lazy)
  57. // Chat-template markers (OpenAI / Llama / generic `<|...|>` family).
  58. /<\|im_start\|>/gi,
  59. /<\|im_end\|>/gi,
  60. /<\|start_header_id\|>/gi,
  61. /<\|end_header_id\|>/gi,
  62. /<\|eot_id\|>/gi,
  63. /<\|begin_of_text\|>/gi,
  64. /<\|end_of_text\|>/gi,
  65. /<\|[a-z_]+\|>/gi, // generic chat-template marker fallback
  66. ];
  67. // Structural separators that could end a prompt section or open a new one.
  68. const STRUCTURAL_BREAKS = [
  69. /```+/g, // fenced code (backticks)
  70. /~~~+/g, // fenced code (tildes)
  71. /"""/g, // python-style triple quote
  72. /'''/g, // python-style single triple quote
  73. /^\s*#{1,6}\s+/gm, // markdown headers at line start
  74. /^\s*-{3,}\s*$/gm, // horizontal-rule divider
  75. /^\s*={3,}\s*$/gm, // setext-style divider
  76. // XMLish role / instruction tags. Covers system/user/assistant plus
  77. // common prompt-engineering wrappers (instructions, context, role, task,
  78. // example, document, tool_call, thinking).
  79. /<\/?(system|user|assistant|instructions?|context|role|task|example|document|tool_call|thinking)\b[^>]*>/gi,
  80. ];
  81. export function sanitizeClaim(text: string | undefined): string {
  82. if (!text) return '';
  83. let s = text;
  84. // Decode HTML entities BEFORE the structural-break strips, so
  85. // `&lt;system&gt;` 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
  86. // a lazy host could bypass the XML-tag strip by HTML-escaping.
  87. s = decodeHtmlEntities(s);
  88. // Structural separators are matched first — some are anchored to line
  89. // starts (markdown headers, HR dividers), which require newlines still
  90. // to be present. We replace them with a space so surrounding words
  91. // don't fuse after the subsequent whitespace collapse.
  92. for (const re of STRUCTURAL_BREAKS) s = s.replace(re, ' ');
  93. // Now collapse newlines/tabs to spaces — claims are single-line
  94. // assertions. (Done before control-char strip because \n/\r/\t are
  95. // themselves control chars and would otherwise be deleted outright,
  96. // fusing adjacent words.)
  97. s = s.replace(/[\n\r\t]+/g, ' ');
  98. // Strip unicode control / format / private-use chars (what's left is
  99. // non-whitespace).
  100. s = s.replace(/[\p{Cf}\p{Cc}\p{Co}]/gu, '');
  101. // Strip role markers.
  102. for (const re of ROLE_MARKERS) s = s.replace(re, '');
  103. // Replace ASCII double quotes with single quotes so the surrounding
  104. // `"{claim}"` delimiter in phrasings and the observer prompt stays
  105. // balanced, and so the output reads naturally (rather than using
  106. // typographic quotes that render as two LEFT marks regardless of
  107. // position). Single quotes are safe — nothing in our prompts uses
  108. // single-quote delimiters.
  109. s = s.replace(/"/g, "'");
  110. // Collapse runs of whitespace.
  111. s = s.replace(/\s{2,}/g, ' ');
  112. s = s.trim();
  113. if (s.length > REASONING_CONFIG.MAX_CLAIM_TEXT_LENGTH) {
  114. s = s.slice(0, REASONING_CONFIG.MAX_CLAIM_TEXT_LENGTH - 1) + '…';
  115. }
  116. return s;
  117. }
uninstall.ps1 · Bundled script · 161 lines · 1 finding marked
  1. # Buddy MCP Server — Windows PowerShell Uninstaller
  2. #
  3. # Usage:
  4. # irm https://raw.githubusercontent.com/fiorastudio/buddy/master/uninstall.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 4 on GitHub
  5. param(
  6. [switch]$Force,
  7. [switch]$KeepData
  8. )
  9. $ErrorActionPreference = "Stop"
  10. $InstallDir = "$env:USERPROFILE\.buddy\server"
  11. $DataDir = "$env:USERPROFILE\.buddy"
  12. $StatusFile = "$env:USERPROFILE\.claude\buddy-status.json"
  13. Write-Host ""
  14. Write-Host " Buddy MCP Server Uninstaller" -ForegroundColor Cyan
  15. Write-Host " ────────────────────────────" -ForegroundColor Cyan
  16. Write-Host ""
  17. function Remove-BuddyFromJsonConfig($configPath, $cliName) {
  18. if (!(Test-Path $configPath)) { return }
  19. try {
  20. $content = Get-Content $configPath -Raw | ConvertFrom-Json
  21. if (!$content.mcpServers -or !$content.mcpServers.buddy) { return }
  22. $content.mcpServers.PSObject.Properties.Remove('buddy')
  23. if ($content.mcpServers.PSObject.Properties.Count -eq 0) {
  24. $content.PSObject.Properties.Remove('mcpServers')
  25. }
  26. $content | ConvertTo-Json -Depth 8 | Set-Content $configPath -Encoding UTF8
  27. Write-Host " ✓ Removed Buddy MCP entry from $cliName ($configPath)" -ForegroundColor Green
  28. } catch {
  29. Write-Host " ! Could not update $cliName config ($configPath)" -ForegroundColor Yellow
  30. }
  31. }
  32. function Remove-BuddyPromptBlock($filePath, $cliName) {
  33. if (!(Test-Path $filePath)) { return }
  34. $content = Get-Content $filePath -Raw
  35. $pattern = '(?s)\s*<!-- buddy-companion -->.*?<!-- /buddy-companion -->\s*'
  36. if ($content -notmatch 'buddy-companion') { return }
  37. try {
  38. $updated = ([regex]::Replace($content, $pattern, '')).Trim()
  39. if ($updated.Length -gt 0) {
  40. Set-Content -Path $filePath -Value ($updated + "`n") -Encoding UTF8
  41. } else {
  42. Set-Content -Path $filePath -Value '' -Encoding UTF8
  43. }
  44. Write-Host " ✓ Removed Buddy instructions from $cliName ($filePath)" -ForegroundColor Green
  45. } catch {
  46. Write-Host " ! Could not update $cliName prompt file ($filePath)" -ForegroundColor Yellow
  47. }
  48. }
  49. Write-Host " This will remove Buddy MCP config and prompt instructions."
  50. if ($KeepData) {
  51. Write-Host " Local Buddy data will be preserved."
  52. } else {
  53. Write-Host " Local Buddy data in $DataDir will also be removed."
  54. }
  55. if (-not $Force) {
  56. $reply = Read-Host "Proceed with uninstall? [y/N]"
  57. if ($reply -notin @('y', 'Y', 'yes', 'YES')) {
  58. Write-Host " Aborted."
  59. exit 0
  60. }
  61. }
  62. function Remove-BuddyHooks($configPath, $cliName) {
  63. if (!(Test-Path $configPath)) { return }
  64. try {
  65. $content = Get-Content $configPath -Raw | ConvertFrom-Json
  66. if (!$content.hooks -or !$content.hooks.PostToolUse) { return }
  67. $before = $content.hooks.PostToolUse.Count
  68. $filtered = @($content.hooks.PostToolUse | Where-Object {
  69. $dominated = $false
  70. if ($_.hooks) {
  71. foreach ($hk in $_.hooks) {
  72. if ($hk.command -and $hk.command -like '*post-tool-handler*') {
  73. $dominated = $true
  74. }
  75. }
  76. }
  77. -not $dominated
  78. })
  79. if ($filtered.Count -eq $before) { return }
  80. if ($filtered.Count -eq 0) {
  81. $content.hooks.PSObject.Properties.Remove('PostToolUse')
  82. } else {
  83. $content.hooks.PostToolUse = $filtered
  84. }
  85. if ($content.hooks.PSObject.Properties.Count -eq 0) {
  86. $content.PSObject.Properties.Remove('hooks')
  87. }
  88. $content | ConvertTo-Json -Depth 8 | Set-Content $configPath -Encoding UTF8
  89. Write-Host " ✓ Removed Buddy hooks from $cliName ($configPath)" -ForegroundColor Green
  90. } catch {
  91. Write-Host " ! Could not update $cliName hooks ($configPath)" -ForegroundColor Yellow
  92. }
  93. }
  94. Write-Host ""
  95. Write-Host " Removing MCP client configuration..."
  96. Remove-BuddyFromJsonConfig "$env:USERPROFILE\.claude\settings.json" "Claude Code"
  97. Remove-BuddyHooks "$env:USERPROFILE\.claude\settings.json" "Claude Code"
  98. Remove-BuddyFromJsonConfig "$env:USERPROFILE\.cursor\mcp.json" "Cursor"
  99. Remove-BuddyFromJsonConfig "$env:USERPROFILE\.copilot\mcp-config.json" "GitHub Copilot CLI"
  100. try {
  101. $null = Get-Command codex -ErrorAction Stop
  102. codex mcp get buddy *> $null
  103. if ($LASTEXITCODE -eq 0) {
  104. codex mcp remove buddy *> $null
  105. if ($LASTEXITCODE -eq 0) {
  106. Write-Host " ✓ Removed Buddy MCP entry from Codex CLI" -ForegroundColor Green
  107. } else {
  108. Write-Host " ! Could not remove Buddy MCP entry from Codex CLI" -ForegroundColor Yellow
  109. }
  110. }
  111. } catch {
  112. # Codex not installed; nothing to remove
  113. }
  114. Write-Host ""
  115. Write-Host " Removing injected prompt instructions..."
  116. Remove-BuddyPromptBlock "$env:USERPROFILE\.claude\CLAUDE.md" "Claude Code"
  117. Remove-BuddyPromptBlock "$env:USERPROFILE\.cursor\rules\buddy.md" "Cursor"
  118. Remove-BuddyPromptBlock "$env:USERPROFILE\.codex\instructions.md" "Codex CLI"
  119. Remove-BuddyPromptBlock "$env:USERPROFILE\.codex\AGENTS.md" "Codex CLI"
  120. Remove-BuddyPromptBlock "$env:USERPROFILE\.gemini\GEMINI.md" "Gemini CLI"
  121. Remove-BuddyPromptBlock "$env:USERPROFILE\.gemini\AGENTS.md" "Gemini CLI"
  122. Remove-BuddyPromptBlock "$env:USERPROFILE\.copilot\copilot-instructions.md" "GitHub Copilot CLI"
  123. Remove-BuddyPromptBlock "$env:USERPROFILE\.copilot\AGENTS.md" "GitHub Copilot CLI"
  124. if (Test-Path $StatusFile) {
  125. Remove-Item $StatusFile -Force
  126. Write-Host " ✓ Removed Buddy status file ($StatusFile)" -ForegroundColor Green
  127. }
  128. Write-Host ""
  129. Write-Host " Removing local files..."
  130. if (Test-Path $InstallDir) {
  131. Remove-Item $InstallDir -Recurse -Force
  132. Write-Host " ✓ Removed install directory ($InstallDir)" -ForegroundColor Green
  133. }
  134. if (-not $KeepData -and (Test-Path $DataDir)) {
  135. Remove-Item $DataDir -Recurse -Force
  136. Write-Host " ✓ Removed data directory ($DataDir)" -ForegroundColor Green
  137. } elseif ($KeepData) {
  138. Write-Host " Preserved data directory ($DataDir)" -ForegroundColor DarkGray
  139. }
  140. Write-Host ""
  141. Write-Host " ✅ Buddy uninstalled." -ForegroundColor Green
  142. Write-Host ""

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.