Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): run Codex unsandboxed on Windows to stop reject-by-policy (MUL-4957) (#5672)

Bohan Jiangfbe00ca16497
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index de91c89f2f..9f823e988e 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4178,6 +4178,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
agentEnvOverrides = task.Agent.CustomEnv
agentCustomArgs = task.Agent.CustomArgs
}
+ // Effective Codex CLI args the task will launch with, normalized through the
+ // same agent.NormalizeCodexLaunchArgs pipeline buildCodexArgs uses (shell
+ // unquoting + blocked-flag filtering), preserving its ExtraArgs
+ // (profile-fixed + daemon defaults) vs CustomArgs (per-agent custom_args)
+ // split so the filtering matches launch exactly. Threaded into execenv so
+ // the Windows sandbox decision can honor a `-c windows.sandbox=...` override
+ // that never lands in config.toml — even when it arrives shell-quoted —
+ // instead of silently downgrading a user's isolation opt-in (MUL-4957).
+ var codexSandboxArgs []string
+ if provider == "codex" {
+ extraArgs := append(append([]string{}, profileFixedArgs...), defaultArgsForProvider(d.cfg, provider)...)
+ codexSandboxArgs = agent.NormalizeCodexLaunchArgs(extraArgs, agentCustomArgs, effectiveMcpConfig, d.logger)
+ }
// Hermes: resolve the overlay source home through one resolver contract —
// the selection parsed from custom_args (agent.ParseHermesProfileArgs) plus
// the agent's custom_env HERMES_HOME feed execenv.ResolveHermesProfile, which
@@ -4232,6 +4245,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
HermesEnv: hermesEnv,
+ CodexCustomArgs: codexSandboxArgs,
Task: taskCtx,
})
if err != nil {
@@ -4255,6 +4269,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
HermesSourceHome: hermesSourceHome,
HermesSourceMustExist: hermesSourceMustExist,
HermesEnv: hermesEnv,
+ CodexCustomArgs: codexSandboxArgs,
Task: taskCtx,
}
if localAssignment != nil {
diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.go
index 00edd875b7..014aad1bd8 100644
--- a/server/internal/daemon/execenv/codex_home.go
+++ b/server/internal/daemon/execenv/codex_home.go
@@ -83,6 +83,12 @@ type CodexHomeOptions struct {
// Only meaningful when the policy resolves to workspace-write; ignored on
// darwin danger-full-access. See task_home.go and MUL-4856.
WritableRoots []string
+ // CodexCustomArgs are the effective Codex CLI args this task will launch
+ // with (daemon defaults + profile-fixed + per-agent custom_args). Only the
+ // Windows sandbox decision reads them, to honor a `-c windows.sandbox=...`
+ // override that never lands in config.toml. See resolveWindowsSandboxState
+ // and MUL-4957.
+ CodexCustomArgs []string
}
// prepareCodexHome is a thin wrapper around prepareCodexHomeWithOpts kept for
@@ -93,6 +99,96 @@ func prepareCodexHome(codexHome string, logger *slog.Logger) error {
return prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{GOOS: "linux"}, logger)
}
+// sharedConfigPresence is the tri-state existence of the shared
+// ~/.codex/config.toml copy source. It is three-valued so a stat that fails for
+// a reason other than "not found" (permission/IO) never masquerades as a
+// confident "the user has no config" — which would let the daemon loosen to
+// danger-full-access on doubt. See resolveWindowsSandboxState (MUL-4957).
+type sharedConfigPresence int
+
+const (
+ // sharedConfigAbsent: the shared config.toml is confidently not present
+ // (os.IsNotExist), so an absent per-task copy is a genuine "unconfigured".
+ sharedConfigAbsent sharedConfigPresence = iota
+ // sharedConfigPresent: the shared config.toml exists.
+ sharedConfigPresent
+ // sharedConfigUndecidable: the stat failed for a reason other than
+ // not-found; the daemon cannot tell whether the user has a config.
+ sharedConfigUndecidable
+)
+
+// statSharedCodexConfig classifies the shared ~/.codex/config.toml (the copy
+// source) into the tri-state above, distinguishing a genuine absence from a
+// stat that could not complete.
+func statSharedCodexConfig(sharedHome string) sharedConfigPresence {
+ if sharedHome == "" {
+ return sharedConfigAbsent
+ }
+ _, err := os.Stat(filepath.Join(sharedHome, "config.toml"))
+ switch {
+ case err == nil:
+ return sharedConfigPresent
+ case os.IsNotExist(err):
+ return sharedConfigAbsent
+ default:
+ return sharedConfigUndecidable
+ }
+}
+
+// resolveWindowsSandboxState determines, for a Windows task, whether a native
+// Codex sandbox is configured — across the per-task config.toml and the
+// effective custom args — failing closed (Undecidable) when it cannot tell.
+//
+// Two signals it does NOT gather itself (the caller does) keep the fail-closed
+// logic unit-testable without faulting the filesystem, and close MUL-4957's
+// round-3 must-fix where a failed sync could be misread as "unconfigured":
+//
+// - configSyncErr: the error (if any) from syncing the shared config.toml
+// into this per-task home. Non-nil means the per-task config.toml is
+// unreliable — stale from a prior run, or never (re)written — so neither its
+// contents nor its absence reflect the user's intent. Fail closed.
+// - sharedPresence: whether the shared config.toml source exists. Only a
+// confident absence lets an absent per-task copy count as genuinely
+// unconfigured; a present-or-undecidable source whose per-task copy is
+// missing means the copy silently did not land, so fail closed.
+func resolveWindowsSandboxState(configFile string, configSyncErr error, sharedPresence sharedConfigPresence, customArgs []string, logger *slog.Logger) windowsSandboxConfig {
+ configState := classifyPerTaskWindowsSandbox(configFile, configSyncErr, sharedPresence)
+ state := resolveWindowsSandbox(configState, windowsSandboxFromCustomArgs(customArgs))
+ if state == windowsSandboxUndecidable && logger != nil {
+ logger.Error("codex sandbox: cannot determine Windows native sandbox config; keeping workspace-write and refusing to loosen to danger-full-access",
+ "config_file", configFile)
+ }
+ return state
+}
+
+// classifyPerTaskWindowsSandbox inspects the per-task config.toml given the
+// outcome of syncing it from the shared source, failing closed whenever the
+// file cannot be trusted or read.
+func classifyPerTaskWindowsSandbox(configFile string, configSyncErr error, sharedPresence sharedConfigPresence) windowsSandboxConfig {
+ // A failed shared→per-task sync leaves config.toml stale or missing; neither
+ // its contents nor its absence reflect the user's intent. Fail closed.
+ if configSyncErr != nil {
+ return windowsSandboxUndecidable
+ }
+ data, err := os.ReadFile(configFile)
+ switch {
+ case err == nil:
+ return windowsSandboxFromConfig(string(data))
+ case os.IsNotExist(err):
+ // Sync succeeded and the per-task config is absent. That is a genuine
+ // "no config" only when the shared source is confidently absent too; a
+ // present or undecidable source whose copy is missing means the copy
+ // did not land → fail closed rather than loosen.
+ if sharedPresence == sharedConfigAbsent {
+ return windowsSandboxAbsent
+ }
+ return windowsSandboxUndecidable
+ default:
+ // A read error (permission/IO) on a file the daemon just wrote.
+ return windowsSandboxUndecidable
+ }
+}
+
// prepareCodexHomeWithOpts creates a per-task CODEX_HOME directory and seeds
// it with config from the shared ~/.codex/ home. Auth is symlinked (shared),
// config files are copied (isolated). The per-task config.toml gets a
@@ -130,12 +226,19 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *s
// into a stale local copy.
logCodexAuthState(filepath.Join(codexHome, "auth.json"), logger)
- // Sync isolated files from the shared source.
+ // Sync isolated files from the shared source. Track the config.toml sync
+ // outcome specifically: on Windows a failed sync makes the per-task config
+ // untrustworthy, so the sandbox decision must fail closed rather than read a
+ // stale or absent copy as "unconfigured" and loosen (MUL-4957).
+ var configSyncErr error
for _, name := range codexCopiedFiles {
src := filepath.Join(sharedHome, name)
dst := filepath.Join(codexHome, name)
if err := syncCopiedFile(src, dst); err != nil {
logger.Warn("execenv: codex-home sync failed", "file", name, "error", err)
+ if name == "config.toml" {
+ configSyncErr = err
+ }
}
}
// Drop `[[skills.config]]` entries inherited from the user's
@@ -169,12 +272,29 @@ func prepareCodexHomeWithOpts(codexHome string, opts CodexHomeOptions, logger *s
}
// Write a daemon-managed sandbox block into config.toml. On macOS we may
- // need to fall back to danger-full-access because of openai/codex#10390;
- // see codex_sandbox.go for the full rationale.
- policy := codexSandboxPolicyFor(opts.GOOS, opts.CodexVersion)
+ // need to fall back to danger-full-access because of openai/codex#10390,
+ // and on Windows the daemon defaults to danger-full-access unless the user
+ // opted into a native windows.sandbox; see codex_sandbox.go for the full
+ // rationale. On Windows, resolve the native-sandbox state across the copied
+ // config and the effective custom args so an explicit user opt-in is honored
+ // and an undecidable config fails closed instead of loosening.
+ configFile := filepath.Join(codexHome, "config.toml")
+ winState := windowsSandboxAbsent
+ if resolveGOOS(opts.GOOS) == "windows" {
+ winState = resolveWindowsSandboxState(configFile, configSyncErr, statSharedCodexConfig(sharedHome), opts.CodexCustomArgs, logger)
+ }
+ policy := codexSandboxPolicyForConfig(opts.GOOS, opts.CodexVersion, winState)
policy.WritableRoots = opts.WritableRoots
- if err := ensureCodexSandboxConfig(filepath.Join(codexHome, "config.toml"), policy, opts.CodexVersion, logger); err != nil {
- logger.Warn("execenv: codex-home ensure sandbox config failed", "error", err)
+ if err := ensureCodexSandboxConfig(configFile, policy, opts.CodexVersion, logger); err != nil {
+ // The managed block is the authoritative on-disk sandbox policy. If it
+ // can't be written, config.toml keeps whatever it already had — on a
+ // reused home that may be a stale danger-full-access from a prior run —
+ // so the fail-closed policy just computed above would only exist in
+ // memory while the effective config silently stays loose. Abort rather
+ // than launch Codex with an unenforced sandbox: on fresh Prepare this
+ // fails the task; on Reuse the caller leaves env.CodexHome unset, which
+ // configureCodexTaskShellEnvironment then refuses to start (MUL-4957).
+ return fmt.Errorf("ensure codex sandbox config: %w", err)
}
// Disable Codex native multi-agent inside daemon-managed task sessions
diff --git a/server/internal/daemon/execenv/codex_sandbox.go b/server/internal/daemon/execenv/codex_sandbox.go
index 4f08be61ca..99b251ca29 100644
--- a/server/internal/daemon/execenv/codex_sandbox.go
+++ b/server/internal/daemon/execenv/codex_sandbox.go
@@ -8,6 +8,8 @@ import (
"runtime"
"strconv"
"strings"
+
+ "github.com/pelletier/go-toml/v2"
)
// Background
@@ -49,13 +51,44 @@ type codexSandboxPolicy struct {
WritableRoots []string
// Reason is a short human-readable label used in warn-level logs.
Reason string
+ // Hint is an optional, actionable remediation surfaced in warn-level logs
+ // when Mode is danger-full-access. It is empty when there is no generic
+ // action to surface (e.g. the Windows compatibility fallback, where
+ // enabling Codex's native sandbox is deferred follow-up work rather than a
+ // version bump), so the log omits the hint instead of showing an irrelevant
+ // one.
+ Hint string
+}
+
+// resolveGOOS returns goos, or runtime.GOOS when goos is empty. Callers pass an
+// explicit goos in tests; production leaves it empty to use the host platform.
+func resolveGOOS(goos string) string {
+ if goos == "" {
+ return runtime.GOOS
+ }
+ return goos
}
-// codexSandboxPolicyFor picks the right policy for the given platform and
-// detected Codex CLI version.
+// codexSandboxPolicyFor picks the default policy for the given platform and
+// detected Codex CLI version. It is the platform baseline; per-task user config
+// can refine it (see codexSandboxPolicyForConfig).
//
-// - Non-darwin: always workspace-write with network access (Landlock is not
-// affected by the macOS Seatbelt bug).
+// - Linux: workspace-write with network access. Landlock enforces the
+// filesystem sandbox and is not affected by the macOS Seatbelt bug.
+// - Windows: danger-full-access, as a deliberate compatibility choice.
+// Codex ships a native Windows sandbox (windows.sandbox = "unelevated" via
+// a Restricted Token, or "elevated"), but it is still experimental with
+// known reliability limitations, so the daemon does not enable it by
+// default. When no native windows.sandbox is configured, Codex cannot
+// enforce workspace-write on Windows (it downgrades to read-only) and then
+// rejects non-safe mutation commands "by policy" — e.g. `multica issue
+// create` fails — because under approval_policy = "never" the request never
+// reaches the daemon's auto-approver. danger-full-access sidesteps that.
+// Enabling the native sandbox is tracked as separate follow-up work. See
+// MUL-4957. A user who has opted into windows.sandbox (via config.toml or a
+// `-c` custom arg) keeps workspace-write instead of this fallback, and an
+// undecidable config fails closed; that logic lives in
+// codexSandboxPolicyForConfig / resolveWindowsSandboxState.
// - darwin with a version at or above CodexDarwinNetworkAccessFixedVersion:
// workspace-write with network access (upstream bug fixed).
// - darwin otherwise (including when the version is unknown): fall back to
@@ -64,6 +97,12 @@ func codexSandboxPolicyFor(goos, detectedVersion string) codexSandboxPolicy {
if goos == "" {
goos = runtime.GOOS
}
+ if goos == "windows" {
+ return codexSandboxPolicy{
+ Mode: "danger-full-access",
+ Reason: "codex on windows: compatibility fallback; no native windows.sandbox configured, so workspace-write cannot be enforced (MUL-4957)",
+ }
+ }
if goos != "darwin" {
return codexSandboxPolicy{
Mode: "workspace-write",
@@ -86,7 +125,172 @@ func codexSandboxPolicyFor(goos, detectedVersion string) codexSandboxPolicy {
Mode: "danger-full-access",
NetworkAccess: false,
Reason: reason,
+ Hint: codexUpgradeHint(),
+ }
+}
+
+// windowsSandboxConfig is the tri-state of a native Codex Windows sandbox
+// selection. It is three-valued (not a bool) so an undecidable config fails
+// closed — the daemon never loosens to danger-full-access when it cannot
+// confirm the user's intent. See MUL-4957.
+type windowsSandboxConfig int
+
+const (
+ // windowsSandboxAbsent: confidently no native sandbox is selected anywhere,
+ // so the danger-full-access compatibility fallback is safe to apply.
+ windowsSandboxAbsent windowsSandboxConfig = iota
+ // windowsSandboxNative: a valid windows.sandbox = "unelevated"|"elevated"
+ // is selected, so keep workspace-write and let Codex enforce isolation.
+ windowsSandboxNative
+ // windowsSandboxUndecidable: the config could not be read/parsed, or holds
+ // a windows.sandbox value Codex does not accept. The daemon cannot tell
+ // whether the user asked for isolation, so it must NOT loosen — fail closed.
+ windowsSandboxUndecidable
+)
+
+// codexSandboxPolicyForConfig returns the platform default from
+// codexSandboxPolicyFor for linux/darwin. On Windows it applies the resolved
+// native-sandbox state (see resolveWindowsSandboxState): a user who opted into
+// windows.sandbox keeps workspace-write, an undecidable config fails closed to
+// workspace-write, and only a confidently absent sandbox gets the
+// danger-full-access compatibility fallback. See MUL-4957.
+//
+// This is intentionally the branch point for the eventual native-sandbox
+// rollout: flipping the Windows default later means writing windows.sandbox
+// ourselves and defaulting winState to native, not restructuring callers.
+func codexSandboxPolicyForConfig(goos, detectedVersion string, winState windowsSandboxConfig) codexSandboxPolicy {
+ if goos == "" {
+ goos = runtime.GOOS
+ }
+ if goos == "windows" {
+ return codexSandboxPolicyForWindows(winState)
}
+ return codexSandboxPolicyFor(goos, detectedVersion)
+}
+
+// codexSandboxPolicyForWindows maps a resolved native-sandbox state to a
+// policy. Native and Undecidable both keep workspace-write (Undecidable is the
+// fail-closed case — it never loosens on doubt); only a confidently absent
+// native sandbox gets the danger-full-access compatibility fallback.
+func codexSandboxPolicyForWindows(state windowsSandboxConfig) codexSandboxPolicy {
+ switch state {
+ case windowsSandboxNative:
+ return codexSandboxPolicy{
+ Mode: "workspace-write",
+ NetworkAccess: true,
+ Reason: "codex on windows: native windows.sandbox configured; keeping workspace-write so Codex enforces task isolation",
+ }
+ case windowsSandboxUndecidable:
+ return codexSandboxPolicy{
+ Mode: "workspace-write",
+ NetworkAccess: true,
+ Reason: "codex on windows: windows.sandbox config undecidable (unreadable/unparseable/invalid); failing closed to workspace-write rather than loosening (MUL-4957)",
+ }
+ default: // windowsSandboxAbsent
+ return codexSandboxPolicy{
+ Mode: "danger-full-access",
+ Reason: "codex on windows: compatibility fallback; no native windows.sandbox configured (MUL-4957)",
+ }
+ }
+}
+
+// windowsSandboxFromConfig classifies the windows.sandbox selection in a
+// config.toml body. Codex accepts only the exact-lowercase variants
+// "unelevated"/"elevated" and refuses to load a config with any other value, so
+// anything else present is treated as undecidable (fail closed) rather than a
+// safe "absent". Unparseable TOML is likewise undecidable — Codex would reject
+// the same file. An absent windows.sandbox key is a genuine "absent".
+func windowsSandboxFromConfig(config string) windowsSandboxConfig {
+ var probe struct {
+ Windows struct {
+ Sandbox string `toml:"sandbox"`
+ } `toml:"windows"`
+ }
+ if err := toml.Unmarshal([]byte(config), &probe); err != nil {
+ return windowsSandboxUndecidable
+ }
+ return classifyWindowsSandboxValue(probe.Windows.Sandbox)
+}
+
+// codexConfigOverrideValueRe matches the value token of a Codex `-c` /
+// `--config` windows.sandbox override, e.g. `windows.sandbox = "unelevated"`.
+// It tolerates whitespace around the dotted key and the `=`, matching Codex's
+// own lenient `-c` parsing.
+var codexWindowsSandboxOverrideRe = regexp.MustCompile(`^\s*windows\s*\.\s*sandbox\s*=`)
+
+// windowsSandboxFromCustomArgs classifies a native Windows sandbox selection
+// passed via Codex `-c windows.sandbox=...` / `--config windows.sandbox=...`
+// args. These never land in config.toml (they stay in argv and are applied on
+// top of it), so config-only detection would miss them — the MUL-4957 review's
+// second must-fix. Mirrors the override-parsing shape in server/pkg/agent's
+// buildCodexArgs: inline (`-c=windows.sandbox=x`) and two-token
+// (`-c windows.sandbox=x`) forms, last occurrence winning (Codex is last-wins).
+func windowsSandboxFromCustomArgs(args []string) windowsSandboxConfig {
+ state := windowsSandboxAbsent
+ for i := 0; i < len(args); i++ {
+ arg := args[i]
+ flag := arg
+ value := ""
+ hasInlineValue := false
+ if idx := strings.Index(arg, "="); idx > 0 {
+ flag = arg[:idx]
+ value = arg[idx+1:]
+ hasInlineValue = true
+ }
+ if flag != "-c" && flag != "--config" {
+ continue
+ }
+ if !hasInlineValue {
+ if i+1 >= len(args) {
+ continue
+ }
+ i++
+ value = args[i]
+ }
+ if !codexWindowsSandboxOverrideRe.MatchString(value) {
+ continue
+ }
+ // A windows.sandbox override token: take the part after its first `=`.
+ if eq := strings.Index(value, "="); eq >= 0 {
+ state = classifyWindowsSandboxValue(value[eq+1:])
+ }
+ }
+ return state
+}
+
+// classifyWindowsSandboxValue maps a raw windows.sandbox value (from config.toml
+// or a `-c` arg, possibly surrounded by whitespace/quotes) to a tri-state. Only
+// the exact-lowercase variants Codex accepts count as native; a present but
+// unaccepted value is undecidable (Codex would refuse the config); an empty
+// value is absent.
+func classifyWindowsSandboxValue(raw string) windowsSandboxConfig {
+ v := strings.TrimSpace(raw)
+ v = strings.Trim(v, `"'`)
+ v = strings.TrimSpace(v)
+ switch v {
+ case "":
+ return windowsSandboxAbsent
+ case "unelevated", "elevated":
+ return windowsSandboxNative
+ default:
+ return windowsSandboxUndecidable
+ }
+}
+
+// resolveWindowsSandbox folds per-layer states into one. Undecidable wins over
+// everything (any broken/ambiguous layer means fail closed), then Native over
+// Absent (an opt-in in any layer keeps isolation).
+func resolveWindowsSandbox(states ...windowsSandboxConfig) windowsSandboxConfig {
+ result := windowsSandboxAbsent
+ for _, s := range states {
+ if s == windowsSandboxUndecidable {
+ return windowsSandboxUndecidable
+ }
+ if s == windowsSandboxNative {
+ result = windowsSandboxNative
+ }
+ }
+ return result
}
// codexDarwinNetworkAccessFixed returns true if the given detected version is
@@ -262,12 +466,15 @@ func ensureCodexSandboxConfig(configPath string, policy codexSandboxPolicy, dete
if version == "" {
version = "unknown"
}
- logger.Warn("codex sandbox: falling back to danger-full-access on macOS",
+ attrs := []any{
"reason", policy.Reason,
"codex_version", version,
- "hint", codexUpgradeHint(),
"config_path", configPath,
- )
+ }
+ if policy.Hint != "" {
+ attrs = append(attrs, "hint", policy.Hint)
+ }
+ logger.Warn("codex sandbox: running unsandboxed with danger-full-access", attrs...)
}
if err := os.WriteFile(configPath, []byte(updated), 0o644); err != nil {
diff --git a/server/internal/daemon/execenv/codex_windows_sandbox_integration_test.go b/server/internal/daemon/execenv/codex_windows_sandbox_integration_test.go
new file mode 100644
index 0000000000..a327eda744
--- /dev/null
+++ b/server/internal/daemon/execenv/codex_windows_sandbox_integration_test.go
@@ -0,0 +1,49 @@
+package execenv
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// TestWindowsSandboxHonorsShellQuotedCustomArg is the MUL-4957 round-3 must-fix
+// 2 integration test. A `-c windows.sandbox=...` opt-in supplied shell-quoted
+// (as users commonly type custom_args) reaches Codex normalized by
+// agent.NormalizeCodexLaunchArgs; the Windows sandbox decision must consume the
+// SAME normalized args, not the raw tokens, or the two drift and the user's
+// isolation opt-in is silently downgraded. This locks the raw-args →
+// normalized → policy chain end to end across the two packages so they cannot
+// diverge again.
+func TestWindowsSandboxHonorsShellQuotedCustomArg(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ raw []string
+ }{
+ {"both tokens single-quoted", []string{"'-c'", "'windows.sandbox=unelevated'"}},
+ {"value double-quoted", []string{"-c", `"windows.sandbox=elevated"`}},
+ {"inline flag single-quoted", []string{"'-c=windows.sandbox=unelevated'"}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ // The raw tokens still carry shell quotes, so scanning them directly
+ // must NOT recognize the opt-in — this is the drift the bug was.
+ if got := windowsSandboxFromCustomArgs(tc.raw); got == windowsSandboxNative {
+ t.Fatalf("raw shell-quoted args unexpectedly recognized without normalization: %v", tc.raw)
+ }
+ // After the daemon's normalization the same args resolve to native,
+ // so the policy keeps workspace-write instead of loosening.
+ norm := agent.NormalizeCodexLaunchArgs(nil, tc.raw, nil, testLogger())
+ missing := filepath.Join(t.TempDir(), "config.toml")
+ state := resolveWindowsSandboxState(missing, nil, sharedConfigAbsent, norm, testLogger())
+ if state != windowsSandboxNative {
+ t.Fatalf("normalized %v -> state %v, want native", norm, state)
+ }
+ if p := codexSandboxPolicyForWindows(state); p.Mode != "workspace-write" {
+ t.Fatalf("policy mode = %q, want workspace-write (isolation preserved)", p.Mode)
+ }
+ })
+ }
+}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index dfde644814..4edb666106 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -81,7 +81,12 @@ type PrepareParams struct {
// blocklisted keys) used to expand ${VAR} in Hermes external_dirs so it
// matches what the Hermes child process actually sees. Only used for hermes.
HermesEnv map[string]string
- Task TaskContextForEnv // context data for writing files
+ // CodexCustomArgs are the effective Codex CLI args this task launches with
+ // (daemon defaults + profile-fixed + per-agent custom_args). Only the
+ // Windows sandbox decision reads them, to honor a `-c windows.sandbox=...`
+ // override that never lands in config.toml (MUL-4957).
+ CodexCustomArgs []string
+ Task TaskContextForEnv // context data for writing files
}
// TaskContextForEnv is the subset of task context used for writing context files.
@@ -343,7 +348,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
return nil, fmt.Errorf("execenv: prepare task home: %w", err)
}
env.TaskHome = taskHome
- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots}, logger); err != nil {
+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots, CodexCustomArgs: params.CodexCustomArgs}, logger); err != nil {
return nil, fmt.Errorf("execenv: prepare codex-home: %w", err)
}
if err := hydrateCodexSkills(codexHome, params.Task.AgentSkills, logger); err != nil {
@@ -452,7 +457,11 @@ type ReuseParams struct {
HermesSourceHome string
HermesSourceMustExist bool
HermesEnv map[string]string
- Task TaskContextForEnv // refreshed context files / skills
+ // CodexCustomArgs mirrors PrepareParams.CodexCustomArgs on reuse so the
+ // Windows sandbox decision honors a `-c windows.sandbox=...` override here
+ // too (MUL-4957).
+ CodexCustomArgs []string
+ Task TaskContextForEnv // refreshed context files / skills
}
// Reuse wraps an existing workdir into an Environment and refreshes context files.
@@ -555,7 +564,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
logger.Warn("execenv: refresh task home failed", "error", err)
}
env.TaskHome = taskHome
- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, ResumeSessionID: params.ResumeSessionID, IsLocalDirectory: params.LocalDirectory, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots}, logger); err != nil {
+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, ResumeSessionID: params.ResumeSessionID, IsLocalDirectory: params.LocalDirectory, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task.AgentID, params.Task.IssueID), WritableRoots: writableRoots, CodexCustomArgs: params.CodexCustomArgs}, logger); err != nil {
logger.Warn("execenv: refresh codex-home failed", "error", err)
} else {
env.CodexHome = codexHome
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index d82b5ad763..825d6c17a8 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -2,6 +2,7 @@ package execenv
import (
"encoding/json"
+ "errors"
"io"
"log/slog"
"os"
@@ -2582,6 +2583,78 @@ func TestEnsureCodexSandboxConfigDarwinFallsBack(t *testing.T) {
}
}
+// TestEnsureCodexSandboxConfigWindowsFallsBack pins MUL-4957: when a Windows
+// user has not opted into a native Codex sandbox, Codex cannot enforce
+// workspace-write and rejects mutation commands (e.g. `multica issue create`)
+// "by policy". The daemon therefore defaults Windows to danger-full-access and
+// emits no workspace-write keys.
+func TestEnsureCodexSandboxConfigWindowsFallsBack(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ configPath := filepath.Join(dir, "config.toml")
+
+ // No native sandbox configured → danger-full-access.
+ policy := codexSandboxPolicyForConfig("windows", "0.144.5", windowsSandboxAbsent)
+ if err := ensureCodexSandboxConfig(configPath, policy, "0.144.5", testLogger()); err != nil {
+ t.Fatalf("ensureCodexSandboxConfig failed: %v", err)
+ }
+
+ s, _ := os.ReadFile(configPath)
+ if !strings.Contains(string(s), `sandbox_mode = "danger-full-access"`) {
+ t.Errorf("expected danger-full-access fallback on windows, got:\n%s", s)
+ }
+ if strings.Contains(string(s), "sandbox_workspace_write") {
+ t.Errorf("should not emit any workspace-write keys on windows fallback, got:\n%s", s)
+ }
+}
+
+// TestEnsureCodexSandboxConfigWindowsRespectsUserSandbox pins the MUL-4957
+// must-fix: a Windows user who explicitly opted into a native Codex sandbox
+// (windows.sandbox = "unelevated"|"elevated") must NOT be silently downgraded
+// to danger-full-access. The daemon keeps workspace-write so Codex enforces
+// task isolation with the user's chosen backend, and preserves their
+// windows.sandbox line verbatim.
+func TestEnsureCodexSandboxConfigWindowsRespectsUserSandbox(t *testing.T) {
+ t.Parallel()
+ for _, mode := range []string{"unelevated", "elevated"} {
+ t.Run(mode, func(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ configPath := filepath.Join(dir, "config.toml")
+
+ userConfig := "model = \"o3\"\n\n[windows]\nsandbox = \"" + mode + "\"\n"
+ if err := os.WriteFile(configPath, []byte(userConfig), 0o644); err != nil {
+ t.Fatalf("write config: %v", err)
+ }
+
+ winState := resolveWindowsSandboxState(configPath, nil, sharedConfigPresent, nil, testLogger())
+ if winState != windowsSandboxNative {
+ t.Fatalf("resolveWindowsSandboxState = %v, want native", winState)
+ }
+ policy := codexSandboxPolicyForConfig("windows", "0.144.5", winState)
+ if err := ensureCodexSandboxConfig(configPath, policy, "0.144.5", testLogger()); err != nil {
+ t.Fatalf("ensureCodexSandboxConfig failed: %v", err)
+ }
+
+ data, _ := os.ReadFile(configPath)
+ s := string(data)
+ if !strings.Contains(s, `sandbox_mode = "workspace-write"`) {
+ t.Errorf("expected workspace-write kept for user-configured windows.sandbox, got:\n%s", s)
+ }
+ if strings.Contains(s, "danger-full-access") {
+ t.Errorf("must not downgrade a user-configured windows.sandbox to danger-full-access, got:\n%s", s)
+ }
+ if !strings.Contains(s, "network_access = true") {
+ t.Errorf("expected network_access = true under workspace-write, got:\n%s", s)
+ }
+ // The user's explicit opt-in must survive verbatim.
+ if !strings.Contains(s, `sandbox = "`+mode+`"`) {
+ t.Errorf("user windows.sandbox = %q must be preserved, got:\n%s", mode, s)
+ }
+ })
+ }
+}
+
func TestEnsureCodexSandboxConfigIsIdempotent(t *testing.T) {
t.Parallel()
dir := t.TempDir()
@@ -2779,11 +2852,18 @@ func TestCodexSandboxPolicyFor(t *testing.T) {
version string
wantMode string
wantNet bool
+ // wantHint is whether the policy carries an actionable upgrade hint.
+ // Only the macOS seatbelt fallback has one; the Windows compatibility
+ // fallback has no generic upgrade action, so it must not surface a
+ // misleading macOS hint.
+ wantHint bool
}{
- {"linux any version", "linux", "0.100.0", "workspace-write", true},
- {"linux unknown version", "linux", "", "workspace-write", true},
- {"darwin old version", "darwin", "0.121.0", "danger-full-access", false},
- {"darwin unknown version", "darwin", "", "danger-full-access", false},
+ {"linux any version", "linux", "0.100.0", "workspace-write", true, false},
+ {"linux unknown version", "linux", "", "workspace-write", true, false},
+ {"windows any version", "windows", "0.144.5", "danger-full-access", false, false},
+ {"windows unknown version", "windows", "", "danger-full-access", false, false},
+ {"darwin old version", "darwin", "0.121.0", "danger-full-access", false, true},
+ {"darwin unknown version", "darwin", "", "danger-full-access", false, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -2797,10 +2877,284 @@ func TestCodexSandboxPolicyFor(t *testing.T) {
if p.Reason == "" {
t.Error("expected non-empty Reason")
}
+ if (p.Hint != "") != tc.wantHint {
+ t.Errorf("hint present = %v, want %v (hint=%q)", p.Hint != "", tc.wantHint, p.Hint)
+ }
+ })
+ }
+}
+
+// TestCodexSandboxPolicyForConfig maps resolved Windows sandbox states to
+// policies: native and undecidable both keep workspace-write (undecidable fails
+// closed), only absent gets danger-full-access. Linux/darwin ignore winState.
+func TestCodexSandboxPolicyForConfig(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ goos string
+ winState windowsSandboxConfig
+ wantMode string
+ wantNet bool
+ }{
+ {"windows native keeps workspace-write", "windows", windowsSandboxNative, "workspace-write", true},
+ {"windows undecidable fails closed", "windows", windowsSandboxUndecidable, "workspace-write", true},
+ {"windows absent falls back", "windows", windowsSandboxAbsent, "danger-full-access", false},
+ // Non-Windows platforms ignore winState entirely.
+ {"linux ignores winState", "linux", windowsSandboxNative, "workspace-write", true},
+ {"darwin ignores winState", "darwin", windowsSandboxNative, "danger-full-access", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ p := codexSandboxPolicyForConfig(tc.goos, "0.144.5", tc.winState)
+ if p.Mode != tc.wantMode {
+ t.Errorf("mode = %q, want %q", p.Mode, tc.wantMode)
+ }
+ if p.NetworkAccess != tc.wantNet {
+ t.Errorf("network_access = %v, want %v", p.NetworkAccess, tc.wantNet)
+ }
+ if p.Reason == "" {
+ t.Error("expected non-empty Reason")
+ }
+ })
+ }
+}
+
+// TestWindowsSandboxFromConfig verifies config.toml classification: only the
+// exact-lowercase variants Codex accepts are native; any other present value or
+// unparseable TOML is undecidable (fail closed); an absent key is absent.
+func TestWindowsSandboxFromConfig(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ config string
+ want windowsSandboxConfig
+ }{
+ {"unelevated dotted", `windows.sandbox = "unelevated"`, windowsSandboxNative},
+ {"elevated table", "[windows]\nsandbox = \"elevated\"\n", windowsSandboxNative},
+ {"absent key", `model = "o3"`, windowsSandboxAbsent},
+ {"empty config", "", windowsSandboxAbsent},
+ {"mixed case is invalid to codex", `windows.sandbox = "Unelevated"`, windowsSandboxUndecidable},
+ {"disabled is invalid to codex", `windows.sandbox = "disabled"`, windowsSandboxUndecidable},
+ {"unparseable toml", "this is not = valid toml [[", windowsSandboxUndecidable},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := windowsSandboxFromConfig(tc.config); got != tc.want {
+ t.Errorf("windowsSandboxFromConfig(%q) = %v, want %v", tc.config, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestWindowsSandboxFromCustomArgs verifies detection of a native sandbox opted
+// into via `-c windows.sandbox=...` args — the second MUL-4957 must-fix, since
+// such args never land in config.toml.
+func TestWindowsSandboxFromCustomArgs(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ args []string
+ want windowsSandboxConfig
+ }{
+ {"two-token bare", []string{"-c", "windows.sandbox=unelevated"}, windowsSandboxNative},
+ {"two-token quoted", []string{"-c", `windows.sandbox="unelevated"`}, windowsSandboxNative},
+ {"two-token spaced", []string{"-c", `windows.sandbox = "elevated"`}, windowsSandboxNative},
+ {"inline -c=", []string{"-c=windows.sandbox=unelevated"}, windowsSandboxNative},
+ {"--config long form", []string{"--config", "windows.sandbox=elevated"}, windowsSandboxNative},
+ {"last occurrence wins", []string{"-c", "windows.sandbox=unelevated", "-c", "windows.sandbox=elevated"}, windowsSandboxNative},
+ {"invalid value undecidable", []string{"-c", "windows.sandbox=disabled"}, windowsSandboxUndecidable},
+ {"unrelated override ignored", []string{"-c", "model=o3"}, windowsSandboxAbsent},
+ {"no args", nil, windowsSandboxAbsent},
+ {"dangling -c ignored", []string{"-c"}, windowsSandboxAbsent},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := windowsSandboxFromCustomArgs(tc.args); got != tc.want {
+ t.Errorf("windowsSandboxFromCustomArgs(%v) = %v, want %v", tc.args, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestResolveWindowsSandbox verifies the fold precedence: undecidable > native
+// > absent.
+func TestResolveWindowsSandbox(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ states []windowsSandboxConfig
+ want windowsSandboxConfig
+ }{
+ {"all absent", []windowsSandboxConfig{windowsSandboxAbsent, windowsSandboxAbsent}, windowsSandboxAbsent},
+ {"native in args", []windowsSandboxConfig{windowsSandboxAbsent, windowsSandboxNative}, windowsSandboxNative},
+ {"undecidable beats native", []windowsSandboxConfig{windowsSandboxNative, windowsSandboxUndecidable}, windowsSandboxUndecidable},
+ {"undecidable beats absent", []windowsSandboxConfig{windowsSandboxUndecidable, windowsSandboxAbsent}, windowsSandboxUndecidable},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := resolveWindowsSandbox(tc.states...); got != tc.want {
+ t.Errorf("resolveWindowsSandbox(%v) = %v, want %v", tc.states, got, tc.want)
+ }
})
}
}
+// TestStatSharedCodexConfig verifies the shared-config tri-state used to tell a
+// genuinely config-less user from one whose config could not be stat'd.
+func TestStatSharedCodexConfig(t *testing.T) {
+ t.Parallel()
+
+ t.Run("present", func(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "config.toml"), []byte(`model = "o3"`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if got := statSharedCodexConfig(dir); got != sharedConfigPresent {
+ t.Errorf("got %v, want present", got)
+ }
+ })
+
+ t.Run("absent", func(t *testing.T) {
+ t.Parallel()
+ if got := statSharedCodexConfig(t.TempDir()); got != sharedConfigAbsent {
+ t.Errorf("got %v, want absent", got)
+ }
+ })
+
+ t.Run("empty home is absent", func(t *testing.T) {
+ t.Parallel()
+ if got := statSharedCodexConfig(""); got != sharedConfigAbsent {
+ t.Errorf("got %v, want absent", got)
+ }
+ })
+}
+
+// TestResolveWindowsSandboxStateFailsClosed pins the MUL-4957 fail-closed
+// invariant across every path where the daemon cannot confidently confirm the
+// user configured no native sandbox: a missing per-task copy of an existing (or
+// un-stat'able) shared config, and a failed config sync that leaves a stale
+// copy behind, all keep the restrictive workspace-write policy. Only a
+// genuinely config-less user with no custom-arg opt-in resolves to absent (the
+// one state that earns the danger-full-access compatibility fallback).
+func TestResolveWindowsSandboxStateFailsClosed(t *testing.T) {
+ t.Parallel()
+
+ t.Run("shared config present but per-task copy missing -> undecidable", func(t *testing.T) {
+ t.Parallel()
+ missing := filepath.Join(t.TempDir(), "config.toml")
+ if got := resolveWindowsSandboxState(missing, nil, sharedConfigPresent, nil, testLogger()); got != windowsSandboxUndecidable {
+ t.Errorf("got %v, want undecidable (fail closed)", got)
+ }
+ })
+
+ t.Run("shared config stat undecidable -> undecidable", func(t *testing.T) {
+ t.Parallel()
+ // The shared source could not be stat'd (permission/IO), so an absent
+ // per-task copy cannot be trusted as "the user has no config".
+ missing := filepath.Join(t.TempDir(), "config.toml")
+ if got := resolveWindowsSandboxState(missing, nil, sharedConfigUndecidable, nil, testLogger()); got != windowsSandboxUndecidable {
+ t.Errorf("got %v, want undecidable (fail closed)", got)
+ }
+ })
+
+ t.Run("config sync error with stale absent-looking copy -> undecidable", func(t *testing.T) {
+ t.Parallel()
+ // A leftover per-task config that reads as "no sandbox" must NOT be
+ // trusted when the sync that should have refreshed it failed — the
+ // reuse-path fail-open Elon's round-3 must-fix 1 called out.
+ dir := t.TempDir()
+ stale := filepath.Join(dir, "config.toml")
+ if err := os.WriteFile(stale, []byte(`model = "o3"`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ syncErr := errors.New("copy failed")
+ if got := resolveWindowsSandboxState(stale, syncErr, sharedConfigPresent, nil, testLogger()); got != windowsSandboxUndecidable {
+ t.Errorf("got %v, want undecidable (fail closed on sync error)", got)
+ }
+ })
+
+ t.Run("no shared config and successful sync -> absent", func(t *testing.T) {
+ t.Parallel()
+ missing := filepath.Join(t.TempDir(), "config.toml")
+ if got := resolveWindowsSandboxState(missing, nil, sharedConfigAbsent, nil, testLogger()); got != windowsSandboxAbsent {
+ t.Errorf("got %v, want absent", got)
+ }
+ })
+
+ t.Run("custom-arg opt-in detected even with no config file", func(t *testing.T) {
+ t.Parallel()
+ missing := filepath.Join(t.TempDir(), "config.toml")
+ args := []string{"-c", "windows.sandbox=unelevated"}
+ if got := resolveWindowsSandboxState(missing, nil, sharedConfigAbsent, args, testLogger()); got != windowsSandboxNative {
+ t.Errorf("got %v, want native", got)
+ }
+ })
+}
+
+// TestPrepareCodexHomeFailsClosedWhenSandboxWriteFails pins the MUL-4957
+// round-4 must-fix: the computed fail-closed policy must not stay only in
+// memory. It reproduces the reuse scenario where (1) the per-task config.toml
+// still holds last run's managed danger-full-access, (2) the shared config has
+// since opted into a native windows.sandbox but the sync cannot refresh the
+// copy, and (3) the managed block cannot be rewritten. Previously prepare
+// warned and returned success, so the task launched with the stale
+// danger-full-access — the decision failed closed while the effective config
+// failed open. prepareCodexHomeWithOpts must now return an error, which blocks
+// startup on both paths (fresh Prepare fails the task; Reuse leaves
+// env.CodexHome unset, which configureCodexTaskShellEnvironment refuses).
+func TestPrepareCodexHomeFailsClosedWhenSandboxWriteFails(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("running as root bypasses the read-only permissions this test relies on")
+ }
+ // Cannot use t.Parallel() with t.Setenv.
+
+ // Shared home the user has since pointed at a native Windows sandbox.
+ sharedHome := t.TempDir()
+ if err := os.WriteFile(filepath.Join(sharedHome, "config.toml"), []byte("windows.sandbox = \"unelevated\"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CODEX_HOME", sharedHome)
+
+ // Reused per-task home still holding the prior run's danger-full-access.
+ codexHome := t.TempDir()
+ configPath := filepath.Join(codexHome, "config.toml")
+ stale := multicaManagedBeginMarker + "\nsandbox_mode = \"danger-full-access\"\n" + multicaManagedEndMarker + "\n"
+ if err := os.WriteFile(configPath, []byte(stale), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // Read-only file + directory: the sync cannot replace the stale copy and
+ // the managed block cannot be rewritten.
+ if err := os.Chmod(configPath, 0o444); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(codexHome, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ // Restore before t.TempDir's own cleanup so removal succeeds (LIFO).
+ t.Cleanup(func() {
+ _ = os.Chmod(codexHome, 0o755)
+ _ = os.Chmod(configPath, 0o644)
+ })
+
+ err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{GOOS: "windows", CodexVersion: "0.144.5"}, testLogger())
+ if err == nil {
+ t.Fatal("expected prepareCodexHomeWithOpts to fail closed when the sandbox block cannot be written, got nil")
+ }
+ if !strings.Contains(err.Error(), "sandbox config") {
+ t.Errorf("expected a sandbox-config error, got: %v", err)
+ }
+ // The stale danger-full-access is still on disk — proving the task would
+ // have launched unsandboxed had prepare reported success.
+ data, readErr := os.ReadFile(configPath)
+ if readErr != nil {
+ t.Fatalf("read config: %v", readErr)
+ }
+ if !strings.Contains(string(data), `sandbox_mode = "danger-full-access"`) {
+ t.Fatalf("expected the stale danger-full-access to remain (write failed), got:\n%s", data)
+ }
+}
+
func TestPrepareCodexHomeEnsuresNetworkAccess(t *testing.T) {
// Cannot use t.Parallel() with t.Setenv.
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 369cf200c3..a5efc3842f 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -123,22 +123,41 @@ type codexBackend struct {
func buildCodexArgs(opts ExecOptions, logger *slog.Logger) []string {
args := []string{"app-server", "--listen", "stdio://"}
- extra := filterCustomArgs(opts.ExtraArgs, codexBlockedArgs, logger)
- custom := filterCustomArgs(opts.CustomArgs, codexBlockedArgs, logger)
+ return append(args, NormalizeCodexLaunchArgs(opts.ExtraArgs, opts.CustomArgs, opts.McpConfig, logger)...)
+}
+
+// NormalizeCodexLaunchArgs returns the user-supplied Codex args (extra then
+// custom) exactly as buildCodexArgs hands them to the launched process: shell
+// quoting stripped, protocol-critical flags removed, and — when a managed
+// mcp_config owns the mcp_servers namespace — stray `-c mcp_servers.*`
+// overrides dropped. buildCodexArgs only prepends the fixed
+// `app-server --listen stdio://` transport flags to this result.
+//
+// It is exported so the daemon can reconstruct the *effective* launch args when
+// deciding the Windows sandbox mode. A `-c windows.sandbox=…` opt-in may arrive
+// shell-quoted (users commonly type custom_args with shell syntax, e.g.
+// `'-c' 'windows.sandbox=unelevated'`), and only after this same normalization
+// does it match the `-c windows.sandbox=…` shape the sandbox detector looks
+// for. Reconstructing the args any other way lets the two drift, silently
+// downgrading a user's isolation opt-in (MUL-4957).
+func NormalizeCodexLaunchArgs(extraArgs, customArgs []string, mcpConfig json.RawMessage, logger *slog.Logger) []string {
+ extra := filterCustomArgs(extraArgs, codexBlockedArgs, logger)
+ custom := filterCustomArgs(customArgs, codexBlockedArgs, logger)
// Only claim ownership of the `mcp_servers` namespace when the agent
// actually has a managed mcp_config in the MCP Tab. Otherwise existing
// users who configure MCP via `custom_args: ["-c", "mcp_servers.…"]`
- // would silently lose those entries after this PR ships. With managed
- // mcp_config present, daemon-written `$CODEX_HOME/config.toml` is the
- // authoritative source and stray `-c mcp_servers.*` overrides are
- // dropped to keep last-wins from re-shadowing it.
- if hasManagedCodexMcpConfig(opts.McpConfig) {
+ // would silently lose those entries. With managed mcp_config present,
+ // daemon-written `$CODEX_HOME/config.toml` is the authoritative source and
+ // stray `-c mcp_servers.*` overrides are dropped to keep last-wins from
+ // re-shadowing it.
+ if hasManagedCodexMcpConfig(mcpConfig) {
extra = filterCodexCustomConfigOverrides(extra, logger)
custom = filterCodexCustomConfigOverrides(custom, logger)
}
- args = append(args, extra...)
- args = append(args, custom...)
- return args
+ out := make([]string, 0, len(extra)+len(custom))
+ out = append(out, extra...)
+ out = append(out, custom...)
+ return out
}
// hasManagedCodexMcpConfig reports whether the agent's mcp_config field is
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index ceb5dc0a68..deb3fe35fe 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -2988,6 +2988,27 @@ func TestBuildCodexArgsDoesNotLeakMcpToArgv(t *testing.T) {
}
}
+// TestNormalizeCodexLaunchArgsStripsShellQuotes locks the normalization the
+// daemon reuses for the Windows sandbox decision (MUL-4957): a shell-quoted
+// `-c windows.sandbox=...` opt-in must come out as clean tokens, and
+// buildCodexArgs must be exactly the transport prefix followed by this result,
+// so the sandbox decision and the launch argv can never diverge.
+func TestNormalizeCodexLaunchArgsStripsShellQuotes(t *testing.T) {
+ t.Parallel()
+
+ got := NormalizeCodexLaunchArgs(nil, []string{"'-c'", "'windows.sandbox=unelevated'"}, nil, slog.Default())
+ want := []string{"-c", "windows.sandbox=unelevated"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("NormalizeCodexLaunchArgs = %v, want %v", got, want)
+ }
+
+ launch := buildCodexArgs(ExecOptions{CustomArgs: []string{"'-c'", "'windows.sandbox=unelevated'"}}, slog.Default())
+ wantLaunch := append([]string{"app-server", "--listen", "stdio://"}, want...)
+ if !reflect.DeepEqual(launch, wantLaunch) {
+ t.Fatalf("buildCodexArgs = %v, want %v", launch, wantLaunch)
+ }
+}
+
func TestCodexExecuteFailsClosedWhenMcpConfigInvalid(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {