# Identify chained commands in type validation errors

- Task: `task_009_exceptions_context_or_c`
- Status: accepted
- Module: src/click/exceptions.py
- Behaviour axis: context_or_command_chaining
- Interaction partner: src/click/types.py
- Files changed: src/click/exceptions.py, src/click/types.py
- Repairs: 1

## Gates

| Gate | Result |
| --- | --- |
| Patch precheck | passed |
| Shape precheck | passed |
| Test hygiene precheck | passed |
| Interface precheck | passed |
| G1 Applies cleanly | passed |
| Base fail ratio | passed |
| G5 Every requirement tested | passed |
| G2 Fail-to-pass | passed |
| G3 No regressions | passed |
| G4 Same result every time | passed |
| G6 Mutation testing | passed |
| Harbor official checks | passed |
| N1 Not already in Click | passed |
| G7 Blind solve | passed |

Mutation testing (G6): 6 of 6 mutants caught.

Harbor: nop reward 0.0 (must be 0.0), oracle reward 1.0 (must be 1.0).

Blind solve (G7): reward 1.0, fail-to-pass 14 / 14, 0 regression failures, 1 attempt.

## instruction.md

The only file the agent under test sees.

# Identify Chained Commands in Type Validation Errors

## Problem Description

Type conversion errors in a command chain do not identify which command failed. When `ParamType.fail` raises a `BadParameter` for a chained subcommand, its formatted message should include that command's full context command path.

The change must preserve the existing parameter hint and validation message. It must not change errors from non-chain commands or `BadParameter` exceptions raised directly by application code.

## Acceptance Criteria

- **AC1**: Every `BadParameter` raised by `ParamType.fail` is classified as a type-validation error, including when `param` or `ctx` is `None`. The classification remains effective if Click attaches a parameter or context later.
- **AC2**: When a classified error has a context whose direct parent context belongs to a group with `chain=True`, `BadParameter.format_message()` prefixes the existing formatted message with the failing context's full `command_path` followed by `: `.
- **AC3**: Errors from different subcommands in the same chain identify their respective failing commands. A chain nested beneath other commands uses the full context command path, including those ancestors.
- **AC4**: A classified error without a context, an error for the chain group's own parameter, and an error whose direct parent is not a chain group retain their existing formatting.
- **AC5**: A `BadParameter` constructed and raised directly by application code retains its existing formatting, even if it has a chained-subcommand context or is raised during type conversion. Calling `ParamType.fail` is classified according to AC1, including when application code calls it.
- **AC6**: Existing hint selection, hint quoting and joining, validation messages, localization, exception status, and usage/help output remain unchanged apart from the specified prefix. Repeated calls to `format_message()` do not accumulate prefixes.
- **AC7**: Tests cover built-in and custom type failures, different commands in one chain, a nested chain path, missing context, later context attachment, non-chain commands, and directly raised `BadParameter` exceptions.

## Interface

### Symbols

- `BadParameter`
- `BadParameter.__init__`
- `BadParameter.format_message`
- `ParamType.fail`

### Contract Details

- `BadParameter.__init__(self, message: str, ctx: Context | None = None, param: Parameter | None = None, param_hint: Sequence[str] | str | None = None) -> None` retains its existing signature and defaults. Direct construction does not classify the exception as a type-validation error.
- `ParamType.fail(self, message: str, param: Parameter | None = None, ctx: Context | None = None) -> NoReturn` retains its existing signature and raises a `BadParameter` carrying the supplied message, parameter, and context. The resulting exception is classified as a type-validation error. No new public classification attribute is required.
- `BadParameter.format_message(self) -> str` retains its existing signature. For an eligible classified error, it returns `{command_path}: {existing_formatted_message}`. The path is the failing context's `command_path`, evaluated when the message is formatted; eligibility is likewise determined from the current context.
- In the default English locale, an eligible error with command path `pipeline import`, parameter hint `'--count'`, and validation message `not a valid integer` formats exactly as `pipeline import: Invalid value for '--count': not a valid integer`. Without a parameter hint, the existing `Invalid value: {message}` form is preserved after the prefix.
- When Click displays an eligible error, its error line uses the existing `Error: {message}` format, with the prefixed formatted message substituted for `{message}`. Existing usage and help lines are unchanged.

## Compatibility & Out of Scope

