The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: route claimed Kanban tasks through trusted owner admission
Teknium5aeba055f282
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pynew file mode 100644index 00000000000..097bb0fe159--- /dev/null+++ b/gateway/session_kanban.py@@ -0,0 +1,162 @@+"""Trusted dispatcher claims enter the ordinary owner's durable admission queue."""+from contextlib import closing+from dataclasses import asdict, replace+import json+from pathlib import Path+import sqlite3++from hermes_state_runtime import RuntimeStoreError+++def build_kanban_policy(connection, params, config):+ from hermes_cli import kanban_db as kb+ from hermes_cli.profiles import resolve_profile_env+ from gateway.session_policy import build_policy+ authority, actor = connection.authority, connection.actor+ if not connection.native_owner or 'session:create' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ if actor.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if (set(params) != {'board', 'task_id', 'run_id', 'claim_lock'}+ or any(not isinstance(params[k], str) or not params[k] for k in ('board', 'task_id', 'claim_lock'))+ or type(params['run_id']) is not int):+ raise RuntimeStoreError('invalid_params')+ try:+ board = kb._require_slug(params['board'])+ path = kb.kanban_db_path(board=board).resolve()+ with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as conn:+ conn.row_factory = sqlite3.Row+ task = kb.get_task(conn, params['task_id'])+ run = conn.execute('SELECT * FROM task_runs WHERE id=?', (params['run_id'],)).fetchone()+ if (task is None or run is None or task.status != 'running' or run['status'] != 'running'+ or task.current_run_id != params['run_id'] or run['task_id'] != task.id+ or task.claim_lock != params['claim_lock'] or run['claim_lock'] != task.claim_lock):+ raise RuntimeStoreError('stale_kanban_claim')+ if Path(resolve_profile_env(task.assignee)).resolve() != Path(authority.profile_id).resolve():+ raise RuntimeStoreError('profile_mismatch')+ context = kb.build_worker_context(conn, task.id)+ except (ValueError, OSError, sqlite3.Error) as exc:+ raise RuntimeStoreError('invalid_kanban_claim') from exc+ cwd = task.workspace_path+ params_policy = {'source': 'cli', 'cwd': cwd}+ for name, value in (('model', task.model_override), ('provider', task.provider_override), ('reasoning', task.reasoning_effort)):+ if value:+ params_policy[name] = value+ private = {}+ policy = build_policy(params_policy, config, private_secrets=private)+ if policy.model is None:+ from gateway.run import _resolve_gateway_model+ policy = replace(policy, model=_resolve_gateway_model(policy.config()))+ context = dict(params, db=str(path), workspace=cwd, branch=task.branch_name, tenant=task.tenant,+ profile=task.assignee, workspaces_root=str(kb.workspaces_root(board=board).resolve()),+ skills=list(task.skills or ()), goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,+ goal_text='\n\n'.join(p for p in (task.title, task.body) if p), context=context,+ max_runtime_seconds=task.max_runtime_seconds, accept_hooks=True)+ request = json.loads(policy.request_json)+ request.update(source='kanban', board=board, task_id=task.id, run_id=task.current_run_id)+ return replace(policy, source='kanban', platform='cli', toolsets=tuple(sorted(set(policy.toolsets) | {'kanban'})),+ request_json=json.dumps(request, sort_keys=True), kanban_json=json.dumps(context)), private+++async def run_task(connection, params):+ if not connection.native_owner or 'session:create' not in connection.actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ from gateway.run import _load_gateway_config+ from gateway.session_local import create_local_session+ from gateway.session_contract import Submission+ from gateway.session_local_recovery import local_identity+ from hermes_state_local import local_receipt+ from gateway.session_policy import restore_policy+ authority = connection.authority+ # The dispatcher attempt is the durable request identity, including after the+ # task closes. Retry checks the saved claim, never reinterprets updated cards.+ request_id = 'kanban:' + json.dumps([params.get('board'), params.get('task_id'), params.get('run_id')], separators=(',', ':'))+ sid = local_identity(authority.profile_id, connection.actor.subject, request_id)+ saved = local_receipt(authority.db, sid) if authority.db.get_session(sid) is not None else None+ if saved:+ policy = restore_policy(saved['policy'])+ context = json.loads(policy.kanban_json or '{}')+ if (not connection.native_owner or set(params) != {'board', 'task_id', 'run_id', 'claim_lock'}+ or any(params[k] != context.get(k) for k in params)):+ raise RuntimeStoreError('permission_denied')+ from gateway.session_local_recovery import restore_local_session+ ref = restore_local_session(authority, sid)+ else:+ policy, private = build_kanban_policy(connection, params, _load_gateway_config())+ ref = create_local_session(authority, connection.actor, {'request_id': request_id},+ trusted_policy=policy, trusted_secrets=private)+ await connection.resume(ref, {})+ receipt = await authority.submit(connection.actor, Submission(request_id, ref,+ {'text': f'work kanban task {params["task_id"]}'}, 'queue'))+ return {'session_id': ref.session_id, 'receipt': asdict(receipt)}+++def bind_worker_context(frame):+ """Only the adopted private exec calls this, before tool discovery imports."""+ import os+ context = json.loads(frame['policy'].get('kanban_json') or 'null')+ if context is None:+ return+ if frame['policy']['source'] != 'kanban':+ raise ValueError('invalid_kanban_policy')+ env = {'HERMES_KANBAN_TASK': context['task_id'], 'HERMES_KANBAN_BOARD': context['board'],+ 'HERMES_KANBAN_DB': context['db'], 'HERMES_KANBAN_RUN_ID': str(context['run_id']),+ 'HERMES_KANBAN_CLAIM_LOCK': context['claim_lock'], 'HERMES_KANBAN_WORKSPACE': context['workspace'],+ 'HERMES_KANBAN_WORKSPACES_ROOT': context['workspaces_root'], 'HERMES_PROFILE': context['profile'],+ 'HERMES_SESSION_SOURCE': 'kanban'}+ for key, value in (('HERMES_KANBAN_BRANCH', context['branch']), ('HERMES_TENANT', context['tenant'])):+ if value:+ env[key] = value+ if context['goal_mode']:+ env['HERMES_KANBAN_GOAL_MODE'] = '1'+ from hermes_cli.kanban_db_dispatch import _worker_terminal_timeout_env+ for key in ('TERMINAL_TIMEOUT', 'TERMINAL_MAX_FOREGROUND_TIMEOUT'):+ value = _worker_terminal_timeout_env(context['max_runtime_seconds'], os.environ.get(key))+ if value:+ env[key] = value+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ with connect_closing(Path(context['db'])) as conn:+ with kb.write_txn(conn):+ task = kb.get_task(conn, context['task_id'])+ if (task is None or task.status != 'running' or task.current_run_id != context['run_id']+ or task.claim_lock != context['claim_lock']):+ raise RuntimeStoreError('stale_kanban_claim')+ # Reclaim/timeout must track the executing interpreter, not its disposable viewer.+ conn.execute('UPDATE tasks SET worker_pid=? WHERE id=?', (os.getpid(), task.id))+ conn.execute('UPDATE task_runs SET worker_pid=? WHERE id=?', (os.getpid(), context['run_id']))+ os.environ.update(env)+ os.chdir(context['workspace'])+ from agent.shell_hooks import register_from_config+ register_from_config(json.loads(frame['policy']['config_json']), accept_hooks=context['accept_hooks'])+++def run_worker_turns(agent, frame, history):+ context = json.loads(frame['policy'].get('kanban_json') or 'null')+ if context is None:+ return agent.run_conversation(frame['text'], conversation_history=history)+ from agent.skill_commands import build_preloaded_skills_prompt+ skills, loaded, missing = build_preloaded_skills_prompt(context['skills'], task_id=agent.session_id)+ if missing and not loaded:+ raise ValueError('kanban_skills_unavailable')+ prompt = '\n\n'.join(p for p in (skills, context['context'], frame['text']) if p)+ result = agent.run_conversation(prompt, conversation_history=history)+ if not context['goal_mode']:+ return result+ from hermes_cli.goals import run_kanban_goal_loop, DEFAULT_MAX_TURNS+ from hermes_cli import kanban_db as kb+ from hermes_cli.kanban_db_connect import connect_closing+ def status():+ with connect_closing() as conn:+ return kb.goal_run_status(conn, context['task_id'], context['run_id'])+ def block(reason):+ with connect_closing() as conn:+ kb.block_task(conn, context['task_id'], reason=reason, expected_run_id=context['run_id'])+ def turn(prompt):+ nonlocal result+ result = agent.run_conversation(prompt, conversation_history=agent._session_db.get_messages_as_conversation(agent.session_id))+ return result.get('final_response', '')+ run_kanban_goal_loop(task_id=context['task_id'], goal_text=context['goal_text'], run_turn=turn,+ task_status_fn=status, block_fn=block, max_turns=context['goal_max_turns'] or DEFAULT_MAX_TURNS,+ first_response=result.get('final_response', ''))+ return resultdiff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 5876caaa161..13505aa71a3 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -2084,43 +2084,9 @@ def _retag_legacy_worker_sessions(workspaces_root_path: str) -> None:def _worker_argv(task: Task, profile_arg: str, hermes_home: Optional[str]) -> list[str]:- """Build the ``hermes -p <profile> --cli ... chat -q ...`` worker command."""- cmd = [- *_resolve_hermes_argv(),- "-p", profile_arg,- # A worker must NEVER boot the interactive TUI: its no-TTY bail-out- # exits 0 without doing the task → "protocol violation" every attempt.- "--cli",- # Workers run under a profile-scoped HERMES_HOME and so see that- # profile's shell-hook allowlist; pass --accept-hooks explicitly so- # configured hooks still register.- "--accept-hooks",- ]- # One `--skills X` pair per name: easier to read in `ps` and avoids quoting- # ambiguity if a skill name contains unusual chars.- for sk in task.skills or ():- if sk:- cmd.extend(["--skills", sk])- if task.model_override:- cmd.extend(["-m", task.model_override])- # Pin the provider too so the worker resolves the model against the- # intended backend (model X with provider Y is the classic board-stall).- if task.provider_override:- cmd.extend(["--provider", task.provider_override])- # Independent of the model override — a task can run the profile's own- # model at a different depth.- if task.reasoning_effort:- cmd.extend(["--reasoning", task.reasoning_effort])- worker_toolsets = _resolve_worker_cli_toolsets(hermes_home)- if worker_toolsets:- cmd.extend(["--toolsets", ",".join(worker_toolsets)])- cmd.extend(["chat", "-q", f"work kanban task {task.id}"])- if task.goal_mode:- # The kanban goal-loop hook only runs in cli.py's fully-quiet branch.- # Without -Q the worker gets one turn, prints text, exits rc=0, and the- # dispatcher records a protocol violation.- cmd.append("-Q")- return cmd+ """The profile owner executes; this subprocess only waits for its receipt."""+ import sys+ return [sys.executable, "-m", "hermes_cli.kanban_worker_client"]def _open_worker_log(task: Task, board: Optional[str]):@@ -2239,7 +2205,6 @@ def _default_spawn(task: Task, workspace: str, *, board: Optional[str] = None) -# match after `hermes -p` rewrites HERMES_HOME (symlink / Docker layouts).env["HERMES_KANBAN_DB"] = str(_kb.kanban_db_path(board=board))env["HERMES_KANBAN_WORKSPACES_ROOT"] = str(_kb.workspaces_root(board=board))- _retag_legacy_worker_sessions(env["HERMES_KANBAN_WORKSPACES_ROOT"])# Board slug — defense-in-depth pin if a path is resolved without the# DB / workspaces env vars.env["HERMES_KANBAN_BOARD"] = _kb._normalize_board_slug(board) or _kb.get_current_board()diff --git a/hermes_cli/kanban_worker_client.py b/hermes_cli/kanban_worker_client.pynew file mode 100644index 00000000000..76ec172760e--- /dev/null+++ b/hermes_cli/kanban_worker_client.py@@ -0,0 +1,40 @@+"""Dispatcher subprocess: submit one claim to its profile owner; never run an agent."""+import asyncio+import os+import sys+++async def run(params):+ from hermes_cli.gateway_client import connect_gateway, GatewayClientError+ if os.environ.get('HERMES_TUI_GATEWAY_URL'):+ raise GatewayClientError('Kanban requires the assigned local profile owner')+ async with connect_gateway() as client:+ accepted = await client.rpc('kanban.run', **params)+ sid, receipt = accepted['session_id'], accepted['receipt']+ print(f'Session: {sid}', file=sys.stderr)+ while receipt['status'] not in {'terminal', 'unknown'}:+ await asyncio.sleep(.2)+ receipt = await client.rpc('prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])+ if receipt['status'] == 'unknown':+ raise GatewayClientError('Kanban execution unknown; retained by owner')+ return 0 if receipt.get('outcome') == 'completed' else 1+++def main():+ try:+ params = {'board': os.environ['HERMES_KANBAN_BOARD'], 'task_id': os.environ['HERMES_KANBAN_TASK'],+ 'run_id': int(os.environ['HERMES_KANBAN_RUN_ID']), 'claim_lock': os.environ['HERMES_KANBAN_CLAIM_LOCK']}+ # Owner startup must never inherit this worker's task/tool/goal identity.+ for key in list(os.environ):+ if key.startswith('HERMES_KANBAN_') and key != 'HERMES_KANBAN_HOME':+ os.environ.pop(key)+ for key in ('HERMES_SESSION_SOURCE', 'HERMES_TENANT', 'TERMINAL_CWD'):+ os.environ.pop(key, None)+ return asyncio.run(run(params))+ except (KeyError, ValueError, OSError) as exc:+ print(f'Kanban owner refused: {exc}', file=sys.stderr)+ return 1+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/tests/gateway/fixtures/kanban_owner_probe.py b/tests/gateway/fixtures/kanban_owner_probe.pynew file mode 100644index 00000000000..d827c1d2018--- /dev/null+++ b/tests/gateway/fixtures/kanban_owner_probe.py@@ -0,0 +1,125 @@+"""Actual dispatcher argv, ordinary daemon, loopback tool round, disposable board."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import subprocess+import sys+import threading++from local_recovery_probe import daemon, websocket, rpc+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ if messages:+ self.server.requests.append(body)+ has_result = any(m['role'] == 'tool' for m in messages)+ message = {'role': 'assistant', 'content': 'OWNED_COMPLETE'}+ finish = 'stop'+ if messages and not body.get('tools'):+ message['content'] = json.dumps({'verdict': 'done', 'reason': 'Owned acceptance satisfied'})+ elif messages and (not has_result or messages[-1]['role'] == 'user'):+ continuation = has_result+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{'index': 0, 'id': 'owned-complete',+ 'type': 'function', 'function': {'name': 'kanban_complete' if continuation else 'kanban_comment', 'arguments': json.dumps({'summary': 'Owned probe complete'} if continuation else {'body': 'Owned first turn'})}}]}+ finish = 'tool_calls'+ payload = json.dumps({'id': 'owned', 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()+ kind = 'application/json'+ if body.get('stream'):+ payload = ('data: ' + json.dumps({'id': 'owned', 'choices': [{'index': 0, 'delta': message, 'finish_reason': finish}]}) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+++def main():+ root = Path(__file__).resolve().parents[3]+ home = Path(os.environ['HERMES_HOME'])+ home.mkdir(parents=True, exist_ok=True)+ Path(os.environ['HOME']).mkdir(parents=True, exist_ok=True)+ os.environ['HERMES_KANBAN_HOME'] = str(home)+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ workspace = home / 'workspace'+ workspace.mkdir(exist_ok=True)+ skill = home / 'skills' / 'owned-skill'+ skill.mkdir(parents=True)+ (skill / 'SKILL.md').write_text('---\nname: owned-skill\ndescription: Owned fixture\n---\nKANBAN_SKILL_SENTINEL\n', encoding='utf-8')+ hook = home / 'hook.py'+ hook.write_text('from pathlib import Path\nPath(' + repr(str(home / 'hook-effect')) + ').write_text("accepted")\n', encoding='utf-8')+ cfg = {'gateway': {'multiplex_profiles': False}, 'model': {'provider': 'custom', 'default': 'loop-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': ['terminal', 'file']},+ 'terminal': {'backend': 'local'}, 'kanban': {'dispatch_in_gateway': False},+ 'hooks': {'post_tool_call': [{'command': f'{sys.executable} {hook}'}]}}+ (home / 'config.yaml').write_text(json.dumps(cfg), encoding='utf-8')+ from hermes_cli import kanban_db as kb+ from hermes_cli.kanban_db_connect import connect+ from hermes_cli import kanban_db_dispatch as dispatch+ # Pin the installed launcher to this checkout for base/fixed argv comparisons.+ dispatch._resolve_hermes_argv = lambda: [sys.executable, '-m', 'hermes_cli.main']+ _worker_argv = dispatch._worker_argv+ with closing(connect(board='owned')) as conn:+ tid = kb.create_task(conn, title='KANBAN_TASK_SENTINEL', body='Acceptance: finish owned card', assignee='default',+ workspace_kind='dir', workspace_path=str(workspace), skills=['owned-skill'], goal_mode=True, goal_max_turns=2)+ kb.recompute_ready(conn)+ task = kb.claim_task(conn, tid)+ env = dict(os.environ)+ worker_env = env | {'HERMES_KANBAN_TASK': tid, 'HERMES_KANBAN_BOARD': 'owned',+ 'HERMES_KANBAN_RUN_ID': str(task.current_run_id), 'HERMES_KANBAN_CLAIM_LOCK': task.claim_lock,+ 'HERMES_KANBAN_DB': str(kb.kanban_db_path(board='owned'))}+ params = dict(task_id=tid, board='owned', run_id=task.current_run_id, claim_lock=task.claim_lock)+ receipt = {}+ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ command = _worker_argv(task, 'default', str(home))+ if os.environ.get('KANBAN_PROBE_TRACE'):+ command = ['strace', '-f', '-e', 'trace=openat', '-o', str(home / 'client.strace'), *command]+ result = subprocess.run(command, cwd=workspace, env=worker_env,+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=80)+ receipt.update(worker_rc=result.returncode, stdout=result.stdout, stderr=result.stderr)+ assert result.returncode == 0, receipt+ async def retry():+ async with websocket(home, desc) as ws:+ first = await rpc(ws, 'kanban.run', **params)+ second = await rpc(ws, 'kanban.run', **params)+ assert 'result' in first and 'result' in second, (first, second)+ return first['result']['session_id'], first['result']['session_id'] == second['result']['session_id']+ sid, same = asyncio.run(retry())+ import sqlite3+ with closing(sqlite3.connect((home / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:+ receipt['source'] = db.execute('SELECT source FROM sessions WHERE id=?', (sid,)).fetchone()[0]+ receipt['admissions'] = db.execute('SELECT count(*) FROM session_admissions').fetchone()[0]+ with closing(connect(board='owned')) as conn:+ receipt['task_status'] = kb.get_task(conn, tid).status+ wire = json.dumps(peer.requests)+ turns = [r for r in peer.requests if r.get('tools')]+ prefixes = [json.dumps([m for m in r['messages'] if m['role'] in {'system', 'developer'}]) for r in turns]+ receipt.update(goal_continuation=len(turns) >= 4, stable_prefix=len(set(prefixes)) == 1,+ retry_same_session=same, tools='kanban_complete' in wire,+ task_context='KANBAN_TASK_SENTINEL' in wire, skill_context='KANBAN_SKILL_SENTINEL' in wire,+ hook_effect=(home / 'hook-effect').exists())+ finally:+ peer.shutdown()+ peer.server_close()+ (home / 'model-requests.json').write_text(json.dumps(peer.requests, indent=2), encoding='utf-8')+ (home / 'receipt.json').write_text(json.dumps(receipt, indent=2), encoding='utf-8')+ print(json.dumps(receipt))+++if __name__ == '__main__':+ main()diff --git a/tests/gateway/test_session_kanban.py b/tests/gateway/test_session_kanban.pynew file mode 100644index 00000000000..388f82cb14c--- /dev/null+++ b/tests/gateway/test_session_kanban.py@@ -0,0 +1,69 @@+"""Task claims, not caller-supplied launch policy, authorize Kanban execution."""+import json+from pathlib import Path+from types import SimpleNamespace++import pytest+++def test_claim_freezes_task_policy_and_rejects_forgery(tmp_path, monkeypatch):+ from hermes_cli import kanban_db as kb+ from hermes_cli.kanban_db_connect import connect+ from gateway.session_contract import Principal+ from hermes_state_runtime import RuntimeStoreError+ monkeypatch.setenv('HERMES_KANBAN_HOME', str(tmp_path))+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setenv('HOME', str(tmp_path / 'home'))+ monkeypatch.delenv('HERMES_KANBAN_DB', raising=False)+ monkeypatch.delenv('HERMES_DELEGATED_CHILD', raising=False)+ monkeypatch.setattr('hermes_cli.profiles.resolve_profile_env', lambda name: str(tmp_path) if name == 'default' else str(tmp_path / name))+ workspace = tmp_path / 'workspace'+ workspace.mkdir()+ from contextlib import closing+ with closing(connect(board='owned')) as conn:+ task_id = kb.create_task(conn, title='Owned acceptance', body='Goal criteria', assignee='default',+ workspace_kind='dir', workspace_path=str(workspace), skills=['owned-skill'], goal_mode=True,+ goal_max_turns=3, model_override='loop-model', provider_override='custom')+ kb.recompute_ready(conn)+ task = kb.claim_task(conn, task_id)+ actor = Principal('owner', str(tmp_path), frozenset({'session:create'}), 'transport')+ connection = SimpleNamespace(authority=SimpleNamespace(profile_id=str(tmp_path)), actor=actor, native_owner=True)+ params = dict(board='owned', task_id=task.id, run_id=task.current_run_id, claim_lock=task.claim_lock)+ from gateway.session_kanban import build_kanban_policy+ config = {'model': {'default': 'loop-model', 'provider': 'custom'}, 'platform_toolsets': {'cli': ['terminal', 'file']}}+ policy, secrets = build_kanban_policy(connection, params, config)+ context = json.loads(policy.kanban_json)+ assert policy.source == 'kanban' and policy.cwd == str(workspace)+ assert policy.model == task.model_override and policy.provider == task.provider_override+ assert {'kanban', 'terminal', 'file'} <= set(policy.toolsets)+ assert context['task_id'] == task.id and context['run_id'] == task.current_run_id+ assert context['board'] == 'owned' and context['claim_lock'] == task.claim_lock+ assert context['skills'] == ['owned-skill'] and context['goal_mode'] and context['goal_max_turns'] == 3+ assert context['accept_hooks'] is True and 'Goal criteria' in context['goal_text']+ for changed in ({'run_id': task.current_run_id + 1}, {'board': 'foreign'}, {'claim_lock': 'forged'}, {'cwd': '/tmp'}):+ with pytest.raises(RuntimeStoreError):+ build_kanban_policy(connection, params | changed, config)+ connection.native_owner = False+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ build_kanban_policy(connection, params, config)+ from gateway.session_policy import build_policy+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ build_policy({'source': 'kanban', 'cwd': str(workspace)}, config)+++def test_real_dispatcher_argv_completes_owned_task(tmp_path):+ import os+ import subprocess+ import sys+ repo = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'SYSTEMROOT') if k in os.environ}+ env.update(HOME=str(tmp_path / 'home'), HERMES_HOME=str(tmp_path / 'state'), PYTHONPATH=str(repo))+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'kanban_owner_probe.py')],+ env=env, cwd=repo, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=150)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads((tmp_path / 'state' / 'receipt.json').read_text())+ assert receipt['task_status'] == 'done' and receipt['source'] == 'kanban'+ assert receipt['tools'] and receipt['task_context'] and receipt['skill_context'] and receipt['hook_effect']+ assert receipt['admissions'] == 1 and receipt['retry_same_session']+ assert receipt['goal_continuation'] and receipt['stable_prefix']+ print(json.dumps(receipt))diff --git a/tests/hermes_cli/test_kanban_core_functionality.py b/tests/hermes_cli/test_kanban_core_functionality.pyindex 2a0cf6d7598..61c9ca03b60 100644--- a/tests/hermes_cli/test_kanban_core_functionality.py+++ b/tests/hermes_cli/test_kanban_core_functionality.py@@ -736,12 +736,8 @@ def test_default_spawn_does_not_auto_load_any_skill(kanban_home, monkeypatch):assert "--skills" not in cmd, (f"spawn argv should not auto-load any skill: {cmd}")- assert "--accept-hooks" in cmd, f"spawn argv missing --accept-hooks: {cmd}"- assert cmd.index("--accept-hooks") < cmd.index("chat"), (- f"--accept-hooks must come before 'chat' in argv: {cmd}"- )- # Assignee + task env are still present- assert "some-profile" in cmd+ assert cmd[-2:] == ["-m", "hermes_cli.kanban_worker_client"]+ # Assignee + task identity reaches the owner client; policy is read from the board.env = captured["env"]assert env.get("HERMES_KANBAN_TASK") == tidassert env.get("HERMES_PROFILE") == "some-profile"diff --git a/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py b/tests/hermes_cli/test_kanban_worker_spawn_toolsets.pyindex c221d63f964..f2ed93a6d0a 100644--- a/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py+++ b/tests/hermes_cli/test_kanban_worker_spawn_toolsets.py@@ -25,14 +25,7 @@ def _make_task(kb, *, assignee: str):def test_default_spawn_pins_assignee_profile_cli_toolsets(monkeypatch, tmp_path):- """Manual profile assignment should keep that profile's CLI tools.-- Regression guard for dispatcher-spawned workers that boot with- HERMES_KANBAN_TASK: the worker must not collapse to only kanban lifecycle- tools when the assigned profile's top-level ``toolsets`` is the default- composite. The spawned CLI gets an explicit --toolsets pin resolved from- platform_toolsets.cli; model_tools appends task-scoped kanban tools later.- """+ """The transport client reaches the assigned profile with its exact run claim."""root = tmp_path / ".hermes"profile = root / "profiles" / "elias"profile.mkdir(parents=True)@@ -84,19 +77,13 @@ agent:assert pid == 4242assert captured["env"]["HERMES_HOME"] == str(profile)assert captured["env"]["HERMES_KANBAN_TASK"] == "t_spawn_tools"- assert "--toolsets" in captured["cmd"]- pinned = captured["cmd"][captured["cmd"].index("--toolsets") + 1].split(",")- for required in ("terminal", "web", "file", "skills", "code_execution", "delegation"):- assert required in pinned+ assert captured["cmd"][-2:] == ["-m", "hermes_cli.kanban_worker_client"]+ assert captured["env"]["HERMES_KANBAN_RUN_ID"] == "7"+ assert captured["env"]["HERMES_KANBAN_CLAIM_LOCK"] == "lock"-def test_default_spawn_model_override_survives_real_cli_parse(monkeypatch, tmp_path):- """The dispatcher's pre-``chat`` model flag must reach ``args.model``.-- This is an integration contract between Kanban's worker argv builder and- the real CLI parser. A parser default once erased the explicit override,- silently sending the worker to its profile default or fallback instead.- """+def test_default_spawn_does_not_pass_mutable_launch_overrides(monkeypatch, tmp_path):+ """Owner policy reads overrides from the claimed card, not executable argv."""root = tmp_path / ".hermes"(root / "profiles" / "elias").mkdir(parents=True)root.joinpath("config.yaml").write_text("{}\n", encoding="utf-8")@@ -104,7 +91,6 @@ def test_default_spawn_model_override_survives_real_cli_parse(monkeypatch, tmp_pfrom hermes_cli import kanban_db as kbfrom hermes_cli import kanban_db_dispatch as kbd- from hermes_cli._parser import build_top_level_parsermonkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: ["hermes"])captured = {}@@ -124,16 +110,9 @@ def test_default_spawn_model_override_survives_real_cli_parse(monkeypatch, tmp_ptask.model_override = "gpt-5.6-sol"kbd._default_spawn(task, str(workspace))- parser, _subparsers, _chat_parser = build_top_level_parser()- # Profile selection is attached by the outer CLI bootstrap rather than- # build_top_level_parser(); remove that already-validated prefix and parse- # the worker flags/subcommand through the real shared parser.- assert captured["cmd"][1:3] == ["-p", "elias"]- args = parser.parse_args(captured["cmd"][3:])-- assert args.command == "chat"- assert args.model == "gpt-5.6-sol"- assert args.query == "work kanban task t_spawn_tools"+ # Mutable model strings are not launch authority; the owner reads the claimed card.+ assert captured["cmd"][-2:] == ["-m", "hermes_cli.kanban_worker_client"]+ assert task.model_override not in captured["cmd"]def test_resolve_worker_cli_toolsets_uses_profile_home_not_parent_config(monkeypatch, tmp_path):