@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
@@ -1,39 +1,41 @@
1
1
  #!/usr/bin/env bash
2
2
  # rt-hook: PreToolUse Edit|Write|MultiEdit|mcp__webstorm__create_new_file|Bash|mcp__webstorm__execute_terminal_command
3
- # Требует: agents/strict-teacher.md, hooks/roles.sh, hooks/deny-tail.sh, hooks/write-targets.sh
4
- # Гард экзамена: правка не идёт, пока за сессию не сдан экзамен по загруженным правилам.
3
+ # Requires: agents/strict-teacher.md, hooks/roles.sh, hooks/deny-tail.sh, hooks/write-targets.sh
4
+ # Exam guard: no edit goes through until the exam on the loaded rules has been passed this session.
5
5
  #
6
- # Зачем именно так. Гейт правил требует загрузить правило перед правкой и на этом кончается:
7
- # загруженное правило и прочитанное правило для дерева неразличимы. Правило на четыре сотни
8
- # строк уезжает в контекст целиком, а исполняется выборочно — промахи случаются после того, как
9
- # правило было загружено. Спрашивает роль экзаменатора, а гард судит её вердикт.
6
+ # Why this way. The rules gate demands that a rule be loaded before an edit, and ends there: to
7
+ # the tree, a loaded rule and a read rule cannot be told apart. A rule of four hundred lines goes
8
+ # into the context whole and is carried out selectively — misses happen after the rule was loaded.
9
+ # The examiner role asks, and the guard judges its verdict.
10
10
  #
11
- # Вердикт роль отдаёт первой строкой: «ЭКЗАМЕН: сдано N из 5». Сдано — это пять из пяти; любое
12
- # другое число означает, что правило перечитывается целиком и экзамен пересдаётся.
11
+ # The role gives its verdict in the first line: "ЭКЗАМЕН: сдано N из 5". Passed means five out of
12
+ # five; any other number means the rule is reread whole and the exam is retaken.
13
13
  #
14
- # Списанный ответ экзаменом не считается. Отличить его от знания роль не может — а гард может:
15
- # между вопросами и ответами не должно быть чтения тех же правил. Признак грубый и своей границы
16
- # не скрывает: чтение соседнего правила он засчитает списыванием тоже.
14
+ # A copied answer does not count as an exam. The role cannot tell it from knowledge — the guard
15
+ # can: between the questions and the answers there must be no reading of the same rules. The sign
16
+ # is crude and does not hide its boundary: reading a neighbouring rule it counts as copying too.
17
17
  #
18
- # Вердикт ищется во всех формах записи хода, а не в одной. Форму доставки выбирает хост: роль,
19
- # работающая фоном, отдаёт результат уведомлением о завершении, и записи вида «ответ инструмента»
20
- # у неё нет вовсе. Дерево, где роль так и работает, гард запер целиком — пять кругов экзамена с
21
- # полным вердиктом не отпустили ни одной правки; разбор — в описаниях происшествий.
18
+ # The verdict is looked for in every form of the turn record, not in one. The delivery form is
19
+ # chosen by the host: a role running in the background returns its result as a completion notice,
20
+ # and has no record of the "tool result" kind at all. A tree where the role works that way was
21
+ # locked by the guard entirely — five rounds of the exam with a full verdict let no edit through;
22
+ # the analysis is in the incident records.
22
23
  #
23
- # Отброшены при этом две формы, и обе намеренно. Свой текст помощника вердиктом не бывает:
24
- # написать нужную строку в ответе стоит одного движения. Ответы инструментов чтения и записи —
25
- # тоже: печать той же строки эхом или чтение файла с нею проходили бы гард, то есть единственным
26
- # достижимым способом стала бы подделка. Засчитывается ответ инструмента, который читать и
27
- # писать файлы не умеет, — им роль и запускают.
24
+ # Two forms are discarded, both on purpose. The assistant's own text is never a verdict: writing
25
+ # the needed line in a reply costs one move. Results of the reading and writing tools are discarded
26
+ # too: echoing the same line or reading a file with it would pass the guard, so forgery would
27
+ # become the only reachable way. What counts is the result of a tool that cannot read or write
28
+ # files — the one the role is launched with.
28
29
  #
29
- # Из-под гарда выведены настройка дерева, её надстройки и передача захода: настройка, которой
30
- # гард выключается, этим гардом не запирается — иначе выхода из отказа нет вовсе. Отправка груза
31
- # в приём заперта была той же дырой: адрес приёма живёт в той же настройке.
30
+ # Taken out from under the guard: the tree settings, their overrides and the session handover.
31
+ # The setting that switches the guard off is not locked by this guard — otherwise there is no way
32
+ # out of the refusal at all. Sending cargo to the intake was locked by the same hole: the intake
33
+ # address lives in the same settings.
32
34
  #
