Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions openspec/changes/2531-a-devops-command-run-from-a/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

## Decisions

- **Catch OSError in _resolve_git_dir at the Path.cwd() call site**: This is the origin of the exception. The function already returns None when no git directory is found, so returning None on a deleted CWD is consistent with its contract. Catching it here protects all callers, not just _detect_vcs_metadata.
- **Catch OSError rather than FileNotFoundError**: FileNotFoundError is a subclass of OSError. Path.cwd() can raise OSError for reasons other than a missing directory, such as a permission error on the getcwd syscall. The existing code in this file already catches OSError in _resolve_git_dir_from_file and _read_packed_refs, so OSError is the established pattern.
- **Return None when the CWD is unavailable**: The function signature is Path | None, and it already returns None when no .git entry is found. A deleted CWD is another case of no git directory found. The caller _detect_vcs_metadata already handles None by returning an empty dict.
- **Return `None` from `_resolve_git_dir` when `Path.cwd()` raises `OSError`.** The function returns `Path | None` and already returns `None` when it finds no `.git` entry. A removed directory is one more case of "no git directory". `_detect_vcs_metadata` already treats `None` as "no attributes". `OSError` is the established pattern in the same file (`_resolve_git_dir_from_file`, `_read_packed_refs`, `_read_ref_file`), and it covers `FileNotFoundError`.
- **Stop a command at the exit seam when `os.getcwd()` raises `FileNotFoundError`.** `OTelTyper.command` wraps every command. The wrapper raises a `DevOpsCLIError` with the message "The working directory does not exist.", and `_report_devops_error` prints it as one line with exit status 1. This is the "one error line" case of the issue. Only `FileNotFoundError` is the case of the issue; another `OSError` of `os.getcwd()` is out of scope and propagates as before.
- **Check in the command wrapper, not in `_report_devops_error`.** `_report_devops_error` also wraps group callbacks, and `devops gh --help` runs the callback of its group. A check there made `devops gh --help` fail in a scratch copy, where it works on `origin/main`.
- **Keep both guards.** The seam covers every command. The guard in `_resolve_git_dir` covers a caller that starts a span outside a command, and meets the first requirement of the issue.

## Rejected alternatives

- **Catch the exception in _detect_vcs_metadata**: This leaves _resolve_git_dir vulnerable for any other caller. The exception would still propagate if any other code calls _resolve_git_dir directly. The fix at the origin is more targeted.
- **Catch the exception in the CLI entry point**: Too broad. It hides the specific cause and makes the telemetry path less testable in isolation. A targeted guard at the call site is simpler and more precise.
- **Catch FileNotFoundError only**: Narrower than needed. A permission error on getcwd would still crash the command. OSError covers all OS-level failures from the getcwd syscall.
- **Raise a custom exception for a deleted CWD**: Adds a new exception type for a case that is semantically identical to no git directory found. The existing None-return contract already covers this. Unnecessary complexity.
- **Guard `_resolve_git_dir` only.** The command then fails at `settings.py:1313` (`_config_layers`, `os.getcwd()`). The scratch run is in the proposal.
- **Guard each `Path.cwd()` and `os.getcwd()` call.** There are 47 calls in `src/` (`git grep -nE "os\.getcwd\(\)|Path\.cwd\(\)" -- src | wc -l`). Each needs its own fallback, and the next new call breaks the rule again.
- **Catch the error in `_detect_vcs_metadata`.** `_resolve_git_dir` would still raise for any other caller.
- **Change to a fallback directory such as the home directory.** Relative paths of the command would then point to a place the person did not choose, and the command would run with a wrong root.
- **A custom exception class for a removed directory.** The message and the status are all the person needs, and `DevOpsCLIError` is raised directly in other places (`src/devops_cli/ai/inspection.py`).
50 changes: 33 additions & 17 deletions openspec/changes/2531-a-devops-command-run-from-a/proposal.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,54 @@

## Why

#2531 reports that a devops command run from a deleted working directory prints a FileNotFoundError traceback from _resolve_git_dir in the telemetry setup. The command does not report a clean error and does not complete. The root cause is that Path.cwd() raises FileNotFoundError when the directory no longer exists, and _resolve_git_dir does not catch it.
Issue #2531: a devops command that runs from a working directory that no longer exists prints a `FileNotFoundError` traceback. A worktree cleanup after a merge can remove the directory of a running shell. The first crash is in `_resolve_git_dir` (`src/devops_cli/telemetry/tracer.py`), which calls `Path.cwd()`. The issue asks that the command run, or stop with one error line, and that `_resolve_git_dir` return `None` for a deleted directory.

A guard in `_resolve_git_dir` alone does not give that. The next crash is in `_config_layers` (`src/devops_cli/config/settings.py`), which calls `os.getcwd()`. The source holds 47 more calls of `Path.cwd()` or `os.getcwd()`. This change guards `_resolve_git_dir`, and it stops a command at the exit seam of `new_typer()` with one error line.