- Only direct children of a chain-enabled group receive the prefix. An ancestor chain group alone does not make an otherwise non-chain child eligible.
- Other exception types, missing-parameter formatting, command parsing, and chain execution behavior are unchanged.
- Do not introduce new eager top-level standard-library imports that increase Click's startup import footprint.
- The entire existing repository test suite must continue to pass with zero regressions.

## Requirements and their tests

| Requirement | Text | Tests |
| --- | --- | --- |
| AC1 | Every `BadParameter` raised by `ParamType.fail` is classified as a type-validation error, including when `param` or `ctx` is `None`. The classification remains effective if Click attaches a parameter or context later. | test_fail_classification_survives_later_attachment |
| AC2 | When a classified error has a context whose direct parent context belongs to a group with `chain=True`, `BadParameter.format_message()` prefixes the existing formatted message with the failing context's full `command_path` followed by `: `. | test_prefix_uses_current_context_and_path |
| AC3 | Errors from different subcommands in the same chain identify their respective failing commands. A chain nested beneath other commands uses the full context command path, including those ancestors. | test_distinct_commands_and_nested_chain_paths |
| AC4 | A classified error without a context, an error for the chain group's own parameter, and an error whose direct parent is not a chain group retain their existing formatting. | test_only_direct_children_of_chain_groups_are_prefixed |
| AC5 | A `BadParameter` constructed and raised directly by application code retains its existing formatting, even if it has a chained-subcommand context or is raised during type conversion. Calling `ParamType.fail` is classified according to AC1, including when application code calls it. | test_direct_bad_parameter_is_not_classified_even_during_conversion, test_bad_parameter_init_signature_and_direct_construction |
| AC6 | Existing hint selection, hint quoting and joining, validation messages, localization, exception status, and usage/help output remain unchanged apart from the specified prefix. Repeated calls to `format_message()` do not accumulate prefixes. | test_hints_localization_and_repeated_formatting, test_parameter_returning_none_hint_keeps_existing_format, test_cli_error_keeps_usage_help_and_status |
| AC7 | Tests cover built-in and custom type failures, different commands in one chain, a nested chain path, missing context, later context attachment, non-chain commands, and directly raised `BadParameter` exceptions. | test_click_attaches_context_and_parameter_to_custom_failure, test_group_parameter_and_missing_parameter_keep_existing_errors |

Fail-to-pass tests: 14. Pass-to-pass tests: 2434.

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_none_flip | src/click/exceptions.py: if self.param_hint is None and self.param is None: -> if self.param_hint is not None and self.param is None: | yes |
| M02_is_not_none_flip | src/click/exceptions.py: if self._type_validation_error and self.ctx is not None: -> if self._type_validation_error and self.ctx is None: | yes |
| M03_is_not_none_flip | src/click/exceptions.py: if parent is not None: -> if parent is None: | yes |
| M04_return_val_none | src/click/exceptions.py: return f"{self.ctx.command_path}: {message}" -> return None | yes |
| M05_return_val_none | src/click/exceptions.py: return message -> return None | yes |
| M06_raise_remove | src/click/types.py: raise error -> pass | yes |

## Reference patch

````diff
diff --git a/src/click/exceptions.py b/src/click/exceptions.py
index 6272c38..07c31ce 100644
--- a/src/click/exceptions.py
+++ b/src/click/exceptions.py
@@ -142,6 +142,7 @@ class BadParameter(UsageError):
         super().__init__(message, ctx)
         self.param = param
         self.param_hint = param_hint
+        self._type_validation_error = False
 
     def format_message(self) -> str:
         if self.param_hint is not None:
@@ -149,11 +150,25 @@ class BadParameter(UsageError):
         elif self.param is not None:
             param_hint = self.param.get_error_hint(self.ctx)
         else:
-            return _("Invalid value: {message}").format(message=self.message)
+            param_hint = None
 
-        return _("Invalid value for {param_hint}: {message}").format(
-            param_hint=_join_param_hints(param_hint), message=self.message
-        )
+        if self.param_hint is None and self.param is None:
+            message = _("Invalid value: {message}").format(message=self.message)
+        else:
+            message = _("Invalid value for {param_hint}: {message}").format(
+                param_hint=_join_param_hints(param_hint), message=self.message
+            )
+
+        if self._type_validation_error and self.ctx is not None:
+            parent = self.ctx.parent
+
+            if parent is not None:
+                from .core import Group
+
+                if isinstance(parent.command, Group) and parent.command.chain:
+                    return f"{self.ctx.command_path}: {message}"
+
+        return message
 
 
 class MissingParameter(BadParameter):
