# Share Confirmed Answers Across a Command Chain

- Task: `task_008_termui_context_or_c`
- Status: rejected
- Module: src/click/termui.py
- Behaviour axis: context_or_command_chaining
- Interaction partner: src/click/core.py
- Files changed: src/click/core.py, src/click/termui.py
- Repairs: 1

**Stopped at G7 Blind solve:** G7 solver inconclusive after retry (empty solver patch; patch application/synthesis error: FIND block not matched verbatim in src/click/termui.py: '    while True:\n        # Write the prompt separately so that ; empty failure_output; empty attempts_log)

## 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 | failed |

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

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

Blind solve (G7): reward 0.0, fail-to-pass undefined / undefined, undefined regression failures, 0 attempts.

## requirements.md

Rejected tasks are never packaged, so there is no instruction.md.

# Share Confirmed Answers Across a Command Chain

## Problem Description

Add an opt-in confirmation cache shared by commands in one Click context chain. A root command enables it through `context_settings={"cache_confirmations": True}`. While that root context is active, calls to `confirm` reuse explicit yes/no answers for the same question text.

The cache belongs to the root context, not to an individual command. It is discarded when that context closes. Outside an enabled root context, `confirm` retains its existing behavior.

## Acceptance Criteria

- **AC1**: A root command can enable confirmation caching with the `cache_confirmations` context setting. The default is disabled.
- **AC2**: Within an enabled root context, an explicit valid answer to `confirm` is cached by the exact `text` argument. Subsequent calls with the same text return that answer without prompting or writing prompt output.
- **AC3**: The answer is shared across the root and its descendant contexts, including separate commands in a chained command invocation. Closing a descendant context does not discard the root's cache.
- **AC4**: An explicit negative answer is cached even when the call that receives it raises `Abort` because `abort=True`. A cached negative answer also raises `Abort` when a later call has `abort=True`; it returns `False` when that call has `abort=False`.
- **AC5**: An answer selected by pressing Enter for a default is not cached, including when it causes an abort. Invalid input is not cached and continues to produce the existing error and retry behavior. A later explicit valid answer after invalid input is cached.
- **AC6**: Cache keys are case-sensitive exact question text. Other `confirm` arguments do not distinguish cache entries. A cached answer takes precedence over a later call's default and display settings.
- **AC7**: Closing the root context discards its cached answers. A subsequent invocation or independently rooted context starts with an empty cache. Calls without an active enabled root context behave as before.
- **AC8**: Add tests covering enabled and disabled roots, chained commands, positive and negative answers, default and invalid input, abort behavior, exact-text keys, and cache cleanup.

## Interface

### Symbols

- `click.confirm`
- `click.core.Context`
- `click.core.Context.__init__`

### Contract Details

- `click.confirm(text: str, default: bool | None = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False) -> bool`
  - Its signature remains unchanged.
  - Explicit input is recognized using the existing case-insensitive, whitespace-stripped forms: `y` and `yes` mean `True`; `n` and `no` mean `False`.
  - An empty stripped input uses a non-`None` default without caching it. With `default=None`, it remains invalid input.
  - Invalid input emits the existing localized message `Error: invalid input` followed by a newline, to the stream selected by `err`, and retries.
  - A cache hit performs no input read and emits no prompt or confirmation output, regardless of `prompt_suffix`, `show_default`, or `err`.
  - A negative result with `abort=True` raises `click.exceptions.Abort()` with no message, whether the result is newly entered, defaulted, or cached. Existing interruption and EOF behavior remains unchanged.

- `click.core.Context.__init__(self, command: Command, parent: Context | None = None, info_name: str | None = None, obj: t.Any | None = None, auto_envvar_prefix: str | None = None, default_map: cabc.MutableMapping[str, t.Any] | None = None, terminal_width: int | None = None, max_content_width: int | None = None, resilient_parsing: bool = False, allow_extra_args: bool | None = None, allow_interspersed_args: bool | None = None, ignore_unknown_options: bool | None = None, help_option_names: list[str] | None = None, token_normalize_func: t.Callable[[str], str] | None = None, color: bool | None = None, show_default: bool | None = None, cache_confirmations: bool = False) -> None`
  - `cache_confirmations` is also accepted through a command's existing `context_settings` mapping.
  - The root context's setting controls caching for its entire context chain. A descendant's setting neither enables caching for a disabled root nor disables caching for an enabled root.
  - The cache is scoped to the root context and is discarded when that root closes. If the same context is subsequently used again, it starts with no cached answers.
  - The supported setting values are `True` and `False`; behavior for other values is not part of this contract.

## Compatibility & Out of Scope

- Do not change the public `confirm` signature or the existing prompt formatting and input behavior on cache misses.
- Do not cache answers from `prompt` or its confirmation-prompt feature, persist answers across invocations, or add a public cache-management API.
- 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.

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_not_none_flip | src/click/termui.py: root = ctx.find_root() if ctx is not None else None -> root = ctx.find_root() if ctx is None else None | yes |
| M02_is_not_none_flip | src/click/termui.py: if root is not None and root._cache_confirmations -> if root is None and root._cache_confirmations | yes |
| M03_is_not_none_flip | src/click/termui.py: if cache is not None and text in cache: -> if cache is None and text in cache: | yes |
| M04_raise_remove | src/click/termui.py: raise Abort() -> pass | yes |
| M05_return_val_none | src/click/termui.py: return rv -> return None | yes |
| M06_is_not_none_flip | src/click/termui.py: if value and cache is not None: -> if value and cache is None: | yes |
| M07_is_not_none_flip | src/click/termui.py: assert root is not None -> assert root is None | yes |

## Reference patch

````diff
diff --git a/src/click/core.py b/src/click/core.py
index e4b6b57..cab1285 100644
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -280,6 +280,8 @@ class Context:
         value is not set, it defaults to the value from the parent
         context. ``Command.show_default`` overrides this default for the
         specific command.
+    :param cache_confirmations: Cache explicit confirmation answers for
+        the context chain. Only the root context's setting is used.
 
     .. versionchanged:: 8.2
         The ``protected_args`` attribute is deprecated and will be removed in
@@ -360,9 +362,12 @@ class Context:
         token_normalize_func: t.Callable[[str], str] | None = None,
         color: bool | None = None,
         show_default: bool | None = None,
+        cache_confirmations: bool = False,
     ) -> None:
         #: the parent context or `None` if none exists.
         self.parent = parent
