Skip to content

[Windows][Codex App] Non-forced cleanup of verified empty worktree directory blocked by policy #43732

Open

Description

@MaxFabian25

Environment

  • Codex Desktop Windows package: OpenAI.Codex 26.901.6511.0 (verified with Get-AppxPackage; About dialog not inspected).
  • Windows build: 10.0.26200.0; PowerShell 7.6.
  • Separately installed Codex CLI: 0.153.4; not assumed to be the app's bundled version.
  • Session: full filesystem access (danger-full-access), approval policy never.
  • Subscription: not included.

Issue

Automatic command review rejected explicitly requested post-merge cleanup with only blocked by policy. The rejected PowerShell commands used Remove-Item -LiteralPath ... -ErrorAction Stop without -Force.

Two observed cases:

  1. Git worktree removal removed the checkout contents and deregistered the worktree, but Windows denied removal of the empty top-level directory. A separate read-only check confirmed that directory had zero entries. An exact-path, non-recursive, non-forced Remove-Item recovery command was then blocked by automatic review.
  2. Cleanup of two individually enumerated HTML reports created by the agent in the user's temporary directory was separately blocked. The paths and file details had been checked. This command also used no force option.

The agent stopped after the policy denials. No alternative deletion API or force flag was used to bypass them. Ordinary branch deletion and Git pruning succeeded, and other authorized cleanup had succeeded earlier.

Steps / reproduction shape

Observed during one real cleanup session; a standalone deterministic reproduction has not been established. The following is a sanitized equivalent of the empty-directory operation, not an exact transcript:

$cleanupTarget = 'C:\example\retired-worktree'
$resolvedTarget = (Resolve-Path -LiteralPath $cleanupTarget -ErrorAction Stop).Path
if ($resolvedTarget -ne 'C:\example\retired-worktree') { throw 'Unexpected target' }
if (@(Get-ChildItem -LiteralPath $resolvedTarget -Force -ErrorAction Stop).Count -ne 0) { throw 'Directory is not empty' }
Remove-Item -LiteralPath $resolvedTarget -ErrorAction Stop

-Force above is only on the read-only directory listing so hidden entries are counted; it is not on deletion. The empty-directory operation does not need recursive deletion.

Expected behavior

Permit a narrowly scoped, user-authorized cleanup when policy allows it. Otherwise, explain which policy condition caused the denial and provide a supported resolution. A generic denial makes it impossible to distinguish a legitimate restriction from a false positive. Recovery should not require force, alternate deletion APIs, or weaker safety settings.

Related reports / scope

Related to #38886 and #34331. This report supplies evidence on app package 26.901.6511.0 that removal can be rejected even without a force flag, including an already empty, deregistered worktree directory. The example in #38886 uses forced deletion.

The observed denial is verified; the underlying policy rule and root cause are unknown. A custom no-force hook was installed only AFTER these failures, so that new hook did not cause them. No private repository identifiers, actual local paths, workbook contents, credentials, or raw session logs are included.