## What Changes

- Wrap the Path.cwd() call in _resolve_git_dir with a try/except OSError guard that returns None on failure.
- Add a test that patches Path.cwd to raise FileNotFoundError and asserts _resolve_git_dir returns None.
- Add a test that confirms _resolve_git_dir still returns the correct .git path for a valid working directory.
- The change fits one pull request.
- `_resolve_git_dir` returns `None` when `Path.cwd()` raises `OSError`. A span then starts with no `vcs.*` attribute.
- A command of a `new_typer()` app checks the working directory before it runs. When the directory is gone, the command prints one error line, exits with status 1 and runs no body. A group that shows its help is not a command and keeps working.
- The paragraph of `ARCHITECTURE.md` on the exit seam names this check.
- The change fits one pull request. It has two task groups.

This change alters what a person observes (a command message and a span), so it carries spec deltas: `command-telemetry` and `command-error-exit`.

## Capabilities

### New Capabilities
### Modified Capabilities

- `command-telemetry`: a span starts without VCS attributes when the working directory is gone, and keeps them when it exists.
- `command-error-exit`: a command run from a deleted working directory stops with one error line.

None.
## Acceptance

### Modified Capabilities
Acceptance criteria of #2531, from the refine block of the issue:

- `command-telemetry`: Deleted CWD returns no git directory, Command completes without traceback from deleted CWD, Normal resolution unaffected
- Deleted CWD returns no git directory: group 1 (a span starts with no `vcs.*` attribute, which needs `_resolve_git_dir` to return `None`).
- Command completes without traceback: group 2 (one error line, status 1, no traceback).
- Normal resolution unaffected: group 1 (a test pins the `vcs.*` attributes of a client inside a git repository).

## Impact

- Code: `src/devops_cli/telemetry/tracer.py`
- Tests: `tests/test_tracer.py`
- Code: `src/devops_cli/telemetry/tracer.py` (`_resolve_git_dir`), `src/devops_cli/core/cli.py` (`OTelTyper.command`).
- Tests: `tests/telemetry/test_telemetry.py`, `tests/commands/test_command_error_exit.py`.
- Documents: `ARCHITECTURE.md` (section 7, the exit seam).
- Existing code the change keeps: `_detect_vcs_metadata` already treats `None` as "no git directory" and returns an empty mapping. `reset_tracer()` clears its cache, which the tests use. `_report_devops_error` prints a `DevOpsCLIError` as one line and exits with its status. The test `test_every_command_app_passes_its_commands_through_the_exit_seam` and the requirements of `command-error-exit` must still pass.

## Feasibility

- The code at src/devops_cli/telemetry/tracer.py line 628 shows current = (start_dir or Path.cwd()).resolve() with no exception handling around Path.cwd(). This confirms the premise of the issue.
- The same file already catches OSError in _resolve_git_dir_from_file (line 618) and _read_packed_refs (line 596), so catching OSError is the established pattern in this module.
- The caller _detect_vcs_metadata (line 646) already handles a None return from _resolve_git_dir by returning an empty dict, so returning None on a deleted CWD is consistent with the existing contract.
- First check: run uv run devops ci test tests/test_tracer.py to confirm the new test passes and existing tests are unaffected.
- Second check: run uv run devops ci test to confirm the full test suite passes with the guard in place.
Every check below ran on `origin/main` (0.37.1) on 2026-11-01, in a worktree of this branch.

