@bonesofspring/ai-rules 0.2.8 → 0.2.9

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 (59) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/package.json +1 -1
  3. package/presets/_shared/README.md +1 -1
  4. package/presets/_shared/core/quality/anti-sycophancy-discipline.md +21 -0
  5. package/presets/_shared/core/quality/code-quality-and-refactoring.md +21 -52
  6. package/presets/claude/go/agents/ci-investigator.md +4 -0
  7. package/presets/claude/go/agents/debugger.md +4 -0
  8. package/presets/claude/go/agents/feature-developer.md +4 -0
  9. package/presets/claude/go/rules/README.md +1 -0
  10. package/presets/claude/go/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  11. package/presets/claude/go/rules/tooling-and-review/code-quality.md +22 -53
  12. package/presets/claude/ios-swift/agents/ci-investigator.md +4 -0
  13. package/presets/claude/ios-swift/agents/debugger.md +4 -0
  14. package/presets/claude/ios-swift/agents/feature-developer.md +4 -0
  15. package/presets/claude/ios-swift/rules/README.md +2 -0
  16. package/presets/claude/ios-swift/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  17. package/presets/claude/ios-swift/rules/tooling-and-review/code-quality.md +23 -54
  18. package/presets/claude/java/agents/ci-investigator.md +4 -0
  19. package/presets/claude/java/agents/debugger.md +4 -0
  20. package/presets/claude/java/agents/feature-developer.md +4 -0
  21. package/presets/claude/java/rules/README.md +1 -0
  22. package/presets/claude/java/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  23. package/presets/claude/java/rules/tooling-and-review/code-quality.md +21 -52
  24. package/presets/claude/next/agents/ci-investigator.md +4 -0
  25. package/presets/claude/next/agents/debugger.md +4 -0
  26. package/presets/claude/next/agents/feature-developer.md +8 -0
  27. package/presets/claude/next/rules/README.md +5 -1
  28. package/presets/claude/next/rules/anti-hallucination/react-next-anti-hallucination.md +67 -0
  29. package/presets/claude/next/rules/stack/next-app-router.md +2 -0
  30. package/presets/claude/next/rules/tooling-and-review/anti-sycophancy-discipline.md +29 -0
  31. package/presets/claude/next/rules/tooling-and-review/code-quality.md +25 -55
  32. package/presets/claude/next/skills/feature-delivery/SKILL.md +4 -0
  33. package/presets/cursor/go/agents/ci-investigator.md +4 -0
  34. package/presets/cursor/go/agents/debugger.md +4 -0
  35. package/presets/cursor/go/agents/feature-developer.md +4 -0
  36. package/presets/cursor/go/rules/README.md +3 -1
  37. package/presets/cursor/go/rules/anti-sycophancy-discipline.mdc +30 -0
  38. package/presets/cursor/go/rules/code-quality-and-refactoring.mdc +21 -52
  39. package/presets/cursor/ios-swift/agents/ci-investigator.md +4 -0
  40. package/presets/cursor/ios-swift/agents/debugger.md +4 -0
  41. package/presets/cursor/ios-swift/agents/feature-developer.md +4 -0
  42. package/presets/cursor/ios-swift/rules/README.md +3 -1
  43. package/presets/cursor/ios-swift/rules/anti-sycophancy-discipline.mdc +30 -0
  44. package/presets/cursor/ios-swift/rules/code-quality-and-refactoring.mdc +21 -52
  45. package/presets/cursor/java/agents/ci-investigator.md +4 -0
  46. package/presets/cursor/java/agents/debugger.md +4 -0
  47. package/presets/cursor/java/agents/feature-developer.md +4 -0
  48. package/presets/cursor/java/rules/README.md +3 -1
  49. package/presets/cursor/java/rules/anti-sycophancy-discipline.mdc +30 -0
  50. package/presets/cursor/java/rules/code-quality-and-refactoring.mdc +21 -52
  51. package/presets/cursor/next/agents/ci-investigator.md +4 -0
  52. package/presets/cursor/next/agents/debugger.md +4 -0
  53. package/presets/cursor/next/agents/feature-developer.md +8 -0
  54. package/presets/cursor/next/rules/README.md +4 -2
  55. package/presets/cursor/next/rules/anti-sycophancy-discipline.mdc +30 -0
  56. package/presets/cursor/next/rules/code-quality-and-refactoring.mdc +21 -52
  57. package/presets/cursor/next/rules/next-app-router.mdc +2 -0
  58. package/presets/cursor/next/rules/react-next-anti-hallucination.mdc +66 -0
  59. package/presets/cursor/next/skills/feature-delivery/SKILL.md +4 -0
@@ -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`).
@@ -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).