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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-25
skip_specs: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Design

## Context

See `proposal.md` for problem motivation and scope.

Git commands emit listings in human format by default. Human format C-quotes characters outside 7-bit US-ASCII and whitespace characters. It prints renames as `old -> new`.

Several modules parse these listings with line splitting and quote stripping. This causes path corruption, loss of leading characters, and silent drops.

## Goals / Non-Goals

**Goals:**
- Read git path listings with `-z` across `argo/gitops.py`, `core/repo.py`, `commands/test_cmd.py`, `roadmap/refine.py`, and `core/cleanup.py`.
- Correctly parse rename records in `git status --porcelain=v1 -z`.
- Resolve relative porcelain status paths against the repository root.
- Add tests in temporary git repositories verifying paths with spaces, non-ASCII characters, leading spaces, and renames.

**Non-Goals:**
- Change git commit, branch, or tag management.
- Modify release or PR commands that were already cleaned in #1952.
- Introduce external git wrapper libraries.

## Decisions

### 1. Tokenize `git status --porcelain=v1 -z` with two-path rename handling

In `argo/gitops.py`, run `git status --porcelain=v1 -z`. Split the output by `\0`.

When the two-letter status code contains `R` or `C`, git emits the new path followed by the old path as a separate null-terminated token. The parser consumes the original path token to keep synchronization with subsequent entries.

*Rejected Alternative*: Parse line-oriented `git status --porcelain` with regex unquoting.
*Evidence*: C-style unquoting does not reliably distinguish between literal escape characters and escaped octal bytes (such as `\303\251`). It also corrupts paths that contain ` -> `.

### 2. Resolve porcelain status paths against the repository root

`git status` outputs paths relative to the repository root. `inspect_git_manifest_drift` resolves relative paths using `(repo_root / rel_path).resolve()`.

*Rejected Alternative*: Resolve paths against `Path.cwd()`.
*Evidence*: When the process working directory is not the repository root, `Path(rel_path).resolve()` targets the wrong directory on disk.

### 3. Parse `git ls-files` and `git diff` with `-z`

In `core/repo.py` and `commands/test_cmd.py`, append `-z` to `ls-files` and `diff --name-only`. Split output on `\0`.

*Rejected Alternative*: Set `git config core.quotePath false`.
*Evidence*: Modifying git configuration alters persistent repository or global state, violating AGENTS.md rule 12.

### 4. Parse `git worktree list --porcelain -z`

In `core/cleanup.py`, run `git worktree list --porcelain -z` and split on `\0`. Extract records starting with `worktree `.

*Rejected Alternative*: Split on newline characters without `-z`.
*Evidence*: Worktree paths with spaces or unusual characters get misparsed or stripped.

## Risks / Trade-offs

- [Risk] Null-separated parsing can produce an empty string at the end of the split list.
→ Mitigation: Filter out empty tokens when splitting by `\0`.
- [Risk] Renamed manifests might leave the old file in persistent caches.
→ Mitigation: For renames, the new path is tracked as modified/created, and the old path is consumed so subsequent entries parse cleanly.
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Proposal

## Why

Issue #1440: several modules parse git command outputs in human format. Git C-quotes paths with non-ASCII or special characters, formats renames as `old -> new`, and translates strings.

- In `src/devops_cli/argo/gitops.py`, `inspect_git_manifest_drift` strips the output before splitting it. This removes the leading space from a first ` M` status line. The parser then drops the first character of the path. A rename leaves ` -> ` in the path. Non-ASCII paths contain C-escape sequences. The function also resolves paths against the current working directory instead of the repository root.
- In `src/devops_cli/core/repo.py`, `_list_git_tracked_files` runs `git ls-files` without `-z`. C-quoted files such as `"caf\303\251.py"` fail the `is_file()` check and drop out of file lists.
- In `src/devops_cli/commands/test_cmd.py`, `_changed_paths` splits output lines by hand and strips quotes.
- In `src/devops_cli/roadmap/refine.py`, `_collect_repo_map` and `collect_context` read `git ls-tree` without `-z`. C-quoted ADR paths fail later reads.
- In `src/devops_cli/core/cleanup.py`, `_listed_worktrees` reads `git worktree list --porcelain` without `-z`.

## What Changes

- Update `inspect_git_manifest_drift` in `src/devops_cli/argo/gitops.py` to run `git status --porcelain=v1 -z`. Parse entries terminated by null bytes. Handle the original path field for renames. Resolve paths against the repository root.
- Update `_list_git_tracked_files` in `src/devops_cli/core/repo.py` to run `git ls-files -z` and split on null bytes.
- Update `_changed_paths` in `src/devops_cli/commands/test_cmd.py` to run `git diff --name-only -z` and `git status --porcelain=v1 -z`, splitting on null bytes.
- Update `_collect_repo_map` and `collect_context` in `src/devops_cli/roadmap/refine.py` to run `git ls-tree -r -z --name-only` and split on null bytes.
- Update `_listed_worktrees` in `src/devops_cli/core/cleanup.py` to run `git worktree list --porcelain -z` and split on null bytes.
- This change alters no CLI commands, options, messages, manifests, or service behavior. It fixes internal git command parsing.
- The change sets `skip_specs: true` in `.openspec.yaml`.
- This change fits in one pull request.

## Capabilities

### New Capabilities

None.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/argo/gitops.py`: `inspect_git_manifest_drift` and `_parse_drift_event`.
- `src/devops_cli/core/repo.py`: `_list_git_tracked_files`.
- `src/devops_cli/commands/test_cmd.py`: `_changed_paths` and `_porcelain_path`.
- `src/devops_cli/roadmap/refine.py`: `_git`, `_collect_repo_map`, and `collect_context`.
- `src/devops_cli/core/cleanup.py`: `_listed_worktrees`.
- `tests/test_argo_gitops.py`: unit tests for drift parsing with real git repository.
- `tests/test_repos.py`: unit tests for `list_repo_files` with non-ASCII and spaced paths.
- `tests/test_test_cmd.py`: unit tests for `_changed_paths` with non-ASCII, spaces, and renames.
- `tests/roadmap/test_refine.py`: unit tests for `collect_context` with non-ASCII and spaced ADR paths.
- `tests/core/test_cleanup_fuzzing.py`: update worktree list test to use null-separated output.

## Feasibility

- Git version 2.55.0 on Linux confirms the null-separated formats:
- `git status --porcelain=v1 -z` separates entries with null bytes. Renames supply the new path followed by the old path as a separate field. Paths with spaces or non-ASCII characters remain unquoted. Unstaged modifications retain the leading space (for example, ` M`).
- `git ls-files -z` provides raw unquoted paths separated by null bytes.
- `git diff --name-only -z` provides raw unquoted paths separated by null bytes.
- `git ls-tree -r -z --name-only` provides raw unquoted paths separated by null bytes.
- `git worktree list --porcelain -z` separates all records and attributes with null bytes.
- Python tests in temporary git repositories reproduced each defect:
- `argo/gitops.py`: `k8s/app.yaml` with status ` M` lost the leading character when the output was stripped.
- `core/repo.py`: `café.py` was listed with C-escapes (`"caf\303\251.py"`) and omitted from results.
- `commands/test_cmd.py`: quoted paths with spaces or non-ASCII characters were corrupted.
- `roadmap/refine.py`: `docs/adr/0001-café.md` was quoted and could not be read.
- `core/cleanup.py`: worktrees with spaces or non-ASCII characters were split on newlines.

## Existing Tool Considered

Git CLI with the `-z` option and Python standard library string methods (`str.split("\0")`) cover the need. The codebase already uses `-z` in `git/operations.py`, `git/worktree_inventory.py`, and `core/cleanup.py`. No new library or custom string parser is necessary.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Tasks

## 1. Drift Events and Repository Files

- [x] 1.1 Write failing tests in `tests/test_argo_gitops.py` and `tests/test_repos.py` for `inspect_git_manifest_drift` and `list_repo_files` in a real git repository with ` M` status, paths with spaces, non-ASCII paths, and renames. Verify with `uv run devops ci test tests/test_argo_gitops.py tests/test_repos.py`.
- [x] 1.2 Update `inspect_git_manifest_drift` in `src/devops_cli/argo/gitops.py` to use `git status --porcelain=v1 -z`, consume rename fields, and resolve paths relative to the repository root. Verify with `uv run devops ci test tests/test_argo_gitops.py tests/argo/test_gitops_fuzzing.py`.
- [x] 1.3 Update `_list_git_tracked_files` in `src/devops_cli/core/repo.py` to use `git ls-files -z` and split on null bytes. Verify with `uv run devops ci test tests/test_repos.py`.
- [x] 1.4 Regenerate documentation with `uv run devops docs generate --sync-readme`.

## 2. Test Selection, Refinement Context, and Worktree List

- [x] 2.1 Write failing tests in `tests/test_test_cmd.py` and `tests/roadmap/test_refine.py` for test selection and refinement context with paths containing spaces, non-ASCII characters, and renames. Verify with `uv run devops ci test tests/test_test_cmd.py tests/roadmap/test_refine.py`.
- [x] 2.2 Update `_changed_paths` and `_porcelain_path` in `src/devops_cli/commands/test_cmd.py` to run `git diff --name-only -z` and `git status --porcelain=v1 -z`. Verify with `uv run devops ci test tests/test_test_cmd.py`.
- [x] 2.3 Update `_git`, `_collect_repo_map`, and `collect_context` in `src/devops_cli/roadmap/refine.py` to run `git ls-tree -r -z --name-only`. Verify with `uv run devops ci test tests/roadmap/test_refine.py`.
- [x] 2.4 Update `_listed_worktrees` in `src/devops_cli/core/cleanup.py` to run `git worktree list --porcelain -z` and update `tests/core/test_cleanup_fuzzing.py` for null-separated output. Verify with `uv run devops ci test tests/core/test_cleanup_fuzzing.py`.
- [x] 2.5 Regenerate documentation with `uv run devops docs generate --sync-readme`.


## 3. Verification

- [x] 3.1 Run full CI checks. Verify with `uv run devops ci`.


## Workflow follow-up

- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`).
47 changes: 40 additions & 7 deletions src/devops_cli/argo/gitops.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from typing import TYPE_CHECKING, Literal

