Files
basicmachines-co-basic-memory/plugins/claude-code/hooks/pre-compact.sh
T
phernandez 3ff40d51fc feat(plugins): rebuild Claude Code plugin as the memory bridge (v0.4 Phase 1)
Reframes the Claude Code plugin as the bridge between Claude's working
memory and Basic Memory's durable graph, per plugins/claude-code/DESIGN.md.
This is the minimal-first vertical slice with a clean break from v0.3.x.

Added:
- hooks/session-start.sh — SessionStart brief: one structured `type: task`
  query against the configured (or default) project + always-on recall
  prompt. Plain stdout, silent if BM is absent.
- hooks/pre-compact.sh — PreCompact checkpoint: writes a `type: session`
  note before compaction (extractive). Only writes when primaryProject is
  set, so it never touches an un-opted-in graph.
- output-styles/basic-memory.md — capture reflexes (search-first, typed
  decision notes, cite permalinks); keep-coding-instructions: true.
- schemas/{session,decision,task}.md — picoschema seeds (validation: warn)
  so plugin-written notes are findable via metadata_filters. task mirrors
  the memory-tasks skill.
- settings.example.json — copyable config with sensible defaults.

Removed (clean break):
- the six bundled skills, the basic-memory-manager agent, the
  PreToolUse/PostToolUse write_note hooks, the basic-memory config-note
  convention, and PLUGIN.md. Equivalent workflows live in top-level skills/.

Other:
- Rewrote scripts/validate_claude_plugin.py for the new layout (hooks +
  output-style + schemas; agent dropped; skills optional). Passes
  `just package-check-claude-code` incl. `claude plugin validate --strict`.
- Rewrote README around the bridge story; updated CHANGELOG, marketplace
  descriptions, and the AGENTS.md package-check note.
- Hooks tested end-to-end against throwaway projects (brief surfaces tasks;
  checkpoint writes a queryable session note; both degrade silently).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: phernandez <paul@basicmachines.co>
2026-05-31 12:31:08 -05:00

198 lines
6.2 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# PreCompact hook — checkpoint the session to Basic Memory before compaction.
#
# This is the write side of the memory bridge: right before Claude Code compacts
# the context window (and the texture of the session is about to be lost), we
# write a durable SessionNote to the graph so the next session can resume from it.
#
# Phase 1 is the *extractive* cut (see DESIGN.md): we lift the opening request and
# the most recent turns straight from the transcript — no LLM call. Verified (Q2)
# that PreCompact has a ~600s budget, so a real LLM-summarized checkpoint is the
# planned "enrich later" upgrade; extractive is the safe, fast first version.
#
# Contract: advisory, never blocks compaction. Every failure path exits 0. We only
# write when a primaryProject is configured — we never write to a user's default
# graph unless they've explicitly pointed the plugin at a project.
set -u
input="$(cat 2>/dev/null || true)"
BM="$(command -v basic-memory || command -v bm || true)"
[ -z "$BM" ] && exit 0
BM_HOOK_INPUT="$input" BM_BIN="$BM" python3 <<'PY' 2>/dev/null || exit 0
import json
import os
import re
import subprocess
import sys
from datetime import datetime
bm = os.environ.get("BM_BIN", "basic-memory")
try:
payload = json.loads(os.environ.get("BM_HOOK_INPUT") or "{}")
except Exception:
payload = {}
cwd = payload.get("cwd") or os.getcwd()
transcript_path = payload.get("transcript_path") or ""
session_id = payload.get("session_id") or ""
def load_settings(directory):
merged = {}
for name in ("settings.json", "settings.local.json"):
path = os.path.join(directory, ".claude", name)
try:
with open(path) as fh:
merged.update(json.load(fh).get("basicMemory") or {})
except FileNotFoundError:
continue
except Exception:
continue
return merged
cfg = load_settings(cwd)
primary_project = (cfg.get("primaryProject") or "").strip()
capture_folder = (cfg.get("captureFolder") or "sessions").strip()
# Trigger: no project pinned for this Claude Code project.
# Why: a checkpoint must land somewhere intentional. Writing to the default graph
# on every compaction would pollute it without consent.
# Outcome: silent no-op until the user sets basicMemory.primaryProject.
if not primary_project:
sys.exit(0)
# --- Extract conversation text from the transcript (JSONL) ---
# The transcript is one JSON object per line. Schemas vary across Claude Code
# versions, so we probe a few shapes defensively rather than assume one.
def text_of(content):
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
t = block.get("text")
if isinstance(t, str):
parts.append(t)
return "\n".join(parts)
return ""
def turns(path):
collected = []
try:
with open(path) as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except Exception:
continue
msg = obj.get("message") if isinstance(obj.get("message"), dict) else obj
role = msg.get("role") or obj.get("type")
if role not in ("user", "assistant"):
continue
text = text_of(msg.get("content")).strip()
# Skip tool-result noise and empty frames.
if not text or text.startswith("<"):
continue
collected.append((role, text))
except Exception:
return []
return collected
conversation = turns(transcript_path)
# Trigger: nothing usable in the transcript.
# Why: an empty checkpoint is worse than none — it clutters the graph.
# Outcome: silent no-op.
if not conversation:
sys.exit(0)
user_msgs = [t for r, t in conversation if r == "user"]
opening = user_msgs[0] if user_msgs else ""
recent_user = user_msgs[-3:]
def clip(s, n):
s = " ".join(s.split())
return s if len(s) <= n else s[: n - 1].rstrip() + "…"
# --- Build a schema-conforming SessionNote ---
# Frontmatter carries type/status/started so structured recall (SessionStart) can
# find it with metadata filters. BM merges a leading frontmatter block from the
# content into the note's frontmatter (verified empirically).
now = datetime.now()
stamp = now.strftime("%Y-%m-%d-%H%M%S")
iso = now.strftime("%Y-%m-%dT%H:%M")
slug = re.sub(r"[^a-z0-9]+", "-", clip(opening, 50).lower()).strip("-") or "session"
title = f"Session {now.strftime('%Y-%m-%d %H:%M')} — {clip(opening, 40)}"
frontmatter = [
"---",
"type: session",
"status: open",
f"started: {iso}",
f"ended: {iso}",
f"project: {primary_project}",
f"cwd: {cwd}",
]
if session_id:
frontmatter.append(f"claude_session_id: {session_id}")
frontmatter += ["capture: extractive", "---"]
body = [
"",
f"# {title}",
"",
"_Automatic pre-compaction checkpoint (extractive). Full detail lives in the "
"session transcript; this note captures the thread so the next session can "
"resume._",
"",
"## Summary",
f"Working in `{cwd}`.",
f"- Opening request: {clip(opening, 300)}" if opening else "",
"",
"## Recent thread",
]
body += [f"- {clip(m, 200)}" for m in recent_user] or ["- (no recent user messages captured)"]
body += [
"",
"## Observations",
f"- [context] Session opened with: {clip(opening, 200)}" if opening else "- [context] Session checkpointed before compaction",
"- [next_step] Review this checkpoint and continue where the thread left off",
]
content = "\n".join(frontmatter + body)
# --- Write the checkpoint (best-effort) ---
try:
subprocess.run(
[
bm, "tool", "write-note",
"--title", title,
"--folder", capture_folder,
"--project", primary_project,
"--tags", "session",
"--tags", "auto-capture",
],
input=content,
capture_output=True,
text=True,
timeout=60,
)
except Exception:
sys.exit(0)
PY