К основному содержанию
скилл CX Codex

rust-crate-ci — скилл для Claude Code: проверки Rust-крейта перед push

Скилл rust-crate-ci для правки Rust-крейта runners/swarm-sandbox-runner: задаёт порядок локальных проверок и разбирает ошибки Windows, которые видит только CI.

MIT ★ 539 обновлён 2026-10-29

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add ZaxbyHub/opencode-swarm --skill rust-crate-ci -a claude-code
Открыть на GitHub

Что делает rust-crate-ci

Скилл закрывает один крейт в репозитории, runners/swarm-sandbox-runner, и job rust-sandbox-runner, который гоняет его на windows-latest. Внутри жёсткий порядок из четырёх команд: cargo fmt --check, затем cargo clippy --all-targets -- -D warnings, затем cargo test --all-targets, затем cargo build --release. Порядок не косметика: пока не прошёл fmt, ошибки clippy просто не покажутся.

Дальше грабли. rustfmt решает по каждому синтаксическому элементу, поэтому format!, разбитый руками, схлопнется в одну строку, а длинный вызов развалится на аргументы. Скилл велит запускать cargo fmt и читать дифф. По clippy перечислены зафиксированная версия windows-rs, сырой HANDLE, который нельзя передать между потоками, импорты только под #[cfg(windows)] и Win32-структуры вроде STARTUPINFOW с ..Default::default().

Самое полезное — про пути. canonicalize на Windows возвращает префикс \\?\, а GitHub Actions отдаёт %TEMP% в коротком имени RUNNER~1, и сравнение с путём политики тихо проваливается. Канонизировать надо обе стороны. Коды 64–69 в error.rs заморожены для вызовов из runner-client.ts, событие exit обязано уходить и на таймауте, и на превышении квоты. Если cargo в PATH нет, скилл советует открыть draft PR и читать лог CI.

Какие задачи решает

  • прогнать fmt, clippy, тесты и release-сборку в правильном порядке
  • починить падение clippy из-за -D warnings
  • поймать расхождение путей с префиксом \\?\ до пуша
  • не сломать коды выхода IPC при правке error.rs
  • разобраться, почему %TEMP% на GitHub Actions не совпадает с корнем политики

Примеры запросов агенту

  • Загрузи скилл rust-crate-ci и прогони обязательные проверки перед пушем в runners/swarm-sandbox-runner.
  • Поправь сравнение путей в temp_watcher.rs, сверяясь с rust-crate-ci.
  • Почему clippy ругается на HANDLE? Посмотри в rust-crate-ci.

Как установить rust-crate-ci

1Через Skills CLI (Vercel)

npx skills add ZaxbyHub/opencode-swarm --skill rust-crate-ci -a claude-code

2Вручную: положить файлы

~/.claude/skills/rust-crate-ci/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/rust-crate-ci/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о rust-crate-ci

Как установить rust-crate-ci в Claude Code?

Выполните npx skills add ZaxbyHub/opencode-swarm --skill rust-crate-ci -a claude-code, скилл окажется в ~/.claude/skills/rust-crate-ci/SKILL.md.

Что делает rust-crate-ci?

Описывает, как локально проверить крейт runners/swarm-sandbox-runner и какие ошибки под Windows поймает job на windows-latest.

Нужен ли Windows локально?

Нет, но часть ошибок видна только в CI. Если cargo в PATH нет, скилл советует запушить draft PR и читать лог, а не гадать.

Исходный текст

SKILL.md · MIT
---
name: rust-crate-ci
description: >
  Load before editing any Rust crate in this repo (currently runners/swarm-sandbox-runner).
  Covers the mandatory local validation gate, common rustfmt/clippy pitfalls, and
  Windows-specific Rust correctness patterns that CI enforces but are hard to catch locally
  without a Windows toolchain.
metadata:
  audience: swarm-plugin
  effort: low
---

# Rust Crate CI Guide

This repo contains a Rust crate at `runners/swarm-sandbox-runner/`. The CI job that
validates it is `rust-sandbox-runner` (runs on `windows-latest`). This guide prevents
the most common failure modes before they reach CI.

## Mandatory local gate (run in order before pushing)

```powershell
cd runners/swarm-sandbox-runner

# 1. Format check — CI fails here first; clippy will not run if this fails
cargo fmt --check

# 2. Clippy — -D warnings makes all warnings hard errors; --all-targets matches CI,
#    which also lints tests, examples, and benches (ci.yml rust-sandbox-runner job)
cargo clippy --all-targets -- -D warnings

# 3. Tests — --all-targets matches CI; Windows-specific tests are gated with #[cfg(windows)]
cargo test --all-targets

# 4. Release build — confirms the binary compiles with optimizations
cargo build --release
```

