# Mutually exclusive command-line options

- Task: `task_003_decorators_option_inter`
- Status: accepted
- Module: src/click/decorators.py
- Behaviour axis: option_interaction_or_precedence
- Interaction partner: src/click/__init__.py
- Files changed: src/click/__init__.py, src/click/core.py, src/click/decorators.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): 11 of 12 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 10 / 10, 0 regression failures, 1 attempt.

## instruction.md

The only file the agent under test sees.

# Mutually exclusive command-line options

## Problem Description

Add an `exclusive_options` decorator that declares a group of mutually exclusive option parameter names. A command may have multiple such groups. An invocation conflicts when at least two members of any one group were supplied on the command line, regardless of their parsed values.

The decorator must work on either side of `command` and interact correctly with Click's option parsing, parameter sources, command groups, and normal error handling.

## Acceptance Criteria

- **AC1**: `exclusive_options` can decorate either a callback before it becomes a command or an existing `Command`. Repeated applications declare independent groups, including overlapping groups.
- **AC2**: After successful parsing and before the affected command's callback runs, reject a group if at least two of its members have source `ParameterSource.COMMANDLINE`. Report all selected members of the first conflicting group, in that group's name order.
- **AC3**: Selection depends on parameter source, not value. Explicit false-valued flags, equal values, aliases, and repeated occurrences of one option are handled according to their resulting parameter sources; repeated occurrences of one member count as one member.
- **AC4**: Defaults, environment variables, default maps, and prompts do not count as command-line selections. When no group conflicts, invoke the callback normally.
- **AC5**: Groups belong only to the command on which they are declared. Parent and child commands, including commands with identically named parameters, are checked independently.
- **AC6**: Invalid declarations and unresolved option names produce the errors specified below. Options may be attached before or after the exclusivity decorator, provided they are present when invocation begins.
- **AC7**: Existing parsing errors and eager exits retain their normal behavior. A conflict does not invoke the affected command callback; it is handled as a Click `UsageError` in both standalone and non-standalone invocation modes.
- **AC8**: Add tests covering decorator order, multiple and overlapping groups, parameter sources, flags and aliases, invalid declarations, nested commands, and error handling.

## Interface

### Symbols

- `click.decorators.exclusive_options`
- `click.exclusive_options`
- `click.decorators.command`
- `click.command`
- `click.decorators.option`
- `click.option`
- `click.decorators.group`
- `click.group`

### Contract Details

`click.exclusive_options` and `click.decorators.exclusive_options` are the same public function:

- Signature: `exclusive_options(*names: str) -> Callable[[FC], FC]`, where `FC` is a callable or `Command` subtype, matching the existing `option` decorator's type-preserving convention.
- Each name is the exact Click option parameter name, such as `output_file`, not an option spelling such as `--output-file`. Names are case-sensitive.
- The returned decorator accepts a callback or `Command`, records one group, and returns the same object.
- A group requires at least two distinct, nonempty string names. At the call to `exclusive_options`:
  - Any non-string name raises `TypeError("Exclusive option names must be strings.")`.
  - Fewer than two names, an empty name, or a duplicate name raises `ValueError("An exclusive option group requires at least two distinct nonempty names.")`.
  - If both conditions apply, the `TypeError` takes precedence.
- At the start of an invocation, after the command's parameters have been assembled but before parsing, each declared name must match exactly one `Option` on that command by parameter name. Otherwise raise `ValueError("Exclusive option name '<name>' must match exactly one option.")`, substituting the offending name literally. Check groups in decorator application order and names in the order passed to the decorator.

For valid declarations:

- Groups are checked in decorator application order: the decorator applied first is checked first. Within a group, names are ordered as passed to `exclusive_options`.
- For the first conflicting group, raise `click.UsageError` associated with that command's context. Its message is exactly `Options are mutually exclusive: <names>.`, where `<names>` is the conflicting parameter names joined by `, ` in group order. For example, a group declared with names `alpha`, `beta`, `gamma` and all three selected has the message `Options are mutually exclusive: alpha, beta, gamma.`.
- Standalone invocation uses Click's normal usage-error rendering and exit status. With `standalone_mode=False`, the `UsageError` propagates.
- The conflict check applies to normal command-line invocation after parsing. Parsing a context without invoking its command does not itself raise a conflict. Direct programmatic callback invocation through `Context.invoke` is outside this conflict-check contract.
- Parameter callbacks and other parsing behavior retain their existing timing. A parse error or eager exit that prevents invocation takes precedence over conflict checking.