Activity

  1. added
    bug
    app
    windows-os
    sandbox
    on Sep 8, 2026
  2. MilyOAA commented on Sep 10, 2026

    @MilyOAA

    Additional occurrence and source-level diagnosis: PowerShell force-delete false positive

    We observed a related independent occurrence on Windows with desktop package OpenAI.Codex 26.901.6511.0 and bundled codex-cli 0.153.4, with unrestricted filesystem access and approval policy never. The larger compound PowerShell script was rejected before execution with blocked by policy, although neither deletion command used -Force; that flag belonged to a separate Get-ChildItem listing.

    This adds source-level evidence for the deletion/listing association described in this issue. It does not establish the internal decision path of the original reporter’s incident or directly instrument the production binary.

    Minimal classifier input

    This JSON contains command text for a classifier-only test. Do not execute the contained script; all paths are placeholders.

    {
      "argv": [
        "pwsh.exe",
        "-Command",
        "$probe = 'classification-only';\nRemove-Item -LiteralPath 'C:\\placeholder\\temporary.txt'\nGet-ChildItem -LiteralPath 'C:\\placeholder' -Force"
      ]
    }

    Expected: the forced-deletion predicate returns false. The deletion has only -LiteralPath; the directory listing owns -Force.

    Observed in an offline Python port of the published release predicate using POSIX shlex: true. The minimal input has not been submitted to the live Codex executor or tested directly in Rust. The real larger script was refused by the installed runner. PowerShell’s native parser reported zero syntax errors in that original script and confirmed that both deletion commands had only LiteralPath, while the listing had LiteralPath and Force.

    Source trace

    Release: rust-v0.153.4, commit 3d2ee51ca2d5db578f328aa75e20aa22c0197c9a.

    For the archived original command, the offline predicate matched a segment incorrectly combining the deletion and the later listing flag. Removing only the listing flag in an in-memory comparison made the classification false; each relevant command classified individually was also false. These comparisons only classified strings and did not execute the denied operation.

    Requested correction and regression coverage

    Preserve PowerShell command boundaries and associate flags with the command that owns them, while retaining real forced-deletion detection. A simple newline split needs care around quoted strings, here-strings, continuations, blocks and nested expressions.

    Classifier-only case Expected forced-deletion result
    Minimal input above false
    Actual Remove-Item ... -Force true
    Get-ChildItem ... -Force alone false
    Genuine forced deletion inside compound control flow true

    The first three cases were checked in the offline port: the first incorrectly returned true; the two controls returned true and false as expected. The fourth is proposed coverage, not a completed test.

    Related: #40060 discusses cross-command association in URL-launch detection; this occurrence concerns the separate forced-deletion predicate.

    No denied operation was retried, and no security setting or installed Codex binary was changed. This report contains placeholder paths and public source references, without private project files, credentials, raw logs or session transcripts.

  3. MatthewLukePublishing commented on Sep 10, 2026

    @MatthewLukePublishing

    Compiled Rust reproduction and further-back source trace

    Adding compiled evidence to the source diagnosis above. The same classifier is still present in the latest release checked today (2026-09-10), rust-v0.154.0: its windows_dangerous_commands.rs is text-identical to the pinned 0.153.4 baseline.

    Minimal classifier-only regression (the script is an input string, never executed):

    let argv = [
        "pwsh",
        "-Command",
        "$x='test'\nGet-ChildItem -Force\nRemove-Item -LiteralPath $x",
    ].map(str::to_string);
    
    assert!(!is_dangerous_command_windows(&argv));

    The unmodified Windows classifier incorrectly returns true. Native PowerShell's AST attributes -Force only to Get-ChildItem, not Remove-Item.

    Validation against the actual Rust module, pinned to release commit 3d2ee51ca2d5db578f328aa75e20aa22c0197c9a:

    • Original module: 40 existing tests passed; two added regressions failed as expected (the minimal multiline case and a sanitized cleanup-shaped case).
    • Local candidate correction: 48 Rust tests passed, none skipped.
    • Independent native PowerShell 7.6.5 AST checks: 23 cases passed, zero input scripts executed.

    These are compiled-module results, not a Python port. The focused harness used Rust 1.95.0 and matching direct classifier dependencies, with its own transitive lockfile. The complete upstream crate and policy integration suite were not built or tested; this is not a production per-call decision trace.

    Provenance: 3bdcbc7 / #7111 introduced POSIX shlex parsing of PowerShell scripts on 2025-11-21. 80f8018 / #8590 added forced-deletion detection over those flattened tokens on 2026-01-20, introducing this demonstrated false positive. Its unrelated-Force regression used semicolons, not the equivalent newline-separated input.

    The immediate chain is PowerShell wrapper tokenization discarding newlines, then the deletion detector associating unrelated tokens. Core's fallback turns that classification into a hard rejection when effective approval mode is Never.

    The candidate approach preserves parser-proven inter-command boundaries using the existing PowerShell grammar, without splitting continued commands, literals, or comments. Genuine forced-deletion checks remain required; uncertain syntax keeps conservative handling.

    Following the current contributing policy, this is additional reproduction/root-cause evidence rather than an external PR. Could maintainers add the newline regression and integrate a boundary-aware correction through a supported runtime release? No installed runtime, permission rules, or approval settings were modified, and the rejected cleanup was not retried.

  4. dicky0727-lab commented on Sep 20, 2026

    @dicky0727-lab

    Additional Windows occurrence: Get-Item -Force associated with a separate non-forced Remove-Item

    Additional occurrence and classifier-only evidence for this issue, collected on 2026-09-20.

    Summary

    An explicitly authorized, guarded deletion of one obsolete local SQLite file was rejected before PowerShell started, with only blocked by policy. The deletion used neither -Force nor -Recurse. Two preceding read-only Get-Item commands used -Force to inspect file and ancestor attributes.

    The preserved command, native PowerShell AST, an offline classifier model, and the public source strongly support the same cross-command force-flag false positive described in #43732. The exact installed binary's per-call policy decision has not been recovered, so this is not a claim of instrumented production-root-cause confirmation.

    Environment and observed failure

    • Incident: 2026-09-20 05:52:17 UTC / 13:52:17 UTC+08:00.
    • Installed Windows Desktop package observed during diagnosis: OpenAI.Codex 26.915.4065.0 (Get-AppxPackage; About dialog not inspected).
    • Active Desktop backend: codex-cli 0.155.0-alpha.9.2, queried from the executable used by the incident process. A different CLI on PATH was not used for the policy check.
    • Windows: Microsoft Windows NT 10.0.26200.0; native PowerShell 7.6.5 observed during diagnosis.
    • The incident-time backend log confirms DangerFullAccess and approval policy Never.
    • Tool path: functions.exec calling exec_command, using the native PowerShell shell.

    Abridged error shape, with private command/path text omitted:

    CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
    

    There was no native PowerShell execution result or Windows filesystem denial. The file was not deleted. No rejected operation was retried, no alternative deletion channel was used, and no permission/rule settings were changed.

    Evidence from the original command

    The original script checked the exact target against an allowed workspace path, checked ancestors and the target for reparse points, checked that the obsolete queue held no extraction results, and verified file size and SHA-256 before the single-file deletion.

    Native PowerShell Parser.ParseInput inspected the script without executing it and reported zero syntax errors:

    Command Original line Parameters
    Get-Item 9 Force, LiteralPath
    Get-Item 11 Force, LiteralPath
    Remove-Item 14 LiteralPath, ErrorAction

    The installed backend's execpolicy check, applied to the original invocation with the inspected user default.rules, returned matchedRules: []. This checks that rule file, not all runtime heuristics or managed policy layers.

    Classifier-only reproduction

    The following is input text for a classifier, not a script to execute:

    $x='classification-only'
    Get-Item -Force -LiteralPath $x
    Remove-Item -LiteralPath $x -ErrorAction Stop

    Expected force-delete predicate: false, because only the inspection owns -Force.

    Observed in the Python model included below: true. The original private script also matches. Removing only the Get-Item force flags in an in-memory text comparison changes that model result to false; the modified script was never submitted for execution.

    02_classifier_only.py performs string classification only and prints the five synthetic cases below. It uses Python POSIX shlex as a model of Rust shlex, so it is not a compiled-Rust or installed-runtime test. 03_evidence.json contains the observed results and a sanitized original-script summary.

    Classifier input Expected force-delete Python model
    Newline-separated inspection and non-forced deletion above false true
    Get-Item -Force alone false false
    Non-forced Remove-Item alone false false
    Actual Remove-Item -Force true true
    Explicit command-boundary control false false

    The last case is a classifier regression control, not a proposed runtime workaround.

    Source-level explanation

    Source inspected at public commit 5c5308fc9a9ee789049d646ef11e5400384b9c6f:

    1. The literal PowerShell lowerer does not accept assignment/control-flow forms used in the guarded script. Exec policy falls back to the wrapper when literal lowering is unavailable.
    2. The Windows fallback uses shlex_split(script), consuming unquoted newlines.
    3. has_force_delete_cmdlet reconstructs segments from those tokens and checks for any delete atom together with any force atom in the same reconstructed segment. The original script's inspection and deletion land together in the offline model.
    4. The unmatched-command decision maps a dangerous match to Forbidden when approval policy is Never. The Windows match becomes Other, rendered as generic blocked by policy.

    The Windows classifier file fetched at this commit is text-identical to release baseline 3d2ee51ca2d5db578f328aa75e20aa22c0197c9a, sharing Git blob SHA cc1ae671c831130dd33d11bac690d3052430b6dd.

    The earlier compiled-Rust reproduction in this issue reports the equivalent newline/inspection-Force failure against that baseline. Those Rust results are attributed to the earlier reporter; they were not rerun here. This source comparison does not independently establish the exact source commit embedded in our alpha backend.

    Request to maintainers

    Please correlate this newer-backend occurrence with #43732 and confirm whether the incident hit this forced-deletion fallback. Preserve PowerShell command ownership and boundaries so a read-only inspection's flags cannot be attached to deletion, while retaining protection for genuinely forced deletion and uncertain syntax.

    Please also expose the specific matched heuristic and the reason approval cannot be requested, instead of reducing all Windows matches to Other / blocked by policy.

    This report requests a supported classifier/diagnostics correction, not weaker enforcement or a way around a rejected action. The supporting files below contain no customer files, private paths, credentials, raw logs, or full session transcripts. Correlation identifiers remain in the local diagnostic record and can be supplied privately if needed.

    Inline supporting files

    These contain the same classifier code and diagnostic measurements prepared locally; no PowerShell input is executed by the Python program.

    02_classifier_only.py — offline string classifier
    """Offline classifier regression: treat all PowerShell as data; never execute it.
    
    This is a Python model of the force-delete fallback in OpenAI's public source,
    not a test of the installed Codex executable or Rust shlex itself.
    Reference commit: 5c5308fc9a9ee789049d646ef11e5400384b9c6f
    codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs
    Functions: parse_powershell_invocation and has_force_delete_cmdlet.
    Python shlex approximates the source's Rust shlex tokenization.
    No subprocess, eval, filesystem deletion, or permission modification is used.
    """
    
    import json
    import re
    import shlex
    
    
    def force_delete_fallback(script):
        words = [t.strip("'").strip('"').lower()
                 for t in shlex.split(script, comments=True, posix=True)]
        segments = [[]]
        for word in words:
            current = ''
            for char in word:
                if char in ';|&\n\r\t':
                    if current.strip():
                        segments[-1].append(current.strip())
                    current = ''
                    if segments[-1]:
                        segments.append([])
                else:
                    current += char
            if current.strip():
                segments[-1].append(current.strip())
        hits = []
        for number, segment in enumerate(segments):
            atoms = [part.strip() for word in segment
                     for part in re.split(r'[{}()\[\],;]', word) if part.strip()]
            deletes = [part for part in atoms if part in
                       ('remove-item', 'ri', 'rm', 'del', 'erase', 'rd', 'rmdir')]
            forces = [part for part in atoms
                      if part == '-force' or part.startswith('-force:')]
            if deletes and forces:
                hits.append({'segment': number, 'delete_atoms': deletes,
                             'force_atoms': forces})
        return bool(hits), hits
    
    
    def synthetic_cases():
        # These strings are classifier inputs, not executable test commands.
        return [
            ('newline_separated_inspect_then_delete', False,
             "$x='classification-only'\nGet-Item -Force -LiteralPath $x\n"
             'Remove-Item -LiteralPath $x -ErrorAction Stop'),
            ('inspection_only', False, 'Get-Item -Force -LiteralPath $x'),
            ('non_forced_deletion_only', False,
             'Remove-Item -LiteralPath $x -ErrorAction Stop'),
            ('actual_forced_deletion', True,
             'Remove-Item -Force -LiteralPath $x'),
            ('explicit_boundary_classifier_control', False,
             "$x='classification-only'; Get-Item -Force -LiteralPath $x; "
             'Remove-Item -LiteralPath $x -ErrorAction Stop'),
        ]
    
    
    def main():
        cases = []
        for name, expected, script in synthetic_cases():
            actual, hits = force_delete_fallback(script)
            cases.append({'name': name, 'script_is_data_only': script,
                          'semantic_expected_force_delete': expected,
                          'simulated_force_delete_match': actual,
                          'matches_semantic_expectation': actual == expected,
                          'matched_segments': hits})
        print(json.dumps({
            'mode': 'classifier-only; zero PowerShell inputs executed',
            'scope': 'Python port, not installed Codex or compiled Rust verification',
            'source_commit': '5c5308fc9a9ee789049d646ef11e5400384b9c6f',
            'cases': cases,
        }, ensure_ascii=False, indent=2))
    
    
    if __name__ == '__main__':
        main()
    03_evidence.json — sanitized measurements
    {
      "mode": "classifier-only; zero PowerShell inputs executed",
      "scope": "Python port, not installed Codex or compiled Rust verification",
      "source_commit": "5c5308fc9a9ee789049d646ef11e5400384b9c6f",
      "cases": [
        {
          "name": "newline_separated_inspect_then_delete",
          "script_is_data_only": "$x='classification-only'\nGet-Item -Force -LiteralPath $x\nRemove-Item -LiteralPath $x -ErrorAction Stop",
          "semantic_expected_force_delete": false,
          "simulated_force_delete_match": true,
          "matches_semantic_expectation": false,
          "matched_segments": [
            {
              "segment": 0,
              "delete_atoms": [
                "remove-item"
              ],
              "force_atoms": [
                "-force"
              ]
            }
          ]
        },
        {
          "name": "inspection_only",
          "script_is_data_only": "Get-Item -Force -LiteralPath $x",
          "semantic_expected_force_delete": false,
          "simulated_force_delete_match": false,
          "matches_semantic_expectation": true,
          "matched_segments": []
        },
        {
          "name": "non_forced_deletion_only",
          "script_is_data_only": "Remove-Item -LiteralPath $x -ErrorAction Stop",
          "semantic_expected_force_delete": false,
          "simulated_force_delete_match": false,
          "matches_semantic_expectation": true,
          "matched_segments": []
        },
        {
          "name": "actual_forced_deletion",
          "script_is_data_only": "Remove-Item -Force -LiteralPath $x",
          "semantic_expected_force_delete": true,
          "simulated_force_delete_match": true,
          "matches_semantic_expectation": true,
          "matched_segments": [
            {
              "segment": 0,
              "delete_atoms": [
                "remove-item"
              ],
              "force_atoms": [
                "-force"
              ]
            }
          ]
        },
        {
          "name": "explicit_boundary_classifier_control",
          "script_is_data_only": "$x='classification-only'; Get-Item -Force -LiteralPath $x; Remove-Item -LiteralPath $x -ErrorAction Stop",
          "semantic_expected_force_delete": false,
          "simulated_force_delete_match": false,
          "matches_semantic_expectation": true,
          "matched_segments": []
        }
      ],
      "prepared_at": "2026-09-20T16:46:43.035516+08:00",
      "incident_local": "2026-09-20T13:52:17+08:00",
      "incident_utc": "2026-09-20T05:52:17Z",
      "environment": {
        "desktop_package_observed_during_diagnosis": "26.915.4065.0",
        "active_backend_version": "0.155.0-alpha.9.2",
        "windows": "Microsoft Windows NT 10.0.26200.0",
        "powershell_observed_during_diagnosis": "7.6.5",
        "incident_access": "DangerFullAccess",
        "incident_approval_policy": "Never"
      },
      "native_powershell_parse": {
        "input_executed": false,
        "parse_error_count": 0,
        "relevant_commands": [
          {
            "name": "Get-Item",
            "line": 9,
            "parameters": [
              "Force",
              "LiteralPath"
            ]
          },
          {
            "name": "Get-Item",
            "line": 11,
            "parameters": [
              "Force",
              "LiteralPath"
            ]
          },
          {
            "name": "Remove-Item",
            "line": 14,
            "parameters": [
              "LiteralPath",
              "ErrorAction"
            ]
          }
        ]
      },
      "original_script_offline_model": {
        "input_executed": false,
        "force_delete_match": true,
        "matched_segments": [
          {
            "segment": 2,
            "delete_atoms": [
              "remove-item"
            ],
            "force_atoms": [
              "-force"
            ]
          }
        ],
        "private_command_text_omitted": true
      },
      "original_script_in_memory_classifier_control": {
        "change": "remove Force only from Get-Item text; never submit modified command",
        "input_executed": false,
        "force_delete_match": false
      },
      "user_rules_only_check": {
        "tool": "packaged codex execpolicy check",
        "exit_code": 0,
        "matchedRules": [],
        "not_runtime_heuristic_verification": true
      },
      "source_comparison": {
        "path": "codex-rs/shell-command/src/command_safety/windows_dangerous_commands.rs",
        "current_commit": "5c5308fc9a9ee789049d646ef11e5400384b9c6f",
        "release_baseline_commit": "3d2ee51ca2d5db578f328aa75e20aa22c0197c9a",
        "shared_git_blob_sha": "cc1ae671c831130dd33d11bac690d3052430b6dd",
        "text_identical": true,
        "exact_installed_binary_source_commit_not_verified": true
      },
      "limits": [
        "No live executor reproduction or deletion retry",
        "No local Rust toolchain was available; upstream compiled results are attributed, not rerun",
        "No security settings or installed binaries modified"
      ]
    }
  5. charonwang commented on Sep 28, 2026

    @charonwang

    Additional executed reproduction on 2026-09-28: newly created empty directory inside the workspace

    Adding a fresh occurrence rather than opening a duplicate. This reproduces the non-forced empty-directory case on a newer Windows desktop build, without involving a retired worktree or user-owned assets.

    Environment

    • Desktop runtime log reports release 26.924.22138 (not collected from the About dialog; bundled CLI version not established).
    • Windows 10.0.26200.0, PowerShell 7.6.6.
    • Effective task settings: sandbox_policy.type = danger-full-access, approval_policy = never, permission profile disabled.
    • The user explicitly authorized a disposable cleanup reproduction within the active repository, and subsequently explicitly requested deletion of those test artifacts.

    Observed sequence

    1. A new, uniquely named directory under the repository's .scratch/ was created successfully, containing a newly created empty subdirectory and unrelated task-owned control artifacts. The path was checked for pre-existence before creation.
    2. A separate exec_command call submitted the following compound PowerShell script. Paths and the diagnostic marker are anonymized; the command structure is preserved. The deletion itself has neither -Force nor -Recurse. The -Force flags are on read-only inspection commands.
    # disposable cleanup probe
    $probeRoot='D:\example\repository\.scratch\delete-probe'
    $target=Join-Path $probeRoot 'empty'
    $item=Get-Item -LiteralPath $target -Force
    if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Not an ordinary directory' }
    if (@(Get-ChildItem -LiteralPath $target -Force).Count -ne 0) { throw 'Not empty' }
    Remove-Item -LiteralPath $target
    [pscustomobject]@{case='single-empty';removed=(-not (Test-Path -LiteralPath $target));traceEvents=@(Get-Content -LiteralPath "$probeRoot\hook-trace.jsonl").Count} | ConvertTo-Json
    1. The tool returned before process execution (reported wall time 0.5 seconds):
    exec_command failed: CreateProcess { message: "Rejected(... rejected: blocked by policy)" }
    
    1. A subsequent read-only call succeeded and confirmed that the target directory still existed and contained zero entries.
    2. After the user's separate explicit cleanup request, a guarded Remove-Item -LiteralPath <exact-test-root> -Recurse call, also without a deletion -Force flag, received the same rejection. Inspection in that compound script again used -Force. No alternate deletion API or security-setting change was used; the test artifacts were left in place.

    Custom-hook control and limits

    A temporary trace in an existing custom PreToolUse hook matched only this probe's unique marker and recorded event metadata, without changing decisions. A direct Node invocation of the hook produced one trace entry. Neither the actual marked deletion call nor the marked follow-up read-only call added another entry. The trace was removed afterward. This supports that the configured custom hook did not issue this rejection; it does not identify the internal rejecting predicate or establish general hook coverage.

    The inspection/deletion combination is consistent with the cross-command -Force association discussed above, but the exact installed backend's classifier has not been instrumented or mapped to a source commit. Please retain this as executed symptom evidence, not proof of that internal cause.

    Please expose the rejecting predicate and a supported review/recovery path, and test that inspection flags do not become deletion flags across PowerShell statement boundaries. No private paths, account details, task IDs, credentials, or raw session logs are included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    appbugsandboxwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions