From 6d538854450759925735852bcf372ea57dac657e Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 12:25:23 +0100 Subject: [PATCH 1/6] =?UTF-8?q?=F0=9F=94=A7=20Tell=20ruff=20.claude/hooks/?= =?UTF-8?q?=20is=20a=20namespace=20dir?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Claude Code hooks are standalone scripts that share a helper module. The directory is deliberately not a package, the same way the other namespace directories listed here are not. Assisted-by: LLM --- .ruff.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/.ruff.toml b/.ruff.toml index 54649fdd55..fcc8f97115 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -1,6 +1,7 @@ line-length = 79 # Accessibility-friendly namespace-packages = [ + ".claude/hooks/", "bin/", "cheroot/test/", "docs/", From 033264900765d76fff814a3bcc2eeb432497ff08 Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 12:25:25 +0100 Subject: [PATCH 2/6] =?UTF-8?q?=F0=9F=A7=AA=20Let=20wemake=20accept=20the?= =?UTF-8?q?=20`=5Ft`=20typing=20alias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `flake8-typing-as-t` already makes `typing` imported as `_t`, but only stub files used it so far, where WPS checks are off. The Claude Code hooks coming next use it in regular modules, so wemake's `allowed-domain-names` now accepts `_t` and `_c` as legitimate short module aliases, like in ansible/pylibssh. Assisted-by: LLM --- .flake8 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.flake8 b/.flake8 index 68a4c514ab..c79a58df2d 100644 --- a/.flake8 +++ b/.flake8 @@ -177,5 +177,10 @@ pytest-mark-no-parentheses = true typing-as-t-imported-name = _t # wemake-python-styleguide +# WPS111: +# `_t` will be enforced by `flake8-typing-as-t` +allowed-domain-names = + _t, + _c, show-source = true show-violation-links = true From f664b57db15b4f835f253d9eac98abae1901cabe Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 12:25:26 +0100 Subject: [PATCH 3/6] =?UTF-8?q?=F0=9F=93=9D=20Import=20the=20agent=20docs?= =?UTF-8?q?=20from=20ansible/pylibssh?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md, CLAUDE.md and the shared .agents-ctx/ docs are copied unchanged from ansible/pylibssh as of 5ff33f5d, so the next commit shows exactly what differs here. The pylibssh-only CYTHON_AND_LIBSSH.md is left out. Assisted-by: LLM --- .agents-ctx/.gitignore | 3 + .agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md | 140 +++++++++++ .agents-ctx/DONT_GHOST_THE_REVIEWER.md | 137 +++++++++++ .agents-ctx/DONT_SHOOT_THE_MESSENGER.md | 180 ++++++++++++++ .agents-ctx/HOUSE_RULES.md | 137 +++++++++++ .agents-ctx/HOUSE_STYLE.md | 85 +++++++ .agents-ctx/HUMAN_IN_THE_LOOP.md | 95 ++++++++ .agents-ctx/LICENSING.md | 34 +++ .agents-ctx/NAMING_THE_DUCKS.md | 32 +++ .agents-ctx/PR_HYGIENE.md | 226 ++++++++++++++++++ .agents-ctx/README.md | 3 + .agents-ctx/TESTING.md | 219 +++++++++++++++++ .agents-ctx/WHERE_TO_LOOK_FIRST.md | 33 +++ AGENTS.md | 5 + CLAUDE.md | 4 + 15 files changed, 1333 insertions(+) create mode 100644 .agents-ctx/.gitignore create mode 100644 .agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md create mode 100644 .agents-ctx/DONT_GHOST_THE_REVIEWER.md create mode 100644 .agents-ctx/DONT_SHOOT_THE_MESSENGER.md create mode 100644 .agents-ctx/HOUSE_RULES.md create mode 100644 .agents-ctx/HOUSE_STYLE.md create mode 100644 .agents-ctx/HUMAN_IN_THE_LOOP.md create mode 100644 .agents-ctx/LICENSING.md create mode 100644 .agents-ctx/NAMING_THE_DUCKS.md create mode 100644 .agents-ctx/PR_HYGIENE.md create mode 100644 .agents-ctx/README.md create mode 100644 .agents-ctx/TESTING.md create mode 100644 .agents-ctx/WHERE_TO_LOOK_FIRST.md create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.agents-ctx/.gitignore b/.agents-ctx/.gitignore new file mode 100644 index 0000000000..91dee74955 --- /dev/null +++ b/.agents-ctx/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!*.md diff --git a/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md b/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md new file mode 100644 index 0000000000..a10b0a0962 --- /dev/null +++ b/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md @@ -0,0 +1,140 @@ +# Workflow & Tooling Infrastructure + +The project uses `tox` as the single entry point for all local +automation -- the same one CI and core devs use. Agents must +never bypass it by invoking the wrapped tools (`pytest`, +`pre-commit`, `coverage`, `build`, `towncrier`, etc.) directly; +doing so skips project-specific configuration and is liable to +run with unsupported, undefined, or outright dangerous defaults. + +## `tox list` is the source of truth + +The contributing docs mention some environments, but that's not +exhaustive or authoritative -- `tox list` is. Run it to see +every available environment, each with its own description. +Don't assume an environment exists, or what it does, without +checking there first. + +## Running tests + +`tox run -e py` runs the test suite under whichever Python +runtime is currently active. Other environments cover other +purposes (linting, building docs or dists, drafting the changelog, +etc.) -- check `tox list` rather than assuming `py` is the only +one relevant to a given task. + +## Default to low verbosity + +Prefer `tox run -e py -qq` by default. Only reach for more +verbose tox-level output (drop the `-q`, or add `-v`/`-vv`) once +there's an actual reason to inspect tox's own internals -- don't +lead with a wall of logs. + +## Spell commands out + +Use the long subcommand forms -- `tox run`, `tox list`, +`tox config` -- in automation, docs, and anything shown to the +operator. `tox r`/`tox l` are fine interactively but easy to +misread in scripts and CI logs. + +The same goes for the options of any tool used in scripts, spec +files, and CI: `sed --in-place` over `sed -i`, `git rebase +--interactive` over `git rebase -i`. + +Don't invent flags. Check `tox --help` when unsure: +e.g. env selection is `-e` only, there's no `--env`. + +## `pyNNN`-style environment names are native tox behavior + +`tox run -e py312` isn't something this project specifically +configured -- it's tox's own built-in convention: an env name +matching `pyNN`/`pyNNN` makes tox look up a `python3.N` +interpreter and create/use `.tox/py312` for it, if available. +This, and other generic tox mechanics not specific to this +project, are covered by tox's own documentation -- read that +rather than expecting everything generic about tox to be +re-explained here. + +## Passing arguments through to the wrapped tool + +Arguments after a bare `--` are forwarded to whatever tool the +environment wraps. For example, `tox run -e py -- -k smoke` +passes `-k smoke` to `pytest`, selecting only the matching tests. + +Watch out, though: when a `commands =` line uses +`{posargs:}` with a *non-empty* default, anything +passed after `--` **replaces that default wholesale** -- it does +not get appended to it. Always check what a given env's default +posargs actually are (`tox config -e `, or read `tox.ini`) +before assuming `--` just "adds more flags." + +Here: `py` and `just-pytest` use a bare `{posargs:}`, so e.g. +`tox run -e py -- -n0` (disabling `pytest-xdist` parallelism) +loses nothing. Other envs do have non-empty defaults: + +- `pre-commit` defaults to `--all-files`; passing + `-- --files ...` checks only those files instead. +- `build-docs`'s Sphinx invocation defaults to a full flag set + (`-j auto -b html ... -a -n -W --keep-going -d ... . `) + -- passing any custom posargs there replaces the whole thing. +- `make-changelog`'s default posargs are `'[UNRELEASED DRAFT]' + --draft` (draft-preview mode); its own `description` field + documents overriding this deliberately -- passing a real version + after `--` (e.g. `tox run -e make-changelog -- 1.3.2`) switches + it into actually cutting that release, dropping `--draft` + entirely. + +## Read the tool's own output + +Many envs print follow-up instructions after running -- where an +artifact landed, how to open or serve it, how to install hooks. +Read what the invocation actually printed instead of guessing a +path or a next step. + +Here: `build-docs` prints where the built HTML docs landed and how +to serve them locally; `pre-commit` prints a reminder of how to +install its hooks into Git. + +## Parse structured output, not text meant for humans + +When an agent needs to act on a tool's results, it should ask for +machine-readable output and parse that, rather than scrape text +laid out for people. Human-readable output is for the operator, +and its layout shifts between versions and locales. For example: +`gh ... --json`, `git status --porcelain`, `git ls-remote`, +`git for-each-ref --format=...`, coverage's XML or JSON reports, +or `tox config`. + +## Make sure a check saw the real state + +- `tox run -e pre-commit` only checks the files Git tracks. Mark + new files with `git add --intent-to-add`, or commit them, before + reporting the run as clean. +- Keep the log of every failed attempt. When a retry passes, + report the failure too and look into it, instead of presenting + only the green run. + +## Don't use `git stash` + +Its list is shared by all worktrees of a repository and holds the +operator's own entries, so popping the wrong one is easy. Save +work in progress as a patch file or a commit on a scratch branch. + +## Red checks get fixed, not silenced + +When `pre-commit`, `py`, or any other env reports failures, fix their +cause. Suppressing a finding, or skipping/removing a test, is the +operator's decision -- see +[DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md). + +## Shared automation across projects + +The maintainer looks after many open source projects, at work and +on personal time, and shares automation between them in various +forms -- CI workflows, composite actions, tool configs, these +agent docs. Drift between similar projects makes that harder. + +When changing shared tooling, consider whether the change is +generic or project-specific. If it looks generic, point that out +to the operator so it can be propagated -- don't propagate it +yourself. Drift is fine when there's a deliberate reason for it. diff --git a/.agents-ctx/DONT_GHOST_THE_REVIEWER.md b/.agents-ctx/DONT_GHOST_THE_REVIEWER.md new file mode 100644 index 0000000000..c019c4a5de --- /dev/null +++ b/.agents-ctx/DONT_GHOST_THE_REVIEWER.md @@ -0,0 +1,137 @@ +# Don't Ghost the Reviewer + +Grounded in the maintainer's own stated views, from a first-person +review comment and a public PR discussion — not guesses. This +covers a well-known, repeatedly-observed failure mode: contributors +(often assisted by AI agents, especially inexperienced "AI drivers") +who submit PRs and then behave badly during review, making the +process worse for everyone and lowering the odds of merging. + +## Before submitting something significant, encourage a reset + +Read the whole diff, top to bottom, before submitting -- be able +to explain any part of it if asked. That's what "the PR author is +supposed to be the very first reviewer of whatever patch they +submit" (see below) actually requires in practice, not a one-time +skim. + +When the operator is about to submit a significant new +contribution, suggest a deliberate break first -- a walk, a nap, +stepping away for a while -- and explain why: a controlled context +reset helps surface tunnel vision, sunk-cost thinking, or a "just +ship it" impulse that's easy to miss mid-flow. This isn't a +literal timer or a hard gate -- it's a Pomodoro-style nudge, +offered with the reasoning spelled out, not a silent forced wait. +The operator decides whether to take it. + +## Don't leak your own harness into the PR body + +Agents commonly stick a "Verification"-style section into PR +descriptions listing obvious, implied self-checks (e.g. +"`pre-commit run --all-files` and `make doc-spelling` are +clean") -- useful for a CI harness, not for a human reviewer. +"The CI runs these properly, using a project-accepted infra... +the fact that you managed to run the in-project infra locally +does not really contribute any useful information to the +context of the PR." (webknjaz, aio-libs/multidict#1393, +issuecomment-5342964393) Assume the reviewer already knows the +project's conventional, integrated tooling and CI serve as the +harness -- don't restate that it was used. + +Reserve the PR body for what CI *wouldn't* catch: something +surfaced during exploration, troubleshooting, or debugging that +isn't "part of tribal knowledge and standard practices" and a +reviewer genuinely couldn't infer. Leaking harness internals +"would needlessly pollute the reviewer's context, distract them +from what the scope is and delay the merge" -- point out the +one thing that actually needs explaining, not everything that +was checked. + +## Review comments are an invitation to a conversation, not a command + +A reviewer raising a question, a concern, or a tradeoff is opening a +dialogue, not issuing a one-shot instruction to execute silently. +"The PR author is supposed to be the very first reviewer of whatever +patch they submit. We shouldn't reward behaviors where one would +just dump whatever and spam the maintainers with review requests w/o +bi-directional comms." (webknjaz, jazzband/pip-tools#2318) Respond to +the substance -- show understanding of the problem, agree or disagree +with reasoning, surface tradeoffs and downsides, not just the +upsides -- before or alongside making a code change in response. +Agents: don't respond to or act on review input until you and the +operator agree on how to proceed -- see +[HUMAN_IN_THE_LOOP.md](HUMAN_IN_THE_LOOP.md). + +## Two named antipatterns to avoid + +From the same discussion: (1) going silent or closing the PR with no +explanation when challenged, and (2) pushing new commits in response +to feedback with no explanation and no response to the actual +questions asked -- "this often repeats in a loop." Both leave the +reviewer's actual question unanswered and force them to either drop +it or re-ask it. + +## Don't resolve a conversation you didn't start + +"Whoever started the discussion gets to click resolve. If you think +that you really need to do that, add a comment saying that you're +resolving and click resolve (otherwise, it gets lost, and it's +difficult to dig it up in the GH UI)." (webknjaz, +aio-libs/aiosmtpd#593, discussion_r3750771195) Prefer opening a +follow-up issue over letting a live discussion go stale or buried. +This is aimed at contributors resolving threads prematurely or +silently -- maintainers may deliberately leave threads open longer, +or resolve/unresolve around merge time, for their own discoverability +reasons; that's their call to make, not a contributor's (or an +agent's) to preempt. + +## Why this matters: context-recovery cost + +"Back to the etiquette -- small changes, reduced context switching, +optimization for review and long-term maintenance... Smaller context +== quicker response time == better chance I get to help out with +more things." (webknjaz, same aiosmtpd comment) A maintainer spread +across many projects pays a real cost every time they have to +rebuild context on a PR -- keep changes and conversations easy to +follow, not something that has to be re-discovered. + +## Don't push new commits, and never force-push, mid-review + +When a reviewer opens a discussion, engage with it first. If a code +change genuinely is the right response, make it a deliberate, +well-explained, reviewable commit -- not a reflexive push made +instead of answering the question. Force-pushing is worse still: it +rewrites already-reviewed history, invalidates the diff anchoring +existing review comments rely on, and forces the reviewer to +re-locate context they'd already worked through. Don't do either +without engaging in the conversation first. Agents never force-push +mid-review on their own -- if it's ever warranted, the operator does +it by hand, or confirms the exact command for the agent to run (see +[HUMAN_IN_THE_LOOP.md](HUMAN_IN_THE_LOOP.md)). + +## Don't parallelize contribution efforts without explicit sign-off + +Opening multiple concurrent PRs, or running multiple parallel +attempts at solving the same problem, without the operator +explicitly agreeing to each one first, mirrors what the maintainer +has called "sloperators" elsewhere -- contributors mass-creating PRs +and seeing what sticks (jazzband/pip-tools#2318) -- just at a +smaller, individual scale. It multiplies review burden and makes it +harder for a maintainer to track what's actually being proposed. +Before starting a second (or third) concurrent effort on the same +project, check in with the operator and get an explicit go-ahead -- +don't assume it just because the first one is still pending. + +## LLM/agent transparency + +The maintainer has repeatedly wanted issue/PR templates across +projects he maintains to ask contributors to disclose the LLM name +and prompt used (jazzband/pip-tools#2318) -- not (yet) a formal rule +in this repo specifically, but a stated preference worth honoring in +spirit: be transparent about AI involvement rather than presenting +a submission as though it had no agent in the loop. Per a maintainer +he cited approvingly: use LLMs "to replace typing, don't use them to +replace thinking" -- the human (regardless of whether there is an +agent interacting with the project on their behalf or not) still owns +understanding and decisions of the interactions with their name +attached. diff --git a/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md b/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md new file mode 100644 index 0000000000..650c846f24 --- /dev/null +++ b/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md @@ -0,0 +1,180 @@ +# Don't Shoot the Messenger + +> [!important] +> +> Linters, type checkers, coverage, and tests are messengers. When +> one of them reports a problem, fix the problem -- don't silence +> the messenger. Whether a check gets silenced is always the +> operator's decision, made case by case, never the agent's. + +## What counts as silencing + +All of these need an explicit, per-case decision from the +operator. + +Linters, type checkers, coverage: + +- Inline suppressions: `# noqa[: ...]`, `# ruff: noqa`, + `# flake8: noqa`, `# type: ignore[...]`, `# mypy: ignore-errors`, + `# pylint: disable=...`, `# pragma: no cover`. +- Config-level ignores: `per-file-ignores`, `extend-ignore`, + `exclude` entries, and similar in `.flake8`, `.ruff.toml`, mypy + or any other tool config. Editing a tool's config to make a + finding go away is a suppression too. +- Disabling or narrowing a pre-commit hook, or bypassing hooks + with `SKIP=` / `git commit --no-verify`. +- Loosening types to make a finding go away: replacing a precise + annotation with `typing.Any`, or adding a `typing.cast()`. When + a value really can be anything, `object` is the honest + annotation. + +Tests: + +- Deleting a test, a fixture, or a whole test module. +- Commenting out a test or a test module. +- Adding `skip`/`skipif`/`xfail` markers to an existing test, or + calling `pytest.skip()`/`pytest.xfail()`/`pytest.importorskip()` + to dodge a failure. +- Weakening assertions: removing them, dropping `match=` from + `pytest.raises()`, catching a broader exception type, or + changing an expected value to match buggy output. +- Taking a test's expected values from the code's current output + instead of from the issue, a spec, or a reference + implementation. Such a test agrees with whatever bugs the code + has, so it can never report them. See + [TESTING.md](TESTING.md#tests-state-what-the-code-should-do-not-what-it-does). +- Adding `ignore` entries to `filterwarnings`. + +Thresholds and CI: + +- Lowering coverage targets, adding `continue-on-error`, dropping + a job or a matrix entry. + +Reporting: + +- Running a subset (`-k`, `--deselect`, `--ignore`) is fine while + iterating, but never report a run as green while failures are + excluded from it. + +## Don't game the messenger either + +Silencing has a mirror image: making a check report success while +the thing it measures isn't actually true. A coverage number going +up is not proof that anything is better tested. Gaming a check is +no more the agent's call than silencing it. + +These count as gaming: + +- Tests that execute lines without checking behavior: no + assertions, or assertions that can't fail. +- Reaching code through private or internal API (`_name()`), or + calling it in an order or a number of times no real caller + would, just to mark lines as covered. +- Forcing an object into a state that its public API, or a real + external scenario, can never produce. + +Instead, drive the code the way it runs for real: through the +public API, or an end-to-end scenario -- a full object lifecycle, +a failure provoked at a real boundary. Before writing a test for +an uncovered line, check whether existing tests already reach it +that way, and whether the coverage tool can see it at all. When a +line can't be reached realistically, stop and bring it to the +operator as a finding, not a test: it's either dead or purely +defensive code -- the operator decides whether to drop it or to +exclude it as described in [Presenting a case](#presenting-a-case) +-- or a blind spot of the tooling. Say what each new test proves, +not which lines it turns green. + +Here: PR #879 added a test calling `_RemoteFile._cleanup()` by hand, +without assertions, to cover its early return on an already-closed +handle. Real use already takes that branch: `__exit__()` closes the +handle and `__dealloc__()` runs `_cleanup()` again, and a failed +`sftp_open()` deallocates an object whose handle was never set. +With Cython line tracing on, dozens of other tests in +`tests/unit/sftp_test.py`, including plain `SFTP.get()` and +`SFTP.put()` calls, were already recorded taking it. + +## Presenting a case + +When you believe silencing is warranted, stop and show the +operator, one case at a time: + +1. The tool or test, the error code or failure message, and the + `file:line`. +2. Why the cause can't reasonably be fixed right now. +3. The proposed scope -- line, file, or (rarely) directory. +4. The exact comment text that will accompany it. +5. When it can be removed -- the condition, the issue, or the + upstream fix it waits for. + +Then restate the trade-off in your own words and confirm the +operator understands and agrees with it. Approval of one case says +nothing about the next one. + +## Preferred shape: line-scoped, explained, temporary + +Scope a suppression to the single line that needs it, name the +specific codes, and explain why it exists and when it can go: + +```python +value = call(42) # noqa: WPS432 # mirrors an upstream constant; drop once it's exposed by name +``` + +Blanket `# noqa` without codes is rejected by the +`python-check-blanket-noqa` pre-commit hook anyway. A `skip` or +`xfail` carries a `reason=` that links the tracking issue. + +Most suppressions should be temporary. Treat each as tracked debt, +not a resolution. + +## File-level suppressions are exceptional + +Acceptable only with the operator's decision, for well-reasoned +cases -- e.g. a test module that intentionally passes wrong +argument types to check that runtime validation rejects them. +Where the tool supports code-specific file-level directives +(`# ruff: noqa: ` at the top of the file), use those. +Otherwise, use a `per-file-ignores` entry preceded by a comment +explaining each code, following the convention at the top of the +`per-file-ignores` block in `.flake8`. + +## Directory-scoped suppressions + +Avoid globs like `tests/**.py` in ignore lists. They hide every +future violation in that tree, not just the one in front of you. +Only add one with a well-reasoned decision from the operator, +recorded in a comment next to the entry. + +## Legitimate test changes still get presented + +When behavior changes on purpose and a test's expectations have +to change with it, say so explicitly -- don't slip it into a +larger diff. The accepted `xfail`-only PR in +[TESTING.md](TESTING.md) openly adds a *new* failing test ahead of +its fix. It is not a way to hide an existing test that broke. + +## Existing suppressions + +Some suppressions in the tree predate this rule. Don't rewrite +them unasked. Point them out to the operator if they're in the +area you're touching. Removing a suppression that's no longer +needed is welcome, but show it too. + +Here: e.g. the bare `# noqa: DAR101` lines in `tests/conftest.py`, +without an explanation. + +## Tool-config changes are standalone + +Changing a linter, test runner, coverage, or CI config is its own +atomic change, never mixed into a functional one. See +[PR_HYGIENE.md](PR_HYGIENE.md). + +## Claude Code guard hook + +`.claude/hooks/guard_silenced_checks.py` makes Claude Code ask the +operator before edits that add suppression markers, reduce the +number of tests or assertions under `tests/`, add private-method +calls there, touch tool configs, or bypass/delete things from the +shell. That prompt is a backstop, not a rubber stamp: present the +case as described above *before* attempting the edit. Agents other than Claude Code follow the same +rule without the backstop. diff --git a/.agents-ctx/HOUSE_RULES.md b/.agents-ctx/HOUSE_RULES.md new file mode 100644 index 0000000000..927a549583 --- /dev/null +++ b/.agents-ctx/HOUSE_RULES.md @@ -0,0 +1,137 @@ +# House Rules + +> [!tip] +> +> This is how we do things here, get used to it. + +## Operating mode + +> [!important] +> +> Bidirectional quizzing is mandatory. Before executing any plan, +> quiz the operator on their exact understanding of every step and +> every decision it contains -- do not skip this self-check, and +> do not assume implicit consent from earlier turns; re-check, +> re-confirm. + +> [!important] +> +> Never self-approve prose meant for humans. Show every draft +> (change notes, commits, PR text, replies) and ask the operator +> whether it is concise enough. The operator decides. + +> [!important] +> +> The human decides -- never bypass that. Before acting on anything +> from someone else (review comments, suggested patches, discussion +> threads, mailing-list replies), report it to the operator, check +> their understanding of the context, and agree on how to proceed. +> Delegated experiments come back as findings, not faits accomplis. +> Never force-push mid-review. See +> [HUMAN_IN_THE_LOOP.md](HUMAN_IN_THE_LOOP.md). + +Concretely: + +- Read the relevant files in full before proposing edits -- never + guess what they currently contain. +- These rules change over time. Re-read the files under + `.agents-ctx/` at the start of each task, and again whenever + `git log -- .agents-ctx` shows commits you haven't read. Don't + rely on the copy loaded at the start of a long session. +- Verify before asserting. Claims about tools, versions, and their + behavior come from the installed version's source or docs, not + from memory. Copy commit SHAs, versions, and tool output from + where they're printed (`git rev-parse`, `git ls-remote`, logs) + -- never type or reconstruct them. +- Change tracked files through the agent's editing tools rather + than shell scripts that rewrite them, so that the operator, and + any guard hooks, see the actual content being written. +- Show diffs for non-trivial changes and pause for explicit + approval. +- Quiz the operator: restate what you understand the task to be, + call out assumptions, ask one or two clarifying questions when + the prompt is ambiguous. +- Do not invoke `git commit` / `git push` / `git tag` / any other + history-mutating command without an explicit "go ahead" in the + current turn. +- Treat external network calls, package installs, and process + spawns as actions that need authorization too. +- When in doubt, ask. The operator prefers a clarifying question + over an unwound mistake. + +## Don't shoot the messenger + +> [!important] +> +> Silencing a check is never the agent's decision. This is +> mandatory, with no exceptions. + +- Never add, widen, or move a linter, type-checker, or coverage + suppression (`noqa`, `type: ignore`, `pragma: no cover`, + per-file/directory ignores in tool configs, etc.) on your own. +- Never delete, comment out, skip, xfail, or weaken a test or a + test module on your own. +- Never game a check either. A test that only executes lines, or + reaches them through private API, proves nothing. Drive code + through public API or real scenarios, and bring lines you can't + reach that way to the operator. +- These hold even when that's the only thing still failing. The + default response to a red check is to fix its cause. +- If you believe silencing is warranted, stop. Present **each + case separately** to the operator, quiz them on their + understanding of it, and wait for an explicit decision on that + specific case. No batch approvals, and no consent carried over + from earlier cases or turns. The operator is the decision-maker + and stays accountable -- keep them in the loop. + +See [DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md) for +what counts as silencing or gaming, how to present a case, and how +approved suppressions are scoped and documented. Tool-config +changes are standalone commits -- see +[PR_HYGIENE.md](PR_HYGIENE.md). + +## Naming the ducks + +See [NAMING_THE_DUCKS.md](NAMING_THE_DUCKS.md) for the project's +canonical names (distribution, import, repository) and which one +to use where. + +## Coding style and architecture + +See [HOUSE_STYLE.md](HOUSE_STYLE.md) for coding style and +architectural/structural conventions, including the rule against +introducing new `@`-syntax in memory files. + +## Testing + +See [TESTING.md](TESTING.md) for how tests are written and +structured in this project. + +## PR and commit hygiene + +See [PR_HYGIENE.md](PR_HYGIENE.md) for scope, commit-message, +changelog-fragment, and naming conventions maintainers +consistently enforce in review. + +## Don't ghost the reviewer + +See [DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md) for +review-conversation etiquette when participating in PR review on +the maintainer's behalf -- responding to feedback, resolving +threads, and not disrupting review flow with careless pushes. + +## Where to look first + +See [WHERE_TO_LOOK_FIRST.md](WHERE_TO_LOOK_FIRST.md) for a reading +order when picking up a task, and a map of the repository. + +## Licensing + +See [LICENSING.md](LICENSING.md) -- license terms and metadata +change only with the maintainer's explicit approval. + +## Tooling + +See [CONTRIB_WORKFLOW_INFRA_TOOLING.md](CONTRIB_WORKFLOW_INFRA_TOOLING.md) +for how to run tests, linters, and other project automation -- +always through `tox`, never by invoking the wrapped tools directly. diff --git a/.agents-ctx/HOUSE_STYLE.md b/.agents-ctx/HOUSE_STYLE.md new file mode 100644 index 0000000000..f689d3fa05 --- /dev/null +++ b/.agents-ctx/HOUSE_STYLE.md @@ -0,0 +1,85 @@ +# House Style + +Grounded in the maintainer's review history and merged commits +(PR numbers below are from `ansible/pylibssh`), plus explicit +maintainer conventions carried across projects — not guesses. + +## No new `@`-syntax in memory files + +Do not introduce additional Claude `@`-mention/import syntax inside +any file under `.agents-ctx/`. The existing chain (`CLAUDE.md` -> +`AGENTS.md` -> `.agents-ctx/HOUSE_RULES.md`) is the only sanctioned +use of `@`-imports. + +`@`-mentions load eagerly, at the start of every session, whether +or not the content ends up being relevant. Everything reachable +from `HOUSE_RULES.md` onward links to further material with plain +Markdown links instead, so an agent can pull it into context on +demand -- when a task actually needs it -- rather than having the +whole tree pollute the context window up front. + +## Structural constraints + +- No `setup.py`. Packaging metadata is declarative; don't + reintroduce an imperative build script. +- No `tests/__init__.py`. Pytest must not promote the project + root into `sys.path` via package discovery. + +Here: `setup.py` was dropped in `b08a7fd4`. The metadata lives in +the PEP 621 `[project]` table of `pyproject.toml` (see +[NAMING_THE_DUCKS.md](NAMING_THE_DUCKS.md)). + +## Python + +- `typing` is aliased as `_t` (see [PR_HYGIENE.md](PR_HYGIENE.md)), + `collections.abc` as `_c`. +- Tuples for fixed-size sequences such as command arguments or + `parametrize` values; lists only where something needs to + mutate them, or where a tool documents a list as its + convention (e.g. `pytest_plugins`). +- Single quotes for inline strings, triple-double quotes for + multi-line strings. +- `from __future__ import annotations` in every *new* `.py` + module. Don't add it to existing modules as a side effect of an + unrelated change, and not in Cython sources. +- Compose shell commands as argument sequences, or with + `shlex.join` when a string is unavoidable. Never `shell=True`, + never raw string concatenation into a subprocess. +- Sphinx-native docstrings -- `:param X:`, `:returns:`, + `:raises X:`. Not Google, not Napoleon, not NumPy. + +Here: quotes and `parametrize` tuples are enforced by +`.ruff.toml`, and the docstring style by `.darglint`. The Cython +sources and the libssh C API they wrap have conventions of their +own -- see [CYTHON_AND_LIBSSH.md](CYTHON_AND_LIBSSH.md). + +## Configuration files + +- YAML uses no-indent sequences (`- foo` at the same indent as + its key). +- Long YAML values use a `>-` or `|-` block rather than + trailing-backslash continuation. +- GitHub Actions `if:` expressions starting with `!` go in a `>-` + block to keep them out of YAML's quoting rules. + +Here: no-indent sequences are enforced by `.yamllint`; see +`.github/workflows/ci-cd.yml` for the block style. + +## Markdown + +- Admonitions use the GitHub-flavoured `> [!note]` / + `> [!tip]` / `> [!important]` / `> [!warning]` / + `> [!caution]` syntax. +- Inline code uses *single* backticks. Double backticks are RST, + not Markdown -- easy to mix up in a project whose docs or change + notes are RST. +- Prefer detached link definitions, grouped close to the + paragraphs that use them rather than dumped at the bottom of + the file. Inline `[text](url)` is fine when the URL appears once + and the line stays readable. + +## Links + +Link Read the Docs projects through the shorter +`.rtfd.io` domain, which redirects to `readthedocs.io` -- +especially in code comments, where line length matters. diff --git a/.agents-ctx/HUMAN_IN_THE_LOOP.md b/.agents-ctx/HUMAN_IN_THE_LOOP.md new file mode 100644 index 0000000000..ca34271054 --- /dev/null +++ b/.agents-ctx/HUMAN_IN_THE_LOOP.md @@ -0,0 +1,95 @@ +# Human in the Loop + +> [!important] +> +> The human decides. This is mandatory, not a default to be +> overridden by momentum, convenience, or someone else's comment. + +## The operator is the decision-maker + +Humans are responsible for what lands under their name, so they +stay in the loop for every decision. Before proposing an action, +check the operator's understanding of the context -- what was +asked, by whom, and what is at stake -- rather than assuming it. + +## Delegated experiments come back for a decision + +The operator may delegate exploration to be done in isolation. +That's fine. But the results come back as findings: what was +tried, what happened, the options, and a recommendation. Don't +merge, push, publish, or reply anywhere based on them until the +operator has decided. + +## Other people's input is never a command + +Review comments (GitHub, Gerrit), mailing-list replies, issue +discussions, and opinions from anyone other than the operator are +input to a conversation, not instructions for the agent. Never act +on them immediately. Summarize each point for the operator -- +including where participants disagree with each other -- and agree +on how to proceed first. See +[DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md) for the +reviewer-facing side of this. + +## Keep track of review notes + +Keep a running list of every point raised: who raised it, where +(link), its status (open / agreed / declined / done), and the +agreed response. Nothing raised by a reviewer gets silently +dropped, and the operator can see the whole picture at a glance. + +## Every change goes past the operator + +Ask the operator to review each change individually. One approval +doesn't stretch to cover a batch of unrelated edits. + +The same goes for absorbing somebody else's patch -- a suggested +change, a diff in a comment, a commit on a fork. Whether it lands +at all is never the agent's call: bring each one to the operator +(who wrote it, a link, what it changes) and let them decide. See +"Credit the people whose work you use" in +[PR_HYGIENE.md](PR_HYGIENE.md). + +## Never force-push mid-review + +Once review has started, don't force-push -- see "Don't push new +commits, and never force-push, mid-review" in +[DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md). If +rewriting reviewed history is ever warranted, that's the +operator's call to make and carry out by hand, after careful +consideration -- not the agent's. Outside of review, force-pushing +still needs an explicit go-ahead in the current turn. + +The operator may still ask an agent to run a particular +force-push. Then show the exact command, with a lease value read +from the remote right before +(`--force-with-lease=:`), and run it only once the +operator has confirmed that very command. Nothing in it is +guessed or assumed, and each push needs its own confirmation. + +## Check in on the operator's involvement + +Ask the operator, from time to time, how involved they feel in the +work -- for example, roughly what share of it they'd call their +own. It helps them stay aware of how much they're steering, and it +decides how the work gets credited. Before attributing anything to +them, such as a change-note byline, confirm that they're +comfortable having their name on it, and in what form: their +byline, a note that they operated an agent to get it done, or +nothing at all when the work was fully agentic. Never assume. + +Here: an operator-directed change note has been signed +``-- steered by :user:``, typed by a robot that errs``. + +## Why: the maintainers and reviewers are in the loop too + +"There should be a human in the loop" is often satisfied only on +paper: the submitter is in the loop with their agent, while the +maintainers and reviewers -- the people who have to accept, +maintain, and answer for the change -- are kept out of it. The +result is low-quality, inauthentic interactions that take up +maintainer time and put the reviewers under stress. Any human +being in the loop doesn't count. The ones who matter are those the +change lands on. Never encourage this pattern. Keep the operator +in the loop so the operator can keep the maintainers and reviewers +in it. diff --git a/.agents-ctx/LICENSING.md b/.agents-ctx/LICENSING.md new file mode 100644 index 0000000000..5117f476a9 --- /dev/null +++ b/.agents-ctx/LICENSING.md @@ -0,0 +1,34 @@ +# Licensing + +> [!important] +> +> License terms are the maintainer's decision, never the agent's. + +- Never change the license terms, relicense, or alter license + metadata -- license files, the `license` / `license-files` + fields in packaging metadata, per-file license headers or SPDX + tags -- without the maintainer's explicit approval. Present the + change to the operator and wait. +- New source files carry the same license header as the existing + ones, if any. +- Code copied in from elsewhere keeps its original license and + notices. Before copying any, tell the operator where it comes + from and under which license, and let them decide whether it + can come in. + +Here: ansible-pylibssh is `LGPL-2.1-or-later` (`LICENSE.rst`, +`pyproject.toml`). Source files carry the LGPL boilerplate header, +not SPDX tags. `build-scripts/manylinux-container-image/` is +derived from PyCA/infra and stays under Apache-2.0 / BSD-3-Clause, +with its license files next to it. The wheels bundle libssh, which +is LGPL-2.1 itself. + +## Claude Code guard hook + +`.claude/hooks/guard_license_changes.py` makes Claude Code ask the +operator before edits that touch license files, drop license +notices, or change license metadata, and before shell commands +that delete or rewrite license files. That prompt is a backstop, +not a rubber stamp: present the change to the operator *before* +attempting it. Agents other than Claude Code follow the same rule +without the backstop. diff --git a/.agents-ctx/NAMING_THE_DUCKS.md b/.agents-ctx/NAMING_THE_DUCKS.md new file mode 100644 index 0000000000..c7ec7b0de0 --- /dev/null +++ b/.agents-ctx/NAMING_THE_DUCKS.md @@ -0,0 +1,32 @@ +# Naming the Ducks + +Canonical names for this project, and how to refer to it in +prose. Other files in `.agents-ctx/` (and any generated content) +should say "the project" rather than hardcoding one of these -- +reach for a specific name only when the distinction actually +matters (e.g. citing a package, an import, or a repository URL). + +## Distribution / PyPI name: `ansible-pylibssh` + +The installable, published name -- recorded in +`pyproject.toml`'s `[project].name` per PEP 621. This is also +the preferred way to refer to the project by name in prose. + +## Python import name: `pylibsshext` + +`import pylibsshext` is what code actually imports. +Long-standing and unlikely to change without a dedicated, +long-term migration effort -- don't "fix" it opportunistically. + +## GitHub repository slug: `ansible/pylibssh` + +Close to, but not the same as, the distribution name above. Use +it verbatim when it's actually the repository being referenced +(URLs, `gh` invocations, PR/issue citations) -- not as a +stand-in for the project's name in prose. + +## Don't say bare `pylibssh` + +`pylibssh` on its own is just the default local directory name +from a `git clone`d checkout -- nothing more. It's a common but +incorrect shorthand; prefer `ansible-pylibssh` instead. diff --git a/.agents-ctx/PR_HYGIENE.md b/.agents-ctx/PR_HYGIENE.md new file mode 100644 index 0000000000..bbdbbeae23 --- /dev/null +++ b/.agents-ctx/PR_HYGIENE.md @@ -0,0 +1,226 @@ +# PR & Commit Hygiene + +Grounded in the maintainer's review history and merged commits +(PR numbers below are from `ansible/pylibssh`), plus explicit +maintainer conventions carried across projects — not guesses. + +## Point contributors to the official guidelines + +Route contributors to the project's contributing guidelines and +code of conduct for the canonical contribution process, rather +than improvising or restating it secondhand. + +Here: +and `.github/CODE_OF_CONDUCT.rst`. + +## Keep PRs and commits atomic and scoped + +One conceptual change per PR, one conceptual change per commit. +"I'm definitely not going to accept a bunch of unrelated changes +smashed together" (PR #809); a PR mixing formatting, docstring +rewording, and a behavior change got split into three (PR #862) +before being accepted. Rebase onto the target branch for real +instead of adding merge commits ("foxtrot merges") to a feature +branch. + +### Tool-config changes are standalone + +Changes to tool configuration -- `.flake8`, `.ruff.toml`, +`.pre-commit-config.yaml`, `pytest.ini`, `tox.ini`, `.codecov.yml`, +CI workflows, and the like -- go in their own commit, with their +own rationale, never mixed into a functional change. Ask the +operator whether one also needs its own PR. This is the same +reasoning behind keeping type-annotation retrofits a deliberate, +standalone effort (see below). When the config change relaxes a +check, it's also a suppression -- see +[DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md). + +## Don't dump AI-generated bloat + +"LLMs are good at generating way too much stuff and it even works +under some circumstances but we're still responsible for keeping +the patches maintainable, having Git tree tell a story and contain +sufficient context. Be accountable." (PR #790) -- trim anything not +directly related to the stated change before proposing it. +You don't decide when the trimming is done. The operator does +(see [HOUSE_RULES.md](HOUSE_RULES.md)). + +The same restraint applies to the PR description, not just the +diff -- see +[DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md) for why +internal self-check noise (e.g. a "Verification" section +restating that conventional tooling was run) doesn't belong +there either. + +## Commit messages + +- Imperative-mood subject, 50 characters or fewer. +- The body is descriptive, not imperative: explain *why*, not + *what* -- the diff already shows what. +- Focus the body on how the commit affects the project. Mention a + third-party tool's internals or quirks only when they justify a + non-obvious choice in the code, and say that they do. + Implementation details belong in code comments. +- Credit the sources that shaped a design -- a discussion, a gist, + a document -- by linking them from the body. +- Wrap the body at 72 columns. +- No conventional-commits prefixes (`feat:`, `fix:`, etc.). A + leading [gitmoji] (e.g. 📝 for docs, 🔧 for tool configs) is + fine -- the maintainer uses them -- but optional. + +[gitmoji]: https://gitmoji.dev + +Here: commit messages must pass [gitlint], even though it isn't +wired into the linters yet. + +[gitlint]: https://jorisroovers.com/gitlint/ + +## PR descriptions + +Fill in the repository's PR template instead of replacing it: keep +its headings and shape, pick the options that apply, and drop the +placeholder comments. Describe what the change brings to the +project -- the problem, the approach, and the decisions a reviewer +needs to know about. Evidence, such as root-cause findings, +measurements, or verbatim tool output, goes where the template asks +for additional information. Leave out third-party internals, +sibling PRs that don't affect the review, and anything the diff +already shows. Disclose the agent's involvement in plain words, +without linking a vendor's site or keeping the harness's default +signature -- e.g. "🤖 Produced by a probabilistic agent with a +token generator using an LLM to sound convincing." (see +[DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md)). + +Here: the template is `.github/PULL_REQUEST_TEMPLATE.md`, with +SUMMARY, ISSUE TYPE, and ADDITIONAL INFORMATION sections. + +## Brushing up a branch before merge + +Follow-up commits pile up while a PR evolves. Before merge, the +operator may ask to turn them into a story: a series of atomic +commits on top of the target branch, without the intermediate +experimental states. + +- Change existing commits through `fixup!` commits + (`git commit --fixup=`, or `--fixup=amend:` and + `--fixup=reword:` for their messages), folded in with + `git rebase --interactive --autosquash`. That keeps each change + visible until it's absorbed. +- Carry the discoveries and references of the old commits over + into the new commit bodies. +- Record the pre-cleanup tip first, and check that the result adds + up to it: the rewritten branch's tree must match that tip merged + into the target branch. +- Every commit in the new series has to pass the checks on its + own. + +Publishing the result is a force-push, which is the operator's to +run -- see [HUMAN_IN_THE_LOOP.md](HUMAN_IN_THE_LOOP.md). + +## Every change needs a changelog fragment + +Every PR needs at least one changelog fragment. Consider every +audience the change affects -- end users, contributors, downstream +packagers -- and add a fragment for each. + +A changelog fragment is not a restated commit message -- it covers +everything since the previous release, for end-users, not +developers. Changelog entries are a permanent historical record: +they're never retroactively removed, even if the underlying code +is later reverted, unlike commit history, which can be reworded, +rebased, or squashed. + +Recurring, specific review feedback: + +- One change per fragment, not several changes "smashed" into one + (#756, #862). +- Wording is past-tense and end-user-facing, not + imperative/developer-facing. +- Reference related issues, PRs, users, and files through the + roles the docs tooling provides, instead of raw links or + backticks (#620, #786, #790, #809). +- A byline credits a human. Whether the operator gets one, and in + which form, depends on how involved they feel, so ask them (see + [HUMAN_IN_THE_LOOP.md](HUMAN_IN_THE_LOOP.md)). Fully agentic + work gets none -- crediting a probabilistic machine in a loop is + silly. Disclose agent involvement in the PR instead. + +Here: fragments are Towncrier-managed RST files in +`docs/changelog-fragments/`, named `..rst` -- +or after the commit hash for changes committed straight to the +default branch -- with `...rst` for several of +one type. `docs/changelog-fragments/README.rst` lists the types and +the full rationale. References use the `sphinx-issues` roles +(`:pr:`, `:user:`, `:file:`); bylines name people through `:user:`. + +## Credit the people whose work you use + +When incorporating a patch someone suggested, credit them with a +`Co-Authored-By: Name ` trailer, per + +(GitHub's `ID+username@users.noreply.github.com` works). If it +came via `git format-patch`/`git am`, preserve the original Author +field instead. Add one trailer per contributor when there are +several. Who to credit, and how, is always the operator's call -- +ask every time, not only when unsure. + +- Prefer native authorship: the operator clicking "Commit + suggestion" in the GitHub UI, or the author pushing it + themselves, beats re-applying their change locally. +- Look the trailer up with `gh api users/` (`.id`, and + `.name` falling back to `.login`) -- don't guess. Keep the + `+login` part; the bare ID doesn't work. Show the exact trailer + to the operator before committing. +- Rewording, restructuring, or re-implementing a suggestion so it + "isn't really theirs" anymore still requires the credit. +- Agents are not authors and never get a `Co-Authored-By` + trailer -- they aren't sentient, they're guessing machines + deriving tokens from other people's content. Humans whose work + was used always get credited. Agent assistance is disclosed with a + literal `Assisted-by: LLM` trailer -- no model name, no email + -- following the [Linux kernel's convention][kernel], which + others follow too ([standard][assisted-by], + [rationale][dont-abuse-co-authored-by]). The kernel stopped + naming the model because that advertises vendors while adding + little information. Add the trailer by default; it replaces + whatever attribution format the agent's harness suggests. +- Never drop existing `Co-Authored-By` trailers, or replace the + original author, when rebasing, squashing, or rewording. + +[kernel]: https://docs.kernel.org/process/coding-assistants.html#attribution +[assisted-by]: https://allthingsopen.org/articles/open-source-ai-contributions-assisted-by-git-trailer-standard +[dont-abuse-co-authored-by]: https://bence.ferdinandy.com/2025/12/29/dont-abuse-co-authored-by-for-marking-ai-assistance/ + +## Names and docstrings carry the meaning, not comments + +"Comments repeating what the code does are pointless. Proper +identifier names should be used instead" (PR #621). Docstrings +describe what a function does; motivation/rationale, if needed, +belongs in a comment or the PR description, not the docstring +(PR #658). + +## Type annotations on new code + +New code -- including new tests -- needs type annotations: +parameter types and return types, using `import typing as _t` +for standard-library constructs (e.g. `_t.Optional[...]`). This +isn't retrofitted into existing/legacy code as a side effect of +an unrelated change -- that's a deliberate, standalone future +effort, not something to bundle into whatever else a PR is +doing. + +Here: this is a real, acknowledged gap. `.ruff.toml` disables +`ANN001`/`ANN201`/`ANN202`/`ANN401` with an explicit `# FIXME: +These flake8-annotations errors need fixing and removal` +comment, and none of the current test functions in `tests/` are +annotated. Don't read the absence of annotations in existing +code as license to skip them in new code -- it's tracked debt, +not the house style. + +## Common micro-conventions flagged in review + +- f-strings over `.format()`/`%` formatting. +- `contextlib.suppress()` over bare `try`/`except: pass`. +- No monkey-patching stdlib. +- Public vs. private intent must be explicit -- prefix with `_` if + not part of the public API. diff --git a/.agents-ctx/README.md b/.agents-ctx/README.md new file mode 100644 index 0000000000..64d743d980 --- /dev/null +++ b/.agents-ctx/README.md @@ -0,0 +1,3 @@ +# 'sup? + +See [HOUSE_RULES.md](HOUSE_RULES.md). diff --git a/.agents-ctx/TESTING.md b/.agents-ctx/TESTING.md new file mode 100644 index 0000000000..97e45aa4e1 --- /dev/null +++ b/.agents-ctx/TESTING.md @@ -0,0 +1,219 @@ +# Testing + +Grounded in the maintainer's review history and merged commits +(PR numbers below are from `ansible/pylibssh`), plus explicit +maintainer conventions carried across projects — not guesses. + +## Tests are proof, not decoration + +New or changed behavior needs a test demonstrating it, covering the +cases actually touched (including edge cases like `None`). "I don't +think there's a proof that this works as intended without tests" is +a near-verbatim recurring review comment (e.g. PR #756, #786, #790, +#479, #669, #809). Missing test coverage is the single most common +reason PRs stall or get closed unmerged. + +Justify new tests by what they actually verify, not by the +coverage number alone. Coverage still matters a lot -- 100% +coverage is a genuinely useful self-check (e.g. it can catch tests +that silently start getting skipped in CI). The point is: don't +game the number -- a test that exercises a line without +meaningfully checking behavior doesn't count, passing or not (see +"Don't game the messenger either" in +[DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md)). The +same reasoning-over-metrics standard applies to every change, not +just tests: infra, packaging, and runtime code all need +well-reasoned, architecturally sound justification, not just a +passing check. + +Deleting, commenting out, skipping, xfailing, or weakening a test +is never the agent's call -- see +[DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md). + +Here: `.codecov.yml` targets 100% for `src/`/`tests/`. It isn't +wired up as a required CI check yet, only because of unresolved +infra problems measuring Cython coverage -- not because it's +considered optional. + +## Tests state what the code should do, not what it does + +Expected values come from somewhere other than the code under +test: the issue, a spec or RFC, upstream library docs, or the +observed behavior of a reference implementation. A test whose +expectations were read off the implementation only restates it, +and it keeps passing when the code is wrong in the same way. +Doing so counts as silencing -- see +[DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md). + +- Show that a regression test catches its bug. Run it against + the unfixed code (revert or stash the fix) and confirm it fails + for the reason the test names, then confirm it passes with the + fix. Say in the PR how this was checked. This is a verification + step, not a commit-ordering rule -- the test still lands in the + same commit as the fix. +- For new behavior, write down the expected outcomes from the + issue or spec before reading or writing the implementation, and + bring them to the operator when the source is ambiguous rather + than settling the question by running the code. +- Assert on outcomes a caller can observe, not on how the code + gets there. +- When an expected value can't be traced to a source outside the + code, say so to the operator instead of copying it from the + current output. + +Here: the live `sshd` in every test is the main independent +oracle -- prefer comparing against what the server, or the OpenSSH +client against the same server, actually does. + +## No test classes + +Every test in `tests/` is a plain `def test_*` function. Don't +introduce `unittest.TestCase` subclasses or bare grouping classes. + +Here: there are zero `class` definitions anywhere in the test +suite, across the full project history. + +## Prefer parametrize/fixtures over duplicated test logic + +When two tests differ only in their input data, that's a +parametrized fixture or test, not two near-identical functions. +Precedent: PR #638 collapses two payload fixtures into one +parametrized fixture. + +Loop-based checks inside a single test are generally a sign the +test should be parametrized instead. The one accepted exception is +`pytest-subtests` (the `subtests` fixture), for structured, +individually reported sub-assertions within one test. + +Here: PR #638's result is +`@pytest.fixture(params=(32, SFTP_MAX_CHUNK + 1), ids=(...))`, +replacing `other_payload`/`large_payload`. A later commit merges +near-duplicate `NOTSET`/`TRACE` tests into a single +`@pytest.mark.parametrize` case. + +## Real e2e over mocking + +Don't introduce mocking as a substitute for exercising the real +behavior of the components involved. + +Here: `tests/` contains zero uses of `mock`, `Mock`, or +`monkeypatch`. Every test -- unit and integration alike -- +exercises a real `sshd` process spun up per-test via the +`sshd_addr` fixture in `tests/conftest.py`. + +## Design for testability + +Prefer decoupling techniques -- dependency injection in particular +-- that let code be tested in isolation, over reaching for +monkeypatching. Monkeypatching (via `unittest.mock` or the +`monkeypatch` fixture) is only acceptable at real system +boundaries: the system clock/timezone, environment variables, or +swapping in a stub server. It's not a substitute for designing +components to be testable on their own. + +## Test doubles for intercepted components + +When end-to-end tests need to patch or intercept a real component +-- say, to withhold a server's replies -- the test double gets its +own directory in the tests' stub area, named after its purpose +rather than the library it's built on. Its `fixtures.py` module is +the entry point, loaded as a local pytest plugin. + +- Entry points are imported eagerly at startup, so they must not + import their component's optional dependencies at the module + level. Import those inside a fixture through + `pytest.importorskip()`, so that a missing one skips only the + tests that need it. That's a declared optional dependency, not + a way to dodge a failure. +- The stub area is excluded from the doctest collection, which + would otherwise import those dependencies. +- Code running in child processes only gets its coverage recorded + when those processes exit cleanly instead of being killed. + +Here: stubs live in `tests/_stubs//`, discovered via +`pytest_plugins` in `tests/conftest.py`, and excluded through +`norecursedirs` in `pytest.ini`. `tests/_stubs/sshd_mitm_tcp_relay/` +is the first one. Child-process coverage relies on +`concurrency = multiprocessing` in `.coveragerc`. + +## Test layout + +Test files are named `_test.py`, not `test_.py`. +Match the existing file when extending it. + +Once the suite splits into categories, unit tests loosely mirror +the source modules -- `_test.py`, with a new file only for +a genuinely new module -- while integration tests are organized by +scenario or feature instead. + +Here: `tests/unit/` mirrors `src/pylibsshext/` -- `channel_test.py`, +`session_test.py`, `sftp_test.py`, `scp_test.py`, `version_test.py`. +The correspondence isn't strict 1:1: `errors` is covered via +`pytest.raises` inside other files, not its own file. +`tests/integration/` holds the scenario-based tests. + +## Tests usually land in the same commit as the behavior they cover + +When a change adds or alters behavior, the test change normally +lands in the *same* atomic commit, not a follow-up -- there's no +evidence of strict test-first/TDD commit ordering as a project +ritual. That style of TDD is mainly useful for interactive +development and exploration, used in tandem with continuous +adjustment, not as a blanket rule here. + +The one accepted exception: a PR that adds only a failing test, +marked `@pytest.mark.xfail`, can be merged on its own ahead of the +fix, to be resolved in a follow-up. Don't treat a merged `xfail` as +done, though -- it's a tracked gap, not a resolution. This +exception covers adding a *new* failing test; marking an existing +test `xfail` because it broke is silencing it. + +## Assertions + +Use `pytest.raises(..., match=...)` -- never a bare +`pytest.raises(SomeError)` -- so the assertion pins down which +failure is expected, not just its type. Use a raw string (e.g. +`r'^foo\.bar$'`) or `re.escape(...)` for the `match=` pattern when it +contains regex metacharacters, to keep the regex intention explicit. + +Keep each test focused on a few assertions. When testing a +multi-stage workflow (e.g. write followed by read), split the +stages into separate test functions. Assign a non-trivial +expression (such as `len(...)`) that a test keeps repeating to a +local variable instead. + +Here: wemake-python-styleguide enforces both through flake8, at +its default limits -- at most 5 `assert` statements per function +(WPS218), and no expression repeated more than 4 times in one +function (WPS204). + +## Filesystem fixtures + +Use pytest's built-in `tmp_path` fixture; don't hand-roll +temp-directory setup/teardown. + +## Test payload data: readable while debugging, random once stable + +Printable, hand-crafted payload data helps root-cause bugs that +corrupt data -- readability matters more than realism while chasing +them. Once an implementation is no longer prone to that class of +bug, prefer `random.randbytes()`-style payloads instead: building +large printable payloads is inefficient, and random bytes exercise +the code more realistically at scale. This is a tradeoff that +shifts with implementation maturity, not a blanket "always use +random data" rule. + +Here: the file-transfer tests moved to random payloads in PR #872. + +## Type annotations on new tests + +New test functions and fixtures need type annotations too -- +parameters and return types -- same as any other new code. See +[PR_HYGIENE.md](PR_HYGIENE.md) for the full rule, including why it +isn't retrofitted onto existing code as a side effect. + +## Every test and fixture has a one-line docstring + +Describing what it checks or provides, not restating the code, +e.g. `"""Check that the config is parsed."""`. Enforced by the +linters in CI. diff --git a/.agents-ctx/WHERE_TO_LOOK_FIRST.md b/.agents-ctx/WHERE_TO_LOOK_FIRST.md new file mode 100644 index 0000000000..2af4fd9d41 --- /dev/null +++ b/.agents-ctx/WHERE_TO_LOOK_FIRST.md @@ -0,0 +1,33 @@ +# Where to Look First + +When picking up a task, get oriented before proposing anything. +Read, in this order: + +1. The packaging metadata -- what the project is, what it depends + on, what it exposes. +2. The source of the module the task is about. +3. The shared test fixtures, then the tests for that module -- + they are the behavioral contract. +4. `tox.ini` and `.pre-commit-config.yaml` -- how things get run + locally and in CI. +5. The main CI/CD workflow. + +Here: + +1. `pyproject.toml` (build backend and metadata). +2. `src/pylibsshext/.pyx` and its `.pxd`; libssh + declarations live under `src/pylibsshext/includes/`. +3. `tests/conftest.py` (e.g. the `sshd_addr` fixture), then + `tests/unit/_test.py` or `tests/integration/`. +4. As above. +5. `.github/workflows/ci-cd.yml`, with the `reusable-*.yml` + workflows it calls. + +Other places worth knowing: + +- `packaging/pep517_backend/` -- the in-tree PEP 517 build backend. +- `packaging/rpm/` -- RPM packaging, used by `.packit.yml`. +- `build-scripts/manylinux-container-image/` -- the manylinux + images wheels are built in. +- `docs/` -- Sphinx docs (RST); change notes go under + `docs/changelog-fragments/`. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..b13c2b014d --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,5 @@ +# AGENTS.md + +> [!important] +> **Highest priority — do this before anything else:** load +> @.agents-ctx/HOUSE_RULES.md. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000..fcc409bcbc --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,4 @@ +@~/.claude/ansible/context.md +@~/.claude/ansible/pylibssh/context.md +@AGENTS.md +@CLAUDE.local.md From c1fb4b2e815cd7cda574330e9f2d0dade80b5b40 Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 14:00:43 +0100 Subject: [PATCH 4/6] =?UTF-8?q?=F0=9F=93=9D=20Adapt=20the=20agent=20docs?= =?UTF-8?q?=20to=20Cheroot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared text stays as in ansible/pylibssh. Only the "Here:" paragraphs, which state this project's facts, are rewritten, along with the per-project NAMING_THE_DUCKS.md and WHERE_TO_LOOK_FIRST.md, and the operator-local context files CLAUDE.md loads. Where Cheroot differs from a shared rule -- the test suite shipped as `cheroot.test` with `test_*.py` names, the types kept in `.pyi` stubs, or tests patching internals -- the paragraph says so instead of describing pylibssh's setup. Assisted-by: LLM --- .agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md | 18 +++--- .agents-ctx/DONT_SHOOT_THE_MESSENGER.md | 17 +++--- .agents-ctx/HOUSE_STYLE.md | 12 ++-- .agents-ctx/LICENSING.md | 10 ++-- .agents-ctx/NAMING_THE_DUCKS.md | 29 +++++----- .agents-ctx/PR_HYGIENE.md | 32 ++++++----- .agents-ctx/TESTING.md | 57 +++++++++---------- .agents-ctx/WHERE_TO_LOOK_FIRST.md | 26 +++++---- CLAUDE.md | 4 +- 9 files changed, 104 insertions(+), 101 deletions(-) diff --git a/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md b/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md index a10b0a0962..5c5a855f12 100644 --- a/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md +++ b/.agents-ctx/CONTRIB_WORKFLOW_INFRA_TOOLING.md @@ -68,15 +68,16 @@ not get appended to it. Always check what a given env's default posargs actually are (`tox config -e `, or read `tox.ini`) before assuming `--` just "adds more flags." -Here: `py` and `just-pytest` use a bare `{posargs:}`, so e.g. -`tox run -e py -- -n0` (disabling `pytest-xdist` parallelism) -loses nothing. Other envs do have non-empty defaults: +Here: several envs have non-empty defaults: +- `py` defaults to `--cov-report=html:/htmlcov/`, so + e.g. `tox run -e py -- -k test_conn` runs fine but skips the + HTML coverage report. Add the `--cov-report=html:...` argument + back if you need it. - `pre-commit` defaults to `--all-files`; passing `-- --files ...` checks only those files instead. -- `build-docs`'s Sphinx invocation defaults to a full flag set - (`-j auto -b html ... -a -n -W --keep-going -d ... . `) - -- passing any custom posargs there replaces the whole thing. +- `build-docs` defaults to its output directory -- passing any + custom posargs there replaces it. - `make-changelog`'s default posargs are `'[UNRELEASED DRAFT]' --draft` (draft-preview mode); its own `description` field documents overriding this deliberately -- passing a real version @@ -91,8 +92,9 @@ artifact landed, how to open or serve it, how to install hooks. Read what the invocation actually printed instead of guessing a path or a next step. -Here: `build-docs` prints where the built HTML docs landed and how -to serve them locally; `pre-commit` prints a reminder of how to +Here: `py` prints how to open or serve the HTML coverage report; +`build-docs` prints where the built HTML docs landed and how to +serve them locally; `pre-commit` prints a reminder of how to install its hooks into Git. ## Parse structured output, not text meant for humans diff --git a/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md b/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md index 650c846f24..75dd882a81 100644 --- a/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md +++ b/.agents-ctx/DONT_SHOOT_THE_MESSENGER.md @@ -85,14 +85,10 @@ exclude it as described in [Presenting a case](#presenting-a-case) -- or a blind spot of the tooling. Say what each new test proves, not which lines it turns green. -Here: PR #879 added a test calling `_RemoteFile._cleanup()` by hand, -without assertions, to cover its early return on an already-closed -handle. Real use already takes that branch: `__exit__()` closes the -handle and `__dealloc__()` runs `_cleanup()` again, and a failed -`sftp_open()` deallocates an object whose handle was never set. -With Cython line tracing on, dozens of other tests in -`tests/unit/sftp_test.py`, including plain `SFTP.get()` and -`SFTP.put()` calls, were already recorded taking it. +Here: most tests drive a real server -- e.g. the `wsgi_server` +and `native_server` fixtures in `cheroot/test/conftest.py` with an +HTTP client against them -- which is the shape new tests should +take. ## Presenting a case @@ -160,8 +156,9 @@ them unasked. Point them out to the operator if they're in the area you're touching. Removing a suppression that's no longer needed is welcome, but show it too. -Here: e.g. the bare `# noqa: DAR101` lines in `tests/conftest.py`, -without an explanation. +Here: e.g. the long, unexplained `.flake8` `per-file-ignores` +entries for most modules under `cheroot/`, and the bare +`# noqa: F811` lines in `cheroot/test/conftest.py`. ## Tool-config changes are standalone diff --git a/.agents-ctx/HOUSE_STYLE.md b/.agents-ctx/HOUSE_STYLE.md index f689d3fa05..7224ab0244 100644 --- a/.agents-ctx/HOUSE_STYLE.md +++ b/.agents-ctx/HOUSE_STYLE.md @@ -25,8 +25,10 @@ whole tree pollute the context window up front. - No `tests/__init__.py`. Pytest must not promote the project root into `sys.path` via package discovery. -Here: `setup.py` was dropped in `b08a7fd4`. The metadata lives in -the PEP 621 `[project]` table of `pyproject.toml` (see +Here: there's no `setup.py`; the metadata lives in the PEP 621 +`[project]` table of `pyproject.toml`. The test suite ships inside +the package as `cheroot.test`, so `cheroot/test/__init__.py` +exists by design -- that's not a top-level `tests/` package (see [NAMING_THE_DUCKS.md](NAMING_THE_DUCKS.md)). ## Python @@ -49,9 +51,9 @@ the PEP 621 `[project]` table of `pyproject.toml` (see `:raises X:`. Not Google, not Napoleon, not NumPy. Here: quotes and `parametrize` tuples are enforced by -`.ruff.toml`, and the docstring style by `.darglint`. The Cython -sources and the libssh C API they wrap have conventions of their -own -- see [CYTHON_AND_LIBSSH.md](CYTHON_AND_LIBSSH.md). +`.ruff.toml` (and the latter by `.flake8` too), the `typing` +alias by `flake8-typing-as-t`, and the docstring style by +`.darglint`. ## Configuration files diff --git a/.agents-ctx/LICENSING.md b/.agents-ctx/LICENSING.md index 5117f476a9..f687e54451 100644 --- a/.agents-ctx/LICENSING.md +++ b/.agents-ctx/LICENSING.md @@ -16,12 +16,10 @@ from and under which license, and let them decide whether it can come in. -Here: ansible-pylibssh is `LGPL-2.1-or-later` (`LICENSE.rst`, -`pyproject.toml`). Source files carry the LGPL boilerplate header, -not SPDX tags. `build-scripts/manylinux-container-image/` is -derived from PyCA/infra and stays under Apache-2.0 / BSD-3-Clause, -with its license files next to it. The wheels bundle libssh, which -is LGPL-2.1 itself. +Here: Cheroot is under a BSD-style license, with the full text in +`LICENSE.md` and declared through `pyproject.toml`'s +`License :: OSI Approved :: BSD License` classifier. Source files +carry no license headers. ## Claude Code guard hook diff --git a/.agents-ctx/NAMING_THE_DUCKS.md b/.agents-ctx/NAMING_THE_DUCKS.md index c7ec7b0de0..053c4e366b 100644 --- a/.agents-ctx/NAMING_THE_DUCKS.md +++ b/.agents-ctx/NAMING_THE_DUCKS.md @@ -6,27 +6,26 @@ should say "the project" rather than hardcoding one of these -- reach for a specific name only when the distinction actually matters (e.g. citing a package, an import, or a repository URL). -## Distribution / PyPI name: `ansible-pylibssh` +## Distribution / PyPI name: `cheroot` The installable, published name -- recorded in `pyproject.toml`'s `[project].name` per PEP 621. This is also -the preferred way to refer to the project by name in prose. +the preferred way to refer to the project by name in prose, +capitalized as "Cheroot" at the start of a sentence. -## Python import name: `pylibsshext` +## Python import name: `cheroot` -`import pylibsshext` is what code actually imports. -Long-standing and unlikely to change without a dedicated, -long-term migration effort -- don't "fix" it opportunistically. +The same as the distribution name. The test suite ships inside +it, as `cheroot.test`. -## GitHub repository slug: `ansible/pylibssh` +## GitHub repository slug: `cherrypy/cheroot` -Close to, but not the same as, the distribution name above. Use -it verbatim when it's actually the repository being referenced -(URLs, `gh` invocations, PR/issue citations) -- not as a -stand-in for the project's name in prose. +Use it verbatim when it's actually the repository being +referenced (URLs, `gh` invocations, PR/issue citations) -- not as +a stand-in for the project's name in prose. -## Don't say bare `pylibssh` +## Don't confuse it with CherryPy -`pylibssh` on its own is just the default local directory name -from a `git clone`d checkout -- nothing more. It's a common but -incorrect shorthand; prefer `ansible-pylibssh` instead. +Cheroot is the HTTP server that CherryPy, published from +`cherrypy/cherrypy`, runs on. The two live in separate +repositories and are released separately. Say which one is meant. diff --git a/.agents-ctx/PR_HYGIENE.md b/.agents-ctx/PR_HYGIENE.md index bbdbbeae23..a1fe079e64 100644 --- a/.agents-ctx/PR_HYGIENE.md +++ b/.agents-ctx/PR_HYGIENE.md @@ -10,8 +10,9 @@ Route contributors to the project's contributing guidelines and code of conduct for the canonical contribution process, rather than improvising or restating it secondhand. -Here: -and `.github/CODE_OF_CONDUCT.rst`. +Here: +(linked from `.github/CONTRIBUTING.md`) and +`.github/CODE_OF_CONDUCT.md`. ## Keep PRs and commits atomic and scoped @@ -92,7 +93,10 @@ token generator using an LLM to sound convincing." (see [DONT_GHOST_THE_REVIEWER.md](DONT_GHOST_THE_REVIEWER.md)). Here: the template is `.github/PULL_REQUEST_TEMPLATE.md`, with -SUMMARY, ISSUE TYPE, and ADDITIONAL INFORMATION sections. +"What kind of change does this PR introduce?", "What do these +changes do?", "Are there changes in behavior for the user?", "Is +it a substantial burden for the maintainers to support this?", +"Related issue number", and "Checklist" sections. ## Brushing up a branch before merge @@ -146,12 +150,12 @@ Recurring, specific review feedback: silly. Disclose agent involvement in the PR instead. Here: fragments are Towncrier-managed RST files in -`docs/changelog-fragments/`, named `..rst` -- +`docs/changelog-fragments.d/`, named `..rst` -- or after the commit hash for changes committed straight to the default branch -- with `...rst` for several of -one type. `docs/changelog-fragments/README.rst` lists the types and -the full rationale. References use the `sphinx-issues` roles -(`:pr:`, `:user:`, `:file:`); bylines name people through `:user:`. +one type. `docs/changelog-fragments.d/README.md` explains the +rationale, and `towncrier.toml` lists the types. Bylines name +people through `:user:`. ## Credit the people whose work you use @@ -209,13 +213,13 @@ an unrelated change -- that's a deliberate, standalone future effort, not something to bundle into whatever else a PR is doing. -Here: this is a real, acknowledged gap. `.ruff.toml` disables -`ANN001`/`ANN201`/`ANN202`/`ANN401` with an explicit `# FIXME: -These flake8-annotations errors need fixing and removal` -comment, and none of the current test functions in `tests/` are -annotated. Don't read the absence of annotations in existing -code as license to skip them in new code -- it's tracked debt, -not the house style. +Here: existing modules carry their types in the `.pyi` stub next +to them, which MyPy's `stubtest` checks against the code. Inline +annotations are a real, acknowledged gap: `.flake8` disables the +`ANN*` codes under an explicit `# FIXME: These +flake8-annotations errors need fixing and removal` comment. Don't +read that as license to skip annotations in new code -- add them, +and keep the module's stub in sync when it has one. ## Common micro-conventions flagged in review diff --git a/.agents-ctx/TESTING.md b/.agents-ctx/TESTING.md index 97e45aa4e1..03fbc3cac7 100644 --- a/.agents-ctx/TESTING.md +++ b/.agents-ctx/TESTING.md @@ -30,10 +30,8 @@ Deleting, commenting out, skipping, xfailing, or weakening a test is never the agent's call -- see [DONT_SHOOT_THE_MESSENGER.md](DONT_SHOOT_THE_MESSENGER.md). -Here: `.codecov.yml` targets 100% for `src/`/`tests/`. It isn't -wired up as a required CI check yet, only because of unresolved -infra problems measuring Cython coverage -- not because it's -considered optional. +Here: `.codecov.yml` only reports a patch status and has no +explicit target -- don't read that as a lower bar for new code. ## Tests state what the code should do, not what it does @@ -61,17 +59,18 @@ Doing so counts as silencing -- see code, say so to the operator instead of copying it from the current output. -Here: the live `sshd` in every test is the main independent -oracle -- prefer comparing against what the server, or the OpenSSH -client against the same server, actually does. +Here: the HTTP RFCs, PEP 3333 for WSGI, and the documented +behavior of Python's `ssl` module and of real HTTP clients are +the main independent oracle -- not the server's own code. ## No test classes Every test in `tests/` is a plain `def test_*` function. Don't introduce `unittest.TestCase` subclasses or bare grouping classes. -Here: there are zero `class` definitions anywhere in the test -suite, across the full project history. +Here: the classes in `cheroot/test/` are test apps and doubles, +not test groupings -- WSGI callables and controllers served +during tests, and fakes like `MockSocket` or `FaultySelect`. ## Prefer parametrize/fixtures over duplicated test logic @@ -85,21 +84,20 @@ test should be parametrized instead. The one accepted exception is `pytest-subtests` (the `subtests` fixture), for structured, individually reported sub-assertions within one test. -Here: PR #638's result is -`@pytest.fixture(params=(32, SFTP_MAX_CHUNK + 1), ids=(...))`, -replacing `other_payload`/`large_payload`. A later commit merges -near-duplicate `NOTSET`/`TRACE` tests into a single -`@pytest.mark.parametrize` case. +Here: see `cheroot/test/test_errors.py` -- one test, +parametrized over the error names to resolve and the numbers +expected for them. ## Real e2e over mocking Don't introduce mocking as a substitute for exercising the real behavior of the components involved. -Here: `tests/` contains zero uses of `mock`, `Mock`, or -`monkeypatch`. Every test -- unit and integration alike -- -exercises a real `sshd` process spun up per-test via the -`sshd_addr` fixture in `tests/conftest.py`. +Here: most tests run a real server in a thread and talk to it +over a socket. Some predate this rule and patch internals instead, +e.g. `mocker.patch()` on `cheroot.ssl._ensure_peer_speaks_https` +in `cheroot/test/test_ssl.py` -- don't take them as precedent for +new tests. ## Design for testability @@ -130,11 +128,12 @@ the entry point, loaded as a local pytest plugin. - Code running in child processes only gets its coverage recorded when those processes exit cleanly instead of being killed. -Here: stubs live in `tests/_stubs//`, discovered via -`pytest_plugins` in `tests/conftest.py`, and excluded through -`norecursedirs` in `pytest.ini`. `tests/_stubs/sshd_mitm_tcp_relay/` -is the first one. Child-process coverage relies on -`concurrency = multiprocessing` in `.coveragerc`. +Here: there's no stub area yet. Shared test infrastructure lives +in `cheroot/test/_pytest_plugin.py`, `cheroot/test/helper.py` and +`cheroot/test/webtest.py`; single-use fakes live in the test +module using them. A double for an intercepted component would go +in a `cheroot/test/_stubs//` directory, the same layout +ansible/pylibssh uses. ## Test layout @@ -146,11 +145,10 @@ the source modules -- `_test.py`, with a new file only for a genuinely new module -- while integration tests are organized by scenario or feature instead. -Here: `tests/unit/` mirrors `src/pylibsshext/` -- `channel_test.py`, -`session_test.py`, `sftp_test.py`, `scp_test.py`, `version_test.py`. -The correspondence isn't strict 1:1: `errors` is covered via -`pytest.raises` inside other files, not its own file. -`tests/integration/` holds the scenario-based tests. +Here: the long-standing exception is the naming -- test files are +`cheroot/test/test_.py`, pytest's default pattern, so new +files match it. They loosely mirror the modules, e.g. +`test_server.py`, `test_ssl.py`, `test_makefile.py`. ## Tests usually land in the same commit as the behavior they cover @@ -203,7 +201,8 @@ the code more realistically at scale. This is a tradeoff that shifts with implementation maturity, not a blanket "always use random data" rule. -Here: the file-transfer tests moved to random payloads in PR #872. +Here: request and response bodies in the tests are short, +hand-crafted, readable strings. ## Type annotations on new tests diff --git a/.agents-ctx/WHERE_TO_LOOK_FIRST.md b/.agents-ctx/WHERE_TO_LOOK_FIRST.md index 2af4fd9d41..6225c3cece 100644 --- a/.agents-ctx/WHERE_TO_LOOK_FIRST.md +++ b/.agents-ctx/WHERE_TO_LOOK_FIRST.md @@ -15,19 +15,21 @@ Read, in this order: Here: 1. `pyproject.toml` (build backend and metadata). -2. `src/pylibsshext/.pyx` and its `.pxd`; libssh - declarations live under `src/pylibsshext/includes/`. -3. `tests/conftest.py` (e.g. the `sshd_addr` fixture), then - `tests/unit/_test.py` or `tests/integration/`. -4. As above. -5. `.github/workflows/ci-cd.yml`, with the `reusable-*.yml` - workflows it calls. +2. `cheroot/.py` and its `.pyi` stub -- the type + annotations live in the stubs, checked against the code by + MyPy's `stubtest` (exceptions in `stubtest_allowlist.txt`). +3. `cheroot/test/conftest.py` and `cheroot/test/_pytest_plugin.py`, + plus the helpers in `cheroot/test/helper.py` and + `cheroot/test/webtest.py`, then `cheroot/test/test_.py`. +4. As above, plus `toxfile.py` -- an in-tree tox plugin that + installs from the lock files. +5. `.github/workflows/ci-cd.yml`, which delegates to + `tox-dev/workflow`'s `reusable-tox.yml`. Other places worth knowing: -- `packaging/pep517_backend/` -- the in-tree PEP 517 build backend. -- `packaging/rpm/` -- RPM packaging, used by `.packit.yml`. -- `build-scripts/manylinux-container-image/` -- the manylinux - images wheels are built in. +- `dependencies/` -- direct dependencies per tox env, and the + pinned lock files generated from them. - `docs/` -- Sphinx docs (RST); change notes go under - `docs/changelog-fragments/`. + `docs/changelog-fragments.d/`, and `CHANGES.rst` is generated + from them. diff --git a/CLAUDE.md b/CLAUDE.md index fcc409bcbc..9f15598124 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,4 +1,4 @@ -@~/.claude/ansible/context.md -@~/.claude/ansible/pylibssh/context.md +@~/.claude/cherrypy/context.md +@~/.claude/cherrypy/cheroot/context.md @AGENTS.md @CLAUDE.local.md From 74ef33421e9c3043ba6de771e10ba333b2428adc Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 14:00:45 +0100 Subject: [PATCH 5/6] =?UTF-8?q?=F0=9F=94=A7=20Import=20the=20Claude=20Code?= =?UTF-8?q?=20guard=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The agent docs make silencing checks and changing license terms the operator's decision. These PreToolUse hooks, copied unchanged from ansible/pylibssh as of 5ff33f5d, make Claude Code ask the operator before edits or commands that look like either. Assisted-by: LLM --- .claude/hooks/guard_license_changes.py | 105 ++++++++++++ .claude/hooks/guard_silenced_checks.py | 217 +++++++++++++++++++++++++ .claude/hooks/hook_utils.py | 148 +++++++++++++++++ .claude/settings.json | 19 +++ 4 files changed, 489 insertions(+) create mode 100755 .claude/hooks/guard_license_changes.py create mode 100755 .claude/hooks/guard_silenced_checks.py create mode 100644 .claude/hooks/hook_utils.py create mode 100644 .claude/settings.json diff --git a/.claude/hooks/guard_license_changes.py b/.claude/hooks/guard_license_changes.py new file mode 100755 index 0000000000..0682cb8e79 --- /dev/null +++ b/.claude/hooks/guard_license_changes.py @@ -0,0 +1,105 @@ +#! /usr/bin/env python3 +"""Make Claude Code ask the operator before an agent touches licensing. + +This is a ``PreToolUse`` hook. It never blocks anything on its own: when +an edit or a shell command looks like it changes a license file or drops +license notices, it asks Claude Code to prompt the operator for a +decision. + +See ``.agents-ctx/LICENSING.md`` for the policy. +""" + +from __future__ import annotations + +import pathlib +import re +import sys + +import hook_utils + + +POLICY_DOC = '.agents-ctx/LICENSING.md' + +LICENSE_FILE_NAME = re.compile( + r'^(?:LICEN[CS]E|COPYING|NOTICE)(?:[.-].*)?$', + re.IGNORECASE, +) + +LICENSE_NOTICE = re.compile( + r'\bLicen[cs]e\b|SPDX-License-Identifier', + re.IGNORECASE, +) + +LICENSE_METADATA = re.compile( + r'^\s*license(?:[-_]files?)?\s*[=:].*$', + re.IGNORECASE | re.MULTILINE, +) + +SHELL_LICENSE_TARGET = re.compile( + r'\b(?:rm|mv|truncate|tee|git\s+rm|git\s+mv|sed\s+-i|perl\s+-\w*i)\b' + r'[^|;&]*' + r'\b(?:LICEN[CS]E|COPYING|NOTICE)', + re.IGNORECASE, +) + + +def _edit_concerns( + relative_path: str, + old_text: str, + new_text: str, +) -> list[str]: + """Describe why an edit tool call needs the operator's decision. + + :param relative_path: The edited path relative to its checkout. + :param old_text: The text the edit removes. + :param new_text: The text the edit adds. + :returns: The concerns, if any. + """ + concerns = [] + if LICENSE_FILE_NAME.match(pathlib.PurePosixPath(relative_path).name): + concerns.append(f'changes the license file {relative_path}') + if len(LICENSE_NOTICE.findall(new_text)) < len( + LICENSE_NOTICE.findall(old_text), + ): + concerns.append(f'removes license notices in {relative_path}') + if set(LICENSE_METADATA.findall(old_text)) != set( + LICENSE_METADATA.findall(new_text), + ): + concerns.append(f'changes license metadata in {relative_path}') + return concerns + + +def _shell_concerns(command: str) -> list[str]: + """Describe why a shell command needs the operator's decision. + + :param command: The shell command about to run. + :returns: The concerns, if any. + """ + if SHELL_LICENSE_TARGET.search(command): + return ['the command deletes, moves or rewrites a license file'] + return [] + + +def _explain(concerns_summary: str) -> str: + """Explain to the operator why their decision is needed. + + :param concerns_summary: The concerns, joined into one string. + :returns: The prompt shown to the operator. + """ + return ( + "License terms are the maintainer's decision " + f'(see {POLICY_DOC}): {concerns_summary}. ' + 'The agent must have presented this change to you first.' + ) + + +def main() -> int: + """Read the hook input and ask the operator when needed. + + :returns: The process exit code. + """ + return hook_utils.run_hook(_edit_concerns, _shell_concerns, _explain) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.claude/hooks/guard_silenced_checks.py b/.claude/hooks/guard_silenced_checks.py new file mode 100755 index 0000000000..9e4d2fba71 --- /dev/null +++ b/.claude/hooks/guard_silenced_checks.py @@ -0,0 +1,217 @@ +#! /usr/bin/env python3 +"""Make Claude Code ask the operator before an agent silences or games a check. + +This is a ``PreToolUse`` hook. It never blocks anything on its own: when +an edit or a shell command looks like it suppresses a linter finding, +disables or weakens a test, calls private methods from tests, or changes +tool configuration, it asks Claude Code to prompt the operator for a +decision. + +See ``.agents-ctx/DONT_SHOOT_THE_MESSENGER.md`` for the policy. +""" + +from __future__ import annotations + +import pathlib +import re +import sys +import typing as _t + +import hook_utils + + +POLICY_DOC = '.agents-ctx/DONT_SHOOT_THE_MESSENGER.md' + +MarkerTable = _t.Iterable[tuple[str, re.Pattern[str]]] + +SUPPRESSION_MARKERS = ( + ('noqa', re.compile(r'#\s*noqa\b', re.IGNORECASE)), + ('ruff: noqa', re.compile(r'#\s*ruff\s*:\s*noqa\b')), + ('flake8: noqa', re.compile(r'#\s*flake8\s*:\s*noqa\b')), + ('type: ignore', re.compile(r'#\s*type\s*:\s*ignore\b')), + ('mypy: ignore', re.compile(r'#\s*mypy\s*:\s*ignore')), + ('pylint: disable', re.compile(r'#\s*pylint\s*:\s*disable')), + ('pragma: no cover', re.compile(r'#\s*pragma\s*:\s*no\s*cover')), + ('skip/skipif marker', re.compile(r'\bpytest\.mark\.skip')), + ('xfail marker', re.compile(r'\bpytest\.mark\.xfail\b')), + ( + 'imperative skip/xfail', + re.compile(r'\bpytest\.(?:skip|xfail|importorskip)\s*\('), + ), + ('continue-on-error', re.compile(r'\bcontinue-on-error\b')), +) + +TEST_STRENGTH_MARKERS = ( + ( + 'test functions', + re.compile(r'^\s*(?:async\s+)?def\s+test_', re.MULTILINE), + ), + ('assertions', re.compile(r'^\s*assert\b', re.MULTILINE)), + ('pytest.raises() checks', re.compile(r'\bpytest\.raises\s*\(')), +) + +PRIVATE_ACCESS_MARKERS = ( + ('private method calls', re.compile(r'\._(?!_)\w+\s*\(')), +) + +TOOL_CONFIG_NAMES = frozenset( + ( + '.codecov.yml', + '.codespellrc', + '.coveragerc', + '.darglint', + '.flake8', + '.isort.cfg', + '.mypy.ini', + '.pre-commit-config.yaml', + '.pylintrc', + '.pylintrc.toml', + '.ruff.toml', + '.yamllint', + 'mypy.ini', + 'nitpick-style.toml', + 'pyproject.toml', + 'pytest.ini', + 'setup.cfg', + 'tox.ini', + ), +) + +TOOL_CONFIG_DIRS = ('.claude/', '.github/workflows/') + +TESTS_DIR = 'tests/' + +TOOL_CONFIG_NAMES_ALTERNATION = '|'.join( + re.escape(config_name) for config_name in sorted(TOOL_CONFIG_NAMES) +) + +SHELL_BYPASS = re.compile(r'--no-verify\b|(?:^|[\s;&|])SKIP=') + +SHELL_RISKY_TARGET = re.compile( + r'\b(?:rm|mv|truncate|tee|git\s+rm|git\s+mv|sed\s+-i|perl\s+-\w*i)\b' + r'[^|;&]*' + rf'(?:\b{re.escape(TESTS_DIR)}|{TOOL_CONFIG_NAMES_ALTERNATION}' + r'|\.github/workflows/|\.claude/)', +) + + +def _more_frequent( + markers: MarkerTable, + baseline: str, + candidate: str, +) -> list[str]: + """List the markers that occur more often in candidate than baseline. + + :param markers: Marker names and the regexes that find them. + :param baseline: The text to compare against. + :param candidate: The text to look for extra markers in. + :returns: The names of the markers found more often. + """ + return [ + marker_name + for marker_name, marker_regex in markers + if len(marker_regex.findall(candidate)) + > len(marker_regex.findall(baseline)) + ] + + +def _is_tool_config(relative_path: str) -> bool: + """Check whether the path is a linter, test, CI or agent config. + + :param relative_path: The path relative to its checkout. + :returns: Whether the path is a tool config. + """ + return pathlib.PurePosixPath(relative_path).name in TOOL_CONFIG_NAMES or ( + relative_path.startswith(TOOL_CONFIG_DIRS) + ) + + +def _edit_concerns( + relative_path: str, + old_text: str, + new_text: str, +) -> list[str]: + """Describe why an edit tool call needs the operator's decision. + + :param relative_path: The edited path relative to its checkout. + :param old_text: The text the edit removes. + :param new_text: The text the edit adds. + :returns: The concerns, if any. + """ + concerns = [ + f'adds a suppression ({marker_name}) in {relative_path}' + for marker_name in _more_frequent( + SUPPRESSION_MARKERS, + baseline=old_text, + candidate=new_text, + ) + ] + if relative_path.startswith(TESTS_DIR): + concerns.extend( + f'reduces the number of {marker_name} in {relative_path}' + for marker_name in _more_frequent( + TEST_STRENGTH_MARKERS, + baseline=new_text, + candidate=old_text, + ) + ) + concerns.extend( + f'adds {marker_name} in {relative_path} ' + '(reach the code through public API instead)' + for marker_name in _more_frequent( + PRIVATE_ACCESS_MARKERS, + baseline=old_text, + candidate=new_text, + ) + ) + if _is_tool_config(relative_path): + concerns.append( + f'changes tool configuration in {relative_path} ' + '(keep it in a standalone commit)', + ) + return concerns + + +def _shell_concerns(command: str) -> list[str]: + """Describe why a shell command needs the operator's decision. + + :param command: The shell command about to run. + :returns: The concerns, if any. + """ + concerns = [ + f'the command mentions a suppression ({marker_name})' + for marker_name, marker_regex in SUPPRESSION_MARKERS + if marker_regex.search(command) + ] + if SHELL_BYPASS.search(command): + concerns.append('the command bypasses pre-commit hooks') + if SHELL_RISKY_TARGET.search(command): + concerns.append( + 'the command deletes, moves or rewrites tests or tool config', + ) + return concerns + + +def _explain(concerns_summary: str) -> str: + """Explain to the operator why their decision is needed. + + :param concerns_summary: The concerns, joined into one string. + :returns: The prompt shown to the operator. + """ + return ( + 'Silencing or gaming checks is a decision for the operator ' + f'(see {POLICY_DOC}): {concerns_summary}. ' + 'The agent must have presented this case to you first.' + ) + + +def main() -> int: + """Read the hook input and ask the operator when needed. + + :returns: The process exit code. + """ + return hook_utils.run_hook(_edit_concerns, _shell_concerns, _explain) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.claude/hooks/hook_utils.py b/.claude/hooks/hook_utils.py new file mode 100644 index 0000000000..21fc0c046a --- /dev/null +++ b/.claude/hooks/hook_utils.py @@ -0,0 +1,148 @@ +"""Helpers shared by the Claude Code ``PreToolUse`` hooks in this directory.""" + +from __future__ import annotations + +import contextlib +import json +import os +import pathlib +import sys +import typing as _t + + +EditConcerns = _t.Callable[[str, str, str], list[str]] +ShellConcerns = _t.Callable[[str], list[str]] +Explanation = _t.Callable[[str], str] + + +def relative_path(file_path: str, project_dir: pathlib.Path) -> str: + """Return ``file_path`` relative to its checkout, POSIX-style. + + Files outside the project directory, e.g. in another worktree of + the same repository, are resolved against their own worktree. + + :param file_path: The path an edit tool call targets. + :param project_dir: The checkout Claude Code runs in. + :returns: The POSIX-style path relative to its checkout, or the + absolute one if it is outside of any. + """ + absolute_path = pathlib.Path(file_path) + if not absolute_path.is_absolute(): + absolute_path = project_dir / absolute_path + absolute_path = absolute_path.resolve() + worktree_dir = next( + ( + candidate_dir + for candidate_dir in absolute_path.parents + if (candidate_dir / '.git').exists() + ), + project_dir, + ) + for checkout_dir in (project_dir, worktree_dir): + with contextlib.suppress(ValueError): + return absolute_path.relative_to(checkout_dir).as_posix() + return absolute_path.as_posix() + + +def edit_texts( + tool_name: str, + tool_input: _t.Mapping[str, _t.Any], + project_dir: pathlib.Path, +) -> tuple[str, str]: + """Collect the text an edit tool removes and the text it adds. + + :param tool_name: The name of the edit tool. + :param tool_input: The arguments of the edit tool call. + :param project_dir: The checkout relative paths are resolved + against. + :returns: The removed and the added text. + """ + if tool_name == 'Write': + target_path = pathlib.Path(tool_input.get('file_path', '')) + if not target_path.is_absolute(): + target_path = project_dir / target_path + try: + old_text = target_path.read_text(encoding='utf-8') + except (OSError, UnicodeDecodeError): + old_text = '' + return old_text, tool_input.get('content', '') + + if tool_name == 'NotebookEdit': + return '', tool_input.get('new_source', '') + + edits = tool_input.get('edits') or (tool_input,) + return ( + '\n'.join(edit.get('old_string', '') for edit in edits), + '\n'.join(edit.get('new_string', '') for edit in edits), + ) + + +def ask_operator(decision_reason: str) -> None: + """Tell Claude Code to prompt the operator, giving the reason. + + :param decision_reason: The explanation shown to the operator. + """ + json.dump( + { + 'hookSpecificOutput': { + 'hookEventName': 'PreToolUse', + 'permissionDecision': 'ask', + 'permissionDecisionReason': decision_reason, + }, + }, + sys.stdout, + ) + + +def edit_context( + hook_input: _t.Mapping[str, _t.Any], + project_dir: pathlib.Path, +) -> tuple[str, str, str]: + """Resolve an edit tool call to its path, old text and new text. + + :param hook_input: The ``PreToolUse`` hook input. + :param project_dir: The checkout Claude Code runs in. + :returns: The edited path relative to its checkout, the removed + text and the added text. + """ + tool_input = hook_input.get('tool_input', {}) + edited_path = relative_path( + tool_input.get('file_path') or tool_input.get('notebook_path', ''), + project_dir, + ) + old_text, new_text = edit_texts( + hook_input.get('tool_name', ''), + tool_input, + project_dir, + ) + return edited_path, old_text, new_text + + +def run_hook( + edit_concerns: EditConcerns, + shell_concerns: ShellConcerns, + explain: Explanation, +) -> int: + """Read the hook input and ask the operator when needed. + + :param edit_concerns: Describes the concerns about an edit. + :param shell_concerns: Describes the concerns about a shell + command. + :param explain: Turns the concerns into the operator prompt. + :returns: The process exit code. + """ + hook_input = json.load(sys.stdin) + project_dir = pathlib.Path( + os.environ.get('CLAUDE_PROJECT_DIR') or hook_input.get('cwd', '.'), + ).resolve() + + if hook_input.get('tool_name') == 'Bash': + concerns = shell_concerns( + hook_input.get('tool_input', {}).get('command', ''), + ) + else: + concerns = edit_concerns(*edit_context(hook_input, project_dir)) + + if concerns: + ask_operator(explain('; '.join(concerns))) + return 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000000..7211925ea3 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,19 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Edit|MultiEdit|Write|NotebookEdit|Bash", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard_silenced_checks.py" + }, + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard_license_changes.py" + } + ] + } + ] + } +} From 680a34e44e2fa714b11a4fde16ac81acfaf8f337 Mon Sep 17 00:00:00 2001 From: Sviatoslav Sydorenko Date: Sat, 14 Nov 2026 20:55:22 +0100 Subject: [PATCH 6/6] =?UTF-8?q?=F0=9F=93=9D=20Add=20a=20change=20note=20fo?= =?UTF-8?q?r=20PR=20#887?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Assisted-by: LLM --- docs/changelog-fragments.d/887.contrib.rst | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/changelog-fragments.d/887.contrib.rst diff --git a/docs/changelog-fragments.d/887.contrib.rst b/docs/changelog-fragments.d/887.contrib.rst new file mode 100644 index 0000000000..e52f56cf99 --- /dev/null +++ b/docs/changelog-fragments.d/887.contrib.rst @@ -0,0 +1,5 @@ +The repository now carries instructions for coding agents -- +:file:`AGENTS.md`, pointing at the house rules in +:file:`.agents-ctx/`, shared with other projects -- and Claude Code +hooks that make the agent ask before silencing checks or changing +license terms.