from devops_cli.argo.sync import build_sync_request_body
from devops_cli.config.constants import CONST_GIT_NAME_STATUS_TWO_PATH_LETTERS
from devops_cli.config.defaults import DEFAULT_HTTP_TIMEOUT_SECONDS
from devops_cli.config.settings import get_argocd_token, load_settings
from devops_cli.core.paths import validate_no_path_traversal
from devops_cli.core.process import run_subprocess
from devops_cli.core.repo import find_repo_root, is_ignored_by_git
from devops_cli.git.operations import git_show_toplevel
from devops_cli.http.validation import validate_service_url
from devops_cli.k8s.credentials import get_or_mint_argocd_token
from devops_cli.models.argo import GitOpsDriftEvent, GitOpsSyncTriggerResult
Expand Down Expand Up @@ -225,15 +227,27 @@ def _resolve_valid_drift_paths(paths: Sequence[Path | str]) -> list[str]:
return resolved_paths


def _parse_drift_event(line: str, now: float) -> GitOpsDriftEvent | None:
def _parse_drift_event(
line: str,
now: float,
repo_root: Path | None = None,
) -> GitOpsDriftEvent | None:
"""Parse a single porcelain status line into a GitOpsDriftEvent."""
if len(line) < 4:
return None
status_code = line[:2].strip()
rel_path = line[3:].strip().strip('"')
rel_path = line[3:]
if rel_path.startswith('"') and rel_path.endswith('"'):
rel_path = rel_path[1:-1]
try:
validate_no_path_traversal(rel_path, label="Drift relative path")
fpath = Path(rel_path).resolve()
path_obj = Path(rel_path)
if path_obj.is_absolute():
fpath = path_obj.resolve()
elif repo_root is not None:
fpath = (repo_root / path_obj).resolve()
else:
fpath = path_obj.resolve()
except Exception:
return None

