From 70a06fcf54f3c869f9cccd836a927ffac3a41c96 Mon Sep 17 00:00:00 2001 From: Divya Chukkapalli <12871391+divya0795@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:15:46 -0800 Subject: [PATCH 1/4] fix(init): remove a new project directory when shared infra fails `specify init ` creates the project directory, then installs shared infrastructure. `_install_shared_infra_or_exit` reports an OSError/ValueError there and raises typer.Exit(1), but init re-raised typer.Exit before the cleanup that removes a directory the run created. A disk-full failure therefore left a half-initialized project behind and the retry failed with "Directory already exists". Run the same new-directory cleanup for a non-zero typer.Exit/SystemExit, keeping the existing guards for --here, pre-existing directories and lifecycle-owned rollback. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/command_init.py | 13 ++++- tests/specify_cli/test_command_init.py | 66 ++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index 1214cc376f..720cb08a95 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -1041,7 +1041,18 @@ def init( ensure_constitution_from_template(project_path, tracker=tracker) tracker.complete("final", "project ready") - except (typer.Exit, SystemExit): + except (typer.Exit, SystemExit) as exc: + # A failing step that already reported its own error exits + # here (e.g. a shared-infrastructure OSError becomes + # typer.Exit(1)); remove a directory this run created, as the + # generic failure path below does. + exit_code = getattr(exc, "exit_code", getattr(exc, "code", 1)) + if ( + exit_code not in (0, None) + and not here and project_path.exists() and not dir_existed_before + and initial_directory_state(project_path) is None + ): + shutil.rmtree(project_path, ignore_errors=True) raise except Exception as e: tracker.error("final", str(e)) diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 7dd683e4e7..ba74229fae 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -257,6 +257,72 @@ def test_invalid_integration_value_is_rendered_literally(tmp_path: Path): assert "nope[/red]" in _strip(result.stdout) +def _fail_shared_infra(monkeypatch): + """Make the shared-infrastructure step fail part-way, as a full disk would. + + ``_install_shared_infra_or_exit`` turns the ``OSError`` into + ``typer.Exit(1)``, which is how init sees a real shared-infra failure. + """ + import specify_cli + + def partial_install(project_path, *args, **kwargs): + scripts = Path(project_path) / ".specify" / "scripts" + scripts.mkdir(parents=True, exist_ok=True) + (scripts / "partial.sh").write_text("#!/usr/bin/env bash\n", encoding="utf-8") + raise OSError(28, "No space left on device") + + monkeypatch.setattr(specify_cli, "_install_shared_infra", partial_install) + + +def test_shared_infra_failure_removes_new_project_dir(tmp_path: Path, monkeypatch): + """A failed init into a new directory removes it, so a retry can succeed. + + The shared-infrastructure failure arrives as ``typer.Exit(1)``. It used to + be re-raised before the cleanup ran, leaving a half-initialized project + that made the retry fail with "Directory already exists". + """ + _fail_shared_infra(monkeypatch) + + result = _init(tmp_path, "proj") + + assert result.exit_code == 1, _strip(result.stdout) + assert "Failed to install shared infrastructure" in _strip(result.stdout) + assert not (tmp_path / "proj").exists() + + monkeypatch.undo() + retry = _init(tmp_path, "proj") + assert retry.exit_code == 0, _strip(retry.stdout) + assert (tmp_path / "proj" / ".specify").is_dir() + + +def test_shared_infra_failure_keeps_existing_project_dir(tmp_path: Path, monkeypatch): + """A failed init never deletes a directory that existed before it ran.""" + existing = tmp_path / "proj" + existing.mkdir() + keep = existing / "notes.txt" + keep.write_text("user data\n", encoding="utf-8") + _fail_shared_infra(monkeypatch) + + previous = os.getcwd() + os.chdir(tmp_path) + try: + result = CliRunner().invoke( + app, + [ + "init", "proj", "--force", + "--integration", "generic", + "--integration-options", "--commands-dir .agent/commands", + "--ignore-agent-tools", "--offline", + ], + catch_exceptions=True, + ) + finally: + os.chdir(previous) + + assert result.exit_code == 1, _strip(result.stdout) + assert keep.read_text(encoding="utf-8") == "user data\n" + + def _cd_argument(stdout: str) -> str: """Return the argument of the printed `cd` command, verbatim. From cd07b547dce44b0392856686d8865994f22fa4b0 Mon Sep 17 00:00:00 2001 From: Divya Chukkapalli <12871391+divya0795@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:03:18 -0800 Subject: [PATCH 2/4] fix(init): leave a noncanonical new target to lifecycle rollback The external-integration lifecycle records the init target as spelled (anchor/../proj), while init compares it against the resolved path after prepare_init_root(). initial_directory_state() therefore returned None, and the shared-infrastructure exit path removed the whole target before the journal rollback could preserve files it does not own. Compare the recorded and requested paths in resolved form, and skip the cleanup while lifecycle_owns_rollback() is true. Scope the failing installer in the retry test with monkeypatch.context() so the retry keeps the home and environment isolation fixtures. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/command_init.py | 1 + src/specify_cli/integrations/_lifecycle.py | 10 ++++-- tests/specify_cli/test_command_init.py | 39 +++++++++++++++++++--- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index 720cb08a95..81d13cd21d 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -1051,6 +1051,7 @@ def init( exit_code not in (0, None) and not here and project_path.exists() and not dir_existed_before and initial_directory_state(project_path) is None + and not lifecycle_owns_rollback() ): shutil.rmtree(project_path, ignore_errors=True) raise diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index af61010c42..3af2b8afc3 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -52,9 +52,15 @@ def lifecycle_success(message: str) -> None: def initial_directory_state(path: Path) -> tuple[bool, list[Path]] | None: - """Init validation sees the directory before the lifecycle lock created it.""" + """Init validation sees the directory before the lifecycle lock created it. + + The lifecycle records the target as spelled (``parent/../proj``) while + init later works with the resolved path, so compare resolved forms. + """ state = _init_directory.get() - if state is not None and state[0] == path: + if state is None: + return None + if state[0] == path or state[0].resolve() == path.resolve(): return state[1], state[2] return None diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index ba74229fae..5914c4cc60 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -257,11 +257,13 @@ def test_invalid_integration_value_is_rendered_literally(tmp_path: Path): assert "nope[/red]" in _strip(result.stdout) -def _fail_shared_infra(monkeypatch): +def _fail_shared_infra(monkeypatch, unowned: str | None = None): """Make the shared-infrastructure step fail part-way, as a full disk would. ``_install_shared_infra_or_exit`` turns the ``OSError`` into ``typer.Exit(1)``, which is how init sees a real shared-infra failure. + ``unowned`` names a project-root file written outside any journalled + scope, standing in for a concurrent write the rollback must preserve. """ import specify_cli @@ -269,6 +271,8 @@ def partial_install(project_path, *args, **kwargs): scripts = Path(project_path) / ".specify" / "scripts" scripts.mkdir(parents=True, exist_ok=True) (scripts / "partial.sh").write_text("#!/usr/bin/env bash\n", encoding="utf-8") + if unowned: + (Path(project_path) / unowned).write_text("unowned\n", encoding="utf-8") raise OSError(28, "No space left on device") monkeypatch.setattr(specify_cli, "_install_shared_infra", partial_install) @@ -281,20 +285,45 @@ def test_shared_infra_failure_removes_new_project_dir(tmp_path: Path, monkeypatc be re-raised before the cleanup ran, leaving a half-initialized project that made the retry fail with "Directory already exists". """ - _fail_shared_infra(monkeypatch) - - result = _init(tmp_path, "proj") + # Scope only the failing installer, so the retry keeps the home and + # environment isolation fixtures. + with monkeypatch.context() as failing: + _fail_shared_infra(failing) + result = _init(tmp_path, "proj") assert result.exit_code == 1, _strip(result.stdout) assert "Failed to install shared infrastructure" in _strip(result.stdout) assert not (tmp_path / "proj").exists() - monkeypatch.undo() retry = _init(tmp_path, "proj") assert retry.exit_code == 0, _strip(retry.stdout) assert (tmp_path / "proj" / ".specify").is_dir() +def test_shared_infra_failure_leaves_noncanonical_target_to_lifecycle( + tmp_path: Path, monkeypatch +): + """Lifecycle rollback, not init's cleanup, owns a noncanonical new target. + + The lifecycle records ``anchor/../proj`` as spelled while init works with + the resolved path. The lookup must still match, so init leaves the + directory to journal rollback, which preserves files it does not own + instead of deleting the whole target. + """ + from specify_cli.integrations import installer + + (tmp_path / "anchor").mkdir() + monkeypatch.setattr(installer, "read_records", lambda root: {"generic": {}}) + monkeypatch.setattr(installer, "load_installed_integrations", lambda root: None) + _fail_shared_infra(monkeypatch, unowned="concurrent.txt") + + result = _init(tmp_path, str(Path("anchor") / ".." / "proj")) + + assert result.exit_code == 1, _strip(result.stdout) + project = tmp_path / "proj" + assert (project / "concurrent.txt").read_text(encoding="utf-8") == "unowned\n" + + def test_shared_infra_failure_keeps_existing_project_dir(tmp_path: Path, monkeypatch): """A failed init never deletes a directory that existed before it ran.""" existing = tmp_path / "proj" From 042847afd6451c7583cbbf61353f9342ad514800 Mon Sep 17 00:00:00 2001 From: Divya Chukkapalli <12871391+divya0795@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:12:44 -0800 Subject: [PATCH 3/4] fix(init): route the new cleanup through FileHelper The lint job's FileHelper migration guard rejected the two direct filesystem calls this branch added: shutil.rmtree for the cleanup on a failing step's exit, and Path.resolve() in initial_directory_state(). Remove the new project directory with a deny-mode FileHelper rooted at its parent instead. Deletion is handle-based and never follows links below the target, and it stays best effort like the previous ignore_errors removal. Match the resolved target without resolving it again: the init lifecycle already resolves the root through preflight_init_root(), so keep that root in a context variable and accept either spelling. The noncanonical-target test now asserts the lookup itself from inside the failing installer, since lifecycle_owns_rollback() would otherwise hide a regression: the resolved target must match and an unrelated directory must not. It fails when the comparison reverts to the spelled path only. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/command_init.py | 10 ++++++++-- src/specify_cli/integrations/_lifecycle.py | 10 ++++++---- tests/specify_cli/test_command_init.py | 21 +++++++++++++++++++-- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index 81d13cd21d..8681cfef75 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -547,7 +547,7 @@ def init( from ._file_policy import ( ProjectPolicyError, prepare_init_root, read_project_options, ) - from .file_helper import FileHelperError + from .file_helper import FileHelper, FileHelperError try: # Existing targets are checked before any integration or scaffold mutation. @@ -1053,7 +1053,13 @@ def init( and initial_directory_state(project_path) is None and not lifecycle_owns_rollback() ): - shutil.rmtree(project_path, ignore_errors=True) + # Deny-mode, handle-based removal beneath the trusted + # parent; best effort, so the step's own error stands. + try: + with FileHelper(project_path.parent) as files: + files.delete(project_path.name, recursive=True) + except (OSError, FileHelperError): + pass raise except Exception as e: tracker.error("final", str(e)) diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index 3af2b8afc3..7ca6e205dc 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -30,6 +30,7 @@ _init_directory: ContextVar[tuple[Path, bool, list[Path]] | None] = ContextVar( "external_integration_init_directory", default=None ) +_init_root: ContextVar[Path | None] = ContextVar("external_integration_init_root", default=None) _success_messages: ContextVar[list[str] | None] = ContextVar( "external_integration_success_messages", default=None ) @@ -55,12 +56,11 @@ def initial_directory_state(path: Path) -> tuple[bool, list[Path]] | None: """Init validation sees the directory before the lifecycle lock created it. The lifecycle records the target as spelled (``parent/../proj``) while - init later works with the resolved path, so compare resolved forms. + init later works with the resolved path, so also match the root the + lifecycle resolved through ``preflight_init_root``. """ state = _init_directory.get() - if state is None: - return None - if state[0] == path or state[0].resolve() == path.resolve(): + if state is not None and path in (state[0], _init_root.get()): return state[1], state[2] return None @@ -658,6 +658,8 @@ def invoke(*args, **kwargs): (creation_root, root.exists(), list(root.iterdir()) if root.is_dir() else []) ) stack.callback(_init_directory.reset, token) + root_token = _init_root.set(root) + stack.callback(_init_root.reset, root_token) transaction = ( _transaction(root, key, state, records, creation_root=creation_root) if operation == "init" diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 5914c4cc60..b0f7260287 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -257,17 +257,20 @@ def test_invalid_integration_value_is_rendered_literally(tmp_path: Path): assert "nope[/red]" in _strip(result.stdout) -def _fail_shared_infra(monkeypatch, unowned: str | None = None): +def _fail_shared_infra(monkeypatch, unowned: str | None = None, probe=None): """Make the shared-infrastructure step fail part-way, as a full disk would. ``_install_shared_infra_or_exit`` turns the ``OSError`` into ``typer.Exit(1)``, which is how init sees a real shared-infra failure. ``unowned`` names a project-root file written outside any journalled scope, standing in for a concurrent write the rollback must preserve. + ``probe`` is called with the project path init passed to the installer. """ import specify_cli def partial_install(project_path, *args, **kwargs): + if probe is not None: + probe(Path(project_path)) scripts = Path(project_path) / ".specify" / "scripts" scripts.mkdir(parents=True, exist_ok=True) (scripts / "partial.sh").write_text("#!/usr/bin/env bash\n", encoding="utf-8") @@ -311,16 +314,30 @@ def test_shared_infra_failure_leaves_noncanonical_target_to_lifecycle( instead of deleting the whole target. """ from specify_cli.integrations import installer + from specify_cli.integrations._lifecycle import initial_directory_state (tmp_path / "anchor").mkdir() monkeypatch.setattr(installer, "read_records", lambda root: {"generic": {}}) monkeypatch.setattr(installer, "load_installed_integrations", lambda root: None) - _fail_shared_infra(monkeypatch, unowned="concurrent.txt") + lookups: dict[str, object] = {} + + def probe(project_path: Path) -> None: + # The deletion guard also checks lifecycle_owns_rollback(), so assert + # the lookup itself: it must match the resolved target init uses and + # still reject an unrelated directory. + lookups["target"] = project_path + lookups["resolved"] = initial_directory_state(project_path) + lookups["unrelated"] = initial_directory_state(tmp_path / "anchor") + + _fail_shared_infra(monkeypatch, unowned="concurrent.txt", probe=probe) result = _init(tmp_path, str(Path("anchor") / ".." / "proj")) assert result.exit_code == 1, _strip(result.stdout) project = tmp_path / "proj" + assert lookups["target"] == project.resolve() + assert lookups["resolved"] == (False, []) + assert lookups["unrelated"] is None assert (project / "concurrent.txt").read_text(encoding="utf-8") == "unowned\n" From cbbd0a414e978d00acf64e4b850779d3d79564a6 Mon Sep 17 00:00:00 2001 From: Divya Chukkapalli <12871391+divya0795@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:38:21 -0800 Subject: [PATCH 4/4] fix(init): drop the redundant existence probe before cleanup The new cleanup checked project_path.exists() before deleting. That is a direct filesystem call outside the FileHelper boundary, and it is redundant: FileHelper.delete() raises FileNotFoundError for a missing target (and the FileHelper constructor does for a missing parent), which the best-effort except OSError already absorbs. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/command_init.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index 8681cfef75..424c112dde 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -1049,12 +1049,13 @@ def init( exit_code = getattr(exc, "exit_code", getattr(exc, "code", 1)) if ( exit_code not in (0, None) - and not here and project_path.exists() and not dir_existed_before + and not here and not dir_existed_before and initial_directory_state(project_path) is None and not lifecycle_owns_rollback() ): # Deny-mode, handle-based removal beneath the trusted - # parent; best effort, so the step's own error stands. + # parent; best effort, so the step's own error stands + # (an already-missing target raises FileNotFoundError). try: with FileHelper(project_path.parent) as files: files.delete(project_path.name, recursive=True)