Existing decorator interfaces remain unchanged, including their existing overloads and public aliases:

- `command(name: str | Callable[..., Any] | None = None, cls: type[CmdType] | None = None, **attrs: Any) -> Command | Callable[[Callable[..., Any]], Command | CmdType]`
- `option(*param_decls: str, cls: type[Option] | None = None, **attrs: Any) -> Callable[[FC], FC]`
- `group(name: str | Callable[..., Any] | None = None, cls: type[GrpType] | None = None, **attrs: Any) -> Group | Callable[[Callable[..., Any]], Group | GrpType]`

The new decorator also applies to `Group` instances and group callbacks under the same rules.

## Compatibility & Out of Scope

- Do not change the existing signatures or ordinary behavior of `command`, `option`, or `group` for commands without exclusive groups.
- Custom command classes that bypass Click's normal parsing or invocation behavior are outside scope.
- This feature does not require changes to help text or support for mutually exclusive arguments.
- Preserve existing startup import constraints; do not introduce eager top-level standard-library imports that violate them.
- The entire existing repository test suite must continue to pass with zero regressions.

## Requirements and their tests

| Requirement | Text | Tests |
| --- | --- | --- |
| AC1 | `exclusive_options` can decorate either a callback before it becomes a command or an existing `Command`. Repeated applications declare independent groups, including overlapping groups. | test_factory_returns_decorator_and_preserves_identity, test_decorator_identity_order_and_overlapping_groups |
| AC2 | After successful parsing and before the affected command's callback runs, reject a group if at least two of its members have source `ParameterSource.COMMANDLINE`. Report all selected members of the first conflicting group, in that group's name order. | test_conflict_reports_all_selected_in_group_order_after_parsing |
| AC3 | Selection depends on parameter source, not value. Explicit false-valued flags, equal values, aliases, and repeated occurrences of one option are handled according to their resulting parameter sources; repeated occurrences of one member count as one member. | test_sources_not_values_aliases_and_repeated_options |
| AC4 | Defaults, environment variables, default maps, and prompts do not count as command-line selections. When no group conflicts, invoke the callback normally. | test_non_commandline_sources_do_not_conflict |
| AC5 | Groups belong only to the command on which they are declared. Parent and child commands, including commands with identically named parameters, are checked independently. | test_parent_and_child_groups_are_independent |
| AC6 | Invalid declarations and unresolved option names produce the errors specified below. Options may be attached before or after the exclusivity decorator, provided they are present when invocation begins. | test_invalid_declarations_and_type_error_precedence, test_unresolved_names_validation_and_late_options |
| AC7 | Existing parsing errors and eager exits retain their normal behavior. A conflict does not invoke the affected command callback; it is handled as a Click `UsageError` in both standalone and non-standalone invocation modes. | test_parsing_errors_eager_exits_and_usage_error_modes |
| AC8 | Add tests covering decorator order, multiple and overlapping groups, parameter sources, flags and aliases, invalid declarations, nested commands, and error handling. | test_group_decorator_on_existing_group_and_child_without_group |

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

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_none_flip | src/click/core.py: if groups is None: -> if groups is not None: | yes |
| M02_eq_to_neq | src/click/core.py: isinstance(param, Option) and param.name == name -> isinstance(param, Option) and param.name != name | yes |
| M03_neq_to_eq | src/click/core.py: ) != 1: -> ) == 1: | yes |
| M04_raise_remove | src/click/core.py: raise ValueError( -> pass | yes |
| M05_return_val_none | src/click/core.py: return original_parse_args(ctx, args) -> return None | yes |
| M06_raise_remove | src/click/core.py: raise UsageError( -> pass | yes |
| M07_return_val_none | src/click/core.py: return original_invoke(ctx) -> return None | yes |
| M08_raise_remove | src/click/decorators.py: raise TypeError("Exclusive option names must be strings.") -> pass | yes |
| M09_neq_to_eq | src/click/decorators.py: if len(names) < 2 or any(not name for name in names) or len(set(names)) != len(names): -> if len(names) < 2 or any(not name for name in names) or len(set(names)) == len(names): | yes |
| M10_raise_remove | src/click/decorators.py: raise ValueError( -> pass | yes |
| M11_return_val_none | src/click/decorators.py: return f -> return None | yes |
| M12_return_val_none | src/click/decorators.py: return decorator -> return None | no |

## Reference patch

````diff
diff --git a/src/click/__init__.py b/src/click/__init__.py
index a34ab02..bd68eb1 100644
--- a/src/click/__init__.py
+++ b/src/click/__init__.py
@@ -19,6 +19,7 @@ from .decorators import argument as argument
 from .decorators import command as command
 from .decorators import confirmation_option as confirmation_option
 from .decorators import custom_version_option as custom_version_option
+from .decorators import exclusive_options as exclusive_options
 from .decorators import group as group
 from .decorators import help_option as help_option
 from .decorators import make_pass_decorator as make_pass_decorator
diff --git a/src/click/core.py b/src/click/core.py
index e4b6b57..e6c7405 100644
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -99,6 +99,54 @@ def _check_nested_chain(
     raise RuntimeError(message)
 
 
+def _add_exclusive_options(command: Command, names: tuple[str, ...]) -> None:
+    """Attach an exclusive group to a command's parsing and invocation."""
+    groups = getattr(command, "_exclusive_option_groups", None)
+
+    if groups is None:
+        groups = []
+        command._exclusive_option_groups = groups
+        original_parse_args = command.parse_args
+        original_invoke = command.invoke
+
+        def parse_args(ctx: Context, args: list[str]) -> list[str]:
+            params = command.get_params(ctx)
+
+            for group in groups:
+                for name in group:
+                    if sum(
+                        isinstance(param, Option) and param.name == name
+                        for param in params
+                    ) != 1:
+                        raise ValueError(
+                            f"Exclusive option name '{name}' must match exactly one"
+                            " option."
+                        )
+
+            return original_parse_args(ctx, args)
+
+        def invoke(ctx: Context) -> t.Any:
+            for group in groups:
+                selected = [
+                    name
+                    for name in group
+                    if ctx.get_parameter_source(name) is ParameterSource.COMMANDLINE
+                ]
+
+                if len(selected) >= 2:
+                    raise UsageError(
+                        f"Options are mutually exclusive: {', '.join(selected)}.",
+                        ctx,
+                    )
+
+            return original_invoke(ctx)
+
+        command.parse_args = parse_args  # type: ignore[method-assign]
+        command.invoke = invoke  # type: ignore[method-assign]
+
+    groups.append(names)
+
+
 def _echo_aborted() -> None:
     """Write the final abort message to standard error."""
     echo(_("Aborted!"), file=sys.stderr)
diff --git a/src/click/decorators.py b/src/click/decorators.py
index 0c7b6c4..3fc8b11 100644
--- a/src/click/decorators.py
+++ b/src/click/decorators.py
@@ -5,6 +5,7 @@ import typing as t
 from functools import update_wrapper
 from gettext import gettext as _
 
+from .core import _add_exclusive_options
 from .core import Argument
 from .core import Command
 from .core import Context
@@ -246,6 +247,10 @@ def command(
                 cmd_name = cmd_left
 
         cmd = cls(name=cmd_name, callback=f, params=params, **attrs)
+
+        for names in getattr(f, "__click_exclusive_options__", ()):
+            _add_exclusive_options(cmd, names)
+
         cmd.__doc__ = f.__doc__
         return cmd
 
@@ -349,6 +354,34 @@ def argument(
     return decorator
 
 
+def exclusive_options(*names: str) -> t.Callable[[FC], FC]:
+    """Declare option parameter names that cannot be selected together.
+
+    The decorator may be applied to a callback or an existing command.
+    Multiple applications declare independent groups.
+    """
+    if any(not isinstance(name, str) for name in names):
+        raise TypeError("Exclusive option names must be strings.")
+
+    if len(names) < 2 or any(not name for name in names) or len(set(names)) != len(names):
+        raise ValueError(
+            "An exclusive option group requires at least two distinct nonempty names."
+        )
+
+    def decorator(f: FC) -> FC:
+        if isinstance(f, Command):
+            _add_exclusive_options(f, names)
+        else:
+            if not hasattr(f, "__click_exclusive_options__"):
+                f.__click_exclusive_options__ = []  # type: ignore
+
+            f.__click_exclusive_options__.append(names)  # type: ignore
+
+        return f
+
+    return decorator
+
+
 def option(
     *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any
 ) -> t.Callable[[FC], FC]:
````

## Feature tests

### tests/feature/test_exclusive_options.py

````python
# TEST_CODE
from __future__ import annotations

import click
import pytest
from click.testing import CliRunner

# AC1
def test_factory_returns_decorator_and_preserves_identity():
    decorator = click.exclusive_options("alpha", "beta")
    assert callable(decorator)

    def callback(alpha, beta):
        return alpha, beta

    assert decorator(callback) is callback
    cmd = click.command()(callback)
    assert click.exclusive_options("alpha", "beta")(cmd) is cmd

# AC1
def test_decorator_identity_order_and_overlapping_groups():
    assert click.exclusive_options is click.decorators.exclusive_options

    def callback(alpha, beta, gamma):
        click.echo(f"{alpha},{beta},{gamma}")

    original = callback
    callback = click.exclusive_options("gamma", "beta")(callback)
    assert callback is original
    callback = click.exclusive_options("alpha", "beta")(callback)
    callback = click.option("--alpha", is_flag=True)(callback)
    callback = click.option("--beta", is_flag=True)(callback)
    callback = click.option("--gamma", is_flag=True)(callback)
    cmd = click.command()(callback)
    assert click.exclusive_options("alpha", "gamma")(cmd) is cmd

    runner = CliRunner()
    result = runner.invoke(cmd, ["--alpha", "--beta", "--gamma"])
    assert result.exit_code == 2
    assert "Options are mutually exclusive: gamma, beta." in result.output
    result = runner.invoke(cmd, ["--alpha", "--beta"])
    assert "Options are mutually exclusive: alpha, beta." in result.output
    result = runner.invoke(cmd, ["--alpha", "--gamma"])
    assert "Options are mutually exclusive: alpha, gamma." in result.output
    result = runner.invoke(cmd, ["--gamma"])
    assert result.exit_code == 0
    assert result.output == "False,False,True\n"

# AC2
def test_conflict_reports_all_selected_in_group_order_after_parsing():
    events = []

    def record(ctx, param, value):
        if value:
            events.append(param.name)
        return value

    @click.command()
    @click.exclusive_options("third", "first", "second")
    @click.option("--first", is_flag=True, callback=record)
    @click.option("--second", is_flag=True, callback=record)
    @click.option("--third", is_flag=True, callback=record)
    def cmd(first, second, third):
        events.append("callback")

    runner = CliRunner()
    result = runner.invoke(
        cmd, ["--second", "--first", "--third"], standalone_mode=False
    )
    assert isinstance(result.exception, click.UsageError)
    assert result.exception.message == (
        "Options are mutually exclusive: third, first, second."
    )
    assert result.exception.ctx.command is cmd
    assert events == ["second", "first", "third"]

    with cmd.make_context("cmd", ["--first", "--second"]) as ctx:
        assert ctx.get_parameter_source("first") is click.ParameterSource.COMMANDLINE
        assert ctx.get_parameter_source("second") is click.ParameterSource.COMMANDLINE
        with pytest.raises(click.UsageError) as exc:
            cmd.invoke(ctx)
        assert exc.value.message == "Options are mutually exclusive: first, second."

# AC3
def test_sources_not_values_aliases_and_repeated_options():
    calls = []

    @click.command()
    @click.exclusive_options("enabled", "name", "hidden")
    @click.option("--enabled/--no-enabled", default=True)
    @click.option("-n", "--name", default="same")
    @click.option("--hidden", is_flag=True, expose_value=False)
    def cmd(enabled, name):
        calls.append((enabled, name))

    runner = CliRunner()
    result = runner.invoke(cmd, ["--no-enabled", "-n", "same"])
    assert result.exit_code == 2
    assert "Options are mutually exclusive: enabled, name." in result.output
    assert calls == []

    result = runner.invoke(cmd, ["-n", "first", "--name", "same"])
    assert result.exit_code == 0
    assert calls == [(True, "same")]
    result = runner.invoke(cmd, ["--no-enabled", "--hidden"])
    assert result.exit_code == 2
    assert "Options are mutually exclusive: enabled, hidden." in result.output
    result = runner.invoke(cmd, ["--enabled", "--no-enabled"])
    assert result.exit_code == 0
    assert calls[-1] == (False, "same")

# AC4
def test_non_commandline_sources_do_not_conflict():
    seen = []

    @click.command()
    @click.exclusive_options("alpha", "beta", "gamma", "delta")
    @click.option("--alpha", default="default")
    @click.option("--beta", envvar="EXCLUSIVE_TEST_BETA")
    @click.option("--gamma")
    @click.option("--delta", prompt=True)
    @click.pass_context
    def cmd(ctx, alpha, beta, gamma, delta):
        seen.append(
            (
                (alpha, beta, gamma, delta),
                tuple(
                    ctx.get_parameter_source(name)
                    for name in ("alpha", "beta", "gamma", "delta")
                ),
            )
        )

    runner = CliRunner()
    result = runner.invoke(
        cmd,
        ["--alpha", "cli"],
        env={"EXCLUSIVE_TEST_BETA": "env"},
        default_map={"gamma": "map"},
        input="prompted\n",
    )
    assert result.exit_code == 0, result.output
    assert seen[-1] == (
        ("cli", "env", "map", "prompted"),
        (
            click.ParameterSource.COMMANDLINE,
            click.ParameterSource.ENVIRONMENT,
            click.ParameterSource.DEFAULT_MAP,
            click.ParameterSource.PROMPT,
        ),
    )

    result = runner.invoke(
        cmd,
        [],
        env={"EXCLUSIVE_TEST_BETA": "env"},
        default_map={"gamma": "map"},
        input="prompted\n",
    )
    assert result.exit_code == 0
    assert seen[-1][1][0] is click.ParameterSource.DEFAULT
    result = runner.invoke(
        cmd, ["--alpha", "x", "--beta", "y"], input="prompted\n"
    )
    assert result.exit_code == 2
    assert len(seen) == 2

# AC5
def test_parent_and_child_groups_are_independent():
    events = []

    @click.group()
    @click.exclusive_options("alpha", "beta")
    @click.option("--alpha", is_flag=True)
    @click.option("--beta", is_flag=True)
    def root(alpha, beta):
        events.append(("parent", alpha, beta))

    @root.command()
    @click.exclusive_options("alpha", "beta")
    @click.option("--alpha", is_flag=True)
    @click.option("--beta", is_flag=True)
    def child(alpha, beta):
        events.append(("child", alpha, beta))

    runner = CliRunner()
    result = runner.invoke(root, ["--alpha", "child", "--beta"])
    assert result.exit_code == 0
    assert events == [("parent", True, False), ("child", False, True)]

    events.clear()
    result = runner.invoke(root, ["--alpha", "--beta", "child"])
    assert result.exit_code == 2
    assert "Options are mutually exclusive: alpha, beta." in result.output
    assert events == []

    result = runner.invoke(root, ["--alpha", "child", "--alpha", "--beta"])
    assert result.exit_code == 2
    assert "Options are mutually exclusive: alpha, beta." in result.output
    assert events == [("parent", True, False)]

# AC6
def test_invalid_declarations_and_type_error_precedence():
    value_message = (
        "An exclusive option group requires at least two distinct nonempty names."
    )
    for names in [(), ("one",), ("", "two"), ("one", "one")]:
        with pytest.raises(ValueError) as exc:
            click.exclusive_options(*names)
        assert str(exc.value) == value_message

    for names in [(1,), ("", 1), ("one", "one", None)]:
        with pytest.raises(TypeError) as exc:
            click.exclusive_options(*names)
        assert str(exc.value) == "Exclusive option names must be strings."

# AC6
def test_unresolved_names_validation_and_late_options():
    runner = CliRunner()

    @click.command()
    @click.exclusive_options("--alpha", "beta")
    @click.option("--alpha")
    @click.option("--beta")
    def spelling(alpha, beta):
        pass

    result = runner.invoke(spelling, ["--help"])
    assert isinstance(result.exception, ValueError)
    assert str(result.exception) == (
        "Exclusive option name '--alpha' must match exactly one option."
    )

    @click.command()
    @click.exclusive_options("missing_second", "other")
    @click.exclusive_options("Missing", "missing_first")
    @click.option("--other")
    def ordered(other):
        pass

    result = runner.invoke(ordered, [])
    assert str(result.exception) == (
        "Exclusive option name 'Missing' must match exactly one option."
    )

    @click.command()
    @click.exclusive_options("alpha", "beta")
    @click.argument("alpha")
    @click.option("--beta")
    def argument_only(alpha, beta):
        pass

    result = runner.invoke(argument_only, ["value"])
    assert str(result.exception) == (
        "Exclusive option name 'alpha' must match exactly one option."
    )

    duplicate = click.Command(
        "duplicate",
        params=[
            click.Option(["--alpha"]),
            click.Option(["--other", "alpha"]),
            click.Option(["--beta"]),
        ],
    )
    click.exclusive_options("alpha", "beta")(duplicate)
    result = runner.invoke(duplicate, [])
    assert str(result.exception) == (
        "Exclusive option name 'alpha' must match exactly one option."
    )

    @click.exclusive_options("alpha", "beta")
    @click.command()
    def late(alpha, beta):
        click.echo(f"{alpha}:{beta}")

    click.option("--alpha")(late)
    click.option("--beta")(late)
    result = runner.invoke(late, ["--alpha", "a"])
    assert result.exit_code == 0
    assert result.output == "a:None\n"
    result = runner.invoke(late, ["--alpha", "a", "--beta", "b"])
    assert result.exit_code == 2

# AC7
def test_parsing_errors_eager_exits_and_usage_error_modes():
    calls = []

    @click.command()
    @click.exclusive_options("alpha", "beta")
    @click.option("--alpha", is_flag=True)
    @click.option("--beta", is_flag=True)
    @click.option("--count", type=int)
    def cmd(alpha, beta, count):
        calls.append((alpha, beta, count))

    runner = CliRunner()
    result = runner.invoke(cmd, ["--alpha", "--beta", "--count", "bad"])
    assert result.exit_code == 2
    assert "Invalid value for '--count'" in result.output
    assert "mutually exclusive" not in result.output

    result = runner.invoke(cmd, ["--alpha", "--beta", "--help"])
    assert result.exit_code == 0
    assert "Usage:" in result.output
    assert "mutually exclusive" not in result.output

    result = runner.invoke(cmd, ["--alpha", "--beta"])
    assert result.exit_code == 2
    assert "Usage:" in result.output
    assert "Error: Options are mutually exclusive: alpha, beta." in result.output
    assert calls == []

    with pytest.raises(click.UsageError) as exc:
        cmd.main(
            args=["--alpha", "--beta"],
            prog_name="example",
            standalone_mode=False,
        )
    assert exc.value.message == "Options are mutually exclusive: alpha, beta."
    assert exc.value.ctx.command is cmd
    assert calls == []

# AC8
def test_group_decorator_on_existing_group_and_child_without_group():
    events = []

    @click.exclusive_options("left", "right")
    @click.group()
    @click.option("--left", is_flag=True)
    @click.option("--right", is_flag=True)
    def root(left, right):
        events.append(("root", left, right))

    @root.command()
    @click.option("--left", is_flag=True)
    @click.option("--right", is_flag=True)
    def child(left, right):
        events.append(("child", left, right))

    runner = CliRunner()
    result = runner.invoke(root, ["--left", "child", "--left", "--right"])
    assert result.exit_code == 0
    assert events == [("root", True, False), ("child", True, True)]

    events.clear()
    result = runner.invoke(root, ["--left", "--right", "child"])
    assert result.exit_code == 2
    assert events == []
````