Expand Down Expand Up @@ -263,15 +277,34 @@ def inspect_git_manifest_drift(paths: Sequence[Path | str]) -> list[GitOpsDriftE
resolved_paths = _resolve_valid_drift_paths(paths)
if not resolved_paths:
return []
first_path = Path(resolved_paths[0])
repo_root = git_show_toplevel(first_path) or find_repo_root(first_path)
try:
cmd = ["git", "status", "--porcelain", "--", *resolved_paths]
res = run_subprocess(cmd, check=False, capture_output=True, timeout=5.0)
cmd = ["git", "status", "--porcelain=v1", "-z", "--", *resolved_paths]
res = run_subprocess(cmd, cwd=repo_root, check=False, capture_output=True, timeout=5.0)
if res.returncode != 0:
return []
now = time.time()
events: list[GitOpsDriftEvent] = []
for line in res.stdout.strip().splitlines():
ev = _parse_drift_event(line, now)
tokens = (
[t for t in res.stdout.split("\0") if t]
if "\0" in res.stdout
else res.stdout.strip().splitlines()
)
idx = 0
while idx < len(tokens):
line = tokens[idx]
idx += 1
if len(line) < 4:
continue
status_code = line[:2]
if (
status_code[0] in CONST_GIT_NAME_STATUS_TWO_PATH_LETTERS
or status_code[1] in CONST_GIT_NAME_STATUS_TWO_PATH_LETTERS
):
if idx < len(tokens):
idx += 1
ev = _parse_drift_event(line, now, repo_root=repo_root)
if ev is not None:
events.append(ev)
return events
Expand Down
32 changes: 23 additions & 9 deletions src/devops_cli/commands/test_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,16 @@
app = new_typer(help=HELP.test.app, no_args_is_help=False)


def _porcelain_path(line: str) -> str:
"""The path a `git status --porcelain --no-renames` line names; empty if none."""
parts = line.strip().split(maxsplit=1)
if len(parts) != 2:
def _porcelain_path(entry: str) -> str:
"""The path a `git status --porcelain=v1 -z --no-renames` entry names; empty if none."""
if len(entry) < 4:
return ""
return parts[1].strip().strip('"')
if entry[2] == " ":
return entry[3:]
parts = entry.strip().split(maxsplit=1)
if len(parts) == 2:
return parts[1].strip().strip('"')
return ""


def _changed_paths(repo_root: Path) -> list[str]:
Expand All @@ -61,17 +65,27 @@ def _changed_paths(repo_root: Path) -> list[str]:
and its new path added, so a helper renamed away reaches what it reached (#1312)."""
changed: set[str] = set()
diff_proc = run_subprocess(
["git", "diff", "--name-only", "--no-renames", f"{CONST_GIT_MAIN_BRANCH}...HEAD"],
["git", "diff", "--name-only", "-z", "--no-renames", f"{CONST_GIT_MAIN_BRANCH}...HEAD"],
cwd=repo_root,
check=False,
)
if diff_proc.returncode == 0 and diff_proc.stdout:
changed.update(diff_proc.stdout.strip().splitlines())
diff_entries = (
diff_proc.stdout.split("\0")
if "\0" in diff_proc.stdout
else diff_proc.stdout.strip().splitlines()
)
changed.update(p for p in diff_entries if p)

status = ["git", "status", "--porcelain", "--no-renames", "--untracked-files=all"]
status = ["git", "status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all"]
wt_proc = run_subprocess(status, cwd=repo_root, check=False)
if wt_proc.returncode == 0 and wt_proc.stdout:
changed.update(_porcelain_path(line) for line in wt_proc.stdout.strip().splitlines())
wt_entries = (
wt_proc.stdout.split("\0")
if "\0" in wt_proc.stdout
else wt_proc.stdout.strip().splitlines()
)
changed.update(_porcelain_path(entry) for entry in wt_entries if entry)
return sorted(path for path in changed if path)


Expand Down
9 changes: 5 additions & 4 deletions src/devops_cli/core/cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,15 @@ def _listed_worktrees(main_root: Path) -> list[Path]:
"""Every worktree of the repository whose main worktree is `main_root`, as git lists them;
none when `main_root` is not in a repository."""
listing = run_subprocess(
["git", "worktree", "list", "--porcelain"], cwd=main_root, check=False, quiet=True
["git", "worktree", "list", "--porcelain", "-z"], cwd=main_root, check=False, quiet=True
)
if listing.returncode != 0:
return []
entries = listing.stdout.split("\0") if "\0" in listing.stdout else listing.stdout.splitlines()
return [
Path(line.removeprefix("worktree ")).resolve()
for line in listing.stdout.splitlines()
if line.startswith("worktree ")
Path(entry.removeprefix("worktree ")).resolve()
for entry in entries
if entry.startswith("worktree ")
]


Expand Down
6 changes: 4 additions & 2 deletions src/devops_cli/core/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ def _list_git_tracked_files(repo_root: Path, resolved_target: Path) -> list[Path
"--cached",
"--others",
"--exclude-standard",
"-z",
]
if resolved_target != repo_root:
rel_to_repo = resolved_target.relative_to(repo_root)
Expand All @@ -568,8 +569,9 @@ def _list_git_tracked_files(repo_root: Path, resolved_target: Path) -> list[Path
files: list[Path] = []
repo_root_resolved = repo_root.resolve()
inside: dict[Path, bool] = {}
for line in proc.stdout.splitlines():
line_str = line.strip()
entries = proc.stdout.split("\0") if "\0" in proc.stdout else proc.stdout.splitlines()
for entry in entries:
line_str = entry.strip() if "\0" not in proc.stdout else entry
if not line_str:
continue
p = repo_root / line_str
Expand Down
13 changes: 8 additions & 5 deletions src/devops_cli/roadmap/refine.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def _git(checkout: Path, *args: str) -> tuple[int, str]:
timeout=15,
quiet=True,
)
return proc.returncode, (proc.stdout or proc.stderr or "").strip()
return proc.returncode, proc.stdout if proc.returncode == 0 else (proc.stderr or "").strip()


def inspect_checkout(source: Path | str, expected_repo: str) -> str:
Expand All @@ -325,6 +325,7 @@ def inspect_checkout(source: Path | str, expected_repo: str) -> str:
},
)
code_sha, sha = _git(path, "rev-parse", "HEAD")
sha = sha.strip()
if code_sha != 0 or not sha:
raise GitHubOperationError(
f"Could not determine HEAD SHA in {source}.",
Expand Down Expand Up @@ -392,9 +393,10 @@ def _collect_repo_map(source: Path, sha: str, paths: Sequence[str]) -> list[str]
dirs = {str(Path(p).parent) for p in paths if "/" in p}
files: list[str] = []
for d in sorted(dirs):
code, out = _git(source, "ls-tree", "-r", "--name-only", sha, d)
code, out = _git(source, "ls-tree", "-r", "-z", "--name-only", sha, d)
if code == 0 and out:
files.extend(out.splitlines()[:15])
items = out.split("\0") if "\0" in out else out.splitlines()
files.extend([f for f in items if f][:15])
if len(files) >= 50:
break
return files[:50]
Expand All @@ -415,9 +417,10 @@ def collect_context(
sections.append(f"### CONTEXT.md\n{ctx}")

# docs/adr/*.md
code_adr, adr_list = _git(source, "ls-tree", "-r", "--name-only", sha, "docs/adr")
code_adr, adr_list = _git(source, "ls-tree", "-r", "-z", "--name-only", sha, "docs/adr")
if code_adr == 0 and adr_list:
for adr_path in adr_list.splitlines()[:5]:
adr_items = adr_list.split("\0") if "\0" in adr_list else adr_list.splitlines()
for adr_path in [p for p in adr_items if p][:5]:
adr_content = _read_git_file(source, sha, adr_path)
if adr_content:
sections.append(f"### {adr_path}\n{adr_content}")
Expand Down
Loading
Loading