@rt-tools/agent-kit 0.24.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 (279) hide show
  1. package/assets/agents/business-analyst.md +51 -50
  2. package/assets/agents/conscience.md +37 -35
  3. package/assets/agents/project-manager.md +49 -48
  4. package/assets/agents/prose-editor.md +31 -29
  5. package/assets/agents/qa-engineer.md +50 -48
  6. package/assets/agents/rules-reviewer.md +63 -58
  7. package/assets/agents/skill-curator.md +83 -78
  8. package/assets/agents/spec-critic.md +34 -29
  9. package/assets/agents/spec-writer.md +35 -32
  10. package/assets/agents/strict-teacher.md +39 -37
  11. package/assets/checks/archive-age.mjs +48 -28
  12. package/assets/checks/archive-prune.mjs +16 -14
  13. package/assets/checks/board-epics.github.mjs +75 -41
  14. package/assets/checks/board-folders.mjs +61 -0
  15. package/assets/checks/board-gh.github.mjs +35 -26
  16. package/assets/checks/board-long-work.github.mjs +24 -24
  17. package/assets/checks/board-paths.github.mjs +21 -16
  18. package/assets/checks/board-runs.github.mjs +45 -43
  19. package/assets/checks/board-titles.github.mjs +19 -17
  20. package/assets/checks/board.github.mjs +149 -127
  21. package/assets/checks/check-archive-age.mjs +23 -19
  22. package/assets/checks/check-board.github.mjs +172 -164
  23. package/assets/checks/check-descriptions.mjs +30 -29
  24. package/assets/checks/check-doc-paths.mjs +91 -88
  25. package/assets/checks/check-dupes.mjs +84 -80
  26. package/assets/checks/check-file-size.mjs +74 -71
  27. package/assets/checks/check-glossary.mjs +47 -37
  28. package/assets/checks/check-hook-scope.mjs +30 -27
  29. package/assets/checks/check-lib-layers.mjs +22 -21
  30. package/assets/checks/check-profile-drift.mjs +48 -43
  31. package/assets/checks/check-prose-style.mjs +120 -37
  32. package/assets/checks/check-push-gate.mjs +53 -50
  33. package/assets/checks/check-reuse.mjs +50 -40
  34. package/assets/checks/check-schema-drift.mjs +87 -83
  35. package/assets/checks/check-specs.mjs +155 -134
  36. package/assets/checks/check-state-next.mjs +66 -52
  37. package/assets/checks/check-states.mjs +32 -30
  38. package/assets/checks/check-styles.mjs +52 -51
  39. package/assets/checks/check-turn-map.mjs +54 -46
  40. package/assets/checks/lib-boundaries.mjs +32 -30
  41. package/assets/checks/lib-common.mjs +30 -29
  42. package/assets/checks/lib-domains.mjs +34 -34
  43. package/assets/checks/lib-manifests.mjs +17 -15
  44. package/assets/checks/lib-reexports.mjs +18 -18
  45. package/assets/checks/rt-kit-checks.config.mjs +174 -142
  46. package/assets/checks/signals.mjs +43 -39
  47. package/assets/checks/spec-anchors.mjs +114 -87
  48. package/assets/checks/spec-common.mjs +128 -84
  49. package/assets/checks/spec-contract.mjs +30 -30
  50. package/assets/checks/spec-proposed.mjs +27 -24
  51. package/assets/checks/spec-scenarios.mjs +51 -28
  52. package/assets/checks/task-new.github.mjs +85 -56
  53. package/assets/commands/feedback.md +65 -59
  54. package/assets/commands/next-session.md +64 -57
  55. package/assets/commands/skill-curator.md +83 -79
  56. package/assets/defaults/gate-map.sh +108 -97
  57. package/assets/defaults/project.sh +225 -185
  58. package/assets/defaults/shell.sh +73 -68
  59. package/assets/defaults/turn-map.md +45 -44
  60. package/assets/docs/GLOSSARY.md +142 -65
  61. package/assets/hooks/browser-device-id.sh +12 -12
  62. package/assets/hooks/browser-guard-device-id.sh +30 -28
  63. package/assets/hooks/browser-guard-no-asking.sh +5 -4
  64. package/assets/hooks/browser-guard-no-listing.sh +12 -11
  65. package/assets/hooks/browser-guard-no-other-drivers.sh +48 -42
  66. package/assets/hooks/browser-guard-require-select.sh +34 -23
  67. package/assets/hooks/claim-guard.sh +62 -56
  68. package/assets/hooks/commit-msg.sh +11 -10
  69. package/assets/hooks/conscience-guard.sh +91 -45
  70. package/assets/hooks/constitution-index.sh +16 -16
  71. package/assets/hooks/deny-tail.sh +28 -26
  72. package/assets/hooks/dev-server-guard.sh +46 -43
  73. package/assets/hooks/dispatch.sh +60 -46
  74. package/assets/hooks/docs-guard.sh +100 -91
  75. package/assets/hooks/exam-guard.sh +105 -93
  76. package/assets/hooks/git-guard-delivery-conflict.sh +38 -36
  77. package/assets/hooks/git-guard-delivery-draft.sh +45 -38
  78. package/assets/hooks/git-guard-delivery-folder.sh +50 -43
  79. package/assets/hooks/git-guard-delivery-signature.sh +88 -52
  80. package/assets/hooks/git-guard-delivery.sh +196 -180
  81. package/assets/hooks/git-guard-main.sh +38 -34
  82. package/assets/hooks/git-guard-push-tests.sh +99 -87
  83. package/assets/hooks/glossary-load.sh +23 -22
  84. package/assets/hooks/grill-gate-ask.sh +12 -11
  85. package/assets/hooks/grill-gate.sh +94 -87
  86. package/assets/hooks/guard-note.sh +20 -19
  87. package/assets/hooks/handoff-entry-guard.sh +26 -24
  88. package/assets/hooks/handoff-write.sh +74 -67
  89. package/assets/hooks/hook-input.sh +67 -58
  90. package/assets/hooks/lint-after-edit.sh +95 -61
  91. package/assets/hooks/observe.sh +28 -26
  92. package/assets/hooks/override-write-guard.sh +23 -21
  93. package/assets/hooks/postmortem-guard.sh +42 -39
  94. package/assets/hooks/profile-check.sh +22 -20
  95. package/assets/hooks/proposal-guard.sh +57 -49
  96. package/assets/hooks/prose-style-guard.sh +19 -17
  97. package/assets/hooks/qa-dataid-guard.sh +52 -49
  98. package/assets/hooks/rerun-guard.sh +31 -30
  99. package/assets/hooks/reuse-first-guard.sh +108 -87
  100. package/assets/hooks/roles.sh +14 -14
  101. package/assets/hooks/rule-article.sh +36 -34
  102. package/assets/hooks/rule-source-guard.sh +47 -42
  103. package/assets/hooks/skill-gate-layers.sh +59 -57
  104. package/assets/hooks/skill-gate-rearm.sh +15 -8
  105. package/assets/hooks/skill-gate.sh +89 -81
  106. package/assets/hooks/skill-loaded.sh +6 -6
  107. package/assets/hooks/sql-guard-parse.sh +68 -66
  108. package/assets/hooks/sql-guard-request.sh +48 -46
  109. package/assets/hooks/sql-guard-target.sh +57 -51
  110. package/assets/hooks/sql-guard-write.sh +84 -79
  111. package/assets/hooks/sql-guard.sh +52 -47
  112. package/assets/hooks/stand-login-guard.sh +40 -37
  113. package/assets/hooks/task-context-load.sh +60 -55
  114. package/assets/hooks/task-flow-context.sh +87 -69
  115. package/assets/hooks/task-flow-draft-guard.sh +55 -48
  116. package/assets/hooks/task-flow-guard.sh +67 -64
  117. package/assets/hooks/turn-entry-load.sh +39 -32
  118. package/assets/hooks/turn-exit-guard.sh +256 -204
  119. package/assets/hooks/turn-exit-patterns.sh +53 -0
  120. package/assets/hooks/utf8.sh +11 -11
  121. package/assets/hooks/waiting-turn-guard.sh +94 -94
  122. package/assets/hooks/window-fill-guard.sh +70 -62
  123. package/assets/hooks/work-start-guard.sh +52 -49
  124. package/assets/hooks/write-targets.sh +96 -44
  125. package/assets/laws/autonomous-work.md +29 -27
  126. package/assets/laws/code-structure.md +31 -30
  127. package/assets/laws/delivery.md +148 -137
  128. package/assets/laws/entity-editing.md +52 -50
  129. package/assets/laws/entity-models.md +14 -13
  130. package/assets/laws/frontend-application.md +39 -38
  131. package/assets/laws/lib-imports.md +27 -27
  132. package/assets/laws/lists.md +31 -29
  133. package/assets/laws/navigation.md +37 -37
  134. package/assets/laws/observability.md +41 -40
  135. package/assets/laws/project-documentation.md +106 -99
  136. package/assets/laws/reuse-first.md +31 -29
  137. package/assets/laws/shared-code.md +27 -27
  138. package/assets/laws/verifiability.md +131 -124
  139. package/assets/laws/work-conduct.md +250 -244
  140. package/assets/patterns/admin-lists-screen.md +72 -69
  141. package/assets/patterns/admin-nav-item.md +51 -46
  142. package/assets/patterns/angular-patterns-state.md +32 -31
  143. package/assets/patterns/api-layer-pair.md +33 -31
  144. package/assets/patterns/autonomous-work-run.md +50 -49
  145. package/assets/patterns/browser-verification-measure.md +124 -88
  146. package/assets/patterns/browser-verification-stand.md +169 -157
  147. package/assets/patterns/component-structure-new.md +51 -42
  148. package/assets/patterns/dependencies-upgrade.md +55 -39
  149. package/assets/patterns/doc-style-human.md +55 -37
  150. package/assets/patterns/doc-style-sweep.md +82 -79
  151. package/assets/patterns/doc-style-trace.md +87 -81
  152. package/assets/patterns/doc-style-write.md +130 -122
  153. package/assets/patterns/entity-aside.md +77 -63
  154. package/assets/patterns/entity-models-new.md +37 -37
  155. package/assets/patterns/entity-store.md +33 -33
  156. package/assets/patterns/git-workflow-commit.azure.md +93 -86
  157. package/assets/patterns/git-workflow-commit.github.md +152 -141
  158. package/assets/patterns/git-workflow-commit.gitlab.md +95 -89
  159. package/assets/patterns/git-workflow-docker.md +165 -147
  160. package/assets/patterns/git-workflow-freshness.md +45 -45
  161. package/assets/patterns/git-workflow-merge.md +98 -93
  162. package/assets/patterns/git-workflow-migration.md +54 -52
  163. package/assets/patterns/git-workflow-pr-ready.md +57 -56
  164. package/assets/patterns/git-workflow-pr.azure.md +126 -121
  165. package/assets/patterns/git-workflow-pr.github.md +179 -175
  166. package/assets/patterns/git-workflow-pr.gitlab.md +138 -131
  167. package/assets/patterns/git-workflow-restart.md +35 -31
  168. package/assets/patterns/git-workflow-secrets.md +80 -73
  169. package/assets/patterns/git-workflow-stack.md +131 -106
  170. package/assets/patterns/lib-layers-move.md +62 -53
  171. package/assets/patterns/lib-layers-new.md +59 -45
  172. package/assets/patterns/observability-record.md +72 -67
  173. package/assets/patterns/platform-access-di.md +31 -29
  174. package/assets/patterns/reuse-first-extend.md +66 -61
  175. package/assets/patterns/shared-code-new.md +39 -38
  176. package/assets/patterns/spec-driven-domain.md +161 -151
  177. package/assets/patterns/spec-driven-rule.md +179 -168
  178. package/assets/patterns/spec-driven-sweep.md +41 -39
  179. package/assets/patterns/status-report-table.github.md +37 -36
  180. package/assets/patterns/styling-bem-component.md +42 -42
  181. package/assets/patterns/styling-bem-layout.md +39 -34
  182. package/assets/patterns/styling-bem-sheet.md +59 -58
  183. package/assets/patterns/task-flow-archive.md +222 -215
  184. package/assets/patterns/task-flow-close.md +215 -203
  185. package/assets/patterns/task-flow-handoff.md +154 -145
  186. package/assets/patterns/task-flow-resume.md +138 -133
  187. package/assets/patterns/task-flow-start.md +204 -192
  188. package/assets/patterns/testing-e2e.md +102 -101
  189. package/assets/patterns/testing-unit.md +77 -70
  190. package/assets/patterns/ts-procedure.md +32 -29
  191. package/assets/patterns/turn-entry-map.md +50 -48
  192. package/assets/pitfalls/agent-kit.md +152 -141
  193. package/assets/pitfalls/doc-style.md +96 -91
  194. package/assets/pitfalls/git-workflow.azure.md +49 -46
  195. package/assets/pitfalls/git-workflow.github.md +264 -234
  196. package/assets/pitfalls/git-workflow.gitlab.md +49 -45
  197. package/assets/pitfalls/spec-driven.md +73 -71
  198. package/assets/pitfalls/styling-bem.md +46 -40
  199. package/assets/pitfalls/task-flow.md +262 -246
  200. package/assets/pitfalls/testing.md +99 -92
  201. package/assets/pitfalls/turn-conduct.md +96 -81
  202. package/assets/rules/angular-patterns.md +81 -80
  203. package/assets/rules/api-layer.md +77 -74
  204. package/assets/rules/autonomous-work.md +75 -74
  205. package/assets/rules/browser-verification.md +223 -214
  206. package/assets/rules/component-structure.md +72 -69
  207. package/assets/rules/dependencies.md +74 -67
  208. package/assets/rules/deploy-flow.azure.md +118 -108
  209. package/assets/rules/deploy-flow.github.md +145 -135
  210. package/assets/rules/deploy-flow.gitlab.md +120 -110
  211. package/assets/rules/doc-style.md +198 -173
  212. package/assets/rules/entity-conventions.needs-admin.md +81 -79
  213. package/assets/rules/entity-models.md +73 -70
  214. package/assets/rules/git-workflow.azure.md +224 -228
  215. package/assets/rules/git-workflow.github.md +250 -239
  216. package/assets/rules/git-workflow.gitlab.md +218 -217
  217. package/assets/rules/lib-layers.md +85 -86
  218. package/assets/rules/lists.md +101 -97
  219. package/assets/rules/navigation.md +78 -78
  220. package/assets/rules/observability.needs-app.md +165 -153
  221. package/assets/rules/platform-access.md +76 -75
  222. package/assets/rules/reuse-first.md +153 -143
  223. package/assets/rules/shared-code.md +82 -79
  224. package/assets/rules/spec-driven.md +272 -260
  225. package/assets/rules/status-report.md +55 -58
  226. package/assets/rules/styling-bem.md +81 -77
  227. package/assets/rules/task-flow.md +282 -270
  228. package/assets/rules/testing.md +224 -209
  229. package/assets/rules/turn-conduct.md +255 -258
  230. package/assets/rules/turn-entry.md +92 -87
  231. package/assets/rules/typescript-conventions.md +94 -88
  232. package/assets/samples/specs/_template/spec.md +47 -47
  233. package/assets/samples/tasks/_template/grill.md +20 -20
  234. package/assets/samples/tasks/_template/plan.md +32 -30
  235. package/assets/samples/tasks/_template/progress.md +16 -16
  236. package/assets/skills/agent-kit-extend.md +129 -113
  237. package/assets/skills/agent-kit.md +235 -211
  238. package/assets/skills/write-a-skill.md +76 -71
  239. package/assets/templates/findings.md +19 -19
  240. package/assets/templates/gate-map.sh +16 -14
  241. package/assets/templates/implementation.md +28 -27
  242. package/assets/templates/pattern.md +17 -17
  243. package/assets/templates/pitfalls.md +6 -6
  244. package/assets/templates/postmortem.md +24 -23
  245. package/assets/templates/project.sh +24 -24
  246. package/assets/templates/proposal.md +62 -60
  247. package/assets/templates/rule.md +38 -38
  248. package/assets/workflows/feature.js +46 -46
  249. package/assets/workflows/plan.js +54 -54
  250. package/lib/catalog.d.ts +2 -0
  251. package/lib/catalog.d.ts.map +1 -1
  252. package/lib/catalog.js +4 -3
  253. package/lib/catalog.js.map +1 -1
  254. package/lib/commands.d.ts.map +1 -1
  255. package/lib/commands.js +5 -2
  256. package/lib/commands.js.map +1 -1
  257. package/lib/companion.js +3 -2
  258. package/lib/companion.js.map +1 -1
  259. package/lib/enroll.d.ts +7 -1
  260. package/lib/enroll.d.ts.map +1 -1
  261. package/lib/enroll.js +12 -3
  262. package/lib/enroll.js.map +1 -1
  263. package/lib/plan.d.ts +11 -0
  264. package/lib/plan.d.ts.map +1 -1
  265. package/lib/plan.js +10 -1
  266. package/lib/plan.js.map +1 -1
  267. package/lib/ship.d.ts +0 -7
  268. package/lib/ship.d.ts.map +1 -1
  269. package/lib/ship.js +10 -2
  270. package/lib/ship.js.map +1 -1
  271. package/lib/shipment.d.ts.map +1 -1
  272. package/lib/shipment.js +6 -2
  273. package/lib/shipment.js.map +1 -1
  274. package/lib/sync.d.ts.map +1 -1
  275. package/lib/sync.js +45 -11
  276. package/lib/sync.js.map +1 -1
  277. package/package.json +1 -1
  278. package/rt-tools-agent-kit-0.26.0.tgz +0 -0
  279. package/rt-tools-agent-kit-0.24.0.tgz +0 -0
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env bash
2
- # Разбор команды для гарда хранилища: приведение к одному виду, нарезка на сегменты и ответ
3
- # на вопрос, доставляет ли сегмент SQL до сервера.
2
+ # Parsing a command for the storage guard: bringing it to one shape, cutting it into segments and
3
+ # answering the question whether the segment delivers SQL to the server.
4
4
  #
