@rt-tools/agent-kit 0.24.0 → 0.27.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 (312) hide show
  1. package/assets/agents/business-analyst.md +51 -50
  2. package/assets/agents/cargo-writer.md +54 -0
  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-epic-link.github.mjs +29 -0
  15. package/assets/checks/board-epics.github.mjs +286 -49
  16. package/assets/checks/board-folders.mjs +61 -0
  17. package/assets/checks/board-gh.github.mjs +35 -26
  18. package/assets/checks/board-long-work.github.mjs +29 -25
  19. package/assets/checks/board-paths.github.mjs +21 -16
  20. package/assets/checks/board-pull-state.github.mjs +168 -0
  21. package/assets/checks/board-runs.github.mjs +45 -43
  22. package/assets/checks/board-task-dirs.github.mjs +98 -0
  23. package/assets/checks/board-titles.github.mjs +19 -17
  24. package/assets/checks/board.github.mjs +133 -194
  25. package/assets/checks/check-archive-age.mjs +23 -19
  26. package/assets/checks/check-board.github.mjs +131 -263
  27. package/assets/checks/check-descriptions.mjs +30 -29
  28. package/assets/checks/check-doc-paths.mjs +91 -88
  29. package/assets/checks/check-dupes.mjs +84 -80
  30. package/assets/checks/check-file-size.mjs +74 -71
  31. package/assets/checks/check-glossary.mjs +47 -37
  32. package/assets/checks/check-hook-scope.mjs +30 -27
  33. package/assets/checks/check-lib-layers.mjs +22 -21
  34. package/assets/checks/check-profile-drift.mjs +48 -43
  35. package/assets/checks/check-prose-style.mjs +138 -39
  36. package/assets/checks/check-push-gate.mjs +53 -50
  37. package/assets/checks/check-reuse.mjs +50 -40
  38. package/assets/checks/check-schema-drift.mjs +104 -84
  39. package/assets/checks/check-specs.mjs +155 -134
  40. package/assets/checks/check-state-next.mjs +66 -52
  41. package/assets/checks/check-states.mjs +32 -30
  42. package/assets/checks/check-styles.mjs +52 -51
  43. package/assets/checks/check-turn-map.mjs +54 -46
  44. package/assets/checks/epic-table.github.mjs +268 -0
  45. package/assets/checks/lib-boundaries.mjs +32 -30
  46. package/assets/checks/lib-common.mjs +30 -29
  47. package/assets/checks/lib-domains.mjs +34 -34
  48. package/assets/checks/lib-manifests.mjs +17 -15
  49. package/assets/checks/lib-reexports.mjs +18 -18
  50. package/assets/checks/rt-kit-checks.config.mjs +187 -142
  51. package/assets/checks/signals.mjs +43 -39
  52. package/assets/checks/spec-anchors.mjs +114 -87
  53. package/assets/checks/spec-common.mjs +128 -84
  54. package/assets/checks/spec-contract.mjs +30 -30
  55. package/assets/checks/spec-proposed.mjs +27 -24
  56. package/assets/checks/spec-scenarios.mjs +51 -28
  57. package/assets/checks/specs-for.mjs +214 -0
  58. package/assets/checks/task-new.github.mjs +315 -61
  59. package/assets/commands/feedback.md +65 -59
  60. package/assets/commands/next-session.md +64 -57
  61. package/assets/commands/night.md +115 -0
  62. package/assets/commands/skill-curator.md +83 -79
  63. package/assets/defaults/gate-map.sh +108 -97
  64. package/assets/defaults/project.sh +232 -185
  65. package/assets/defaults/shell.sh +73 -68
  66. package/assets/defaults/turn-map.md +47 -44
  67. package/assets/docs/GLOSSARY.md +142 -65
  68. package/assets/hooks/browser-device-id.sh +16 -12
  69. package/assets/hooks/browser-guard-device-id.sh +34 -28
  70. package/assets/hooks/browser-guard-no-asking.sh +5 -4
  71. package/assets/hooks/browser-guard-no-listing.sh +12 -11
  72. package/assets/hooks/browser-guard-no-other-drivers.sh +48 -42
  73. package/assets/hooks/browser-guard-require-select.sh +34 -23
  74. package/assets/hooks/claim-guard.sh +62 -56
  75. package/assets/hooks/commit-msg.sh +14 -10
  76. package/assets/hooks/conscience-guard.sh +91 -45
  77. package/assets/hooks/constitution-index.sh +16 -16
  78. package/assets/hooks/deny-tail.sh +28 -26
  79. package/assets/hooks/dev-server-guard.sh +50 -43
  80. package/assets/hooks/dispatch.sh +60 -46
  81. package/assets/hooks/docs-guard.sh +100 -91
  82. package/assets/hooks/epic-over.sh +49 -0
  83. package/assets/hooks/epic-stop-guard.sh +108 -0
  84. package/assets/hooks/exam-guard.sh +105 -93
  85. package/assets/hooks/git-guard-delivery-conflict.sh +41 -36
  86. package/assets/hooks/git-guard-delivery-draft.sh +48 -38
  87. package/assets/hooks/git-guard-delivery-epic.sh +167 -0
  88. package/assets/hooks/git-guard-delivery-folder.sh +50 -43
  89. package/assets/hooks/git-guard-delivery-signature.sh +119 -53
  90. package/assets/hooks/git-guard-delivery.sh +223 -183
  91. package/assets/hooks/git-guard-main.sh +38 -34
  92. package/assets/hooks/git-guard-push-tests.sh +99 -87
  93. package/assets/hooks/glossary-load.sh +23 -22
  94. package/assets/hooks/grill-gate-ask.sh +12 -11
  95. package/assets/hooks/grill-gate.sh +94 -87
  96. package/assets/hooks/guard-note.sh +20 -19
  97. package/assets/hooks/handoff-entry-guard.sh +45 -25
  98. package/assets/hooks/handoff-write.sh +74 -67
  99. package/assets/hooks/hook-input.sh +67 -58
  100. package/assets/hooks/lint-after-edit.sh +95 -61
  101. package/assets/hooks/observe.sh +28 -26
  102. package/assets/hooks/override-write-guard.sh +23 -21
  103. package/assets/hooks/postmortem-guard.sh +42 -39
  104. package/assets/hooks/profile-check.sh +22 -20
  105. package/assets/hooks/proposal-guard.sh +57 -49
  106. package/assets/hooks/prose-style-guard.sh +49 -24
  107. package/assets/hooks/qa-dataid-guard.sh +83 -58
  108. package/assets/hooks/rerun-guard.sh +31 -30
  109. package/assets/hooks/reuse-first-guard.sh +108 -87
  110. package/assets/hooks/roles.sh +14 -14
  111. package/assets/hooks/rule-article.sh +39 -34
  112. package/assets/hooks/rule-source-guard.sh +47 -42
  113. package/assets/hooks/skill-gate-layers.sh +63 -57
  114. package/assets/hooks/skill-gate-rearm.sh +15 -8
  115. package/assets/hooks/skill-gate.sh +89 -81
  116. package/assets/hooks/skill-loaded.sh +10 -6
  117. package/assets/hooks/sql-guard-parse.sh +71 -66
  118. package/assets/hooks/sql-guard-request.sh +51 -46
  119. package/assets/hooks/sql-guard-target.sh +60 -51
  120. package/assets/hooks/sql-guard-write.sh +87 -79
  121. package/assets/hooks/sql-guard.sh +52 -47
  122. package/assets/hooks/stand-login-guard.sh +43 -37
  123. package/assets/hooks/task-context-load.sh +60 -55
  124. package/assets/hooks/task-flow-context.sh +87 -69
  125. package/assets/hooks/task-flow-draft-guard.sh +55 -48
  126. package/assets/hooks/task-flow-guard.sh +67 -64
  127. package/assets/hooks/turn-entry-load.sh +39 -32
  128. package/assets/hooks/turn-exit-guard.sh +260 -204
  129. package/assets/hooks/turn-exit-patterns.sh +63 -0
  130. package/assets/hooks/utf8.sh +14 -11
  131. package/assets/hooks/waiting-turn-guard.sh +104 -94
  132. package/assets/hooks/window-fill-guard.sh +70 -62
  133. package/assets/hooks/work-start-guard.sh +52 -49
  134. package/assets/hooks/write-targets.sh +99 -44
  135. package/assets/laws/autonomous-work.md +29 -27
  136. package/assets/laws/code-structure.md +31 -30
  137. package/assets/laws/delivery.md +170 -137
  138. package/assets/laws/entity-editing.md +52 -50
  139. package/assets/laws/entity-models.md +14 -13
  140. package/assets/laws/frontend-application.md +39 -38
  141. package/assets/laws/lib-imports.md +27 -27
  142. package/assets/laws/lists.md +31 -29
  143. package/assets/laws/navigation.md +37 -37
  144. package/assets/laws/observability.md +41 -40
  145. package/assets/laws/project-documentation.md +106 -99
  146. package/assets/laws/reuse-first.md +31 -29
  147. package/assets/laws/shared-code.md +27 -27
  148. package/assets/laws/verifiability.md +131 -124
  149. package/assets/laws/work-conduct.md +250 -244
  150. package/assets/patterns/admin-lists-screen.md +72 -69
  151. package/assets/patterns/admin-nav-item.md +51 -46
  152. package/assets/patterns/angular-patterns-state.md +32 -31
  153. package/assets/patterns/api-layer-pair.md +33 -31
  154. package/assets/patterns/autonomous-work-run.md +50 -49
  155. package/assets/patterns/browser-verification-measure.md +124 -88
  156. package/assets/patterns/browser-verification-stand.md +169 -157
  157. package/assets/patterns/component-structure-new.md +51 -42
  158. package/assets/patterns/dependencies-upgrade.md +55 -39
  159. package/assets/patterns/doc-style-human.md +55 -37
  160. package/assets/patterns/doc-style-sweep.md +82 -79
  161. package/assets/patterns/doc-style-trace.md +87 -81
  162. package/assets/patterns/doc-style-write.md +130 -122
  163. package/assets/patterns/entity-aside.md +77 -63
  164. package/assets/patterns/entity-models-new.md +37 -37
  165. package/assets/patterns/entity-store.md +33 -33
  166. package/assets/patterns/git-workflow-commit.azure.md +94 -87
  167. package/assets/patterns/git-workflow-commit.github.md +160 -142
  168. package/assets/patterns/git-workflow-commit.gitlab.md +96 -90
  169. package/assets/patterns/git-workflow-docker.md +165 -147
  170. package/assets/patterns/git-workflow-freshness.md +45 -45
  171. package/assets/patterns/git-workflow-merge.md +102 -94
  172. package/assets/patterns/git-workflow-migration.md +54 -52
  173. package/assets/patterns/git-workflow-pr-ready.md +57 -56
  174. package/assets/patterns/git-workflow-pr.azure.md +127 -122
  175. package/assets/patterns/git-workflow-pr.github.md +186 -177
  176. package/assets/patterns/git-workflow-pr.gitlab.md +139 -132
  177. package/assets/patterns/git-workflow-restart.md +35 -31
  178. package/assets/patterns/git-workflow-secrets.md +80 -73
  179. package/assets/patterns/git-workflow-stack.md +136 -107
  180. package/assets/patterns/lib-layers-move.md +62 -53
  181. package/assets/patterns/lib-layers-new.md +59 -45
  182. package/assets/patterns/observability-record.md +72 -67
  183. package/assets/patterns/platform-access-di.md +31 -29
  184. package/assets/patterns/reuse-first-extend.md +66 -61
  185. package/assets/patterns/shared-code-new.md +39 -38
  186. package/assets/patterns/spec-driven-domain.md +161 -151
  187. package/assets/patterns/spec-driven-rule.md +179 -168
  188. package/assets/patterns/spec-driven-sweep.md +41 -39
  189. package/assets/patterns/status-report-table.github.md +48 -36
  190. package/assets/patterns/styling-bem-component.md +42 -42
  191. package/assets/patterns/styling-bem-layout.md +39 -34
  192. package/assets/patterns/styling-bem-sheet.md +59 -58
  193. package/assets/patterns/task-flow-archive.md +222 -215
  194. package/assets/patterns/task-flow-close.md +234 -203
  195. package/assets/patterns/task-flow-handoff.md +154 -145
  196. package/assets/patterns/task-flow-resume.md +138 -133
  197. package/assets/patterns/task-flow-start.md +228 -202
  198. package/assets/patterns/testing-e2e.md +102 -101
  199. package/assets/patterns/testing-unit.md +77 -70
  200. package/assets/patterns/ts-procedure.md +32 -29
  201. package/assets/patterns/turn-entry-map.md +50 -48
  202. package/assets/pitfalls/agent-kit.md +172 -142
  203. package/assets/pitfalls/doc-style.md +96 -91
  204. package/assets/pitfalls/git-workflow.azure.md +49 -46
  205. package/assets/pitfalls/git-workflow.github.md +270 -234
  206. package/assets/pitfalls/git-workflow.gitlab.md +49 -45
  207. package/assets/pitfalls/spec-driven.md +73 -71
  208. package/assets/pitfalls/styling-bem.md +46 -40
  209. package/assets/pitfalls/task-flow.md +262 -246
  210. package/assets/pitfalls/testing.md +99 -92
  211. package/assets/pitfalls/turn-conduct.md +96 -81
  212. package/assets/rules/angular-patterns.md +81 -80
  213. package/assets/rules/api-layer.md +77 -74
  214. package/assets/rules/autonomous-work.md +87 -74
  215. package/assets/rules/browser-verification.md +223 -214
  216. package/assets/rules/component-structure.md +72 -69
  217. package/assets/rules/dependencies.md +74 -67
  218. package/assets/rules/deploy-flow.azure.md +118 -108
  219. package/assets/rules/deploy-flow.github.md +145 -135
  220. package/assets/rules/deploy-flow.gitlab.md +120 -110
  221. package/assets/rules/doc-style.md +201 -173
  222. package/assets/rules/entity-conventions.needs-admin.md +81 -79
  223. package/assets/rules/entity-models.md +73 -70
  224. package/assets/rules/git-workflow.azure.md +224 -228
  225. package/assets/rules/git-workflow.github.md +268 -239
  226. package/assets/rules/git-workflow.gitlab.md +218 -217
  227. package/assets/rules/lib-layers.md +85 -86
  228. package/assets/rules/lists.md +101 -97
  229. package/assets/rules/navigation.md +78 -78
  230. package/assets/rules/observability.needs-app.md +165 -153
  231. package/assets/rules/platform-access.md +76 -75
  232. package/assets/rules/reuse-first.md +153 -143
  233. package/assets/rules/shared-code.md +82 -79
  234. package/assets/rules/spec-driven.md +279 -260
  235. package/assets/rules/status-report.md +62 -58
  236. package/assets/rules/styling-bem.md +81 -77
  237. package/assets/rules/task-flow.md +303 -270
  238. package/assets/rules/testing.md +224 -209
  239. package/assets/rules/turn-conduct.md +262 -258
  240. package/assets/rules/turn-entry.md +92 -87
  241. package/assets/rules/typescript-conventions.md +94 -88
  242. package/assets/samples/specs/_template/spec.md +47 -47
  243. package/assets/samples/tasks/_template/grill.md +20 -20
  244. package/assets/samples/tasks/_template/plan.md +32 -30
  245. package/assets/samples/tasks/_template/progress.md +16 -16
  246. package/assets/skills/agent-kit-extend.md +129 -113
  247. package/assets/skills/agent-kit.md +259 -233
  248. package/assets/skills/write-a-skill.md +76 -71
  249. package/assets/templates/findings.md +19 -19
  250. package/assets/templates/gate-map.sh +16 -14
  251. package/assets/templates/implementation.md +28 -27
  252. package/assets/templates/pattern.md +17 -17
  253. package/assets/templates/pitfalls.md +6 -6
  254. package/assets/templates/postmortem.md +24 -23
  255. package/assets/templates/project.sh +24 -24
  256. package/assets/templates/proposal.md +62 -60
  257. package/assets/templates/rule.md +38 -38
  258. package/assets/workflows/feature.js +46 -46
  259. package/assets/workflows/plan.js +54 -54
  260. package/bin/agent-kit.d.ts.map +1 -1
  261. package/bin/agent-kit.js +8 -1
  262. package/bin/agent-kit.js.map +1 -1
  263. package/lib/cargo-prose.d.ts +41 -0
  264. package/lib/cargo-prose.d.ts.map +1 -0
  265. package/lib/cargo-prose.js +88 -0
  266. package/lib/cargo-prose.js.map +1 -0
  267. package/lib/cargo.d.ts +12 -1
  268. package/lib/cargo.d.ts.map +1 -1
  269. package/lib/cargo.js +8 -2
  270. package/lib/cargo.js.map +1 -1
  271. package/lib/catalog.d.ts +2 -0
  272. package/lib/catalog.d.ts.map +1 -1
  273. package/lib/catalog.js +4 -3
  274. package/lib/catalog.js.map +1 -1
  275. package/lib/commands.d.ts.map +1 -1
  276. package/lib/commands.js +5 -2
  277. package/lib/commands.js.map +1 -1
  278. package/lib/companion.js +3 -2
  279. package/lib/companion.js.map +1 -1
  280. package/lib/enroll.d.ts +7 -1
  281. package/lib/enroll.d.ts.map +1 -1
  282. package/lib/enroll.js +12 -3
  283. package/lib/enroll.js.map +1 -1
  284. package/lib/fate.d.ts +29 -0
  285. package/lib/fate.d.ts.map +1 -0
  286. package/lib/fate.js +147 -0
  287. package/lib/fate.js.map +1 -0
  288. package/lib/override-marks.d.ts +7 -0
  289. package/lib/override-marks.d.ts.map +1 -1
  290. package/lib/override-marks.js +14 -0
  291. package/lib/override-marks.js.map +1 -1
  292. package/lib/plan.d.ts +11 -0
  293. package/lib/plan.d.ts.map +1 -1
  294. package/lib/plan.js +10 -1
  295. package/lib/plan.js.map +1 -1
  296. package/lib/ship.d.ts +29 -9
  297. package/lib/ship.d.ts.map +1 -1
  298. package/lib/ship.js +44 -2
  299. package/lib/ship.js.map +1 -1
  300. package/lib/shipment.d.ts.map +1 -1
  301. package/lib/shipment.fixture.d.ts +8 -1
  302. package/lib/shipment.fixture.d.ts.map +1 -1
  303. package/lib/shipment.fixture.js +9 -0
  304. package/lib/shipment.fixture.js.map +1 -1
  305. package/lib/shipment.js +38 -5
  306. package/lib/shipment.js.map +1 -1
  307. package/lib/sync.d.ts.map +1 -1
  308. package/lib/sync.js +45 -11
  309. package/lib/sync.js.map +1 -1
  310. package/package.json +1 -1
  311. package/rt-tools-agent-kit-0.27.0.tgz +0 -0
  312. package/rt-tools-agent-kit-0.24.0.tgz +0 -0
