agentleFS
MicrosoftKnown publishermicrosoft/webui/.github/skills/code-review/SKILL.md

code-review

Skill93 starsChanged 6 months agoMITView on GitHub

Framework code review checklist - correctness, performance, concurrency, design, and style.

188 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use starter, media-processing and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • ww-w-aiSkill

    starter

    Static web development guide for beginners. Covers HTML/CSS/JavaScript and Next.js App Router basics. Project initialization with "init starter". Triggers: static website, portfolio, landing page, HTML CSS, beginner, 정적 웹, 포트폴리오, 초보자, 静的サイト, 初心者, 静态网站, 初学者, sitio web estático, site statique, statische Website, sito web statico Do NOT use for: fullstack apps (use $dynamic), enterprise (use $enterprise).

    Also in 4 projects that use this

  • mrgoonieSkill

    media-processing

    Process multimedia files with FFmpeg (video/audio encoding, conversion, streaming, filtering, hardware acceleration) and ImageMagick (image manipulation, format conversion, batch processing, effects, composition). Use when converting media formats, encoding videos with specific codecs (H.264, H.265, VP9), resizing/cropping images, extracting audio from video, applying filters and effects, optimizing file sizes, creating streaming manifests (HLS/DASH), generating thumbnails, batch processing images, creating composite images, or implementing media processing pipelines. Supports 100+ formats, hardware acceleration (NVENC, QSV), and complex filtergraphs.

    Also in 5 projects that use this

  • loulanyueSkill

    setup-ts-deep-modules

    Wire dependency-cruiser into a TypeScript repo so each package is a deep module — implementation hidden in subfolders, reachable only through its entry-point files. User-invoked.

    Also in 15 projects that use this

  • mrgoonieSkill

    aesthetic

    Create aesthetically beautiful interfaces following proven design principles. Use when building UI/UX, analyzing designs from inspiration sites, generating design images with ai-multimodal, implementing visual hierarchy and color theory, adding micro-interactions, or creating design documentation. Includes workflows for capturing and analyzing inspiration screenshots with chrome-devtools and ai-multimodal, iterative design image generation until aesthetic standards are met, and comprehensive design system guidance covering BEAUTIFUL (aesthetic principles), RIGHT (functionality/accessibility), SATISFYING (micro-interactions), and PEAK (storytelling) stages. Integrates with chrome-devtools, ai-multimodal, media-processing, ui-styling, and web-frameworks skills.

    Also in 4 projects that use this

  • AWSSkill

    ask-matt

    Ask which skill or flow fits your situation. A router over the skills in this repo.

    Also in 32 projects that use this

  • AWSSkill

    resolving-merge-conflicts

    Use when you need to resolve an in-progress git merge/rebase conflict.

    Also in 48 projects that use this

  • +1 more from mrgoonie
  • +2 more from aws

The file

Show its rules and text

We split this skill into the rules it gives an agent

13 rules. 0 are common, 9 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 174 edited versions we read keep these.

  • 9

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill when reviewing or writing framework-level code: handler, parser, protocol, router, CLI runtime, FFI, or state management.

    line 8
  2. Distinctive:

    Every behavioral contract that spans more than one layer (parser → protocol → handler → client) must be identical in semantics.

    line 16
  3. Distinctive:

    Write a table: "Input X → Layer A produces Y₁, Layer B produces Y₂".

    line 33
  4. Distinctive:

    Ensure tests exist that exercise the same input through all layers.

    line 34
  5. Very specific:

    Search for tests that assert spec-violating behavior (e.g., test_array_index_not_resolved) - these are bugs masquerading as tests.

    line 36
  6. Very specific:

    Search for HashMap or HashSet usage where iteration order affects output.

    line 53
  7. Distinctive:

    Run the same input twice in different process instances - output must be identical.

    line 54
  8. Distinctive:

    Every unnecessary allocation is CPU time and GC pressure.

    line 98
  9. Distinctive:

    When the change touches dev-server, API proxy, request handling, or package discovery:

    line 256
  10. Very specific:

    When the change touches .proto files, serialization, or the binary protocol:

    line 276
  11. Very specific:

    When the change touches crates/webui-ffi or C ABI signatures:

    line 293
  12. Distinctive:

    Every behavioral change must include corresponding documentation updates.

    line 309
  13. Distinctive:

    When producing a code review, report findings as:

    line 326

