From da5d6182972bf276c6dd0094b90edc24b6113921 Mon Sep 17 00:00:00 2001 From: lzkk <956449176@qq.com> Date: Tue, 26 May 2026 00:29:01 +0800 Subject: [PATCH] =?UTF-8?q?fix(hooks):=20memory-guard=20=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E5=90=88=E6=B3=95=20JSON=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E5=B4=A9=E6=BA=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SessionStart hook 要求 stdout 输出 JSON,但旧版 memory-guard.sh 只写 stderr,stdout 为空,导致 Claude Code hook runner JSON 解析异常后崩溃。 改为输出 {"continue": true} 并将警告注入 additionalContext。 --- .claude/hooks/memory-guard.sh | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100755 .claude/hooks/memory-guard.sh diff --git a/.claude/hooks/memory-guard.sh b/.claude/hooks/memory-guard.sh new file mode 100755 index 00000000..ebf3f4a4 --- /dev/null +++ b/.claude/hooks/memory-guard.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# 会话启动时的内存/进程守卫 +# 1. 检查可用内存,低于 2GB 时警告 +# 2. 检查是否有多个 claude 会话在运行 +# 输出 JSON 到 stdout,警告通过 additionalContext 注入 + +AVAILABLE_MB=$(awk '/^MemAvailable:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo "0") +CLAUDE_COUNT=$(pgrep -c -f "claude.*permission-mode" 2>/dev/null || echo "0") + +WARNINGS="" + +if [[ "$AVAILABLE_MB" -gt 0 && "$AVAILABLE_MB" -lt 2048 ]]; then + WARNINGS="${WARNINGS}- ⚠ 可用内存仅 ${AVAILABLE_MB}MB,建议关闭其他应用后再操作\n" +fi + +if [[ "$CLAUDE_COUNT" -gt 2 ]]; then + WARNINGS="${WARNINGS}- ⚠ 检测到 ${CLAUDE_COUNT} 个 claude 会话在运行,多会话可能导致 OOM\n" +fi + +if [[ -n "$WARNINGS" ]]; then + cat << EOF +{ + "continue": true, + "hookSpecificOutput": { + "hookEventName": "SessionStart", + "additionalContext": "## ⚠ 资源警告\n\n${WARNINGS}" + } +} +EOF +else + echo '{"continue": true}' +fi