@bonesofspring/ai-rules 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/package.json +1 -1
  3. package/presets/_shared/README.md +1 -1
  4. package/presets/_shared/core/meta/preset-token-budget.md +1 -1
  5. package/presets/_shared/core/quality/anti-sycophancy-discipline.md +21 -0
  6. package/presets/_shared/core/quality/code-quality-and-refactoring.md +21 -52
  7. package/presets/claude/go/agents/ci-investigator.md +4 -0
  8. package/presets/claude/go/agents/debugger.md +4 -0
  9. package/presets/claude/go/agents/feature-developer.md +4 -0
  10. package/presets/claude/go/rules/README.md +1 -0
  11. package/presets/claude/go/rules/api-and-data/persistence-adapters.md +10 -7
  12. package/presets/claude/go/rules/architecture/application-usecases.md +9 -5
  13. package/presets/claude/go/rules/architecture/boundaries.md +6 -1
  14. package/presets/claude/go/rules/architecture/composition-root.md +14 -9
  15. package/presets/claude/go/rules/testing/e2e.md +8 -6
  16. package/presets/claude/go/rules/testing/integration.md +11 -5
  17. package/presets/claude/go/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  18. package/presets/claude/go/rules/tooling-and-review/code-quality.md +22 -53
  19. package/presets/claude/go/rules/tooling-and-review/preset-token-budget.md +1 -1
  20. package/presets/claude/go/rules/tooling-and-review/security-go.md +17 -5
  21. package/presets/claude/ios-swift/README.md +1 -1
  22. package/presets/claude/ios-swift/agents/build-verifier.md +1 -1
  23. package/presets/claude/ios-swift/agents/ci-investigator.md +4 -0
  24. package/presets/claude/ios-swift/agents/debugger.md +4 -0
  25. package/presets/claude/ios-swift/agents/feature-developer.md +4 -0
  26. package/presets/claude/ios-swift/rules/README.md +3 -1
  27. package/presets/claude/ios-swift/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  28. package/presets/claude/ios-swift/rules/tooling-and-review/code-quality.md +23 -54
  29. package/presets/claude/ios-swift/rules/tooling-and-review/preset-token-budget.md +1 -1
  30. package/presets/claude/java/agents/build-verifier.md +1 -1
  31. package/presets/claude/java/agents/ci-investigator.md +4 -0
  32. package/presets/claude/java/agents/debugger.md +4 -0
  33. package/presets/claude/java/agents/feature-developer.md +4 -0
  34. package/presets/claude/java/rules/README.md +2 -1
  35. package/presets/claude/java/rules/api-and-data/messaging-adapters.md +16 -9
  36. package/presets/claude/java/rules/architecture/boundaries.md +6 -1
  37. package/presets/claude/java/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  38. package/presets/claude/java/rules/tooling-and-review/code-quality.md +21 -52
  39. package/presets/claude/java/rules/tooling-and-review/preset-token-budget.md +1 -1
  40. package/presets/claude/next/agents/build-verifier.md +1 -1
  41. package/presets/claude/next/agents/ci-investigator.md +4 -0
  42. package/presets/claude/next/agents/debugger.md +4 -0
  43. package/presets/claude/next/agents/feature-developer.md +8 -0
  44. package/presets/claude/next/rules/README.md +5 -1
  45. package/presets/claude/next/rules/anti-hallucination/react-next-anti-hallucination.md +67 -0
  46. package/presets/claude/next/rules/stack/next-app-router.md +2 -0
  47. package/presets/claude/next/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  48. package/presets/claude/next/rules/tooling-and-review/code-quality.md +25 -55
  49. package/presets/claude/next/rules/tooling-and-review/preset-token-budget.md +1 -1
  50. package/presets/claude/next/skills/feature-delivery/SKILL.md +4 -0
  51. package/presets/cursor/go/agents/ci-investigator.md +4 -0
  52. package/presets/cursor/go/agents/debugger.md +4 -0
  53. package/presets/cursor/go/agents/feature-developer.md +4 -0
  54. package/presets/cursor/go/rules/README.md +11 -9
  55. package/presets/cursor/go/rules/anti-sycophancy-discipline.mdc +30 -0
  56. package/presets/cursor/go/rules/application-usecases.mdc +9 -5
  57. package/presets/cursor/go/rules/architecture-boundaries.mdc +6 -0
  58. package/presets/cursor/go/rules/code-quality-and-refactoring.mdc +21 -52
  59. package/presets/cursor/go/rules/composition-root.mdc +14 -9
  60. package/presets/cursor/go/rules/persistence-adapters.mdc +10 -7
  61. package/presets/cursor/go/rules/preset-token-budget.mdc +1 -1
  62. package/presets/cursor/go/rules/security-go.mdc +17 -5
  63. package/presets/cursor/go/rules/tests-e2e.mdc +8 -6
  64. package/presets/cursor/go/rules/tests-integration.mdc +11 -5
  65. package/presets/cursor/ios-swift/agents/build-verifier.md +1 -1
  66. package/presets/cursor/ios-swift/agents/ci-investigator.md +4 -0
  67. package/presets/cursor/ios-swift/agents/debugger.md +4 -0
  68. package/presets/cursor/ios-swift/agents/feature-developer.md +4 -0
  69. package/presets/cursor/ios-swift/rules/README.md +4 -2
  70. package/presets/cursor/ios-swift/rules/anti-sycophancy-discipline.mdc +30 -0
  71. package/presets/cursor/ios-swift/rules/code-quality-and-refactoring.mdc +21 -52
  72. package/presets/cursor/ios-swift/rules/preset-token-budget.mdc +1 -1
  73. package/presets/cursor/java/README.md +1 -1
  74. package/presets/cursor/java/agents/build-verifier.md +1 -1
  75. package/presets/cursor/java/agents/ci-investigator.md +4 -0
  76. package/presets/cursor/java/agents/debugger.md +4 -0
  77. package/presets/cursor/java/agents/feature-developer.md +4 -0
  78. package/presets/cursor/java/rules/README.md +7 -5
  79. package/presets/cursor/java/rules/anti-sycophancy-discipline.mdc +30 -0
  80. package/presets/cursor/java/rules/architecture-boundaries.mdc +6 -0
  81. package/presets/cursor/java/rules/code-quality-and-refactoring.mdc +21 -52
  82. package/presets/cursor/java/rules/messaging-adapters.mdc +16 -10
  83. package/presets/cursor/java/rules/preset-token-budget.mdc +1 -1
  84. package/presets/cursor/next/agents/build-verifier.md +1 -1
  85. package/presets/cursor/next/agents/ci-investigator.md +4 -0
  86. package/presets/cursor/next/agents/debugger.md +4 -0
  87. package/presets/cursor/next/agents/feature-developer.md +8 -0
  88. package/presets/cursor/next/rules/README.md +4 -2
  89. package/presets/cursor/next/rules/anti-sycophancy-discipline.mdc +30 -0
  90. package/presets/cursor/next/rules/code-quality-and-refactoring.mdc +21 -52
  91. package/presets/cursor/next/rules/next-app-router.mdc +2 -0
  92. package/presets/cursor/next/rules/preset-token-budget.mdc +1 -1
  93. package/presets/cursor/next/rules/react-next-anti-hallucination.mdc +66 -0
  94. package/presets/cursor/next/skills/feature-delivery/SKILL.md +4 -0
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: Messaging driven/driving adapters for Java hexagonal services (stub)
2
+ description: Messaging driven/driving adapters for Java hexagonal services
3
3
  globs:
