C6: вырезать legacy sentiment-физику и сузить недоказанные перцептивные API - #345
Conversation
WalkthroughPR переводит Lab Colors на версию 0.3.0: удаляет sentiment-модель, вводит family-источники и строгие DTO, обновляет Ys candidate-score solver, добавляет валидированные координаты и точные серые преобразования, а также синхронизирует Rust, WASM, TypeScript, conformance и release-контракты. ChangesЯдро и численные контракты
WASM и runtime-контракты
Документация и release
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 26
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
crates/labcolors-core/src/solve.rs (1)
1294-1300: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winСчитайте метрики непосредственно из
encoded.
hexиcolorстроятся изencoded, ноlcи WCAG — из повторногоquantised_display(rgb_ideal). Получите encoded-компоненты какbyte / 255.0, чтобы весьSolvedописывал один фактически emitted state.Предлагаемая правка
let encoded = srgb8_from_linear(rgb_ideal); let hex = encoded.to_hex(); let color = LcsColor::from_srgb8_with_vc(encoded, vc); -let disp = quantised_display(rgb_ideal); +let disp = encoded + .bytes() + .map(|channel| f64::from(channel) / 255.0);As per coding guidelines: «Один объявленный colorimetric state должен иметь единственный источник истины» и «Решения по конечному output domain необходимо перепроверять на финальном encoded значении».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/solve.rs` around lines 1294 - 1300, Update the metric calculations in the surrounding solve flow to use the emitted `encoded` value as the single source of truth: derive its RGB components as byte values divided by 255.0, then pass that reconstructed color to `wcag::relative_luminance` and `wcag::contrast_ratio` while computing `lc`. Remove the `quantised_display(rgb_ideal)` input for these metrics, leaving `hex` and `color` based on `encoded` unchanged.Source: Coding guidelines
crates/labcolors-core/src/config.rs (1)
1150-1155: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winНе заменяйте neutral-source общей policy таблицы.
Например,
NeutralPick::Lightс#FFFFFFпри chromatic neutral policy получитhue: Noneи станет цветным, хотя документация обещает exact-byte классификацию источника. Передавайте скомпилированный тинт для любогоLadderSource.Предлагаемое исправление
- let hue = match source { - LadderSource::Neutral(_) => None, - _ => Some(self.compile_ladder_tint(role, source)?), - }; + let hue = Some(self.compile_ladder_tint(role, source)?);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/config.rs` around lines 1150 - 1155, В обработке источника рядом с `compile_ladder_tint` передавайте скомпилированный тинт для каждого `LadderSource`, включая `LadderSource::Neutral(_)`; удалите специальную ветку, возвращающую `hue: None` для neutral-source. Сохраните exact-byte классификацию neutral-источников и не позволяйте общей policy таблицы переопределять её.crates/labcolors-core/src/pair_label_tests.rs (1)
174-194: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
assert_ne!не доказывает отсутствие near-black collapse.Регрессия в соседний near-black байт пройдёт тест. Либо сузьте название до byte-неравенства с primary, либо проверяйте объявленную количественную границу без нового hue-claim.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/pair_label_tests.rs` around lines 174 - 194, Тест pair_label_does_not_collapse_to_primary_label сейчас проверяет лишь байтовое неравенство и пропускает соседний near-black оттенок. Замените assert_ne на проверку объявленной количественной границы для solved относительно primary, не добавляя требований к hue; либо переименуйте тест, если требуется сохранить только проверку различия байтов.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/labcolors-core/src/accent_golden_tests.rs`:
- Line 1: Переведите модульную документацию контракта AccentCurve и описание
fixture helper в диапазоне 10–26 на краткий русский язык, сохранив смысл golden
snapshot и структуру Diataxis. Изменяйте только документирующие комментарии, не
затрагивая тестовую логику.
In `@crates/labcolors-core/src/agnostic_gates.rs`:
- Around line 191-212: Обновите тест
named_roles_do_not_gain_hierarchy_from_declaration_order, чтобы собрать и
скомпилировать переставленную таблицу ролей, разрешить её для того же bg и
сравнить результаты с исходной таблицей для всех проверяемых ролей. Сохраните
проверки отсутствия compressed-отношений и удалите комментарий со ссылкой на
будущий C7, не добавляя семантики, зависящей от имён ролей.
In `@crates/labcolors-core/src/config.rs`:
- Around line 1059-1074: После вычисления RoleChroma в текущем конфигурационном
пути сохраните cross-field validation для chromatic Brand/Family Material,
включая exact-gray neutral без hue override. Стройте таблицу через общий
checked-путь либо выполняйте preflight с типизированным ConfigError до обхода
RoleSpec::validate_with_chroma, чтобы resolve_named_set() не отклонял уже
построенный набор. Добавьте regression-тест для exact-gray neutral с chromatic
Material.
In `@crates/labcolors-core/src/curve.rs`:
- Around line 5-15: Переведите на русский краткую rustdoc-документацию для
CurvePosition и ColorCurve, включая связанные блоки около конструктора, методов
и примеров в указанных участках. Сохраните смысл описаний и
compile_fail-примера, но используйте краткую структуру Diataxis и не изменяйте
поведение кода.
In `@crates/labcolors-core/src/lcs.rs`:
- Around line 10-14: Переведите на русский язык всю добавленную
rustdoc-документацию для LcsColor, включая описание locus-инварианта, accessor
API и границ квантования в указанных блоках. Сохраните краткость и примените
подходящую структуру Diátaxis, не изменяя код или смысл технических контрактов.
In `@crates/labcolors-core/src/lib.rs`:
- Around line 154-264: Переведите на русский язык все поясняющие doc-комментарии
у структур InternalAccentRecipes, NoHueVisibilityVerdict,
NoCompatibilityAliases, NoHybridLpcSurfaceMetric, NoPrematureScalarLpcApi и
NoPublicPairRecipeApi, сохранив краткость и структуру Diataxis. Не изменяйте
кодовые блоки compile_fail, импорты, выражения или атрибуты #[cfg(doctest)].
In `@crates/labcolors-core/src/neutral.rs`:
- Around line 65-71: Переведите все изменённые doc-комментарии в neutral.rs,
включая участки около символов и строк, указанных в замечании, на краткий
русский язык. Уберите оставшиеся полностью англоязычные и смешанные
формулировки, сохранив исходный технический смысл и без изменения кода.
In `@crates/labcolors-core/src/semantic.rs`:
- Around line 395-417: Переведите на русский язык новые публичные rustdoc для
TextAnchor, DjMagnitude, RoleSpec и RoleChroma, включая связанные описания
полей, конструкторов и методов в указанных участках. Сохраните точность
терминов, ссылочные элементы rustdoc и краткую структуру Diataxis; изменяйте
только документацию, не поведение кода.
- Around line 801-804: Синхронизируйте проверку canonical_hue_deg в
NamedRoleTable::new с границей конфигурации [0, 360): до запуска curve scan
нормализуйте угол в канонический диапазон либо отклоняйте значения вне него,
включая чрезмерно большие конечные значения. Сохраните заявленный проверяемый
численный домен для всех входов политики.
In `@crates/labcolors-core/src/solve.rs`:
- Line 1393: Ys tests still use the retired H-K oracle through
apparent_contrast_candidate_hex_with_vc_for_test, so they do not actually
validate Ys candidate scoring. In the affected test sections, replace those
calls with ys_candidate_score_for_test or a local candidate_lc calculation,
preserving the existing candidate-score assertions. Update the related import
and all occurrences also covered near the other referenced test ranges.
In `@crates/labcolors-core/src/spaces/cam16.rs`:
- Around line 105-131: Вынесите веса и константы CAM16 из inverse-расчёта вокруг
residual_slope в именованные общие константы или другой единый источник, уже
используемый прямым путём adapt. Замените локальные W, 400, 27.13 и 0.42 в adapt
и inverse ссылками на эти символы, сохранив текущие формулы и граничное
поведение.
In `@crates/labcolors-core/src/spaces/srgb.rs`:
- Around line 199-210: The public hex_from_srgb path must not convert NaN or
other non-finite linear-sRGB components into 00. Make srgb8_from_linear fallible
or require a validated finite linear-sRGB type, and propagate a typed error
through hex_from_srgb instead of allowing the cast fallback; preserve normal
quantization for valid inputs.
In `@crates/labcolors-core/src/spaces/vc.rs`:
- Around line 24-32: Переведите на русский язык новые публичные
rustdoc-комментарии, описывающие инвариант производных полей и getters, в
ViewingConditions и связанных участках, сохранив их краткость и структуру
Diataxis. Не изменяйте код, примеры compile_fail или смысл документации.
In `@crates/labcolors-core/src/wcag.rs`:
- Line 116: Переведите изменённый doc-комментарий в `wcag.rs` на краткий русский
язык, сохранив смысл сравнения с кривой кандидата (`candidate curve`) и
используя принятую терминологию документации.
In `@crates/labcolors-core/tests/agnostic_production_surface.rs`:
- Around line 1-10: Переведите на русский новые модульные документы и
комментарии к контрактам scanner в тесте agnostic_production_surface, включая
участки 43–48, 65–70, 84–112, 239–256 и 275–301. Сохраните краткость,
технический смысл и существующую структуру документации Diataxis; изменяйте
только англоязычные пояснения, не затрагивая код, идентификаторы и проверяемые
значения.
In `@crates/labcolors-core/tests/empirical_inventory.rs`:
- Around line 60-62: Обновите комментарий в тесте empirical_inventory.rs,
дополнив перечень STANDARD-MODEL модулей символом spaces/oklab.rs рядом с
scale.rs, lpc.rs, lcs.rs и solve.rs. Сохраните пояснение о том, что остальные
модули являются стандартной моделью и входят в numeric-аудит.
In `@crates/labcolors-core/tests/hue_sweep.rs`:
- Around line 38-43: Update the documentation for candidate_lc to describe its
signed lightness-contrast coordinate, not an absolute magnitude or universal
readability measure. Keep the implementation unchanged and state only that it is
rechecked through the public resolver boundary against the solver’s luminance
axis, preserving the polarity semantics validated below.
In `@crates/labcolors-core/tests/on_disk_audit_probe.rs`:
- Around line 58-68: Translate the updated isolation documentation in the
module-level comments around the temp-directory copy and atomic write, including
the related comments at the additional referenced section, into concise Russian.
Preserve the existing technical meaning and structure while leaving code
unchanged.
In `@crates/labcolors-core/tests/splice_support.rs`:
- Around line 1-3: Переведите модульную документацию в начале модуля
splice_support на русский язык, сохранив её краткость и описательный смысл;
структуру кода и остальные элементы модуля не изменяйте.
In `@crates/labcolors-wasm/src/lib.rs`:
- Around line 54-62: Переведите на русский и кратко перепишите публичные
doc-комментарии экспортируемого TypeScript API для полей lc, wcagRatio,
compressed, achievedDj и связанных участков, сохранив точное описание их
поведения и структуру Diataxis. В комментарии на участке 106 используйте
каноническое имя lc вместо Lc; обновите также отмеченные участки 122–124,
661–667 и 703–705, не изменяя реализацию.
In `@docs/decisions/0001-config-boundary.md`:
- Around line 28-31: Проверьте слово «названным» в предложении о special case:
оно уже написано правильно, с двумя «н». Не вносите изменений в этот фрагмент,
если дополнительная проверка не выявит иной орфографической ошибки.
In `@docs/whitepaper.md`:
- Around line 152-155: В предложении про «Exact-сертификат» исправьте написание
слова «названной» в соответствии с орфографической рекомендацией, не изменяя
остальной смысл или формулировку абзаца.
- Around line 119-121: В предложении о производных foreground, surface и
effect-ролях устраните повтор местоимения «их», сохранив смысл о том, что итог
ролей определяется их физическим контрактом.
In `@packages/colors/test/public-claims.test.mjs`:
- Around line 744-769: Расширьте проверку `surfaces` в тесте
`public-claims.test.mjs` на всю production-поверхность, включая `semantic.rs`,
projection и runtime-модули пакетов. Добавьте соответствующие пути и регулярные
выражения для всех удалённых sentiment-символов, включая `SentimentCurve` и
связанные API, чтобы любое их возвращение приводило к ошибке теста; существующие
проверки сохраните.
In `@packages/colors/test/release-contract.test.mjs`:
- Around line 87-93: Ограничьте проверки version, rust-version и repository в
тесте release-contract через границы секции [workspace.package], чтобы
совпадения из последующих секций не учитывались. Обновите регулярные выражения
вокруг этих assert.match, сохранив текущие ожидаемые значения и проверку
обязательных полей.
In `@README.md`:
- Around line 9-28: Перепишите раздел README о целевой архитектуре, описывая
только фактический контракт версии 0.3.0: текущий browser runtime, повторное
разрешение всей таблицы при изменении контекста и переходную модель
NamedRoleTable/рецептов. Удалите формулировки о будущем selective re-resolve,
публичном dependency graph и прочих планах миграции; явно укажите гарантии и
возможности, которых текущая версия не предоставляет.
---
Outside diff comments:
In `@crates/labcolors-core/src/config.rs`:
- Around line 1150-1155: В обработке источника рядом с `compile_ladder_tint`
передавайте скомпилированный тинт для каждого `LadderSource`, включая
`LadderSource::Neutral(_)`; удалите специальную ветку, возвращающую `hue: None`
для neutral-source. Сохраните exact-byte классификацию neutral-источников и не
позволяйте общей policy таблицы переопределять её.
In `@crates/labcolors-core/src/pair_label_tests.rs`:
- Around line 174-194: Тест pair_label_does_not_collapse_to_primary_label сейчас
проверяет лишь байтовое неравенство и пропускает соседний near-black оттенок.
Замените assert_ne на проверку объявленной количественной границы для solved
относительно primary, не добавляя требований к hue; либо переименуйте тест, если
требуется сохранить только проверку различия байтов.
In `@crates/labcolors-core/src/solve.rs`:
- Around line 1294-1300: Update the metric calculations in the surrounding solve
flow to use the emitted `encoded` value as the single source of truth: derive
its RGB components as byte values divided by 255.0, then pass that reconstructed
color to `wcag::relative_luminance` and `wcag::contrast_ratio` while computing
`lc`. Remove the `quantised_display(rgb_ideal)` input for these metrics, leaving
`hex` and `color` based on `encoded` unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6173d694-65bb-42db-8207-bd188c1eae5e
⛔ Files ignored due to path filters (2)
Cargo.lockis excluded by!**/*.lockpackages/colors/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (93)
.github/workflows/ci.yml.gitignoreCargo.tomlREADME.mdconformance/README.mdconformance/vectors/manifest.jsoncrates/labcolors-conformance/src/lib.rscrates/labcolors-core/Cargo.tomlcrates/labcolors-core/benches/neutral_at.rscrates/labcolors-core/benches/y_hk.rscrates/labcolors-core/contracts/solve-characterization-v1-linux-x64.jsoncrates/labcolors-core/contracts/solve-characterization-v1-macos-aarch64.jsoncrates/labcolors-core/examples/bg_ladder_anchors.rscrates/labcolors-core/examples/figma_anchor_provenance.rscrates/labcolors-core/examples/tint_target_sweep.rscrates/labcolors-core/src/accent.rscrates/labcolors-core/src/accent_balance.rscrates/labcolors-core/src/accent_golden_tests.rscrates/labcolors-core/src/accent_surface.rscrates/labcolors-core/src/agnostic_gates.rscrates/labcolors-core/src/appearance.rscrates/labcolors-core/src/config.rscrates/labcolors-core/src/config/fixture.rscrates/labcolors-core/src/config/preset.rscrates/labcolors-core/src/config/tests.rscrates/labcolors-core/src/curve.rscrates/labcolors-core/src/dim_tinted_tests.rscrates/labcolors-core/src/exposure_support.rscrates/labcolors-core/src/glow.rscrates/labcolors-core/src/ladder.rscrates/labcolors-core/src/lcs.rscrates/labcolors-core/src/lib.rscrates/labcolors-core/src/lpc.rscrates/labcolors-core/src/material.rscrates/labcolors-core/src/neutral.rscrates/labcolors-core/src/one_levelness_tests.rscrates/labcolors-core/src/pair.rscrates/labcolors-core/src/pair_label_tests.rscrates/labcolors-core/src/r3_byte_identity_tests.rscrates/labcolors-core/src/scale.rscrates/labcolors-core/src/semantic.rscrates/labcolors-core/src/sentiment.rscrates/labcolors-core/src/solve.rscrates/labcolors-core/src/spaces/cam16.rscrates/labcolors-core/src/spaces/oklab.rscrates/labcolors-core/src/spaces/oklch.rscrates/labcolors-core/src/spaces/srgb.rscrates/labcolors-core/src/spaces/vc.rscrates/labcolors-core/src/srgb8.rscrates/labcolors-core/src/wcag.rscrates/labcolors-core/tests/agnostic_production_surface.rscrates/labcolors-core/tests/anchor_transfer_derivation.rscrates/labcolors-core/tests/chain_invariants.rscrates/labcolors-core/tests/empirical_inventory.rscrates/labcolors-core/tests/gate_green_smoke.rscrates/labcolors-core/tests/hue_sweep.rscrates/labcolors-core/tests/level3_polarity_validation.rscrates/labcolors-core/tests/on_disk_audit_probe.rscrates/labcolors-core/tests/property_accent_surface.rscrates/labcolors-core/tests/property_invariants.rscrates/labcolors-core/tests/reference_vectors.rscrates/labcolors-core/tests/s2b_baseline_guards.rscrates/labcolors-core/tests/sentiment_categorical_zones.rscrates/labcolors-core/tests/solve_characterization.rscrates/labcolors-core/tests/splice_support.rscrates/labcolors-core/tests/symmetry.rscrates/labcolors-ffi/src/lib.rscrates/labcolors-wasm/src/config_dto.rscrates/labcolors-wasm/src/dto.rscrates/labcolors-wasm/src/engine.rscrates/labcolors-wasm/src/error.rscrates/labcolors-wasm/src/lib.rscrates/labcolors-wasm/src/projection.rscrates/labcolors-wasm/tests/chain_invariants.rscrates/labcolors-wasm/tests/data/labui.config.jsoncrates/labcolors-wasm/tests/data/labui.config.prod.jsoncrates/labcolors-wasm/tests/wasm_parity.rsdocs/decisions/0001-config-boundary.mddocs/decisions/0003-hk-scope.mddocs/decisions/0004-finite-alpha-glow-reference.mddocs/empirical-inventory.mddocs/whitepaper.mdpackages/colors/README.mdpackages/colors/adapt-theme.jspackages/colors/package.jsonpackages/colors/smoke.consumer.tspackages/colors/test/adapt-theme.test.mjspackages/colors/test/chain-invariants.test.mjspackages/colors/test/public-claims.test.mjspackages/colors/test/release-contract.test.mjspackages/colors/test/wasm-boundary.golden.jsonreference/labui-accent-primitives.mdscripts/verify-package-release.mjs
💤 Files with no reviewable changes (14)
- crates/labcolors-core/benches/y_hk.rs
- .gitignore
- crates/labcolors-core/tests/symmetry.rs
- crates/labcolors-core/src/accent_surface.rs
- crates/labcolors-core/tests/anchor_transfer_derivation.rs
- crates/labcolors-core/tests/property_accent_surface.rs
- crates/labcolors-core/src/accent.rs
- crates/labcolors-core/tests/level3_polarity_validation.rs
- crates/labcolors-core/tests/s2b_baseline_guards.rs
- crates/labcolors-core/examples/tint_target_sweep.rs
- crates/labcolors-core/tests/sentiment_categorical_zones.rs
- crates/labcolors-core/src/sentiment.rs
- packages/colors/test/chain-invariants.test.mjs
- packages/colors/test/adapt-theme.test.mjs
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
🛑 Comments failed to post (26)
crates/labcolors-core/src/accent_golden_tests.rs (1)
1-1: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите описание golden-контракта на русский.
Новая модульная документация и описание fixture helper не соответствуют языку документации репозитория.
As per coding guidelines: «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 10-26
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/accent_golden_tests.rs` at line 1, Переведите модульную документацию контракта AccentCurve и описание fixture helper в диапазоне 10–26 на краткий русский язык, сохранив смысл golden snapshot и структуру Diataxis. Изменяйте только документирующие комментарии, не затрагивая тестовую логику.Source: Coding guidelines
crates/labcolors-core/src/agnostic_gates.rs (1)
191-212: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Действительно переставьте роли в тесте порядка.
Текущий тест запускает только исходный порядок, поэтому не доказывает заявленную инвариантность. Скомпилируйте переставленную таблицу и сравните результаты; ссылку на будущий C7 удалите.
Предлагаемое усиление теста
- // or mutate either result. C7 will express such a relation explicitly. + // or mutate either result. let table = labui_reference().compile_named_role_table().unwrap(); let bg = BgInput::solid("`#767676`").unwrap(); let set = resolve_named_set(&bg, &table, &ViewingConditions::srgb()) .expect("valid opaque-role fixture must resolve"); + + let mut reordered_config = labui_reference(); + reordered_config.roles.reverse(); + let reordered_table = reordered_config + .compile_named_role_table() + .expect("reordering opaque declarations must remain valid"); + let reordered_set = resolve_named_set( + &bg, + &reordered_table, + &ViewingConditions::srgb(), + ) + .expect("reordered opaque-role fixture must resolve"); @@ for role in ["label-primary", "label-secondary", "border-strong"] { + assert_eq!(hex(&set, role), hex(&reordered_set, role)); + assert_eq!(compressed(&set, role), compressed(&reordered_set, role)); assert!(As per coding guidelines: «Core должен трактовать имена вроде
Primary,Danger,HoverиSurfaceкак непрозрачные ID и не содержать client-specific semantics, UI-пресеты или скрытые эвристики по именам»; «Не коммитьте roadmap […] или статус Issue-графа».📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.fn named_roles_do_not_gain_hierarchy_from_declaration_order() { // This background is an anti-vacuum witness: two independently solved fixture // anchors quantise to the same byte colour. Their neighbouring declaration // positions and client-owned names must not make Core invent a hierarchy edge // or mutate either result. let table = labui_reference().compile_named_role_table().unwrap(); let bg = BgInput::solid("`#767676`").unwrap(); let set = resolve_named_set(&bg, &table, &ViewingConditions::srgb()) .expect("valid opaque-role fixture must resolve"); let mut reordered_config = labui_reference(); reordered_config.roles.reverse(); let reordered_table = reordered_config .compile_named_role_table() .expect("reordering opaque declarations must remain valid"); let reordered_set = resolve_named_set( &bg, &reordered_table, &ViewingConditions::srgb(), ) .expect("reordered opaque-role fixture must resolve"); assert_eq!( hex(&set, "label-primary"), hex(&set, "label-secondary"), "fixture must exercise the equality that used to trigger inferred hierarchy" ); for role in ["label-primary", "label-secondary", "border-strong"] { assert_eq!(hex(&set, role), hex(&reordered_set, role)); assert_eq!(compressed(&set, role), compressed(&reordered_set, role)); assert!( !compressed(&set, role), "opaque role `{role}` acquired an undeclared order relation" ); } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/agnostic_gates.rs` around lines 191 - 212, Обновите тест named_roles_do_not_gain_hierarchy_from_declaration_order, чтобы собрать и скомпилировать переставленную таблицу ролей, разрешить её для того же bg и сравнить результаты с исходной таблицей для всех проверяемых ролей. Сохраните проверки отсутствия compressed-отношений и удалите комментарий со ссылкой на будущий C7, не добавляя семантики, зависящей от имён ролей.Source: Coding guidelines
crates/labcolors-core/src/config.rs (1)
1059-1074: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Не пропускайте cross-field validation после вычисления
RoleChroma.При exact-gray
neutral.anchors.darkбез override здесь выбираетсяRoleChroma::Neutral. Если конфиг содержит chromatic Brand/Family Material, последующийfrom_validated_partsобходитRoleSpec::validate_with_chroma:validate()возвращаетOk, ноresolve_named_set()позднее отклоняет весь набор какInvalidInput.Стройте таблицу через общий checked-путь либо возвращайте типизированную
ConfigErrorна preflight. Добавьте regression для exact-gray neutral + chromatic Material.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/config.rs` around lines 1059 - 1074, После вычисления RoleChroma в текущем конфигурационном пути сохраните cross-field validation для chromatic Brand/Family Material, включая exact-gray neutral без hue override. Стройте таблицу через общий checked-путь либо выполняйте preflight с типизированным ConfigError до обхода RoleSpec::validate_with_chroma, чтобы resolve_named_set() не отклонял уже построенный набор. Добавьте regression-тест для exact-gray neutral с chromatic Material.crates/labcolors-core/src/curve.rs (1)
5-15: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите новую публичную rustdoc на русский.
Описание
CurvePositionиColorCurveдобавлено на английском, хотя правило репозитория требует русскоязычную краткую документацию.As per coding guidelines: «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 19-19, 74-80, 90-95, 99-115
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/curve.rs` around lines 5 - 15, Переведите на русский краткую rustdoc-документацию для CurvePosition и ColorCurve, включая связанные блоки около конструктора, методов и примеров в указанных участках. Сохраните смысл описаний и compile_fail-примера, но используйте краткую структуру Diataxis и не изменяйте поведение кода.Source: Coding guidelines
crates/labcolors-core/src/lcs.rs (1)
10-14: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите новую rustdoc
LcsColorна русский.Документация нового locus-инварианта, accessor API и границы квантования не соответствует принятому языку документации.
As per coding guidelines: «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 24-31, 48-59, 78-83, 112-119, 134-139, 150-159
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/lcs.rs` around lines 10 - 14, Переведите на русский язык всю добавленную rustdoc-документацию для LcsColor, включая описание locus-инварианта, accessor API и границ квантования в указанных блоках. Сохраните краткость и примените подходящую структуру Diátaxis, не изменяя код или смысл технических контрактов.Source: Coding guidelines
crates/labcolors-core/src/lib.rs (1)
154-264: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Локализуйте документацию новых compile-fail контрактов.
Все новые публичные описания отрицательной API-поверхности написаны по-английски. Переведите пояснения, сохранив код doctest без изменений.
As per coding guidelines: «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/lib.rs` around lines 154 - 264, Переведите на русский язык все поясняющие doc-комментарии у структур InternalAccentRecipes, NoHueVisibilityVerdict, NoCompatibilityAliases, NoHybridLpcSurfaceMetric, NoPrematureScalarLpcApi и NoPublicPairRecipeApi, сохранив краткость и структуру Diataxis. Не изменяйте кодовые блоки compile_fail, импорты, выражения или атрибуты #[cfg(doctest)].Source: Coding guidelines
crates/labcolors-core/src/neutral.rs (1)
65-71: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите изменённые doc-комментарии на русский.
В публичной и тестовой документации остались полностью англоязычные либо смешанные формулировки.
As per coding guidelines: «Документацию следует писать по-русски и кратко».
Also applies to: 112-115, 130-130, 138-146, 279-284, 355-357, 441-443, 470-471, 489-491, 561-564, 592-594
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/neutral.rs` around lines 65 - 71, Переведите все изменённые doc-комментарии в neutral.rs, включая участки около символов и строк, указанных в замечании, на краткий русский язык. Уберите оставшиеся полностью англоязычные и смешанные формулировки, сохранив исходный технический смысл и без изменения кода.Source: Coding guidelines
crates/labcolors-core/src/semantic.rs (2)
395-417: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите новые публичные rustdoc на русский.
Документация
TextAnchor,DjMagnitude,RoleSpecиRoleChromaнарушает язык документации репозитория.As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 455-469, 494-529, 772-786, 858-878
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/semantic.rs` around lines 395 - 417, Переведите на русский язык новые публичные rustdoc для TextAnchor, DjMagnitude, RoleSpec и RoleChroma, включая связанные описания полей, конструкторов и методов в указанных участках. Сохраните точность терминов, ссылочные элементы rustdoc и краткую структуру Diataxis; изменяйте только документацию, не поведение кода.Source: Coding guidelines
801-804: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Синхронизируйте домен
canonical_hue_degс config boundary.Rustdoc заявляет проверяемый численный домен, но
NamedRoleTable::newпринимает любое конечное значение, включая1e308, тогда как config допускает только[0, 360). Нормализуйте угол до запуска curve scan либо отклоняйте значения вне канонического диапазона.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/semantic.rs` around lines 801 - 804, Синхронизируйте проверку canonical_hue_deg в NamedRoleTable::new с границей конфигурации [0, 360): до запуска curve scan нормализуйте угол в канонический диапазон либо отклоняйте значения вне него, включая чрезмерно большие конечные значения. Сохраните заявленный проверяемый численный домен для всех входов политики.crates/labcolors-core/src/solve.rs (1)
1393-1393: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Ys-тесты всё ещё используют retired H-K oracle.
apparent_contrast_candidate_*вычисляет вход черезY_hk, хотя эти тесты заявляют проверку Ys candidate-score. Для насыщенных фонов два домена могут даже выбрать разную полярность; замените вызовы наys_candidate_score_for_testили локальныйcandidate_lc. На black/white совпадение случайно скрывает ошибку.Also applies to: 1818-1823, 2484-2487, 3233-3244
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/solve.rs` at line 1393, Ys tests still use the retired H-K oracle through apparent_contrast_candidate_hex_with_vc_for_test, so they do not actually validate Ys candidate scoring. In the affected test sections, replace those calls with ys_candidate_score_for_test or a local candidate_lc calculation, preserving the existing candidate-score assertions. Update the related import and all occurrences also covered near the other referenced test ranges.crates/labcolors-core/src/spaces/cam16.rs (1)
105-131: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Вынесите коэффициенты CAM16 в единый источник истины.
Веса
[2, 1, 1/20]и константы400,27.13,0.42дублируют прямой CAM16-путь. Их следует именовать и совместно использовать вadaptи inverse, иначе изменение формулы рассинхронизирует преобразования.As per path instructions: «Отсутствие магических констант без комментариев». As per coding guidelines: «Каждая формула, граница или коэффициент должна быть отнесена к одному из явно указанных классов».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/spaces/cam16.rs` around lines 105 - 131, Вынесите веса и константы CAM16 из inverse-расчёта вокруг residual_slope в именованные общие константы или другой единый источник, уже используемый прямым путём adapt. Замените локальные W, 400, 27.13 и 0.42 в adapt и inverse ссылками на эти символы, сохранив текущие формулы и граничное поведение.Sources: Coding guidelines, Path instructions
crates/labcolors-core/src/spaces/srgb.rs (1)
199-210: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Не превращайте нечисловой цвет в правдоподобный чёрный.
NaNпроходит черезclamp/roundи приas u8становится0, поэтому публичныйhex_from_srgbмолча эмитит00. Сделайте квантование fallible либо принимайте валидированный тип конечного linear-sRGB.As per coding guidelines: «Новый или изменяемый public path не должен вызывать panic или возвращать plausible fallback; invalid … context должны возвращаться типизированно».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/spaces/srgb.rs` around lines 199 - 210, The public hex_from_srgb path must not convert NaN or other non-finite linear-sRGB components into 00. Make srgb8_from_linear fallible or require a validated finite linear-sRGB type, and propagate a typed error through hex_from_srgb instead of allowing the cast fallback; preserve normal quantization for valid inputs.Source: Coding guidelines
crates/labcolors-core/src/spaces/vc.rs (1)
24-32: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите новую публичную документацию на русский.
Новые rustdoc для инварианта и getters написаны по-английски.
As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 78-121, 165-171
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/spaces/vc.rs` around lines 24 - 32, Переведите на русский язык новые публичные rustdoc-комментарии, описывающие инвариант производных полей и getters, в ViewingConditions и связанных участках, сохранив их краткость и структуру Diataxis. Не изменяйте код, примеры compile_fail или смысл документации.Source: Coding guidelines
crates/labcolors-core/src/wcag.rs (1)
116-116: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите изменённый doc-комментарий на русский.
Формулировка про candidate curve должна соответствовать принятому языку документации.
As per coding guidelines: «Документацию следует писать по-русски и кратко».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/wcag.rs` at line 116, Переведите изменённый doc-комментарий в `wcag.rs` на краткий русский язык, сохранив смысл сравнения с кривой кандидата (`candidate curve`) и используя принятую терминологию документации.Source: Coding guidelines
crates/labcolors-core/tests/agnostic_production_surface.rs (1)
1-10: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите новые документирующие комментарии на русский.
Module docs и комментарии к scanner-контрактам преимущественно написаны по-английски.
As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 43-48, 65-70, 84-112, 239-256, 275-301
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/tests/agnostic_production_surface.rs` around lines 1 - 10, Переведите на русский новые модульные документы и комментарии к контрактам scanner в тесте agnostic_production_surface, включая участки 43–48, 65–70, 84–112, 239–256 и 275–301. Сохраните краткость, технический смысл и существующую структуру документации Diataxis; изменяйте только англоязычные пояснения, не затрагивая код, идентификаторы и проверяемые значения.Source: Coding guidelines
crates/labcolors-core/tests/empirical_inventory.rs (1)
60-62: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Укажите
spaces/oklab.rsв перечне STANDARD-MODEL модулей.После добавления файла на Line 41 комментарий о «remaining modules» перечисляет только четыре из пяти неполитических модулей. Это искажает заявленную область numeric-аудита.
Предлагаемая правка
-// modules (`scale.rs`, `lpc.rs`, `lcs.rs`, `solve.rs`) are STANDARD-MODEL +// modules (`scale.rs`, `spaces/oklab.rs`, `lpc.rs`, `lcs.rs`, `solve.rs`) are +// STANDARD-MODELAs per coding guidelines, «Комментарий в коде должен объяснять, почему существует решение и какой инвариант оно сохраняет, а не пересказывать оператор».
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.// modules (`scale.rs`, `spaces/oklab.rs`, `lpc.rs`, `lcs.rs`, `solve.rs`) are // STANDARD-MODEL🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/tests/empirical_inventory.rs` around lines 60 - 62, Обновите комментарий в тесте empirical_inventory.rs, дополнив перечень STANDARD-MODEL модулей символом spaces/oklab.rs рядом с scale.rs, lpc.rs, lcs.rs и solve.rs. Сохраните пояснение о том, что остальные модули являются стандартной моделью и входят в numeric-аудит.Source: Coding guidelines
crates/labcolors-core/tests/hue_sweep.rs (1)
38-43: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Не называйте знаковую candidate-координату readability-величиной.
candidate_lcвозвращает знаковое значение, но комментарий описывает его как|Lc| MAGNITUDEи «readability domain». Это противоречит проверке полярности ниже и новому публичному контракту.Предлагаемая правка
-/// Independent re-measure of an emitted hex's `|Lc|` MAGNITUDE in the readability -/// domain the solver targets since глава `#64` (ADR-0003): `Ys` (WCAG relative -/// luminance of the emitted display bytes). Rechecking through the public -/// resolver boundary keeps the test on the actual production axis. +/// Независимое повторное измерение знаковой candidate-оценки `Lc` по `Ys` +/// на финальных sRGB8-байтах. Проверка через публичный `recheck_against` +/// сохраняет тест на фактически испускаемом состоянии.As per coding guidelines, «Не называйте chroma, saturation, purity, preference, harmony или один RGB-derived scalar универсальной „чистотой“ цвета; человеческий смысл утверждайте только в границах опубликованных данных».
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements./// Независимое повторное измерение знаковой candidate-оценки `Lc` по `Ys` /// на финальных sRGB8-байтах. Проверка через публичный `recheck_against` /// сохраняет тест на фактически испускаемом состоянии. fn candidate_lc(fg_hex: &str, bg_hex: &str, vc: &ViewingConditions) -> f64 { recheck_against(bg_hex, &[fg_hex], vc).expect("solver and fixture emit valid sRGB8 hex")[0].0🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/tests/hue_sweep.rs` around lines 38 - 43, Update the documentation for candidate_lc to describe its signed lightness-contrast coordinate, not an absolute magnitude or universal readability measure. Keep the implementation unchanged and state only that it is rechecked through the public resolver boundary against the solver’s luminance axis, preserving the polarity semantics validated below.Source: Coding guidelines
crates/labcolors-core/tests/on_disk_audit_probe.rs (1)
58-68: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите изменённое описание изоляции на русский.
Публичная модульная документация и doc-комментарий теста написаны по-английски.
As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 169-170
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/tests/on_disk_audit_probe.rs` around lines 58 - 68, Translate the updated isolation documentation in the module-level comments around the temp-directory copy and atomic write, including the related comments at the additional referenced section, into concise Russian. Preserve the existing technical meaning and structure while leaving code unchanged.Source: Coding guidelines
crates/labcolors-core/tests/splice_support.rs (1)
1-3: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите модульную документацию на русский.
As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/tests/splice_support.rs` around lines 1 - 3, Переведите модульную документацию в начале модуля splice_support на русский язык, сохранив её краткость и описательный смысл; структуру кода и остальные элементы модуля не изменяйте.Source: Coding guidelines
crates/labcolors-wasm/src/lib.rs (1)
54-62: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Переведите изменённую публичную документацию на русский.
Эти doc-комментарии экспортируются в TypeScript API, но написаны по-английски. Заодно в Line 106 используйте каноническое имя
lc, а неLc.As per coding guidelines, «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
Also applies to: 106-106, 122-124, 661-667, 703-705
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-wasm/src/lib.rs` around lines 54 - 62, Переведите на русский и кратко перепишите публичные doc-комментарии экспортируемого TypeScript API для полей lc, wcagRatio, compressed, achievedDj и связанных участков, сохранив точное описание их поведения и структуру Diataxis. В комментарии на участке 106 используйте каноническое имя lc вместо Lc; обновите также отмеченные участки 122–124, 661–667 и 703–705, не изменяя реализацию.Source: Coding guidelines
docs/decisions/0001-config-boundary.md (1)
28-31: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Возможная опечатка: «названным» → проверьте написание.
Статический анализатор (LanguageTool) отмечает потенциальную орфографическую ошибку в этом месте — причастие от приставочного глагола пишется с двумя «н».
📝 Предлагаемое исправление
-семантически названым special case. +семантически названным special case.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.Текущая версия ещё содержит закрытое физическое меню рецептов и позиций лестницы. Оно не анализирует client ID, но и не является целевой произвольной топологией: новые продуктовые потребности не должны расширять его очередным семантически названным special case.🧰 Tools
🪛 LanguageTool
[uncategorized] ~31-~31: Прилагательное пишется с «н», зависимых слов нет: «названым»
Context: ...ны расширять его очередным семантически названным special case. ## JSON-схема `ThemeCon...(NN_N_pril_prich)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/decisions/0001-config-boundary.md` around lines 28 - 31, Проверьте слово «названным» в предложении о special case: оно уже написано правильно, с двумя «н». Не вносите изменений в этот фрагмент, если дополнительная проверка не выявит иной орфографической ошибки.Source: Linters/SAST tools
docs/whitepaper.md (2)
119-121: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Стилистический повтор «их» в одном предложении.
"...используют тот же якорь как источник идентичности, но их итог определяется их физическим контрактом."— двойное «их» затрудняет чтение.📝 Предлагаемое исправление
-как источник идентичности, но их итог определяется их физическим контрактом. +как источник идентичности, но итог определяется их собственным физическим контрактом.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.режимах. Производные foreground, surface и effect-роли используют тот же якорь как источник идентичности, но итог определяется их собственным физическим контрактом.🧰 Tools
🪛 LanguageTool
[uncategorized] ~120-~120: Стиль: не ставьте два «их» в предложении.
Context: ...к идентичности, но их итог определяется их физическим контрактом.NeutralCurve,...(DoubleIH)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/whitepaper.md` around lines 119 - 121, В предложении о производных foreground, surface и effect-ролях устраните повтор местоимения «их», сохранив смысл о том, что итог ролей определяется их физическим контрактом.Source: Linters/SAST tools
152-155: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Возможная опечатка: «названной» — проверьте написание.
Статический анализатор указывает на потенциальную орфографическую ошибку рядом с «Exact-сертификат относится только к названной конечной арифметике…» — причастие от приставочного глагола пишется с двумя «н».
🧰 Tools
🪛 LanguageTool
[uncategorized] ~153-~153: Прилагательное пишется с «н», зависимых слов нет: «названой»
Context: ...r. Exact-сертификат относится только к названной конечной арифметике и версионированному...(NN_N_pril_prich)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/whitepaper.md` around lines 152 - 155, В предложении про «Exact-сертификат» исправьте написание слова «названной» в соответствии с орфографической рекомендацией, не изменяя остальной смысл или формулировку абзаца.Source: Linters/SAST tools
packages/colors/test/public-claims.test.mjs (1)
744-769: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Расширьте sentiment-gate на всю production-поверхность.
Сейчас код проверяется только в четырёх файлах. Возврат
SentimentCurveвsemantic.rs, projection или runtime пакета останется незамеченным, хотя тест заявляет полное удаление модели.Предлагаемое расширение проверки
+ const productionSurfaces = [ + ...claimFiles(join(ROOT, "crates"), [], /\.rs$/u), + ...claimFiles(join(ROOT, "packages", "colors"), [], /\.(?:js|mjs|ts)$/u), + ].filter( + (path) => + !/(?:^|[/\\])(?:test|tests|benches|examples)(?:[/\\]|$)/u.test( + relative(ROOT, path), + ), + ); + + for (const path of productionSurfaces) { + assert.doesNotMatch( + readFileSync(path, "utf8"), + RETIRED_SENTIMENT_MODEL, + `${relative(ROOT, path)}: retired sentiment model resurfaced`, + ); + }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const productionSurfaces = [ ...claimFiles(join(ROOT, "crates"), [], /\.rs$/u), ...claimFiles(join(ROOT, "packages", "colors"), [], /\.(?:js|mjs|ts)$/u), ].filter( (path) => !/(?:^|[/\\])(?:test|tests|benches|examples)(?:[/\\]|$)/u.test( relative(ROOT, path), ), ); for (const path of productionSurfaces) { assert.doesNotMatch( readFileSync(path, "utf8"), RETIRED_SENTIMENT_MODEL, `${relative(ROOT, path)}: retired sentiment model resurfaced`, ); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/colors/test/public-claims.test.mjs` around lines 744 - 769, Расширьте проверку `surfaces` в тесте `public-claims.test.mjs` на всю production-поверхность, включая `semantic.rs`, projection и runtime-модули пакетов. Добавьте соответствующие пути и регулярные выражения для всех удалённых sentiment-символов, включая `SentimentCurve` и связанные API, чтобы любое их возвращение приводило к ошибке теста; существующие проверки сохраните.packages/colors/test/release-contract.test.mjs (1)
87-93: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Ограничьте проверки секцией
[workspace.package].Текущие регулярные выражения просматривают весь остаток файла. При неверной workspace-версии тест ложно пройдёт, если
0.3.0,rust-versionили repository встретятся в последующей секции.Предлагаемое исправление
const workspace = read("Cargo.toml"); -assert.match(workspace, /\[workspace\.package\][\s\S]*\nversion = "0\.3\.0"/); -assert.match(workspace, /\nrust-version = "1\.85"/); +const workspacePackage = workspace + .split(/(?=^\[)/m) + .find((section) => section.startsWith("[workspace.package]")); +assert.ok(workspacePackage, "missing [workspace.package]"); +assert.match(workspacePackage, /^version = "0\.3\.0"$/m); +assert.match(workspacePackage, /^rust-version = "1\.85"$/m); assert.match( - workspace, - /repository = "https:\/\/github\.com\/Labpics-Team\/lab-colors"/, + workspacePackage, + /^repository = "https:\/\/github\.com\/Labpics-Team\/lab-colors"$/m, );📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.const workspace = read("Cargo.toml"); const workspacePackage = workspace .split(/(?=^\[)/m) .find((section) => section.startsWith("[workspace.package]")); assert.ok(workspacePackage, "missing [workspace.package]"); assert.match(workspacePackage, /^version = "0\.3\.0"$/m); assert.match(workspacePackage, /^rust-version = "1\.85"$/m); assert.match( workspacePackage, /^repository = "https:\/\/github\.com\/Labpics-Team\/lab-colors"$/m, );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/colors/test/release-contract.test.mjs` around lines 87 - 93, Ограничьте проверки version, rust-version и repository в тесте release-contract через границы секции [workspace.package], чтобы совпадения из последующих секций не учитывались. Обновите регулярные выражения вокруг этих assert.match, сохранив текущие ожидаемые значения и проверку обязательных полей.README.md (1)
9-28: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Опишите текущий контракт вместо roadmap перехода.
Фразы «появится» и «подлежат удалению после» фиксируют будущий план в README. Оставьте только поведение версии 0.3.0 и явно отсутствующие гарантии.
Предлагаемая формулировка
-Целевая архитектура Lab Colors принимает декларативную программу клиента, +Lab Colors 0.3.0 принимает декларативную конфигурацию клиента, связывает цветовые источники с местами их использования и разрешает зависимый -граф для текущего локального контекста. Нынешний браузерный runtime уже -перепроверяет окружение, но при необходимости повторно решает всю таблицу; -selective re-resolve появится вместе с публичным dependency graph. +граф для текущего локального контекста. Браузерный runtime перепроверяет +окружение и повторно решает всю таблицу. -Целевой pipeline: +Текущий pipeline: @@ -→ runtime invalidation + selective re-resolve +→ runtime invalidation + full-table re-resolve @@ -Они документируют только поддерживаемый сегодня ввод и подлежат удалению после переноса полезных -source-over, screen, ordering и occurrence-законов в общий граф. +Они описывают поддерживаемый в версии 0.3.0 ввод и не являются extension point.As per coding guidelines: «Не коммитьте roadmap, prompt, внутренний handoff, статус Issue-графа, временный benchmark dump или миграционную хронику».
Also applies to: 142-149
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.md` around lines 9 - 28, Перепишите раздел README о целевой архитектуре, описывая только фактический контракт версии 0.3.0: текущий browser runtime, повторное разрешение всей таблицы при изменении контекста и переходную модель NamedRoleTable/рецептов. Удалите формулировки о будущем selective re-resolve, публичном dependency graph и прочих планах миграции; явно укажите гарантии и возможности, которых текущая версия не предоставляет.Source: Coding guidelines
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
crates/labcolors-wasm/src/dto.rs (1)
148-151: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winУдалите утверждение о compatibility-алиасе.
У
MaterialColorнет такого булевого поля, а TypeScript-контракт уже удалилguaranteed. Этот Rustdoc обещает потребителю несуществующую поверхность.Предлагаемое исправление
- /// Типизированный исход проверки пола; от него выведен булев псевдоним совместимости. + /// Типизированный исход проверки пола.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-wasm/src/dto.rs` around lines 148 - 151, Удалите из Rustdoc поля alpha_status в структуре MaterialColor утверждение о выведенном булевом compatibility-алиасе; оставьте только описание типизированного результата проверки, соответствующее фактическому полю и актуальному TypeScript-контракту.crates/labcolors-wasm/src/lib.rs (1)
376-405: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy liftУдалите публичный
RoleRecipeиз конфигурационного контракта.
ThemeConfig.rolesпо-прежнему принимает специальный recipe enum, причём комментарий прямо называет его compatibility surface. Это сохраняет дублирующую legacy-модель на публичной границе вместо графа render/occurrence и противоречит заявленному breaking cleanup. Замените его целевым графовым контрактом и удалите recipe-путь в этом PR.As per coding guidelines: «Роли foreground, surface и layer должны задаваться графом render/occurrence, а не именами токенов или специальным recipe enum» и «PR готов только без TODO, compatibility shim, silent fallback…».
Also applies to: 423-426
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-wasm/src/lib.rs` around lines 376 - 405, Удалите публичный тип RoleRecipe и весь recipe-контракт из ThemeConfig.roles, включая связанные ветки обработки и compatibility surface. Переведите роли foreground, surface и layer на целевой граф render/occurrence, обновив соответствующие типы и потребителей вместо сохранения recipe enum или fallback-пути; уберите оставшиеся TODO и compatibility shim.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/labcolors-core/src/config/tests.rs`:
- Around line 1966-1968: Переведите doc-комментарий над тестом NeutralPick на
краткий русский язык, сохранив смысл о том, что точный серый выбранный якорь
остаётся ахроматичным и не наследует общий хроматический подтон таблицы.
In `@crates/labcolors-core/tests/agnostic_production_surface.rs`:
- Around line 104-107: Update production_lines to track braces only in Rust
code, ignoring string literals and line/block comments; preserve removal of
#[cfg(test)] blocks and semicolon-terminated declarations. Add a RED regression
test in the agnostic production-surface tests using a brace inside a test-module
string (and comments if applicable), verifying subsequent production lines
remain visible and forbidden identifiers are detected.
In `@crates/labcolors-wasm/src/dto.rs`:
- Around line 208-210: Обновите документацию поля achieved_dj, убрав устаревшее
обозначение candidate-score как `Lc`. Для contrast-score ролей опишите
переходную координату через актуальную знаковую Ys candidate-координату `lc`, не
связывая её с LPC или доказательством читаемости; остальную семантику поля
сохраните.
In `@packages/colors/effective-bg.js`:
- Around line 108-109: Переведите изменённый JSDoc-комментарий рядом с
oklabToLinearRgb и linearToSrgb на краткий русский язык, сохранив описание того
же преобразования в sRGB и инвариант clamp-then-round для финального
sRGB8-вывода.
In `@packages/colors/test/public-claims.test.mjs`:
- Around line 347-350: Update productionRustFiles so its src-directory filter is
path-separator independent on Windows and POSIX systems, using the existing path
utilities or an equivalent separator-agnostic check instead of
file.includes("/src/"). Preserve the Rust extension filtering and
production-file scope.
In `@scripts/cargo-workspace.mjs`:
- Around line 42-55: Update the comments above workspacePackageTable and
workspaceVersion to document the parsing rationale and invariant: release
metadata must be read only from [workspace.package] and must never leak from a
subsequent TOML table. Replace the current action-oriented wording while
preserving the existing parsing behavior.
---
Outside diff comments:
In `@crates/labcolors-wasm/src/dto.rs`:
- Around line 148-151: Удалите из Rustdoc поля alpha_status в структуре
MaterialColor утверждение о выведенном булевом compatibility-алиасе; оставьте
только описание типизированного результата проверки, соответствующее
фактическому полю и актуальному TypeScript-контракту.
In `@crates/labcolors-wasm/src/lib.rs`:
- Around line 376-405: Удалите публичный тип RoleRecipe и весь recipe-контракт
из ThemeConfig.roles, включая связанные ветки обработки и compatibility surface.
Переведите роли foreground, surface и layer на целевой граф render/occurrence,
обновив соответствующие типы и потребителей вместо сохранения recipe enum или
fallback-пути; уберите оставшиеся TODO и compatibility shim.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 58b421d9-7e3d-40d9-807e-00549a57d5dc
📒 Files selected for processing (31)
README.mdcrates/labcolors-core/src/accent_golden_tests.rscrates/labcolors-core/src/agnostic_gates.rscrates/labcolors-core/src/config.rscrates/labcolors-core/src/config/tests.rscrates/labcolors-core/src/curve.rscrates/labcolors-core/src/lcs.rscrates/labcolors-core/src/lib.rscrates/labcolors-core/src/neutral.rscrates/labcolors-core/src/pair_label_tests.rscrates/labcolors-core/src/semantic.rscrates/labcolors-core/src/solve.rscrates/labcolors-core/src/spaces/cam16.rscrates/labcolors-core/src/spaces/srgb.rscrates/labcolors-core/src/spaces/vc.rscrates/labcolors-core/src/wcag.rscrates/labcolors-core/tests/agnostic_production_surface.rscrates/labcolors-core/tests/empirical_inventory.rscrates/labcolors-core/tests/hue_sweep.rscrates/labcolors-core/tests/on_disk_audit_probe.rscrates/labcolors-core/tests/splice_support.rscrates/labcolors-wasm/src/dto.rscrates/labcolors-wasm/src/lib.rsdocs/whitepaper.mdpackages/colors/bench/wasm-size-budget-v14.jsonpackages/colors/effective-bg.jspackages/colors/test/public-claims.test.mjspackages/colors/test/release-contract.test.mjspackages/colors/test/release-provenance.test.mjsscripts/cargo-workspace.mjsscripts/check-wasm-size-budget.mjs
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/labcolors-core/src/srgb8.rs (1)
42-52: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winПереведите новые doc-комментарии на русский.
Комментарии к
to_hexиis_achromaticостаются англоязычными.As per coding guidelines: «Документацию следует писать по-русски и кратко, с применением структуры Diataxis».
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/labcolors-core/src/srgb8.rs` around lines 42 - 52, Переведите на русский краткие doc-комментарии для методов to_hex и is_achromatic, сохранив их смысл и структуру Diataxis. Не изменяйте реализацию методов или другие англоязычные комментарии.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/colors/test/release-contract.test.mjs`:
- Around line 1717-1723: Обновите тест вокруг checker.parseBudgetDocument:
вместо прямого вызова запишите мутированный budget и проверьте поведение через
CLI-путь run с отсутствующим или невалидным WASM. Утверждайте конкретный schema
diagnostic, а не любое исключение, чтобы тест подтверждал валидацию схемы до
чтения и оценки артефакта.
---
Outside diff comments:
In `@crates/labcolors-core/src/srgb8.rs`:
- Around line 42-52: Переведите на русский краткие doc-комментарии для методов
to_hex и is_achromatic, сохранив их смысл и структуру Diataxis. Не изменяйте
реализацию методов или другие англоязычные комментарии.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 57c34d94-3f30-4e89-a709-b9a9ba3e7668
📒 Files selected for processing (19)
crates/labcolors-core/src/alpha.rscrates/labcolors-core/src/config.rscrates/labcolors-core/src/config/tests.rscrates/labcolors-core/src/glow.rscrates/labcolors-core/src/semantic.rscrates/labcolors-core/src/solve.rscrates/labcolors-core/src/spaces/oklab.rscrates/labcolors-core/src/spaces/srgb.rscrates/labcolors-core/src/srgb8.rscrates/labcolors-core/tests/agnostic_production_surface.rscrates/labcolors-core/tests/common/mod.rscrates/labcolors-core/tests/common/source.rscrates/labcolors-core/tests/empirical_inventory.rscrates/labcolors-wasm/src/dto.rspackages/colors/effective-bg.jspackages/colors/test/public-claims.test.mjspackages/colors/test/release-contract.test.mjspackages/colors/test/release-provenance.test.mjsscripts/cargo-workspace.mjs
Зачем
В Core накопились клиентская sentiment-семантика, специальные hue-правила и недоказанные perceptual claims. Причина — временные исследовательские и recipe-швы стали публичным контрактом раньше общего occurrence/constraint-графа, а затем сохранялись как compatibility surface при отсутствии клиентов.
C6 удаляет эту физику, не подменяя её новой гипотезой.
Что изменено
sentiment.rs, sentiment schema/DTO,SentimentCategory,SentimentsConfig,LadderSource::Sentiment, специальные ошибки, ручки и тесты.lpc,pairиaccent_balanceстали внутренними;accent_surface, scalar/hybrid LPC helpers иTypographicContextудалены.neutral.tint.ratio, flat-neutral path, Y-HK benchmark seam и недоказанные result aliaseshueVanished, GlowachievedDj/degraded, Materialguaranteed.LcsColorиCurvePositionтеперь несут собственные инварианты; non-finite и out-of-range состояния нельзя представить через публичный API.h_ok = 0.Solved::color()иSolved::hex()используют один источник истины.deny_unknown_fields: удалённые поля отклоняются явно.chromatic Material source + neutral policyотклоняется на compile-boundary, без тихой потери клиентского цвета; config и runtime используют один предикат и одну причину ошибки.Srgb8SSOT без численного дрейфа.lcописан только как знаковая candidate-координата замороженной SAPC-shaped кривой вYs. Это не LPC/readability verdict и не certificate; нормативный WCAG evaluator остаётся отдельной поверхностью.cfg(test), комментариев и литералов; release/provenance guards проверяют настоящий CLI-путь и exact source.Breaking changes
sentiments, sourcekind: "sentiment"иneutral.tint.ratioбольше не принимаются.LcsColorдоступны только через getters.h_ok()теперь всегда возвращает канонический ноль.ConfigError::IncompatibleRolePolicyбольше не несёт произвольныйreason: у варианта одна каноническая причина.Compatibility shims намеренно не добавлены: клиентов нет, а двойная schema восстановила бы удаляемую физику и второй SSOT.
Доказательства
h_ok_bitsexact-gray строк.455074 B → 428403 B(−26671 B); append-only exact v15 ratchet, без headroom. Измерение: run29654779091; финальное подтверждение exact-head: run29655394803, artifact SHA-256145098c0cb1b8c199b7cb3580362f47f4b79f39ee7311bdeed2303c378e6f88a.428281 B, SHA-256af0e13a0a5349a2fb322cbffe5e07159bde482db81263d87bc31a68b8180c438.Риск и откат
Ожидаемый риск — compile/config break для скрытой интеграции и изменение только hue-coordinate exact-gray результатов. Эмитированные gray-байты не меняются.
Откат допустим только целиком: schema, generated types, fixtures, guards и документация связаны. Частично возвращать sentiment/LPC aliases в Core нельзя.
Не входит в срез
Это cleanup-фундамент.
PairFill,PairLabel,GlowиMaterialостаются переходным transport старого API, не целевой архитектурой. Их последующая замена — единый графclient token + source + occurrence/surface relation + constraints.