@rt-tools/agent-kit 0.23.0 → 0.26.0

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 (288) hide show
  1. package/README.md +8 -2
  2. package/assets/agents/business-analyst.md +51 -50
  3. package/assets/agents/conscience.md +37 -35
  4. package/assets/agents/project-manager.md +49 -48
  5. package/assets/agents/prose-editor.md +31 -29
  6. package/assets/agents/qa-engineer.md +50 -48
  7. package/assets/agents/rules-reviewer.md +63 -58
  8. package/assets/agents/skill-curator.md +83 -78
  9. package/assets/agents/spec-critic.md +34 -29
  10. package/assets/agents/spec-writer.md +35 -32
  11. package/assets/agents/strict-teacher.md +39 -37
  12. package/assets/checks/archive-age.mjs +48 -28
  13. package/assets/checks/archive-prune.mjs +16 -14
  14. package/assets/checks/board-epics.github.mjs +75 -41
  15. package/assets/checks/board-folders.mjs +61 -0
  16. package/assets/checks/board-gh.github.mjs +35 -26
  17. package/assets/checks/board-long-work.github.mjs +24 -24
  18. package/assets/checks/board-paths.github.mjs +21 -16
  19. package/assets/checks/board-runs.github.mjs +45 -43
  20. package/assets/checks/board-titles.github.mjs +19 -17
  21. package/assets/checks/board.github.mjs +150 -128
  22. package/assets/checks/check-archive-age.mjs +23 -19
  23. package/assets/checks/check-board.github.mjs +179 -157
  24. package/assets/checks/check-descriptions.mjs +30 -29
  25. package/assets/checks/check-doc-paths.mjs +104 -82
  26. package/assets/checks/check-dupes.mjs +84 -80
  27. package/assets/checks/check-file-size.mjs +79 -70
  28. package/assets/checks/check-glossary.mjs +47 -37
  29. package/assets/checks/check-hook-scope.mjs +30 -27
  30. package/assets/checks/check-lib-layers.mjs +22 -21
  31. package/assets/checks/check-profile-drift.mjs +48 -43
  32. package/assets/checks/check-prose-style.mjs +125 -33
  33. package/assets/checks/check-push-gate.mjs +53 -50
  34. package/assets/checks/check-reuse.mjs +50 -40
  35. package/assets/checks/check-schema-drift.mjs +87 -83
  36. package/assets/checks/check-specs.mjs +155 -134
  37. package/assets/checks/check-state-next.mjs +66 -52
  38. package/assets/checks/check-states.mjs +32 -30
  39. package/assets/checks/check-styles.mjs +52 -51
  40. package/assets/checks/check-turn-map.mjs +54 -46
  41. package/assets/checks/lib-boundaries.mjs +32 -30
  42. package/assets/checks/lib-common.mjs +30 -29
  43. package/assets/checks/lib-domains.mjs +34 -34
  44. package/assets/checks/lib-manifests.mjs +17 -15
  45. package/assets/checks/lib-reexports.mjs +18 -18
  46. package/assets/checks/rt-kit-checks.config.mjs +174 -142
  47. package/assets/checks/signals.mjs +43 -39
  48. package/assets/checks/spec-anchors.mjs +114 -87
  49. package/assets/checks/spec-common.mjs +128 -84
  50. package/assets/checks/spec-contract.mjs +30 -30
  51. package/assets/checks/spec-proposed.mjs +27 -24
  52. package/assets/checks/spec-scenarios.mjs +51 -28
  53. package/assets/checks/task-new.github.mjs +85 -56
  54. package/assets/commands/feedback.md +65 -59
  55. package/assets/commands/next-session.md +64 -57
  56. package/assets/commands/skill-curator.md +83 -79
  57. package/assets/defaults/gate-map.sh +115 -91
  58. package/assets/defaults/project.sh +228 -178
  59. package/assets/defaults/shell.sh +85 -65
  60. package/assets/defaults/turn-map.md +45 -44
  61. package/assets/docs/GLOSSARY.md +142 -65
  62. package/assets/hooks/browser-device-id.sh +12 -12
  63. package/assets/hooks/browser-guard-device-id.sh +46 -14
  64. package/assets/hooks/browser-guard-no-asking.sh +5 -4
  65. package/assets/hooks/browser-guard-no-listing.sh +12 -11
  66. package/assets/hooks/browser-guard-no-other-drivers.sh +48 -42
  67. package/assets/hooks/browser-guard-require-select.sh +34 -23
  68. package/assets/hooks/claim-guard.sh +62 -56
  69. package/assets/hooks/commit-msg.sh +11 -10
  70. package/assets/hooks/conscience-guard.sh +91 -45
  71. package/assets/hooks/constitution-index.sh +16 -16
  72. package/assets/hooks/deny-tail.sh +28 -26
  73. package/assets/hooks/dev-server-guard.sh +46 -43
  74. package/assets/hooks/dispatch.sh +84 -39
  75. package/assets/hooks/docs-guard.sh +105 -86
  76. package/assets/hooks/exam-guard.sh +146 -84
  77. package/assets/hooks/git-guard-delivery-conflict.sh +38 -36
  78. package/assets/hooks/git-guard-delivery-draft.sh +85 -0
  79. package/assets/hooks/git-guard-delivery-folder.sh +50 -43
  80. package/assets/hooks/git-guard-delivery-signature.sh +88 -52
  81. package/assets/hooks/git-guard-delivery.sh +207 -253
  82. package/assets/hooks/git-guard-main.sh +65 -26
  83. package/assets/hooks/git-guard-push-tests.sh +133 -75
  84. package/assets/hooks/glossary-load.sh +23 -22
  85. package/assets/hooks/grill-gate-ask.sh +12 -11
  86. package/assets/hooks/grill-gate.sh +94 -87
  87. package/assets/hooks/guard-note.sh +20 -19
  88. package/assets/hooks/handoff-entry-guard.sh +26 -24
  89. package/assets/hooks/handoff-write.sh +74 -67
  90. package/assets/hooks/hook-input.sh +70 -50
  91. package/assets/hooks/lint-after-edit.sh +95 -61
  92. package/assets/hooks/observe.sh +28 -26
  93. package/assets/hooks/override-write-guard.sh +23 -21
  94. package/assets/hooks/postmortem-guard.sh +42 -39
  95. package/assets/hooks/profile-check.sh +22 -20
  96. package/assets/hooks/proposal-guard.sh +57 -49
  97. package/assets/hooks/prose-style-guard.sh +19 -17
  98. package/assets/hooks/qa-dataid-guard.sh +52 -49
  99. package/assets/hooks/rerun-guard.sh +31 -30
  100. package/assets/hooks/reuse-first-guard.sh +108 -87
  101. package/assets/hooks/roles.sh +14 -14
  102. package/assets/hooks/rule-article.sh +36 -34
  103. package/assets/hooks/rule-source-guard.sh +52 -36
  104. package/assets/hooks/skill-gate-layers.sh +59 -57
  105. package/assets/hooks/skill-gate-rearm.sh +15 -8
  106. package/assets/hooks/skill-gate.sh +89 -81
  107. package/assets/hooks/skill-loaded.sh +6 -6
  108. package/assets/hooks/sql-guard-parse.sh +68 -66
  109. package/assets/hooks/sql-guard-request.sh +48 -46
  110. package/assets/hooks/sql-guard-target.sh +57 -51
  111. package/assets/hooks/sql-guard-write.sh +84 -79
  112. package/assets/hooks/sql-guard.sh +52 -47
  113. package/assets/hooks/stand-login-guard.sh +104 -0
  114. package/assets/hooks/task-context-load.sh +60 -55
  115. package/assets/hooks/task-flow-context.sh +87 -69
  116. package/assets/hooks/task-flow-draft-guard.sh +55 -48
  117. package/assets/hooks/task-flow-guard.sh +67 -64
  118. package/assets/hooks/turn-entry-load.sh +39 -32
  119. package/assets/hooks/turn-exit-guard.sh +256 -204
  120. package/assets/hooks/turn-exit-patterns.sh +53 -0
  121. package/assets/hooks/utf8.sh +11 -11
  122. package/assets/hooks/waiting-turn-guard.sh +94 -94
  123. package/assets/hooks/window-fill-guard.sh +70 -62
  124. package/assets/hooks/work-start-guard.sh +52 -49
  125. package/assets/hooks/write-targets.sh +115 -30
  126. package/assets/laws/autonomous-work.md +29 -27
  127. package/assets/laws/code-structure.md +31 -30
  128. package/assets/laws/delivery.md +148 -137
  129. package/assets/laws/entity-editing.md +52 -50
  130. package/assets/laws/entity-models.md +14 -13
  131. package/assets/laws/frontend-application.md +39 -38
  132. package/assets/laws/lib-imports.md +27 -27
  133. package/assets/laws/lists.md +31 -29
  134. package/assets/laws/navigation.md +37 -37
  135. package/assets/laws/observability.md +41 -40
  136. package/assets/laws/project-documentation.md +106 -99
  137. package/assets/laws/reuse-first.md +31 -29
  138. package/assets/laws/shared-code.md +27 -27
  139. package/assets/laws/verifiability.md +131 -114
  140. package/assets/laws/work-conduct.md +250 -250
  141. package/assets/patterns/admin-lists-screen.md +72 -69
  142. package/assets/patterns/admin-nav-item.md +51 -46
  143. package/assets/patterns/angular-patterns-state.md +32 -31
  144. package/assets/patterns/api-layer-pair.md +33 -31
  145. package/assets/patterns/autonomous-work-run.md +50 -49
  146. package/assets/patterns/browser-verification-measure.md +143 -67
  147. package/assets/patterns/browser-verification-stand.md +181 -128
  148. package/assets/patterns/component-structure-new.md +51 -42
  149. package/assets/patterns/dependencies-upgrade.md +55 -39
  150. package/assets/patterns/doc-style-human.md +93 -0
  151. package/assets/patterns/doc-style-sweep.md +82 -79
  152. package/assets/patterns/doc-style-trace.md +87 -81
  153. package/assets/patterns/doc-style-write.md +130 -122
  154. package/assets/patterns/entity-aside.md +77 -63
  155. package/assets/patterns/entity-models-new.md +37 -37
  156. package/assets/patterns/entity-store.md +33 -33
  157. package/assets/patterns/git-workflow-commit.azure.md +94 -75
  158. package/assets/patterns/git-workflow-commit.github.md +153 -129
  159. package/assets/patterns/git-workflow-commit.gitlab.md +96 -78
  160. package/assets/patterns/git-workflow-docker.md +165 -147
  161. package/assets/patterns/git-workflow-freshness.md +45 -45
  162. package/assets/patterns/git-workflow-merge.md +99 -86
  163. package/assets/patterns/git-workflow-migration.md +54 -52
  164. package/assets/patterns/git-workflow-pr-ready.md +57 -56
  165. package/assets/patterns/git-workflow-pr.azure.md +126 -121
  166. package/assets/patterns/git-workflow-pr.github.md +179 -175
  167. package/assets/patterns/git-workflow-pr.gitlab.md +138 -131
  168. package/assets/patterns/git-workflow-restart.md +35 -31
  169. package/assets/patterns/git-workflow-secrets.md +80 -73
  170. package/assets/patterns/git-workflow-stack.md +131 -106
  171. package/assets/patterns/lib-layers-move.md +62 -53
  172. package/assets/patterns/lib-layers-new.md +59 -45
  173. package/assets/patterns/observability-record.md +72 -67
  174. package/assets/patterns/platform-access-di.md +31 -29
  175. package/assets/patterns/reuse-first-extend.md +66 -61
  176. package/assets/patterns/shared-code-new.md +39 -38
  177. package/assets/patterns/spec-driven-domain.md +161 -151
  178. package/assets/patterns/spec-driven-rule.md +179 -168
  179. package/assets/patterns/spec-driven-sweep.md +41 -39
  180. package/assets/patterns/status-report-table.github.md +37 -36
  181. package/assets/patterns/styling-bem-component.md +42 -42
  182. package/assets/patterns/styling-bem-layout.md +39 -34
  183. package/assets/patterns/styling-bem-sheet.md +59 -58
  184. package/assets/patterns/task-flow-archive.md +222 -215
  185. package/assets/patterns/task-flow-close.md +215 -203
  186. package/assets/patterns/task-flow-handoff.md +154 -145
  187. package/assets/patterns/task-flow-resume.md +138 -133
  188. package/assets/patterns/task-flow-start.md +204 -192
  189. package/assets/patterns/testing-e2e.md +103 -92
  190. package/assets/patterns/testing-unit.md +77 -70
  191. package/assets/patterns/ts-procedure.md +32 -29
  192. package/assets/patterns/turn-entry-map.md +50 -48
  193. package/assets/pitfalls/agent-kit.md +152 -141
  194. package/assets/pitfalls/doc-style.md +96 -91
  195. package/assets/pitfalls/git-workflow.azure.md +49 -46
  196. package/assets/pitfalls/git-workflow.github.md +264 -234
  197. package/assets/pitfalls/git-workflow.gitlab.md +49 -45
  198. package/assets/pitfalls/spec-driven.md +73 -71
  199. package/assets/pitfalls/styling-bem.md +46 -40
  200. package/assets/pitfalls/task-flow.md +262 -246
  201. package/assets/pitfalls/testing.md +99 -92
  202. package/assets/pitfalls/turn-conduct.md +96 -81
  203. package/assets/rules/angular-patterns.md +81 -80
  204. package/assets/rules/api-layer.md +77 -74
  205. package/assets/rules/autonomous-work.md +75 -74
  206. package/assets/rules/browser-verification.md +223 -188
  207. package/assets/rules/component-structure.md +72 -69
  208. package/assets/rules/dependencies.md +74 -67
  209. package/assets/rules/deploy-flow.azure.md +118 -108
  210. package/assets/rules/deploy-flow.github.md +145 -135
  211. package/assets/rules/deploy-flow.gitlab.md +120 -110
  212. package/assets/rules/doc-style.md +209 -148
  213. package/assets/rules/entity-conventions.needs-admin.md +81 -79
  214. package/assets/rules/entity-models.md +73 -70
  215. package/assets/rules/git-workflow.azure.md +224 -228
  216. package/assets/rules/git-workflow.github.md +250 -242
  217. package/assets/rules/git-workflow.gitlab.md +218 -217
  218. package/assets/rules/lib-layers.md +85 -86
  219. package/assets/rules/lists.md +101 -97
  220. package/assets/rules/navigation.md +78 -78
  221. package/assets/rules/observability.needs-app.md +165 -153
  222. package/assets/rules/platform-access.md +76 -75
  223. package/assets/rules/reuse-first.md +153 -137
  224. package/assets/rules/shared-code.md +82 -79
  225. package/assets/rules/spec-driven.md +272 -260
  226. package/assets/rules/status-report.md +55 -58
  227. package/assets/rules/styling-bem.md +83 -72
  228. package/assets/rules/task-flow.md +282 -270
  229. package/assets/rules/testing.md +224 -188
  230. package/assets/rules/turn-conduct.md +255 -258
  231. package/assets/rules/turn-entry.md +92 -87
  232. package/assets/rules/typescript-conventions.md +94 -88
  233. package/assets/samples/specs/_template/spec.md +47 -47
  234. package/assets/samples/tasks/_template/grill.md +20 -20
  235. package/assets/samples/tasks/_template/plan.md +32 -30
  236. package/assets/samples/tasks/_template/progress.md +16 -16
  237. package/assets/skills/agent-kit-extend.md +129 -113
  238. package/assets/skills/agent-kit.md +236 -222
  239. package/assets/skills/write-a-skill.md +76 -71
  240. package/assets/templates/findings.md +19 -19
  241. package/assets/templates/gate-map.sh +16 -14
  242. package/assets/templates/implementation.md +28 -27
  243. package/assets/templates/pattern.md +17 -17
  244. package/assets/templates/pitfalls.md +6 -6
  245. package/assets/templates/postmortem.md +24 -23
  246. package/assets/templates/project.sh +24 -24
  247. package/assets/templates/proposal.md +62 -60
  248. package/assets/templates/rule.md +38 -38
  249. package/assets/workflows/feature.js +46 -46
  250. package/assets/workflows/plan.js +54 -54
  251. package/lib/catalog.d.ts +2 -0
  252. package/lib/catalog.d.ts.map +1 -1
  253. package/lib/catalog.js +4 -3
  254. package/lib/catalog.js.map +1 -1
  255. package/lib/commands.d.ts.map +1 -1
  256. package/lib/commands.js +68 -4
  257. package/lib/commands.js.map +1 -1
  258. package/lib/companion.js +3 -2
  259. package/lib/companion.js.map +1 -1
  260. package/lib/enroll.d.ts +7 -1
  261. package/lib/enroll.d.ts.map +1 -1
  262. package/lib/enroll.js +13 -4
  263. package/lib/enroll.js.map +1 -1
  264. package/lib/observations.d.ts +10 -1
  265. package/lib/observations.d.ts.map +1 -1
  266. package/lib/observations.js +1 -0
  267. package/lib/observations.js.map +1 -1
  268. package/lib/override-marks.d.ts +24 -0
  269. package/lib/override-marks.d.ts.map +1 -0
  270. package/lib/override-marks.js +98 -0
  271. package/lib/override-marks.js.map +1 -0
  272. package/lib/plan.d.ts +11 -0
  273. package/lib/plan.d.ts.map +1 -1
  274. package/lib/plan.js +10 -1
  275. package/lib/plan.js.map +1 -1
  276. package/lib/ship.d.ts +0 -7
  277. package/lib/ship.d.ts.map +1 -1
  278. package/lib/ship.js +10 -2
  279. package/lib/ship.js.map +1 -1
  280. package/lib/shipment.d.ts.map +1 -1
  281. package/lib/shipment.js +7 -3
  282. package/lib/shipment.js.map +1 -1
  283. package/lib/sync.d.ts.map +1 -1
  284. package/lib/sync.js +45 -11
  285. package/lib/sync.js.map +1 -1
  286. package/package.json +1 -1
  287. package/rt-tools-agent-kit-0.26.0.tgz +0 -0
  288. package/rt-tools-agent-kit-0.23.0.tgz +0 -0
