fix(cli): keep non-ASCII working directory names out of the init profile slug (#3718)

## Description

`headroom init` aborts with `Invalid profile name` from any working
directory whose name is not pure ASCII.

`_local_profile` (`headroom/cli/init.py:115`) builds its slug with
`str.isalnum`, which is Unicode-aware and therefore keeps Cyrillic, CJK
and accented Latin letters. `validate_profile_name`
(`headroom/install/paths.py`) then rejects that slug against
`^[A-Za-z0-9._-]+$`.

This is not limited to Cyrillic as originally reported — `café-app`
fails too, so it hits French, Spanish and Portuguese directory names as
well.

Closes #3467

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `_local_profile` keeps only ASCII alphanumerics (plus `-._`) in the
slug; everything else becomes `-`, as non-alphanumerics already did.
- A name that slugs away entirely still falls back to
`init-repo-<digest>`, and the sha1 of the full path still distinguishes
two folders sharing a name.
- ASCII directory names produce byte-identical output to before.
- Regression tests in `tests/test_cli/test_init_cli.py`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`) — not run, see Not tested
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New tests against **unpatched** `_local_profile` (fix stashed) — they
fail:

```text
$ python -m pytest tests/test_cli/test_init_cli.py -k local_profile -q
FAILED tests/test_cli/test_init_cli.py::test_local_profile_accepts_non_ascii_directory_names[Мастеринг в HW]
FAILED tests/test_cli/test_init_cli.py::test_local_profile_accepts_non_ascii_directory_names[项目]
FAILED tests/test_cli/test_init_cli.py::test_local_profile_accepts_non_ascii_directory_names[caf\xe9-app]
FAILED tests/test_cli/test_init_cli.py::test_local_profile_accepts_non_ascii_directory_names[\xdcnicode Projekt]
FAILED tests/test_cli/test_init_cli.py::test_local_profile_distinguishes_identical_non_ascii_names
5 failed, 2 passed, 72 deselected, 1 warning in 0.34s
```

With the fix:

```text
$ python -m pytest tests/test_cli/test_init_cli.py tests/test_install/test_paths.py -q
82 passed, 1 warning in 1.00s

$ ruff check headroom/cli/init.py tests/test_cli/test_init_cli.py
All checks passed!

$ ruff format --check headroom/cli/init.py tests/test_cli/test_init_cli.py
2 files already formatted
```

## Real Behavior Proof

- Environment: macOS 15.6 (Darwin 25.6.0, arm64, M3 Pro), Python
3.12.14, headroom at `5ff4ea1` (main), APFS (case-insensitive,
Unicode-preserving)
- Exact command / steps: `mkdir -p "/tmp/hr demo/Мастеринг в HW" && cd
"/tmp/hr demo/Мастеринг в HW" && python -c "from headroom.cli.init
import _local_profile; print(_local_profile())"` — run once with the fix
stashed and once with it applied; full form below.
- Observed result: before the fix `ClickException: Invalid profile name
'init-мастеринг-в-hw-8db7d005'`; after the fix `init-hw-8db7d005`. Full
transcript below.
- Not tested: Windows (where it was reported), the full `headroom init
hook ensure` CLI path, and `mypy`. Details below.

Full form:

```bash
mkdir -p "/tmp/hr demo/Мастеринг в HW"
cd "/tmp/hr demo/Мастеринг в HW"
python -c "from headroom.cli.init import _local_profile; print(_local_profile())"
```

Observed result:

```text
cwd: /tmp/hr demo/Мастеринг в HW

=== BEFORE FIX ===
  ClickException: Invalid profile name 'init-мастеринг-в-hw-8db7d005'

=== AFTER FIX ===
  profile: init-hw-8db7d005
```

The digest is identical across both runs (`8db7d005`), confirming only
the slug changed and profile identity for a given path is otherwise
preserved.

Slug behaviour across scripts after the fix:

```text
'Мастеринг в HW'     -> 'init-hw-080fa965'
'café-app'           -> 'init-caf--app-b393d6a7'
'项目'                -> 'init-repo-5f1f15e6'
'Ünicode Projekt'    -> 'init-nicode-projekt-b7b5d10e'
'my-repo'            -> 'init-my-repo-c9d86e48'   (unchanged by this patch)
```

Not tested, in detail:

- Windows, which is where the issue was originally reported. I
reproduced and fixed it on macOS; the code path is platform-independent
(`Path.resolve().name`), but I have not run it on Windows.
- The full `headroom init hook ensure` command end to end — this venv
has the pure-Python dependencies only, not the compiled Rust extension,
so I exercised `_local_profile` directly rather than through the CLI
entry point.
- `mypy`, for the same reason (the package does not fully import in this
environment).

## Runtime Rollout Safety

- Rollout-managed feature(s): none — this is a pure function used during
`init`, behind no rollout flag.
- Minimum rollout channel: n/a — not rollout-managed.
- Stable/default behavior changed: only for directories that previously
raised `Invalid profile name`; ASCII directory names are byte-identical.
- Kill switch / disable path: n/a — no flag to disable; `--profile
<name>` remains the explicit override it always was.
- Unsafe override required: no.
- Qualification impact: none — no qualification surface is touched.
- Rollback path: revert this commit; slug generation returns to the
previous behaviour.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation — n/a, no
user-facing docs describe the slug format
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

Users with an existing profile for a non-ASCII directory cannot exist,
since `init` could never create one there — so there is no migration
concern.

`café-app` slugs to `caf--app` (a doubled dash where `é` was). Valid per
the regex and I kept the transformation minimal rather than collapsing
dash runs, which would change output for ASCII names too. Happy to
collapse them if you would prefer.

AI assistance was used to investigate and prepare this change. I
reviewed every changed line and ran the commands shown above.

Signed-off-by: Iyed Sebai <iyed.se1ai@gmail.com>
This commit is contained in:
Sebai Iyed
2026-09-24 11:27:45 -05:00
committed by GitHub
parent 690fb251dc
commit f3d95ee275
2 changed files with 53 additions and 3 deletions
+3 -3
View File
@@ -120,9 +120,9 @@ def _enable_verbose_logging() -> None:
def _local_profile(cwd: Path | None = None) -> str:
root = (cwd or Path.cwd()).resolve()
slug = "".join(ch if ch.isalnum() or ch in "-._" else "-" for ch in root.name.lower()).strip(
"-"
)
slug = "".join(
ch if (ch.isascii() and ch.isalnum()) or ch in "-._" else "-" for ch in root.name.lower()
).strip("-")
digest = sha1(str(root).encode("utf-8")).hexdigest()[:8]
return validate_profile_name(f"init-{slug or 'repo'}-{digest}")
+50
View File
@@ -6,6 +6,7 @@ import os
import sys
import types
from contextlib import contextmanager
from hashlib import sha1
from pathlib import Path
from types import SimpleNamespace
@@ -18,6 +19,8 @@ import click
import pytest
from click.testing import CliRunner
from headroom.install.paths import _PROFILE_RE as PROFILE_RE
def _load_init_module(monkeypatch):
monkeypatch.delitem(sys.modules, "headroom.cli.init", raising=False)
@@ -1594,3 +1597,50 @@ def test_init_codex_strip_removes_openai_base_url(monkeypatch, tmp_path: Path) -
f"_strip_codex_init_block must remove orphaned openai_base_url:\n{orphan_stripped}"
)
assert 'model = "gpt-4o"' in orphan_stripped
@pytest.mark.parametrize(
"dir_name",
[
"Мастеринг в HW",
"项目",
"café-app",
"Ünicode Projekt",
],
)
def test_local_profile_accepts_non_ascii_directory_names(monkeypatch, tmp_path, dir_name) -> None:
"""A non-ASCII working directory must still yield a valid profile name.
``str.isalnum`` is Unicode-aware, so Cyrillic/CJK/accented letters survived
into the slug and ``validate_profile_name`` then rejected it, making
``headroom init`` unusable from such a directory.
"""
init_cli, _ = _load_init_module(monkeypatch)
root = tmp_path / dir_name
root.mkdir()
profile = init_cli._local_profile(root)
assert PROFILE_RE.fullmatch(profile), profile
assert profile.startswith("init-")
def test_local_profile_is_unchanged_for_ascii_directory_names(monkeypatch, tmp_path) -> None:
"""The ASCII slug path keeps its existing output."""
init_cli, _ = _load_init_module(monkeypatch)
root = tmp_path / "my-repo"
root.mkdir()
digest = sha1(str(root.resolve()).encode("utf-8")).hexdigest()[:8]
assert init_cli._local_profile(root) == f"init-my-repo-{digest}"
def test_local_profile_distinguishes_identical_non_ascii_names(monkeypatch, tmp_path) -> None:
"""Two folders sharing a fully non-ASCII name must not collide."""
init_cli, _ = _load_init_module(monkeypatch)
first = tmp_path / "a" / "项目"
second = tmp_path / "b" / "项目"
first.mkdir(parents=True)
second.mkdir(parents=True)
assert init_cli._local_profile(first) != init_cli._local_profile(second)