@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,28 +1,31 @@
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
+ # NOT a guard: it has no `rt-hook:` declaration and hooks into no agent event. The storage guard
6
+ # sources it — the parsing of the request, 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 the
9
+ # guard itself, and a helper next to it is not registered as a hook and decides nothing alone.
7
10
 
8
- # Дальше разбираем без учёта регистра и переводов строк: `delete\n from bookings`
9
- # — тот же запрос, что и в одну строку.
11
+ # From here on we parse ignoring case and newlines: `delete\n from bookings` is the same query as
12
+ # the one written on a single line.
10
13
  #
11
- # Перевод строки при этом превращается в `;`, а не в пробел: в командной строке он РАЗДЕЛЯЕТ
12
- # вызовы ровно как `;`, и склейка его в пробел стирала границу между ними. Многострочная
13
- # команда становилась одним сегментом, доказательство чтения из первой строки покрывало
14
- # неразобранный вызов из второй, и запись на боевую базу проходила молча — тот же обход,
15
- # что чинили для `&&`, только набранный с новой строки.
14
+ # A newline turns into `;`, not into a space: on the command line it SEPARATES calls exactly like
15
+ # `;`, and gluing it into a space erased the boundary between them. A multi-line command became one
16
+ # segment, the proof of reading from the first line covered an unparsed call from the second, and a
17
+ # write to the production database went through silently — the same bypass that was fixed for `&&`,
18
+ # only typed from a new line.
16
19
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
17
20
 
18
21
  normalize() {
19
22
  perl -0ne '
20
- # Продолжение длинной команды обратным слешем — это одна строка, а не две: без
21
- # склейки адрес из первой уезжал в соседний сегмент, где клиента уже нет.
23
+ # A long command continued by a backslash is one line, not two: without gluing, the address
24
+ # from the first went into the neighbouring segment, where there is no client any more.
22
25
  s/\\\n/ /g;
23
- # Перевод строки заменяется на `;` ТОЛЬКО вне кавычек. Внутри `-c "…"` он часть
24
- # запроса: многострочный SELECT резался на сегменты, и штатное чтение боевой базы
25
- # переставало быть доказанным.
26
+ # A newline is replaced by `;` ONLY outside quotes. Inside `-c "…"` it is part of the
27
+ # query: a multi-line SELECT was cut into segments, and regular reading of the production
28
+ # database stopped being proven.
26
29
  my ($out, $quote, $esc) = ("", "", 0);
27
30
  for my $ch (split //, $_) {
28
31
  if ($esc) { $out .= $ch; $esc = 0; next; }
@@ -33,31 +36,31 @@ normalize() {
33
36
  } elsif ($ch eq q{"} || $ch eq q{'"'"'}) {
34
37
  $quote = $ch; $out .= $ch;
35
38
  } elsif ($ch eq "\n" || $ch eq ";") {
36
- $out .= "\x01"; # граница независимых команд
39
+ $out .= "\x01"; # the boundary of independent commands
37
40
  } elsif ($ch eq "|") {
38
- $out .= "\x02"; # граница звена конвейера
41
+ $out .= "\x02"; # the boundary of a pipeline link
39
42
  } elsif ($ch eq "&") {
40
43
  $out .= "\x01";
41
44
  } else {
42
45
  $out .= $ch;
43
46
  }
44
47
  }
45
- # Соседние маркеры схлопываются: `&&` и `||` дают по два подряд.
48
+ # Neighbouring markers collapse: `&&` and `||` give two of them in a row each.
46
49
  $out =~ s/\x01+/\x01/g;
47
50
  $out =~ s/\x02\x01/\x01/g;
48
51
  $out =~ s/\x01\x02/\x01/g;
49
- # Незакрытая кавычка означает, что автомат разъехался: апостроф в комментарии
50
- # (`# don'"'"'t forget`) оставлял состояние «внутри строки» до конца ввода, и все
51
- # последующие переводы строк переставали разделять вызовы — сегментация выключалась
52
- # одним символом. В таком случае честнее ничего не печатать: вызывающий разделит
53
- # строки грубым способом, и лишнее дробление сыграет в пользу строгости.
52
+ # An unclosed quote means the automaton has come apart: an apostrophe in a comment
53
+ # (`# don'"'"'t forget`) left the state "inside a string" until the end of the input, and
54
+ # all the newlines after it stopped separating calls — segmentation was switched off by one
55
+ # character. In that case it is more honest to print nothing: the caller will split the
56
+ # lines the rough way, and the extra splitting plays in favour of strictness.
54
57
  print $out if $quote eq "";
55
58
  ' 2>/dev/null
56
59
  }