@@ -1,23 +1,28 @@
1
1
  #!/usr/bin/env bash
2
- # Адресат запроса для гарда хранилища: боевая база, одноразовая база проверки или что-то
3
- # третье — и что на боевой разрешено.
2
+ # The request's target for the storage guard: the production database, a throwaway check
3
+ # database or something else — and what is allowed on production.
4
4
  #
5
- # Строки `# rt-hook:` здесь нет намеренно: событие и образец вызова объявляет сам гард, а
6
- # помощник рядом хуком не регистрируется и в одиночку ничего не решает.
5
+ # NOT a guard: it has no `rt-hook:` declaration and hooks into no agent event. The storage guard
6
+ # sources it — one tier of its verdict, moved out when the guard reached its length limit.
7
+ #
8
+ # There is no `# rt-hook:` line here on purpose: the event and the call sample are declared by the
9
+ # guard itself, and the helper next to it is not registered as a hook and decides nothing alone.
7
10
 
8
- # --- прод: запись запрещена в любом виде ------------------------------------------------
9
- # Признак берётся из профиля: порт туннеля, хост, домен — у каждого дерева свои.
11
+ # --- production: a write is forbidden in any form ------------------------------------------
12
+ # The sign is taken from the profile: the tunnel port, the host, the domain — each tree has its
13
+ # own.
10
14
  #
11
- # Ищем его в АДРЕСЕ, а не в данных: домен приложения живёт и в самих строках — в почте
12
- # владельца, в канонической ссылке объекта. Пока признак брался по всей команде, вставка
13
- # строки с таким адресом в локальную базу отклонялась как запись в бой, а опт-аута у этой
14
- # ветки нет по замыслу — команда становилась неисполнимой.
15
- # Поэтому текст запроса (то, что стоит после `-c`/`--command`) из проверки вырезается.
15
+ # We look for it in the ADDRESS, not in the data: the application's domain also lives in the rows
16
+ # themselves — in the owner's email, in the canonical link of an object. While the sign was taken
17
+ # over the whole command, inserting a row with such an address into the local database was
18
+ # refused as a write to production, and this branch has no opt-out by design — the command became
19
+ # impossible to run.
20
+ # So the request text (what stands after `-c`/`--command`) is cut out of the check.
16
21
  #
17
- # Запрос из редактора адресата в тексте не называет: база выбирается идентификатором
18
- # подключения, и по одному SQL отличить прод от локальной копии невозможно. Поэтому
19
- # подключения опознаются в лицо. Список сверяется вызовом list_database_connections;
20
- # добавили новое — допишите сюда, иначе оно попадёт в «неизвестные» ниже.
22
+ # A request from the IDE does not name the target in its text: the database is chosen by a
23
+ # connection identifier, and by the SQL alone production cannot be told from the local copy. So
24
+ # connections are recognised by sight. The list is checked against list_database_connections;
25
+ # added a new one — add it here, otherwise it lands in the "unknown" below.
21
26
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
22
27
 