33
- # FAIL-OPEN: нет jq, нет записи хода, чужой инструмент → пропуск. Сломанный гард не должен
34
- # мешать работать.
35
+ # FAIL-OPEN: no jq, no turn record, a foreign tool → pass. A broken guard must not get in the
36
+ # way of work.
35
37
 
36
- # Своё имя в наблюдениях: отбой пишет общий хвост отказа, а не сам гард.
38
+ # Its own name in observations: the refusal is written by the shared deny tail, not by the guard.
37
39
  RT_GUARD_NAME=exam-guard
38
40
 
39
41
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
@@ -44,21 +46,21 @@ input="$RT_HOOK_INPUT"
44
46
  [ -z "$input" ] && exit 0
45
47
  command -v jq >/dev/null 2>&1 || exit 0
46
48
 
47
- # Роль, выключенная деревом, гарда не держит: список выключенных лежит в настройке дерева, а
48
- # читает его помощник рядом. Нечитаемая настройка выключением не считается — гард работает как
49
- # прежде.
49
+ # A role disabled by the tree does not hold the guard: the list of disabled roles lies in the tree
50
+ # settings, and a helper next door reads it. Unreadable settings do not count as disabling — the
51
+ # guard works as before.
50
52
  rt_hooks_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
51
53
  # shellcheck disable=SC1090
52
54
  [ -f "$rt_hooks_dir/roles.sh" ] && . "$rt_hooks_dir/roles.sh" 2>/dev/null
53
55
  command -v rt_role_off >/dev/null 2>&1 && rt_role_off strict-teacher && exit 0
54
56
 
55
- # Цели записи разбирает общий помощник — тот же, которым их разбирает гард места правки.
57
+ # Write targets are parsed by the shared helper — the same one the edit-location guard uses.
56
58
  # shellcheck disable=SC1090
57
59
  [ -f "$rt_hooks_dir/write-targets.sh" ] && . "$rt_hooks_dir/write-targets.sh" 2>/dev/null
58
60
  command -v rt_write_targets >/dev/null 2>&1 || rt_write_targets() { cat >/dev/null; }
59
61
 
60
- # Пути, которые гард не судит: настройка дерева, её надстройки и каталог передачи захода.
61
- # Печатает «да», если все названные цели выведены из-под гарда.
62
+ # Paths the guard does not judge: the tree settings, their overrides and the session handover
63
+ # directory. Prints "да" if every named target is out from under the guard.
62
64
  rt_exam_free_paths() {
63
65
  free=1
64
66
  while IFS= read -r target; do
@@ -68,29 +70,33 @@ rt_exam_free_paths() {
68
70
  *) free=0 ;;
69
71
  esac
70
72
  done
71
- [ "$free" = "1" ] && printf 'да'
73
+ [ "$free" = "1" ] && printf 'yes'
72
74
  }
73
75
 
74
76
  tool="$(rt_hook_tool)"
75
- # Второй экзамен спрашивается на снятии черновика: работа кончилась, и правила поставки к этому
76
- # моменту читались давно — между их чтением и этой минутой прошёл весь заход.
77
+ # The second exam is asked when the draft is lifted: the work is over, and by then the delivery
78
+ # rules were read long ago — the whole session passed between their reading and this minute.
77
79
  ready=0
78
80
  case "$tool" in
79
81
  Edit | Write | MultiEdit | mcp__webstorm__create_new_file)
80
82
  target="$(printf '%s' "$input" | jq -r '.tool_input.file_path // .tool_input.pathInProject // empty' 2>/dev/null)"
81
- [ -n "$target" ] && [ "$(printf '%s\n' "$target" | rt_exam_free_paths)" = "да" ] && exit 0
83
+ [ -n "$target" ] && [ "$(printf '%s\n' "$target" | rt_exam_free_paths)" = "yes" ] && exit 0
82
84
  ;;
83
85
  Bash | mcp__webstorm__execute_terminal_command)
84
86
  cmd="$(rt_hook_cmd)"
85
- if printf '%s' "$cmd" | grep -qE 'pr[[:space:]]+ready|mr[[:space:]]+update[^|;&]*--ready'; then
87
+ # Lifting the draft is a client call, not an occurrence of the words: a command that only
88
+ # writes about lifting — a line in the proposals file, a commit body, an incident analysis
89
+ # — was checked the same as the lifting itself, and the refusal came on an attempt to
90
+ # describe this defect.
91
+ if printf '%s' "$cmd" | grep -qE "${RT_CMD_BOUND}(gh[[:space:]]+pr[[:space:]]+ready|glab[[:space:]]+mr[[:space:]]+update[^|;&]*--ready)([[:space:]]|\$)"; then
86
92
  ready=1
87
93
  else
88
- # Запись файла вызовом оболочки судится наравне с правкой: закрытый честный путь при
89
- # открытом обходном означает, что гард держит того, кто правилам следует, и пропускает
90
- # того, кто их обходит.
94
+ # Writing a file through a shell call is judged the same as an edit: an honest path
95
+ # closed while the bypass stays open means the guard holds whoever follows the rules
96
+ # and lets through whoever bypasses them.
91
97
  targets="$(printf '%s' "$cmd" | rt_write_targets)"
