From 0fa9a7bcd7854383646dda4881d006ca9996ad5c Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Sat, 14 Nov 2026 22:36:49 -0600 Subject: [PATCH] Stop repeated local Holmes tool calls --- docs/doctor-overview.md | 3 ++ scripts/doctor-focus | 3 ++ scripts/ollama-tool-proxy.py | 31 +++++++++++++++++++ tests/jeannie/test_doctor_focus.py | 22 +++++++++++++ .../jeannie/test_ollama_tool_call_adapter.py | 11 +++++++ 5 files changed, 70 insertions(+) diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index f0ad2c5..e2623ef 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -120,6 +120,9 @@ additional request with a shorter prompt. It forwards the reply only if it is one schema-valid Bash call containing a single read-only `kubectl get` command. It does not invent a call from the prose or force a tool after tool history exists. Subsequent Holmes actions retain the permissions described above. +If the model immediately repeats an identical Bash command, the adapter asks it +once to continue using the previous result. If it repeats again, Doctor stops +the investigation and reports it as incomplete rather than rerunning it. For native K3s on the Orange Pi, `doctor opi5` collects the K3s service state, data and runtime mount identities, USB ext4 candidates and recent storage diff --git a/scripts/doctor-focus b/scripts/doctor-focus index 817fca0..2b0ec2c 100644 --- a/scripts/doctor-focus +++ b/scripts/doctor-focus @@ -195,6 +195,9 @@ doctor_focus_holmes_fix() { wait "${proxy_pid}" 2>/dev/null || true fi [[ "${tool_status}" == observed ]] || { tool_status=not-observed; status=1; } + if grep -q 'JEANNIE_STOP_REPEATED_TOOL_CALL' "${artifact}/holmes-output.txt" "${artifact}/holmes-retry-output.txt" 2>/dev/null; then + status=1 + fi { 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" for i in 1 2 3; do diff --git a/scripts/ollama-tool-proxy.py b/scripts/ollama-tool-proxy.py index b68a66f..3769419 100644 --- a/scripts/ollama-tool-proxy.py +++ b/scripts/ollama-tool-proxy.py @@ -69,6 +69,25 @@ def safe_initial_call(message, tools): return False +def same_as_last_call(message, history): + calls = message.get("tool_calls") or [] + if len(calls) != 1: + return False + previous = next((m.get("tool_calls") for m in reversed(history) + if isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")), None) + if not isinstance(previous, list) or len(previous) != 1: + return False + try: + current_fn, previous_fn = calls[0]["function"], previous[0]["function"] + if current_fn.get("name") != "bash" or previous_fn.get("name") != "bash": + return False + current_args = json.loads(current_fn["arguments"], object_pairs_hook=adapter.unique_object) + previous_args = json.loads(previous_fn["arguments"], object_pairs_hook=adapter.unique_object) + return current_args.get("command") == previous_args.get("command") + except (KeyError, TypeError, ValueError, AttributeError): + return False + + def complete(request, bash_mode): """Retry an initial prose-only answer once; never fabricate a tool call.""" result = translate(query_ollama(request), request.get("tools", [])) @@ -96,6 +115,18 @@ def complete(request, bash_mode): print("initial_retry", "tool_call=" + str(bool(retried["choices"][0]["message"].get("tool_calls"))), "accepted=" + str(accepted), flush=True) if accepted: return retried + message = result["choices"][0]["message"] + if bash_mode and same_as_last_call(message, messages): + retry = dict(request) + retry["messages"] = messages + [{"role": "user", "content": + "That exact command was just run. Do not repeat it. Use its result to continue with a different check, " + "perform an evidence-supported next action, or provide the final report."}] + retried = translate(query_ollama(retry), request.get("tools", [])) + if not same_as_last_call(retried["choices"][0]["message"], messages): + return retried + result["choices"][0]["message"] = {"role": "assistant", "content": + "JEANNIE_STOP_REPEATED_TOOL_CALL: Holmes repeated the preceding command; investigation is incomplete."} + result["choices"][0]["finish_reason"] = "stop" return result diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index 753412c..128949f 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -78,6 +78,28 @@ doctor_focus_holmes_fix n8n''' self.assertNotEqual(result.returncode, 0) self.assertIn("No completed Holmes tool calls were recorded", result.stdout) + def test_holmes_repair_marks_repeated_tool_stop_incomplete(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; printf '%s' '{\"tool_calls\":[{}]}' > \"$1\"; break; fi; shift; done\necho JEANNIE_STOP_REPEATED_TOOL_CALL\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) + self.assertNotEqual(result.returncode, 0) + self.assertIn("incomplete", result.stdout) + def test_holmes_retries_only_after_completed_zero_tool_response(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/tests/jeannie/test_ollama_tool_call_adapter.py b/tests/jeannie/test_ollama_tool_call_adapter.py index 23b593c..7b40cf1 100644 --- a/tests/jeannie/test_ollama_tool_call_adapter.py +++ b/tests/jeannie/test_ollama_tool_call_adapter.py @@ -72,3 +72,14 @@ class ToolAdapterTests(unittest.TestCase): message = {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({ "command": command, "suggested_prefixes": ["kubectl"]})}}]} self.assertFalse(PROXY.safe_initial_call(message, tools)) + + def test_repeated_command_is_not_forwarded_after_one_retry(self): + args = json.dumps({"command": "printf hello", "suggested_prefixes": ["printf"]}) + previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": args}}]} + request = {"tools": self.tools, "messages": [previous, {"role": "tool", "content": "hello"}]} + repeated = {"choices": [{"message": {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": args}}]}, "finish_reason": "tool_calls"}]} + with patch.object(PROXY, "query_ollama", side_effect=[repeated, repeated]) as query: + result = PROXY.complete(request, True) + self.assertEqual(query.call_count, 2) + self.assertIn("JEANNIE_STOP_REPEATED_TOOL_CALL", result["choices"][0]["message"]["content"]) + self.assertNotIn("tool_calls", result["choices"][0]["message"])