How to Use the Codex IDE Extension in VS Code — Inline Editing, Context Sharing, and Task Handoff

Complete Tutorial: Using the Codex IDE Extension in VS Code (Installation, Configuration, Inline Edits, Work Hand-offs, and Advanced Multi-File Workflows)

The Codex IDE extension for Visual Studio Code brings state-of-the-art AI development capabilities directly into your editor, tightly integrated with your files, terminals, and extensions. In this end-to-end tutorial, you will learn how to install and configure the extension, craft high-signal prompts that automatically include relevant context, review and apply AI-generated edits inline, hand off long-running or large-scope tasks to Codex Work without breaking your flow, orchestrate multi-file edits with discipline, and integrate with your existing VS Code extension stack. We will also cover how to use the newest GPT-5.6 Sol, Terra, and Luna models effectively, share context safely between the IDE and the Codex cloud environment, and troubleshoot common issues with clear, actionable steps.

How to Use the Codex IDE Extension in VS Code — Inline Editing, Context Sharing, and Task Handoff

Who This Tutorial Is For

This tutorial is for developers and engineering teams who want to augment their VS Code workflows with reliable AI assistance. Whether you’re writing greenfield features, migrating frameworks, upgrading dependencies, building APIs, or documenting code, the Codex IDE extension helps you move faster while preserving reviewability and control.

  • Individual developers who want to boost productivity with inline AI edits and context-aware prompts.
  • Team leads and staff/principal engineers who need governance, reproducibility, and safe multi-file refactors.
  • DevOps, platform engineers, and SREs who want to automate repetitive edits and apply change sets across repos.
  • Technical writers and developer advocates who want to generate or improve docs, READMEs, and examples.

Table of Contents

Prerequisites

Before installing the Codex IDE extension, verify the following prerequisites. These ensure optimal performance, access to the Codex cloud environment for long-running tasks, and compatibility with your local toolchain.

Supported Operating Systems and VS Code Versions

  • Operating Systems: Windows 10/11, macOS 12+ (Apple Silicon and Intel), Linux (Ubuntu 20.04+, Debian 11+, Fedora 37+).
  • VS Code: Stable channel version 1.85+ (recommended 1.90+). Ensure all pending updates have been applied.

Runtime and Tooling

  • Node.js 18+ if you’re developing JavaScript/TypeScript. For legacy projects, consider nvm to manage versions.
  • Python 3.10+ for Python projects. Ensure pip/venv or conda are set up as per your team’s practices.
  • Git 2.35+ to review and manage AI-generated change sets effectively.
  • Optional: Docker or Dev Containers if you plan to leverage containerized Codex Work environments.

Codex Account and Access

  • Codex account with IDE access enabled. Organization SSO may be required for enterprise plans.
  • API key or OAuth sign-in capability for Codex services.
  • Network egress allowed for model endpoints and Codex Work (check corporate proxies or VPN).

Security, Privacy, and Compliance

  • Consult your organization’s AI policy on source code sharing. Configure redaction rules and .codexignore to exclude secrets.
  • Review data retention and telemetry settings and set them to your compliance requirements before first use.
  • Use workspace trust in VS Code to isolate untrusted projects.

Recommended VS Code Extensions for a Smooth Experience

  • ESLint and Prettier (JS/TS) to auto-format AI edits after apply.
  • Python, Pylance for Python language services.
  • GitLens for diffing and code authorship insights on AI-generated edits.
  • Test adapters (Jest, Vitest, pytest, JUnit) for test-first prompting and validation loops.
  • Dev Containers / Remote Development extensions for containerized workflows.

Installation

Install the Codex IDE extension through the VS Code Marketplace or a .vsix file, then configure authentication, workspace settings, and model defaults to begin using Codex seamlessly inside your editor.

Section illustration

1. Install from Marketplace

  1. Open VS Code.
  2. Go to the Extensions view (Ctrl/Cmd+Shift+X).
  3. Search for “Codex IDE”. Publisher should be “Codex AI”.
  4. Click Install.

Alternatively, open the command palette (Ctrl/Cmd+Shift+P) and run: Extensions: Install Extensions, then search for “Codex IDE”.

2. Offline or Air-Gapped Installation via .vsix

  1. Obtain the signed .vsix package from your administrator or the official download URL.
  2. In VS Code, run: Extensions: Install from VSIX…
  3. Browse to the downloaded file and confirm installation.

For CI-managed developer workstations, you may script the install:

code --install-extension codex-ai.codex-ide-<version>.vsix --force

3. Sign In and Authenticate

Upon first launch, the extension may prompt you to sign in through OAuth or paste an API key. For OAuth:

  1. Click “Sign in to Codex”.
  2. Authenticate in your browser; SSO may be required for enterprise orgs.
  3. Return to VS Code. Authentication state should be reflected in the status bar (“Codex: Signed In”).

