diff --git a/AGENTS.md b/AGENTS.md
index 91c5d7a..2b35132 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -56,6 +56,7 @@ Request flow: **command → resolve → async SDK wrapper → (cache | Plane SDK
- Estimate points: no API endpoint; `cached_list_estimate_points` derives them from work items with `expand=estimate_point`.
- **A `200` is not always a write.** Some Plane endpoints accept a mutation and ignore it — the intake `PATCH` returns `200` with the record unchanged when the caller is not a project Admin. Where that is known, read the raw response and compare the field you meant to change *before* enriching it for display, then raise `APIError`. See [ADR-0007](docs/adr/0007-verify-writes-the-api-can-silently-ignore.md).
- **Intake mutations take the work item UUID**, not the intake wrapper `id` — the `Issue ID` column of `intake ls`. `intake delete` also deletes the underlying work item for any status other than `accepted`; destructive commands are documented, never prompted (see [ADR-0008](docs/adr/0008-destructive-deletes-are-documented-not-prompted.md)).
+- **States are not fuzzy.** `resolve_state*` take an exact name or a partial name that fits only one state, and fail otherwise (ADR-0009). Do not route state names through `find_best_match`.
- **Guard optional flags with `is not None`, not truthiness.** `--priority ""` must reach the validator and be rejected; `if priority:` would silently fall back to the default.
- **Docstrings are `--help` text, so literal angle brackets vanish.** cyclopts/Rich renders them as markup — write "a paragraph tag", not `
`.
- **Reference versioned docs, not tracker issues.** Do not cite Plane/Linear issue IDs or external tracker URLs in code comments — they are unreachable after delivery. Point to an ADR or guide instead.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66ffbab..8e198e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
### Added
- `planecli intake` command group: `ls`, `create`, `accept`, `decline`, `delete`, `enabled` for project intake queues. Mutations take the work item UUID shown in the `Issue ID` column of `intake ls`. `accept`/`decline` require the project Admin role (the API silently ignores the change for lower roles, so the CLI verifies it and fails loudly). `delete` also permanently deletes the underlying work item for any status other than `accepted`
+### Changed
+- State names no longer resolve fuzzily in `wi create --state`, `wi update --state`, `wi ls --state` and `state show/update/delete`. An exact case-insensitive name wins; otherwise a partial name is used only if it fits exactly one state, with a `State matched: "x" -> "y"` notice on stderr. An ambiguous or unknown name fails with exit code 5 and lists the project's states (before, `--state qa` could silently pick "pronto p/ qa"; an unknown name exited with 3). `wi ls --state` no longer ORs every state containing the text. State UUIDs work as before
+
## [0.5.1] - 2026-07-03
### Added
diff --git a/README.md b/README.md
index f9532cb..8ac3eae 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,7 @@ planecli wi ls
planecli wi ls -p "Frontend"
# Filter by state and/or labels (comma-separated for OR logic)
+# State names match exactly (case-insensitive) or by a partial name that fits only one state
planecli wi ls -p "Frontend" --state "In Progress,In Review"
planecli wi ls -p "Frontend" --labels "bug,critical"
diff --git a/docs/adr/0009-states-resolve-strictly.md b/docs/adr/0009-states-resolve-strictly.md
new file mode 100644
index 0000000..da38262
--- /dev/null
+++ b/docs/adr/0009-states-resolve-strictly.md
@@ -0,0 +1,61 @@
+---
+status: accepted
+date: 2026-10-20
+decision-makers: PlaneCLI maintainers
+---
+
+# ADR-0009: States resolve strictly, not fuzzily
+
+## Context and Problem Statement
+
+[ADR-0002](0002-fuzzy-resource-resolution.md) resolves every resource name with rapidfuzz at a
+threshold of 60. For states that is the wrong trade-off. State names are short and a workflow
+often has several that share words — "pronto p/ qa", "em qa", "pronto p/ hml", "em hml" — so
+`wi update ABC-1 --state qa` fuzzy-matched whichever name scored highest and moved the work item
+to a column the user never named. `wi ls --state` had the opposite problem: a substring filter
+that silently ORed every state containing the text. Either way the command succeeded, so the
+mistake surfaced only later, on the board.
+
+## Considered Options
+
+- **A. Strict matching with a unique partial fallback** — exact name, else the only name that
+ contains the query, else fail with the list of states.
+- **B. Keep fuzzy, raise the threshold** — fewer wrong picks, but still a guess.
+- **C. Exact names only** — unambiguous, but `--state review` for "code review" stops working.
+
+## Decision Outcome
+
+Chosen option: **A**, because a state change is a write that is easy to miss, so the CLI must
+never guess between candidates, while a partial name that fits exactly one state is still
+convenient and safe.
+
+- A UUID is looked up directly, as before.
+- An exact, case-insensitive name wins.
+- Otherwise the only name containing the query as a whole word is used, then the only name
+ containing it as a substring. Either prints `State matched: "query" -> "name"` on stderr.
+- Several candidates, or none, raise `ValidationError` (exit 5) listing the project's states.
+ A fuzzy-only resemblance is not a match.
+- `wi ls --state` matches each name per project. With `--project` the rules above apply as is.
+ Across projects a name may be missing from some projects, but it must match in at least one
+ and be ambiguous in none.
+- Other resources keep fuzzy resolution (ADR-0002).
+
+## Confirmation
+
+`match_state_name` / `resolve_state_name` in `utils/resolve.py` implement the rules and back
+`resolve_state` / `resolve_state_async`; `_resolve_state_filter` in `commands/work_items.py`
+applies them to `wi ls --state`. Covered by `tests/test_resolve.py` and the `TestStateFilter`
+tests in `tests/test_commands/test_work_items.py`.
+
+## Consequences
+
+**Positive:**
+- A state name either lands where the user meant or fails before anything is written.
+- The error lists the valid names, so the fix is one retry away.
+
+**Negative:**
+- Inputs that used to resolve by fuzzy resemblance (typos such as "dne" for "Done") now fail.
+- `wi ls --state qa` no longer ORs every state containing "qa"; list the states explicitly.
+
+**Neutral:**
+- An unknown state name now exits with 5 (ValidationError) instead of 3 (not found).
diff --git a/docs/architecture.md b/docs/architecture.md
index 3a888a5..27f4441 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -28,7 +28,7 @@ record before reporting success — see [ADR-0007](adr/0007-verify-writes-the-ap
**`commands/`** — one module per resource, each exposing a `cyclopts.App` with `list`/`show`/`create`/`update`/`delete` subcommands. This is where new features are added.
-**`utils/resolve.py`** — the resolution layer. Each resource has a `resolve_` / `resolve__async` pair that tries **UUID → identifier → fuzzy name** in that order. Commands call the `_async` versions, which read through the cache.
+**`utils/resolve.py`** — the resolution layer. Each resource has a `resolve_` / `resolve__async` pair that tries **UUID → identifier → fuzzy name** in that order (states match names strictly instead, see [ADR-0009](adr/0009-states-resolve-strictly.md)). Commands call the `_async` versions, which read through the cache.
**`api/`** — `client.py` holds the `PlaneClient` singleton (`get_client`) plus `get_config`/`get_workspace`; `async_sdk.py` wraps the blocking SDK.
@@ -45,7 +45,7 @@ record before reporting success — see [ADR-0007](adr/0007-verify-writes-the-ap
`planecli wi update ABC-123 --state "review"`:
1. The `wi update` command resolves `ABC-123`. Because it matches the `ABC-123` identifier pattern, `resolve_work_item_async` fetches it directly via the raw SDK path (bypassing broken SDK validation — see [ADR-0003](adr/0003-sdk-escape-hatches.md)).
-2. `--state "review"` is resolved: `resolve_state_async` reads the project's **cached** state list and fuzzy-matches "review" to "In Review".
+2. `--state "review"` is resolved: `resolve_state_async` reads the project's **cached** state list and, since "review" is not an exact name but fits only "In Review", picks it and notes the match on stderr. States never resolve fuzzily — see [ADR-0009](adr/0009-states-resolve-strictly.md).
3. The update call runs through `run_sdk()` — in a thread, rate-limited, retried on 429/5xx.
4. The relevant cache entry is invalidated via `invalidate_resource(...)`.
5. The result is rendered as a table (stderr) or JSON (stdout).
@@ -62,6 +62,7 @@ Major architecture decisions are documented as ADRs in [docs/adr/](adr/):
- [ADR-0006](adr/0006-secondary-enrichment-degrades-to-null.md) — Secondary enrichment degrades to a null sentinel (partial success)
- [ADR-0007](adr/0007-verify-writes-the-api-can-silently-ignore.md) — Verify writes the API can silently ignore
- [ADR-0008](adr/0008-destructive-deletes-are-documented-not-prompted.md) — Destructive deletes are documented, not prompted
+- [ADR-0009](adr/0009-states-resolve-strictly.md) — States resolve strictly, not fuzzily
New decisions use [adr/template.md](adr/template.md) (MADR 4.0).
diff --git a/skills/SKILL.md b/skills/SKILL.md
index 6087ab3..e3f68fe 100644
--- a/skills/SKILL.md
+++ b/skills/SKILL.md
@@ -146,6 +146,9 @@ planecli comment create ABC-123 --body "Fixed in PR #456" --json
- **`sequence_id` shape differs.** `wi show` / `wi create` return an integer (`204`); `wi ls`
returns the full identifier as a string (`"PIPERAG-204"`). Build identifiers as
`sequence_id` from `wi ls`, or `"{project_identifier}-{sequence_id}"` from `wi show`.
+- **State names are strict.** `--state` takes an exact name (case-insensitive) or a partial name
+ that fits only one state (stderr notes `State matched: "x" -> "y"`). Ambiguous or unknown names
+ exit 5 and list the project's states — pick a full name from that list instead of retrying.
- **`wi show` bundles comments and can degrade to `comments: null`.** `[]` = none, a list = some,
`null` = the comment fetch failed while the work item still returned and the command exited 0.
Check for `null` explicitly when "no comments" and "couldn't load comments" differ for you.
diff --git a/skills/references/command-reference.md b/skills/references/command-reference.md
index 1ad46ee..d2f04c0 100644
--- a/skills/references/command-reference.md
+++ b/skills/references/command-reference.md
@@ -57,7 +57,7 @@ planecli wi ls [OPTIONS]
|---|---|
| `--project` / `-p` | Project name, identifier, or UUID (omit for all projects) |
| `--assignee` | Filter by assignee name or `me` |
-| `--state` | Filter by state name (comma-separated for OR) |
+| `--state` | Filter by state name (comma-separated for OR); exact name, or a partial name that fits one state |
| `--labels` | Filter by label name (comma-separated for OR) |
| `--sort` | Sort by: `created` (default), `updated` |
| `--limit` / `-l` | Max results (default: 50) |
diff --git a/src/planecli/commands/work_items.py b/src/planecli/commands/work_items.py
index 8030118..5775aab 100644
--- a/src/planecli/commands/work_items.py
+++ b/src/planecli/commands/work_items.py
@@ -197,6 +197,49 @@ async def _resolve_project_id_async(project: str | None) -> str:
return resolved["id"]
+def _state_id(item: dict) -> str | None:
+ """The state UUID of a work item (bare UUID or expanded object)."""
+ st = item.get("state")
+ return st.get("id") if isinstance(st, dict) else st
+
+
+def _resolve_state_filter(
+ tokens: list[str], project_states: dict[str, list[dict]], *, single_project: bool
+) -> set[str]:
+ """Resolve `wi ls --state` names to state UUIDs, strictly (ADR-0009).
+
+ Each token is matched per project, since every project has its own
+ states. With --project, an unknown or ambiguous name is an error.
+ Across projects, a name that exists in only some projects is fine, but
+ it must match somewhere, and it must not be ambiguous anywhere —
+ silently dropping one project's items is the failure this guards
+ against.
+ """
+ from planecli.formatters import console
+ from planecli.utils.resolve import match_state_name, state_match_error
+
+ ids: set[str] = set()
+ for token in tokens:
+ matched: dict[str, str] = {} # state id -> name
+ for proj, states in project_states.items():
+ st, candidates = match_state_name(token, states)
+ if st is not None:
+ matched[st["id"]] = st.get("name") or ""
+ elif candidates or single_project:
+ raise state_match_error(token, states, candidates, where=f"project {proj}")
+ if not matched:
+ all_states = [s for states in project_states.values() for s in states]
+ unique = list({s.get("name"): s for s in all_states}.values())
+ raise state_match_error(token, unique, [], where="any project")
+ for name in sorted(set(matched.values())):
+ if name.casefold() != token.casefold():
+ console.print(
+ f'State matched: "{token}" -> "{name}"', markup=False, highlight=False
+ )
+ ids.update(matched)
+ return ids
+
+
async def _fetch_project_data(
client, workspace: str, project_id: str
) -> tuple[list[dict], list[dict], list[dict]]:
@@ -235,7 +278,8 @@ async def list_(
assignee
Filter by assignee name or 'me'.
state
- Filter by state name (comma-separated).
+ Filter by state name (comma-separated). Names match exactly (case
+ insensitive), or by a word or substring that fits only one state.
labels
Filter by label name (comma-separated).
parent
@@ -272,6 +316,7 @@ async def list_(
# Fetch all projects in parallel (each project fetches items+states+labels in parallel)
data = []
+ project_states: dict[str, list[dict]] = {}
if projects_to_list:
# Use fresh client instances for parallel project fetching
async def _fetch_and_enrich(proj_dict: dict) -> list[dict]:
@@ -282,6 +327,7 @@ async def _fetch_and_enrich(proj_dict: dict) -> list[dict]:
items, states, labels_list = await _fetch_project_data(
proj_client, workspace, project_id
)
+ project_states[proj_identifier or project_id] = states
if not items:
return []
@@ -347,17 +393,14 @@ async def _fetch_and_enrich(proj_dict: dict) -> list[dict]:
)
]
- # Filter by state (comma-separated, OR logic, substring match)
- if state:
- state_tokens = [s.strip().lower() for s in state.split(",") if s.strip()]
+ # Filter by state (comma-separated, OR logic, strict name match)
+ if state is not None:
+ state_tokens = [s.strip() for s in state.split(",") if s.strip()]
if state_tokens:
- data = [
- d for d in data
- if any(
- token in str(d.get("state_detail_name") or "").lower()
- for token in state_tokens
- )
- ]
+ state_ids = _resolve_state_filter(
+ state_tokens, project_states, single_project=bool(project)
+ )
+ data = [d for d in data if _state_id(d) in state_ids]
# Filter by parent work item
if parent:
@@ -504,7 +547,8 @@ async def create(
assignee
Assignee name, email, or 'me'.
state
- State name (e.g. 'Todo', 'In Progress').
+ State name (e.g. 'Todo', 'In Progress') or UUID. A partial name must
+ fit only one state.
labels
Comma-separated label names.
priority
@@ -637,7 +681,7 @@ async def update(
project
Project name/ID (required for name-based lookup).
state
- New state name.
+ New state name or UUID. A partial name must fit only one state.
priority
New priority: urgent, high, medium, low, none.
assignee
diff --git a/src/planecli/utils/resolve.py b/src/planecli/utils/resolve.py
index b18c79f..f9f6dce 100644
--- a/src/planecli/utils/resolve.py
+++ b/src/planecli/utils/resolve.py
@@ -1,19 +1,20 @@
"""Resource name/ID/UUID resolution layer.
Tries resolution in order: UUID direct lookup -> identifier match -> fuzzy name match.
+States are the exception: their names match strictly (match_state_name).
"""
from __future__ import annotations
import re
-from typing import Any
+from typing import Any, Sequence
from loguru import logger
from plane.client import PlaneClient
from plane.errors import HttpError
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_random_exponential
-from planecli.exceptions import ResourceNotFoundError
+from planecli.exceptions import ResourceNotFoundError, ValidationError
from planecli.utils.fuzzy import find_best_match, find_matches
UUID_PATTERN = re.compile(
@@ -41,6 +42,83 @@ def _reraise_if_retryable(exc: HttpError) -> None:
raise
+def match_state_name(
+ query: str, states: Sequence[dict[str, Any]]
+) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
+ """Match a state by name without fuzzy guessing.
+
+ States are matched strictly because their names are short and often
+ overlap ("em qa", "pronto p/ qa"): a fuzzy pick silently moves a work
+ item to the wrong column (see ADR-0009). In order:
+
+ 1. an exact, case-insensitive name;
+ 2. the only name containing the query as a whole word;
+ 3. the only name containing the query as a substring.
+
+ Returns (state, []) on a match. Otherwise returns (None, candidates):
+ the names that matched ambiguously, or [] when none did.
+ """
+ q = query.strip().casefold()
+ if not q:
+ return None, []
+
+ def name(s: dict[str, Any]) -> str:
+ return (s.get("name") or "").strip().casefold()
+
+ exact = [s for s in states if name(s) == q]
+ if exact:
+ return exact[0], []
+ word = re.compile(rf"(? dict[str, Any]:
+ """Resolve a state name strictly (see match_state_name).
+
+ Prints a notice on stderr when the name was not an exact match, so the
+ user sees which state a partial name landed on. Raises ValidationError
+ listing the project's state names when nothing, or more than one state,
+ matches.
+ """
+ state, candidates = match_state_name(query, states)
+ if state is None:
+ raise state_match_error(query, states, candidates)
+ if (state.get("name") or "").strip().casefold() != query.strip().casefold():
+ from planecli.formatters import console
+
+ console.print(
+ f'State matched: "{query}" -> "{state.get("name")}"', markup=False, highlight=False
+ )
+ return state
+
+
+def state_match_error(
+ query: str,
+ states: Sequence[dict[str, Any]],
+ candidates: Sequence[dict[str, Any]],
+ *,
+ where: str = "this project",
+) -> ValidationError:
+ """Build the error for a state name that is unknown or ambiguous."""
+ names = ", ".join(f'"{s.get("name")}"' for s in states if s.get("name"))
+ hint = f"States in {where}: {names}." if names else f"There are no states in {where}."
+ if candidates:
+ matched = ", ".join(f'"{s.get("name")}"' for s in candidates)
+ return ValidationError(
+ f'State "{query}" is ambiguous: it matches {matched}.',
+ hint=f"Use the full state name. {hint}",
+ )
+ return ValidationError(f'No state matches "{query}".', hint=hint)
+
+
@retry(
retry=retry_if_exception(_is_retryable),
wait=wait_random_exponential(min=1, max=60),
@@ -269,7 +347,7 @@ def resolve_module(
def resolve_state(
query: str, client: PlaneClient, workspace: str, project_id: str
) -> dict[str, Any]:
- """Resolve a state by UUID or fuzzy name match.
+ """Resolve a state by UUID or strict name match (see match_state_name).
Returns the state as a dict.
"""
@@ -282,12 +360,7 @@ def resolve_state(
raise ResourceNotFoundError("State", query)
states = _paginate_all(client.states.list, workspace, project_id)
-
- match = find_best_match(query, states, key=lambda s: s.name or "")
- if match:
- return match.item.model_dump()
-
- raise ResourceNotFoundError("State", query)
+ return resolve_state_name(query, [s.model_dump() for s in states])
def resolve_cycle(
@@ -551,12 +624,7 @@ async def resolve_state_async(
raise ResourceNotFoundError("State", query)
states = await cached_list_states(workspace, project_id)
-
- match = find_best_match(query, states, key=lambda s: s.get("name", ""))
- if match:
- return match.item
-
- raise ResourceNotFoundError("State", query)
+ return resolve_state_name(query, states)
async def resolve_cycle_async(
diff --git a/tests/test_commands/test_work_items.py b/tests/test_commands/test_work_items.py
index f97cb8c..02d07e8 100644
--- a/tests/test_commands/test_work_items.py
+++ b/tests/test_commands/test_work_items.py
@@ -1418,3 +1418,50 @@ async def test_show_no_false_failure_when_fetch_not_attempted(
mock_fetch.assert_not_awaited()
printed = " ".join(str(c.args[0]) for c in mock_console.print.call_args_list)
assert "failed to load" not in printed
+
+
+class TestStateFilter:
+ """wi ls --state resolves names strictly, per project (ADR-0009)."""
+
+ FE = [{"id": "fe-qa", "name": "em qa"}, {"id": "fe-ready", "name": "pronto p/ qa"}]
+ BE = [{"id": "be-qa", "name": "QA"}, {"id": "be-done", "name": "Done"}]
+
+ def test_exact_name_in_one_project_is_enough(self):
+ from planecli.commands.work_items import _resolve_state_filter
+
+ ids = _resolve_state_filter(["em qa"], {"fe": self.FE, "be": self.BE}, single_project=False)
+ assert ids == {"fe-qa"}
+
+ def test_ambiguous_in_any_project_fails(self):
+ from planecli.commands.work_items import _resolve_state_filter
+ from planecli.exceptions import ValidationError
+
+ with pytest.raises(ValidationError, match="ambiguous"):
+ _resolve_state_filter(["qa"], {"fe": self.FE, "be": self.BE}, single_project=False)
+
+ def test_unknown_everywhere_fails(self):
+ from planecli.commands.work_items import _resolve_state_filter
+ from planecli.exceptions import ValidationError
+
+ with pytest.raises(ValidationError, match="No state matches"):
+ _resolve_state_filter(["review"], {"fe": self.FE, "be": self.BE}, single_project=False)
+
+ def test_missing_in_the_selected_project_fails(self):
+ from planecli.commands.work_items import _resolve_state_filter
+ from planecli.exceptions import ValidationError
+
+ with pytest.raises(ValidationError):
+ _resolve_state_filter(["done"], {"fe": self.FE}, single_project=True)
+
+ def test_partial_match_prints_notice(self, capsys):
+ from planecli.commands.work_items import _resolve_state_filter
+
+ ids = _resolve_state_filter(["pronto"], {"fe": self.FE}, single_project=True)
+ assert ids == {"fe-ready"}
+ assert 'State matched: "pronto" -> "pronto p/ qa"' in capsys.readouterr().err
+
+ def test_state_id_reads_bare_or_expanded_state(self):
+ from planecli.commands.work_items import _state_id
+
+ assert _state_id({"state": "s1"}) == "s1"
+ assert _state_id({"state": {"id": "s2"}}) == "s2"
diff --git a/tests/test_resolve.py b/tests/test_resolve.py
index a4a6b5a..645c1af 100644
--- a/tests/test_resolve.py
+++ b/tests/test_resolve.py
@@ -2,7 +2,15 @@
from __future__ import annotations
-from planecli.utils.resolve import ISSUE_ID_PATTERN, _is_uuid
+import pytest
+
+from planecli.exceptions import ValidationError
+from planecli.utils.resolve import (
+ ISSUE_ID_PATTERN,
+ _is_uuid,
+ match_state_name,
+ resolve_state_name,
+)
class TestIsUUID:
@@ -48,3 +56,97 @@ def test_invalid_no_prefix(self):
def test_invalid_numbers_in_prefix(self):
match = ISSUE_ID_PATTERN.match("A1B-123")
assert match is None
+
+
+# ---------------------------------------------------------------------------
+# Strict state matching (ADR-0009)
+# ---------------------------------------------------------------------------
+
+MB_STATES = [
+ {"id": "s1", "name": "Backlog"},
+ {"id": "s2", "name": "Em desenvolvimento"},
+ {"id": "s3", "name": "code review"},
+ {"id": "s4", "name": "pronto p/ qa"},
+ {"id": "s5", "name": "em qa"},
+ {"id": "s6", "name": "Done"},
+]
+
+
+class TestMatchStateName:
+ def test_exact_match_is_case_insensitive(self):
+ assert match_state_name("EM QA", MB_STATES) == (MB_STATES[4], [])
+
+ def test_exact_match_wins_over_containing_names(self):
+ states = [{"id": "a", "name": "QA"}, {"id": "b", "name": "pronto p/ qa"}]
+ assert match_state_name("qa", states) == (states[0], [])
+
+ def test_unique_whole_word(self):
+ assert match_state_name("review", MB_STATES) == (MB_STATES[2], [])
+
+ def test_unique_substring(self):
+ assert match_state_name("desenv", MB_STATES) == (MB_STATES[1], [])
+
+ def test_ambiguous_word_returns_candidates(self):
+ state, candidates = match_state_name("qa", MB_STATES)
+ assert state is None
+ assert candidates == [MB_STATES[3], MB_STATES[4]]
+
+ def test_unique_whole_word_beats_other_substrings(self):
+ states = [{"id": "a", "name": "Todo"}, {"id": "b", "name": "to do later"}]
+ assert match_state_name("do", states) == (states[1], [])
+
+ def test_fuzzy_only_is_not_a_match(self):
+ # "dne" fuzzy-matches "Done" but is not contained in any name
+ assert match_state_name("dne", MB_STATES) == (None, [])
+
+ def test_blank_query_matches_nothing(self):
+ assert match_state_name(" ", MB_STATES) == (None, [])
+
+
+class TestResolveStateName:
+ def test_partial_match_prints_notice(self, capsys):
+ assert resolve_state_name("review", MB_STATES) == MB_STATES[2]
+ assert 'State matched: "review" -> "code review"' in capsys.readouterr().err
+
+ def test_exact_match_prints_nothing(self, capsys):
+ resolve_state_name("Done", MB_STATES)
+ assert capsys.readouterr().err == ""
+
+ def test_ambiguous_lists_matches_and_states(self):
+ with pytest.raises(ValidationError) as exc:
+ resolve_state_name("qa", MB_STATES)
+ assert '"pronto p/ qa", "em qa"' in exc.value.message
+ assert '"Backlog"' in exc.value.hint
+ assert exc.value.exit_code == 5
+
+ def test_no_match_lists_states(self):
+ with pytest.raises(ValidationError, match='No state matches "dne"') as exc:
+ resolve_state_name("dne", MB_STATES)
+ assert '"code review"' in exc.value.hint
+
+
+@pytest.mark.asyncio
+async def test_resolve_state_async_uses_strict_match():
+ from unittest.mock import AsyncMock, patch
+
+ from planecli.utils.resolve import resolve_state_async
+
+ with patch("planecli.cache.cached_list_states", new_callable=AsyncMock) as mock_states:
+ mock_states.return_value = MB_STATES
+ assert (await resolve_state_async("em qa", None, "ws", "p1"))["id"] == "s5"
+ with pytest.raises(ValidationError):
+ await resolve_state_async("qa", None, "ws", "p1")
+
+
+@pytest.mark.asyncio
+async def test_resolve_state_async_uuid_skips_name_matching():
+ from unittest.mock import AsyncMock, MagicMock, patch
+
+ from planecli.utils.resolve import resolve_state_async
+
+ uuid = "550e8400-e29b-41d4-a716-446655440000"
+ state = MagicMock()
+ state.model_dump.return_value = {"id": uuid, "name": "Done"}
+ with patch("planecli.api.async_sdk.run_sdk", new_callable=AsyncMock) as mock_run:
+ mock_run.return_value = state
+ assert (await resolve_state_async(uuid, MagicMock(), "ws", "p1"))["id"] == uuid