Skip to content

fix(mcp): write env-sourced MCP headers into Codex's runtime fields - #3042

Merged
Daniel Meppiel (danielmeppiel) merged 7 commits into
microsoft:mainfrom
edenfunf:fix/2984-codex-env-sourced-headers
Sep 30, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 7 commits into
microsoft:mainfrom
edenfunf:fix/2984-codex-env-sourced-headers

Conversation

@edenfunf

Copy link
Copy Markdown
Contributor

What

A header whose value references an environment variable now reaches Codex in a form Codex resolves at server start, instead of being copied into http_headers as an unexpanded placeholder.

Given headers: { Authorization: "Bearer ${TOKEN}", X-Api-Key: "${API_KEY}", X-Mixed: "prefix-${SOME_VAR}-suffix", X-Static: "literal-value" }, ~/.codex/config.toml goes from

[mcp_servers.bridge]
url = "http://127.0.0.1:4521/mcp"
id = ""

[mcp_servers.bridge.http_headers]
Authorization = "Bearer ${TOKEN}"
X-Api-Key = "${API_KEY}"
X-Mixed = "prefix-${SOME_VAR}-suffix"
X-Static = "literal-value"

to

[mcp_servers.bridge]
url = "http://127.0.0.1:4521/mcp"
id = ""
bearer_token_env_var = "TOKEN"

[mcp_servers.bridge.http_headers]
X-Static = "literal-value"

[mcp_servers.bridge.env_http_headers]
X-Api-Key = "API_KEY"

with one warning naming X-Mixed, which no Codex field can express.

Why

Codex documents http_headers as a map of header names to static values. CodexClientAdapter does not override _supports_runtime_env_substitution (base.py defaults it to False), so _resolve_variable_placeholders leaves ${VAR} untouched and the literal text is what the server receives. Claude Code's adapter writes the same placeholder into headers, where expansion is documented, so one manifest authenticated for one target and silently failed for the other -- apm install reported success for both.

How

Implements the scope recorded on #2984, in _format_server_config's remote branch:

  • Authorization: "Bearer ${VAR}" -> bearer_token_env_var = "VAR".
  • A value that is exactly ${VAR} -> env_http_headers = { "<Header>" = "VAR" }.
  • Anything else still holding a placeholder -> skipped with a warning naming the headers, in the same "what happened, what to do" shape as the adapter's other skip warnings.
  • A value with no placeholder -> unchanged, still http_headers, which is what that field means.

Both match regexes are built from base._ENV_VAR_RE, so the two spellings APM accepts (${VAR} and ${env:VAR}) cannot drift apart here; the Bearer scheme matches case-insensitively per RFC 7235. bearer_token_env_var is inserted before the dict-valued keys so tomlkit emits the scalar ahead of the sub-tables it renders.

Authorization: "${VAR}" (no scheme) deliberately routes to env_http_headers, not bearer_token_env_var -- the latter would make Codex send a Bearer prefix the manifest never declared.

One coupled change, flagged on the issue before writing it. http_headers sits on the extra: passthrough denylist (_HARNESS_EXTRA_ALIASES) as a harness alias of the modeled headers field -- the boundary from #1670 / PR #1765 that stops a transitive dependency smuggling a modeled field through passthrough. bearer_token_env_var and env_http_headers were not on it; I confirmed on main that both pass straight through into config.toml today. That is inert only while APM never writes them. This PR makes them APM-rendered aliases for headers, so leaving them off would open exactly the hole the denylist exists to close: an extra: block could reach an Authorization header that headers modeling never sees. They are added to the same frozenset, and docs/.../manifest-schema.md, which enumerates those reserved keys, is updated to match. Happy to split this out if you would rather review it separately.

_warn_input_variables coverage is unchanged: ${input:VAR} is disjoint from _ENV_VAR_RE by design, so those values still land in http_headers and still warn.

Test

Live verification -- real apm install -g -t codex against a self-defined remote dep, sandboxed HOME, on main before and this branch after:

Header value Before After
Authorization: Bearer ${TOKEN} http_headers literal bearer_token_env_var = "TOKEN"
X-Api-Key: ${API_KEY} http_headers literal env_http_headers
X-Env-Alt: ${env:ALT_VAR} http_headers literal env_http_headers
X-Mixed: prefix-${SOME_VAR}-suffix http_headers literal, silent skipped, one warning naming it
X-Static: literal-value http_headers http_headers (unchanged)

Output re-parsed with tomllib to confirm the scalar-before-sub-tables ordering is valid TOML. Installing the same manifest with -t claude,codex confirms Claude Code's .claude.json is byte-identical to before, so the parity gap closes without moving the other adapter.

Denylist, verified live: extra: { bearer_token_env_var: ATTACKER_VAR, env_http_headers: {...} } reaches config.toml on main; on this branch it is dropped with the existing reserved passthrough key(s) ignored warning.

Unit tests -- 6 new in TestCodexClientAdapter (tests/unit/test_mcp_client_factory.py) covering each routing decision including the two that must not happen (Authorization: ${VAR} staying out of bearer_token_env_var; Bearer ${VAR} on a non-Authorization header being skipped), plus a literal-value regression guard. 1 new in TestAdapterRealPathShadowGuard (tests/unit/test_mcp_from_dict_unknown_keys.py) for the passthrough boundary, sitting beside the existing http_headers one. All 7 fail on main and pass here.

Updated test -- test_format_server_config_remote_with_headers in tests/integration/test_wave2_adapters_coverage.py asserted "http_headers" in result for a fixture whose value is ${MY_TOKEN}, i.e. it pinned the buggy behavior. Its intent (headers reach the config) is preserved; it now asserts the field that actually works, with a docstring saying why.

Suites -- tests/unit + tests/test_console.py (22622 passed), tests/integration/test_wave2_adapters_coverage.py + test_core_smoke.py + tests/red_team/ (713 passed), CI quality ratchets (90 passed). ruff check src tests and ruff format --check clean. Three tests/unit failures (test_install_safety.py::TestAbsolutePathGuard::test_accepts_unix_absolute, TestSuffixGuard::test_accepts_lib_apm_suffix, test_view_command.py::test_view_versions_bare_registry_flag_forces_registry) reproduce identically on an unmodified main checkout and are unrelated.

Issue: #2984 (status/accepted, claimed in this comment).

Codex documents http_headers as a map of header names to static values, so
the ${VAR} APM wrote there reached the server as literal text and the
connection could not authenticate. The same dependency worked for Claude
Code, which documents expansion of that placeholder, so one manifest
behaved differently per target with no warning.

