@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,23 +1,25 @@
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
+ # There is no `# rt-hook:` line here on purpose: the event and the call sample are declared by the
6
+ # guard itself, and the helper next to it is not registered as a hook and decides nothing alone.
7
7
 
8
- # --- прод: запись запрещена в любом виде ------------------------------------------------
9
- # Признак берётся из профиля: порт туннеля, хост, домен — у каждого дерева свои.
8
+ # --- production: a write is forbidden in any form ------------------------------------------
9
+ # The sign is taken from the profile: the tunnel port, the host, the domain — each tree has its
10
+ # own.
10
11
  #
11
- # Ищем его в АДРЕСЕ, а не в данных: домен приложения живёт и в самих строках — в почте
12
- # владельца, в канонической ссылке объекта. Пока признак брался по всей команде, вставка
13
- # строки с таким адресом в локальную базу отклонялась как запись в бой, а опт-аута у этой
14
- # ветки нет по замыслу — команда становилась неисполнимой.
15
- # Поэтому текст запроса (то, что стоит после `-c`/`--command`) из проверки вырезается.
12
+ # We look for it in the ADDRESS, not in the data: the application's domain also lives in the rows
13
+ # themselves — in the owner's email, in the canonical link of an object. While the sign was taken
14
+ # over the whole command, inserting a row with such an address into the local database was
15
+ # refused as a write to production, and this branch has no opt-out by design — the command became
16
+ # impossible to run.
17
+ # So the request text (what stands after `-c`/`--command`) is cut out of the check.
16
18
  #
17
- # Запрос из редактора адресата в тексте не называет: база выбирается идентификатором
18
- # подключения, и по одному SQL отличить прод от локальной копии невозможно. Поэтому
19
- # подключения опознаются в лицо. Список сверяется вызовом list_database_connections;
20
- # добавили новое — допишите сюда, иначе оно попадёт в «неизвестные» ниже.
19
+ # A request from the IDE does not name the target in its text: the database is chosen by a
20
+ # connection identifier, and by the SQL alone production cannot be told from the local copy. So
21
+ # connections are recognised by sight. The list is checked against list_database_connections;
22
+ # added a new one — add it here, otherwise it lands in the "unknown" below.
21
23
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
22
24
 
23
25
  sql_resolve_target() {
@@ -28,18 +30,18 @@ sql_resolve_target() {
28
30
  conn_known=""
29
31
  if [ -n "$conn" ]; then
30
32
  case " $PROD_CONNECTIONS " in *" $conn "*) is_prod="yes"; conn_known="prod" ;; esac
31
- # Опознанное локальное подключение сильнее текстовой догадки: домен приложения живёт в
32
- # самих данных — в почте владельца, в канонической ссылке объекта. Пока вывод не
33
- # отменялся, обновление такой строки на локальной базе отклонялось как запись в бой, и
34
- # обойти это было нечем.
33
+ # A recognised local connection outweighs a textual guess: the application's domain lives
34
+ # in the data itself — in the owner's email, in the canonical link of an object. While
35
+ # the verdict was not overridden, updating such a row on the local database was refused as
36
+ # a write to production, and there was nothing to bypass it with.
35
37
  case " $LOCAL_CONNECTIONS " in *" $conn "*) conn_known="local"; is_prod="" ;; esac
36
38
  fi
37
39
 
38
- # Для запроса из редактора адрес в тексте не назван вовсе: там решает опознанное
39
- # подключение, а если оно неизвестно — ветка ниже спросит пользователя.
40
+ # For a request from the IDE the address is not named in the text at all: there the
41
+ # recognised connection decides, and if it is unknown, the branch below asks the user.
40
42
  is_scratch=""
41
43
  addr_other=""
42
- if [ -z "$conn" ] && [ "$context" != "запрос через подключение редактора (обёртка исполнителя)" ]; then
44
+ if [ -z "$conn" ] && [ "$context" != "a request through the connection of the editor (the wrapper of the executor)" ]; then
43
45
  while IFS= read -r seg; do