92
98
  [ -z "$targets" ] && exit 0
93
- [ "$(printf '%s\n' "$targets" | rt_exam_free_paths)" = "да" ] && exit 0
99
+ [ "$(printf '%s\n' "$targets" | rt_exam_free_paths)" = "yes" ] && exit 0
94
100
  fi
95
101
  ;;
96
102
  *) exit 0 ;;
@@ -100,14 +106,34 @@ transcript="$(printf '%s' "$input" | jq -r '.transcript_path // empty' 2>/dev/nu
100
106
  [ -z "$transcript" ] && exit 0
101
107
  [ -f "$transcript" ] || exit 0
102
108
 
103
- # Общий хвост отказа: два законных хода и законная форма обхода, если она у отказа есть. Файл
104
- # может быть не разложен — тогда хвоста нет, а причина отказа остаётся прежней.
109
+ # The shared deny tail: two lawful moves and the lawful form of bypass, if the refusal has one.
110
+ # The file may not be laid out — then there is no tail, and the reason for the refusal stays.
105
111
  # shellcheck disable=SC1090
106
112
  [ -f "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/deny-tail.sh" ] \
107
113
  && . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/deny-tail.sh" 2>/dev/null
108
114
  command -v rt_deny_tail >/dev/null 2>&1 || rt_deny_tail() { :; }
109
115
 