Route a header value that references an environment variable to the field
Codex resolves at server start: bearer_token_env_var for an Authorization
"Bearer ${VAR}" value, env_http_headers for a value that is exactly ${VAR}.
A value mixing literal text with a placeholder fits neither field and is
skipped with a warning rather than written as a literal.

Both fields now render a value APM models under headers, so they join
http_headers on the extra: passthrough denylist. Without that, an extra:
block could reach an Authorization header that headers modeling never sees.

Fixes microsoft#2984

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

One or more issues must be addressed before approval.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 1 Medium severity · 1 Low severity

Open (3)
What changed in this PR

Fixes Codex MCP header rendering so environment-backed values use Codex runtime fields instead of static placeholders.

Changes:

  • Maps bearer and exact environment placeholders to Codex fields.
  • Rejects unsupported mixed placeholders and blocks passthrough injection.
  • Updates tests, schema documentation, and changelog.
File Description
tests/​unit/​test_mcp_from_dict_unknown_keys.py Updated as part of this pull request.
tests/​unit/​test_mcp_client_factory.py Updated as part of this pull request.
tests/​integration/​test_wave2_adapters_coverage.py Updated as part of this pull request.
src/​apm_cli/​models/​dependency/​mcp.py Updated as part of this pull request.
src/​apm_cli/​adapters/​client/​codex.py Updated as part of this pull request.
docs/​src/​content/​docs/​reference/​manifest-schema.md Updated as part of this pull request.
CHANGELOG.md Updated as part of this pull request.

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/apm_cli/models/dependency/mcp.py Resolved
Comment thread src/apm_cli/adapters/client/codex.py Resolved
Selecting unsupported headers with the canonical placeholder parser missed
the shape the reported context7 manifest declares. That parser does not
model a shell default, so "${CONTEXT7_API_KEY:-}" matched neither runtime
field nor the unsupported check and was written to http_headers as though
it were static, silently, which is the reported failure.

Widen the check in the Codex adapter to any reference still standing after
resolution, excluding ${input:...}, which is collected elsewhere and keeps
its own warning. Widening it here rather than in the shared parser leaves
every other adapter's placeholder semantics untouched.

Also restate the denylist literal the architecture guard pins verbatim.
Adding two aliases had reflowed it, so mutation_writes.mcp_passthrough_denylist
no longer matched and its mutation fixture no longer had a fragment to edit.
The comment moves above the assignment to keep the literal pinnable, and the
fixture now drops one member line.

Docs said Codex resolves ${VAR} at install time, which was already only true
of env: remote headers were passed through verbatim, the bug behind this
change, and now resolve at server start. Correct both the schema reference
and the apm-usage skill resource.
@sergio-sisternes-epam

Copy link
Copy Markdown
Collaborator

Thank you for this pull request. It is linked to #2984, which already carries status/accepted. This comment is advisory only, not merge or scope approval.

CODEOWNERS review contacts are Daniel Meppiel (@danielmeppiel) and Sergio Sisternes (@sergio-sisternes-epam) (already requested). A responsible maintainer still needs to review the implementation. Labels and this comment are not authorization to merge.


Generated by autopilot-pr-triage-worker. This comment is AI-generated and may contain errors.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) added triage/recommended Automated advice completed; not human scope approval. type/bug Something does not work as documented. area/mcp-config MCP server configuration depth, transports, variable resolution. labels Sep 23, 2026
Preserve contributor commits while synchronizing current architecture and lifecycle contracts for microsoft#3042.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: needs_rework

Codex runtime header mappings improve manifest portability, but unchanged reinstalls leave affected users on the old configuration and critical regression coverage is still missing.

panel-mode=full; personas=python-architect,test-coverage-expert,auth-expert,supply-chain-security-expert,cli-logging-expert,devx-ux-expert,doc-writer

cc Eden (@edenfunf) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

This first full advisory panel covers local synchronized head c12d2cb, not the unupdated remote head 0b5687f. The adapter-local design and shared passthrough ownership are sound. The strongest adoption concern is DevX's reproduced upgrade gap: installing with the base formatter inside the candidate pipeline, then reinstalling an unchanged manifest with the candidate formatter, retained the old literal placeholder while reporting 'All servers up to date'. This is a bounded manual reproduction, not an automated failed test or a complete base-checkout upgrade test. Nevertheless, a fix that existing affected users do not receive through reinstall needs targeted migration work and durable lifecycle proof before I recommend shipping it.

Passing evidence supports the formatter boundary, not the complete install or Codex runtime contract. In tests/unit/test_mcp_client_factory.py, self.assertEqual(config["bearer_token_env_var"], "TOKEN") proves native bearer rendering; in tests/unit/test_mcp_from_dict_unknown_keys.py, assert "bearer_token_env_var" not in cfg and assert "env_http_headers" not in cfg prove direct adapter alias filtering; in tests/integration/test_wave2_adapters_coverage.py, assert result["env_http_headers"] == {"Authorization": "MY_TOKEN"} proves whole-value Authorization mapping without adding a bearer scheme. That last test is unit-level despite its directory. The orchestrator reports 117 existing tests passed, with 6 subtests, in 11.85 seconds; no new scenarios have run. Missing lifecycle persistence/replacement coverage and manifest-to-install alias-rejection coverage remain load-bearing gaps for portability, secure defaults, and policy enforcement. Historical manual checks do not replace these guards, and neither actual Codex wire behavior nor final-head CI is established.

Architecture, auth, supply-chain security, and logging converge on one exact-reference defect, not four separate findings: permissive anchors and whitespace matching silently normalize malformed references into native credential fields. Consolidate their cases into one local matching fix and regression matrix, including terminal LF, embedded CR/LF, and non-ASCII separator whitespace. Manifest CR/LF validation limits the demonstrated reach; the evidence does not establish credential leakage or a manifest-level bypass. Escaping control characters in diagnostic identifiers is a separate output-integrity concern. The residual GitHub Actions template claim also needs a narrow correction. None of this calls for a shared-parser expansion, unrelated authentication refactor, or reopening the three resolved Copilot findings.

Scope clarification received after this first panel: The coordinator requires preserving unchanged-install no-op semantics, consistently with #3041 and #3103. Automatic rendering migration is outside this approved change. The revision will instead prove and document the old-config limitation and an existing targeted declaration-refresh path, then return that bounded contract to the delta panel. No shared migration infrastructure is authorized by this advisory.

Dissent. There is no explicit severity disagreement: all seven panelists classified their findings as recommended. I resolve the small whitespace-policy difference in favor of ASCII-space bearer separation rather than Unicode-aware whitespace, and weigh missing critical-promise tests more heavily than their advisory severity alone suggests; manual probes remain reproductions, not durable test evidence.