44
46
  [ -z "$seg" ] && continue
45
47
  if [ -n "$PROD_DSN" ] && printf '%s' "$seg" | grep -qE "$PROD_DSN"; then
@@ -47,23 +49,26 @@ sql_resolve_target() {
47
49
  addr_other="yes"
48
50
  continue
49
51
  fi
50
- # Одноразовая база проверки: петлевой адрес и порт из отведённого под них диапазона.
51
- # Диапазон занимают контейнеры, которые поднимают на время одной проверки —
52
- # восстановление копии, репетиция миграции на непустой базе — и сносят следом. Данных,
53
- # которые стоило бы стеречь, там нет по построению, а вопрос на каждую строку такой
54
- # проверки приучает отвечать «да» не читая и обесценивает тот вопрос, который был важен.
52
+ # A throwaway check database: a loopback address and a port from the range set aside
53
+ # for them. The range is taken by containers raised for the time of one check —
54
+ # restoring a copy, rehearsing a migration on a non-empty database — and torn down
55
+ # right after. There is no data worth guarding there by construction, and a question
56
+ # on every line of such a check teaches answering "yes" without reading and devalues
57
+ # the question that mattered.
55
58
  #
56
- # Диапазон узкий и петлевой намеренно: под него не должны попадать ни рабочая база
57
- # дерева, ни туннель к бою, ни базы соседних деревьев на этой машине. Какой он здесь,
58
- # знает профиль; не назван — исключения нет вовсе, и вопрос задаётся всегда.
59
+ # The range is narrow and loopback on purpose: neither the tree's working database,
60
+ # nor the tunnel to production, nor the databases of neighbouring trees on this
61
+ # machine must fall under it. What it is here is known by the profile; not named —
62
+ # there is no exception at all, and the question is always asked.
59
63
  if [ -n "${RT_SCRATCH_PORT_RE:-}" ] \
60
64
  && printf '%s' "$seg" | grep -qE "$RT_SCRATCH_PORT_RE" \
61
65
  && printf '%s' "$seg" | grep -qE '127\.0\.0\.1|localhost|host\.docker\.internal'; then
62
66
  is_scratch="yes"
63
67
  else
64
- # Любой другой адресованный вызов снимает исключение целиком: в цепочке
65
- # `psql -p 19434 -f x.sql && psql -c "delete …"` ранний выход убрал бы проверку
66
- # со второго звена, а это ровно тот обход, ради которого гард и написан.
68
+ # Any other addressed call lifts the exception entirely: in the chain
69
+ # `psql -p 19434 -f x.sql && psql -c "delete …"` an early exit would remove the
70
+ # check from the second link, and that is exactly the bypass the guard is written
71
+ # against.
67
72
  addr_other="yes"
68
73
  fi
69
74
  done <<EOF
@@ -72,28 +77,29 @@ EOF
72
77
  fi
73
78
  }
74
79
 
75
- # Исключение стоит ПОСЛЕ разбора адреса и ПЕРЕД правилами записи, но строго после того, как
76
- # признак боевой базы уже выставлен: прод перекрывает исключение при любом совпадении, а не
77
- # наоборот. Условие тройное — одноразовый адрес найден, боевого нет, и других адресованных
78
- # вызовов в команде нет вовсе.
80
+ # The exception stands AFTER the address parsing and BEFORE the write rules, but strictly after
81
+ # the production sign has already been set: production overrides the exception on any match, not
82
+ # the other way round. The condition is threefold — a throwaway address is found, there is no
83
+ # production one, and there are no other addressed calls in the command at all.
79
84
  sql_pass_scratch() {
80
85
  if [ -n "$is_scratch" ] && [ -z "$is_prod" ] && [ -z "$addr_other" ]; then
81
86
  exit 0
82
87
  fi
83
88
  }
84
89
 
85
- # На боевой базе разрешено только то, что гард опознал как чтение — БЕЛЫМ списком, а не
86
- # перечислением запретов. Чёрный список здесь принципиально не работает: SQL доезжает до
87
- # сервера файлом, редиректом, `\copy`, `SELECT … INTO`, и каждая заделанная форма оставляет
88
- # соседнюю. Поэтому вопрос перевёрнут: не «есть ли здесь запись», а «доказано ли чтение».
90
+ # On the production database only what the guard recognised as a read is allowed — by an ALLOW
91
+ # list, not by enumerating prohibitions. A deny list fundamentally does not work here: SQL reaches
92
+ # the server as a file, a redirect, `\copy`, `SELECT … INTO`, and every form sealed leaves the
93
+ # neighbouring one open. So the question is turned around: not "is there a write here" but "is a
94
+ # read proven".
89
95
  #
90
- # Чтением считаются три формы, и каждая проверяется в СЕГМЕНТЕ своего вызова:
91
- # pg_dump без --clean/--create — снятие дампа
92
- # psql -c "<один SELECT>" — запрос без второго стейтмента
93
- # psql -l / --version / --help — проверка соединения без запроса
96
+ # Three forms count as a read, and each is checked in the SEGMENT of its own call:
97
+ # pg_dump without --clean/--create — taking a dump
98
+ # psql -c "<one SELECT>" — a query without a second statement
99
+ # psql -l / --version / --help — a connection check without a query
94
100
  sql_check_prod() {
95
101
  if [ -n "$is_prod" ] && [ -n "$is_write" ]; then
96
- deny "BLOCKED: запись в БОЕВОЕ хранилище (${context}). Адрес ведёт на бой — оттуда данные не восстанавливаются ничем, кроме копии. Схема на бою меняется миграцией через выкатку, данные — через панель владельца. Если правка данных на бою действительно нужна, её делает владелец руками, предварительно сняв копию; гард обойти нельзя."
102
+ 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
103
  fi
98
104
 
99
105
  if [ -n "$is_prod" ]; then
@@ -101,9 +107,9 @@ sql_check_prod() {
101
107
  while IFS= read -r seg; do
102
108
  [ -z "$seg" ] && continue
103
109
  seg_read=""
104
- # Аргументы клиента — всё, что стоит ПОСЛЕ его имени. До имени в том же сегменте
105
- # свободно живут чужие флаги: `docker compose -f docker-compose.prod.yml … psql`,
106
- # и `-f` от compose однажды отменял доказательство чтения.
110
+ # The client's arguments are everything AFTER its name. Before the name in the same
111
+ # segment other flags live freely: `docker compose -f docker-compose.prod.yml … psql`,
112
+ # and compose's `-f` once cancelled the proof of a read.
107
113
  seg_tail="$(printf '%s' "$seg" | perl -0pe 's{^.*?(?<![[:alnum:]_./-])(psql|pg_restore|prisma)(?=\s|$)}{$1}s' 2>/dev/null)"
108
114
  [ -z "$seg_tail" ] && seg_tail="$seg"
109
115
 
@@ -114,7 +120,7 @@ sql_check_prod() {
114
120
  esac
115
121
  fi
116
122
 
117
- # Один SELECT и ничего кроме: второй стейтмент через `;` уже не чтение.
123
+ # One SELECT and nothing else: a second statement after `;` is no longer a read.
118
124
  if printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_])select([^[:alnum:]_]|$)' \
119
125
  && ! printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
120
126
  && ! printf '%s' "$seg_tail" | grep -qE '(^|[[:space:]])(-f|--file)([[:space:]]|=)'; then
@@ -130,7 +136,7 @@ $segments
130
136
  EOF
131
137
 
132
138
  if [ -n "$unproven" ]; then
133
- deny "BLOCKED: вызов клиента БД против БОЕВОЙ базы (${context}). На проде разрешено только доказанное чтение — \`pg_dump\` без \`--clean\`, одиночный SELECT через \`-c\`, либо \`-l\`/\`--version\`. Всё остальное отклоняется, даже если гард просто не разобрал команду: содержимое файлов (\`-f\`, \`< dump.sql\`), \`\\copy\` и восстановление дампа ему не видны. Если нужен разбор данных боевой базы — снимай дамп и работай с локальной копией."
139
+ 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
140
  fi
135
141
  fi
136
142
  }