- The crash exists. `mkdir /tmp/gone && cd /tmp/gone && rmdir /tmp/gone`, then `.venv/bin/devops gh api rate_limit` ends with `tracer.py:646 in _detect_vcs_metadata`, `tracer.py:630 in _resolve_git_dir`, `pathlib/__init__.py:927 in cwd` and `FileNotFoundError: [Errno 2] No such file or directory`. The line of the issue (628) is now 630.
- The mechanism is as the issue says. `git grep -n "Path.cwd" -- src/devops_cli/telemetry/tracer.py` shows `current = (start_dir or Path.cwd()).resolve()` in `_resolve_git_dir`, with no handler. `_detect_vcs_metadata` runs `if git_dir is not None:`, so `None` gives an empty mapping.
- The guard alone is not enough. A scratch run of the same command with `_resolve_git_dir` wrapped to return `None` on `OSError` still fails: `settings.py:1396 in load_settings`, `settings.py:1313 in _config_layers`, `os.getcwd()`, reached from `run_gh` and `get_github_rate_limiter`. `git grep -nE "os\.getcwd\(\)|Path\.cwd\(\)" -- src | wc -l` prints 47. So a guard at each site is not a bounded change.
- The seam works. With a check of `os.getcwd()` added to `OTelTyper.command` in a scratch copy, `devops gh api rate_limit`, `devops config show` and `devops pr list` from a deleted directory each print `The working directory does not exist.` with exit status 1 and no traceback. `devops --version` and `devops gh --help` still work. A copy that put the check in `_report_devops_error` also broke `devops gh --help`, because the group callback uses that seam. So the check belongs to the command wrapper only.
- The public interface shows the first defect. A scratch script that removes its working directory, calls `reset_tracer()` and starts `OTelTelemetryClient(enabled=True).span("x")` raises `FileNotFoundError` from `Path.cwd()` on `origin/main`. A test through this interface needs no patch of a devops-cli name, as `docs/TESTING.md` requires.
- `_normalize_code_filepath` needs no guard, as the issue says: `git grep -n -A8 "def _normalize_code_filepath" -- src/devops_cli/telemetry/tracer.py` shows its body in `try: ... except Exception: return filepath`.
- Nothing newer did this. `git log origin/main --oneline -i --grep="working directory"` and `--grep="getcwd"` list only #2128 and #2619 (reviews take the workspace from the caller) and the plan #2995. The last change to the exit seam in `src/devops_cli/core/cli.py` is #2502 (eadd55f1). This change extends that seam. The newer commit #2708 is a dashboard change and does not touch the seam. The search of issues for "deleted working directory" finds only #2531 and its plan.
- The test file of the first plan, `tests/test_tracer.py`, does not exist on `origin/main`. The tracer tests sit in `tests/telemetry/test_telemetry.py`. The seam tests sit in `tests/commands/test_command_error_exit.py`.

## Existing Tool Considered

No external tool or library covers this need. The fix is a try/except OSError block of about 4 lines around the Path.cwd() call in _resolve_git_dir (src/devops_cli/telemetry/tracer.py:628). The written cost is one guard block, one test case, and the maintenance of that guard for the lifetime of the function. No internal code is deleted.
The standard library covers the need: `os.getcwd()` raises `FileNotFoundError` for a removed directory, and the change catches it. No external tool or library does more. The written cost is two short guards (about 10 lines), three tests, one paragraph of `ARCHITECTURE.md`, and the upkeep of the check in `OTelTyper.command`. The change deletes no internal code.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
## ADDED Requirements

### Requirement: A command run from a deleted working directory stops with one error line
When a command registered on a `new_typer()` app starts and the working directory of the process no longer exists, the command SHALL print one error line that says the working directory does not exist, SHALL exit with status 1, and SHALL print no traceback. The command body SHALL not run. A command group that shows its help SHALL still print the help.

#### Scenario: A command starts after its working directory was removed
- **WHEN** the working directory of the process is removed and a person runs a command of a `new_typer()` app
- **THEN** the command exits with status 1, prints one line that says the working directory does not exist, prints no traceback, and does not run its body

#### Scenario: A command group shows its help
- **WHEN** the working directory of the process is removed and a person runs `devops gh --help`
- **THEN** the command prints the help of the group and exits with status 0
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
## ADDED Requirements

### Requirement: Deleted CWD returns no git directory
_resolve_git_dir SHALL return None when Path.cwd() raises OSError because the working directory no longer exists.
### Requirement: A span starts without VCS attributes when the working directory is gone
The telemetry client SHALL start a span, with no `vcs.*` attribute and no exception, when the working directory of the process no longer exists. When the working directory exists and lies inside a git repository, the span SHALL hold the branch and the revision of that repository in its `vcs.*` attributes.

#### Scenario: CWD deleted before call
- **WHEN** Path.cwd() raises FileNotFoundError because the process working directory was removed
- **THEN** _resolve_git_dir returns None and no exception propagates to the caller
#### Scenario: The working directory was removed
- **WHEN** the working directory of the process is removed and a client starts a span
- **THEN** the span starts and holds no `vcs.ref.name`, `vcs.branch`, `vcs.revision_id` and `vcs.commit` attribute

### Requirement: Command completes without traceback from deleted CWD
A devops command run from a deleted working directory SHALL complete without an unhandled FileNotFoundError traceback from the telemetry setup.

#### Scenario: gh api from deleted directory
- **WHEN** a devops gh api command runs after its working directory has been deleted
- **THEN** the command exits with a clean result or a single error line, not a traceback

### Requirement: Normal resolution unaffected
_resolve_git_dir SHALL return the correct git directory when the working directory exists and contains a .git entry.

#### Scenario: CWD inside a git repository
- **WHEN** the process working directory exists and is inside a git repository
- **THEN** _resolve_git_dir returns the path to the .git directory
#### Scenario: The working directory is inside a git repository
- **WHEN** the working directory holds a `.git` directory whose `HEAD` names a branch and whose branch file holds a revision, and a client starts a span
- **THEN** the span holds that branch in `vcs.ref.name` and `vcs.branch`, and that revision in `vcs.revision_id` and `vcs.commit`
Loading
Loading