The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): re-read config-derived settings when a client attaches to a session
unsupportedpastelsd6663968571c
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex a0c446d8ad9..bf28109c800 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -512,6 +512,11 @@ class AuthorityConnection:# reopens it (``reopen_local_session`` in the drain), so opening a finished chat# never re-lights DB-derived liveness with no new activity.self.authority.authorize(self.actor, ref, 'session:read')+ if 'session:control' in self.actor.capabilities and ref.session_id not in self.subscriptions:+ # A client attaching (main's `hermes -c` was a new process) re-reads the config-derived settings+ # (CFG-2); a snapshot poll on this attachment does not.+ from gateway.session_policy_refresh import refresh_resumed_policy+ await refresh_resumed_policy(self.authority, ref)snapshot = await self.authority.attach(self.actor, ref)self.subscriptions[ref.session_id] = snapshot.subscription_idself._spawn_notice(ref)diff --git a/gateway/session_policy_refresh.py b/gateway/session_policy_refresh.pynew file mode 100644index 00000000000..6d3cab0198f--- /dev/null+++ b/gateway/session_policy_refresh.py@@ -0,0 +1,132 @@+"""A resumed local session re-reads its config-derived settings (CFG-2).++Main's ``hermes -c`` was a new process: toolsets, ``terminal.backend``, ``max_turns``, checkpoints and the+reasoning default came from the config it started with, while the stored session kept its model/provider.+The owner keeps that line on ``session.resume``: it re-derives exactly those fields from the session+profile's current config and commits them as a new policy generation. The creation flags (request_json),+the model route and a committed ``/reasoning`` pick stay; a session with a turn running or queued keeps the+policy that turn was admitted under.+"""+import asyncio+import json+import logging+from dataclasses import asdict, replace+from functools import partial+from pathlib import Path++logger = logging.getLogger(__name__)+++def _follow(target, live, key):+ if key in live:+ target[key] = live[key]+ else:+ target.pop(key, None)+++def refreshed_policy(policy, live, terminal, *, picked=()):+ """``(policy, terminal_secrets)``: *policy* with its config-derived fields from *live* (the profile's+ config) and *terminal* (its terminal scope); explicit picks (launch flags, the *picked* policy edits)+ stay. *policy* itself when nothing moved."""+ from gateway.session_policy import (_extract_config_secrets, _resolve_toolsets, present_sections,+ terminal_uses_host_cwd)+ request = json.loads(policy.request_json)+ old, config = json.loads(policy.config_json), json.loads(policy.config_json)+ live = present_sections(live)+ live_agent = live.get('agent') or {}+ agent = dict(config.get('agent') or {})+ keys = [] if 'max_turns' in request else ['max_turns']+ keys += [] if 'reasoning' in request or 'reasoning' in picked else ['reasoning_effort', 'reasoning_overrides']+ toolsets = policy.toolsets+ if 'toolsets' not in request and policy.editor_mcp_json is None:+ keys.append('disabled_toolsets')+ _follow(config, live, 'platform_toolsets')+ toolsets = tuple(sorted(_resolve_toolsets({}, live, policy.source, policy.safe_mode, policy.coding_posture)))+ for key in keys:+ _follow(agent, live_agent, key)+ if agent or 'agent' in config:+ config['agent'] = agent+ if 'max_turns' not in request:+ _follow(config, live, 'max_turns')+ _follow(config, live, 'checkpoints')+ if request.get('checkpoints') is True:+ section = config.get('checkpoints')+ section = dict(section) if isinstance(section, dict) else {'enabled': bool(section)} if section else {}+ config['checkpoints'] = {**section, 'enabled': True}+ terminal, secrets = dict(terminal), {}+ # The session's own folder, where it now is, under build_policy's rule; a committed Move to project is+ # the user's pick on every backend (it rewrote the policy, never the launch request).+ if request.get('cwd_explicit') is True or 'workspace' in picked or terminal_uses_host_cwd(terminal):+ terminal['TERMINAL_CWD'] = policy.cwd+ _extract_config_secrets(terminal, secrets, (None,))+ if config == old and toolsets == policy.toolsets and terminal == json.loads(policy.terminal_json):+ return policy, {}+ return replace(policy, toolsets=toolsets, config_json=json.dumps(config), terminal_json=json.dumps(terminal)), secrets+++def _prepare(authority, session_id):+ """Off the owner loop: the stored policy, its refresh from this profile home's files, and the generation+ it was derived at. None when the session takes no refresh or nothing moved."""+ from gateway.run import _load_gateway_config+ from gateway.session_policy import SURFACES, restore_policy+ from hermes_state_local import local_receipt+ from hermes_state_mutation_prepared import policy_picks+ from tools.terminal_scope import build_profile_terminal_scope+ generation = authority.db.get_session(session_id)['runtime_generation']+ stored = local_receipt(authority.db, session_id)['policy']+ old = restore_policy(stored)+ # A bypass launch never reads the profile; cron, Kanban and room routes are not resumed CLI sessions.+ if old.ignore_user_config or old.source not in SURFACES:+ return None+ home = Path(authority.db.db_path).resolve().parent+ policy, secrets = refreshed_policy(old, _load_gateway_config(home / 'config.yaml'),+ build_profile_terminal_scope(home),+ picked=policy_picks(authority.db, session_id))+ return None if policy == old else (stored, old, policy, secrets, generation)+++def _rebind(authority, session_id, old, policy, terminal_secrets):+ """Re-bind the private values like a policy mutation: policy identity covers config and terminal, and+ the terminal's own secrets are the profile's current ones."""+ from gateway.session_policy import bind_launch_key, launch_key+ from gateway.session_policy_credentials import recover_config_secrets+ secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}+ secrets = {path: value for path, value in secrets.items() if path[0] is not None}+ secrets.update(terminal_secrets)+ return bind_launch_key(authority, session_id, policy, launch_key(authority, old), config_secrets=secrets)+++async def refresh_resumed_policy(authority, ref):+ """Commit the config refresh of an idle local session before it is attached. Never fails the resume:+ a busy session, a revoked launch credential or an unreadable profile keeps the stored policy."""+ from gateway.session_runtime_workers import tracked_write+ from hermes_state_mutation_prepared import commit_refreshed_policy+ try:+ prepared = await asyncio.to_thread(_prepare, authority, ref.session_id)+ if prepared is None:+ return+ stored, old, policy, secrets, generation = prepared+ policy = _rebind(authority, ref.session_id, old, policy, secrets)+ # Compare-and-swap against the receipt as stored (JSON lists), not its restored tuple form. The+ # publication is the commit's own shielded follow-up: a caller cancelled mid-commit cannot leave the+ # stored policy ahead of the live one (restore_local_session refuses that pair).+ await tracked_write(authority, partial(commit_refreshed_policy, authority.db, epoch=authority.epoch,+ session_id=ref.session_id, old=stored, new=asdict(policy),+ generation=generation),+ then=lambda _generation: _publish(authority, ref))+ except Exception as exc: # health: allow BLE001 -- a refresh is best-effort; the resume itself must proceed+ logger.info('Session %s keeps its stored policy on resume: %s', ref.session_id,+ getattr(exc, 'reason', None) or type(exc).__name__)+++def _publish(authority, ref):+ from gateway.session_local import local_session_info, publish_local_policy+ publish_local_policy(authority, ref.session_id)+ # A drain that ran during the off-loop commit saw the new stored policy beside the old live one and+ # paused; with both equal again, anything admitted meanwhile runs.+ authority._schedule(ref)+ # Every viewer already attached adopts the new generation (its next fenced edit would otherwise be+ # refused as stale) and repaints from the refreshed policy, as a reasoning/workspace edit publishes.+ authority._publish_pending(ref)+ authority.sessions[ref.session_id].event_stream.publish(+ ref.session_id, local_session_info(authority, ref), event_type='session.info')diff --git a/hermes_state_mutation_branch.py b/hermes_state_mutation_branch.pyindex a61a94470e3..ba6b6460207 100644--- a/hermes_state_mutation_branch.py+++ b/hermes_state_mutation_branch.py@@ -91,6 +91,10 @@ def branch_in_transaction(db, conn, session_id, payload, prepared=None):source=db.TITLE_SOURCE_DERIVED)receipt = dict(profile_id=saved['profile_id'], principal_id=saved['principal_id'],request_id=request_id, session_id=child, route=route, entry=entry.to_dict(), policy=policy)+ # The copied policy holds the parent's picks; the child's refresh must keep them as picks, not defaults.+ from hermes_state_mutation_prepared import picks_on+ if picks := picks_on(conn, session_id):+ receipt['picks'] = sorted(picks)conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?)",(route, _json(entry.to_dict()), now.timestamp()))conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (POLICY_PREFIX + child, _json(receipt)))diff --git a/hermes_state_mutation_prepared.py b/hermes_state_mutation_prepared.pyindex 5b547938340..0c929b58f6f 100644--- a/hermes_state_mutation_prepared.py+++ b/hermes_state_mutation_prepared.py@@ -87,3 +87,38 @@ def editor_mcp_in_transaction(db, conn, session_id, payload, prepared):POLICY_HANDLERS = {'model': model_in_transaction, 'reasoning': reasoning_in_transaction,'workspace': workspace_in_transaction, 'editor_mcp': editor_mcp_in_transaction}+++def picks_on(conn, session_id):+ """The policy edits (``reasoning``, ``workspace``) a ``session.mutate`` ever committed for *session_id*:+ their receipts (kept for exact retries, also past deletion) are the durable record of the user's pick.+ A branch copied its parent's policy, picks included, under its own id: its local receipt's ``picks``."""+ picked = {row[0] for row in conn.execute(+ "SELECT DISTINCT json_extract(value, '$.result.operation') FROM state_meta "+ "WHERE key GLOB 'gateway.mutation.v1.*' AND json_valid(value) "+ "AND json_extract(value, '$.result.operation') IN ('reasoning', 'workspace') "+ "AND json_extract(value, '$.result.session_id')=?", (session_id,))}+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + session_id,)).fetchone()+ return picked | set(json.loads(saved[0]).get('picks', ())) if saved else picked+++def policy_picks(db, session_id):+ with db._read_ctx() as conn:+ return picks_on(conn, session_id)+++def commit_refreshed_policy(db, *, epoch, session_id, old, new, generation):+ """The owner's config refresh of an idle session: *new* replaces exactly *old* at *generation* (a+ concurrent mutation or turn wins) and opens the next policy generation. Returns that generation."""+ from hermes_state_mutation_guards import require_idle+ from hermes_state_runtime import _epoch++ def write(conn):+ _epoch(conn, epoch)+ snapshot = local_snapshot(db, conn, session_id)+ require_idle(db, conn, list({session_id, snapshot['target']}))+ current = conn.execute('SELECT runtime_generation FROM sessions WHERE id=?', (session_id,)).fetchone()+ if snapshot['receipt']['policy'] != old or current is None or current[0] != generation:+ raise RuntimeStoreError('revision_conflict')+ return _commit_policy(db, conn, session_id, {'snapshot': snapshot, 'policy': new})[1]+ return db._execute_write(write)diff --git a/tests/gateway/test_session_resume_config_refresh.py b/tests/gateway/test_session_resume_config_refresh.pynew file mode 100644index 00000000000..5750c794074--- /dev/null+++ b/tests/gateway/test_session_resume_config_refresh.py@@ -0,0 +1,428 @@+"""CFG-2: a resumed local session runs the profile's CURRENT config-derived settings.++Main's ``hermes -c`` was a new CLI process: toolsets, ``terminal.backend``, ``max_turns``, checkpoints and+the reasoning default came from the config it read at startup, while the stored session supplied the+model/provider (``cli_model_switch_mixin.py`` restore). The owner freezes a LocalSessionPolicy at creation,+so ``session.resume`` re-derives those fields from the profile as a new policy generation, keeping the+explicit launch flags, the model route and a committed ``/reasoning`` pick, and never touching a turn+that is already running. Real SessionStore/SessionAuthority and a real config.yaml.+"""+import asyncio+import json+from types import SimpleNamespace++import pytest++from tests.waiting import async_wait_until++BEFORE = ('model: {default: m1, provider: custom, base_url: "http://127.0.0.1:9/v1"}\n'+ 'agent: {reasoning_effort: high, max_turns: 30}\ncheckpoints: {enabled: false}\n'+ 'platform_toolsets: {cli: [web, terminal]}\nterminal: {backend: local}\n')+AFTER = ('model: {default: m2, provider: custom, base_url: "http://127.0.0.1:9/v1"}\n'+ 'agent: {reasoning_effort: low, max_turns: 7}\ncheckpoints: {enabled: true}\n'+ 'platform_toolsets: {cli: [terminal]}\nterminal: {backend: docker}\n')+++def _home(monkeypatch):+ """The profile home the store's state.db lives in: creation and the refresh read its config.yaml."""+ from gateway import run+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ home.mkdir(parents=True, exist_ok=True)+ (home / 'config.yaml').write_text(BEFORE)+ # gateway.run binds its home at first import; another test module may have imported it elsewhere.+ monkeypatch.setattr(run, '_hermes_home', home)+ return home+++def _runner(store, handle=None):+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _evict_cached_agent=lambda route: None,+ _set_session_reasoning_override=lambda route, value: None,+ _resolve_session_agent_runtime=lambda **k: ('m1', {}), _handle_message=handle)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ return runner+++async def _call(connection, method, **params):+ reply = await connection.dispatch({'id': 1, 'method': method, 'params': params})+ assert 'result' in reply, reply+ return reply['result']+++def _policy(authority, sid):+ from gateway.session_policy import policy_for_source+ return policy_for_source(authority.runner, authority.sessions[sid].source)+++def _view(policy):+ return {'web': 'web' in policy.toolsets, 'max_turns': policy.max_turns,+ 'checkpoints': policy.checkpoints_enabled, 'effort': policy.reasoning_config.get('effort'),+ 'backend': json.loads(policy.terminal_json).get('TERMINAL_ENV'), 'model': policy.model}+++async def test_resume_after_restart_rereads_config_derived_fields_and_keeps_picks(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ home = _home(monkeypatch)+ store = SessionStore(home / 'sessions', GatewayConfig())+ assert store._db.db_path.parent.resolve() == home.resolve()+ first = await initialize_session_authority(_runner(store), profile_id=str(home), instance_id='first')+ owner = AuthorityConnection(first, object(), {'user_id': 'human'})+ plain = (await _call(owner, 'session.create', request_id='plain', source='cli', cwd=str(tmp_path)))['session_id']+ flags = (await _call(owner, 'session.create', request_id='flags', source='cli', cwd=str(tmp_path),+ toolsets=['web'], max_turns=5, reasoning='minimal', checkpoints=True))['session_id']+ picked = (await _call(owner, 'session.create', request_id='picked', source='cli', cwd=str(tmp_path)))['session_id']+ snap = store._db.get_session(picked)+ mutation = dict(session_id=picked, request_id='r1', operation='reasoning', payload={'effort': 'medium'},+ expected_revision=snap['runtime_revision'], expected_generation=snap['runtime_generation'])+ applied = await _call(owner, 'session.mutate', **mutation)+ created = _view(_policy(first, plain))+ assert created == {'web': True, 'max_turns': 30, 'checkpoints': False, 'effort': 'high',+ 'backend': 'local', 'model': 'm1'}, created+ await owner.close()++ # `hermes tools disable web`, `hermes config set ...`, then a gateway restart and `hermes -c`.+ (home / 'config.yaml').write_text(AFTER)+ cold = await initialize_session_authority(_runner(store), profile_id=str(home), instance_id='restarted')+ viewer = AuthorityConnection(cold, object(), {'user_id': 'human'})+ try:+ before = store._db.get_session(plain)['runtime_generation']+ resumed = await _call(viewer, 'session.resume', session_id=plain)+ assert _view(_policy(cold, plain)) == {'web': False, 'max_turns': 7, 'checkpoints': True, 'effort': 'low',+ 'backend': 'docker', 'model': 'm1'}+ # A new policy generation the resume reply already reports, durable in the receipt.+ assert resumed['execution_generation'] == before + 1 == store._db.get_session(plain)['runtime_generation']+ from hermes_state_local import local_receipt+ from gateway.session_policy import restore_policy+ assert restore_policy(local_receipt(store._db, plain)['policy']) == _policy(cold, plain)+ # The launch flags stay the session's own; a config-derived field still follows.+ await _call(viewer, 'session.resume', session_id=flags)+ kept = _view(_policy(cold, flags))+ assert (kept['web'], kept['max_turns'], kept['checkpoints'], kept['effort']) == (True, 5, True, 'minimal'), kept+ assert kept['backend'] == 'docker'+ # A committed /reasoning pick is the session's choice, not a config default.+ await _call(viewer, 'session.resume', session_id=picked)+ assert _view(_policy(cold, picked))['effort'] == 'medium'+ assert _view(_policy(cold, picked))['web'] is False+ # Nothing changed since: a second resume commits no new generation.+ again = await _call(viewer, 'session.resume', session_id=plain)+ assert again['execution_generation'] == before + 1+ # Exact retries committed before the refresh still resolve to their original outcome: the creation+ # request is untouched, and a mutation receipt answers before any revision or generation fence.+ retried = await _call(viewer, 'session.create', request_id='plain', source='cli', cwd=str(tmp_path))+ assert retried['session_id'] == plain+ assert await _call(viewer, 'session.mutate', **mutation) == applied+ finally:+ await viewer.close()+ store.close_all_db_handles()+++async def test_resume_never_changes_a_running_turns_policy(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Submission+ from gateway.session_controls import AuthorityConnection+ import hermes_state_runtime as rt+ home = _home(monkeypatch)+ store = SessionStore(home / 'sessions', GatewayConfig())+ assert store._db.db_path.parent.resolve() == home.resolve()+ started, release, seen = asyncio.Event(), asyncio.Event(), []++ async def handle(event):+ from gateway.session_policy import policy_for_source+ seen.append('web' in policy_for_source(authority.runner, event.source).toolsets)+ started.set()+ await release.wait()+ return 'ok'+ authority = await initialize_session_authority(_runner(store, handle), profile_id=str(home), instance_id='only')+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ viewer = AuthorityConnection(authority, object(), {'user_id': 'human'})+ late = AuthorityConnection(authority, object(), {'user_id': 'human'})+ try:+ sid = (await _call(owner, 'session.create', request_id='busy', source='cli', cwd=str(tmp_path)))['session_id']+ ref = authority.sessions[sid]+ from gateway.session_contract import SessionRef+ turn = await authority.submit(owner.actor, Submission('turn-1', SessionRef(authority.profile_id, sid),+ {'text': 'one'}, 'queue'))+ await asyncio.wait_for(started.wait(), 10)+ (home / 'config.yaml').write_text(AFTER)+ generation = store._db.get_session(sid)['runtime_generation']+ await _call(viewer, 'session.resume', session_id=sid)+ assert 'web' in _policy(authority, sid).toolsets # the running turn's policy is untouched+ assert store._db.get_session(sid)['runtime_generation'] == generation+ release.set()+ await async_wait_until(lambda: rt.get_session_admission(store._db, admission_id=turn.admission_id)['status']+ == 'terminal', what='turn-1 to settle')+ # A snapshot poll on an attachment is not an attach: like main's running process, it re-reads nothing.+ await _call(viewer, 'session.resume', session_id=sid)+ assert 'web' in _policy(authority, sid).toolsets+ # The next client attaching to the now idle session does.+ await _call(late, 'session.resume', session_id=sid)+ assert 'web' not in _policy(authority, sid).toolsets+ assert seen == [True] and ref is authority.sessions[sid]+ finally:+ release.set()+ for connection in (owner, viewer, late):+ await connection.close()+ store.close_all_db_handles()+++class _Frames:+ """A viewer's socket: the event frames the owner fans out to it."""+ def __init__(self):+ self.frames = []++ def write(self, obj):+ self.frames.append(obj)+ return True++ def close(self):+ pass++ def generations(self):+ return [f['params'].get('execution_generation', f['params']['payload'].get('execution_generation'))+ for f in self.frames if f.get('method') == 'event']+++async def _owner_authority(home, instance='only'):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ store = SessionStore(home / 'sessions', GatewayConfig())+ assert store._db.db_path.parent.resolve() == home.resolve()+ return store, await initialize_session_authority(_runner(store), profile_id=str(home), instance_id=instance)+++def _connect(authority, transport=None):+ from gateway.session_controls import AuthorityConnection+ return AuthorityConnection(authority, transport or object(), {'user_id': 'human'})+++async def test_a_resume_cancelled_mid_commit_still_publishes_the_committed_policy(tmp_path, monkeypatch):+ """The refresh commit runs off-loop; a caller cancelled while it is in flight must not leave the stored+ policy ahead of the live one (restore_local_session refuses that mismatch, and a later refresh that finds+ the stored policy current returns early without repairing it)."""+ import threading+ import hermes_state_mutation_prepared as prepared+ from gateway.session_policy import restore_policy+ from gateway.session_runtime_workers import mutation_tasks+ from hermes_state_local import local_receipt+ home = _home(monkeypatch)+ store, authority = await _owner_authority(home)+ owner, viewer = _connect(authority), _connect(authority)+ entered, release = threading.Event(), threading.Event()+ commit = prepared.commit_refreshed_policy++ def held_commit(*args, **kwargs):+ entered.set()+ assert release.wait(10)+ return commit(*args, **kwargs)+ monkeypatch.setattr(prepared, 'commit_refreshed_policy', held_commit)+ try:+ sid = (await _call(owner, 'session.create', request_id='c', source='cli', cwd=str(tmp_path)))['session_id']+ (home / 'config.yaml').write_text(AFTER)+ resume = asyncio.create_task(viewer.dispatch({'id': 1, 'method': 'session.resume',+ 'params': {'session_id': sid}}))+ await async_wait_until(entered.is_set, what='the refresh commit to start')+ resume.cancel()+ with pytest.raises(asyncio.CancelledError):+ await resume+ release.set()+ await asyncio.gather(*mutation_tasks(authority), return_exceptions=True)+ stored = restore_policy(local_receipt(store._db, sid)['policy'])+ assert stored.max_turns == 7 # the commit landed+ assert _policy(authority, sid) == stored # and its publication with it+ finally:+ release.set()+ for connection in (owner, viewer):+ await connection.close()+ store.close_all_db_handles()+++async def test_resume_keeps_a_moved_workspace_on_a_backend_with_its_own_cwd(tmp_path, monkeypatch):+ """Move to project rewrites the policy cwd and TERMINAL_CWD, not the launch request: an ssh session+ created without an explicit cwd keeps the folder it was moved to through a config refresh."""+ home = _home(monkeypatch)+ remote = 'terminal: {backend: ssh, ssh_host: box.invalid, ssh_user: me}\n'+ (home / 'config.yaml').write_text(BEFORE.replace('terminal: {backend: local}\n', remote))+ moved = tmp_path / 'project'+ moved.mkdir()+ store, authority = await _owner_authority(home)+ owner = _connect(authority)+ later = _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='w', source='cli', cwd=str(tmp_path)))['session_id']+ snap = store._db.get_session(sid)+ await _call(owner, 'session.mutate', session_id=sid, request_id='move', operation='workspace',+ payload={'cwd': str(moved)}, expected_revision=snap['runtime_revision'],+ expected_generation=snap['runtime_generation'])+ (home / 'config.yaml').write_text(AFTER.replace('terminal: {backend: docker}\n', remote))+ await _call(later, 'session.resume', session_id=sid)+ policy = _policy(authority, sid)+ assert policy.max_turns == 7 # the refresh ran+ terminal = json.loads(policy.terminal_json)+ assert (terminal['TERMINAL_ENV'], policy.cwd, terminal.get('TERMINAL_CWD')) == ('ssh', str(moved), str(moved))+ finally:+ for connection in (owner, later):+ await connection.close()+ store.close_all_db_handles()+++async def test_a_refresh_by_one_viewer_reaches_every_attached_viewer(tmp_path, monkeypatch):+ """Viewer B's attach commits generation G+1; viewer A, attached at G, learns it from the fanout and its+ next generation-fenced mutation succeeds without reopening the session."""+ home = _home(monkeypatch)+ store, authority = await _owner_authority(home)+ socket = _Frames()+ first, second = _connect(authority, socket), _connect(authority)+ try:+ sid = (await _call(first, 'session.create', request_id='v', source='cli', cwd=str(tmp_path)))['session_id']+ attached = await _call(first, 'session.resume', session_id=sid)+ (home / 'config.yaml').write_text(AFTER)+ refreshed = await _call(second, 'session.resume', session_id=sid)+ assert refreshed['execution_generation'] == attached['execution_generation'] + 1+ await async_wait_until(lambda: refreshed['execution_generation'] in socket.generations(),+ what='viewer A to receive the refreshed generation')+ revisions = [f['params']['payload']['revision'] for f in socket.frames+ if f['params'].get('type') == 'session.info' and 'revision' in f['params']['payload']]+ info = [f['params']['payload'] for f in socket.frames if f['params'].get('type') == 'session.info'+ and 'launch_request' in f['params']['payload']]+ assert info and info[-1]['cwd'] == str(tmp_path) # the refreshed policy projection+ mutated = await _call(first, 'session.mutate', session_id=sid, request_id='after', operation='reasoning',+ payload={'effort': 'medium'}, expected_revision=max([attached['revision'], *revisions]),+ expected_generation=max(g for g in socket.generations() if g is not None))+ assert mutated['execution_generation'] == refreshed['execution_generation'] + 1+ finally:+ for connection in (first, second):+ await connection.close()+ store.close_all_db_handles()+++def hold_refresh_commit(monkeypatch):+ """A barrier at the refresh's commit seam (its preflight has read the stored policy and generation, its+ write transaction has not begun): ``(entered, release, done, outcome)``, *outcome* what the commit did."""+ import threading+ import hermes_state_mutation_prepared as prepared+ entered, release, done, outcome = threading.Event(), threading.Event(), threading.Event(), []+ commit = prepared.commit_refreshed_policy++ def held_commit(*args, **kwargs):+ entered.set()+ assert release.wait(10)+ try:+ outcome.append(commit(*args, **kwargs))+ except Exception as exc:+ outcome.append(exc)+ raise+ finally:+ done.set()+ monkeypatch.setattr(prepared, 'commit_refreshed_policy', held_commit)+ return entered, release, done, outcome+++async def admit_during_refresh(authority, actor, sid, refresh, barrier):+ """Run *refresh* to its commit seam, commit a queued admission there, then let the write transaction run+ while that admission is still queued: the owner loop is held until it finishes, so the drain (a task the+ admission scheduled) cannot start the turn first. The refused transaction left the stored policy and its+ generation as they were. ``(refresh result, admission)``."""+ import hermes_state_runtime as rt+ from gateway.session_contract import SessionRef, Submission+ from hermes_state_local import local_receipt+ from hermes_state_runtime import RuntimeStoreError+ entered, release, done, outcome = barrier+ task = asyncio.create_task(refresh)+ await async_wait_until(entered.is_set, what='the refresh to reach its commit')+ stored = local_receipt(authority.db, sid)['policy']+ turn = await authority.submit(actor, Submission('queued-1', SessionRef(authority.profile_id, sid),+ {'text': 'one'}, 'queue'))+ assert rt.get_session_admission(authority.db, admission_id=turn.admission_id)['status'] == 'queued'+ generation = authority.db.get_session(sid)['runtime_generation']+ release.set()+ assert done.wait(10) # blocks the loop on purpose+ assert isinstance(outcome[0], RuntimeStoreError) and outcome[0].reason == 'session_busy', outcome+ assert rt.get_session_admission(authority.db, admission_id=turn.admission_id)['status'] == 'queued'+ assert local_receipt(authority.db, sid)['policy'] == stored+ assert authority.db.get_session(sid)['runtime_generation'] == generation+ return await task, turn+++async def test_an_admission_queued_during_an_attach_refresh_keeps_the_old_policy(tmp_path, monkeypatch):+ """The idle check is inside the refresh's write transaction: a turn queued after the refresh read the+ stored policy refuses the commit, and that turn runs the policy it was admitted under."""+ import hermes_state_runtime as rt+ from hermes_state_local import local_receipt+ home = _home(monkeypatch)+ seen = []++ async def handle(event):+ from gateway.session_policy import policy_for_source+ seen.append('web' in policy_for_source(authority.runner, event.source).toolsets)+ return 'ok'+ store, authority = await _owner_authority(home)+ authority.runner._handle_message = handle+ owner, later = _connect(authority), _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='q', source='cli', cwd=str(tmp_path)))['session_id']+ stored = local_receipt(store._db, sid)['policy']+ (home / 'config.yaml').write_text(AFTER)+ barrier = hold_refresh_commit(monkeypatch)+ resume = later.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': sid}})+ reply, turn = await admit_during_refresh(authority, owner.actor, sid, resume, barrier)+ assert 'result' in reply, reply # the refusal never fails the attach+ assert local_receipt(store._db, sid)['policy'] == stored+ await async_wait_until(lambda: rt.get_session_admission(store._db, admission_id=turn.admission_id)['status']+ == 'terminal', what='the queued turn to run')+ assert seen == [True] and 'web' in _policy(authority, sid).toolsets+ finally:+ for connection in (owner, later):+ await connection.close()+ store.close_all_db_handles()+++async def _mutate(connection, store, sid, request_id, operation, payload):+ snap = store._db.get_session(sid)+ return await _call(connection, 'session.mutate', session_id=sid, request_id=request_id, operation=operation,+ payload=payload, expected_revision=snap['runtime_revision'],+ expected_generation=snap['runtime_generation'])+++async def test_a_branch_keeps_the_reasoning_and_workspace_its_parent_picked(tmp_path, monkeypatch):+ """A branch copies its parent's policy, picks included: resuming it after a config change keeps the+ picked reasoning level and, on ssh, the folder the parent was moved to (the receipts are the parent's)."""+ home = _home(monkeypatch)+ remote = 'terminal: {backend: ssh, ssh_host: box.invalid, ssh_user: me}\n'+ (home / 'config.yaml').write_text(BEFORE.replace('terminal: {backend: local}\n', remote))+ moved = tmp_path / 'project'+ moved.mkdir()+ store, authority = await _owner_authority(home)+ owner, later = _connect(authority), _connect(authority)+ try:+ sid = (await _call(owner, 'session.create', request_id='p', source='cli', cwd=str(tmp_path)))['session_id']+ await _mutate(owner, store, sid, 'move', 'workspace', {'cwd': str(moved)})+ await _mutate(owner, store, sid, 'pick', 'reasoning', {'effort': 'medium'})+ child = (await _mutate(owner, store, sid, 'fork', 'branch', {}))['branched_session_id']+ grandchild = (await _mutate(owner, store, child, 'fork-again', 'branch', {}))['branched_session_id']+ (home / 'config.yaml').write_text(AFTER.replace('terminal: {backend: docker}\n', remote))+ for branch in (child, grandchild):+ await _call(later, 'session.resume', session_id=branch)+ policy = _policy(authority, branch)+ assert policy.max_turns == 7 # the refresh ran+ terminal = json.loads(policy.terminal_json)+ assert (policy.reasoning_config.get('effort'), policy.cwd, terminal.get('TERMINAL_CWD')) == (+ 'medium', str(moved), str(moved)), branch+ finally:+ for connection in (owner, later):+ await connection.close()+ store.close_all_db_handles()+