@@ -1,22 +1,23 @@
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
+ # 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 no hook and decides nothing on its own.
7
7
 
8
- # Глаголы ищутся в сегментах ВЫЗОВА, а не по всей строке: иначе слово из шаблона поиска в
9
- # соседнем звене цепочки объявляло записью читающую команду.
8
+ # The verbs are looked for in the segments of the CALL, not over the whole line: otherwise a word
9
+ # from a search pattern in a neighbouring link of the chain declared a reading command a write.
10
10
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
11
11
 
12
12
  sql_detect_write() {
13
13
  is_write=""
14
14
  write_scope="$segments"
15
- # `copy … from` и `select … into` — запись, не называющая ни одного привычного глагола.
15
+ # `copy … from` and `select … into` are a write that names not one of the usual verbs.
16
16
  printf '%s' "$write_scope" | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|create|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
17
17
  && is_write="yes"
18
- # Конвейер из источника в клиент — та же доставка файла, только без флага: содержимое
19
- # `cat fix.sql | psql …` гарду не видно, значит это запись по определению.
18
+ # A pipeline from a source into the client is the same file delivery, only without a flag: the
19
+ # content of `cat fix.sql | psql …` is not visible to the guard, so this is a write by
20
+ # definition.
20
21
  while IFS= read -r seg; do
21
22
  [ -z "$seg" ] && continue
22
23
  printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_.-])(cat|head|tail|gzcat|zcat|gunzip|echo|printf|curl|wget)([[:space:]]|$)' \
@@ -25,34 +26,36 @@ sql_detect_write() {
25
26
  $(client_segments)
26
27
  PIPE_EOF
27
28
 
28
- # Команды prisma меняют базу, не называя ни одного SQL-глагола: `migrate reset` пересоздаёт
29
- # её целиком, `db push` подгоняет схему под модель, `db execute` льёт произвольный файл.
29
+ # prisma commands change the database without naming a single SQL verb: `migrate reset`
30
+ # recreates it whole, `db push` fits the schema to the model, `db execute` pours in an
31
+ # arbitrary file.
30
32
  printf '%s' "$write_scope" | grep -qE 'prisma[[:space:]]+(migrate[[:space:]]+(reset|deploy|dev)|db[[:space:]]+(push|execute))' \
31
33
  && is_write="yes"
32
34
 
33
- # Глагол в командной строке — не единственный способ довезти SQL до сервера. Файл (`-f`,
34
- # `--file`, `< dump.sql`) и `pg_restore` не называют ни одного, поэтому раньше проходили
35
- # мимо всех трёх уровней: доставка файла в клиент на боевой базе завершалась нулём
36
- # без единого вопроса, а `pg_restore` не мог сработать в принципе, хотя `--clean` сносит
37
- # содержимое. Содержимое файла гарду недоступно — значит это запись по определению.
35
+ # A verb on the command line is not the only way to get SQL to the server. A file (`-f`,
36
+ # `--file`, `< dump.sql`) and `pg_restore` name none, so they used to pass by all three levels:
37
+ # delivering a file into the client on the production database ended with zero without a single
38
+ # question, and `pg_restore` could not fire in principle, although `--clean` wipes the content.
39
+ # The content of the file is unavailable to the guard — so this is a write by definition.
38
40
  printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_.-])pg_restore([^[:alnum:]_.-]|$)' \
39
41
  && is_write="yes"