Run them in this exact order. If `cargo fmt --check` fails, fix formatting first —
clippy errors may be masked until fmt passes.

If `cargo` is not in PATH locally (e.g. you are on a machine without Rust installed),
push to a draft PR and let CI run the checks. Read the CI log carefully; do not guess
at what failed.

## How rustfmt makes decisions

rustfmt (current stable — `rust-toolchain.toml` floats on `channel = "stable"`)
applies line-length thresholds per syntax item, not per file or per block.
Two patterns that look equivalent locally can format differently:

**Long `format!` macros:** If the total length of `format!("...", arg)` exceeds the
line limit, rustfmt splits it. If it fits on one line, rustfmt collapses it.

```rust
// rustfmt will COLLAPSE this to one line if it fits:
return Err(RunnerError::PolicyViolation {
    reason: format!(
        "cwd resolves outside allowed roots (symlink egress): {canonical_str}"
    ),
});

// rustfmt will SPLIT this if it exceeds the limit:
events::emit(&events::denial_event("deny_symlink_egress", Some(canonical_str)));
// becomes:
events::emit(&events::denial_event(
    "deny_symlink_egress",
    Some(canonical_str),
));
```

**Rule of thumb:** After editing, always run `cargo fmt` (not `--check`) locally to
apply rustfmt's opinion, then read the diff before committing. Do not hand-format
and assume rustfmt agrees.

## Common clippy errors in this codebase

**`windows-rs` 0.58 API changes:** Several Win32 APIs changed signatures between
`windows` crate versions. The `Cargo.toml` pins the version; do not bump it without
checking the full API diff.

**`HANDLE` is not `Send + Sync`:** Raw `HANDLE` values cannot be sent across threads.
Wrap them in a newtype with `unsafe impl Send` and `unsafe impl Sync`, or use
`OwnedHandle` from `std::os::windows::io`. The kill-callback pattern in
`temp_watcher.rs` uses raw `isize` (handle as integer) to sidestep this.

**Unused imports:** `#[cfg(windows)]` blocks frequently hide imports that are used
only on Windows. On non-Windows builds, the import becomes dead code. Use
`#[cfg(windows)]` on the `use` statement itself or accept the `#[allow(unused_imports)]`
annotation for platform-conditional code.

**`struct` default initialization:** For Win32 structs like `STARTUPINFOW`, use a
struct initializer with `..Default::default()` rather than `unsafe { std::mem::zeroed() }`
— clippy flags the latter when `Default` is available.

## Windows path normalization (critical correctness patterns)

These bugs are invisible on Linux/macOS CI and will only appear on `windows-latest`.

### `std::fs::canonicalize` always prepends `\\?\`

On Windows, `canonicalize` typically returns a verbatim extended-length path with
the `\\?\` prefix, but this is not guaranteed across all Windows configurations and
path forms. Always use `.strip_prefix` with a fallback:

```
C:\foo\bar  →  \\?\C:\foo\bar  (typical)
```

If you compare a canonicalized path against a policy root stored without this prefix,
the comparison silently fails. Strip the prefix before comparing, always with `.unwrap_or`:

```rust
let lower = canonical.to_string_lossy().to_lowercase();
let canonical_str = lower.strip_prefix("\\\\?\\").unwrap_or(&lower);
```

Apply the same strip to both sides of any comparison.

### GitHub Actions CI uses 8.3 short names in `%TEMP%`

`std::env::temp_dir()` on GitHub Actions Windows runners returns a path like:
```
C:\Users\RUNNER~1\AppData\Local\Temp
```

But `std::fs::canonicalize` expands it to:
```
C:\Users\runneradmin\AppData\Local\Temp
```

If your code stores the `temp_dir()` path as a policy root and then canonicalizes
the cwd, the comparison will fail because `RUNNER~1` ≠ `runneradmin`.

**Fix:** Canonicalize both the policy root AND the cwd before comparing. Fall back
to the raw value if the root does not exist on disk yet:

```rust
let root_resolved = std::fs::canonicalize(root)
    .map(|p| p.to_string_lossy().to_lowercase())
    .unwrap_or_else(|_| root.to_lowercase());
let root_cmp = root_resolved
    .strip_prefix("\\\\?\\")
    .unwrap_or(&root_resolved)
    .to_owned();