Aligned with: Native Codex fields improve manifest translation, but unchanged-install migration and persisted header transitions need automated protection. Runtime references and reserved aliases reduce unsafe configuration paths; exact matching, secret-safe diagnostics, and install-level rejection tests remain necessary. Retain the shared passthrough denylist as the sole authority and prove both manifest entry paths reject native aliases through installation. Keep this correction Codex-local and preserve other adapters' placeholder semantics; broader runtime compatibility is not proven by this panel. An unchanged reinstall should deliver this repair for untouched APM-managed entries without overwriting user edits or unrelated settings.

Panel summary

Persona B R N Takeaway
python-architect 0 1 0 Canonical ownership is preserved. Tighten exact header matching so trailing newlines and bearer control whitespace cannot become native runtime references.
test-coverage-expert 0 2 0 Focused probes pass, but Codex header persistence lacks lifecycle proof and native-alias rejection lacks a manifest-to-install regression trap.
auth-expert 0 1 0 Native mappings preserve ordinary static tokens and case-sensitive variable names, but malformed whitespace is silently accepted as an exact runtime reference.
supply-chain-security-expert 0 1 0 Shared ownership rejects both native aliases at parser and adapter boundaries; new diagnostics omit header values. Tighten control-character matching. Static review only.
cli-logging-expert 0 2 0 Tighten exact-reference matching and escape diagnostic identifiers. Header values stay out of warnings; existing input-variable handling is preserved.
devx-ux-expert 0 1 0 Fresh install and managed header transitions work in a hermetic CLI probe; upgrading an existing managed config does not apply the fix.
doc-writer 0 1 0 Runtime header mapping is documented accurately; one blanket template-preservation claim contradicts Codex's new warn-and-skip path.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 5 follow-ups

  1. [devx-ux-expert] Repair old provenance-owned Codex output on unchanged reinstall and add upgrade plus lifecycle regression coverage. -- The manual base-formatter-to-candidate reproduction leaves affected users with literal placeholders despite success output. Combine that migration trap with test-coverage-expert's missing canonical lifecycle scenario: project/global persistence, byte-stable reinstall, static-to-env-to-bearer-to-removal transitions, obsolete-field removal, and unrelated-setting preservation. Exercise self-defined and registry migration paths while preserving user-modified entries. Fresh-install success is not upgrade evidence.

  2. [test-coverage-expert] Prove both reserved native aliases are rejected from manifests through the real install consumer. -- The passing adapter-only assertions do not cover MCPDependency.from_dict, top-level versus explicit extra placement, configuration writing, or warning semantics. Extend tests/integration/test_mcp_install_flow.py with fixture-backed CLI cases that reparse TOML, retain a safe custom field, reject both aliases, and assert they are reported as ignored. This missing secure-by-default and governed-by-policy guard ranks above documentation-only followups.

  3. [auth-expert] Consolidate the four overlapping whitespace findings into strict whole-value matching and one malformed-reference regression matrix. -- Auth, architecture, supply-chain security, and logging reproduced the same classification boundary defect. Use fullmatch and ASCII-space bearer separation; cover final LF on both placeholder spellings, bearer terminal LF, embedded CR/LF, and Unicode whitespace. Assert omission from native and static fields plus a value-free warning. Manual probes currently provide no lasting secure-default regression guard; keep the fix local to Codex.

  4. [cli-logging-expert] Escape control characters in displayed server and skipped-header identifiers. -- The plain-console probe rendered a forged-looking extra status line from a header name. Escape identifiers only for display, preserve configuration names, and test that LF/CR cannot create extra status lines and synthetic secret values never appear. This is a distinct diagnostic-integrity issue, not evidence of an end-to-end exploit.

  5. [doc-writer] Qualify the remaining GitHub Actions template-preservation sentence in the canonical manifest reference. -- docs/src/content/docs/reference/manifest-schema.md still implies these templates survive unchanged, but Codex warns and omits remote headers containing them. State that APM does not evaluate GitHub Actions templates and Codex skips such headers with a warning; avoid duplicating the supported-shape rules elsewhere.

Architecture

classDiagram
    direction LR
    class MCPClientAdapter {
      <<AbstractBase>>
      +render_server_config(server_info) dict
      +configure_mcp_server()
      +_merge_extra(config, server_info) dict
      +_resolve_variable_placeholders(value, resolved_env, runtime_vars)
    }
    class CodexClientAdapter {
      <<Adapter>>
      +_format_server_config(server_info)
      +get_current_config()
      +update_config(config_updates)
    }
    class MCPDependency {
      <<Dataclass>>
      +headers
      +extra
      +from_dict(d)
      +validate(strict)
    }
    class MCPVocabulary {
      <<Module>>
      _HARNESS_EXTRA_ALIASES
      _EXTRA_DENYLIST
    }
    class BasePlaceholderSyntax {
      <<Module>>
      _ENV_VAR_RE
    }
    class SimpleRegistryClient
    class RegistryIntegration
    MCPClientAdapter <|-- CodexClientAdapter
    CodexClientAdapter *-- SimpleRegistryClient : registry_client
    CodexClientAdapter *-- RegistryIntegration : registry_integration
    CodexClientAdapter ..> BasePlaceholderSyntax : reuses accepted env syntax
    MCPClientAdapter ..> MCPVocabulary : filters passthrough
    MCPDependency ..> MCPVocabulary : filters parsed extras
    note for MCPClientAdapter "Base + subclass: shared resolution and passthrough; target-specific native rendering"
    note for MCPVocabulary "models/dependency/mcp.py owns the denylist; registry ownership is unchanged"
    class CodexClientAdapter:::touched
    class MCPVocabulary:::touched
    classDef touched fill:#fff3b0,stroke:#d47600