40
- # У `pg_dump` тот же `-f` означает файл ВЫВОДА: это чтение, и записью его считать нельзя —
41
- # иначе штатное снятие дампа с боевой базы отклонялось, хотя текст отказа сам его советует.
42
+ # For `pg_dump` the same `-f` means the OUTPUT file: this is a read, and it must not be counted
43
+ # as a write — otherwise a routine dump of the production database was rejected, although the
44
+ # text of the refusal advises it itself.
42
45
  #
43
- # Исключение действует ПОСЕГМЕНТНО. Пока оно проверялось по всей команде, одного упоминания
44
- # `pg_dump` где угодно в цепочке хватало, чтобы `-f` перестал считаться записью во всех
45
- # остальных вызовах: `pg_dump … > /dev/null && psql -d app -f /tmp/x.sql` проходил молча.
46
+ # The exception acts PER SEGMENT. While it was checked over the whole command, one mention of
47
+ # `pg_dump` anywhere in the chain was enough for `-f` to stop counting as a write in all the
48
+ # other calls: `pg_dump … > /dev/null && psql -d app -f /tmp/x.sql` passed silently.
46
49
  while IFS= read -r seg; do
47
50
  [ -z "$seg" ] && continue
48
- # Граница слова обязательна: `-f /tmp/pg_dump-restore.sql` — это заливка дампа, а не
49
- # его снятие, и подстрочное совпадение снимало с неё обе защиты разом.
51
+ # The word boundary is mandatory: `-f /tmp/pg_dump-restore.sql` is loading a dump, not
52
+ # taking one, and a substring match removed both protections from it at once.
50
53
  if printf '%s' "$seg" | grep -qE '(^|[^[:alnum:]_.-])pg_dump(all)?([^[:alnum:]_.-]|$)'; then
51
54
  continue
52
55
  fi
53
- # Хвост сегмента после имени клиента: `-f` у `docker compose` (боевой compose-файл
54
- # называется нестандартно, без флага не поднимается) стоит ДО `psql` и к запросу
55
- # отношения не имеет.
56
+ # The tail of the segment after the client name: the `-f` of `docker compose` (the
57
+ # production compose file is named non-standardly and does not come up without the flag)
58
+ # stands BEFORE `psql` and has nothing to do with the query.
56
59
  seg_tail="$(printf '%s' "$seg" | perl -0pe 's{^.*?(?<![[:alnum:]_./-])(psql|pg_restore|prisma)(?=\s|$)}{$1}s' 2>/dev/null)"
57
60
  [ -z "$seg_tail" ] && seg_tail="$seg"
58
61
  if printf '%s' "$seg_tail" | grep -qE '(^|[[:space:]])(-f|--file)([[:space:]]|=)|<[[:space:]]*[^[:space:]|<]+\.(sql|dump)'; then
@@ -64,13 +67,13 @@ $segments
64
67
  EOF
65
68
  }
66
69
 
67
- # --- заведомо разрушительное ------------------------------------------------------------
70
+ # --- destructive for certain ------------------------------------------------------------
68
71
  verdict() {
69
72
  if [ -n "$soft" ]; then
70
- ask "Запрос помечен маркером destructive-ok, но остаётся разрушительным: $1 Подтверди выполнение, если это осознанно."
73
+ ask "The request is marked by the destructive-ok marker but stays destructive: $1 Confirm the execution if this is deliberate."
71
74
  fi
72
- deny "BLOCKED: $1 Адресуй строки по первичному ключу — \`WHERE id IN ('…','…')\`: так затрагивается ровно столько строк, сколько перечислено, и промах виден до выполнения. Удаление по маске (email LIKE '%test%') однажды унесло вместе с тестовыми записями демонстрационные брони владельца. Если адресация по id действительно не подходит — сначала выполни SELECT с тем же условием и покажи пользователю, что попадает под удаление." \
73
- "маркер destructive-ok при запросе, с объяснением"
75
+ 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." \
76
+ "the destructive-ok marker at the request, with an explanation"
74
77
  }
75
78
 