“Common” is measured: kept by at least 6 in 10 of the 174 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Framework Code Review

Use this skill when reviewing or writing framework-level code: handler, parser, protocol, router, CLI runtime, FFI, or state management. The checklist is generic - apply every section to every PR that touches core logic.

Complements: perf (speed and memory optimization), quality-gate (automated checks), ffi (C ABI boundary safety).


1 - Cross-layer contract parity

Every behavioral contract that spans more than one layer (parser → protocol → handler → client) must be identical in semantics. Mismatches cause silent divergence between SSR and client rendering.

CheckWhy
Encoding / decoding policyIf one layer decodes (e.g., decodeURIComponent), all layers that consume the value must agree on whether the value is decoded or raw.
Matching semanticsOptional, splat, exact, and wildcard rules must produce the same result on server and client for the same input.
Tie-breaking determinismWhen multiple candidates match with equal rank, the selection rule must be documented and identical across layers.
Edge valuesEmpty strings, /, encoded slashes (%2F), Unicode, and values containing delimiters (., :, *) must be tested at every boundary.
Error representationWhen one layer returns an error, the other layers must handle or propagate it consistently - no silent swallowing.
Architecture-vs-code parityDESIGN.md must match system boundaries and invariants; exact cross-language contracts in specs/ and supported syntax in public docs must match the defining source and tests. Tests that lock in contradictory behavior are bugs, not proof of correctness.
Binding surface parityNode, WASM, and CLI bindings must expose the same logical API. If one uses protobuf bytes and another uses JSON strings, transparent fallback is impossible.
Type coercion consistencyIf == uses strict equality but > coerces strings to numbers, document the coercion matrix. Operators on the same pair of operands should not produce contradictory outcomes.
Literal grammar completenessIf the expression engine supports true, false, "strings", and numbers as literals, it must also support null. Missing literals create dead-end conditions (e.g., foo == null fails).
Fallback contract validityIf a function falls back to a CLI subprocess or alternative backend, the result shape must satisfy the same postconditions as the primary path. An empty buffer from a fallback is a contract violation.

How to check

  • Write a table: "Input X → Layer A produces Y₁, Layer B produces Y₂". If Y₁ ≠ Y₂, file a parity bug.
  • Ensure tests exist that exercise the same input through all layers.
  • Diff the function signatures between Node/WASM/TS bindings - arguments and return types must match logically.
  • Search for tests that assert spec-violating behavior (e.g., test_array_index_not_resolved) - these are bugs masquerading as tests.

2 - Determinism

Non-deterministic behavior is a correctness bug, even if it "usually works."

Anti-patternFix
Iterating HashMap / HashSet for order-dependent logic (ranking, tie-breaking, first-match)Use BTreeMap, IndexMap, or add an explicit ordering field.
Relying on allocation or hash seed order across process restartsUse deterministic comparison (insertion order, lexicographic, priority field).
Floating-point comparison for equalityUse integer arithmetic or epsilon-aware comparison.
rand / Uuid::new_v4 in deterministic pathsInject randomness explicitly; keep core logic pure.

How to check

  • Search for HashMap or HashSet usage where iteration order affects output.
  • Run the same input twice in different process instances - output must be identical.

3 - Concurrency and race safety

Rust (server / CLI)