23
28
  sql_resolve_target() {
@@ -28,18 +33,18 @@ sql_resolve_target() {
28
33
  conn_known=""
29
34
  if [ -n "$conn" ]; then
30
35
  case " $PROD_CONNECTIONS " in *" $conn "*) is_prod="yes"; conn_known="prod" ;; esac
31
- # Опознанное локальное подключение сильнее текстовой догадки: домен приложения живёт в
32
- # самих данных — в почте владельца, в канонической ссылке объекта. Пока вывод не
33
- # отменялся, обновление такой строки на локальной базе отклонялось как запись в бой, и
34
- # обойти это было нечем.
36
+ # A recognised local connection outweighs a textual guess: the application's domain lives
37
+ # in the data itself — in the owner's email, in the canonical link of an object. While
38
+ # the verdict was not overridden, updating such a row on the local database was refused as
39
+ # a write to production, and there was nothing to bypass it with.
35
40
  case " $LOCAL_CONNECTIONS " in *" $conn "*) conn_known="local"; is_prod="" ;; esac
36
41
  fi
37
42
 
38
- # Для запроса из редактора адрес в тексте не назван вовсе: там решает опознанное
39
- # подключение, а если оно неизвестно — ветка ниже спросит пользователя.
43
+ # For a request from the IDE the address is not named in the text at all: there the
44
+ # recognised connection decides, and if it is unknown, the branch below asks the user.
40
45
  is_scratch=""
41
46
  addr_other=""
42
- if [ -z "$conn" ] && [ "$context" != "запрос через подключение редактора (обёртка исполнителя)" ]; then
47
+ if [ -z "$conn" ] && [ "$context" != "a request through the connection of the editor (the wrapper of the executor)" ]; then
43
48
  while IFS= read -r seg; do
44
49
  [ -z "$seg" ] && continue
45
50
  if [ -n "$PROD_DSN" ] && printf '%s' "$seg" | grep -qE "$PROD_DSN"; then
@@ -47,23 +52,26 @@ sql_resolve_target() {
47
52
  addr_other="yes"
48
53
  continue
49
54
  fi
50
- # Одноразовая база проверки: петлевой адрес и порт из отведённого под них диапазона.
51
- # Диапазон занимают контейнеры, которые поднимают на время одной проверки —
52
- # восстановление копии, репетиция миграции на непустой базе — и сносят следом. Данных,
53
- # которые стоило бы стеречь, там нет по построению, а вопрос на каждую строку такой
54
- # проверки приучает отвечать «да» не читая и обесценивает тот вопрос, который был важен.
55
+ # A throwaway check database: a loopback address and a port from the range set aside
56
+ # for them. The range is taken by containers raised for the time of one check —
57
+ # restoring a copy, rehearsing a migration on a non-empty database — and torn down
58
+ # right after. There is no data worth guarding there by construction, and a question
59
+ # on every line of such a check teaches answering "yes" without reading and devalues
60
+ # the question that mattered.
55
61
  #
56
- # Диапазон узкий и петлевой намеренно: под него не должны попадать ни рабочая база
57
- # дерева, ни туннель к бою, ни базы соседних деревьев на этой машине. Какой он здесь,
58
- # знает профиль; не назван — исключения нет вовсе, и вопрос задаётся всегда.
62
+ # The range is narrow and loopback on purpose: neither the tree's working database,
63
+ # nor the tunnel to production, nor the databases of neighbouring trees on this
64
+ # machine must fall under it. What it is here is known by the profile; not named —
65
+ # there is no exception at all, and the question is always asked.
59
66
  if [ -n "${RT_SCRATCH_PORT_RE:-}" ] \
60
67
  && printf '%s' "$seg" | grep -qE "$RT_SCRATCH_PORT_RE" \
61
68
  && printf '%s' "$seg" | grep -qE '127\.0\.0\.1|localhost|host\.docker\.internal'; then
62
69
  is_scratch="yes"
63
70
  else
64
- # Любой другой адресованный вызов снимает исключение целиком: в цепочке
65
- # `psql -p 19434 -f x.sql && psql -c "delete …"` ранний выход убрал бы проверку
66
- # со второго звена, а это ровно тот обход, ради которого гард и написан.
71
+ # Any other addressed call lifts the exception entirely: in the chain
72
+ # `psql -p 19434 -f x.sql && psql -c "delete …"` an early exit would remove the
73
+ # check from the second link, and that is exactly the bypass the guard is written
74
+ # against.
67
75
  addr_other="yes"
68
76
  fi
69
77
  done <<EOF
@@ -72,28 +80,29 @@ EOF
72
80
  fi
73
81
  }
74
82
 
75
- # Исключение стоит ПОСЛЕ разбора адреса и ПЕРЕД правилами записи, но строго после того, как
76
- # признак боевой базы уже выставлен: прод перекрывает исключение при любом совпадении, а не
77
- # наоборот. Условие тройное — одноразовый адрес найден, боевого нет, и других адресованных
78
- # вызовов в команде нет вовсе.
83
+ # The exception stands AFTER the address parsing and BEFORE the write rules, but strictly after
84
+ # the production sign has already been set: production overrides the exception on any match, not
85
+ # the other way round. The condition is threefold — a throwaway address is found, there is no
86
+ # production one, and there are no other addressed calls in the command at all.
79
87
  sql_pass_scratch() {
80
88
  if [ -n "$is_scratch" ] && [ -z "$is_prod" ] && [ -z "$addr_other" ]; then
81
89
  exit 0
82
90
  fi
83
91
  }