```

### `WaitForSingleObject` return value semantics

`WAIT_TIMEOUT` is `0x00000102u32`, not a Rust `Err`. Check the return value
explicitly before treating the child as having exited normally.

## IPC contract stability

The exit codes in `error.rs` are **frozen** — do not renumber them. TypeScript
callers in `runner-client.ts` depend on these values:

| Code | Meaning |
|------|---------|
| 0 | Child exited zero (or non-zero child exit code passed through directly) |
| 64 | Policy violation |
| 65 | Temp quota exceeded |
| 66 | Wall-clock timeout |
| 67 | Launcher misconfiguration or policy parse error (invalid JSON from caller) |
| 68 | OS API failure, I/O error, or JSON error |
| 69 | Probe failed |

The NDJSON event types on stderr (`start`, `denial`, `quota_exceeded`, `exit`) are
also frozen. Adding new event types is safe; renaming or removing existing ones
is a breaking IPC change.

**Exit events are required on every termination path.** Emit `exit_event` before
returning from both the wall-clock timeout path and the temp-cap kill path, not
only on the normal exit path. TypeScript consumers block waiting for an `exit` event.

## CI workflow reference

The job is defined in `.github/workflows/ci.yml` as `rust-sandbox-runner`.
It runs on `windows-latest` with the toolchain pinned in `runners/swarm-sandbox-runner/rust-toolchain.toml`.
All third-party `uses:` actions are pinned to 40-character SHAs per the repo policy.

Steps in order: fmt check → clippy → tests → release build → probe smoke test.

© ZaxbyHub · MIT · ZaxbyHub/opencode-swarm

Похожие скиллы

Все скиллы по теме «Языки программирования» →
rust_development vuralserhat86 Скилл rust_development задаёт правила разработки на Rust: от асинхронного рантайма Tokio и веб-сервисов на Axum до строгой обработки ошибок. CX Codex +1 1установок rust-best-practices morganlinton Скилл rust-best-practices для Claude Code помогает писать, проверять и объяснять код на Rust. Активируется при упоминании Rust, Cargo, .rs, borrow checker, clippy или rustfmt. CX Codex +1 1 100установок rust-coder sno-ai Скилл rust-coder для Claude Code помогает писать и менять код на Rust с учётом устройства репозитория. Включается для новых функций, рефакторинга и миграций, в том числе при крупных изменениях .rs и Cargo.toml. CX Codex +1 ★ 869звёзд репо rust-engineer sammcj Скилл rust-engineer на Claude Code настраивает помощника по Rust: от владения памятью и async-кода до тестов, Miri и оптимизации. Охватывает системные проекты. CX Codex +1 ★ 173звёзд репо rust-expert 0xfurai rust-expert — субагент для Claude Code, который пишет идиоматический Rust и проверяет безопасность кода. Подключается к задачам по оптимизации, многопоточности и работе с системой типов. CX Codex ★ 1 029звёзд репо bugfix-crate ulpi-io Скилл bugfix-crate последовательно разбирает существующий файл с проблемами Rust-крейта: проверяет каждую находку тестом и обновляет её статус после исправления. CX Codex +1 117установок

Из того же набора121

Весь набор →
commit-pr Скилл commit-pr ведёт работу с коммитами и pull request: от подготовки публикации до проверки CI и завершения PR. Он пригодится при выпуске изменений по GitHub issue. CX Codex +1 ★ 539звёзд репо contributing Скилл contributing проводит агента по всему циклу пул-реквеста в репозитории opencode-swarm: ветка, формат коммитов, фрагмент release notes, локальные проверки и шаблон описания. CX Codex +1 ★ 539звёзд репо clarify-spec Скилл clarify-spec устраняет маркеры неопределённости в спецификациях Swarm, опрашивая разработчика по одному вопросу за раз. CX Codex +1 ★ 539звёзд репо pre-phase-briefing Скилл pre-phase-briefing собирает контекст перед фазой проекта, проверяет прошлые ретроспективы и сверяет план с реальным состоянием кодовой базы. CX Codex +1 ★ 539звёзд репо clarify Скилл clarify разбирает неясные требования через четырёхэтапную воронку с проверкой критиком и готовит пакет решений без лишних вопросов. CX Codex +1 ★ 539звёзд репо editing-skills Скилл editing-skills помогает менять SKILL.md в opencode-swarm, не нарушая правила зеркалирования, публикации и проверки расхождений. Загрузите его перед редактированием скиллов в этом репозитории. CX Codex +1 ★ 539звёзд репо pr-reviewer Субагент pr-reviewer для ревью пул-реквестов в плагине opencode-swarm: восстанавливает замысел PR, сверяет его с кодом и ищет дефекты. Работает только на чтение. CX Codex +1 ★ 539звёзд репо git-revert-safety Скилл git-revert-safety помогает безопасно откатывать коммиты и мержи в Git без поломки версий в релизных манифестах и локфайлах. CX Codex +1 ★ 539звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой