Skip to content
Back to search

thedotmack

SkillWorks with CodexGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked yesterday

Check it deeper on your machine

Its scripts were only partly scanned.

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/thedotmack/claude-mem 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/thedotmack/claude-mem'

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/thedotmack-claude-mem/badge.svg)](/listings/thedotmack-claude-mem)

HTML

<a href="/listings/thedotmack-claude-mem"><img src="/api/listings/thedotmack-claude-mem/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.

**Installing for someone as an AI agent?** If the user is available, run `npx claude-mem install --setup browser` on their computer and keep it running. In an interactive terminal, they can enter a work email and an optional message, or press Enter to skip. An unattended terminal skips both prompts. The installer prepares the local runtime, then opens the browser for the user to choose agents, integrations, skills, model, and usage analytics. If the page doesn't open, give them the printed URL. If the user is away, run `npx claude-mem install --setup defer` to prepare the runtime and leave setup waiting for their first visit. Their next session shows them the link. Don't make their choices for them.

npx claude-mem install

The installer finds the agents on your machine and asks which ones to set up. Then just start working: observations stream in from your first prompt, and your second session in a project opens with memory from the first. (Copilot CLI, Goose, Roo Code, Warp and Zed get memory search only, so their sessions don't add to it.)

The installer sets everything up first, then asks you to sign in to claude-mem in your browser (email magic link, no card required to sign in). Choosing the **claude-mem observer** then starts its **30 Day Free Trial** on a checkout page that asks for a payment method; once it completes, the installer saves your memory key. With the observer, memory runs off-plan, so you get up to 100% more usage from your plan. When the free trial ends, memory automatically falls back to your Anthropic plan unless you subscribe. After sign-in you pick your memory provider: the claude-mem observer, your own OpenRouter or Gemini key, or your Anthropic plan.

Prefer to skip the sign-in? Pass an explicit `--provider` flag, set `CLAUDE_MEM_ONLINE_OPTIN=false`, or run in CI/non-interactive shells — the installer completes without any account interaction.

Your memory lives in `~/.claude-mem` on your machine. Cloud sync is opt-in. Anonymous usage analytics are on by default; `npx claude-mem telemetry disable` turns them off ([what's collected](https://docs.claude-mem.ai/telemetry)).

Or install from the plugin marketplace inside Claude Code:

/plugin marketplace add thedotmack/claude-mem

/plugin install claude-mem

Restart Claude Code. Context from previous sessions will automatically appear in new sessions.

> **Note:** Claude-Mem is also published on npm, but `npm install -g claude-mem` installs the **SDK/library only** — it does not register the plugin hooks or set up the worker service. Always install via `npx claude-mem install` or the `/plugin` commands above.

Other agents

`npx claude-mem install` covers every supported agent. To set up one agent directly, pass `--ide`.

**OpenCode** (1.3.4 or later, including OpenCode 2). Restart OpenCode after installing.

npx claude-mem install --ide opencode

**T3 Code** (Codex and Claude Code providers). The installer discovers T3 Code's enabled providers, registers native Claude-Mem plugins in their configured homes, and supports T3-managed Codex. Restart T3 Code, trust the provider's hooks when prompted, and start a new thread. See the [T3 Code integration guide](https://docs.claude-mem.ai/t3code-integration) for custom server settings, status, and removal.

npx claude-mem install --ide t3code

**Antigravity CLI** ([setup guide](https://docs.claude-mem.ai/antigravity-cli/setup)):

npx claude-mem install --ide antigravity

**OMP (Oh My Pi):**

npx claude-mem install --ide omp

**Pi and DeepSeek Harness** use the worker runtime. See [native harness setup](docs/native-harness-integrations.md) for capture, recall, and troubleshooting.

npx claude-mem install --ide pi
npx claude-mem install --ide dsh --dsh-profile tui

**Grok Bot:** see [Grok Bot](#grok-bot) below.

npx claude-mem install --ide grok-bot

The full list of `--ide` values is in `npx claude-mem --help`.

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/marketplace.json · Manifest · 27 lines
  1. {
  2. "name": "thedotmack",
  3. "owner": {
  4. "name": "Alex Newman"
  5. },
  6. "metadata": {
  7. "description": "Plugins by Alex Newman (thedotmack)"
  8. },
  9. "plugins": [
  10. {
  11. "name": "claude-mem",
  12. "version": "16.0.1",
  13. "source": "./plugin",
  14. "description": "Persistent memory for Claude Code: the next session starts where the last one left off."
  15. },
  16. {
  17. "name": "cmem-pro",
  18. "displayName": "CMEM Pro",
  19. "version": "0.2.1",
  20. "source": "./cowork",
  21. "description": "CMEM Pro for the Claude app - hooks stream tool use to cmem.ai and inject observations into new sessions and agents"
  22. }
  23. ],
  24. "renames": {
  25. "claude-mem-cowork": "cmem-pro"
  26. }
  27. }
README.md · README · 486 lines · 1 finding marked
  1. <h1 align="center">
  2. <br>
  3. <a href="https://github.com/thedotmack/claude-mem">
  4. <picture>
  5. <source media="(prefers-color-scheme: dark)" srcset="docs/public/claude-mem-logo-for-dark-mode.webp">
  6. <source media="(prefers-color-scheme: light)" srcset="docs/public/claude-mem-logo-for-light-mode.webp">
  7. <img src="docs/public/claude-mem-logo-for-light-mode.webp" alt="Claude-Mem" width="400">
  8. </picture>
  9. </a>
  10. </h1>
  11. <p align="center">
  12. <img alt="Vercel OSS Program" src="https://vercel.com/oss/program-badge-2026.svg" height="24" />
  13. &nbsp;&nbsp;&nbsp;
  14. <img alt="Greptile" src="docs/public/greptile-wordmark-green.svg" height="24" />
  15. &nbsp;&nbsp;&nbsp;
  16. <img alt="SerpApi" src="docs/public/serpapi-logo-with-wordmark-gradient.svg" height="24" />
  17. </p>
  18. <p align="center">
  19. <a href="docs/i18n/README.zh.md">🇨🇳 中文</a> •
  20. <a href="docs/i18n/README.zh-tw.md">🇹🇼 繁體中文</a> •
  21. <a href="docs/i18n/README.ja.md">🇯🇵 日本語</a> •
  22. <a href="docs/i18n/README.pt.md">🇵🇹 Português</a> •
  23. <a href="docs/i18n/README.pt-br.md">🇧🇷 Português</a> •
  24. <a href="docs/i18n/README.ko.md">🇰🇷 한국어</a> •
  25. <a href="docs/i18n/README.es.md">🇪🇸 Español</a> •
  26. <a href="docs/i18n/README.de.md">🇩🇪 Deutsch</a> •
  27. <a href="docs/i18n/README.fr.md">🇫🇷 Français</a> •
  28. <a href="docs/i18n/README.he.md">🇮🇱 עברית</a> •
  29. <a href="docs/i18n/README.ar.md">🇸🇦 العربية</a> •
  30. <a href="docs/i18n/README.ru.md">🇷🇺 Русский</a> •
  31. <a href="docs/i18n/README.pl.md">🇵🇱 Polski</a> •
  32. <a href="docs/i18n/README.cs.md">🇨🇿 Čeština</a> •
  33. <a href="docs/i18n/README.nl.md">🇳🇱 Nederlands</a> •
  34. <a href="docs/i18n/README.tr.md">🇹🇷 Türkçe</a> •
  35. <a href="docs/i18n/README.uk.md">🇺🇦 Українська</a> •
  36. <a href="docs/i18n/README.vi.md">🇻🇳 Tiếng Việt</a> •
  37. <a href="docs/i18n/README.tl.md">🇵🇭 Tagalog</a> •
  38. <a href="docs/i18n/README.id.md">🇮🇩 Indonesia</a> •
  39. <a href="docs/i18n/README.th.md">🇹🇭 ไทย</a> •
  40. <a href="docs/i18n/README.hi.md">🇮🇳 हिन्दी</a> •
  41. <a href="docs/i18n/README.bn.md">🇧🇩 বাংলা</a> •
  42. <a href="docs/i18n/README.ur.md">🇵🇰 اردو</a> •
  43. <a href="docs/i18n/README.ro.md">🇷🇴 Română</a> •
  44. <a href="docs/i18n/README.sv.md">🇸🇪 Svenska</a> •
  45. <a href="docs/i18n/README.it.md">🇮🇹 Italiano</a> •
  46. <a href="docs/i18n/README.el.md">🇬🇷 Ελληνικά</a> •
  47. <a href="docs/i18n/README.hu.md">🇭🇺 Magyar</a> •
  48. <a href="docs/i18n/README.fi.md">🇫🇮 Suomi</a> •
  49. <a href="docs/i18n/README.da.md">🇩🇰 Dansk</a> •
  50. <a href="docs/i18n/README.no.md">🇳🇴 Norsk</a>
  51. </p>
  52. <h4 align="center">Your coding agent forgets everything between sessions. Claude-Mem remembers for it.</h4>
  53. <p align="center">
  54. <a href="LICENSE">
  55. <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License">
  56. </a>
  57. <a href="package.json">
  58. <img src="https://img.shields.io/badge/version-16.0.1-green.svg" alt="Version">
  59. </a>
  60. <a href="package.json">
  61. <img src="https://img.shields.io/badge/node-%5E20.19%20%7C%7C%20%3E%3D22.12-brightgreen.svg" alt="Node">
  62. </a>
  63. <a href="https://github.com/thedotmack/awesome-claude-code">
  64. <img src="https://awesome.re/mentioned-badge.svg" alt="Mentioned in Awesome Claude Code">
  65. </a>
  66. </p>
  67. <p align="center">
  68. <a href="https://www.star-history.com/thedotmack/claude-mem">
  69. <picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=rank&theme=dark" /><source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=rank" /><img alt="Star History Rank" src="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=rank" /></picture> <picture><source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=trending&theme=dark" /><source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=trending" /><img alt="GitHub Trending Repository of the Day" src="https://api.star-history.com/badge?repo=thedotmack/claude-mem&type=trending" /></picture>
  70. </a>
  71. </p>
  72. <br>
  73. <table align="center">
  74. <tr>
  75. <td align="center">
  76. <a href="https://github.com/thedotmack/claude-mem">
  77. <picture>
  78. <img
  79. src="https://raw.githubusercontent.com/thedotmack/claude-mem/main/docs/public/cm-preview.gif"
  80. alt="Claude-Mem Preview"
  81. width="500"
  82. >
  83. </picture>
  84. </a>
  85. </td>
  86. <td align="center">
  87. <a href="https://www.star-history.com/#thedotmack/claude-mem&Date">
  88. <picture>
  89. <source
  90. media="(prefers-color-scheme: dark)"
  91. srcset="https://api.star-history.com/image?repos=thedotmack/claude-mem&type=date&theme=dark&legend=top-left"
  92. />
  93. <source
  94. media="(prefers-color-scheme: light)"
  95. srcset="https://api.star-history.com/image?repos=thedotmack/claude-mem&type=date&legend=top-left"
  96. />
  97. <img
  98. alt="Star History Chart"
  99. src="https://api.star-history.com/image?repos=thedotmack/claude-mem&type=date&legend=top-left"
  100. width="500"
  101. />
  102. </picture>
  103. </a>
  104. </td>
  105. </tr>
  106. </table>
  107. <p align="center">
  108. <a href="#quick-start">Quick Start</a> •
  109. <a href="#how-it-works">How It Works</a> •
  110. <a href="#mcp-search-tools">Search Tools</a> •
  111. <a href="#documentation">Documentation</a> •
  112. <a href="#configuration">Configuration</a> •
  113. <a href="#troubleshooting">Troubleshooting</a> •
  114. <a href="#license">License</a>
  115. </p>
  116. <p align="center">
  117. Every new session, your agent starts from zero. It re-reads the same files, re-asks the same questions, and walks back into mistakes you already fixed together.
  118. </p>
  119. <p align="center">
  120. Claude-Mem runs a second agent beside it that takes notes while it works. The next session starts with a short index of what matters, and pulls in the details only when it needs them. Works with Claude Code, Codex, Cursor, OpenCode and 11 more agents. Copilot CLI, Goose, Roo Code, Warp and Zed can search your memory, but their sessions aren't recorded.
  121. </p>
  122. ---
  123. ## Quick Start
  124. **Installing for someone as an AI agent?** If the user is available, run `npx claude-mem install --setup browser` on their computer and keep it running. In an interactive terminal, they can enter a work email and an optional message, or press Enter to skip. An unattended terminal skips both prompts. The installer prepares the local runtime, then opens the browser for the user to choose agents, integrations, skills, model, and usage analytics. If the page doesn't open, give them the printed URL. If the user is away, run `npx claude-mem install --setup defer` to prepare the runtime and leave setup waiting for their first visit. Their next session shows them the link. Don't make their choices for them.
  125. ```bash
  126. npx claude-mem install
  127. ```
  128. The installer finds the agents on your machine and asks which ones to set up. Then just start working: observations stream in from your first prompt, and your second session in a project opens with memory from the first. (Copilot CLI, Goose, Roo Code, Warp and Zed get memory search only, so their sessions don't add to it.)
  129. The installer sets everything up first, then asks you to sign in to claude-mem in your browser (email magic link, no card required to sign in). Choosing the **claude-mem observer** then starts its **30 Day Free Trial** on a checkout page that asks for a payment method; once it completes, the installer saves your memory key. With the observer, memory runs off-plan, so you get up to 100% more usage from your plan. When the free trial ends, memory automatically falls back to your Anthropic plan unless you subscribe. After sign-in you pick your memory provider: the claude-mem observer, your own OpenRouter or Gemini key, or your Anthropic plan.
  130. Prefer to skip the sign-in? Pass an explicit `--provider` flag, set `CLAUDE_MEM_ONLINE_OPTIN=false`, or run in CI/non-interactive shells — the installer completes without any account interaction.
  131. Your memory lives in `~/.claude-mem` on your machine. Cloud sync is opt-in. Anonymous usage analytics are on by default; `npx claude-mem telemetry disable` turns them off ([what's collected](https://docs.claude-mem.ai/telemetry)).
  132. Or install from the plugin marketplace inside Claude Code:
  133. ```bash
  134. /plugin marketplace add thedotmack/claude-mem
  135. /plugin install claude-mem
  136. ```
  137. Restart Claude Code. Context from previous sessions will automatically appear in new sessions.
  138. > **Note:** Claude-Mem is also published on npm, but `npm install -g claude-mem` installs the **SDK/library only** — it does not register the plugin hooks or set up the worker service. Always install via `npx claude-mem install` or the `/plugin` commands above.
  139. ### Other agents
  140. `npx claude-mem install` covers every supported agent. To set up one agent directly, pass `--ide`.
  141. **OpenCode** (1.3.4 or later, including OpenCode 2). Restart OpenCode after installing.
  142. ```bash
  143. npx claude-mem install --ide opencode
  144. ```
  145. **T3 Code** (Codex and Claude Code providers). The installer discovers T3 Code's enabled providers, registers native Claude-Mem plugins in their configured homes, and supports T3-managed Codex. Restart T3 Code, trust the provider's hooks when prompted, and start a new thread. See the [T3 Code integration guide](https://docs.claude-mem.ai/t3code-integration) for custom server settings, status, and removal.
  146. ```bash
  147. npx claude-mem install --ide t3code
  148. ```
  149. **Antigravity CLI** ([setup guide](https://docs.claude-mem.ai/antigravity-cli/setup)):
  150. ```bash
  151. npx claude-mem install --ide antigravity
  152. ```
  153. **OMP (Oh My Pi):**
  154. ```bash
  155. npx claude-mem install --ide omp
  156. ```
  157. **Pi and DeepSeek Harness** use the worker runtime. See [native harness setup](docs/native-harness-integrations.md) for capture, recall, and troubleshooting.
  158. ```bash
  159. npx claude-mem install --ide pi
  160. npx claude-mem install --ide dsh --dsh-profile tui
  161. ```
  162. **Grok Bot:** see [Grok Bot](#grok-bot) below.
  163. ```bash
  164. npx claude-mem install --ide grok-bot
  165. ```
  166. The full list of `--ide` values is in `npx claude-mem --help`.
  167. #### Grok Bot
  168. Grok Bot has no host hooks, so we watch the chat log files. Default is CMEM Pro, the hosted memory. Local observer is opt-in: `--provider host`. Installing this plugin does not install Cursor.
  169. **Opt-in awareness push:** needle observations (`decision`, `bugfix`, `security_alert`, `sensitive`) are appended as dated `- YYYY-MM-DD [awareness] …` lines into that bot's `memory/log/YYYY-MM.md`. Grok Bot already re-reads the log from disk. This does not write `profile.md`, user-memory, or project memory. Enable with `CLAUDE_MEM_GROK_BOT_AWARENESS_ENABLED=true` and set `CLAUDE_MEM_GROK_BOT_AWARENESS_AGENT_IDS` to your agent UUIDs (empty by default).
  170. #### 🦞 OpenClaw Gateway
  171. Install claude-mem as a persistent memory plugin on [OpenClaw](https://openclaw.ai) gateways with a single command:
  172. ```bash
  173. curl -fsSL https://install.cmem.ai/openclaw.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 217 on GitHub
  174. ```
  175. The installer handles dependencies, plugin setup, AI provider configuration, worker startup, and optional real-time observation feeds to Telegram, Discord, Slack, and more. See the [OpenClaw Integration Guide](https://docs.claude-mem.ai/openclaw-integration) for details.
  176. ## What You Get
  177. - 🧠 **The next session starts where the last one left off.** Each session opens with a compact index of past observations, layered so the agent opens full details only when it needs them, and the header can show what each layer costs in tokens.
  178. - 🔍 **Find anything you worked on.** The mem-search skill searches your project history in three steps (index, timeline, details), so the agent spends tokens only on what it opens.
  179. - 🖥️ **Watch it work, and keep track of yours.** My Work shows live requests, progress, human handoffs and a saved review queue at the worker URL printed on startup. [Guide](https://docs.claude-mem.ai/usage/my-work). Memory, sessions and settings remain at `/viewer`.
  180. - 👥 **Share with your team, if you want.** TeamBrain is an optional shared workspace beside My Work, with real team work lists, member attribution and linked findings. Each person chooses what to share; personal requests and review notes stay separate. [Set up a team](https://cmem.ai/teambrain/start).
  181. - 💻 **Search from Claude Desktop.** Search your memory from Claude Desktop conversations.
  182. - 🔒 **Keep secrets out.** Wrap anything in `<private>` tags and it never gets stored.
  183. - 🖼️ **Screenshots, kept by default.** Keep converted copies of tool screenshots under `~/.claude-mem/media-v1/` and show them in My Work, upload them to cmem.ai only when Cloud Sync is on, and send them to the observer model only when image inference is separately enabled. Turn it off with the "Keep images" switch in Settings ([details](https://docs.claude-mem.ai/configuration#screenshots-and-images)).
  184. - ⚙️ **Choose what gets injected.** Fine-grained settings for what context a new session starts with.
  185. - 🤖 **Nothing to remember to do.** It runs on its own once installed.
  186. - 🔗 **Point back to past work.** Every observation has an ID you can cite through the worker API or open in the web viewer.
  187. ---
  188. ## Documentation
  189. 📚 **[View Full Documentation](https://docs.claude-mem.ai/)** - Browse on official website
  190. ### Getting Started
  191. - **[Installation Guide](https://docs.claude-mem.ai/installation)** - Quick start & advanced installation
  192. - **[Usage Guide](https://docs.claude-mem.ai/usage/getting-started)** - How Claude-Mem works automatically
  193. - **[Search Tools](https://docs.claude-mem.ai/usage/search-tools)** - Query your project history with natural language
  194. - **[Cloud Sync](https://docs.claude-mem.ai/cloud-sync)** - Back up your memory to cmem.ai — no daemon, the worker syncs on write
  195. ### Best Practices
  196. - **[Context Engineering](https://docs.claude-mem.ai/context-engineering)** - AI agent context optimization principles
  197. - **[Progressive Disclosure](https://docs.claude-mem.ai/progressive-disclosure)** - Philosophy behind Claude-Mem's context priming strategy
  198. ### Architecture
  199. - **[Overview](https://docs.claude-mem.ai/architecture/overview)** - System components & data flow
  200. - **[Architecture Evolution](https://docs.claude-mem.ai/architecture-evolution)** - The journey from v3 to v5
  201. - **[Hooks Architecture](https://docs.claude-mem.ai/hooks-architecture)** - How Claude-Mem uses lifecycle hooks
  202. - **[Hooks Reference](https://docs.claude-mem.ai/architecture/hooks)** - Every hook entry explained
  203. - **[Worker Service](https://docs.claude-mem.ai/architecture/worker-service)** - HTTP API & Bun management
  204. - **[Database](https://docs.claude-mem.ai/architecture/database)** - SQLite schema & FTS5 search
  205. - **[Search Architecture](https://docs.claude-mem.ai/architecture/search-architecture)** - Hybrid search with Chroma vector database
  206. ### Configuration & Development
  207. - **[Configuration](https://docs.claude-mem.ai/configuration)** - Environment variables & settings
  208. - **[Development](https://docs.claude-mem.ai/development)** - Building, testing, contributing
  209. - **[Troubleshooting](https://docs.claude-mem.ai/troubleshooting)** - Common issues & solutions
  210. ---
  211. ## How It Works
  212. 1. **Your agent works.** Hooks in your agent hand each tool call (what it reads, edits and runs) to a small local worker.
  213. 2. **The observer takes notes.** A second agent turns that activity into short observations, and writes a summary when the session ends.
  214. 3. **The next session starts with them.** When a session starts, your agent gets a compact index of the observations that matter for this project, and fetches full details only when it needs them.
  215. Memory injection starts on your second session in a project. To front-load a whole repo instead, run `/learn-codebase` (~5 minutes on a typical repo, optional).
  216. See [Architecture Overview](https://docs.claude-mem.ai/architecture/overview) for details.
  217. ### How it fits together
  218. For contributors, the main parts and where they live:
  219. - **The `claude-mem` command** (`src/npx-cli/index.ts`): install, repair, doctor, start, search and the rest. The installer puts a small launcher on PATH so hooks can run `claude-mem` directly.
  220. - **Hooks** (`src/cli/hook-command.ts`, one adapter per agent in `src/cli/adapters/`): each agent event runs one shell-free command, such as `claude-mem hook claude-code <event>`. For Claude Code that's Setup (`claude --init` / `--maintenance`), SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PostToolUseFailure, Stop, SubagentStop and SessionEnd.
  221. - **The worker** (`src/services/worker-service.ts`, routes in `src/services/worker/http/routes/`): a local HTTP service managed by Bun. It takes tool activity from the hooks, runs the observer, and serves the viewer and search.
  222. - **The observer** (prompts in `src/sdk/`, one provider per model source in `src/services/worker/`, such as `ClaudeProvider.ts` and `OpenRouterProvider.ts`): turns tool activity into observations and summaries.
  223. - **Storage** (`src/services/sqlite/`): SQLite at `~/.claude-mem/claude-mem.db` holds sessions, observations and summaries. Chroma adds semantic search on top of SQLite's keyword search (`src/services/worker/search/`).
  224. - **Context** (`src/services/context/`): builds the block a new session starts with.
  225. - **Search** (`src/servers/mcp-server.ts`, `plugin/skills/mem-search/`): the MCP tools and the mem-search skill that drives them.
  226. - **The viewer** (`src/ui/viewer/` at `/viewer`, `src/ui/my-work/` at `/`): memory, sessions and settings, plus My Work.
  227. - **The built plugin** (`plugin/`): written by `npm run build`; edit `src/`, not the generated scripts.
  228. The words we use for each of these, and the story they tell, are in [docs/story.md](docs/story.md).
  229. ---
  230. ## MCP Search Tools
  231. Search runs through three MCP tools in a token-efficient three-step workflow. The mem-search skill drives it for you:
  232. **The three steps:**
  233. 1. **`search`** - Get compact index with IDs (~50-100 tokens/result)
  234. 2. **`timeline`** - Get chronological context around interesting results
  235. 3. **`get_observations`** - Fetch full details ONLY for filtered IDs (~500-1,000 tokens/result)
  236. **Step by step:**
  237. - Your agent uses MCP tools to search your memory
  238. - Start with `search` to get an index of results
  239. - Use `timeline` to see what was happening around specific observations
  240. - Use `get_observations` to fetch full details for relevant IDs
  241. - **Index rows are about a tenth the size of a full record**: ~50-100 tokens versus ~500-1,000. Filtering decides how many records you pay to fetch, not how large each one is; the workflow's total cost also includes the timeline and the selected details. The ratio is not a measured recall or end-to-end saving ([#4138](https://github.com/thedotmack/claude-mem/issues/4138)).
  242. **Available MCP Tools:**
  243. 1. **`search`** - Search memory index with full-text queries, filters by type/date/project
  244. 2. **`timeline`** - Get chronological context around a specific observation or query
  245. 3. **`get_observations`** - Fetch full observation details by IDs (always batch multiple IDs)
  246. **Example Usage:**
  247. ```typescript
  248. // Step 1: Search for index
  249. search(query="authentication bug", type="bugfix", limit=10)
  250. // Step 2: Review index, identify relevant IDs (e.g., #123, #456)
  251. // Step 3: Fetch full details
  252. get_observations(ids=[123, 456])
  253. ```
  254. The worker also offers tools for code navigation (`smart_search`, `smart_outline`, `smart_unfold`), saving a note on purpose (`save_memory`) and tracking work in progress. See [Search Tools Guide](https://docs.claude-mem.ai/usage/search-tools) for detailed examples.
  255. ---
  256. ## System Requirements
  257. - **Node.js**: 20.19 or later in the 20.x line, or 22.12 or later
  258. - **A supported agent**: Claude Code (latest, with plugin support) or any agent in [Other agents](#other-agents)
  259. - **Bun**: JavaScript runtime and process manager (auto-installed if missing)
  260. - **uv**: Python package manager for vector search (auto-installed if missing)
  261. - **SQLite 3**: For persistent storage (bundled)
  262. ---
  263. ### Windows Setup Notes
  264. If you see an error like:
  265. ```powershell
  266. npm : The term 'npm' is not recognized as the name of a cmdlet
  267. ```
  268. Make sure Node.js and npm are installed and added to your PATH. Download the latest Node.js installer from https://nodejs.org and restart your terminal after installation.
  269. Claude Code hooks do not need Git Bash. Each hook runs `claude-mem` directly, and `npx claude-mem install` places that launcher at `%LOCALAPPDATA%\claude-mem\bin\claude-mem.exe` and adds the folder to your user Path. Restart your terminal or IDE afterwards so Claude Code picks up the new Path. If hooks report `Executable not found in $PATH: "claude-mem"`, run `npx claude-mem doctor` and see [Troubleshooting](https://docs.claude-mem.ai/troubleshooting#claude-mem-command-not-found-in-hooks).
  270. ---
  271. ## Configuration
  272. Settings are managed in `~/.claude-mem/settings.json` (auto-created with defaults on first run). Configure AI model, worker port, data directory, log level, and context injection settings.
  273. To include observations from every harness in Claude Code and Codex SessionStart context, set `"CLAUDE_MEM_SESSION_START_INCLUDE_ALL_SOURCES": "true"` in that file, or enable **Include all sources at session start** in the viewer settings. The default is `"false"`, which limits startup context to the current harness. The observation count limit still applies across the selected sources.
  274. See the **[Configuration Guide](https://docs.claude-mem.ai/configuration)** for all available settings and examples.
  275. ### Mode & Language Configuration
  276. Claude-Mem supports multiple workflow modes and languages via the `CLAUDE_MEM_MODE` setting.
  277. This option controls both:
  278. - The workflow behavior (e.g. code, chill, investigation)
  279. - The language used in generated observations
  280. #### How to Configure
  281. Edit your settings file at `~/.claude-mem/settings.json`:
  282. ```json
  283. {
  284. "CLAUDE_MEM_MODE": "code--zh"
  285. }
  286. ```
  287. Modes are defined in `plugin/modes/`. To see all available modes locally:
  288. ```bash
  289. ls ~/.claude/plugins/marketplaces/thedotmack/plugin/modes/
  290. ```
  291. #### Available Modes
  292. | Mode | Description |
  293. |------------|-------------------------|
  294. | `code` | Default English mode |
  295. | `code--chill` | Records fewer observations, keeping only what would be painful to rediscover |
  296. | `code--[lang]` | Same as `code`, with observations and summaries written in another language |
  297. Built-in language codes: `ar`, `bn`, `cs`, `da`, `de`, `el`, `es`, `fi`, `fr`, `he`, `hi`, `hu`, `id`, `it`, `ja`, `ko`, `nl`, `no`, `pl`, `pt-br`, `ro`, `ru`, `sv`, `th`, `tr`, `uk`, `ur`, `vi`, `zh`. For example, `code--ko` writes observations and summaries in Korean.
  298. See [Modes](https://docs.claude-mem.ai/modes) for each language's name, the email investigation mode, and custom modes.
  299. > Note: All of these modes are built in. No additional installation or plugin update is required.
  300. #### After Changing Mode
  301. Restart Claude Code to apply the new mode configuration.
  302. ---
  303. ## Development
  304. See the **[Development Guide](https://docs.claude-mem.ai/development)** for build instructions, testing, and contribution workflow.
  305. ---
  306. ## Troubleshooting
  307. Start with `npx claude-mem doctor`. It checks Bun, uv, the hook launcher and the worker, and tells you what to fix.
  308. See the **[Troubleshooting Guide](https://docs.claude-mem.ai/troubleshooting)** for common issues and solutions.
  309. ---
  310. ## Bug Reports
  311. Create comprehensive bug reports with the automated generator:
  312. ```bash
  313. cd ~/.claude/plugins/marketplaces/thedotmack
  314. npm run bug-report
  315. ```
  316. ## Contributing
  317. Contributions are welcome! Please:
  318. 1. Fork the repository
  319. 2. Create a feature branch
  320. 3. Make your changes with tests
  321. 4. Update documentation (user-facing words follow [docs/story.md](docs/story.md))
  322. 5. Submit a Pull Request against `main`
  323. Releases ship from `main` and are published to npm.
  324. See [Development Guide](https://docs.claude-mem.ai/development) for contribution workflow.
  325. ---
  326. ## License
  327. Claude-Mem is licensed under the Apache License 2.0.
  328. We chose Apache-2.0 because durable agentic memory should be easy to embed in
  329. developer tools, local agents, MCP servers, enterprise systems, robotics stacks,
  330. and production agent harnesses.
  331. See the [LICENSE](LICENSE) file for full details. See [docs/license.md](docs/license.md)
  332. and [docs/ip-boundary.md](docs/ip-boundary.md) for licensing scope and the
  333. open/commercial boundary.
  334. ---
  335. ## Support
  336. - **Documentation**: [docs/](docs/)
  337. - **Issues**: [GitHub Issues](https://github.com/thedotmack/claude-mem/issues)
  338. - **Repository**: [github.com/thedotmack/claude-mem](https://github.com/thedotmack/claude-mem)
  339. - **Official X Account**: [@Claude_Memory](https://x.com/Claude_Memory)
  340. - **Official Discord**: [Join Discord](https://discord.com/invite/J4wttp9vDu)
  341. - **Author**: Alex Newman ([@thedotmack](https://github.com/thedotmack))
  342. ---
  343. **Built with Claude Agent SDK** | **Works with Claude Code, Codex, Cursor, OpenCode and more** | **Made with TypeScript**
  344. ---
  345. ### What About CMEM?
  346. CMEM is a token created by a 3rd party but officially embraced by the creator of Claude-Mem (Alex Newman, @thedotmack). The token acts as a community catalyst for growth and a vehicle for bringing CMEM to the developers and knowledge workers that need it most.
  347. Official BASE CA: 0x76b1967eec0ccaeb001bbbb2b40dc4badba31ba3
openclaw/install.sh · Bundled script · 1,691 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. readonly MIN_BUN_VERSION="1.1.14"
  4. readonly INSTALLER_VERSION="1.0.0"
  5. NON_INTERACTIVE=""
  6. CLI_PROVIDER=""
  7. CLI_API_KEY=""
  8. UPGRADE_MODE=""
  9. CLI_BRANCH=""
  10. while [[ $# -gt 0 ]]; do
  11. case "$1" in
  12. --non-interactive)
  13. NON_INTERACTIVE="true"
  14. shift
  15. ;;
  16. --upgrade)
  17. UPGRADE_MODE="true"
  18. shift
  19. ;;
  20. --branch=*)
  21. CLI_BRANCH="${1#--branch=}"
  22. shift
  23. ;;
  24. --branch)
  25. CLI_BRANCH="${2:-}"
  26. shift 2
  27. ;;
  28. --provider=*)
  29. CLI_PROVIDER="${1#--provider=}"
  30. shift
  31. ;;
  32. --provider)
  33. CLI_PROVIDER="${2:-}"
  34. shift 2
  35. ;;
  36. --api-key=*)
  37. CLI_API_KEY="${1#--api-key=}"
  38. shift
  39. ;;
  40. --api-key)
  41. CLI_API_KEY="${2:-}"
  42. shift 2
  43. ;;
  44. *)
  45. shift
  46. ;;
  47. esac
  48. done
  49. TTY_FD=0
  50. setup_tty() {
  51. if [[ -t 0 ]]; then
  52. TTY_FD=0
  53. elif [[ "$NON_INTERACTIVE" == "true" ]]; then
  54. TTY_FD=0
  55. elif [[ -r /dev/tty ]]; then
  56. exec 3</dev/tty
  57. TTY_FD=3
  58. else
  59. echo "Error: No terminal available for interactive prompts." >&2
  60. echo "Use --non-interactive or run directly: bash install.sh" >&2
  61. exit 1
  62. fi
  63. }
  64. if [[ -t 1 ]] && [[ "${TERM:-}" != "dumb" ]]; then
  65. readonly COLOR_RED='\033[0;31m'
  66. readonly COLOR_GREEN='\033[0;32m'
  67. readonly COLOR_YELLOW='\033[0;33m'
  68. readonly COLOR_BLUE='\033[0;34m'
  69. readonly COLOR_MAGENTA='\033[0;35m'
  70. readonly COLOR_CYAN='\033[0;36m'
  71. readonly COLOR_BOLD='\033[1m'
  72. readonly COLOR_RESET='\033[0m'
  73. else
  74. readonly COLOR_RED=''
  75. readonly COLOR_GREEN=''
  76. readonly COLOR_YELLOW=''
  77. readonly COLOR_BLUE=''
  78. readonly COLOR_MAGENTA=''
  79. readonly COLOR_CYAN=''
  80. readonly COLOR_BOLD=''
  81. readonly COLOR_RESET=''
  82. fi
  83. info() { echo -e "${COLOR_BLUE}ℹ${COLOR_RESET} $*"; }
  84. success() { echo -e "${COLOR_GREEN}✓${COLOR_RESET} $*"; }
  85. warn() { echo -e "${COLOR_YELLOW}⚠${COLOR_RESET} $*"; }
  86. error() { echo -e "${COLOR_RED}✗${COLOR_RESET} $*" >&2; }
  87. prompt_user() {
  88. if [[ "$NON_INTERACTIVE" == "true" ]]; then
  89. error "Cannot prompt in non-interactive mode: $*"
  90. return 1
  91. fi
  92. echo -en "${COLOR_CYAN}?${COLOR_RESET} $* "
  93. }
  94. read_tty() {
  95. read "$@" <&"$TTY_FD"
  96. }
  97. CLEANUP_DIRS=()
  98. register_cleanup_dir() {
  99. CLEANUP_DIRS+=("$1")
  100. }
  101. cleanup_on_exit() {
  102. local exit_code=$?
  103. for dir in "${CLEANUP_DIRS[@]+"${CLEANUP_DIRS[@]}"}"; do
  104. if [[ -d "$dir" ]]; then
  105. rm -rf "$dir"
  106. fi
  107. done
  108. if [[ $exit_code -ne 0 ]]; then
  109. echo "" >&2
  110. error "Installation failed (exit code: ${exit_code})"
  111. error "Any temporary files have been cleaned up."
  112. error "Fix the issue above and re-run the installer."
  113. fi
  114. }
  115. trap cleanup_on_exit EXIT
  116. check_git() {
  117. if command -v git &>/dev/null; then
  118. return 0
  119. fi
  120. error "git is not installed"
  121. echo "" >&2
  122. case "${PLATFORM:-}" in
  123. macos)
  124. error "Install git on macOS with:"
  125. error " xcode-select --install"
  126. error " # or: brew install git"
  127. ;;
  128. linux)
  129. error "Install git on Linux with:"
  130. error " sudo apt install git # Debian/Ubuntu"
  131. error " sudo dnf install git # Fedora/RHEL"
  132. error " sudo pacman -S git # Arch"
  133. ;;
  134. *)
  135. error "Please install git and re-run this installer."
  136. ;;
  137. esac
  138. exit 1
  139. }
  140. check_port_37777() {
  141. local port_in_use=""
  142. if command -v lsof &>/dev/null; then
  143. if lsof -i :37777 -sTCP:LISTEN &>/dev/null; then
  144. port_in_use="true"
  145. fi
  146. elif command -v ss &>/dev/null; then
  147. if ss -tlnp 2>/dev/null | grep -q ':37777 '; then
  148. port_in_use="true"
  149. fi
  150. elif command -v curl &>/dev/null; then
  151. local response
  152. response="$(curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:37777/api/health" 2>/dev/null)" || true
  153. if [[ "$response" == "200" ]]; then
  154. port_in_use="true"
  155. fi
  156. fi
  157. if [[ "$port_in_use" == "true" ]]; then
  158. return 0
  159. fi
  160. return 1
  161. }
  162. is_claude_mem_installed() {
  163. if find_claude_mem_install_dir 2>/dev/null; then
  164. return 0
  165. fi
  166. return 1
  167. }
  168. ensure_jq_or_fallback() {
  169. local json_file="$1"
  170. shift
  171. local jq_filter="$1"
  172. shift
  173. if command -v jq &>/dev/null; then
  174. local tmp_file
  175. tmp_file="$(mktemp)"
  176. jq "$@" "$jq_filter" "$json_file" > "$tmp_file" && mv "$tmp_file" "$json_file"
  177. return $?
  178. fi
  179. if command -v python3 &>/dev/null; then
  180. :
  181. fi
  182. warn "jq not found — using node for JSON manipulation"
  183. return 1
  184. }
  185. parse_health_json() {
  186. local raw_json="$1"
  187. WORKER_VERSION=""
  188. WORKER_AI_PROVIDER=""
  189. WORKER_INITIALIZED=""
  190. WORKER_REPORTED_PID=""
  191. WORKER_UPTIME=""
  192. if [[ -z "$raw_json" ]]; then
  193. return 0
  194. fi
  195. if command -v jq &>/dev/null; then
  196. WORKER_VERSION="$(echo "$raw_json" | jq -r '.version // empty' 2>/dev/null)" || true
  197. WORKER_AI_PROVIDER="$(echo "$raw_json" | jq -r '.ai.provider // empty' 2>/dev/null)" || true
  198. WORKER_INITIALIZED="$(echo "$raw_json" | jq -r '.initialized // empty' 2>/dev/null)" || true
  199. WORKER_REPORTED_PID="$(echo "$raw_json" | jq -r '.pid // empty' 2>/dev/null)" || true
  200. WORKER_UPTIME="$(echo "$raw_json" | jq -r '.uptime // empty' 2>/dev/null)" || true
  201. return 0
  202. fi
  203. if command -v python3 &>/dev/null; then
  204. local parsed
  205. parsed="$(INSTALLER_HEALTH_JSON="$raw_json" python3 -c "
  206. import json, os, sys
  207. try:
  208. data = json.loads(os.environ['INSTALLER_HEALTH_JSON'])
  209. ai = data.get('ai') or {}
  210. fields = [
  211. str(data.get('version', '')),
  212. str(ai.get('provider', '')),
  213. str(data.get('initialized', '')),
  214. str(data.get('pid', '')),
  215. str(data.get('uptime', '')),
  216. ]
  217. sys.stdout.write('\n'.join(fields))
  218. except Exception:
  219. sys.stdout.write('\n\n\n\n')
  220. " 2>/dev/null)" || true
  221. if [[ -n "$parsed" ]]; then
  222. local -a health_fields
  223. IFS=$'\n' read -r -d '' -a health_fields <<< "$parsed" || true
  224. WORKER_VERSION="${health_fields[0]:-}"
  225. WORKER_AI_PROVIDER="${health_fields[1]:-}"
  226. WORKER_INITIALIZED="${health_fields[2]:-}"
  227. WORKER_REPORTED_PID="${health_fields[3]:-}"
  228. WORKER_UPTIME="${health_fields[4]:-}"
  229. [[ "$WORKER_VERSION" == "None" ]] && WORKER_VERSION=""
  230. [[ "$WORKER_AI_PROVIDER" == "None" ]] && WORKER_AI_PROVIDER=""
  231. [[ "$WORKER_INITIALIZED" == "None" ]] && WORKER_INITIALIZED=""
  232. [[ "$WORKER_REPORTED_PID" == "None" ]] && WORKER_REPORTED_PID=""
  233. [[ "$WORKER_UPTIME" == "None" ]] && WORKER_UPTIME=""
  234. fi
  235. return 0
  236. fi
  237. local parsed
  238. parsed="$(INSTALLER_HEALTH_JSON="$raw_json" node -e "
  239. try {
  240. const data = JSON.parse(process.env.INSTALLER_HEALTH_JSON);
  241. const ai = data.ai || {};
  242. const fields = [
  243. data.version ?? '',
  244. ai.provider ?? '',
  245. data.initialized != null ? String(data.initialized) : '',
  246. data.pid != null ? String(data.pid) : '',
  247. data.uptime != null ? String(data.uptime) : '',
  248. ];
  249. process.stdout.write(fields.join('\n'));
  250. } catch (e) {
  251. process.stdout.write('\n\n\n\n');
  252. }
  253. " 2>/dev/null)" || true
  254. if [[ -n "$parsed" ]]; then
  255. local -a health_fields
  256. IFS=$'\n' read -r -d '' -a health_fields <<< "$parsed" || true
  257. WORKER_VERSION="${health_fields[0]:-}"
  258. WORKER_AI_PROVIDER="${health_fields[1]:-}"
  259. WORKER_INITIALIZED="${health_fields[2]:-}"
  260. WORKER_REPORTED_PID="${health_fields[3]:-}"
  261. WORKER_UPTIME="${health_fields[4]:-}"
  262. fi
  263. }
  264. format_uptime_ms() {
  265. local ms="$1"
  266. local secs=$((ms / 1000))
  267. if (( secs >= 3600 )); then
  268. echo "$((secs / 3600))h $((secs % 3600 / 60))m"
  269. elif (( secs >= 60 )); then
  270. echo "$((secs / 60))m $((secs % 60))s"
  271. else
  272. echo "${secs}s"
  273. fi
  274. }
  275. print_banner() {
  276. echo -e "${COLOR_MAGENTA}${COLOR_BOLD}"
  277. cat << 'BANNER'
  278. ┌─────────────────────────────────────────┐
  279. │ claude-mem × OpenClaw │
  280. │ Persistent Memory Plugin Installer │
  281. └─────────────────────────────────────────┘
  282. BANNER
  283. echo -e "${COLOR_RESET}"
  284. info "Installer v${INSTALLER_VERSION}"
  285. echo ""
  286. }
  287. PLATFORM=""
  288. IS_WSL=""
  289. detect_platform() {
  290. local uname_out
  291. uname_out="$(uname -s)"
  292. case "${uname_out}" in
  293. Darwin*)
  294. PLATFORM="macos"
  295. ;;
  296. Linux*)
  297. if grep -qi microsoft /proc/version 2>/dev/null; then
  298. PLATFORM="linux"
  299. IS_WSL="true"
  300. else
  301. PLATFORM="linux"
  302. fi
  303. ;;
  304. MINGW*|MSYS*|CYGWIN*)
  305. PLATFORM="windows"
  306. ;;
  307. *)
  308. error "Unsupported platform: ${uname_out}"
  309. exit 1
  310. ;;
  311. esac
  312. info "Detected platform: ${PLATFORM}${IS_WSL:+ (WSL)}"
  313. }
  314. version_gte() {
  315. local v1="$1" v2="$2"
  316. local -a parts1 parts2
  317. IFS='.' read -ra parts1 <<< "$v1"
  318. IFS='.' read -ra parts2 <<< "$v2"
  319. for i in 0 1 2; do
  320. local p1="${parts1[$i]:-0}"
  321. local p2="${parts2[$i]:-0}"
  322. if (( p1 > p2 )); then return 0; fi
  323. if (( p1 < p2 )); then return 1; fi
  324. done
  325. return 0
  326. }
  327. BUN_PATH=""
  328. find_bun_path() {
  329. if command -v bun &>/dev/null; then
  330. BUN_PATH="$(command -v bun)"
  331. return 0
  332. fi
  333. local -a bun_paths=(
  334. "${HOME}/.bun/bin/bun"
  335. "/usr/local/bin/bun"
  336. "/opt/homebrew/bin/bun"
  337. )
  338. for candidate in "${bun_paths[@]}"; do
  339. if [[ -x "$candidate" ]]; then
  340. BUN_PATH="$candidate"
  341. return 0
  342. fi
  343. done
  344. BUN_PATH=""
  345. return 1
  346. }
  347. check_bun() {
  348. if ! find_bun_path; then
  349. return 1
  350. fi
  351. local bun_version
  352. bun_version="$("$BUN_PATH" --version 2>/dev/null)" || return 1
  353. if version_gte "$bun_version" "$MIN_BUN_VERSION"; then
  354. success "Bun ${bun_version} found at ${BUN_PATH}"
  355. return 0
  356. else
  357. warn "Bun ${bun_version} is below minimum required version ${MIN_BUN_VERSION}"
  358. return 1
  359. fi
  360. }
  361. install_bun() {
  362. info "Installing Bun runtime..."
  363. if ! curl -fsSL https://bun.sh/install | bash; then
  364. error "Failed to install Bun automatically"
  365. error "Please install manually:"
  366. error " curl -fsSL https://bun.sh/install | bash"
  367. error " Or: brew install oven-sh/bun/bun (macOS)"
  368. error "Then restart your terminal and re-run this installer."
  369. exit 1
  370. fi
  371. if ! find_bun_path; then
  372. error "Bun installation completed but binary not found in expected locations"
  373. error "Please restart your terminal and re-run this installer."
  374. exit 1
  375. fi
  376. local bun_version
  377. bun_version="$("$BUN_PATH" --version 2>/dev/null)" || true
  378. success "Bun ${bun_version} installed at ${BUN_PATH}"
  379. }
  380. UV_PATH=""
  381. find_uv_path() {
  382. if command -v uv &>/dev/null; then
  383. UV_PATH="$(command -v uv)"
  384. return 0
  385. fi
  386. local -a uv_paths=(
  387. "${HOME}/.local/bin/uv"
  388. "${HOME}/.cargo/bin/uv"
  389. "/usr/local/bin/uv"
  390. "/opt/homebrew/bin/uv"
  391. )
  392. for candidate in "${uv_paths[@]}"; do
  393. if [[ -x "$candidate" ]]; then
  394. UV_PATH="$candidate"
  395. return 0
  396. fi
  397. done
  398. UV_PATH=""
  399. return 1
  400. }
  401. check_uv() {
  402. if ! find_uv_path; then
  403. return 1
  404. fi
  405. local uv_version
  406. uv_version="$("$UV_PATH" --version 2>/dev/null)" || return 1
  407. success "uv ${uv_version} found at ${UV_PATH}"
  408. return 0
  409. }
  410. install_uv() {
  411. info "Installing uv (Python package manager for Chroma support)..."
  412. if ! curl -LsSf https://astral.sh/uv/install.sh | sh; then
  413. error "Failed to install uv automatically"
  414. error "Please install manually:"
  415. error " curl -LsSf https://astral.sh/uv/install.sh | sh"
  416. error " Or: brew install uv (macOS)"
  417. error "Then restart your terminal and re-run this installer."
  418. exit 1
  419. fi
  420. if ! find_uv_path; then
  421. error "uv installation completed but binary not found in expected locations"
  422. error "Please restart your terminal and re-run this installer."
  423. exit 1
  424. fi
  425. local uv_version
  426. uv_version="$("$UV_PATH" --version 2>/dev/null)" || true
  427. success "uv ${uv_version} installed at ${UV_PATH}"
  428. }
  429. OPENCLAW_PATH=""
  430. find_openclaw() {
  431. for bin_name in openclaw openclaw.mjs; do
  432. if command -v "$bin_name" &>/dev/null; then
  433. OPENCLAW_PATH="$(command -v "$bin_name")"
  434. return 0
  435. fi
  436. done
  437. local -a openclaw_paths=(
  438. "${HOME}/.openclaw/openclaw.mjs"
  439. "/usr/local/bin/openclaw.mjs"
  440. "/usr/local/bin/openclaw"
  441. "/usr/local/lib/node_modules/openclaw/openclaw.mjs"
  442. "${HOME}/.npm-global/lib/node_modules/openclaw/openclaw.mjs"
  443. "${HOME}/.npm-global/bin/openclaw"
  444. )
  445. if [[ -n "${NODE_PATH:-}" ]]; then
  446. openclaw_paths+=("${NODE_PATH}/openclaw/openclaw.mjs")
  447. fi
  448. for candidate in "${openclaw_paths[@]}"; do
  449. if [[ -f "$candidate" ]]; then
  450. OPENCLAW_PATH="$candidate"
  451. return 0
  452. fi
  453. done
  454. OPENCLAW_PATH=""
  455. return 1
  456. }
  457. check_openclaw() {
  458. if ! find_openclaw; then
  459. error "OpenClaw gateway not found"
  460. error ""
  461. error "The claude-mem plugin requires an OpenClaw gateway to be installed."
  462. error "Please install OpenClaw first:"
  463. error ""
  464. error " npm install -g openclaw"
  465. error " # or visit: https://openclaw.dev/docs/installation"
  466. error ""
  467. error "Then re-run this installer."
  468. exit 1
  469. fi
  470. success "OpenClaw gateway found at ${OPENCLAW_PATH}"
  471. }
  472. run_openclaw() {
  473. if [[ "$OPENCLAW_PATH" == *.mjs ]]; then
  474. node "$OPENCLAW_PATH" "$@"
  475. else
  476. "$OPENCLAW_PATH" "$@"
  477. fi
  478. }
  479. CLAUDE_MEM_REPO="https://github.com/thedotmack/claude-mem.git"
  480. CLAUDE_MEM_BRANCH="${CLI_BRANCH:-main}"
  481. PLUGIN_FRESHLY_INSTALLED=""
  482. resolve_extension_dir() {
  483. local oc_config="${HOME}/.openclaw/openclaw.json"
  484. if [[ -f "$oc_config" ]] && command -v node &>/dev/null; then
  485. local existing_path
  486. existing_path="$(node -e "
  487. try {
  488. const c = require('$oc_config');
  489. const p = c?.plugins?.installs?.['claude-mem']?.installPath;
  490. if (p) console.log(p);
  491. } catch {}
  492. " 2>/dev/null)" || true
  493. if [[ -n "$existing_path" ]]; then
  494. echo "$existing_path"
  495. return
  496. fi
  497. local load_path
  498. load_path="$(node -e "
  499. try {
  500. const c = require('$oc_config');
  501. const paths = c?.plugins?.load?.paths || [];
  502. const p = paths.find(p => p.endsWith('/claude-mem'));
  503. if (p) console.log(p);
  504. } catch {}
  505. " 2>/dev/null)" || true
  506. if [[ -n "$load_path" ]]; then
  507. echo "$load_path"
  508. return
  509. fi
  510. fi
  511. echo "${HOME}/.openclaw/extensions/claude-mem"
  512. }
  513. CLAUDE_MEM_EXTENSION_DIR=""
  514. # Newer OpenClaw asks before installing from any source outside ClawHub and,
  515. # with no terminal to answer (curl | bash), cancels unless --force confirms the
  516. # source. A local copy also needs --accept-capabilities. Running this installer
  517. # is the request to install this build, so confirm both. Older OpenClaw rejects
  518. # either flag as unknown, so print only the ones its CLI lists, one per line.
  519. openclaw_install_confirmation_flags() {
  520. local install_help flag
  521. install_help="$(run_openclaw plugins install --help 2>&1)" || true
  522. for flag in --force --accept-capabilities; do
  523. if grep -qE -- "(^|[[:space:],])${flag}([[:space:],]|$)" <<<"$install_help"; then
  524. echo "$flag"
  525. fi
  526. done
  527. }
  528. install_plugin() {
  529. check_git
  530. CLAUDE_MEM_EXTENSION_DIR="$(resolve_extension_dir)"
  531. local existing_plugin_dir="$CLAUDE_MEM_EXTENSION_DIR"
  532. if [[ -d "$existing_plugin_dir" ]]; then
  533. info "Removing existing claude-mem plugin at ${existing_plugin_dir}..."
  534. rm -rf "$existing_plugin_dir"
  535. fi
  536. local build_dir
  537. build_dir="$(mktemp -d)"
  538. register_cleanup_dir "$build_dir"
  539. info "Cloning claude-mem repository (branch: ${CLAUDE_MEM_BRANCH})..."
  540. if ! git clone --depth 1 --branch "$CLAUDE_MEM_BRANCH" "$CLAUDE_MEM_REPO" "$build_dir/claude-mem" 2>&1; then
  541. error "Failed to clone claude-mem repository"
  542. error "Check your internet connection and try again."
  543. exit 1
  544. fi
  545. local plugin_src="${build_dir}/claude-mem/openclaw"
  546. info "Building TypeScript plugin..."
  547. if ! (cd "$plugin_src" && NODE_ENV=development npm install --ignore-scripts 2>&1 && npx tsc 2>&1); then
  548. error "Failed to build the claude-mem OpenClaw plugin"
  549. error "Make sure Node.js and npm are installed."
  550. exit 1
  551. fi
  552. local installable_dir="${build_dir}/claude-mem-installable"
  553. mkdir -p "${installable_dir}/dist"
  554. cp "${plugin_src}/dist/index.js" "${installable_dir}/dist/"
  555. cp "${plugin_src}/dist/index.d.ts" "${installable_dir}/dist/" 2>/dev/null || true
  556. cp "${plugin_src}/openclaw.plugin.json" "${installable_dir}/"
  557. INSTALLER_PACKAGE_DIR="$installable_dir" node -e "
  558. const pkg = {
  559. name: 'claude-mem',
  560. version: '1.0.0',
  561. type: 'module',
  562. main: 'dist/index.js',
  563. openclaw: { extensions: ['./dist/index.js'] }
  564. };
  565. require('fs').writeFileSync(process.env.INSTALLER_PACKAGE_DIR + '/package.json', JSON.stringify(pkg, null, 2));
  566. "
  567. local oc_config="${HOME}/.openclaw/openclaw.json"
  568. local saved_plugin_config=""
  569. if [[ -f "$oc_config" ]]; then
  570. saved_plugin_config=$(INSTALLER_CONFIG_FILE="$oc_config" node -e "
  571. const fs = require('fs');
  572. const configPath = process.env.INSTALLER_CONFIG_FILE;
  573. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  574. const entry = config?.plugins?.entries?.['claude-mem'];
  575. const allowHasClaudeMem = Array.isArray(config?.plugins?.allow) && config.plugins.allow.includes('claude-mem');
  576. if (entry || config?.plugins?.slots?.memory === 'claude-mem' || allowHasClaudeMem) {
  577. // Save the config block so we can restore it after install
  578. process.stdout.write(JSON.stringify(entry?.config || {}));
  579. // Remove the stale entry so OpenClaw CLI can run
  580. if (entry) delete config.plugins.entries['claude-mem'];
  581. // Also remove stale allowlist reference — this alone can block ALL CLI commands
  582. if (Array.isArray(config?.plugins?.allow)) {
  583. config.plugins.allow = config.plugins.allow.filter((x) => x !== 'claude-mem');
  584. }
  585. // Also remove the slot reference — if the slot points to a plugin
  586. // that isn't in entries, OpenClaw's config validator rejects ALL commands
  587. if (config?.plugins?.slots?.memory === 'claude-mem') {
  588. delete config.plugins.slots.memory;
  589. }
  590. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  591. }
  592. " 2>/dev/null) || true
  593. fi
  594. local -a install_flags=()
  595. local flag
  596. while IFS= read -r flag; do
  597. install_flags+=("$flag")
  598. done < <(openclaw_install_confirmation_flags)
  599. info "Installing claude-mem plugin into OpenClaw..."
  600. if [[ ${#install_flags[@]} -gt 0 ]]; then
  601. info "Confirming this claude-mem build from ${CLAUDE_MEM_REPO} (${CLAUDE_MEM_BRANCH}) with: ${install_flags[*]}"
  602. fi
  603. if ! run_openclaw plugins install ${install_flags[@]+"${install_flags[@]}"} "$installable_dir" 2>&1; then
  604. error "Failed to install claude-mem plugin"
  605. error "Try manually: ${OPENCLAW_PATH} plugins install ${install_flags[*]+"${install_flags[*]} "}<path>"
  606. exit 1
  607. fi
  608. info "Enabling claude-mem plugin..."
  609. if ! run_openclaw plugins enable claude-mem 2>&1; then
  610. error "Failed to enable claude-mem plugin"
  611. error "Try manually: ${OPENCLAW_PATH} plugins enable claude-mem"
  612. exit 1
  613. fi
  614. if [[ -f "$oc_config" ]]; then
  615. if ! INSTALLER_CONFIG_FILE="$oc_config" node -e "
  616. const fs = require('fs');
  617. const configPath = process.env.INSTALLER_CONFIG_FILE;
  618. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  619. if (!config.plugins) config.plugins = {};
  620. if (!Array.isArray(config.plugins.allow)) config.plugins.allow = [];
  621. if (!config.plugins.allow.includes('claude-mem')) {
  622. config.plugins.allow.push('claude-mem');
  623. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  624. console.log('Added claude-mem to plugins.allow');
  625. } else {
  626. console.log('claude-mem already in plugins.allow');
  627. }
  628. " 2>&1; then
  629. warn "Failed to write plugins.allow — claude-mem may need manual allowlisting"
  630. fi
  631. else
  632. info "OpenClaw config not yet materialized; will ensure allowlist in post-install"
  633. if run_openclaw status --json >/dev/null 2>&1 && [[ -f "$oc_config" ]]; then
  634. if ! INSTALLER_CONFIG_FILE="$oc_config" node -e "
  635. const fs = require('fs');
  636. const configPath = process.env.INSTALLER_CONFIG_FILE;
  637. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  638. if (!config.plugins) config.plugins = {};
  639. if (!Array.isArray(config.plugins.allow)) config.plugins.allow = [];
  640. if (!config.plugins.allow.includes('claude-mem')) {
  641. config.plugins.allow.push('claude-mem');
  642. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  643. console.log('Added claude-mem to plugins.allow (post-materialization)');
  644. }
  645. " 2>&1; then
  646. warn "Failed to write plugins.allow after materialization — configure manually"
  647. fi
  648. fi
  649. fi
  650. if [[ -n "$saved_plugin_config" && "$saved_plugin_config" != "{}" ]]; then
  651. info "Restoring previous plugin configuration..."
  652. INSTALLER_CONFIG_FILE="$oc_config" INSTALLER_SAVED_CONFIG="$saved_plugin_config" node -e "
  653. const fs = require('fs');
  654. const configPath = process.env.INSTALLER_CONFIG_FILE;
  655. const savedConfig = JSON.parse(process.env.INSTALLER_SAVED_CONFIG);
  656. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  657. if (config?.plugins?.entries?.['claude-mem']) {
  658. config.plugins.entries['claude-mem'].config = savedConfig;
  659. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  660. }
  661. " 2>/dev/null || warn "Could not restore previous plugin config — configure manually"
  662. fi
  663. success "claude-mem plugin installed and enabled"
  664. local extension_dir="$CLAUDE_MEM_EXTENSION_DIR"
  665. local repo_root="${build_dir}/claude-mem"
  666. if [[ -d "$extension_dir" && -d "${repo_root}/plugin" ]]; then
  667. info "Copying core plugin files to ${extension_dir}..."
  668. cp -R "${repo_root}/plugin" "${extension_dir}/"
  669. local root_version
  670. root_version="$(node -e "console.log(require('${repo_root}/package.json').version)")"
  671. node -e "
  672. const fs = require('fs');
  673. const pkgPath = '${extension_dir}/package.json';
  674. const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
  675. pkg.version = '${root_version}';
  676. fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
  677. "
  678. success "Core plugin files updated at ${extension_dir}"
  679. else
  680. warn "Could not copy core plugin files — worker may need manual update"
  681. fi
  682. PLUGIN_FRESHLY_INSTALLED="true"
  683. }
  684. configure_memory_slot() {
  685. local config_dir="${HOME}/.openclaw"
  686. local config_file="${config_dir}/openclaw.json"
  687. mkdir -p "$config_dir"
  688. if [[ ! -f "$config_file" ]]; then
  689. info "Creating OpenClaw configuration with claude-mem memory slot..."
  690. INSTALLER_CONFIG_FILE="$config_file" node -e "
  691. const config = {
  692. plugins: {
  693. slots: { memory: 'claude-mem' },
  694. entries: {
  695. 'claude-mem': {
  696. enabled: true,
  697. config: {
  698. workerPort: 37777,
  699. syncMemoryFile: true
  700. }
  701. }
  702. }
  703. }
  704. };
  705. require('fs').writeFileSync(process.env.INSTALLER_CONFIG_FILE, JSON.stringify(config, null, 2));
  706. "
  707. success "Created ${config_file} with memory slot set to claude-mem"
  708. return 0
  709. fi
  710. info "Updating OpenClaw configuration to use claude-mem memory slot..."
  711. INSTALLER_CONFIG_FILE="$config_file" node -e "
  712. const fs = require('fs');
  713. const configPath = process.env.INSTALLER_CONFIG_FILE;
  714. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  715. // Ensure plugins structure exists
  716. if (!config.plugins) config.plugins = {};
  717. if (!config.plugins.slots) config.plugins.slots = {};
  718. if (!config.plugins.entries) config.plugins.entries = {};
  719. // Set memory slot to claude-mem
  720. config.plugins.slots.memory = 'claude-mem';
  721. // Ensure claude-mem entry exists and is enabled
  722. if (!config.plugins.entries['claude-mem']) {
  723. config.plugins.entries['claude-mem'] = {
  724. enabled: true,
  725. config: {
  726. workerPort: 37777,
  727. syncMemoryFile: true
  728. }
  729. };
  730. } else {
  731. config.plugins.entries['claude-mem'].enabled = true;
  732. // Remove unrecognized keys that cause OpenClaw config validation errors
  733. const allowedKeys = new Set(['enabled', 'config']);
  734. for (const key of Object.keys(config.plugins.entries['claude-mem'])) {
  735. if (!allowedKeys.has(key)) {
  736. delete config.plugins.entries['claude-mem'][key];
  737. }
  738. }
  739. }
  740. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  741. "
  742. success "Memory slot set to claude-mem in ${config_file}"
  743. }
  744. # Newer OpenClaw blocks before_prompt_build and agent_end for plugins that are
  745. # not bundled with it unless the plugin's entry allows conversation access.
  746. # Those hooks record the prompt, inject context and summarize the session, so
  747. # claude-mem does nothing useful without the grant. Older OpenClaw has no such
  748. # gate and rejects the key, so let OpenClaw's own config validation decide.
  749. allow_conversation_hooks() {
  750. local grant_key="plugins.entries.claude-mem.hooks.allowConversationAccess"
  751. local output
  752. if output="$(run_openclaw config set "$grant_key" true 2>&1)"; then
  753. success "Allowed claude-mem's conversation hooks (${grant_key})"
  754. return 0
  755. fi
  756. if grep -qF 'plugins.entries.claude-mem: Unrecognized key: "hooks"' <<<"$output"; then
  757. info "This OpenClaw version does not gate conversation hooks; nothing to allow"
  758. return 0
  759. fi
  760. echo "$output" >&2
  761. error "Could not allow claude-mem's conversation hooks"
  762. error "Without this, OpenClaw blocks prompt capture, context injection and session summaries."
  763. error "Run: ${OPENCLAW_PATH} config set ${grant_key} true"
  764. exit 1
  765. }
  766. AI_PROVIDER=""
  767. AI_PROVIDER_API_KEY=""
  768. mask_api_key() {
  769. local key="$1"
  770. local len=${#key}
  771. if (( len <= 4 )); then
  772. echo "****"
  773. else
  774. local masked_len=$((len - 4))
  775. local mask=""
  776. for (( i=0; i<masked_len; i++ )); do
  777. mask+="*"
  778. done
  779. echo "${mask}${key: -4}"
  780. fi
  781. }
  782. setup_ai_provider() {
  783. echo ""
  784. info "AI Provider Configuration"
  785. echo ""
  786. if [[ -n "$CLI_PROVIDER" ]]; then
  787. case "$CLI_PROVIDER" in
  788. claude)
  789. AI_PROVIDER="claude"
  790. success "Selected via --provider: Claude Max Plan (CLI authentication)"
  791. ;;
  792. gemini)
  793. AI_PROVIDER="gemini"
  794. AI_PROVIDER_API_KEY="${CLI_API_KEY}"
  795. if [[ -n "$AI_PROVIDER_API_KEY" ]]; then
  796. success "Selected via --provider: Gemini (API key set via --api-key)"
  797. else
  798. warn "Selected via --provider: Gemini (no API key — add later in ~/.claude-mem/settings.json)"
  799. fi
  800. ;;
  801. openrouter)
  802. AI_PROVIDER="openrouter"
  803. AI_PROVIDER_API_KEY="${CLI_API_KEY}"
  804. if [[ -n "$AI_PROVIDER_API_KEY" ]]; then
  805. success "Selected via --provider: OpenRouter (API key set via --api-key)"
  806. else
  807. warn "Selected via --provider: OpenRouter (no API key — add later in ~/.claude-mem/settings.json)"
  808. fi
  809. ;;
  810. *)
  811. error "Unknown provider: ${CLI_PROVIDER}"
  812. error "Valid providers: claude, gemini, openrouter"
  813. exit 1
  814. ;;
  815. esac
  816. return 0
  817. fi
  818. if [[ "$NON_INTERACTIVE" == "true" ]]; then
  819. info "Non-interactive mode: defaulting to Claude Max Plan (no API key needed)"
  820. AI_PROVIDER="claude"
  821. return 0
  822. fi
  823. echo -e " Choose your AI provider for claude-mem:"
  824. echo ""
  825. echo -e " ${COLOR_BOLD}1)${COLOR_RESET} Claude Max Plan ${COLOR_GREEN}(recommended)${COLOR_RESET}"
  826. echo -e " Uses your existing subscription, no API key needed"
  827. echo ""
  828. echo -e " ${COLOR_BOLD}2)${COLOR_RESET} Gemini"
  829. echo -e " Free tier available — requires API key from ai.google.dev"
  830. echo ""
  831. echo -e " ${COLOR_BOLD}3)${COLOR_RESET} OpenRouter"
  832. echo -e " Pay-per-use — requires API key from openrouter.ai"
  833. echo ""
  834. local choice
  835. while true; do
  836. prompt_user "Enter choice [1/2/3] (default: 1):"
  837. read_tty -r choice
  838. choice="${choice:-1}"
  839. case "$choice" in
  840. 1)
  841. AI_PROVIDER="claude"
  842. success "Selected: Claude Max Plan (CLI authentication)"
  843. break
  844. ;;
  845. 2)
  846. AI_PROVIDER="gemini"
  847. echo ""
  848. prompt_user "Enter your Gemini API key (from https://ai.google.dev):"
  849. read_tty -rs AI_PROVIDER_API_KEY
  850. echo ""
  851. if [[ -z "$AI_PROVIDER_API_KEY" ]]; then
  852. warn "No API key provided — you can add it later in ~/.claude-mem/settings.json"
  853. else
  854. success "Gemini API key set ($(mask_api_key "$AI_PROVIDER_API_KEY"))"
  855. fi
  856. break
  857. ;;
  858. 3)
  859. AI_PROVIDER="openrouter"
  860. echo ""
  861. prompt_user "Enter your OpenRouter API key (from https://openrouter.ai):"
  862. read_tty -rs AI_PROVIDER_API_KEY
  863. echo ""
  864. if [[ -z "$AI_PROVIDER_API_KEY" ]]; then
  865. warn "No API key provided — you can add it later in ~/.claude-mem/settings.json"
  866. else
  867. success "OpenRouter API key set ($(mask_api_key "$AI_PROVIDER_API_KEY"))"
  868. fi
  869. break
  870. ;;
  871. *)
  872. warn "Invalid choice. Please enter 1, 2, or 3."
  873. ;;
  874. esac
  875. done
  876. }
  877. write_settings() {
  878. local settings_dir="${HOME}/.claude-mem"
  879. local settings_file="${settings_dir}/settings.json"
  880. mkdir -p "$settings_dir"
  881. INSTALLER_AI_PROVIDER="$AI_PROVIDER" \
  882. INSTALLER_AI_API_KEY="$AI_PROVIDER_API_KEY" \
  883. INSTALLER_SETTINGS_FILE="$settings_file" \
  884. node -e "
  885. const fs = require('fs');
  886. const path = require('path');
  887. const homedir = require('os').homedir();
  888. const provider = process.env.INSTALLER_AI_PROVIDER;
  889. const apiKey = process.env.INSTALLER_AI_API_KEY || '';
  890. const settingsPath = process.env.INSTALLER_SETTINGS_FILE;
  891. // All defaults from SettingsDefaultsManager.ts
  892. const defaults = {
  893. CLAUDE_MEM_MODEL: 'claude-sonnet-5',
  894. CLAUDE_MEM_CONTEXT_OBSERVATIONS: '50',
  895. CLAUDE_MEM_WORKER_PORT: '37777',
  896. CLAUDE_MEM_WORKER_HOST: '127.0.0.1',
  897. CLAUDE_MEM_SKIP_TOOLS: 'ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion',
  898. CLAUDE_MEM_PROVIDER: 'claude',
  899. CLAUDE_MEM_CLAUDE_AUTH_METHOD: 'cli',
  900. CLAUDE_MEM_GEMINI_API_KEY: '',
  901. CLAUDE_MEM_GEMINI_MODEL: 'gemini-2.5-flash-lite',
  902. CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED: 'true',
  903. CLAUDE_MEM_OPENROUTER_API_KEY: '',
  904. CLAUDE_MEM_OPENROUTER_MODEL: 'cohere/north-mini-code:free',
  905. CLAUDE_MEM_OPENROUTER_SITE_URL: '',
  906. CLAUDE_MEM_OPENROUTER_APP_NAME: 'claude-mem',
  907. CLAUDE_MEM_DATA_DIR: path.join(homedir, '.claude-mem'),
  908. CLAUDE_MEM_LOG_LEVEL: 'INFO',
  909. CLAUDE_MEM_PYTHON_VERSION: '3.13',
  910. CLAUDE_CODE_PATH: '',
  911. CLAUDE_MEM_MODE: 'code',
  912. CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS: 'true',
  913. CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS: 'true',
  914. CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES: 'bugfix,feature,refactor,discovery,decision,change',
  915. CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS: 'how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off',
  916. CLAUDE_MEM_CONTEXT_FULL_COUNT: '5',
  917. CLAUDE_MEM_CONTEXT_FULL_FIELD: 'narrative',
  918. CLAUDE_MEM_CONTEXT_SESSION_COUNT: '10',
  919. CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY: 'true',
  920. CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE: 'false',
  921. CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED: 'false',
  922. CLAUDE_MEM_EXCLUDED_PROJECTS: '',
  923. CLAUDE_MEM_FOLDER_MD_EXCLUDE: '[]'
  924. };
  925. // Build provider-specific overrides safely from environment variables
  926. const overrides = { CLAUDE_MEM_PROVIDER: provider };
  927. if (provider === 'claude') {
  928. overrides.CLAUDE_MEM_CLAUDE_AUTH_METHOD = 'cli';
  929. } else if (provider === 'gemini') {
  930. overrides.CLAUDE_MEM_GEMINI_API_KEY = apiKey;
  931. overrides.CLAUDE_MEM_GEMINI_MODEL = 'gemini-2.5-flash-lite';
  932. } else if (provider === 'openrouter') {
  933. overrides.CLAUDE_MEM_OPENROUTER_API_KEY = apiKey;
  934. overrides.CLAUDE_MEM_OPENROUTER_MODEL = 'cohere/north-mini-code:free';
  935. }
  936. const settings = Object.assign(defaults, overrides);
  937. // If settings file already exists, merge (preserve user customizations)
  938. if (fs.existsSync(settingsPath)) {
  939. try {
  940. let existing = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
  941. // Handle old nested schema
  942. if (existing.env && typeof existing.env === 'object') {
  943. existing = existing.env;
  944. }
  945. // Existing settings take priority, except for provider settings we
  946. // just set. Preserve EVERY existing key — not only ones the installer
  947. // happens to know — so a reinstall can never silently drop a secret
  948. // (e.g. CLAUDE_MEM_LOCAL_API_TOKEN) while keeping the non-loopback bind that
  949. // secret was protecting (CLAUDE_MEM_WORKER_HOST is a known default).
  950. for (const key of Object.keys(existing)) {
  951. if (!(key in overrides)) {
  952. settings[key] = existing[key];
  953. }
  954. }
  955. } catch (e) {
  956. // Corrupted file — overwrite with fresh defaults
  957. }
  958. }
  959. fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
  960. "
  961. success "Settings written to ${settings_file}"
  962. }
  963. CLAUDE_MEM_INSTALL_DIR=""
  964. find_claude_mem_install_dir() {
  965. local resolved_dir
  966. resolved_dir="$(resolve_extension_dir)"
  967. local -a search_paths=(
  968. "$resolved_dir"
  969. "${HOME}/.openclaw/extensions/claude-mem"
  970. "${HOME}/.claude/plugins/marketplaces/thedotmack"
  971. "${HOME}/.openclaw/plugins/claude-mem"
  972. )
  973. for candidate in "${search_paths[@]}"; do
  974. if [[ -f "${candidate}/plugin/scripts/worker-service.cjs" ]]; then
  975. CLAUDE_MEM_INSTALL_DIR="$candidate"
  976. return 0
  977. fi
  978. done
  979. local -a roots=(
  980. "${HOME}/.openclaw"
  981. "${HOME}/.claude/plugins"
  982. )
  983. for root in "${roots[@]}"; do
  984. if [[ -d "$root" ]]; then
  985. local found
  986. found="$(find "$root" -name "worker-service.cjs" -path "*/plugin/scripts/*" 2>/dev/null | head -n 1)" || true
  987. if [[ -n "$found" ]]; then
  988. CLAUDE_MEM_INSTALL_DIR="${found%/plugin/scripts/worker-service.cjs}"
  989. return 0
  990. fi
  991. fi
  992. done
  993. CLAUDE_MEM_INSTALL_DIR=""
  994. return 1
  995. }
  996. WORKER_PID=""
  997. WORKER_VERSION=""
  998. WORKER_AI_PROVIDER=""
  999. WORKER_INITIALIZED=""
  1000. WORKER_REPORTED_PID=""
  1001. WORKER_UPTIME=""
  1002. start_worker() {
  1003. info "Starting claude-mem worker service..."
  1004. if ! find_claude_mem_install_dir; then
  1005. error "Cannot find claude-mem plugin installation directory"
  1006. error "Expected worker-service.cjs in one of:"
  1007. error " ~/.openclaw/extensions/claude-mem/plugin/scripts/"
  1008. error " ~/.claude/plugins/marketplaces/thedotmack/plugin/scripts/"
  1009. error ""
  1010. error "Try reinstalling the plugin and re-running this installer."
  1011. return 1
  1012. fi
  1013. local worker_script="${CLAUDE_MEM_INSTALL_DIR}/plugin/scripts/worker-service.cjs"
  1014. local log_dir="${HOME}/.claude-mem/logs"
  1015. local log_date
  1016. log_date="$(date +%Y-%m-%d)"
  1017. local log_file="${log_dir}/worker-${log_date}.log"
  1018. mkdir -p "$log_dir"
  1019. if [[ -z "$BUN_PATH" ]]; then
  1020. if ! find_bun_path; then
  1021. error "Bun not found — cannot start worker service"
  1022. return 1
  1023. fi
  1024. fi
  1025. CLAUDE_MEM_WORKER_PORT=37777 nohup "$BUN_PATH" "$worker_script" \
  1026. >> "$log_file" 2>&1 &
  1027. WORKER_PID=$!
  1028. local pid_file="${HOME}/.claude-mem/worker.pid"
  1029. mkdir -p "${HOME}/.claude-mem"
  1030. INSTALLER_PID_FILE="$pid_file" INSTALLER_WORKER_PID="$WORKER_PID" node -e "
  1031. const info = {
  1032. pid: parseInt(process.env.INSTALLER_WORKER_PID, 10),
  1033. port: 37777,
  1034. startedAt: new Date().toISOString(),
  1035. version: 'installer'
  1036. };
  1037. require('fs').writeFileSync(process.env.INSTALLER_PID_FILE, JSON.stringify(info, null, 2));
  1038. "
  1039. success "Worker process started (PID: ${WORKER_PID})"
  1040. info "Logs: ${log_file}"
  1041. }
  1042. verify_health() {
  1043. local max_attempts=30
  1044. local attempt=1
  1045. local health_url="http://127.0.0.1:37777/api/health"
  1046. local readiness_url="http://127.0.0.1:37777/api/readiness"
  1047. local health_alive=false
  1048. info "Verifying worker health..."
  1049. while (( attempt <= max_attempts )); do
  1050. local http_status
  1051. http_status="$(curl -s -o /dev/null -w "%{http_code}" "$health_url" 2>/dev/null)" || true
  1052. if [[ "$http_status" == "200" ]]; then
  1053. health_alive=true
  1054. local body
  1055. body="$(curl -s "$health_url" 2>/dev/null)" || true
  1056. parse_health_json "$body"
  1057. success "Worker is alive, waiting for initialization..."
  1058. break
  1059. fi
  1060. info "Waiting for worker to start... (attempt ${attempt}/${max_attempts})"
  1061. sleep 1
  1062. attempt=$((attempt + 1))
  1063. done
  1064. if [[ "$health_alive" != "true" ]]; then
  1065. warn "Worker health check timed out after ${max_attempts} attempts"
  1066. warn "The worker may still be starting up. Check status with:"
  1067. warn " curl http://127.0.0.1:37777/api/health"
  1068. warn " Or check logs: ~/.claude-mem/logs/"
  1069. return 1
  1070. fi
  1071. attempt=$((attempt + 1))
  1072. while (( attempt <= max_attempts )); do
  1073. local readiness_status
  1074. readiness_status="$(curl -s -o /dev/null -w "%{http_code}" "$readiness_url" 2>/dev/null)" || true
  1075. if [[ "$readiness_status" == "200" ]]; then
  1076. success "Worker is ready!"
  1077. return 0
  1078. fi
  1079. info "Waiting for worker to initialize... (attempt ${attempt}/${max_attempts})"
  1080. sleep 1
  1081. attempt=$((attempt + 1))
  1082. done
  1083. warn "Worker is running but initialization is still in progress"
  1084. warn "This is normal on first run — the worker will finish initializing in the background."
  1085. warn "Check readiness with: curl http://127.0.0.1:37777/api/readiness"
  1086. return 0
  1087. }
  1088. FEED_CHANNEL=""
  1089. FEED_TARGET_ID=""
  1090. FEED_CONFIGURED=false
  1091. setup_observation_feed() {
  1092. echo ""
  1093. echo -e " ${COLOR_BOLD}Real-Time Observation Feed${COLOR_RESET}"
  1094. echo ""
  1095. echo " claude-mem can stream AI-compressed observations to a messaging"
  1096. echo " channel in real time. Every time an agent learns something,"
  1097. echo " you'll see it in your chat."
  1098. echo ""
  1099. if [[ "$NON_INTERACTIVE" == "true" ]]; then
  1100. info "Non-interactive mode: skipping observation feed setup"
  1101. info "Configure later in ~/.openclaw/openclaw.json under"
  1102. info " plugins.entries.claude-mem.config.observationFeed"
  1103. return 0
  1104. fi
  1105. prompt_user "Would you like to set up real-time observation streaming to a messaging channel? (y/n)"
  1106. local answer
  1107. read_tty -r answer
  1108. answer="${answer:-n}"
  1109. if [[ "$answer" != [yY] && "$answer" != [yY][eE][sS] ]]; then
  1110. echo ""
  1111. info "Skipped observation feed setup."
  1112. info "You can configure it later by re-running this installer or"
  1113. info "editing ~/.openclaw/openclaw.json under"
  1114. info " plugins.entries.claude-mem.config.observationFeed"
  1115. return 0
  1116. fi
  1117. echo ""
  1118. echo -e " ${COLOR_BOLD}Select your messaging channel:${COLOR_RESET}"
  1119. echo ""
  1120. echo -e " ${COLOR_BOLD}1)${COLOR_RESET} Telegram"
  1121. echo -e " ${COLOR_BOLD}2)${COLOR_RESET} Discord"
  1122. echo -e " ${COLOR_BOLD}3)${COLOR_RESET} Slack"
  1123. echo -e " ${COLOR_BOLD}4)${COLOR_RESET} Signal"
  1124. echo -e " ${COLOR_BOLD}5)${COLOR_RESET} WhatsApp"
  1125. echo -e " ${COLOR_BOLD}6)${COLOR_RESET} LINE"
  1126. echo ""
  1127. local channel_choice
  1128. while true; do
  1129. prompt_user "Enter choice [1-6]:"
  1130. read_tty -r channel_choice
  1131. case "$channel_choice" in
  1132. 1)
  1133. FEED_CHANNEL="telegram"
  1134. echo ""
  1135. echo -e " ${COLOR_CYAN}How to find your Telegram chat ID:${COLOR_RESET}"
  1136. echo " Message @userinfobot on Telegram (https://t.me/userinfobot)"
  1137. echo " — it replies with your numeric chat ID."
  1138. echo " For groups, the ID is negative (e.g., -1001234567890)."
  1139. break
  1140. ;;
  1141. 2)
  1142. FEED_CHANNEL="discord"
  1143. echo ""
  1144. echo -e " ${COLOR_CYAN}How to find your Discord channel ID:${COLOR_RESET}"
  1145. echo " Enable Developer Mode (Settings → Advanced → Developer Mode),"
  1146. echo " right-click the target channel → Copy Channel ID"
  1147. break
  1148. ;;
  1149. 3)
  1150. FEED_CHANNEL="slack"
  1151. echo ""
  1152. echo -e " ${COLOR_CYAN}How to find your Slack channel ID:${COLOR_RESET}"
  1153. echo " Open the channel, click the channel name at top,"
  1154. echo " scroll to bottom — ID looks like C01ABC2DEFG"
  1155. break
  1156. ;;
  1157. 4)
  1158. FEED_CHANNEL="signal"
  1159. echo ""
  1160. echo -e " ${COLOR_CYAN}How to find your Signal target ID:${COLOR_RESET}"
  1161. echo " Use the phone number or group ID from your"
  1162. echo " OpenClaw Signal plugin config"
  1163. break
  1164. ;;
  1165. 5)
  1166. FEED_CHANNEL="whatsapp"
  1167. echo ""
  1168. echo -e " ${COLOR_CYAN}How to find your WhatsApp target ID:${COLOR_RESET}"
  1169. echo " Use the phone number or group JID from your"
  1170. echo " OpenClaw WhatsApp plugin config"
  1171. break
  1172. ;;
  1173. 6)
  1174. FEED_CHANNEL="line"
  1175. echo ""
  1176. echo -e " ${COLOR_CYAN}How to find your LINE target ID:${COLOR_RESET}"
  1177. echo " Use the user ID or group ID from the"
  1178. echo " LINE Developer Console"
  1179. break
  1180. ;;
  1181. *)
  1182. warn "Invalid choice. Please enter a number between 1 and 6."
  1183. ;;
  1184. esac
  1185. done
  1186. echo ""
  1187. prompt_user "Enter your ${FEED_CHANNEL} target ID:"
  1188. read_tty -r FEED_TARGET_ID
  1189. if [[ -z "$FEED_TARGET_ID" ]]; then
  1190. warn "No target ID provided — skipping observation feed setup."
  1191. warn "You can configure it later in ~/.openclaw/openclaw.json"
  1192. FEED_CHANNEL=""
  1193. return 0
  1194. fi
  1195. success "Observation feed: ${FEED_CHANNEL} → ${FEED_TARGET_ID}"
  1196. FEED_CONFIGURED=true
  1197. }
  1198. write_observation_feed_config() {
  1199. if [[ "$FEED_CONFIGURED" != "true" ]]; then
  1200. return 0
  1201. fi
  1202. local config_file="${HOME}/.openclaw/openclaw.json"
  1203. if [[ ! -f "$config_file" ]]; then
  1204. warn "OpenClaw config file not found at ${config_file}"
  1205. warn "Cannot write observation feed config."
  1206. return 1
  1207. fi
  1208. info "Writing observation feed configuration..."
  1209. if command -v jq &>/dev/null; then
  1210. local tmp_file
  1211. tmp_file="$(mktemp)"
  1212. jq --arg channel "$FEED_CHANNEL" --arg target "$FEED_TARGET_ID" '
  1213. .plugins //= {} |
  1214. .plugins.entries //= {} |
  1215. .plugins.entries["claude-mem"] //= {"enabled": true, "config": {}} |
  1216. .plugins.entries["claude-mem"].config //= {} |
  1217. .plugins.entries["claude-mem"].config.observationFeed = {
  1218. "enabled": true,
  1219. "channel": $channel,
  1220. "to": $target
  1221. }
  1222. ' "$config_file" > "$tmp_file" && mv "$tmp_file" "$config_file"
  1223. elif command -v python3 &>/dev/null; then
  1224. INSTALLER_FEED_CHANNEL="$FEED_CHANNEL" \
  1225. INSTALLER_FEED_TARGET_ID="$FEED_TARGET_ID" \
  1226. INSTALLER_CONFIG_FILE="$config_file" \
  1227. python3 -c "
  1228. import json, os
  1229. config_path = os.environ['INSTALLER_CONFIG_FILE']
  1230. channel = os.environ['INSTALLER_FEED_CHANNEL']
  1231. target_id = os.environ['INSTALLER_FEED_TARGET_ID']
  1232. with open(config_path) as f:
  1233. config = json.load(f)
  1234. config.setdefault('plugins', {})
  1235. config['plugins'].setdefault('entries', {})
  1236. config['plugins']['entries'].setdefault('claude-mem', {'enabled': True, 'config': {}})
  1237. config['plugins']['entries']['claude-mem'].setdefault('config', {})
  1238. config['plugins']['entries']['claude-mem']['config']['observationFeed'] = {
  1239. 'enabled': True,
  1240. 'channel': channel,
  1241. 'to': target_id
  1242. }
  1243. with open(config_path, 'w') as f:
  1244. json.dump(config, f, indent=2)
  1245. "
  1246. else
  1247. INSTALLER_FEED_CHANNEL="$FEED_CHANNEL" \
  1248. INSTALLER_FEED_TARGET_ID="$FEED_TARGET_ID" \
  1249. INSTALLER_CONFIG_FILE="$config_file" \
  1250. node -e "
  1251. const fs = require('fs');
  1252. const configPath = process.env.INSTALLER_CONFIG_FILE;
  1253. const channel = process.env.INSTALLER_FEED_CHANNEL;
  1254. const targetId = process.env.INSTALLER_FEED_TARGET_ID;
  1255. const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  1256. if (!config.plugins) config.plugins = {};
  1257. if (!config.plugins.entries) config.plugins.entries = {};
  1258. if (!config.plugins.entries['claude-mem']) {
  1259. config.plugins.entries['claude-mem'] = { enabled: true, config: {} };
  1260. }
  1261. if (!config.plugins.entries['claude-mem'].config) {
  1262. config.plugins.entries['claude-mem'].config = {};
  1263. }
  1264. config.plugins.entries['claude-mem'].config.observationFeed = {
  1265. enabled: true,
  1266. channel: channel,
  1267. to: targetId
  1268. };
  1269. fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
  1270. "
  1271. fi
  1272. success "Observation feed config written to ${config_file}"
  1273. echo ""
  1274. echo -e " ${COLOR_BOLD}Observation feed summary:${COLOR_RESET}"
  1275. echo -e " Channel: ${COLOR_CYAN}${FEED_CHANNEL}${COLOR_RESET}"
  1276. echo -e " Target: ${COLOR_CYAN}${FEED_TARGET_ID}${COLOR_RESET}"
  1277. echo -e " Enabled: ${COLOR_GREEN}yes${COLOR_RESET}"
  1278. echo ""
  1279. info "Restart your OpenClaw gateway to activate the observation feed."
  1280. info "You should see these log lines:"
  1281. echo " [claude-mem] Observation feed starting — channel: ${FEED_CHANNEL}, target: ${FEED_TARGET_ID}"
  1282. echo ""
  1283. info "After restarting, run /claude-mem-feed in any OpenClaw chat to verify"
  1284. info "the feed is connected."
  1285. }
  1286. print_completion_summary() {
  1287. local provider_display=""
  1288. case "$AI_PROVIDER" in
  1289. claude) provider_display="Claude Max Plan (CLI authentication)" ;;
  1290. gemini) provider_display="Gemini (gemini-2.5-flash-lite)" ;;
  1291. openrouter) provider_display="OpenRouter (cohere/north-mini-code:free)" ;;
  1292. *) provider_display="$AI_PROVIDER" ;;
  1293. esac
  1294. echo ""
  1295. echo -e "${COLOR_MAGENTA}${COLOR_BOLD}"
  1296. echo " ┌──────────────────────────────────────────┐"
  1297. echo " │ Installation Complete! │"
  1298. echo " └──────────────────────────────────────────┘"
  1299. echo -e "${COLOR_RESET}"
  1300. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Dependencies installed (Bun, uv)"
  1301. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} OpenClaw gateway detected"
  1302. if [[ -n "$WORKER_VERSION" ]]; then
  1303. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} claude-mem v${COLOR_BOLD}${WORKER_VERSION}${COLOR_RESET} installed and running"
  1304. else
  1305. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} claude-mem plugin installed and enabled"
  1306. fi
  1307. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Memory slot configured"
  1308. # /api/health names the provider but not its auth method (#6309), so the
  1309. # summary describes the provider this install configured.
  1310. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} AI provider: ${COLOR_BOLD}${provider_display}${COLOR_RESET}"
  1311. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Settings written to ~/.claude-mem/settings.json"
  1312. if [[ -n "$WORKER_PID" ]] && kill -0 "$WORKER_PID" 2>/dev/null; then
  1313. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Worker running on port ${COLOR_BOLD}37777${COLOR_RESET} (PID: ${WORKER_PID})"
  1314. elif [[ -n "$WORKER_UPTIME" && "$WORKER_UPTIME" =~ ^[0-9]+$ ]] && (( WORKER_UPTIME > 0 )); then
  1315. local uptime_formatted
  1316. uptime_formatted="$(format_uptime_ms "$WORKER_UPTIME")"
  1317. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Worker running on port ${COLOR_BOLD}37777${COLOR_RESET} (PID: ${WORKER_REPORTED_PID}, uptime: ${uptime_formatted})"
  1318. else
  1319. echo -e " ${COLOR_YELLOW}⚠${COLOR_RESET} Worker may not be running — check logs at ~/.claude-mem/logs/"
  1320. fi
  1321. if [[ "$WORKER_INITIALIZED" != "true" ]] && { [[ -n "$WORKER_REPORTED_PID" ]] || { [[ -n "$WORKER_PID" ]] && kill -0 "$WORKER_PID" 2>/dev/null; }; }; then
  1322. echo -e " ${COLOR_YELLOW}⚠${COLOR_RESET} Worker is starting but still initializing (this is normal on first run)"
  1323. fi
  1324. if [[ "$FEED_CONFIGURED" == "true" ]]; then
  1325. echo -e " ${COLOR_GREEN}✓${COLOR_RESET} Observation feed: ${COLOR_BOLD}${FEED_CHANNEL}${COLOR_RESET} → ${FEED_TARGET_ID}"
  1326. else
  1327. echo -e " ${COLOR_YELLOW}─${COLOR_RESET} Observation feed: not configured (optional)"
  1328. echo -e " Configure later in ~/.openclaw/openclaw.json under"
  1329. echo -e " plugins.entries.claude-mem.config.observationFeed"
  1330. fi
  1331. echo ""
  1332. echo -e " ${COLOR_BOLD}What's next?${COLOR_RESET}"
  1333. echo ""
  1334. echo -e " ${COLOR_CYAN}1.${COLOR_RESET} Restart your OpenClaw gateway to load the plugin"
  1335. echo -e " ${COLOR_CYAN}2.${COLOR_RESET} Verify with ${COLOR_BOLD}/claude-mem-status${COLOR_RESET} in any OpenClaw chat"
  1336. echo -e " ${COLOR_CYAN}3.${COLOR_RESET} Check the viewer UI at ${COLOR_BOLD}http://localhost:37777${COLOR_RESET}"
  1337. if [[ "$FEED_CONFIGURED" == "true" ]]; then
  1338. echo -e " ${COLOR_CYAN}4.${COLOR_RESET} Run ${COLOR_BOLD}/claude-mem-feed${COLOR_RESET} to check feed status"
  1339. fi
  1340. echo ""
  1341. echo -e " ${COLOR_BOLD}To re-run this installer:${COLOR_RESET}"
  1342. echo " bash <(curl -fsSL https://install.cmem.ai/openclaw.sh)"
  1343. echo ""
  1344. }
  1345. main() {
  1346. setup_tty
  1347. print_banner
  1348. detect_platform
  1349. echo ""
  1350. info "${COLOR_BOLD}[1/8]${COLOR_RESET} Checking dependencies..."
  1351. echo ""
  1352. if ! check_bun; then
  1353. install_bun
  1354. fi
  1355. if ! check_uv; then
  1356. install_uv
  1357. fi
  1358. echo ""
  1359. success "All dependencies satisfied"
  1360. echo ""
  1361. info "${COLOR_BOLD}[2/8]${COLOR_RESET} Locating OpenClaw gateway..."
  1362. check_openclaw
  1363. echo ""
  1364. info "${COLOR_BOLD}[3/8]${COLOR_RESET} Installing claude-mem plugin..."
  1365. if [[ "$UPGRADE_MODE" == "true" ]] && is_claude_mem_installed; then
  1366. success "claude-mem already installed at ${CLAUDE_MEM_INSTALL_DIR}"
  1367. info "Upgrade mode: skipping clone/build/register, updating settings only"
  1368. else
  1369. install_plugin
  1370. fi
  1371. echo ""
  1372. info "${COLOR_BOLD}[4/8]${COLOR_RESET} Configuring memory slot..."
  1373. configure_memory_slot
  1374. allow_conversation_hooks
  1375. echo ""
  1376. info "${COLOR_BOLD}[5/8]${COLOR_RESET} AI provider setup..."
  1377. setup_ai_provider
  1378. echo ""
  1379. info "${COLOR_BOLD}[6/8]${COLOR_RESET} Writing settings..."
  1380. write_settings
  1381. echo ""
  1382. info "${COLOR_BOLD}[7/8]${COLOR_RESET} Starting worker service..."
  1383. if check_port_37777; then
  1384. warn "Port 37777 is already in use (worker may already be running)"
  1385. info "Checking if the existing service is healthy..."
  1386. if verify_health; then
  1387. local expected_version=""
  1388. if [[ -n "$CLAUDE_MEM_INSTALL_DIR" ]] || find_claude_mem_install_dir; then
  1389. expected_version="$(INSTALLER_PKG="${CLAUDE_MEM_INSTALL_DIR}/package.json" node -e "
  1390. try { process.stdout.write(JSON.parse(require('fs').readFileSync(process.env.INSTALLER_PKG, 'utf8')).version || ''); }
  1391. catch(e) {}
  1392. " 2>/dev/null)" || true
  1393. fi
  1394. local needs_restart=""
  1395. if [[ "$PLUGIN_FRESHLY_INSTALLED" == "true" ]]; then
  1396. if [[ -n "$WORKER_VERSION" && -n "$expected_version" && "$WORKER_VERSION" != "$expected_version" ]]; then
  1397. info "Upgrading worker from v${WORKER_VERSION} to v${expected_version}..."
  1398. else
  1399. info "Plugin files updated — restarting worker to load new code..."
  1400. fi
  1401. needs_restart="true"
  1402. fi
  1403. if [[ "$needs_restart" != "true" && -n "$WORKER_VERSION" && -n "$expected_version" && "$WORKER_VERSION" != "$expected_version" ]]; then
  1404. info "Upgrading worker from v${WORKER_VERSION} to v${expected_version}..."
  1405. needs_restart="true"
  1406. fi
  1407. if [[ "$needs_restart" != "true" && -n "$WORKER_AI_PROVIDER" && -n "$AI_PROVIDER" && "$WORKER_AI_PROVIDER" != "$AI_PROVIDER" ]]; then
  1408. warn "Worker is using ${WORKER_AI_PROVIDER} but you configured ${AI_PROVIDER} — restarting to apply"
  1409. needs_restart="true"
  1410. fi
  1411. if [[ "$needs_restart" == "true" ]]; then
  1412. info "Stopping existing worker..."
  1413. curl -s -X POST "http://127.0.0.1:37777/api/admin/shutdown" >/dev/null 2>&1 || true
  1414. sleep 2
  1415. if check_port_37777; then
  1416. if [[ -n "$WORKER_REPORTED_PID" ]]; then
  1417. kill "$WORKER_REPORTED_PID" 2>/dev/null || true
  1418. sleep 1
  1419. fi
  1420. local pid_file="${HOME}/.claude-mem/worker.pid"
  1421. if [[ -f "$pid_file" ]]; then
  1422. local file_pid
  1423. file_pid="$(INSTALLER_PID_FILE="$pid_file" node -e "
  1424. try { process.stdout.write(String(JSON.parse(require('fs').readFileSync(process.env.INSTALLER_PID_FILE, 'utf8')).pid || '')); }
  1425. catch(e) {}
  1426. " 2>/dev/null)" || true
  1427. if [[ -n "$file_pid" ]]; then
  1428. kill "$file_pid" 2>/dev/null || true
  1429. sleep 1
  1430. fi
  1431. fi
  1432. fi
  1433. if start_worker; then
  1434. verify_health || true
  1435. else
  1436. warn "Worker restart failed — you can start it manually later"
  1437. fi
  1438. else
  1439. local uptime_display=""
  1440. if [[ -n "$WORKER_UPTIME" && "$WORKER_UPTIME" =~ ^[0-9]+$ && "$WORKER_UPTIME" != "0" ]]; then
  1441. uptime_display="$(format_uptime_ms "$WORKER_UPTIME")"
  1442. fi
  1443. local status_parts=""
  1444. if [[ -n "$WORKER_VERSION" ]]; then
  1445. status_parts="v${WORKER_VERSION}"
  1446. fi
  1447. if [[ -n "$WORKER_AI_PROVIDER" ]]; then
  1448. status_parts="${status_parts:+${status_parts}, }${WORKER_AI_PROVIDER}"
  1449. fi
  1450. if [[ -n "$uptime_display" ]]; then
  1451. status_parts="${status_parts:+${status_parts}, }uptime: ${uptime_display}"
  1452. fi
  1453. if [[ -n "$status_parts" ]]; then
  1454. success "Existing worker is healthy (${status_parts}) — skipping startup"
  1455. else
  1456. success "Existing worker is healthy — skipping startup"
  1457. fi
  1458. fi
  1459. else
  1460. warn "Port 37777 is occupied but not responding to health checks"
  1461. warn "Another process may be using this port. Stop it and re-run the installer,"
  1462. warn "or change CLAUDE_MEM_WORKER_PORT in ~/.claude-mem/settings.json"
  1463. fi
  1464. else
  1465. if start_worker; then
  1466. verify_health || true
  1467. else
  1468. warn "Worker startup failed — you can start it manually later"
  1469. warn " cd ~/.openclaw/extensions/claude-mem && bun plugin/scripts/worker-service.cjs"
  1470. fi
  1471. fi
  1472. echo ""
  1473. info "${COLOR_BOLD}[8/8]${COLOR_RESET} Observation feed setup..."
  1474. setup_observation_feed
  1475. write_observation_feed_config
  1476. print_completion_summary
  1477. }
  1478. main "$@"

Ratings and comments

Sign in to rate this skill.

Sign in

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