@@ -2,129 +2,140 @@
2
2
  name: testing-e2e
3
3
  kind: pattern
4
4
  rule: testing
5
- description: Паттерн правила testing. Брать при правке и прогоне сквозных спек в apps/site-e2e и apps/admin-e2e — что закрывается сквозной спекой, готовые команды прогона, стенд из прод-сборки под настоящим nginx, выключатели спек. Не брать для юнитов — это паттерн testing-unit.
5
+ description: Pattern of rule testing. Load when editing and running end-to-end tests in apps/site-e2e and apps/admin-e2e — what an end-to-end test closes, ready-made run commands, a stand from the production build behind real nginx, test switches. Not for unit tests — that is pattern testing-unit.
6
6
  ---
7
7
 
8
- # Сквозные спеки
8
+ # End-to-end tests
9
9
 
10
- Паттерн правила `testing`. Что при этом должно быть верно — закон
10
+ Pattern of the rule `testing`. What must be true — the law
11
11
  `docs/constitution/verifiability.md`.
12
12
 
13
- ## Когда брать
13
+ ## When to use
14
14
 
15
- - Пишется или правится спека в `apps/site-e2e/src` или `apps/admin-e2e/src`.
16
- - Надо воспроизвести дефект, который виден только на прод-конфигурации.
17
- - Готовится стенд под прогон против nginx.
15
+ - A test file in `apps/site-e2e/src` or `apps/admin-e2e/src` is being written or edited.
16
+ - A defect visible only on the production configuration needs reproducing.
17
+ - A stand is being prepared for a run against nginx.
18
18
 
