# Limit invalid custom-type prompt attempts

- Task: `task_002_termui_custom_param`
- Status: accepted
- Module: src/click/termui.py
- Behaviour axis: custom_param_type
- Files changed: src/click/termui.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): 4 of 4 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 22 / 22, 0 regression failures, 1 attempt.

## instruction.md

The only file the agent under test sees.

# Limit invalid custom-type prompt attempts

## Problem Description

Add an optional limit to conversion failures in `click.prompt`. Callers should be able to stop prompting after a specified number of rejected values while retaining the existing error display and abort behavior.

The limit applies both to direct calls and to calls made from a decorated command callback. By default, retries remain unlimited.

## Acceptance Criteria

- **AC1**: `prompt` accepts the keyword-only `max_invalid_attempts` parameter. Its default, `None`, preserves existing unlimited conversion retries.
- **AC2**: When conversion raises `UsageError`, display the usual conversion error and count one failure. This applies to custom parameter types, built-in types, and an explicit `value_proc`.
- **AC3**: For a positive limit, raise `click.Abort` immediately after displaying the error for the failure that reaches the limit. Do not request another value.
- **AC4**: Count failures cumulatively for one `prompt` call. A successful conversion followed by a confirmation mismatch does not reset the count, and the mismatch itself does not count as a conversion failure.
- **AC5**: Reject a non-positive limit with the specified `ValueError` before displaying or requesting any prompt input.
- **AC6**: Preserve existing handling of empty input, defaults, confirmation, hidden input, output streams, interrupts, and exceptions other than conversion `UsageError`. A rejected default counts as a conversion failure.
- **AC7**: The limit works when `prompt` is called directly and when it is called from a decorated command callback. An uncaught `Abort` in a command follows Click's existing command-level abort handling.
- **AC8**: Add tests covering unlimited retries, the failure boundary, successful conversion before the boundary, cumulative failures across confirmation mismatches, invalid limits, custom types, `value_proc`, hidden input, and a decorated command callback.

## Interface

### Symbols

- `prompt`

### Contract Details

`click.prompt` and `click.termui.prompt` refer to the extended public function. Its existing positional parameters remain positional-or-keyword, in this order:

| Parameter | Type | Default |
|---|---|---|
| `text` | `str` | required |
| `default` | `V \| str \| None` | `None` |
| `hide_input` | `bool` | `False` |
| `confirmation_prompt` | `bool \| str` | `False` |
| `type` | `ParamType[V, str] \| type[V] \| None` | `None` |
| `value_proc` | `t.Callable[[str], V] \| None` | `None` |
| `prompt_suffix` | `str` | `": "` |
| `show_default` | `bool \| str` | `True` |
| `err` | `bool` | `False` |
| `show_choices` | `bool` | `True` |

The new parameter follows these parameters:

| Parameter | Kind | Type | Default |
|---|---|---|---|
| `max_invalid_attempts` | keyword-only | `int \| None` | `None` |

The implementation signature returns `V`. The existing overloads retain their return types and gain the same keyword-only parameter:

- The string overload uses `default: str | None = None`, `type: None = None`, and `value_proc: None = None`; it returns `str`.
- The generic overload uses the parameter types and defaults in the table above; it returns `V`.

For a non-positive `max_invalid_attempts`, raise `ValueError` with the exact message `max_invalid_attempts must be greater than 0`.

Each caught conversion `UsageError` retains the existing localized error format, `Error: {message}`, followed by a newline. The existing hidden-input masking and `err` stream selection apply, including on the final failure. After that error, the limit raises `click.Abort` without adding a new prompt-specific message. Normal command-level handling of an uncaught abort remains unchanged.

Document the new parameter and its failure-counting behavior in the public `prompt` documentation.

## Compatibility & Out of Scope