5
- # Строки `# rt-hook:` здесь нет намеренно: событие и образец вызова объявляет сам гард, а
6
- # помощник рядом хуком не регистрируется и в одиночку ничего не решает.
5
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by the
6
+ # guard itself, and a helper next to it is not registered as a hook and decides nothing alone.
7
7
 
8
- # Дальше разбираем без учёта регистра и переводов строк: `delete\n from bookings`
9
- # — тот же запрос, что и в одну строку.
8
+ # From here on we parse ignoring case and newlines: `delete\n from bookings` is the same query as
9
+ # the one written on a single line.
10
10
  #
11
- # Перевод строки при этом превращается в `;`, а не в пробел: в командной строке он РАЗДЕЛЯЕТ
12
- # вызовы ровно как `;`, и склейка его в пробел стирала границу между ними. Многострочная
13
- # команда становилась одним сегментом, доказательство чтения из первой строки покрывало
14
- # неразобранный вызов из второй, и запись на боевую базу проходила молча — тот же обход,
15
- # что чинили для `&&`, только набранный с новой строки.
11
+ # A newline turns into `;`, not into a space: on the command line it SEPARATES calls exactly like
12
+ # `;`, and gluing it into a space erased the boundary between them. A multi-line command became one
13
+ # segment, the proof of reading from the first line covered an unparsed call from the second, and a
14
+ # write to the production database went through silently — the same bypass that was fixed for `&&`,
15
+ # only typed from a new line.
16
16
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
17
17
 
