From 33e29a3b2ed0fc0d4cae4e3fe9cf7794ca8ee15d Mon Sep 17 00:00:00 2001 From: Alessandro <155005371+3clyp50@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:06:45 +0100 Subject: [PATCH] fix(secrets): omit empty and overridden prompt aliases List only non-empty effective definitions, honoring case-insensitive last-definition precedence across global, native, and project stores. Exclude malformed source lines from the alias inventory. Keep the existing conditional secrets guidance and independent variables section. Cover empty values, overrides, non-empty literals, and rendered prompt behavior. --- helpers/secrets.py | 20 +++++++-- helpers/secrets.py.dox.md | 2 + prompts/AGENTS.md | 1 + tests/test_secrets.py | 85 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 104 insertions(+), 4 deletions(-) diff --git a/helpers/secrets.py b/helpers/secrets.py index 593b9d9bf..729bc64f9 100644 --- a/helpers/secrets.py +++ b/helpers/secrets.py @@ -254,18 +254,32 @@ class SecretsManager: return list(secrets.keys()) def get_secrets_for_prompt(self) -> str: - """Get formatted string of secret keys for system prompt""" + """Get non-empty secret aliases from their effective last definitions.""" content = self.read_secrets_raw() if not content: return "" - env_lines = self.parse_env_lines(content) + seen: Set[str] = set() + env_lines: List[EnvLine] = [] + for line in reversed(self.parse_env_lines(content)): + if line.type == "pair" and line.key is not None: + key = line.key.upper() + if key in seen: + continue + seen.add(key) + if not line.value: + continue + env_lines.append(line) + + if not any(line.type == "pair" for line in env_lines): + return "" + env_lines.reverse() return self._serialize_env_lines( env_lines, with_values=False, with_comments=True, with_blank=True, - with_other=True, + with_other=False, key_formatter=alias_for_key, ) diff --git a/helpers/secrets.py.dox.md b/helpers/secrets.py.dox.md index 20c6815bf..d08b59dc3 100644 --- a/helpers/secrets.py.dox.md +++ b/helpers/secrets.py.dox.md @@ -33,6 +33,8 @@ ## Runtime Contracts +- `get_secrets_for_prompt` lists only non-empty effective values, once per uppercase key at its last definition, preserving comments and order. Empty overrides still clear earlier values without changing loading, masking, editing, or substitution. Non-empty literals, including quoted whitespace, remain available. An empty inventory returns `""`, so the prompt template omits the secrets section. + - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. - The agent-facing `get_secrets_manager` masks and unpacks `API_KEY_*` and login/password credentials from `usr/.env`, every value from the global `usr/secrets.env`, and every value from the active project's `secrets.env`; ordinary runtime settings are not treated as secrets. `get_default_secrets_manager` remains scoped to the single writable `usr/secrets.env` file. - Secret serialization escapes backslashes, double quotes, and carriage returns in double-quoted values so global and project saves preserve their parsed values across disk reads and masked edits. Literal line feeds remain multiline; empty values, comments, and deletion semantics are unchanged. diff --git a/prompts/AGENTS.md b/prompts/AGENTS.md index badb6ff77..73e05148e 100644 --- a/prompts/AGENTS.md +++ b/prompts/AGENTS.md @@ -19,6 +19,7 @@ - `agent.system.main.communication.native.md` owns native function-call formatting; profiles may override it alongside the legacy communication template. Shared communication additions remain transport-neutral; the brace terminator belongs only to legacy JSON formatting. - Native communication requests public commentary without a sentence limit; the display maps it to thoughts without adding fields to native arguments. - Prompt changes can alter agent behavior; keep edits narrow and intentional. +- `agent.system.secrets.md` renders secret-alias guidance only when aliases are available; the variables section is conditional independently. `helpers/secrets.py` owns filtering the alias inventory. - Shared solving guidance owns observable success, evidence-driven replanning, task progress notes, source-preserving synthesis, and bug reproduction; specialist methods belong in profile specifics. - Maintain clear separation between core behavior prompts and profile/plugin-specific customization. - Delegation catalogs show profile IDs, titles, and context (description fallback) on separate lines; preserve project-scoped discovery. diff --git a/tests/test_secrets.py b/tests/test_secrets.py index 945b7e898..fa61374b8 100644 --- a/tests/test_secrets.py +++ b/tests/test_secrets.py @@ -1,4 +1,5 @@ import json +from pathlib import Path import pytest @@ -18,6 +19,9 @@ def test_agent_secret_manager_masks_runtime_credentials_only(monkeypatch): "usr/secrets.env": "PROJECT_SECRET=project-value\n", "usr/.env": ( "API_KEY_OPENAI=llm-secret-value\n" + 'API_KEY_ANTHROPIC=""\n' + "AUTH_LOGIN=\n" + "ROOT_PASSWORD=generated-root-value\n" "ANONYMIZED_TELEMETRY=false\n" "DEFAULT_USER_TIMEZONE=Europe/Rome\n" ), @@ -32,7 +36,11 @@ def test_agent_secret_manager_masks_runtime_credentials_only(monkeypatch): "§§secret(PROJECT_SECRET); key=§§secret(API_KEY_OPENAI); " "avoid falsely accusing a utility" ) - assert "ANONYMIZED_TELEMETRY" not in manager.get_secrets_for_prompt() + prompt = manager.get_secrets_for_prompt() + assert "§§secret(API_KEY_OPENAI)" in prompt + assert "§§secret(ROOT_PASSWORD)" in prompt + for key in ("API_KEY_ANTHROPIC", "AUTH_LOGIN", "ANONYMIZED_TELEMETRY"): + assert key not in prompt stream_filter = manager.create_streaming_filter() assert stream_filter.process_chunk("avoid falsely accusing a utility") == ( @@ -41,6 +49,81 @@ def test_agent_secret_manager_masks_runtime_credentials_only(monkeypatch): assert stream_filter.finalize() == "" +@pytest.mark.parametrize("content", [ + "", "# Heading\n", "KEY=\n", 'KEY=""\n', "KEY=''\n", "KEY\n", + "export KEY=\n", "KEY= \n", '# Heading\nKEY="" # Inline\n', +]) +def test_secret_prompt_omits_empty_values(tmp_path, content): + path = tmp_path / "secrets.env" + path.write_text(content) + manager = secrets.SecretsManager(str(path)) + + assert manager.get_secrets_for_prompt() == "" + + +@pytest.mark.parametrize("global_content, project_content, expected", [ + ("KEY=global-value\n", "key=\n", ""), + ("key=\n", "KEY=project-value\n", "§§secret(KEY)"), + ( + "key=global-value # Old\nOTHER=other-value # Other\n", + "# Project\nKEY=project-value # New\n", + "§§secret(OTHER) # Other\n\n# Project\n§§secret(KEY) # New", + ), +]) +def test_secret_prompt_respects_overrides(tmp_path, global_content, project_content, expected): + paths = [tmp_path / "global.env", tmp_path / "project.env"] + for path, content in zip(paths, (global_content, project_content)): + path.write_text(content) + manager = secrets.SecretsManager(*(str(path) for path in paths)) + + assert manager.get_secrets_for_prompt() == expected + value = manager.parse_env_content(project_content)["KEY"] + assert manager.load_secrets()["KEY"] == value + assert manager.replace_placeholders("§§secret(KEY)") == value + assert [path.read_text() for path in paths] == [global_content, project_content] + + +@pytest.mark.parametrize("value", ["0", "false", "None", " ", "first\nsecond"]) +def test_secret_prompt_preserves_nonempty_literals(tmp_path, value): + path = tmp_path / "secrets.env" + path.write_text(f'KEY={json.dumps(value)}\n') + manager = secrets.SecretsManager(str(path)) + + assert manager.get_secrets_for_prompt() == "§§secret(KEY)" + assert manager.replace_placeholders("§§secret(KEY)") == value + + +@pytest.mark.parametrize("content", ["", 'KEY=""\n', "KEY=synthetic-value\n"]) +@pytest.mark.parametrize("variables", ["", "PLAIN=example"]) +def test_secret_guidance_requires_available_aliases(tmp_path, content, variables): + path = tmp_path / "secrets.env" + path.write_text(content) + manager = secrets.SecretsManager(str(path)) + prompt = secrets.files.read_prompt_file( + "agent.system.secrets.md", + _directories=[str(Path(__file__).resolve().parents[1] / "prompts")], + secrets=manager.get_secrets_for_prompt(), + vars=variables, + ) + + available = bool(manager.load_secrets().get("KEY")) + assert ("## secret aliases" in prompt) == available + if available: + assert prompt.lstrip("\n").startswith( + "## secret aliases\n" + "use exact alias form `§§secret(name)`; real values are injected automatically\n" + "only use provided aliases; do not expose or invent secret values\n" + "values may contain special characters, so quote or escape them correctly in shell or code\n" + "comments help explain each secret's purpose\n" + ) + else: + assert "use exact alias form" not in prompt + assert ("§§secret(KEY)" in prompt) == available + assert ("## variables" in prompt) == bool(variables) + assert "synthetic-value" not in prompt + assert "{{" not in prompt + + @pytest.mark.parametrize("value", [ 'value with "quotes" and # inside', r"C:\new\folder\test",