From 581f06e8ad458e6e07ed6bf212085e0388e6ce35 Mon Sep 17 00:00:00 2001 From: Jason Docton Date: Tue, 3 Nov 2026 14:51:00 -0800 Subject: [PATCH] Register Claude response capture directly with Lucid Replace the Claude marketplace package with a native Stop hook. Preserve user opt-in and unrelated hooks across setup, upgrades, and removal. Refs #9 --- .claude-plugin/marketplace.json | 16 -- README.md | 18 +- install.ps1 | 9 + install.sh | 13 ++ .../.claude-plugin/plugin.json | 8 - .../claude-response-capture/capture.ts | 22 --- .../claude-response-capture/hooks/hooks.json | 23 --- packages/lucid-server/src/claude-hook.ts | 156 ++++++++++++++++++ packages/lucid-server/src/claude-stop.test.ts | 96 ++++++++++- packages/lucid-server/src/cli.ts | 13 ++ scripts/upgrade-v065-capture.sh | 10 +- uninstall.ps1 | 6 + uninstall.sh | 5 + 13 files changed, 308 insertions(+), 87 deletions(-) delete mode 100644 .claude-plugin/marketplace.json delete mode 100644 packages/lucid-server/claude-response-capture/.claude-plugin/plugin.json delete mode 100644 packages/lucid-server/claude-response-capture/capture.ts delete mode 100644 packages/lucid-server/claude-response-capture/hooks/hooks.json create mode 100644 packages/lucid-server/src/claude-hook.ts diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json deleted file mode 100644 index 706c6ab..0000000 --- a/.claude-plugin/marketplace.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "lucid-memory", - "owner": { - "name": "Lucid Memory" - }, - "plugins": [ - { - "name": "claude-response-capture", - "source": "./packages/lucid-server/claude-response-capture", - "description": "Capture assistant replies for an existing Lucid Memory installation." - } - ], - "metadata": { - "description": "Optional Claude Code integrations for Lucid Memory." - } -} diff --git a/README.md b/README.md index ca70cc4..9561a27 100644 --- a/README.md +++ b/README.md @@ -245,20 +245,20 @@ Restart Lucid after changing a serving model. When the endpoint reports a differ
Optional Claude Code assistant-response capture -**Existing v0.6.5 installations.** Close Lucid clients. From a full checkout of this repository, run `bash scripts/upgrade-v065-capture.sh` (on Windows, use Git Bash). This one-time migration verifies the five server source files it touches and preserves the database, profiles, dependencies and other hooks. It refuses locally edited sources. Use `--rollback` to restore the stock files after uninstalling the plugin. A fresh install from a revision containing this feature can skip the migration. - -The v0.6.5 migration installs response capture only. It keeps the v0.6.5 embedding cache code. Before a newer server upgrades a shared database for endpoint-specific vectors, stop and update **every** client that uses that database. A stock or capture-only v0.6.5 server can discard other models' cached vectors when it opens the upgraded database. Use separate databases if clients must run different versions during rollout. - -With an updated Lucid Memory installation, enable the first-party Claude Code plugin to save replies observed at a Claude Code Stop event. Start a new Claude session after installation. +If you select Claude Code during installation, the installer offers to capture assistant replies. You can also turn capture on or off afterward. Restart Claude Code after changing the setting. ```shell -claude plugin marketplace add JasonDocton/lucid-memory -claude plugin install claude-response-capture@lucid-memory +lucid config claude-responses on +lucid config claude-responses off ``` -The plugin saves up to 2,000 Unicode characters from each nonempty final reply in the active Claude database and project. Replies are tagged as assistant conversations and can be retrieved in later sessions. Lucid's configured embedding provider may process this text. Repeated delivery of the same reply for the same prompt is ignored. A Stop hook can ask Claude to continue, so a single user prompt can produce several replies. Capture requires a Stop payload with a session ID, prompt or turn ID, working directory, and final message. Use Claude Code 2.1.258 or later for the tested hook fields. Configless installations use the shared default. For named profiles, specify an absolute or home-relative database path. +Lucid registers a command under `hooks.Stop` in your Claude Code settings. Your other Stop handlers stay in place. Turning capture off preserves replies you have already saved. + +**Existing v0.6.5 installations.** Close Lucid clients and run `bash scripts/upgrade-v065-capture.sh` from a full checkout (Git Bash on Windows). It checks the five server source files, enables the direct hook, and preserves database and profile settings. Use `--rollback` to remove the hook and restore the stock files. If the server already has response capture but the CLI predates this setting, run `bun run --no-env-file --no-install ./packages/lucid-server/src/claude-hook.ts on` from the checkout instead. Use `off` to disable it. The setup migrates an enabled user-level `claude-response-capture@lucid-memory` installation to the direct hook. + +The v0.6.5 migration installs response capture only. It keeps the v0.6.5 embedding cache code. Before a newer server upgrades a shared database for endpoint-specific vectors, stop and update **every** client that uses that database. A stock or capture-only v0.6.5 server can discard other models' cached vectors when it opens the upgraded database. Use separate databases if clients must run different versions during rollout. -To turn off future capture, run `claude plugin uninstall claude-response-capture@lucid-memory` and start a new session. Previously stored replies stay in Lucid. Uninstall the plugin before removing Lucid itself. +Lucid saves up to 2,000 Unicode characters from each nonempty final reply in the active Claude database and project. Replies are tagged as assistant conversations and can be retrieved in later sessions. Lucid's configured embedding provider may process this text. Repeated delivery of the same reply for the same prompt is ignored. A Stop hook can ask Claude to continue, so a single user prompt can produce several replies. Capture requires a Stop payload with a session ID, prompt or turn ID, working directory, and final message. Use Claude Code 2.1.258 or later for the tested hook fields. Configless installations use the shared default. For named profiles, specify an absolute or home-relative database path.
diff --git a/install.ps1 b/install.ps1 index af7e181..d284bb9 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1084,6 +1084,15 @@ if ($InstallClaude) { } catch { Write-Warn "Could not configure Claude hook in settings.json - manual setup may be needed" } + + $CaptureMode = "keep" + $Choice = Read-Host "Save Claude's assistant replies in Lucid? [y/n, Enter keeps current setting; default off]" + if ($Choice -match '^[Yy]') { $CaptureMode = "on" } + if ($Choice -match '^[Nn]') { $CaptureMode = "off" } + & bun run --cwd "$LucidDir\server" --no-env-file --no-install "$LucidDir\server\src\claude-hook.ts" $CaptureMode + if ($LASTEXITCODE -ne 0) { Write-Warn "Could not configure assistant-response capture." } + Write-Host "Manage assistant-response capture with: lucid config claude-responses on|off" + } if ($InstallCodex) { diff --git a/install.sh b/install.sh index a004a1e..799d692 100755 --- a/install.sh +++ b/install.sh @@ -1583,6 +1583,19 @@ if [ "$INSTALL_CLAUDE" = true ]; then else warn "Claude hook configuration requires manual setup" fi + + capture_mode=keep + if [ "$INTERACTIVE" = true ]; then + read -r -p "Save Claude's assistant replies in Lucid? [y/n, Enter keeps current setting; default off]: " choice || choice= + case "$choice" in + [Yy]*) capture_mode=on ;; + [Nn]*) capture_mode=off ;; + esac + fi + if ! bun run --cwd "$LUCID_DIR/server" --no-env-file --no-install "$LUCID_DIR/server/src/claude-hook.ts" "$capture_mode"; then + warn "Could not configure assistant-response capture." + fi + echo "Manage assistant-response capture with: lucid config claude-responses on|off" fi # === Add to PATH === diff --git a/packages/lucid-server/claude-response-capture/.claude-plugin/plugin.json b/packages/lucid-server/claude-response-capture/.claude-plugin/plugin.json deleted file mode 100644 index 54ee615..0000000 --- a/packages/lucid-server/claude-response-capture/.claude-plugin/plugin.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "claude-response-capture", - "description": "Capture completed assistant replies in your Lucid Memory database.", - "version": "0.1.0", - "author": { - "name": "Lucid Memory" - } -} diff --git a/packages/lucid-server/claude-response-capture/capture.ts b/packages/lucid-server/claude-response-capture/capture.ts deleted file mode 100644 index 82c4347..0000000 --- a/packages/lucid-server/claude-response-capture/capture.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { homedir } from "node:os" -import { join } from "node:path" -import { pathToFileURL } from "node:url" - -const handler = join(homedir(), ".lucid", "server", "src", "claude-stop.ts") -const installed = Bun.file(join(homedir(), ".lucid", "server", "package.json")) -if ((await installed.exists()) && !(await Bun.file(handler).exists())) { - console.error( - "Lucid response capture requires an updated Lucid Memory installation." - ) - process.exitCode = 1 -} else if (await installed.exists()) { - try { - const { captureStop } = await import(pathToFileURL(handler).href) - await captureStop(await Bun.stdin.text()) - } catch { - console.error( - "Lucid could not store the response. Check the Claude profile and database." - ) - process.exitCode = 1 - } -} diff --git a/packages/lucid-server/claude-response-capture/hooks/hooks.json b/packages/lucid-server/claude-response-capture/hooks/hooks.json deleted file mode 100644 index 8014a4c..0000000 --- a/packages/lucid-server/claude-response-capture/hooks/hooks.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "hooks": { - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "bun", - "args": [ - "run", - "--cwd", - "${CLAUDE_PLUGIN_ROOT}", - "--no-env-file", - "--no-install", - "${CLAUDE_PLUGIN_ROOT}/capture.ts" - ], - "timeout": 10 - } - ] - } - ] - } -} diff --git a/packages/lucid-server/src/claude-hook.ts b/packages/lucid-server/src/claude-hook.ts new file mode 100644 index 0000000..85d157b --- /dev/null +++ b/packages/lucid-server/src/claude-hook.ts @@ -0,0 +1,156 @@ +// This file also runs from ~/.lucid/hooks on v0.6.5 installations. +import { randomUUID } from "node:crypto" +import { + link, + lstat, + mkdir, + readFile, + realpath, + rename, + rm, + stat, + writeFile, +} from "node:fs/promises" +import { homedir } from "node:os" +import { dirname, join } from "node:path" +import { pathToFileURL } from "node:url" + +const lucid = join(homedir(), ".lucid") +const installedHook = join(lucid, "hooks", "claude-stop.ts") +const handler = join(lucid, "server", "src", "claude-stop.ts") +const args = [ + "run", + "--cwd", + dirname(installedHook), + "--no-env-file", + "--no-install", + installedHook, +] +const byteOrderMark = /^\uFEFF/ +const oldPlugin = "claude-response-capture@lucid-memory" + +function object(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +async function readOptional(path: string) { + try { + return await readFile(path, "utf8") + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return undefined + } +} + +async function replaceFile( + path: string, + contents: string, + previous: string | undefined, + mode: number +) { + const temporary = `${path}.${randomUUID()}.tmp` + await mkdir(dirname(path), { recursive: true }) + try { + await writeFile(temporary, contents, { flag: "wx", mode }) + if ((await readOptional(path)) !== previous) + throw new Error(`File changed during update: ${path}`) + if (previous === undefined) await link(temporary, path) + else await rename(temporary, path) + } finally { + await rm(temporary, { force: true }) + } +} + +export async function configureClaudeHook(action: "on" | "off" | "keep") { + const location = join( + // biome-ignore lint/style/noProcessEnv: Claude honors a custom configuration directory. + process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), + "settings.json" + ) + const entry = await lstat(location).catch((error: NodeJS.ErrnoException) => { + if (error.code !== "ENOENT") throw error + return undefined + }) + const path = entry ? await realpath(location) : location + const previous = await readOptional(path) + const config: unknown = + previous === undefined + ? {} + : JSON.parse(previous.replace(byteOrderMark, "")) + if (!object(config)) throw new Error("Invalid Claude settings") + const original = JSON.stringify(config) + const hooks = config.hooks === undefined ? {} : config.hooks + if (!object(hooks)) throw new Error("Invalid Claude hooks") + const groups = hooks.Stop === undefined ? [] : hooks.Stop + if (!Array.isArray(groups)) throw new Error("Invalid Claude Stop hooks") + + const plugins = config.enabledPlugins + const priorOptIn = object(plugins) && plugins[oldPlugin] === true + let found = false + const updated = groups.flatMap((group: unknown) => { + if (!object(group) || !Array.isArray(group.hooks)) + throw new Error("Invalid Claude Stop handler group") + const remaining = group.hooks.filter((hook: unknown) => { + if ( + !object(hook) || + hook.type !== "command" || + hook.command !== "bun" || + JSON.stringify(hook.args) !== JSON.stringify(args) + ) + return true + const retain = action !== "off" && !found + found = true + return retain + }) + if (remaining.length === group.hooks.length) return [group] + return remaining.length ? [{ ...group, hooks: remaining }] : [] + }) + const enable = action === "on" || (action === "keep" && (priorOptIn || found)) + if (enable) { + if (!(await Bun.file(handler).exists())) + throw new Error( + "Update the Lucid server before enabling response capture" + ) + const source = await readFile(import.meta.path, "utf8") + const existing = await readOptional(installedHook) + if (source !== existing) + await replaceFile(installedHook, source, existing, 0o600) + if (!found) + updated.push({ + hooks: [{ type: "command", command: "bun", args, timeout: 10 }], + }) + } + if (JSON.stringify(updated) !== JSON.stringify(groups)) { + config.hooks = hooks + if (updated.length) hooks.Stop = updated + else delete hooks.Stop + } + if (object(plugins) && priorOptIn) plugins[oldPlugin] = false + if (JSON.stringify(config) === original) return + await replaceFile( + path, + `${JSON.stringify(config, null, 2)}\n`, + previous, + entry ? (await stat(path)).mode & 0o777 : 0o600 + ) +} + +if (import.meta.main) { + const action = process.argv[2] + try { + if (action === "on" || action === "off" || action === "keep") + await configureClaudeHook(action) + else if (action !== undefined) throw new Error("Expected on, off, or keep") + else if (await Bun.file(join(lucid, "server", "package.json")).exists()) { + const { captureStop } = await import(pathToFileURL(handler).href) + await captureStop(await Bun.stdin.text()) + } + } catch (error) { + console.error( + action + ? `Lucid could not update Claude's Stop hook: ${error instanceof Error ? error.message : String(error)}` + : "Lucid could not store the response. Check the Claude profile and database." + ) + process.exitCode = 1 + } +} diff --git a/packages/lucid-server/src/claude-stop.test.ts b/packages/lucid-server/src/claude-stop.test.ts index 3b1ff8d..1ee3ca1 100644 --- a/packages/lucid-server/src/claude-stop.test.ts +++ b/packages/lucid-server/src/claude-stop.test.ts @@ -4,6 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, + readFileSync, rmSync, symlinkSync, writeFileSync, @@ -13,12 +14,8 @@ import { join, resolve } from "node:path" import { LucidStorage } from "./storage.ts" const server = resolve(import.meta.dir, "..") -const plugin = join(server, "claude-response-capture") -const manifest = await Bun.file(join(plugin, "hooks", "hooks.json")).json() -const handler = manifest.hooks.Stop[0].hooks[0] -const args = handler.args.map((arg: string) => - arg.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, plugin) -) +const setup = join(server, "src", "claude-hook.ts") +let handler: { command: string; args: string[] } let home: string let dir: string let project: string @@ -35,7 +32,7 @@ function configure(config: unknown) { writeFileSync(join(dir, "config.json"), JSON.stringify(config)) } async function run(input: string) { - const child = Bun.spawn([process.execPath, ...args], { + const child = Bun.spawn([process.execPath, ...handler.args], { cwd: project, env: { HOME: home, USERPROFILE: home, LUCID_CLIENT: "codex" }, stdin: new Blob([input]), @@ -49,6 +46,29 @@ async function run(input: string) { ]) return { exit, stdout, stderr } } +function configureHook(mode: "on" | "off" | "keep") { + return Bun.spawnSync( + [ + process.execPath, + "run", + "--cwd", + server, + "--no-env-file", + "--no-install", + setup, + mode, + ], + { + env: { HOME: home, USERPROFILE: home }, + cwd: project, + } + ) +} +function readSettings() { + return JSON.parse( + readFileSync(join(home, ".claude", "settings.json"), "utf8") + ) +} beforeEach(() => { home = mkdtempSync(join(tmpdir(), "lucid-claude-")) dir = join(home, ".lucid") @@ -57,6 +77,8 @@ beforeEach(() => { mkdirSync(project) symlinkSync(server, join(dir, "server"), "junction") configure({ databaseMode: "per-client" }) + expect(configureHook("on").exitCode).toBe(0) + handler = readSettings().hooks.Stop[0].hooks[0] }) afterEach(() => { rmSync(home, { recursive: true, force: true }) @@ -196,7 +218,7 @@ test("disabled or broken configuration never falls back to the shared database", expect(existsSync(join(dir, "memory.db"))).toBe(false) }) -test("the manifest does not load project preloads before reading private Stop input", async () => { +test("the registered hook does not load project preloads before reading private Stop input", async () => { expect(handler.command).toBe("bun") writeFileSync(join(project, "bunfig.toml"), 'preload = ["./preload.ts"]') // Record any execution, even if the hook exits before trying to store. @@ -273,3 +295,61 @@ test("a dangling config symlink cannot redirect a private reply into the shared expect(result.exit).toBe(1) expect(existsSync(join(dir, "memory.db"))).toBe(false) }) + +test("enable, reinstall and disable preserve unrelated handlers and settings", () => { + const settingsPath = join(home, ".claude", "settings.json") + const sibling = { type: "command", command: "/team/stop.sh" } + const other = { type: "prompt", prompt: "Review the results" } + const fromUser = { + theme: "dark", + hooks: { + Stop: [{ matcher: "", hooks: [sibling, handler, other] }], + SessionStart: [{ hooks: [sibling] }], + }, + } + writeFileSync(settingsPath, JSON.stringify(fromUser)) + expect(configureHook("keep").exitCode).toBe(0) + expect(configureHook("on").exitCode).toBe(0) + expect(readFileSync(settingsPath, "utf8")).toBe(JSON.stringify(fromUser)) + expect(configureHook("off").exitCode).toBe(0) + expect(readSettings()).toEqual({ + ...fromUser, + hooks: { + ...fromUser.hooks, + Stop: [{ matcher: "", hooks: [sibling, other] }], + }, + }) +}) + +test("migrates the former opt-in exactly once; malformed settings remain untouched", () => { + const path = join(home, ".claude", "settings.json") + const other = { type: "command", command: "/other/stop.sh" } + writeFileSync( + path, + JSON.stringify({ + enabledPlugins: { + "claude-response-capture@lucid-memory": true, + "other@team": true, + }, + hooks: { Stop: [{ hooks: [other] }] }, + }) + ) + expect(configureHook("keep").exitCode).toBe(0) + expect(configureHook("keep").exitCode).toBe(0) + expect(readSettings()).toEqual({ + enabledPlugins: { + "claude-response-capture@lucid-memory": false, + "other@team": true, + }, + hooks: { Stop: [{ hooks: [other] }, { hooks: [handler] }] }, + }) + writeFileSync(path, "{bad") + expect(configureHook("on").exitCode).toBe(1) + expect(readFileSync(path, "utf8")).toBe("{bad") +}) + +test("a normal noninteractive install preserves the opt-out", () => { + rmSync(join(home, ".claude", "settings.json")) + expect(configureHook("keep").exitCode).toBe(0) + expect(existsSync(join(home, ".claude", "settings.json"))).toBe(false) +}) diff --git a/packages/lucid-server/src/cli.ts b/packages/lucid-server/src/cli.ts index 855381f..bd829d8 100644 --- a/packages/lucid-server/src/cli.ts +++ b/packages/lucid-server/src/cli.ts @@ -57,6 +57,17 @@ async function saveConfig(config: LucidConfig): Promise { } async function main() { + if (command === "config" && args[1] === "claude-responses") { + const mode = args[2] + if (mode !== "on" && mode !== "off") + throw new Error("Usage: lucid config claude-responses on|off") + const { configureClaudeHook } = await import("./claude-hook.ts") + await configureClaudeHook(mode) + console.log( + `Claude response capture is ${mode}. Start a new Claude Code session.` + ) + return + } // Load config and resolve database path const config = await loadConfig() const dbPath = resolveDbPath(config, LUCID_CLIENT) @@ -228,6 +239,7 @@ async function main() { console.log(` Lucid Config Commands + lucid config claude-responses on|off Configure assistant-response capture lucid config show Show current configuration lucid config set-mode Set database mode (shared|per-client|profiles) lucid config set-profile Set profile for a client @@ -823,6 +835,7 @@ Commands: --type=TYPE Type: learning, decision, context, bug, solution --project=/path Associate with project + config claude-responses on|off Configure Claude assistant-response capture config show Show current configuration config set-mode Set database mode (shared|per-client|profiles) config set-profile Set profile for a client diff --git a/scripts/upgrade-v065-capture.sh b/scripts/upgrade-v065-capture.sh index 0a3ab61..2f056dc 100755 --- a/scripts/upgrade-v065-capture.sh +++ b/scripts/upgrade-v065-capture.sh @@ -56,7 +56,13 @@ for name in "${files[@]}"; do matches "$before" "$installed" || all_from=false matches "$after" "$installed" || all_to=false done -if [[ "$all_to" == true ]]; then echo "The requested sources are already installed."; exit 0; fi +configure_capture() { + bun run --cwd "$repo" --no-env-file --no-install "$repo/packages/lucid-server/src/claude-hook.ts" "$1" +} +if [[ "$all_to" == true ]]; then + if [[ ${1:-} == --rollback ]]; then configure_capture off; else configure_capture on; fi + echo "The requested sources are already installed."; exit 0 +fi [[ "$all_from" == true ]] || { echo "Installed sources differ from the expected revision. No files changed." >&2; exit 1; } # Generate one patch with the verified byte sequences. Git checks every hunk before applying. cd "$stage" @@ -64,5 +70,7 @@ rc=0 git -c core.autocrlf=false diff --no-index --no-ext-diff --no-color --src-prefix=a/ --dst-prefix=b/ before after > changes.patch || rc=$? [[ $rc == 1 ]] || { echo "Could not prepare the source update." >&2; exit 1; } git -C "$server" -c core.autocrlf=false apply -p2 --whitespace=nowarn --check "$stage/changes.patch" +if [[ ${1:-} == --rollback ]]; then configure_capture off; fi git -C "$server" -c core.autocrlf=false apply -p2 --whitespace=nowarn "$stage/changes.patch" +if [[ ${1:-} != --rollback ]]; then configure_capture on; fi echo "Lucid server sources updated. Start a new session to load them." diff --git a/uninstall.ps1 b/uninstall.ps1 index bd6fd58..05e5a6e 100644 --- a/uninstall.ps1 +++ b/uninstall.ps1 @@ -125,6 +125,12 @@ if ($Confirm -notmatch "^[Yy]$") { } Write-Host "" +$StopHandler = Join-Path $LucidDir 'hooks\claude-stop.ts' +if (Test-Path $StopHandler) { + & bun run --cwd "$LucidDir\hooks" --no-env-file --no-install $StopHandler off + if ($LASTEXITCODE -ne 0) { throw "Could not remove the Lucid Stop hook. Uninstall stopped." } +} + # === Remove MCP Config === if (Test-Path $McpConfig) { diff --git a/uninstall.sh b/uninstall.sh index cbc2b06..4c8b415 100755 --- a/uninstall.sh +++ b/uninstall.sh @@ -132,6 +132,11 @@ else echo "" fi +# Remove the direct Stop handler before deleting its executable. +if [ -f "$LUCID_DIR/hooks/claude-stop.ts" ]; then + bun run --cwd "$LUCID_DIR/hooks" --no-env-file --no-install "$LUCID_DIR/hooks/claude-stop.ts" off || exit 1 +fi + # === Remove MCP Config === if [ -f "$MCP_CONFIG" ]; then