mempalace/hooks
undeadindustries b06cf2452e fix(antigravity): address gemini-code-assist review on PR #1633
Five fixes for issues called out by the gemini-code-assist[bot] review.
Each gets a regression test that locks in the correction.

1. CRITICAL: marker-cleanup watcher used POSIX `wait` on a sibling pid
   (save hook). bash `wait` only works on direct children of the
   calling shell — the `( wait $MINE_PID ... ) &` subshell runs as a
   sibling of MINE_PID, so wait fails immediately and the pending
   marker is deleted within milliseconds, defeating the concurrency
   guard. Replace with `while kill -0 $MINE_PID; do sleep 1; done`,
   which queries pid existence regardless of parent-child relationship.
   Test: test_save_hook_marker_watcher_uses_kill_polling.

2. Bare `mempalace` console-script invocation in the save hook fails
   when the venv's bin/ is not on the hook's PATH (e.g. uv tool
   install in some configurations, manually managed virtualenvs).
   Switch to `"$MEMPAL_PYTHON_BIN" -m mempalace mine ...` so the
   resolved interpreter runs the package directly via
   mempalace/__main__.py. Tests:
   test_save_hook_uses_python_module_invocation,
   test_save_hook_missing_mempalace_python_module_does_not_crash.

3. Same issue in the wake hook's inner Python helper. Switch
   `['mempalace', 'wake-up', ...]` to `[sys.executable, '-m',
   'mempalace', 'wake-up', ...]` — sys.executable is the same
   interpreter that resolved MEMPAL_PYTHON in lib/common.sh.
   Test: test_wake_hook_uses_sys_executable_module_invocation.

4. The Python parser in lib/common.sh wrapped `json.load` in
   `try/except` and silently fell back to `data = {}`. The script
   then printed the `__MEMPAL_PARSE_OK__` sentinel even on parse
   failure, so the bash sentinel-check on the caller side
   (`[ "$_marker" != "__MEMPAL_PARSE_OK__" ]`) never triggered the
   defense-in-depth `input parse failed` branch. Remove the
   try/except so the exception propagates, Python exits non-zero,
   and the sentinel is omitted on bad JSON. The traceback still
   lands in antigravity_last_python_err.log for debugging.
   Test: test_common_sh_parser_omits_sentinel_on_malformed_json.

5. `mempal_save_interval()` failed to strip leading zeros from
   MEMPAL_SAVE_INTERVAL. Values like "08" or "09" then crashed the
   modulo step `$((COUNT % INTERVAL))` because bash arithmetic
   parses tokens starting with `0` as octal, and 8/9 are not valid
   octal digits ("value too great for base"). Strip leading zeros
   while preserving the literal "0" (which is then floored to 15).
   Test: test_save_hook_handles_leading_zero_save_interval (4 cases).

Plus one cosmetic fix in install.sh: removed a no-op `(cd "$OLDPWD"
2>/dev/null || cd .) >/dev/null 2>&1` line in mempal_absolutize().
The subshell cd doesn't affect the parent shell, and the installer
never cd's in the main shell anyway, so $PWD is already correct.

Verification:
* 9 new regression tests, all 65 antigravity tests pass
* full repo: 2323 passed (was 2314), 3 skipped, 1 unrelated warning
* ruff check + ruff format --check both clean across 139 files
* bash -n clean on all four shell files
* clean reinstall to ~/.gemini/config/plugins/mempalace/ succeeds
* idempotent re-run produces zero file writes (cmp-gated)
* both hooks return {} exit 0 with synthetic camelCase stdin

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-27 19:49:19 +10:00
..
antigravity fix(antigravity): address gemini-code-assist review on PR #1633 2026-05-27 19:49:19 +10:00
README.md feat: add Antigravity IDE support (plugin, MCP, skill, hooks, docs, tests) 2026-05-27 19:19:17 +10:00
mempal_precompact_hook.sh fix: address review — enrich block reasons, clean up tests 2026-05-23 12:05:34 -04:00
mempal_save_hook.sh fix: address review — enrich block reasons, clean up tests 2026-05-23 12:05:34 -04:00

