# Prioritize unused commands in chain completion

- Task: `task_005_shell_completion_context_or_c`
- Status: rejected
- Module: src/click/shell_completion.py
- Behaviour axis: context_or_command_chaining
- Files changed: src/click/shell_completion.py
- Repairs: 2

**Stopped at Shape precheck:** Task shape constraint failed: task matches disallowed 'single_kwarg_validation' shape; task must change behaviour across >=2 existing features or src/ modules

## Gates

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

## requirements.md

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

# Prioritize unused commands in chain completion

## Problem Description

When completing a command name in a chain-enabled Click group, suggest eligible commands that have not yet been invoked in that chain before commands that have. Repeated commands must remain available.

Completion values and help text supplied as bytes must be normalized with `click.utils.make_str` before command comparison or shell formatting.

## Acceptance Criteria

- **AC1**: When the resolved completion target is a chain-enabled group's command name, reorder command completion items so unused commands precede previously invoked commands. Preserve the original relative order within each partition.
- **AC2**: Leave non-command completion items at their original list indices. Repeated commands remain in the results, and no completion item is added or removed.
- **AC3**: Determine previously invoked commands from the parsed context for the same chain group. Option values, argument values, and command names belonging to other group contexts must not count as invocations in that chain.
- **AC4**: Normalize byte-valued completion values and help text with `click.utils.make_str` before comparing or formatting them. This applies to results from custom completion providers as well as built-in providers.
- **AC5**: Apply the normalization when `ShellComplete.complete` receives items from an overridden `get_completions`, and when callers use the base `get_completions` directly. Preserve item type and arbitrary metadata.
- **AC6**: Bash, Zsh, Fish, and PowerShell completion must retain their existing shell-specific formatting and escaping, operating on normalized text.
- **AC7**: Completion for parameters, non-chain groups, and contexts outside chain command-name completion must retain its existing ordering and eligibility behavior.

## Interface

### Symbols

- `click.shell_completion.ShellComplete.get_completions`
- `click.shell_completion.ShellComplete.complete`
- `click.utils.make_str`

### Contract Details

- `ShellComplete.get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem[str]]`
  - `args` contains the complete arguments before the value being completed; `incomplete` is that value and may be empty.
  - Resolve the completion target and obtain its existing completion results as before. Return those results with byte-valued `value` and `help` fields normalized.
  - Apply prioritization only when the resolved target is a chain-enabled group completing a command name. Within that result, a command item is a `plain` item whose normalized value equals a visible command name available from that group. Other items are non-command items. A custom `plain` item with the same value as such a command name is treated as a command item.
  - Classify a command item as used when that command name was resolved as an invocation in the parsed chain for that group. Respect the group's existing command resolution and token-normalization behavior. Distinct resolved command names, including aliases, are treated as distinct names.
  - Do not introduce additional prefix filtering, deduplication, or hidden-command eligibility changes.
- `ShellComplete.complete(self) -> str`
  - Continue to obtain arguments through `get_completion_args`, obtain items through `get_completions`, and format each item through `format_completion`.
  - Normalize byte-valued item values and help text before passing items to the formatter, including when `get_completions` is overridden.
  - The returned string is exactly the formatted item strings joined by `"\n"`, with no additional trailing newline. An empty result returns `""`. Shell entry-point output retains its existing newline behavior.
- `click.utils.make_str(value: str | bytes) -> str`
  - Use the existing function's behavior for byte values, including its decoding and error handling. Non-byte values are not newly coerced by this feature; `None` help remains `None`.
- No new public parameters, exceptions, or CLI diagnostics are introduced. Existing error and exception behavior remains unchanged.

## Compatibility & Out of Scope

- Existing completion providers, shell subclasses, command registration, and shell scripts remain supported. No new public API is required.
- Prioritization does not apply to completion of an option or argument, even when its value resembles a command name.
- Changing shell-specific output protocols, command eligibility, or command execution semantics is out of scope.
- Preserve existing startup import constraints; do not introduce eager top-level standard-library imports that regress startup behavior.
- The entire existing repository test suite must continue to pass with zero regressions.