- This feature limits conversion failures, not confirmation mismatches or empty-input retries that do not invoke conversion.
- No new limit is added to declarative option prompting, `confirm`, or other prompt APIs.
- Behavior for values outside the annotated `int | None` parameter type is not specified by this task.
- Preserve existing startup and module-import behavior; do not introduce eager top-level standard-library imports that violate repository startup import constraints.
- The entire existing repository test suite must continue to pass with zero regressions.

## Requirements and their tests

| Requirement | Text | Tests |
| --- | --- | --- |
| AC1 | `prompt` accepts the keyword-only `max_invalid_attempts` parameter. Its default, `None`, preserves existing unlimited conversion retries. | test_public_signature_and_overloads, test_unlimited_retries_by_default_and_explicit_none |
| AC2 | When conversion raises `UsageError`, display the usual conversion error and count one failure. This applies to custom parameter types, built-in types, and an explicit `value_proc`. | test_custom_type_failures_are_displayed_and_counted, test_value_processor_usage_error_is_counted |
| AC3 | For a positive limit, raise `click.Abort` immediately after displaying the error for the failure that reaches the limit. Do not request another value. | test_builtin_type_aborts_after_final_error_without_another_read, test_success_before_boundary_and_counter_is_per_call |
| AC4 | Count failures cumulatively for one `prompt` call. A successful conversion followed by a confirmation mismatch does not reset the count, and the mismatch itself does not count as a conversion failure. | test_failures_accumulate_across_confirmation_mismatch, test_confirmation_mismatches_do_not_consume_limit |
| AC5 | Reject a non-positive limit with the specified `ValueError` before displaying or requesting any prompt input. | test_nonpositive_limit_rejected_before_input_or_output |
| AC6 | Preserve existing handling of empty input, defaults, confirmation, hidden input, output streams, interrupts, and exceptions other than conversion `UsageError`. A rejected default counts as a conversion failure. | test_empty_input_and_valid_default, test_rejected_default_counts_as_failure, test_hidden_input_masks_final_error_and_uses_stderr, test_input_interrupts_still_raise_abort, test_non_usage_error_from_processor_propagates |
| AC7 | The limit works when `prompt` is called directly and when it is called from a decorated command callback. An uncaught `Abort` in a command follows Click's existing command-level abort handling. | test_decorated_command_abort_and_success |
| AC8 | Add tests covering unlimited retries, the failure boundary, successful conversion before the boundary, cumulative failures across confirmation mismatches, invalid limits, custom types, `value_proc`, hidden input, and a decorated command callback. | test_documentation_describes_limit_and_counting |

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

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_not_none_flip | src/click/termui.py: if max_invalid_attempts is not None and max_invalid_attempts <= 0: -> if max_invalid_attempts is None and max_invalid_attempts <= 0: | yes |
| M02_raise_remove | src/click/termui.py: raise ValueError("max_invalid_attempts must be greater than 0") -> pass | yes |
| M03_is_not_none_flip | src/click/termui.py: if max_invalid_attempts is not None and invalid_attempts >= max_invalid_attempts: -> if max_invalid_attempts is None and invalid_attempts >= max_invalid_attempts: | yes |
| M04_raise_remove | src/click/termui.py: raise Abort() from None -> pass | yes |

## Reference patch

````diff
diff --git a/src/click/termui.py b/src/click/termui.py
index 8fe0085..5ea6435 100644
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -147,6 +147,8 @@ def prompt(
     show_default: bool | str = True,
     err: bool = False,
     show_choices: bool = True,
+    *,
+    max_invalid_attempts: int | None = None,
 ) -> str: ...
 
 
@@ -162,6 +164,8 @@ def prompt(
     show_default: bool | str = True,
     err: bool = False,
     show_choices: bool = True,
+    *,
+    max_invalid_attempts: int | None = None,
 ) -> V: ...
 
 