57
60
 
58
- # Грубое разделение — запасной путь: все переводы строк становятся разделителями. Оно строже
59
- # точного (может разрезать многострочный запрос), поэтому годится и как фолбэк без perl,
60
- # и как ответ на неразобранную команду.
61
+ # Rough splitting is the fallback path: all newlines become separators. It is stricter than the
62
+ # exact one (it may cut a multi-line query in two), so it serves both as a fallback without perl and
63
+ # as the answer to an unparsed command.
61
64
  sql_flatten() {
62
65
  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
66
  [ -z "$flat_rough" ] && flat_rough="$(printf '%s' "$sql" | tr '\n;&' '\001\001\001' | tr '|' '\002' | tr '\t' ' ' | tr '[:upper:]' '[:lower:]')"
@@ -70,47 +73,47 @@ sql_flatten() {
70
73
  fi
71
74
  }
72
75
 
73
- # Разбор идёт по сегментам, а не по всей строке: `ls -l /opt && … psql -c "\copy …"` целиком
74
- # выглядел как чтение, потому что `-l` от `ls` засчитывался за `psql -l`.
76
+ # Parsing goes by segments, not by the whole line: `ls -l /opt && … psql -c "\copy …"` looked as a
77
+ # whole like reading, because the `-l` of `ls` counted as `psql -l`.
75
78
  #
76
- # Нарезка живёт в ЕДИНСТВЕННОМ месте. Пока наборов разделителей было два — один в раннем слое,
77
- # другой здесь, — расхождение само по себе оказалось дырой: одиночный `|` считался границей
78
- # тут и не считался там, и доставка файла конвейером в клиент проходила как чтение.
79
- # Команда — то, что стоит между `;`, `&&`, `||` и переводами строк. Конвейер границей НЕ
80
- # является: `cat fix.sql | psql …` — не две независимые команды, а одна доставка SQL, где
81
- # левое звено питает правое. Пока `|` резал команды, глагол из `echo "drop table …"` терялся
82
- # вместе с отброшенным звеном, и запись проходила молча.
79
+ # The cutting lives in a SINGLE place. While there were two sets of separators — one in the early
80
+ # layer, another here — the divergence itself turned out to be a hole: a lone `|` counted as a
81
+ # boundary here and did not count there, and delivering a file into the client by a pipeline passed
82
+ # as reading. A command is what stands between `;`, `&&`, `||` and newlines. A pipeline is NOT a
83
+ # boundary: `cat fix.sql | psql …` is not two independent commands but one delivery of SQL, where
84
+ # the left link feeds the right one. While `|` cut commands, the verb from `echo "drop table …"` was
85
+ # lost together with the discarded link, and the write went through silently.
83
86
  split_segments() {
84
- # Перевод строки в конце обязателен: без него `read` не отдаёт последнюю строку в тело
85
- # цикла, и команда из одного сегмента молча выпадала из разбора целиком.
87
+ # The trailing newline is mandatory: without it `read` does not give the last line to the body
88
+ # of the loop, and a command of one segment silently fell out of the parsing entirely.
86
89
  printf '%s\n' "$1" | tr '\001' '\n'
87
90
  }
88
91
 
89
- # Звенья конвейера внутри одной команды.
92
+ # Pipeline links inside one command.
90
93
  split_pipeline() {
91
94
  printf '%s' "$1" | tr '\002' '\n'
92
95
  }
93
96
 
94
- # Команда считается вызовом клиента, только если клиент стоит ГОЛОВОЙ хотя бы одного звена.
95
- # Имя в аргументе (`grep -rn "prisma db push" docs/`) вызовом не является.
97
+ # A command counts as a call of the client only if the client stands as the HEAD of at least one
98
+ # link. A name in an argument (`grep -rn "prisma db push" docs/`) is not a call.
96
99
  calls_client() {
97
100
  _found=""
98
101
  _links="$(printf '%s' "$1" | tr '\002' '\n')"
99
102
  while IFS= read -r link; do
100
103
  [ -z "$link" ] && continue
101
- # Голова звена: пропускаем присваивания окружения и обёртки вроде sudo/time/xargs.
104
+ # The head of the link: we skip environment assignments and wrappers such as sudo/time/xargs.
102
105
  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
106
  case "$head" in
104
107
  psql*|pg_restore*|pg_dump*|pg_dumpall*|prisma*|*/psql*|*/pg_restore*|*/pg_dump*)
105
108
  _found="yes"; break ;;
106
109
  esac
107
- # Транспорт до машины: сам вызов стоит внутри строки, которую он исполняет.
110
+ # Transport to the machine: the call itself stands inside the string it executes.
108
111
  case "$head" in
109
112
  ssh\ *|scp\ *|docker\ *|*/ssh\ *|*/docker\ *)
