Commit b8a36803d1 for aom
commit b8a36803d13194b19b90d1e5ce5ab847d7454886
Author: Jiamei Liu <jiameil@google.com>
Date: Wed Oct 28 21:10:18 2026 +0000
[agentic-review] Add base libaom knowledge base rules
Add foundational libaom code review knowledge base rules backed by
multiple CLs (52 rules across 4 directories)
under `knowledge_base/rules/` and export `COMMON_METADATA` for
embedding via `DIR_METADATA` `mixins`:
- `knowledge_base/rules/aom/` (4 rules)
- `knowledge_base/rules/aom_dsp/` (9 rules)
- `knowledge_base/rules/av1/` (19 rules)
- `knowledge_base/rules/general/` (20 rules)
NO_IFTTT=Documentation examples in markdown rules reference LINT.IfChange.
Bug: b:578206319, b:568026769
Change-Id: I83a35c19ed988e26598f48bf4b1a466337364d66
diff --git a/knowledge_base/COMMON_METADATA b/knowledge_base/COMMON_METADATA
new file mode 100644
index 0000000000..ea9c24edcd
--- /dev/null
+++ b/knowledge_base/COMMON_METADATA
@@ -0,0 +1,263 @@
+# Copyright (c) 2026, Alliance for Open Media. All rights reserved.
+#
+# This source code is subject to the terms of the BSD 2 Clause License and
+# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+# was not distributed with this source code in the LICENSE file, you can
+# obtain it at www.aomedia.org/license/software. If the Alliance for Open
+# Media Patent License 1.0 was not distributed with this source code in the
+# PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+
+agentic_review {
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:h|hpp)"
+ rules: "knowledge_base/rules/aom/append-new-public-enum-values-at-end.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/aom/document-mechanism-and-purpose-for-codec-controls.md"
+ }
+ capability_groups {
+ path_expression: "aom/.*"
+ path_expression: "apps/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "examples/.*"
+ path_expression_exclusion: "test/.*"
+ rules: "knowledge_base/rules/aom/omit-tuning-overrides-from-codec-control-defaults.md"
+ }
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "apps/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/aom/sync-cli-arg-descriptions-with-codec-control-docs.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression: "common/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/simd/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "test/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/aom_dsp/name-dsp-functions-by-metrics-and-block-layout.md"
+ rules: "knowledge_base/rules/av1/delegate-composite-dsp-to-standalone-primitives.md"
+ rules: "knowledge_base/rules/av1/hoist-scratch-buffer-allocations.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*_hwy[^/]*\\.cc"
+ path_expression: "(?:.*/)?[^/]*_hwy_avx512\\.cc"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/override-hwy-broken-32bit-for-highway-targets.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?x86/.*"
+ path_expression: "av1/(?:.*/)?x86/.*"
+ path_expression: "common/x86/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/pack-pairs-of-simd-rows-before-storing.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "test/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*avx[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*sse[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*sve[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*x86[^/]*/.*"
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "test/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/use-aligned-simd-loads-for-aligned-buffers.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "aom_scale/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "test/.*"
+ rules: "knowledge_base/rules/av1/avoid-direct-calls-to-c-rtcd-functions.md"
+ }
+ capability_groups {
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|h)"
+ rules: "knowledge_base/rules/av1/derive-and-validate-shear-params-on-warped-motion.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|h)"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/dispatch-8bit-simd-by-runtime-bit-depth.md"
+ }
+ capability_groups {
+ path_expression: "av1/encoder/.*"
+ rules: "knowledge_base/rules/av1/document-shared-codec-structs-for-encoder-and-decoder.md"
+ rules: "knowledge_base/rules/av1/preserve-default-rate-control-tuning.md"
+ rules: "knowledge_base/rules/av1/split-independent-speed-features.md"
+ rules: "knowledge_base/rules/av1/sync-frame-resize-realloc-paths.md"
+ }
+ capability_groups {
+ path_expression: "av1/encoder/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/document-speed-feature-levels-and-validation-checks.md"
+ rules: "knowledge_base/rules/av1/separate-stage-multithreading-state.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/explicit-block-size-checks-over-bitmasks.md"
+ rules: "knowledge_base/rules/av1/size-scratch-buffers-tightly.md"
+ }
+ capability_groups {
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/keep-encoder-only-code-in-encoder-directory.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/maintain-highbd-and-lowbd-counterpart-parity.md"
+ }
+ capability_groups {
+ path_expression: "aom_util/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/terminate-workers-before-freeing-worker-arrays.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch.md"
+ }
+ capability_groups {
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/use-exact-resolution-bounds-for-speed-features.md"
+ }
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:c|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/use-ppi-number-spatial-layers-for-sequence-config.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/arm-neon-guard-msvc-32bit-xn-intrinsics.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "apps/.*"
+ path_expression_exclusion: "examples/.*"
+ path_expression_exclusion: "test/.*"
+ path_expression_exclusion: "third_party/.*"
+ path_expression_exclusion: "tools/.*"
+ rules: "knowledge_base/rules/general/avoid-fatal-exit-in-library-code.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/general/avoid-log-on-zero-valued-metrics-use-log1p.md"
+ rules: "knowledge_base/rules/general/cast-subwords-to-unsigned-before-bitwise-packing.md"
+ rules: "knowledge_base/rules/general/initialize-all-output-parameters-in-stubs.md"
+ rules: "knowledge_base/rules/general/scale-allocation-by-element-sizeof.md"
+ rules: "knowledge_base/rules/general/update-buffer-alloc-size-only-on-realloc.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|inc)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/avoid-raw-compiler-attributes.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/check-memory-allocation-failure.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/clamp-floating-point-conversions-to-integer-limits.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/document-reference-c-implementation-fallbacks.md"
+ }
+ capability_groups {
+ path_expression: "av1/decoder/.*"
+ path_expression: "av1/encoder/.*"
+ rules: "knowledge_base/rules/general/no-assert-for-untrusted-bitstream.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/no-top-level-const-on-function-params.md"
+ rules: "knowledge_base/rules/general/omit-redundant-narrowing-casts-on-wider-integers.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "aom_dsp/aom_dsp_common\\.h"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/prefer-clamp-over-nested-min-max-macros.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/record-error-details-with-aom-set-error.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ rules: "knowledge_base/rules/general/trailing-comment-on-endif-directives.md"
+ rules: "knowledge_base/rules/general/use-bool-for-boolean-flags-and-arrays.md"
+ rules: "knowledge_base/rules/general/use-sizeof-pointer-dereference-in-allocations.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/use-neon-lane-intrinsics-not-vector-subscript.md"
+ }
+}
diff --git a/knowledge_base/rules/aom/COMMON_METADATA b/knowledge_base/rules/aom/COMMON_METADATA
new file mode 100644
index 0000000000..3a4ff62ffd
--- /dev/null
+++ b/knowledge_base/rules/aom/COMMON_METADATA
@@ -0,0 +1,35 @@
+# Copyright (c) 2026, Alliance for Open Media. All rights reserved.
+#
+# This source code is subject to the terms of the BSD 2 Clause License and
+# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+# was not distributed with this source code in the LICENSE file, you can
+# obtain it at www.aomedia.org/license/software. If the Alliance for Open
+# Media Patent License 1.0 was not distributed with this source code in the
+# PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+
+agentic_review {
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:h|hpp)"
+ rules: "knowledge_base/rules/aom/append-new-public-enum-values-at-end.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/aom/document-mechanism-and-purpose-for-codec-controls.md"
+ }
+ capability_groups {
+ path_expression: "aom/.*"
+ path_expression: "apps/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "examples/.*"
+ path_expression_exclusion: "test/.*"
+ rules: "knowledge_base/rules/aom/omit-tuning-overrides-from-codec-control-defaults.md"
+ }
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "apps/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/aom/sync-cli-arg-descriptions-with-codec-control-docs.md"
+ }
+}
diff --git a/knowledge_base/rules/aom/append-new-public-enum-values-at-end.md b/knowledge_base/rules/aom/append-new-public-enum-values-at-end.md
new file mode 100644
index 0000000000..bf58ac9a6d
--- /dev/null
+++ b/knowledge_base/rules/aom/append-new-public-enum-values-at-end.md
@@ -0,0 +1,53 @@
+---
+name: libaom/aom/append-new-public-enum-values-at-end
+description: When modifying public API enums in aom/*.h, append new enumerators at the end and retain legacy reserved constants as aliases for ABI compatibility
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** In public API headers (aom/*.h), maintain ABI stability when extending
+or updating enum definitions: append new enumerators at the end of the enum
+(after existing values and before/after sentinels without shifting implicit
+integers), and do not insert unnumbered items into the middle. When giving
+concrete names to previously reserved or placeholder enumerators, retain the
+legacy constant (e.g., *_RESERVED_*) as an alias assigned to the same numeric
+value.
+
+**Why.** Public headers define libaom's public C API and ABI contract. Inserting
+new unnumbered enumerators into the middle shifts implicit integer values of
+subsequent enumerators, and removing existing placeholder or reserved constants
+breaks symbol and binary compatibility for external applications compiled
+against earlier library versions.
+
+## Examples
+
+Bad:
+
+```cpp
+// Shifting values by inserting in the middle:
+typedef enum {
+ AOM_CONTENT_DEFAULT,
+ AOM_CONTENT_SCREEN,
+ AOM_CONTENT_ENHANCED, // Shifts subsequent values like AOM_CONTENT_INVALID!
+ AOM_CONTENT_INVALID
+} aom_tune_content;
+
+// Removing reserved placeholder breaks ABI:
+AOM_CICP_MC_IPT_C2 = 15,
+```
+
+Good:
+
+```cpp
+// Appending new values at the end:
+typedef enum {
+ AOM_CONTENT_DEFAULT,
+ AOM_CONTENT_SCREEN,
+ AOM_CONTENT_INVALID,
+ AOM_CONTENT_ENHANCED // Appended at end to preserve ABI
+} aom_tune_content;
+
+// Retaining legacy reserved enumerator as alias:
+AOM_CICP_MC_RESERVED_15 = 15, /**< For backward compatibility */
+AOM_CICP_MC_IPT_C2 = 15,
+```
diff --git a/knowledge_base/rules/aom/document-mechanism-and-purpose-for-codec-controls.md b/knowledge_base/rules/aom/document-mechanism-and-purpose-for-codec-controls.md
new file mode 100644
index 0000000000..f24d00c3e0
--- /dev/null
+++ b/knowledge_base/rules/aom/document-mechanism-and-purpose-for-codec-controls.md
@@ -0,0 +1,102 @@
+---
+name: libaom/aom/document-mechanism-and-purpose-for-codec-controls
+description: When declaring codec controls, config structs, or enum options in headers, document parameter types, numeric mappings, units, ranges, and restrictions, and use int /* enum_type */ in AOM_CTRL_USE_TYPE
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** When defining public codec controls (`AOME_SET_*`, `AV1E_SET_*`,
+`AOMD_GET_*`, `AV1D_GET_*`), configuration flags (`AOM_EFLAG_*`), config structs
+(`aom_codec_enc_cfg_t`, `aom_image_t`), tuning enums (`AOM_TUNE_*`), or enum
+types and mode options in headers (such as `aom/aomcx.h`, `aom/aomdx.h`, or
+internal headers), provide comprehensive Doxygen doc comments (`/*!\brief ...
+*/`, `\note`) and format type declarations as follows:
+
+1. **Brief Summary and Parameter Types**:
+ - In codec control ID comments, state the expected parameter type directly in the opening `\brief` summary sentence (e.g., `'/*!\brief Codec control to ..., unsigned int parameter.'`). When the control accepts an enum, name the specific enum type (e.g., `'aom_screen_detection_mode parameter'`).
+ - Separate subsequent detailed paragraphs, rationale, or option lists from the `\brief` summary line with a blank comment line.
+2. **AOM_CTRL_USE_TYPE for Enum Controls**:
+ - When declaring type-checking for enum-valued controls with `AOM_CTRL_USE_TYPE`, pass `int` as the type argument rather than `unsigned int` or the enum type name directly, and append an inline comment specifying the expected enum type (e.g., `AOM_CTRL_USE_TYPE(AV1E_SET_MODE, int) /* aom_mode_t */`).
+3. **Enumerator Behavior, Option Lists, and Numeric Values**:
+ - In option lists for enum controls and when defining enum types (e.g., `DELTA_Q_MODE`), document each enumerator's intended behavior, algorithm variant, and how non-default options differ from standard or default behavior.
+ - Document both the numeric integer value and the enum constant identifier (e.g., `'- 1: AOM_SCREEN_DETECTION_STANDARD = standard'`), especially when enum values start at non-zero numbers.
+4. **Purpose, Mechanism, and Units**:
+ - Describe underlying mechanisms and algorithm effects rather than tautological descriptions. For tuning enums, describe user-facing intent and internal shared logic (e.g., shared `rdmult` calculation).
+ - Document concrete units and scaling interpretations (percentages, milliseconds, scaling factors), valid numerical ranges, and default values.
+5. **Modulation, Bounds, and Prerequisites**:
+ - For controls that dynamically modulate another setting (such as `AV1E_SET_ENABLE_ADAPTIVE_SHARPNESS`), document modulation ranges and interaction with maximum bounds (`AOME_SET_SHARPNESS`).
+ - Explicitly document configuration prerequisites (e.g., requiring `g_lag_in_frames == 0`), applicable operating modes or profile restrictions (such as 'for all-intra mode only' or 'real-time only'), and concrete caller data preparation requirements (e.g., 'upshift the frame to the codec bit-depth').
+
+**Why.** Public API and subsystem headers serve as the primary reference for
+library consumers and maintainers. In public C headers, enum types are passed as
+integers through the variadic `aom_codec_control` interface; specifying `int` in
+`AOM_CTRL_USE_TYPE` with a trailing inline comment maintains portable C calling
+conventions while clearly identifying the expected enum type for API consumers.
+Doxygen treats comment text up to the first blank line as part of the brief
+summary; stating parameter or enum types in `\brief` and separating details with
+a blank line ensures clean summary tables and enables IDE navigation.
+Documenting explicit numeric mappings alongside enum constants clarifies usage
+when values start non-zero. Omitting explicit behaviors, mechanisms, units,
+prerequisites, bounds interactions, operating mode restrictions, or caller
+transformation steps forces developers to inspect internal source code and leads
+to misconfigurations or pipeline bugs.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Missing parameter type in brief sentence, details not separated by blank line:
+/*!\brief Set deltaq strength. Valid range: [0, 1000] */
+AV1E_SET_DELTAQ_STRENGTH = 148,
+AOM_CTRL_USE_TYPE(AV1E_SET_DELTAQ_STRENGTH, int)
+
+// 2. Generic int in brief, missing numeric values, and direct enum/unsigned int in AOM_CTRL_USE_TYPE:
+/*!\brief Codec control to set the screen content detection mode, unsigned int parameter.
+ * - AOM_SCREEN_DETECTION_STANDARD = standard (default)
+ * - AOM_SCREEN_DETECTION_ANTIALIASING_AWARE = anti-aliased text aware */
+AV1E_SET_SCREEN_CONTENT_DETECTION_MODE = 171,
+AOM_CTRL_USE_TYPE(AV1E_SET_SCREEN_CONTENT_DETECTION_MODE, unsigned int)
+
+// 3. Operating mode restriction omitted on enum values and missing prerequisite on flag:
+/*!\brief Calculate PSNR for this frame */
+#define AOM_EFLAG_CALCULATE_PSNR (1 << 1)
+
+typedef enum {
+ DELTA_Q_OBJECTIVE = 1, // Modulation to improve objective quality
+ DELTA_Q_PERCEPTUAL = 2, // Modulation to improve perceptual quality
+ DELTA_Q_VARIANCE_BOOST = 6, // Variance Boost style modulation
+} DELTA_Q_MODE;
+```
+
+Good:
+
+```cpp
+// 1. Explicit parameter type in brief, blank line separation, unit (percentage), range, default:
+/*!\brief Codec control to set --deltaq-mode strength, unsigned int parameter.
+ *
+ * Value is a percentage scaling factor. Valid range: [0, 1000]. Default is 100.
+ */
+AV1E_SET_DELTAQ_STRENGTH = 148,
+AOM_CTRL_USE_TYPE(AV1E_SET_DELTAQ_STRENGTH, int)
+
+// 2. Specific enum in brief, numeric values mapped, and int + inline comment in AOM_CTRL_USE_TYPE:
+/*!\brief Codec control to set the screen content detection mode, aom_screen_detection_mode parameter.
+ *
+ * - 1: AOM_SCREEN_DETECTION_STANDARD = standard (default)
+ * - 2: AOM_SCREEN_DETECTION_ANTIALIASING_AWARE = anti-aliased text aware
+ */
+AV1E_SET_SCREEN_CONTENT_DETECTION_MODE = 171,
+AOM_CTRL_USE_TYPE(AV1E_SET_SCREEN_CONTENT_DETECTION_MODE,
+ int) /* aom_screen_detection_mode */
+
+// 3. Explicit prerequisite on flag and operating mode restriction on enum values:
+/*!\brief Calculate PSNR for this frame, requires g_lag_in_frames to be 0 */
+#define AOM_EFLAG_CALCULATE_PSNR (1 << 1)
+
+typedef enum {
+ DELTA_Q_OBJECTIVE = 1, // Modulation to improve objective quality
+ DELTA_Q_PERCEPTUAL = 2, // Modulation to improve perceptual quality
+ DELTA_Q_VARIANCE_BOOST = 6, // Variance Boost modulation for all intra mode only
+} DELTA_Q_MODE;
+```
diff --git a/knowledge_base/rules/aom/omit-tuning-overrides-from-codec-control-defaults.md b/knowledge_base/rules/aom/omit-tuning-overrides-from-codec-control-defaults.md
new file mode 100644
index 0000000000..d893acdcc0
--- /dev/null
+++ b/knowledge_base/rules/aom/omit-tuning-overrides-from-codec-control-defaults.md
@@ -0,0 +1,71 @@
+---
+name: libaom/aom/omit-tuning-overrides-from-codec-control-defaults
+description: When adding or modifying codec controls and CLI options (ARG_DEF), document usage-mode-specific initialization defaults in headers and help text, but omit tuning-metric overrides
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** When documenting or modifying default values for public codec controls
+in API headers (such as `aom/aomcx.h` or `aom/aomdx.h`) and CLI argument
+definitions (`ARG_DEF` in `av1/arg_defs.c` or `apps/`):
+1. Accurately document baseline encoder initialization defaults across all supported usage modes, clearly distinguishing mode-specific values when they differ (such as `AOM_USAGE_ALL_INTRA`, `AOM_USAGE_REALTIME`, or `AOM_USAGE_GOOD_QUALITY`). When changing or adding usage-mode defaults in encoder initialization code (e.g., `av1/av1_cx_iface.c`), always update the corresponding header and CLI doc comments to match.
+2. Do not document dynamic tuning-metric parameter overrides (such as SSIMULACRA 2 or `AOM_TUNE_IQ`) as default values on individual option or codec control definitions; document tuning overrides centrally under the tuning mode enum (`aom_tune_metric`) or `--tune` argument definition.
+
+**Why.** Default values in API headers and CLI help text describe baseline
+parameters configured during encoder initialization (`aom_codec_enc_init()`)
+across standard usage modes (`AOM_USAGE_*`). Accurately documenting
+usage-mode-specific defaults prevents caller confusion about active encoder
+behavior when switching between all-intra, realtime, and good-quality modes.
+Conversely, tuning metrics dynamically override configuration parameters at
+runtime; documenting these overrides under individual options and codec controls
+causes clutter and documentation drift, whereas centralizing overrides under the
+tuning metric definition keeps option defaults clean and presets easy to find.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Omits usage-mode distinctions when defaults change in encoder init
+// av1/av1_cx_iface.c sets tuning to AOM_TUNE_SSIM for AOM_USAGE_ALL_INTRA, but header states:
+/*!\brief Codec control function to set visual tuning
+ *
+ * The default is AOM_TUNE_PSNR.
+ */
+AOME_SET_TUNING = 24,
+
+// Variant 2: Documents tuning override as an option default in CLI and header
+.qm_min = ARG_DEF(NULL, "qm-min", 1,
+ "Min quant matrix flatness (0..15), default is 5 (4 for "
+ "all intra mode, 2 for SSIMULACRA 2 tune)"),
+
+/*!\brief Codec control to set min quant matrix flatness
+ *
+ * The default is 5 (or 4 for all-intra, 2 for AOM_TUNE_SSIMULACRA2).
+ */
+AV1E_SET_QM_MIN = 64,
+```
+
+Good:
+
+```cpp
+// Variant 1: Accurately reflects defaults across usage modes in header doc
+// av1/av1_cx_iface.c sets tuning to AOM_TUNE_SSIM for AOM_USAGE_ALL_INTRA:
+/*!\brief Codec control function to set visual tuning
+ *
+ * The default is AOM_TUNE_PSNR (or AOM_TUNE_SSIM in all-intra mode).
+ */
+AOME_SET_TUNING = 24,
+
+// Variant 2: Documents usage-mode default and centralizes tuning overrides
+.qm_min = ARG_DEF(
+ NULL, "qm-min", 1,
+ "Min quant matrix flatness (0..15), default is 5 (4 for all intra mode)"),
+
+// In aom/aomcx.h under enum aom_tune_metric:
+/*!\brief SSIMULACRA 2 tuning metric.
+ * Automatically overrides the following options:
+ * * --qm-min=2
+ */
+AOM_TUNE_SSIMULACRA2 = 11,
+```
diff --git a/knowledge_base/rules/aom/sync-cli-arg-descriptions-with-codec-control-docs.md b/knowledge_base/rules/aom/sync-cli-arg-descriptions-with-codec-control-docs.md
new file mode 100644
index 0000000000..fbfed93a80
--- /dev/null
+++ b/knowledge_base/rules/aom/sync-cli-arg-descriptions-with-codec-control-docs.md
@@ -0,0 +1,62 @@
+---
+name: libaom/aom/sync-cli-arg-descriptions-with-codec-control-docs
+description: When adding or updating codec controls, configuration settings, or CLI options, keep documentation, valid values, and terminology consistent across public headers and av1/arg_defs.c
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** When adding, updating, or clarifying codec controls, operational
+modes, configuration struct fields (such as in aom_codec_enc_cfg_t), or CLI
+options, ensure public API header doc comments (e.g., in aom/aomcx.h,
+aom/aomdx.h, or aom/aom_encoder.h) and corresponding command-line argument
+definitions (ARG_DEF in av1/arg_defs.c) remain consistent. Document all valid
+values, supported modes, behavior details, and precise terminology (such as
+input source bit-depth vs. codec bit-depth) across public headers, CLI help
+text, and internal struct comments.
+
+**Why.** Public API headers and CLI help strings serve as the primary references
+for library callers and CLI users. Inconsistent terminology or omitting newly
+supported modes, behaviors, or semantic distinctions across headers, ARG_DEF
+help strings, and internal comments creates confusion and leaves features
+undiscoverable.
+
+## Examples
+
+Bad:
+
+```cpp
+// In aom/aomcx.h (missing newly added deltaq modes 5 and 6):
+ * - 4 = use modulation for user rating based perceptual quality optimization
+ */
+AV1E_SET_DELTAQ_MODE = 107,
+
+// In av1/arg_defs.c (missing mode descriptions or imprecise terminology):
+.deltaq_mode =
+ ARG_DEF(NULL, "deltaq-mode", 1,
+ "Delta qindex mode (0: off, 1: deltaq objective (default), "
+ "2: deltaq placeholder, 3: key frame visual quality, 4: user "
+ "rating based visual quality optimization); "
+ "requires --enable-tpl-model=1"),
+.inbitdeptharg = ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input");
+```
+
+Good:
+
+```cpp
+// In aom/aomcx.h (documents all valid modes):
+ * - 4 = use modulation for user rating based perceptual quality optimization
+ * - 5 = use modulation for HDR video
+ * - 6 = use modulation for all intra using Variance Boost
+ */
+AV1E_SET_DELTAQ_MODE = 107,
+
+// In av1/arg_defs.c (accurate mode descriptions and precise terminology):
+.deltaq_mode =
+ ARG_DEF(NULL, "deltaq-mode", 1,
+ "Delta qindex mode (0: off, 1: deltaq objective (default), "
+ "2: deltaq placeholder, 3: key frame visual quality, 4: user "
+ "rating based visual quality optimization, 5: HDR video, 6: "
+ "Variance Boost); --deltaq-mode=1 requires --enable-tpl-model=1"),
+.inbitdeptharg =
+ ARG_DEF(NULL, "input-bit-depth", 1, "Bit depth of input source");
+```
diff --git a/knowledge_base/rules/aom_dsp/COMMON_METADATA b/knowledge_base/rules/aom_dsp/COMMON_METADATA
new file mode 100644
index 0000000000..fc282d31a0
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/COMMON_METADATA
@@ -0,0 +1,85 @@
+# Copyright (c) 2026, Alliance for Open Media. All rights reserved.
+#
+# This source code is subject to the terms of the BSD 2 Clause License and
+# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+# was not distributed with this source code in the LICENSE file, you can
+# obtain it at www.aomedia.org/license/software. If the Alliance for Open
+# Media Patent License 1.0 was not distributed with this source code in the
+# PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+
+agentic_review {
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression: "common/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/simd/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "test/x86/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/aom_dsp/name-dsp-functions-by-metrics-and-block-layout.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*_hwy[^/]*\\.cc"
+ path_expression: "(?:.*/)?[^/]*_hwy_avx512\\.cc"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/override-hwy-broken-32bit-for-highway-targets.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?x86/.*"
+ path_expression: "av1/(?:.*/)?x86/.*"
+ path_expression: "common/x86/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/pack-pairs-of-simd-rows-before-storing.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "test/(?:.*/)?x86/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*avx[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*sse[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*sve[^/]*/.*"
+ path_expression: "(?:.*/)?[^/]*x86[^/]*/.*"
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "test/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/aom_dsp/use-aligned-simd-loads-for-aligned-buffers.md"
+ }
+}
diff --git a/knowledge_base/rules/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers.md b/knowledge_base/rules/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers.md
new file mode 100644
index 0000000000..78a2624835
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers.md
@@ -0,0 +1,59 @@
+---
+name: libaom/aom_dsp/factor-repetitive-simd-arithmetic-into-inline-helpers
+description: When implementing SIMD routines, use existing helper functions (e.g., abs_diff16) or factor repetitive multi-instruction arithmetic sequences across lanes and sub-registers into static inline helpers
+rubric: design
+severity: should_fix
+---
+
+**Rule.** When implementing or modifying SIMD routines, use established inline
+helper functions (such as abs_diff16() or abs_diff()) rather than open-coding
+equivalent multi-instruction intrinsic sequences (such as
+_mm_or_si128(_mm_subs_epu16(a, b), _mm_subs_epu16(b, a))). When repetitive
+multi-step arithmetic sequences (such as multiply-accumulate followed by
+rounding shifts), mask calculations, or sub-register operations across low/high
+halves (such as vget_low_*/vget_high_*, _mm_extract*, or _mm256_extract*) recur
+across vector lanes, loop unrolls, or related kernel functions without an
+existing helper, factor the shared sequence into a static inline helper
+function.
+
+**Why.** Using established inline SIMD helpers and factoring repetitive
+multi-instruction sequences into reusable static inline functions clarifies
+mathematical intent, reduces visual clutter, and eliminates copy-paste errors
+across sub-registers and unrolled lanes without incurring runtime call overhead.
+
+## Examples
+
+Bad:
+
+```cpp
+// Open-coded unsigned absolute difference instead of using helper
+const __m128i abs_p1p0 =
+ _mm_or_si128(_mm_subs_epu16(p[1], p[0]), _mm_subs_epu16(p[0], p[1]));
+
+// Duplicated multi-instruction arithmetic across low and high sub-registers
+uint32x4_t m0_lo = vmull_u16(vget_low_u16(m0), vget_low_u16(s0));
+m0_lo = vmlal_u16(m0_lo, vget_low_u16(m0_inv), vget_low_u16(s1));
+uint16x4_t res_lo = vshrn_n_u32(m0_lo, AOM_BLEND_A64_ROUND_BITS);
+uint32x4_t m0_hi = vmull_u16(vget_high_u16(m0), vget_high_u16(s0));
+m0_hi = vmlal_u16(m0_hi, vget_high_u16(m0_inv), vget_high_u16(s1));
+uint16x4_t res_hi = vshrn_n_u32(m0_hi, AOM_BLEND_A64_ROUND_BITS);
+```
+
+Good:
+
+```cpp
+// Use existing SIMD helper function
+const __m128i abs_p1p0 = abs_diff16(p[1], p[0]);
+
+// Factored repetitive lane/sub-register sequence into a static inline helper
+static inline uint16x4_t blend_u16x4(uint16x4_t m, uint16x4_t m_inv,
+ uint16x4_t a, uint16x4_t b) {
+ uint32x4_t acc = vmull_u16(m, a);
+ acc = vmlal_u16(acc, m_inv, b);
+ return vshrn_n_u32(acc, AOM_BLEND_A64_ROUND_BITS);
+}
+uint16x4_t res_lo = blend_u16x4(vget_low_u16(m0), vget_low_u16(m0_inv),
+ vget_low_u16(s0), vget_low_u16(s1));
+uint16x4_t res_hi = blend_u16x4(vget_high_u16(m0), vget_high_u16(m0_inv),
+ vget_high_u16(s0), vget_high_u16(s1));
+```
diff --git a/knowledge_base/rules/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks.md b/knowledge_base/rules/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks.md
new file mode 100644
index 0000000000..f7852d0ad6
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks.md
@@ -0,0 +1,43 @@
+---
+name: libaom/aom_dsp/load-only-four-bytes-for-four-wide-simd-blocks
+description: When loading narrow block rows or reference buffers in x86 SIMD routines, use width-matched loads like xx_loadl_32/64 rather than full-register loads
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** In x86 SIMD routines, use width-matched load helpers or intrinsics
+(such as xx_loadl_32 or _mm_cvtsi32_si128 for 4-byte/32-bit rows, and
+xx_loadl_64 or _mm_loadl_epi64 for 8-byte/64-bit rows) when reading lines,
+reference buffers, or mask rows narrower than full vector registers. Do not use
+wider or full-register loads (such as _mm_loadl_epi64 on 4-byte buffers or
+xx_loadu_128 / _mm_loadu_si128 on 8-byte rows) on buffers that are only
+allocated or valid for the narrower width.
+
+**Why.** Loading 8 or 16 bytes from buffers or row strides that only allocate 4
+or 8 valid bytes over-reads past allocated buffer boundaries or row strides.
+This causes memory over-read errors, AddressSanitizer violations, or potential
+segmentation faults when processing narrow blocks near image or buffer edges.
+
+## Examples
+
+Bad:
+
+```cpp
+// 4-byte reference buffer: over-reading 8 bytes with _mm_loadl_epi64
+__m128i d = _mm_loadl_epi64((const __m128i *)above);
+
+// 8-byte mask row: over-reading 16 bytes with xx_loadu_128
+const __m128i v_ra = xx_loadu_128(mask);
+const __m128i v_rb = xx_loadu_128(mask + mask_stride);
+```
+
+Good:
+
+```cpp
+// 4-byte reference buffer: load exact 4 bytes (32 bits)
+__m128i d = _mm_cvtsi32_si128(*(const uint32_t *)above);
+
+// 8-byte mask row: load exact 8 bytes (64 bits)
+const __m128i v_ra = xx_loadl_64(mask);
+const __m128i v_rb = xx_loadl_64(mask + mask_stride);
+```
diff --git a/knowledge_base/rules/aom_dsp/name-dsp-functions-by-metrics-and-block-layout.md b/knowledge_base/rules/aom_dsp/name-dsp-functions-by-metrics-and-block-layout.md
new file mode 100644
index 0000000000..fc54b05c6c
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/name-dsp-functions-by-metrics-and-block-layout.md
@@ -0,0 +1,61 @@
+---
+name: libaom/aom_dsp/name-dsp-functions-by-metrics-and-block-layout
+description: When defining DSP helper functions, RTCD primitives, or SIMD kernels, explicitly name their calculated metrics, full 2D block dimensions, and batching layout
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** Name DSP helper functions, RTCD declarations, and SIMD kernels
+explicitly after the exact metrics they compute and their precise 2D block
+dimensions and multi-block layout. Specifically:
+1. **Computed metrics**: Name all calculated outputs accurately (e.g., `get_var_sse_sum` or `get_sse_sum` rather than generic `var` when variance is not computed).
+2. **2D Block dimensions**: Specify explicit width-by-height dimensions (e.g., `<name>_<width>x<height>` such as `blend_8x4`, `subtract_4x8`, or `_8x1` for single-row helpers) rather than ambiguous width-only suffixes (e.g., `_w8`).
+3. **Batching layout**: Qualify multi-block batching formats (such as `8x8_quad` or `16x16_dual`) consistently across C references, RTCD tables, and architecture-specific SIMD implementations.
+
+**Why.** Inaccurate or truncated names mislead callers and SIMD implementers.
+Using generic metric names (like `var` when only SSE and sum are computed)
+obscures what values are populated, while omitting height dimensions (like `_w8`
+for an 8x4 block) causes ambiguity or naming collisions when introducing
+single-line (`_8x1`) or other height variants. Explicit naming ensures
+consistent RTCD integration and maintainability across SIMD backends.
+
+## Examples
+
+Bad:
+
+```cpp
+// Misleading metric name and ambiguous block layout
+void aom_get8x8var_quad_c(const uint8_t *a, int a_stride, const uint8_t *b,
+ int b_stride, uint32_t *sse, int *sum);
+
+// Width-only suffix for a 2D 8x4 block kernel
+static INLINE void blend_w8(uint8_t *dst, uint32_t dst_stride,
+ const CONV_BUF_TYPE *src0, uint32_t src0_stride,
+ const CONV_BUF_TYPE *src1, uint32_t src1_stride,
+ int16x8_t mask0, int16x8_t mask1, int16x8_t mask2,
+ int16x8_t mask3, const int16x4_t v_maxval,
+ const uint16x8_t vec_round_offset,
+ const int16x8_t vec_round_bits) {
+ // Processes an 8x4 block
+}
+```
+
+Good:
+
+```cpp
+// Accurately names computed metrics and quad-batching layout
+void aom_get_sse_sum_8x8_quad_c(const uint8_t *a, int a_stride,
+ const uint8_t *b, int b_stride, uint32_t *sse,
+ int *sum);
+
+// Explicit 2D dimensions match block geometry (8x4)
+static INLINE void blend_8x4(uint8_t *dst, uint32_t dst_stride,
+ const CONV_BUF_TYPE *src0, uint32_t src0_stride,
+ const CONV_BUF_TYPE *src1, uint32_t src1_stride,
+ int16x8_t mask0, int16x8_t mask1, int16x8_t mask2,
+ int16x8_t mask3, const int16x4_t v_maxval,
+ const uint16x8_t vec_round_offset,
+ const int16x8_t vec_round_bits) {
+ // Explicit 8x4 dimensions match block geometry
+}
+```
diff --git a/knowledge_base/rules/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow.md b/knowledge_base/rules/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow.md
new file mode 100644
index 0000000000..0ee5952cb8
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow.md
@@ -0,0 +1,65 @@
+---
+name: libaom/aom_dsp/omit-simd-chunking-loops-when-accumulators-cannot-overflow
+description: When implementing SIMD or DSP accumulation kernels, omit chunking loops when accumulators cannot overflow, or hardcode fixed chunking when only 128x128 overflows
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** In SIMD or DSP accumulation kernels (such as variance, SAD, SSE, or
+sum of squares), check theoretical maximum sums against accumulator bit-depth
+limits across discrete block sizes. If the maximum sum cannot overflow 32-bit
+vector registers for any supported size, eliminate chunking loops and accumulate
+directly in 32-bit registers with a single post-loop 64-bit reduction. When
+accumulator overflow is only possible for the largest discrete block size (e.g.,
+128x128), branch directly on that size and use fixed chunk constants instead of
+dynamic pixel multiplication and division.
+
+**Why.** Intermediate chunking sub-loops, horizontal reductions, and dynamic
+dimension calculations (w * h, limit / w) introduce unnecessary arithmetic,
+branching, and register shuffling in hot DSP loops. Determining overflow
+boundaries statically against known discrete block sizes maximizes vector
+pipeline throughput and avoids runtime division.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Unnecessary intermediate chunking and reduction when max sum fits in 32-bit
+do {
+ __m128i v_acc_q = _mm_setzero_si128();
+ const int step = AOMMIN(height - r, 32);
+ for (int j = 0; j < step; j += 4) { ... }
+ v_acc_q = _mm_add_epi32(v_acc_q, _mm_srli_epi64(v_acc_q, 32));
+ sum += (uint64_t)_mm_cvtsi128_si32(v_acc_q);
+} while (r < height);
+
+// Bad: Dynamic pixel multiplication and division when only 128x128 can overflow
+} else if (w * h <= max_pel_allowed_per_ovf) {
+ hbd_obmc_variance_w8n(pre, stride, wsrc, mask, &sse, &sum, w, h);
+} else {
+ int h_per_ovf = max_pel_allowed_per_ovf / w;
+ hbd_obmc_variance_w8n(pre, stride, wsrc, mask, &sse, &sum, w, h_per_ovf);
+}
+```
+
+Good:
+
+```cpp
+// Good: Single continuous accumulation loop with post-loop 64-bit widening
+do {
+ const __m128i v_acc_d = sum_squares_i16_4x4_sse2(src, stride);
+ v_acc_q = _mm_add_epi32(v_acc_q, v_acc_d);
+ src += stride << 2;
+ r += 4;
+} while (r < height);
+return (uint64_t)xx_cvtsi128_si64(reduce_to_64(v_acc_q));
+
+// Good: Direct dimension check with fixed constant chunk height
+} else if (w < 128 || h < 128) {
+ hbd_obmc_variance_w8n(pre, stride, wsrc, mask, &sse, &sum, w, h);
+} else {
+ assert(w == 128 && h == 128);
+ hbd_obmc_variance_w8n(pre, stride, wsrc, mask, &sse, &sum, w, 64);
+}
+```
diff --git a/knowledge_base/rules/aom_dsp/override-hwy-broken-32bit-for-highway-targets.md b/knowledge_base/rules/aom_dsp/override-hwy-broken-32bit-for-highway-targets.md
new file mode 100644
index 0000000000..e84b8aa765
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/override-hwy-broken-32bit-for-highway-targets.md
@@ -0,0 +1,45 @@
+---
+name: libaom/aom_dsp/override-hwy-broken-32bit-for-highway-targets
+description: When configuring x86 Highway SIMD target macros, define HWY_BASELINE_TARGETS as HWY_AVX3_DL for AVX-512 and override HWY_BROKEN_32BIT instead of HWY_BROKEN_TARGETS
+rubric: readability
+severity: blocking
+---
+
+**Rule.** When configuring Highway SIMD target macros at the top of x86
+translation units before including Highway headers, define
+`HWY_BASELINE_TARGETS` as `HWY_AVX3_DL` rather than `HWY_AVX3` in AVX-512 files
+(`*_hwy_avx512.cc`) (and match the respective target macro such as `HWY_AVX2` or
+`HWY_SSE4` for other SIMD units). Additionally, override target-specific
+brokenness with `HWY_BROKEN_32BIT` (e.g., `#define HWY_BROKEN_32BIT 0` or
+`#define HWY_BROKEN_32BIT (HWY_AVX3 | (HWY_AVX3 - 1))`) instead of globally
+resetting compiler filters with `#define HWY_BROKEN_TARGETS 0`.
+
+**Why.** Libaom standardizes on `HWY_AVX3_DL` (AVX-512 with double-pumped
+256-bit vectors and AVX-512BW/DQ/VL extensions including VBMI, VBMI2, VNNI,
+BITALG) for its AVX-512 Highway targets, ensuring consistent baseline detection,
+RTCD dispatch, and compatibility. Selectively defining `HWY_BROKEN_32BIT`
+controls 32-bit SIMD target availability without bypassing compiler and
+architecture safeguards that `#define HWY_BROKEN_TARGETS 0` would globally
+disable.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Using plain HWY_AVX3 for AVX-512 or globally disabling all broken target protections
+#define HWY_BASELINE_TARGETS HWY_AVX3
+#define HWY_BROKEN_TARGETS 0
+
+#include "aom_dsp/sad_hwy.h"
+```
+
+Good:
+
+```cpp
+// Good: Using HWY_AVX3_DL for AVX-512 files and overriding HWY_BROKEN_32BIT selectively
+#define HWY_BASELINE_TARGETS HWY_AVX3_DL
+#define HWY_BROKEN_32BIT 0
+
+#include "aom_dsp/sad_hwy.h"
+```
diff --git a/knowledge_base/rules/aom_dsp/pack-pairs-of-simd-rows-before-storing.md b/knowledge_base/rules/aom_dsp/pack-pairs-of-simd-rows-before-storing.md
new file mode 100644
index 0000000000..5828fa95f1
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/pack-pairs-of-simd-rows-before-storing.md
@@ -0,0 +1,56 @@
+---
+name: libaom/aom_dsp/pack-pairs-of-simd-rows-before-storing
+description: In x86 SIMD routines handling narrow rows, pack row pairs into 128-bit or 256-bit vectors using high-half loads or yy_loadu2_128 instead of half-utilized registers
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** In x86 SIMD routines processing rows narrower than vector capacity,
+pack row pairs into full-width registers rather than leaving vectors
+half-utilized:
+1. When loading 8-byte (64-bit) rows into 128-bit vectors, use high-half loads (e.g., xx_loadh_64, _mm_loadh_pi, _mm_loadh_pd, loadh_epi64) instead of separate loads and _mm_unpacklo_epi64; on output, pack vector pairs (_mm_packus_epi16(a, b)) and store via paired 64-bit stores (_mm_storel_epi64, _mm_storeh_pi) instead of self-packing.
+2. When loading 16-byte (128-bit) rows into 256-bit AVX2 vectors, pack two rows per iteration using yy_loadu2_128 instead of casting single 128-bit loads via _mm256_castsi128_si256.
+
+**Why.** Leaving registers half-utilized (such as casting single 128-bit loads
+into 256-bit AVX2 vectors or processing single 64-bit rows in 128-bit vectors)
+incurs vector instruction overhead without utilizing execution throughput or
+outperforming narrower instruction sets. Packing row pairs halves loop
+iterations, arithmetic instructions, and intermediate register usage.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Casting 128-bit load into half-utilized AVX2 vector
+for (int i = 0; i < N; i++) {
+ src_reg = _mm256_castsi128_si256(_mm_load_si128((const __m128i *)src));
+ ref0_reg = _mm256_castsi128_si256(_mm_loadu_si128((const __m128i *)ref0));
+ src += src_stride;
+}
+
+// Bad: Loading separate 64-bit halves and unpacking, or self-packing output
+const __m128i v0 = xx_loadl_64(src + 0 * stride);
+const __m128i v1 = xx_loadl_64(src + 1 * stride);
+const __m128i v01 = _mm_unpacklo_epi64(v0, v1);
+_mm_storel_epi64((__m128i *)(dst + j), _mm_packus_epi16(roundA, roundA));
+_mm_storel_epi64((__m128i *)(dst + j + stride), _mm_packus_epi16(roundB, roundB));
+```
+
+Good:
+
+```cpp
+// Good: Packing two 128-bit rows into 256-bit AVX2 registers with yy_loadu2_128
+for (int i = 0; i < N; i += 2) {
+ src_reg = yy_loadu2_128(src + src_stride, src);
+ ref0_reg = yy_loadu2_128(ref0 + ref_stride, ref0);
+ src += 2 * src_stride;
+}
+
+// Good: Combining 64-bit rows with high-half load, and packing pairs for store
+const __m128i v0 = xx_loadl_64(src + 0 * stride);
+const __m128i v01 = xx_loadh_64(v0, src + 1 * stride);
+const __m128i round = _mm_packus_epi16(roundA, roundB);
+_mm_storel_epi64((__m128i *)(dst + j), round);
+_mm_storeh_pi((__m64 *)(dst + j + stride), _mm_castsi128_ps(round));
+```
diff --git a/knowledge_base/rules/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args.md b/knowledge_base/rules/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args.md
new file mode 100644
index 0000000000..f45b7adad8
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args.md
@@ -0,0 +1,64 @@
+---
+name: libaom/aom_dsp/pass-all-x86-vectors-as-pointers-over-three-args
+description: When defining SIMD helper functions with multiple vector parameters, pass vector types (__m128i, __m256i, __m512i) as pointers rather than by value or mixed conventions
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When defining SIMD helper functions that accept vector parameters
+(such as `__m128i`, `__m256i`, or `__m512i`), pass vector arguments by pointer
+(e.g., `const __m256i *` for read-only inputs or `__m256i *` for mutated/in-out
+accumulators) rather than by value. Consistently pass all SIMD vector parameters
+as pointers rather than mixing value and pointer parameters, and pass addresses
+of array-resident vectors (`&vec[i]`) directly to pointer-based helper
+functions.
+
+**Why.** Platform ABIs and calling conventions (such as 32-bit x86 MSVC on
+Windows and Windows x64) pass only a limited number of vector parameters in
+registers (typically 3 or 4). Passing large SIMD vectors by value or passing
+excess parameters spills arguments onto the stack without guaranteed 16- or
+32-byte alignment, causing compiler errors (e.g., MSVC C2719),
+calling-convention mismatches, and register spills. Passing vector parameters by
+pointer avoids alignment hazards and reduces register pressure while inlining
+compilers optimize pointer indirection with zero runtime overhead.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern 1: Passing multiple __m256i vector parameters by value
+static INLINE __m256i fold_mul_and_sum_avx2(__m256i partiala, __m256i partialb,
+ __m256i const1, __m256i const2) {
+ const __m256i tmp = _mm256_madd_epi16(partiala, const1);
+ return _mm256_add_epi32(tmp, _mm256_madd_epi16(partialb, const2));
+}
+
+// Anti-pattern 2: Mixing value and pointer vector parameters
+static INLINE __m128i filter_block_2rows(const __m128i a0, const __m128i b0,
+ const __m128i a1, const __m128i *b1,
+ const __m128i *filter);
+
+// Anti-pattern 3: Passing array elements by value
+res = hadd_four_32_to_64_avx2(sum[0], sum[1], sum[2], sum[3]);
+```
+
+Good:
+
+```cpp
+// Pattern 1: Pass vector inputs/accumulators as const or mutable pointers
+static INLINE __m256i fold_mul_and_sum_avx2(__m256i *partiala, __m256i *partialb,
+ const __m256i *const1,
+ const __m256i *const2) {
+ const __m256i tmp = _mm256_madd_epi16(*partiala, *const1);
+ return _mm256_add_epi32(tmp, _mm256_madd_epi16(*partialb, *const2));
+}
+
+// Pattern 2: Consistently pass all vector parameters as pointers
+static INLINE __m128i filter_block_2rows(const __m128i *a0, const __m128i *b0,
+ const __m128i *a1, const __m128i *b1,
+ const __m128i *filter);
+
+// Pattern 3: Pass memory-resident array elements by pointer address
+res = hadd_four_32_to_64_avx2(&sum[0], &sum[1], &sum[2], &sum[3]);
+```
diff --git a/knowledge_base/rules/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels.md b/knowledge_base/rules/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels.md
new file mode 100644
index 0000000000..f840890f4e
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels.md
@@ -0,0 +1,72 @@
+---
+name: libaom/aom_dsp/unroll-short-fixed-loops-in-simd-dsp-kernels
+description: In SIMD and DSP kernels, unroll short fixed-iteration loops using constant pointer offsets or compile-time immediate intrinsics instead of dynamic indexing or switch wrappers
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** In performance-critical SIMD and DSP kernels, explicitly unroll small
+loops with short, fixed iteration counts (e.g., 2–8 iterations or horizontal
+vector passes for fixed block widths like 16, 32, 64, or 128) rather than using
+loop counters and dynamic indexing. Access sequential vector blocks using
+explicit constant pointer offsets (e.g., `ptr + 16`) instead of calculating
+dynamic offsets with loop counter indices. Additionally, when extracting or
+aligning SIMD vector elements with varying offsets, unroll small loops and
+invoke vector extract/align intrinsics (such as ARM NEON `vextq_*` / `vext_*` or
+x86 `_mm_alignr_epi8`) directly using compile-time constant literals rather than
+writing dynamic wrapper functions with `switch` statements.
+
+**Why.** Small inner loops with fixed iteration counts introduce unnecessary
+loop counter increments, condition branches, and dynamic indexing calculations.
+Compilers may disable automatic loop unrolling at `-O2` due to code-size
+heuristics. Explicit unrolling eliminates loop branch overhead, guarantees
+consistent performance across `-O2` and `-O3` optimization levels, and allows
+the compiler to better interleave and schedule vector loads and arithmetic
+across registers. Furthermore, intrinsics like `vextq_*` and `_mm_alignr_epi8`
+require immediate constant byte offsets encoded directly into hardware
+instructions; wrapping them in runtime `switch` statements introduces branch
+penalties that are completely avoided by unrolling.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Loop overhead and dynamic indexing for fixed 2-vector block pass (width 32):
+for (int j = 0; j < 2; ++j) {
+ uint8x16_t s = vld1q_u8(src + j * 16);
+ uint8x16_t r = vld1q_u8(ref + j * 16);
+ sse += sse_16x1_neon(s, r);
+}
+
+// 2. Switch-based wrapper to emulate runtime-variable offset in a loop:
+static INLINE uint32x4_t valign(uint32x4_t l, uint32x4_t r, int offset) {
+ switch (offset) {
+ case 1: return vextq_u32(l, r, 1);
+ case 2: return vextq_u32(l, r, 2);
+ case 3: return vextq_u32(l, r, 3);
+ default: return l;
+ }
+}
+for (int i = 0; i < 4; i++) {
+ vmask[i] = valign(k0, kf, 4 - i);
+}
+```
+
+Good:
+
+```cpp
+// 1. Explicitly unroll fixed 2-vector pass with constant pointer offsets:
+uint8x16_t s0 = vld1q_u8(src);
+uint8x16_t r0 = vld1q_u8(ref);
+uint8x16_t s1 = vld1q_u8(src + 16);
+uint8x16_t r1 = vld1q_u8(ref + 16);
+sse += sse_16x1_neon(s0, r0);
+sse += sse_16x1_neon(s1, r1);
+
+// 2. Unroll loop and pass compile-time constant literals directly:
+vmask[0] = kf;
+vmask[1] = vextq_u32(k0, kf, 3);
+vmask[2] = vextq_u32(k0, kf, 2);
+vmask[3] = vextq_u32(k0, kf, 1);
+```
diff --git a/knowledge_base/rules/aom_dsp/use-aligned-simd-loads-for-aligned-buffers.md b/knowledge_base/rules/aom_dsp/use-aligned-simd-loads-for-aligned-buffers.md
new file mode 100644
index 0000000000..68fa62ac56
--- /dev/null
+++ b/knowledge_base/rules/aom_dsp/use-aligned-simd-loads-for-aligned-buffers.md
@@ -0,0 +1,48 @@
+---
+name: libaom/aom_dsp/use-aligned-simd-loads-for-aligned-buffers
+description: In SIMD routines, use unaligned loads (like _mm_loadu_si128 or load_unaligned_u8) for unverified buffers, reserving aligned loads strictly for guaranteed-aligned memory
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** In x86 (SSE/AVX) and ARM NEON SIMD routines, use unaligned load
+intrinsics or helpers (such as _mm_loadu_si128, _mm256_loadu_si256,
+xx_loadu_128, or load_unaligned_u8 / load_unaligned_u8_4x4 / load_unaligned_u8q)
+when reading from arbitrary, unverified, offset, or reference frame buffer
+pointers. Use alignment-restricted loads or helpers (such as _mm_load_si128,
+_mm256_load_si256, or load_u8_4x1 / load_u8_4x2 / load_u8_4x4) strictly when the
+source buffer is guaranteed and declared to meet vector/stride alignment (e.g.,
+via DECLARE_ALIGNED).
+
+**Why.** Aligned load instructions (e.g., MOVDQA) and alignment-restricted load
+helpers trigger general protection faults, hardware exceptions, assertion
+failures in debug builds, or undefined behavior when executed on unaligned
+addresses or unaligned strides. Conversely, using aligned loads on
+guaranteed-aligned buffers documents data layout invariants and avoids unaligned
+access penalties on older architectures.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad (x86): Aligned load on arbitrary/unverified reference pointer
+__m128i src_line = _mm_load_si128((const __m128i *)ref);
+
+// Bad (ARM NEON): Using load helpers that assume 4-byte pointer/stride alignment
+const uint8x8_t r0 = load_u8_4x2(ref, ref_stride);
+const uint8x16_t r1 = load_u8_4x4(ref + 2 * ref_stride, ref_stride);
+```
+
+Good:
+
+```cpp
+// Good (x86): Use unaligned load for unverified pointer; aligned load for DECLARE_ALIGNED buffer
+__m128i src_line = _mm_loadu_si128((const __m128i *)ref);
+__m128i iscan0 = _mm_load_si128((const __m128i *)iscan_ptr);
+
+// Good (ARM NEON): Use unaligned load helpers safe for arbitrary byte offsets and strides
+const uint8x8_t r0 = load_unaligned_u8_4x2(ref, ref_stride);
+uint8x8_t r1, r2;
+load_unaligned_u8_4x4(ref + 2 * ref_stride, ref_stride, &r1, &r2);
+```
diff --git a/knowledge_base/rules/av1/COMMON_METADATA b/knowledge_base/rules/av1/COMMON_METADATA
new file mode 100644
index 0000000000..12c57d3ab8
--- /dev/null
+++ b/knowledge_base/rules/av1/COMMON_METADATA
@@ -0,0 +1,83 @@
+# Copyright (c) 2026, Alliance for Open Media. All rights reserved.
+#
+# This source code is subject to the terms of the BSD 2 Clause License and
+# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+# was not distributed with this source code in the LICENSE file, you can
+# obtain it at www.aomedia.org/license/software. If the Alliance for Open
+# Media Patent License 1.0 was not distributed with this source code in the
+# PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+
+agentic_review {
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "aom_scale/.*"
+ path_expression: "av1/.*"
+ path_expression_exclusion: "test/.*"
+ rules: "knowledge_base/rules/av1/avoid-direct-calls-to-c-rtcd-functions.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/delegate-composite-dsp-to-standalone-primitives.md"
+ rules: "knowledge_base/rules/av1/hoist-scratch-buffer-allocations.md"
+ }
+ capability_groups {
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|h)"
+ rules: "knowledge_base/rules/av1/derive-and-validate-shear-params-on-warped-motion.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|h)"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/dispatch-8bit-simd-by-runtime-bit-depth.md"
+ }
+ capability_groups {
+ path_expression: "av1/encoder/.*"
+ rules: "knowledge_base/rules/av1/document-shared-codec-structs-for-encoder-and-decoder.md"
+ rules: "knowledge_base/rules/av1/preserve-default-rate-control-tuning.md"
+ rules: "knowledge_base/rules/av1/split-independent-speed-features.md"
+ rules: "knowledge_base/rules/av1/sync-frame-resize-realloc-paths.md"
+ }
+ capability_groups {
+ path_expression: "av1/encoder/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/document-speed-feature-levels-and-validation-checks.md"
+ rules: "knowledge_base/rules/av1/separate-stage-multithreading-state.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/explicit-block-size-checks-over-bitmasks.md"
+ rules: "knowledge_base/rules/av1/size-scratch-buffers-tightly.md"
+ }
+ capability_groups {
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/keep-encoder-only-code-in-encoder-directory.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/.*"
+ path_expression: "av1/.*"
+ path_expression: "common/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/maintain-highbd-and-lowbd-counterpart-parity.md"
+ }
+ capability_groups {
+ path_expression: "aom_util/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/av1/terminate-workers-before-freeing-worker-arrays.md"
+ }
+ capability_groups {
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch.md"
+ }
+ capability_groups {
+ path_expression: "av1/.*"
+ rules: "knowledge_base/rules/av1/use-exact-resolution-bounds-for-speed-features.md"
+ }
+ capability_groups {
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:c|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/av1/use-ppi-number-spatial-layers-for-sequence-config.md"
+ }
+}
diff --git a/knowledge_base/rules/av1/avoid-direct-calls-to-c-rtcd-functions.md b/knowledge_base/rules/av1/avoid-direct-calls-to-c-rtcd-functions.md
new file mode 100644
index 0000000000..64e2fdbad8
--- /dev/null
+++ b/knowledge_base/rules/av1/avoid-direct-calls-to-c-rtcd-functions.md
@@ -0,0 +1,55 @@
+---
+name: libaom/av1/avoid-direct-calls-to-c-rtcd-functions
+description: When calling RTCD functions, use base dispatch symbols in production code and matching architecture SIMD kernels in architecture wrappers instead of _c fallbacks
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** Do not directly invoke unoptimized C fallback (*_c) RTCD or DSP
+functions in production code or architecture-specific wrapper implementations:
+1. In general production code, call the base RTCD dispatch symbol (without _c or architecture suffixes such as _neon, _sse2, _avx2) to enable runtime CPU detection.
+2. In architecture-specific wrapper, dual, or quad SIMD functions (such as *_dual_neon, *_quad_sse2, or *_dual_avx2), invoke the matching architecture-specific SIMD kernels (e.g., *_neon, *_sse2, *_avx2) rather than calling C fallback routines (*_c).
+
+**Why.** In libaom, RTCD (Run-Time CPU Detection) dynamically selects optimized
+SIMD implementations at runtime. Directly calling *_c functions in production
+code bypasses CPU detection and forces unoptimized C execution. Similarly,
+invoking *_c routines inside architecture-specific SIMD wrappers silently
+defeats SIMD acceleration and degrades codec performance.
+
+## Examples
+
+Bad:
+
+```cpp
+// In general codec code: directly calling _c bypasses RTCD
+aom_lpf_horizontal_14_dual_c(s, pitch, lfi->mblim, lfi->lim,
+ lfi->hev_thr, lfin->mblim, lfin->lim,
+ lfin->hev_thr);
+
+// In architecture wrappers: calling _c defeats SIMD acceleration
+void aom_lpf_vertical_6_dual_neon(uint8_t *s, int pitch, const uint8_t *blimit0,
+ const uint8_t *limit0, const uint8_t *thresh0,
+ const uint8_t *blimit1, const uint8_t *limit1,
+ const uint8_t *thresh1) {
+ aom_lpf_vertical_6_c(s, pitch, blimit0, limit0, thresh0);
+ aom_lpf_vertical_6_c(s + 4 * pitch, pitch, blimit1, limit1, thresh1);
+}
+```
+
+Good:
+
+```cpp
+// In general codec code: use base RTCD dispatch symbol
+aom_lpf_horizontal_14_dual(s, pitch, lfi->mblim, lfi->lim,
+ lfi->hev_thr, lfin->mblim, lfin->lim,
+ lfin->hev_thr);
+
+// In architecture wrappers: invoke matching architecture SIMD kernels
+void aom_lpf_vertical_6_dual_neon(uint8_t *s, int pitch, const uint8_t *blimit0,
+ const uint8_t *limit0, const uint8_t *thresh0,
+ const uint8_t *blimit1, const uint8_t *limit1,
+ const uint8_t *thresh1) {
+ aom_lpf_vertical_6_neon(s, pitch, blimit0, limit0, thresh0);
+ aom_lpf_vertical_6_neon(s + 4 * pitch, pitch, blimit1, limit1, thresh1);
+}
+```
diff --git a/knowledge_base/rules/av1/delegate-composite-dsp-to-standalone-primitives.md b/knowledge_base/rules/av1/delegate-composite-dsp-to-standalone-primitives.md
new file mode 100644
index 0000000000..762db1937d
--- /dev/null
+++ b/knowledge_base/rules/av1/delegate-composite-dsp-to-standalone-primitives.md
@@ -0,0 +1,68 @@
+---
+name: libaom/av1/delegate-composite-dsp-to-standalone-primitives
+description: When implementing composite DSP or SIMD routines, invoke existing standalone primitives (e.g., aom_comp_avg_pred, aom_dist_wtd_comp_avg_pred) rather than inlining vector loops
+rubric: design
+severity: should_fix
+---
+
+**Rule.** In composite DSP and SIMD routines (such as compound average upsampled
+prediction or distance-weighted compound prediction), invoke the corresponding
+standalone DSP primitive functions (such as `aom_comp_avg_pred_*`,
+`aom_highbd_comp_avg_pred_*`, or `aom_dist_wtd_comp_avg_pred_*`) instead of
+duplicating or open-coding vector intrinsic loops. When chaining multi-stage
+operations, pass intermediate buffers between the specialized building blocks
+and maintain consistent delegation across low-bitdepth and high-bitdepth
+implementations.
+
+**Why.** Inlining arithmetic or blending loops across multiple composite
+functions duplicates complex SIMD logic, increases maintenance burden, and
+creates redundant code across architecture variants. Delegating sub-operations
+to dedicated standalone primitives eliminates duplicate vector code, ensures
+consistent math, rounding, and bitdepth handling across call sites, reduces
+binary size, and allows composite routines to automatically benefit from
+optimizations or bug fixes in the underlying building blocks.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern: Open-coding inline SIMD loops inside composite prediction functions
+void aom_highbd_comp_avg_upsampled_pred_neon(...) {
+ aom_highbd_upsampled_pred_neon(xd, cm, mi_row, mi_col, mv, comp_pred8, ...);
+ for (int i = 0; i < width * height; i += 8) {
+ uint16x8_t cp = vqrshlq_u16(vaddq_u16(vld1q_u16(&pred[i]), vld1q_u16(&comp_pred[i])), shift);
+ vst1q_u16(&comp_pred[i], cp);
+ }
+}
+
+void aom_highbd_dist_wtd_comp_avg_upsampled_pred_neon(...) {
+ aom_highbd_upsampled_pred_neon(xd, cm, mi_row, mi_col, mv, comp_pred8, ...);
+ for (int i = 0; i < width * height; i += 8) {
+ // Inlined distance-weighted blending calculation loop
+ uint32x4_t cp0 = vmlal_u16(vmull_u16(vget_low_u16(p), bck_offset_u16), vget_low_u16(cp), fwd_offset_u16);
+ ...
+ }
+}
+```
+
+Good:
+
+```cpp
+// Delegate composite sub-operations to dedicated standalone SIMD primitives
+void aom_highbd_comp_avg_upsampled_pred_neon(...) {
+ aom_highbd_upsampled_pred_neon(xd, cm, mi_row, mi_col, mv, comp_pred8, width,
+ height, subpel_x_q3, subpel_y_q3, ref8,
+ ref_stride, bd, subpel_search);
+ aom_highbd_comp_avg_pred_neon(comp_pred8, pred8, width, height, comp_pred8,
+ width);
+}
+
+void aom_highbd_dist_wtd_comp_avg_upsampled_pred_neon(...) {
+ aom_highbd_upsampled_pred_neon(xd, cm, mi_row, mi_col, mv, comp_pred8, width,
+ height, subpel_x_q3, subpel_y_q3, ref8,
+ ref_stride, bd, subpel_search);
+ aom_highbd_dist_wtd_comp_avg_pred_neon(comp_pred8, pred8, width, height,
+ comp_pred8, width, jcp_param);
+}
+```
diff --git a/knowledge_base/rules/av1/derive-and-validate-shear-params-on-warped-motion.md b/knowledge_base/rules/av1/derive-and-validate-shear-params-on-warped-motion.md
new file mode 100644
index 0000000000..fec89db634
--- /dev/null
+++ b/knowledge_base/rules/av1/derive-and-validate-shear-params-on-warped-motion.md
@@ -0,0 +1,57 @@
+---
+name: libaom/av1/derive-and-validate-shear-params-on-warped-motion
+description: When estimating, constructing, or transforming affine warped motion models (WarpedMotionParams), calculate base matrix parameters before transformations and call av1_get_shear_params() to validate
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When computing or updating affine warped motion models
+(WarpedMotionParams), ensure base transformation parameters (wmmat) are
+estimated or initialized (e.g., via find_affine_int() from sample points or
+copied from global motion) before applying additional transformations such as
+rotation (av1_warp_rotation()). After constructing or modifying matrix
+parameters, call av1_get_shear_params() to derive shear parameters and verify
+model validity, handling invalid models by falling back or clearing active
+warp/rotation flags.
+
+**Why.** Transformation functions modify wmmat in place; applying them before
+model estimation operates on stale or uninitialized matrix values and causes
+transformations to be overwritten by find_affine_int(). Furthermore, warped
+motion compensation requires valid shear parameters derived from the final
+transformation matrix, and omitting av1_get_shear_params() leaves uninitialized
+parameters or executes invalid transforms exceeding hardware precision limits.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: applying rotation before base affine model estimation
+#if CONFIG_EXT_ROTATION
+ av1_warp_rotation(mbmi, mbmi->rotation, center_x, center_y);
+#endif
+ if (find_affine_int(np, pts1, pts2, bsize, mvy, mvx, wm_params, mi_row, mi_col))
+ return 1;
+
+// Bad: modifying matrix parameters without re-deriving shear parameters
+memcpy(&mi->wm_params, &xd->global_motion[mi->ref_frame[ref]], sizeof(WarpedMotionParams));
+av1_warp_rotation(mi, mi->rotation, center_x, center_y);
+```
+
+Good:
+
+```cpp
+// Good: estimate base affine model first, then apply rotation
+ if (find_affine_int(np, pts1, pts2, bsize, mvy, mvx, wm_params, mi_row, mi_col))
+ return 1;
+#if CONFIG_EXT_ROTATION
+ av1_warp_rotation(mbmi, mbmi->rotation, center_x, center_y);
+#endif
+
+// Good: re-derive shear parameters and validate model
+memcpy(&mi->wm_params, &xd->global_motion[mi->ref_frame[ref]], sizeof(WarpedMotionParams));
+av1_warp_rotation(mi, mi->rotation, center_x, center_y);
+if (!av1_get_shear_params(&mi->wm_params)) {
+ mi->rot_flag = 0;
+}
+```
diff --git a/knowledge_base/rules/av1/dispatch-8bit-simd-by-runtime-bit-depth.md b/knowledge_base/rules/av1/dispatch-8bit-simd-by-runtime-bit-depth.md
new file mode 100644
index 0000000000..16c63df1ec
--- /dev/null
+++ b/knowledge_base/rules/av1/dispatch-8bit-simd-by-runtime-bit-depth.md
@@ -0,0 +1,50 @@
+---
+name: libaom/av1/dispatch-8bit-simd-by-runtime-bit-depth
+description: When implementing 8-bit SIMD optimizations, dispatch based on runtime bit depth at caller sites rather than disabling SIMD under CONFIG_AV1_HIGHBITDEPTH
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** Do not disable 8-bit SIMD optimizations or unconditionally fall back
+to C reference implementations using compile-time #if CONFIG_AV1_HIGHBITDEPTH
+inside SIMD functions. Instead, keep 8-bit SIMD routines enabled and dispatch
+between 8-bit and high-bit-depth routines at caller sites based on runtime bit
+depth (e.g., cm->seq_params.bit_depth == AOM_BITS_8).
+
+**Why.** In libaom, CONFIG_AV1_HIGHBITDEPTH is a build-time configuration macro
+indicating that the compiled binary supports both 8-bit and 10/12-bit video
+streams dynamically at runtime. Using #if CONFIG_AV1_HIGHBITDEPTH inside
+low-bitdepth SIMD routines disables SIMD acceleration for standard 8-bit streams
+in high-bitdepth-enabled builds, causing severe performance regressions.
+
+## Examples
+
+Bad:
+
+```cpp
+// Inside 8-bit SIMD implementation (e.g., resize_neon.c or resize_ssse3.c):
+#if CONFIG_AV1_HIGHBITDEPTH
+ // Disables 8-bit SIMD optimization whenever high-bitdepth build is enabled
+ av1_resize_and_extend_frame_c(src, dst, filter, num_planes, phase);
+#else
+ av1_resize_and_extend_frame_ssse3(src, dst, filter, num_planes, phase);
+#endif
+```
+
+Good:
+
+```cpp
+// In caller dispatch (e.g., av1_scale_if_required()):
+#if CONFIG_AV1_HIGHBITDEPTH
+ if ((cm->width << 1) == unscaled->y_crop_width &&
+ (cm->height << 1) == unscaled->y_crop_height &&
+ cm->seq_params.bit_depth == AOM_BITS_8) {
+ av1_resize_and_extend_frame(unscaled, scaled, filter, phase, num_planes);
+ } else {
+ av1_resize_and_extend_frame_nonnormative(
+ unscaled, scaled, (int)cm->seq_params.bit_depth, num_planes);
+ }
+#else
+ av1_resize_and_extend_frame(unscaled, scaled, filter, phase, num_planes);
+#endif
+```
diff --git a/knowledge_base/rules/av1/document-shared-codec-structs-for-encoder-and-decoder.md b/knowledge_base/rules/av1/document-shared-codec-structs-for-encoder-and-decoder.md
new file mode 100644
index 0000000000..1ef98d9ebf
--- /dev/null
+++ b/knowledge_base/rules/av1/document-shared-codec-structs-for-encoder-and-decoder.md
@@ -0,0 +1,76 @@
+---
+name: libaom/av1/document-shared-codec-structs-for-encoder-and-decoder
+description: When documenting fields or reference-counted resources in shared codec structs, cover both encoder and decoder contexts, list all referencing variables, or document pipeline restrictions.
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** In shared and common codec headers (such as av1/common/ or aom/),
+ensure doc comments for struct fields accurately reflect both encoder and
+decoder contexts (e.g., 'encoded or decoded') when shared across pipelines. When
+documenting reference-counted resources (such as RefCntBuffer or BufferPool),
+ensure any enumeration of reference-holding pointers or variables exhaustively
+covers all referencing fields across both encoder and decoder states (e.g.,
+cm->ref_frame_map, cm->cur_frame, cm->scaled_ref_buf, pbi->output_frames). If a
+field in a shared structure is restricted to one pipeline (such as encoder-only
+or decoder-only) or exists for a non-obvious workaround (e.g.,
+display_order_hint), explicitly document its scope restriction, purpose, and
+rationale.
+
+**Why.** Shared structures in common headers are accessed across both encoder
+and decoder pipelines. Describing a shared field from only one pipeline's
+perspective or omitting decoder/encoder reference-holding variables in
+reference-counted resource docs obscures resource ownership, making
+reference-count leaks, premature releases, and buffer reuse bugs difficult to
+audit. Conversely, omitting scope restrictions or rationale for single-pipeline
+fields in shared structs leads to confusion about where and why the fields are
+maintained.
+
+## Examples
+
+Bad:
+
+```cpp
+// In shared header (e.g., av1/common/onyxc_int.h or av1/common/buffer_pool.h):
+
+// Variant 1: Shared field described from only one pipeline's perspective
+// Index to the 'new' frame (i.e. the frame currently being encoded) in the
+// buffer pool 'cm->buffer_pool'.
+int new_fb_idx;
+
+// Variant 2: Reference-holding list misses decoder-specific referencing fields
+// For a RefCntBuffer, the following are reference-holding variables:
+// - cm->ref_frame_map[]
+// - cm->cur_frame
+// - cm->scaled_ref_buf[] (encoder only)
+int ref_count;
+
+// Variant 3: Scope-restricted field added without scope or rationale comment
+unsigned int display_order_hint;
+unsigned int ref_display_order_hint[INTER_REFS_PER_FRAME];
+```
+
+Good:
+
+```cpp
+// In shared header (e.g., av1/common/onyxc_int.h or av1/common/buffer_pool.h):
+
+// Variant 1: Explicitly documents both encoding and decoding contexts
+// Index to the 'new' frame (i.e. the frame currently being encoded or
+// decoded) in the buffer pool 'cm->buffer_pool'.
+int new_fb_idx;
+
+// Variant 2: Exhaustively enumerates both encoder and decoder ref holders
+// For a RefCntBuffer, the following are reference-holding variables:
+// - cm->ref_frame_map[]
+// - cm->cur_frame
+// - cm->scaled_ref_buf[] (encoder only)
+// - pbi->output_frames[] / pbi->output_frame_index[] (decoder only)
+int ref_count;
+
+// Variant 3: Explicitly documents encoder-only scope and rationale
+// These variables are used only in encoder to compare absolute display
+// order hints and compute relative distance when old frames are referenced.
+unsigned int display_order_hint;
+unsigned int ref_display_order_hint[INTER_REFS_PER_FRAME];
+```
diff --git a/knowledge_base/rules/av1/document-speed-feature-levels-and-validation-checks.md b/knowledge_base/rules/av1/document-speed-feature-levels-and-validation-checks.md
new file mode 100644
index 0000000000..40f6bda2b6
--- /dev/null
+++ b/knowledge_base/rules/av1/document-speed-feature-levels-and-validation-checks.md
@@ -0,0 +1,63 @@
+---
+name: libaom/av1/document-speed-feature-levels-and-validation-checks
+description: When defining or modifying encoder speed features, heuristic flags, or search enums, document affected parameters, mode restrictions, pipeline stages, metric sources, and per-level fallback conditions
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** When defining or modifying encoder speed features, heuristic flags,
+thresholds, or search enums in SPEED_FEATURES structs and speed_features.h,
+document their exact behavior in comments. Specify the concrete encoder state or
+parameter being modified (e.g., rc_bits_per_mb) and the intended objective
+(e.g., reducing overshoot) rather than vague summaries. Explicitly document
+applicable pipeline stages (e.g., MODE_EVAL vs. WINNER_MODE_EVAL), operating
+mode restrictions (such as all-intra mode or keyframes only), interactions with
+base speed features, metric sources (e.g., estimated vs. measured RD costs), and
+valid values. For multi-level numeric speed features, document each numeric
+level with its exact evaluation conditions, which stages or calculations are
+skipped (e.g., start MV vs. final MV checks), and any fallback or redo behavior.
+
+**Why.** Vague comments like 'adjust the RC' or underspecified level summaries
+obscure algorithmic differences, evaluation timing, fallback re-searches, and
+pipeline stage constraints. Clear and comprehensive comments enable maintainers
+to safely tune, debug, and understand speed/quality tradeoffs without
+reverse-engineering heuristic implementations across multiple files.
+
+## Examples
+
+Bad:
+
+```cpp
+// For keyframes in rtc: adjust the RC based on content.
+int rc_adjust_keyframe;
+
+// Default Transform search case - used in evaluation of best inter candidates
+TX_SEARCH_DEFAULT = 0,
+// Transform search in motion mode rd
+TX_SEARCH_MOTION_MODE,
+
+// 0: Do not downsample rows
+// 1: Use SAD deviation of the even rows to odd rows as the metric to
+// downsample rows
+// 2: Downsample rows
+int use_downsampled_sad;
+```
+
+Good:
+
+```cpp
+// For keyframes in rtc: adjust the rc_bits_per_mb, to reduce overshoot.
+int rc_adjust_keyframe;
+
+// Default transform search used in evaluation of best inter candidates
+// (MODE_EVAL stage) and motion mode winner processing (WINNER_MODE_EVAL stage).
+TX_SEARCH_DEFAULT = 0,
+// Transform search in motion mode rd during MODE_EVAL stage.
+TX_SEARCH_MOTION_MODE,
+
+// 0: Disabled (do not downsample rows)
+// 1: Skip SAD calculation of odd rows if SAD deviation for start MV is small.
+// Redo motion search with sf off when SAD deviation is high for final MV.
+// 2: Skip SAD calculation of odd rows without start MV testing.
+int use_downsampled_sad;
+```
diff --git a/knowledge_base/rules/av1/explicit-block-size-checks-over-bitmasks.md b/knowledge_base/rules/av1/explicit-block-size-checks-over-bitmasks.md
new file mode 100644
index 0000000000..a81e0ce650
--- /dev/null
+++ b/knowledge_base/rules/av1/explicit-block-size-checks-over-bitmasks.md
@@ -0,0 +1,59 @@
+---
+name: libaom/av1/explicit-block-size-checks-over-bitmasks
+description: When checking block dimensions or buffer thresholds, use direct relational comparisons (>= 8) or explicit equality (w == 4) instead of bitwise masking or modulo
+rubric: readability
+severity: should_fix
+---
+
+**Rule.** When checking block dimensions, buffer sizes, or value thresholds
+(such as w, h, bw, bh, width, height, size, len, or stride) against boundary
+conditions or discrete power-of-two sizes, prefer direct relational comparisons
+(e.g., bw >= 8, width >= 16) or explicit equality checks (e.g., w == 4) rather
+than bitwise masking checks (e.g., !(bw & 0x07), !(w & 0x03), (width & 15) == 0)
+or modulo arithmetic (e.g., w % 4). Additionally, when a branch dispatches on a
+specific discrete block size in SIMD or DSP kernels, test that size directly
+with equality (e.g., w == 4) rather than using relational inequalities like w <=
+4 that imply unreachable sub-4 dimensions.
+
+**Why.** Relational comparisons (>=, >, <=, <) and explicit equality checks (==)
+directly communicate the intended dimension threshold or discrete block size
+requirement, making developer intent clear. Block dimensions in AV1 and DSP
+kernels are constrained to discrete power-of-two sizes with a minimum of 4
+(e.g., 4, 8, 16, 32, 64, 128); bitwise masking checks like !(w & 0x03) or
+inequalities like w <= 4 obscure intent by implying arbitrary multiples of 4 or
+non-existent sub-4 dimensions might be encountered. Compilers optimize
+relational power-of-two checks as efficiently as bitwise masks.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bitwise masking checks for block threshold and discrete size
+if (!(bw & 0x07)) {
+ process_8x8_block(src, dst);
+} else if (!(w & 0x03)) {
+ process_block_w4_neon(src, dst, w, h);
+}
+
+// Inequality check implying unreachable sub-4 block sizes
+if (w <= 4) {
+ process_block_w4_neon(src, dst, w, h);
+}
+```
+
+Good:
+
+```cpp
+// Direct relational threshold and explicit discrete size equality check
+if (bw >= 8) {
+ process_8x8_block(src, dst);
+} else if (w == 4) {
+ process_block_w4_neon(src, dst, w, h);
+}
+
+// Explicit equality check for discrete minimum 4-wide block
+if (w == 4) {
+ process_block_w4_neon(src, dst, w, h);
+}
+```
diff --git a/knowledge_base/rules/av1/hoist-scratch-buffer-allocations.md b/knowledge_base/rules/av1/hoist-scratch-buffer-allocations.md
new file mode 100644
index 0000000000..169d2b2db4
--- /dev/null
+++ b/knowledge_base/rules/av1/hoist-scratch-buffer-allocations.md
@@ -0,0 +1,62 @@
+---
+name: libaom/av1/hoist-scratch-buffer-allocations
+description: Avoid heap allocations in block-level or inner-loop routines by using bounded stack arrays or hoisting scratch buffers to frame or context setup
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** Avoid allocating and freeing dynamic heap memory (such as via
+malloc(), calloc(), aom_malloc(), or aom_memalign()) inside per-block,
+prediction, search, or inner-loop DSP/SIMD routines. For temporary buffers with
+bounded dimensions (e.g., maximum superblock size 128x128), use fixed-size
+stack-allocated arrays guarded by dimension assertions (e.g., assert(bw <= 128
+&& bh <= 128)). For large, aligned, or reusable scratch buffers (such as SIMD
+restoration unit stats buffers), hoist dynamic memory allocations to frame-,
+tile-, or search-level context structures (such as pick_lr_ctxt) and pass buffer
+pointers into processing kernels.
+
+**Why.** Performing dynamic memory allocation and deallocation inside per-block
+or inner-loop functions introduces substantial heap allocator overhead, system
+calls, cache penalties, and error-handling failure paths in performance-critical
+code paths. Fixed-size stack arrays provide fast, zero-allocation local storage
+for bounded block buffers, while hoisting allocations to frame or context setup
+amortizes allocation overhead across all blocks and eliminates per-block failure
+checks.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Dynamic heap allocation for a bounded prediction block
+uint8_t *pred_block = (uint8_t *)malloc(bw * bh * sizeof(uint8_t));
+if (!pred_block) return;
+generate_prediction(pred_block, bw, bh);
+free(pred_block);
+
+// Bad: Dynamic scratch memory allocation inside per-unit SIMD routine
+int16_t *dgd_avg = (int16_t *)aom_memalign(
+ 32, sizeof(*dgd_avg) * 6 * RESTORATION_UNITSIZE_MAX * RESTORATION_UNITSIZE_MAX);
+// ... compute stats ...
+aom_free(dgd_avg);
+```
+
+Good:
+
+```cpp
+// Good: Fixed-size stack array bounded by maximum superblock dimensions
+assert(bw <= 128 && bh <= 128);
+uint8_t pred_block[128 * 128];
+const int pred_block_stride = 128;
+generate_prediction(pred_block, bw, bh, pred_block_stride);
+
+// Good: Hoist scratch allocations to frame or context setup structures
+CHECK_MEM_ERROR(cm, cpi->pick_lr_ctxt.dgd_avg,
+ (int16_t *)aom_memalign(32, buf_size));
+rsc.dgd_avg = cpi->pick_lr_ctxt.dgd_avg;
+
+void av1_compute_stats_avx2(int wiener_win, const uint8_t *dgd, const uint8_t *src,
+ int16_t *dgd_avg, int16_t *src_avg, ...) {
+ // Use passed-in scratch buffers directly without allocating
+}
+```
diff --git a/knowledge_base/rules/av1/keep-encoder-only-code-in-encoder-directory.md b/knowledge_base/rules/av1/keep-encoder-only-code-in-encoder-directory.md
new file mode 100644
index 0000000000..187434c298
--- /dev/null
+++ b/knowledge_base/rules/av1/keep-encoder-only-code-in-encoder-directory.md
@@ -0,0 +1,76 @@
+---
+name: libaom/av1/keep-encoder-only-code-in-encoder-directory
+description: Keep encoder/decoder logic, state (AV1_COMP, MACROBLOCK), definitions, and macros in av1/encoder/ or av1/decoder/, and never include pipeline headers in av1/common/
+rubric: design
+severity: should_fix
+---
+
+**Rule.** Keep logic, state, definitions, and headers used exclusively by the
+encoder or decoder in dedicated pipeline directories and structs rather than in
+shared common files:
+
+1. **File and Header Boundaries**: Do not place encoder-only or decoder-only logic, helper functions, macros, constants, lookup tables, enums, structs, or experimental flags (such as rate control, first-pass analysis, search heuristics, RDO, or TPL) in `av1/common/`. Common files (`av1/common/*`) must never `#include` headers from `av1/encoder/` or `av1/decoder/`.
+2. **Codec- and Frame-Level State**: Place encoder-only state and configuration parameters (such as motion search history, speed features, rate control) in `AV1_COMP`, `AV1EncoderConfig`, or `ThreadData`, and decoder-only state in `AV1Decoder` or `AV1DecoderConfig`, reserving `AV1_COMMON` (`AV1Common`) strictly for shared codec data.
+3. **Block-Level State**: Place encoder-only search, mode evaluation, and rate-distortion state in `MACROBLOCK` (`macroblock`, `av1/encoder/block.h`), reserving `MACROBLOCKD` (`macroblockd`, `av1/common/blockd.h`) strictly for state shared with or required by the decoder.
+4. **Shared Code Consolidation**: Pass encoder optimization parameters into shared workers via worker context structs (e.g., `AV1CdefWorkerData`). Consolidate logic shared by both encoder and decoder in `av1/common/` using the `av1_` prefix rather than duplicating implementations across pipelines.
+
+**Why.** libaom supports standalone decoder-only and encoder-only builds while
+enforcing strict architectural separation of concerns. Placing encoder-only or
+decoder-only logic, macros, constants, lookup tables, or struct fields into
+shared locations (`av1/common/`, `AV1_COMMON`, `MACROBLOCKD`) introduces
+unwanted dependencies, pollutes shared interfaces, increases memory footprint
+for decoder instances, and bloats decoder-only binaries. Including encoder or
+decoder headers from `av1/common/` breaks modularity and build isolation.
+Conversely, duplicating shared helpers across `av1/encoder/` and `av1/decoder/`
+creates maintenance overhead and risks logic divergence.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern 1: Including encoder or decoder headers in common files
+// In av1/common/av1_common_int.h
+#include "av1/decoder/decoder.h"
+#include "av1/encoder/encoder.h"
+
+// Anti-pattern 2: Placing encoder-only macros, enums, tables, or state in common
+#define MAX_FIRSTPASS_ANALYSIS_FRAMES 150
+typedef enum { ENCODER_SEARCH_FAST, ENCODER_SEARCH_ACCURATE } ENCODER_SEARCH_MODE;
+static const uint16_t av1_derived_intra_tx_used_flag[INTRA_MODES] = { 0x0209, 0x0403 };
+
+typedef struct AV1Common {
+ FRAME_TYPE last_frame_type; // Bad: encoder-only motion search state
+} AV1Common;
+
+// Anti-pattern 3: Placing encoder-only block search state in MACROBLOCKD
+// In av1/common/blockd.h
+typedef struct macroblockd {
+ FRAME_CONTEXT *backup_tile_ctx; // Bad: encoder-only RD search state
+} MACROBLOCKD;
+```
+
+Good:
+
+```cpp
+// Pattern 1: Common headers include only common dependencies
+// In av1/common/av1_common_int.h
+#include "aom/aom_codec.h"
+#include "av1/common/enums.h"
+
+// Pattern 2: Encoder-only macros, enums, tables, and state in av1/encoder/
+// In av1/encoder/encoder.h or av1/encoder/firstpass.h
+#define MAX_FIRSTPASS_ANALYSIS_FRAMES 150
+typedef enum { ENCODER_SEARCH_FAST, ENCODER_SEARCH_ACCURATE } ENCODER_SEARCH_MODE;
+static const uint16_t av1_derived_intra_tx_used_flag[INTRA_MODES] = { 0x0209, 0x0403 };
+
+typedef struct AV1_COMP {
+ FRAME_TYPE last_frame_type; // Good: encoder search context
+} AV1_COMP;
+
+// Pattern 3: Encoder-only block search state in MACROBLOCK
+// In av1/encoder/block.h
+typedef struct macroblock {
+ FRAME_CONTEXT *backup_tile_ctx; // Good: encoder-only backup state
+} MACROBLOCK;
+```
diff --git a/knowledge_base/rules/av1/maintain-highbd-and-lowbd-counterpart-parity.md b/knowledge_base/rules/av1/maintain-highbd-and-lowbd-counterpart-parity.md
new file mode 100644
index 0000000000..7a4717993d
--- /dev/null
+++ b/knowledge_base/rules/av1/maintain-highbd-and-lowbd-counterpart-parity.md
@@ -0,0 +1,78 @@
+---
+name: libaom/av1/maintain-highbd-and-lowbd-counterpart-parity
+description: When implementing or updating high-bitdepth or low-bitdepth counterpart routines, keep function signatures, parameterization, buffer sizing, loop constructs, and algorithm logic synchronized
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When implementing, modifying, or refactoring high-bitdepth
+(`*_highbd`, `highbd_*`, `*_hbd`) or low-bitdepth (8-bit) counterpart functions
+across C, DSP, and SIMD implementations, keep their function signatures,
+parameterization, and structural implementation logic synchronized. Ensure that:
+1. Function signatures, parameters, and algorithmic logic remain in sync; do not retain hardcoded constants or outdated logic in one bit-depth path when the counterpart is updated to support dynamic parameters (such as block sizes or precision controls).
+2. Internal structures—including stack buffer dimensions, boundary padding formulas (e.g., `MAX_UPSAMPLE_SZ + 3`), loop constructs (`do-while` vs. `while`), and explanatory comments—mirror their counterpart rather than introducing ad-hoc sizes or divergent loop control when the underlying algorithm and vectorization structure are identical.
+
+**Why.** High-bitdepth and low-bitdepth processing routines mirror each other
+across prediction, motion estimation, filtering, and reconstruction pipelines.
+Divergence in signatures, parameters, loop control, or buffer sizing causes
+feature parity regressions, incorrect processing for high-bitdepth streams,
+cross-architecture review difficulties, and memory safety bugs from mismatched
+buffer padding.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Divergent signature and parameterization (hardcoded OF_BSIZE vs flexible n in lowbd)
+int opfl_mv_refinement_nxn_highbd(const uint16_t *p0, int pstride0,
+ const uint16_t *p1, int pstride1,
+ const int16_t *gx0, const int16_t *gy0,
+ const int16_t *gx1, const int16_t *gy1,
+ int gstride, int bw, int bh, int d0, int d1,
+ int grad_prec_bits, int mv_prec_bits,
+ int *vx0, int *vy0, int *vx1, int *vy1) {
+ assert(bw % OF_BSIZE == 0 && bh % OF_BSIZE == 0);
+ for (int i = 0; i < bh; i += OF_BSIZE) {
+ for (int j = 0; j < bw; j += OF_BSIZE) {
+ av1_opfl_mv_refinement_highbd(..., OF_BSIZE, OF_BSIZE, ...);
+ }
+ }
+}
+
+// Variant 2: Divergent stack buffer sizing and loop construct (diverging from 8-bit version)
+void av1_highbd_upsample_intra_edge_neon(uint16_t *p, int sz, int bd) {
+ uint16_t edge[141]; // Ad-hoc buffer size diverging from 8-bit formula
+ while (sz > 0) {
+ sz -= 8;
+ }
+}
+```
+
+Good:
+
+```cpp
+// Variant 1: Synchronized signature and flexible parameterization
+int opfl_mv_refinement_nxn_highbd(const uint16_t *p0, int pstride0,
+ const uint16_t *p1, int pstride1,
+ const int16_t *gx0, const int16_t *gy0,
+ const int16_t *gx1, const int16_t *gy1,
+ int gstride, int bw, int bh, int n, int d0,
+ int d1, int grad_prec_bits, int mv_prec_bits,
+ int *vx0, int *vy0, int *vx1, int *vy1) {
+ assert(bw % n == 0 && bh % n == 0);
+ for (int i = 0; i < bh; i += n) {
+ for (int j = 0; j < bw; j += n) {
+ av1_opfl_mv_refinement_highbd(..., n, n, ...);
+ }
+ }
+}
+
+// Variant 2: Normalized buffer sizing and loop construct matching lowbd counterpart
+void av1_highbd_upsample_intra_edge_neon(uint16_t *p, int sz, int bd) {
+ uint16_t edge[MAX_UPSAMPLE_SZ + 3]; // Identical padding and size formula
+ do {
+ sz -= 8;
+ } while (sz > 0);
+}
+```
diff --git a/knowledge_base/rules/av1/preserve-default-rate-control-tuning.md b/knowledge_base/rules/av1/preserve-default-rate-control-tuning.md
new file mode 100644
index 0000000000..15f86edac6
--- /dev/null
+++ b/knowledge_base/rules/av1/preserve-default-rate-control-tuning.md
@@ -0,0 +1,70 @@
+---
+name: libaom/av1/preserve-default-rate-control-tuning
+description: When modifying rate control or Q-clamping heuristics for specific modes or content types, guard them with explicit conditions like is_screen_content_type and preserve baseline fallbacks
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When adding or modifying rate control, Q clamping, or delta-QP
+heuristics intended for specific modes or content types (such as
+CYCLIC_REFRESH_AQ, SVC, or screen content), explicitly guard the logic with the
+appropriate condition (such as cpi->is_screen_content_type). Ensure
+mode-specific branches isolate their parameter calculations so baseline tuning
+and fallback calculations for standard camera content and unconfigured modes
+(such as NO_AQ) remain intact.
+
+**Why.** Rate control adjustments and Q clamping thresholds tuned specifically
+for screen content or adaptive quantization modes can cause severe rate
+overshoot, undershoot, or quality regressions on standard video if applied
+unconditionally or if baseline fallback calculations are accidentally
+overwritten.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Screen-specific CBR adjustment applied unconditionally
+if (!cpi->ppi->use_svc) {
+ if (p_rc->buffer_level > p_rc->optimal_buffer_level) {
+ max_delta_up = AOMMAX(4, max_delta_down);
+ } else {
+ max_delta_up = AOMMAX(8, max_delta_down);
+ }
+}
+
+// Variant 2: AQ mode adjustment overwriting baseline screen content fallback
+int max_delta_down = AOMMIN(16, AOMMAX(1, rc->q_1_frame / 8));
+if (use_cyclic_refresh && cpi->is_screen_content_type) {
+ if (cr->sb_index > cr->last_sb_index) {
+ max_delta_down = AOMMIN(8, AOMMAX(1, rc->q_1_frame / 32));
+ }
+}
+```
+
+Good:
+
+```cpp
+// Variant 1: Explicitly guarded by is_screen_content_type
+if (!cpi->ppi->use_svc && cpi->is_screen_content_type) {
+ if (p_rc->buffer_level > p_rc->optimal_buffer_level) {
+ max_delta_up = AOMMAX(4, max_delta_down);
+ } else {
+ max_delta_up = AOMMAX(8, max_delta_down);
+ }
+}
+
+// Variant 2: Explicit branching preserving baseline fallback
+if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
+ cpi->cyclic_refresh->apply_cyclic_refresh) {
+ max_delta_down = AOMMIN(16, AOMMAX(1, rc->q_1_frame / 8));
+ if (cpi->is_screen_content_type &&
+ cpi->cyclic_refresh->sb_index > cpi->cyclic_refresh->last_sb_index) {
+ max_delta_down = AOMMIN(8, AOMMAX(1, rc->q_1_frame / 32));
+ }
+} else {
+ max_delta_down = (cpi->is_screen_content_type)
+ ? AOMMIN(8, AOMMAX(1, rc->q_1_frame / 16))
+ : AOMMIN(16, AOMMAX(1, rc->q_1_frame / 8));
+}
+```
diff --git a/knowledge_base/rules/av1/separate-stage-multithreading-state.md b/knowledge_base/rules/av1/separate-stage-multithreading-state.md
new file mode 100644
index 0000000000..a23b07cec8
--- /dev/null
+++ b/knowledge_base/rules/av1/separate-stage-multithreading-state.md
@@ -0,0 +1,69 @@
+---
+name: libaom/av1/separate-stage-multithreading-state
+description: When adding encoder multi-threading state, isolate persistent stage state in dedicated structs and scope ephemeral synchronization and progress variables locally
+rubric: design
+severity: should_fix
+---
+
+**Rule.** When adding multi-threading state or synchronization callbacks for
+distinct encoder stages, isolate persistent state in dedicated stage-specific
+structs and AV1_COMP/AV1_PRIMARY members rather than general row multi-threading
+structures (such as AV1EncRowMultiThreadInfo). Additionally, do not store
+ephemeral synchronization structures, buffers, or transient error-recovery
+progress counters (such as prepared worker counts) on persistent context structs
+(like AV1_PRIMARY, AV1_COMP, or PrimaryMultiThreadInfo); declare them as local
+variables within the executing function and pass them as parameters to cleanup
+or restore helpers.
+
+**Why.** Encapsulating persistent stage-specific multi-threading state in
+dedicated structures avoids coupling independent pipeline passes and prevents
+monolithic context structs. Scoping ephemeral synchronization data and
+single-call progress state locally minimizes persistent struct size, prevents
+context state pollution, and clarifies variable lifetime and error-recovery
+ownership.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Mixing stage-specific MT callbacks into general encoder row-MT info:
+typedef struct {
+ void (*intra_sync_read_ptr)(AV1EncRowMultiThreadSync *const, int, int);
+} AV1EncRowMultiThreadInfo;
+
+// 2. Attaching ephemeral sync structures or transient progress state to persistent structs:
+typedef struct PrimaryMultiThreadInfo {
+ AV1EncRowMultiThreadSync intra_row_mt_sync;
+ int num_fpmt_workers_prepared;
+} PrimaryMultiThreadInfo;
+
+void prepare_fpmt_workers(AV1_PRIMARY *ppi, ...) {
+ ppi->p_mt_info.num_fpmt_workers_prepared = i;
+}
+```
+
+Good:
+
+```cpp
+// 1. Dedicated stage-specific struct and AV1_COMP member for persistent MT state:
+typedef struct {
+ void (*intra_sync_read_ptr)(AV1EncRowMultiThreadSync *const, int, int);
+} AV1EncAllIntraMultiThreadInfo;
+
+struct AV1_COMP {
+ AV1EncRowMultiThreadInfo enc_row_mt;
+ AV1EncAllIntraMultiThreadInfo intra_mt;
+};
+
+// 2. Declaring ephemeral sync structures and progress counters locally:
+void prepare_fpmt_workers(AV1_PRIMARY *ppi, ...) {
+ int num_fpmt_workers_prepared = 0;
+ if (setjmp(error->jmp)) {
+ restore_workers_after_fpmt(ppi, parallel_frame_count, num_fpmt_workers_prepared);
+ ...
+ }
+ ...
+ num_fpmt_workers_prepared = i;
+}
+```
diff --git a/knowledge_base/rules/av1/size-scratch-buffers-tightly.md b/knowledge_base/rules/av1/size-scratch-buffers-tightly.md
new file mode 100644
index 0000000000..6346efed31
--- /dev/null
+++ b/knowledge_base/rules/av1/size-scratch-buffers-tightly.md
@@ -0,0 +1,83 @@
+---
+name: libaom/av1/size-scratch-buffers-tightly
+description: When allocating heap, stack scratch, zero-reference, or SIMD intermediate buffers, size them tightly to required strides, strip widths, or maximum transform dimensions without unused padding.
+rubric: safety
+severity: should_fix
+---
+
+**Rule.** When allocating heap, stack scratch, prediction, zero-reference, or
+intermediate SIMD vector buffers, size dimensions tightly based on the actual
+required stride and block dimensions (e.g., using fixed subblock constants like
+SUBBLOCK_SIZE instead of MAX_SB_SIZE for fixed-size routines, or exact element
+counts for local vector arrays). In multi-pass SIMD filtering routines (such as
+2D convolution or Wiener filtering) that process blocks in column-wise strips,
+size intermediate stack buffers (e.g., im_block) to the active strip width (such
+as 8 or 4 columns) rather than the full superblock width (MAX_SB_SIZE).
+Additionally, ensure multi-size routines accommodate the maximum supported
+transform or block dimension (such as 64x8 vector registers for 64x64
+transforms) to prevent out-of-bounds writes. Do not allocate arbitrary oversized
+buffers or unused padding dimensions, remove obsolete comments describing former
+padding requirements, and document size derivations using named constants rather
+than magic numbers.
+
+**Why.** Over-allocating temporary scratch, stack, or zero-reference
+buffers—such as allocating full-superblock intermediate buffers ((MAX_SB_SIZE +
+taps) * MAX_SB_SIZE) when filtering data is consumed per column strip—causes
+stack frame bloat, wastes memory, and degrades data cache locality. Retaining
+unused padding or stale layout comments misleads maintainers about memory
+safety, stride calculations, and vector access invariants. Conversely,
+undersizing intermediate buffers causes out-of-bounds memory accesses and buffer
+overflows when handling maximum supported block dimensions.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Heap scratch buffer with arbitrary magic dimensions
+const int offset = 8;
+const int dst_buffer_stride = 128;
+const int buf_width = 256;
+const int buf_height = 256;
+CHECK_MEM_ERROR(cm, pred_buffer,
+ aom_memalign(32, buf_width * buf_height * sizeof(*pred_buffer)));
+
+// Variant 2: Column-strip SIMD intermediate buffer oversized to full superblock width
+DECLARE_ALIGNED(32, int16_t,
+ im_block[(MAX_SB_SIZE + MAX_FILTER_TAP - 1) * MAX_SB_SIZE]);
+
+// Variant 3: Undersized intermediate buffer for multi-size transform routines
+int16x8_t intermediate[32]; // Bad: Undersized for 64x64 transforms (requires 64*8)
+process_txfm_neon(input, intermediate, txfm_size);
+
+// Variant 4: Local SIMD buffer with unused padding or oversized zero-reference
+uint32_t frame_sse[(BW + 4) * BH] = { 0 };
+DECLARE_ALIGNED(16, static const uint8_t, av1_all_zeros[MAX_SB_SIZE]) = { 0 };
+```
+
+Good:
+
+```cpp
+// Variant 1: Sized tightly with documented named constants and strides
+#define MB_WIENER_PRED_BLOCK_SIZE BLOCK_128X128
+#define MB_WIENER_PRED_BUF_STRIDE 128
+const int offset = 8;
+const int buf_width = block_size_wide[MB_WIENER_PRED_BLOCK_SIZE];
+const int buf_height = block_size_high[MB_WIENER_PRED_BLOCK_SIZE] + 2 * offset;
+assert(buf_width == MB_WIENER_PRED_BUF_STRIDE);
+CHECK_MEM_ERROR(cm, pred_buffer,
+ aom_memalign(32, buf_width * buf_height * sizeof(*pred_buffer)));
+
+// Variant 2: Intermediate stack buffer sized tightly to active column strip width (e.g., 8)
+DECLARE_ALIGNED(32, int16_t,
+ im_block[(MAX_SB_SIZE + MAX_FILTER_TAP) * 8]);
+
+// Variant 3: Dimensioned to accommodate maximum supported 64x64 transform size
+int16x8_t intermediate[64 * 8];
+process_txfm_neon(input, intermediate, txfm_size);
+
+// Variant 4: Tight unpadded SIMD buffers and fixed subblock constants
+uint32_t frame_sse[BW * BH] = { 0 };
+#define SUBBLOCK_SIZE 8
+DECLARE_ALIGNED(16, static const uint8_t, av1_all_zeros[SUBBLOCK_SIZE]) = { 0 };
+```
diff --git a/knowledge_base/rules/av1/split-independent-speed-features.md b/knowledge_base/rules/av1/split-independent-speed-features.md
new file mode 100644
index 0000000000..c1260d3239
--- /dev/null
+++ b/knowledge_base/rules/av1/split-independent-speed-features.md
@@ -0,0 +1,44 @@
+---
+name: libaom/av1/split-independent-speed-features
+description: When modifying encoder speed features or fixing bugs, split independent feature adjustments and feature re-enablements into separate, focused CLs for isolated benchmarking
+rubric: change_scope
+severity: should_fix
+---
+
+**Rule.** Split independent speed feature tunings, heuristic adjustments, and
+bug fixes into separate, focused CLs rather than bundling them together. When
+fixing an underlying bug that previously necessitated disabling a speed feature
+or optimization, keep the fix self-contained and re-enable or tune the speed
+feature in a dedicated follow-up CL with isolated BD-rate and speedup benchmark
+results.
+
+**Why.** Bundling multiple unrelated speed feature changes or combining bug
+fixes with feature re-enablement obscures performance and quality trade-offs,
+complicates code review, introduces behavioral risk, and hinders git bisection
+during regression triage.
+
+## Examples
+
+Bad:
+
+```cpp
+// BAD: Bundling multiple unrelated speed feature changes in one CL:
+sf->gm_sf.num_refinement_steps = 0;
+sf->inter_sf.skip_repeated_ref_mv = 1;
+
+// BAD: Re-enabling a disabled speed feature within an underlying bug fix CL:
+// (In a CL fixing buffer allocation, prematurely removing a disablement guard):
+- if (cpi->svc.number_spatial_layers > 1) sf->rt_sf.use_rtc_tf = 0;
+```
+
+Good:
+
+```cpp
+// GOOD: Split unrelated speed feature tunings into dedicated, benchmarked CLs:
+sf->gm_sf.num_refinement_steps = 0;
+
+// GOOD: Keep bug fixes isolated; re-enable speed features in a follow-up CL:
+// (In the bug fix CL, retain the disablement guard):
+if (cpi->svc.number_spatial_layers > 1) sf->rt_sf.use_rtc_tf = 0;
+// (In a separate follow-up CL, remove the guard and attach BD-rate benchmarks).
+```
diff --git a/knowledge_base/rules/av1/sync-frame-resize-realloc-paths.md b/knowledge_base/rules/av1/sync-frame-resize-realloc-paths.md
new file mode 100644
index 0000000000..94d6eb2690
--- /dev/null
+++ b/knowledge_base/rules/av1/sync-frame-resize-realloc-paths.md
@@ -0,0 +1,65 @@
+---
+name: libaom/av1/sync-frame-resize-realloc-paths
+description: When updating buffer reallocation conditions or dimension tracking in encoder routines, synchronize all parallel execution paths (single-thread, tile MT, row MT, first pass) identically
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When modifying buffer reallocation checks, dimension tracking, or
+state initialization across encoder routines, ensure all parallel execution
+paths (single-threaded frame encode in encodeframe.c, tile multi-threading in
+av1_encode_tiles_mt, row multi-threading in av1_encode_tiles_row_mt /
+av1_row_mt_mem_alloc, and first-pass multi-threading in firstpass.c /
+first_pass_row_mt_mem_alloc) and entry points (such as av1_change_config(),
+set_size_literal(), or av1_check_initial_width()) are updated consistently.
+Verify that reallocation conditions (such as testing exact tile count mismatch
+allocated_tiles != tile_cols * tile_rows rather than <) match across all paths,
+and ensure dimension updates and setup reset flags (such as initial_dimensions
+and frame_size_related_setup_done) are synchronized when triggering compressor
+or segmentation map reallocations (alloc_compressor_data(),
+realloc_segmentation_maps(), av1_alloc_tile_data()).
+
+**Why.** Encoder logic is split across multiple independent single-threaded and
+multi-threaded pathways and passes that manage shared or parallel buffer
+allocations. If reallocation conditions diverge (e.g., checking only growth <
+instead of any mismatch !=), buffers become desynchronized from multi-threading
+synchronization structures (such as row_mt_sync) or skip required reallocations
+during dynamic resolution changes, leading to null-pointer dereferences, memory
+corruption, or stale configuration state.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern 1: Reallocation condition divergence across threading paths and passes
+// In ethread.c (av1_encode_tiles_row_mt): updated to check mismatch
+const bool alloc_tile_data = cpi->allocated_tiles != tile_cols * tile_rows;
+// In ethread.c (av1_encode_tiles_mt) and firstpass.c: missed update, still checks <
+const bool alloc_tile_data = cpi->allocated_tiles < tile_cols * tile_rows;
+
+// Anti-pattern 2: Omitting setup flag reset in parallel resize entry points
+if (cm->width > cpi->data_alloc_width || cm->height > cpi->data_alloc_height) {
+ alloc_compressor_data(cpi);
+ realloc_segmentation_maps(cpi);
+ cpi->initial_dimensions.width = cpi->initial_dimensions.height = 0;
+}
+```
+
+Good:
+
+```cpp
+// Pattern 1: Reallocation condition consistently updated across all parallel paths
+// In ethread.c (av1_encode_tiles_row_mt, av1_encode_tiles_mt) and firstpass.c:
+const bool alloc_tile_data = cpi->allocated_tiles != tile_cols * tile_rows;
+if (alloc_tile_data) av1_alloc_tile_data(cpi);
+
+// Pattern 2: Resize paths synchronized with matching dimension updates and flag resets
+if (cm->width > cpi->data_alloc_width || cm->height > cpi->data_alloc_height) {
+ alloc_compressor_data(cpi);
+ realloc_segmentation_maps(cpi);
+ cpi->initial_dimensions.width = cm->width;
+ cpi->initial_dimensions.height = cm->height;
+ cpi->frame_size_related_setup_done = false;
+}
+```
diff --git a/knowledge_base/rules/av1/terminate-workers-before-freeing-worker-arrays.md b/knowledge_base/rules/av1/terminate-workers-before-freeing-worker-arrays.md
new file mode 100644
index 0000000000..7a17afabff
--- /dev/null
+++ b/knowledge_base/rules/av1/terminate-workers-before-freeing-worker-arrays.md
@@ -0,0 +1,69 @@
+---
+name: libaom/av1/terminate-workers-before-freeing-worker-arrays
+description: When freeing or reconfiguring AVxWorker thread arrays, terminate active workers before freeing memory, and handle teardown at caller layers rather than inside creation helpers
+rubric: design
+severity: blocking
+---
+
+**Rule.** Before freeing or reallocating AVxWorker thread arrays or their
+associated context structures (such as p_mt_info.workers or tile_workers),
+explicitly terminate all active worker threads (e.g. calling
+av1_terminate_workers() or winterface->end()) and deallocate per-thread data.
+Additionally, perform worker teardown and reconfiguration at the caller or codec
+interface layer (e.g., av1_cx_iface.c) rather than embedding conditional
+teardown inside worker creation helpers (e.g., av1_create_workers()), keeping
+creation helpers focused solely on allocation and asserting an uninitialized
+state (assert(num_workers == 0)).
+
+**Why.** Freeing or reallocating AVxWorker structures while worker threads are
+active leaves background threads accessing deallocated memory and causes
+use-after-free crashes or data races. Embedding teardown inside creation helpers
+mixes lifecycle responsibilities and risks incomplete cleanup when dependent
+context and thread data must be coordinated by the caller.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern 1: Freeing worker array while threads may still be active
+if (p_mt_info->num_workers > 0) {
+ aom_free(p_mt_info->workers);
+ p_mt_info->workers = NULL;
+}
+
+// Anti-pattern 2: Embedding conditional teardown inside creation helper
+void av1_create_workers(AV1_PRIMARY *ppi, int num_workers) {
+ if (p_mt_info->num_workers > 0) {
+ av1_terminate_workers(ppi);
+ aom_free(p_mt_info->tile_thr_data);
+ p_mt_info->tile_thr_data = NULL;
+ aom_free(p_mt_info->workers);
+ p_mt_info->workers = NULL;
+ p_mt_info->num_workers = 0;
+ }
+ // Allocate new workers...
+}
+```
+
+Good:
+
+```cpp
+// In caller / codec interface layer (e.g., av1_cx_iface.c):
+if (ppi->p_mt_info.num_workers > 0) {
+ av1_terminate_workers(ppi);
+ free_thread_data(ppi);
+ aom_free(ppi->p_mt_info.tile_thr_data);
+ ppi->p_mt_info.tile_thr_data = NULL;
+ aom_free(ppi->p_mt_info.workers);
+ ppi->p_mt_info.workers = NULL;
+ ppi->p_mt_info.num_workers = 0;
+}
+av1_create_workers(ppi, num_workers);
+
+// In ethread.c (creation helper asserts uninitialized state):
+void av1_create_workers(AV1_PRIMARY *ppi, int num_workers) {
+ assert(p_mt_info->num_workers == 0);
+ // Allocate new workers...
+}
+```
diff --git a/knowledge_base/rules/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch.md b/knowledge_base/rules/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch.md
new file mode 100644
index 0000000000..523627d111
--- /dev/null
+++ b/knowledge_base/rules/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch.md
@@ -0,0 +1,59 @@
+---
+name: libaom/av1/use-capability-helper-or-flag-for-optimized-scaler-dispatch
+description: When gating dispatch to specialized or optimized routines like frame scalers, use centralized capability helpers and guard platform-specific ratios with architecture macros
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When gating dispatch to specialized or optimized routines (such as
+frame scalers or resize kernels), control execution using centralized capability
+helpers (such as av1_has_optimized_scaler()) or explicit flags rather than
+hardcoding dimension checks at call sites. Within capability query helpers,
+guard platform-specific parameters, ratios, or block sizes with matching
+architecture macros (such as #if HAVE_SSSE3 || HAVE_NEON) so unsupported
+platforms do not incorrectly report optimized availability.
+
+**Why.** Hardcoding dimension ratio checks at call sites duplicates logic and
+obscures intent. Query helpers that report optimized kernel availability without
+checking architecture macros (such as HAVE_SSSE3 or HAVE_NEON) cause unsupported
+platforms to take optimized branches that lack SIMD implementations or fall back
+incorrectly.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Hardcoding dimension ratio checks at call sites
+if (((cm->width << 1) == unscaled->y_crop_width &&
+ (cm->height << 1) == unscaled->y_crop_height)) {
+ av1_resize_and_extend_frame(unscaled, scaled, filter, phase, num_planes);
+}
+
+// Bad: Capability helper assumes platform support without architecture guards
+static inline bool av1_has_optimized_scaler(int src_w, int src_h,
+ int dst_w, int dst_h) {
+ return (dst_w * 4 == src_w * 3 && dst_h * 4 == src_h * 3);
+}
+```
+
+Good:
+
+```cpp
+// Good: Call sites check centralized capability helper and flag
+if (use_optimized_scaler &&
+ av1_has_optimized_scaler(unscaled->y_crop_width, unscaled->y_crop_height,
+ scaled->y_crop_width, scaled->y_crop_height)) {
+ av1_resize_and_extend_frame(unscaled, scaled, filter, phase, num_planes);
+}
+
+// Good: Capability helper guards platform-specific ratios with HAVE_* macros
+static inline bool av1_has_optimized_scaler(int src_w, int src_h,
+ int dst_w, int dst_h) {
+ bool has_scaler = false;
+#if HAVE_SSSE3 || HAVE_NEON
+ has_scaler = has_scaler || (4 * dst_w == 3 * src_w && 4 * dst_h == 3 * src_h);
+#endif
+ return has_scaler;
+}
+```
diff --git a/knowledge_base/rules/av1/use-exact-resolution-bounds-for-speed-features.md b/knowledge_base/rules/av1/use-exact-resolution-bounds-for-speed-features.md
new file mode 100644
index 0000000000..93f3c864b8
--- /dev/null
+++ b/knowledge_base/rules/av1/use-exact-resolution-bounds-for-speed-features.md
@@ -0,0 +1,62 @@
+---
+name: libaom/av1/use-exact-resolution-bounds-for-speed-features
+description: When gating encoder features by resolution using AOMMIN(width, height), specify exact short-edge lower and upper bounds (e.g., >= 720 && <= 1080) instead of unbounded, loose, or higher-tier thresholds
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** When defining resolution-dependent encoder speed features, presets, or
+mode conditions using AOMMIN(width, height) (such as AOMMIN(cfg->g_w, cfg->g_h)
+or AOMMIN(cm->width, cm->height)), specify explicit, exact short-edge lower and
+upper bounds matching tested resolution tiers (such as >= 720 && <= 1080 or >=
+608 && <= 1080). Do not use unbounded lower limits (such as >= 720 or
+is_720p_or_larger) that inadvertently enable features on higher unverified
+resolutions (such as 4K), loose/exclusive intervals (such as > 480 && < 1080)
+that miss target boundaries, or higher-tier/long-edge dimensions (such as < 2160
+instead of <= 1080 for 1080p content).
+
+**Why.** Encoder speed-versus-quality heuristics and presets are benchmarked on
+specific resolution tiers. Because AOMMIN(width, height) resolves to the
+short-edge dimension for both landscape (e.g., 1920x1080) and portrait (e.g.,
+1080x1920) orientations, resolution bounds must test against the target tier's
+short-edge threshold (such as <= 1080 for 1080p). Using higher-tier or long-edge
+values (such as < 2160) mistakenly enables features on intermediate classes like
+1440p (2560x1440, min dim 1440). Furthermore, omitting upper bounds (>= 720)
+allows heuristics to bleed into unverified 4K/UHD resolutions causing
+rate-distortion loss, while loose intervals (> 480 && < 1080) miss exact
+boundary cases or trigger on unverified resolutions.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Unbounded lower check bleeds into 4K/2160p; loose interval misidentifies bounds.
+const bool is_720p_or_larger = AOMMIN(cm->width, cm->height) >= 720;
+if (!is_vertical_video && is_720p_or_larger) {
+ sf->gm_sf.gm_erroradv_tr_level = 1;
+}
+
+// Bad: AOMMIN gives short edge (1080 for 1080p); '< 2160' mistakenly includes 1440p.
+const int is_low_complexity_decode_mode_supported =
+ (cfg->g_usage == AOM_USAGE_GOOD_QUALITY) &&
+ (oxcf->speed >= 1 && oxcf->speed <= 3) &&
+ (AOMMIN(cfg->g_w, cfg->g_h) >= 608 && AOMMIN(cfg->g_w, cfg->g_h) < 2160);
+```
+
+Good:
+
+```cpp
+// Good: Explicitly bound both lower and upper dimensions to tested ranges.
+const bool is_between_720p_and_1080p = AOMMIN(cm->width, cm->height) >= 720 &&
+ AOMMIN(cm->width, cm->height) <= 1080;
+if (!is_vertical_video && is_between_720p_and_1080p) {
+ sf->gm_sf.gm_erroradv_tr_level = 1;
+}
+
+// Good: Upper-bounding with short-edge '<= 1080' properly restricts up to 1080p.
+const int is_low_complexity_decode_mode_supported =
+ (cfg->g_usage == AOM_USAGE_GOOD_QUALITY) &&
+ (oxcf->speed >= 1 && oxcf->speed <= 3) &&
+ (AOMMIN(cfg->g_w, cfg->g_h) >= 608 && AOMMIN(cfg->g_w, cfg->g_h) <= 1080);
+```
diff --git a/knowledge_base/rules/av1/use-ppi-number-spatial-layers-for-sequence-config.md b/knowledge_base/rules/av1/use-ppi-number-spatial-layers-for-sequence-config.md
new file mode 100644
index 0000000000..0a560bfde5
--- /dev/null
+++ b/knowledge_base/rules/av1/use-ppi-number-spatial-layers-for-sequence-config.md
@@ -0,0 +1,67 @@
+---
+name: libaom/av1/use-ppi-number-spatial-layers-for-sequence-config
+description: When querying or validating layer counts for sequence configuration, superblock sizing, or codec controls, use ppi layer counts rather than uninitialized cpi->svc fields
+rubric: correctness
+severity: should_fix
+---
+
+**Rule.** Query and validate spatial and temporal layer counts via the primary
+compressor instance (ppi->number_spatial_layers, ppi->number_temporal_layers, or
+cpi->ppi->... / ctx->ppi->...) rather than sub-mode structures
+(cpi->svc.number_spatial_layers or cpi->svc.number_temporal_layers) when
+configuring sequence parameters, selecting superblock sizes
+(av1_select_sb_size), or bounds-checking layer ID parameters in codec control
+handlers (such as ctrl_set_spatial_layer_id or ctrl_set_layer_id). Reserve
+cpi->svc layer fields strictly for layer-specific SVC rate control and internal
+layer context state.
+
+**Why.** Primary compressor layer counts (ppi->number_spatial_layers and
+ppi->number_temporal_layers) are initialized at encoder creation and updated by
+both AOME_SET_NUMBER_SPATIAL_LAYERS and AV1E_SET_SVC_PARAMS. In contrast,
+sub-mode structures (cpi->svc) are only populated when full SVC parameters are
+configured and remain uninitialized or zero during early codec control calls or
+non-SVC multi-layer modes (such as progressive image encoding). Referencing
+cpi->svc for sequence configuration or control handlers results in incorrect
+superblock sizing or premature rejection of valid layer indices.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Sequence setup / superblock sizing: cpi->svc is unpopulated in non-SVC multi-layer
+set_sb_size(cm->seq_params,
+ av1_select_sb_size(&cpi->oxcf, cm->width, cm->height,
+ cpi->svc.number_spatial_layers));
+
+// 2. Control handlers: cpi->svc is uninitialized before full SVC setup
+static aom_codec_err_t ctrl_set_spatial_layer_id(aom_codec_alg_priv_t *ctx,
+ va_list args) {
+ const int id = va_arg(args, int);
+ if (id < 0 || id >= ctx->ppi->cpi->svc.number_spatial_layers) {
+ return AOM_CODEC_INVALID_PARAM;
+ }
+ ctx->ppi->cpi->common.spatial_layer_id = id;
+ return AOM_CODEC_OK;
+}
+```
+
+Good:
+
+```cpp
+// 1. Sequence setup / superblock sizing: use canonical ppi layer counts
+set_sb_size(cm->seq_params,
+ av1_select_sb_size(&cpi->oxcf, cm->width, cm->height,
+ cpi->ppi->number_spatial_layers));
+
+// 2. Control handlers: bounds-check against initialized primary compressor counts
+static aom_codec_err_t ctrl_set_spatial_layer_id(aom_codec_alg_priv_t *ctx,
+ va_list args) {
+ const int id = va_arg(args, int);
+ if (id < 0 || id >= (int)ctx->ppi->number_spatial_layers) {
+ return AOM_CODEC_INVALID_PARAM;
+ }
+ ctx->ppi->cpi->common.spatial_layer_id = id;
+ return AOM_CODEC_OK;
+}
+```
diff --git a/knowledge_base/rules/general/COMMON_METADATA b/knowledge_base/rules/general/COMMON_METADATA
new file mode 100644
index 0000000000..59033161f0
--- /dev/null
+++ b/knowledge_base/rules/general/COMMON_METADATA
@@ -0,0 +1,97 @@
+# Copyright (c) 2026, Alliance for Open Media. All rights reserved.
+#
+# This source code is subject to the terms of the BSD 2 Clause License and
+# the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+# was not distributed with this source code in the LICENSE file, you can
+# obtain it at www.aomedia.org/license/software. If the Alliance for Open
+# Media Patent License 1.0 was not distributed with this source code in the
+# PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+
+agentic_review {
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/arm-neon-guard-msvc-32bit-xn-intrinsics.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "apps/.*"
+ path_expression_exclusion: "examples/.*"
+ path_expression_exclusion: "test/.*"
+ path_expression_exclusion: "third_party/.*"
+ path_expression_exclusion: "tools/.*"
+ rules: "knowledge_base/rules/general/avoid-fatal-exit-in-library-code.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ rules: "knowledge_base/rules/general/avoid-log-on-zero-valued-metrics-use-log1p.md"
+ rules: "knowledge_base/rules/general/cast-subwords-to-unsigned-before-bitwise-packing.md"
+ rules: "knowledge_base/rules/general/initialize-all-output-parameters-in-stubs.md"
+ rules: "knowledge_base/rules/general/scale-allocation-by-element-sizeof.md"
+ rules: "knowledge_base/rules/general/update-buffer-alloc-size-only-on-realloc.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|inc)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/avoid-raw-compiler-attributes.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/check-memory-allocation-failure.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/clamp-floating-point-conversions-to-integer-limits.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom_dsp/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression: "aom_scale/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/document-reference-c-implementation-fallbacks.md"
+ }
+ capability_groups {
+ path_expression: "av1/decoder/.*"
+ path_expression: "av1/encoder/.*"
+ rules: "knowledge_base/rules/general/no-assert-for-untrusted-bitstream.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/no-top-level-const-on-function-params.md"
+ rules: "knowledge_base/rules/general/omit-redundant-narrowing-casts-on-wider-integers.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression_exclusion: "aom_dsp/aom_dsp_common\\.h"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/prefer-clamp-over-nested-min-max-macros.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "aom/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "av1/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ rules: "knowledge_base/rules/general/record-error-details-with-aom-set-error.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp)"
+ rules: "knowledge_base/rules/general/trailing-comment-on-endif-directives.md"
+ rules: "knowledge_base/rules/general/use-bool-for-boolean-flags-and-arrays.md"
+ rules: "knowledge_base/rules/general/use-sizeof-pointer-dereference-in-allocations.md"
+ }
+ capability_groups {
+ path_expression: "(?:.*/)?[^/]*\\.(?:c|cc|cpp|h)"
+ path_expression: "(?:.*/)?[^/]*_neon\\.[^/]*"
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "(?:.*/)?[^/]*arm[^/]*/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/(?:.*/)?[^/]*\\.(?:cc|cpp|h|hpp|mm)"
+ path_expression: "(?:.*/)?[^/]*neon[^/]*/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|mm)"
+ path_expression: "(?:.*/)?arm/(?:.*/)?[^/]*\\.(?:c|cc|cpp|h|hpp|mm)"
+ path_expression_exclusion: "third_party/.*"
+ rules: "knowledge_base/rules/general/use-neon-lane-intrinsics-not-vector-subscript.md"
+ }
+}
diff --git a/knowledge_base/rules/general/arm-neon-guard-msvc-32bit-xn-intrinsics.md b/knowledge_base/rules/general/arm-neon-guard-msvc-32bit-xn-intrinsics.md
new file mode 100644
index 0000000000..20a77aed89
--- /dev/null
+++ b/knowledge_base/rules/general/arm-neon-guard-msvc-32bit-xn-intrinsics.md
@@ -0,0 +1,76 @@
+---
+name: libaom/arm-neon-guard-msvc-32bit-xn-intrinsics
+description: When defining compiler fallback polyfills for ARM Neon multi-vector xN intrinsics, guard with exact major/minor compiler version checks and include 32-bit MSVC
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When defining compiler fallback polyfills or compatibility wrappers
+for ARM Neon multi-vector load/store intrinsics (such as `vld1q_*_xN` or
+`vst1q_*_xN`) or backported compiler intrinsics:
+1. Guard definitions with exact major and minor compiler version checks (such as `((__GNUC__ << 8) | __GNUC_MINOR__) < 0x805` or `__GNUC__ < 14`) rather than unconditional definitions or coarse major-only checks whenever native support was added in a specific minor/point release. Precede the fallback with a comment documenting the exact compiler version where native support was introduced.
+2. Include 32-bit MSVC targets (`(defined(__clang__) || defined(_MSC_VER)) && defined(ARM_32_BIT)` or `defined(_M_ARM)`), as MSVC implements Neon multi-vector intrinsics on AArch64 (`_M_ARM64`) but omits them on 32-bit ARM.
+
+**Why.** Newer compiler releases (such as GCC 14 or backports in GCC 8.5.0)
+provide native definitions for Neon xN intrinsics that were absent in older
+versions, causing duplicate symbol or conflicting declaration compiler errors if
+polyfills are defined unconditionally or guarded only by major version numbers.
+Conversely, 32-bit MSVC lacks multi-vector Neon intrinsics that are supported on
+64-bit MSVC (AArch64), causing unresolved identifier errors if 32-bit MSVC is
+excluded from the fallback definitions.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Omits 32-bit MSVC or unconditionally defines fallbacks for all GCC versions:
+#if defined(__GNUC__) && !defined(__clang__) && defined(ARM_32_BIT)
+#define GCC_32_BIT
+#endif
+
+#if defined(DEFICIENT_CLANG_32_BIT) || defined(GCC_32_BIT)
+static inline int16x8x4_t vld1q_s16_x4(const int16_t *ptr) {
+ // ...
+}
+#endif
+
+// 2. Coarse major-only guard causes conflicts on point release backports (e.g. GCC 8.5.0):
+#if __GNUC__ < 9
+static INLINE uint16x8x4_t vld1q_u16_x4(const uint16_t *ptr) {
+ uint16x8x4_t res = { { vld1q_u16(ptr + 0 * 8), vld1q_u16(ptr + 1 * 8),
+ vld1q_u16(ptr + 2 * 8), vld1q_u16(ptr + 3 * 8) } };
+ return res;
+}
+#endif
+```
+
+Good:
+
+```cpp
+// 1. Includes 32-bit MSVC and guards GCC with version thresholds:
+#if (defined(__clang__) || defined(_MSC_VER)) && defined(ARM_32_BIT)
+#define DEFICIENT_CLANG_32_BIT
+#endif
+
+#if defined(__GNUC__) && !defined(__clang__) && defined(ARM_32_BIT) && \
+ __GNUC__ < 14
+#define DEFICIENT_GCC_32_BIT
+#endif
+
+#if defined(DEFICIENT_CLANG_32_BIT) || defined(DEFICIENT_GCC_32_BIT)
+static inline int16x8x4_t vld1q_s16_x4(const int16_t *ptr) {
+ // ...
+}
+#endif
+
+// 2. Exact major and minor version guard for point release backports:
+// vld1q_u16_x4 is defined in GCC from 8.5.0 onwards:
+#if ((__GNUC__ << 8) | __GNUC_MINOR__) < 0x805
+static INLINE uint16x8x4_t vld1q_u16_x4(const uint16_t *ptr) {
+ uint16x8x4_t res = { { vld1q_u16(ptr + 0 * 8), vld1q_u16(ptr + 1 * 8),
+ vld1q_u16(ptr + 2 * 8), vld1q_u16(ptr + 3 * 8) } };
+ return res;
+}
+#endif
+```
diff --git a/knowledge_base/rules/general/avoid-fatal-exit-in-library-code.md b/knowledge_base/rules/general/avoid-fatal-exit-in-library-code.md
new file mode 100644
index 0000000000..02fbe8d953
--- /dev/null
+++ b/knowledge_base/rules/general/avoid-fatal-exit-in-library-code.md
@@ -0,0 +1,56 @@
+---
+name: libaom/avoid-fatal-exit-in-library-code
+description: When handling errors or allocation failures in library functions, return an error status or return early and free allocated resources instead of calling exit() or abort()
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** Do not call `exit()`, `abort()`, `_Exit()`, `quick_exit()`, or other
+process-terminating functions upon errors or memory allocation failures in
+library code. When an error or allocation failure occurs, release all locally
+allocated resources (such as via `aom_free()`) and return an error status (e.g.
+`AOM_CODEC_MEM_ERROR` or `0`) or return early to allow caller recovery.
+
+**Why.** libaom is compiled as a shared or static library embedded into external
+host applications. Abruptly terminating the process with `exit()` or `abort()`
+crashes the host application without allowing graceful error recovery, and
+failing to free locally allocated buffers before returning causes memory leaks
+on error paths.
+
+## Examples
+
+Bad:
+
+```cpp
+uint8_t *src_rgb = (uint8_t *)aom_malloc(buffer_size);
+uint8_t *dst_rgb = (uint8_t *)aom_malloc(buffer_size);
+if (!src_rgb || !dst_rgb) {
+ fprintf(stderr, "Fatal error: calculation failed.\n");
+ exit(EXIT_FAILURE);
+}
+
+uint16_t *im_block = (uint16_t *)aom_memalign(16, size);
+if (!im_block) {
+ abort();
+}
+```
+
+Good:
+
+```cpp
+uint8_t *src_rgb = (uint8_t *)aom_malloc(buffer_size);
+uint8_t *dst_rgb = (uint8_t *)aom_malloc(buffer_size);
+if (!src_rgb || !dst_rgb) {
+ aom_free(src_rgb);
+ aom_free(dst_rgb);
+ return 0;
+}
+
+uint16_t *im_block = (uint16_t *)aom_memalign(16, size);
+if (!im_block) return;
+uint16_t *im_block2 = (uint16_t *)aom_memalign(16, size);
+if (!im_block2) {
+ aom_free(im_block);
+ return;
+}
+```
diff --git a/knowledge_base/rules/general/avoid-log-on-zero-valued-metrics-use-log1p.md b/knowledge_base/rules/general/avoid-log-on-zero-valued-metrics-use-log1p.md
new file mode 100644
index 0000000000..76c7216e53
--- /dev/null
+++ b/knowledge_base/rules/general/avoid-log-on-zero-valued-metrics-use-log1p.md
@@ -0,0 +1,38 @@
+---
+name: libaom/avoid-log-on-zero-valued-metrics-use-log1p
+description: When computing logarithms of non-negative metrics or error statistics that can be zero, use log1p() or an offset instead of bare log() or ternary checks
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When calculating the logarithm of non-negative metrics, error values,
+distortion, variance, or statistics (such as coded_error, intra_error,
+log_energy, or frame_avg_wavelet_energy) that can be zero, use log1p(x) or
+log1pf(x) (or add an explicit offset such as log(x + 1.0)) rather than calling
+bare log() or using ternary/conditional checks against zero. Never pass
+unvalidated zeroable quantities directly into log().
+
+**Why.** Evaluating log(0.0) produces -INFINITY or mathematical domain errors,
+which corrupt floating-point accumulators and distort downstream rate control
+and distortion statistics. Furthermore, ternary zero checks (e.g., `x ? log(x) :
+0.0`) produce discontinuities and negative logarithms for fractional values in
+(0, 1). Using log1p(x) computes ln(1 + x) accurately, smoothly mapping 0.0 to
+0.0 without branching.
+
+## Examples
+
+Bad:
+
+```cpp
+// Direct log() produces -INFINITY when input is 0.0; ternary check yields negative logs for (0, 1)
+section->log_coded_error += log(frame->coded_error);
+section->log_intra_error += frame->intra_error ? log(frame->intra_error) : 0.0;
+```
+
+Good:
+
+```cpp
+// log1p(x) computes ln(1 + x), safely mapping 0.0 to 0.0 without branching
+section->log_coded_error += log1p(frame->coded_error);
+section->log_intra_error += log1p(frame->intra_error);
+```
diff --git a/knowledge_base/rules/general/avoid-raw-compiler-attributes.md b/knowledge_base/rules/general/avoid-raw-compiler-attributes.md
new file mode 100644
index 0000000000..8b214c76e6
--- /dev/null
+++ b/knowledge_base/rules/general/avoid-raw-compiler-attributes.md
@@ -0,0 +1,57 @@
+---
+name: libaom/avoid-raw-compiler-attributes
+description: When annotating functions or declaring aligned buffers, avoid raw `__attribute__((...))` or `__declspec(...)` syntax; use project portability macros such as `AOM_FORCE_INLINE` or `DECLARE_ALIGNED`
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** Do not use raw GNU/Clang or MSVC compiler attribute syntax such as
+`__attribute__((...))`, `__declspec(...)`, or `alignas` directly on functions,
+variables, or buffers in cross-platform source files. Use project-defined
+portability macros such as `AOM_FORCE_INLINE`, `AOM_INLINE`, `AOM_NO_RETURN`, or
+`DECLARE_ALIGNED(n, typ, val)` (from `aom_ports/mem.h`), or guard
+compiler-specific attributes with `#if defined(_MSC_VER)` / `#elif
+defined(__GNUC__)` checks to ensure cross-compiler compatibility across GCC,
+Clang, and Microsoft Visual Studio (MSVC). Ensure alignment boundaries `n`
+passed to `DECLARE_ALIGNED` match target SIMD vector widths (e.g., 16 bytes for
+SSE/NEON, 32 bytes for AVX2, or 64 bytes for AVX-512).
+
+**Why.** Libaom officially supports cross-platform builds across GCC, Clang, and
+Microsoft Visual C++ (MSVC). Raw compiler attributes such as
+`__attribute__((...))` or `__declspec(...)` cause syntax errors or build
+failures on non-matching toolchains. Project portability macros (like
+`AOM_FORCE_INLINE` and `DECLARE_ALIGNED`) encapsulate compiler-specific syntax
+portably.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Raw GCC/Clang attributes cause build failures under MSVC.
+static void __attribute__((noinline))
+dr_prediction_z2_Nx4_neon(int N, uint8_t *dst, ptrdiff_t stride);
+
+static __attribute__((always_inline)) int fast_calc(int x) {
+ return x * 2;
+}
+
+// Bad: Direct compiler alignment attribute breaks cross-platform builds.
+__attribute__((aligned(64))) uint16_t dstT[64 * 64];
+```
+
+Good:
+
+```cpp
+#include "aom_ports/mem.h"
+
+// Good: Use project portability macros or omit non-essential attributes.
+static void dr_prediction_z2_Nx4_neon(int N, uint8_t *dst, ptrdiff_t stride);
+
+static AOM_FORCE_INLINE int fast_calc(int x) {
+ return x * 2;
+}
+
+// Good: DECLARE_ALIGNED ensures portable alignment across GCC, Clang, and MSVC.
+DECLARE_ALIGNED(32, uint16_t, dstT[64 * 64]);
+```
diff --git a/knowledge_base/rules/general/cast-subwords-to-unsigned-before-bitwise-packing.md b/knowledge_base/rules/general/cast-subwords-to-unsigned-before-bitwise-packing.md
new file mode 100644
index 0000000000..93b1ff4a99
--- /dev/null
+++ b/knowledge_base/rules/general/cast-subwords-to-unsigned-before-bitwise-packing.md
@@ -0,0 +1,44 @@
+---
+name: libaom/cast-subwords-to-unsigned-before-bitwise-packing
+description: When bitwise packing sub-word integers or right-shifting SIMD-extracted scalar data, cast operands to unsigned types to prevent arithmetic sign-extension bugs
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When packing sub-word values (such as two 16-bit integers into a
+32-bit scalar or SIMD constant) via bitwise shifts and OR operations, or when
+right-shifting packed data extracted from SIMD registers (such as via
+_mm_cvtsi128_si32), explicitly cast the operands to unsigned types (such as
+uint16_t and uint32_t) before shifting. Do not perform bitwise left-shifts, ORs,
+or logical right-shifts on signed integer types.
+
+**Why.** In C and C++, right-shifting a signed integer performs an arithmetic
+shift (sign extension), corrupting upper sub-word values when the sign bit is
+set. Similarly, casting negative signed values to wider signed types fills upper
+bits with ones, corrupting bitwise ORed values, and left-shifting negative
+numbers is undefined behavior. Unsigned types guarantee zero-extension and
+well-defined logical bitwise shifts.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Signed operands cause sign-extension during bitwise packing and shifting
+#define pair_set_epi16(a, b) \
+ _mm_set1_epi32(((int32_t)((int16_t)(a))) | (((int32_t)(b)) << 16))
+
+int sum32 = _mm_cvtsi128_si32(sum);
+sum32 >>= 16; // Arithmetic shift: sign-extends if bit 31 is set
+```
+
+Good:
+
+```cpp
+// Good: Unsigned types ensure zero-extension and logical shift semantics
+#define pair_set_epi16(a, b) \
+ _mm_set1_epi32((int32_t)(((uint16_t)(a)) | (((uint32_t)(b)) << 16)))
+
+uint32_t sum32 = (uint32_t)_mm_cvtsi128_si32(sum);
+sum32 >>= 16; // Logical shift: preserves upper 16 bits without sign extension
+```
diff --git a/knowledge_base/rules/general/check-memory-allocation-failure.md b/knowledge_base/rules/general/check-memory-allocation-failure.md
new file mode 100644
index 0000000000..f91aabb10e
--- /dev/null
+++ b/knowledge_base/rules/general/check-memory-allocation-failure.md
@@ -0,0 +1,83 @@
+---
+name: libaom/check-memory-allocation-failure
+description: Validate dynamic memory allocations with runtime NULL checks or CHECK_MEM_ERROR rather than assert(), release resources on errors, and return fallible status
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** Always verify that return pointers from dynamic memory allocation
+functions (aom_malloc, aom_calloc, aom_memalign, aom_realloc, malloc, calloc,
+realloc) and opaque resource handles are non-NULL using runtime checks
+(CHECK_MEM_ERROR, AOM_CHECK_MEM_ERROR, explicit NULL checks, or abort()) rather
+than debug-only assert() or aom_assert(). In codec routines where an error
+context (AV1_COMMON *cm or struct aom_internal_error_info *error_info) is
+available, wrap allocations in CHECK_MEM_ERROR(cm, ptr, expr) or
+AOM_CHECK_MEM_ERROR(error_info, ptr, expr). On allocation failure, validation
+error, or early-exit path, explicitly release all locally allocated buffers
+(aom_free / free) and destroy acquired handles, or route execution through a
+shared cleanup label (goto fail; or goto cleanup;). Additionally, helper
+functions that perform dynamic memory allocation or fallible operations must
+return a status code (e.g., non-zero on success, zero on error, or an
+aom_codec_err_t) rather than returning void, and all call sites must check and
+handle the returned status. Never rely on assert() or aom_assert() for
+allocation checks since assertions are stripped in release builds when NDEBUG is
+defined.
+
+**Why.** Dynamic memory allocation and handle creation functions can return NULL
+upon memory exhaustion or invalid sizing. Dereferencing, indexing, or performing
+pointer arithmetic on unchecked pointers causes segmentation faults and
+undefined behavior. Relying on assert() or aom_assert() leaves release builds
+unprotected because assertions are compiled out when NDEBUG is defined. Using
+CHECK_MEM_ERROR or AOM_CHECK_MEM_ERROR raises aom_internal_error with
+AOM_CODEC_MEM_ERROR safely, while explicit runtime NULL checks combined with
+proper cleanup prevent progressive memory and handle leaks along error paths.
+Furthermore, returning void from fallible functions causes callers to proceed
+with uninitialized or invalid buffers, leading to silent data corruption or
+crashes.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Unchecked allocation or missing cleanup
+size_t size = width * height * 3;
+uint8_t *src_rgb = (uint8_t *)aom_malloc(size);
+uint8_t *dst_rgb = (uint8_t *)aom_malloc(size);
+I420ToRGB24Matrix(source->y_buffer, ..., src_rgb, dst_rgb);
+
+// Variant 2: assert() stripped in release builds with NDEBUG
+syms = realloc(syms, sizeof(Symbol) * count);
+assert(syms != NULL);
+
+// Variant 3: Leaking handle or void function ignoring allocation error
+JxlButteraugliApi *api = JxlButteraugliApiCreate(NULL);
+JxlButteraugliResult *res = JxlButteraugliCompute(api, ...);
+if (!res) return; // Leaks api handle and caller cannot detect error
+```
+
+Good:
+
+```cpp
+// Variant 1: Verify allocations, free prior buffers on failure
+size_t size = width * height * 3;
+uint8_t *src_rgb = (uint8_t *)aom_malloc(size);
+uint8_t *dst_rgb = (uint8_t *)aom_malloc(size);
+if (!src_rgb || !dst_rgb) {
+ aom_free(src_rgb);
+ aom_free(dst_rgb);
+ return 0;
+}
+
+// Variant 2: Explicit runtime check or abort() instead of assert
+syms = realloc(syms, sizeof(Symbol) * count);
+if (!syms) abort();
+
+// Variant 3: Clean up acquired handle and return fallible status code
+JxlButteraugliApi *api = JxlButteraugliApiCreate(NULL);
+JxlButteraugliResult *res = JxlButteraugliCompute(api, ...);
+if (!res) {
+ if (api) JxlButteraugliApiDestroy(api);
+ return 0;
+}
+```
diff --git a/knowledge_base/rules/general/clamp-floating-point-conversions-to-integer-limits.md b/knowledge_base/rules/general/clamp-floating-point-conversions-to-integer-limits.md
new file mode 100644
index 0000000000..d88f5d2e22
--- /dev/null
+++ b/knowledge_base/rules/general/clamp-floating-point-conversions-to-integer-limits.md
@@ -0,0 +1,58 @@
+---
+name: libaom/clamp-floating-point-conversions-to-integer-limits
+description: When casting floating-point expressions or 64-bit integers to narrower integer types, clamp values to target bounds using AOMMIN or saturate_cast_double_to_int to avoid overflow
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When casting floating-point calculations (such as values from ceil(),
+floor(), round(), or rate-control formulas) or wider integer variables (such as
+int64_t rate-distortion multipliers, frame targets, bit budgets, or
+accumulators) to narrower integer types (like int or unsigned int), clamp values
+to target integer limits using AOMMIN(..., INT_MAX) or
+saturate_cast_double_to_int() before casting. Verify that scaled values or
+multi-step accumulations cannot exceed INT_MAX (or [INT_MIN, INT_MAX]) and wrap
+or trigger undefined behavior.
+
+**Why.** In C and C++, converting a floating-point value that exceeds the target
+integer type's representable range (greater than INT_MAX or less than INT_MIN)
+results in undefined behavior. Similarly, casting out-of-range int64_t values
+directly to signed 32-bit int causes signed integer overflow and undefined
+behavior, leading to negative rate-distortion multipliers, corrupted bit
+budgets, or runtime errors. Clamping or saturating prior to casting guarantees
+well-defined, range-safe conversions.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Casting unbounded floating-point calculation directly to int
+rc->max_consec_drop = (int)ceil(cpi->oxcf.rc_cfg.max_consec_drop_time *
+ cpi->framerate / 1000);
+
+// Bad: Direct cast of unbounded wide 64-bit integer / rate calculation to int
+int64_t rdmult = av1_compute_rd_mult_based_on_qindex(bit_depth, update_type,
+ qindex, tuning);
+rdmult = (rdmult * rd_layer_depth_factor[layer_depth]) >> 7;
+rdmult += ((rdmult * rd_boost_factor[boost_index]) >> 7);
+return (int)rdmult;
+```
+
+Good:
+
+```cpp
+// Good: Clamping floating-point result or using saturation helper
+rc->max_consec_drop = (int)AOMMIN(
+ ceil(cpi->oxcf.rc_cfg.max_consec_drop_ms * cpi->framerate / 1000),
+ INT_MAX);
+rc->max_consec_drop = saturate_cast_double_to_int(
+ ceil(cpi->oxcf.rc_cfg.max_consec_drop_ms * cpi->framerate / 1000));
+
+// Good: Clamping 64-bit integer to INT_MAX before casting to int
+int64_t rdmult = av1_compute_rd_mult_based_on_qindex(bit_depth, update_type,
+ qindex, tuning);
+rdmult = (rdmult * rd_layer_depth_factor[layer_depth]) >> 7;
+rdmult += ((rdmult * rd_boost_factor[boost_index]) >> 7);
+return rdmult > 0 ? (int)AOMMIN(rdmult, INT_MAX) : 1;
+```
diff --git a/knowledge_base/rules/general/document-reference-c-implementation-fallbacks.md b/knowledge_base/rules/general/document-reference-c-implementation-fallbacks.md
new file mode 100644
index 0000000000..b04f558361
--- /dev/null
+++ b/knowledge_base/rules/general/document-reference-c-implementation-fallbacks.md
@@ -0,0 +1,112 @@
+---
+name: libaom/document-reference-c-implementation-fallbacks
+description: When implementing partial SIMD kernels or dispatchers, guard unsupported parameters at entry, fall back to lower-tier SIMD or scalar C, return immediately, and add attributed TODOs
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When relaxing caller dispatch conditions or implementing SIMD routines
+and dispatchers with partial parameter or dimension support (such as minimum
+vector step sizes like 4, 8, or 16 pixels, filter tap counts, block dimensions,
+or window lengths):
+1. Preserve caller guard checks and do not replace conditional dispatch with unconditional SIMD calls when only a subset of configurations is optimized.
+2. Inside SIMD kernels, guard unsupported configurations at function entry before allocating intermediate buffers or performing preprocessing calculations, routing execution safely rather than asserting on expanded RTCD inputs.
+3. Fall back to available lower-tier SIMD implementations (e.g., SSSE3, SSE4.1, or SSE2 from AVX2/AVX-512) before falling back to the scalar C reference implementation (*_c).
+4. When delegating to scalar C or lower-tier fallback functions, immediately return or use an else branch to prevent execution from falling through into vector processing code.
+5. Always document fallback constraints with explanatory comments and include attributed TODO comments with tracking issue numbers (e.g., // TODO(aomedia:XXXX): ...) for deferred or missing SIMD optimizations.
+
+**Why.** SIMD intrinsic kernels assume fixed vector widths, specific tap counts,
+or aligned block sizes; invoking them on sub-vector dimensions or unsupported
+parameter configurations causes buffer overruns, undefined behavior, or
+assertion failures. Omitting an immediate return after fallback delegation
+causes dangerous fallthrough into vector code, leading to duplicate work and
+memory corruption. In higher-tier kernels (e.g., AVX2), delegating unsupported
+cases to lower-tier SIMD (e.g., SSSE3) preserves vectorization performance
+rather than falling off a scalar performance cliff. Dispatching at function
+entry avoids wasted setup computations, and documenting deferred paths with
+attributed TODOs ensures missing SIMD coverage is properly tracked.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Falling back directly to scalar C from AVX2 instead of lower-tier SIMD (SSSE3)
+if (filter_params_x->taps == 12) {
+ av1_highbd_convolve_x_sr_c(src, src_stride, dst, dst_stride, w, h,
+ filter_params_x, subpel_x_qn, conv_params, bd);
+ return;
+}
+
+// Variant 2: Missing dimension guard and missing return after fallback (fallthrough bug)
+if (filter_params_x->taps > 8) {
+ av1_convolve_x_sr_12tap_sse2(src, src_stride, dst, dst_stride, w, h,
+ filter_params_x, subpel_x_qn, conv_params);
+}
+if (filtered_length < 16) {
+ av1_resize_horz_dir_c(input, in_stride, intbuf, height, filtered_length,
+ width2);
+ // Missing return: falls through into SSE2 vector processing!
+}
+
+// Variant 3: Wasted buffer setup before C fallback, asserting, and missing attributed TODO
+void av1_compute_stats_avx2(int wiener_win, const uint8_t *dgd, ...) {
+ sub_avg_block_avx2(dgd, ...); // Wasted work if wiener_win is unsupported
+ if (wiener_win == WIENER_WIN) {
+ compute_stats_win7_avx2(...);
+ } else {
+ av1_compute_stats_c(wiener_win, dgd, ...);
+ }
+}
+
+void av1_apply_temporal_filter_neon(...) {
+ // Asserts instead of falling back to C for newly supported 64x64 block size
+ assert(block_size == BLOCK_32X32 && "Only support 32x32 block with Neon!");
+}
+```
+
+Good:
+
+```cpp
+// Variant 1: Fall back to lower-tier SIMD (SSSE3) before scalar C reference
+if (filter_params_x->taps == 12) {
+ av1_highbd_convolve_x_sr_ssse3(src, src_stride, dst, dst_stride, w, h,
+ filter_params_x, subpel_x_qn, conv_params, bd);
+ return;
+}
+
+// Variant 2: Guard sub-vector dimensions and return immediately after fallback
+if (filter_params_x->taps > 8) {
+ if (w < 4) {
+ av1_convolve_x_sr_c(src, src_stride, dst, dst_stride, w, h,
+ filter_params_x, subpel_x_qn, conv_params);
+ } else {
+ av1_convolve_x_sr_12tap_sse2(src, src_stride, dst, dst_stride, w, h,
+ filter_params_x, subpel_x_qn, conv_params);
+ }
+}
+if (filtered_length < 16) {
+ av1_resize_horz_dir_c(input, in_stride, intbuf, height, filtered_length,
+ width2);
+ return;
+}
+
+// Variant 3: Fall back at entry before work, and document with attributed TODO
+void av1_compute_stats_avx2(int wiener_win, const uint8_t *dgd, ...) {
+ if (wiener_win != WIENER_WIN && wiener_win != WIENER_WIN_CHROMA) {
+ av1_compute_stats_c(wiener_win, dgd, ...);
+ return;
+ }
+ sub_avg_block_avx2(dgd, ...);
+ compute_stats_win7_avx2(...);
+}
+
+// TODO(aomedia:493082083): Modify temporal filter to support 64x64 block size with Neon.
+void av1_apply_temporal_filter_neon(...) {
+ if (block_size == BLOCK_64X64) {
+ av1_apply_temporal_filter_c(frame_to_filter, mbd, block_size, ...);
+ return;
+ }
+ assert(block_size == BLOCK_32X32 && "Only support 32x32 block with Neon!");
+}
+```
diff --git a/knowledge_base/rules/general/initialize-all-output-parameters-in-stubs.md b/knowledge_base/rules/general/initialize-all-output-parameters-in-stubs.md
new file mode 100644
index 0000000000..f6f83b8186
--- /dev/null
+++ b/knowledge_base/rules/general/initialize-all-output-parameters-in-stubs.md
@@ -0,0 +1,84 @@
+---
+name: libaom/initialize-all-output-parameters-in-stubs
+description: Unconditionally initialize or populate all output pointer parameters at function entry, across all branches and stubs, and via direct boolean expressions without caller pre-initialization
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When defining or implementing functions with output pointer
+parameters, ensure all output parameters are unconditionally initialized and
+populated across all execution paths without relying on callers to
+pre-initialize dummy values:
+1. **Function entry and early returns**: Explicitly initialize or reset all out-parameters (e.g., to 0, NULL, false, or a clean default state) at the start of the function body before processing or early returns, ensuring no output pointer is left unmodified if no data is produced.
+2. **Stubs, fallbacks, and callbacks**: In stub, mock, fallback, or alternative implementations matching a function pointer interface (e.g., `av1_return_max_sub_pixel_mv`), explicitly assign valid values to every output pointer parameter (e.g., `*distortion`, `*sse1`, `*bestmv`) rather than omitting them (such as via `(void)param;`) and forcing callers to mask uninitialized reads with dummy values.
+3. **Boolean and flag outputs**: Unconditionally assign evaluated boolean expressions directly to the output pointer (e.g., `*use_scaled_ref = ref_is_scaled && scaled_ref;`) rather than conditionally assigning only on true paths (e.g., `if (condition) *out_param = 1;`), which leaves the destination unassigned on false paths.
+
+**Why.** Functions taking output pointer parameters must maintain
+self-contained, deterministic contracts without assuming callers pre-initialized
+variables. Omitting assignments on early exits, false branches, or in stub
+implementations leaves caller stack or heap memory uninitialized, leading to
+non-deterministic execution and sanitizer/Valgrind warnings. Masking these
+warnings with dummy caller-side initializations hides callee contract violations
+and conceals missing data across implementations. Direct unconditional
+assignment guarantees deterministic state on all paths while simplifying
+branching.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Incomplete reset at function entry / early exit:
+static void get_cx_data(struct stream_state *stream,
+ struct AvxEncoderConfig *global, int *got_data,
+ size_t *frame_size) {
+ *got_data = 0;
+ // *frame_size is not reset at entry; caller risks reading stale value
+ if (!stream) return;
+ *frame_size = 100;
+}
+
+// 2. Stub/fallback ignoring out-parameters, forcing caller dummy init:
+int av1_return_max_sub_pixel_mv(..., MV *bestmv, int *distortion,
+ unsigned int *sse1, ...) {
+ (void)distortion; // leaves *distortion unassigned
+ *sse1 = besterr;
+ return besterr;
+}
+
+// 3. Conditional boolean assignment leaving false path uninitialized:
+void check_scaled_reference(int ref_is_scaled, int scaled_ref,
+ bool *use_scaled_ref) {
+ if (ref_is_scaled && scaled_ref) {
+ *use_scaled_ref = 1; // unassigned when condition is false
+ }
+}
+```
+
+Good:
+
+```cpp
+// 1. Explicitly reset all out-parameters at function entry:
+static void get_cx_data(struct stream_state *stream,
+ struct AvxEncoderConfig *global, int *got_data,
+ size_t *frame_size) {
+ *got_data = 0;
+ *frame_size = 0;
+ if (!stream) return;
+ *frame_size = 100;
+}
+
+// 2. Stub/fallback explicitly populating all out-parameters:
+int av1_return_max_sub_pixel_mv(..., MV *bestmv, int *distortion,
+ unsigned int *sse1, ...) {
+ *distortion = besterr;
+ *sse1 = besterr;
+ return besterr;
+}
+
+// 3. Unconditionally assign evaluated boolean expression:
+void check_scaled_reference(int ref_is_scaled, int scaled_ref,
+ bool *use_scaled_ref) {
+ *use_scaled_ref = ref_is_scaled && scaled_ref;
+}
+```
diff --git a/knowledge_base/rules/general/no-assert-for-untrusted-bitstream.md b/knowledge_base/rules/general/no-assert-for-untrusted-bitstream.md
new file mode 100644
index 0000000000..469524fafa
--- /dev/null
+++ b/knowledge_base/rules/general/no-assert-for-untrusted-bitstream.md
@@ -0,0 +1,44 @@
+---
+name: libaom/no-assert-for-untrusted-bitstream
+description: When validating untrusted bitstream syntax, sequence headers, tile parameters, or operating points, use runtime error returns or aom_internal_error rather than assert()
+rubric: safety
+severity: blocking
+---
+
+**Rule.** Do not use assert(), aom_assert(), or debug-only assertions to
+validate untrusted bitstream syntax, sequence headers, operating points, tile
+parameters, or external stream data. Reject invalid or unsupported bitstream
+values through standard runtime control flow, calling aom_internal_error() with
+appropriate error codes (such as AOM_CODEC_CORRUPT_FRAME or
+AOM_CODEC_UNSUP_BITSTREAM) or returning an error status code explicitly.
+
+**Why.** Bitstreams are external, untrusted inputs. Assertions verify internal
+programmer invariants and are stripped in release builds when NDEBUG is defined,
+leaving malformed bitstreams unchecked and causing memory corruption or
+undefined behavior in production. In debug or fuzzing builds, assertion failures
+trigger spurious crashes and denial-of-service failures instead of clean codec
+error propagation.
+
+## Examples
+
+Bad:
+
+```cpp
+// Asserting on untrusted bitstream headers or operating points:
+assert(i == 0 || use_level_7_above);
+aom_assert(tile_info->tile_columns <= MAX_TILE_COLS);
+```
+
+Good:
+
+```cpp
+// Validating untrusted bitstream data with runtime error handling:
+if (i != 0 && !use_level_7_above) {
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid operating point level configuration");
+}
+if (tile_info->tile_columns > MAX_TILE_COLS) {
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Unsupported tile columns count");
+}
+```
diff --git a/knowledge_base/rules/general/no-top-level-const-on-function-params.md b/knowledge_base/rules/general/no-top-level-const-on-function-params.md
new file mode 100644
index 0000000000..755739988a
--- /dev/null
+++ b/knowledge_base/rules/general/no-top-level-const-on-function-params.md
@@ -0,0 +1,54 @@
+---
+name: libaom/no-top-level-const-on-function-params
+description: When declaring or defining functions, omit top-level const qualifiers on pass-by-value scalar parameters and pointer parameters like const int or Type *const
+rubric: readability
+severity: blocking
+---
+
+**Rule.** In function declarations, prototypes, and definitions, do not use
+top-level const qualifiers on pass-by-value scalar parameters (such as int,
+size_t, ptrdiff_t, uint8_t, tran_low_t, or enum/typedef values like width,
+height, stride, log_bw) or on pointer parameters (Type *const param). Pass
+scalar parameters by plain unmodified value and pointers as Type *param (or
+const Type *param for pointer-to-const data).
+
+**Why.** Top-level const on pass-by-value scalar parameters or pointer
+parameters is an internal callee implementation detail that provides no
+caller-facing interface guarantee or optimization benefit. It adds visual
+clutter to function signatures, causes unnecessary discrepancies between header
+declarations, RTCD definitions, and C implementations, and violates readability
+conventions (e.g. clang-tidy readability-avoid-const-params-in-decls).
+
+## Examples
+
+Bad:
+
+```cpp
+void aom_smooth_h_predictor_32x8_ssse3(uint8_t *LIBAOM_RESTRICT dest,
+ const ptrdiff_t stride,
+ const uint8_t *LIBAOM_RESTRICT top_row,
+ const uint8_t *LIBAOM_RESTRICT left_column);
+
+bool av1_use_qmatrix(const struct CommonQuantParams *quant_params,
+ const struct macroblockd *const xd,
+ const int segment_id);
+
+int aom_vector_var_avx2(const int16_t *ref, const int16_t *src,
+ const int log_bw);
+```
+
+Good:
+
+```cpp
+void aom_smooth_h_predictor_32x8_ssse3(uint8_t *LIBAOM_RESTRICT dest,
+ ptrdiff_t stride,
+ const uint8_t *LIBAOM_RESTRICT top_row,
+ const uint8_t *LIBAOM_RESTRICT left_column);
+
+bool av1_use_qmatrix(const struct CommonQuantParams *quant_params,
+ const struct macroblockd *xd,
+ int segment_id);
+
+int aom_vector_var_avx2(const int16_t *ref, const int16_t *src,
+ int log_bw);
+```
diff --git a/knowledge_base/rules/general/omit-redundant-narrowing-casts-on-wider-integers.md b/knowledge_base/rules/general/omit-redundant-narrowing-casts-on-wider-integers.md
new file mode 100644
index 0000000000..c663171dd9
--- /dev/null
+++ b/knowledge_base/rules/general/omit-redundant-narrowing-casts-on-wider-integers.md
@@ -0,0 +1,51 @@
+---
+name: libaom/omit-redundant-narrowing-casts-on-wider-integers
+description: When computing or accumulating expressions assigned to int64_t variables, avoid premature (int) truncation casts or redundant widening casts
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** Do not insert narrowing integer casts (such as `(int)` or `(int32_t)`)
+when computing expressions assigned to wider integer variables (such as
+`int64_t`) or passed to helpers expecting wider integers; cast intermediate
+floating-point calculations to `int64_t` rather than `int` to prevent premature
+32-bit truncation. Additionally, do not add redundant widening casts (such as
+`(int64_t)`) when accumulating, subtracting, or assigning narrower integers into
+wider variables, as implicit integer promotion already converts the operands.
+
+**Why.** Narrowing intermediate 64-bit or floating-point expressions with 32-bit
+`(int)` casts prematurely truncates values exceeding `INT_MAX`, risking integer
+overflow, precision loss, and visual clutter before downstream clamping or
+scaling. Conversely, explicit widening casts in compound assignments or
+arithmetic with wider variables add unnecessary clutter without altering
+promotion semantics.
+
+## Examples
+
+Bad:
+
+```cpp
+// Redundant narrowing cast on intermediate 64-bit calculation
+int64_t target = (int)(((int64_t)(16 + kf_boost) * rc->avg_frame_bandwidth) >> 4);
+target = clamp_iframe_target_size(cpi, target);
+
+// Premature 32-bit cast on intermediate floating-point calculation
+int64_t rdmult = (int)((double)rdmult * weight / 128.0);
+
+// Redundant widening cast when accumulating into wider integer
+p_rc->bits_off_target -= (int64_t)encoded_frame_size;
+```
+
+Good:
+
+```cpp
+// Intermediate calculation kept in wider int64_t type
+int64_t target = ((int64_t)(16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
+target = clamp_iframe_target_size(cpi, target);
+
+// Cast floating-point result directly to int64_t to prevent truncation
+int64_t rdmult = (int64_t)((double)rdmult * weight / 128.0);
+
+// Implicit promotion converts operand cleanly
+p_rc->bits_off_target -= encoded_frame_size;
+```
diff --git a/knowledge_base/rules/general/prefer-clamp-over-nested-min-max-macros.md b/knowledge_base/rules/general/prefer-clamp-over-nested-min-max-macros.md
new file mode 100644
index 0000000000..1aebf4ab3f
--- /dev/null
+++ b/knowledge_base/rules/general/prefer-clamp-over-nested-min-max-macros.md
@@ -0,0 +1,52 @@
+---
+name: libaom/prefer-clamp-over-nested-min-max-macros
+description: When constraining values to a range, use clamp(), clamp64(), fclamp(), or clip_pixel() instead of nested AOMMIN/AOMMAX macros, ensuring low <= high for dynamic bounds
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When constraining integer, 64-bit, floating-point, or pixel values
+between lower and upper limits, use standard inline helper functions clamp()
+(for int), clamp64() (for int64_t), fclamp() (for double/float), or clip_pixel()
+/ clip_pixel_highbd() from aom_dsp/aom_dsp_common.h rather than nesting or
+chaining AOMMIN and AOMMAX macros. Additionally, when bounds are computed
+dynamically and could invert (low > high), ensure low <= high holds or sanitize
+the upper/lower bounds with AOMMAX/AOMMIN prior to calling clamp().
+
+**Why.** AOMMIN and AOMMAX macros evaluate their arguments multiple times,
+risking redundant computation and accidental side effects with complex
+expressions. The inline helper functions evaluate arguments exactly once,
+provide type safety, and improve readability across the codebase. Furthermore,
+clamp(val, low, high) is implemented assuming low <= high; if dynamic bounds
+invert (low > high), calling clamp() will produce values outside the intended
+upper bound.
+
+## Examples
+
+Bad:
+
+```cpp
+// Nested macro calls cause redundant evaluations and side effects
+const int val = AOMMAX(0, AOMMIN(QINDEX_RANGE - 1, input_val));
+const double fval = AOMMAX(0.0, AOMMIN(1.0, rate_factor));
+
+// Chained macros evaluate expressions multiple times
+mv_limits->row_min = AOMMAX(mv_limits->row_min, -top_margin);
+mv_limits->row_min = AOMMIN(mv_limits->row_min, mv_limits->row_max);
+
+// If dynamic bounds can invert (-top_margin > row_max), clamp returns -top_margin (> row_max)
+mv_limits->row_min = clamp(mv_limits->row_min, -top_margin, mv_limits->row_max);
+```
+
+Good:
+
+```cpp
+// Use inline helpers for concise, single-evaluation bounding
+const int val = clamp(input_val, 0, QINDEX_RANGE - 1);
+const double fval = fclamp(rate_factor, 0.0, 1.0);
+
+// Sanitize dynamic bounds to guarantee low <= high before clamping
+bottom_margin = AOMMAX(bottom_margin, -top_margin);
+mv_limits->row_min = AOMMAX(mv_limits->row_min, -top_margin);
+mv_limits->row_max = AOMMIN(mv_limits->row_max, bottom_margin);
+```
diff --git a/knowledge_base/rules/general/record-error-details-with-aom-set-error.md b/knowledge_base/rules/general/record-error-details-with-aom-set-error.md
new file mode 100644
index 0000000000..a4b59314b8
--- /dev/null
+++ b/knowledge_base/rules/general/record-error-details-with-aom-set-error.md
@@ -0,0 +1,84 @@
+---
+name: libaom/record-error-details-with-aom-set-error
+description: When handling codec errors, establish setjmp in interface wrappers and assert active error_info->setjmp upstream, or record details with aom_set_error and return explicitly in non-longjmp paths
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** In codec interface wrapper functions and control handlers (such as
+ctrl_* in av1_*x_iface.c), establish the setjmp error-handling buffer around
+internal codec calls so internal routines can report errors uniformly via
+aom_internal_error(), rather than branching conditionally on error->setjmp. In
+internal decoder and encoder functions that rely on aom_internal_error() to
+abort execution via longjmp, assert that the error jump buffer is active (e.g.,
+assert(cm->error->setjmp) or assert(error_info->setjmp)) upstream at caller
+entry points and common execution paths. In codec control functions or other
+non-longjmp execution paths without active setjmp targets, record error details
+with aom_set_error() and return the error code explicitly rather than calling
+aom_internal_error() or returning bare error codes without recorded details.
+
+**Why.** aom_internal_error() only performs a longjmp() when error_info->setjmp
+is non-zero; without an active setjmp target, it records error details and
+returns silently, causing unexpected fallthrough into subsequent code.
+Establishing setjmp at interface boundaries ensures uniform error handling
+without internal fallback branching, while asserting error_info->setjmp at
+upstream function entry points guarantees missing error-handling boundaries are
+caught immediately during testing rather than silently failing on corrupt
+bitstreams. In execution paths not bounded by setjmp, calling aom_set_error()
+and returning explicitly ensures safe control flow while preserving
+human-readable error descriptions on struct aom_internal_error_info.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: Conditional error reporting fallback in decoder helper
+if (cm->error->setjmp) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR, "Invalid param");
+} else {
+ return AOM_CODEC_ERROR;
+}
+
+// Bad: Relying on aom_internal_error() longjmp without asserting active setjmp upstream
+aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx) {
+ YV12_BUFFER_CONFIG *ref_buf = get_ref_frame(cm, idx);
+ if (ref_buf == NULL) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR, "No reference frame");
+ }
+}
+
+// Bad: Returning bare error code without recording error detail
+if (ref_buf == NULL) {
+ return AOM_CODEC_ERROR;
+}
+```
+
+Good:
+
+```cpp
+// Good: Establish setjmp buffer in interface wrappers (e.g. av1_dx_iface.c)
+struct aom_internal_error_info *const error = frame_worker_data->pbi->common.error;
+if (setjmp(error->jmp)) {
+ error->setjmp = 0;
+ return error->error_code;
+}
+error->setjmp = 1;
+av1_decode_frame(pbi, data, data_sz);
+error->setjmp = 0;
+
+// Good: Assert setjmp is active when relying on aom_internal_error() longjmp
+aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx) {
+ assert(cm->error->setjmp);
+ YV12_BUFFER_CONFIG *ref_buf = get_ref_frame(cm, idx);
+ if (ref_buf == NULL) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR, "No reference frame");
+ }
+}
+
+// Good: In non-longjmp paths, record details with aom_set_error() and return explicitly
+if (ref_buf == NULL) {
+ aom_set_error(&pbi->error, AOM_CODEC_ERROR, "No reference frame");
+ return pbi->error.error_code;
+}
+```
diff --git a/knowledge_base/rules/general/scale-allocation-by-element-sizeof.md b/knowledge_base/rules/general/scale-allocation-by-element-sizeof.md
new file mode 100644
index 0000000000..2ed41414f1
--- /dev/null
+++ b/knowledge_base/rules/general/scale-allocation-by-element-sizeof.md
@@ -0,0 +1,43 @@
+---
+name: libaom/scale-allocation-by-element-sizeof
+description: When allocating dynamic buffers with aom_malloc, aom_memalign, or malloc, multiply element counts by sizeof and pass a single byte-size expression
+rubric: safety
+severity: blocking
+---
+
+**Rule.** When allocating dynamic memory with aom_malloc, aom_memalign, malloc,
+or realloc, pass a single total byte size computed by multiplying the element
+count by the element size (e.g., count * sizeof(*ptr) or count * sizeof(Type)).
+Do not pass an unscaled element count or pass count and size as separate
+arguments (use aom_calloc(count, size) when allocating with separate count and
+size parameters).
+
+**Why.** aom_malloc, aom_memalign, and malloc accept a single argument
+representing total size in bytes rather than element counts. Allocating without
+multiplying by sizeof creates an undersized heap buffer, causing out-of-bounds
+memory corruption. Passing count and element size as separate arguments to
+aom_malloc causes a signature mismatch.
+
+## Examples
+
+Bad:
+
+```cpp
+// Incorrect: Allocating an unscaled element count creates an undersized buffer.
+buf2[0] = (float *)aom_malloc(newallocsize);
+
+// Incorrect: Passing separate count and size arguments to a single-argument allocator.
+CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
+ aom_malloc(current_size, sizeof(*cpi->consec_zero_mv)));
+```
+
+Good:
+
+```cpp
+// Correct: Scale count by sizeof element to allocate the required bytes.
+buf2[0] = (float *)aom_malloc(newallocsize * sizeof(*buf2[0]));
+
+// Correct: Pass a single multiplied byte size expression (or use aom_calloc for separate args).
+CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
+ aom_malloc(current_size * sizeof(*cpi->consec_zero_mv)));
+```
diff --git a/knowledge_base/rules/general/trailing-comment-on-endif-directives.md b/knowledge_base/rules/general/trailing-comment-on-endif-directives.md
new file mode 100644
index 0000000000..fd2456ea45
--- /dev/null
+++ b/knowledge_base/rules/general/trailing-comment-on-endif-directives.md
@@ -0,0 +1,91 @@
+---
+name: libaom/trailing-comment-on-endif-directives
+description: 'Annotate #endif and #else on long preprocessor blocks and header guards with matching condition comments formatted without directive keywords, omitting on short blocks'
+rubric: readability
+severity: blocking
+---
+
+**Rule.** Annotate `#endif` and `#else` directives on long or multi-function
+preprocessor blocks and header guards with trailing comments accurately matching
+the opening condition, macro name, or guard token (e.g., `#endif //
+CONFIG_AV1_HIGHBITDEPTH`, `#else // !CONFIG_CTX_ADAPT_LOG_WEIGHT`, `#endif //
+AOM_AV1_COMMON_CCSO_H_`). Format closing comments cleanly as `#endif //
+<CONDITION>` or `#endif // <MACRO>` without repeating preprocessor directive
+keywords like `#if` (e.g., avoid `#endif // #if defined(...)`). When modifying
+multi-branch blocks (`#if`/`#elif`/`#endif`), ensure `#endif` comments remain
+synchronized with the opening `#if` condition rather than referencing an inner
+`#elif`, and ensure `#else` comments accurately reflect the inverted condition.
+Maintain consistent directive styles within each file (prefer `#ifdef MACRO` or
+`#ifndef MACRO` for standalone identifiers over `#if defined(...)`). Conversely,
+omit trailing comments on short, locally visible `#if` blocks or when
+expressions would wrap across multiple comment lines.
+
+**Why.** In preprocessor blocks spanning many lines, multiple functions, or
+header guards, trailing comments on `#else` and `#endif` clarify directive
+boundaries and compilation scopes without requiring readers to scroll back.
+Accurately formatted comments without repeated `#if` tokens comply with project
+conventions and cpplint rules. Comments referencing inner `#elif` branches or
+copy-pasted guard names mislead maintainers about active build configurations,
+while commenting short, locally visible blocks adds unnecessary visual clutter.
+
+## Examples
+
+Bad:
+
+```cpp
+// Variant 1: Bare #else / #endif on multi-line functions or mismatched header guard
+#ifndef AOM_AV1_COMMON_CCSO_H_
+#define AOM_AV1_COMMON_CCSO_H_
+#if CONFIG_AV1_HIGHBITDEPTH
+static void highbd_pred(...) { /* multi-line implementation */ }
+#endif
+#endif // AOM_AV1_COMMON_CDEF_H_
+
+// Variant 2: Repeating directive token #if or referencing #elif instead of opening #if
+#if defined(CONFIG_AV1_ENCODER)
+void encode_frame(void);
+#endif // #if defined(CONFIG_AV1_ENCODER)
+
+#if defined(__aarch64__) && defined(__ARM_FEATURE_MATMUL_INT8)
+void process_neon(...);
+#elif defined(__aarch64__) && defined(__ARM_FEATURE_DOTPROD)
+void process_neon(...);
+#endif // defined(__aarch64__) && defined(__ARM_FEATURE_DOTPROD)
+
+// Variant 3: Unnecessary multi-line comment on short, locally visible block
+#if defined(AOM_ADDRESS_SANITIZER) && !defined(NDEBUG)
+const size_t kMinStackSize = 1024 * 1024;
+#else
+const size_t kMinStackSize = 256 * 1024;
+#endif // defined(AOM_ADDRESS_SANITIZER) && !defined(NDEBUG)
+```
+
+Good:
+
+```cpp
+// Variant 1: Annotated #else / #endif matching opening condition and header guard
+#ifndef AOM_AV1_COMMON_CCSO_H_
+#define AOM_AV1_COMMON_CCSO_H_
+#if CONFIG_AV1_HIGHBITDEPTH
+static void highbd_pred(...) { /* multi-line implementation */ }
+#endif // CONFIG_AV1_HIGHBITDEPTH
+#endif // AOM_AV1_COMMON_CCSO_H_
+
+// Variant 2: Clean comment without directive token, synchronized with opening #if
+#ifdef CONFIG_AV1_ENCODER
+void encode_frame(void);
+#endif // CONFIG_AV1_ENCODER
+
+#if defined(__aarch64__) && defined(__ARM_FEATURE_MATMUL_INT8)
+void process_neon(...);
+#elif defined(__aarch64__) && defined(__ARM_FEATURE_DOTPROD)
+void process_neon(...);
+#endif // defined(__aarch64__) && defined(__ARM_FEATURE_MATMUL_INT8)
+
+// Variant 3: Omit trailing comment on short, locally visible block
+#if defined(AOM_ADDRESS_SANITIZER) && !defined(NDEBUG)
+const size_t kMinStackSize = 1024 * 1024;
+#else
+const size_t kMinStackSize = 256 * 1024;
+#endif
+```
diff --git a/knowledge_base/rules/general/update-buffer-alloc-size-only-on-realloc.md b/knowledge_base/rules/general/update-buffer-alloc-size-only-on-realloc.md
new file mode 100644
index 0000000000..59a5d2221f
--- /dev/null
+++ b/knowledge_base/rules/general/update-buffer-alloc-size-only-on-realloc.md
@@ -0,0 +1,80 @@
+---
+name: libaom/update-buffer-alloc-size-only-on-realloc
+description: When allocating or reallocating buffers, update allocation and dimension tracking fields strictly inside initial setup or reallocation blocks, not in downstream helpers or per-frame routines
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** When allocating, initializing, or dynamically resizing buffers, update
+allocation and dimension tracking fields (such as *_alloc_size,
+allocated_tile_cols/rows, allocated_tiles, or initial_dimensions) strictly
+within the function or conditional block that performs the allocation or initial
+setup. Do not set or clear tracking variables in downstream helper functions, do
+not reset them to zero upon reallocation, and do not update them unconditionally
+in per-frame routines outside setup or reallocation branches.
+
+**Why.** Setting dimension and capacity trackers directly where buffers are
+allocated or initialized ensures lifecycle consistency and guarantees error
+handlers and resize checks operate on accurate reference state. Updating
+trackers outside reallocation blocks or unconditionally in per-frame routines
+corrupts baseline dimensions and capacity tracking, causing redundant
+reallocations and breaking dynamic resolution changes.
+
+## Examples
+
+Bad:
+
+```cpp
+// Anti-pattern 1: Setting allocation dimension trackers in downstream helper rather than allocation function
+// In downstream helper row_mt_mem_alloc():
+enc_row_mt->allocated_tile_cols = tile_cols;
+enc_row_mt->allocated_tile_rows = tile_rows;
+
+// Anti-pattern 2: Updating allocation size unconditionally outside reallocation branch
+if (cpi->consec_zero_mv && cpi->consec_zero_mv_alloc_size < current_size) {
+ aom_free(cpi->consec_zero_mv);
+ CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
+ aom_calloc(current_size, sizeof(*cpi->consec_zero_mv)));
+}
+cpi->consec_zero_mv_alloc_size = current_size;
+
+// Anti-pattern 3: Updating baseline dimensions unconditionally in per-frame routine
+void av1_check_initial_width(AV1_COMP *cpi, ...) {
+ cpi->initial_dimensions.width = cm->width;
+ cpi->initial_dimensions.height = cm->height;
+ if (!cpi->frame_size_related_setup_done) {
+ alloc_compressor_data(cpi);
+ cpi->frame_size_related_setup_done = true;
+ }
+}
+```
+
+Good:
+
+```cpp
+// Pattern 1: Set dimension tracking directly in allocation function av1_alloc_tile_data()
+CHECK_MEM_ERROR(
+ cm, cpi->tile_data,
+ aom_memalign(32, tile_cols * tile_rows * sizeof(*cpi->tile_data)));
+cpi->allocated_tiles = tile_cols * tile_rows;
+enc_row_mt->allocated_tile_cols = tile_cols;
+enc_row_mt->allocated_tile_rows = tile_rows;
+
+// Pattern 2: Update allocation size strictly inside the reallocation block
+if (cpi->consec_zero_mv && cpi->consec_zero_mv_alloc_size < current_size) {
+ aom_free(cpi->consec_zero_mv);
+ CHECK_MEM_ERROR(cm, cpi->consec_zero_mv,
+ aom_calloc(current_size, sizeof(*cpi->consec_zero_mv)));
+ cpi->consec_zero_mv_alloc_size = current_size;
+}
+
+// Pattern 3: Update baseline dimensions strictly inside the initial setup block
+void av1_check_initial_width(AV1_COMP *cpi, ...) {
+ if (!cpi->frame_size_related_setup_done) {
+ alloc_compressor_data(cpi);
+ cpi->initial_dimensions.width = cm->width;
+ cpi->initial_dimensions.height = cm->height;
+ cpi->frame_size_related_setup_done = true;
+ }
+}
+```
diff --git a/knowledge_base/rules/general/use-bool-for-boolean-flags-and-arrays.md b/knowledge_base/rules/general/use-bool-for-boolean-flags-and-arrays.md
new file mode 100644
index 0000000000..882a206724
--- /dev/null
+++ b/knowledge_base/rules/general/use-bool-for-boolean-flags-and-arrays.md
@@ -0,0 +1,80 @@
+---
+name: libaom/use-bool-for-boolean-flags-and-arrays
+description: When declaring, assigning, or evaluating boolean flags, struct members, arrays, pointers, or predicates, use bool with <stdbool.h>, true/false, direct checks, and inline call-site comments
+rubric: readability
+severity: blocking
+---
+
+**Rule.** In C and dual C/C++ code, use `bool` (explicitly including
+`<stdbool.h>` in `.c` and `.h` files rather than relying on transitive includes)
+instead of integer types (`int`, `unsigned int`, `uint32_t`, `uint8_t`) for
+predicate functions, local variables, flags, struct members, status arrays,
+binary status return types, and out-parameters (`bool *` instead of `int *`). Do
+not split boolean field types across `#ifdef __cplusplus` guards.
+
+Follow these conventions for boolean usage:
+1. **Literals & Conditions**: In assignments, initializations, and returns, use boolean literals `true` and `false` rather than `1` and `0`. Evaluate boolean expressions directly (`if (flag)`, `if (!flag)`) rather than comparing against literals or zero (`== true`, `== false`, `== 1`, `== 0`, `!= 0`).
+2. **Explicit Conversions**: Explicitly compare against zero (`!= 0` or `> 0`) when converting bitwise mask checks (e.g., `(flags & MASK) != 0`), comparison function results (e.g., `strcmp(...) != 0`), or multi-valued integer settings/enums to boolean values or function arguments.
+3. **Call-Site Annotations & Comments**: Annotate non-obvious boolean literal arguments at call sites with inline parameter-name comments (e.g., `/*param=*/false`). Document ambiguous boolean return value semantics (e.g., `// Returns true on success, false on failure.`) above function declarations in headers, and use `true`/`false` rather than `1`/`0` in code comments.
+
+**Why.** Explicitly including `<stdbool.h>` avoids brittle transitive header
+dependencies that break during refactoring. Using standard `bool` with
+`true`/`false` enforces strong type safety, clarifies binary intent, avoids
+`#ifdef __cplusplus` preprocessor branching, reduces struct memory footprints (1
+byte vs. 4 bytes), and prevents pointer type mismatches on output parameters.
+Direct conditional checks eliminate redundant comparisons. Explicit conversions
+(`!= 0`) clarify intentional truth-value conversions from bitmasks or
+multi-level features without implicit truncation. Inline parameter comments
+(`/*param=*/false`) make call sites self-documenting without requiring function
+signature lookups.
+
+## Examples
+
+Bad:
+
+```cpp
+// Bad: missing <stdbool.h>, using int / #ifdef for flags, out-params, comparisons
+struct SvcRtcRef {
+#if defined(__cplusplus)
+ bool is_key_frame;
+#else
+ int is_key_frame;
+#endif
+ unsigned int enable_cdef;
+ int is_frame_dropped[MAX_STATIC_GF_GROUP_LENGTH];
+};
+
+int check_neighbor_blk(const MACROBLOCKD *xd, int *use_scaled_ref) {
+ int using_file = strcmp(fn, "-");
+ bool is_layer_obu = metadata->flags & AOM_MIF_LAYER_SPECIFIC;
+ if (is_layer_obu == 1 || is_screen == false) return 1;
+ return 0;
+}
+
+diffwtd_mask_neon(mask, 0, src0, src0_stride, src1, src1_stride, h, w);
+av1_pick_cdef_from_qp(cm, cpi->sf.rt_sf.skip_cdef_sb, is_screen, avoid_uv);
+```
+
+Good:
+
+```cpp
+// Good: explicit <stdbool.h>, bool everywhere, true/false, inline comments, != 0
+#include <stdbool.h>
+
+struct SvcRtcRef {
+ bool is_key_frame;
+ bool enable_cdef;
+ bool is_frame_dropped[MAX_STATIC_GF_GROUP_LENGTH];
+};
+
+// Returns true if neighbor block is valid, false otherwise.
+bool check_neighbor_blk(const MACROBLOCKD *xd, bool *use_scaled_ref) {
+ const bool using_file = strcmp(fn, "-") != 0;
+ const bool is_layer_obu = (metadata->flags & AOM_MIF_LAYER_SPECIFIC) != 0;
+ if (is_layer_obu || !is_screen) return true;
+ return false;
+}
+
+diffwtd_mask_neon(mask, /*inverse=*/false, src0, src0_stride, src1, src1_stride, h, w);
+av1_pick_cdef_from_qp(cm, cpi->sf.rt_sf.skip_cdef_sb != 0, is_screen, avoid_uv);
+```
diff --git a/knowledge_base/rules/general/use-neon-lane-intrinsics-not-vector-subscript.md b/knowledge_base/rules/general/use-neon-lane-intrinsics-not-vector-subscript.md
new file mode 100644
index 0000000000..cc06301ed6
--- /dev/null
+++ b/knowledge_base/rules/general/use-neon-lane-intrinsics-not-vector-subscript.md
@@ -0,0 +1,71 @@
+---
+name: libaom/use-neon-lane-intrinsics-not-vector-subscript
+description: On ARM NEON and SIMD vector types, use standard intrinsics (vadd, vmul, vget_lane, vset_lane, vdup_n, vld1) instead of compiler vector operators, array subscripting, or brace initialization
+rubric: correctness
+severity: blocking
+---
+
+**Rule.** In ARM NEON and SIMD implementations, do not use compiler-specific
+vector extensions—such as arithmetic and compound assignment operators (+, -, *,
++=, -=, *=), shift and bitwise operators (<<, >>, &, |, ^), array subscript
+indexing (vec[i]), or aggregate/zero brace initialization ({ ... }, { 0 }, { { 0
+} })—on vector types (such as uint64x2_t, uint32x4_t, int32x4_t, int16x8_t,
+int16x4_t, uint8x16_t, __m128i) or arrays of vectors. Instead, initialize vector
+constants and sequential vectors by loading from file-scope static const arrays
+with standard load intrinsics (such as vld1[q]_*, _mm_loadu_*) or set intrinsics
+(such as _mm_setr_*, vdup[q]_n_*). Use standard intrinsics for arithmetic and
+logic (vadd[q]_*, vsub[q]_*, vmul[q]_*, vshl[q]_*, vshr[q]_*, vand[q]_*,
+vorr[q]_*, veor[q]_*), lane access (vget[q]_lane_*, vset[q]_lane_*), and leave
+overwritten vector arrays uninitialized.
+
+**Why.** In Microsoft Visual C++ (MSVC) for Windows on ARM as well as standard C
+SIMD headers, vector types are defined as opaque union or struct types rather
+than GCC/Clang vector extension types. Relying on GNU/Clang vector operator
+overloads, array subscripting, or brace aggregate initialization breaks
+compilation on MSVC. Direct brace initialization of vector constants is
+non-portable across C compilers. Additionally, zero-initializing vector arrays
+with brace syntax when they are immediately overwritten generates redundant
+stores on function entry. Loading constant sequences from file-scope static
+const arrays with standard load intrinsics and using standard arithmetic/lane
+intrinsics guarantees cross-compiler portability, consistent code generation,
+and optimal performance.
+
+## Examples
+
+Bad:
+
+```cpp
+// 1. Non-portable brace initialization on vectors & sequential constants:
+const int16x4_t iota = { 0, 1, 2, 3 };
+const int16x8_t iota_seq = { 0, 1, 2, 3, 4, 5, 6, 7 };
+int16x8_t temp_buf[8] = { { 0 } };
+
+// 2. Vector arithmetic, shifts, and compound assignment operators:
+const int16x4_t x0123 = vdup_n_s16(x0) + (iota << 6);
+uint64x2_t sum = vdupq_n_u64(0);
+sum += mse_wxh_16bit(dst, dstride, src, w, w, h);
+
+// 3. Array subscript indexing on NEON vector types:
+s[0] = s[2];
+ret = vld1_lane_u8(src + idx[0], ret, 0);
+```
+
+Good:
+
+```cpp
+// 1. Load constants from file-scope static const arrays via vld1_*; leave overwritten buffers uninitialized:
+static const int16_t iota_s16[] = { 0, 1, 2, 3 };
+static const int16_t iota1_s16[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
+const int16x4_t iota = vld1_s16(iota_s16);
+const int16x8_t iota_seq = vld1q_s16(iota1_s16);
+int16x8_t temp_buf[8];
+
+// 2. Use standard NEON intrinsics for vector arithmetic and shifts:
+const int16x4_t x0123 = vadd_s16(vdup_n_s16(x0), vshl_n_s16(iota, 6));
+uint64x2_t sum = vdupq_n_u64(0);
+sum = vaddq_u64(sum, mse_wxh_16bit(dst, dstride, src, w, w, h));
+
+// 3. Use dedicated NEON lane extraction and insertion intrinsics:
+s = vsetq_lane_u16(vgetq_lane_u16(s, 2), s, 0);
+ret = vld1_lane_u8(src + vget_lane_s16(vget_low_s16(idx), 0), ret, 0);
+```
diff --git a/knowledge_base/rules/general/use-sizeof-pointer-dereference-in-allocations.md b/knowledge_base/rules/general/use-sizeof-pointer-dereference-in-allocations.md
new file mode 100644
index 0000000000..d5a3b6cb9b
--- /dev/null
+++ b/knowledge_base/rules/general/use-sizeof-pointer-dereference-in-allocations.md
@@ -0,0 +1,69 @@
+---
+name: libaom/use-sizeof-pointer-dereference-in-allocations
+description: When sizing allocations and memory operations with sizeof, use sizeof(*ptr), matching index dereferences, or sizeof(array) rather than explicit types, manual multiplications, or mismatched indices
+rubric: readability
+severity: blocking
+---
+
+**Rule.** When sizing dynamic allocations (aom_malloc, aom_calloc, aom_memalign,
+aom_realloc, malloc, calloc), vector containers (aom_vector_setup), or memory
+operations (memset, memcpy, memmove), derive element sizes using dereferenced
+target expressions (such as sizeof(*ptr)) rather than hardcoding sizeof(Type).
+For fixed-size local/static arrays or struct array members (e.g.,
+ptr->member_array), pass sizeof(array) directly instead of multiplying element
+size by dimension constants. When indexing into arrays of pointers or
+multi-dimensional lookups, dereference the exact matching target expression
+(such as sizeof(*arr[i]) or sizeof(*table[key])) or a clean base index
+sizeof(*buf[0]), avoiding mismatched index variables or offsets (such as
+sizeof(*dst->buf[c]) when copying dst->buf[dst_offset + c]).
+
+**Why.** Deriving buffer and allocation sizes directly from the target pointer
+(sizeof(*ptr)) or fixed array symbol (sizeof(array)) ensures sizes automatically
+update when variable types or array dimensions change during refactoring,
+preventing truncation, buffer overflows, and heap corruption. It also eliminates
+redundant dimension constants and verbose arithmetic. Using exact matching
+destination expressions or clean base index [0] prevents misleading indexing
+mismatches and copy-paste errors.
+
+## Examples
+
+Bad:
+
+```cpp
+// Hardcoded type in allocation:
+flow->u = (double *)aom_calloc(flow_size, sizeof(double));
+block_hash_values[k] = (uint32_t *)aom_malloc(pic_size * sizeof(uint32_t));
+
+// Manual element multiplication on fixed-size arrays:
+int64_t M_trn[25];
+memset(M_trn, 0, sizeof(*M_trn) * 25);
+memset(gf_group->is_frame_dropped, 0,
+ sizeof(gf_group->is_frame_dropped[0]) * MAX_STATIC_GF_GROUP_LENGTH);
+memcpy(dst->stats, src->stats, sizeof(FIRSTPASS_STATS) * MAX_STATS_LEN);
+
+// Mismatched index variable or dummy index in indexed operations:
+memcpy(dst->buf[dst_offset + c], src->buf[c],
+ sizeof(*dst->buf[c]) * src->width * src->height);
+table[val] = aom_malloc(sizeof(table[0][0]));
+```
+
+Good:
+
+```cpp
+// Sizing derived from target pointer dereference:
+CHECK_MEM_ERROR(cm, flow->u,
+ (double *)aom_calloc(flow_size, sizeof(*flow->u)));
+block_hash_values[k] =
+ (uint32_t *)aom_malloc(pic_size * sizeof(*block_hash_values[k]));
+
+// Fixed-size array size used directly:
+int64_t M_trn[25];
+memset(M_trn, 0, sizeof(M_trn));
+memset(gf_group->is_frame_dropped, 0, sizeof(gf_group->is_frame_dropped));
+memcpy(dst->stats, src->stats, sizeof(dst->stats));
+
+// Consistent matching index or clean base index [0]:
+memcpy(dst->buf[dst_offset + c], src->buf[c],
+ sizeof(*dst->buf[0]) * src->width * src->height);
+table[val] = aom_malloc(sizeof(*table[val]));
+```