84
92
 
85
- # На боевой базе разрешено только то, что гард опознал как чтение — БЕЛЫМ списком, а не
86
- # перечислением запретов. Чёрный список здесь принципиально не работает: SQL доезжает до
87
- # сервера файлом, редиректом, `\copy`, `SELECT … INTO`, и каждая заделанная форма оставляет
88
- # соседнюю. Поэтому вопрос перевёрнут: не «есть ли здесь запись», а «доказано ли чтение».
93
+ # On the production database only what the guard recognised as a read is allowed — by an ALLOW
94
+ # list, not by enumerating prohibitions. A deny list fundamentally does not work here: SQL reaches
95
+ # the server as a file, a redirect, `\copy`, `SELECT … INTO`, and every form sealed leaves the
96
+ # neighbouring one open. So the question is turned around: not "is there a write here" but "is a
97
+ # read proven".
89
98
  #
90
- # Чтением считаются три формы, и каждая проверяется в СЕГМЕНТЕ своего вызова:
91
- # pg_dump без --clean/--create — снятие дампа
92
- # psql -c "<один SELECT>" — запрос без второго стейтмента
93
- # psql -l / --version / --help — проверка соединения без запроса
99
+ # Three forms count as a read, and each is checked in the SEGMENT of its own call:
100
+ # pg_dump without --clean/--create — taking a dump
101
+ # psql -c "<one SELECT>" — a query without a second statement
102
+ # psql -l / --version / --help — a connection check without a query
94
103
  sql_check_prod() {
95
104
  if [ -n "$is_prod" ] && [ -n "$is_write" ]; then
96
- deny "BLOCKED: запись в БОЕВОЕ хранилище (${context}). Адрес ведёт на бой — оттуда данные не восстанавливаются ничем, кроме копии. Схема на бою меняется миграцией через выкатку, данные — через панель владельца. Если правка данных на бою действительно нужна, её делает владелец руками, предварительно сняв копию; гард обойти нельзя."
105
+ deny "BLOCKED: a write into the PRODUCTION storage (${context}). The address leads to production — data is restored from there by nothing but a copy. The schema in production is changed by a migration through the rollout, the data — through the panel of the owner. If an edit of production data really is needed, the owner makes it by hand, having taken a copy first; the guard cannot be bypassed."
97
106
  fi
98
107
 
99
108
  if [ -n "$is_prod" ]; then
@@ -101,9 +110,9 @@ sql_check_prod() {
101
110
  while IFS= read -r seg; do
102
111
  [ -z "$seg" ] && continue
103
112
  seg_read=""
104
- # Аргументы клиента — всё, что стоит ПОСЛЕ его имени. До имени в том же сегменте
105
- # свободно живут чужие флаги: `docker compose -f docker-compose.prod.yml … psql`,
106
- # и `-f` от compose однажды отменял доказательство чтения.
113
+ # The client's arguments are everything AFTER its name. Before the name in the same
114
+ # segment other flags live freely: `docker compose -f docker-compose.prod.yml … psql`,
115
+ # and compose's `-f` once cancelled the proof of a read.
107
116
  seg_tail="$(printf '%s' "$seg" | perl -0pe 's{^.*?(?<![[:alnum:]_./-])(psql|pg_restore|prisma)(?=\s|$)}{$1}s' 2>/dev/null)"
108
117
  [ -z "$seg_tail" ] && seg_tail="$seg"
109
118
 
@@ -114,7 +123,7 @@ sql_check_prod() {
114
123
  esac
115
124
  fi
116
125
 
117
- # Один SELECT и ничего кроме: второй стейтмент через `;` уже не чтение.
126
+ # One SELECT and nothing else: a second statement after `;` is no longer a read.
118
127
  if printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_])select([^[:alnum:]_]|$)' \
119
128
  && ! printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
120
129
  && ! printf '%s' "$seg_tail" | grep -qE '(^|[[:space:]])(-f|--file)([[:space:]]|=)'; then
@@ -130,7 +139,7 @@ $segments
130
139
  EOF
131
140
 
132
141
  if [ -n "$unproven" ]; then
133
- deny "BLOCKED: вызов клиента БД против БОЕВОЙ базы (${context}). На проде разрешено только доказанное чтение — \`pg_dump\` без \`--clean\`, одиночный SELECT через \`-c\`, либо \`-l\`/\`--version\`. Всё остальное отклоняется, даже если гард просто не разобрал команду: содержимое файлов (\`-f\`, \`< dump.sql\`), \`\\copy\` и восстановление дампа ему не видны. Если нужен разбор данных боевой базы — снимай дамп и работай с локальной копией."
142
+ deny "BLOCKED: a call of the database client against the PRODUCTION database (${context}). In production only a proven read is allowed — \`pg_dump\` without \`--clean\`, a single SELECT through \`-c\`, or \`-l\`/\`--version\`. Everything else is refused, even when the guard simply did not parse the command: the content of files (\`-f\`, \`< dump.sql\`), \`\\copy\` and restoring a dump are invisible to it. If an analysis of production data is needed — take a dump and work with a local copy."
134
143
  fi
135
144
  fi
136
145
  }
@@ -1,22 +1,26 @@
1
1
  #!/usr/bin/env bash
2
- # Запись для гарда хранилища: что считается записью, что из неё заведомо разрушительно, куда
3
- # идут миграции и по чему запрос адресует строки.
2
+ # The write part of the storage guard: what counts as a write, what in it is destructive for
3
+ # certain, where migrations go and by what a query addresses rows.
4
4
  #
5
- # Строки `# rt-hook:` здесь нет намеренно: событие и образец вызова объявляет сам гард, а
6
- # помощник рядом хуком не регистрируется и в одиночку ничего не решает.
5
+ # NOT a guard: it has no `rt-hook:` declaration and hooks into no agent event. The storage guard
6
+ # sources it — one tier of its verdict, moved out when the guard reached its length limit.
7
+ #
8
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by
9
+ # the guard itself, while a helper next to it registers no hook and decides nothing on its own.
7
10
 
8
- # Глаголы ищутся в сегментах ВЫЗОВА, а не по всей строке: иначе слово из шаблона поиска в
9
- # соседнем звене цепочки объявляло записью читающую команду.
11
+ # The verbs are looked for in the segments of the CALL, not over the whole line: otherwise a word
12
+ # from a search pattern in a neighbouring link of the chain declared a reading command a write.
10
13
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
11
14
 