19
- ## Сквозной спекой закрывается накопленное состояние
19
+ ## An end-to-end test closes accumulated state
20
20
 
21
- Случай для неё — тот, где состояние копится нажатиями: открытая панель, активный маршрут,
22
- гард прошлого экрана. Всё, что проверяется одним заходом по адресу, дешевле закрыть юнитом на
23
- чистой функции или замером экрана.
21
+ Its case is the one where state accumulates by clicks: an open panel, an active route, the guard
22
+ of the previous screen. Everything checked by one visit to an address is cheaper to close by a
23
+ unit test on a pure function or by a screen measurement.
24
24
 
25
- Отсюда и способ: нажатия по тем же элементам, что нажимает владелец, несколько подряд, без
26
- перезагрузки между ними. Заход по прямому адресу поднимает приложение заново, накопленного
27
- состояния у него нет, и проход читается как «дефект не подтверждается» — так на прод уехала
28
- панель, застревавшая в адресе при уходе в соседний раздел.
25
+ Hence the method: clicks on the same elements the owner clicks, several in a row, with no reload
26
+ between them. Entering by a direct address raises the application anew, it has no accumulated state,
27
+ and the pass reads as "the defect is not confirmed". That is how a panel that got stuck in the
28
+ address on leaving for a neighbouring section went out to production.
29
29
 
30
- Элементы находятся по `qa-dataid`: классы меняются вместе с вёрсткой, а поиск по роли и тексту
31
- ломается на переводах.
30
+ Elements are found by `qa-dataid`: classes change together with the layout, and a search by role
31
+ and text breaks on translations.
32
32
 
33
- ## Прогон
33
+ ## Run
34
34
 
35
35
  ```bash
36
- npx nx e2e site-e2e -- --project=chromium
37
- npx nx e2e admin-e2e -- --project=chromium
38
- BASE_URL=http://localhost:{{dockerSitePort}} npx nx e2e site-e2e -- --project=chromium # против внешнего стенда
36
+ npx nx e2e <suite target> -- --project=chromium
37
+ BASE_URL=http://localhost:$PROXY_SITE_PORT npx nx e2e <suite target> -- --project=chromium # against an external stand
39
38
  ```
40
39
 
41
- По умолчанию конфиг идёт на {{sitePort}} и подхватывает уже поднятый сервер. С `BASE_URL` свой сервер
42
- не стартует вовсе.
40
+ The runner target names and the port numbers are each tree's own: the pattern does not know them.
41
+ The tree names them by its own profile — by environment variables or by an override section of
42
+ this pattern, where the ready-made commands stand with its names.
43
43
 
44
- Полный набор админки гоняется **одним воркером** (`--workers=1`): тесты с настоящей сессией
45
- правят одни и те же объекты живой базы и в параллельном прогоне мешают друг другу. Одни и те
46
- же файлы дали три падения на восьми воркерах и ноль на одном.
44
+ By default the config goes to the site stand port and picks up the server already raised. With
45
+ `BASE_URL` no server of its own is started.
47
46
 
48
- ## Стенд из прод-сборки под настоящим nginx
47
+ The full admin suite is run **by one worker** (`--workers=1`): tests with a real session edit the
48
+ same objects of the live database and get in each other's way in a parallel run. The same files
49
+ gave three failures on eight workers and zero on one.
49
50
 
50
- Как его поднять — паттерн `browser-verification-stand`; там же сказано, почему главный конфиг
51
- монтируется отдельной строкой и почему каталогом, а не файлом. Здесь важно одно: против такого
52
- стенда прогон идёт с `BASE_URL`, и вместе с ним включаются проверки перенаправлений локалей.
51
+ ## A stand from the production build behind real nginx
53
52
 
54
- ## Выключатели
53
+ How to raise it — pattern `browser-verification-stand`; it also says why the main config is
54
+ mounted by a separate line and why as a directory, not as a file. One thing matters here: against
55
+ such a stand the run goes with `BASE_URL`, and with it the locale redirect checks switch on.
56
+
57
+ ## Switches
55
58
 
56
59
  ```typescript
57
60
  const ALLOW_RENAME: boolean = process.env['E2E_ALLOW_SLUG_RENAME'] === '1';
58
61
  test.skip(!ALLOW_RENAME, 'меняет живой адрес объекта: включается E2E_ALLOW_SLUG_RENAME=1');
59
62
  ```
60
63
 
61
- Выключатели бывают двух родов, и покрытием считается только первый. **Выключатель по состоянию
62
- стенда** пропускает случай, которого на этом стенде не бывает по устройству, — сценарий закрыт,
63
- и отметки он не требует. **Выключатель по переменной окружения** оставляет тест невыполненным:
64
- сценарий за ним числится покрытым, а не проверен ничем, и такой сценарий несёт отметку
65
- частичного покрытия с причиной. Из трёх ниже к первому роду не относится ни один: все три
66
- управляются переменной.
64
+ Switches come in two kinds, and only the first counts as coverage. **A switch by stand state**
65
+ skips a case the stand never has by design — the scenario is closed, and it needs no mark. **A
66
+ switch by environment variable** leaves the test unrun: the scenario behind it is listed as
67
+ covered while nothing checks it, and such a scenario carries a partial-coverage mark with a
68
+ reason. Of the three below not one belongs to the first kind: all three are driven by a variable.
67
69
 
68
- - Спека, необратимо меняющая данные стенда, по умолчанию пропускается и включается своей
69
- переменной.
70
- - `BEHIND_NGINX` в `home.smoke.spec.ts` — это `!!process.env['BASE_URL']`: вместе с ним
71
- просыпаются проверки перенаправлений локалей. Голый сервер отдачи страниц их не проходит, и
72
- два падения выглядят регрессией.
73
- - `HAS_ADMIN_SESSION` в `sign-in.ts` — пара `E2E_ADMIN_EMAIL` и `E2E_ADMIN_PASSWORD`.
74
- - `playwright/no-skipped-test` выключен в `eslint.config.mjs`: выключатель теста здесь —
75
- приём, а не забытый `test.skip`.
70
+ - A test that irreversibly changes stand data is skipped by default and switched on by its own
71
+ variable.
72
+ - `BEHIND_NGINX` in `home.smoke.spec.ts` is `!!process.env['BASE_URL']`: with it the locale
73
+ redirect checks wake. A bare page-serving server does not pass them, and two failures look like
74
+ a regression.
75
+ - `HAS_ADMIN_SESSION` in `sign-in.ts` — the pair `E2E_ADMIN_EMAIL` and `E2E_ADMIN_PASSWORD`.
76
+ - `playwright/no-skipped-test` is switched off in `eslint.config.mjs`: the test switch here is a
77
+ technique, not a forgotten `test.skip`.
76
78
 
77
- ## Код перехода проверяется ответом, а не переходом по нему
79
+ ## A redirect code is checked by the answer, not by following it
78
80
 
79
- Переход браузер проходит сам, и код после него — код конечной страницы: спека, названная
80
- «отвечает 301», утверждала 200 и не заметила бы подмены постоянного перехода на временный.
81
- Спрашивается сам ответ, без хождения по нему:
81
+ The browser follows the redirect itself, and the code after it is the code of the final page: a
82
+ test named "answers 301" asserted 200 and would not have noticed a permanent redirect replaced by
83
+ a temporary one. The answer itself is asked, without following it:
82
84
 
83
85
  ```ts
84
- const answer = await request.get('/старый-адрес', { maxRedirects: 0 });
86
+ const answer = await request.get('/old-address', { maxRedirects: 0 });
85
87
 
86
88
  expect(answer.status()).toBe(301);
87
- expect(answer.headers()['location']).toBe('/новый-адрес');
89
+ expect(answer.headers()['location']).toBe('/new-address');
88
90
  ```
89
91
 