18
18
  normalize() {
19
19
  perl -0ne '
20
- # Продолжение длинной команды обратным слешем — это одна строка, а не две: без
21
- # склейки адрес из первой уезжал в соседний сегмент, где клиента уже нет.
20
+ # A long command continued by a backslash is one line, not two: without gluing, the address
21
+ # from the first went into the neighbouring segment, where there is no client any more.
22
22
  s/\\\n/ /g;
23
- # Перевод строки заменяется на `;` ТОЛЬКО вне кавычек. Внутри `-c "…"` он часть
24
- # запроса: многострочный SELECT резался на сегменты, и штатное чтение боевой базы
25
- # переставало быть доказанным.
23
+ # A newline is replaced by `;` ONLY outside quotes. Inside `-c "…"` it is part of the
24
+ # query: a multi-line SELECT was cut into segments, and regular reading of the production
25
+ # database stopped being proven.
26
26
  my ($out, $quote, $esc) = ("", "", 0);
27
27
  for my $ch (split //, $_) {
28
28
  if ($esc) { $out .= $ch; $esc = 0; next; }
@@ -33,31 +33,31 @@ normalize() {
33
33
  } elsif ($ch eq q{"} || $ch eq q{'"'"'}) {
34
34
  $quote = $ch; $out .= $ch;
35
35
  } elsif ($ch eq "\n" || $ch eq ";") {
36
- $out .= "\x01"; # граница независимых команд
36
+ $out .= "\x01"; # the boundary of independent commands
37
37
  } elsif ($ch eq "|") {
38
- $out .= "\x02"; # граница звена конвейера
38
+ $out .= "\x02"; # the boundary of a pipeline link
39
39
  } elsif ($ch eq "&") {
40
40
  $out .= "\x01";
41
41
  } else {
42
42
  $out .= $ch;
43
43
  }
44
44
  }
45
- # Соседние маркеры схлопываются: `&&` и `||` дают по два подряд.
45
+ # Neighbouring markers collapse: `&&` and `||` give two of them in a row each.
46
46
  $out =~ s/\x01+/\x01/g;
47
47
  $out =~ s/\x02\x01/\x01/g;
48
48
  $out =~ s/\x01\x02/\x01/g;
49
- # Незакрытая кавычка означает, что автомат разъехался: апостроф в комментарии
50
- # (`# don'"'"'t forget`) оставлял состояние «внутри строки» до конца ввода, и все
51
- # последующие переводы строк переставали разделять вызовы — сегментация выключалась
52
- # одним символом. В таком случае честнее ничего не печатать: вызывающий разделит
53
- # строки грубым способом, и лишнее дробление сыграет в пользу строгости.
49
+ # An unclosed quote means the automaton has come apart: an apostrophe in a comment
50
+ # (`# don'"'"'t forget`) left the state "inside a string" until the end of the input, and
51
+ # all the newlines after it stopped separating calls — segmentation was switched off by one
52
+ # character. In that case it is more honest to print nothing: the caller will split the
53
+ # lines the rough way, and the extra splitting plays in favour of strictness.
54
54
  print $out if $quote eq "";
55
55
  ' 2>/dev/null
56
56
  }