12
15
  sql_detect_write() {
13
16
  is_write=""
14
17
  write_scope="$segments"
15
- # `copy … from` и `select … into` — запись, не называющая ни одного привычного глагола.
18
+ # `copy … from` and `select … into` are a write that names not one of the usual verbs.
16
19
  printf '%s' "$write_scope" | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|create|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
17
20
  && is_write="yes"
18
- # Конвейер из источника в клиент — та же доставка файла, только без флага: содержимое
19
- # `cat fix.sql | psql …` гарду не видно, значит это запись по определению.
21
+ # A pipeline from a source into the client is the same file delivery, only without a flag: the
22
+ # content of `cat fix.sql | psql …` is not visible to the guard, so this is a write by
23
+ # definition.
20
24
  while IFS= read -r seg; do
21
25
  [ -z "$seg" ] && continue
22
26
  printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_.-])(cat|head|tail|gzcat|zcat|gunzip|echo|printf|curl|wget)([[:space:]]|$)' \
@@ -25,34 +29,36 @@ sql_detect_write() {
25
29
  $(client_segments)
26
30
  PIPE_EOF
27
31
 
28
- # Команды prisma меняют базу, не называя ни одного SQL-глагола: `migrate reset` пересоздаёт
29
- # её целиком, `db push` подгоняет схему под модель, `db execute` льёт произвольный файл.
32
+ # prisma commands change the database without naming a single SQL verb: `migrate reset`
33
+ # recreates it whole, `db push` fits the schema to the model, `db execute` pours in an
34
+ # arbitrary file.
30
35
  printf '%s' "$write_scope" | grep -qE 'prisma[[:space:]]+(migrate[[:space:]]+(reset|deploy|dev)|db[[:space:]]+(push|execute))' \
31
36
  && is_write="yes"
32
37
 
33
- # Глагол в командной строке — не единственный способ довезти SQL до сервера. Файл (`-f`,
34
- # `--file`, `< dump.sql`) и `pg_restore` не называют ни одного, поэтому раньше проходили
35
- # мимо всех трёх уровней: доставка файла в клиент на боевой базе завершалась нулём
36
- # без единого вопроса, а `pg_restore` не мог сработать в принципе, хотя `--clean` сносит
37
- # содержимое. Содержимое файла гарду недоступно — значит это запись по определению.
38
+ # A verb on the command line is not the only way to get SQL to the server. A file (`-f`,
39
+ # `--file`, `< dump.sql`) and `pg_restore` name none, so they used to pass by all three levels:
40
+ # delivering a file into the client on the production database ended with zero without a single
41
+ # question, and `pg_restore` could not fire in principle, although `--clean` wipes the content.
42
+ # The content of the file is unavailable to the guard — so this is a write by definition.
38
43
  printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_.-])pg_restore([^[:alnum:]_.-]|$)' \
39
44
  && is_write="yes"
40
- # У `pg_dump` тот же `-f` означает файл ВЫВОДА: это чтение, и записью его считать нельзя —
41
- # иначе штатное снятие дампа с боевой базы отклонялось, хотя текст отказа сам его советует.
45
+ # For `pg_dump` the same `-f` means the OUTPUT file: this is a read, and it must not be counted
46
+ # as a write — otherwise a routine dump of the production database was rejected, although the
47
+ # text of the refusal advises it itself.
42
48
  #
43
- # Исключение действует ПОСЕГМЕНТНО. Пока оно проверялось по всей команде, одного упоминания
44
- # `pg_dump` где угодно в цепочке хватало, чтобы `-f` перестал считаться записью во всех
45
- # остальных вызовах: `pg_dump … > /dev/null && psql -d app -f /tmp/x.sql` проходил молча.
49
+ # The exception acts PER SEGMENT. While it was checked over the whole command, one mention of
50
+ # `pg_dump` anywhere in the chain was enough for `-f` to stop counting as a write in all the
51
+ # other calls: `pg_dump … > /dev/null && psql -d app -f /tmp/x.sql` passed silently.
46
52
  while IFS= read -r seg; do
47
53
  [ -z "$seg" ] && continue
48
- # Граница слова обязательна: `-f /tmp/pg_dump-restore.sql` — это заливка дампа, а не
49
- # его снятие, и подстрочное совпадение снимало с неё обе защиты разом.
54
+ # The word boundary is mandatory: `-f /tmp/pg_dump-restore.sql` is loading a dump, not
55
+ # taking one, and a substring match removed both protections from it at once.
50
56
  if printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_.-])pg_dump(all)?([^[:alnum:]_.-]|$)'; then
51
57
  continue
52
58
  fi
53
- # Хвост сегмента после имени клиента: `-f` у `docker compose` (боевой compose-файл
54
- # называется нестандартно, без флага не поднимается) стоит ДО `psql` и к запросу
55
- # отношения не имеет.
59
+ # The tail of the segment after the client name: the `-f` of `docker compose` (the
60
+ # production compose file is named non-standardly and does not come up without the flag)
61
+ # stands BEFORE `psql` and has nothing to do with the query.
56
62
  seg_tail="$(printf '%s' "$seg" | perl -0pe 's{^.*?(?<![[:alnum:]_./-])(psql|pg_restore|prisma)(?=\s|$)}{$1}s' 2>/dev/null)"
57
63
  [ -z "$seg_tail" ] && seg_tail="$seg"
58
64
  if printf '%s' "$seg_tail" | grep -qE '(^|[[:space:]])(-f|--file)([[:space:]]|=)|<[[:space:]]*[^[:space:]|<]+\.(sql|dump)'; then
@@ -64,13 +70,13 @@ $segments
64
70
  EOF
65
71
  }
66
72
 
67
- # --- заведомо разрушительное ------------------------------------------------------------
73
+ # --- destructive for certain ------------------------------------------------------------
68
74
  verdict() {
69
75
  if [ -n "$soft" ]; then
70
- ask "Запрос помечен маркером destructive-ok, но остаётся разрушительным: $1 Подтверди выполнение, если это осознанно."
76
+ ask "The request is marked by the destructive-ok marker but stays destructive: $1 Confirm the execution if this is deliberate."
71
77
  fi
72
- deny "BLOCKED: $1 Адресуй строки по первичному ключу — \`WHERE id IN ('…','…')\`: так затрагивается ровно столько строк, сколько перечислено, и промах виден до выполнения. Удаление по маске (email LIKE '%test%') однажды унесло вместе с тестовыми записями демонстрационные брони владельца. Если адресация по id действительно не подходит — сначала выполни SELECT с тем же условием и покажи пользователю, что попадает под удаление." \
73
- "маркер destructive-ok при запросе, с объяснением"
78
+ deny "BLOCKED: $1 Address the rows by the primary key — \`WHERE id IN ('…','…')\`: that way exactly as many rows are touched as are listed, and a miss is visible before the execution. A deletion by a mask (email LIKE '%test%') once carried away, together with the test records, the demonstration bookings of the owner. If addressing by id really does not fit — first run a SELECT with the same condition and show the user what falls under the deletion." \
79
+ "the destructive-ok marker at the request, with an explanation"
74
80
  }
75
81
 