For API key usage, set it once and Codex stores it securely in the OS keychain:

// VS Code Settings (User or Workspace)
"codex.auth.provider": "apiKey",
"codex.auth.apiKey": "paste_your_key_here" // Prefer environment variable or Command Palette prompt

To keep secrets out of settings files, use environment variables:

# macOS/Linux (shell)
export CODEX_API_KEY="<your-key>"

# Windows (PowerShell)
setx CODEX_API_KEY "<your-key>"

Then in VS Code Settings:

"codex.auth.provider": "env",
"codex.auth.envKey": "CODEX_API_KEY"

4. Configure Models and Defaults

Codex supports GPT-5.6 Sol, Terra, and Luna. Each model targets different tasks:

  • GPT-5.6 Sol: Large-context, rigorous reasoning, refactors across many files, deep code comprehension.
  • GPT-5.6 Terra: General-purpose coding, balanced speed and quality, great for day-to-day development.
  • GPT-5.6 Luna: Lightweight, fast completions, ideal for docs, tests, and quick edits.

Set workspace defaults:

// .vscode/settings.json
{
  "codex.model.chat": "gpt-5.6-terra",
  "codex.model.edit": "gpt-5.6-terra",
  "codex.model.work": "gpt-5.6-sol",
  "codex.temperature": 0.2,
  "codex.maxTokens": 4096,
  "codex.inlineDiff.autoOpen": true,
  "codex.context.autoIncludeOpenFiles": true,
  "codex.context.maxFiles": 12,
  "codex.telemetry": "off",
  "codex.secure.mode": "org-policy",
  "codex.ignoreFile": ".codexignore",
  "codex.completions.enableCodeActions": true
}

5. Network, Proxy, and SSL

  • If behind a corporate proxy, configure both VS Code and Codex:
// VS Code Settings
"http.proxy": "http://proxy.company:8080",
"http.proxyAuthorization": "Basic base64userpass",
"http.systemCertificates": true,

// Codex-specific
"codex.network.proxy": "http://proxy.company:8080",
"codex.network.strictSSL": true

Provide custom CA certs as needed via your OS trust store or NODE_EXTRA_CA_CERTS for child processes:

export NODE_EXTRA_CA_CERTS="/etc/ssl/certs/your-ca.pem"

6. Telemetry, Privacy, and Exclusions

Exclude sensitive files from being uploaded as context to the Codex cloud or used in local prompts:

# .codexignore
**/*.pem
**/*.key
**/.env
secrets/**

# Optionally exclude large generated sources
dist/**
build/**
.target/**

Control what’s shared via settings:

"codex.context.shareTerminal": false,
"codex.context.shareEnv": false,
"codex.context.shareGitHistory": true

Basic Usage

Once installed and configured, begin with in-IDE prompts and inline edits. Learn how to bring open files and selections into prompts, review AI-generated changes in a diff view, and switch among GPT-5.6 Sol, Terra, and Luna for different development tasks.

Section illustration

Open the Codex Panel and Start a Conversation

  1. Open the Codex side panel from the Activity Bar (Codex logo) or run: Codex: Open Chat.
  2. Type your question or instruction in natural language.
  3. Codex auto-includes relevant context from your open file(s) if enabled. You can toggle this per message.

Example prompt:

Explain how this function works and propose a faster implementation.
Constrain changes to be backward compatible and add a docstring.

Bringing Open Files and Selections into Codex Prompts

Codex lets you explicitly add context from your editor selection or entire files. This improves precision and reduces hallucinations.

  1. Select a code block in the editor.
  2. Right-click and choose “Codex: Add Selection to Prompt.” The sidebar will show “Selection (filename:line-range)” as attached context.
  3. Alternatively, use the paperclip icon in the Codex chat input to attach files or run “Codex: Attach Open Files.”

Example—attach a function, then ask for an algorithmic improvement:

// selection in sort_utils.py
def top_k(items, k):
    result = []
    for item in items:
        # naive insert sort
        inserted = False
        for i in range(len(result)):
            if item > result[i]:
                result.insert(i, item)
                inserted = True
                break
        if not inserted:
            result.append(item)
        if len(result) > k:
            result.pop()
    return result

# prompt
Please rewrite this to O(n log k) using a min-heap, ensure equivalent outputs, and add unit tests.

Requesting Inline Edits

Inline edits apply directly to your code with a safe review step. There are two main modes:

  • Ask mode (chat): Describe a change; Codex proposes a patch.
  • Edit mode (command palette): Select code, then run Codex: Edit Selection with instructions.

Example—edit selection for a Node.js route handler:

// original server.js snippet
app.get('/api/users/:id', async (req, res) => {
  const user = await db.getUser(req.params.id);
  res.json(user);
});

// instruction
Harden the endpoint: validate id is UUID v4, handle not found with 404, and log errors.

Codex generates a patch. You’ll see an inline diff in the editor:

// proposed server.js change (diff conceptually)
- app.get('/api/users/:id', async (req, res) => {
-   const user = await db.getUser(req.params.id);
-   res.json(user);
- });
+ app.get('/api/users/:id', async (req, res) => {
+   try {
+     const id = req.params.id;
+     if (!isUuidV4(id)) return res.status(400).json({ error: 'Invalid id' });
+     const user = await db.getUser(id);
+     if (!user) return res.status(404).json({ error: 'Not found' });
+     res.json(user);
+   } catch (err) {
+     req.logger?.error({ err }, 'get user failed');
+     res.status(500).json({ error: 'Internal error' });
+   }
+ });

Accept hunks selectively, leave comments, or revert entirely. When ready, apply changes and run tests.

Reviewing AI-Generated Edits Inline (Diff View)

The diff view appears as squiggly-gutter inline change blocks or a split editor. Use the toolbar to:

  • Accept or reject individual change hunks.
  • Expand context around a change to understand impact.
  • Open a full diff view (Cmd/Ctrl+Shift+P → “Codex: Open Full Diff”).
  • Comment on changes inline; Codex can respond to comments with revisions.

For multi-file changes, Codex groups edits into a change set. You can:

  • Preview the patch across files.
  • Apply all, or cherry-pick file-by-file or hunk-by-hunk.
  • Stage and commit via Git with a generated message.

Switching Models On the Fly: GPT-5.6 Sol, Terra, Luna

Use the model switcher in the Codex panel footer. Rules of thumb:

  • Sol for cross-file refactors, deep analysis, and Work hand-offs.
  • Terra for everyday code edits and tests.
  • Luna for documentation and quick transformations.

Per-message override using command palette:

// Override for current prompt only
"Use gpt-5.6-sol for this refactor, respect TypeScript strict mode."

Integrating with Existing VS Code Extensions

Codex interoperates with your tools. Some examples:

  • ESLint/Prettier: Run on save to normalize style after applying an AI patch.
  • GitLens: Inspect authorship and blame context around changes; audit AI edits with commit metadata.
  • Testing Adapters: Ask Codex to generate or update tests, then run them via Test Explorer.
  • Dev Containers: Combine Codex edits with containerized runtime for reproducible environments.
  • Docker: Let Codex update Dockerfiles and compose definitions, then build locally for feedback.

Example: Documenting a Function with Luna

Use Luna for quick docs and examples:

// original
export function chunk(arr, size) {
  const out = [];
  for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
  return out;
}

// prompt
Add a JSDoc comment, examples, and edge-case notes. Remain concise and correct.

Codex proposes doc comments and examples that you can review in a diff view before applying.

Advanced Workflows

Move beyond single-file edits. Hand off complex tasks to Codex Work, share context safely between your IDE and the Codex cloud environment, orchestrate multi-file edits and migrations, and use robust prompt engineering patterns designed for in-IDE development.

Handing Off Longer Tasks to Codex Work Without Breaking Flow

Some requests are too long for a quick inline edit: large refactors, framework upgrades, performance audits, or cross-repo changes. Codex Work runs these tasks in the cloud with your project’s context and returns reviewable change sets.

  1. Select “Codex: Create Work” from the command palette or click “Hand Off to Work” in the chat panel.
  2. Choose a template (e.g., “Migrate to React 18”, “Replace Lodash with native APIs”, “TypeScript strict-ify”).
  3. Confirm scope: include folders, max files, and ignored paths (honors .codexignore).
  4. Select model (Sol recommended) and constraints (e.g., run linter/tests, limit file changes per PR).
  5. Start the Work job. Continue local editing while it runs; progress updates appear in the status bar.

When ready, the Work job posts a summary and proposed change set. Click “Review” to open a multi-file diff inside VS Code.

Context Sharing Between IDE and Codex Cloud Environment

Codex can synchronize relevant context from your IDE to the cloud Work environment, including:

  • File content and directory structure (respecting ignore rules).
  • Important configuration: tsconfig.json, pyproject.toml, package.json, Dockerfile, CI definitions.
  • Git metadata (optional): last commits, branches, remotes for patch generation.

Recommended settings for safe context sharing:

// .vscode/settings.json
{
  "codex.context.share": "explicit", // explicit | auto
  "codex.context.allowedGlobs": [
    "src/**",
    "lib/**",
    "app/**",
    "tests/**",
    "package.json",
    "requirements.txt",
    "pyproject.toml",
    "tsconfig.json"
  ],
  "codex.context.redactions": [
    { "pattern": "AKIA[0-9A-Z]{16}", "replacement": "REDACTED_AWS_KEY" },
    { "pattern": "-----BEGIN PRIVATE KEY-----[\\s\\S]*?-----END PRIVATE KEY-----", "replacement": "REDACTED_PRIVATE_KEY" }
  ]
}

When a Work task needs to run commands (lint, build, test), configure the runtime:

// .codex/work.yaml
runtime:
  image: "ghcr.io/company/dev:node-18"
  setup:
    - npm ci
    - npm run build
  test:
    - npm test -- --reporter=json
limits:
  maxChangedFiles: 200
  maxDiffHunksPerFile: 50
review:
  requirePassingTests: true
  annotateWithCoverage: true

Codex uses ephemeral cloud workspaces for privacy. Artifacts and patch results are stored for review and auditing; source files are not retained beyond policy windows you configure.

Multi-File Editing Workflows

Multi-file edits require discipline to avoid regressions. Codex assists with scoping, previewing, and validating change sets.

Strategy 1: Iterative Scopes with Tests

  1. Start small: “Update input validation across routes under src/routes/. Add tests for missing cases.”
  2. Review the diff; ask Codex to justify risky changes in comments.
  3. Run unit tests and smoke tests locally; iterate on failures with “Codex: Fix Failing Tests.”
  4. Commit with AI-generated but human-reviewed message.

Strategy 2: Pattern-Driven Transformations

Codex is excellent at repetitive transformations if you express the rule. Example: migrate from CommonJS to ES Modules across src/.

// Prompt template (attach representative samples)
Goal:
- Convert CommonJS to ESM across src/**
- Maintain behavior and default exports
- Update tsconfig and package.json "type"

Rules:
- Replace require(...) with import
- Replace module.exports / exports.something with export default / named export
- Update dynamic imports to await import()
- Respect TS types and strictNullChecks

Constraints:
- Do not change public API signatures
- Provide per-file diffs and a single patch
- Add a codemod report: "transforms.md"

Codex returns a change set and a transforms.md report. You can request follow-ups like “roll back risky files” or “split the patch by feature.”

Strategy 3: Spec-and-Implement with Tests

Codex performs best when you give it a spec. Example—new feature end-to-end:

// spec.md (attach to prompt)
Feature: CSV export for user lists
Requirements:
- Endpoint: GET /api/export/users.csv
- Format: header row, quoted fields, UTF-8
- Auth: admin only
- Streaming response
- Add integration tests
- Update README with usage and curl example

Prompt:

Implement the feature per spec.md. Use GPT-5.6 Terra for code, Luna for docs.
Add tests and update CI. Validate with existing middlewares. Return a multi-file patch.

Code Examples: Multi-File Edits and Validation

Below is an example of a Codex-suggested multi-file change set for a TypeScript project, followed by test updates.

// src/utils/env.ts (proposed)
export function getEnv(key: string, fallback?: string): string {
  const v = process.env[key];
  if (v == null || v === "") {
    if (fallback !== undefined) return fallback;
    throw new Error(`Missing environment variable: ${key}`);
  }
  return v;
}

// src/server.ts (proposed)
import express from 'express';
import { getEnv } from './utils/env';
const app = express();
app.get('/health', (_req, res) => res.json({ ok: true, env: getEnv('NODE_ENV', 'dev') }));
export default app;

// tests/env.test.ts (proposed)
import { getEnv } from '../src/utils/env';

describe('getEnv', () => {
  it('returns value when present', () => {
    process.env.FOO = 'bar';
    expect(getEnv('FOO')).toBe('bar');
  });
  it('returns fallback when missing', () => {
    delete process.env.MISSING;
    expect(getEnv('MISSING', 'x')).toBe('x');
  });
  it('throws when missing and no fallback', () => {
    delete process.env.SECRET;
    expect(() => getEnv('SECRET')).toThrow(/Missing environment variable/);
  });
});

Ask Codex to run tests in a Work environment or locally trigger your test runner. Iterate if needed.

Inline Diff Mastery: Hunk Control, Comments, and Revisions

Use the inline diff toolbar for granular control:

  • Accept hunk: merges a single block.
  • Reject hunk: discards a block; Codex can revise based on your reasoning.
  • Comment: “This breaks streaming—keep the chunked response.” Codex will propose a new hunk.
  • Split View: Compare full files to spot subtle changes (imports, types, config).

Combining Work Hand-Off with Local Edits

Example mixed flow:

  1. Local: “Codex: Add rate limiting middleware and tests.” Review, apply.
  2. Hand off to Work: “Scale changes across all route groups and document limits.”
  3. Local: Integrate patch, resolve conflicts flagged by Git, run lint/tests.
  4. Work: Request “patch shrink”—reduce diff noise, consolidate duplicate helpers.
  5. Local: Final pass with GitLens and code owners’ review.

Using GPT-5.6 Sol, Terra, and Luna Together

You can orchestrate multiple models within a single task:

  • Analysis phase: Sol reads the repo and writes a plan and risks.
  • Implementation phase: Terra generates code changes with guardrails.
  • Documentation phase: Luna drafts docs, READMEs, and upgrade notes.

Sample meta-prompt for a Work job:

Plan: Use gpt-5.6-sol to produce a migration design doc, then implement with gpt-5.6-terra.
After code stabilizes, have gpt-5.6-luna draft docs and a CHANGELOG with clear upgrade steps.
Enforce tests must pass. Limit to 150 files per patch. Output a structured report.

Integration with Existing Extensions and Tooling

Codex can call VS Code tasks and scripts. Example configuration to run lint/tests before accepting a large patch:

// .vscode/tasks.json
{
  "version": "2.0.0",
  "tasks": [
    { "label": "lint", "type": "shell", "command": "npm run lint" },
    { "label": "test", "type": "shell", "command": "npm test" }
  ]
}

Link tasks into Codex settings so patches trigger validations:

// .vscode/settings.json
{
  "codex.validation.tasks": ["lint", "test"],
  "codex.validation.blockApplyOnFailure": true
}

Dev Containers and Remote

If you code inside a Dev Container or SSH remote, Codex works with your remote filesystem and can still hand off to Work. Ensure your .devcontainer/devcontainer.json includes prerequisites.

{
  "name": "Node 18 + tools",
  "image": "mcr.microsoft.com/devcontainers/javascript-node:0-18",
  "postCreateCommand": "npm ci",
  "customizations": {
    "vscode": {
      "extensions": [
        "codex-ai.codex-ide",
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode"
      ]
    }
  }
}

When in a container, Codex respects in-container paths, shells, and tasks. Work hand-offs still run in Codex cloud containers, ensuring parity when images match.

Prompt Engineering in the IDE: Best Practices

Codex is most effective when prompts are concrete and constrained. The IDE context system helps, but you can shape outcomes further.

  • State the goal: what to change, where, and why.
  • Specify constraints and invariants: API must remain backward-compatible, tests must pass, no new runtime deps.
  • Provide exemplars: attach a representative file or test that demonstrates expected patterns.
  • Request diffs and rationales: ask for a summary of each change with risk flags.
  • Iterate: ask Codex to address comments and revise hunks you rejected.

Prompt Templates You Can Reuse

// "Refactor with invariants"
Refactor [path/glob] to [goal]. Keep APIs stable. Do not change public exports.
Respect [linters] and [tests]. Return a unified patch. Flag any risky changes.

// "Test-first bug fix"
Given failing test output (attached), localize the bug. Create minimal fix with tests.
Explain root cause and add a regression test. Keep diffs small.

// "Performance pass"
Optimize [function/module]. Include micro-benchmarks. Avoid premature allocation.
Measure and report improvement. Keep algorithmic complexity constraints.

// "Security hardening"
Audit [path] for input validation, authz checks, and unsafe dynamic operations.
Fix issues and add tests. Follow [org security policy] attached. Summarize key changes.

Case Study: Framework Upgrade With Work and Local Edits

Scenario: Upgrading from Express 4 to 5 across a large codebase.

  1. Local: Ask Codex (Sol) to scan for incompatible res usages. It proposes a checklist.
  2. Work: Submit a plan: “Perform incremental upgrade in three patches: middleware, routing, error handling.”
  3. Local: Apply patch 1; run tests and fix minor issues via inline edits.
  4. Work: Patch 2 generated; docs updated by Luna; verify with staging environment.
  5. Local: Patch 3 applied; finalize with GitLens and code owner review.

Tips & Tricks

Level up your daily flow with customization, keyboard shortcuts, and model-specific tactics. These tips help you keep Codex responsive, precise, and integrated with your habits.

Keybindings for Speed

// keybindings.json (examples)
[
  {
    "key": "ctrl+alt+.",
    "command": "codex.editSelection",
    "when": "editorHasSelection"
  },
  {
    "key": "ctrl+alt+/",
    "command": "codex.openChat"
  },
  {
    "key": "ctrl+alt+,",
    "command": "codex.attachOpenFiles"
  },
  {
    "key": "ctrl+alt+;",
    "command": "codex.acceptCurrentHunk",
    "when": "codex.diffActive"
  }
]

Prompt Snippets

// .vscode/codex.prompts.json
{
  "security_hardening": {
    "description": "Harden endpoints with validation and errors",
    "prompt": "Harden the following endpoints: add input validation, handle 400/404/500 properly, log failures, and do not leak stack traces. Keep API backward compatible."
  },
  "strict_typescript": {
    "description": "Enable and satisfy TS strict mode",
    "prompt": "Enable strict mode in tsconfig and satisfy resulting errors across src/**. Do not relax rules. Maintain public API compatibility. Provide a patch and a checklist."
  },
  "docstring_python": {
    "description": "Generate Google-style docstrings",
    "prompt": "Add Google-style docstrings to these Python functions. Do not change behavior. Add one example each."
  }
}

Insert a saved prompt via the Codex chat dropdown and attach the active file or selection.

Access 40,000+ AI Prompts for ChatGPT, Claude & Codex — Free!

Subscribe to get instant access to our complete Notion Prompt Library…

Get Free Access Now

Model Tuning: Temperature and Max Tokens

  • Lower temperature (0.1–0.3): deterministic, consistent edits (ideal for refactors).
  • Medium (0.4–0.6): creative variations (good for docs and test generation).
  • Higher tokens: larger diffs but riskier. Keep under policy limits and review carefully.

Managing Context Budget

To prevent context overflow:

  • Attach only relevant files and line ranges. Use “Attach Open Files” sparingly.
  • Leverage .codexignore to avoid huge generated directories.
  • Use Sol for big-picture tasks; Terra and Luna for focused edits.

Using Codex with Git Cleanly

  • Create a feature branch per Work job or major refactor.
  • Commit frequently, grouping conceptual changes.
  • Use Git hooks to run lints/tests pre-commit for AI-generated changes.
// .husky/pre-commit (example)
#!/bin/sh
npm run lint && npm test
[ $? -ne 0 ] && echo "Fix issues before commit." && exit 1

Security and Privacy Controls

  • Set codex.secure.mode to “org-policy” or “strict”.
  • Redact secrets with patterns and explicitly denylist files/folders.
  • Disable terminal/env sharing unless necessary.
  • Use ephemeral Workspaces for cloud execution and enable retention windows.

Team Conventions and Prompt Hygiene

Create a repo-level CODING_WITH_AI.md with norms for prompting, reviewing, and committing AI changes:

# CODING_WITH_AI.md
- Always attach the smallest relevant context.
- List invariants and constraints explicitly.
- Prefer test-first or test-included changes.
- Use Sol for design, Terra for code, Luna for docs.
- Accept hunks selectively; ask for revisions with comments.
- Never commit secrets; validate redactions.

IDE Workflows for Documentation with Luna

For docs-heavy tasks, pipe Luna through your docs tooling:

  • Generate Markdown and run it through your linter (e.g., markdownlint).
  • Ask Luna to include code fences consistent with your site builder.
  • Request a changelog and migration guide for significant patches.

Internal Resources

For deeper dives on related topics, see our companion guides: Prompt Engineering in VS Code, AI Governance for Enterprise Dev Teams, and Dev Containers with AI Tooling. Each guide expands on specific workflows, policies, and performance tips linked to your IDE usage.

Troubleshooting

Below are common issues and proven solutions. When in doubt, enable verbose logs and check the Codex Output panel.

1) Installation Fails or Extension Not Loading

  • Check VS Code version: must be 1.85+.
  • Disable conflicting extensions temporarily (especially other AI/edit providers) and retry.
  • Look at Developer Tools (Help → Toggle Developer Tools) for activation errors.
  • Reinstall via Marketplace or VSIX with --force:
code --install-extension codex-ai.codex-ide --force

2) Sign-In or API Key Issues

  • For OAuth, complete the browser flow and ensure your org domain is allowed.
  • For API keys, prefer environment variables over settings. Verify with:
echo $CODEX_API_KEY  # macOS/Linux
echo %CODEX_API_KEY%  # Windows
  • Clear stored credentials if corrupt: VS Code → Settings → Security → Clear Codex entry.
  • Ensure system clock is correct; OAuth tokens can fail if time is skewed.

3) Proxy or SSL Problems

  • Configure http.proxy in VS Code and codex.network.proxy for Codex.
  • Set http.systemCertificates to true if your org uses a custom CA.
  • Provide the CA via OS trust or NODE_EXTRA_CA_CERTS.
  • Check firewall rules allow Codex endpoints on 443.

4) “Context Limit Exceeded” or Truncated Responses

  • Reduce attached files or limit to selections.
  • Use Sol for large-context tasks or hand off to Work.
  • Lower codex.maxTokens to encourage concise patches and ask Codex for chunked diffs (“split into batches of 50 files”).

5) Inline Diff Doesn’t Appear

  • Ensure codex.inlineDiff.autoOpen is true or open it from the Codex panel manually.
  • Check editor state: an unsaved conflicting change can block patch application.
  • Disable other inline edit providers temporarily to isolate conflicts.
  • Validate that the file on disk matches the version Codex used for the patch; re-run if drifted.

6) Edits Partially Apply or Cause Merge Conflicts

  • Stage your current work; stash local changes if necessary; run Codex on a clean working tree.
  • Apply hunks selectively. If conflicts persist, ask Codex: “Rebase the patch against the latest main.”
  • Use GitLens to inspect conflicting lines and ask Codex to regenerate only the conflicting sections.

7) Work Job Stuck or Failing

  • Open the job details: check logs for build or test failures.
  • Ensure the Work runtime image has all dependencies and correct Node/Python versions.
  • Reduce scope: limit changed files or split tasks into phases.
  • Retry with Sol for better planning, or disable “requirePassingTests” temporarily to fetch a patch you can amend locally.

8) Model-Specific Behavior Not as Expected

  • If Terra seems too verbose, lower temperature and ask for minimal diffs.
  • If Luna misses details in docs, attach the spec and examples explicitly.
  • If Sol is slow, restrict scope or provide a tighter plan to reduce analysis time.

9) Performance Issues in Large Repos

  • Disable auto-inclusion of open files when working with large monorepos; attach explicit files only.
  • Use Work to process large tree changes remotely and review summarized patches.
  • Ensure VS Code file watchers are not overwhelmed; tune files.watcherExclude.
// settings.json
"files.watcherExclude": {
  "**/node_modules/**": true,
  "**/dist/**": true,
  "**/.git/**": true
}

10) Security and Compliance Concerns

  • Set codex.telemetry to off and “strict” secure mode if your policy requires it.
  • Verify redaction rules and ignore lists catch secrets and large binaries.
  • Use Work’s ephemeral environment with enforced retention and audit logs.

11) Validation Failures After Applying Patches

  • Ask Codex: “Fix failing tests” and attach the test output.
  • Run formatters/linters automatically on save to normalize style diffs.
  • Use Test Explorer to re-run only affected suites for fast iteration.

Collecting Logs and Filing a Report

  1. Open Output → Codex IDE. Set log level to “Debug.”
  2. Reproduce the issue and copy logs.
  3. Gather environment details: OS, VS Code version, extension version, proxy settings.
  4. Attach anonymized logs and your settings to your support ticket.

End-to-End Example: From Prompt to Multi-File Patch with Review

Let’s walk through a real-world scenario: adding structured logging to an Express app, with type-safe helpers, tests, and docs, using a combination of Terra (implementation) and Luna (docs), and then escalating to Sol for a larger codebase-wide consistency pass.

Step 1: Seed Context and Request a Local Edit

  1. Open src/server.ts and src/logger.ts. Attach both to a Codex chat.
  2. Prompt: “Introduce pino-based structured logging. Add requestId per request, log errors with stack, redact secrets. Update existing routes to use logger.”
  3. Use Terra for balanced quality/speed. Review the inline diff for server.ts and logger.ts.

Step 2: Validate and Iterate

  1. Run npm test. If failures appear, right-click failure output → “Codex: Fix Failing Tests.”
  2. Ask Codex to add integration tests for logging behavior and redact patterns.

Step 3: Documentation with Luna

  1. Prompt: “Generate docs/logger.md with usage, examples, and advice on redaction patterns.”
  2. Review generated Markdown in the diff view. Apply and run markdownlint.

Step 4: Scale with Sol via Work

  1. “Codex: Create Work” → Template: “Standardize logging across services.”
  2. Scope: services/**/src/**, ignore dist/**.
  3. Constraints: 100 files per patch, tests must pass, single helper module per service.
  4. Run job. Continue local development while Work executes.

Step 5: Review the Multi-File Change Set

  1. Open the Work summary. Skim risk notes and files changed.
  2. Open the full diff. Reject hunks that alter unrelated behavior. Ask for revisions via comments (“keep original error shape”).
  3. Apply, run npm run lint && npm test, and commit with a generated summary.

Sample Generated Logger Helper

// src/logger.ts
import pino, { Logger } from 'pino';
import { randomUUID } from 'crypto';
const redact = ['req.headers.authorization', 'req.headers.cookie', 'password', 'secret', 'token'];

export function createLogger(): Logger {
  return pino({
    level: process.env.LOG_LEVEL || 'info',
    redact,
    transport: process.env.NODE_ENV !== 'production'
      ? { target: 'pino-pretty', options: { colorize: true } }
      : undefined
  });
}

export function requestId(): string {
  return randomUUID();
}

Sample Middleware with Request ID

// src/middleware/requestId.ts
import { requestId } from '../logger';

export function withRequestId(req, _res, next) {
  req.requestId = req.requestId || requestId();
  next();
}

Route Using the Logger

// src/routes/users.ts
import { createLogger } from '../logger';
const log = createLogger();

export async function getUser(req, res) {
  try {
    const user = await req.db.getUser(req.params.id);
    if (!user) return res.status(404).json({ error: 'Not found' });
    log.info({ rid: req.requestId, userId: req.params.id }, 'user fetched');
    res.json(user);
  } catch (err) {
    log.error({ rid: req.requestId, err }, 'getUser failed');
    res.status(500).json({ error: 'Internal error' });
  }
}

Docs Example (Luna)

# docs/logger.md
# Structured Logging

This project uses Pino for structured logs. Each request has a requestId for traceability.
Sensitive fields are redacted by default. Avoid logging raw user input or credentials.

## Usage
- Use `createLogger()` to construct a logger instance.
- Include `withRequestId` middleware in your Express pipeline.
- Log with context objects to preserve structure.

## Example
log.info({ rid: req.requestId, userId }, "user fetched");

Hands-On: Cross-Language Editing Scenarios

Codex excels across languages. Here are some focused examples showing selection prompts, inline diffs, and Work hand-offs for Python, TypeScript, and Go.

Python: Data Processing Optimization

# src/etl/transform.py (selection)
def dedupe_records(records):
    seen = set()
    out = []
    for r in records:
        key = (r['id'], r['timestamp'])
        if key not in seen:
            out.append(r)
            seen.add(key)
    return out

# prompt
Optimize for very large inputs (10M+). Use iterators, avoid large memory spikes, and add unit tests. Keep behavior identical.

TypeScript: Stronger Types and Exhaustive Switch

// src/models/events.ts
export type Event =
  | { type: 'user.created'; userId: string }
  | { type: 'user.deleted'; userId: string }
  | { type: 'billing.charged'; amount: number };

// selection in handler
switch (evt.type) {
  case 'user.created':
    // ...
    break;
  default:
    // ...
}

Prompt: “Refactor to exhaustive switch and handle all known event types; add a compile-time error on missing case. Provide tests.”

Go: Concurrency Safety

// pkg/cache/cache.go (selection)
type Cache struct {
  data map[string]string
}

func (c *Cache) Get(k string) string {
  return c.data[k]
}

func (c *Cache) Set(k, v string) {
  c.data[k] = v
}

// prompt
Make this cache concurrency-safe with RWMutex, add tests and benchmarks. Keep API identical.

Configuration Reference: Settings You’ll Use Often

Below is a compact reference of common settings to tune Codex in the IDE and cloud Work environment.

// .vscode/settings.json (select highlights)
{
  "codex.model.chat": "gpt-5.6-terra",
  "codex.model.edit": "gpt-5.6-terra",
  "codex.model.work": "gpt-5.6-sol",
  "codex.temperature": 0.2,
  "codex.maxTokens": 4096,
  "codex.inlineDiff.autoOpen": true,
  "codex.context.autoIncludeOpenFiles": true,
  "codex.context.maxFiles": 12,
  "codex.context.share": "explicit",
  "codex.context.allowedGlobs": ["src/**", "tests/**", "package.json", "pyproject.toml", "tsconfig.json"],
  "codex.context.redactions": [],
  "codex.validation.tasks": ["lint", "test"],
  "codex.validation.blockApplyOnFailure": true,
  "codex.telemetry": "off",
  "codex.secure.mode": "org-policy",
  "codex.network.proxy": "",
  "codex.network.strictSSL": true,
  "codex.ignoreFile": ".codexignore"
}
# .codex/work.yaml (typical)
runtime:
  image: "ghcr.io/org/dev:unified"
  setup:
    - npm ci
  test:
    - npm run test:ci
limits:
  maxChangedFiles: 150
  maxDiffHunksPerFile: 50
review:
  requirePassingTests: true
  annotateWithCoverage: true
split:
  perPackage: true
  maxFilesPerPR: 60

FAQ

Can I restrict Codex to read-only mode?

Yes. Disable edit capabilities with a policy or user setting and use chat-only analysis. You can still request patches as text and apply them manually.

How do I ensure consistent style across AI edits?

Use Prettier/ESLint or language-formatters on save and include a check in codex.validation.tasks. Ask Codex to run the same formatter in Work.

What’s the difference between Sol, Terra, and Luna?

Sol: deep reasoning and large-context tasks (planning, migrations). Terra: balanced code generation and refactors. Luna: fast, concise writing for docs and light edits.

How do I keep secrets safe?

Use .codexignore, redaction patterns, strict secure mode, and avoid attaching files with secrets. Disable terminal/env sharing unless explicitly needed.

With the Codex IDE extension, you can bring the full power of GPT-5.6 Sol, Terra, and Luna into your daily VS Code workflow. Start with small, reviewable edits, then scale to multi-file changes and Work hand-offs with strong guardrails, tests, and governance. The key is precise prompts, disciplined review in the diff view, and thoughtful integration with your existing tools.

Get Free Access to 40,000+ AI Prompts for ChatGPT, Claude & Codex

Subscribe for instant access to the largest curated Notion Prompt Library for AI workflows.

More on this

25 ChatGPT-5.5 Prompts for Legal Professionals — Contract Review, Case Research, Compliance Analysis, and Document Drafting

Reading Time: 26 minutes
25 Expert ChatGPT-5.5 Prompts for Legal Professionals: Contract Review, Case Law Research, Compliance, Drafting, and Litigation Support 25 Expert ChatGPT-5.5 Prompts for Legal Professionals: Contract Review, Case Law Research, Compliance, Drafting, and Litigation Support Artificial intelligence has shifted from theoretical…