57
57
 
58
- # Грубое разделение — запасной путь: все переводы строк становятся разделителями. Оно строже
59
- # точного (может разрезать многострочный запрос), поэтому годится и как фолбэк без perl,
60
- # и как ответ на неразобранную команду.
58
+ # Rough splitting is the fallback path: all newlines become separators. It is stricter than the
59
+ # exact one (it may cut a multi-line query in two), so it serves both as a fallback without perl and
60
+ # as the answer to an unparsed command.
61
61
  sql_flatten() {
62
62
  flat_rough="$(printf '%s' "$sql" | perl -0pe 's/\\\n/ /g' 2>/dev/null | tr '\n;&' '\001\001\001' | tr '|' '\002' | tr '\t' ' ' | tr '[:upper:]' '[:lower:]')"
63
63
  [ -z "$flat_rough" ] && flat_rough="$(printf '%s' "$sql" | tr '\n;&' '\001\001\001' | tr '|' '\002' | tr '\t' ' ' | tr '[:upper:]' '[:lower:]')"
@@ -70,47 +70,47 @@ sql_flatten() {
70
70
  fi
71
71
  }
72
72
 
73
- # Разбор идёт по сегментам, а не по всей строке: `ls -l /opt && … psql -c "\copy …"` целиком
74
- # выглядел как чтение, потому что `-l` от `ls` засчитывался за `psql -l`.
73
+ # Parsing goes by segments, not by the whole line: `ls -l /opt && … psql -c "\copy …"` looked as a
74
+ # whole like reading, because the `-l` of `ls` counted as `psql -l`.
75
75
  #
76
- # Нарезка живёт в ЕДИНСТВЕННОМ месте. Пока наборов разделителей было два — один в раннем слое,
77
- # другой здесь, — расхождение само по себе оказалось дырой: одиночный `|` считался границей
78
- # тут и не считался там, и доставка файла конвейером в клиент проходила как чтение.
79
- # Команда — то, что стоит между `;`, `&&`, `||` и переводами строк. Конвейер границей НЕ
80
- # является: `cat fix.sql | psql …` — не две независимые команды, а одна доставка SQL, где
81
- # левое звено питает правое. Пока `|` резал команды, глагол из `echo "drop table …"` терялся
82
- # вместе с отброшенным звеном, и запись проходила молча.
76
+ # The cutting lives in a SINGLE place. While there were two sets of separators — one in the early
77
+ # layer, another here — the divergence itself turned out to be a hole: a lone `|` counted as a
78
+ # boundary here and did not count there, and delivering a file into the client by a pipeline passed
79
+ # as reading. A command is what stands between `;`, `&&`, `||` and newlines. A pipeline is NOT a
80
+ # boundary: `cat fix.sql | psql …` is not two independent commands but one delivery of SQL, where
81
+ # the left link feeds the right one. While `|` cut commands, the verb from `echo "drop table …"` was
82
+ # lost together with the discarded link, and the write went through silently.
83
83
  split_segments() {
84
- # Перевод строки в конце обязателен: без него `read` не отдаёт последнюю строку в тело
85
- # цикла, и команда из одного сегмента молча выпадала из разбора целиком.
84
+ # The trailing newline is mandatory: without it `read` does not give the last line to the body
85
+ # of the loop, and a command of one segment silently fell out of the parsing entirely.
86
86
  printf '%s\n' "$1" | tr '\001' '\n'
87
87
  }
88
88
 
89
- # Звенья конвейера внутри одной команды.
89
+ # Pipeline links inside one command.
90
90
  split_pipeline() {
91
91
  printf '%s' "$1" | tr '\002' '\n'
92
92
  }
93
93
 
94
- # Команда считается вызовом клиента, только если клиент стоит ГОЛОВОЙ хотя бы одного звена.
95
- # Имя в аргументе (`grep -rn "prisma db push" docs/`) вызовом не является.
94
+ # A command counts as a call of the client only if the client stands as the HEAD of at least one
95
+ # link. A name in an argument (`grep -rn "prisma db push" docs/`) is not a call.
96
96
  calls_client() {
97
97
  _found=""
98
98
  _links="$(printf '%s' "$1" | tr '\002' '\n')"
99
99
  while IFS= read -r link; do
100
100
  [ -z "$link" ] && continue
101
- # Голова звена: пропускаем присваивания окружения и обёртки вроде sudo/time/xargs.
101
+ # The head of the link: we skip environment assignments and wrappers such as sudo/time/xargs.
102
102
  head="$(printf '%s' "$link" | sed -E 's/^[[:space:]]*//; s/^([A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*[[:space:]]+)*//; s/^(sudo|time|env|nice|xargs)[[:space:]]+//')"
103
103
  case "$head" in
104
104
  psql*|pg_restore*|pg_dump*|pg_dumpall*|prisma*|*/psql*|*/pg_restore*|*/pg_dump*)
105
105
  _found="yes"; break ;;
106
106
  esac
107
- # Транспорт до машины: сам вызов стоит внутри строки, которую он исполняет.
107
+ # Transport to the machine: the call itself stands inside the string it executes.
108
108
  case "$head" in
109
109
  ssh\ *|scp\ *|docker\ *|*/ssh\ *|*/docker\ *)