Loading
flowchart TD
    A["apm install: Codex adapter rendering boundary"] --> B["MCPClientAdapter.render_server_config<br/>src/apm_cli/adapters/client/base.py"]
    B --> C["CodexClientAdapter._format_server_config<br/>src/apm_cli/adapters/client/codex.py"]
    C --> D{"_raw_stdio present?"}
    D -->|yes| S["Existing stdio resolution and _merge_extra"]
    D -->|no| E{"remotes and not packages?"}
    E -->|no| P["Existing package launcher path<br/>missing packages raises ValueError"]
    E -->|yes| F{"SSE, empty URL, or non-HTTPS outside loopback?"}
    F -->|yes| G["[I/O] _rich_warning; return None"]
    G --> H["render_server_config raises ValueError"]
    F -->|no| I["For each nonempty header:<br/>_resolve_variable_placeholders"]
    I --> J{"_CODEX_BEARER_VALUE_RE.match<br/>and authorization header?"}
    J -->|yes| K["Set bearer_token_env_var"]
    J -->|no| L{"_CODEX_ENV_HEADER_VALUE_RE.match?"}
    L -->|yes| M["Add env_http_headers entry"]
    L -->|no| N{"_CODEX_UNSUPPORTED_REFERENCE_RE.search?"}
    N -->|yes| O["Collect unsupported header name; omit value"]
    N -->|no| Q["Add static http_headers entry"]
    K --> R["After all headers"]
    M --> R
    O --> R
    Q --> R
    R --> T{"unsupported_headers nonempty?"}
    T -->|yes| U["[I/O] _rich_warning without header values"]
    T -->|no| V["Assemble scalar and header maps"]
    U --> V
    V --> W["[I/O when input references remain]<br/>_warn_input_variables(http_headers)"]
    W --> X["MCPClientAdapter._merge_extra<br/>reject model-owned _EXTRA_DENYLIST"]
    X --> Y["Return native mapping; render_server_config performs no config write"]
    S --> Y
    P --> Y
Loading

Recommendation

Recommend a bounded in-PR revision centered on the unchanged-reinstall migration gap, backed by automated upgrade/lifecycle and manifest-to-install alias tests. Fold the local exact-match, diagnostic-escaping, and documentation corrections into that revision, then collect evidence on the resulting head. The existing green tests are useful but insufficient for those promises. This is an advisory recommendation to the maintainer, not a shipping decision or decision label.


Full per-persona findings

python-architect

  • [recommended] Use strict whole-value matching for native runtime header references at src/apm_cli/adapters/client/codex.py:333
    The new expressions use ^...$ with match(), but Python's $ also matches before a final newline. An exact-head, in-memory probe showed '${TOKEN}\n' matching TOKEN while consuming only 8 of 9 characters; '${env:TOKEN}\n' likewise consumed 12 of 13. The bearer expression also accepts an embedded newline because its separator is \s+. These malformed values therefore take a native-field branch before the unsupported-reference warning, rather than satisfying the packet's warn-and-skip contract. MCPDependency.validate rejects CR/LF in modeled manifest headers, so this is not evidence of a manifest-level security bypass; the formatter also accepts registry/server-info data, and its own exact-value boundary is too permissive. No install lifecycle or outgoing HTTP was executed.

Design patterns

  • Used in this PR: Adapter -- CodexClientAdapter translates neutral header declarations into Codex-native fields.

  • Used in this PR: Base + subclass -- MCPClientAdapter retains shared placeholder resolution and passthrough filtering; Codex adds only target-specific representation.

  • Pragmatic suggestion: none -- the current shape is the simplest correct design at this scope; fix the local match predicates without broadening shared parser semantics.

    Suggested: Use fullmatch() for both native-value expressions and reject control whitespace in the bearer separator, using an ordinary-space separator if that is the intended contract. Add focused formatter regressions for terminal LF on both placeholder spellings and embedded LF/CR in the bearer separator; assert omission plus a value-free warning.

    Proof (manual, manual-only): Malformed control-character references are currently recognized as native runtime header references instead of being skipped. python3 AST-extracted regex assignments from git show c12d2cb: both trailing-LF forms matched a strict prefix; bearer with embedded LF matched. No repository imports or writes.

test-coverage-expert

  • [recommended] Exercise native header persistence through the real install lifecycle. at tests/integration/test_required_lifecycle_state_machine.py
    The formatter regression traps pass, including the test under tests/integration/test_wave2_adapters_coverage.py, but that test calls _format_server_config and inspects a dictionary: its proof tier is unit, not integration. Searching tests/**/*.py for env_http_headers and bearer_token_env_var found assertions only in that formatter test and the two unit files. The existing test_install_loopback_http_remote_is_byte_idempotent_for_requested_targets exercises real config writes through CliRunner but supplies no headers. The canonical reinstall lifecycle test covers Copilot skills/instructions, not these Codex fields. Thus no exercised transition protects TOML persistence, stable reinstall, or removal of an obsolete native header field. The brief explicitly marks new lifecycle evidence as planned, not executed. This is a coverage gap, not a demonstrated product failure.

    Suggested: Add test_required_codex_remote_headers_survive_reinstall_and_replacement to the existing canonical lifecycle module, using ApmLifecycleRunner with isolated HOME/APM_HOME. A separate scenario in that module is justified because the existing reinstall test is a Copilot primitive/alias matrix, not an MCP configuration transition. Drive install -> identical install -> change a managed header from static to whole-value environment reference -> install -> change to bearer reference -> install -> remove the header -> install. Reparse the real TOML after each step, assert the expected native field and absence of obsolete fields, compare bytes on identical reinstall, and preserve an unrelated setting sentinel. Cover project and global scope. Extending the existing CliRunner loopback test with header assertions is useful interim integration evidence, but does not replace the real-binary lifecycle signal.

    Proof (missing, e2e): Installing and reinstalling my Codex MCP server preserves runtime header references and my unrelated settings without retaining replaced header fields.

  • [recommended] Add a manifest-to-install test for both reserved Codex aliases. at tests/integration/test_mcp_install_flow.py
    The new test_codex_remote_extra_cannot_inject_env_sourced_auth passes, but supplies _extra directly to the formatter. It does not exercise MCPDependency.from_dict, the top-level versus explicit-extra paths, or the generated config through install. Searching all Python tests for the two native alias names found no manifest-to-install scenario; reading the parser tests showed reserved command/type coverage, not the new aliases. The existing install passthrough scenario is OpenCode-only. The architecture mutation fixture checks removal of environment from the static denylist, so it does not supply functional proof for the new Codex consumer path. A regression in parser filtering or reporting could therefore survive the new adapter-only trap.

    Suggested: Extend the existing safe-passthrough install fixture with test_install_codex_rejects_native_header_alias_passthrough, parametrized over top-level and explicit extra placement. Install a self-defined Codex remote containing bearer_token_env_var and env_http_headers injection attempts plus a safe custom field, without mocking the parser, integrator, adapter, or writer. Reparse the generated TOML, assert both injected aliases are absent and the safe field remains, and assert the warning describes the aliases as ignored rather than preserved. Keep this a fixture-backed CLI test; actual Codex execution or outgoing HTTP inspection is unnecessary.

    Proof (missing, integration-with-fixtures): A manifest cannot inject Codex authentication through reserved passthrough aliases, while safe custom settings still install.