76
79
  sql_check_destructive() {
@@ -80,38 +83,38 @@ sql_check_destructive() {
80
83
  esac
81
84
 
82
85
  if printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_])(truncate|drop[[:space:]]+(table|database|schema|column|index)|alter[[:space:]]+table)([^[:alnum:]_]|$)'; then
83
- verdict "запрос меняет саму схему или очищает таблицу целиком (${context})."
86
+ verdict "the request changes the schema itself or empties a table whole (${context})."
84
87
  fi
85
88
 
86
89
  if printf '%s' "$flat" | grep -qE 'prisma[[:space:]]+(migrate[[:space:]]+reset|db[[:space:]]+push)'; then
87
- verdict "\`prisma migrate reset\` / \`db push\` пересоздаёт базу и теряет её содержимое (${context})."
90
+ verdict "\`prisma migrate reset\` / \`db push\` recreates the database and loses its content (${context})."
88
91
  fi
89
92
 
90
- # `pg_restore --clean` перед загрузкой удаляет существующие объекты — то же очищение
91
- # таблиц, только чужими руками. Без `--clean` это обычная догрузка, она идёт общим путём.
93
+ # `pg_restore --clean` deletes the existing objects before loading — the same emptying of
94
+ # tables, only by someone else's hands. Without `--clean` it is an ordinary top-up, and it goes
95
+ # the common path.
92
96
  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})."
97
+ verdict "\`pg_restore --clean\` deletes the objects of the database before loading the dump (${context})."
94
98
  fi
95
99
  }
96
100
 
97
- # Штатное применение миграций разрушительным не считается. Раньше здесь стоял безусловный
98
- # `ask` со словами «убедись, что DATABASE_URL указывает на локальную базу» — гард
99
- # перекладывал на человека ровно ту работу, которую умеет сделать сам. На локальной базе
100
- # миграции гоняются постоянно, и вопрос на каждую не добавляет безопасности: гард, который
101
- # спрашивает по десятому разу, перестают читать вместе с тем единственным вопросом, который
102
- # был важен.
101
+ # A routine application of migrations does not count as destructive. There used to stand an
102
+ # unconditional `ask` here with the words "make sure DATABASE_URL points at the local database" —
103
+ # the guard shifted onto a person exactly the work it can do itself. On a local database migrations
104
+ # are run all the time, and a question on each adds no safety: a guard that asks for the tenth time
105
+ # stops being read together with that one question that mattered.
103
106
  #
104
- # Поэтому адрес РАЗРЕШАЕТСЯ, а не угадывается: сначала inline-префикс самой команды, затем
105
- # переменная окружения, затем `.env` рабочего каталога.
107
+ # So the address is RESOLVED, not guessed: first the inline prefix of the command itself, then the
108
+ # environment variable, then the `.env` of the working directory.
106
109
  unquote() {
107
110
  sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//"
108
111
  }
109
112
 
