Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): upsert last duplicate active dotenv key

santhreald1f83c096ca9
diff --git a/agent/src/api/helpers.py b/agent/src/api/helpers.py
index fbec14dd0..33b976eb4 100644
--- a/agent/src/api/helpers.py
+++ b/agent/src/api/helpers.py
@@ -185,17 +185,19 @@ def _write_env_values(path: Path, updates: Dict[str, str]) -> None:
"""Upsert active dotenv values while preserving comments and ordering."""
_ensure_agent_env_file(path)
lines = path.read_text(encoding="utf-8").splitlines()
- seen: set[str] = set()
+ # Last active KEY= wins on read; update that line so upserts stick.
+ last_active: Dict[str, int] = {}
for index, raw in enumerate(lines):
stripped = raw.lstrip()
- is_comment = stripped.startswith("#")
- candidate = stripped[1:].lstrip() if is_comment else stripped
- if "=" not in candidate:
+ if stripped.startswith("#") or "=" not in stripped:
continue
- key = candidate.split("=", 1)[0].strip()
- if key in updates and key not in seen:
- lines[index] = f"{key}={_format_env_value(updates[key])}"
- seen.add(key)
+ key = stripped.split("=", 1)[0].strip()
+ if key in updates:
+ last_active[key] = index
+ seen: set[str] = set()
+ for key, index in last_active.items():
+ lines[index] = f"{key}={_format_env_value(updates[key])}"
+ seen.add(key)
missing = [key for key in updates if key not in seen]
if missing:
if lines and lines[-1].strip():
diff --git a/agent/tests/test_api_infrastructure.py b/agent/tests/test_api_infrastructure.py
index f1fdf87aa..7a800f7f6 100644
--- a/agent/tests/test_api_infrastructure.py
+++ b/agent/tests/test_api_infrastructure.py
@@ -256,6 +256,18 @@ def test_strip_env_value_inline_comment():
assert helpers._strip_env_value("value # comment") == "value"
+def test_write_env_values_updates_last_duplicate_active_key(tmp_path):
+ """Duplicate active KEY= lines: read is last-wins; upsert must update last."""
+ env_file = tmp_path / ".env"
+ env_file.write_text("K=old\nK=older\n", encoding="utf-8")
+ assert helpers._read_env_values(env_file)["K"] == "older"
+
+ helpers._write_env_values(env_file, {"K": "new"})
+ assert helpers._read_env_values(env_file)["K"] == "new"
+ lines = [ln for ln in env_file.read_text(encoding="utf-8").splitlines() if ln.startswith("K=")]
+ assert lines[-1] == "K=new"
+
+
# ============================================================================
# state._get_session_service writeback
# ============================================================================