76
82
  sql_check_destructive() {
@@ -80,38 +86,38 @@ sql_check_destructive() {
80
86
  esac
81
87
 
82
88
  if printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_])(truncate|drop[[:space:]]+(table|database|schema|column|index)|alter[[:space:]]+table)([^[:alnum:]_]|$)'; then
83
- verdict "запрос меняет саму схему или очищает таблицу целиком (${context})."
89
+ verdict "the request changes the schema itself or empties a table whole (${context})."
84
90
  fi
85
91
 
86
92
  if printf '%s' "$flat" | grep -qE 'prisma[[:space:]]+(migrate[[:space:]]+reset|db[[:space:]]+push)'; then
87
- verdict "\`prisma migrate reset\` / \`db push\` пересоздаёт базу и теряет её содержимое (${context})."
93
+ verdict "\`prisma migrate reset\` / \`db push\` recreates the database and loses its content (${context})."
88
94
  fi
89
95
 
90
- # `pg_restore --clean` перед загрузкой удаляет существующие объекты — то же очищение
91
- # таблиц, только чужими руками. Без `--clean` это обычная догрузка, она идёт общим путём.
96
+ # `pg_restore --clean` deletes the existing objects before loading — the same emptying of
97
+ # tables, only by someone else's hands. Without `--clean` it is an ordinary top-up, and it goes
98
+ # the common path.
92
99
  if printf '%s' "$flat" | grep -q 'pg_restore' && printf '%s' "$flat" | grep -qE '(^|[[:space:]])(--clean|-c|--create)([[:space:]]|=|$)'; then
93
- verdict "\`pg_restore --clean\` удаляет объекты базы перед загрузкой дампа (${context})."
100
+ verdict "\`pg_restore --clean\` deletes the objects of the database before loading the dump (${context})."
94
101
  fi
95
102
  }
96
103
 
97
- # Штатное применение миграций разрушительным не считается. Раньше здесь стоял безусловный
98
- # `ask` со словами «убедись, что DATABASE_URL указывает на локальную базу» — гард
99
- # перекладывал на человека ровно ту работу, которую умеет сделать сам. На локальной базе
100
- # миграции гоняются постоянно, и вопрос на каждую не добавляет безопасности: гард, который
101
- # спрашивает по десятому разу, перестают читать вместе с тем единственным вопросом, который
102
- # был важен.
104
+ # A routine application of migrations does not count as destructive. There used to stand an
105
+ # unconditional `ask` here with the words "make sure DATABASE_URL points at the local database" —
106
+ # the guard shifted onto a person exactly the work it can do itself. On a local database migrations
107
+ # are run all the time, and a question on each adds no safety: a guard that asks for the tenth time
108
+ # stops being read together with that one question that mattered.
103
109
  #
104
- # Поэтому адрес РАЗРЕШАЕТСЯ, а не угадывается: сначала inline-префикс самой команды, затем
105
- # переменная окружения, затем `.env` рабочего каталога.
110
+ # So the address is RESOLVED, not guessed: first the inline prefix of the command itself, then the
111
+ # environment variable, then the `.env` of the working directory.
106
112
  unquote() {
107
113
  sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//"
108
114
  }
109
115
 
110
116
  resolve_database_url() {
111
- # Искать по `$flat` нельзя: он приведён к нижнему регистру, и `DATABASE_URL=` в нём
112
- # не встречается никогда — правило молча брало бы адрес из `.env`, игнорируя явно
113
- # указанный в команде. Разбирается исходная строка, а `$flat` остаётся запасным
114
- # вариантом с регистронезависимым поиском.
117
+ # Searching by `$flat` is not allowed: it is brought to lower case, and `DATABASE_URL=` never
118
+ # occurs in it — the rule would silently take the address from `.env`, ignoring the one named
119
+ # explicitly in the command. The original line is parsed, and `$flat` stays the fallback with a
120
+ # case-insensitive search.
115
121
  inline="$(printf '%s' "${cmd:-}" | grep -oE '[Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee]_[Uu][Rr][Ll]=[^[:space:]]+' | tail -n1)"
116
122
  [ -z "$inline" ] && inline="$(printf '%s' "$flat" | grep -oiE 'database_url=[^[:space:]]+' | tail -n1)"
117
123
  if [ -n "$inline" ]; then
@@ -122,10 +128,10 @@ resolve_database_url() {
122
128
  printf '%s' "$DATABASE_URL" | unquote
123
129
  return
124
130
  fi
125
- # Подъём по дереву, а не только рабочий каталог: агент работает в git worktree под
126
- # `.claude/worktrees/<ветка>/`, где своего `.env` нет, а у основного чекаута — есть,
127
- # и он лежит ровно выше по пути. Без подъёма гард не разрешил бы адрес ни разу
128
- # именно там, где миграции и гоняются.
131
+ # Climbing up the tree, not only the working directory: the agent works in a git worktree under
132
+ # `.claude/worktrees/<branch>/`, where there is no `.env` of its own, while the main checkout
133
+ # has one, and it lies exactly higher up the path. Without the climb the guard would not have
134
+ # resolved the address once, exactly where the migrations are run.
129
135
  dir="$hook_cwd"
130
136
  depth=0
131
137
  while [ -n "$dir" ] && [ "$dir" != '/' ] && [ "$depth" -lt 8 ]; do
@@ -145,21 +151,22 @@ resolve_database_url() {
145
151
  sql_check_migrations() {
146
152
  if printf '%s' "$flat" | grep -qE 'prisma[[:space:]]+migrate[[:space:]]+(deploy|dev)'; then
147
153
  migrate_target="$(resolve_database_url)"
148
- # Боевой адрес проверяется ДО разбора по видам: туннель к бою тоже висит на петлевом
149
- # адресе, только на своём порту, и общее правило «петлевой значит локальный» пропустило бы
150
- # миграцию на бой.
154
+ # The production address is checked BEFORE the parse by kinds: a tunnel to production also
155
+ # hangs on a loopback address, only on a port of its own, and the common rule "loopback
156
+ # means local" would have let a migration through to production.
151
157
  if [ -n "$PROD_DSN" ] && printf '%s' "$migrate_target" | grep -qE "$PROD_DSN"; then
152
- deny "BLOCKED: применение миграций к БОЕВОЙ базе (${context}). Адрес базы ведёт на бой. Схема на бою меняется выкаткой: она сама зовёт применение миграций одноразовым контейнером до старта приложения. Руками этого делать нельзя — гард обойти нельзя."
158
+ deny "BLOCKED: applying migrations to the PRODUCTION database (${context}). The address of the database leads to production. The schema in production is changed by the rollout: it calls the applying of migrations itself, by a one-off container, before the application starts. Doing this by hand is not allowed — the guard must not be bypassed."
153
159
  fi
154
160
  case "$migrate_target" in
155
161
  *@localhost:*|*@127.0.0.1:*|*@postgres:*|*@host.docker.internal:*)
156
- # Локальная база — штатная работа. Разбор завершается здесь, иначе ниже
157
- # сработает общее правило про запись в базу и вопрос всё равно будет задан:
158
- # `migrate deploy` помечен записью выше по тексту.
162
+ # A local database is routine work. The parse ends here, otherwise the common rule
163
+ # about writing to the database fires below and the question is asked anyway:
164
+ # `migrate deploy` is marked a write higher up the text.
159
165
  #
160
- # Но выйти можно, только если запись в команде ОДНА — сама миграция. В цепочке
161
- # `prisma migrate deploy && psql -c "delete …"` ранний выход снял бы проверку со
162
- # второго звена, а это ровно тот обход, ради которого гард и написан.
166
+ # But it can be exited only if there is ONE write in the command — the migration
167
+ # itself. In the chain `prisma migrate deploy && psql -c "delete …"` an early exit
168
+ # would remove the check from the second link, and that is exactly the bypass the
169
+ # guard is written for.
163
170
  other_write=""
164
171
  printf '%s' "$write_scope" \
165
172
  | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|create|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
@@ -174,42 +181,43 @@ MIGRATE_PIPE_EOF
174
181
  [ -z "$other_write" ] && exit 0
175
182
  ;;
176
183
  '')
177
- ask "Применение миграций к базе (${context}), но адрес разрешить не удалось: DATABASE_URL нет ни в команде, ни в окружении, ни в \`.env\` рабочего каталога. Проверь, куда пойдёт миграция, и подтверди."
184
+ ask "Applying migrations to a database (${context}), but the address could not be resolved: DATABASE_URL is neither in the command, nor in the environment, nor in the \`.env\` of the working directory. Check where the migration will go, and confirm."
178
185
  ;;
179
186
  *)
180
- ask "Применение миграций по адресу, НЕИЗВЕСТНОМУ ГАРДУ (${context}). Гард знает локальные адреса и боевые; этот — ни то, ни другое. Убедись, что это не прод, и подтверди."
187
+ ask "Applying migrations to an address UNKNOWN TO THE GUARD (${context}). The guard knows local addresses and production ones; this is neither. Make sure this is not production, and confirm."
181
188
  ;;
182
189
  esac
183
190
  fi
184
191
  }
