Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,10 @@ Two options are worth knowing early:
It does not block or edit the session; without a key it does nothing, and failed judge calls
go to `.magnolia/claim-critic/errors.jsonl`.
See the [hook guide](docs/harness-adaptation.md#what-the-opencode-plugins-actually-do) before enabling it.
- `magnolia memory status` reports which models are in force, and `magnolia doctor [project]` runs a
quick health check across Python, OpenCode, memory config and the `compchem-tools` daemon.
- `magnolia memory status` reports which models are in force, `magnolia doctor [project]` runs a
quick health check across Python, OpenCode, memory config, live MCP status and the
`compchem-tools` daemon, and `magnolia service restart` restarts the OpenCode v2 background
service while keeping Magnolia's `OPENCODE_DB` intact.

Commands run through `magnolia-run <command…>` are recorded in the session log, so shell-driven work
is captured alongside tool calls.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1350,7 +1350,39 @@ def get_runs_index() -> str:
return json.dumps(proj_m.get_run_history(pd), indent=2)


def _patch_mcp_cancelled_respond() -> bool:
"""Work around mcp 1.x bug where RequestResponder.respond() asserts
``not self._completed`` before checking ``if not self.cancelled:``.

When a client cancels an in-flight synchronous tool call, ``cancel()`` sets
``_completed = True`` and sends the cancellation error; when the sync
handler later returns, ``respond()`` raises ``AssertionError: Request
already responded to``, escaping the anyio TaskGroup and crashing the MCP
server process. Safe no-op on mcp >= 2.0 where ``mcp.shared.session`` is
absent.
"""
try:
from mcp.shared.session import RequestResponder
except Exception:
return False
orig = getattr(RequestResponder, "respond", None)
if orig is None:
return False
if getattr(orig, "_magnolia_cancel_safe", False):
return True

async def _safe_respond(self, response):
if getattr(self, "cancelled", False) and getattr(self, "_completed", False):
return None
return await orig(self, response)

_safe_respond._magnolia_cancel_safe = True # type: ignore[attr-defined]
RequestResponder.respond = _safe_respond # type: ignore[method-assign]
return True


if __name__ == "__main__":
_patch_mcp_cancelled_respond()
# A native crash (sqlite/ssl/…) must leave a stack trace, not just a closed
# MCP pipe. Keep the handle alive for the lifetime of the process.
_crash_file = None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Regression tests for the mcp 1.x cancelled-request respond() guard."""

from __future__ import annotations

import asyncio
from unittest.mock import AsyncMock

import pytest


def test_patch_mcp_cancelled_respond_suppresses_assertion_after_cancel():
from compchem_memory.server import _patch_mcp_cancelled_respond

try:
from mcp.shared.session import RequestResponder
except ImportError:
pytest.skip("mcp.shared.session not present (mcp >= 2.x)")

assert _patch_mcp_cancelled_respond() is True
# Idempotent on repeated calls.
assert _patch_mcp_cancelled_respond() is True

session = AsyncMock()
session._send_response = AsyncMock()
on_complete = lambda _r: None

async def _run():
responder = RequestResponder(
request_id=5,
request_meta=None,
request="dummy",
session=session,
on_complete=on_complete,
)
with responder:
await responder.cancel()
assert responder.cancelled is True
assert responder._completed is True
# Without the guard, mcp 1.26.0 raises AssertionError here and
# kills the server's anyio TaskGroup.
await responder.respond({"ok": True})

# Only the cancellation response should have been sent.
assert session._send_response.await_count == 1

asyncio.run(_run())


def test_patch_mcp_cancelled_respond_still_rejects_duplicate_uncancelled():
from compchem_memory.server import _patch_mcp_cancelled_respond

try:
from mcp.shared.session import RequestResponder
except ImportError:
pytest.skip("mcp.shared.session not present (mcp >= 2.x)")

assert _patch_mcp_cancelled_respond() is True

session = AsyncMock()
session._send_response = AsyncMock()

async def _run():
responder = RequestResponder(
request_id=6,
request_meta=None,
request="dummy",
session=session,
on_complete=lambda _r: None,
)
with responder:
await responder.respond({"first": True})
with pytest.raises(AssertionError, match="Request already responded to"):
await responder.respond({"second": True})

asyncio.run(_run())
133 changes: 132 additions & 1 deletion opencode_cc_mem/softwares/bin/magnolia
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ usage() {
cat <<EOF
Usage: magnolia [--profile NAME] [setup] [--critic] <project>
magnolia doctor [project]
magnolia service [status|restart|start|stop]
magnolia memory set <model> [--provider P]
magnolia memory status

Expand Down Expand Up @@ -670,6 +671,97 @@ _key_var_for_model() {
esac
}

# Resolve the OpenCode v2 binary path (prints path on stdout, returns 1 if missing/v1).
_find_opencode_v2_bin() {
local cand="" ver=""
if [ -n "${MAGNOLIA_OPENCODE_V2_BIN:-}" ]; then
[ -x "$MAGNOLIA_OPENCODE_V2_BIN" ] || return 1
printf '%s' "$MAGNOLIA_OPENCODE_V2_BIN"
return 0
elif [ -x "$HOME/.local/share/magnolia-v2/bin/opencode" ]; then
printf '%s' "$HOME/.local/share/magnolia-v2/bin/opencode"
return 0
elif command -v opencode >/dev/null 2>&1; then
cand="$(command -v opencode)"
ver="$("$cand" --version 2>/dev/null | head -1 || true)"
case "$ver" in
*2.*|2.*) printf '%s' "$cand"; return 0 ;;
esac
fi
return 1
}

# Persist OPENCODE_DB in OpenCode v2's service config when unset so even a bare
# `opencode service restart` or reboot stays on Magnolia's isolated v2 database.
_ensure_v2_service_db() {
local oc_bin="$1" db_path="$2"
[ -n "$oc_bin" ] && [ -x "$oc_bin" ] && [ -n "$db_path" ] || return 0
local cur=""
cur="$("$oc_bin" service get env OPENCODE_DB 2>/dev/null | tr -d '\r\n' || true)"
if [ -z "$cur" ]; then
"$oc_bin" service set env OPENCODE_DB "$db_path" >/dev/null 2>&1 || true
fi
}

# Inspect a running `opencode serve --service` process on Linux and print
# `<pid><TAB><opencode_db_or_empty>` when its OPENCODE_DB differs from expected.
_find_service_db_mismatch() {
local expected_db="$1"
[ -n "$expected_db" ] && [ -d /proc ] || return 1
command -v pgrep >/dev/null 2>&1 || return 1
local uid pid actual
uid="$(id -u)"
while IFS= read -r pid; do
[ -n "$pid" ] && [ -r "/proc/$pid/environ" ] || continue
actual="$(tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null | sed -n 's/^OPENCODE_DB=//p' | head -1 || true)"
if [ "$actual" != "$expected_db" ]; then
printf '%s\t%s\n' "$pid" "$actual"
return 0
fi
done < <(pgrep -u "$uid" -f "opencode serve --service" 2>/dev/null || true)
return 1
}

# Manage the OpenCode v2 background service with Magnolia's OPENCODE_DB and env.
cmd_service() {
local action="${1:-status}"
case "$action" in
status|restart|start|stop) ;;
-h|--help)
echo "Usage: magnolia service [status|restart|start|stop]"
echo "Manage the OpenCode v2 background daemon with Magnolia's OPENCODE_DB."
return 0
;;
*)
echo "error: unknown service action '$action' (expected status|restart|start|stop)" >&2
return 1
;;
esac
if [ "${MAGNOLIA_OPENCODE_V2:-1}" != "1" ]; then
echo "error: 'magnolia service' requires OpenCode v2 (MAGNOLIA_OPENCODE_V2=1)." >&2
return 1
fi
local oc_bin=""
if ! oc_bin="$(_find_opencode_v2_bin)"; then
echo "error: opencode v2 binary not found (install opencode or set MAGNOLIA_OPENCODE_V2_BIN)" >&2
return 1
fi
if [ -z "${OPENCODE_DB:-}" ]; then
OPENCODE_DB="$HOME/.local/share/opencode/opencode-v2.db"
mkdir -p "$(dirname "$OPENCODE_DB")"
export OPENCODE_DB
fi
if [ "$action" = "start" ] || [ "$action" = "restart" ]; then
_ensure_v2_service_db "$oc_bin" "$OPENCODE_DB"
fi
OPENCODE_DB="$OPENCODE_DB" "$oc_bin" service "$action"
local rc=$?
if [ "$rc" -eq 0 ] && { [ "$action" = "start" ] || [ "$action" = "restart" ]; }; then
echo "OpenCode v2 service (${action}) ready with OPENCODE_DB=$OPENCODE_DB"
fi
return "$rc"
}

cmd_doctor() {
local proj="${1:-}"
local fails=0 warns=0
Expand Down Expand Up @@ -820,6 +912,30 @@ PY
else
_info "compchem-tools daemon is stopped on port $port (starts automatically when you run: magnolia $proj)"
fi

if [ "${MAGNOLIA_OPENCODE_V2:-1}" = "1" ] && [ -n "$oc_bin" ] && [ -x "$oc_bin" ]; then
local want_db="${OPENCODE_DB:-$HOME/.local/share/opencode/opencode-v2.db}"
local svc_db mismatch=""
svc_db="$("$oc_bin" service get env OPENCODE_DB 2>/dev/null | tr -d '\r\n' || true)"
if [ -n "$svc_db" ]; then
_ok "OpenCode service OPENCODE_DB persisted: $svc_db"
else
_info "OpenCode service OPENCODE_DB not persisted yet (set automatically on next 'magnolia' launch)"
fi
if [ -f "$pcfg" ] && "$oc_bin" service status >/dev/null 2>&1; then
if mismatch="$(_find_service_db_mismatch "$want_db")"; then
local m_pid="${mismatch%%$'\t'*}" m_db="${mismatch#*$'\t'}"
_warn "OpenCode background service (PID $m_pid) is using ${m_db:-default opencode.db} instead of $want_db — run: magnolia service restart"
fi
local mcp_out=""
mcp_out="$(_run_with_timeout 10 bash -c 'cd "$1" && "$2" mcp list' _ "$pdir" "$oc_bin" 2>/dev/null || true)"
if printf '%s\n' "$mcp_out" | grep -qE "compchem-memory.*connected"; then
_ok "compchem-memory MCP is connected in OpenCode"
elif printf '%s\n' "$mcp_out" | grep -qE "compchem-memory.*failed"; then
_fail "compchem-memory MCP is failed in OpenCode — run: magnolia service restart"
fi
fi
fi
fi

echo
Expand Down Expand Up @@ -1349,12 +1465,17 @@ if [ -z "${MAGNOLIA_OPENCODE_V2:-}" ]; then
export MAGNOLIA_OPENCODE_V2=1
fi

# Subcommand dispatch: `magnolia doctor` / `magnolia memory …` run and exit.
# Subcommand dispatch: `magnolia doctor` / `magnolia service` / `magnolia memory …` run and exit.
if [ "${1:-}" = "doctor" ]; then
shift
cmd_doctor "${1:-}"
exit $?
fi
if [ "${1:-}" = "service" ]; then
shift
cmd_service "${1:-status}"
exit $?
fi
if [ "${1:-}" = "memory" ]; then
shift
case "${1:-}" in
Expand Down Expand Up @@ -1470,6 +1591,16 @@ if [ "${MAGNOLIA_OPENCODE_V2:-}" = "1" ]; then
mkdir -p "$(dirname "$OPENCODE_DB")"
export OPENCODE_DB
fi
if [ "${PRINT_ENV:-0}" != "1" ]; then
_ensure_v2_service_db "$OPENCODE_BIN" "$OPENCODE_DB"
_db_mismatch=""
if _db_mismatch="$(_find_service_db_mismatch "$OPENCODE_DB")"; then
_m_pid="${_db_mismatch%%$'\t'*}"
_m_db="${_db_mismatch#*$'\t'}"
echo "warning: OpenCode background service (PID $_m_pid) is using ${_m_db:-default opencode.db} instead of $OPENCODE_DB." >&2
echo " Your Magnolia sessions live in $OPENCODE_DB — run: magnolia service restart" >&2
fi
fi
# Per-project v2 daemon port (base 8201). The old fixed 8012 let every v2
# project reuse the first project's daemon env (2026-11-10 cross-project
# shell telemetry + session mix). MAGNOLIA_V2_PORT stays an explicit
Expand Down
75 changes: 75 additions & 0 deletions opencode_cc_mem/softwares/bin/tests/install_and_doctor_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,80 @@ EOF
rm -rf "$cache_dir" "$stub_oc"
}

test_service_subcommand_and_doctor_mcp_check() {
if [ -z "$REAL_VENV" ]; then
fail "service_and_doctor_mcp" "no .venv found"
return
fi
local root fake_home stub_dir state_file out rc
root="$(make_scratch_install_repo)"
fake_home="$(mktemp -d)"
stub_dir="$(mktemp -d)"
state_file="$stub_dir/service_db.txt"

cat > "$stub_dir/opencode" <<EOF
#!/usr/bin/env bash
case "\${1:-}" in
--version) echo "opencode 2.4.3"; exit 0 ;;
service)
case "\${2:-}" in
get)
[ -f "$state_file" ] && cat "$state_file"
exit 0
;;
set)
if [ "\${3:-}" = "env" ] && [ "\${4:-}" = "OPENCODE_DB" ]; then
printf '%s\n' "\${5:-}" > "$state_file"
fi
exit 0
;;
restart|status)
echo "http://127.0.0.1:49999"
exit 0
;;
esac
;;
mcp)
if [ "\${2:-}" = "list" ]; then
echo "✗ compchem-memory failed: Connection closed"
exit 0
fi
;;
esac
exit 0
EOF
chmod +x "$stub_dir/opencode"

# 1. `magnolia service restart` persists OPENCODE_DB via `opencode service set env`.
out="$(HOME="$fake_home" PATH="$stub_dir:$PATH" \
env -u MAGNOLIA_OPENCODE_V2 -u MAGNOLIA_OPENCODE_V2_BIN -u OPENCODE_DB \
"$root/opencode_cc_mem/softwares/bin/magnolia" service restart 2>&1)"
rc=$?
assert_eq "$rc" "0" "magnolia_service_restart_exit_0"
assert_eq "$(cat "$state_file" 2>/dev/null || true)" \
"$fake_home/.local/share/opencode/opencode-v2.db" \
"magnolia_service_restart_persists_opencode_db"

# 2. `magnolia doctor <project>` catches a failed compchem-memory MCP and recommends `magnolia service restart`.
mkdir -p "$root/opencode_cc_mem/projects/demo/.magnolia"
cat > "$root/opencode_cc_mem/projects/demo/opencode.json" <<'EOF'
{"mcp":{"servers":{"compchem-tools":{"type":"remote"},"compchem-memory":{"type":"local"}}}}
EOF
out="$(HOME="$fake_home" PATH="$stub_dir:$PATH" \
env -u MAGNOLIA_OPENCODE_V2 -u MAGNOLIA_OPENCODE_V2_BIN -u OPENCODE_DB \
"$root/opencode_cc_mem/softwares/bin/magnolia" doctor demo 2>&1)"
rc=$?
if [ "$rc" -ne 0 ] && \
printf '%s\n' "$out" | grep -q "compchem-memory MCP is failed in OpenCode" && \
printf '%s\n' "$out" | grep -q "magnolia service restart"; then
pass "doctor_catches_failed_compchem_memory_mcp"
else
fail "doctor_catches_failed_compchem_memory_mcp" "rc=$rc out=$out"
fi

rm -rf "$root" "$fake_home" "$stub_dir"
}

if [ $# -gt 0 ]; then
"$1"
else
Expand All @@ -337,6 +411,7 @@ else
test_doctor_catches_v1_under_v2_mode
test_env_file_does_not_override_caller_env
test_provider_picker_sorting_and_filtering
test_service_subcommand_and_doctor_mcp_check
fi

echo ""
Expand Down
Loading