# Context-scoped idempotent help text

- Task: `task_007_globals_idempotency`
- Status: accepted
- Module: src/click/globals.py
- Behaviour axis: idempotency
- Interaction partner: src/click/formatting.py
- Files changed: src/click/formatting.py, src/click/globals.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): 3 of 3 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 9 / 9, 0 regression failures, 1 attempt.

## instruction.md

The only file the agent under test sees.

# Context-scoped idempotent help text

## Problem Description

Help formatters cannot currently suppress repeated text by key within a snapshot of the active context stack. Add a context-chain snapshot API and a formatter method that writes text once per key and context-chain identity.

## Acceptance Criteria

- **AC1**: `get_context_chain()` returns an immutable tuple containing the calling thread's active contexts in bottom-to-top stack order. It returns an empty tuple when no context is active, whether the stack has never been created or has been emptied.
- **AC2**: A snapshot retains the context objects present when it was taken and does not change when contexts are subsequently pushed or popped. Taking a snapshot does not modify the stack.
- **AC3**: For each formatter instance, `write_text_once` calls `write_text` on the first call for a given key and context chain. Subsequent calls for that pair do nothing, even when their text differs.
- **AC4**: Context chains are the same only when they have the same length and contain the same context objects by identity in the same order. Repeated occurrences of a context are significant. Context equality must not substitute for identity.
- **AC5**: Different chains have independent recorded keys. Returning to a previously used chain preserves its recorded keys, including for the empty chain. Records on one formatter do not affect another formatter.
- **AC6**: A direct call to `write_text` retains its existing behavior and neither consults nor changes the records used by `write_text_once`.
- **AC7**: If `write_text` raises during a `write_text_once` call, the exception propagates unchanged and that call does not record the key as written.
- **AC8**: Add tests covering snapshots, stack transitions, chain identity, formatter isolation, differing text for a repeated key, and failure of `write_text`. The entire existing repository test suite must continue to pass without regression.

## Interface

### Symbols

- `click.globals.get_current_context`
- `click.globals.push_context`
- `click.globals.pop_context`
- `click.globals.get_context_chain`
- `click.formatting.HelpFormatter.write_text`
- `click.formatting.HelpFormatter.write_text_once`

### Contract Details

- `get_current_context(silent: bool = False) -> Context | None`: Existing overload behavior remains unchanged: the default call returns a `Context` or raises `RuntimeError` with the exact message `There is no active click context.`; `silent=True` returns `None` when no context is active.
- `push_context(ctx: Context) -> None`: Existing stack behavior remains unchanged.
- `pop_context() -> None`: Existing stack behavior and exceptions remain unchanged.
- `get_context_chain() -> tuple[Context, ...]`: Returns the calling thread's stack snapshot as described above. It takes no parameters and does not raise merely because no context is active.
- `HelpFormatter.write_text(self, text: str) -> None`: Existing formatting and output behavior remains unchanged.
- `HelpFormatter.write_text_once(self, key: str, text: str) -> None`: Uses string equality for keys and context-object identity for chains. On a first call for the pair, it passes `text` to that formatter's `write_text`; otherwise it produces no output. An empty string is a valid key. No new validation exception or exception message is specified; exceptions from `write_text` propagate unchanged.

The chain used by `write_text_once` is the calling thread's chain at the time of the call. Sequential use of the same formatter from different threads with identical chains uses the same recorded pair.

## Compatibility & Out of Scope

- This task does not add a reset API or change existing `write_text` semantics.
- Concurrent or reentrant calls to the same formatter are outside the scope of this contract.
- Do not introduce eager top-level standard-library imports that violate the repository's existing startup import constraints.
- The entire existing repository test suite must continue to pass with zero regressions.

## Requirements and their tests