185
192
 
186
- # --- delete/update: смотрим на адресацию ------------------------------------------------
193
+ # --- delete/update: looking at the addressing -------------------------------------------
187
194
  sql_check_addressing() {
188
195
  if printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_])(delete[[:space:]]+from|update)([^[:alnum:]_]|$)'; then
189
196
  if ! printf '%s' "$flat" | grep -q 'where'; then
190
- verdict "DELETE/UPDATE без WHERE затрагивает всю таблицу (${context})."
197
+ verdict "DELETE/UPDATE without WHERE touches the whole table (${context})."
191
198
  fi
192
199
 
193
- # Адресация ищется ТОЛЬКО в хвосте после последнего `where`. Пока смотрели на весь
194
- # запрос, присваивание в SET засчитывалось за адресацию: `UPDATE bookings SET
195
- # "propertyId" = 'p1' WHERE source = 'site'` выглядел адресным, хотя задевал все прямые
196
- # заявки объекта — ровно то, от чего гард и защищает.
197
- # Регистр здесь сохраняется, в отличие от `flat`: колонки Prisma пишутся в camelCase, и
198
- # приведённый к нижнему регистру `bookingid` уже не отличить от слова `paid`.
200
+ # The addressing is looked for ONLY in the tail after the last `where`. While the whole
201
+ # query was looked at, an assignment in SET counted as addressing: `UPDATE bookings SET
202
+ # "propertyId" = 'p1' WHERE source = 'site'` looked addressed, although it touched every
203
+ # direct request for the property — exactly what the guard protects from.
204
+ # The case is kept here, unlike in `flat`: Prisma columns are written in camelCase, and
205
+ # `bookingid` brought to lower case is no longer distinguishable from the word `paid`.
199
206
  where_tail="$(printf '%s' "$sql" | tr '\n\t' ' ' | sed -E 's/.*[Ww][Hh][Ee][Rr][Ee]/where/')"
200
207
 
201
- # Имя колонки требуется целиком: `id`, `booking_id`, `"bookingId"`. Прежний шаблон
202
- # `[a-z_]*id` принимал за идентификатор `paid` и `valid`.
208
+ # The column name is required whole: `id`, `booking_id`, `"bookingId"`. The former pattern
209
+ # `[a-z_]*id` took `paid` and `valid` for an identifier.
203
210
  if ! printf '%s' "$where_tail" | grep -qE '(^|[^[:alnum:]_"])"?(id|[A-Za-z_]+_id|[a-zA-Z]+Id)"?[[:space:]]*(=|[Ii][Nn][[:space:]]*\()'; then
204
- verdict "DELETE/UPDATE адресует строки не по идентификатору (${context}) — условие может совпасть шире, чем задумано."
211
+ verdict "DELETE/UPDATE addresses the rows not by an identifier (${context}) — the condition may match wider than intended."
205
212
  fi
206
213
 
207
- # Гард видит имя колонки, но не схему: `propertyId` и `session_id` — внешние ключи, и
208
- # запрос по ним адресный только на вид. `DELETE … WHERE "propertyId" = 'p1'` сносит все
209
- # брони объекта. Отличить это от первичного ключа без схемы нельзя, поэтому решение
210
- # остаётся за пользователем — но предупреждение должно быть прямым, а не общим.
214
+ # The guard sees the column name but not the schema: `propertyId` and `session_id` are
215
+ # foreign keys, and a query by them is addressed only in appearance. `DELETE … WHERE
216
+ # "propertyId" = 'p1'` wipes every booking of the property. Telling this from a primary key
217
+ # without the schema is impossible, so the decision stays with the user — but the warning
218
+ # must be direct, not general.
211
219
  if ! printf '%s' "$where_tail" | grep -qE '(^|[^[:alnum:]_"])"?id"?[[:space:]]*(=|[Ii][Nn][[:space:]]*\()'; then
212
- ask "Условие адресует строки по ВНЕШНЕМУ ключу, а не по первичному (${context}): $(printf '%s' "$where_tail" | head -c 200). Под него попадут ВСЕ строки, связанные с этой сущностью, — например \`WHERE \"propertyId\" = …\` заденет все брони объекта, включая демонстрационные. Если нужны конкретные строки, сперва выбери их SELECT-ом и перечисли в \`WHERE id IN (…)\`."
220
+ ask "The condition addresses the rows by a FOREIGN key, not by the primary one (${context}): $(printf '%s' "$where_tail" | head -c 200). ALL the rows tied to that record fall under it — for example \`WHERE \"propertyId\" = …\` touches every booking of the property, the demonstration ones included. If specific rows are needed, first select them by a SELECT and list them in \`WHERE id IN (…)\`."
213
221
  fi
214
222
  fi
215
223
  }