## Reference patch

````diff
diff --git a/src/click/shell_completion.py b/src/click/shell_completion.py
index 9cf2314..c09d78f 100644
--- a/src/click/shell_completion.py
+++ b/src/click/shell_completion.py
@@ -14,6 +14,7 @@ from .core import Option
 from .core import Parameter
 from .core import ParameterSource
 from .utils import echo
+from .utils import make_str
 
 
 def shell_complete(
@@ -101,6 +102,17 @@ class CompletionItem(t.Generic[_ValueT_co]):
         return self._info.get(name)
 
 
+def _normalize_completion(item: CompletionItem[t.Any]) -> CompletionItem[t.Any]:
+    """Normalize byte-valued shell completion text without changing metadata."""
+    if isinstance(item.value, bytes):
+        item.value = make_str(item.value)
+
+    if isinstance(item.help, bytes):
+        item.help = make_str(item.help)
+
+    return item
+
+
 # Only Bash >= 4.4 has the nosort option.
 _SOURCE_BASH = """\
 %(complete_func)s() {
@@ -360,9 +372,54 @@ class ShellComplete:
         :param args: List of complete args before the incomplete value.
         :param incomplete: Value being completed. May be empty.
         """
-        ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
+        used_commands: dict[Context, list[str]] = {}
+        ctx = _resolve_context(
+            self.cli, self.ctx_args, self.prog_name, args, used_commands
+        )
         obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
-        return obj.shell_complete(ctx, incomplete)
+        items = [_normalize_completion(item) for item in obj.shell_complete(ctx, incomplete)]
+
+        # A chain command also provides its parent group's command completions.
+        # Parameter and option-name completion must keep their original order.
+        group_ctx = None
+
+        if obj is ctx.command and not (
+            "--" not in args and _start_of_option(ctx, incomplete)
+        ):
+            if isinstance(ctx.command, Group) and ctx.command.chain:
+                group_ctx = ctx
+            elif (
+                ctx.parent is not None
+                and isinstance(ctx.parent.command, Group)
+                and ctx.parent.command.chain
+            ):
+                group_ctx = ctx.parent
+
+        if group_ctx is None or not used_commands.get(group_ctx):
+            return items
+
+        group = t.cast("Group", group_ctx.command)
+        visible_names = []
+
+        for name in group.list_commands(group_ctx):
+            command = group.get_command(group_ctx, name)
+
+            if command is not None and not command.hidden:
+                visible_names.append(name)
+
+        indices = [
+            i
+            for i, item in enumerate(items)
+            if item.type == "plain" and item.value in visible_names
+        ]
+        commands = [items[i] for i in indices]
+        used = used_commands[group_ctx]
+        commands.sort(key=lambda item: item.value in used)
+
+        for i, item in zip(indices, commands):
+            items[i] = item
+
+        return items
 
     def format_completion(self, item: CompletionItem[str]) -> str:
         """Format a completion item into the form recognized by the
@@ -381,7 +438,7 @@ class ShellComplete:
         """
         args, incomplete = self.get_completion_args()
         completions = self.get_completions(args, incomplete)
-        out = [self.format_completion(item) for item in completions]
+        out = [self.format_completion(_normalize_completion(item)) for item in completions]
         return "\n".join(out)
 
 
@@ -693,6 +750,7 @@ def _resolve_context(
     ctx_args: cabc.MutableMapping[str, t.Any],
     prog_name: str,
     args: list[str],
+    used_commands: dict[Context, list[str]] | None = None,
 ) -> Context:
     """Produce the context hierarchy starting with the command and
     traversing the complete arguments. This only follows the commands,
@@ -730,6 +788,9 @@ def _resolve_context(
                         if cmd is None:
                             return ctx
 
+                        if used_commands is not None and name is not None:
+                            used_commands.setdefault(ctx, []).append(name)
+
                         with cmd.make_context(
                             name,
                             args,
````