+        self._cache_confirmations = cache_confirmations
+        self._confirmation_cache: dict[str, bool] = {}
         #: the :class:`Command` for this context.
         self.command = command
         #: the descriptive information name
diff --git a/src/click/termui.py b/src/click/termui.py
index 8fe0085..dda3552 100644
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -309,6 +309,9 @@ def confirm(
     :param err: if set to true the file defaults to ``stderr`` instead of
                 ``stdout``, the same as with echo.
 
+    An enabled root context shares explicit answers with its descendants.
+    Answers selected using a default are not cached.
+
     .. versionchanged:: 8.3.1
         A space is no longer appended to the prompt.
 
@@ -318,6 +321,22 @@ def confirm(
     .. versionadded:: 4.0
         Added the ``err`` parameter.
     """
+    from .globals import get_current_context
+
+    ctx = get_current_context(silent=True)
+    root = ctx.find_root() if ctx is not None else None
+    cache = (
+        root._confirmation_cache
+        if root is not None and root._cache_confirmations
+        else None
+    )
+
+    if cache is not None and text in cache:
+        rv = cache[text]
+        if abort and not rv:
+            raise Abort()
+        return rv
+
     prompt = _build_prompt(
         text,
         prompt_suffix,
@@ -339,6 +358,11 @@ def confirm(
         else:
             echo(_("Error: invalid input"), err=err)
             continue
+        if value and cache is not None:
+            if not cache:
+                assert root is not None
+                root.call_on_close(cache.clear)
+            cache[text] = rv
         break
     if abort and not rv:
         raise Abort()
````