CheckWhy
Lock scopeHold Mutex / RwLock only long enough to copy or read what you need. Never hold a lock across I/O, rendering, or network calls.
Snapshot consistencyIf a request reads multiple fields from shared state, read them all under one lock acquisition. Two separate locks can produce mixed old/new data if a writer updates between them.
std::sync::Mutex on async pathsBlocking mutexes on async paths can starve the executor. Prefer tokio::sync::RwLock or Arc<ArcSwap<T>> for read-heavy shared state.
AtomicsUse AtomicU64 for simple counters/versions instead of locking.
File watcher error recoveryIf a rebuild fails, the watcher must NOT update its "last seen" timestamps - otherwise it won't retry when the error is transient. Keep a retry/backoff path.
Cache concurrent writesTemp files used for atomic-replace must have unique names (PID + random suffix). Two writers using the same {key}.tmp will clobber each other.
Event-driven vs pollingPolling every N ms scales poorly. Prefer event-driven file notifications (notify crate) or at least directory-level mtime checks before deep scans.

Rust (FFI / WASM boundaries)

CheckWhy
catch_unwind on FFI exportsEvery extern "C" function must wrap its body in std::panic::catch_unwind(). Panics from transitive dependencies (serde, prost) crossing the FFI boundary are UB in unwind mode and abrupt termination in abort mode.
WASM panic hooksInstall console_error_panic_hook (or equivalent) so panics produce diagnosable errors instead of opaque host traps.
Callback error propagationIf a host callback (e.g., JS chunk writer) fails, stop processing immediately. Continuing to render after the sink has failed wastes CPU and can produce partial/corrupt output.

TypeScript (client)

CheckWhy
In-flight request cancellationRapid user actions (navigations, searches) can launch multiple async operations. Use AbortController + sequence IDs to discard stale results.
Event orderingDOM events and CustomEvent dispatches can interleave with async completions. Ensure state mutations are guarded by a generation counter or similar.
Feature detectionBrowser APIs (Navigation API, View Transitions) may not exist. Guard with typeof / 'navigation' in window before use.

Node.js bindings

CheckWhy
Event loop blockingSynchronous native calls that do parsing, rendering, or I/O block the Node.js event loop. Expose async variants via napi::Task/AsyncTask for any operation that takes > 1ms.

4 - Allocation and clone discipline

Every unnecessary allocation is CPU time and GC pressure. Apply these rules in hot paths (request handling, rendering, matching, serialization).

Rust

Anti-patternFix
format!() in loops or hot pathsUse write!(buf, ...) into a pre-allocated buffer, or push_str.
String::from(ch) for single charactersUse buf.push(ch) or write!(buf, "{ch}").
.clone() on a value used only for read accessPass &T or &str instead.
.clone() to insert into HashSet after a .contains() checkReorder: do the lookup / get first, then insert(owned_value) by move.
.to_string() on Cow<str>Write the Cow directly; .to_string() defeats zero-copy.
collect::<Vec<_>>() when sequential iteration sufficesIterate the iterator directly.
Vec<T> when max size is small and knownUse SmallVec<[T; N]> or a stack array to avoid heap allocation.
Deep-cloning large structures (protocol, state trees) per requestUse Arc<T> with clone-on-write or snapshot swapping.
Re-parsing static data on every requestCache the parsed form alongside the raw data.
to_vec() before join()Slice the original and join directly: segments[idx..].join("/").
Recompiling parser queries per callCache compiled queries in OnceLock<Query> or extract all attributes once into a struct per element.
chars[i..].iter().collect::<String>() for substring comparisonCompare without allocation: use byte-level starts_with or slice equality.
Zero-capacity String::new() for output buffersPre-allocate with String::with_capacity(estimated_size). For HTML output, 4096 is a reasonable starting point.
Cloning JSON Value subtrees on lookupAdd a borrowed lookup API (-> &Value) for the hot path; keep owned API as a thin wrapper.
Full-tree validation pre-pass on every evaluationValidate once at AST construction time and cache the result, not on every evaluation call.

TypeScript

Anti-patternFix
Array.filter().length for countingUse a for loop with a counter, or reduce.
Repeated DOM queries (querySelectorAll) on unchanged DOMCache the result; invalidate on mutation.
JSON.parse(JSON.stringify(x)) for deep copyUse structuredClone() or avoid the copy entirely.
Rebuilding derived data every call when inputs haven't changedMemoize or cache with invalidation.

5 - Data structure selection

Choose the structure that matches the access pattern. A wrong choice is a design bug.

