Skip to content

Commit 504dd1f

Browse files
nftpoetristteknium1
authored andcommitted
fix(raft): scope RAFT_PROFILE resolution to the active multiplex profile
_spawn_bridge, _env_enablement and register()'s platform_hint read RAFT_PROFILE via raw os.environ. Under a multiplexed secondary profile os.environ holds the DEFAULT profile's bridged value, so the bridge subprocess / CLI hint pointed at another profile's Raft identity. Resolve through get_secret() only when running inside a secondary profile's scope (Buzz/SimpleX _profile_scoped() pattern, #98738); the default profile keeps its unscoped os.environ read. No fallthrough to os.environ after a scoped miss. Salvaged from #100392 (tests trimmed to two).
1 parent d9b051a commit 504dd1f

2 files changed

Lines changed: 161 additions & 3 deletions

File tree

‎plugins/platforms/raft/adapter.py‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,52 @@
9797
_RAFT_PROMPT_TURN_IDS: set[str] = set()
9898

9999

100+
def _profile_scoped() -> bool:
101+
"""True when running inside a multiplexed secondary profile's scope.
102+
103+
Secondary-profile adapters are constructed, connected, and reloaded
104+
inside ``_profile_runtime_scope`` (secret scope installed + multiplex
105+
active) — the same discriminator the Buzz/SimpleX adapters use for this
106+
bug class (#98738). The DEFAULT profile under multiplexing runs
107+
unscoped: ``os.environ`` holds its own bridge output there and keeps its
108+
legacy precedence.
109+
"""
110+
try:
111+
from agent.secret_scope import current_secret_scope, is_multiplex_active
112+
113+
return bool(is_multiplex_active() and current_secret_scope() is not None)
114+
except Exception:
115+
return False
116+
117+
118+
def _resolve_raft_profile() -> str:
119+
"""Scope-aware resolution of the ``RAFT_PROFILE`` slug.
120+
121+
Raft has no ``config.yaml`` equivalent for this value (env-only), so a
122+
secondary multiplex profile's only way to configure Raft is via its own
123+
``.env`` file — which the installed secret scope (built from that
124+
profile's ``.env`` by ``_profile_runtime_scope``) already carries.
125+
Reading raw ``os.environ.get("RAFT_PROFILE")`` here would instead return
126+
the DEFAULT profile's bridged value, misdirecting the bridge subprocess
127+
or CLI hint at another profile's external Raft workspace/agent identity.
128+
129+
``get_secret()`` is only called when ``_profile_scoped()`` is True — the
130+
callers of this helper (``connect()``/``register()``) run inside
131+
``_profile_runtime_scope`` for secondary profiles, but the DEFAULT
132+
profile's own startup path never installs a scope, where ``get_secret()``
133+
would raise ``UnscopedSecretError``; the guard keeps that path on the
134+
unchanged ``os.environ`` read.
135+
"""
136+
if _profile_scoped():
137+
try:
138+
from agent.secret_scope import get_secret
139+
140+
return (get_secret("RAFT_PROFILE") or "").strip()
141+
except Exception:
142+
return ""
143+
return os.environ.get("RAFT_PROFILE", "").strip()
144+
145+
100146
def check_raft_requirements() -> bool:
101147
"""Check if Raft channel dependencies are available.
102148
@@ -533,7 +579,7 @@ def _spawn_bridge(self, port: int) -> None:
533579
logger.warning("[raft] raft CLI not found in PATH; bridge not spawned — wake-only polling mode")
534580
return
535581

536-
profile = os.environ.get("RAFT_PROFILE", "")
582+
profile = _resolve_raft_profile()
537583
if not profile:
538584
logger.warning("[raft] RAFT_PROFILE not set; bridge not spawned")
539585
return
@@ -777,8 +823,12 @@ def _env_enablement() -> Optional[dict]:
777823
"""Seed PlatformConfig.extra from env vars during gateway config load.
778824
779825
Auto-enables when RAFT_PROFILE is set (the adapter needs it anyway).
826+
Scope-aware: consults the active profile's own RAFT_PROFILE (env, or a
827+
secondary profile's own .env via the secret scope) instead of the
828+
default profile's bridged env value (mirrors the Buzz/SimpleX fix for
829+
#98738) — see ``_resolve_raft_profile``.
780830
"""
781-
if not os.getenv("RAFT_PROFILE"):
831+
if not _resolve_raft_profile():
782832
return None
783833

784834
return {"enabled": True}
@@ -839,12 +889,18 @@ def register(ctx) -> None:
839889
setup_fn=interactive_setup,
840890
env_enablement_fn=_env_enablement,
841891
emoji="🔔",
892+
# Scope-aware (mirrors _resolve_raft_profile's docstring): register()
893+
# runs inside _profile_runtime_scope for a secondary multiplex
894+
# profile (via discover_plugins() in
895+
# gateway/run.py::_start_one_profile_adapters), so this resolves
896+
# that profile's own RAFT_PROFILE instead of the default profile's
897+
# bridged env value baked into a shared registry entry.
842898
platform_hint=(
843899
"You are connected to Raft via an external-agent channel. "
844900
"Run `raft --profile {profile} profile show` to confirm which agent profile is active. "
845901
"Run `raft --profile {profile} manual get raft-cli-overview` to learn available Raft commands. "
846902
"Always pass `--profile {profile}` to every raft CLI call."
847-
).format(profile=os.environ.get("RAFT_PROFILE", "your-agent-profile")),
903+
).format(profile=_resolve_raft_profile() or "your-agent-profile"),
848904
)
849905
ctx.register_hook("on_session_start", _on_session_start)
850906
ctx.register_hook("pre_llm_call", _on_pre_llm_call)

‎tests/gateway/test_raft_adapter.py‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import asyncio
44
import json
55
import os
6+
from types import SimpleNamespace
67
from unittest.mock import AsyncMock, patch
78

89
import pytest
@@ -218,3 +219,104 @@ def test_interactive_setup_keeps_existing_profile_when_not_reconfigured(
218219
assert os.environ["RAFT_PROFILE"] == "existing"
219220
assert "Keeping RAFT_PROFILE=existing" in capsys.readouterr().out
220221

222+
223+
# ---------------------------------------------------------------------------
224+
# Multiplex secondary-profile scope (RAFT_PROFILE resolution)
225+
# ---------------------------------------------------------------------------
226+
#
227+
# _spawn_bridge, _env_enablement, and register()'s platform_hint all
228+
# previously read RAFT_PROFILE via raw os.environ.get unconditionally. Under
229+
# a multiplexed secondary profile, os.environ holds the DEFAULT profile's
230+
# YAML-to-env bridge output — a secondary profile with its own RAFT_PROFILE
231+
# (set only in its own .env, resolved via the installed secret scope) would
232+
# silently connect the bridge subprocess / CLI hint to the default profile's
233+
# external Raft workspace/agent identity instead of its own. Mirrors the
234+
# Buzz/SimpleX fix for #98738.
235+
236+
@pytest.fixture
237+
def multiplex_scope():
238+
"""Install multiplex + a secondary-profile secret scope; restore after."""
239+
tokens = []
240+
241+
def install(scope=None):
242+
from agent.secret_scope import set_multiplex_active, set_secret_scope
243+
244+
set_multiplex_active(True)
245+
tokens.append(set_secret_scope(scope or {}))
246+
return tokens[-1]
247+
248+
yield install
249+
250+
from agent.secret_scope import reset_secret_scope, set_multiplex_active
251+
252+
for token in reversed(tokens):
253+
reset_secret_scope(token)
254+
set_multiplex_active(False)
255+
256+
257+
@pytest.fixture
258+
def default_profile_env(monkeypatch):
259+
"""The default profile's YAML-to-env bridge output in os.environ."""
260+
monkeypatch.setenv("RAFT_PROFILE", "default-profile-slug")
261+
262+
263+
class _FakeCtx:
264+
"""Minimal ``ctx`` capturing ``register_platform``'s kwargs."""
265+
266+
def __init__(self):
267+
self.platform_kwargs = None
268+
269+
def register_platform(self, **kwargs):
270+
self.platform_kwargs = kwargs
271+
272+
def register_hook(self, *args, **kwargs):
273+
pass
274+
275+
276+
class TestMultiplexProfileScope:
277+
278+
def test_secondary_profile_uses_its_own_slug_and_never_borrows_default(
279+
self, multiplex_scope, default_profile_env, monkeypatch
280+
):
281+
"""Bridge spawn, env-enablement and the register() hint all resolve
282+
the secondary profile's own RAFT_PROFILE; with none of its own the
283+
profile fails closed (bridge not spawned, not auto-enabled)."""
284+
import plugins.platforms.raft.adapter as raft_mod
285+
286+
monkeypatch.setattr(raft_mod.shutil, "which", lambda name: "/usr/bin/raft")
287+
spawned = []
288+
monkeypatch.setattr(
289+
raft_mod.subprocess, "Popen",
290+
lambda cmd, **kwargs: spawned.append(cmd) or SimpleNamespace(pid=1),
291+
)
292+
293+
multiplex_scope({"RAFT_PROFILE": "secondary-profile-slug"})
294+
_make_adapter()._spawn_bridge(9999)
295+
assert spawned[-1][:3] == ["/usr/bin/raft", "--profile", "secondary-profile-slug"]
296+
assert _env_enablement() == {"enabled": True}
297+
ctx = _FakeCtx()
298+
register(ctx)
299+
assert "--profile secondary-profile-slug" in ctx.platform_kwargs["platform_hint"]
300+
assert "default-profile-slug" not in ctx.platform_kwargs["platform_hint"]
301+
302+
spawned.clear()
303+
multiplex_scope({})
304+
_make_adapter()._spawn_bridge(9999)
305+
assert spawned == []
306+
assert _env_enablement() is None
307+
308+
def test_default_profile_unscoped_keeps_env_precedence(
309+
self, monkeypatch, default_profile_env
310+
):
311+
"""Multiplex ON but no scope (the DEFAULT profile constructs
312+
unscoped): env is its own bridge output and still wins."""
313+
from agent.secret_scope import set_multiplex_active
314+
315+
set_multiplex_active(True)
316+
try:
317+
assert _env_enablement() == {"enabled": True}
318+
ctx = _FakeCtx()
319+
register(ctx)
320+
assert "--profile default-profile-slug" in ctx.platform_kwargs["platform_hint"]
321+
finally:
322+
set_multiplex_active(False)

0 commit comments

Comments
 (0)