diff --git a/src/click/types.py b/src/click/types.py
index b6e98a9..f86b9ce 100644
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -219,7 +219,9 @@ class ParamType(t.Generic[_ValueT_co, _InputT_contra], abc.ABC):
         ctx: Context | None = None,
     ) -> t.NoReturn:
         """Helper method to fail with an invalid value message."""
-        raise BadParameter(message, ctx=ctx, param=param)
+        error = BadParameter(message, ctx=ctx, param=param)
+        error._type_validation_error = True
+        raise error
 
     def shell_complete(
         self, ctx: Context, param: Parameter, incomplete: str
````

## Feature tests

### tests/feature/test_chained_type_errors.py

````python
# TEST_CODE
from __future__ import annotations

import inspect
import io

import click
import pytest
from click.testing import CliRunner

def make_chain_contexts():
    group_ctx = click.Context(
        click.Group("pipeline", chain=True), info_name="pipeline"
    )
    child_ctx = click.Context(
        click.Command("import"), info_name="import", parent=group_ctx
    )
    return group_ctx, child_ctx

@pytest.mark.parametrize("provide_param", [False, True])
@pytest.mark.parametrize("provide_ctx", [False, True])
# AC1
def test_fail_classification_survives_later_attachment(provide_param, provide_ctx):
    _, child_ctx = make_chain_contexts()
    param = click.Option(["--count"], type=int)

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail(
            "not a valid integer",
            param=param if provide_param else None,
            ctx=child_ctx if provide_ctx else None,
        )

    error = caught.value
    assert error.message == "not a valid integer"
    assert error.param is (param if provide_param else None)
    assert error.ctx is (child_ctx if provide_ctx else None)

    error.param = param
    error.ctx = child_ctx
    assert error.format_message() == (
        "pipeline import: Invalid value for '--count': not a valid integer"
    )

    error.ctx = None
    assert error.format_message() == "Invalid value for '--count': not a valid integer"
    error.param = None
    assert error.format_message() == "Invalid value: not a valid integer"

# AC2
def test_prefix_uses_current_context_and_path():
    group_ctx, child_ctx = make_chain_contexts()

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("bad", ctx=child_ctx)

    error = caught.value
    assert error.format_message() == "pipeline import: Invalid value: bad"
    child_ctx.info_name = "export"
    assert error.format_message() == "pipeline export: Invalid value: bad"

    other_ctx = click.Context(
        click.Command("check"), info_name="check", parent=group_ctx
    )
    error.ctx = other_ctx
    assert error.format_message() == "pipeline check: Invalid value: bad"
    group_ctx.command.chain = False
    assert error.format_message() == "Invalid value: bad"
    group_ctx.command.chain = True
    assert error.format_message() == "pipeline check: Invalid value: bad"
    error.ctx = None
    assert error.format_message() == "Invalid value: bad"

# AC3
def test_distinct_commands_and_nested_chain_paths():
    class Reject(click.ParamType):
        name = "reject"

        def convert(self, value, param, ctx):
            self.fail("rejected", param, ctx)

    @click.group()
    def app():
        pass

    @app.group(chain=True)
    def pipeline():
        pass

    @pipeline.command("import")
    @click.option("--count", type=int)
    def import_command(count):
        click.echo(f"imported {count}")

    @pipeline.command("export")
    @click.option("--value", type=Reject())
    def export_command(value):
        pass

    runner = CliRunner()
    first = runner.invoke(
        app, ["pipeline", "import", "--count", "nope"], prog_name="app"
    )
    assert first.exit_code == 2
    assert (
        "Error: app pipeline import: Invalid value for '--count': "
        "'nope' is not a valid integer.\n"
    ) in first.output

    second = runner.invoke(
        app,
        ["pipeline", "import", "--count", "1", "export", "--value", "x"],
        prog_name="app",
    )
    assert second.exit_code == 2
    assert (
        "Error: app pipeline export: Invalid value for '--value': rejected\n"
    ) in second.output
    assert "app pipeline import: Invalid value" not in second.output

    success = runner.invoke(
        app, ["pipeline", "import", "--count", "1"], prog_name="app"
    )
    assert success.exit_code == 0
    assert success.output == "imported 1\n"

# AC4
def test_only_direct_children_of_chain_groups_are_prefixed():
    chain_ctx, child_ctx = make_chain_contexts()

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("bad", ctx=child_ctx)
    error = caught.value
    assert error.format_message() == "pipeline import: Invalid value: bad"

    error.ctx = chain_ctx
    assert error.format_message() == "Invalid value: bad"
    error.ctx = None
    assert error.format_message() == "Invalid value: bad"

    ordinary_group = click.Context(
        click.Group("ordinary", chain=False), info_name="ordinary", parent=chain_ctx
    )
    grandchild = click.Context(
        click.Command("leaf"), info_name="leaf", parent=ordinary_group
    )
    error.ctx = grandchild
    assert error.format_message() == "Invalid value: bad"

    command = click.Command("not-a-group")
    command.chain = True
    command_ctx = click.Context(command, info_name="not-a-group")
    error.ctx = click.Context(
        click.Command("leaf"), info_name="leaf", parent=command_ctx
    )
    assert error.format_message() == "Invalid value: bad"

# AC5
def test_direct_bad_parameter_is_not_classified_even_during_conversion():
    _, child_ctx = make_chain_contexts()

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("application failure", ctx=child_ctx)
    assert caught.value.format_message() == (
        "pipeline import: Invalid value: application failure"
    )

    direct = click.BadParameter("direct", ctx=child_ctx, param_hint="'--value'")
    assert direct.format_message() == "Invalid value for '--value': direct"

    class DirectFailure(click.ParamType):
        name = "direct"

        def convert(self, value, param, ctx):
            raise click.BadParameter("raised directly")

    @click.group(chain=True)
    def pipeline():
        pass

    @pipeline.command("import")
    @click.option("--value", type=DirectFailure())
    def import_command(value):
        pass

    result = CliRunner().invoke(
        pipeline, ["import", "--value", "x"], prog_name="pipeline"
    )
    assert result.exit_code == 2
    assert "Error: Invalid value for '--value': raised directly\n" in result.output
    assert "Error: pipeline import:" not in result.output

# AC5
def test_bad_parameter_init_signature_and_direct_construction():
    # BadParameter.__init__ must retain its signature and not classify direct errors.
    signature = inspect.signature(click.BadParameter.__init__)
    assert list(signature.parameters) == ["self", "message", "ctx", "param", "param_hint"]
    assert signature.parameters["message"].default is inspect.Parameter.empty
    for name in ("ctx", "param", "param_hint"):
        assert signature.parameters[name].default is None

    _, child_ctx = make_chain_contexts()
    param = click.Option(["--count"])
    direct = click.BadParameter("original")
    click.BadParameter.__init__(direct, "direct", child_ctx, param, ["--value", "-v"])
    assert direct.message == "direct"
    assert direct.ctx is child_ctx
    assert direct.param is param
    assert direct.param_hint == ["--value", "-v"]
    assert direct.format_message() == "Invalid value for '--value' / '-v': direct"

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("classified", param=param, ctx=child_ctx)
    assert caught.value.format_message() == (
        "pipeline import: Invalid value for '--count': classified"
    )

# AC6
def test_hints_localization_and_repeated_formatting(monkeypatch):
    import click.exceptions as exceptions

    _, child_ctx = make_chain_contexts()
    param = click.Option(["--count"])

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("bad input", param=param, ctx=child_ctx)
    error = caught.value
    expected = "pipeline import: Invalid value for '--count': bad input"
    assert error.format_message() == expected
    assert error.format_message() == expected
    assert error.exit_code == 2
    assert str(error) == "bad input"

    error.param_hint = ["--other", "-o"]
    assert error.format_message() == (
        "pipeline import: Invalid value for '--other' / '-o': bad input"
    )
    error.param_hint = "CUSTOM"
    assert error.format_message() == "pipeline import: Invalid value for CUSTOM: bad input"

    translations = {
        "Invalid value for {param_hint}: {message}": (
            "Valeur incorrecte pour {param_hint}: {message}"
        ),
        "Invalid value: {message}": "Valeur incorrecte: {message}",
        "Error: {message}": "Erreur: {message}",
    }
    monkeypatch.setattr(exceptions, "_", lambda text: translations.get(text, text))
    assert error.format_message() == (
        "pipeline import: Valeur incorrecte pour CUSTOM: bad input"
    )
    output = io.StringIO()
    error.show(file=output)
    assert output.getvalue().endswith(
        "Erreur: pipeline import: Valeur incorrecte pour CUSTOM: bad input\n"
    )
    error.param_hint = None
    error.param = None
    assert error.format_message() == "pipeline import: Valeur incorrecte: bad input"

# AC6
def test_parameter_returning_none_hint_keeps_existing_format():
    class NoneHintOption(click.Option):
        def get_error_hint(self, ctx):
            return None

    _, child_ctx = make_chain_contexts()
    param = NoneHintOption(["--value"])
    direct = click.BadParameter("bad", ctx=child_ctx, param=param)
    assert direct.format_message() == "Invalid value for None: bad"

    with pytest.raises(click.BadParameter) as caught:
        click.INT.fail("bad", param=param, ctx=child_ctx)
    assert caught.value.format_message() == (
        "pipeline import: Invalid value for None: bad"
    )

# AC6
def test_cli_error_keeps_usage_help_and_status():
    @click.group(chain=True)
    def pipeline():
        pass

    @pipeline.command("import")
    @click.option("--count", type=int)
    def import_command(count):
        pass

    runner = CliRunner()
    result = runner.invoke(
        pipeline, ["import", "--count", "nope"], prog_name="pipeline"
    )
    assert result.exit_code == 2
    assert result.output == (
        "Usage: pipeline import [OPTIONS]\n"
        "Try 'pipeline import --help' for help.\n"
        "\n"
        "Error: pipeline import: Invalid value for '--count': "
        "'nope' is not a valid integer.\n"
    )

    help_result = runner.invoke(pipeline, ["import", "--help"], prog_name="pipeline")
    assert help_result.exit_code == 0
    assert help_result.output.startswith("Usage: pipeline import [OPTIONS]\n")
    assert "--count INTEGER" in help_result.output
    assert "Error:" not in help_result.output

# AC7
def test_click_attaches_context_and_parameter_to_custom_failure():
    class ContextlessFailure(click.ParamType):
        name = "contextless"

        def convert(self, value, param, ctx):
            self.fail("custom rejection")

    @click.group(chain=True)
    def pipeline():
        pass

    @pipeline.command("import")
    @click.option("--value", type=ContextlessFailure())
    def import_command(value):
        pass

    result = CliRunner().invoke(
        pipeline, ["import", "--value", "x"], prog_name="pipeline"
    )
    assert result.exit_code == 2
    assert (
        "Error: pipeline import: Invalid value for '--value': custom rejection\n"
    ) in result.output

    @click.command()
    @click.option("--value", type=ContextlessFailure())
    def ordinary(value):
        pass

    ordinary_result = CliRunner().invoke(
        ordinary, ["--value", "x"], prog_name="ordinary"
    )
    assert ordinary_result.exit_code == 2
    assert "Error: Invalid value for '--value': custom rejection\n" in ordinary_result.output
    assert "Error: ordinary:" not in ordinary_result.output

# AC7
def test_group_parameter_and_missing_parameter_keep_existing_errors():
    @click.group(chain=True)
    @click.option("--count", type=int)
    def pipeline(count):
        pass

    @pipeline.command("import")
    @click.option("--required", required=True)
    def import_command(required):
        pass

    @pipeline.command("export")
    @click.option("--count", type=int)
    def export_command(count):
        pass

    runner = CliRunner()
    child = runner.invoke(
        pipeline, ["export", "--count", "nope"], prog_name="pipeline"
    )
    assert (
        "Error: pipeline export: Invalid value for '--count': "
        "'nope' is not a valid integer.\n"
    ) in child.output

    group = runner.invoke(
        pipeline, ["--count", "nope", "import"], prog_name="pipeline"
    )
    assert group.exit_code == 2
    assert "Error: Invalid value for '--count': 'nope' is not a valid integer.\n" in group.output

    missing = runner.invoke(pipeline, ["import"], prog_name="pipeline")
    assert missing.exit_code == 2
    assert "Error: Missing option '--required'.\n" in missing.output
    assert "Error: pipeline import:" not in missing.output
````