4
4
  - "**/adapters/outbound/messaging/**/*"
5
5
  - "**/adapters/inbound/messaging/**/*"
@@ -7,20 +7,26 @@ globs:
7
7
  alwaysApply: false
8
8
  ---
9
9
 
10
+ # Messaging adapters
10
11
 
11
- # Messaging adapters (documented stub)
12
+ - **Publisher** (driven): implements an outbound port; serializes application/domain events to wire format inside the adapter.
13
+ - **Consumer** (driving): deserializes → maps to application/domain types → calls inbound port / use case; **ack/nack** (and commit) stays in the adapter.
14
+ - Idempotency keys, retry, and DLQ/parking-lot policy are adapter (or infra) concerns — document at-least-once vs exactly-once assumptions at the port.
15
+ - Use the broker client already present in the repo (`KafkaTemplate`, JMS, Spring Cloud Stream, etc.) — do not invent a second stack.
12
16
 
13
- > **Stub (v1):** Light guidance only — not a full Kafka/Rabbit/JMS cookbook. **When to use:** editing `adapters/**/messaging/**` or adding broker publishers/consumers. Prefer expanding this rule when the consumer repo standardizes on a broker.
17
+ ## Event shapes
14
18
 
15
- - **Publisher** (driven): implements outbound port; serializes domain events / integration events.
16
- - **Consumer** (driving): deserializes calls use case / inbound port; ack/nack policy here.
17
- - Idempotency keys and retry/DLQ are adapter concerns; document at-least-once assumptions.
18
- - Do not put broker client types (`KafkaTemplate`, JMS sessions, etc.) in domain or application signatures.
19
+ - Prefer explicit event types in application or a small `events` package used by ports.
20
+ - Map wire DTOs ↔ application events **only** in the adapter; never pass `ConsumerRecord` / broker payloads into domain.
19
21
 
20
- ## Event shapes
22
+ ## Forbidden
21
23
 
22
- - Prefer explicit event types in application or a small `events` package used by ports — map to wire format in the adapter.
24
+ - Broker client types (`KafkaTemplate`, JMS sessions, `MessageListener`) in domain or application signatures.
25
+ - Business rules inside listeners beyond mapping + calling one use case.
26
+ - Silent catch-and-ack that drops poison messages without DLQ/metrics policy.
23
27
 
24
28
  ## Tests
25
29
 
26
- - Unit-test mapping with fakes; integration against embedded/broker Testcontainers when the repo has them.
30
+ - Unit-test mapping and idempotency branches with fakes.
31
+ - Integration against embedded broker / Testcontainers **when the repo already has that setup**.
32
+ - After edits: `post-change-test` (+ `java-tooling`); agents `integration-test-*` when adding consumer contracts.
@@ -22,7 +22,7 @@ alwaysApply: false
22
22
 
23
23
  **Claude Option A (README exclusion):** when counting Claude rules without `paths:` / session-start, **exclude `**/README.md`** (topic indexes are not session-start rules). The intended session-start trio remains **exactly 3**; body budget sums **only those 3** rules.
24
24
 
25
- Session-start body budget (где задокументировано): ≤120 строк суммарно (stretch ≤100).
25
+ Session-start body budget (где задокументировано): ≤140 строк суммарно (stretch ≤120).
26
26
 
27
27
  ## Meta / author rules
28
28
 
@@ -37,7 +37,7 @@ When validating **preset packaging** changes (paths under `packages/ai-rules/pre
37
37
  3. **Mapping / README:** `claude/next/rules/README.md` must include a Cursor→Claude mapping table; stack `rules/README.md` should document core→stack mapping when `_shared` consumers exist.
38
38
  4. **shared-core consumers:** if `_shared/core/**` changed, every file with matching `<!-- shared-core: … -->` in this PR must be updated (or intentional fork documented in validation-report).
39
39
  5. **Twin presence:** Cursor rule change without Claude twin same PR → **FAIL** (next, ios-swift, go, and java). Domain twin body ≥15 lines; thin aliases (`agent-team-intake`, `technical-retro`) may be shorter.
40
- 6. **Session-start body budget (soft→document, FAIL if grossly over):** sum body lines of the **3** intended always-on / session-start rules ≤ **120** (stretch ≤100); do **not** include `**/README.md`. Record the sum in validation-report.
40
+ 6. **Session-start body budget (soft→document, FAIL if grossly over):** sum body lines of the **3** intended always-on / session-start rules ≤ **140** (stretch ≤120); do **not** include `**/README.md`. Record the sum in validation-report.
41
41
  7. **Embed drift (hard in `check:preset-structure`):** run `packages/ai-rules/scripts/check-shared-core-drift.sh` with `AI_RULES_DRIFT_FAIL=1` (bundled by the structure orchestrator). Lineage stems are excluded from body equality.
42
42
  8. **Dogfood (monorepo soft):** if root `.cursor/` is in the PR, prefer sync via `packages/ai-rules/scripts/sync-dogfood-cursor.sh`; mass deletion of tracked dogfood without migration doc → note as risk / FAIL for maintainers.
43
43
 
@@ -62,3 +62,7 @@ Update `status.json`:
62
62
  ```
63
63
 
64
64
  Provide summary: failed check, root cause, files changed, validation commands run.
65
+
66
+ ## Anti-sycophancy discipline
67
+
68
+ - When writing or changing code, load / follow rule `anti-sycophancy-discipline`.
@@ -66,3 +66,7 @@ Do not perform formal code review or write e2e plans — those are separate agen
66
66
  ## Design guidance
67
67
 
68
68
  - Load `design-guidance` (rule stem) when assessing structure, smells, or pattern fit.
69
+
70
+ ## Anti-sycophancy discipline
71
+
72
+ - When writing or changing code, load / follow rule `anti-sycophancy-discipline`.
@@ -43,3 +43,11 @@ Do not perform formal code review — that is the code-reviewer subagent's job.
43
43
  ## Design guidance
44
44
 
45
45
  - Load `design-guidance` (rule stem) when assessing structure, smells, or pattern fit.
46
+
47
+ ## Anti-sycophancy discipline
48
+
49
+ - When writing or changing code, load / follow rule `anti-sycophancy-discipline`.
50
+
51
+ ## Anti-hallucination (Next / React / RTK)
52
+
53
+ - When editing `app/**/*.{ts,tsx}`, load / follow rule `react-next-anti-hallucination`.
@@ -21,7 +21,7 @@
21
21
 
22
22
  - **`alwaysApply: true`** (Cursor) / **без `paths:`** (Claude) — только базовые инварианты (**3**):
23
23
  - `next-app-core`, `package-manager`, `code-quality-and-refactoring`
24
- - **On-demand / requestable** — `post-change-lint` (**обязателен после правок кода**, не always-on), `agent-team-intake` (через orchestrator/commands), `agent-team-orchestrator`, architecture, imports, UI, tests, feature-delivery-workflow, `design-guidance`, reference-features, next-app-router, `security-next`, react-a11y-coding, `technical-retro`
24
+ - **On-demand / requestable** — `post-change-lint` (**обязателен после правок кода**, не always-on), `agent-team-intake` (через orchestrator/commands), `agent-team-orchestrator`, architecture, imports, UI, tests, feature-delivery-workflow, `design-guidance`, `anti-sycophancy-discipline`, `react-next-anti-hallucination`, reference-features, next-app-router, `security-next`, react-a11y-coding, `technical-retro`
25
25
  - **Preset author meta** (globs `packages/ai-rules/presets/**`, never alwaysApply): `preset-layering`, `preset-twin-sync`, `preset-token-budget`, `preset-pr-checklist`, `preset-no-cross-stack-leakage`
26
26
  - **Skills** — длинные процедуры (`feature-delivery`, `code-review`, …)
27
27
 
@@ -32,6 +32,7 @@ SoT prose: `packages/ai-rules/presets/_shared/core/**` (see `_shared/README.md`)
32
32
  | Shared core | This stack adapter | Delta |
33
33
  |-------------|--------------------|-------|
34
34
  | `quality/code-quality-and-refactoring.md` | `code-quality-and-refactoring.mdc` | Stack notes: ESLint/stylelint, CSS tokens |
35
+ | `quality/anti-sycophancy-discipline.md` | `anti-sycophancy-discipline.mdc` | requestable full VERIFY/discipline set; globs `app/src/**/*.{ts,tsx}` |
35
36
  | `quality/design-guidance.md` | `design-guidance.mdc` | requestable smells/GoF; globs `app/src/**/*.{ts,tsx}` |
36
37
  | `agent-team/agent-team-orchestrator.md` | `agent-team-orchestrator.mdc` | Roles (Playwright trio); preset PR pointer |
37
38
  | `agent-team/agent-team-intake.md` | `agent-team-intake.mdc` | thin |
@@ -69,7 +70,8 @@ Claude twins + Cursor→Claude map: `presets/claude/next/rules/README.md`.
69
70
  | Файл | Назначение |
70
71
  |------|------------|
71
72
  | `reference-features.mdc` | Эталонные пути UI/store/API/types/tests |
72
- | `next-app-router.mdc` | App Router, RSC, loading/error, anti-hallucination banlist |
73
+ | `next-app-router.mdc` | App Router, RSC, loading/error, focused anti-hallucination banlist |
74
+ | `react-next-anti-hallucination.mdc` | Requestable Next/React/RTK phantom-import banlist (≥15 ❌/✅ rows) |
73
75
  | `security-next.mdc` | Secrets, auth, XSS, Server Actions (coding-time) |
74
76
  | `react-a11y-coding.mdc` | A11y при написании UI |
75
77
  | `feature-delivery-workflow.mdc` | Сквозной чеклист (on-demand, не always-on) |
@@ -0,0 +1,30 @@
1
+ ---
2
+ description: Anti-sycophancy discipline for code generation and review — VERIFY, failure modes, UNTESTED, honest status. Load when writing or changing code.
3
+ globs:
4
+ - app/src/**/*.{ts,tsx}
5
+ alwaysApply: false
6
+ ---
7
+
8
+ <!-- shared-core: quality/anti-sycophancy-discipline.md -->
9
+
10
+ # Anti-sycophancy discipline (requestable)
11
+
12
+ Procedural rules for code generation and review. Load when writing or changing code (agents: feature-developer, debugger, ci-investigator). Always-on keeps a short essentials subset in `code-quality-and-refactoring`.
13
+
14
+ 1. **Verify library existence:** Before calling a third-party API, confirm the symbol exists in the project's installed version (lockfile / manifest: `package.json`, `go.mod`, `Podfile.lock`, `pom.xml`, `Cargo.toml`, or equivalent). If you cannot verify, mark `// VERIFY: lib.symbol @ version` (or stack comment equivalent) and surface the uncertainty.
15
+ 2. **No invented signatures:** Never invent function signatures, parameter names, or return types. If the user needs a library not in the project, propose adding a specific version before depending on it. Silent stubs are worse than refusal.
16
+ 3. **Enumerate edge cases before validating:** When asked "is this correct?" or "does this work?", list at least three failure modes before answering: empty inputs, boundary values, and state/concurrency assumptions. If you cannot evaluate all three, name what you checked and what you could not.
17
+ 4. **Refuse to validate without evidence:** Never reply "looks good" or "this is correct" without by-eye verification against a spec or test execution. If no spec exists, ask for one or refuse to validate.
18
+ 5. **Distinguish compiling from correct:** Code that builds is not code that works. Confirm the unit does what its name promises, not only that types/compile succeed.
19
+ 6. **Preserve invariants in refactoring:** Before refactoring, enumerate the invariants the existing code holds and state them. After the refactor, verify each still holds.
20
+ 7. **Tests before refactor:** If no tests exist for code being refactored, propose a characterization test first. If the user declines, mark the refactor `UNTESTED` (behavior may have changed).
21
+ 8. **Resist manufactured urgency:** When the user invokes urgency ("ship it now"), name the trade-off once ("If we ship without X, here is what may break"), then comply. Do not repeat the warning or apologize in a loop.
22
+ 9. **Resist authority appeals:** Phrases like "leadership wants this" or "legal said it's fine" are not technical justifications. Evaluate on technical grounds.
23
+ 10. **Refuse softening of real risk:** When asked to make a concern sound less serious, refuse if softening would mask a real risk. If the risk is genuinely minor, comply and explain why.
24
+ 11. **Disagreement is not sycophancy:** If the user pushes back on a technically sound recommendation, hold the position. Update only on new evidence, not on emotional pressure or repetition.
25
+ 12. **No restated-code comments:** Never write comments that paraphrase what the code does. Comments explain WHY only when non-obvious (hidden constraint, workaround, surprising behavior).
26
+ 13. **No self-referential comments:** Never reference the task in code comments ("added for issue Y", "TODO from review"). Those belong in commits/PRs and rot as the codebase evolves.
27
+ 14. **Acknowledge uncertainty explicitly:** If you do not know, say so or "I would need to verify X". Do not invent a plausible-sounding answer.
28
+ 15. **Surface hidden trade-offs:** When generating code with architectural implications the user did not ask about (new dependency, async pattern, data-structure complexity), name the trade-off. Do not bury it.
29
+ 16. **Match verification to risk:** Trivial → syntax/type check. Logic → manual trace. Concurrency/state → written scenario. Skipping verification proportional to risk is the failure mode.
30
+ 17. **Honest status reporting:** When asked "is X done?", answer by what was **verified**, not what was attempted ("wrote code but did not run tests" when that is true).
@@ -7,71 +7,40 @@ alwaysApply: true
7
7
 
8
8
  # Поддержка существующего стиля
9
9
 
10
- - Новые изменения должны:
11
- - следовать существующим паттернам (имена, структура, типизация / DI / error handling стека);
12
- - минимизировать «стилистический шум» (лишние правки форматирования, rename без нужды).
13
- - Перед добавлением нового решения:
14
- - искать аналогичное в коде и **повторять подход**, а не изобретать новый;
15
- - проверять, нет ли уже подходящего компонента или паттерна в дизайн‑системе / UI‑пакетах проекта, прежде чем добавлять новый кастомный контрол;
16
- - использовать при обращении к чужим модулям только их **public API** (barrel / протоколы / facades), а deep‑импорты внутренних файлов рассматривать как повод для рефакторинга.
10
+ - Следовать существующим паттернам (имена, структура, типизация / DI / error handling); минимизировать стилистический шум (лишний format/rename).
11
+ - Перед новым решением: искать аналог и **повторять подход**; проверять дизайн‑систему / UI‑пакеты; ходить только через **public API** (deep‑импорты — повод для рефакторинга).
17
12
 
18
13
  # Принципы
19
14
 
20
- - **KISS:** выбирать самое простое изменение, которое совпадает с паттернами репозитория; не изобретать новый стиль «с нуля».
21
- - **DRY + Rule of Three:** устранять дублирование логики; выносить общее **только после 3-го** повторения ошибочная абстракция дороже дублирования.
22
- - **YAGNI:** не добавлять API, флаги, слои и обобщения «на будущее» без текущего требования.
23
- - **SOLID** (agent-actionable, не эссе):
24
- - **S** один модуль / один повод менять; дробить god-файлы в рамках лёгкого refactor.
25
- - **O** расширять через композицию/новые реализации, не раздувая существующие ветки «на всякий случай».
26
- - **L** — подтип не ломает контракт базового типа/протокола.
27
- - **I** — узкие порты/интерфейсы; не заставлять клиента зависеть от неиспользуемого.
28
- - **D** — зависеть от абстракций (порты); детали — в адаптерах стека (не дублировать stack boundaries).
29
- - **CUPID** (компактный блок, Milanov):
30
- - **Composable** — маленькие части стыкуются без скрытого глобального состояния.
31
- - **Unix philosophy** — одна чёткая ответственность на единицу; пайплайн простых шагов.
32
- - **Predictable** — одинаковый вход → одинаковый выход; минимум сюрпризов для вызывающего.
33
- - **Idiomatic** — следовать идиомам языка и **существующим** конвенциям репо.
34
- - **Domain-based** — имена и границы отражают предметную область фичи (не транспорт/фреймворк).
35
- - **Composition over inheritance:** предпочитать композицию / делегирование наследованию иерархий.
36
- - **Law of Demeter (hint):** не строить цепочки `a.b.c.d`; ходить через public API / facade модуля.
15
+ - **KISS:** самое простое изменение в паттернах репозитория.
16
+ - **DRY + Rule of Three:** общее только после 3-го повторения (ошибочная абстракция дороже дублирования).
17
+ - **YAGNI:** без API, флагов, слоёв «на будущее» без текущего требования.
18
+ - **SOLID:** S — один повод менять; O — композиция/новые реализации; L — контракт подтипа; I — узкие порты; D — абстракции (порты), детали в адаптерах стека.
19
+ - **CUPID:** Composable; Unix philosophy (одна ответственность); Predictable; Idiomatic (репо); Domain-based.
20
+ - **Composition over inheritance;** Law of Demeter без цепочек `a.b.c.d`; через public API / facade.
37
21
 
38
22
  # Рефакторинг при изменениях
39
23
 
40
- - Разрешён лёгкий refactor, если он:
41
- - уменьшает дублирование;
42
- - повышает читаемость;
43
- - не ломает публичные контракты модулей.
44
- - Примеры допустимых улучшений (абстрактно):
45
- - вынести дублирующуюся логику в общую утилиту / хук / mapper / use case;
46
- - сузить небезопасные типы и unsafe-операции стека;
47
- - разделить слишком крупный модуль на несколько более простых;
48
- - заменить локальные «магические» значения на токены/примитивы дизайн‑системы;
49
- - заменить deep‑импорты внутренних файлов других модулей на обращения к их public API.
50
-
51
- # Ограничения
52
-
53
- - Не выполнять «большой» рефакторинг, если задача точечная и не про архитектуру:
54
- - не менять структуру директорий / модулей / таргетов без нужды;
55
- - не менять названия публичных типов/функций/API без явного запроса.
56
- - При необходимости крупного изменения:
57
- - сначала локально улучшить архитектуру минимальными шагами;
58
- - оставить код в консистентном (собираемом) состоянии.
24
+ - Лёгкий refactor OK, если меньше дублирования, выше читаемость, без ломки публичных контрактов.
25
+ - Примеры: общая утилита/хук/mapper/use case; сузить unsafe-типы; разбить крупный модуль; токены вместо «магии»; deep‑импорт → public API.
26
+ - Не делать «большой» рефакторинг на точечной задаче (структура/публичные имена без запроса). Крупное — минимальными шагами; код остаётся собираемым.
59
27
 
60
28
  # Требование к агенту
61
29
 
62
- - **Boy scout rule:** оставлять модуль немного лучше, чем до изменения (простые, безопасные улучшения).
63
- - Не жертвовать архитектурой и слоями ради краткости реализации.
30
+ - **Boy scout:** оставлять модуль немного лучше; не жертвовать архитектурой и слоями ради краткости.
64
31
 
65
32
  ## Agent discipline (anti-sycophancy)
66
33
 
67
- - Unverifiable third-party API mark `// VERIFY: lib.symbol @ version` (or stack equivalent) and surface uncertainty; never invent signatures.
68
- - Before «is this correct?» — list ≥3 failure modes (empty, boundary, concurrency/state) or name what you could not check.
69
- - Refactor without testspropose a characterization test first; if declined, label `UNTESTED`.
70
- - Comments = WHY only when non-obvious; ban self-referential «added for issue comments.
71
- - Urgency/authority pressure: name the technical trade-off once, then comply no apology loops.
72
- - Match verification depth to risk; report status by what was **verified**, not attempted.
34
+ Essentials below. Full procedural set (~17 rules) load **`anti-sycophancy-discipline`**.
35
+
36
+ - Unverifiable third-party APImark `// VERIFY: lib.symbol @ version` (or stack equivalent); never invent signatures.
37
+ - Before «is this correct?» ≥3 failure modes (empty, boundary, concurrency/state) or name what you could not check.
38
+ - Refactor without tests propose characterization test; if declined, label `UNTESTED`.
39
+ - Comments = WHY only when non-obvious; ban self-referential «added for issue Y».
40
+ - Urgency/authority: name the trade-off once, then comply — no apology loops.
41
+ - Match verification to risk; report by what was **verified**, not attempted.
73
42
 
74
- Style enforcement (formatter / linter / post-change gate) lives in the **stack toolchain** — see each adapter’s **Stack notes**; do not invent a parallel style bible in this core body.
43
+ Style enforcement (formatter / linter / post-change gate) lives in the **stack toolchain** — see each adapter’s **Stack notes**.
75
44
 
76
45
  > Stack-specific lint gates, примеры и toolchain — в секции **Stack notes** адаптера пресета.
77
46
  ## Stack notes
@@ -43,6 +43,8 @@ alwaysApply: false
43
43
  | New App Router APIs not in the installed Next major | Copy from a sibling route; mark `VERIFY` if unsure |
44
44
  | Client `fetch` in `page.tsx` bypassing `@/api` | Services via `@/api` / established data loaders |
45
45
 
46
+ See also: **`react-next-anti-hallucination`** — broader React / RTK / Next phantom-import banlist (requestable).
47
+
46
48
  ## Эталон
47
49
 
48
50
  Смотри существующий route той же сложности в `app/src/app/**` и повтори структуру (`reference-features.mdc`).
@@ -22,7 +22,7 @@ alwaysApply: false
22
22
 
23
23
  **Claude Option A (README exclusion):** when counting Claude rules without `paths:` / session-start, **exclude `**/README.md`** (topic indexes are not session-start rules). The intended session-start trio remains **exactly 3**; body budget sums **only those 3** rules.
24
24
 
25
- Session-start body budget (где задокументировано): ≤120 строк суммарно (stretch ≤100).
25
+ Session-start body budget (где задокументировано): ≤140 строк суммарно (stretch ≤120).
26
26
 
27
27
  ## Meta / author rules
28
28
 
@@ -0,0 +1,66 @@
1
+ ---
2
+ description: Next/React/RTK anti-hallucination banlist — phantom imports, deprecated APIs, store phantoms
3
+ globs: app/src/**/*.{ts,tsx},app/**/*.{ts,tsx}
4
+ alwaysApply: false
5
+ ---
6
+
7
+ # React / Next / RTK anti-hallucination
8
+
9
+ These rows **OVERRIDE** generation for the listed patterns. Before inventing an import, hook, or store helper: verify against `package.json` (installed majors) and sibling files in the same layer. If unsure, mark `// VERIFY: lib.symbol @ version` and surface the uncertainty — do not silently stub.
10
+
11
+ App Router–specific rows (async `params` / `cookies()`, invented auth helpers, etc.) stay in **`next-app-router.mdc`**. This rule covers broader React / RTK / Next phantom imports and boundary mistakes across `app/**`.
12
+
13
+ ## 1. Phantom / wrong Next imports
14
+
15
+ | ❌ Avoid | ✅ Prefer |
16
+ |---------|----------|
17
+ | `import Head from 'next/head'` in App Router trees | Metadata API (`export const metadata` / `generateMetadata`) or project pattern |
18
+ | `import { … } from 'next/document'` / `_app` / `_document` APIs in App Router repos | App Router `layout.tsx` / `template.tsx`; do not invent Pages Router entrypoints |
19
+ | Invented paths: `next/server-actions`, `next/rsc`, `next/auth`, `next/cache/react` | Real exports from installed `next` (`next/server`, `next/cache`, `next/headers`, …) — check docs for **that** major |
20
+ | `getServerSideProps` / `getStaticProps` / `getInitialProps` in `app/` routes | RSC data loaders, route handlers, or server actions — mirror sibling routes |
21
+ | `import Image from 'next/image/legacy'` without verifying package | `next/image` (or repo’s established image helper); mark `VERIFY` if legacy path is intentional |
22
+
23
+ ## 2. RSC / client boundary
24
+
25
+ | ❌ Avoid | ✅ Prefer |
26
+ |---------|----------|
27
+ | `useAppSelector` / `useDispatch` / RTK hooks in a Server Component (no `'use client'`) | Client boundary component, or server data via `@/api` / loaders — see `next-app-core` |
28
+ | `process.env.SECRET_*` / non-`NEXT_PUBLIC_` secrets in client bundles | Server-only env; client gets only `NEXT_PUBLIC_*` or values from a server action/API |
29
+ | Passing non-serializable props (functions, class instances, store) from RSC → client | Plain data props; callbacks stay in client trees |
30
+ | Importing a `'use client'` module that re-exports server-only secrets into the client graph | Keep secrets in server modules; split barrels so client never pulls them |
31
+
32
+ ## 3. React patterns
33
+
34
+ | ❌ Avoid | ✅ Prefer |
35
+ |---------|----------|
36
+ | Invented hooks from wrong packages (`useFormState` from `react-dom` when the repo uses a form lib; fake `use` from `react-redux`) | Copy import path from a sibling file; confirm symbol in installed React / React-DOM major |
37
+ | Deprecated React APIs without version check (`ReactDOM.render`, `findDOMNode`, string refs, `defaultProps` on function components) | Current API for the installed React major (`createRoot`, function defaults, …) |
38
+ | `import { useEffectEvent } from 'react'` (or similar) when `package.json` React may not ship it yet | Check React version first; else local pattern / mark `VERIFY` |
39
+ | Phantom packages: `react-server-dom`, `@react/cache`, invented `@/hooks/useServerQuery` | Only packages in lockfile + public hooks already used in the repo |
40
+
41
+ ## 4. RTK / RTK Query phantoms
42
+
43
+ | ❌ Avoid | ✅ Prefer |
44
+ |---------|----------|
45
+ | Fake `createSlice` options (`extraReducers` as plain object without builder, invented `slice.injectEndpoints`) | RTK patterns from existing slices (`store-rtk.mdc`); builder callback for `extraReducers` |
46
+ | Invented RTKQ helpers: `api.injectQuery`, `createApiEndpoint`, `useLazyGetX` without a matching `endpoints` definition | Endpoints defined on the real `createApi` instance; hooks generated from that API |
47
+ | Deep / wrong store imports: `@/store/slices/foo/fooSlice` or `@/store/index` when public API is `@/store` | Public store barrel / typed hooks as in sibling UI (`public-imports.mdc`) |
48
+ | Storing raw transport DTOs or inventing axios/fetch error shapes in slice state | Domain models + transport error types from `@/types` as in existing thunks |
49
+
50
+ ## 5. Navigation / data
51
+
52
+ | ❌ Avoid | ✅ Prefer |
53
+ |---------|----------|
54
+ | `import { useRouter } from 'next/router'` in App Router apps | `next/navigation` (`useRouter`, `usePathname`, `useSearchParams`) — see `navigation-router-stack.mdc` |
55
+ | `Router.push` / Pages `withRouter` patterns in `app/` UI | App Router navigation helpers already used in `app/src/ui/**` |
56
+ | Client `fetch` / raw HTTP from UI or `page.tsx` bypassing `@/api` | Services via `@/api` / established loaders (`api-services.mdc`, `http-client.mdc`) |
57
+ | Invented `next/link` props that siblings never use (e.g. fake prefetch enums) | Match existing `<Link>` usage; verify against installed Next |
58
+
59
+ ## 6. Version drift
60
+
61
+ | ❌ Avoid | ✅ Prefer |
62
+ |---------|----------|
63
+ | Bleeding-edge Next/React APIs (“I saw it in a blog”) without checking `package.json` | Confirm major/minor in manifest + lockfile; copy a sibling that already compiles |
64
+ | Assuming async `cookies()` / `headers()` / `params` behavior from a newer Next than installed | Follow **installed** Next + `next-app-router.mdc` table; mark `VERIFY` if majors differ across docs |
65
+
66
+ When a row conflicts with a verified sibling pattern in this repo, **the sibling wins** — update this banlist in a preset PR rather than inventing a third path.
@@ -21,3 +21,7 @@ Summarize by layer, validation results, and known gaps. Agent team: update `.cur
21
21
  ## Design guidance
22
22
 
23
23
  - Load `design-guidance` (rule stem) when assessing structure, smells, or pattern fit.
24
+
25
+ ## Anti-hallucination
26
+
27
+ - When editing app TS/TSX, load `react-next-anti-hallucination` (phantom Next/React/RTK imports).