import importlib.util import json import io import os import tempfile from pathlib import Path import unittest from unittest.mock import patch SPEC = importlib.util.spec_from_file_location("tool_adapter", Path(__file__).resolve().parents[2] / "scripts/ollama-tool-call-adapter.py") ADAPTER = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(ADAPTER) PROXY_SPEC = importlib.util.spec_from_file_location("tool_proxy", Path(__file__).resolve().parents[2] / "scripts/ollama-tool-proxy.py") PROXY = importlib.util.module_from_spec(PROXY_SPEC) PROXY_SPEC.loader.exec_module(PROXY) CONFIG_SPEC = importlib.util.spec_from_file_location('local_config', Path(__file__).resolve().parents[2] / 'scripts/doctor-holmes-local-config.py') CONFIG = importlib.util.module_from_spec(CONFIG_SPEC) CONFIG_SPEC.loader.exec_module(CONFIG) class ToolAdapterTests(unittest.TestCase): def test_compact_evidence_keeps_facts_and_candidate_without_command_list_duplication(self): candidate = {'pod_uid': 'observed-uid', 'candidate_command': 'verified command'} rows = ('warn\tKubernetes evidence\tapp\tUnavailable\t$ kubectl get pod app -o json | ' 'python3 helper.py | pod app CrashLoopBackOff | pod app CrashLoopBackOff | ' 'Conditional recovery candidate (not executed): ' + json.dumps(candidate) + '\t\t\n') result = CONFIG.compact_evidence(rows) self.assertEqual(result[0]['observed_evidence'], ['pod app CrashLoopBackOff']) self.assertEqual(result[0]['conditional_recovery_candidate'], candidate) self.assertEqual(result[0]['summary'], 'Unavailable') def test_local_config_loads_only_bash_without_modifying_source(self): source = {'model': 'original', 'custom_toolsets': ['custom.yaml'], 'toolsets': {'other': {'enabled': True}}} result = CONFIG.local_config(source, ['bash', 'kubernetes/core']) self.assertEqual(result['toolsets'], {'bash': {'enabled': True}, 'kubernetes/core': {'enabled': False}}) self.assertNotIn('custom_toolsets', result) self.assertEqual(source['custom_toolsets'], ['custom.yaml']) self.assertEqual(result['model'], 'original') with self.assertRaises(ValueError): CONFIG.local_config(source, ['other']) def test_native_request_sets_context_and_converts_tool_arguments(self): response = {"model": "test", "prompt_eval_count": 20, "eval_count": 5, "total_duration": 1000, "load_duration": 200, "prompt_eval_duration": 300, "eval_duration": 500, "done_reason": "stop", "message": {"role": "assistant", "tool_calls": [ {"function": {"name": "bash", "arguments": {"command": "kubectl get pods"}}}]}} request = {"_jeannie_native": True, "model": "test", "messages": [], "max_tokens": 512} with patch.object(PROXY.urllib.request, "urlopen", return_value=io.BytesIO(json.dumps(response).encode())) as query: answer = PROXY.query_ollama(request) sent = json.loads(query.call_args.args[0].data) self.assertEqual(sent["options"], {"num_ctx": 8192, "num_predict": 512, "temperature": 0, "seed": 42}) self.assertNotIn("_jeannie_native", sent) call = answer["choices"][0]["message"]["tool_calls"][0] self.assertEqual(json.loads(call["function"]["arguments"])["command"], "kubectl get pods") self.assertEqual(answer['usage'], {'prompt_tokens': 20, 'completion_tokens': 5, 'total_tokens': 25}) self.assertEqual(answer['ollama']['eval_duration'], 500) self.assertEqual(answer['ollama']['done_reason'], 'stop') def test_native_length_stop_and_missing_usage_are_preserved(self): response = {'message': {'role': 'assistant', 'content': 'partial'}, 'done_reason': 'length'} with patch.object(PROXY.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(response).encode())): answer = PROXY.query_ollama({'_jeannie_native': True, 'model': 'test', 'messages': []}) self.assertEqual(answer['choices'][0]['finish_reason'], 'length') self.assertIsNone(answer['usage']['total_tokens']) def test_metrics_artifact_excludes_model_content(self): with tempfile.TemporaryDirectory() as directory: target = Path(directory) / 'metrics.jsonl' with patch.dict(os.environ, JEANNIE_OLLAMA_METRICS_FILE=str(target)): PROXY.record_metrics({'model': 'test', 'usage': {'prompt_tokens': 10}, 'choices': [{'finish_reason': 'length', 'message': {'content': 'private evidence'}}]}, 1.2) data = target.read_text() self.assertNotIn('private evidence', data) self.assertEqual(json.loads(data)['finish_reason'], 'length') self.assertEqual(target.stat().st_mode & 0o777, 0o600) def test_partial_tool_trace_is_separate_and_private(self): with tempfile.TemporaryDirectory() as directory: metrics = Path(directory) / 'metrics.jsonl' evidence = {'role': 'tool', 'tool_call_id': 'call-test', 'content': 'actual tool result'} call = {'function': {'name': 'bash', 'arguments': '{"command":"kubectl get pods"}'}} with patch.dict(os.environ, JEANNIE_OLLAMA_METRICS_FILE=str(metrics)): PROXY.record_tool_trace({'messages': [{'role': 'user', 'content': 'private prompt'}, evidence]}, {'choices': [{'message': {'tool_calls': [call]}, 'finish_reason': 'tool_calls'}]}) trace = Path(directory) / 'holmes-tool-trace.jsonl' row = json.loads(trace.read_text()) self.assertEqual(row['previous_result'], evidence) self.assertEqual(row['tool_calls'], [call]) self.assertNotIn('private prompt', trace.read_text()) self.assertEqual(trace.stat().st_mode & 0o777, 0o600) def setUp(self): self.tools = [{"type": "function", "function": {"name": "get_status", "parameters": { "type": "object", "properties": {"service": {"type": "string"}}, "required": ["service"], "additionalProperties": False}}}] def test_valid_call(self): result = ADAPTER.convert(json.dumps({"name": "get_status", "arguments": {"service": "demo"}}), self.tools) self.assertEqual(result["function"]["arguments"], {"service": "demo"}) self.assertIsNotNone(ADAPTER.convert('```json\n{"name":"get_status","arguments":{"service":"demo"}}\n```', self.tools)) def test_holmes_strict_optional_timeout_uses_nullable_default(self): schema = {'type': 'object', 'properties': {'command': {'type': 'string'}, 'suggested_prefixes': {'type': 'array', 'items': {'type': 'string'}}, 'timeout': {'anyOf': [{'type': 'integer'}, {'type': 'null'}]}}, 'required': ['command', 'suggested_prefixes', 'timeout'], 'additionalProperties': False} tools = [{'type': 'function', 'function': {'name': 'bash', 'parameters': schema}}] content = json.dumps({'name': 'bash', 'arguments': {'command': 'kubectl get pods', 'suggested_prefixes': ['kubectl get']}}) call = ADAPTER.convert(content, tools) self.assertEqual(call['function']['arguments']['timeout'], 30) schema['properties']['timeout'] = {'type': 'integer'} self.assertIsNone(ADAPTER.convert(content, tools)) self.assertIsNone(ADAPTER.convert('{"name":"bash","arguments":{"command":"kubectl get pods"}}', tools)) def test_compact_prompt_preserves_task_and_tool_evidence(self): task = {'role': 'user', 'content': 'Only repair the named test service.'} evidence = {'role': 'tool', 'tool_call_id': 'x', 'content': 'error'} result = PROXY.compact_messages([{'role': 'system', 'content': 'generic prompt'}, task, evidence]) self.assertEqual(result[1:], [task, evidence]) self.assertIn('authorized', result[0]['content']) def test_summarizer_instructions_are_not_replaced(self): request = {'messages': [{'role': 'system', 'content': 'Summarize the following output.'}, {'role': 'user', 'content': 'observed output'}]} response = {'choices': [{'message': {'content': 'summary'}}]} with patch.object(PROXY, 'query_ollama', return_value=response) as query: PROXY.complete(request, True) self.assertEqual(query.call_args.args[0]['messages'], request['messages']) def test_native_call_format_matches_actual_tool_schema(self): tools = [{'type': 'function', 'function': {'name': 'bash', 'parameters': { 'type': 'object', 'properties': {'command': {'type': 'string'}}, 'required': ['command']}}}] response = {'message': {'role': 'assistant', 'content': '{"report":"done"}'}, 'done_reason': 'stop'} with patch.object(PROXY.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(response).encode())) as query: result = PROXY.query_ollama({'_jeannie_native': True, 'model': 'test', 'messages': [], 'tools': tools}) sent = json.loads(query.call_args.args[0].data) self.assertEqual(sent['format']['properties']['arguments'], tools[0]['function']['parameters']) self.assertNotIn('tools', sent) self.assertEqual(result['choices'][0]['message']['content'], 'done') def test_invalid_or_ambiguous_calls_are_not_translated(self): for value in ('prefix {"name":"get_status","arguments":{}}', 'prose\n```json\n{"name":"get_status","arguments":{"service":"demo"}}\n```', '{"name":"unknown","arguments":{}}', '{"name":"get_status","arguments":{"service":42}}', '{"name":"get_status","arguments":{"service":"demo","extra":1}}', '{"name":"get_status","name":"other","arguments":{"service":"demo"}}', '{"name":"get_status","arguments":{"service":"demo"},"extra":true}'): self.assertIsNone(ADAPTER.convert(value, self.tools)) self.assertIsNone(ADAPTER.convert('{"name":"get_status","arguments":{"service":"demo"}}', self.tools * 2)) def test_bash_only_excludes_other_tools(self): bash = {"type": "function", "function": {"name": "bash", "parameters": {}}} self.assertEqual(PROXY.bash_only(self.tools + [bash]), [bash]) with self.assertRaises(ValueError): PROXY.bash_only(self.tools) with self.assertRaises(ValueError): PROXY.bash_only([bash, bash]) def test_first_prose_answer_retries_and_translates_only_valid_call(self): tools = [{"type": "function", "function": {"name": "bash", "parameters": { "type": "object", "properties": {"command": {"type": "string"}, "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, "required": ["command", "suggested_prefixes"]}}}] request = {"tools": tools, "messages": [{"role": "user", "content": "investigate"}]} plan = {"choices": [{"message": {"role": "assistant", "content": "Inspect the pod."}, "finish_reason": "stop"}]} call = {"choices": [{"message": {"role": "assistant", "content": json.dumps({"name": "bash", "arguments": { "command": "kubectl get pods", "suggested_prefixes": ["kubectl"]}})}, "finish_reason": "stop"}]} with patch.object(PROXY, "query_ollama", side_effect=[plan, call]) as query: result = PROXY.complete(request, True) self.assertEqual(query.call_count, 2) self.assertEqual(result["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "bash") def test_does_not_force_another_tool_after_tool_history(self): request = {"tools": self.tools, "messages": [{"role": "tool", "content": "ok"}]} plan = {"choices": [{"message": {"role": "assistant", "content": "Complete."}, "finish_reason": "stop"}]} with patch.object(PROXY, "query_ollama", return_value=plan) as query: PROXY.complete(request, True) self.assertEqual(query.call_count, 1) def test_bash_requests_limit_model_output(self): request = {"tools": self.tools, "messages": [], "max_completion_tokens": 64000} response = {"choices": [{"message": {"role": "assistant", "content": "Done."}}]} with patch.object(PROXY, "query_ollama", return_value=response) as query: PROXY.complete(request, True) sent = query.call_args.args[0] self.assertEqual(sent["max_tokens"], 1024) self.assertNotIn("max_completion_tokens", sent) self.assertEqual(request["max_completion_tokens"], 64000) def test_resource_echo_prompts_one_valid_next_read_only_check(self): tools = [{"type": "function", "function": {"name": "bash", "parameters": { "type": "object", "properties": {"command": {"type": "string"}, "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, "required": ["command", "suggested_prefixes"]}}}] previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl -n n8n get pod n8n", "suggested_prefixes": ["kubectl"]})}}]} request = {"tools": tools, "messages": [{"role": "user", "content": "pvc n8n-data phase=Bound pv=pvc-123"}, previous, {"role": "tool", "content": "pod output"}]} echo = {"choices": [{"message": {"role": "assistant", "content": '{"name":"n8n","image":"n8n:2"}'}, "finish_reason": "stop"}]} next_call = {"choices": [{"message": {"role": "assistant", "content": json.dumps({"name": "bash", "arguments": { "command": "kubectl -n n8n get pvc n8n-data", "suggested_prefixes": ["kubectl"]}})}, "finish_reason": "stop"}]} with patch.object(PROXY, "query_ollama", side_effect=[echo, next_call]) as query: result = PROXY.complete(request, True) self.assertEqual(query.call_count, 2) self.assertEqual(result["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "bash") def test_complete_json_diagnosis_is_not_treated_as_resource_echo(self): self.assertFalse(PROXY.is_resource_extract({"content": '{"status":"bad","diagnosis":"disk"}'})) self.assertTrue(PROXY.is_resource_extract({"content": '{"response":"Pod is crashing."}'})) self.assertFalse(PROXY.is_resource_extract({"content": '{"response":"Diagnosis: disk. Mitigation: none. Validation: failed."}'})) self.assertTrue(PROXY.is_resource_extract({"content": "The pod is running an application and has a container image. " * 3})) self.assertFalse(PROXY.is_resource_extract({"content": "Diagnosis: bad pod. Mitigation: none. Validation: unavailable."})) self.assertTrue(PROXY.is_resource_extract({"content": '```json\n{"name":"fetch_pvc_details","arguments":{"pvc_name":"n8n-data"}}\n```'})) def test_pv_result_leads_to_decision_with_tool_history(self): tools = [{"type": "function", "function": {"name": "bash", "parameters": { "type": "object", "properties": {"command": {"type": "string"}, "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, "required": ["command", "suggested_prefixes"]}}}] previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl get pv pvc-123"})}}]} history = [{"role": "user", "content": "investigate"}, previous, {"role": "tool", "content": "volume output"}] echo = {"choices": [{"message": {"content": '{"kind":"PersistentVolume"}'}}]} decision = {"choices": [{"message": {"content": "Diagnosis: missing evidence. Mitigation: none. Validation: unavailable."}}]} with patch.object(PROXY, "query_ollama", side_effect=[echo, decision]) as query: result = PROXY.complete({"tools": tools, "messages": history}, True) prompt = query.call_args_list[1].args[0]["messages"] self.assertEqual(prompt[1], history[0]) self.assertIn("volume output", prompt[2]["content"]) self.assertNotIn(previous, prompt) self.assertIn("missing evidence", result["choices"][0]["message"]["content"]) def test_last_bash_command_reads_recorded_tool_arguments(self): messages = [{"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl -n n8n get pvc n8n-data"})}}]}, {"role": "tool", "content": "ok"}] self.assertEqual(PROXY.last_bash_command(messages), "kubectl -n n8n get pvc n8n-data") def test_seen_bash_command_checks_earlier_calls(self): def call(command): return {"function": {"name": "bash", "arguments": json.dumps({"command": command})}} history = [{"role": "assistant", "tool_calls": [call("kubectl get pvc")]}, {"role": "assistant", "tool_calls": [call("kubectl get pv")]}] self.assertTrue(PROXY.seen_bash_command({"tool_calls": [call("kubectl get pvc")]}, history)) self.assertFalse(PROXY.seen_bash_command({"tool_calls": [call("kubectl get pod")]}, history)) def test_alternating_old_commands_are_not_forwarded(self): def call(command): return {'function': {'name': 'bash', 'arguments': json.dumps({'command': command})}} history = [{'role': 'assistant', 'tool_calls': [call('journalctl -u kubelet')]}, {'role': 'tool', 'content': 'permission denied'}, {'role': 'assistant', 'tool_calls': [call('journalctl -u kubelet -n 20')]}, {'role': 'tool', 'content': 'permission denied'}] repeated = {'choices': [{'message': {'role': 'assistant', 'tool_calls': [call('journalctl -u kubelet')]}}]} with patch.object(PROXY, 'query_ollama', side_effect=[repeated, repeated]): result = PROXY.complete({'messages': history, 'tools': self.tools}, True) self.assertIn('JEANNIE_STOP_REPEATED_TOOL_CALL', result['choices'][0]['message']['content']) def test_retry_cannot_turn_a_plan_into_a_mutating_command(self): tools = [{"type": "function", "function": {"name": "bash", "parameters": { "type": "object", "properties": {"command": {"type": "string"}, "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, "required": ["command", "suggested_prefixes"]}}}] for command in ("kubectl delete pod n8n", "kubectl get pods; rm -rf /", "kubectl get --raw=/api/v1/secrets"): message = {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({ "command": command, "suggested_prefixes": ["kubectl"]})}}]} self.assertFalse(PROXY.safe_initial_call(message, tools)) def test_pvc_and_pv_names_must_match_the_evidence(self): tools = [{"type": "function", "function": {"name": "bash", "parameters": { "type": "object", "properties": {"command": {"type": "string"}, "suggested_prefixes": {"type": "array", "items": {"type": "string"}}}, "required": ["command", "suggested_prefixes"]}}}] context = "pvc n8n-data phase=Bound pv=pvc-123 storage_class=local" def call(command): return {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": command, "suggested_prefixes": ["kubectl"]})}}]} self.assertTrue(PROXY.safe_initial_call(call("kubectl -n n8n get pvc n8n-data"), tools, context)) self.assertTrue(PROXY.safe_initial_call(call("kubectl get pv pvc-123"), tools, context)) self.assertFalse(PROXY.safe_initial_call(call("kubectl -n n8n get pvc pvc-123"), tools, context)) self.assertFalse(PROXY.safe_initial_call(call("kubectl get pv n8n-data"), tools, context)) 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"])