Retry incomplete Holmes investigations safely
Homelab Main / validate (push) Failing after 1m59s Details
Homelab Main / running-update (push) Has been skipped Details
Homelab Main / debian-ops (push) Has been skipped Details

This commit is contained in:
juvenal.diaz 2026-11-14 13:37:04 -06:00
parent 552f4be1ad
commit 4940a283d3
3 changed files with 70 additions and 25 deletions

View File

@ -95,6 +95,11 @@ paths containing brackets are not interpreted as terminal markup.
If Holmes records no tool calls, Doctor marks the investigation incomplete even
when the model prints what looks like a tool request as ordinary text. A tool
call record alone does not prove that a repair was made or succeeded.
When a completed response records exactly zero tool calls, Doctor retries once
with the same evidence and retains both conversations. Failed, timed-out, or
unreadable conversations are not retried because actions may have occurred.
The independent post-repair identity and application check retries twice on
failure, then reports unknown if it still cannot obtain evidence.
Repair mode defaults to 30 model steps, a 900-second timeout and a 2048 MiB
per-tool memory limit; `LAB_HOLMES_REPAIR_MAX_STEPS`,
`LAB_HOLMES_REPAIR_TIMEOUT_SECONDS` and `LAB_HOLMES_REPAIR_TOOL_MEMORY_MB`

View File

