[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M69APJNTXJDYJQYAQWHJTW0K":3,"skill-same:01M69APJNTXJDYJQYAQWHJTW0K":73},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":31,"publishedAt":44,"linkOnly":45,"markdownContent":46,"markdownBody":47,"frontMatter":48,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":54,"ownerHtmlUrl":55,"ownerBlogUrl":56,"ownerDescription":57,"updatedAt":58,"install":59,"resources":72},"01M69APJNTXJDYJQYAQWHJTW0K","code-review",null,"Framework code review checklist - correctness, performance, concurrency, design, and style.","microsoft\u002Fwebui","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M69APCAY31B400ERZA9BVA20",102,"MIT","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fcode-review\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000007","代码审查","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41,42,43],"code review","review","code","design","performance","review checklist","framework","code review checklist","concurrency","checklist","style","correctness","2026-11-10 10:12:30",false,"---\r\nname: code-review\r\ndescription: Framework code review checklist - correctness, performance, concurrency, design, and style.\r\n---\r\n\r\n# Framework Code Review\r\n\r\nUse 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.\r\n\r\n> **Complements**: `perf` (speed and memory optimization), `quality-gate` (automated checks), `ffi` (C ABI boundary safety).\r\n\r\n---\r\n\r\n## 1 - Cross-layer contract parity\r\n\r\nEvery 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.\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Encoding \u002F decoding policy** | If one layer decodes (e.g., `decodeURIComponent`), all layers that consume the value must agree on whether the value is decoded or raw. |\r\n| **Matching semantics** | Optional, splat, exact, and wildcard rules must produce the same result on server and client for the same input. |\r\n| **Tie-breaking determinism** | When multiple candidates match with equal rank, the selection rule must be documented and identical across layers. |\r\n| **Edge values** | Empty strings, `\u002F`, encoded slashes (`%2F`), Unicode, and values containing delimiters (`.`, `:`, `*`) must be tested at every boundary. |\r\n| **Error representation** | When one layer returns an error, the other layers must handle or propagate it consistently - no silent swallowing. |\r\n| **Architecture-vs-code parity** | `DESIGN.md` must match system boundaries and invariants; exact cross-language contracts in `specs\u002F` 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. |\r\n| **Binding surface parity** | Node, WASM, and CLI bindings must expose the same logical API. If one uses protobuf bytes and another uses JSON strings, transparent fallback is impossible. |\r\n| **Type coercion consistency** | If `==` uses strict equality but `>` coerces strings to numbers, document the coercion matrix. Operators on the same pair of operands should not produce contradictory outcomes. |\r\n| **Literal grammar completeness** | If 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). |\r\n| **Fallback contract validity** | If 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. |\r\n\r\n### How to check\r\n\r\n- Write a table: \"Input X → Layer A produces Y₁, Layer B produces Y₂\". If Y₁ ≠ Y₂, file a parity bug.\r\n- Ensure tests exist that exercise the same input through all layers.\r\n- Diff the function signatures between Node\u002FWASM\u002FTS bindings - arguments and return types must match logically.\r\n- Search for tests that assert spec-violating behavior (e.g., `test_array_index_not_resolved`) - these are bugs masquerading as tests.\r\n\r\n---\r\n\r\n## 2 - Determinism\r\n\r\nNon-deterministic behavior is a correctness bug, even if it \"usually works.\"\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| Iterating `HashMap` \u002F `HashSet` for order-dependent logic (ranking, tie-breaking, first-match) | Use `BTreeMap`, `IndexMap`, or add an explicit ordering field. |\r\n| Relying on allocation or hash seed order across process restarts | Use deterministic comparison (insertion order, lexicographic, priority field). |\r\n| Floating-point comparison for equality | Use integer arithmetic or epsilon-aware comparison. |\r\n| `rand` \u002F `Uuid::new_v4` in deterministic paths | Inject randomness explicitly; keep core logic pure. |\r\n\r\n### How to check\r\n\r\n- Search for `HashMap` or `HashSet` usage where iteration order affects output.\r\n- Run the same input twice in different process instances - output must be identical.\r\n\r\n---\r\n\r\n## 3 - Concurrency and race safety\r\n\r\n### Rust (server \u002F CLI)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Lock scope** | Hold `Mutex` \u002F `RwLock` only long enough to copy or read what you need. Never hold a lock across I\u002FO, rendering, or network calls. |\r\n| **Snapshot consistency** | If a request reads multiple fields from shared state, read them all under **one** lock acquisition. Two separate locks can produce mixed old\u002Fnew data if a writer updates between them. |\r\n| **`std::sync::Mutex` on async paths** | Blocking mutexes on async paths can starve the executor. Prefer `tokio::sync::RwLock` or `Arc\u003CArcSwap\u003CT>>` for read-heavy shared state. |\r\n| **Atomics** | Use `AtomicU64` for simple counters\u002Fversions instead of locking. |\r\n| **File watcher error recovery** | If 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\u002Fbackoff path. |\r\n| **Cache concurrent writes** | Temp files used for atomic-replace must have unique names (PID + random suffix). Two writers using the same `{key}.tmp` will clobber each other. |\r\n| **Event-driven vs polling** | Polling every N ms scales poorly. Prefer event-driven file notifications (`notify` crate) or at least directory-level mtime checks before deep scans. |\r\n\r\n### Rust (FFI \u002F WASM boundaries)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **`catch_unwind` on FFI exports** | Every `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. |\r\n| **WASM panic hooks** | Install `console_error_panic_hook` (or equivalent) so panics produce diagnosable errors instead of opaque host traps. |\r\n| **Callback error propagation** | If 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\u002Fcorrupt output. |\r\n\r\n### TypeScript (client)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **In-flight request cancellation** | Rapid user actions (navigations, searches) can launch multiple async operations. Use `AbortController` + sequence IDs to discard stale results. |\r\n| **Event ordering** | DOM events and `CustomEvent` dispatches can interleave with async completions. Ensure state mutations are guarded by a generation counter or similar. |\r\n| **Feature detection** | Browser APIs (`Navigation API`, `View Transitions`) may not exist. Guard with `typeof` \u002F `'navigation' in window` before use. |\r\n\r\n### Node.js bindings\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Event loop blocking** | Synchronous native calls that do parsing, rendering, or I\u002FO block the Node.js event loop. Expose async variants via `napi::Task`\u002F`AsyncTask` for any operation that takes > 1ms. |\r\n\r\n---\r\n\r\n## 4 - Allocation and clone discipline\r\n\r\nEvery unnecessary allocation is CPU time and GC pressure. Apply these rules in hot paths (request handling, rendering, matching, serialization).\r\n\r\n### Rust\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| `format!()` in loops or hot paths | Use `write!(buf, ...)` into a pre-allocated buffer, or `push_str`. |\r\n| `String::from(ch)` for single characters | Use `buf.push(ch)` or `write!(buf, \"{ch}\")`. |\r\n| `.clone()` on a value used only for read access | Pass `&T` or `&str` instead. |\r\n| `.clone()` to insert into `HashSet` after a `.contains()` check | Reorder: do the lookup \u002F get first, then `insert(owned_value)` by move. |\r\n| `.to_string()` on `Cow\u003Cstr>` | Write the `Cow` directly; `.to_string()` defeats zero-copy. |\r\n| `collect::\u003CVec\u003C_>>()` when sequential iteration suffices | Iterate the iterator directly. |\r\n| `Vec\u003CT>` when max size is small and known | Use `SmallVec\u003C[T; N]>` or a stack array to avoid heap allocation. |\r\n| Deep-cloning large structures (protocol, state trees) per request | Use `Arc\u003CT>` with clone-on-write or snapshot swapping. |\r\n| Re-parsing static data on every request | Cache the parsed form alongside the raw data. |\r\n| `to_vec()` before `join()` | Slice the original and join directly: `segments[idx..].join(\"\u002F\")`. |\r\n| Recompiling parser queries per call | Cache compiled queries in `OnceLock\u003CQuery>` or extract all attributes once into a struct per element. |\r\n| `chars[i..].iter().collect::\u003CString>()` for substring comparison | Compare without allocation: use byte-level `starts_with` or slice equality. |\r\n| Zero-capacity `String::new()` for output buffers | Pre-allocate with `String::with_capacity(estimated_size)`. For HTML output, 4096 is a reasonable starting point. |\r\n| Cloning JSON `Value` subtrees on lookup | Add a borrowed lookup API (`-> &Value`) for the hot path; keep owned API as a thin wrapper. |\r\n| Full-tree validation pre-pass on every evaluation | Validate once at AST construction time and cache the result, not on every evaluation call. |\r\n\r\n### TypeScript\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| `Array.filter().length` for counting | Use a `for` loop with a counter, or `reduce`. |\r\n| Repeated DOM queries (`querySelectorAll`) on unchanged DOM | Cache the result; invalidate on mutation. |\r\n| `JSON.parse(JSON.stringify(x))` for deep copy | Use `structuredClone()` or avoid the copy entirely. |\r\n| Rebuilding derived data every call when inputs haven't changed | Memoize or cache with invalidation. |\r\n\r\n---\r\n\r\n## 5 - Data structure selection\r\n\r\nChoose the structure that matches the access pattern. A wrong choice is a design bug.\r\n\r\n| Access pattern | Preferred structure |\r\n|---------------|-------------------|\r\n| Order-dependent iteration (ranking, priority) | `BTreeMap`, `Vec` sorted by key, `IndexMap` |\r\n| Membership test only | `HashSet`, bloom filter (but beware false positives - see below) |\r\n| Frequent insert + lookup by key | `HashMap` (if order doesn't matter) |\r\n| Small fixed-size collections (\u003C 16 elements) | Stack array, `SmallVec`, `ArrayVec` |\r\n| Append-only log | `Vec` with `push` |\r\n| 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. |\r\n\r\n### How to check\r\n\r\n- For every `HashMap` in the diff: \"Does any consumer iterate this and depend on order?\" If yes, switch.\r\n- For every `Vec`: \"Is the capacity known?\" If yes, use `with_capacity`.\r\n- For every bloom filter: \"What is the false-positive rate at expected load?\" If > 1%, redesign.\r\n\r\n---\r\n\r\n## 6 - API surface and design deduplication\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **No duplicate logic across layers** | If server and client both implement matching, both must call equivalent code, not independent reimplementations. Any behavioral change must update both. |\r\n| **No duplicate calls in the same request** | If `match_route()` is called twice on the same path in one request flow, extract the result and pass it through. |\r\n| **Free functions vs. methods** | If standalone helper functions duplicate methods on a type (e.g., `activateRoute(el)` and `el.activate()`), remove one. Keep the method; delete the free function. |\r\n| **Caching static computations** | Parsing a template string into segments is pure. If the template set is static, parse once and cache. |\r\n| **Minimal public surface** | Use `pub(crate)` for internal helpers. Every public API is a maintenance commitment. |\r\n| **Error paths are actionable** | Errors must say what went wrong AND what the caller can do. \"Parse error\" is not actionable. \"Invalid parameter name 'id-x' in path '\u002Fusers\u002F:id-x': only alphanumeric and underscore allowed\" is. |\r\n\r\n---\r\n\r\n## 7 - Type safety, correctness idioms, and architectural rules\r\n\r\n### Rust - banned patterns\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `unwrap()` \u002F `expect()` in library code | **Banned.** Use `?` with typed errors via `thiserror`. |\r\n| `unsafe` without `\u002F\u002F SAFETY:` comment | **Banned.** Document the invariant upheld. |\r\n| Recursion in core algorithms | **Banned.** Use iterative loops with an explicit stack. Recursion blows the call stack on deep\u002Fadversarial inputs and defeats branch prediction. |\r\n| `as any` casts (in FFI or interop) | Minimize. Use typed wrappers or trait objects. |\r\n| Raw pointer arithmetic | Prefer safe abstractions. Use `unsafe` only when necessary, with safety proof. |\r\n\r\n### Rust - required annotations\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `#[must_use]` | Add to all public constructors, serialization\u002Fdeserialization methods, and functions returning `Option`\u002F`Result` whose value should not be silently discarded. |\r\n| `#[allow(dead_code)]` | Remove the annotation AND the dead code. If the field\u002Ffunction is planned for future use, delete it now and re-add when needed (with a TODO referencing an issue). |\r\n\r\n### Rust - error handling precision\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| 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\u002Fend markers). If a default is genuinely correct, add a comment explaining why. |\r\n| `Option\u003CT>` return for lookups that can fail in multiple ways | Use `Result\u003CT, E>` with a typed error enum distinguishing missing-key, invalid-path, type-mismatch, etc. Collapsing all failures to `None` makes debugging impossible. |\r\n| Error variants that abuse a generic `Validation(String)` | Add dedicated variants (`Decode`, `Encode`, `MissingField`) so callers can match programmatically. |\r\n| Byte vs char index confusion | When 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. |\r\n\r\n### Rust - numeric precision\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| Forcing all numbers through `f64` for comparisons | Preserve exact integer comparisons (`i64`\u002F`u64`) when both operands are integral. Only fall back to `f64` for genuine floats. Large integers above 2^53 lose precision in `f64`. |\r\n\r\n### Rust - build-time validation\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| Deferring validation to render-time | Validate at parse\u002Fbuild 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. |\r\n| Accepting invalid inputs that pass through | If a `\u003Croute>` element is missing `path` or references an unknown component, the parser must reject it with an actionable error. |\r\n| `bytes[i] as char` on UTF-8 strings | This silently corrupts multi-byte characters. Use `str` slicing or `char_indices()` to preserve UTF-8 correctness. |\r\n\r\n### Rust - diagnostics & error presentation\r\n\r\nSee `skills\u002Fdiagnostics\u002FSKILL.md` for the full workflow. On review, check:\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `panic!`\u002F`unwrap` on recoverable (template\u002FCLI\u002Fstate) input | **Banned.** Return `Result` - `panic = \"abort\"` kills FFI\u002FWASM\u002FNode hosts. Authoring mistakes return `ParserError::Template(Box\u003CDiagnostic>)`. |\r\n| 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. |\r\n| Color\u002FANSI in a library, host, browser, or JSON channel | Color belongs **only** in `webui-cli` (`console::style()`). Libraries emit plain data; FFI\u002FWASM\u002FNode\u002Fbrowser get plain `Display`. Split terminal-vs-machine renderings (e.g. `RebuildError { display, message }`) rather than leaking ANSI. |\r\n| A single SGR span wrapping newlines | Style each line independently - a span across `\\n` bleeds when lines are re-prefixed (`[server]`). |\r\n| Error construction inlined into a hot function | Mark error builders `#[cold]`\u002F`#[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. |\r\n| `serde_json::json!` macro in CLI output | Use the `serde_json::Map` API; the macro `unwrap`s internally and trips `disallowed_methods`. |\r\n| Tests asserting on error prose | Assert on the stable `code` (and that JSON output contains no `\\x1b`), not the human message. |\r\n\r\n### TypeScript\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `(x as any)` | Use proper type narrowing, generics, or `unknown` with guards. |\r\n| Untyped expando properties (`(el as any)._data = ...`) | Use `WeakMap\u003CElement, T>` or typed fields on a subclass. |\r\n| `var` | **Banned.** Use `const` by default, `let` only when reassignment is needed. |\r\n| `== null` | Use `=== null \\|\\| === undefined` or optional chaining (`?.`). |\r\n| Callback-based async | Use `async\u002Fawait`. |\r\n| `arguments` object | Use rest parameters (`...args`). |\r\n| 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. |\r\n\r\n---\r\n\r\n## 8 - Style, comments, and documentation\r\n\r\n| Check | Rule |\r\n|-------|------|\r\n| **Dead code** | Remove unused functions, imports, and variables. Don't comment them out. |\r\n| **Commented-out code** | Delete it. Git has history. |\r\n| **Obvious comments** | Remove comments that restate the code: `\u002F\u002F increment counter` above `counter += 1`. |\r\n| **Missing comments** | Add comments for non-obvious decisions: \"We use BTreeMap here for deterministic iteration order.\" |\r\n| **`TODO` \u002F `FIXME` \u002F `HACK`** | Acceptable only with an associated issue number: `\u002F\u002F TODO(#123): switch to streaming parser`. |\r\n| **Naming** | Rust: `snake_case` functions, `PascalCase` types, `SCREAMING_SNAKE` constants. TS: `camelCase` variables\u002Ffunctions, `PascalCase` classes\u002Ftypes. |\r\n| **Magic numbers** | Extract to named constants with a doc comment. |\r\n| **File length** | When a file exceeds ~400 lines, split by concern. |\r\n| **Function arguments** | Max 5 parameters. Use a config\u002Foptions struct beyond that. |\r\n| **Unused dependencies** | Remove deps listed in `Cargo.toml` that are never imported. `anyhow` is for binary crates only - library crates use `thiserror`. |\r\n| **Placeholder \u002F no-op APIs** | If a public function always returns empty\u002Fdefault, either implement it or remove it behind a feature gate. Silent no-ops mislead callers. |\r\n| **Tests that lock in wrong behavior** | A test named `test_feature_not_supported` that asserts `None` for spec-required behavior is a bug, not a test. Delete or fix it. |\r\n\r\n---\r\n\r\n## 9 - Server runtime, proxy, and discovery correctness\r\n\r\nWhen the change touches dev-server, API proxy, request handling, or package discovery:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **HTTP semantics** | `Accept` header parsing must respect quality weights (`q=`). Substring matching (`contains(\"application\u002Fjson\")`) is incorrect per RFC 7231. |\r\n| **Status codes** | A \"no match\" must return 404, not 200 with empty body. Clients cannot distinguish \"valid empty\" from \"not found\" otherwise. |\r\n| **Proxy header forwarding** | Forward a safe allowlist: `Authorization`, `Cookie`, `Accept`, `Content-Type`, `X-Request-ID`, etc. Don't forward `Host` or hop-by-hop headers. |\r\n| **Path handling** | Paths with dots (e.g., `\u002Fapi\u002Fv2.1\u002Fusers`) are valid routes, not file requests. Don't use `contains('.')` as a file-vs-route heuristic. |\r\n| **Resource reuse** | HTTP clients, TLS contexts, and connection pools are expensive to create. Reuse them across requests. |\r\n| **HMR injection** | Search for closing tags case-insensitively. `\u003C\u002FBODY>` and `\u003C\u002Fbody>` are both valid HTML. |\r\n| **Input validation** | CLI commands must validate that input paths are directories (not files) before proceeding. Actionable error early beats cryptic failure later. |\r\n| **Cache invalidation scope** | Cache keys must include hashes\u002Fmtimes of ALL files that affect the cached result - not just `package.json`. If template HTML or CSS changes, the cache must invalidate. |\r\n| **Cache write safety** | Use per-write unique temp file names (PID + random suffix) and atomic rename. Concurrent writers must not clobber each other's temp files. |\r\n| **Symlink policy** | Package resolvers must allow workspace-linked packages (symlinks outside `node_modules`). Blocking all external symlinks breaks common monorepo patterns. |\r\n| **File-size guardrails** | Discovery that reads arbitrary files must cap read sizes. A 100MB HTML file shouldn't cause OOM during component scanning. |\r\n\r\n---\r\n\r\n## 10 - Protocol and schema hygiene\r\n\r\nWhen the change touches `.proto` files, serialization, or the binary protocol:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Field additions are backward-compatible** | New fields must have defaults that preserve old behavior. |\r\n| **Removed fields use `reserved`** | Prevents accidental reuse of field numbers. |\r\n| **Enum variants are exhaustive** | Match arms must handle unknown variants (use a default\u002Funknown variant or `_` with a log). |\r\n| **No unnecessary nesting** | Flat structures decode faster than deeply nested ones. |\r\n| **Measure payload size** | Before\u002Fafter byte counts for representative inputs. Extra fields add decode overhead even when empty. |\r\n| **Prioritize decode speed** | Breaking field changes are allowed when they improve performance measurably. Remove unused fields and message shapes that add decode overhead. |\r\n| **Cascade all layers** | Schema changes affect the whole stack: protocol -> handler -> FFI -> CLI. Update all in the same change. Run `cargo xtask build && cargo xtask test` to validate. |\r\n| **Update architecture when needed** | A change to the protocol graph or producer\u002Fconsumer boundary updates `DESIGN.md`; field-level details belong in `.proto`, consumers, and tests. |\r\n\r\n---\r\n\r\n## 10b - FFI boundary safety\r\n\r\nWhen the change touches `crates\u002Fwebui-ffi` or C ABI signatures:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **`# Safety` doc on every `extern \"C\" fn`** | Documents the invariants the caller must uphold. |\r\n| **`\u002F\u002F SAFETY:` on every `unsafe` block** | Explains why the unsafe operation is sound. |\r\n| **`catch_unwind` wraps all FFI bodies** | Panics from transitive deps (serde, prost) crossing the boundary are UB in unwind mode. On panic, set last-error and return null. |\r\n| **Validate all foreign inputs** | Null pointers, invalid UTF-8, out-of-range values - check before dereferencing. |\r\n| **No `unwrap()` or `expect()`** | Anywhere in the FFI code path, including error-handling helpers. |\r\n| **Minimal stable surface** | Prefer opaque pointers and integer error codes over exposing Rust layouts. |\r\n| **Header sync** | If any `#[no_mangle]` signature changes, verify `crates\u002Fwebui-ffi\u002Finclude\u002Fwebui_ffi.h`. |\r\n\r\n---\r\n\r\n## 11 - Documentation sync\r\n\r\nEvery behavioral change must include corresponding documentation updates. Missing docs are a review finding.\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **DESIGN.md updated when architecture changes** | Changes 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. |\r\n| **User-facing docs updated** | If the change affects CLI flags, template syntax, component authoring, routing, or integration behavior, `docs\u002F` must be updated. |\r\n| **AI reference updated** | If the change affects anything a code-generation AI would need to know, `docs\u002Fai.md` must be updated. |\r\n| **README links to docs portal** | Package READMEs should defer to the docs portal, not duplicate content. |\r\n| **No stale examples** | Code examples in docs must use current API signatures, flag names, and marker formats. |\r\n| **docs build passes** | `cd docs && pnpm build` must succeed (catches broken links, unescaped `{{`, missing pages). |\r\n\r\nSee `docs-sync` skill for the full file mapping of what-changed to which-docs-to-update.\r\n\r\n---\r\n\r\n## Review output format\r\n\r\nWhen producing a code review, report findings as:\r\n\r\n```\r\n### ISSUE-NNN: \u003Cshort title>\r\n\r\n**Severity**: ? Bug | ? Security | ? Performance | ? Design\u002FStyle\r\n**Files**: `path\u002Fto\u002Ffile.rs` (lines N-M)\r\n**Description**: What is wrong, with a code snippet showing the problem.\r\n**Impact**: What breaks or degrades, and under what conditions.\r\n**Fix**: Concrete suggestion, with a code snippet when helpful.\r\n```\r\n\r\nEach finding must be **self-contained** - readable without context from other findings. This allows direct conversion to GitHub issues.\r\n","# Framework Code Review\r\n\r\nUse 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.\r\n\r\n> **Complements**: `perf` (speed and memory optimization), `quality-gate` (automated checks), `ffi` (C ABI boundary safety).\r\n\r\n---\r\n\r\n## 1 - Cross-layer contract parity\r\n\r\nEvery 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.\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Encoding \u002F decoding policy** | If one layer decodes (e.g., `decodeURIComponent`), all layers that consume the value must agree on whether the value is decoded or raw. |\r\n| **Matching semantics** | Optional, splat, exact, and wildcard rules must produce the same result on server and client for the same input. |\r\n| **Tie-breaking determinism** | When multiple candidates match with equal rank, the selection rule must be documented and identical across layers. |\r\n| **Edge values** | Empty strings, `\u002F`, encoded slashes (`%2F`), Unicode, and values containing delimiters (`.`, `:`, `*`) must be tested at every boundary. |\r\n| **Error representation** | When one layer returns an error, the other layers must handle or propagate it consistently - no silent swallowing. |\r\n| **Architecture-vs-code parity** | `DESIGN.md` must match system boundaries and invariants; exact cross-language contracts in `specs\u002F` 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. |\r\n| **Binding surface parity** | Node, WASM, and CLI bindings must expose the same logical API. If one uses protobuf bytes and another uses JSON strings, transparent fallback is impossible. |\r\n| **Type coercion consistency** | If `==` uses strict equality but `>` coerces strings to numbers, document the coercion matrix. Operators on the same pair of operands should not produce contradictory outcomes. |\r\n| **Literal grammar completeness** | If 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). |\r\n| **Fallback contract validity** | If 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. |\r\n\r\n### How to check\r\n\r\n- Write a table: \"Input X → Layer A produces Y₁, Layer B produces Y₂\". If Y₁ ≠ Y₂, file a parity bug.\r\n- Ensure tests exist that exercise the same input through all layers.\r\n- Diff the function signatures between Node\u002FWASM\u002FTS bindings - arguments and return types must match logically.\r\n- Search for tests that assert spec-violating behavior (e.g., `test_array_index_not_resolved`) - these are bugs masquerading as tests.\r\n\r\n---\r\n\r\n## 2 - Determinism\r\n\r\nNon-deterministic behavior is a correctness bug, even if it \"usually works.\"\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| Iterating `HashMap` \u002F `HashSet` for order-dependent logic (ranking, tie-breaking, first-match) | Use `BTreeMap`, `IndexMap`, or add an explicit ordering field. |\r\n| Relying on allocation or hash seed order across process restarts | Use deterministic comparison (insertion order, lexicographic, priority field). |\r\n| Floating-point comparison for equality | Use integer arithmetic or epsilon-aware comparison. |\r\n| `rand` \u002F `Uuid::new_v4` in deterministic paths | Inject randomness explicitly; keep core logic pure. |\r\n\r\n### How to check\r\n\r\n- Search for `HashMap` or `HashSet` usage where iteration order affects output.\r\n- Run the same input twice in different process instances - output must be identical.\r\n\r\n---\r\n\r\n## 3 - Concurrency and race safety\r\n\r\n### Rust (server \u002F CLI)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Lock scope** | Hold `Mutex` \u002F `RwLock` only long enough to copy or read what you need. Never hold a lock across I\u002FO, rendering, or network calls. |\r\n| **Snapshot consistency** | If a request reads multiple fields from shared state, read them all under **one** lock acquisition. Two separate locks can produce mixed old\u002Fnew data if a writer updates between them. |\r\n| **`std::sync::Mutex` on async paths** | Blocking mutexes on async paths can starve the executor. Prefer `tokio::sync::RwLock` or `Arc\u003CArcSwap\u003CT>>` for read-heavy shared state. |\r\n| **Atomics** | Use `AtomicU64` for simple counters\u002Fversions instead of locking. |\r\n| **File watcher error recovery** | If 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\u002Fbackoff path. |\r\n| **Cache concurrent writes** | Temp files used for atomic-replace must have unique names (PID + random suffix). Two writers using the same `{key}.tmp` will clobber each other. |\r\n| **Event-driven vs polling** | Polling every N ms scales poorly. Prefer event-driven file notifications (`notify` crate) or at least directory-level mtime checks before deep scans. |\r\n\r\n### Rust (FFI \u002F WASM boundaries)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **`catch_unwind` on FFI exports** | Every `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. |\r\n| **WASM panic hooks** | Install `console_error_panic_hook` (or equivalent) so panics produce diagnosable errors instead of opaque host traps. |\r\n| **Callback error propagation** | If 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\u002Fcorrupt output. |\r\n\r\n### TypeScript (client)\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **In-flight request cancellation** | Rapid user actions (navigations, searches) can launch multiple async operations. Use `AbortController` + sequence IDs to discard stale results. |\r\n| **Event ordering** | DOM events and `CustomEvent` dispatches can interleave with async completions. Ensure state mutations are guarded by a generation counter or similar. |\r\n| **Feature detection** | Browser APIs (`Navigation API`, `View Transitions`) may not exist. Guard with `typeof` \u002F `'navigation' in window` before use. |\r\n\r\n### Node.js bindings\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Event loop blocking** | Synchronous native calls that do parsing, rendering, or I\u002FO block the Node.js event loop. Expose async variants via `napi::Task`\u002F`AsyncTask` for any operation that takes > 1ms. |\r\n\r\n---\r\n\r\n## 4 - Allocation and clone discipline\r\n\r\nEvery unnecessary allocation is CPU time and GC pressure. Apply these rules in hot paths (request handling, rendering, matching, serialization).\r\n\r\n### Rust\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| `format!()` in loops or hot paths | Use `write!(buf, ...)` into a pre-allocated buffer, or `push_str`. |\r\n| `String::from(ch)` for single characters | Use `buf.push(ch)` or `write!(buf, \"{ch}\")`. |\r\n| `.clone()` on a value used only for read access | Pass `&T` or `&str` instead. |\r\n| `.clone()` to insert into `HashSet` after a `.contains()` check | Reorder: do the lookup \u002F get first, then `insert(owned_value)` by move. |\r\n| `.to_string()` on `Cow\u003Cstr>` | Write the `Cow` directly; `.to_string()` defeats zero-copy. |\r\n| `collect::\u003CVec\u003C_>>()` when sequential iteration suffices | Iterate the iterator directly. |\r\n| `Vec\u003CT>` when max size is small and known | Use `SmallVec\u003C[T; N]>` or a stack array to avoid heap allocation. |\r\n| Deep-cloning large structures (protocol, state trees) per request | Use `Arc\u003CT>` with clone-on-write or snapshot swapping. |\r\n| Re-parsing static data on every request | Cache the parsed form alongside the raw data. |\r\n| `to_vec()` before `join()` | Slice the original and join directly: `segments[idx..].join(\"\u002F\")`. |\r\n| Recompiling parser queries per call | Cache compiled queries in `OnceLock\u003CQuery>` or extract all attributes once into a struct per element. |\r\n| `chars[i..].iter().collect::\u003CString>()` for substring comparison | Compare without allocation: use byte-level `starts_with` or slice equality. |\r\n| Zero-capacity `String::new()` for output buffers | Pre-allocate with `String::with_capacity(estimated_size)`. For HTML output, 4096 is a reasonable starting point. |\r\n| Cloning JSON `Value` subtrees on lookup | Add a borrowed lookup API (`-> &Value`) for the hot path; keep owned API as a thin wrapper. |\r\n| Full-tree validation pre-pass on every evaluation | Validate once at AST construction time and cache the result, not on every evaluation call. |\r\n\r\n### TypeScript\r\n\r\n| Anti-pattern | Fix |\r\n|-------------|-----|\r\n| `Array.filter().length` for counting | Use a `for` loop with a counter, or `reduce`. |\r\n| Repeated DOM queries (`querySelectorAll`) on unchanged DOM | Cache the result; invalidate on mutation. |\r\n| `JSON.parse(JSON.stringify(x))` for deep copy | Use `structuredClone()` or avoid the copy entirely. |\r\n| Rebuilding derived data every call when inputs haven't changed | Memoize or cache with invalidation. |\r\n\r\n---\r\n\r\n## 5 - Data structure selection\r\n\r\nChoose the structure that matches the access pattern. A wrong choice is a design bug.\r\n\r\n| Access pattern | Preferred structure |\r\n|---------------|-------------------|\r\n| Order-dependent iteration (ranking, priority) | `BTreeMap`, `Vec` sorted by key, `IndexMap` |\r\n| Membership test only | `HashSet`, bloom filter (but beware false positives - see below) |\r\n| Frequent insert + lookup by key | `HashMap` (if order doesn't matter) |\r\n| Small fixed-size collections (\u003C 16 elements) | Stack array, `SmallVec`, `ArrayVec` |\r\n| Append-only log | `Vec` with `push` |\r\n| 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. |\r\n\r\n### How to check\r\n\r\n- For every `HashMap` in the diff: \"Does any consumer iterate this and depend on order?\" If yes, switch.\r\n- For every `Vec`: \"Is the capacity known?\" If yes, use `with_capacity`.\r\n- For every bloom filter: \"What is the false-positive rate at expected load?\" If > 1%, redesign.\r\n\r\n---\r\n\r\n## 6 - API surface and design deduplication\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **No duplicate logic across layers** | If server and client both implement matching, both must call equivalent code, not independent reimplementations. Any behavioral change must update both. |\r\n| **No duplicate calls in the same request** | If `match_route()` is called twice on the same path in one request flow, extract the result and pass it through. |\r\n| **Free functions vs. methods** | If standalone helper functions duplicate methods on a type (e.g., `activateRoute(el)` and `el.activate()`), remove one. Keep the method; delete the free function. |\r\n| **Caching static computations** | Parsing a template string into segments is pure. If the template set is static, parse once and cache. |\r\n| **Minimal public surface** | Use `pub(crate)` for internal helpers. Every public API is a maintenance commitment. |\r\n| **Error paths are actionable** | Errors must say what went wrong AND what the caller can do. \"Parse error\" is not actionable. \"Invalid parameter name 'id-x' in path '\u002Fusers\u002F:id-x': only alphanumeric and underscore allowed\" is. |\r\n\r\n---\r\n\r\n## 7 - Type safety, correctness idioms, and architectural rules\r\n\r\n### Rust - banned patterns\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `unwrap()` \u002F `expect()` in library code | **Banned.** Use `?` with typed errors via `thiserror`. |\r\n| `unsafe` without `\u002F\u002F SAFETY:` comment | **Banned.** Document the invariant upheld. |\r\n| Recursion in core algorithms | **Banned.** Use iterative loops with an explicit stack. Recursion blows the call stack on deep\u002Fadversarial inputs and defeats branch prediction. |\r\n| `as any` casts (in FFI or interop) | Minimize. Use typed wrappers or trait objects. |\r\n| Raw pointer arithmetic | Prefer safe abstractions. Use `unsafe` only when necessary, with safety proof. |\r\n\r\n### Rust - required annotations\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `#[must_use]` | Add to all public constructors, serialization\u002Fdeserialization methods, and functions returning `Option`\u002F`Result` whose value should not be silently discarded. |\r\n| `#[allow(dead_code)]` | Remove the annotation AND the dead code. If the field\u002Ffunction is planned for future use, delete it now and re-add when needed (with a TODO referencing an issue). |\r\n\r\n### Rust - error handling precision\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| 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\u002Fend markers). If a default is genuinely correct, add a comment explaining why. |\r\n| `Option\u003CT>` return for lookups that can fail in multiple ways | Use `Result\u003CT, E>` with a typed error enum distinguishing missing-key, invalid-path, type-mismatch, etc. Collapsing all failures to `None` makes debugging impossible. |\r\n| Error variants that abuse a generic `Validation(String)` | Add dedicated variants (`Decode`, `Encode`, `MissingField`) so callers can match programmatically. |\r\n| Byte vs char index confusion | When 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. |\r\n\r\n### Rust - numeric precision\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| Forcing all numbers through `f64` for comparisons | Preserve exact integer comparisons (`i64`\u002F`u64`) when both operands are integral. Only fall back to `f64` for genuine floats. Large integers above 2^53 lose precision in `f64`. |\r\n\r\n### Rust - build-time validation\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| Deferring validation to render-time | Validate at parse\u002Fbuild 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. |\r\n| Accepting invalid inputs that pass through | If a `\u003Croute>` element is missing `path` or references an unknown component, the parser must reject it with an actionable error. |\r\n| `bytes[i] as char` on UTF-8 strings | This silently corrupts multi-byte characters. Use `str` slicing or `char_indices()` to preserve UTF-8 correctness. |\r\n\r\n### Rust - diagnostics & error presentation\r\n\r\nSee `skills\u002Fdiagnostics\u002FSKILL.md` for the full workflow. On review, check:\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `panic!`\u002F`unwrap` on recoverable (template\u002FCLI\u002Fstate) input | **Banned.** Return `Result` - `panic = \"abort\"` kills FFI\u002FWASM\u002FNode hosts. Authoring mistakes return `ParserError::Template(Box\u003CDiagnostic>)`. |\r\n| 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. |\r\n| Color\u002FANSI in a library, host, browser, or JSON channel | Color belongs **only** in `webui-cli` (`console::style()`). Libraries emit plain data; FFI\u002FWASM\u002FNode\u002Fbrowser get plain `Display`. Split terminal-vs-machine renderings (e.g. `RebuildError { display, message }`) rather than leaking ANSI. |\r\n| A single SGR span wrapping newlines | Style each line independently - a span across `\\n` bleeds when lines are re-prefixed (`[server]`). |\r\n| Error construction inlined into a hot function | Mark error builders `#[cold]`\u002F`#[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. |\r\n| `serde_json::json!` macro in CLI output | Use the `serde_json::Map` API; the macro `unwrap`s internally and trips `disallowed_methods`. |\r\n| Tests asserting on error prose | Assert on the stable `code` (and that JSON output contains no `\\x1b`), not the human message. |\r\n\r\n### TypeScript\r\n\r\n| Pattern | Preference |\r\n|---------|-----------|\r\n| `(x as any)` | Use proper type narrowing, generics, or `unknown` with guards. |\r\n| Untyped expando properties (`(el as any)._data = ...`) | Use `WeakMap\u003CElement, T>` or typed fields on a subclass. |\r\n| `var` | **Banned.** Use `const` by default, `let` only when reassignment is needed. |\r\n| `== null` | Use `=== null \\|\\| === undefined` or optional chaining (`?.`). |\r\n| Callback-based async | Use `async\u002Fawait`. |\r\n| `arguments` object | Use rest parameters (`...args`). |\r\n| 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. |\r\n\r\n---\r\n\r\n## 8 - Style, comments, and documentation\r\n\r\n| Check | Rule |\r\n|-------|------|\r\n| **Dead code** | Remove unused functions, imports, and variables. Don't comment them out. |\r\n| **Commented-out code** | Delete it. Git has history. |\r\n| **Obvious comments** | Remove comments that restate the code: `\u002F\u002F increment counter` above `counter += 1`. |\r\n| **Missing comments** | Add comments for non-obvious decisions: \"We use BTreeMap here for deterministic iteration order.\" |\r\n| **`TODO` \u002F `FIXME` \u002F `HACK`** | Acceptable only with an associated issue number: `\u002F\u002F TODO(#123): switch to streaming parser`. |\r\n| **Naming** | Rust: `snake_case` functions, `PascalCase` types, `SCREAMING_SNAKE` constants. TS: `camelCase` variables\u002Ffunctions, `PascalCase` classes\u002Ftypes. |\r\n| **Magic numbers** | Extract to named constants with a doc comment. |\r\n| **File length** | When a file exceeds ~400 lines, split by concern. |\r\n| **Function arguments** | Max 5 parameters. Use a config\u002Foptions struct beyond that. |\r\n| **Unused dependencies** | Remove deps listed in `Cargo.toml` that are never imported. `anyhow` is for binary crates only - library crates use `thiserror`. |\r\n| **Placeholder \u002F no-op APIs** | If a public function always returns empty\u002Fdefault, either implement it or remove it behind a feature gate. Silent no-ops mislead callers. |\r\n| **Tests that lock in wrong behavior** | A test named `test_feature_not_supported` that asserts `None` for spec-required behavior is a bug, not a test. Delete or fix it. |\r\n\r\n---\r\n\r\n## 9 - Server runtime, proxy, and discovery correctness\r\n\r\nWhen the change touches dev-server, API proxy, request handling, or package discovery:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **HTTP semantics** | `Accept` header parsing must respect quality weights (`q=`). Substring matching (`contains(\"application\u002Fjson\")`) is incorrect per RFC 7231. |\r\n| **Status codes** | A \"no match\" must return 404, not 200 with empty body. Clients cannot distinguish \"valid empty\" from \"not found\" otherwise. |\r\n| **Proxy header forwarding** | Forward a safe allowlist: `Authorization`, `Cookie`, `Accept`, `Content-Type`, `X-Request-ID`, etc. Don't forward `Host` or hop-by-hop headers. |\r\n| **Path handling** | Paths with dots (e.g., `\u002Fapi\u002Fv2.1\u002Fusers`) are valid routes, not file requests. Don't use `contains('.')` as a file-vs-route heuristic. |\r\n| **Resource reuse** | HTTP clients, TLS contexts, and connection pools are expensive to create. Reuse them across requests. |\r\n| **HMR injection** | Search for closing tags case-insensitively. `\u003C\u002FBODY>` and `\u003C\u002Fbody>` are both valid HTML. |\r\n| **Input validation** | CLI commands must validate that input paths are directories (not files) before proceeding. Actionable error early beats cryptic failure later. |\r\n| **Cache invalidation scope** | Cache keys must include hashes\u002Fmtimes of ALL files that affect the cached result - not just `package.json`. If template HTML or CSS changes, the cache must invalidate. |\r\n| **Cache write safety** | Use per-write unique temp file names (PID + random suffix) and atomic rename. Concurrent writers must not clobber each other's temp files. |\r\n| **Symlink policy** | Package resolvers must allow workspace-linked packages (symlinks outside `node_modules`). Blocking all external symlinks breaks common monorepo patterns. |\r\n| **File-size guardrails** | Discovery that reads arbitrary files must cap read sizes. A 100MB HTML file shouldn't cause OOM during component scanning. |\r\n\r\n---\r\n\r\n## 10 - Protocol and schema hygiene\r\n\r\nWhen the change touches `.proto` files, serialization, or the binary protocol:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **Field additions are backward-compatible** | New fields must have defaults that preserve old behavior. |\r\n| **Removed fields use `reserved`** | Prevents accidental reuse of field numbers. |\r\n| **Enum variants are exhaustive** | Match arms must handle unknown variants (use a default\u002Funknown variant or `_` with a log). |\r\n| **No unnecessary nesting** | Flat structures decode faster than deeply nested ones. |\r\n| **Measure payload size** | Before\u002Fafter byte counts for representative inputs. Extra fields add decode overhead even when empty. |\r\n| **Prioritize decode speed** | Breaking field changes are allowed when they improve performance measurably. Remove unused fields and message shapes that add decode overhead. |\r\n| **Cascade all layers** | Schema changes affect the whole stack: protocol -> handler -> FFI -> CLI. Update all in the same change. Run `cargo xtask build && cargo xtask test` to validate. |\r\n| **Update architecture when needed** | A change to the protocol graph or producer\u002Fconsumer boundary updates `DESIGN.md`; field-level details belong in `.proto`, consumers, and tests. |\r\n\r\n---\r\n\r\n## 10b - FFI boundary safety\r\n\r\nWhen the change touches `crates\u002Fwebui-ffi` or C ABI signatures:\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **`# Safety` doc on every `extern \"C\" fn`** | Documents the invariants the caller must uphold. |\r\n| **`\u002F\u002F SAFETY:` on every `unsafe` block** | Explains why the unsafe operation is sound. |\r\n| **`catch_unwind` wraps all FFI bodies** | Panics from transitive deps (serde, prost) crossing the boundary are UB in unwind mode. On panic, set last-error and return null. |\r\n| **Validate all foreign inputs** | Null pointers, invalid UTF-8, out-of-range values - check before dereferencing. |\r\n| **No `unwrap()` or `expect()`** | Anywhere in the FFI code path, including error-handling helpers. |\r\n| **Minimal stable surface** | Prefer opaque pointers and integer error codes over exposing Rust layouts. |\r\n| **Header sync** | If any `#[no_mangle]` signature changes, verify `crates\u002Fwebui-ffi\u002Finclude\u002Fwebui_ffi.h`. |\r\n\r\n---\r\n\r\n## 11 - Documentation sync\r\n\r\nEvery behavioral change must include corresponding documentation updates. Missing docs are a review finding.\r\n\r\n| Check | Why |\r\n|-------|-----|\r\n| **DESIGN.md updated when architecture changes** | Changes 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. |\r\n| **User-facing docs updated** | If the change affects CLI flags, template syntax, component authoring, routing, or integration behavior, `docs\u002F` must be updated. |\r\n| **AI reference updated** | If the change affects anything a code-generation AI would need to know, `docs\u002Fai.md` must be updated. |\r\n| **README links to docs portal** | Package READMEs should defer to the docs portal, not duplicate content. |\r\n| **No stale examples** | Code examples in docs must use current API signatures, flag names, and marker formats. |\r\n| **docs build passes** | `cd docs && pnpm build` must succeed (catches broken links, unescaped `{{`, missing pages). |\r\n\r\nSee `docs-sync` skill for the full file mapping of what-changed to which-docs-to-update.\r\n\r\n---\r\n\r\n## Review output format\r\n\r\nWhen producing a code review, report findings as:\r\n\r\n```\r\n### ISSUE-NNN: \u003Cshort title>\r\n\r\n**Severity**: ? Bug | ? Security | ? Performance | ? Design\u002FStyle\r\n**Files**: `path\u002Fto\u002Ffile.rs` (lines N-M)\r\n**Description**: What is wrong, with a code snippet showing the problem.\r\n**Impact**: What breaks or degrades, and under what conditions.\r\n**Fix**: Concrete suggestion, with a code snippet when helpful.\r\n```\r\n\r\nEach finding must be **self-contained** - readable without context from other findings. This allows direct conversion to GitHub issues.\r\n",{"name":5,"description":7},"main","fd2d75282e29638442f161e202bf109d38e3ceb3",".github\u002Fskills\u002Fcode-review",25,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui","https:\u002F\u002Fmicrosoft.github.io\u002Fwebui\u002F","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-15 02:46:10",{"source":8,"skillName":5,"commands":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add microsoft\u002Fwebui --skill code-review",{"tool":65,"command":66},"bunx","bunx skills add microsoft\u002Fwebui --skill code-review",{"tool":68,"command":69},"pnpm","pnpm dlx skills add microsoft\u002Fwebui --skill code-review","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fcode-review\u002FSKILL.md",true,[],[74,92,111,130,147,160],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":44},"01M69AQ6PSR5AXD1W7K822EJEJ","webui-reference","Use when writing or reviewing WebUI application or framework code. Load the application's installed reference or the WebUI source checkout's canonical reference.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002Fai\u002FSKILL.md",[],[81,82,83,84,85,86,87,88,89,34,90,38,91],"webui reference","webui","reference","writing","checkout","canonical","use","load","source","application","when",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":44},"01M69AQ4B9AXF52SB3A0NVW4QT","webui-dev","Build interactive WebUI apps with compiled-template hydration, template syntax, component patterns, and CLI usage.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fwebui-dev\u002FSKILL.md",[],[99,82,100,101,102,103,104,105,106,107,108,109,110],"dev","webui dev","component","cli","usage","apps","interactive","with","build","template","syntax","patterns",{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":120,"publishedAt":44},"01M69AQ21S81FTXJF5716X3JPB","testing","Test patterns, fixture structure, and when to use E2E vs unit tests.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Ftesting\u002FSKILL.md",[117],{"categoryNo":118,"categoryName":119,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",[113,121,91,110,122,123,124,87,125,126,127,128,129],"structure","when to use","test patterns","fixture","test","unit tests","unit","tests","e2e",{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":44},"01M69APZVHA8B3AM0S1WJ1T5BC","quality-gate","Run before every commit or push: formatting, linting, tests, dependency audits, builds, and docs.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fquality-gate\u002FSKILL.md",[],[137,138,139,140,141,142,143,144,145,128,146],"quality","gate","quality gate","docs","commit","push","linting","dependency","run","formatting",{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":44},"01M69APXXGESWZ75E8B5PKWC8H","pr","Guidance for branch naming, commit messages, and PR titles.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fpr\u002FSKILL.md",[],[149,154,141,155,156,157,158,159],"guidance","branch","for","messages","naming","commit messages",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":44},"01M69APVKEAZD650TFNCT9WMN1","perf","Speed and memory performance rules for Rust crates, the Node addon, webui-framework, and webui-delivery.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fwebui\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fperf\u002FSKILL.md",[],[162,167,36,168,156,82,169,170,171,172,38],"memory","rust","delivery","node","speed","Rules"]