@@ -176,6 +180,8 @@ def prompt(
     show_default: bool | str = True,
     err: bool = False,
     show_choices: bool = True,
+    *,
+    max_invalid_attempts: int | None = None,
 ) -> V:
     """Prompts a user for input.  This is a convenience function that can
     be used to prompt a user for input later.
@@ -205,6 +211,11 @@ def prompt(
                          For example if type is a Choice of either day or week,
                          show_choices is true and text is "Group by" then the
                          prompt will be "Group by (day, week): ".
+    :param max_invalid_attempts: Maximum number of conversion failures before
+        raising :exc:`Abort`. The final conversion error is displayed first.
+        Failures are counted across confirmation mismatches; mismatches and
+        empty input that is not converted do not count. ``None`` allows
+        unlimited retries. A provided limit must be greater than zero.
 
     .. versionchanged:: 8.5.0
         Generically typed: the return type is narrowed by ``type``,
@@ -232,6 +243,9 @@ def prompt(
 
     """
 
+    if max_invalid_attempts is not None and max_invalid_attempts <= 0:
+        raise ValueError("max_invalid_attempts must be greater than 0")
+
     def prompt_func(text: str) -> str:
         f = hidden_prompt_func if hide_input else visible_prompt_func
         try:
@@ -257,6 +271,8 @@ def prompt(
 
         confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
 
+    invalid_attempts = 0
+
     while True:
         while True:
             value = prompt_func(prompt)
@@ -273,6 +289,9 @@ def prompt(
         except UsageError as e:
             message = _mask_hidden_input(e.message, value) if hide_input else e.message
             echo(_("Error: {message}").format(message=message), err=err)
+            invalid_attempts += 1
+            if max_invalid_attempts is not None and invalid_attempts >= max_invalid_attempts:
+                raise Abort() from None
             continue
         if not confirmation_prompt:
             return result
````

## Feature tests

### tests/feature/test_prompt_invalid_attempts.py

````python
# TEST_CODE
from __future__ import annotations

import inspect
import typing

import click
import click.termui
import pytest
from click.testing import CliRunner

def require_limit():
    assert "max_invalid_attempts" in inspect.signature(click.prompt).parameters

def supply(monkeypatch, values, *, hidden=False):
    remaining = iter(values)
    prompts = []

    def read(text):
        prompts.append(text)
        return next(remaining)

    name = "hidden_prompt_func" if hidden else "visible_prompt_func"
    monkeypatch.setattr(click.termui, name, read)
    return prompts

# AC1
def test_public_signature_and_overloads():
    require_limit()
    assert click.prompt is click.termui.prompt
    signature = inspect.signature(click.prompt)
    names = list(signature.parameters)
    assert names == [
        "text",
        "default",
        "hide_input",
        "confirmation_prompt",
        "type",
        "value_proc",
        "prompt_suffix",
        "show_default",
        "err",
        "show_choices",
        "max_invalid_attempts",
    ]
    assert all(
        signature.parameters[name].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
        for name in names[:-1]
    )
    parameter = signature.parameters["max_invalid_attempts"]
    assert parameter.kind is inspect.Parameter.KEYWORD_ONLY
    assert parameter.default is None
    assert typing.get_type_hints(click.prompt)["max_invalid_attempts"] == int | None

    get_overloads = getattr(typing, "get_overloads", None)
    if get_overloads is not None:
        overloads = get_overloads(click.prompt)
        assert len(overloads) == 2
        for overload in overloads:
            param = inspect.signature(overload).parameters["max_invalid_attempts"]
            assert param.kind is inspect.Parameter.KEYWORD_ONLY
            assert param.default is None
        assert typing.get_type_hints(overloads[0])["return"] is str
        assert typing.get_type_hints(overloads[1])["return"] == typing.get_type_hints(
            click.prompt
        )["return"]

    with pytest.raises(TypeError):
        click.prompt("Value", None, False, False, None, None, ": ", True, False, True, 1)

@pytest.mark.parametrize("explicit_none", [False, True])
# AC1
def test_unlimited_retries_by_default_and_explicit_none(
    monkeypatch, capsys, explicit_none
):
    require_limit()
    prompts = supply(monkeypatch, ["bad", "no", "wrong", "7"])
    kwargs = {"max_invalid_attempts": None} if explicit_none else {}
    assert click.prompt("Number", type=int, **kwargs) == 7
    assert prompts == ["Number: "] * 4
    assert capsys.readouterr().out == (
        "Error: 'bad' is not a valid integer.\n"
        "Error: 'no' is not a valid integer.\n"
        "Error: 'wrong' is not a valid integer.\n"
    )

# AC2
def test_custom_type_failures_are_displayed_and_counted(monkeypatch, capsys):
    require_limit()

    class EvenType(click.ParamType):
        name = "even"

        def convert(self, value, param, ctx):
            if value != "ok":
                self.fail(f"rejected {value}", param, ctx)
            return 2

    prompts = supply(monkeypatch, ["first", "second", "ok"])
    with pytest.raises(click.Abort):
        click.prompt("Even", type=EvenType(), max_invalid_attempts=2)
    assert prompts == ["Even: ", "Even: "]
    assert capsys.readouterr().out == "Error: rejected first\nError: rejected second\n"

# AC2
def test_value_processor_usage_error_is_counted(monkeypatch, capsys):
    require_limit()
    seen = []

    def process(value):
        seen.append(value)
        raise click.UsageError(f"cannot process {value}")

    prompts = supply(monkeypatch, ["x", "y", "unused"])
    with pytest.raises(click.Abort):
        click.prompt("Value", value_proc=process, max_invalid_attempts=2)
    assert seen == ["x", "y"]
    assert len(prompts) == 2
    assert capsys.readouterr().out == "Error: cannot process x\nError: cannot process y\n"

# AC3
def test_builtin_type_aborts_after_final_error_without_another_read(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["bad", "12"])
    with pytest.raises(click.Abort) as exc:
        click.prompt("Number", type=int, max_invalid_attempts=1)
    assert str(exc.value) == ""
    assert prompts == ["Number: "]
    captured = capsys.readouterr()
    assert captured.out == "Error: 'bad' is not a valid integer.\n"
    assert captured.err == ""

# AC3
def test_success_before_boundary_and_counter_is_per_call(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["bad", "5", "bad", "6"])
    assert click.prompt("Number", type=int, max_invalid_attempts=2) == 5
    assert click.prompt("Number", type=int, max_invalid_attempts=2) == 6
    assert prompts == ["Number: "] * 4
    assert capsys.readouterr().out == "Error: 'bad' is not a valid integer.\n" * 2

# AC4
def test_failures_accumulate_across_confirmation_mismatch(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["bad", "3", "4", "bad-again", "5"])
    with pytest.raises(click.Abort):
        click.prompt(
            "Number", type=int, confirmation_prompt=True, max_invalid_attempts=2
        )
    assert prompts == [
        "Number: ",
        "Number: ",
        "Repeat for confirmation: ",
        "Number: ",
    ]
    assert capsys.readouterr().out == (
        "Error: 'bad' is not a valid integer.\n"
        "Error: The two entered values do not match.\n"
        "Error: 'bad-again' is not a valid integer.\n"
    )

# AC4
def test_confirmation_mismatches_do_not_consume_limit(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["1", "2", "3", "4", "5", "5"])
    assert (
        click.prompt("Number", type=int, confirmation_prompt="Again", max_invalid_attempts=1)
        == 5
    )
    assert prompts == ["Number: ", "Again: "] * 3
    assert capsys.readouterr().out == "Error: The two entered values do not match.\n" * 2

@pytest.mark.parametrize("limit", [0, -1, -100])
# AC5
def test_nonpositive_limit_rejected_before_input_or_output(monkeypatch, capsys, limit):
    require_limit()
    prompts = supply(monkeypatch, ["unused"])
    with pytest.raises(ValueError, match="^max_invalid_attempts must be greater than 0$"):
        click.prompt("Number", type=int, max_invalid_attempts=limit)
    assert prompts == []
    captured = capsys.readouterr()
    assert captured.out == ""
    assert captured.err == ""

# AC6
def test_empty_input_and_valid_default(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["", "", "8", ""])
    assert click.prompt("Number", type=int, max_invalid_attempts=1) == 8
    assert click.prompt("Number", default=9, type=int, max_invalid_attempts=1) == 9
    assert prompts == ["Number: "] * 3 + ["Number [9]: "]
    assert capsys.readouterr().out == ""

# AC6
def test_rejected_default_counts_as_failure(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["", "", "10"])
    with pytest.raises(click.Abort):
        click.prompt("Number", default="bad", type=int, max_invalid_attempts=2)
    assert prompts == ["Number [bad]: "] * 2
    assert capsys.readouterr().out == "Error: 'bad' is not a valid integer.\n" * 2

# AC6
def test_hidden_input_masks_final_error_and_uses_stderr(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["secret", "unused"], hidden=True)

    def process(value):
        raise click.UsageError(f"rejected {value!r} and {value}")

    with pytest.raises(click.Abort):
        click.prompt(
            "Password",
            hide_input=True,
            value_proc=process,
            err=True,
            max_invalid_attempts=1,
        )
    assert prompts == ["Password: "]
    captured = capsys.readouterr()
    assert captured.out == ""
    assert captured.err == "Error: rejected '***' and '***'\n"
    assert "secret" not in captured.err

@pytest.mark.parametrize("hidden", [False, True])
@pytest.mark.parametrize("exception", [KeyboardInterrupt, EOFError])
# AC6
def test_input_interrupts_still_raise_abort(monkeypatch, capsys, hidden, exception):
    require_limit()
    calls = []

    def interrupt(text):
        calls.append(text)
        raise exception()

    name = "hidden_prompt_func" if hidden else "visible_prompt_func"
    monkeypatch.setattr(click.termui, name, interrupt)
    with pytest.raises(click.Abort):
        click.prompt("Value", hide_input=hidden, err=True, max_invalid_attempts=2)
    assert calls == ["Value: "]
    captured = capsys.readouterr()
    assert captured.out == ""
    assert captured.err == ("\n" if hidden else "")

# AC6
def test_non_usage_error_from_processor_propagates(monkeypatch, capsys):
    require_limit()
    prompts = supply(monkeypatch, ["bad", "unused"])
    failure = RuntimeError()

    def process(value):
        raise failure

    with pytest.raises(RuntimeError) as exc:
        click.prompt("Value", value_proc=process, max_invalid_attempts=1)
    assert exc.value is failure
    assert prompts == ["Value: "]
    captured = capsys.readouterr()
    assert captured.out == ""
    assert captured.err == ""

# AC7
def test_decorated_command_abort_and_success():
    require_limit()

    @click.command()
    @click.option("--limit", type=int, default=2)
    @click.pass_context
    def command(ctx, limit):
        value = click.prompt("Number", type=int, max_invalid_attempts=limit)
        click.echo(f"{ctx.command.name}: {value}")

    runner = CliRunner()
    result = runner.invoke(command, ["--limit", "1"], input="bad\n12\n")
    assert result.exit_code == 1
    assert "Error: 'bad' is not a valid integer.\n" in result.output
    assert "Aborted!" in result.output
    assert result.output.count("Number: ") == 1
    assert "command: 12" not in result.output

    result = runner.invoke(command, input="bad\n12\n")
    assert result.exit_code == 0
    assert "Error: 'bad' is not a valid integer.\n" in result.output
    assert "command: 12\n" in result.output
    assert "Aborted!" not in result.output

# AC8
def test_documentation_describes_limit_and_counting():
    require_limit()
    doc = inspect.getdoc(click.prompt)
    assert doc is not None
    assert "max_invalid_attempts" in doc
    assert "conversion failures" in doc
    assert "confirmation mismatches" in doc
    assert "unlimited retries" in doc
````