| Requirement | Text | Tests |
| --- | --- | --- |
| AC1 | `get_context_chain()` returns an immutable tuple containing the calling thread's active contexts in bottom-to-top stack order. It returns an empty tuple when no context is active, whether the stack has never been created or has been emptied. | test_empty_and_thread_local_context_chains |
| AC2 | A snapshot retains the context objects present when it was taken and does not change when contexts are subsequently pushed or popped. Taking a snapshot does not modify the stack. | test_snapshots_are_immutable_and_preserve_stack_order |
| AC3 | For each formatter instance, `write_text_once` calls `write_text` on the first call for a given key and context chain. Subsequent calls for that pair do nothing, even when their text differs. | test_write_text_once_dispatches_first_text_for_each_key |
| AC4 | Context chains are the same only when they have the same length and contain the same context objects by identity in the same order. Repeated occurrences of a context are significant. Context equality must not substitute for identity. | test_context_chains_use_ordered_identity_not_equality |
| AC5 | Different chains have independent recorded keys. Returning to a previously used chain preserves its recorded keys, including for the empty chain. Records on one formatter do not affect another formatter. | test_chain_transitions_and_formatter_isolation, test_sequential_threads_share_records_for_identical_chains |
| AC6 | A direct call to `write_text` retains its existing behavior and neither consults nor changes the records used by `write_text_once`. | test_direct_write_text_does_not_consult_or_change_once_records |
| AC7 | If `write_text` raises during a `write_text_once` call, the exception propagates unchanged and that call does not record the key as written. | test_write_text_failure_propagates_and_does_not_record_key |
| AC8 | Add tests covering snapshots, stack transitions, chain identity, formatter isolation, differing text for a repeated key, and failure of `write_text`. The entire existing repository test suite must continue to pass without regression. | test_help_command_uses_context_scoped_text |

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

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_not_none_flip | src/click/formatting.py: if record is not None and key in record[1]: -> if record is None and key in record[1]: | yes |
| M02_is_none_flip | src/click/formatting.py: if record is None: -> if record is not None: | yes |
| M03_return_val_none | src/click/globals.py: return tuple(_local.__dict__.get("stack", ())) -> return None | yes |

## Reference patch

````diff
diff --git a/src/click/formatting.py b/src/click/formatting.py
index c4aa2de..81ce8d5 100644
--- a/src/click/formatting.py
+++ b/src/click/formatting.py
@@ -142,6 +142,9 @@ class HelpFormatter:
         self.width = width
         self.current_indent = 0
         self.buffer = []
+        self._text_once: dict[
+            tuple[int, ...], tuple[tuple[object, ...], set[str]]
+        ] = {}
 
     def write(self, string: str) -> None:
         """Writes a unicode string into the internal buffer."""
@@ -226,6 +229,25 @@ class HelpFormatter:
         )
         self.write("\n")
 