110
113
  resolve_database_url() {
111
- # Искать по `$flat` нельзя: он приведён к нижнему регистру, и `DATABASE_URL=` в нём
112
- # не встречается никогда — правило молча брало бы адрес из `.env`, игнорируя явно
113
- # указанный в команде. Разбирается исходная строка, а `$flat` остаётся запасным
114
- # вариантом с регистронезависимым поиском.
114
+ # Searching by `$flat` is not allowed: it is brought to lower case, and `DATABASE_URL=` never
115
+ # occurs in it — the rule would silently take the address from `.env`, ignoring the one named
116
+ # explicitly in the command. The original line is parsed, and `$flat` stays the fallback with a
117
+ # case-insensitive search.
115
118
  inline="$(printf '%s' "${cmd:-}" | grep -oE '[Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee]_[Uu][Rr][Ll]=[^[:space:]]+' | tail -n1)"
116
119
  [ -z "$inline" ] && inline="$(printf '%s' "$flat" | grep -oiE 'database_url=[^[:space:]]+' | tail -n1)"
117
120
  if [ -n "$inline" ]; then
@@ -122,10 +125,10 @@ resolve_database_url() {
122
125
  printf '%s' "$DATABASE_URL" | unquote
123
126
  return
124
127
  fi
125
- # Подъём по дереву, а не только рабочий каталог: агент работает в git worktree под
126
- # `.claude/worktrees/<ветка>/`, где своего `.env` нет, а у основного чекаута — есть,
127
- # и он лежит ровно выше по пути. Без подъёма гард не разрешил бы адрес ни разу
128
- # именно там, где миграции и гоняются.
128
+ # Climbing up the tree, not only the working directory: the agent works in a git worktree under
129
+ # `.claude/worktrees/<branch>/`, where there is no `.env` of its own, while the main checkout
130
+ # has one, and it lies exactly higher up the path. Without the climb the guard would not have
131
+ # resolved the address once, exactly where the migrations are run.
129
132
  dir="$hook_cwd"
130
133
  depth=0
131
134
  while [ -n "$dir" ] && [ "$dir" != '/' ] && [ "$depth" -lt 8 ]; do
@@ -145,21 +148,22 @@ resolve_database_url() {
145
148
  sql_check_migrations() {
146
149
  if printf '%s' "$flat" | grep -qE 'prisma[[:space:]]+migrate[[:space:]]+(deploy|dev)'; then
147
150
  migrate_target="$(resolve_database_url)"
148
- # Боевой адрес проверяется ДО разбора по видам: туннель к бою тоже висит на петлевом
149
- # адресе, только на своём порту, и общее правило «петлевой значит локальный» пропустило бы
150
- # миграцию на бой.
151
+ # The production address is checked BEFORE the parse by kinds: a tunnel to production also
152
+ # hangs on a loopback address, only on a port of its own, and the common rule "loopback
153
+ # means local" would have let a migration through to production.
151
154
  if [ -n "$PROD_DSN" ] && printf '%s' "$migrate_target" | grep -qE "$PROD_DSN"; then
152
- deny "BLOCKED: применение миграций к БОЕВОЙ базе (${context}). Адрес базы ведёт на бой. Схема на бою меняется выкаткой: она сама зовёт применение миграций одноразовым контейнером до старта приложения. Руками этого делать нельзя — гард обойти нельзя."
155
+ 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
156
  fi
154
157
  case "$migrate_target" in
155
158
  *@localhost:*|*@127.0.0.1:*|*@postgres:*|*@host.docker.internal:*)
156
- # Локальная база — штатная работа. Разбор завершается здесь, иначе ниже
157
- # сработает общее правило про запись в базу и вопрос всё равно будет задан:
158
- # `migrate deploy` помечен записью выше по тексту.
159
+ # A local database is routine work. The parse ends here, otherwise the common rule
160
+ # about writing to the database fires below and the question is asked anyway:
161
+ # `migrate deploy` is marked a write higher up the text.
159
162
  #
160
- # Но выйти можно, только если запись в команде ОДНА — сама миграция. В цепочке
161
- # `prisma migrate deploy && psql -c "delete …"` ранний выход снял бы проверку со
162
- # второго звена, а это ровно тот обход, ради которого гард и написан.
163
+ # But it can be exited only if there is ONE write in the command — the migration
164
+ # itself. In the chain `prisma migrate deploy && psql -c "delete …"` an early exit
165
+ # would remove the check from the second link, and that is exactly the bypass the
166
+ # guard is written for.
163
167
  other_write=""
164
168
  printf '%s' "$write_scope" \
165
169
  | grep -qE '(^|[^[:alnum:]_])(delete|update|insert|truncate|drop|alter|create|grant|revoke|copy)([^[:alnum:]_]|$)|\\copy|into[[:space:]]+[a-z_"]' \
@@ -174,42 +178,43 @@ MIGRATE_PIPE_EOF
174
178
  [ -z "$other_write" ] && exit 0
175
179
  ;;
176
180
  '')
177
- ask "Применение миграций к базе (${context}), но адрес разрешить не удалось: DATABASE_URL нет ни в команде, ни в окружении, ни в \`.env\` рабочего каталога. Проверь, куда пойдёт миграция, и подтверди."
181
+ 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
182
  ;;
179
183
  *)
180
- ask "Применение миграций по адресу, НЕИЗВЕСТНОМУ ГАРДУ (${context}). Гард знает локальные адреса и боевые; этот — ни то, ни другое. Убедись, что это не прод, и подтверди."
184
+ 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
185
  ;;
182
186
  esac
183
187
  fi
184
188
  }