Access patternPreferred structure
Order-dependent iteration (ranking, priority)BTreeMap, Vec sorted by key, IndexMap
Membership test onlyHashSet, bloom filter (but beware false positives - see below)
Frequent insert + lookup by keyHashMap (if order doesn't matter)
Small fixed-size collections (< 16 elements)Stack array, SmallVec, ArrayVec
Append-only logVec with push
Probabilistic membership (bloom filter)Use ≥ 2 independent hash functions. A single-hash bloom filter has unacceptable false-positive rates at moderate load. Document the false-positive bound.

How to check

  • For every HashMap in the diff: "Does any consumer iterate this and depend on order?" If yes, switch.
  • For every Vec: "Is the capacity known?" If yes, use with_capacity.
  • For every bloom filter: "What is the false-positive rate at expected load?" If > 1%, redesign.

6 - API surface and design deduplication

CheckWhy
No duplicate logic across layersIf server and client both implement matching, both must call equivalent code, not independent reimplementations. Any behavioral change must update both.
No duplicate calls in the same requestIf match_route() is called twice on the same path in one request flow, extract the result and pass it through.
Free functions vs. methodsIf standalone helper functions duplicate methods on a type (e.g., activateRoute(el) and el.activate()), remove one. Keep the method; delete the free function.
Caching static computationsParsing a template string into segments is pure. If the template set is static, parse once and cache.
Minimal public surfaceUse pub(crate) for internal helpers. Every public API is a maintenance commitment.
Error paths are actionableErrors must say what went wrong AND what the caller can do. "Parse error" is not actionable. "Invalid parameter name 'id-x' in path '/users/:id-x': only alphanumeric and underscore allowed" is.

7 - Type safety, correctness idioms, and architectural rules

Rust - banned patterns

PatternPreference
unwrap() / expect() in library codeBanned. Use ? with typed errors via thiserror.
unsafe without // SAFETY: commentBanned. Document the invariant upheld.
Recursion in core algorithmsBanned. Use iterative loops with an explicit stack. Recursion blows the call stack on deep/adversarial inputs and defeats branch prediction.
as any casts (in FFI or interop)Minimize. Use typed wrappers or trait objects.
Raw pointer arithmeticPrefer safe abstractions. Use unsafe only when necessary, with safety proof.

Rust - required annotations

PatternPreference
#[must_use]Add to all public constructors, serialization/deserialization methods, and functions returning Option/Result whose value should not be silently discarded.
#[allow(dead_code)]Remove the annotation AND the dead code. If the field/function is planned for future use, delete it now and re-add when needed (with a TODO referencing an issue).

Rust - error handling precision

PatternPreference
Silent fallbacks (unwrap_or(0), unwrap_or_default())Replace with explicit error propagation. A silent default can mask a real mismatch (e.g., unbalanced start/end markers). If a default is genuinely correct, add a comment explaining why.
Option<T> return for lookups that can fail in multiple waysUse Result<T, E> with a typed error enum distinguishing missing-key, invalid-path, type-mismatch, etc. Collapsing all failures to None makes debugging impossible.
Error variants that abuse a generic Validation(String)Add dedicated variants (Decode, Encode, MissingField) so callers can match programmatically.
Byte vs char index confusionWhen scanning strings with chars() but slicing with byte indices, panics occur on non-ASCII input. Always use char_indices() or work exclusively with byte offsets.

Rust - numeric precision

PatternPreference
Forcing all numbers through f64 for comparisonsPreserve exact integer comparisons (i64/u64) when both operands are integral. Only fall back to f64 for genuine floats. Large integers above 2^53 lose precision in f64.

Rust - build-time validation

PatternPreference
Deferring validation to render-timeValidate at parse/build time and fail fast. If a route references a component that doesn't exist, or a path is empty, catch it during parsing - not when a user hits the route.
Accepting invalid inputs that pass throughIf a <route> element is missing path or references an unknown component, the parser must reject it with an actionable error.
bytes[i] as char on UTF-8 stringsThis silently corrupts multi-byte characters. Use str slicing or char_indices() to preserve UTF-8 correctness.

Rust - diagnostics & error presentation

See skills/diagnostics/SKILL.md for the full workflow. On review, check:

PatternPreference
panic!/unwrap on recoverable (template/CLI/state) inputBanned. Return Result - panic = "abort" kills FFI/WASM/Node hosts. Authoring mistakes return ParserError::Template(Box<Diagnostic>).
Authoring error without a stable code, location, or help:A Diagnostic must carry a diagnostic::codes constant, --> owner:line:column, snippet, and an actionable help:. Codes are a stable API - flag renames.
Color/ANSI in a library, host, browser, or JSON channelColor belongs only in webui-cli (console::style()). Libraries emit plain data; FFI/WASM/Node/browser get plain Display. Split terminal-vs-machine renderings (e.g. RebuildError { display, message }) rather than leaking ANSI.
A single SGR span wrapping newlinesStyle each line independently - a span across \n bleeds when lines are re-prefixed ([server]).
Error construction inlined into a hot functionMark error builders #[cold]/#[inline(never)]; keep the hot fast-path inlinable. Layout perturbation from cold error code is a real regression - confirm with cargo bench vs the base branch.
serde_json::json! macro in CLI outputUse the serde_json::Map API; the macro unwraps internally and trips disallowed_methods.
Tests asserting on error proseAssert on the stable code (and that JSON output contains no \x1b), not the human message.

TypeScript

PatternPreference
(x as any)Use proper type narrowing, generics, or unknown with guards.
Untyped expando properties ((el as any)._data = ...)Use WeakMap<Element, T> or typed fields on a subclass.
varBanned. Use const by default, let only when reassignment is needed.
== nullUse === null || === undefined or optional chaining (?.).
Callback-based asyncUse async/await.
arguments objectUse rest parameters (...args).
Loose union types (state: object | string)Use precise types. If Rust accepts serde_json::Value, define a recursive JsonValue type on the TS side. If plugin accepts "fast" only, use a string literal union.

8 - Style, comments, and documentation

CheckRule
Dead codeRemove unused functions, imports, and variables. Don't comment them out.
Commented-out codeDelete it. Git has history.
Obvious commentsRemove comments that restate the code: // increment counter above counter += 1.
Missing commentsAdd comments for non-obvious decisions: "We use BTreeMap here for deterministic iteration order."
TODO / FIXME / HACKAcceptable only with an associated issue number: // TODO(#123): switch to streaming parser.
NamingRust: snake_case functions, PascalCase types, SCREAMING_SNAKE constants. TS: camelCase variables/functions, PascalCase classes/types.
Magic numbersExtract to named constants with a doc comment.
File lengthWhen a file exceeds ~400 lines, split by concern.
Function argumentsMax 5 parameters. Use a config/options struct beyond that.
Unused dependenciesRemove deps listed in Cargo.toml that are never imported. anyhow is for binary crates only - library crates use thiserror.
Placeholder / no-op APIsIf a public function always returns empty/default, either implement it or remove it behind a feature gate. Silent no-ops mislead callers.
Tests that lock in wrong behaviorA test named test_feature_not_supported that asserts None for spec-required behavior is a bug, not a test. Delete or fix it.

9 - Server runtime, proxy, and discovery correctness

When the change touches dev-server, API proxy, request handling, or package discovery:

CheckWhy
HTTP semanticsAccept header parsing must respect quality weights (q=). Substring matching (contains("application/json")) is incorrect per RFC 7231.
Status codesA "no match" must return 404, not 200 with empty body. Clients cannot distinguish "valid empty" from "not found" otherwise.
Proxy header forwardingForward a safe allowlist: Authorization, Cookie, Accept, Content-Type, X-Request-ID, etc. Don't forward Host or hop-by-hop headers.
Path handlingPaths with dots (e.g., /api/v2.1/users) are valid routes, not file requests. Don't use contains('.') as a file-vs-route heuristic.
Resource reuseHTTP clients, TLS contexts, and connection pools are expensive to create. Reuse them across requests.
HMR injectionSearch for closing tags case-insensitively. </BODY> and </body> are both valid HTML.
Input validationCLI commands must validate that input paths are directories (not files) before proceeding. Actionable error early beats cryptic failure later.
Cache invalidation scopeCache keys must include hashes/mtimes of ALL files that affect the cached result - not just package.json. If template HTML or CSS changes, the cache must invalidate.
Cache write safetyUse per-write unique temp file names (PID + random suffix) and atomic rename. Concurrent writers must not clobber each other's temp files.
Symlink policyPackage resolvers must allow workspace-linked packages (symlinks outside node_modules). Blocking all external symlinks breaks common monorepo patterns.
File-size guardrailsDiscovery that reads arbitrary files must cap read sizes. A 100MB HTML file shouldn't cause OOM during component scanning.

10 - Protocol and schema hygiene

When the change touches .proto files, serialization, or the binary protocol:

CheckWhy
Field additions are backward-compatibleNew fields must have defaults that preserve old behavior.
Removed fields use reservedPrevents accidental reuse of field numbers.
Enum variants are exhaustiveMatch arms must handle unknown variants (use a default/unknown variant or _ with a log).
No unnecessary nestingFlat structures decode faster than deeply nested ones.
Measure payload sizeBefore/after byte counts for representative inputs. Extra fields add decode overhead even when empty.
Prioritize decode speedBreaking field changes are allowed when they improve performance measurably. Remove unused fields and message shapes that add decode overhead.
Cascade all layersSchema changes affect the whole stack: protocol -> handler -> FFI -> CLI. Update all in the same change. Run cargo xtask build && cargo xtask test to validate.
Update architecture when neededA change to the protocol graph or producer/consumer boundary updates DESIGN.md; field-level details belong in .proto, consumers, and tests.

10b - FFI boundary safety

When the change touches crates/webui-ffi or C ABI signatures:

CheckWhy
# Safety doc on every extern "C" fnDocuments the invariants the caller must uphold.
// SAFETY: on every unsafe blockExplains why the unsafe operation is sound.
catch_unwind wraps all FFI bodiesPanics from transitive deps (serde, prost) crossing the boundary are UB in unwind mode. On panic, set last-error and return null.
Validate all foreign inputsNull pointers, invalid UTF-8, out-of-range values - check before dereferencing.
No unwrap() or expect()Anywhere in the FFI code path, including error-handling helpers.
Minimal stable surfacePrefer opaque pointers and integer error codes over exposing Rust layouts.
Header syncIf any #[no_mangle] signature changes, verify crates/webui-ffi/include/webui_ffi.h.

11 - Documentation sync

Every behavioral change must include corresponding documentation updates. Missing docs are a review finding.

CheckWhy
DESIGN.md updated when architecture changesChanges to responsibilities, data flow, or cross-layer invariants must update the living architecture; individual APIs, fields, error variants, and marker formats do not belong there.
User-facing docs updatedIf the change affects CLI flags, template syntax, component authoring, routing, or integration behavior, docs/ must be updated.
AI reference updatedIf the change affects anything a code-generation AI would need to know, docs/ai.md must be updated.
README links to docs portalPackage READMEs should defer to the docs portal, not duplicate content.
No stale examplesCode examples in docs must use current API signatures, flag names, and marker formats.
docs build passescd docs && pnpm build must succeed (catches broken links, unescaped {{, missing pages).

See docs-sync skill for the full file mapping of what-changed to which-docs-to-update.


Review output format

When producing a code review, report findings as:

### ISSUE-NNN: <short title>

**Severity**: 🔴 Bug | 🟠 Security | 🟡 Performance | 🔵 Design/Style
**Files**: `path/to/file.rs` (lines N-M)
**Description**: What is wrong, with a code snippet showing the problem.
**Impact**: What breaks or degrades, and under what conditions.
**Fix**: Concrete suggestion, with a code snippet when helpful.

Each finding must be self-contained - readable without context from other findings. This allows direct conversion to GitHub issues.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.