90
- Отличать постоянный переход от временного нужно там, где на нём стоит договорённость: поисковые
91
- роботы и браузер запоминают только постоянный, и разница между 301 и 302 видна лишь в ответе.
92
-
93
- ## Состояние экрана после действия ждётся опросом, а не читается следующей строкой
94
-
95
- Между нажатием и новым содержимым лежит сеть: отбор уходит в адрес нажатием, а строки приезжают
96
- ответом сервера, и прочитанные сразу — ещё прежние. Спека, читающая столбец следующей строкой,
97
- проходит на своей машине и краснеет в конвейере: там ответ приходит позже, и разница между
98
- машинами решает исход.
99
-
100
- Ждётся поэтому само состояние — опросом до совпадения с ожидаемым, а не одним чтением и не
101
- паузой на время. Пауза проверяет машину: на свободной её хватает всегда, на занятой не хватает,
102
- и какая именно спека не успела, оказывается делом случая.
103
-
104
- Знание это заводится в правиле, а не в общем модуле набора: записанное только кодом, оно
105
- известно тому, кто его писал, — следующая спека повторяет промах, потому что читает не код, а
106
- правило.
107
-
108
- ## Частые промахи
109
-
110
- - **Порт {{ssrPort}} занимать осторожно:** стенд разработчика на {{sitePort}} ходит по тому же имени
111
- `ssr:{{ssrPort}}` через `host-gateway`, и пока на нём висит чужой процесс, стенд отдаёт чужую
112
- сборку.
113
- - Браузер стоит один — chromium; узкий экран — `--project=mobile-chrome`. Ошибка «Executable
114
- doesn't exist» разобрана в правиле `testing`: она же приходит после смены версии Playwright.
115
- - Спеки админки без сессии пропускаются молча — прогон выглядит успешным, а проверено меньше
116
- половины.
117
- - Конфиг nginx монтируется каталогом, а не одиночным файлом: редактор пересоздаёт файл, и
118
- контейнеру остаётся обрезанная копия.
119
- - **Подменяется не только то, что запрашивает экран, но и то, что запрашивает шапка.** Счётчик
120
- непрочитанного запрашивается на каждом экране под шапкой. Без подмены на этот запрос
121
- отвечает настоящий сервер, поддельный вход он отбивает, интерцептор сбрасывает сессию, и
122
- пятьдесят девять тестов падают на пропавшей шапке — выглядит это дефектом экрана.
123
- - **Состояние, которое живёт только во время операции, тестом не проверяется.** Список заливки
124
- под кнопкой виден, пока файлы летят: на подменённых ответах они долетают раньше, чем тест
125
- успевает его прочитать, и тест краснеет через раз. Проверяют либо конечное состояние
126
- (`data-state` строки стал `done`), либо то же промежуточное — но на ответе, который тест сам
127
- задержал и сам отпускает.
128
- - **Каталог сборки, удалённый под смонтированным томом, оставляет контейнер с пустым
129
- корнем:** стенд отвечает 403 на всё, и падают сразу все тесты. Контейнер после
130
- `rm -rf dist/apps/<приложение>` пересоздаётся.
92
+ Telling a permanent redirect from a temporary one is needed where an agreement rests on it: search
93
+ robots and the browser remember only the permanent one, and the difference between 301 and 302 is
94
+ visible only in the answer.
95
+
96
+ ## The screen state after an action is awaited by polling, not read on the next line
97
+
98
+ Between the click and the new content lies the network: the filter goes into the address by the
99
+ click, and the rows arrive by the server's answer, and those read at once are still the old ones.
100
+ A test that reads a column on the next line passes on its own machine and turns red in the
101
+ pipeline: there the answer comes later, and the difference between machines decides the outcome.
102
+
103
+ So the state itself is awaited — by polling until it matches the expected one, not by one read and
104
+ not by a pause for a time. A pause checks the machine: on a free one it is always enough, on a busy
105
+ one it is not, and which test did not make it turns out a matter of chance.
106
+
107
+ This knowledge is entered in the rule, not in the shared module of the suite. Written only as code,
108
+ it is known to whoever wrote it — the next test repeats the miss, because it reads the rule, not the
109
+ code.
110
+
111
+ ## Common misses
112
+
113
+ - **Take the rendering server port with care:** the developer's stand goes by the same name
114
+ `ssr:<rendering port>` through `host-gateway`, and while a foreign process hangs on it, the stand
115
+ serves a foreign build.
116
+ - There is one browser — chromium; narrow screen — `--project=mobile-chrome`. The error "Executable
117
+ doesn't exist" is taken apart in the rule `testing`: the same one comes after a Playwright version
118
+ change.
119
+ - Admin tests without a session are skipped silently — the run looks successful, while less than
120
+ half was checked.
121
+ - The nginx config is mounted as a directory, not as a single file: the editor recreates the file,
122
+ and the container is left with a truncated copy.
123
+ - **Not only what the screen requests is substituted, but also what the header requests.** The
124
+ unread counter is requested on every screen under the header. Without a substitution the real
125
+ server answers that request, refuses the fake sign-in, the interceptor drops the session, and
126
+ fifty-nine tests fail on the vanished header — it looks like a screen defect.
127
+ - **State that lives only during an operation is not checked by a test.** The upload list under the
128
+ button is visible while the files are in flight: on substituted answers they land before the test
129
+ manages to read it, and the test turns red every other run. What is checked is either the final
130
+ state (the row's `data-state` became `done`) or the same intermediate one — but on an answer the
131
+ test itself delayed and itself releases.
132
+ - **A double moved from a test file into the suite's shared file leaves the exclusion of the
133
+ duplicate check.** It skips test files and reads everything else, doubles and settings included,
134
+ and compares the declaration name — not the value and not the purpose. A setting that lay in a
135
+ test file under a common name matches, after the move, the one of the same name in another layer,
136
+ and the check turns red on a file the edit did not touch. Taking such red apart takes a separate
137
+ turn. On the move the name gets the prefix of its suite; no line goes into the known list — it
138
+ only shrinks.
139
+ - **A build directory removed under a mounted volume leaves the container with an empty root:** the
140
+ stand answers 403 to everything, and all tests fail at once. After
141
+ `rm -rf dist/apps/<application>` the container is recreated.
@@ -2,32 +2,33 @@
2
2
  name: testing-unit
3
3
  kind: pattern
4
4
  rule: testing
5
- description: Паттерн правила testing. Брать при заведении или правке *.spec.ts под Vitest — готовая раскладка describe и it, сборщик фикстур, идентификатор сценария в заголовке, спека процедуры Connect с рукописным двойником базы. Не брать для сквозных спек — это паттерн testing-e2e.
5
+ description: Pattern of rule testing. Load when creating or editing *.spec.ts under Vitest — the ready-made layout of describe and it, the fixture builder, the scenario id in the title, a Connect procedure test with a hand-written database double. Not for end-to-end tests — that is pattern testing-e2e.
6
6
  ---
7
7
 
8
- # Спека на чистую функцию и на процедуру
8
+ # A test on a pure function and on a procedure
9
9
 
10
- Паттерн правила `testing`. Что при этом должно быть верно — закон
10
+ Pattern of the rule `testing`. What must be true — the law
11
11
  `docs/constitution/verifiability.md`.
12
12
 
13
- ## Когда брать
13
+ ## When to use
14
14
 
15
- - Заводится или правится `*.spec.ts` рядом с исходником.
16
- - Логику надо вынести из компонента или сервиса, чтобы её стало чем проверить.
17
- - Пишется спека на процедуру Connect.
15
+ - A `*.spec.ts` next to the source is being created or edited.
16
+ - Logic has to be moved out of a component or a service so that there is something to check it
17
+ with.
18
+ - A test on a Connect procedure is being written.
18
19
 
19
- ## Импорты явные
20
+ ## Imports are explicit
20
21
 
21
- `globals: true` в конфиге стоит, но список всё равно пишется:
22
+ `globals: true` stands in the config, but the list is written anyway:
22
23
 
23
24
  ```typescript
24
25
  import { describe, expect, it } from 'vitest';
25
26
  ```
26
27
 
27
- ## Один `describe` на функцию
28
+ ## One `describe` per function
28
29
 
29
- Имя блока совпадает с именем функции дословно; заголовки `it` — предложения по-русски,
30
- настоящим временем, о поведении, а не об устройстве:
30
+ The block name matches the function name word for word; the `it` titles are sentences in Russian,
31
+ present tense, about behaviour, not about the internals:
31
32
 
32
33
  ```typescript
33
34
  describe('applyDayClick', () => {
@@ -37,12 +38,13 @@ describe('applyDayClick', () => {
37
38
  });
38
39
  ```
39
40
 
40
- Идентификатор сценария из `docs/specs/<домен>/scenarios.md` стоит в начале заголовка, через
41
- тире. Краевые случаи — отдельные `it` в том же блоке, а не один тест с десятком проверок.
41
+ The scenario id from `docs/specs/<domain>/scenarios.md` stands at the start of the title, followed
42
+ by a dash. Edge cases are separate `it` blocks in the same `describe`, not one test with a dozen
43
+ assertions.
42
44
 
43
- ## Фикстура собирается функцией с `Partial<T>`
45
+ ## A fixture is built by a function with `Partial<T>`
44
46
 
45
- Не повторяющимся литералом:
47
+ Not by a repeated literal:
46
48
 
47
49
  ```typescript
48
50
  function day(iso: string, overrides: Partial<ICalendarDay> = {}): ICalendarDay {
@@ -57,74 +59,79 @@ function day(iso: string, overrides: Partial<ICalendarDay> = {}): ICalendarDay {
57
59
  }
58
60
  ```
59
61
 
60
- Общие константы (`PRICING`, `BUSY`) лежат наверху файла, в области модуля.
62
+ Shared constants (`PRICING`, `BUSY`) lie at the top of the file, at module scope.
61
63
 
62
- ## Решение выносится в чистую функцию
64
+ ## A decision is moved into a pure function
63
65
 
64
- Господствующая форма в этом дереве: логика уезжает в `*.logic.ts`, `*.util.ts` или
65
- `*.calculator.ts`, и проверяется вызовом — без `TestBed`, без подмены зависимостей. Образцы —
66
- `libs/site/common/booking/util/src/lib/availability-calendar.logic.ts` и
67
- `libs/api/<домен расчёта>/util/src/lib/quote.calculator.ts`.
66
+ The dominant form in this tree: the logic moves into `*.logic.ts`, `*.util.ts` or
67
+ `*.calculator.ts` and is checked by a call — without `TestBed`, without substituting dependencies.
68
+ Samples — `libs/site/common/booking/util/src/lib/availability-calendar.logic.ts` and
69
+ `libs/api/<quote domain>/util/src/lib/quote.calculator.ts`.
68
70
 
69
- ## Процедура зовётся напрямую
71
+ ## A procedure is called directly
70
72
 
71
- Обработчик — метод `handle` класса процедуры в слое `feature` своего домена. Двойник базы
72
- пишется руками; образец — `FakePrismaClient` в
73
- `libs/api/<домен заявок>/feature/src/lib/link-booking.procedure.spec.ts`:
73
+ The handler is the `handle` method of the procedure class in the `feature` layer of its domain. The
74
+ database double is written by hand; the sample is `FakePrismaClient` in
75
+ `libs/api/<booking domain>/feature/src/lib/link-booking.procedure.spec.ts`:
74
76
 
75
77
  ```typescript
76
78
  const prisma: FakePrismaClient = new FakePrismaClient();
77
79
  await procedureWith(prisma, emitter).handle(request());
78
80
  ```
79
81
 
80
- Проверяются порядок действий, откат при отказе половины, идемпотентность повтора и то, что
81
- именно ушло в базу. Раскладку полей стерегут тесты слоя `api`, и здесь она не повторяется.
82
+ What is checked is the order of actions, the rollback when half of it is refused, the idempotence
83
+ of a repeat and what exactly went into the database. The layout of fields is guarded by the tests
84
+ of the `api` layer and is not repeated here.
82
85
 
83
- ## Разовый тест-доказательство
86
+ ## A one-off proof test
84
87
 
85
- Дефект, который иначе подтверждается только чтением кода, доказывается тестом, написанным на
86
- время разбора: он поднимает настоящую процедуру, подменяет её единственный выход наружу и
87
- считает походы.
88
+ A defect that is otherwise confirmed only by reading the code is proved by a test written for the
89
+ time of the investigation: it raises the real procedure, substitutes its only way out and counts
90
+ the calls.
88
91
 
89
92
  ```typescript
90
93
  globalThis.fetch = (): Promise<Response> => Promise.resolve(Response.json({ success: false }));
91
94
  ```
92
95
 
93
- Число до правки и число после — единственная форма ответа, которую такая проверка даёт: «сто
94
- походов из ста» и «двадцать из ста» различимы, а «код выглядит правильным» — нет.
95
-
96
- Второй способ снять «до» — вернуть на место версию файла из точки расхождения ветки и
97
- прогнать тест ветки: падение теста и есть воспроизведение дефекта. Файл после этого
98
- восстанавливается копией, и восстановление проверяется прогоном того же теста, а не памятью.
99
-
100
- Двойники соседей не выдумываются: рабочий набор берётся из теста соседней процедуры того же
101
- домена. Двойник, собранный по типу, падает не на утверждении, а на вызове метода, которого у
102
- него нет.
103
-
104
- **Такой файл не коммитится.** Он живёт до конца разбора и удаляется вместе с ним; проверка,
105
- которую стоит оставить, переписывается в обычный `*.spec.ts` с идентификатором сценария в
106
- заголовке и едет в ветке. Признак временного файла — его заголовок не называет ни одного
107
- сценария.
108
-
109
- ## Зелёное, которое ничего не проверяет
110
-
111
- **Проба, ждущая молчания, идёт в паре с пробой, ждущей отказа.** Молчание наступает и тогда,
112
- когда проверять было нечем: приставка перед командой в конвейере действует на одно звено, и
113
- хук, получивший пустое значение, молчит ровно так же, как хук, которому нечего отбивать. Две
114
- пробы из трёх при этом зелены — они и ждали молчания, — и промах виден только по третьей,
115
- которая ждёт отказа.
116
-
117
- **Проба на мину, которая не срабатывает, зелена и без починки.** Сценарий на таблицу кодов
118
- отказа у спека без процедур проходил бы и до правки: читать эту таблицу сверке не приходится
119
- вовсе. Проверяется такая проба обеими сторонами — прежнее состояние возвращается на минуту и
120
- прогоняется: не покраснело, значит проба ничего не сторожит.
121
-
122
- ## Частые промахи
123
-
124
- - Либа без своего `vitest.config.mts`: `nx test <проект>` пройдёт зелёным, не запустив ни
125
- одного файла. Прежде чем писать первый тест в либе, проверить, что конфиг рядом есть.
126
- - Подмена модуля (`vi.mock`) скрыла бы то, ради чего тест и заводится, — какой именно вызов
127
- ушёл в базу и в каком порядке. Двойник пишется руками.
128
- - Своих помощников для проверок не заводить: `expect(...).toBe(...)` и `.toEqual(...)` прямо.
129
- - Заголовок с несуществующим идентификатором сценария роняет `npm run check:specs`, а сами
130
- тесты при этом остаются зелёными.
96
+ The number before the edit and the number after are the only form of answer such a check gives. "A
97
+ hundred calls out of a hundred" and "twenty out of a hundred" can be told apart, and "the code looks
98
+ right" cannot.
99
+
100
+ The second way to take the "before" is to put back the version of the file from the point where
101
+ the branch diverged and run the branch's test: the test failing is the reproduction of the defect.
102
+ After that the file is restored from the copy, and the restoration is checked by running the same
103
+ test, not by memory.
104
+
105
+ Doubles of the neighbours are not invented: the working set is taken from the test of a
106
+ neighbouring procedure of the same domain. A double assembled by type fails not on the assertion
107
+ but on the call of a method it does not have.
108
+
109
+ **Such a file is not committed.** It lives until the end of the investigation and is removed
110
+ together with it; a check worth keeping is rewritten as an ordinary `*.spec.ts` with the scenario
111
+ id in the title and goes in the branch. The sign of a temporary file is that its title names no
112
+ scenario at all.
113
+
114
+ ## Green that checks nothing
115
+
116
+ **A probe that expects silence goes paired with a probe that expects a refusal.** Silence also comes
117
+ when there was nothing to check with. A prefix before a command in the pipeline acts on one link,
118
+ and a hook that got an empty value is silent exactly like a hook that has nothing to refuse. Two
119
+ probes out of three are green then — they expected silence — and the miss is visible only by the
120
+ third, which expects a refusal.
121
+
122
+ **A probe on a mine that does not go off is green without the fix.** A scenario on the table of
123
+ refusal codes for a spec without procedures would have passed before the edit too: the audit
124
+ never has to read that table at all. Such a probe is checked from both sides — the previous state
125
+ is brought back for a minute and the probe is run: it did not turn red, so the probe guards
126
+ nothing.
127
+
128
+ ## Common misses
129
+
130
+ - A lib without its own `vitest.config.mts`: `nx test <project>` passes green without running a
131
+ single file. Before writing the first test in a lib, check that the config is next to it.
132
+ - Substituting a module (`vi.mock`) would hide what the test is created for — which call went to
133
+ the database and in what order. The double is written by hand.
134
+ - Do not create your own helpers for assertions: `expect(...).toBe(...)` and `.toEqual(...)`
135
+ directly.
136
+ - A title with a scenario id that does not exist takes `npm run check:specs` down, while the tests
137
+ themselves stay green.
@@ -2,25 +2,26 @@
2
2
  name: ts-procedure
3
3
  kind: pattern
4
4
  rule: typescript-conventions
5
- description: Паттерн правила typescript-conventions. Брать при заведении или правке процедуры Connect на бэкенде: готовый класс с полем метода и обработчиком, зависимости конструктором, имена файла и класса. Доступ к процедуре описывает правило доступа того дерева, где оно есть.
5
+ description: Pattern of rule typescript-conventions. Load when creating or editing a Connect procedure on the backend — the ready-made class with the method field and the handler, dependencies through the constructor, file and class names. Access to a procedure is described by the access rule of the tree.
6
6
  ---
7
7
 
8
- # Процедура Connect
8
+ # A Connect procedure
9
9
 
10
- Паттерн правила `typescript-conventions`. Что при этом должно быть верно — закон
10
+ Pattern of the rule `typescript-conventions`. What must be true — the law
11
11
  `docs/constitution/code-structure.md`.
12
12
 
13
- ## Когда брать
13
+ ## When to use
14
14
 
15
- - Заводится новая процедура бэкенда.
16
- - Правится тело существующей.
17
- - Домен переезжает на вертикальную нарезку.
15
+ - A new backend procedure is created.
16
+ - The body of an existing one is edited.
17
+ - A domain moves onto the vertical cut.
18
18
 
19
- ## Одна процедура — один класс
19
+ ## One procedure — one class
20
20
 
21
- Файл `<процедура>.procedure.ts` в слое `feature` своего домена, класс `<Процедура>Procedure`,
22
- публичное поле `method` с дескриптором из контракта и публичный метод `handle` с телом.
23
- Зависимости приходят конструктором — на бэкенде DI нестовский, `inject()` там нет.
21
+ The file `<procedure>.procedure.ts` in the `feature` layer of its domain, the class
22
+ `<Procedure>Procedure`, a public field `method` with the descriptor from the contract and a
23
+ public method `handle` with the body. Dependencies come through the constructor — on the backend
24
+ the DI is NestJS's, there is no `inject()` there.
24
25
 
25
26
  ```typescript
26
27
  @Injectable()
@@ -41,26 +42,28 @@ export class PingProcedure implements IConnectProcedure<typeof HealthService.met
41
42
  }
42
43
  ```
43
44
 
44
- Объявление доступа обязательно, и оно ровно одно; чем оно объявляется, говорит правило
45
- доступа того дерева, где такое правило есть.
45
+ The access declaration is mandatory, and there is exactly one; what declares it is said by the
46
+ access rule of the tree that has such a rule.
46
47
 
47
- ## Почему форма такая
48
+ ## Why this shape
48
49
 
49
- Прежняя — `register(router)` с телами в замыканиях внутри `router.service(...)` — делала
50
- обработчик недостижимым для спеки: наружу торчал только класс с методом `register`. А
51
- `router.service` заглушает каждый непереданный метод ответом `Unimplemented`, поэтому один
52
- proto-сервис не мог обслуживаться двумя доменами.
50
+ The previous one — `register(router)` with bodies in closures inside `router.service(...)` — made
51
+ the handler unreachable for a test: only a class with a `register` method stuck out. And
52
+ `router.service` stubs every method not passed with an `Unimplemented` answer, so one proto
53
+ service could not be served by two domains.
53
54
 
54
- Класс решает и то, и другое: `handle` зовётся спекой напрямую, а реестр кладёт процедуры
55
- поштучно через `router.rpc`.
55
+ The class solves both: `handle` is called by the test directly, and the registry puts the
56
+ procedures in one by one through `router.rpc`.
56
57
 
57
- ## Частые промахи
58
+ ## Common misses
58
59
 
59
- - Третий суффикс: `*.rpc.ts` и `*.connect.ts` — прежние имена, они уходят вместе с последним
60
- переехавшим доменом, и новых таких файлов не заводится.
61
- - `inject()` в классе процедуры: на бэкенде зависимости идут конструктором.
62
- - Тело в замыкании внутри регистрации роутера: спека до него не дотянется.
63
- - Процедура без объявления доступа: приложение не поднимется.
64
- - Приведение `as` в переводе моделей: на бэкенде оно запрещено так же, как в маппере фронта.
65
- - Свой тип у результата `groupBy` Prisma: он условный, собирается из аргументов вызова и с
66
- выписанным руками не сходится. Там, где ключей единицы, идёт `count` на ключ в `Promise.all`.
60
+ - A third suffix: `*.rpc.ts` and `*.connect.ts` are the previous names, they leave together with
61
+ the last domain moved, and no new such files are created.
62
+ - `inject()` in a procedure class: on the backend dependencies go through the constructor.
63
+ - The body in a closure inside the router registration: a test cannot reach it.
64
+ - A procedure without an access declaration: the application does not start.
65
+ - An `as` cast in model translation: on the backend it is forbidden the same as in a frontend
66
+ mapper.
67
+ - An own type for the result of Prisma's `groupBy`: it is conditional, assembled from the call
68
+ arguments, and does not match one written out by hand. Where the keys are few, a `count` per
69
+ key goes in `Promise.all`.