110
110
  printf '%s' "$link" | grep -qE '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
111
111
  && { _found="yes"; break; } ;;
112
112
  esac
113
- # Раннер пакетов перед клиентом: `npx prisma migrate deploy`.
113
+ # A package runner before the client: `npx prisma migrate deploy`.
114
114
  case "$head" in
115
115
  npx\ *|pnpm\ *|yarn\ *|bun\ *|npm\ *)
116
116
  printf '%s' "$head" | grep -qE '^(npx|pnpm|yarn|bun|npm)([[:space:]]+(exec|run|dlx))?[[:space:]]+(psql|pg_restore|pg_dump|prisma)([[:space:]]|$)' \
@@ -122,32 +122,34 @@ CALLS_EOF
122
122
  [ -n "$_found" ]
123
123
  }
124
124
 
125
- # Голова сегмента — читающий инструмент: имя клиента стоит в его аргументе, то есть это поиск
126
- # или просмотр файла, а не доставка SQL. `grep -rn "prisma db push" docs/` читает документацию.
127
- # Решает именно ГОЛОВА: тот же приём применён в dev-server-guard якорем BOUND.
125
+ # The head of the segment is a reading tool: the client name stands in its argument, meaning this is
126
+ # a search or a look at a file, not a delivery of SQL. `grep -rn "prisma db push" docs/` reads the
127
+ # documentation. It is the HEAD that decides: the same technique is applied in dev-server-guard by
128
+ # the BOUND anchor.
128
129
  is_reader() {
129
130
  printf '%s' "$1" | grep -qE '^[[:space:]]*([A-Za-z_][A-Za-z0-9_]*=[^[:space:]]*[[:space:]]+)*((sudo|time|env|nice|xargs)[[:space:]]+)*([^[:space:]]*/)?(grep|rg|ag|ack|find|awk|sed|cat|less|more|head|tail|wc|echo|printf|jq|diff|comm|sort|uniq|column)([[:space:]]|$)'
130
131
  }
