Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<p>`.
- **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.
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
61 changes: 61 additions & 0 deletions docs/adr/0009-states-resolve-strictly.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 3 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<x>` / `resolve_<x>_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_<x>` / `resolve_<x>_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.

Expand All @@ -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).
Expand All @@ -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).

Expand Down
3 changes: 3 additions & 0 deletions skills/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion skills/references/command-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
70 changes: 57 additions & 13 deletions src/planecli/commands/work_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand All @@ -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 []
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
98 changes: 83 additions & 15 deletions src/planecli/utils/resolve.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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"(?<!\w){re.escape(q)}(?!\w)")
whole = [s for s in states if word.search(name(s))]
if len(whole) == 1:
return whole[0], []
if whole:
return None, whole
partial = [s for s in states if q in name(s)]
if len(partial) == 1:
return partial[0], []
return None, partial


def resolve_state_name(query: str, states: Sequence[dict[str, Any]]) -> 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),
Expand Down Expand Up @@ -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.
"""
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
Loading