diff --git a/.agents/README.md b/.agents/README.md new file mode 100644 index 000000000..54b2a8b8e --- /dev/null +++ b/.agents/README.md @@ -0,0 +1,35 @@ +# Agent skills for UXarray + +Reusable instructions for AI coding agents working on this repository. The repo-wide context every +agent should read is [`AGENTS.md`](../AGENTS.md) at the repo root; the skills here build on it. + +| Skill | Use it to | +|---|---| +| [`uxarray-pr-review`](skills/uxarray-pr-review/SKILL.md) | Review a PR and verify every finding by running code before reporting it | +| [`uxarray-issue-triage`](skills/uxarray-issue-triage/SKILL.md) | Classify an issue, find duplicates and related work, try to reproduce it, and suggest labels | + +Each skill is a folder with a `SKILL.md` (name, description, steps) and optional `references/` files that +the steps link to. + +## Using them + +- **Claude Code**: `.claude/skills/` holds symlinks to these folders, so the skills are available as + `/uxarray-pr-review ` and `/uxarray-issue-triage `. Claude Code reads + `AGENTS.md` itself in recent versions (tested with 2.1.323; 2.1.270 does not); if it isn't loaded, + run `claude update`. +- **Other agents**: agents that read `.agents/skills/` pick them up directly. For any other agent, point + it at the skill's `SKILL.md`, e.g. "Follow `.agents/skills/uxarray-pr-review/SKILL.md` for PR 1889". + +Windows: the `.claude/skills/` symlinks need `git config core.symlinks true` (and Developer Mode or admin +rights) before checkout; otherwise they appear as small text files. + +## Ground rules shared by the skills + +- Never post to GitHub, label, or push without the user's approval of the exact text. +- Work in git worktrees and a scratch environment; never switch branches in the user's checkout. +- Report a finding as fact only after reproducing it; otherwise say it was not reproduced and why. + +## Adding a skill + +Create `.agents/skills//SKILL.md` with `name` and `description` front matter, add a symlink +`ln -s ../../.agents/skills/ .claude/skills/`, and add a row to the table above. diff --git a/.agents/skills/uxarray-issue-triage/SKILL.md b/.agents/skills/uxarray-issue-triage/SKILL.md new file mode 100644 index 000000000..d80e29b87 --- /dev/null +++ b/.agents/skills/uxarray-issue-triage/SKILL.md @@ -0,0 +1,107 @@ +--- +name: uxarray-issue-triage +description: Triage a UXarray (UXARRAY/uxarray) GitHub issue like a senior maintainer - classify it, find duplicates and past decisions, try to reproduce it, locate the code involved, and suggest labels and next steps. Use when asked to triage, review or assess a uxarray issue by number or URL. +--- + +# UXarray issue triage + +Triage the issue given as the argument. The output is a short triage note for the maintainer, plus an +optional comment for the issue thread. Read `AGENTS.md` at the repo root first for the architecture and +the settled design decisions. + +Nothing is posted or labelled without the user's approval. + +## 1. Understand + +`gh issue view --comments`. Note what the reporter observed, what they expected, their UXarray +version and install method (the bug template asks for both), the grid format and model (MPAS, ICON, +SCRIP, ...), the data size, whether dask/chunking is involved, and anything they already tried. + +Read the discussion as carefully as the report: who has already diagnosed or reproduced it, what was +asked of the reporter and whether they answered, existing labels/assignees, decisions posted from +maintainer meetings ("From internal discussion..."), and PRs or issues that mention it +(`gh api repos/UXARRAY/uxarray/issues//timeline` → `cross-referenced` events). Build on that rather +than repeating it, and list unanswered questions or disagreements under **Needs your call**. + +## 2. Classify + +- **Type**: bug, feature request, question/support, docs, performance/scalability, accuracy, CI/infra, + upstream (an xarray/numba/dask/cartopy change; label `fix upstream`), environment (install, conda vs + pip, missing optional extra: often not a UXarray bug). +- **Bot issues** ("🤖 Upstream testing failure", "🤖 Minimum dependency testing failure"): find the first + failing run and the dependency release that broke it; a min-deps failure means a lower bound in + `pyproject.toml` needs raising (with a comment) or the code needs a compatible path. +- **AI-reported bugs** (e.g. "[Claude] ..." titles, lists of several bugs): check each claim separately + against current `main`; some may be duplicates or already fixed. +- **Security-sensitive** (exposed credentials, a vulnerability): stop here. Do not draft a public comment + or reproduce it in public; tell the user, who decides how to handle it privately. +- **Area**: io/reader (which format), grid construction/topology, geometry/accuracy, core + (`UxDataArray`/`UxDataset` ops, aggregations, calculus), remap, subset/cross-section, plotting, dask, + docs, packaging/optional deps. +- **Labels**: suggest only from the repo's labels (`gh label list`), e.g. `bug`, `new feature`, + `improvement`, `documentation`, `scalability`, `accuracy`, `visualization`, `extra dims`, `design`, + `developer experience`, `fix upstream`, `CI`, `testing`. The repo has no priority, size or "good first + issue" labels; `may revisit` is for ideas closed as not planned for now. + +## 3. Look for duplicates, related work and past decisions + +Search open **and** closed issues, PRs and Discussions with 2-3 keyword variants: +`gh search issues --repo UXARRAY/uxarray ""`, `gh pr list --state all --search ""`, +and Discussions via `gh api graphql` (`repository.discussions` or `search(type: DISCUSSION)`). +Also check whether a PR already claims to fix it (`closedByPullRequestsReferences`: +`gh api graphql -f query='query{repository(owner:"UXARRAY",name:"uxarray"){issue(number:){ +closedByPullRequestsReferences(first:10,includeClosedPrs:true){nodes{number title state}}}}}'`). + +For feature requests, check them against the settled decisions in AGENTS.md (scope: 2D grids on the +sphere; structured grids only through `from_structured()`; file writing through xarray; `Grid` not +growing Dataset API) and look for an earlier issue closed as not planned or `may revisit`. Link what +you find rather than re-arguing it. + +## 4. Locate and reproduce + +1. Check whether it is already fixed: get the reporter's version (a dev version such as + `2026.9.1.dev24+ge01d71e37` names the commit after the `g`; a release maps to tag `v`) and + run `git log ..origin/main -- `. If a later commit fixed it, say which. +2. Find the code involved and trace it to the public entry point, as in the PR-review skill's Stage 1 + (`.agents/skills/uxarray-pr-review/SKILL.md`). +3. For a bug, try to reproduce it on current `main` in a clean worktree with the environment from + `.agents/skills/uxarray-pr-review/references/verification.md` §Setup. Write the smallest script that + shows it, preferring a mesh from `test/meshfiles/` (table in verification.md) or a face built with + `Grid.from_face_vertices` over the reporter's large file. Result is one of: + - **Reproduced** — include the script and its output. + - **Not reproduced** — say what was tried; ask the reporter for the missing detail (grid file or a + link to it, version, full traceback). + - **Needs reporter data** — the bug depends on a grid or dataset that isn't available; say what is + needed. Many model files live on NCAR GLADE or are large; a subset or the grid file alone often + suffices. +4. Give a root-cause hypothesis with `file:line`, labelled confirmed or suspected. For geometry bugs, a + sweep over antimeridian, pole and rotated inputs (verification.md §Techniques, item 2) often shows + the pattern. + +For a **feature request**, instead of reproducing: does it fit UXarray's scope, can it be done today with +existing API (e.g. via `.to_xarray()` and plain xarray), does an xarray analogue define what the API +should look like, and does it overlap open work? For a **question**, find the docs page or user-guide +notebook that answers it; if none does, that is a docs gap worth noting. + +## 5. Report + +Show the user, in this order and briefly: + +``` +# +Type / area: ... +Duplicates / related: #.. (why), past decisions (link) — or none found +Reproduction: Reproduced | Not reproduced | Needs reporter data — one line, script path +Likely cause: file:line — confirmed | suspected +Suggested labels: ... +Priority (advisory): high (wrong results, data loss, crash in common path) | medium | low — one-line reason +Size (advisory): S | M | L — one-line reason +Next step: who/what, e.g. "needs reporter's grid file", "fix with #PR", "maintainer design call" +Needs your call: open disagreements or unanswered questions from the thread, if any +``` + +Priority and size are advice to the maintainer, not repo labels. + +Then, if useful, a draft comment for the issue thread (under ~100 words: what was reproduced, what is +needed from the reporter, or the duplicate link). Post the comment or apply labels only after the user +approves, with `gh issue comment` / `gh issue edit --add-label`. diff --git a/.agents/skills/uxarray-pr-review/SKILL.md b/.agents/skills/uxarray-pr-review/SKILL.md new file mode 100644 index 000000000..d5c80b7d9 --- /dev/null +++ b/.agents/skills/uxarray-pr-review/SKILL.md @@ -0,0 +1,125 @@ +--- +name: uxarray-pr-review +description: Review a UXarray (UXARRAY/uxarray) pull request like a senior maintainer and verify every finding by running code before reporting it. Use when asked to review, check or comment on a uxarray PR by number, branch or URL. +--- + +# UXarray PR review (self-verifying) + +Review the pull request given as the argument (number, branch or URL). The goal is a review that is +**deep but short**, where every finding has been **checked by running code**, not just by reading it. +Read `AGENTS.md` at the repo root first: it holds the architecture and the repo rules this review +checks against. + +Work in four stages. Do not skip stage 3: a finding that has not been through it is not reported as fact. + +## Stage 0 — Set up (once per PR) + +Follow [references/verification.md](references/verification.md) §Setup: a worktree for the PR, a clean +worktree of the base branch, and a Python environment that imports the tree under test. Never switch +branches in the user's own checkout. + +PRs from forks run someone else's code on this machine. For an unfamiliar author, say so and ask +before running anything. + +## Stage 1 — Context + +1. `gh pr view <n>` (body, author, commits, `closingIssuesReferences`) and every linked issue with its + comments. Note what the PR **claims** to do: you will check the code against those claims. Maintainer + decisions are often posted on the issue as "From internal discussion..." comments; the PR must follow + them. +2. **Review history** — follow [references/history.md](references/history.md): earlier reviews and the + commit each one reviewed, every inline thread and comment, commits since the last review, description + edits, force-pushes, CI status. Build the ledger of points raised and their status, and note + disagreements and unanswered questions. Do this even when the PR looks fresh. +3. `git diff <base>...HEAD --stat`, then the full diff. If there was an earlier review, also the diff since + that review's commit: it is the least-reviewed code in the PR. +4. For every changed function, **trace its callers up to a public entry point** (`ux.open_*`, a `Grid` + property or classmethod, a `UxDataArray`/`UxDataset` method, an accessor method such as `.remap.*`, + `.subset.*`, `.plot.*`). Record: + - which grid formats and readers reach it, and whether faces can be mixed-size (padded with + `INT_FILL_VALUE`), cross the antimeridian, contain a pole, or come from a projected grid; + - which data locations it handles (node / edge / face) and which it rejects; + - whether it runs on numpy or chunked (dask) data, and whether the caller can pass either; + - which options select the path (`periodic_elements`, `backend`, `remap_to`, `destination`, + `latlon`, `inverse_indices`, ...). + This step decides which findings are possible at all. Skipping it produces false positives. + +## Stage 2 — Find candidates + +Look at the diff along these dimensions. Use parallel subagents (one per dimension) when the PR is +large; for small PRs, do it in one pass. + +- **Correctness and numerics**: degrees vs radians and the two longitude ranges ([-180, 180] vs + [0, 2π)); `INT_FILL_VALUE` padding handled (not `-1`, `0`, `np.nan`); `ERROR_TOLERANCE` vs + `MACHINE_EPSILON`; antimeridian and pole faces; unit sphere vs `sphere_radius` scaling; NaN comparison + semantics; dtype promotion and integer overflow (int32 vs int64, Windows); `np.isclose(a, b, tol)` + passing `rtol` by position. +- **Accuracy-sensitive geometry**: naive arithmetic replacing `utils/computing.py` primitives, + `fastmath=True`, branching inside hot kernels, comments that overclaim ("robust", "exact", + "branch-free") or don't match the code. Compare against an analytic value or the existing accuracy + baselines (`test/grid/geometry/test_eft_accuracy.py`, `test_accusphgeom_baseline.py`). +- **Grid and data model** (AGENTS.md "Core data model"): `uxgrid` lost or not sliced after an op (e.g. + `sel` vs `isel`); coords and attrs dropped; objects on different grids combined without + `GridsMismatchError`; `_uxgrid` vs `uxgrid` misuse; topology mutated in place instead of returning a + new `Grid`; a connectivity renumbered without its pair; new grid variables not registered in + `uxarray/conventions` (works but invisible in `repr`). +- **Dask and performance**: `.values` / `np.asarray` on whole arrays, eager compute or silent rechunking + of chunked input; numba kernels allocating small arrays in loops; raw `njit(parallel=True)` instead of + `parallel_njit`; work done at import time; heavy imports at module level. Does a hot-path change need + the `run-benchmark` label or a new ASV benchmark? +- **API and back-compat**: consistency with xarray and existing UXarray signatures, argument order, + defaults and names; public vs `_private`; behavior changes not stated in the description; removals + without a `FutureWarning` cycle; structured-grid handling leaking into core APIs; new write APIs + (AGENTS.md "Core data model"). +- **Optional dependencies**: optional packages imported at module level or without + `_raise_hint_if_optional_deps_missing`; a new optional dep missing from `_OPTIONAL_DEPS_TO_EXTRAS`; a + newer dependency API used without raising the lower bound (min-deps CI). +- **Errors**: right type (`uxarray/errors.py` for domain errors, built-ins for generic checks), message + with expected and actual values and no private names, no `assert` for validation, no broad + `try/except` hiding the cause, invalid input raising rather than silently changing results. +- **Tests**: do the new tests fail without the fix (stage 3 checks this)? Do they assert what their + name says? Are tolerances and expected values justified? Are mixed-size, antimeridian, pole, extra-dim + and chunked cases covered where the caller allows them? +- **Docs and PR hygiene**: numpydoc docstrings (types in `Parameters`); new public API in `docs/api.rst`; + a user-guide section or notebook for a new user-facing feature; notebook outputs cleared (unless the + notebook is in `nb_execution_excludepatterns`); description matches the code; "Closes" vs "Related + to"; AI disclosure line filled in and its box ticked. +- **Scope and LLM habits**: unrelated changes, PRs that should be split; unneeded defensive code, + over-general helpers, hedging, boilerplate module docstrings (AGENTS.md "Pull requests"). +- **Scientific-software practice**: reproducibility, units, readability, maintainability. + +For each candidate, write down: the claim, `file:line`, the concrete failure scenario, and how you will +verify it. Candidates are hypotheses, not findings. + +Check each candidate against the ledger from Stage 1: drop it if someone already raised it, unless you +have new evidence, in which case it becomes a reply in that thread or a line in the summary. + +## Stage 3 — Verify + +Apply the techniques in [references/verification.md](references/verification.md) §Techniques. Then label +each candidate: + +- **CONFIRMED** — reproduced by running code (a failing test, a mutation that survives, an experiment). +- **PLAUSIBLE** — the code path is real but cannot be run here (e.g. needs YAC, NCAR GLADE data or a + large mesh). State why it cannot be run. +- **Dropped** — disproved. Keep a one-line note of why: dropped candidates show the review was thorough + and stop the next reviewer from raising them again. + +Always run, whatever the candidates: the PR's new and changed tests on the PR; the tests of the touched +area on the PR; a **mutation test of each source hunk** (revert it, rerun the tests; a hunk whose +reversion no test notices is a coverage finding); ruff on changed files under `uxarray/`. + +For a PR with **no source hunks** (docs, notebooks, CI, agent files), mutation testing does not apply. +Instead: build the docs if `docs/` or docstrings changed and compare warnings with base; run touched +notebooks; and check that every code reference in the changed text (paths, functions, options, commands) +exists on the PR branch and says what the text claims. + +For a **refactor or performance PR** (behavior should not change), compare outputs on base vs PR +(verification.md §Techniques, item 4) and time both (item 6). + +## Stage 4 — Report + +Write the draft to a file in the scratchpad using [references/report.md](references/report.md), then +**show it to the user and wait**. Post only after explicit approval, exactly as approved, following +report.md §Posting. Then clean up per verification.md §Cleanup (keep the PR worktree until the PR merges +if a re-review is likely). diff --git a/.agents/skills/uxarray-pr-review/references/history.md b/.agents/skills/uxarray-pr-review/references/history.md new file mode 100644 index 000000000..9c2b84583 --- /dev/null +++ b/.agents/skills/uxarray-pr-review/references/history.md @@ -0,0 +1,75 @@ +# Review history + +A PR often has reviews, threads and new commits before you arrive. Read them before looking for +problems, so the review builds on the discussion instead of repeating it. + +## Fetch everything in one query + +```bash +gh api graphql -F n=<N> -f query=' +query($n:Int!){repository(owner:"UXARRAY",name:"uxarray"){pullRequest(number:$n){ + headRefOid reviewDecision lastEditedAt isDraft + labels(first:20){nodes{name}} + reviews(first:100){nodes{author{login} state submittedAt commit{oid} body}} + reviewThreads(first:100){nodes{isResolved isOutdated path line + comments(first:50){nodes{databaseId author{login} createdAt body}}}} + comments(first:100){nodes{author{login} createdAt body}} + commits(last:100){nodes{commit{oid committedDate messageHeadline}}} + userContentEdits(first:20){nodes{editedAt editor{login}}} + timelineItems(first:100,itemTypes:[HEAD_REF_FORCE_PUSHED_EVENT,REVIEW_REQUESTED_EVENT,RENAMED_TITLE_EVENT]){nodes{ + __typename + ... on HeadRefForcePushedEvent{createdAt} + ... on ReviewRequestedEvent{createdAt requestedReviewer{... on User{login}}} + ... on RenamedTitleEvent{previousTitle currentTitle}}} +}}}' +gh pr checks <N> +``` + +Each list returns at most 100 items (50 comments per thread) and the query does not paginate; for a PR +with more, add `pageInfo{hasNextPage endCursor}` and page with `after:`. `databaseId` is the REST id used +to reply to a thread (report.md §Posting). + +Bots to skip, but read for what they tell you: +- `github-actions`: the **ASV Benchmarking** comment (present only with the `run-benchmark` label). Note + which benchmarks changed and whether anyone discussed them. +- `pre-commit-ci`: lint results; it does not push fixes unless someone comments `pre-commit.ci autofix`. +- `review-notebook-app` (ReviewNB): notebook diffs; maintainers sometimes comment there instead of on + the PR. +- Copilot reviews: treat its points as unverified suggestions; count one only if a human endorsed it or + you verify it yourself. + +## Build these from it + +1. **Rounds.** Each review: who, verdict, date, and the commit it reviewed (`commit.oid`). Who is requested + but has not reviewed yet. Two approvals is the norm before merge. +2. **Ledger of points raised.** One line per point, from review bodies, inline threads and comments: + who raised it → what the author did (commit that addressed it, reply, nothing) → status: + - **Addressed**: verify it in the current code (a mutation test or a quick check), don't trust "done". + - **Open**: still unanswered or unresolved. Authors don't resolve threads (reviewers resolve their + own), so an unresolved thread may be addressed but not yet confirmed by its reviewer. + - **Declined**: the author pushed back. Summarize both positions neutrally. + - **Superseded**: the code it referred to is gone (`isOutdated`). + Reviewers mark points "nit" or "non-blocking"; keep that label in the ledger. +3. **What changed since the last review.** Commits after the last review's commit, and their diff + restricted to the PR's files: `git diff <reviewed-oid> HEAD -- <files>`. Merges from `main` also show + up here; set aside what came from the base (`git log --first-parent`). If the branch was force-pushed + after a review, the reviewed commit may be gone: say so and review the whole PR. +4. **Scope drift.** Compare the original description and linked issue with what the PR does now. Edited + descriptions (`userContentEdits`) and fix commits often move scope; note any that were not discussed. + Check whether "Closes #N" still holds or should become "Related to #N". +5. **Where people agree and disagree.** Reviewer vs author, and reviewer vs reviewer. Points where they + disagree, or questions nobody answered (e.g. "did you run the benchmarks?"), are the candidates for + **Needs your call**. Decisions reported from maintainer meetings ("From internal discussion...", + "Reportback") settle a point; don't reopen them. + +## Use it in the review + +- **Don't repeat** a point already raised. If you have new evidence about it, reply in that thread, or + mention it in the summary with credit ("Sevans711's point 2, now fixed — verified by …"). +- **Focus on the delta.** When the user or anyone else already reviewed, look hardest at the commits after + that review: fixes made in response to a review are new, often unreviewed code. +- **Re-review.** If the current `gh` user reviewed before, check each of their own points (addressed? how?) + before anything else, and keep the new review to what changed. In the posted text, one line per earlier + point at most; often the verdict alone covers them. +- **Explain stale text.** A PR description that no longer matches the code after review-driven changes is a + routine "please update the description", not a mismatch. Say which change made it stale. diff --git a/.agents/skills/uxarray-pr-review/references/report.md b/.agents/skills/uxarray-pr-review/references/report.md new file mode 100644 index 000000000..712e4052c --- /dev/null +++ b/.agents/skills/uxarray-pr-review/references/report.md @@ -0,0 +1,77 @@ +# Review report + +## The briefing (for the user only, never posted) + +Before the draft, a few lines on where the PR stands. Leave out any line with nothing to say. + +``` +State: rounds so far (who, verdict, at which commit), who is still requested, CI +Earlier points: one line each, e.g. "Sevans711 #2 regression test: addressed in a03c46b6, verified" +Scope: drift from the issue or the original description, if any +Needs your call: disagreements or unanswered questions, both positions in one line each +``` + +## The draft shown to the user + +Show exactly what will be posted, nothing more, followed by one short line on the verification behind it. +If other reviewers have already commented, the summary says which of their points you verified as +addressed. Replies to existing threads are listed separately from new inline comments. +Keep the long evidence (tables, scripts, dropped candidates) in a scratch file and mention its path; the +user can ask for it. What was verified, and how, goes in the briefing to the user, not in the posted text. + +``` +Event: COMMENT | APPROVE | REQUEST_CHANGES (default COMMENT; the user decides) + +Summary (posted as the review body) + - One line: the verdict, and whether it does what the linked issue asks. + - One line: what is requested before merge (or "nothing"). + - Optional, one sentence each: problems that predate the PR, asking for a separate issue. + +Inline comments (at most 5, ordered by severity) + file:line — one comment each: + the problem, the evidence (what was run and what happened), the ask. + Mark optional ones "nit" or "non-blocking". Mark unverified ones as not reproduced. +``` + +Style rules: + +- Under ~80 words per inline comment. No praise filler, no restating the diff, no long bullet lists: + UXarray reviewers push back on LLM-style verbosity, and that applies to reviews too. +- One specific sentence on what the PR does well is welcome; skip it if there is nothing specific. +- Only CONFIRMED and PLAUSIBLE findings. Say which, in plain words ("I reproduced…", "not reproduced, needs + YAC"). +- Give evidence a maintainer can rerun: the snippet and its output, or the mutated hunk and the test that + still passed. +- Things the author need not change go in the same comment as "no change needed", or are left out. +- Problems that predate the PR are fine to mention only when the PR touches that exact code; say they + predate it, and suggest a separate issue rather than growing the PR. +- Replies to existing threads are one line ("Fixed in <sha>, verified."). + +## Posting + +Only after the user approves the text. + +1. Check the PR head has not moved since the review: `gh api repos/UXARRAY/uxarray/pulls/<N> -q .head.sha` + must equal the commit you reviewed. If it moved, tell the user and re-verify. +2. Check every inline anchor is inside a diff hunk on the new side (GitHub rejects others): + `gh api repos/UXARRAY/uxarray/pulls/<N>/files -q '.[] | .filename + " " + ([.patch|scan("@@ [^@]+ @@")]|join(" "))'` +3. Post one review (not separate comments) from a JSON file: + +```json +{ + "commit_id": "<head sha>", + "event": "COMMENT", + "body": "<summary>", + "comments": [{"path": "uxarray/grid/x.py", "line": 123, "side": "RIGHT", "body": "<comment>"}] +} +``` + +```bash +gh api -X POST repos/UXARRAY/uxarray/pulls/<N>/reviews --input review.json -q '.html_url' +``` + +4. Post replies to existing inline threads separately (they are not part of the review JSON): + `gh api -X POST repos/UXARRAY/uxarray/pulls/<N>/comments/<comment-id>/replies -f body='<reply>'`. + For points raised in a review body (no thread), mention them in your summary instead. Don't resolve + threads you didn't start. +5. Report the review URL to the user and confirm each inline comment landed on the intended line. diff --git a/.agents/skills/uxarray-pr-review/references/verification.md b/.agents/skills/uxarray-pr-review/references/verification.md new file mode 100644 index 000000000..9d3805d91 --- /dev/null +++ b/.agents/skills/uxarray-pr-review/references/verification.md @@ -0,0 +1,155 @@ +# Verifying findings in UXarray + +## Setup + +Use a scratch directory outside the repo (`$SCRATCH` below), e.g. the agent's scratchpad. + +```bash +# PR worktree (never switch branches in the user's checkout). --detach: the PR branch may already be +# checked out in another worktree, e.g. when reviewing your own or a colleague's branch. +git fetch origin +git worktree add --detach $SCRATCH/pr<N> origin/main +(cd $SCRATCH/pr<N> && gh pr checkout <N> --detach) + +# Clean base worktree, for "does this also happen on main?" comparisons +git worktree add --detach $SCRATCH/base-wt origin/<base> +``` + +**Environment.** Reuse an existing conda env built from `ci/environment.yml` (`uxarray_build`) if there +is one; otherwise create it (several minutes): + +```bash +conda env create -f ci/environment.yml # env "uxarray_build": test deps, geo + viz extras +PY=$(conda run -n uxarray_build which python) +``` + +Don't install the worktree into the env. Select the tree under test with `PYTHONPATH` and check it took +effect: the env may hold a stale non-editable copy, or an editable install of the user's checkout, and +running from the repo root hides that. + +```bash +cd $SCRATCH && PYTHONPATH=$SCRATCH/pr<N> $PY -c "import uxarray; print(uxarray.__file__)" # must print pr<N> +``` + +`uxarray.__version__` comes from installed metadata, so it does not identify the tree; use `__file__`. + +**Faster test runs** (optional). The env has no `pytest-xdist`. Overlay a venv on it and pin to the env's +versions, or uv upgrades numpy past what numba supports: + +```bash +$PY -m pip list --format=freeze | grep -vi '^uxarray' > $SCRATCH/constraints.txt +uv venv -q --system-site-packages --python $PY $SCRATCH/ux-env +VIRTUAL_ENV=$SCRATCH/ux-env uv pip install -q -c $SCRATCH/constraints.txt pytest-xdist +export PROJ_DATA=$(dirname $(dirname $PY))/share/proj # overlay venvs miss it: pyproj DataDirError +``` + +The full suite (~1250 tests, no network needed) takes about 3 min serially and under 1 min with `-n auto`. +Run the touched area first, the full suite at the end. + +**Numba cache.** `@njit(cache=True)` writes its cache into `__pycache__` inside each tree, so a fresh +worktree compiles cold (first runs can be ~10x slower). Never time a first run. + +## Techniques + +Pick the ones that fit the candidate. The first two apply to almost every PR. + +1. **Mutation test each source hunk.** Copy the PR tree (`rsync -a --exclude .git`), revert one hunk (or + replace the new logic with the old behavior), and run the PR's tests with `PYTHONPATH` pointing at the + copy. If the tests still pass, that hunk is untested: run an experiment to show what breaks without it, + and report it as a coverage finding with that consequence. + - "The new tests fail on main" is weak evidence when they fail only because a new symbol does not + exist yet (ImportError). Mutate the behavior, not the existence. +2. **Sweep the inputs and options the change touches.** Write a short script that runs the changed path, + on the PR and on base, over the axes the caller allows, and report the table: + - meshes: an all-quad mesh *and* a mixed-size mesh with fill values (see the table below); + - geometry: a face crossing the antimeridian, a face containing a pole, a vertex exactly on lon 0 or + ±180, and the same face **rotated** by a few degrees (rotation must not change the topology of the + result: this kind of sweep exposed the pole-detection bug in #1657); + - data: node / edge / face-centered; extra dims (`time`, `lev`) before and after the grid dim; + numpy and chunked; + - options: `periodic_elements`, `destination`, `remap_to`, `backend`, `latlon`, `inverse_indices`. + Build small custom faces inline: `ux.Grid.from_face_vertices(np.array([[[lon, lat], ...]]), latlon=True)`. +3. **Compare against an independent answer.** Analytic values (total area of a global mesh is 4π on the + unit sphere: `ux.open_grid(<outCSne30.ug>).calculate_total_face_area()` matches to ~1e-11), an + independent formula for a single face (remember UXarray edges are great-circle arcs), the accuracy + baselines in `test/grid/geometry/`, or `Grid.validate()` for grid construction. +4. **Base vs PR equivalence.** For a refactor or performance change: run the same script with + `PYTHONPATH` at each tree, save outputs, and compare with `np.testing.assert_allclose` or + `xr.testing.assert_identical` (attrs and coords too; losing them is a past bug class). Compare grids + with `Grid.__eq__` or the connectivity arrays directly. +5. **Grid and laziness invariants.** + - `uxgrid` survives: `(v * 2).uxgrid is v.uxgrid`; type stays `UxDataArray`; after a subset or + reorder, `result.uxgrid.n_face == result.sizes["n_face"]`. + - Chunked input stays lazy — count graph executions: + ```python + import dask, dask.array + class Counter(dask.callbacks.Callback): + n = 0 + def _start(self, dsk): Counter.n += 1 + vc = v.chunk({"n_face": 1000}) + with Counter(): out = (vc - vc.mean()) * 2 + assert isinstance(out.data, dask.array.Array) and Counter.n == 0 + ``` + Some functions use `apply_ufunc` with the grid dim as a core dim (e.g. `gradient`), which rejects + multiple chunks along `n_face`; for those, chunk a non-grid dim instead. + - `import uxarray` stays cheap: `test/test_dependencies.py` and `test/utils/test_imports.py` cover + kernel compilation and optional-dependency imports; also time `python -X importtime -c "import uxarray"` + on base vs PR if imports changed. +6. **Timing.** For a quick A/B, a `timeit` script run under each tree's `PYTHONPATH`, after a warm-up call + so numba compilation is excluded. Identical code differs by ~5% between runs: repeat and alternate + the order before calling anything a regression. ASV for a single benchmark without building: + ```bash + cd $SCRATCH/pr<N>/benchmarks && asv machine --yes + PYTHONPATH=$SCRATCH/pr<N> asv run --python=same --quick --bench "quad_hexagon.QuadHexagon.time_open_grid" + ``` + Importing `benchmarks/helpers/_fixtures.py` downloads ~107 MB of meshes into `benchmarks/` (not + gitignored); do it only in a scratch worktree. For full ASV results in CI, suggest the `run-benchmark` + label. +7. **Debug kernels.** `NUMBA_DISABLE_JIT=1` runs jitted code as Python for real tracebacks and `pdb`. Don't + time with it. +8. **Docs.** For docstring or `docs/` changes, a fast build without executing notebooks, run inside each + worktree (the build writes into `docs/`), needs sphinx and the extensions from `ci/docs.yml`: + ```bash + cd $SCRATCH/pr<N>/docs && PYTHONPATH=$SCRATCH/pr<N> sphinx-build -b html -q \ + -D nb_execution_mode=off -D nbsphinx_execute=never . $SCRATCH/docs-pr 2> $SCRATCH/docs-pr.log + ``` + Do the same on base and diff the sorted warning lists: `main` has some warnings already; only new ones + are findings. Check new public names in `docs/api.rst` (nothing else checks it). Run a changed notebook + with `jupyter nbconvert --execute --to notebook --output $SCRATCH/nb.ipynb <path>`, or point to the + Read the Docs preview: `https://uxarray--<N>.org.readthedocs.build/en/<N>/`. +9. **Lint.** ruff excludes `test/` and `benchmarks/`; use the version pinned in `.pre-commit-config.yaml`: + ```bash + git -C $SCRATCH/pr<N> diff --name-only --diff-filter=AMR origin/<base>...HEAD -- 'uxarray/*.py' '*.ipynb' \ + | (cd $SCRATCH/pr<N> && xargs uvx ruff@<pinned> check) # then the same with `format --check` + ``` + +### Test meshes (`test/meshfiles/`) + +| Path | Use it for | +|---|---| +| `ugrid/quad-hexagon/grid.nc` (+ `data.nc`, `random-{node,edge,face}-data.nc`, `multi_dim_data.nc`) | Tiny (4 faces) mixed quad/hexagon grid with fill values; first choice for repros | +| `mpas/QU/mesh.QU.1920km.151026.nc` | Small global MPAS mesh (162 faces), fill values | +| `ugrid/outCSne30/outCSne30.ug` (+ `_vortex.nc`, `_var2.nc`) | Global cubed sphere (5400 quads), area = 4π | +| `ugrid/outRLL1deg/outRLL1deg.ug` | Lat-lon grid with pole rows | +| `scrip/outCSne8/`, `exodus/outCSne8/`, `exodus/mixed/`, `esmf/ne30/`, `geos-cs/c12/`, `icon/R02B04/` (largest, 15 MB), `fesom/` | Reader-specific checks | +| `scrip/scrip_radians/`, `scrip/oasis/` | SCRIP edge cases (radian units, OASIS masks) | +| `structured/`, `points/`, `shp/`, `geojson/`, `healpix/` | `from_structured`, `from_points`, geopandas readers, HEALPix data (grid via `ux.Grid.from_healpix(zoom=...)`) | + +### What can't be verified locally + +YAC remapping (built from source only in `yac-optional.yml`), the DYAMOND benchmarks (NCAR GLADE only), +and OS-specific behavior (Windows int dtypes, paths) unless you have that OS: label those PLAUSIBLE and +point to the CI job that covers them. In `gh pr checks`, the min-deps result shows in `report-failed` +(the `min-deps` job itself is `continue-on-error`). + +Keep every script you write in `$SCRATCH`: they are the evidence, and the author can be pointed to them. + +## Cleanup + +```bash +git worktree remove --force $SCRATCH/pr<N> # after the PR merges, if a re-review was possible +git worktree remove --force $SCRATCH/base-wt +``` + +`--force` is needed because the numba cache, docs build output and benchmark downloads leave untracked +files in the worktrees. diff --git a/.claude/skills/uxarray-issue-triage b/.claude/skills/uxarray-issue-triage new file mode 120000 index 000000000..e727b26a6 --- /dev/null +++ b/.claude/skills/uxarray-issue-triage @@ -0,0 +1 @@ +../../.agents/skills/uxarray-issue-triage \ No newline at end of file diff --git a/.claude/skills/uxarray-pr-review b/.claude/skills/uxarray-pr-review new file mode 120000 index 000000000..547d9792a --- /dev/null +++ b/.claude/skills/uxarray-pr-review @@ -0,0 +1 @@ +../../.agents/skills/uxarray-pr-review \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..fc5a65ebc --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,260 @@ +# AGENTS.md + +Guidance for coding agents (Claude Code, Codex, Copilot, Cursor, etc.) working in this repository. The +repository is the source of truth: if anything here disagrees with the code, follow the code and point +out the stale line. + +## About + +UXarray is an xarray extension for analysis and visualization of **unstructured** grids, mostly from +climate and weather models. It is pure Python; hot loops are JIT-compiled with numba. + +- `UxDataset` / `UxDataArray` subclass `xr.Dataset` / `xr.DataArray` and carry a `Grid` (`.uxgrid`). +- `Grid` (`uxarray/grid/grid.py`) is **not** an xarray subclass: it wraps a plain `xr.Dataset` of + UGRID-named variables in `Grid._ds`. Maintainers don't want `Grid` to grow Dataset-like API (#1647). +- Every supported format (UGRID, MPAS, ICON, SCRIP, ESMF, Exodus, FESOM2, GEOS-CS, HEALPix, shapefile / + GeoJSON, points via Delaunay/Voronoi, ...) is converted to one internal UGRID-style representation. The + minimum is `node_lon`, `node_lat`, `face_node_connectivity`. +- Scope: horizontally 2D grids on the sphere (vertical levels are ordinary dims), convex faces (#1597). + Structured grids enter only through explicit APIs such as `Grid.from_structured()`, never through + `open_dataset()` / `open_grid()` (#1887). +- Mirror xarray's API, names and behavior wherever there is a natural analogue (#1461, #1573). + +## Commands + +```bash +# Dev environment (conda env "uxarray_build", as CI uses), then install the working tree +conda env create -f ci/environment.yml +conda activate uxarray_build +pip install -e . --no-deps +# or, without conda: pip install -e ".[all]" (extras: dev, geo, viz, all/complete) + +python -m pytest test # full suite (testpaths = ["test"]) +python -m pytest test/grid/geometry # one area +python -m pytest test/core/test_dataset.py::test_x -x # one test +pre-commit run --all-files # ruff lint + format, yaml, whitespace, ... +``` + +- `test_optional_deps/` is deliberately outside `testpaths`; CI runs it in separate installs with no + extras, `[geo]`, `[viz]` and `[geo,viz]` (`ci.yml`, job `test-optional-deps`). +- Docs build in their own env: `conda env create -f ci/docs.yml` (env `uxarray-docs`), then + `cd docs && make html`. Notebooks execute during the build, so it is slow and needs network. +- No pytest markers are registered; select tests by path. + +## Repo map + +| Path | Contents | +|---|---| +| `uxarray/__init__.py` | The public top-level API. Not listed here → not top-level public. | +| `uxarray/core/` | `UxDataArray`, `UxDataset`, `api.py` (`open_grid`, `open_dataset`, `open_mfdataset`, ...), `accessors.py` (groupby/resample/... wrappers), aggregation, gradient, zonal | +| `uxarray/grid/` | `Grid` and the topology/geometry numerics: connectivity, coordinates, geometry, arcs, intersections, area, bounds, neighbors (trees, spatial hash), dual, `slice.py`, validation, point_in_face, integrate | +| `uxarray/conventions/` | **Naming authority** for UGRID dims/coords/connectivity (`ugrid.py`), descriptors, and `attrs.py` | +| `uxarray/io/` | One reader per format (`_<fmt>.py`) + `utils.py` (format detection) | +| `uxarray/remap/`, `subset/`, `cross_sections/`, `plot/` | Accessor-based features (`.remap`, `.subset`, `.cross_section`, `.plot`) | +| `uxarray/utils/` | `computing.py` (compensated arithmetic), `numba_math.py`, `parallel.py` (`parallel_njit`), `imports.py` (optional deps), `warnings.py` | +| `test/` | pytest suite; data in `test/meshfiles/<format>/<dataset>/`; ruff-excluded | +| `benchmarks/` | ASV suite (`helpers/` holds fixtures, warm-up, peakmem helpers); ruff-excluded | +| `docs/` | Sphinx + myst-nb; `api.rst` is the hand-maintained API index | + +## Core data model + +- A `UxDataset` and the `UxDataArray`s taken from it share **one `Grid` by reference**; only a deep copy + clones it. +- `self.uxgrid` raises `GridInvalidError` when no grid is attached; use it in anything grid-aware. + `self._uxgrid` may be `None` (xarray's `_replace`/`_construct_direct` rebuild objects without + kwargs) and is for copy/replace/init plumbing only. `UxDataArray(...)` without `uxgrid=` succeeds and + fails later at the first grid-aware call. +- Grid preservation through xarray operations is explicit: `__getattribute__` in `dataarray.py` / + `dataset.py` wraps `groupby`, `groupby_bins`, `resample`, `rolling`, `coarsen`, `weighted`, + `rolling_exp`, `cumulative` with the classes in `core/accessors.py`, and `where`/`fillna` are + overridden. A new xarray method that returns an object needs the same treatment, or results lose the + grid. +- Combining objects on **different grids** raises `GridsMismatchError`; never silently keep one grid. +- Results that no longer have a grid dimension: `zonal_mean` returns plain xarray, but the general rule + is still undecided (#1733). Ask instead of picking one. +- `UxDataArray.isel(..., ignore_grid=False, inverse_indices=False)` slices the grid along with the data + through `Grid.isel` (`grid/slice.py`). `Grid.inverse_indices` maps a subset back to its source grid. +- Operations that change topology return a **new** `Grid`; adding derived variables to an existing grid + is fine. +- File writing goes through xarray (`uxds.to_xarray().to_netcdf()`, `uxgrid.to_xarray()`); don't add + write APIs such as `Grid.to_netcdf()` (#1836). + +## Grid variables are declared in `uxarray/conventions` + +`conventions/ugrid.py` declares every UGRID dim, coordinate and connectivity name with its `dims` tuple +and `attrs`; `conventions/descriptors.py` does the same for descriptors. The name lists there +(`DIM_NAMES`, `SPHERICAL_COORD_NAMES`, `CARTESIAN_COORD_NAMES`, `CONNECTIVITY_NAMES`, +`DESCRIPTOR_NAMES`) drive `Grid.dims`/`.coordinates`/`.connectivity`/`.descriptors`, `repr(grid)` and +the HTML repr: a variable that isn't registered works but stays invisible. Use these constants +rather than literal attrs dicts. + +There is no `cached_property`: presence in `Grid._ds` is the cache. + +```python +@property +def edge_node_connectivity(self) -> xr.DataArray: + if "edge_node_connectivity" not in self._ds: + _populate_edge_node_connectivity(self) + return self._ds["edge_node_connectivity"] +``` + +followed by `x = x.setter(make_setter("x"))`. To add a derived variable: declare `_DIMS`/`_ATTRS` and +register the name in `conventions/`; write `_populate_<name>(grid)` in the matching `grid/` module +(kernel in a separate jitted function); add the guarded property + setter in `grid.py`; list it in +`docs/api.rst`; test that it populates on demand with the right dims. Some variables are built in +pairs: computing `edge_node_connectivity` also derives `face_edge_connectivity` in the same edge order, +so code that renumbers edges must keep both consistent (see the `Grid.edge_node_connectivity` +docstring). + +Non-UGRID derived state (spatial trees, antimeridian face indices, plotting caches) is cached in private +attributes set in `Grid.__init__`; reuse `Grid.get_ball_tree()`, `get_kd_tree()` and +`get_spatial_hash()` rather than building new trees. + +## Numeric conventions (`uxarray/constants.py`) + +- Index arrays use `INT_DTYPE` (`np.intp`); ragged connectivity is padded with `INT_FILL_VALUE` + (`np.iinfo(np.intp).min`), never `np.nan`, `-1` or `0`. Only these two constants are top-level public. +- Tolerances: `ERROR_TOLERANCE` (1e-8) for geometric "is this degenerate/normalized/at the pole" checks; + `MACHINE_EPSILON` only for near-machine-precision arc/intersection math. They are not interchangeable. +- Geometry is computed on the **unit sphere**; the physical radius is `Grid.sphere_radius`. +- Spherical coordinates are **degrees** with longitude in **[-180, 180]**; internal radian helpers use + **[0, 2π)**. Mixing the two ranges is a recurring bug. +- Projected grids (coordinates in meters) skip longitude wrapping with a one-time warning; spherical + geometry does not apply to them (`grid/coordinates.py::_set_desired_longitude_range`). +- Antimeridian-crossing faces: `Grid.antimeridian_face_indices`; plotting and `to_geodataframe` take + `periodic_elements="exclude" | "split" | "ignore"`. +- Accuracy-sensitive geometry (great-circle arcs, intersections, areas) uses the compensated / error-free + primitives in `uxarray/utils/computing.py` (`two_sum`, `diff_of_products`, `accucross`, ...), checked + by `test/grid/geometry/test_eft_accuracy.py` and `test_accusphgeom_baseline.py`. Don't replace them + with naive arithmetic, don't use `fastmath=True` (it breaks compensation), and don't claim + "robust"/"exact" in comments unless a test shows it. + +## numba and dask + +- Kernels use `@njit(cache=True)`. Parallel kernels use `@parallel_njit` (`utils/parallel.py`), not raw + `njit(parallel=True)`: it runs the kernel under `numba_pool()`, which keeps numba's thread pool safe + when called from dask threads. It is only for kernels called from Python, not from other jitted code. +- `import uxarray` must not compile any kernel or start numba's threading layer + (`test/test_dependencies.py::test_no_numba_kernels_built_on_import`), so no module-level work that + triggers compilation. +- Inside kernels, don't allocate small numpy arrays in loops; use scalars or tuples and the 3-vector + helpers in `utils/numba_math.py` (#1648). +- Keep chunked (dask) data lazy: no `.values` / `np.asarray` on whole arrays, no silent rechunking. + Prefer `xr.apply_ufunc` over numba kernels and go through xarray (`.compute()`), not dask directly. + Some global-topology and spatial-index operations must materialize; say so when they do. +- Setting `NUMBA_DISABLE_JIT=1` steps through kernels in a debugger; there is no project-level toggle. + +## Optional dependencies + +Hard dependencies are listed in `pyproject.toml` `dependencies`. Plotting and geo packages (cartopy, +geopandas, healpix, pyproj, spatialpandas, datashader, matplotlib, geoviews, holoviews, hvplot) are the +optional extras `[geo]` / `[viz]` (#1548). Rules, enforced by `test/utils/test_imports.py`: + +- Import optional packages **inside functions only**, never at module level (`if TYPE_CHECKING:` is + exempt). +- Before importing them, call `_raise_hint_if_optional_deps_missing("pkg", ...)` + (`uxarray/utils/imports.py`), naming every optional package the function imports. It raises + `OptionalDependencyNotFoundError` with a `pip install "uxarray[viz]"`-style hint. A new optional + dependency must also be added to `_OPTIONAL_DEPS_TO_EXTRAS`. +- YAC is a remap **backend** (`backend="yac"`), not in any extra; it is imported lazily and raises + `YacNotAvailableError`. Its tests (`test/test_remap_yac.py`) skip without `yac.core`; they run in `.github/workflows/yac-optional.yml`, which builds YAC from source on `uxarray/remap/**` changes. +- Lower bounds on dependencies are added only for a known failure, with a comment saying what breaks. + Min-deps CI (`min-deps-ci.yml`) tests the oldest allowed versions on every PR, so using a newer API of + a dependency may require raising its bound. + +## Errors and warnings + +- Domain errors use the types in `uxarray/errors.py`: `DataCenteringError`, `DimensionError`, + `GridInvalidError`, `GridsMismatchError` (all `ValueError` subclasses), `YacNotAvailableError`, + `OptionalDependencyNotFoundError`. New custom types go there. Plain `ValueError` / `TypeError` / + `FileNotFoundError` stay correct for generic argument checks. +- Messages state expected **and** actual (e.g. "expected node-centered data, got edge-centered") and + tell the user what to do; they don't mention private names. Don't validate with `assert`, and don't + wrap calls in broad `try/except` that hides the original error. Invalid input raises; it never + silently produces a different result. +- Docstrings name custom errors as e.g. "DimensionError (subclass of ValueError)". +- New warnings use `stacklevel=find_stack_level()` (`utils/warnings.py`). Deprecations use + `FutureWarning`, and deprecated code is removed after about a year (#1707). + +## Adding features + +- **Grid format**: detection (`_is_<fmt>` + the if/elif chain in `io/utils.py::_parse_grid_type`) and + dispatch (`Grid.from_dataset`) are two ordered chains, not a registry; first match wins. The reader + `io/_<fmt>.py::_read_<fmt>` returns `(grid_ds, source_dims_dict)`. Add a small mesh under + `test/meshfiles/<fmt>/`, tests under `test/io/`, and the format in `docs/user-guide/grid-formats.rst`. +- **Remap / subset / plot**: add the method on the accessor (`remap/accessor.py`, + `subset/grid_accessor.py` + `subset/dataarray_accessor.py`, `plot/accessor.py`), keep its `__repr__` + method list current, and list it in `docs/api.rst` (accessor methods use + `:template: autosummary/accessor_method.rst`). Plotting calls `plotting_backend.assign(backend)` and + imports hvplot lazily through `_ensure_hvplot_imported()`; keep that, as `import uxarray` time is + watched. + +## Tests + +- pytest only (no `unittest.TestCase`). Mostly module-level `def test_*`; plain `class Test...` groups + exist for variants. Layout loosely mirrors the package (`test/core/`, `test/grid/...`, `test/io/`). +- Get data paths through the `test/conftest.py` fixtures (`gridpath`, `datasetpath`, `test_data_dir`, + `mesh_constants`): `gridpath("ugrid", "quad-hexagon", "grid.nc")`. Passing a **list** of filenames + makes a missing file skip the test instead of failing. +- A bug fix needs a regression test that **fails on `main`** and passes with the fix; reviewers check + this. Tests must assert what their name says, not just call the function. +- Prefer existing meshfiles or a tiny hand-built mesh over new large files; compare floats with + `np.testing.assert_allclose` / `np.isclose` and justify tolerances and expected values (analytic + values, a reference implementation) rather than magic numbers. +- Don't assume dimension order or 1-D data: cover extra dims (e.g. `time`) and use `.sizes` / `.isel`. +- Optional-dependency imports in tests: `try/except ImportError` + `pytest.skip`, or a `skipif` reusing + the source's own check. Tests must be fast; use `monkeypatch` rather than mutating global state. + +## Benchmarks + +ASV under `benchmarks/` (`asv.conf.json`: Python 3.12, env from `ci/environment.yml`). PR benchmarks run +when the `run-benchmark` label is added, in two workflows split for security (#1547): don't merge them. +Put fixture building and numba warm-up in `setup()`, not in timed methods; use `number = 1` when repeat +calls would hit a cache; no assertions. Reviewers expect ASV results (and an accuracy check) on +performance PRs, and a new benchmark when a hot path has none. Peakmem results are noisy. + +## Lint and formatting + +ruff (lint, import sort, format) via pre-commit, also on notebooks. `test/` and `benchmarks/` are +excluded from ruff (`extend-exclude`), so don't reformat them in a functional PR. pre-commit.ci reports +on PRs but doesn't push fixes; comment `pre-commit.ci autofix` to get them. + +## Docs + +- Docstrings are **numpydoc** (`sphinx.ext.napoleon`). `autodoc_typehints = "none"`, so types reach the + docs only through the `Parameters` section. Examples are not doctested. Private helpers may have + short docstrings. +- New public API is listed by hand in `docs/api.rst`; internal names start with `_`. +- A new user-facing feature also gets a user-guide section or notebook; reviewers ask for this before + merge. User-guide notebooks go in `docs/user-guide/` and both lists in `docs/userguide.rst`; gallery + examples go in `docs/examples/` plus `docs/gallery.yml`, `docs/gallery.rst` and a thumbnail. +- Clear notebook outputs before committing, except notebooks in `nb_execution_excludepatterns` + (`docs/conf.py`), whose stored outputs are what the docs render. Notebooks run on Read the Docs, so + they can't use data that exists only on NCAR's GLADE. +- Docs are concise reference for people who know their models, not a tutorial on unstructured grids. +- Vocabulary: node, edge, face, connectivity, fill value (`docs/user-guide/terminology.rst`). +- `docs/contributing.rst` is out of date (being rewritten, #1831): it prescribes Google-style + docstrings, `unittest` and `docs/user_api/index.rst`. The code uses numpydoc, pytest and + `docs/api.rst`; follow the code. + +## Pull requests + +- Follow `.github/PULL_REQUEST_TEMPLATE.md`. The title is a descriptive summary. Use "Closes #N" only if + the PR fully resolves the issue, otherwise "Related to #N". Every PR has a linked issue. +- **AI disclosure**: fill in the "AI Usage:" line (tools, optionally model and how they were used). The + responsibility checkbox is the human author's to tick; leave it unticked in drafts you write. +- Open as draft until ready. Don't resolve review threads you didn't start; reviewers resolve their own. + Two approvals is the norm; the author usually merges. +- Keep PRs focused: split large multi-bug PRs and open issues for follow-ups. Behavior changes that + aren't the point of the PR (ordering, defaults, dtypes) go in the description. +- Reviewers push back on typical LLM output: unneeded defensive code, over-general helpers and + hedging, boilerplate module docstrings, comments that don't match the code, and long bullet-list PR + descriptions. Write the minimal change, and keep docs, comments and descriptions short and accurate. +- Decisions are often made in maintainer meetings and posted back on the issue ("From internal + discussion..."); read the whole thread before proposing a design. + +## Agent skills + +Task-specific instructions live in `.agents/skills/` (see `.agents/README.md`): `uxarray-pr-review` +(review a PR and verify each finding by running code) and `uxarray-issue-triage`. Agents that support skills discover them in `.agents/skills/`. Keep this the only project +instructions file, so every agent sees the same text.