auth-expert

  • [recommended] Require a full value match and valid Bearer separator whitespace at src/apm_cli/adapters/client/codex.py:333
    At c12d2cb, both anchored regexes are used with match(), so Python's $ anchor accepts a position before a final newline. The Bearer pattern also uses Unicode-aware \s+, accepting embedded newlines and non-ASCII whitespace. A local adapter probe confirmed that ${TOKEN}\n becomes env_http_headers, while Bearer ${TOKEN}\n, Bearer\n${TOKEN}, and Bearer followed by U+00A0 and ${TOKEN} become bearer_token_env_var, all without a warning. These are not exact supported header values: the conversion silently removes malformed characters and activates runtime credentials instead of following the declared warn-and-skip contract. The probe exercised configuration generation only; no Codex process, outgoing HTTP, or test suite was run.

    Suggested: Use fullmatch() for both native-reference patterns and restrict the Bearer separator to ASCII spaces rather than \s+. Add regression cases for final LF, embedded CR/LF, and Unicode whitespace, asserting that no native or static header is emitted and that the warning does not expose the value.

    Proof (manual, unit): Malformed header references are silently converted into runtime credential lookups rather than skipped with a warning. Local .venv/bin/python -B probe: trailing-newline, bearer-trailing-newline, bearer-newline-separator, and bearer-unicode-space each emitted a native credential field with warnings=0.

supply-chain-security-expert

  • [recommended] Reject control-character variants before selecting native runtime headers. at src/apm_cli/adapters/client/codex.py:333
    The new match calls do not enforce the promised exact-value boundary: Python's $ accepts a position before a final newline, and the bearer pattern's \s+ also accepts embedded CR/LF. Exact-head regex probes accept ${SYNTHETIC_TOKEN} followed by LF and Bearer followed by LF and ${SYNTHETIC_TOKEN}. These become native environment references instead of reaching the malformed-reference warning and skip path. Manifest validation rejects CR/LF, but this adapter also consumes remote header records directly, so the formatter should enforce its own exact-match contract. This is a malformed-input handling gap, not a demonstrated credential leak or passthrough bypass.

    Suggested: Use fullmatch for both patterns and reject CR/LF before classification; constrain bearer scheme separation to the intended horizontal whitespace. Add formatter regressions for trailing LF on both supported forms and embedded LF/CR in bearer separation, asserting warning-and-skip without printing values.

    Proof (manual, static): Malformed header references can currently be classified as supported runtime references instead of being skipped. python3 -B extracted only regex assignments from git show c12d2cb; trailing-LF env and bearer values and embedded-LF bearer separation all returned accepted=True. No test suite or live network used.

cli-logging-expert

  • [recommended] Reject trailing-newline references instead of silently accepting them at src/apm_cli/adapters/client/codex.py:337
    The new patterns use $ with match(), which accepts a position before a final newline. On candidate c12d2cb, a direct adapter probe with '${TOKEN}\n' produced env_http_headers={'X-Project': 'TOKEN'} and no skip warning. This contradicts the exact-value contract and silently normalizes malformed input rather than taking the actionable warn-and-skip path.

    Suggested: Use fullmatch() for both native-header patterns and add focused cases for trailing newline on bare and Authorization bearer references; assert omission plus the skipped-header warning.

    Proof (manual, unit): A trailing-newline reference currently bypasses the promised skipped-header diagnostic. PYTHONDONTWRITEBYTECODE=1 .venv/bin/python inline adapter probe on c12d2cb: '${TOKEN}\n' -> env_http_headers={'X-Project': 'TOKEN'}, skip_warnings=0.

  • [recommended] Escape control characters in skipped-header diagnostic identifiers at src/apm_cli/adapters/client/codex.py:347
    The warning interpolates header names and the server name directly. Rich markup is already disabled, and header values are correctly omitted, but control characters are not escaped. A direct adapter probe through the plain console fallback with header name 'X-Header\n[+] Forged success' rendered a second line beginning '[+] Forged success'. This demonstrates ambiguous diagnostic display at the adapter boundary, not a claim of a validated end-to-end exploit.

    Suggested: Escape control characters in the displayed identifiers locally while retaining the original configuration names. Add a focused rendering assertion that newline and carriage-return names cannot create extra status lines and that a synthetic secret header value never appears.

    Proof (manual, unit): Skipped-header identifiers can currently introduce misleading extra lines in plain terminal output. PYTHONDONTWRITEBYTECODE=1 .venv/bin/python inline probe on c12d2cb with console fallback forced: captured '[!] Skipping header(s) X-Header\n[+] Forged success ...'.

devx-ux-expert

  • [recommended] Reinstall does not repair an existing APM-managed Codex header configuration at src/apm_cli/integration/mcp_integrator_install.py:951
    Users already affected by this bug can upgrade APM and rerun apm install without receiving the fix. In a hermetic CliRunner probe, I installed a self-defined remote using the exact 07a465b Codex formatter patched into the candidate's install pipeline, then restored the c12d2cb formatter and reinstalled the unchanged manifest. Both invocations exited 0, but the generated config retained http_headers.X-Key = '${TOKEN}' rather than env_http_headers.X-Key = 'TOKEN'. The second invocation reported 'already configured' and 'All servers up to date'. The install branch checks stored manifest drift before deciding to invoke the formatter, so this adapter-only rendering change never reaches an unchanged existing installation. This is an upgrade-path gap, not a claim that a complete base checkout was tested.

    Suggested: Add a narrowly scoped migration or render-version refresh for provenance-owned Codex entries that still match the old generated baseline. Preserve user-modified entries, unrelated settings, and project/user scope. Add a lifecycle regression starting with the old managed literal-placeholder output, then reinstall the unchanged manifest and assert native environment-header fields replace it. Cover the equivalent registry installation branch as well.

    Proof (manual, e2e): Upgrading APM and reinstalling an unchanged manifest does not repair previously generated Codex environment-header configuration. Hermetic CliRunner: install --no-policy with base formatter, then candidate reinstall; exits 0/0; literal http_headers.X-Key remained; output: All servers up to date.

doc-writer

  • [recommended] Qualify the GitHub Actions template-preservation claim for Codex headers. at docs/src/content/docs/reference/manifest-schema.md:678
    Section 4.2.4 still says GitHub Actions templates are intentionally left untouched. At c12d2cb, Codex's new unsupported-reference detector matches '${{ secrets.API_KEY }}', so a remote header containing that template is warned about and omitted rather than preserved. This is a distinct residual contradiction after the resolved runtime-header documentation fix. Readers and agents relying on the reference should not expect that header to survive installation.

    Suggested: Replace the blanket sentence with: 'APM does not evaluate GitHub Actions templates (${{ ... }}); Codex skips remote headers containing them with a warning.' Keep the supported-shape rules in this canonical section rather than repeating them in the consumer guide.