131
132
 
132
- # Сегменты с настоящим вызовом клиента: читающие головы отсеиваются здесь же, а не отдельным
133
- # слоем с собственным выходом.
133
+ # Segments with a real call of the client: reading heads are filtered out right here, not by a
134
+ # separate layer with an exit of its own.
134
135
  client_segments() {
135
136
  split_segments "$flat" | while IFS= read -r seg; do
136
137
  [ -z "$seg" ] && continue
137
138
  calls_client "$seg" || continue
138
- # Маркер звена больше не нужен: дальше команда разбирается как одна строка.
139
+ # The link marker is no longer needed: further on the command is parsed as one line.
139
140
  printf '%s\n' "$(printf '%s' "$seg" | tr '\002' ' ')"
140
141
  done
141
142
  }
142
143
 
143
- # Адресат берётся ТОЛЬКО из сегментов вызова клиента и только из аргументов, а не из данных.
144
- # Домен сайта живёт в самих строках — в почте владельца, в canonical и og:url объекта, — а
145
- # рядом в цепочке его дёргают по HTTP. Пока признак искался по всей команде, `curl
146
- # https://<домен приложения>/... && psql -p 5432 -c "update …"` отклонялся как запись в
147
- # боевую базу, и опт-аута у этой ветки нет по замыслу: команда становилась неисполнимой.
148
- # Текст запроса вырезается ДО нарезки на сегменты. Внутри `-c "…"` свободно живут `;` и `||`
149
- # — по ним сегменты и режутся, поэтому кусок запроса с доменом в данных становился отдельным
150
- # сегментом, и почта на домене приложения снова читалась как адрес боевой базы.
144
+ # The address is taken ONLY from segments that call the client and only from arguments, not from
145
+ # data. The site domain lives in the strings themselves — in the owner mail, in the canonical and
146
+ # og:url of a record — while next to it in the chain it is pulled over HTTP. While the sign was
147
+ # searched for over the whole command, `curl https://<application-domain>/... && psql -p 5432 -c
148
+ # "update …"` was refused as a write to the production database, and this branch has no opt-out by
149
+ # design: the command became unexecutable. The query text is cut out BEFORE the cutting into
150
+ # segments. Inside `-c "…"` there freely live `;` and `||` — the segments are cut by them, so a
151
+ # piece of the query with a domain in the data became a separate segment, and mail on the
152
+ # application domain was again read as the address of the production database.
151
153
  sql_addr_flatten() {
152
154
  addr_flat="$flat"
153
155
  if command -v perl >/dev/null 2>&1; then
@@ -161,8 +163,8 @@ addr_segments() {
161
163
  split_segments "$addr_flat" | while IFS= read -r seg; do
162
164
  [ -z "$seg" ] && continue
163
165
  flat_seg="$(printf '%s' "$seg" | tr '\002' ' ')"
164
- # Адрес берётся из команд с вызовом клиента и из транспорта до машины: `ssh root@…`
165
- # называет боевой хост, а сам вызов стоит дальше по цепочке.
166
+ # The address is taken from commands that call the client and from transport to the machine:
167
+ # `ssh root@…` names the production host, and the call itself stands further down the chain.
166
168
  if calls_client "$seg"; then
167
169
  printf '%s\n' "$flat_seg"
168
170
  elif printf '%s' "$flat_seg" | grep -qE '(^|[^[:alnum:]_.-])(ssh|scp|docker)([^[:alnum:]_.-]|$)|(pghost|pgport|pgdatabase|pguser|database_url|postgres_url)='; then
@@ -172,17 +174,17 @@ addr_segments() {
172
174
  done
173
175
  }
174
176
 
175
- # Сегменты вызова клиента для дальнейшего разбора. У запроса из редактора сегментов нет вовсе
176
- # — там весь текст и есть запрос.
177
+ # Segments that call the client, for further parsing. A query from the editor has no segments at all
178
+ # — there the whole text is the query.
177
179
  sql_collect_segments() {
178
180
  segments="$(client_segments)"
179
181
  if [ -z "$segments" ]; then
180
- if [ -n "$conn" ] || [ "$context" != "команда psql/prisma" ]; then
182
+ if [ -n "$conn" ] || [ "$context" != "a psql/prisma command" ]; then
181
183
  segments="$flat"
182
184
  else
183
- # Команда, где имя клиента встретилось только в аргументах читающих инструментов,
184
- # ничего никуда не доставляет. Выход здесь безопасен: он стоит ПОСЛЕ разбора, а не
185
- # вместо него, и срабатывает лишь когда настоящего вызова в команде нет.
185
+ # A command where the client name met only in the arguments of reading tools delivers
186
+ # nothing anywhere. The exit here is safe: it stands AFTER the parsing, not instead of
187
+ # it, and fires only when there is no real call in the command.
186
188
  exit 0
187
189
  fi
188
190
  fi
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env bash
2
- # Запрос из ввода гарда хранилища: что именно поедет к серверу и через что.
2
+ # The request from the input of the storage guard: what exactly will go to the server and through
3
+ # what.
3
4
  #
4
- # Строки `# rt-hook:` здесь нет намеренно: событие и образец вызова объявляет сам гард, а
5
- # помощник рядом хуком не регистрируется и в одиночку ничего не решает.
5
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by the
6
+ # guard itself, and a helper next to it is not registered as a hook and decides nothing alone.
6
7
  #
7
- # Отсюда выходят четыре значения: `sql` — текст запроса или команда целиком, `conn` —
8
- # идентификатор подключения редактора, `context` — чем это доставляется, и `cmd` — исходная
9
- # командная строка, нужная разбору адреса миграции в исходном регистре.
8
+ # Four values come out of here: `sql` — the query text or the whole command, `conn` — the identifier
9
+ # of the editor connection, `context` — what this is delivered through, and `cmd` — the original
10
+ # command line, needed by the parsing of the migration address in its original case.
10
11
 
11
- # Три вида ввода: запрос через подключение редактора, команда оболочки и та же команда,
12
- # завёрнутая в универсальный исполнитель. Инструмент, не названный здесь, гарда не касается.
12
+ # Three kinds of input: a query through the editor connection, a shell command and the same command
13
+ # wrapped into the universal execution tool. A tool not named here is no concern of the guard.
13
14
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
14
15
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/hook-input.sh" 2>/dev/null || true
15
16
 
@@ -21,18 +22,18 @@ sql_read_request() {
21
22
  mcp__webstorm__execute_sql_query)
22
23
  sql="$(printf '%s' "$input" | jq -r '.tool_input.queryText // empty' 2>/dev/null)"
23
24
  conn="$(printf '%s' "$input" | jq -r '.tool_input.connectionId // empty' 2>/dev/null)"
24
- context="запрос через подключение редактора"
25
+ context="a request through the connection of the editor"
25
26
  ;;
26
- # Терминал IDE исполняет ту же командную строку и кладёт её в то же поле, что и Bash:
27
- # без этой ветки весь гард обходился сменой инструмента.
27
+ # The IDE terminal executes the same command line and puts it into the same field as Bash:
28
+ # without this branch the whole guard was bypassed by changing the tool.
28
29
  Bash | mcp__webstorm__execute_terminal_command | mcp__webstorm__execute_tool)
29
30
  cmd="$(rt_hook_cmd)"
30
31
  [ -z "$cmd" ] && exit 0
31
32
 
32
- # Универсальный исполнитель зовёт ЛЮБОЙ инструмент редактора по имени, в том числе
33
- # `execute_sql_query`, — и тогда в строке нет ни одного имени клиента, по которому
34
- # гард себя включает. Сам инструмент закрыт в permissions.deny, но полагаться только
35
- # на настройку нельзя: её снимут, а гард останется.
33
+ # The universal execution tool calls ANY tool of the editor by name, among them
34
+ # `execute_sql_query` — and then the line holds not a single client name by which the
35
+ # guard switches itself on. The tool itself is closed in permissions.deny, but relying
36
+ # on the setting alone is impossible: it will be lifted, and the guard will stay.
36
37
  if [ "$tool" = "mcp__webstorm__execute_tool" ] && command -v perl >/dev/null 2>&1; then
37
38
  case "$cmd" in
38
39
  *execute_sql_query*)
@@ -48,7 +49,7 @@ sql_read_request() {
48
49
  ' 2>/dev/null)"
49
50
  ;;
50
51
  esac
51
- # Терминал, завёрнутый в тот же исполнитель: разбираем настоящую команду.
52
+ # A terminal wrapped into the same tool: we parse the real command.
52
53
  if [ -z "$inner_sql" ]; then
53
54
  inner_cmd="$(printf '%s' "$cmd" | perl -0ne '
54
55
  if (/--command(?:=|\s+)(?:"((?:[^"\\]|\\.)*)"|\x27([^\x27]*)\x27|(.+))/s) {
@@ -59,60 +60,61 @@ sql_read_request() {
59
60
  fi
60
61
  fi
61
62
 
62
- # Завёрнутый запрос разбирается как запрос из редактора, а не как команда оболочки:
63
- # имени клиента в нём нет, зато есть подключение и текст SQL.
63
+ # A wrapped query is parsed as a query from the editor, not as a shell command: there
64
+ # is no client name in it, but there is a connection and the SQL text.
64
65
  if [ -n "$inner_sql" ]; then
65
66
  sql="$inner_sql"
66
67
  conn="$inner_conn"
67
- context="запрос через подключение редактора (обёртка исполнителя)"
68
+ context="a request through the connection of the editor (the wrapper of the executor)"
68
69
  else
69
70
 
70
- # Команда, которая ничего никуда не доставляет, разбору не подлежит — даже если имя
71
- # клиента стоит в её аргументах. `grep -rn "prisma db push" docs/` читает файлы, а не
72
- # базу; раньше он получал deny, и обойти это можно было только испортив сам шаблон
73
- # поиска. Тот же приём уже применён в dev-server-guard: решает ГОЛОВА команды, а не
74
- # упоминание имени где-то внутри.
75
- # Интересуют команды, которые доносят SQL до сервера. Клиент ищется КАК СЛОВО в любом
76
- # месте команды, а не только в начале: удаление на бою выглядит как
77
- # `ssh root@host "docker compose exec postgres psql -c '…'"` — при проверке одного
78
- # лишь начала строки оно проходило мимо гарда целиком.
71
+ # A command that delivers nothing anywhere is not subject to parsing — even if the
72
+ # client name stands in its arguments. `grep -rn "prisma db push" docs/` reads files,
73
+ # not the database; before, it got a deny, and the only way around that was to spoil the
74
+ # search pattern itself. The same technique is already applied in dev-server-guard: the
75
+ # HEAD of the command decides, not a mention of the name somewhere inside.
76
+ # What matters are commands that carry SQL to the server. The client is looked for AS A
77
+ # WORD anywhere in the command, not only at the start: a deletion on production looks
78
+ # like `ssh root@host "docker compose exec postgres psql -c '…'"` — when only the start
79
+ # of the line was checked, it went past the guard entirely.
79
80
  #
80
- # Порядок здесь принципиален. Раньше выше стояла отсечка «команда начинается с git/gh»,
81
- # снимавшая ложные срабатывания на тексте коммита, — и она же открывала обход: в
82
- # `git log && psql … -c "DELETE …"` первое звено уносило с собой весь остальной SQL.
83
- # Теперь сперва ищется клиент, и только его отсутствие завершает проверку.
81
+ # The order here matters. Before, above stood the cut-off "the command starts with
82
+ # git/gh", which removed false alarms on the commit text — and it opened a bypass: in
83
+ # `git log && psql … -c "DELETE …"` the first link carried away all the rest of the SQL
84
+ # with it. Now the client is looked for first, and only its absence ends the check.
84
85
  printf '%s\n' "$cmd" | grep -qE \
85
86
  '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
86
87
  || exit 0
87
88
 
88
- # Ложные срабатывания на описаниях снимаются иначе — вырезанием текста сообщений
89
- # (`-m '…'`, `-am "…"`, `--message="…"`, `-F file`), а не отказом от проверки всей
90
- # команды. В самом сообщении SQL не исполняется, но слова «delete» и «drop» в нём
91
- # обычны: `git commit -am "chore(api): update prisma schema"` разбирался как
92
- # UPDATE без WHERE, потому что шаблон требовал `-m` вплотную к дефису.
89
+ # False alarms on descriptions are removed differently — by cutting out the text of
90
+ # messages (`-m '…'`, `-am "…"`, `--message="…"`, `-F file`), not by giving up the check
91
+ # of the whole command. SQL is not executed in the message itself, but the words
92
+ # "delete" and "drop" are ordinary in it: `git commit -am "chore(api): update prisma
93
+ # schema"` was parsed as an UPDATE without a WHERE, because the pattern demanded `-m`
94
+ # right next to the hyphen.
93
95
  if command -v perl >/dev/null 2>&1; then
94
- # `file` в альтернации быть не должно: под него попадал `--file=cleanup.sql`
95
- # у psql, и признак «SQL приехал файлом» умирал раньше, чем его проверяли.
96
- # Здесь только флаги, которые несут ТЕКСТ сообщения.
96
+ # `file` must not be in the alternation: `--file=cleanup.sql` of psql fell under it,
97
+ # and the sign "the SQL arrived as a file" died before it was checked. Only the
98
+ # flags that carry the TEXT of the message belong here.
97
99
  cmd="$(printf '%s' "$cmd" | perl -0pe '
98
100
  s/(^|[^[:alnum:]])--?[a-zA-Z]*(m|message|body|title|body-file|F)(=|\s+)("([^"\\]|\\.)*"|\x27[^\x27]*\x27|[^\s;&|]+)/$1/gs
99
101
  ' 2>/dev/null || printf '%s' "$cmd")"
100
- # После вырезания сообщения клиента может уже не остаться — тогда это была
101
- # git-команда, лишь упоминавшая psql в тексте.
102
+ # After the message is cut out the client may no longer be there — then this was a
103
+ # git command that only mentioned psql in the text.
102
104
  printf '%s\n' "$cmd" | grep -qE \
103
105
  '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
104
106
  || exit 0
105
107
  else
106
- # Без perl вырезать текст сообщения нечем, и разбирать его как SQL нельзя:
107
- # штатный коммит упирался бы в отказ. Доставки SQL в git-команде не бывает,
108
- # поэтому здесь дешевле пропустить, чем ломать работу.
108
+ # Without perl there is nothing to cut the message text out with, and it must not
109
+ # be parsed as SQL: a regular commit would run into a refusal. There is no delivery
110
+ # of SQL in a git command, so here it is cheaper to pass than to break the work.
109
111
  case "$cmd" in
110
112
  git\ *|*/git\ *|gh\ *|*/gh\ *) exit 0 ;;
111
113
  esac
112
114
  fi
113
115
 
114
116
  sql="$cmd"
115
- context="команда psql/prisma"
117
+ context="a psql/prisma command"
116
118
  fi
117
119
  ;;
118
120
  *) exit 0 ;;