README.md

MemPalace Hooks — Auto-Save for Terminal AI Tools

These hook scripts make MemPalace save automatically. No manual "save" commands needed.

If you are trying to protect existing Claude Code transcripts immediately, use the short checklist first: website/guide/claude-code-retention.md. It covers hook wiring, JSONL backup, and one-time backfill.

What They Do

Hook When It Fires What Happens
Save Hook Every 15 human messages Auto-mines transcript (tool output included), then blocks the AI to save topics/decisions/quotes
PreCompact Hook Right before context compaction Auto-mines transcript, then emergency save — forces the AI to save EVERYTHING before losing context

Two-layer capture: Hooks auto-mine the JSONL transcript directly into the palace (capturing raw tool output — Bash results, search findings, build errors). They also block the AI with a reason message telling it to save verbatim tool output and key context. Belt and suspenders — tool output gets stored even if the AI summarizes instead of quoting.

Install — Claude Code

Add to .claude/settings.local.json:

{
  "hooks": {
    "Stop": [{
      "matcher": "*",
      "hooks": [{
        "type": "command",
        "command": "/absolute/path/to/hooks/mempal_save_hook.sh",
        "timeout": 30
      }]
    }],
    "PreCompact": [{
      "hooks": [{
        "type": "command",
        "command": "/absolute/path/to/hooks/mempal_precompact_hook.sh",
        "timeout": 30
      }]
    }]
  }
}

Make them executable:

chmod +x hooks/mempal_save_hook.sh hooks/mempal_precompact_hook.sh

Install — Antigravity (Google)

The Antigravity integration lives in its own subdirectory because the wire format (camelCase JSON, injectSteps[] output) and event names (Stop, PreInvocation) are Antigravity-specific. Use the dedicated installer:

bash hooks/antigravity/install.sh

This installs to ~/.gemini/config/plugins/mempalace/, registers the MCP server, ships the mempalace skill, and wires the Stop + PreInvocation hooks. See hooks/antigravity/README.md for the full guide and hooks/antigravity/INVESTIGATION.md for the source-of-truth audit of which Antigravity surfaces the integration uses.

Install — Codex CLI (OpenAI)

Add to .codex/hooks.json:

{
  "Stop": [{
    "type": "command",
    "command": "/absolute/path/to/hooks/mempal_save_hook.sh",
    "timeout": 30
  }],
  "PreCompact": [{
    "type": "command",
    "command": "/absolute/path/to/hooks/mempal_precompact_hook.sh",
    "timeout": 30
  }]
}

Configuration

Edit mempal_save_hook.sh to change:

  • SAVE_INTERVAL=15 — How many human messages between saves. Lower = more frequent saves, higher = less interruption.
  • STATE_DIR — Where hook state is stored (defaults to ~/.mempalace/hook_state/)
  • MEMPAL_DIR — Optional project directory (code, notes, docs) to also mine on each save trigger, with --mode projects. The hook ALWAYS mines the active conversation transcript automatically with --mode convosMEMPAL_DIR is purely additive, never an override. Leave blank if you don't want to ingest project files.
  • MEMPALACE_PYTHON — Optional env var. Python interpreter with mempalace + chromadb installed. Auto-detects: MEMPALACE_PYTHON env var → repo venv/bin/python3 → system python3. Set this if your venv is in a non-standard location.

Disabling Auto-Save (Silent Mode)

To keep hooks installed but disable auto-save blocking entirely, set hooks.auto_save to false in your config:

Option 1 — config file (~/.mempalace/config.json):

{
  "hooks": {
    "auto_save": false
  }
}

Option 2 — environment variable:

export MEMPALACE_HOOKS_AUTO_SAVE=false

When disabled, both the stop hook and precompact hook pass through without blocking. You can still save manually with mempalace mine <dir> --mode convos.

mempalace CLI

The relevant commands are:

mempalace mine <dir>               # Mine all files in a directory
mempalace mine <dir> --mode convos # Mine conversation transcripts only

The hooks resolve the repo root automatically from their own path, so they work regardless of where you install the repo.

How It Works (Technical)

Save Hook (Stop event)

User sends message → AI responds → Claude Code fires Stop hook
                                            ↓
                                    Hook counts human messages in JSONL transcript
                                            ↓
                              ┌─── < 15 since last save ──→ echo "{}" (let AI stop)
                              │
                              └─── ≥ 15 since last save
                                            ↓
                                    Auto-mine transcript → palace (tool output captured)
                                            ↓
                                    {"decision": "block", "reason": "save tool output verbatim..."}
                                            ↓
                                    AI saves to palace (topics, decisions, quotes)
                                            ↓
                                    AI tries to stop again
                                            ↓
                                    stop_hook_active = true
                                            ↓
                                    Hook sees flag → echo "{}" (let it through)

The stop_hook_active flag prevents infinite loops: block once → AI saves → tries to stop → flag is true → we let it through.

PreCompact Hook

Context window getting full → Claude Code fires PreCompact
                                        ↓
                                Find transcript (from input or session_id lookup)
                                        ↓
                                Auto-mine transcript → palace (tool output captured)
                                        ↓
                                {"decision": "block", "reason": "save tool output verbatim..."}
                                        ↓
                                AI saves everything
                                        ↓
                                Compaction proceeds

No counting needed — compaction always warrants a save. The auto-mine captures raw tool output before the AI gets a chance to summarize it away.

Debugging

Check the hook log:

cat ~/.mempalace/hook_state/hook.log

Example output:

[14:30:15] Session abc123: 12 exchanges, 12 since last save
[14:35:22] Session abc123: 15 exchanges, 15 since last save
[14:35:22] TRIGGERING SAVE at exchange 15
[14:40:01] Session abc123: 18 exchanges, 3 since last save

Known Limitations

Hooks require session restart after install. Claude Code loads hooks from settings.json at session start only. If you run mempalace init or manually edit hook config mid-session, the hooks won't fire until you restart Claude Code. This is a Claude Code limitation.

MEMPAL_PYTHON override for the hook's internal Python calls. The save hook parses its JSON input and counts transcript messages with python3. When the harness is launched from a GUI on macOS — open -a, Spotlight, the dock — its PATH is the minimal /usr/bin:/bin:/usr/sbin:/sbin inherited from launchd, not your shell PATH. If python3 isn't on that PATH, those internal calls fail and the hook can't count exchanges.

Point the hook at any Python 3 interpreter to fix it:

export MEMPAL_PYTHON="/usr/bin/python3"                   # system Python is fine
export MEMPAL_PYTHON="$HOME/.venvs/mempalace/bin/python"  # or your venv

Resolution priority: $MEMPAL_PYTHON (if set and executable) → $(command -v python3) → bare python3. The interpreter only needs json and sys from the standard library — mempalace itself does not need to be installed in it.

Note: the mempalace mine auto-ingest runs via the mempalace CLI, so that command also needs to be on the hook's PATH. Installing with pipx install mempalace or uv tool install mempalace puts it on a stable global location; otherwise extend the hook environment's PATH to include your venv's bin/.

Backfill Past Conversations

The hooks only capture conversations going forward. To mine past Claude Code sessions into your palace, run a one-time backfill:

mempalace mine ~/.claude/projects/ --mode convos

This scans all JSONL transcripts from previous sessions and files them into the conversations wing. On a typical developer machine with months of history, this can yield 50K200K drawers.

For Codex CLI sessions:

mempalace mine ~/.codex/sessions/ --mode convos

This only needs to be done once — after that, the hooks auto-mine each session as you go.

Cost

Zero extra tokens. The hooks notify the AI that saves happened in the background — the AI doesn't need to write anything in the chat. All filing is handled automatically. Previous versions asked the AI to write diary entries and drawer content in the chat window, which cost ~$1/session in retransmitted tokens.