This panel is advisory. It does not block merge. Re-apply the panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.

…tract

Preserve unchanged-install behavior and document intentional declaration refresh. Exercise project/global persistence, scoped repair, passthrough rejection, malformed references, and safe diagnostics.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

Codex runtime headers now have exact-reference mapping and tested, intentional declaration repair; the delta panel finds no remaining code concerns, while remote CI and evidence verification remain pending.

panel-mode=delta; personas=python-architect,test-coverage-expert,auth-expert,supply-chain-security-expert,cli-logging-expert,devx-ux-expert,doc-writer,apm-ceo

cc Eden (@edenfunf) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

At verified local HEAD 3aba462, all seven independent delta specialists returned zero findings. The prior exact-match, diagnostic-escaping, manifest-install coverage, lifecycle coverage, and template-documentation recommendations are addressed. Coverage independently reran all four project/global lifecycle cases and 30 manifest-install cases; the supplied exact-head aggregate records 579 passed and 18 subtests passed, with zero skips. Coverage also audited eleven production mutation probes that failed at their intended assertions, followed by restored-source success. These are mixed-tier local results, not 579 integration scenarios or proof of live Codex HTTP behavior. I also read the completed exact-head lint log: ruff, formatting, YAML/relative-path/length, pylint, auth, and architecture checks passed.

The first panel's DevX automatic-migration recommendation is WITHDRAWN AS OUT OF SCOPE, not implemented, deferred, or silently fixed. I adopt that correction to my prior recommendation. Neither declaration drift nor existing ownership proves generated output is untouched. In tests/integration/test_required_lifecycle_state_machine.py, test_required_codex_legacy_header_noop_and_declaration_repair asserts assert unchanged.files == before.files: unchanged seeded legacy output remains a no-op. The bounded repair is an intentional equivalent ${VAR}->${env:VAR} declaration change followed by the original install command with identical scope and targets. Replacement drops the selected entry's manual startup_timeout_sec field; review/back up is essential, not optional reassurance. The same test asserts assert unrelated_file.read_bytes() == unrelated_bytes and assert opposite_path.read_bytes() == opposite_bytes. This is seeded-state repair evidence, not automatic migration or a full historical-binary upgrade. No provenance hashes or shared unchanged-install skip changes are requested.

The remaining prior coverage concerns have executable guards: tests/integration/test_required_lifecycle_state_machine.py::test_required_codex_runtime_headers_follow_declaration_changes asserts assert repeated.files == installed.files, and tests/integration/test_mcp_install_flow.py::test_install_codex_rejects_native_header_passthrough asserts assert "bearer_token_env_var" not in server, assert "env_http_headers" not in server, and assert server["myField"] == "safe-user-setting". The genuine owner-touch-final.json identifies the existing models/dependency/mcp.py (_EXTRA_DENYLIST) owner, not a new policy authority. These results support the scoped code recommendation; they do not complete the coordinator's pending semantic evidence verification. There is no current specialist disagreement or demonstrated defect to justify further code revision. The candidate is not yet pushed, so remote CI and final operational readiness are not established.

Dissent. All seven delta specialists agree. The change from the first CEO recommendation reflects explicit scope authority and new executable evidence: automatic migration is withdrawn as out of scope, while the bounded repair and prior in-scope gaps are now tested.

Aligned with: Exact environment references map to native Codex runtime fields; persisted declaration transitions are tested without claiming live runtime or automatic upgrade coverage. Native mappings avoid secret materialization; malformed references are omitted, diagnostic identifiers are escaped, and reserved aliases are tested through installation. The existing shared denylist remains authoritative; detector output and behavioral/static mutation evidence support that ownership, with semantic verification still pending. The correction remains Codex-local, preserves shared parser semantics, and leaves sibling enabled/OpenCode work outside this PR. Preserve edenfunf's attribution and both original commits, together with the existing CODEOWNERS reviewer requests. Unchanged installs remain stable; intentional same-command, same-scope repair has explicit backup guidance because selected-entry manual additions are replaced.

Panel summary

Persona B R N Takeaway
python-architect 0 0 0 Exact-reference matching is repaired, shared ownership is preserved, and declaration-refresh tests cover the bounded repair contract. No new architecture findings.
test-coverage-expert 0 0 0 Prior coverage gaps are closed: all four real lifecycle cases and 30 manifest-install cases pass independently; exact-head 579-case and mutation logs corroborate the scoped contract.
auth-expert 0 0 0 At 3aba462, exact matching, ASCII separators, case preservation, secret-free native mapping, and alias filtering hold; prior auth finding resolved. Four focused tests and 12 subtests passed.
supply-chain-security-expert 0 0 0 Alias authority unchanged; recorded install/mutation evidence closes gaps. Malformed/diagnostic folds omit values. Enabled remains reserved; no auto-migration. No delta concerns; CI not certified.
cli-logging-expert 0 0 0 Prior logging findings resolved. Escaped names, secret-free actionable warnings, and preserved input warnings verified: 11 focused tests passed on 3aba462. No new logging concerns.
devx-ux-expert 0 0 0 Withdraw prior migration advice as out of scope, not fixed. Exact-head evidence supports opt-in repair, documented selected-entry edit loss, and unrelated-state preservation. No new DevX findings.
doc-writer 0 0 0 The template claim is corrected; runtime-header scope and intentional same-scope repair are documented without promising automatic migration or selected-entry edit preservation.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 1 follow-ups

  1. [test-coverage-expert] Finish the coordinator's semantic evidence verification and reconcile the PR Scenario Evidence table with the exact-head records. -- Coverage verified local execution and the genuine existing-owner detector result, but could not audit the PR table or certify canonical semantic verification. This is operational evidence completion, not a new code finding or a claim that the table is absent.

Recommendation

The scoped code is suitable to ship on the available local evidence; final operational readiness remains unconfirmed. Recommend completing semantic evidence verification and, after an authorized push, observing GitHub CI on the pushed head before declaring the delivery ready. Preserve author attribution, original commits, and the existing danielmeppiel and sergio-sisternes-epam CODEOWNERS requests. Do not expand into automatic migration or shared skip behavior. This is advisory input to the maintainer, not authorization to push or merge.


Full per-persona findings

python-architect

No findings.

test-coverage-expert

No findings.

auth-expert

No findings.

supply-chain-security-expert

No findings.

cli-logging-expert

No findings.