185
189
 
186
- # --- delete/update: смотрим на адресацию ------------------------------------------------
190
+ # --- delete/update: looking at the addressing -------------------------------------------
187
191
  sql_check_addressing() {
188
192
  if printf '%s' "$flat" | grep -qE '(^|[^[:alnum:]_])(delete[[:space:]]+from|update)([^[:alnum:]_]|$)'; then
189
193
  if ! printf '%s' "$flat" | grep -q 'where'; then
190
- verdict "DELETE/UPDATE без WHERE затрагивает всю таблицу (${context})."
194
+ verdict "DELETE/UPDATE without WHERE touches the whole table (${context})."
191
195
  fi
192
196
 
193
- # Адресация ищется ТОЛЬКО в хвосте после последнего `where`. Пока смотрели на весь
194
- # запрос, присваивание в SET засчитывалось за адресацию: `UPDATE bookings SET
195
- # "propertyId" = 'p1' WHERE source = 'site'` выглядел адресным, хотя задевал все прямые
196
- # заявки объекта — ровно то, от чего гард и защищает.
197
- # Регистр здесь сохраняется, в отличие от `flat`: колонки Prisma пишутся в camelCase, и
198
- # приведённый к нижнему регистру `bookingid` уже не отличить от слова `paid`.
197
+ # The addressing is looked for ONLY in the tail after the last `where`. While the whole
198
+ # query was looked at, an assignment in SET counted as addressing: `UPDATE bookings SET
199
+ # "propertyId" = 'p1' WHERE source = 'site'` looked addressed, although it touched every
200
+ # direct request for the property — exactly what the guard protects from.
201
+ # The case is kept here, unlike in `flat`: Prisma columns are written in camelCase, and
202
+ # `bookingid` brought to lower case is no longer distinguishable from the word `paid`.
199
203
  where_tail="$(printf '%s' "$sql" | tr '\n\t' ' ' | sed -E 's/.*[Ww][Hh][Ee][Rr][Ee]/where/')"
200
204
 
201
- # Имя колонки требуется целиком: `id`, `booking_id`, `"bookingId"`. Прежний шаблон
202
- # `[a-z_]*id` принимал за идентификатор `paid` и `valid`.
205
+ # The column name is required whole: `id`, `booking_id`, `"bookingId"`. The former pattern
206
+ # `[a-z_]*id` took `paid` and `valid` for an identifier.
203
207
  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}) — условие может совпасть шире, чем задумано."
208
+ verdict "DELETE/UPDATE addresses the rows not by an identifier (${context}) — the condition may match wider than intended."
205
209
  fi
206
210
 
207
- # Гард видит имя колонки, но не схему: `propertyId` и `session_id` — внешние ключи, и
208
- # запрос по ним адресный только на вид. `DELETE … WHERE "propertyId" = 'p1'` сносит все
209
- # брони объекта. Отличить это от первичного ключа без схемы нельзя, поэтому решение
210
- # остаётся за пользователем — но предупреждение должно быть прямым, а не общим.
211
+ # The guard sees the column name but not the schema: `propertyId` and `session_id` are
212
+ # foreign keys, and a query by them is addressed only in appearance. `DELETE … WHERE
213
+ # "propertyId" = 'p1'` wipes every booking of the property. Telling this from a primary key
214
+ # without the schema is impossible, so the decision stays with the user — but the warning
215
+ # must be direct, not general.
211
216
  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 (…)\`."
217
+ 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
218
  fi
214
219
  fi
215
220
  }