110
113
  printf '%s' "$link" | grep -qE '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
111
114
  && { _found="yes"; break; } ;;
112
115
  esac
113
- # Раннер пакетов перед клиентом: `npx prisma migrate deploy`.
116
+ # A package runner before the client: `npx prisma migrate deploy`.
114
117
  case "$head" in
115
118
  npx\ *|pnpm\ *|yarn\ *|bun\ *|npm\ *)
116
119
  printf '%s' "$head" | grep -qE '^(npx|pnpm|yarn|bun|npm)([[:space:]]+(exec|run|dlx))?[[:space:]]+(psql|pg_restore|pg_dump|prisma)([[:space:]]|$)' \
@@ -122,32 +125,34 @@ CALLS_EOF
122
125
  [ -n "$_found" ]
123
126
  }
124
127
 
125
- # Голова сегмента — читающий инструмент: имя клиента стоит в его аргументе, то есть это поиск
126
- # или просмотр файла, а не доставка SQL. `grep -rn "prisma db push" docs/` читает документацию.
127
- # Решает именно ГОЛОВА: тот же приём применён в dev-server-guard якорем BOUND.
128
+ # The head of the segment is a reading tool: the client name stands in its argument, meaning this is
129
+ # a search or a look at a file, not a delivery of SQL. `grep -rn "prisma db push" docs/` reads the
130
+ # documentation. It is the HEAD that decides: the same technique is applied in dev-server-guard by
131
+ # the BOUND anchor.
128
132
  is_reader() {
129
133
  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
134
  }
131
135
 
132
- # Сегменты с настоящим вызовом клиента: читающие головы отсеиваются здесь же, а не отдельным
133
- # слоем с собственным выходом.
136
+ # Segments with a real call of the client: reading heads are filtered out right here, not by a
137
+ # separate layer with an exit of its own.
134
138
  client_segments() {
135
139
  split_segments "$flat" | while IFS= read -r seg; do
136
140
  [ -z "$seg" ] && continue
137
141
  calls_client "$seg" || continue
138
- # Маркер звена больше не нужен: дальше команда разбирается как одна строка.
142
+ # The link marker is no longer needed: further on the command is parsed as one line.
139
143
  printf '%s\n' "$(printf '%s' "$seg" | tr '\002' ' ')"
140
144
  done
141
145
  }
142
146
 