+    def write_text_once(self, key: str, text: str) -> None:
+        """Write text once per key and active context chain."""
+        from .globals import get_context_chain
+
+        chain = get_context_chain()
+        identity = tuple(id(ctx) for ctx in chain)
+        record = self._text_once.get(identity)
+
+        if record is not None and key in record[1]:
+            return
+
+        self.write_text(text)
+
+        if record is None:
+            # Retain contexts so their identities cannot be reused.
+            self._text_once[identity] = (chain, {key})
+        else:
+            record[1].add(key)
+
     def write_dl(
         self,
         rows: cabc.Iterable[tuple[str, str]],
diff --git a/src/click/globals.py b/src/click/globals.py
index a2f9172..28b7827 100644
--- a/src/click/globals.py
+++ b/src/click/globals.py
@@ -41,6 +41,11 @@ def get_current_context(silent: bool = False) -> Context | None:
     return None
 
 
+def get_context_chain() -> tuple[Context, ...]:
+    """Return a snapshot of the active contexts, from bottom to top."""
+    return tuple(_local.__dict__.get("stack", ()))
+
+
 def push_context(ctx: Context) -> None:
     """Pushes a new context to the current stack."""
     _local.__dict__.setdefault("stack", []).append(ctx)
````

## Feature tests

### tests/feature/test_context_scoped_help.py

````python
# TEST_CODE
from __future__ import annotations

from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager

import click
import pytest
from click.globals import pop_context, push_context
from click.testing import CliRunner

@contextmanager
def pushed(ctx):
    push_context(ctx)
    try:
        yield
    finally:
        pop_context()

def make_context(name):
    return click.Context(click.Command(name))

# AC1
def test_empty_and_thread_local_context_chains():
    from click.globals import get_context_chain

    ctx = make_context("main")

    def fresh_thread():
        assert get_context_chain() == ()
        assert click.get_current_context(silent=True) is None
        with pytest.raises(
            RuntimeError, match=r"^There is no active click context\.$"
        ):
            click.get_current_context()
        with pytest.raises(AttributeError):
            pop_context()

        other = make_context("worker")
        push_context(other)
        try:
            chain = get_context_chain()
            assert isinstance(chain, tuple)
            assert len(chain) == 1
            assert chain[0] is other
            assert click.get_current_context() is other
        finally:
            pop_context()

        assert get_context_chain() == ()
        with pytest.raises(IndexError):
            pop_context()
        return chain

    with pushed(ctx):
        with ThreadPoolExecutor(max_workers=1) as executor:
            worker_chain = executor.submit(fresh_thread).result()
        assert worker_chain[0] is not ctx
        assert get_context_chain()[0] is ctx

    assert get_context_chain() == ()
    assert click.get_current_context(silent=True) is None

# AC2
def test_snapshots_are_immutable_and_preserve_stack_order():
    from click.globals import get_context_chain

    first = make_context("first")
    second = make_context("second")
    empty = get_context_chain()
    assert empty == ()

    with pushed(first):
        one = get_context_chain()
        assert len(one) == 1 and one[0] is first
        assert click.get_current_context() is first

        with pushed(second):
            two = get_context_chain()
            assert len(two) == 2
            assert two[0] is first and two[1] is second
            assert click.get_current_context() is second
            assert one[0] is first and len(one) == 1
            with pytest.raises(TypeError):
                two[0] = second

        assert get_context_chain()[0] is first
        assert len(get_context_chain()) == 1
        assert two[1] is second

    assert get_context_chain() == ()
    assert empty == ()
    assert one[0] is first
    assert two[0] is first and two[1] is second

# AC3
def test_write_text_once_dispatches_first_text_for_each_key():
    class RecordingFormatter(click.HelpFormatter):
        def __init__(self):
            super().__init__(width=80)
            self.calls = []

        def write_text(self, text):
            self.calls.append(text)
            super().write_text(text)

    formatter = RecordingFormatter()
    key = "".join(["same", "-key"])
    formatter.write_text_once(key, "first")
    formatter.write_text_once("same-key", "different")
    formatter.write_text_once("", "empty key")
    formatter.write_text_once("", "ignored")
    formatter.write_text_once("another", "another text")

    assert formatter.calls == ["first", "empty key", "another text"]
    assert formatter.getvalue() == "first\nempty key\nanother text\n"

# AC4
def test_context_chains_use_ordered_identity_not_equality():
    class EqualContext(click.Context):
        __hash__ = None

        def __eq__(self, other):
            return isinstance(other, EqualContext)

    a = EqualContext(click.Command("a"))
    b = EqualContext(click.Command("b"))
    assert a == b and a is not b
    formatter = click.HelpFormatter(width=80)

    with pushed(a):
        formatter.write_text_once("key", "a")
        with pushed(b):
            formatter.write_text_once("key", "a b")
            formatter.write_text_once("key", "ignored a b")
        with pushed(a):
            formatter.write_text_once("key", "a a")
        formatter.write_text_once("key", "ignored a")

    with pushed(b):
        formatter.write_text_once("key", "b")
        with pushed(a):
            formatter.write_text_once("key", "b a")
        with pushed(b):
            formatter.write_text_once("key", "b b")

    with pushed(a):
        with pushed(b):
            formatter.write_text_once("key", "still ignored a b")

    assert formatter.getvalue() == "a\na b\na a\nb\nb a\nb b\n"

# AC5
def test_chain_transitions_and_formatter_isolation():
    from click.globals import get_context_chain

    first = click.HelpFormatter(width=80)
    second = click.HelpFormatter(width=80)
    ctx = make_context("ctx")
    assert get_context_chain() == ()

    first.write_text_once("key", "empty first")
    second.write_text_once("key", "empty second")

    with pushed(ctx):
        first.write_text_once("key", "context first")
        second.write_text_once("key", "context second")
        first.write_text_once("key", "ignored in context")

    first.write_text_once("key", "ignored in empty")
    second.write_text_once("key", "also ignored in empty")
    with pushed(ctx):
        first.write_text_once("key", "ignored after return")
        first.write_text_once("new", "new in context")

    assert first.getvalue() == "empty first\ncontext first\nnew in context\n"
    assert second.getvalue() == "empty second\ncontext second\n"

# AC5
def test_sequential_threads_share_records_for_identical_chains():
    from click.globals import get_context_chain

    formatter = click.HelpFormatter(width=80)
    ctx = make_context("shared")
    formatter.write_text_once("empty", "main empty")

    def worker():
        assert get_context_chain() == ()
        formatter.write_text_once("empty", "worker empty ignored")
        with pushed(ctx):
            assert get_context_chain()[0] is ctx
            formatter.write_text_once("shared", "worker shared ignored")
            formatter.write_text_once("worker", "worker new")
        assert get_context_chain() == ()

    with pushed(ctx):
        formatter.write_text_once("shared", "main shared")
        with ThreadPoolExecutor(max_workers=1) as executor:
            executor.submit(worker).result()
        formatter.write_text_once("worker", "main worker ignored")

    formatter.write_text_once("empty", "main empty ignored")
    assert formatter.getvalue() == "main empty\nmain shared\nworker new\n"

# AC6
def test_direct_write_text_does_not_consult_or_change_once_records():
    formatter = click.HelpFormatter(width=80)
    formatter.write_text("direct before")
    formatter.write_text_once("key", "once")
    formatter.write_text("direct after")
    formatter.write_text_once("key", "suppressed")
    formatter.write_text_once("direct before", "new key")
    formatter.write_text("direct after")

    assert formatter.getvalue() == (
        "direct before\nonce\ndirect after\nnew key\ndirect after\n"
    )

# AC7
def test_write_text_failure_propagates_and_does_not_record_key():
    error = ValueError()

    class FailingFormatter(click.HelpFormatter):
        def __init__(self):
            super().__init__(width=80)
            self.fail = True
            self.calls = []

        def write_text(self, text):
            self.calls.append(text)
            if self.fail:
                raise error
            super().write_text(text)

    formatter = FailingFormatter()
    with pytest.raises(ValueError) as exc_info:
        formatter.write_text_once("key", "failed")
    assert exc_info.value is error
    assert formatter.getvalue() == ""

    formatter.fail = False
    formatter.write_text_once("key", "retry")
    formatter.write_text_once("key", "ignored")

    formatter.fail = True
    with pytest.raises(ValueError) as exc_info:
        formatter.write_text_once("other", "failed again")
    assert exc_info.value is error

    formatter.fail = False
    formatter.write_text_once("key", "still ignored")
    formatter.write_text_once("other", "other")
    formatter.write_text_once("other", "also ignored")
    assert formatter.calls == ["failed", "retry", "failed again", "other"]
    assert formatter.getvalue() == "retry\nother\n"

# AC8
def test_help_command_uses_context_scoped_text():
    class HelpCommand(click.Command):
        def format_help(self, ctx, formatter):
            super().format_help(ctx, formatter)
            formatter.write_text_once("notice", "outer notice")
            formatter.write_text_once("notice", "ignored outer notice")
            with ctx.scope():
                formatter.write_text_once("notice", "inner notice")
                formatter.write_text_once("notice", "ignored inner notice")
            formatter.write_text_once("notice", "ignored after return")

    @click.command(cls=HelpCommand)
    def command():
        """A sample command."""

    result = CliRunner().invoke(command, ["--help"])
    assert result.exit_code == 0, result.output
    assert "Usage:" in result.output
    assert "A sample command." in result.output
    assert result.output.count("outer notice") == 1
    assert result.output.count("inner notice") == 1
    assert "ignored" not in result.output
````
