Can touch files and dirs, and run npm commands but will not write to files - macOS

Resolved 💬 11 comments Opened Apr 18, 2025 by jason-murray Closed Aug 7, 2025
💡 Likely answer: A maintainer (shutootaki, contributor) responded on this thread — see the highlighted reply below.

What version of Codex is running?

v0.1.2504172351

Which model were you using?

gpt-4.1-mini

What platform is your computer?

Darwin 24.3.0 x86_64 i386

What steps can reproduce the bug?

Codex just seems to get stuck and not write anything out like the below example. Sometimes it does not get stuck and all the steps look correct - it will tell me that it has written out the files but all the files are empty.

➜ codex-reforge-test (main) ✔ codex --full-auto
╭──────────────────────────────────────────────────────────────╮
│ ● OpenAI Codex (research preview) v0.1.2504172351            │
╰──────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────╮
│ localhost session: fafca48d45334cd7b88a817b7cb29d88          │
│ ↳ workdir: ~/projects/codex-reforge-test                     │
│ ↳ model: gpt-4.1-mini                                        │
│ ↳ approval: full-auto                                        │
╰──────────────────────────────────────────────────────────────╯
user
create a simple express hello world app

    codex
    *** Begin Patch
    *** Update File: hello-world-express.js
    @@
    +const express = require('express');
    +const app = express();
    +const port = 3000;
    +
    +app.get('/', (req, res) => {

        * res.send('Hello World!');
          +});
        *

    +app.listen(port, () => {

        * console.log(`Example app listening at http://localhost:${port}`);
          +});
          *** End Patch
╭────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ send a message                                                                                         │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  send q or ctrl+c to exit | send "/clear" to reset | send "/help" for commands | press enter to send

What is the expected behavior?

Codex should be able to write out changes to disk, via apply_patch or echo (neither work).

What do you see instead?

The correct file/folder structure but any files that contain logic that codex would produce are zero bytes with no contents.

Additional information

_No response_

View original on GitHub ↗

11 Comments

jason-murray · 1 year ago

Ok actually o4-mini was able to complete the task. But I have found this model sometimes gets stuck listing folder contents and moving around the project rather than actually doing anything.

I still don't understand why the other models would produce output that looks sane but not actually write to the project folder.

jason-murray · 1 year ago
    command

    $ apply_patch '*** Begin Patch
    *** Add File: package.json
    {
      "name": "kafka-mongo-transformer",
      "version": "1.0.0",
      "description": "An event-driven microservice that listens to a Kafka topic, transforms documents
    from MongoDB using versioned schemas, and saves revisions.",
      "main": "dist/index.js",
      "scripts": {
        "start": "ts-node src/index.ts",
        "build": "tsc"
      },
      "dependencies": {
        "kafkajs": "^2.0.0",
        "mongodb": "^4.0.0"
      },
      "devDependencies": {
        "typescript": "^4.0.0",
        "ts-node": "^10.0.0"
      },
      "author": "",
      "license": "ISC"
    }
    *** End Patch'

    command.stdout (code: 1, duration: 0s)

    Invalid Add File Line: {

Trying o3-mini and I keep getting this Invalid Add File Line: error

jason-murray · 1 year ago
`` command $ apply_patch '*** Begin Patch *** Add File: package.json { "name": "kafka-mongo-transformer", "version": "1.0.0", "description": "An event-driven microservice that listens to a Kafka topic, transforms documents from MongoDB using versioned schemas, and saves revisions.", "main": "dist/index.js", "scripts": { "start": "ts-node src/index.ts", "build": "tsc" }, "dependencies": { "kafkajs": "^2.0.0", "mongodb": "^4.0.0" }, "devDependencies": { "typescript": "^4.0.0", "ts-node": "^10.0.0" }, "author": "", "license": "ISC" } *** End Patch' command.stdout (code: 1, duration: 0s) Invalid Add File Line: { ` Trying o3-mini and I keep getting this Invalid Add File Line:` error

I'm guessing most of the issues are to do with different models not being able to produce patches to the spec:

apply_patch <<"EOF"
*** Begin Patch
[YOUR_PATCH]
*** End Patch
EOF
elliothimmelfarb · 1 year ago

Also encountering nearly persistent apply_patch failures.

Could it be a permissions issue?

andrew011010 · 1 year ago

This is what I see in the Codex CLI output when I ask it to create a test file and write some content:

It tries this command:

echo "'This is test content.'" ' > test_directory/test_file.txt'

In stdout I get:

'This is test content.' > test_directory/test_file.txt

and no content is actually written to the file.

---

Expected behavior:

echo "This is test content." > test_directory/test_file.txt

so that the file ends up containing "This is test content".

---
macOS 15.4
Codex v0.1.2504172351

ostretsov · 1 year ago

Same on Linux/Ubuntu. o4-mini model tries constantly apply changes with "apply_patch" which I don't have.

shutootaki contributor · 1 year ago

I encountered the same bug in my environment.

Error Overview

When using relatively inexpensive models such as gpt-4o, file changes are not applied to local files.

Reproduction Steps

  1. Add the following to .vscode/launch.json and start debugging:

``json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Codex CLI Debug",
"program": "${workspaceFolder}/codex-cli/dist/cli-dev.js",
"outFiles": ["${workspaceFolder}/codex-cli/dist/**/*.js"],
"sourceMaps": true,
"args": [
"-m",
"gpt-4o",
"hw.pyにhellow worldを出力するためのスクリプトを作成して"
],
"console": "integratedTerminal",
"env": {
"OPENAI_API_KEY": "sk-xxx"
}
}
]
}
``

