This is an automated email from the ASF dual-hosted git repository.

luigidemasi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-kit.git


The following commit(s) were added to refs/heads/main by this push:
     new b8d75fda fix: validate Codex TOML in init preview and report preserved 
wrapper as-is
b8d75fda is described below

commit b8d75fda36f58780ca20ec819ddadec5bd436363
Author: Matheus AndrĂ© <[email protected]>
AuthorDate: Thu Nov 12 16:33:05 2026 -0300

    fix: validate Codex TOML in init preview and report preserved wrapper as-is
    
    Signed-off-by: Matheus AndrĂ© <[email protected]>
---
 CHANGELOG.md                                       |   5 +
 docs/architecture.md                               |  10 +-
 docs/commands.md                                   |   4 +-
 docs/modules/ROOT/pages/commands.adoc              |   3 +-
 docs/modules/ROOT/pages/existing-project.adoc      |   7 +-
 docs/modules/ROOT/pages/getting-started.adoc       |  16 +++-
 .../org/apache/camel/kit/command/InitCommand.java  |  13 ++-
 .../camel/kit/generator/CodexConfigMerger.java     |  64 ++++++++++---
 .../camel/kit/generator/McpConfigGenerator.java    |  27 ++++--
 .../apache/camel/kit/command/InitCommandTest.java  |   6 ++
 .../camel/kit/service/InitSafeAdoptionTest.java    | 104 +++++++++++++++++++++
 11 files changed, 224 insertions(+), 35 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 60b4cb37..0016d747 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,11 @@ and this project adheres to [Semantic 
Versioning](https://semver.org/spec/v2.0.0
 
 ### Fixed
 
+- `init --ai codex` validates an existing `.codex/config.toml` before writing 
anything, and `--dry-run` rejects the
+  same files: invalid TOML, damaged managed-block markers and Camel-Kit server 
tables defined outside the block no
+  longer leave a partly initialized workspace (#174).
+- A preserved Maven wrapper is reported as kept without a proposed copy and 
points to `--replace-wrapper`; the
+  documentation now describes the wrapper as the exception to 
`.camel-kit/conflicts/` proposals (#174).
 - Preserve legitimate init layouts containing unrelated symlinks and normal 
permissions on new generated files.
 - Exclude VCS, build and dependency trees from graphs; support up to 256 MiB 
of recognized sources while retaining per-file limits and validation before XML 
sniffing.
 - Derive Claude MCP grants from the workflow manifest and validate catalog 
cache version components.
diff --git a/docs/architecture.md b/docs/architecture.md
index e4fcda8d..c3190590 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -918,9 +918,13 @@ that decides what happens to them:
   line-ending differences so a checkout that converts them does not look like 
an edit. A project without a Maven
   wrapper gets the complete one; once any wrapper file is the project's own, 
no further wrapper file is added and
   only files named for replacement are written. Preview and execution share 
that plan.
-- A preserved file is reported and the generated version is saved under 
`.camel-kit/conflicts/`. `--replace <path>`
-  rewrites one shared file in full; `--dry-run` reports the outcome per file 
without writing.
-- Existing JSON MCP configurations are merged, not replaced.
+- A preserved file is reported and the generated version is saved under 
`.camel-kit/conflicts/`. A preserved Maven
+  wrapper file is the exception: it is reported without a saved version, so no 
partial wrapper is offered for
+  merging; `--replace-wrapper` replaces the whole wrapper. `--replace <path>` 
rewrites one shared file in full;
+  `--dry-run` reports the outcome per file without writing.
+- Existing MCP configurations, JSON and `.codex/config.toml`, are merged, not 
replaced. One that cannot
+  be merged is rejected before anything is written, by `--dry-run` as well as 
by initialization; for Codex both build
+  and validate the same merged candidate.
 
 Assets Camel-Kit ships under its own names (`camel-*` skills, subagents, 
personas, hooks, `.camel-kit/templates/`) are
 not tracked and are always regenerated. This keeps reinitialization able to 
restore the restricted Ship worker
diff --git a/docs/commands.md b/docs/commands.md
index c04cd351..1d56a787 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -167,7 +167,9 @@ Camel-Kit owns only the block between its 
`CAMEL-KIT-MANAGED-BLOCK` markers: ini
 file and later replaces only that block. An existing `docs/constitution.md`, 
`.claude/settings.json`, `.qwenignore`,
 `.bob/custom_modes.yaml` or Maven wrapper that Camel-Kit did not write, or 
that you changed afterwards, is left
 untouched and listed at the end of the run; the version Camel-Kit would have 
written is saved under
-`.camel-kit/conflicts/`. Pass `--replace <path>` to replace a file in full, or 
`--dry-run` to preview. Shipped
+`.camel-kit/conflicts/`, except for Maven wrapper files, which are listed 
without a saved version; use
+`--replace-wrapper` to replace the whole wrapper. Pass `--replace <path>` to 
replace a file in full, or `--dry-run` to preview;
+the preview runs the same validation as init and rejects an existing MCP 
configuration that cannot be merged. Shipped
 skills and other `camel-*` assets are always regenerated.
 
 **TUI experience:**
diff --git a/docs/modules/ROOT/pages/commands.adoc 
b/docs/modules/ROOT/pages/commands.adoc
index 46af44a1..8db34bab 100644
--- a/docs/modules/ROOT/pages/commands.adoc
+++ b/docs/modules/ROOT/pages/commands.adoc
@@ -33,7 +33,8 @@ camel-kit init --here [options]
   merging or preserving it. Repeatable; a path that is not a shared file 
written by `init` is rejected before
   anything is written
 | `--dry-run` | `false` | Show what `init` would do to each shared file 
(create, replace, merge or preserve) without
-  writing anything
+  writing anything. Runs the same validation as `init`, so an existing MCP 
configuration that cannot be merged is
+  rejected here too
 | `--replace-wrapper` | `false` | Replace the complete Maven wrapper; use 
`--replace <path>` to replace only one shared file
 | `--record-baseline` | `false` | Run the existing project's build and tests 
once to record baseline results; never runs during `--dry-run`
 | `--source-platform` | `auto` | Source platform of a migration: `mulesoft`, 
`biztalk`, `camel` or `auto`
diff --git a/docs/modules/ROOT/pages/existing-project.adoc 
b/docs/modules/ROOT/pages/existing-project.adoc
index e6ead771..2430f76b 100644
--- a/docs/modules/ROOT/pages/existing-project.adoc
+++ b/docs/modules/ROOT/pages/existing-project.adoc
@@ -45,7 +45,8 @@ Camel Kit `init` is **safe to run over existing projects** 
with these protection
 | Never modified during init
 
 | Maven wrapper (`mvnw`, `.mvn/`)
-| Skipped if exists (use `--replace-wrapper` to force replacement)
+| Skipped if exists and reported under _Existing files preserved_, with no 
proposed copy under
+  `.camel-kit/conflicts/` (use `--replace-wrapper` to force replacement)
 
 | `AGENTS.md` and `CLAUDE.md`
 | Use managed blocks - customizations preserved on reinit
@@ -69,7 +70,9 @@ camel-kit init --here --ai claude --dry-run
 
 The preview lists shared files with a `create`, `replace`, `merge` or 
`preserve` action, using the same
 ownership and replacement rules as initialization. It does not write files or 
run baseline tests, even when
-`--record-baseline` is also supplied. See 
xref:getting-started.adoc#existing-project[Existing projects] for
+`--record-baseline` is also supplied. It also runs the validation of 
initialization: an existing MCP configuration
+that cannot be merged, such as a `.codex/config.toml` that is not valid TOML, 
is rejected by the preview with the
+message `init` would give. See 
xref:getting-started.adoc#existing-project[Existing projects] for
 file ownership and `--replace <path>` behavior.
 
 == Getting Started
diff --git a/docs/modules/ROOT/pages/getting-started.adoc 
b/docs/modules/ROOT/pages/getting-started.adoc
index 39ac88a4..66627094 100644
--- a/docs/modules/ROOT/pages/getting-started.adoc
+++ b/docs/modules/ROOT/pages/getting-started.adoc
@@ -222,8 +222,10 @@ own, Camel Kit adds no further wrapper file and writes 
only the ones named with
 
 A shared file that was not written by Camel Kit, or was changed afterwards, is 
left untouched and listed under
 _Existing files preserved_ at the end of the run. The version Camel Kit would 
have written is saved under
-`.camel-kit/conflicts/` at the same relative path, so you can merge it by 
hand. To let Camel Kit replace a file in
-full, name it explicitly:
+`.camel-kit/conflicts/` at the same relative path, so you can merge it by 
hand. The Maven wrapper is the exception:
+a preserved wrapper file is listed without a saved version, because a wrapper 
is not meant to be merged by hand.
+To replace the whole wrapper, use `--replace-wrapper`; `--replace mvnw` still 
replaces that one file. To let Camel
+Kit replace a file in full, name it explicitly:
 
 [source,bash]
 ----
@@ -237,9 +239,13 @@ To see what a run would do to these files without writing 
anything, add `--dry-r
 camel-kit init --here --ai claude --dry-run
 ----
 
-An existing JSON MCP configuration is merged: Camel Kit adds or updates its 
own servers and keeps other servers and
-settings. A file that is not valid JSON stops `init` before any project file 
is changed. On reinitialization,
-properties you added to `.camel-kit/config.properties` are kept.
+An existing MCP configuration is merged: Camel Kit adds or updates its own 
servers and keeps other servers and
+settings. This applies to the JSON files and to `.codex/config.toml`, where 
Camel Kit keeps its servers between
+`# BEGIN CAMEL-KIT MANAGED MCP SERVERS` and `# END CAMEL-KIT MANAGED MCP 
SERVERS`. A file that cannot be merged
+stops `init` before any project file is changed, and `--dry-run` rejects it 
with the same message: invalid JSON or
+TOML, and for Codex also damaged markers, a `camel`, `camel-knowledge` or 
`citrus` server table defined outside
+the managed block, an `mcp_servers` value that cannot take further tables, or 
a `.codex/config.toml` that is not a
+regular file. On reinitialization, properties you added to 
`.camel-kit/config.properties` are kept.
 
 Camel Kit records the hash of each tracked file it wrote in 
`.camel-kit/managed-files.properties`; commit it with
 the project. Known limits:
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java
index 523a8048..bb56f010 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/command/InitCommand.java
@@ -251,14 +251,21 @@ public class InitCommand extends CamelKitCommand {
         printer().println("  " + yellow("\u26A0") + bold("  Existing files 
preserved"));
         printer().println(dim("  Not written by Camel Kit, or changed since, 
so left as they are:"));
         for (ManagedFiles.Change conflict : result.conflicts()) {
+            // Only the Maven wrapper is preserved without a proposal: it is 
never assembled from mixed files.
             String proposal = conflict.proposal() == null
-                    ? ""
+                    ? dim("  \u2190 kept as is, no Camel Kit version saved")
                     : dim("  \u2190 Camel Kit version: ")
                       + 
result.targetDir().relativize(conflict.proposal()).toString().replace('\\', 
'/');
             printer().println("     " + cyan(conflict.path()) + proposal);
         }
-        printer().println(dim("  Merge the Camel Kit version by hand, or 
replace a file with ")
-                          + bold("--force --replace <path>"));
+        if (result.conflicts().stream().anyMatch(conflict -> 
conflict.proposal() != null)) {
+            printer().println(dim("  Merge the Camel Kit version by hand, or 
replace a file with ")
+                              + bold("--force --replace <path>"));
+        }
+        if (result.conflicts().stream().anyMatch(conflict -> 
conflict.proposal() == null)) {
+            printer().println(dim("  To replace the whole Maven wrapper, use ")
+                              + bold("--force --replace-wrapper"));
+        }
         printer().println();
     }
 
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CodexConfigMerger.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CodexConfigMerger.java
index ded46dfc..de38d48d 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CodexConfigMerger.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/CodexConfigMerger.java
@@ -2,6 +2,7 @@ package org.apache.camel.kit.generator;
 
 import java.io.IOException;
 import java.nio.file.Files;
+import java.nio.file.LinkOption;
 import java.nio.file.Path;
 import java.util.List;
 
@@ -20,17 +21,52 @@ final class CodexConfigMerger {
                 : List.of("camel", "camel-knowledge");
     }
 
+    /** Writes the merged configuration. Everything up to the write is {@link 
#candidate}. */
     void merge(Path configFile, String renderedConfig, boolean citrusEnabled) 
throws IOException {
+        AtomicFileWriter.write(configFile, candidate(configFile, 
renderedConfig, citrusEnabled));
+    }
+
+    /**
+     * Runs every check of {@link #merge} without writing, so a preview and an 
initialization reject the same input.
+     */
+    void validate(Path configFile, String renderedConfig, boolean 
citrusEnabled)
+            throws InvalidAgentConfigurationException {
+        try {
+            candidate(configFile, renderedConfig, citrusEnabled);
+        } catch (IOException e) {
+            throw new InvalidAgentConfigurationException(
+                    "Invalid Codex MCP config " + configFile + ": " + 
e.getMessage()
+                                                         + ". Fix the file 
before retrying.",
+                    e);
+        }
+    }
+
+    /**
+     * Builds and validates the text {@link #merge} would write: the existing 
configuration with the managed block added
+     * or replaced. Reads only.
+     */
+    String candidate(Path configFile, String renderedConfig, boolean 
citrusEnabled) throws IOException {
         validateToml(renderedConfig, "generated Codex MCP configuration");
 
         String managedBlock = BEGIN_MARKER + System.lineSeparator()
                               + renderedConfig.strip() + System.lineSeparator()
                               + END_MARKER;
-        String existing = Files.isRegularFile(configFile) ? 
Files.readString(configFile) : "";
+        String existing = "";
+        if (Files.exists(configFile, LinkOption.NOFOLLOW_LINKS)) {
+            if (!Files.isRegularFile(configFile, LinkOption.NOFOLLOW_LINKS)) {
+                throw new IOException("existing .codex/config.toml must be a 
regular file");
+            }
+            existing = Files.readString(configFile);
+        }
         String merged = merge(existing, managedBlock, citrusEnabled);
-        validateToml(merged, configFile.toString());
-        AtomicFileWriter.write(configFile,
-                merged + (merged.endsWith(System.lineSeparator()) ? "" : 
System.lineSeparator()));
+        // Catches what the checks on the existing file cannot name, such as 
an inline or scalar mcp_servers.
+        TomlParseResult parsed = Toml.parse(merged);
+        if (parsed.hasErrors()) {
+            throw new IOException(
+                    "existing .codex/config.toml cannot hold the Camel-Kit MCP 
server tables, the merged file would"
+                                  + " not be valid TOML: " + 
parsed.errors().get(0));
+        }
+        return merged + (merged.endsWith(System.lineSeparator()) ? "" : 
System.lineSeparator());
     }
 
     private String merge(String existing, String managedBlock, boolean 
citrusEnabled) throws IOException {
@@ -41,16 +77,17 @@ final class CodexConfigMerger {
         validateToml(existing, "existing .codex/config.toml");
         int begin = existing.indexOf(BEGIN_MARKER);
         int end = existing.indexOf(END_MARKER);
-        if (begin >= 0 || end >= 0) {
-            if (begin < 0 || end < begin || existing.indexOf(BEGIN_MARKER, 
begin + 1) >= 0
-                    || existing.indexOf(END_MARKER, end + 1) >= 0) {
-                throw new IOException("existing .codex/config.toml has invalid 
Camel-Kit managed block markers");
-            }
-            return existing.substring(0, begin) + managedBlock + 
existing.substring(end + END_MARKER.length());
+        boolean hasBlock = begin >= 0 || end >= 0;
+        if (hasBlock && (begin < 0 || end < begin || 
existing.indexOf(BEGIN_MARKER, begin + 1) >= 0
+                || existing.indexOf(END_MARKER, end + 1) >= 0)) {
+            throw new IOException("existing .codex/config.toml has invalid 
Camel-Kit managed block markers");
         }
 
-        Object mcpServers = Toml.parse(existing).get("mcp_servers");
-        if (mcpServers instanceof TomlTable servers) {
+        // The servers Camel-Kit manages must not also be defined outside its 
block, with or without a block.
+        String before = hasBlock ? existing.substring(0, begin) : existing;
+        String after = hasBlock ? existing.substring(end + 
END_MARKER.length()) : "";
+        TomlParseResult outside = Toml.parse(before + after);
+        if (!outside.hasErrors() && outside.get("mcp_servers") instanceof 
TomlTable servers) {
             List<String> conflicts = managedServers(citrusEnabled).stream()
                     .filter(server -> servers.get(server) instanceof TomlTable)
                     .toList();
@@ -61,6 +98,9 @@ final class CodexConfigMerger {
             }
         }
 
+        if (hasBlock) {
+            return before + managedBlock + after;
+        }
         return existing + (existing.endsWith(System.lineSeparator())
                 ? System.lineSeparator()
                 : System.lineSeparator() + System.lineSeparator())
diff --git 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java
 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java
index 5b64ca52..6ad07fbf 100644
--- 
a/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java
+++ 
b/kit/camel-kit-core/src/main/java/org/apache/camel/kit/generator/McpConfigGenerator.java
@@ -11,6 +11,7 @@ import org.apache.camel.kit.config.DistributionConfig;
 import org.apache.camel.kit.util.AnsiColors;
 import org.apache.camel.kit.util.TemplateUtils;
 import org.apache.camel.kit.workflow.WorkflowManifest;
+import org.apache.camel.kit.workflow.WorkflowManifestLoader;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -29,10 +30,7 @@ class McpConfigGenerator {
                 Files.createDirectories(configFile.getParent());
             }
 
-            QuteTemplateEngine qute = new QuteTemplateEngine();
-            String template = 
TemplateUtils.readTemplate(ctx.agent().mcpConfigTemplatePath());
-            String processed
-                    = qute.renderString(template, 
templateData(ctx.distribution(), workflow, ctx.withCitrusMcp()));
+            String processed = render(ctx, workflow);
             if ("toml".equals(ctx.agent().mcpConfigFormat())) {
                 new CodexConfigMerger().merge(configFile, processed, 
ctx.withCitrusMcp());
             } else if ("opencode".equals(ctx.agentName())) {
@@ -82,15 +80,28 @@ class McpConfigGenerator {
     }
 
     /**
-     * Validates the JSON MCP config a generator will merge into, so an 
unusable file fails before anything is written.
+     * Validates the MCP config a generator will merge into, so an unusable 
file fails before anything is written. Reads
+     * only, so a preview runs the same checks. OpenCode validates its own 
configuration files.
      */
-    static void preflight(InitContext ctx) throws 
InvalidAgentConfigurationException {
-        if (!"toml".equals(ctx.agent().mcpConfigFormat()) && 
!"opencode".equals(ctx.agentName())) {
+    static void preflight(InitContext ctx) throws IOException {
+        if ("toml".equals(ctx.agent().mcpConfigFormat())) {
+            // The merge itself is checked, with the block initialization will 
write, not only the existing file.
+            new CodexConfigMerger().validate(
+                    ctx.projectDir().resolve(ctx.agent().mcpConfigPath()),
+                    render(ctx, WorkflowManifestLoader.loadDefault()), 
ctx.withCitrusMcp());
+        } else if (!"opencode".equals(ctx.agentName())) {
             
readJsonConfig(ctx.projectDir().resolve(ctx.agent().mcpConfigPath()), 
ctx.agent().name(),
                     ctx.agent().mcpServerContainerKey());
         }
     }
 
+    /** The MCP configuration Camel-Kit generates for this agent, before it is 
merged into an existing file. */
+    private static String render(InitContext ctx, WorkflowManifest workflow) 
throws IOException {
+        String template = 
TemplateUtils.readTemplate(ctx.agent().mcpConfigTemplatePath());
+        return new QuteTemplateEngine()
+                .renderString(template, templateData(ctx.distribution(), 
workflow, ctx.withCitrusMcp()));
+    }
+
     static ObjectNode readJsonConfig(Path configFile, String agent, String key)
             throws InvalidAgentConfigurationException {
         if (!Files.exists(configFile, LinkOption.NOFOLLOW_LINKS)) {
@@ -116,7 +127,7 @@ class McpConfigGenerator {
         }
     }
 
-    private Map<String, Object> templateData(
+    private static Map<String, Object> templateData(
             DistributionConfig dist, WorkflowManifest workflow, boolean 
withCitrusMcp)
             throws IOException {
         Map<String, Object> data = new java.util.HashMap<>(
diff --git 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/InitCommandTest.java
 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/InitCommandTest.java
index b21e5df0..5d9b13a7 100644
--- 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/InitCommandTest.java
+++ 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/command/InitCommandTest.java
@@ -176,6 +176,12 @@ class InitCommandTest {
         assertTrue(Files.isDirectory(project.resolve(".camel-kit")));
         assertTrue(printer.output().contains("Existing files preserved"), 
printer.output());
         assertTrue(printer.output().contains("mvnw"), printer.output());
+        // The wrapper has no proposed copy, so the report points to 
whole-wrapper replacement instead of a merge.
+        assertTrue(printer.output().lines().anyMatch(
+                line -> line.contains("mvnw") && line.contains("no Camel Kit 
version saved")), printer.output());
+        assertTrue(printer.output().contains("--replace-wrapper"), 
printer.output());
+        assertFalse(printer.output().contains("Merge the Camel Kit version by 
hand"), printer.output());
+        
assertFalse(Files.exists(project.resolve(".camel-kit/conflicts/mvnw")));
     }
 
     @Test
diff --git 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java
 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java
index 0d036e56..b077262c 100644
--- 
a/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java
+++ 
b/kit/camel-kit-core/src/test/java/org/apache/camel/kit/service/InitSafeAdoptionTest.java
@@ -147,6 +147,110 @@ class InitSafeAdoptionTest {
         assertEquals(before, snapshot(project));
     }
 
+    static List<String> unmergeableCodexConfigs() {
+        return List.of(
+                "model = [\n",
+                "[mcp_servers.camel]\ncommand = \"custom\"\n",
+                "# BEGIN CAMEL-KIT MANAGED MCP SERVERS\nmodel = \"x\"\n",
+                // A valid block does not excuse a managed server defined 
outside it.
+                "[mcp_servers.camel]\ncommand = \"custom\"\n\n# BEGIN 
CAMEL-KIT MANAGED MCP SERVERS\n"
+                                                                          + 
"[mcp_servers.camel-knowledge]\ncommand = \"old-knowledge\"\n"
+                                                                          + "# 
END CAMEL-KIT MANAGED MCP SERVERS\n",
+                // Valid on their own, but the managed tables cannot be added 
to them.
+                "mcp_servers = {}\n",
+                "mcp_servers = \"none\"\n");
+    }
+
+    @ParameterizedTest
+    @MethodSource("unmergeableCodexConfigs")
+    void 
unmergeableCodexConfigIsRejectedByPreviewAndInitBeforeAnyProjectWrites(String 
content) throws Exception {
+        Path project = tempDir.resolve("orders");
+        Path config = 
Files.createDirectories(project.resolve(".codex")).resolve("config.toml");
+        Files.writeString(config, content);
+        List<String> before = snapshot(project);
+
+        InvalidAgentConfigurationException previewError = 
assertThrows(InvalidAgentConfigurationException.class,
+                () -> new InitService().preview(request(project, "codex")));
+        assertEquals(before, snapshot(project));
+
+        InvalidAgentConfigurationException initError = 
assertThrows(InvalidAgentConfigurationException.class,
+                () -> new InitService().initialize(request(project, "codex")));
+        assertEquals(before, snapshot(project));
+        assertEquals(previewError.getMessage(), initError.getMessage());
+        assertTrue(initError.getMessage().contains(".codex/config.toml"), 
initError.getMessage());
+    }
+
+    @Test
+    void 
codexConfigThatIsNotARegularFileIsRejectedByPreviewAndInitBeforeAnyProjectWrites()
 throws Exception {
+        Path project = tempDir.resolve("orders");
+        Files.createDirectories(project.resolve(".codex/config.toml"));
+        List<String> before = snapshot(project);
+
+        InvalidAgentConfigurationException previewError = 
assertThrows(InvalidAgentConfigurationException.class,
+                () -> new InitService().preview(request(project, "codex")));
+        InvalidAgentConfigurationException initError = 
assertThrows(InvalidAgentConfigurationException.class,
+                () -> new InitService().initialize(request(project, "codex")));
+
+        assertEquals(before, snapshot(project));
+        assertEquals(previewError.getMessage(), initError.getMessage());
+        assertTrue(initError.getMessage().contains("must be a regular file"), 
initError.getMessage());
+    }
+
+    @Test
+    void reinitializationOfCodexReplacesTheManagedBlockAndPassesPreview() 
throws Exception {
+        Path project = tempDir.resolve("orders");
+        new InitService().initialize(request(project, "codex"));
+        Path config = project.resolve(".codex/config.toml");
+        String first = Files.readString(config);
+
+        new InitService().preview(request(project, "codex"));
+        new InitService().initialize(request(project, "codex"));
+
+        assertEquals(first, Files.readString(config));
+    }
+
+    @Test
+    void validCodexConfigIsAcceptedByPreviewAndMergedByInit() throws Exception 
{
+        Path project = tempDir.resolve("orders");
+        Path config = 
Files.createDirectories(project.resolve(".codex")).resolve("config.toml");
+        String existing = "model_reasoning_effort = 
\"high\"\n\n[mcp_servers.other]\ncommand = \"other-mcp\"\n";
+        Files.writeString(config, existing);
+        List<String> before = snapshot(project);
+
+        List<ManagedFiles.Change> preview = new 
InitService().preview(request(project, "codex"));
+
+        assertEquals(before, snapshot(project));
+        assertTrue(preview.stream().anyMatch(
+                change -> change.path().equals(".codex/config.toml") && 
change.action() == Action.MERGE),
+                preview.toString());
+
+        new InitService().initialize(request(project, "codex"));
+
+        String merged = Files.readString(config);
+        assertTrue(merged.startsWith(existing), merged);
+        assertTrue(merged.contains("[mcp_servers.camel]"), merged);
+    }
+
+    @Test
+    void preservedWrapperIsReportedWithoutAProposedCopy() throws Exception {
+        Path project = tempDir.resolve("orders");
+        Files.createDirectories(project);
+        Files.writeString(project.resolve("mvnw"), "#!/bin/sh\n# team 
wrapper\n");
+
+        InitResult result = new InitService().initialize(request(project, 
"claude"));
+
+        assertEquals("#!/bin/sh\n# team wrapper\n", 
Files.readString(project.resolve("mvnw")));
+        ManagedFiles.Change conflict = result.conflicts().stream()
+                .filter(change -> 
change.path().equals("mvnw")).findFirst().orElseThrow();
+        assertNull(conflict.proposal());
+        
assertFalse(Files.exists(project.resolve(ManagedFiles.PROPOSALS).resolve("mvnw")));
+        // No partial wrapper is assembled around the project's own file, in 
the project or as a proposal.
+        for (String other : List.of("mvnw.cmd", 
".mvn/wrapper/maven-wrapper.properties")) {
+            assertFalse(Files.exists(project.resolve(other)), other);
+            
assertFalse(Files.exists(project.resolve(ManagedFiles.PROPOSALS).resolve(other)),
 other);
+        }
+    }
+
     @Test
     void reinitializationPreservesUserEditsAndRefreshesUntouchedFiles() throws 
Exception {
         Path project = tempDir.resolve("orders");

Reply via email to