@ -107,7 +107,7 @@ doctor_focus_holmes() {
}
doctor_focus_holmes_fix() {
local item="$1" base artifact bin config model fast key snapshot validation_row proxy_pid="" proxy_port="" i status=0 validation=unknown tool_status=unknown
local item="$1" base artifact bin config model fast key snapshot validation_row proxy_pid="" proxy_port="" i attempt conversation output error prompt status=0 validation=unknown tool_status=unknown
local tools_env="${LAB_AI_STACK_TOOLS_ENV_FILE:-/data/homelab-ai-stack/ai-tools.env}"
local AI_STACK_AGENT_SMART_MODEL="${AI_STACK_AGENT_SMART_MODEL:-}" AI_STACK_AGENT_FAST_MODEL="${AI_STACK_AGENT_FAST_MODEL:-}"
local OPENAI_BASE_URL="${OPENAI_BASE_URL:-}" OPENAI_API_KEY="${OPENAI_API_KEY:-}"
@ -158,38 +158,52 @@ doctor_focus_holmes_fix() {
printf '\nHomelab skill: use only when its stated conditions match the observed evidence.\n'
cat "${REPO_ROOT}/infra/ai-stack/holmes-skills/k3s-stale-volume/SKILL.md"
} >"${artifact}/holmes-context.txt"
printf 'Investigate and repair Kubernetes application %s using the supplied context file. Follow its procedure and report the outcome.\n' "${item}" >"${artifact}/holmes-prompt.txt"
printf 'Investigate Kubernetes application %s using the supplied context file. First call the bash tool to inspect the issue; include command and suggested_prefixes. Do not answer with a plan before using a tool. Follow the procedure and report the outcome.\n' "${item}" >"${artifact}/holmes-prompt.txt"
record_change_journal "doctor-holmes-k8s-repair" "${item}"
echo "Holmes is authorized to execute commands to repair ${item}; its Bash tool has host-level access."
if ! timeout "${LAB_HOLMES_REPAIR_TIMEOUT_SECONDS:-900}" env KUBECONFIG="${KUBECONFIG_PATH}" \
TOOL_MEMORY_LIMIT_MB="${LAB_HOLMES_REPAIR_TOOL_MEMORY_MB:-2048}" \
OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" \
OPENAI_API_BASE="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" OPENAI_API_KEY="${key}" \
python3 "${REPO_ROOT}/scripts/doctor-holmes-interactive.py" "${artifact}/conversation.json" -- \
"${bin}" ask --config "${config}" --prompt-file "${artifact}/holmes-prompt.txt" \
--file "${artifact}/holmes-context.txt" \
--api-key "${key}" --model "${model}" --fast-model "${fast}" \
--max-steps "${LAB_HOLMES_REPAIR_MAX_STEPS:-30}" --fast-mode --interactive --bash-always-allow --json-output-file "${artifact}/conversation.json" \
>"${artifact}/holmes-output.txt" 2>"${artifact}/holmes-error.txt"; then
status=1
fi
for attempt in 1 2; do
conversation="${artifact}/conversation.json"; output="${artifact}/holmes-output.txt"; error="${artifact}/holmes-error.txt"; prompt="${artifact}/holmes-prompt.txt"
if ((attempt == 2)); then
conversation="${artifact}/retry-conversation.json"; output="${artifact}/holmes-retry-output.txt"; error="${artifact}/holmes-retry-error.txt"; prompt="${artifact}/holmes-retry-prompt.txt"
printf 'You gave a plan without using any tools. Call bash now to inspect Kubernetes application %s using the provided evidence. Include both command and suggested_prefixes. Do not claim a command ran unless it actually ran.\n' "${item}" >"${prompt}"
echo "Holmes made no tool calls; retrying once with the same evidence."
fi
if ! timeout "${LAB_HOLMES_REPAIR_TIMEOUT_SECONDS:-900}" env KUBECONFIG="${KUBECONFIG_PATH}" \
TOOL_MEMORY_LIMIT_MB="${LAB_HOLMES_REPAIR_TOOL_MEMORY_MB:-2048}" \
OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" \
OPENAI_API_BASE="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" OPENAI_API_KEY="${key}" \
python3 "${REPO_ROOT}/scripts/doctor-holmes-interactive.py" "${conversation}" -- \
"${bin}" ask --config "${config}" --prompt-file "${prompt}" \
--file "${artifact}/holmes-context.txt" \
--api-key "${key}" --model "${model}" --fast-model "${fast}" \
--max-steps "${LAB_HOLMES_REPAIR_MAX_STEPS:-30}" --fast-mode --interactive --bash-always-allow --json-output-file "${conversation}" \
>"${output}" 2>"${error}"; then
status=1
break
fi
if python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if isinstance(d.get("tool_calls"),list) and len(d["tool_calls"]) > 0 else 1)' "${conversation}" 2>/dev/null; then
tool_status=observed
break
fi
if ! python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if d.get("tool_calls") == [] else 1)' "${conversation}" 2>/dev/null; then
status=1
break
fi
done
if [[ -n "${proxy_pid}" ]]; then
kill "${proxy_pid}" 2>/dev/null || true
wait "${proxy_pid}" 2>/dev/null || true
fi
if python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if isinstance(d.get("tool_calls"),list) and len(d["tool_calls"]) > 0 else 1)' "${artifact}/conversation.json" 2>/dev/null; then
tool_status=observed
else
tool_status=not-observed
status=1
fi
[[ "${tool_status}" == observed ]] || { tool_status=not-observed; status=1; }
{
printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application %q --ignore-not-found -o json | python3 %q --report\n' "${KUBECONFIG_PATH}" "${item}" "${REPO_ROOT}/scripts/doctor-application.py"
if cluster_context_require && snapshot="$(doctor_focus_application_fetch "${item}")" && [[ -n "${snapshot}" ]] && validation_row="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --report)"; then
printf '%s\n' "${validation_row}"
else
echo "Application state or cluster identity unavailable."
fi
for i in 1 2 3; do
if cluster_context_require && snapshot="$(doctor_focus_application_fetch "${item}")" && [[ -n "${snapshot}" ]] && validation_row="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --report)"; then
printf '%s\n' "${validation_row}"
break
fi
if ((i < 3)); then sleep 1; else echo "Application state or cluster identity unavailable."; fi
done
} >"${artifact}/validation.txt" 2>&1
if grep -q '^ok[[:space:]]' "${artifact}/validation.txt"; then
validation=healthy
@ -200,6 +214,7 @@ doctor_focus_holmes_fix() {
printf 'Jeannie Kubernetes repair report: %s\n\n' "${item}"
printf 'Holmes investigation, five whys and attempted mitigation (model-generated; verify claims):\n'
cat "${artifact}/holmes-output.txt"
if [[ -f "${artifact}/holmes-retry-output.txt" ]]; then printf '\nHolmes retry:\n'; cat "${artifact}/holmes-retry-output.txt"; fi
printf '\nHolmes execution: '
if ((status)); then echo 'incomplete, failed or timed out; changes may already have occurred'; else echo 'completed'; fi
if [[ "${tool_status}" != observed ]]; then echo 'No completed Holmes tool calls were recorded; no tool-based investigation is confirmed.'; fi

View File

@ -78,6 +78,31 @@ doctor_focus_holmes_fix n8n'''
self.assertNotEqual(result.returncode, 0)
self.assertIn("No completed Holmes tool calls were recorded", result.stdout)
def test_holmes_retries_only_after_completed_zero_tool_response(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
binary = root / "jeannie-holmes"
binary.write_text("#!/bin/sh\nwhile [ $# -gt 0 ]; do if [ \"$1\" = --json-output-file ]; then shift; path=$1; break; fi; shift; done\n"
"if [ -e \"$HOME/called\" ]; then printf '%s' '{\"tool_calls\":[{}]}' > \"$path\"; else touch \"$HOME/called\"; printf '%s' '{\"tool_calls\":[]}' > \"$path\"; fi\nread -r line\n")
binary.chmod(0o755)
rows = root / "rows"
rows.write_text("warn\tKubernetes apps\tn8n\tUnavailable\n")
env = os.environ.copy()
env.update(PATH=f"{root}:{env.get('PATH', '')}", REPO_ROOT=str(ROOT), HOME=str(root),
REPORT_UI_ROWS_FILE=str(rows), KUBECONFIG_PATH="/tmp/test-kubeconfig",
LAB_AI_STACK_TOOLS_ENV_FILE=str(root / "missing"), LAB_HOLMES_CONFIG_FILE=str(root / "missing-config"),
LAB_DOCTOR_K8S_ARTIFACT_DIR=str(root / "artifacts"))
code = '''source "$1"
cluster_context_require() { :; }
record_change_journal() { :; }
doctor_focus_application_fetch() { printf '%s' '{"metadata":{"name":"n8n"},"status":{"health":{"status":"Healthy"},"sync":{"status":"Synced"}}}'; }
doctor_focus_holmes_fix n8n'''
result = subprocess.run(["bash", "-c", code, "test", str(DOCTOR)], env=env, capture_output=True, text=True, check=True)
self.assertIn("retrying once", result.stdout)
artifact = next((root / "artifacts").glob("repair.*"))
self.assertTrue((artifact / "conversation.json").exists())
self.assertTrue((artifact / "retry-conversation.json").exists())
def test_holmes_repair_does_not_claim_success_when_validation_fails(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)