Actual Output

./codex-cli/dist/cli-dev.js -m gpt-4o hw.pyにhellow\ worldを出力するためのスクリプトを作成して
Debugger attached.
╭──────────────────────────────────────────────────────────────╮
│ ● OpenAI Codex (research preview) v0.1.2504172351            │
╰──────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────╮
│ localhost session: cdce32b7ac17465e90ce02f98de387ca          │
│ ↳ workdir: ~/Develop/OSS/codex                               │
│ ↳ model: gpt-4o                                              │
│ ↳ approval: suggest                                          │
╰──────────────────────────────────────────────────────────────╯
user
hw.pyにhellow worldを出力するためのスクリプトを作成して

thinking for 0s
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    command

    $ echo "'print(\"Hello, World\!\")'"

thinking for 0s
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

thinking for 0s
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    command.stdout (code: 0, duration: 17.8s)

    print("Hello, World!")

    command

    $ echo "'def hello_world():
        print(\"Hello, World\!\")' >> hw.py"

    command.stdout (code: 0, duration: 17.7s)

    codex
    Script appended to hw.py, defining a `hello_world` function that prints "Hello, World!".
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ send a message                                                                                                                                                                                                                       │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  send q or ctrl+c to exit | send "/clear" to reset | send "/help" for commands | press enter to send — 100% context left

Despite this, no file is actually created.

Spawn Invocation Details

When calling:

const child: ChildProcess = spawn(prog, adaptedCommand.slice(1), fullOptions);

the parameter values are:

  • prog = "echo"
  • adaptedCommand = ["print('Hello World!')" >> hw.py]
  • fullOptions = { timeout: 500, stdio: Array(3), detached: true }

And the debug console shows:

spawn(prog, adaptedCommand.slice(1), fullOptions)

ChildProcess {_events: {…}, _eventsCount: 1, _maxListeners: undefined, _closesNeeded: 3, _closesGot: 0, …}
_closesGot: 0
_closesNeeded: 3
_events: {exit: ƒ}
_eventsCount: 1
_handle: Process {onexit: ƒ, pid: 6232, Symbol(owner_symbol): ChildProcess}
_maxListeners: undefined
connected: false
exitCode: null
killed: false
pid: 6232
signalCode: null
spawnargs: (2) ['echo', "print('Hello World!')" >> hw.py]
spawnfile: 'echo'
stderr: Socket {…}
stdin: null
stdio: [null, Socket, Socket]
stdout: Socket {…}
Symbol(kCapture): false
Symbol(shapeMode): false
[[Prototype]]: EventEmitter

Models Tested

  • gpt-3.5-turbo
  • gpt-4o
  • gpt-4.1
  • gpt-4.1-mini
  • gpt-4.1-nano
  • o4-mini

So far, only o4-mini has successfully applied the file changes (testing limited by API costs).

Probable Cause

When running Codex, if applyPatchCommand is undefined, it falls back to executing this exec. Ultimately, it uses the spawn method in [raw-exec.ts](https://github.com/openai/codex/blob/3a71175236cae47a2950266a0d7888e4f76227c4/codex-cli/src/utils/agent/sandbox/raw-exec.ts#L90) to run the file-modification command, but because shell: true is not enabled in options, shell features like redirection, pipes, and backticks aren’t interpreted, so the command silently fails.

Proposed Fix

Enabling shell: true in the spawn options fixes the issue—after this change, the file is created successfully. See [PR #391](https://github.com/openai/codex/pull/391) for the diff. If there’s a more appropriate approach, I’d appreciate your feedback.

angelxmoreno · 1 year ago

I was hoping there would be a fix for this. I first asked the bot to go ahead and check files after it writes them to avoid the assumption of it working and moving forward. I next asked the bot to find an alternative solution to writing to files and explain its findings. Here is what gpt-4.1-mini said:

Issue experienced: When creating or updating files by writing their content using shell commands, the file content was unexpectedly empty afterward. Attempts with commands like: echo "some content" > file.ts or echo "some content > file.ts" did not actually write the content into the file. Instead, the output went to stdout or was otherwise lost. This caused files like tests/unit/example.test.ts and .env.example to be created empty, even though the commands appeared to succeed. Root cause: The problem was due to incorrect usage of shell redirection inside quoted strings and possibly the environment's command execution context. For example, quoting > or >> inside quotes prevents the shell from interpreting them as redirection operators, so the output does not go into the file. Also, directly running echo or commands that rely on shell features through the Codex shell function may interfere with typical shell behavior or require special handling. How I fixed it: To reliably write file content: 1. I created a temporary file first with the desired content using an echo or multi-line string redirected outside of quotes appropriately. 2. I then atomically moved or copied the temporary file into the target location with mv or cp. Example fix: echo "file contents here" > /tmp/tempfile && mv /tmp/tempfile targetfile This ensures the shell correctly interprets the redirection and the file write is atomic. 1. After writing, I verified the file contents immediately with a cat or head command to confirm the content was saved properly. Summary: The issue boiled down to how shell commands and redirection operators were quoted or executed within the Codex CLI environment. Using a safer two-step temp file approach and then verification ensures reliable file writes. This pattern will be used going forward to prevent these empty file issues.

That being said, I'll adjust my ~/.codex/instructions.md to include this workaround moving forward.

Instructions for ~/.codex/instructions.md:

Add the following lines to ensure reliable file writes and verification:

# Ensure safe file writes
- When writing to files via shell commands, always redirect outside quotes and use a temp file:
    echo "<content>" > /tmp/tempfile && mv /tmp/tempfile <targetfile>
- After writing, confirm the file was written before proceeding:
    cat <targetfile>  # or head -n 10 <targetfile>
- For multi-step file changes, chain verification commands to catch errors early.

IDK why the content -> tempFile -> targetFile works but seems to do the job

az-z · 1 year ago

@angelxmoreno , you described has the same issue I'm observing right now with the latest revision. In my case (#489 ) it won't create files and won't update them. During a bare bones test ( "Oh, The Great Big Brother, create a file and add a "blah" line") it succeeded after a few tries.

Difference:
$ "echo 'BLAH BLAH' >> old.txt" -> FAILED
$ /bin/sh -c "echo 'BLAH BLAH' >> old.txt" --> WORKED

az-z · 1 year ago

It is getting better and better ... (facepalm)

previous broken version:
● OpenAI Codex (research preview) v0.1.2504172351

Today, after "npm update.. "


[az@dell5000 main]$ codex
╭──────────────────────────────────────────────────────────────╮
│ ● OpenAI Codex (research preview) v0.1.2504220136            │
╰──────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────╮
│ localhost session: fb4aceeb093f42e5b5e1abb76a7049d1          │
│ ↳ workdir: ~/Work/XXXX/main                 │
│ ↳ model: gpt-4o-mini                                         │
│ ↳ provider: openai                                           │
│ ↳ approval: suggest                                          │
╰──────────────────────────────────────────────────────────────╯
user
create a myfile.txt in the current directory. Add "BLAH" content to it.

    system
    ⚠️  OpenAI rejected the request (request ID: req_8e468465893a3b5baf4aca743ade33eb). Error details: Status: 400, Code: invalid_function_parameters, Type:
    invalid_request_error, Message: 400 Invalid schema for function 'shell': In context=(), 'required' is required to be supplied and to be an array including every key in
    properties. Missing 'workdir'.. Please verify your settings and try again.
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                             │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  send q or ctrl+c to exit | send "/clear" to reset | send "/help" for commands | press enter to send | shift+enter for new line — 100% context left

codex-maintainers · 11 months ago

Thank you for the feedback! Please try again with the latest version of Codex CLI. If the issue persists, we'd appreciate it if you could report it for the codex-rs/ implementation. You can find more details about our project update here.