The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): name the field a refusal is about
Daniel V. Baeckerc7afde344a57
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 5e10995311a..640a442ef12 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -1,5 +1,6 @@"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""import asyncio+import loggingimport refrom dataclasses import asdictfrom functools import partial@@ -9,8 +10,53 @@ import uuidfrom gateway.config import Platformfrom gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL, Principal, SessionRef, Submission+from hermes_constants import profile_name_for_homefrom hermes_state_runtime import RuntimeStoreError+logger = logging.getLogger(__name__)+++# A refusal names the check that fired: the client prints ``field``/``detail`` beside the reason+# code, and this log line is what a report can quote when the client's copy is not enough.+def _refusal_data(exc: RuntimeStoreError) -> dict:+ """The ``error.data`` for one ``RuntimeStoreError``: always the reason, plus the field and the+ detail when the raiser named them."""+ data = {'reason': exc.reason}+ for key in ('field', 'detail'):+ value = getattr(exc, key, None)+ if value:+ data[key] = value+ return data+++def _profile_label(profile_id) -> str:+ """The profile as a log line should carry it: a named profile by name, a root profile (keyed by its+ home path) by its name, never the path itself."""+ if not profile_id:+ return 'default'+ text = str(profile_id)+ if '/' not in text and '\\' not in text:+ return text+ return profile_name_for_home(text) or 'default'+++def _log_refusal(profile, method, exc: RuntimeStoreError) -> None:+ """One line per refusal, at the level its audience deserves.++ A refusal that names the check that fired is a launch diagnostic (warning). A bare reason code is+ the client's own state: ``permission_denied`` on a submit, ``not_found``, ``session_busy`` are+ routine, and a retrying client must not be able to flood the gateway log, so those stay at debug+ where they were silent before. The shape follows the gateway's own refusal log lines+ (``gateway/run_notifications.py``): what was refused, for which profile, and why."""+ line = '%s refused for profile=%s: %s%s%s'+ args = (method, _profile_label(profile), exc.reason,+ f' field={exc.field}' if getattr(exc, 'field', None) else '',+ f' detail={exc.detail}' if getattr(exc, 'detail', None) else '')+ if getattr(exc, 'field', None) or getattr(exc, 'detail', None):+ logger.warning(line, *args)+ else:+ logger.debug(line, *args)+# ``session.detach end_reason``: a short snake_case label, stored verbatim as ``sessions.end_reason``._END_REASON = re.compile(r'[a-z][a-z_]{0,31}')@@ -156,8 +202,9 @@ class AuthorityConnection:try:routed = self._sibling_for(profile)except RuntimeStoreError as exc:+ _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)return {'jsonrpc': '2.0', 'id': rid, 'error': {- 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}+ 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}if routed is not None:return await routed.dispatch(request)# Our own home: the scope is implicit for the strict session verbs, which refuse@@ -199,8 +246,9 @@ class AuthorityConnection:check_result(contract, result)return {'jsonrpc': '2.0', 'id': rid, 'result': result}except RuntimeStoreError as exc:+ _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)return {'jsonrpc': '2.0', 'id': rid, 'error': {- 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}+ 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}except sqlite3.Error:return {'jsonrpc': '2.0', 'id': rid, 'error': {'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}diff --git a/gateway/session_local_editor.py b/gateway/session_local_editor.pyindex bad74534b05..add6b904335 100644--- a/gateway/session_local_editor.py+++ b/gateway/session_local_editor.py@@ -7,13 +7,29 @@ from hermes_state_runtime import RuntimeStoreErrordef validate_editor(source, editor):+ """The launch's editor policy, or a refusal that names the key it read (create path totality).++ An ACP connection is a viewer; the policy itself lives with execution. Every branch below refuses+ with its own field, so a rejected editor launch says which key was wrong instead of a bare code.+ """if editor is None:return- if (source != 'acp' or not isinstance(editor, dict)- or set(editor) - {'mcp_servers', 'edit_approval_policy'}- or editor.get('edit_approval_policy', 'ask') != 'ask'- or not isinstance(editor.get('mcp_servers', []), list)):- raise RuntimeStoreError('invalid_params')+ if source != 'acp':+ raise RuntimeStoreError('invalid_params', field='editor',+ detail=f'an editor policy is only accepted from an ACP launch, not {source}')+ if not isinstance(editor, dict):+ raise RuntimeStoreError('invalid_params', field='editor',+ detail=f'must be a mapping, got {type(editor).__name__}')+ unknown = sorted(set(editor) - {'mcp_servers', 'edit_approval_policy'})+ if unknown:+ raise RuntimeStoreError('invalid_params', field=f'editor.{unknown[0]}',+ detail='unknown editor key')+ if editor.get('edit_approval_policy', 'ask') != 'ask':+ raise RuntimeStoreError('invalid_params', field='editor.edit_approval_policy',+ detail="must be 'ask': every edit is approved one at a time")+ if not isinstance(editor.get('mcp_servers', []), list):+ raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',+ detail=f'must be a list, got {type(editor.get("mcp_servers")).__name__}')from gateway.session_local_mcp import validate_serversvalidate_servers(editor.get('mcp_servers', []))diff --git a/gateway/session_local_mcp.py b/gateway/session_local_mcp.pyindex 559bd99fa6c..225c91a7fd1 100644--- a/gateway/session_local_mcp.py+++ b/gateway/session_local_mcp.py@@ -42,8 +42,15 @@ def validate_servers(servers):from acp.schema import McpServerStdio, McpServerHttp, McpServerSsefrom pydantic import ValidationErrorkinds = {'stdio': McpServerStdio, 'http': McpServerHttp, 'sse': McpServerSse}- if not isinstance(servers, list) or len(servers) > 16 or len(_json(servers)) > 65536:- raise RuntimeStoreError('invalid_params')+ if not isinstance(servers, list):+ raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',+ detail=f'must be a list, got {type(servers).__name__}')+ if len(servers) > 16:+ raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',+ detail=f'at most 16 servers, got {len(servers)}')+ if len(_json(servers)) > 65536:+ raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',+ detail='the serialized server list exceeds 65536 bytes')names = set()try:for spec in servers:@@ -53,7 +60,8 @@ def validate_servers(servers):raise ValueError('duplicate server')names.add(model.name)except (ValidationError, KeyError, AttributeError, TypeError, ValueError) as exc:- raise RuntimeStoreError('invalid_params') from exc+ raise RuntimeStoreError('invalid_params', field='editor.mcp_servers',+ detail=f'unusable server spec: {str(exc)[:120]}') from excdef private_editor_request(request, private):diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 6ae31807fc2..d3fdbf7319d 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -32,6 +32,16 @@ _TURN_PROFILE: ContextVar = ContextVar('follow_profile_read', default=None) # (SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp', 'tool': 'cli', 'oneshot': 'cli'}+def _refuse(field, detail=None):+ """One named refusal: the launch field the check read, and why it failed.++ ``reason`` stays the bounded wire code every caller compares as a string; ``field`` and+ ``detail`` are what tells ~20 different create checks apart, in the client and in the+ gateway log, without a second run to find out which one fired."""+ raise RuntimeStoreError('invalid_params', field=str(field)[:80],+ detail=None if detail is None else str(detail)[:160])++@dataclass(frozen=True)class LocalSessionPolicy:source: str@@ -263,23 +273,26 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,if source == 'a2a':from gateway.session_a2a import build_forward_policyreturn build_forward_policy(params, config, private_secrets=private_secrets)- if set(params) - CREATE_FIELDS or not isinstance(source, str) or source not in SURFACES:- raise RuntimeStoreError('invalid_params')- if any(name in params and type(params[name]) is not bool for name in BYPASS_FIELDS):- raise RuntimeStoreError('invalid_params')+ unknown = sorted(set(params) - CREATE_FIELDS)+ if unknown or not isinstance(source, str) or source not in SURFACES:+ _refuse(f'params.{unknown[0]}' if unknown else 'source',+ 'unknown create field' if unknown else f'not a surface: {source!r}')+ bad_bypass = next((name for name in BYPASS_FIELDS if name in params and type(params[name]) is not bool), None)+ if bad_bypass:+ _refuse(bad_bypass, 'must be a boolean')safe_mode = params.get('safe_mode', False)ignore_user_config = safe_mode or params.get('ignore_user_config', False)if 'api_key' in params and (not isinstance(params['api_key'], str) or not params['api_key'].strip()):- raise RuntimeStoreError('invalid_params')+ _refuse('api_key', 'must be a non-empty string')model = params.get('model')if 'model' in params and (not isinstance(model, str) or not model.strip()):- raise RuntimeStoreError('invalid_params')+ _refuse('model', 'must be a non-empty string')cwd = params.get('cwd', str(resolve_agent_cwd()))if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():- raise RuntimeStoreError('invalid_params')+ _refuse('cwd', 'must be an absolute path to an existing directory')row_cwd = params.get('row_cwd')if 'row_cwd' in params and (not isinstance(row_cwd, str) or (row_cwd and not Path(row_cwd).is_absolute())):- raise RuntimeStoreError('invalid_params')+ _refuse('row_cwd', 'must be an absolute path when set')if params.get('cwd_explicit') is False and 'cwd' in params:cwd = _profile_workspace_cwd(get_hermes_home()) or cwdfrom gateway.session_local_editor import validate_editor@@ -345,17 +358,18 @@ def _apply_launch_overrides(params, config):if key in params:value = params[key]if not isinstance(value, str) or not value.strip():- raise RuntimeStoreError('invalid_params')+ _refuse(key, 'must be a non-empty string')if key == 'base_url':url = urlsplit(value)if (url.scheme not in {'http', 'https'} or not url.hostnameor url.username or url.password or url.query or url.fragment):- raise RuntimeStoreError('invalid_params')+ _refuse('base_url', 'must be an http(s) URL without credentials, query or fragment')config.setdefault('model', {})[key] = value- for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config',- 'cwd_explicit', 'verbose'):- if flag in params and type(params[flag]) is not bool:- raise RuntimeStoreError('invalid_params')+ bad_flag = next((flag for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id',+ 'follow_profile_config', 'cwd_explicit', 'verbose')+ if flag in params and type(params[flag]) is not bool), None)+ if bad_flag:+ _refuse(bad_flag, 'must be a boolean')if 'service_tier' in params:# An explicit speed pick (Desktop Fast / Ultrafast / Normal): normal pins normal over a# profile tier; an unknown word is refused, never read as normal.@@ -365,14 +379,14 @@ def _apply_launch_overrides(params, config):except ValueError:tier = Noneif tier is None:- raise RuntimeStoreError('invalid_params')+ _refuse('service_tier', f"not a known tier: {params['service_tier']!r}")config.setdefault('agent', {})['service_tier'] = tier or 'normal'if 'run_budget' in params:# `--run-budget SECONDS`: the wall-clock budget per run (80% wrap-up notice, capped provider# timeouts), frozen as the session's `agent.run_budget_seconds` like main's CLI flag over config.value = params['run_budget']if isinstance(value, bool) or not isinstance(value, (int, float)) or not value > 0:- raise RuntimeStoreError('invalid_params')+ _refuse('run_budget', 'must be a positive number of seconds')config.setdefault('agent', {})['run_budget_seconds'] = float(value)if params.get('checkpoints'):section = config.get('checkpoints')@@ -384,11 +398,11 @@ def _apply_launch_overrides(params, config):value = params['max_turns']limit = resolve_turn_limit(value, default=0) if isinstance(value, (int, str)) else 0if not limit:- raise RuntimeStoreError('invalid_params')+ _refuse('max_turns', f'unreadable cap: {value!r}')config.setdefault('agent', {})['max_turns'] = limitif 'reasoning' in params:if not isinstance(params['reasoning'], str) or parse_reasoning_effort(params['reasoning']) is None:- raise RuntimeStoreError('invalid_params')+ _refuse('reasoning', f"not a known effort level: {params['reasoning']!r}")config.setdefault('agent', {})['reasoning_effort'] = params['reasoning']# An explicit launch level wins over a per-model default, just like CLI.config['agent'].pop('reasoning_overrides', None)@@ -402,9 +416,13 @@ def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False):from toolsets import validate_toolsetexplicit = params.get('toolsets')if 'toolsets' in params:- if (not isinstance(explicit, list) or any(not isinstance(x, str) or not validate_toolset(x) for x in explicit)- or ('desktop_ui' in explicit and source != 'gui')):- raise RuntimeStoreError('invalid_params')+ if not isinstance(explicit, list):+ _refuse('toolsets', f'must be a list of toolset names, got {type(explicit).__name__}')+ bad_toolset = next((x for x in explicit if not isinstance(x, str) or not validate_toolset(x)), None)+ if bad_toolset is not None:+ _refuse('toolsets', f'unknown or invalid toolset name: {bad_toolset!r}')+ if 'desktop_ui' in explicit and source != 'gui':+ _refuse('toolsets', f'desktop_ui is only available on the Desktop, not on {source}')config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicitposture = Noneif explicit is None and coding_posture:@@ -416,7 +434,7 @@ def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False):requested = {t for name in explicit for t in resolve_toolset(name)}effective = {t for name in enabled for t in resolve_toolset(name)}if not requested <= effective:- raise RuntimeStoreError('invalid_params')+ _refuse('toolsets', f"not available on this surface: {', '.join(sorted(requested - effective))}")if explicit is None and source in {'tui', 'gui'}:# Same surface toolsets as the native TUI factory, without its env inference.# The fold-in lands after _get_platform_tools subtracted agent.disabled_toolsets, so@@ -470,10 +488,11 @@ def launch_skills(params):"""The validated `-s/--skills` identifiers of a create request (empty when absent). Skillslive in the profile, which a bypass launch must never read: refused there, not dropped."""skills = params.get('skills', [])- if (('skills' in params and (not isinstance(skills, list) or not skills- or any(not isinstance(s, str) or not s.strip() for s in skills)))- or (skills and any(params.get(name) is True for name in BYPASS_FIELDS))):- raise RuntimeStoreError('invalid_params')+ if 'skills' in params and (not isinstance(skills, list) or not skills+ or any(not isinstance(s, str) or not s.strip() for s in skills)):+ _refuse('skills', 'must be a non-empty list of skill names')+ if skills and any(params.get(name) is True for name in BYPASS_FIELDS):+ _refuse('skills', 'a bypass launch never reads the profile, so skills cannot be preloaded')return [s.strip() for s in skills]@@ -584,7 +603,7 @@ def rebind_launch_key(authority, session, api_key):from agent.credential_persistence import fingerprint_secret_valuefrom gateway.config import Platformif not isinstance(api_key, str) or not api_key.strip():- raise RuntimeStoreError('invalid_params')+ _refuse('api_key', 'must be a non-empty string')source = authority.sessions[session.session_id].sourceif source is None or source.platform != Platform.LOCAL:raise RuntimeStoreError('admission_conflict')diff --git a/hermes_cli/cli_chat_error_copy.py b/hermes_cli/cli_chat_error_copy.pyindex d9ca5171061..7457456d83d 100644--- a/hermes_cli/cli_chat_error_copy.py+++ b/hermes_cli/cli_chat_error_copy.py@@ -33,6 +33,22 @@ def _short(text: str, limit: int = _SUMMARY_LIMIT) -> str:return first if len(first) <= limit else first[: limit - 1].rstrip() + "…"+def refusal_text(error: BaseException | str) -> str:+ """The refusal as the client shows it: the reason code, plus the check that fired when the owner+ named one (``invalid_params (toolsets: unknown or invalid toolset name: 'mcp-codegraph')``).++ The gateway sends ``field``/``detail`` in the JSON-RPC error's ``data``+ (``gateway/session_controls.py``), and ``hermes_cli.gateway_client.rpc_error`` carries the+ bounded scalars onto ``GatewayRPCError.data``. A refusal from anywhere else has no ``data`` and+ reads exactly as before."""+ data = getattr(error, "data", None)+ data = data if isinstance(data, dict) else {}+ field, detail = str(data.get("field") or "").strip(), str(data.get("detail") or "").strip()+ if not field and not detail:+ return str(error)+ return f"{error} ({field or 'unnamed field'}{': ' + detail if detail else ''})"++def chat_error_response(error: Exception | str, *, provider: str = "", model: str = "", failure_reason: str | None = None,) -> str:@@ -60,9 +76,9 @@ def chat_error_response(provider=provider or t("cli.error.the_provider"),model=model or t("cli.error.the_current_model"),)- return t("cli.error.with_details", lead=lead, details=_short(str(error), 300))+ return t("cli.error.with_details", lead=lead, details=_short(refusal_text(error), 300))def agent_init_failure_message(error: BaseException) -> str:"""Copy for a failed AIAgent build on first message: the user's turn was dropped."""- return t("cli.error.agent_init_failed", error=_short(str(error)) or type(error).__name__)+ return t("cli.error.agent_init_failed", error=_short(refusal_text(error)) or type(error).__name__)diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex daa942e2fea..55fccbf3c73 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -14,8 +14,14 @@ from hermes_state_keys import admission_fingerprintclass RuntimeStoreError(ValueError):- def __init__(self, reason: str):+ """A refusal by the state authority. ``reason`` is the bounded wire code (callers compare it as a+ string); ``field`` and ``detail`` name the check that fired and why, so a client and the gateway+ log can tell the reasons' many checks apart instead of reporting the bare code."""++ def __init__(self, reason: str, *, field: str | None = None, detail: str | None = None):self.reason = reason+ self.field = field+ self.detail = detailsuper().__init__(reason)diff --git a/tests/gateway/test_session_policy_refusal_fields.py b/tests/gateway/test_session_policy_refusal_fields.pynew file mode 100644index 00000000000..29246d61956--- /dev/null+++ b/tests/gateway/test_session_policy_refusal_fields.py@@ -0,0 +1,224 @@+"""Every create refusal names the check that fired.++``session.create`` refused with a bare ``invalid_params`` cost three reports in one morning+(#138670, #138748, #134889): the gateway logged nothing and the client printed the code alone, so+neither the reporter nor the maintainer could tell which of the ~20 checks had rejected the launch.+These tests pin the naming at the policy, at the wire frame, in the gateway log, and in the CLI+copy that a user actually reads.+"""+import ast+from pathlib import Path+from types import SimpleNamespace++import pytest++from gateway.session_policy import build_policy, rebind_launch_key+from hermes_state_runtime import RuntimeStoreError++_CFG = {'platform_toolsets': {'cli': ['terminal']}}+++def _refusal(params, cfg=None, **kwargs):+ """The ``RuntimeStoreError`` a real ``build_policy`` raises for *params*."""+ with pytest.raises(RuntimeStoreError) as caught:+ build_policy(params, cfg if cfg is not None else dict(_CFG), **kwargs)+ return caught.value++[email protected]('extra, field', [+ ({'bogus': 1}, 'params.bogus'), # an unknown create field+ ({'source': 'nope'}, 'source'), # not a known surface+ ({'source': 'cli', 'safe_mode': 'yes'}, 'safe_mode'),+ ({'source': 'cli', 'ignore_user_config': 1}, 'ignore_user_config'),+ ({'source': 'cli', 'api_key': ' '}, 'api_key'),+ ({'source': 'cli', 'model': ' '}, 'model'),+ ({'source': 'cli', 'cwd': 'relative/place'}, 'cwd'),+ ({'source': 'cli', 'row_cwd': 'relative/place'}, 'row_cwd'),+ ({'source': 'cli', 'provider': ''}, 'provider'),+ ({'source': 'cli', 'base_url': 'ftp://example.invalid'}, 'base_url'),+ ({'source': 'cli', 'yolo': 'yes'}, 'yolo'),+ ({'source': 'cli', 'verbose': 'yes'}, 'verbose'),+ ({'source': 'cli', 'service_tier': 'instant'}, 'service_tier'),+ ({'source': 'cli', 'run_budget': -1}, 'run_budget'),+ ({'source': 'cli', 'max_turns': 'soon'}, 'max_turns'),+ ({'source': 'cli', 'reasoning': 'galaxy'}, 'reasoning'),+ ({'source': 'cli', 'toolsets': 'terminal'}, 'toolsets'), # not a list+ ({'source': 'cli', 'toolsets': ['terminal', 'gone_plugin']}, 'toolsets'), # unknown name+ ({'source': 'cli', 'toolsets': ['desktop_ui']}, 'toolsets'), # Desktop-only+ ({'source': 'cli', 'skills': []}, 'skills'), # empty list+ ({'source': 'cli', 'skills': ['porting'], 'safe_mode': True}, 'skills'), # bypass launch+ ({'source': 'cli', 'editor': {}}, 'editor'), # ACP-only launch key+ ({'source': 'acp', 'editor': {'bogus': 1}}, 'editor.bogus'),+ ({'source': 'acp', 'editor': {'edit_approval_policy': 'always'}}, 'editor.edit_approval_policy'),+ ({'source': 'acp', 'editor': {'mcp_servers': 'terminal'}}, 'editor.mcp_servers'),+ ({'source': 'acp', 'editor': {'mcp_servers': [{'type': 'stdio'}]}}, 'editor.mcp_servers'),+])+def test_every_create_check_names_the_field_it_read(tmp_path, extra, field):+ refusal = _refusal({'cwd': str(tmp_path), **extra})+ assert refusal.reason == 'invalid_params'+ assert refusal.field == field, refusal.detail+ assert refusal.detail, 'a refusal names why, not only which field'+++def test_the_unknown_field_is_named_with_its_own_key(tmp_path):+ """A closed key set reports the key that broke it, not the set."""+ refusal = _refusal({'cwd': str(tmp_path), 'toolsets_extra': 1})+ assert refusal.field == 'params.toolsets_extra'+++def test_an_invalid_toolset_name_reports_that_name(tmp_path):+ refusal = _refusal({'cwd': str(tmp_path), 'toolsets': ['terminal', 'gone_plugin']})+ assert 'gone_plugin' in refusal.detail+++def test_a_rebound_launch_key_names_api_key():+ """``session.resume`` re-supplying a launch key refuses before it touches the authority."""+ with pytest.raises(RuntimeStoreError) as caught:+ rebind_launch_key(object(), object(), ' ')+ assert (caught.value.field, caught.value.reason) == ('api_key', 'invalid_params')+++def test_a_clean_launch_still_builds(tmp_path):+ """The naming must not turn a valid launch into a refusal."""+ policy = build_policy({'source': 'cli', 'cwd': str(tmp_path), 'model': 'fixture'}, dict(_CFG))+ assert policy.cwd == str(tmp_path)+++def test_the_reason_code_is_unchanged_on_the_wire():+ """Callers compare ``str(exc)`` to reason codes; naming may not move it."""+ exc = RuntimeStoreError('invalid_params', field='cwd', detail='nope')+ assert str(exc) == 'invalid_params' and exc.reason == 'invalid_params'+++def test_no_bare_invalid_params_raise_on_the_create_path():+ """A new create check must name its field and why: this guard fails instead of the next report.++ The create path reads launch parameters in three modules: the policy builder, the editor policy and+ the MCP server list. The last one is scanned at function scope, because the same module's mutate+ path (``session.mutate editor_mcp``, a branch carrying servers) still refuses with the bare code —+ a separate, off-path pass."""+ scanned = [('gateway/session_policy.py', None), ('gateway/session_local_editor.py', None),+ ('gateway/session_local_mcp.py', 'validate_servers')]+ root = Path(__file__).resolve().parents[2]+ bare, thin = [], []+ for module, function in scanned:+ tree = ast.parse((root / module).read_text(encoding='utf-8'))+ nodes = tree.body+ if function is not None:+ nodes = [node for node in tree.body+ if isinstance(node, ast.FunctionDef) and node.name == function]+ assert nodes, f'{function} not found in {module}'+ for top in nodes:+ for node in ast.walk(top):+ if not isinstance(node, ast.Call):+ continue+ called = node.func+ name = getattr(called, 'id', None) or getattr(called, 'attr', None)+ if name == '_refuse' and not (len(node.args) >= 2 or node.keywords):+ thin.append(f'{module}:{node.lineno}') # a field with no reason is half a diagnosis+ first = node.args[0] if node.args else None+ if (name == 'RuntimeStoreError' and isinstance(first, ast.Constant)+ and first.value == 'invalid_params' and not node.keywords):+ bare.append(f'{module}:{node.lineno}')+ assert bare == [], f'unnamed invalid_params refusals on the create path: {bare}'+ assert thin == [], f'_refuse() calls without a detail: {thin}'+++def test_the_profile_in_the_log_line_is_a_name_not_a_home_path(tmp_path, caplog):+ """A root profile is keyed by its home path; the log line carries its name, never the path."""+ from gateway.session_controls import _log_refusal, _profile_label++ assert _profile_label('test') == 'test'+ assert _profile_label(None) == 'default'+ assert _profile_label(str(tmp_path)) == 'default'+ with caplog.at_level('WARNING', logger='gateway.session_controls'):+ _log_refusal(str(tmp_path), 'session.create',+ RuntimeStoreError('invalid_params', field='cwd', detail='not a directory'))+ line = caplog.records[-1].getMessage()+ assert 'profile=default' in line and str(tmp_path) not in line, line+++async def test_the_frame_carries_the_field_and_the_gateway_logs_it(tmp_path, caplog):+ """What a report can quote: the JSON-RPC ``error.data`` and one gateway log line."""+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ from hermes_state import SessionDB+ from hermes_state_runtime import begin_runtime_epoch++ detail = "unknown or invalid toolset name: 'gone_plugin'"+ db = SessionDB(db_path=tmp_path / 'state.db')+ try:+ epoch = begin_runtime_epoch(db, instance_id='test')+ authority = SessionAuthority(SimpleNamespace(), profile_id='test', instance_id='test',+ db=db, epoch=epoch)++ class Connection(AuthorityConnection):+ def handlers(self):+ async def probe(ref, params):+ raise RuntimeStoreError('invalid_params', field='toolsets', detail=detail)+ return {'session.policy_probe': probe}++ connection = Connection(authority, object(), {'user_id': 'human'})+ with caplog.at_level('WARNING', logger='gateway.session_controls'):+ reply = await connection.dispatch({'id': 7, 'method': 'session.policy_probe', 'params': {}})+ assert reply['error']['message'] == 'invalid_params'+ assert reply['error']['data'] == {'reason': 'invalid_params', 'field': 'toolsets', 'detail': detail}+ logged = [record.getMessage() for record in caplog.records]+ assert any('field=toolsets' in line and 'session.policy_probe' in line and 'profile=test' in line+ for line in logged), logged+ finally:+ db.close()+++async def test_a_bare_refusal_does_not_warn(tmp_path, caplog):+ """A retrying client must not be able to flood the log: only a named refusal is a warning."""+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ from hermes_state import SessionDB+ from hermes_state_runtime import begin_runtime_epoch++ db = SessionDB(db_path=tmp_path / 'state.db')+ try:+ epoch = begin_runtime_epoch(db, instance_id='test')+ authority = SessionAuthority(SimpleNamespace(), profile_id='test', instance_id='test',+ db=db, epoch=epoch)++ class Connection(AuthorityConnection):+ def handlers(self):+ async def probe(ref, params):+ raise RuntimeStoreError('permission_denied')+ return {'session.unnamed_probe': probe}++ connection = Connection(authority, object(), {'user_id': 'human'})+ with caplog.at_level('DEBUG', logger='gateway.session_controls'):+ reply = await connection.dispatch({'id': 8, 'method': 'session.unnamed_probe', 'params': {}})+ assert reply['error']['data'] == {'reason': 'permission_denied'}+ levels = {record.levelname for record in caplog.records}+ assert 'WARNING' not in levels, [r.getMessage() for r in caplog.records]+ assert 'DEBUG' in levels+ finally:+ db.close()+++def test_the_cli_copy_names_the_field_a_user_reads():+ """The panel line said ``invalid_params`` alone; it now carries the check (#138748)."""+ from hermes_cli.cli_chat_error_copy import agent_init_failure_message+ from hermes_cli.gateway_client import GatewayRPCError++ exc = GatewayRPCError('invalid_params', 4001, {+ 'reason': 'invalid_params', 'field': 'toolsets',+ 'detail': "unknown or invalid toolset name: 'gone_plugin'"})+ message = agent_init_failure_message(exc)+ assert 'invalid_params' in message and 'toolsets' in message+++def test_a_refusal_without_a_named_field_reads_exactly_as_before():+ """Refusals raised elsewhere keep their copy: no empty parentheses on the panel."""+ from hermes_cli.cli_chat_error_copy import agent_init_failure_message+ from hermes_cli.gateway_client import GatewayRPCError++ message = agent_init_failure_message(GatewayRPCError('storage_unavailable', 5001,+ {'reason': 'storage_unavailable'}))+ assert message.count('storage_unavailable') == 1 and '(' not in message