143
- # Адресат берётся ТОЛЬКО из сегментов вызова клиента и только из аргументов, а не из данных.
144
- # Домен сайта живёт в самих строках — в почте владельца, в canonical и og:url объекта, — а
145
- # рядом в цепочке его дёргают по HTTP. Пока признак искался по всей команде, `curl
146
- # https://<домен приложения>/... && psql -p 5432 -c "update …"` отклонялся как запись в
147
- # боевую базу, и опт-аута у этой ветки нет по замыслу: команда становилась неисполнимой.
148
- # Текст запроса вырезается ДО нарезки на сегменты. Внутри `-c "…"` свободно живут `;` и `||`
149
- # — по ним сегменты и режутся, поэтому кусок запроса с доменом в данных становился отдельным
150
- # сегментом, и почта на домене приложения снова читалась как адрес боевой базы.
147
+ # The address is taken ONLY from segments that call the client and only from arguments, not from
148
+ # data. The site domain lives in the strings themselves — in the owner mail, in the canonical and
149
+ # og:url of a record — while next to it in the chain it is pulled over HTTP. While the sign was
150
+ # searched for over the whole command, `curl https://<application-domain>/... && psql -p 5432 -c
151
+ # "update …"` was refused as a write to the production database, and this branch has no opt-out by
152
+ # design: the command became unexecutable. The query text is cut out BEFORE the cutting into
153
+ # segments. Inside `-c "…"` there freely live `;` and `||` — the segments are cut by them, so a
154
+ # piece of the query with a domain in the data became a separate segment, and mail on the
155
+ # application domain was again read as the address of the production database.
151
156
  sql_addr_flatten() {
152
157
  addr_flat="$flat"
153
158
  if command -v perl >/dev/null 2>&1; then
@@ -161,8 +166,8 @@ addr_segments() {
161
166
  split_segments "$addr_flat" | while IFS= read -r seg; do
162
167
  [ -z "$seg" ] && continue
163
168
  flat_seg="$(printf '%s' "$seg" | tr '\002' ' ')"
164
- # Адрес берётся из команд с вызовом клиента и из транспорта до машины: `ssh root@…`
165
- # называет боевой хост, а сам вызов стоит дальше по цепочке.
169
+ # The address is taken from commands that call the client and from transport to the machine:
170
+ # `ssh root@…` names the production host, and the call itself stands further down the chain.
166
171
  if calls_client "$seg"; then
167
172
  printf '%s\n' "$flat_seg"
168
173
  elif printf '%s' "$flat_seg" | grep -qE '(^|[^[:alnum:]_.-])(ssh|scp|docker)([^[:alnum:]_.-]|$)|(pghost|pgport|pgdatabase|pguser|database_url|postgres_url)='; then
@@ -172,17 +177,17 @@ addr_segments() {
172
177
  done
173
178
  }
174
179
 
175
- # Сегменты вызова клиента для дальнейшего разбора. У запроса из редактора сегментов нет вовсе
176
- # — там весь текст и есть запрос.
180
+ # Segments that call the client, for further parsing. A query from the editor has no segments at all
181
+ # — there the whole text is the query.
177
182
  sql_collect_segments() {
178
183
  segments="$(client_segments)"
179
184
  if [ -z "$segments" ]; then
180
- if [ -n "$conn" ] || [ "$context" != "команда psql/prisma" ]; then
185
+ if [ -n "$conn" ] || [ "$context" != "a psql/prisma command" ]; then
181
186
  segments="$flat"
182
187
  else
183
- # Команда, где имя клиента встретилось только в аргументах читающих инструментов,
184
- # ничего никуда не доставляет. Выход здесь безопасен: он стоит ПОСЛЕ разбора, а не
185
- # вместо него, и срабатывает лишь когда настоящего вызова в команде нет.
188
+ # A command where the client name met only in the arguments of reading tools delivers
189
+ # nothing anywhere. The exit here is safe: it stands AFTER the parsing, not instead of
190
+ # it, and fires only when there is no real call in the command.
186
191
  exit 0
187
192
  fi
188
193
  fi
@@ -1,15 +1,19 @@
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
+ # 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.
6
7
  #
7
- # Отсюда выходят четыре значения: `sql` — текст запроса или команда целиком, `conn` —
8
- # идентификатор подключения редактора, `context` — чем это доставляется, и `cmd` — исходная
9
- # командная строка, нужная разбору адреса миграции в исходном регистре.
8
+ # There is deliberately no `# rt-hook:` line here: the event and the call pattern are declared by the
9
+ # guard itself, and a helper next to it is not registered as a hook and decides nothing alone.
10
+ #
11
+ # Four values come out of here: `sql` — the query text or the whole command, `conn` — the identifier
12
+ # of the editor connection, `context` — what this is delivered through, and `cmd` — the original
13
+ # command line, needed by the parsing of the migration address in its original case.
10
14
 
11
- # Три вида ввода: запрос через подключение редактора, команда оболочки и та же команда,
12
- # завёрнутая в универсальный исполнитель. Инструмент, не названный здесь, гарда не касается.
15
+ # Three kinds of input: a query through the editor connection, a shell command and the same command
16
+ # wrapped into the universal execution tool. A tool not named here is no concern of the guard.
13
17
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
14
18
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/hook-input.sh" 2>/dev/null || true
15
19
 
@@ -21,18 +25,18 @@ sql_read_request() {
21
25
  mcp__webstorm__execute_sql_query)
22
26
  sql="$(printf '%s' "$input" | jq -r '.tool_input.queryText // empty' 2>/dev/null)"
23
27
  conn="$(printf '%s' "$input" | jq -r '.tool_input.connectionId // empty' 2>/dev/null)"
24
- context="запрос через подключение редактора"
28
+ context="a request through the connection of the editor"
25
29
  ;;
26
- # Терминал IDE исполняет ту же командную строку и кладёт её в то же поле, что и Bash:
27
- # без этой ветки весь гард обходился сменой инструмента.
30
+ # The IDE terminal executes the same command line and puts it into the same field as Bash:
31
+ # without this branch the whole guard was bypassed by changing the tool.
28
32
  Bash | mcp__webstorm__execute_terminal_command | mcp__webstorm__execute_tool)
29
33
  cmd="$(rt_hook_cmd)"
30
34
  [ -z "$cmd" ] && exit 0
31
35
 
32
- # Универсальный исполнитель зовёт ЛЮБОЙ инструмент редактора по имени, в том числе
33
- # `execute_sql_query`, — и тогда в строке нет ни одного имени клиента, по которому
34
- # гард себя включает. Сам инструмент закрыт в permissions.deny, но полагаться только
35
- # на настройку нельзя: её снимут, а гард останется.
36
+ # The universal execution tool calls ANY tool of the editor by name, among them
37
+ # `execute_sql_query` — and then the line holds not a single client name by which the
38
+ # guard switches itself on. The tool itself is closed in permissions.deny, but relying
39
+ # on the setting alone is impossible: it will be lifted, and the guard will stay.
36
40
  if [ "$tool" = "mcp__webstorm__execute_tool" ] && command -v perl >/dev/null 2>&1; then
37
41
  case "$cmd" in
38
42
  *execute_sql_query*)
@@ -48,7 +52,7 @@ sql_read_request() {
48
52
  ' 2>/dev/null)"
49
53
  ;;
50
54
  esac
51
- # Терминал, завёрнутый в тот же исполнитель: разбираем настоящую команду.
55
+ # A terminal wrapped into the same tool: we parse the real command.
52
56
  if [ -z "$inner_sql" ]; then
53
57
  inner_cmd="$(printf '%s' "$cmd" | perl -0ne '
54
58
  if (/--command(?:=|\s+)(?:"((?:[^"\\]|\\.)*)"|\x27([^\x27]*)\x27|(.+))/s) {
@@ -59,60 +63,61 @@ sql_read_request() {
59
63
  fi
60
64
  fi
61
65
 
62
- # Завёрнутый запрос разбирается как запрос из редактора, а не как команда оболочки:
63
- # имени клиента в нём нет, зато есть подключение и текст SQL.
66
+ # A wrapped query is parsed as a query from the editor, not as a shell command: there
67
+ # is no client name in it, but there is a connection and the SQL text.
64
68
  if [ -n "$inner_sql" ]; then
65
69
  sql="$inner_sql"
66
70
  conn="$inner_conn"
67
- context="запрос через подключение редактора (обёртка исполнителя)"
71
+ context="a request through the connection of the editor (the wrapper of the executor)"
68
72
  else
69
73
 
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
- # лишь начала строки оно проходило мимо гарда целиком.
74
+ # A command that delivers nothing anywhere is not subject to parsing — even if the
75
+ # client name stands in its arguments. `grep -rn "prisma db push" docs/` reads files,
76
+ # not the database; before, it got a deny, and the only way around that was to spoil the
77
+ # search pattern itself. The same technique is already applied in dev-server-guard: the
78
+ # HEAD of the command decides, not a mention of the name somewhere inside.
79
+ # What matters are commands that carry SQL to the server. The client is looked for AS A
80
+ # WORD anywhere in the command, not only at the start: a deletion on production looks
81
+ # like `ssh root@host "docker compose exec postgres psql -c '…'"` — when only the start
82
+ # of the line was checked, it went past the guard entirely.
79
83
  #
80
- # Порядок здесь принципиален. Раньше выше стояла отсечка «команда начинается с git/gh»,
81
- # снимавшая ложные срабатывания на тексте коммита, — и она же открывала обход: в
82
- # `git log && psql … -c "DELETE …"` первое звено уносило с собой весь остальной SQL.
83
- # Теперь сперва ищется клиент, и только его отсутствие завершает проверку.
84
+ # The order here matters. Before, above stood the cut-off "the command starts with
85
+ # git/gh", which removed false alarms on the commit text — and it opened a bypass: in
86
+ # `git log && psql … -c "DELETE …"` the first link carried away all the rest of the SQL
87
+ # with it. Now the client is looked for first, and only its absence ends the check.
84
88
  printf '%s\n' "$cmd" | grep -qE \
85
89
  '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
86
90
  || exit 0
87
91
 
88
- # Ложные срабатывания на описаниях снимаются иначе — вырезанием текста сообщений
89
- # (`-m '…'`, `-am "…"`, `--message="…"`, `-F file`), а не отказом от проверки всей
90
- # команды. В самом сообщении SQL не исполняется, но слова «delete» и «drop» в нём
91
- # обычны: `git commit -am "chore(api): update prisma schema"` разбирался как
92
- # UPDATE без WHERE, потому что шаблон требовал `-m` вплотную к дефису.
92
+ # False alarms on descriptions are removed differently — by cutting out the text of
93
+ # messages (`-m '…'`, `-am "…"`, `--message="…"`, `-F file`), not by giving up the check
94
+ # of the whole command. SQL is not executed in the message itself, but the words
95
+ # "delete" and "drop" are ordinary in it: `git commit -am "chore(api): update prisma
96
+ # schema"` was parsed as an UPDATE without a WHERE, because the pattern demanded `-m`
97
+ # right next to the hyphen.
93
98
  if command -v perl >/dev/null 2>&1; then
94
- # `file` в альтернации быть не должно: под него попадал `--file=cleanup.sql`
95
- # у psql, и признак «SQL приехал файлом» умирал раньше, чем его проверяли.
96
- # Здесь только флаги, которые несут ТЕКСТ сообщения.
99
+ # `file` must not be in the alternation: `--file=cleanup.sql` of psql fell under it,
100
+ # and the sign "the SQL arrived as a file" died before it was checked. Only the
101
+ # flags that carry the TEXT of the message belong here.
97
102
  cmd="$(printf '%s' "$cmd" | perl -0pe '
98
103
  s/(^|[^[:alnum:]])--?[a-zA-Z]*(m|message|body|title|body-file|F)(=|\s+)("([^"\\]|\\.)*"|\x27[^\x27]*\x27|[^\s;&|]+)/$1/gs
99
104
  ' 2>/dev/null || printf '%s' "$cmd")"
100
- # После вырезания сообщения клиента может уже не остаться — тогда это была
101
- # git-команда, лишь упоминавшая psql в тексте.
105
+ # After the message is cut out the client may no longer be there — then this was a
106
+ # git command that only mentioned psql in the text.
102
107
  printf '%s\n' "$cmd" | grep -qE \
103
108
  '(^|[^[:alnum:]_.-])(psql|pg_restore|pg_dump|prisma)([^[:alnum:]_.-]|$)' \
104
109
  || exit 0
105
110
  else
106
- # Без perl вырезать текст сообщения нечем, и разбирать его как SQL нельзя:
107
- # штатный коммит упирался бы в отказ. Доставки SQL в git-команде не бывает,
108
- # поэтому здесь дешевле пропустить, чем ломать работу.
111
+ # Without perl there is nothing to cut the message text out with, and it must not
112
+ # be parsed as SQL: a regular commit would run into a refusal. There is no delivery
113
+ # of SQL in a git command, so here it is cheaper to pass than to break the work.
109
114
  case "$cmd" in
110
115
  git\ *|*/git\ *|gh\ *|*/gh\ *) exit 0 ;;
111
116
  esac
112
117
  fi
113
118
 
114
119
  sql="$cmd"
115
- context="команда psql/prisma"
120
+ context="a psql/prisma command"
116
121
  fi
117
122
  ;;
118
123
  *) exit 0 ;;