devx-ux-expert

No findings.

doc-writer

No findings.

This panel is advisory. It does not block merge. Re-apply the panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.

@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_now

Codex MCP headers now preserve portable runtime references without persisting secrets; exact-head tests, ownership evidence and completed CI support shipping the scoped fix, subject to human review.

panel-mode=delta; personas=python-architect,test-coverage-expert,doc-writer,apm-ceo

cc Eden (@edenfunf) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

For pushed HEAD 0fefe8c against authoritative base d68f052, architecture and documentation report zero new findings. Coverage's sole recommendation was an artifact-labeling omission, not missing functional coverage. It was folded after that return: I verified all six scenario_groups have principles and all five table_row_principles keys exactly match table_row_mapping in head-0fefe8c8/scenario-evidence.json. The consolidated mapping is Authorization/API-key/alternate-env routing -> portability-by-manifest + secure-by-default; mixed omission/warnings -> secure-by-default + devx; static preservation -> portability-by-manifest. The original author narrative and historical checks remain distinct from current evidence. In tests/integration/test_mcp_install_flow.py::test_install_codex_exact_runtime_headers_do_not_materialize_secrets, the passing assertions are assert server == {"http_headers": {"X-Static": "literal-header"}, **expected}, assert secret not in config_text, and assert secret not in result.output. Coverage independently ran 30 fixture-install cases and four installed-CLI lifecycle cases. I read the restored final-head record and log: 579 passed and 18 subtests passed, zero skips, after all eleven mutation probes were killed. This is mixed-tier evidence, not 579 integration scenarios or live Codex HTTP verification.

The prior provisional operational concerns are now closed on the supplied evidence, rather than carried forward as stale recommendations. checks-terminal.json and runs-terminal.json establish completed success on this exact head for both Linux shards, Windows Compatibility, Lifecycle, Coverage Combine, lint, architecture, both CodeQL analyses, spec conformance, docs build, NOTICE and the gate job: CI, gate job. The watch log ends with terminal results; docs deployment is skipped and the separate CodeQL summary and eligibility advisory are neutral, not failures or substitutes for the successful analyses. lint-final-head.log also records every current local lint check passing. architecture-evidence.json is version 2, names the exact base/head and existing models/dependency/mcp.py (_EXTRA_DENYLIST) owner, and supplies four real consumer tests. owner-semantic-preflight.json records schema validity and successful recomputation through the actual terminal-evidence verifier for those four test IDs. This closes the ownership-evidence gap without treating the evidence-only preflight as delivery completion; the final completion CLI check remains a subsequent orchestration step, not a newly discovered code defect.

The scope and communication remain appropriately narrow: the delta from panel 2 integrates authorized main and relocates the attributed Codex note into Unreleased/Fixed; the underlying header implementation is unchanged. Automatic migration advice was explicitly withdrawn as out of scope, not fixed or deferred. In tests/integration/test_required_lifecycle_state_machine.py::test_required_codex_legacy_header_noop_and_declaration_repair, assert unchanged.files == before.files proves the seeded legacy no-op, while assert unrelated_file.read_bytes() == unrelated_bytes and assert opposite_path.read_bytes() == opposite_bytes defend preservation outside the selected entry. An intentional equivalent ${VAR}->${env:VAR} declaration refresh with the same command, scope and targets replaces that entry and loses its manual startup_timeout_sec field; the review/back-up warning remains essential. This is not a historical-binary upgrade, untouched-output provenance or hash authority. No live Codex HTTP test or sibling enabled-policy import is needed for this scope. The technical evidence supports code readiness, while pr-terminal.json separately records an open, MERGEABLE PR whose required human review policy is still outstanding; technical mergeability does not grant permission to merge.

Evidence completion after synthesis: The final completion JSON passed the published schema and the real exact-base/head owner semantic verifier, including all four manifest-install alias cases. GitHub still reports MERGEABLE with its human-policy requirements outstanding: code-owner review and last-push approval remain required. No merge or auto-merge was performed.

Dissent. There is no current specialist disagreement. Coverage's historical artifact-only recommendation is preserved above as resolved after its return; the earlier CI caveats are superseded by exact-head terminal evidence, and withdrawn automatic-migration advice is not an outstanding follow-up.

Aligned with: Exact Authorization, API-key and alternate environment references map to native runtime fields; literal headers remain unchanged, with fixture and lifecycle evidence. Tests defend non-materialization of secrets, omission and safe warnings for unsupported references, and prevention of native-alias passthrough. The existing shared denylist remains the sole owner; four executed consumer cases, static mutation evidence and the semantic verifier receipt support that boundary. The fix retains the Codex-local representation boundary and shared parser semantics; Windows CI passes without claiming live multi-client HTTP certification. The attributed release note, original contributor commits and author narrative are preserved; danielmeppiel and sergio-sisternes-epam remain requested reviewers. Unchanged installs stay stable; deliberate same-command, same-scope refresh has an explicit selected-entry replacement cost and review/back-up guidance.

Panel summary

Persona B R N Takeaway
python-architect 0 0 0 No new architecture findings at 0fefe8c: merged-main additions preserve the Codex boundary, and exact-head evidence closes the prior ownership-verification gap.
test-coverage-expert 0 1 0 Exact-head coverage and owner evidence verified; 34 focused cases independently pass. No code coverage gap; add scenario principle labels. Final-head CI remains pending.
doc-writer 0 0 0 Codex is correctly under Unreleased/Fixed alongside Cursor; repair guidance retains its scoped replacement warning. No documentation findings; final-head remote CI remains pending.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Recommendation

Recommend shipping this scoped code on the verified final-head evidence; no current specialist finding remains outstanding. Complete the planned final completion CLI semantic check and obtain the required human review through the existing reviewer requests. Those procedural steps do not justify inventing a code follow-up or reviving withdrawn migration advice. Preserve author attribution and the documented selected-entry replacement warning. This is advisory code-readiness input only, not merge permission or an instruction to merge or enable auto-merge.


Full per-persona findings

python-architect

No findings.