116
+ # The second way out of the refusal — one that does not require lifting protection.
117
+ #
118
+ # The guard used to name the list of disabled roles in the tree settings as the only way out. The
119
+ # environment the executor works in forbids editing such a list by a mechanism of its own, which
120
+ # the guard knows nothing about: one rule says "get out of here", the other says "not this way",
121
+ # and the work stands with a green suite and the owner's word given.
122
+ #
123
+ # The bypass is declared by the line `Exam-skip: <reason>` in the body of the last commit of the
124
+ # branch: it stays in history and is visible to the owner on the PR page. The reason is mandatory —
125
+ # a placeholder in its place does not count as a bypass, as with the documents guard.
126
+ rt_exam_declared_skip() {
127
+ git -C "${CLAUDE_PROJECT_DIR:-.}" log -1 --format=%B 2>/dev/null \
128
+ | grep -qE '^Exam-skip:[[:space:]]*[^[:space:]<]'
129
+ }
130
+
110
131
  deny() {
132
+ if rt_exam_declared_skip; then
133
+ printf 'the exam guard: a bypass is declared in the body of the last commit by the line Exam-skip. The call is let through, the record stays in the history.\n' >&2
134
+ exit 0
135
+ fi
136
+
111
137
  reason="$1"
112
138
  tail_text="$(rt_deny_tail "$2")"
113
139
  [ -n "$tail_text" ] && reason="$1 ${tail_text}"
@@ -116,86 +142,122 @@ deny() {
116
142
  exit 0
117
143
  }
118
144
 
119
- # Судится вся сессия, а не последний ход: экзамен сдаётся один раз на старте и держится до конца.
145
+ # The whole session is judged, not the last turn: the exam is passed once at the start and holds
146
+ # to the end.
120
147
  verdict="$(jq -s -r '
121
148
  def textof:
122
149
  if type == "string" then .
123
150
  elif type == "array" then (map(if type == "object" then (.text // "") else tostring end) | join("\n"))
124
151
  else tostring end;
125
152
 
126
- # Инструменты, читающие и пишущие файлы: их ответ вердиктом не считается — иначе печать той
127
- # же строки эхом и чтение файла с нею проходят гард, а настоящий вердикт не проходит.
153
+ # The call whose answer is discarded is recognised by its identifier, and the identifier is
154
+ # bound by a name: a dot after a pipe means the list itself, the search over it answers zero
155
+ # on any non-empty list, and every answer of every tool gets muted at once — that is, the
156
+ # verdict is looked for in the host records alone.
157
+ #
158
+ # Tools that read and write files: their result does not count as a verdict — otherwise
159
+ # echoing the same line or reading a file with it passes the guard, and the real verdict
160
+ # does not.
128
161
  ["Bash", "Read", "Grep", "Glob", "Edit", "Write", "MultiEdit", "NotebookEdit"] as $mute
129
162
  | [.[] | select(.type == "assistant") | (.message.content // [])[]
130
163
  | select(.type == "tool_use") | select(.name as $n | $mute | index($n) != null) | (.id // "")] as $muted
131
164
 
132
165
  | [ .[]
133
- # Свой текст помощника вердиктом не бывает: написать нужную строку в ответе стоит одного
134
- # движения.
166
+ # The assistant text is never a verdict: writing the needed line in a reply costs one
167
+ # move.
135
168
  | if .type == "assistant" then ""
136
169
  elif .type == "user" then
137
170
  ([ ((.message.content // []) | if type == "array" then .[] else empty end
138
171
  | select(.type == "tool_result")
139
- | select(((.tool_use_id // "") as $i | $muted | index($i)) == null)
172
+ | select(((.tool_use_id // "") | if . == "" then null else . end) as $id
173
+ | $id == null or ($muted | index($id)) == null)
140
174
  | .content | textof),
141
175
  ((.message.content // "") | if type == "string" then . else "" end),
142
- # Поле результата вызова: та же запись, другая форма. Отбрасывается, только
143
- # если этот результат принадлежит инструменту чтения или записи.
176
+ # The call result field: the same record, another form. Discarded only when
177
+ # this result belongs to a reading or writing tool.
144
178
  (. as $rec
145
179
  | if ($rec.toolUseResult // null) == null then ""
146
180
  elif ([($rec.message.content // []) | if type == "array" then .[] else empty end
147
181
  | select(.type == "tool_result") | (.tool_use_id // "")]
148
- | map($muted | index(.)) | any(. != null)) then ""
182
+ | map(. as $id | $muted | index($id)) | any(. != null)) then ""
149
183
  else ($rec.toolUseResult | textof) end)
150
184
  ] | join("\n"))
151
- # Записи хоста — уведомление о завершении роли и вложение: форму их выбирает хост, и
152
- # засчитываются они целиком.
185
+ # Host records — the role completion notice and the attachment: the host chooses their
186
+ # form, and they count whole.
153
187
  else tostring end ] | join("\n")
154
- | [scan("ЭКЗАМЕН:[[:space:]]*сдано[[:space:]]*([0-9]+)[[:space:]]*из[[:space:]]*([0-9]+)")]
155
- | if length == 0 then "нет"
156
- else (.[-1] | if .[0] == .[1] then "сдан" else "провален" end)
188
+ | [scan("(ЭКЗАМЕН:[[:space:]]*сдано|EXAM:[[:space:]]*passed)[[:space:]]*([0-9]+)[[:space:]]*(из|of)[[:space:]]*([0-9]+)")]
189
+ | if length == 0 then "none"
190
+ else (.[-1] | if .[1] == .[3] then "passed" else "failed" end)
157
191
  end
158
192
  ' "$transcript" 2>/dev/null)"
159
193
 
160
- # Второй экзамен — тот, что вынесен после открытия PR. Первый его не заменяет: спрашивают о
161
- # разном, и между ними лежит вся работа.
194
+ # The second exam is the one placed after the PR is opened. The first does not replace it: they
195
+ # ask about different things, and the whole work lies between them.
162
196
  if [ "$ready" = "1" ]; then
163
- # Записи сводятся в один поток в порядке их появления: команда и ответ инструмента лежат в
164
- # разных полях, и индекс из одного массива в другом не значит ничего.
197
+ # Records are brought into one stream in order of appearance: the command and the tool result
198
+ # lie in different fields, and an index from one array means nothing in the other.
165
199
  after="$(jq -s -r '
166
- [ .[]
167
- | if .type == "assistant"
168
- then ([(.message.content // [])[] | select(.type == "tool_use") | (.input.command // "")] | join("\n"))
169
- elif .type == "user"
170
- then ([(.message.content // []) | select(type == "array") | .[]
171
- | select(.type == "tool_result") | .content
172
- | if type == "string" then . elif type == "array"
173
- then (map(if type == "object" then (.text // "") else tostring end) | join("\n"))
174
- else tostring end] | join("\n"))
175
- else "" end ] as $flow
176
- | ($flow | map(test("pr[[:space:]]+create|mr[[:space:]]+create")) | index(true)) as $opened
177
- | if $opened == null then "нет-pr"
178
- else ($flow[($opened + 1):] | join("\n")
179
- | [scan("ЭКЗАМЕН:[[:space:]]*сдано[[:space:]]*([0-9]+)[[:space:]]*из[[:space:]]*([0-9]+)")]
180
- | if length == 0 then "нет"
181
- elif (.[-1] | .[0] == .[1]) then "сдан"
182
- else "провален" end)
200
+ def textof:
201
+ if type == "string" then .
202
+ elif type == "array" then (map(if type == "object" then (.text // "") else tostring end) | join("\n"))
203
+ else tostring end;
204
+
205
+ # The same set of forms as in the wide selection: the verdict arrives in the form the host
206
+ # chose, and a role running in the background returns it as a completion notice — it has
207
+ # no record of the "tool result" kind. Before, this selection read only the assistant
208
+ # commands and the tool results, and the second exam in such a tree did not count: five
209
+ # rounds with a full verdict let no edit through.
210
+ ["Bash", "Read", "Grep", "Glob", "Edit", "Write", "MultiEdit", "NotebookEdit"] as $mute
211
+ | [.[] | select(.type == "assistant") | (.message.content // [])[]
212
+ | select(.type == "tool_use") | select(.name as $n | $mute | index($n) != null) | (.id // "")] as $muted
213
+
214
+ # A record gives two strings: the command — by it the moment of opening the PR is found —
215
+ # and the verdict, checked by the same rules as in the wide selection. The order is the
216
+ # same, so counting from the found command stays correct.
217
+ | [ .[] | {
218
+ cmd: (if .type == "assistant"
219
+ then ([(.message.content // [])[] | select(.type == "tool_use") | (.input.command // "")] | join("\n"))
220
+ else "" end),
221
+ say: (if .type == "assistant" then ""
222
+ elif .type == "user" then
223
+ ([ ((.message.content // []) | if type == "array" then .[] else empty end
224
+ | select(.type == "tool_result")
225
+ | select(((.tool_use_id // "") | if . == "" then null else . end) as $id
226
+ | $id == null or ($muted | index($id)) == null)
227
+ | .content | textof),
228
+ ((.message.content // "") | if type == "string" then . else "" end),
229
+ (. as $rec
230
+ | if ($rec.toolUseResult // null) == null then ""
231
+ elif ([($rec.message.content // []) | if type == "array" then .[] else empty end
232
+ | select(.type == "tool_result") | (.tool_use_id // "")]
233
+ | map(. as $id | $muted | index($id)) | any(. != null)) then ""
234
+ else ($rec.toolUseResult | textof) end)
235
+ ] | join("\n"))
236
+ else tostring end)
237
+ } ] as $flow
238
+ | ($flow | map(.cmd | test("pr[[:space:]]+create|mr[[:space:]]+create")) | index(true)) as $opened
239
+ | if $opened == null then "no-pr"
240
+ else ($flow[($opened + 1):] | map(.say) | join("\n")
241
+ | [scan("(ЭКЗАМЕН:[[:space:]]*сдано|EXAM:[[:space:]]*passed)[[:space:]]*([0-9]+)[[:space:]]*(из|of)[[:space:]]*([0-9]+)")]
242
+ | if length == 0 then "none"
243
+ elif (.[-1] | .[1] == .[3]) then "passed"
244
+ else "failed" end)
183
245
  end
184
246
  ' "$transcript" 2>/dev/null)"
185
247
  case "$after" in
186
- сдан | нет-pr) exit 0 ;;
248
+ passed | no-pr) exit 0 ;;
187
249
  *)
188
- deny "BLOCKED by exam-guard: черновик снимается после второго экзамена, а его за эту сессию не было. Позови роль strict-teacher с правилами поставки и с тем, чего требовала задача: между чтением этих правил и снятием черновика прошёл весь заход."
250
+ deny "BLOCKED by exam-guard: the draft is lifted after the second exam, and there was none in this session. Call the role strict-teacher with the rules of delivery and with what the task demanded: a whole session passed between reading those rules and lifting the draft. The way out through the list of switched-off roles requires removing the protection, and the runtime may forbid such an edit; the second way out does not require it — declare the bypass by the line «Exam-skip: причина» in the body of the last commit of the branch: it stays in the history and is visible to the owner on the page of the request."
189
251
  ;;
190
252
  esac
191
253
  fi
192
254
 
193
255
  case "$verdict" in
194
- сдан) exit 0 ;;
195
- провален)
196
- deny "BLOCKED by exam-guard: экзамен по загруженным правилам провален. Перечитай правило целиком — не тот кусок, о котором спрашивали, — и позови роль strict-teacher снова. Показанный ответ даёт знание одной строки, а не правила."
256
+ passed) exit 0 ;;
257
+ failed)
258
+ deny "BLOCKED by exam-guard: the exam on the loaded rules is failed. Read the rule whole again — not the piece that was asked about — and call the role strict-teacher anew. The answer shown gives knowledge of one line, not of the rule. The way out through the list of switched-off roles requires removing the protection, and the runtime may forbid such an edit; the second way out does not require it — the bypass is declared by the line «Exam-skip: причина» in the body of the last commit of the branch."
197
259
  ;;
198
260
  *)
199
- deny "BLOCKED by exam-guard: за эту сессию экзамена по загруженным правилам не было. Позови роль strict-teacher, передай ей список загруженных правил, ответь на её вопросы по памяти и верни ей ответы — вердикт она отдаёт строкой «ЭКЗАМЕН: сдано N из 5». Засчитывается он из ответа роли в любой форме, какой его доставил хост, но не из вывода оболочки и не из твоего же текста: печать этой строки эхом гард не отпускает. Роль уже звали и вердикт получен — значит, он пришёл формой, которой гард не видит: это дефект гарда, и правка `.claude/rt-kit.json` из-под него выведена. Загруженное правило и прочитанное правило — разные вещи, и цену этой разницы платит владелец."
261
+ deny "BLOCKED by exam-guard: there was no exam on the loaded rules in this session. Call the role strict-teacher, hand it the list of loaded rules, answer its questions from memory and return the answers to it — the verdict it gives by the line «ЭКЗАМЕН: сдано N из 5». It counts from the answer of the role in whatever form the host delivered it, but not from the output of the shell and not from your own text: printing that line as an echo does not release the guard. The role was already called and the verdict received — then it arrived in a form the guard does not see: that is a defect of the guard, and an edit of `.claude/rt-kit.json` is taken out from under it. A loaded rule and a read rule are different things, and the price of that difference is paid by the owner."
200
262
  ;;
201
263
  esac
@@ -1,63 +1,65 @@
1
1
  #!/usr/bin/env bash
2
- # Конфликтующая своя заявка для гарда поставки: пока хоть одна отданная работа помечена
3
- # конфликтующей, новая не берётся.
2
+ # A conflicting PR of one's own, for the delivery guard: while at least one handed-over piece of
3
+ # work is marked conflicting, a new one is not taken.
4
4
  #
5
- # Строки `# rt-hook:` здесь нет намеренно: событие и образец вызова объявляет сам гард, а
6
- # помощник рядом хуком не регистрируется и в одиночку ничего не решает. Он зовётся из гарда,
7
- # пользуется его переменными и его отказом — тем же приёмом, что помощники папки и подписи.
5
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by
6
+ # the guard itself, while a helper next to it registers as no hook and decides nothing on its own.
7
+ # It is called from the guard, uses the guard's variables and the guard's refusal — the same way as
8
+ # the helpers of the folder and of the signature.
8
9
  #
9
- # Зачем именно так. Гард поставки стоит в трёх точках и в каждой требует того, что в эту минуту
10
- # исправимо, а состояние уже отданного не спрашивает нигде. Конфликт приезжает в отданную заявку
11
- # чужим слиянием, без единого действия её автора: влить её человек больше не может, и заявка
12
- # стоит, пока автор не заметит. Заметить её нечем — требование перечитывать свои открытые заявки
13
- # записано текстом и держится памятью: две заявки простояли конфликтующими весь заход, и заметил
14
- # это владелец.
10
+ # Why exactly so. The delivery guard stands at three points and at each one demands what is fixable
11
+ # at that minute, while the state of what has already been handed over it asks about nowhere. A
12
+ # conflict arrives into a handed-over PR through someone else's merge, without a single action by
13
+ # its author: a person can no longer merge it, and the PR stands until the author notices. There is
14
+ # nothing to notice it by — the demand to reread one's own open PRs is written as text and rests on
15
+ # memory: two PRs stood conflicting for a whole session, and it was the owner who noticed.
15
16
  #
16
- # Исправимо это ровно в минуту, когда берётся следующая работа: после неё конфликтов становится
17
- # больше, а не меньше — каждая новая заявка растёт из той же главной ветки и приезжает в ту же
18
- # очередь, которую придётся догонять.
17
+ # It is fixable exactly at the minute when the next piece of work is taken: after it there are more
18
+ # conflicts, not fewer — every new PR grows from the same main branch and arrives into the same
19
+ # queue that will have to be caught up with.
19
20
  #
20
- # Работой здесь считаются четыре команды: заведение задачи, заведение ветки под задачу, перевод
21
- # колонки в работу и открытие заявки. Всё, чем конфликт чинится, — подтягивание, вливание,
22
- # коммит, отправка, переход между ветками — идёт как прежде: гард, отбивающий починку, запирал
23
- # бы дерево наглухо.
21
+ # Four commands count as taking work here: creating a task, creating a branch for a task, moving the
22
+ # column into work and opening a PR. Everything a conflict is fixed by — pulling, merging,
23
+ # committing, pushing, switching between branches — goes as before: a guard that refuses the repair
24
+ # would lock the tree shut.
24
25
  #
25
- # Судится только прямое «конфликтует». Пока хостинг считает сливаемость, он отвечает
26
- # неопределённостью — и считает он её заново после каждой правки главной ветки, — а читать
27
- # неопределённость как конфликт значило бы отбивать работу на каждой свежей вершине.
26
+ # Only an outright "conflicts" is judged. While the hosting computes mergeability it answers with
27
+ # uncertainty — and it computes it again after every edit of the main branch — and reading
28
+ # uncertainty as a conflict would mean refusing work at every fresh tip.
28
29
  #
29
- # ОТКАЗ В ПОЛЬЗУ РАБОТЫ: нет функции профиля, нет сети, нет машинной записи — ярус пропускается.
30
+ # FAIL-OPEN: no profile function, no network, no machine account — the tier is skipped.
30
31
 
31
32
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
32
- # Начало вызова помощник берёт оттуда же, откуда все гарды. Источается он и здесь, хотя зовущий
33
- # гард это уже сделал: пустой образец превратил бы признак в поиск слова по всей строке.
33
+ # The helper takes the start of a call from the same place as every guard does. It is sourced here
34
+ # too, although the calling guard has already done so: an empty pattern would turn the sign into a
35
+ # word search over the whole line.
34
36
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/hook-input.sh" 2>/dev/null || true
35
37
 
36
38
  rt_delivery_conflict() {
37
- # Признак взятия работы читается из текста команды и стоит первым: опрос ходит в сеть, и
38
- # платить за него на каждой команде оболочки нельзя.
39
+ # The sign of taking work is read from the text of the command and stands first: the query goes
40
+ # to the network, and paying for it on every shell command is not allowed.
39
41
  taking=''
40
42
  case "$cmd" in
41
- *"${task_new}"*) taking='заведение задачи' ;;
43
+ *"${task_new}"*) taking='creating a task' ;;
42
44
  esac
43
- # Перевод колонки судится вместе с именем колонки работы: перевод в разбор и в закрытые —
44
- # это конец работы, а не её начало.
45
+ # Moving the column is judged together with the name of the work column: a move into review and
46
+ # into closed is the end of the work, not its beginning.
45
47
  if [ -z "$taking" ] && [ -n "$task_move" ]; then
46
48
  case "$cmd" in
47
49
  *"${task_move}"*)
48
50
  case "$cmd" in
49
- *"${RT_BOARD_INPROGRESS_KEY:-in-progress}"*) taking='перевод колонки в работу' ;;
51
+ *"${RT_BOARD_INPROGRESS_KEY:-in-progress}"*) taking='moving the column into work' ;;
50
52
  esac
51
53
  ;;
52
54
  esac
53
55
  fi
54
56
  if [ -z "$taking" ] \
55
- && printf '%s' "$cmd" | grep -qE '(^|[;&|[:space:]])git[[:space:]]+(checkout[[:space:]]+-b|switch[[:space:]]+-c)[[:space:]]+[A-Za-z]+-[0-9]+'; then
56
- taking='заведение ветки под задачу'
57
+ && printf '%s' "$cmd" | grep -qE '(^|[;&|[:space:]])git[[:space:]]+(checkout([[:space:]]+-[A-Za-z-]+)*[[:space:]]+-b|switch([[:space:]]+-[A-Za-z-]+)*[[:space:]]+-c)[[:space:]]+[A-Za-z]+-[0-9]+'; then
58
+ taking='creating a branch for a task'
57
59
  fi
58
60
  if [ -z "$taking" ] \
59
61
  && printf '%s' "$cmd" | grep -qE "${RT_CMD_BOUND}(gh[[:space:]]+pr[[:space:]]+create|glab[[:space:]]+mr[[:space:]]+create)([[:space:]]|\$)"; then
60
- taking='открытие заявки'
62
+ taking='opening a request'
61
63
  fi
62
64
  [ -z "$taking" ] && return 0
63
65
 
@@ -75,11 +77,11 @@ ${stuck}
75
77
  EOF
76
78
  [ -z "$listed" ] && return 0
77
79
 
78
- deny "BLOCKED: ${taking} при своей конфликтующей заявке. Отданное конфликтует с главной веткой, и влить его человек не может:
80
+ deny "BLOCKED: ${taking} while a conflicting request of your own stands. What was handed over conflicts with the main branch, and a person cannot merge it:
79
81
 
80
82
  ${listed}
81
83
 
82
- Конфликт приезжает чужим слиянием, без единого действия автора заявки: она стоит, пока её не догонят. Новая работа его не чинит — она прибавляет к очереди ещё одну ветку, которая растёт из той же главной и отстанет так же.
84
+ The conflict arrives by someone else's merge, without a single action by the author of the request: it stands until it is caught up with. New work does not fix it — it adds one more branch to the queue, growing from the same main and falling behind the same way.
83
85
 
84
- Ход отсюда один: подтянуть главную, влить её в названную ветку, разобрать конфликт и отправить — и только потом брать новую работу. Что чем чинится — паттерн git-workflow-freshness."
86
+ There is one move from here: pull the main branch, merge it into the named branch, resolve the conflict and send it — and only then take new work. What is fixed by what — the pattern git-workflow-freshness."
85
87
  }
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bash
2
+ # Leaving draft, for the delivery guard: does the PR have a review, does it conflict, and was it
3
+ # opened by the right account.
4
+ #
5
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by
6
+ # the guard itself, while a helper next to it registers as no hook and decides nothing on its own.
7
+ # It is called from the guard and uses the guard's own variables — the command, the tree root, the
8
+ # machine account — and the guard's refusal.
9
+ #
10
+ # It was moved out because the guard grew to the length limit: leaving draft is the most separate
11
+ # of its subjects — its own check point, its own network tier, its own three refusals.
12
+
13
+ . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
14
+ . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/hook-input.sh" 2>/dev/null || true
15
+
16
+ rt_delivery_draft_ready() {
17
+ # --- leaving draft ----------------------------------------------------------------------
18
+ #
19
+ # Before this edit nobody asked for a reviewer. He stood as prose in the rule, while the
20
+ # hosting accepts a review request on oneself silently and creates none: the review looks
21
+ # requested all the same. There is nowhere to ask earlier than leaving draft — before the PR
22
+ # is opened there is no reviewer at all — and leaving draft is itself the move that declares
23
+ # the work ready.
24
+ #
25
+ # The tier is a network one, and it stays silent the same way as the task state tier: no
26
+ # answer — no demand.
27
+ #
28
+ # Returning a PR to draft does not fall under the demand: it does exactly what the guard is
29
+ # after — it takes the look of readiness off the work.
30
+ if printf '%s' "$cmd" | grep -qE "${RT_CMD_BOUND}(gh[[:space:]]+pr[[:space:]]+ready|glab[[:space:]]+mr[[:space:]]+update[^|;&]*--ready)([[:space:]]|\$)" \
31
+ && ! printf '%s' "$cmd" | grep -q -- '--undo'; then
32
+ # A reference to the PR is optional: without it the client takes the PR of the current
33
+ # branch, and that is the shortest form of the call. Demanding a number would mean lifting
34
+ # the whole demand with a single space. So the first argument is taken, whatever it is —
35
+ # a number, an address or a branch name — and its absence means "ask about the current
36
+ # branch".
37
+ pull_ref="$(printf '%s' "$cmd" | sed -nE 's/.*(gh[[:space:]]+pr[[:space:]]+ready|glab[[:space:]]+mr[[:space:]]+update)[[:space:]]+([^[:space:];&|-][^[:space:];&|]*).*/\2/p' | head -1)"
38
+ if rt_needs rt_pull_state git-guard-delivery; then
39
+ pull="$(cd "$root" && rt_pull_state "$pull_ref" 2>/dev/null)" || pull=''
40
+ if [ -n "$pull" ] && printf '%s' "$pull" | jq -e '.exists' >/dev/null 2>&1; then
41
+ # The number is taken from the answer, and if it is not there — from the command
42
+ # itself: a PR named by an address or a branch name must stay recognisable in the
43
+ # refusal.
44
+ pull_name="$(printf '%s' "$pull" | jq -r '.number // empty' 2>/dev/null)"
45
+ # A number is written with a hash, and a branch name or an address in quotes: a
46
+ # hash before an address reads as a typo, not as a reference to a PR.
47
+ [ -z "$pull_name" ] && pull_name="$pull_ref"
48
+ case "$pull_name" in
49
+ '') ;;
50
+ *[!0-9]*) pull_name=" «${pull_name}»" ;;
51
+ *) pull_name=" #${pull_name}" ;;
52
+ esac
53
+ printf '%s' "$pull" | jq -e '.reviewed' >/dev/null 2>&1 \
54
+ || fault "the request${pull_name} has no review: no reviewer was requested and nobody left a review. A lifted draft reads as «ready to merge», and there is nobody to merge — set a reviewer and repeat."
55
+
56
+ # A conflict arrives into a handed-over PR through someone else's merge, without
57
+ # a single action by its author: the base checked at opening is yesterday's by the
58
+ # time draft is left. A PR out of draft reads as "ready to merge", and there is
59
+ # nothing to merge — the owner opens the PR and finds a conflict there. Silence on
60
+ # unknown mergeability stays: the hosting recomputes it after every edit of the
61
+ # main branch, and "not computed yet" is not "conflicts".
62
+ printf '%s' "$pull" | jq -e '.conflicting' >/dev/null 2>&1 \
63
+ && fault "the request${pull_name} conflicts with the main branch. Merge it into your branch, resolve the conflict and repeat: a lifted draft reads as «ready to merge», and this request cannot be merged."
64
+
65
+ # The author of the PR. At opening there was nothing to judge by but the text of
66
+ # the command: the identity of the call comes from the environment. Here it is
67
+ # already named by the hosting, and this is the last move where the miss is still
68
+ # fixable — after draft is left the PR gets merged, and a merged one cannot be
69
+ # reopened. A tree that named no machine account does not judge the author.
70
+ if [ -n "$task_bot" ]; then
71
+ pull_author="$(printf '%s' "$pull" | jq -r '.author // empty' 2>/dev/null)"
72
+ [ -n "$pull_author" ] && [ "$pull_author" != "$task_bot" ] \
73
+ && fault "the request${pull_name} was opened by the account «${pull_author}», not the machine one «${task_bot}». The author of a request is never its reviewer, and there is nothing to assign the review to. The author cannot be changed — close the request and open it anew${pull_token_hint:+, substituting the token: ${pull_token_hint} …}."
74
+ fi
75
+ fi
76
+ fi
77
+
78
+ # The task folder: the same subject as at opening and at the merge, as a third line. The
79
+ # condition is local — it reads the branch, not the hosting — and therefore stands outside
80
+ # the network tier above.
81
+ command -v rt_delivery_ready_folder >/dev/null 2>&1 && rt_delivery_ready_folder
82
+
83
+ deny_faults
84
+ fi
85
+ }