test-coverage-expert

  • [recommended] Complete the scenario-to-principle mapping without rewriting the author's historical evidence.
    The actual PR body has five user-facing Test rows, but no standardized Scenario Evidence section or principle column. scenario-evidence.json now correctly maps all five rows to executed exact-head tests and separates historical checks from current proof, closing the previous test-traceability uncertainty. However, its scenario groups and row mapping still contain no principle labels; searching the entire artifact for 'principle' returned zero occurrences. This is the remaining scenario-mapping requirement, not a missing functional test or a reason to broaden the implementation. The independently executed fixture tests already defend the promises.

    Suggested: Add principle labels to the five mapped rows in the evidence artifact and consolidated advisory: portability-by-manifest for native reference routing and literal preservation, secure-by-default for non-materialization and omission of unsupported references, and devx for actionable warnings. Preserve the original author narrative, historical Claude verification, and explicit tier distinctions; no source changes or additional test runs are needed.

    Proof (passed, integration-with-fixtures): My exact environment references install as native variable names while static values remain unchanged and secret values are not persisted. .venv/bin/python -m pytest -p no:cacheprovider -o addopts= -q tests/integration/test_mcp_install_flow.py -k install_codex
    30 passed, 39 deselected in 0.91s

doc-writer

No findings.

This panel is advisory. It does not block merge. Re-apply the panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-review-worker. This comment is AI-generated and may contain errors.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 44127b6 into microsoft:main Sep 30, 2026
19 checks passed
Daniel Meppiel (danielmeppiel) added a commit to abhishekacharya200/apm that referenced this pull request Nov 10, 2026
Folds the remaining gaps against the apm-scope:v1 record on microsoft#3393 on
top of the contributor's project-scope reshape.

- User-scope Codex output is byte-identical to main again: the stdio
  entry keeps its historical key order (cwd after args), and the
  env_vars passthrough reservation is reverted because it changed every
  scope's output for manifests that set extra.env_vars. At project scope
  the modeled env_vars still wins over extra through the shadow guard.
- The legacy upgrade now uses the lockfile fingerprint when one exists
  (v0.35.0+): a match proves APM wrote the entry even after the
  variable changed, a mismatch keeps it a conflict. Without a
  fingerprint the literal-or-current-environment check still applies
  and is logged at debug level.
- Names in the new warning and conflict text are ASCII-escaped like the
  microsoft#3042 header warning.
- The simulated-migration e2e records the legacy write's fingerprint as
  v0.35.0 did; real v0.35.0 -> head migration passes unchanged.

Addresses Copilot inline r4399350161 (recorded native hash) and panel
findings from python-architect, supply-chain-security-expert and
cli-logging-expert.

Co-authored-by: Copilot <[email protected]>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 11, 2026
…writing them (#3406)

* fix(codex): forward ${VAR} stdio env values with env_vars

A self-defined stdio dependency that declared a secret as
`FIGMA_API_KEY: ${FIGMA_API_KEY}` had the value resolved at install time and
written to `.codex/config.toml`, which sits in the repository. When the
variable was unset, the literal `${FIGMA_API_KEY}` was written instead and
handed to the server as text.

Codex can read a stdio server's variables from its own environment through
`env_vars`, so a value authored as exactly `${VAR}` under the key `VAR` is now
forwarded instead of resolved. Every other value, including a reference under
a different key, keeps the existing install-time resolution.

Args keep resolving against the forwarded names when the value is available,
so an argument that references the variable is unchanged.

* fix(codex): reserve env_vars and upgrade entries from the older formatter

env_vars now represents the modeled env field, so passthrough can no
longer request launch environment variables. Only an exact ${VAR} value
is forwarded, so authored whitespace keeps install time resolution. A
stdio entry the older formatter wrote counts as managed when its value
is the literal reference or the current environment value; anything
else stays a conflict, so manual edits are preserved.

* fix(codex): keep user scope unchanged and cover the #3393 scope end to end

Forwarding through env_vars now applies to project scope only, so
~/.codex and $CODEX_HOME output is the same as before. References Codex
cannot forward keep install time resolution and get a names-only
warning. On reinstall an APM-written value is replaced only for an
unchanged managed entry, with a credential rotation note; an edited or
unrecorded entry is preserved with manual reconciliation guidance.
Installed-CLI tests cover set and unset variables in both spellings,
static and mismatched values, user scope and migration. Docs and the
packaged apm-usage guidance describe the behavior.

* fix(codex): keep user-scope output identical; prove legacy upgrade

Folds the remaining gaps against the apm-scope:v1 record on #3393 on
top of the contributor's project-scope reshape.

- User-scope Codex output is byte-identical to main again: the stdio
  entry keeps its historical key order (cwd after args), and the
  env_vars passthrough reservation is reverted because it changed every
  scope's output for manifests that set extra.env_vars. At project scope
  the modeled env_vars still wins over extra through the shadow guard.
- The legacy upgrade now uses the lockfile fingerprint when one exists
  (v0.35.0+): a match proves APM wrote the entry even after the
  variable changed, a mismatch keeps it a conflict. Without a
  fingerprint the literal-or-current-environment check still applies
  and is logged at debug level.
- Names in the new warning and conflict text are ASCII-escaped like the
  #3042 header warning.
- The simulated-migration e2e records the legacy write's fingerprint as
  v0.35.0 did; real v0.35.0 -> head migration passes unchanged.

Addresses Copilot inline r4399350161 (recorded native hash) and panel
findings from python-architect, supply-chain-security-expert and
cli-logging-expert.

Co-authored-by: Copilot <[email protected]>

* docs(codex): note args references still resolve when env is forwarded

Addresses doc-writer panel finding on install-mcp-servers.md accuracy.

Co-authored-by: Copilot <[email protected]>

* chore(spec): record Mode B waiver for Codex env_vars rendering

The ownership and install changes apply the existing req-mf-013 matrix
to Codex: a same-key ${VAR} reference is passed through natively
(env_vars) and every other reference keeps install-time resolution with
a diagnostic. No manifest, lockfile schema, resolver or policy semantics
change, so no new requirement anchor is added.

apm-spec-waiver: Codex native env_vars rendering applies existing req-mf-013 (native pass-through where supported, diagnostic otherwise); no new normative requirement, schema or lockfile change.

Co-authored-by: Copilot <[email protected]>

* test(codex): cover extra.env_vars passthrough at both scopes end to end

The installed CLI keeps the modeled env_vars at project scope when a
manifest also sets extra.env_vars, and leaves user-scope passthrough
exactly as before. Pins the boundary the deferred passthrough-denylist
follow-up would change.

Addresses CEO follow-up from test-coverage-expert.

apm-spec-waiver: Codex native env_vars rendering applies existing req-mf-013 (native pass-through where supported, diagnostic otherwise); no new normative requirement, schema or lockfile change.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: abhishekacharya200 <[email protected]>
Co-authored-by: danielmeppiel <[email protected]>
Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/mcp-config MCP server configuration depth, transports, variable resolution. triage/recommended Automated advice completed; not human scope approval. type/bug Something does not work as documented.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Codex adapter writes ${VAR} MCP header values into static http_headers

4 participants