agent-steward 0.0.5 → 0.0.6

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 (191) hide show
  1. package/CHANGELOG.md +176 -1
  2. package/README.md +9 -7
  3. package/ROADMAP-STRATEGY.md +5 -5
  4. package/ROADMAP.md +107 -17
  5. package/dist/cli.js +5 -0
  6. package/dist/core/analytics.d.ts +6 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +20 -3
  9. package/dist/core/audit.d.ts +6 -0
  10. package/dist/core/audit.d.ts.map +1 -1
  11. package/dist/core/audit.js +24 -0
  12. package/dist/core/budget.d.ts +118 -0
  13. package/dist/core/budget.d.ts.map +1 -0
  14. package/dist/core/budget.js +206 -0
  15. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  16. package/dist/core/cron-to-schtasks.js +38 -0
  17. package/dist/core/dry-run.d.ts +26 -1
  18. package/dist/core/dry-run.d.ts.map +1 -1
  19. package/dist/core/dry-run.js +199 -8
  20. package/dist/core/feedback.d.ts +192 -0
  21. package/dist/core/feedback.d.ts.map +1 -0
  22. package/dist/core/feedback.js +426 -0
  23. package/dist/core/gate-integrity.d.ts +36 -0
  24. package/dist/core/gate-integrity.d.ts.map +1 -1
  25. package/dist/core/gate-integrity.js +144 -1
  26. package/dist/core/local-ai.d.ts.map +1 -1
  27. package/dist/core/local-ai.js +7 -3
  28. package/dist/core/matrix.d.ts +8 -0
  29. package/dist/core/matrix.d.ts.map +1 -1
  30. package/dist/core/matrix.js +57 -2
  31. package/dist/core/mission.d.ts +20 -0
  32. package/dist/core/mission.d.ts.map +1 -1
  33. package/dist/core/mission.js +45 -5
  34. package/dist/core/opencode-models.d.ts +2 -2
  35. package/dist/core/opencode-models.d.ts.map +1 -1
  36. package/dist/core/opencode-models.js +28 -21
  37. package/dist/core/opencode-usage.d.ts +35 -0
  38. package/dist/core/opencode-usage.d.ts.map +1 -0
  39. package/dist/core/opencode-usage.js +132 -0
  40. package/dist/core/pipeline-io.d.ts +1 -1
  41. package/dist/core/pipeline-io.d.ts.map +1 -1
  42. package/dist/core/pipeline-io.js +26 -12
  43. package/dist/core/pipeline-map.d.ts +6 -0
  44. package/dist/core/pipeline-map.d.ts.map +1 -1
  45. package/dist/core/pipeline-map.js +12 -0
  46. package/dist/core/ps-wrapper.d.ts +10 -2
  47. package/dist/core/ps-wrapper.d.ts.map +1 -1
  48. package/dist/core/ps-wrapper.js +176 -5
  49. package/dist/core/record-history.d.ts.map +1 -1
  50. package/dist/core/record-history.js +76 -4
  51. package/dist/core/run-mode.d.ts +12 -0
  52. package/dist/core/run-mode.d.ts.map +1 -0
  53. package/dist/core/run-mode.js +17 -0
  54. package/dist/core/scheduler/logs.d.ts +4 -0
  55. package/dist/core/scheduler/logs.d.ts.map +1 -1
  56. package/dist/core/scheduler/logs.js +25 -1
  57. package/dist/core/secrets.d.ts.map +1 -1
  58. package/dist/core/secrets.js +18 -8
  59. package/dist/core/self-analysis.d.ts +32 -2
  60. package/dist/core/self-analysis.d.ts.map +1 -1
  61. package/dist/core/self-analysis.js +38 -27
  62. package/dist/core/shutdown.d.ts +33 -2
  63. package/dist/core/shutdown.d.ts.map +1 -1
  64. package/dist/core/shutdown.js +58 -2
  65. package/dist/core/structured-log.d.ts +30 -0
  66. package/dist/core/structured-log.d.ts.map +1 -1
  67. package/dist/core/structured-log.js +37 -0
  68. package/dist/core/usage-surface.d.ts +25 -0
  69. package/dist/core/usage-surface.d.ts.map +1 -0
  70. package/dist/core/usage-surface.js +41 -0
  71. package/dist/core/wrappers/bash.d.ts +2 -0
  72. package/dist/core/wrappers/bash.d.ts.map +1 -1
  73. package/dist/core/wrappers/bash.js +58 -6
  74. package/dist/db/history-repo.d.ts +32 -0
  75. package/dist/db/history-repo.d.ts.map +1 -1
  76. package/dist/db/history-repo.js +85 -7
  77. package/dist/db/metrics-repo.d.ts +20 -2
  78. package/dist/db/metrics-repo.d.ts.map +1 -1
  79. package/dist/db/metrics-repo.js +33 -11
  80. package/dist/db/migrate.d.ts.map +1 -1
  81. package/dist/db/migrate.js +37 -17
  82. package/dist/db/recovery.d.ts +3 -1
  83. package/dist/db/recovery.d.ts.map +1 -1
  84. package/dist/db/recovery.js +9 -4
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +71 -56
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +70 -1
  90. package/dist/db/templates-repo.d.ts +2 -2
  91. package/dist/db/templates-repo.d.ts.map +1 -1
  92. package/dist/db/templates-repo.js +5 -3
  93. package/dist/history.d.ts +6 -1
  94. package/dist/history.d.ts.map +1 -1
  95. package/dist/history.js +4 -2
  96. package/dist/hook-output.d.ts +2 -0
  97. package/dist/hook-output.d.ts.map +1 -0
  98. package/dist/hook-output.js +31 -0
  99. package/dist/index.d.ts +247 -53
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +999 -211
  102. package/dist/notifications.d.ts +31 -2
  103. package/dist/notifications.d.ts.map +1 -1
  104. package/dist/notifications.js +132 -13
  105. package/dist/profiles.d.ts.map +1 -1
  106. package/dist/profiles.js +66 -15
  107. package/dist/rpc.d.ts +108 -0
  108. package/dist/rpc.d.ts.map +1 -1
  109. package/dist/rpc.js +28 -0
  110. package/dist/server.d.ts +17 -2
  111. package/dist/server.d.ts.map +1 -1
  112. package/dist/server.js +77 -12
  113. package/dist/settings.d.ts +42 -0
  114. package/dist/settings.d.ts.map +1 -1
  115. package/dist/settings.js +82 -0
  116. package/dist/task-transfer.d.ts +5 -0
  117. package/dist/task-transfer.d.ts.map +1 -1
  118. package/dist/task-transfer.js +48 -3
  119. package/dist/templates.d.ts +2 -2
  120. package/dist/templates.d.ts.map +1 -1
  121. package/dist/templates.js +3 -3
  122. package/dist/types.d.ts +22 -2
  123. package/dist/types.d.ts.map +1 -1
  124. package/dist/workspaces.d.ts.map +1 -1
  125. package/dist/workspaces.js +34 -11
  126. package/docs/ARCHITECTURE.md +49 -12
  127. package/docs/COMPATIBILITY.md +2 -2
  128. package/docs/EXECUTION-LOOP.md +6 -3
  129. package/docs/FEATURES.md +65 -4
  130. package/docs/FEATURES.zh.md +45 -2
  131. package/docs/QA-A2-GUI-TUI.md +205 -0
  132. package/docs/README.ru.md +3 -3
  133. package/docs/README.zh.md +2 -2
  134. package/gui-experimental.cjs +9 -9
  135. package/locales/en.json +42 -3
  136. package/locales/ru.json +42 -3
  137. package/locales/zh.json +42 -3
  138. package/package.json +15 -2
  139. package/scripts/check-eslint-baseline.mjs +139 -0
  140. package/scripts/gen-test-plan-counters.mjs +117 -0
  141. package/scripts/github-ci-fetch.ps1 +37 -0
  142. package/scripts/pl-commit.ps1 +112 -0
  143. package/scripts/qa-a2-commit.ps1 +104 -0
  144. package/scripts/test-home.mjs +26 -2
  145. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  146. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  147. package/src/cli.ts +5 -0
  148. package/src/core/analytics.ts +27 -4
  149. package/src/core/audit.ts +25 -0
  150. package/src/core/budget.ts +340 -0
  151. package/src/core/cron-to-schtasks.ts +42 -0
  152. package/src/core/dry-run.ts +233 -10
  153. package/src/core/feedback.ts +582 -0
  154. package/src/core/gate-integrity.ts +171 -1
  155. package/src/core/local-ai.ts +7 -3
  156. package/src/core/matrix.ts +63 -2
  157. package/src/core/mission.ts +51 -5
  158. package/src/core/opencode-models.ts +30 -21
  159. package/src/core/opencode-usage.ts +182 -0
  160. package/src/core/pipeline-io.ts +28 -11
  161. package/src/core/pipeline-map.ts +19 -0
  162. package/src/core/ps-wrapper.ts +173 -4
  163. package/src/core/record-history.ts +94 -4
  164. package/src/core/run-mode.ts +19 -0
  165. package/src/core/scheduler/logs.ts +32 -1
  166. package/src/core/secrets.ts +18 -11
  167. package/src/core/self-analysis.ts +75 -29
  168. package/src/core/shutdown.ts +90 -4
  169. package/src/core/structured-log.ts +67 -0
  170. package/src/core/usage-surface.ts +70 -0
  171. package/src/core/wrappers/bash.ts +60 -5
  172. package/src/db/history-repo.ts +153 -19
  173. package/src/db/metrics-repo.ts +38 -11
  174. package/src/db/migrate.ts +57 -32
  175. package/src/db/recovery.ts +10 -4
  176. package/src/db/runs-repo.ts +113 -61
  177. package/src/db/schema.ts +70 -1
  178. package/src/db/templates-repo.ts +5 -3
  179. package/src/gui.tsx +261 -5
  180. package/src/history.ts +10 -3
  181. package/src/hook-output.ts +39 -0
  182. package/src/index.ts +1407 -345
  183. package/src/notifications.ts +189 -39
  184. package/src/profiles.ts +72 -16
  185. package/src/rpc.ts +30 -0
  186. package/src/server.ts +107 -23
  187. package/src/settings.ts +120 -0
  188. package/src/task-transfer.ts +59 -6
  189. package/src/templates.ts +3 -3
  190. package/src/types.ts +23 -2
  191. package/src/workspaces.ts +37 -14
package/locales/en.json CHANGED
@@ -38,6 +38,18 @@
38
38
  "dryRun.window.reason.neverFires": "the cron never fires",
39
39
  "dryRun.window.reason.neverInWindow": "no run falls inside the window",
40
40
  "dryRun.window.reason.postponeTooFar": "the nearest window opening is more than 12 hours away",
41
+ "feedback.dryRun": "Preview only: nothing was sent. Review the payload above before sending.",
42
+ "feedback.sent": "Report sent to the author via the receiver. Thank you!",
43
+ "feedback.outbox": "Receiver unavailable — the report was saved locally and will be retried on startup. Plugin startup was not blocked.",
44
+ "feedback.duplicate": "An identical report was sent recently — skipped to prevent spam.",
45
+ "feedback.local": "Report sent to local notification channels.",
46
+ "feedback.settingsTitle": "Author feedback (bug reports)",
47
+ "feedback.settingsEnabled": "Send reports to the author",
48
+ "feedback.settingsEndpoint": "Receiver URL (POST /report)",
49
+ "feedback.settingsIncludeLogs": "Attach logs by default",
50
+ "feedback.settingsContactEmail": "Contact email (optional)",
51
+ "feedback.settingsMaxPerHour": "Reports per hour limit",
52
+ "feedback.settingsHint": "The GitHub token lives only in the receiver secrets. Secrets, home paths and emails are redacted from logs.",
41
53
  "gitTrigger.baseline": "Remembered current commit {commit} — the task will run on the next change.",
42
54
  "gitTrigger.branchMismatch": "Branch {branch} does not match the filter \"{pattern}\".",
43
55
  "gitTrigger.changed": "New commit {commit}: {count} files changed ({files}).",
@@ -194,6 +206,14 @@
194
206
  "gui.historyCleanupHint": "Only finished records are deleted; unfinished runs are kept.",
195
207
  "gui.historyDeleteOlderLabel": "Delete records older than, days",
196
208
  "gui.historyHeading": "🧹 History & retention",
209
+ "gui.budgetsHeading": "Budgets (daily / weekly)",
210
+ "gui.budgetsEnabled": "enabled",
211
+ "gui.budgetsDisabled": "disabled",
212
+ "gui.budgetsHint": "When a limit is reached, new runs are skipped. 0 means no limit.",
213
+ "gui.budgetsEnabledLabel": "Enable budget control",
214
+ "gui.budgetsDailyLabel": "Daily limit, USD:",
215
+ "gui.budgetsWeeklyLabel": "Weekly limit, USD:",
216
+ "gui.budgetsZeroNoLimit": "0 means no limit",
197
217
  "gui.historyKeepMaxLabel": "Keep at most records",
198
218
  "gui.historyNoExpiry": "no expiry",
199
219
  "gui.historyNoLimit": "no limit",
@@ -306,7 +326,9 @@
306
326
  "gui.mcpFilterPlaceholder": "e.g. repo=\"my-project\" or regex",
307
327
  "gui.mcpSourceLabel": "MCP server / source",
308
328
  "gui.mcpSourcePlaceholder": "e.g. github",
309
- "gui.metricsTotalsLine": "📊 Total across all tasks: {total} · ✅ {success} · ❌ {error}",
329
+ "gui.metricsTotalsLine": "📊 Runs in history: {total} · ✅ {success} · ❌ {error} · ⏭ {skipped} · ⏸ {interrupted}",
330
+ "gui.metricsToolBlockedLine": "🛡 Tool blocks (14 days): {count}",
331
+ "gui.metricsToolBlockedTitle": "Hybrid policy working as intended, not a run failure",
310
332
  "gui.metricsTotalsTitle": "Total metrics across all tasks (including archived metric records)",
311
333
  "gui.modalShortcutHint": "Ctrl+Enter — save, Escape — cancel",
312
334
  "gui.modelHint": "Empty — the default OpenCode model. Otherwise the --model flag is passed.",
@@ -741,7 +763,7 @@
741
763
  "tool.error.matrixNotMatrix": "Task \"{name}\" is not a matrix.",
742
764
  "tool.error.matrixOverride": "Task \"{task}\": matrix.overrides contains workspace \"{workspace}\" that is not listed in workspaceIds.",
743
765
  "tool.error.modelInvalid": "Invalid model \"{model}\": {error}",
744
- "tool.error.mcpEventRequired": "An MCP trigger requires an event name (mcpEvent.event).",
766
+ "tool.error.mcpEventRequired": "An MCP trigger requires an event name (mcpEvent.event or mcpEvent.eventName).",
745
767
  "tool.error.onceFields": "runAt/delaySeconds are only allowed with triggerType=once.",
746
768
  "tool.error.onceMatrixSchema": "One-shot cannot be combined with matrix: a matrix is started manually only.",
747
769
  "tool.error.onceMatrixUpdate": "One-shot cannot be combined with matrix.",
@@ -774,6 +796,7 @@
774
796
  "tool.event.none": "No tasks are subscribed to event \"{event}\".",
775
797
  "tool.event.processed": "Event \"{event}\" processed. Tasks started: {count}.",
776
798
  "tool.event.triggered": "Tasks started: {count}.",
799
+ "tool.event.startFailed": "Failed to start tasks: {count}.",
777
800
  "tool.history.cleanFailed": "Failed to clean history: {error}",
778
801
  "tool.history.cleaned": "Deleted {deleted} records (by age: {byAge}, by limit: {byCount}), {kept} left.",
779
802
  "tool.localAi.unchanged": "Settings unchanged.",
@@ -860,5 +883,21 @@
860
883
  "gui.missionTitle": "Ad-hoc mission",
861
884
  "gui.missionEmptyPrompt": "Enter a mission prompt.",
862
885
  "gui.missionStarted": "Mission completed",
863
- "gui.missionFailed": "Mission failed"
886
+ "gui.missionFailed": "Mission failed",
887
+ "selfAnalysis.level.excellent": "excellent",
888
+ "selfAnalysis.level.good": "good",
889
+ "selfAnalysis.level.fair": "fair",
890
+ "selfAnalysis.level.poor": "poor",
891
+ "selfAnalysis.level.critical": "critical",
892
+ "selfAnalysis.health": "System health: {level} ({score}/100)",
893
+ "selfAnalysis.anomaliesHigh": "{count, plural, one {Detected # critical anomaly} other {Detected # critical anomalies}}",
894
+ "selfAnalysis.anomaliesAll": "{count, plural, one {Detected # anomaly (all non-critical)} other {Detected # anomalies (all non-critical)}}",
895
+ "selfAnalysis.noAnomalies": "No critical anomalies detected",
896
+ "selfAnalysis.degrading": "{count, plural, one {# metric is degrading} other {# metrics are degrading}}",
897
+ "selfAnalysis.highPriority": "{count, plural, one {# high-priority recommendation} other {# high-priority recommendations}}",
898
+ "selfAnalysis.rec.successRate": "Improve run success rate: check Quality Gate and error logs",
899
+ "selfAnalysis.rec.errorRate": "Reduce error rate: add retryCount for flaky tasks",
900
+ "selfAnalysis.rec.duration": "Optimize duration: split long tasks or increase timeoutSeconds",
901
+ "selfAnalysis.rec.timeouts": "Reduce timeouts: increase timeoutSeconds or simplify prompts",
902
+ "selfAnalysis.rec.crashes": "Reduce interrupted runs: check system stability"
864
903
  }
package/locales/ru.json CHANGED
@@ -38,6 +38,18 @@
38
38
  "dryRun.window.reason.neverFires": "cron не даёт ни одного запуска",
39
39
  "dryRun.window.reason.neverInWindow": "ни один запуск не попадает в окно",
40
40
  "dryRun.window.reason.postponeTooFar": "ближайшее открытие окна позже 12 часов",
41
+ "feedback.dryRun": "Предпросмотр: ничего не отправлено. Проверьте показанный payload перед отправкой.",
42
+ "feedback.sent": "Отчёт отправлен автору через приёмник. Спасибо!",
43
+ "feedback.outbox": "Приёмник недоступен — отчёт сохранён локально и будет отправлен повторно при старте. Запуск плагина не заблокирован.",
44
+ "feedback.duplicate": "Такой отчёт уже был отправлен недавно — повтор пропущен для защиты от спама.",
45
+ "feedback.local": "Отчёт отправлен в локальные каналы уведомлений.",
46
+ "feedback.settingsTitle": "Обратная связь с автором (bug reports)",
47
+ "feedback.settingsEnabled": "Отправлять отчёты автору",
48
+ "feedback.settingsEndpoint": "URL приёмника (POST /report)",
49
+ "feedback.settingsIncludeLogs": "Прикладывать логи по умолчанию",
50
+ "feedback.settingsContactEmail": "Обратный адрес (необязательно)",
51
+ "feedback.settingsMaxPerHour": "Лимит отчётов в час",
52
+ "feedback.settingsHint": "Токен GitHub живёт только в секретах приёмника. Из логов вырезаются секреты, пути home и email.",
41
53
  "gitTrigger.baseline": "Запомнен текущий коммит {commit} — задача запустится на следующем изменении.",
42
54
  "gitTrigger.branchMismatch": "Ветка {branch} не подходит под фильтр «{pattern}».",
43
55
  "gitTrigger.changed": "Новый коммит {commit}: изменено файлов {count} ({files}).",
@@ -194,6 +206,14 @@
194
206
  "gui.historyCleanupHint": "Удаляются только завершённые записи; незавершённые запуски не трогаются.",
195
207
  "gui.historyDeleteOlderLabel": "Удалять записи старше, дней",
196
208
  "gui.historyHeading": "🧹 История и ретеншн",
209
+ "gui.budgetsHeading": "Бюджеты (день / неделя)",
210
+ "gui.budgetsEnabled": "включены",
211
+ "gui.budgetsDisabled": "выключены",
212
+ "gui.budgetsHint": "При достижении лимита новые запуски пропускаются. 0 — без лимита.",
213
+ "gui.budgetsEnabledLabel": "Включить контроль бюджетов",
214
+ "gui.budgetsDailyLabel": "Лимит на день, USD:",
215
+ "gui.budgetsWeeklyLabel": "Лимит на неделю, USD:",
216
+ "gui.budgetsZeroNoLimit": "0 — без лимита",
197
217
  "gui.historyKeepMaxLabel": "Хранить не более записей",
198
218
  "gui.historyNoExpiry": "без срока",
199
219
  "gui.historyNoLimit": "без лимита",
@@ -306,7 +326,9 @@
306
326
  "gui.mcpFilterPlaceholder": "например, repo=\"my-project\" или regex",
307
327
  "gui.mcpSourceLabel": "MCP-сервер / источник",
308
328
  "gui.mcpSourcePlaceholder": "например, github",
309
- "gui.metricsTotalsLine": "📊 Всего по всем задачам: {total} · ✅ {success} · ❌ {error}",
329
+ "gui.metricsTotalsLine": "📊 Запусков в истории: {total} · ✅ {success} · ❌ {error} · ⏭ {skipped} · ⏸ {interrupted}",
330
+ "gui.metricsToolBlockedLine": "🛡 Блокировок инструментов (14 дней): {count}",
331
+ "gui.metricsToolBlockedTitle": "Счётчик корректной работы hybrid-политики прав, а не ошибок запуска",
310
332
  "gui.metricsTotalsTitle": "Суммарные метрики по всем задачам (включая архивные записи метрик)",
311
333
  "gui.modalShortcutHint": "Ctrl+Enter — сохранить, Escape — отмена",
312
334
  "gui.modelHint": "Пусто — модель OpenCode по умолчанию. Иначе будет передан флаг --model.",
@@ -741,7 +763,7 @@
741
763
  "tool.error.matrixNotMatrix": "Задача \"{name}\" не является матрицей.",
742
764
  "tool.error.matrixOverride": "Задача \"{task}\": matrix.overrides содержит workspace \"{workspace}\", которого нет в workspaceIds.",
743
765
  "tool.error.modelInvalid": "Недопустимая модель «{model}»: {error}",
744
- "tool.error.mcpEventRequired": "Для MCP-триггера нужно указать имя события (mcpEvent.event).",
766
+ "tool.error.mcpEventRequired": "Для MCP-триггера нужно указать имя события (mcpEvent.event или mcpEvent.eventName).",
745
767
  "tool.error.onceFields": "runAt/delaySeconds допустимы только при triggerType=once.",
746
768
  "tool.error.onceMatrixSchema": "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
747
769
  "tool.error.onceMatrixUpdate": "One-shot нельзя комбинировать с matrix.",
@@ -774,6 +796,7 @@
774
796
  "tool.event.none": "Нет задач, подписанных на событие \"{event}\".",
775
797
  "tool.event.processed": "Событие \"{event}\" обработано. Запущено задач: {count}.",
776
798
  "tool.event.triggered": "Запущено задач: {count}.",
799
+ "tool.event.startFailed": "Не удалось запустить задач: {count}.",
777
800
  "tool.history.cleanFailed": "Не удалось очистить историю: {error}",
778
801
  "tool.history.cleaned": "Удалено {deleted} записей (по возрасту: {byAge}, по лимиту: {byCount}), осталось {kept}.",
779
802
  "tool.localAi.unchanged": "Настройки не изменились.",
@@ -860,5 +883,21 @@
860
883
  "gui.missionTitle": "Ad-hoc миссия",
861
884
  "gui.missionEmptyPrompt": "Введите промпт миссии.",
862
885
  "gui.missionStarted": "Миссия выполнена",
863
- "gui.missionFailed": "Миссия не выполнена"
886
+ "gui.missionFailed": "Миссия не выполнена",
887
+ "selfAnalysis.level.excellent": "отличное",
888
+ "selfAnalysis.level.good": "хорошее",
889
+ "selfAnalysis.level.fair": "удовлетворительное",
890
+ "selfAnalysis.level.poor": "плохое",
891
+ "selfAnalysis.level.critical": "критическое",
892
+ "selfAnalysis.health": "Здоровье системы: {level} ({score}/100)",
893
+ "selfAnalysis.anomaliesHigh": "{count, plural, one {Обнаружена # критическая аномалия} few {Обнаружено # критические аномалии} many {Обнаружено # критических аномалий} other {Обнаружено # критических аномалий}}",
894
+ "selfAnalysis.anomaliesAll": "{count, plural, one {Обнаружена # аномалия (некритическая)} few {Обнаружено # аномалии (все некритические)} many {Обнаружено # аномалий (все некритические)} other {Обнаружено # аномалии (все некритические)}}",
895
+ "selfAnalysis.noAnomalies": "Критических аномалий не обнаружено",
896
+ "selfAnalysis.degrading": "{count, plural, one {# метрика ухудшается} few {# метрики ухудшаются} many {# метрик ухудшаются} other {# метрики ухудшаются}}",
897
+ "selfAnalysis.highPriority": "{count, plural, one {# рекомендация высокого приоритета} few {# рекомендации высокого приоритета} many {# рекомендаций высокого приоритета} other {# рекомендации высокого приоритета}}",
898
+ "selfAnalysis.rec.successRate": "Повысьте успешность запусков: проверьте Quality Gate и логи ошибок",
899
+ "selfAnalysis.rec.errorRate": "Снизьте частоту ошибок: добавьте retryCount для флакких задач",
900
+ "selfAnalysis.rec.duration": "Оптимизируйте длительность: разбейте длинные задачи или увеличьте timeoutSeconds",
901
+ "selfAnalysis.rec.timeouts": "Уменьшите количество таймаутов: увеличьте timeoutSeconds или упростите промпты",
902
+ "selfAnalysis.rec.crashes": "Снизьте количество прерванных запусков: проверьте стабильность системы"
864
903
  }
package/locales/zh.json CHANGED
@@ -38,6 +38,18 @@
38
38
  "dryRun.window.reason.neverFires": "cron 不会触发任何运行",
39
39
  "dryRun.window.reason.neverInWindow": "没有任何运行落在时间窗内",
40
40
  "dryRun.window.reason.postponeTooFar": "最近的时间窗开放时间超过 12 小时",
41
+ "feedback.dryRun": "仅预览:未发送任何内容。发送前请检查上面的 payload。",
42
+ "feedback.sent": "报告已通过接收端发送给作者,谢谢!",
43
+ "feedback.outbox": "接收端不可用——报告已保存在本地,启动时会自动重试。插件启动未被阻塞。",
44
+ "feedback.duplicate": "最近已发送过相同的报告——为防止刷屏已跳过。",
45
+ "feedback.local": "报告已发送至本地通知渠道。",
46
+ "feedback.settingsTitle": "向作者反馈(bug 报告)",
47
+ "feedback.settingsEnabled": "向作者发送报告",
48
+ "feedback.settingsEndpoint": "接收端 URL(POST /report)",
49
+ "feedback.settingsIncludeLogs": "默认附带日志",
50
+ "feedback.settingsContactEmail": "联系邮箱(可选)",
51
+ "feedback.settingsMaxPerHour": "每小时报告上限",
52
+ "feedback.settingsHint": "GitHub token 仅保存在接收端的 secrets 中。日志中的密钥、home 路径和邮箱会被脱敏。",
41
53
  "gitTrigger.baseline": "已记录当前提交 {commit}——任务将在下次变更时运行。",
42
54
  "gitTrigger.branchMismatch": "分支 {branch} 与筛选条件 “{pattern}” 不匹配。",
43
55
  "gitTrigger.changed": "新提交 {commit}:{count} 个文件已更改({files})。",
@@ -194,6 +206,14 @@
194
206
  "gui.historyCleanupHint": "仅删除已完成的记录;未完成的运行会保留。",
195
207
  "gui.historyDeleteOlderLabel": "删除早于以下天数的记录",
196
208
  "gui.historyHeading": "🧹 历史记录与保留策略",
209
+ "gui.budgetsHeading": "预算(每日 / 每周)",
210
+ "gui.budgetsEnabled": "已启用",
211
+ "gui.budgetsDisabled": "已禁用",
212
+ "gui.budgetsHint": "达到限额后将跳过新任务。0 表示不限制。",
213
+ "gui.budgetsEnabledLabel": "启用预算控制",
214
+ "gui.budgetsDailyLabel": "每日限额(美元):",
215
+ "gui.budgetsWeeklyLabel": "每周限额(美元):",
216
+ "gui.budgetsZeroNoLimit": "0 表示不限制",
197
217
  "gui.historyKeepMaxLabel": "最多保留记录数",
198
218
  "gui.historyNoExpiry": "无期限",
199
219
  "gui.historyNoLimit": "无限制",
@@ -306,7 +326,9 @@
306
326
  "gui.mcpFilterPlaceholder": "例如 repo=\"my-project\" 或正则",
307
327
  "gui.mcpSourceLabel": "MCP 服务器 / 来源",
308
328
  "gui.mcpSourcePlaceholder": "例如 github",
309
- "gui.metricsTotalsLine": "📊 所有任务合计:{total} · ✅ {success} · ❌ {error}",
329
+ "gui.metricsTotalsLine": "📊 历史运行数:{total} · ✅ {success} · ❌ {error} · ⏭ {skipped} · ⏸ {interrupted}",
330
+ "gui.metricsToolBlockedLine": "🛡 工具拦截次数(14 天):{count}",
331
+ "gui.metricsToolBlockedTitle": "混合权限策略正常工作的指标,不是运行失败",
310
332
  "gui.metricsTotalsTitle": "所有任务的汇总指标(包括归档的指标记录)",
311
333
  "gui.modalShortcutHint": "Ctrl+Enter——保存,Escape——取消",
312
334
  "gui.modelHint": "留空——使用 OpenCode 默认模型。否则会传入 --model 标志。",
@@ -741,7 +763,7 @@
741
763
  "tool.error.matrixNotMatrix": "任务 “{name}” 不是矩阵。",
742
764
  "tool.error.matrixOverride": "任务 “{task}”:matrix.overrides 包含未在 workspaceIds 中列出的工作区 “{workspace}”。",
743
765
  "tool.error.modelInvalid": "无效的模型 “{model}”:{error}",
744
- "tool.error.mcpEventRequired": "MCP 触发器需要事件名称(mcpEvent.event)。",
766
+ "tool.error.mcpEventRequired": "MCP 触发器需要事件名称(mcpEvent.event 或 mcpEvent.eventName)。",
745
767
  "tool.error.onceFields": "runAt/delaySeconds 仅在 triggerType=once 时允许。",
746
768
  "tool.error.onceMatrixSchema": "One-shot 不能与矩阵组合:矩阵仅可手动启动。",
747
769
  "tool.error.onceMatrixUpdate": "One-shot 不能与矩阵组合。",
@@ -774,6 +796,7 @@
774
796
  "tool.event.none": "没有任务订阅事件 “{event}”。",
775
797
  "tool.event.processed": "事件 “{event}” 已处理。启动的任务数:{count}。",
776
798
  "tool.event.triggered": "启动的任务数:{count}。",
799
+ "tool.event.startFailed": "启动失败的任务数:{count}。",
777
800
  "tool.history.cleanFailed": "清理历史失败:{error}",
778
801
  "tool.history.cleaned": "已删除 {deleted} 条记录(按年龄:{byAge},按上限:{byCount}),剩余 {kept} 条。",
779
802
  "tool.localAi.unchanged": "设置未更改。",
@@ -860,5 +883,21 @@
860
883
  "gui.missionTitle": "Ad-hoc 任务",
861
884
  "gui.missionEmptyPrompt": "请输入任务提示词。",
862
885
  "gui.missionStarted": "任务已完成",
863
- "gui.missionFailed": "任务失败"
886
+ "gui.missionFailed": "任务失败",
887
+ "selfAnalysis.level.excellent": "优秀",
888
+ "selfAnalysis.level.good": "良好",
889
+ "selfAnalysis.level.fair": "一般",
890
+ "selfAnalysis.level.poor": "较差",
891
+ "selfAnalysis.level.critical": "严重",
892
+ "selfAnalysis.health": "系统健康度:{level} ({score}/100)",
893
+ "selfAnalysis.anomaliesHigh": "检测到 # 个严重异常",
894
+ "selfAnalysis.anomaliesAll": "检测到 # 个异常(均为非严重)",
895
+ "selfAnalysis.noAnomalies": "未检测到严重异常",
896
+ "selfAnalysis.degrading": "# 个指标正在恶化",
897
+ "selfAnalysis.highPriority": "# 条高优先级建议",
898
+ "selfAnalysis.rec.successRate": "提高运行成功率:检查 Quality Gate 和错误日志",
899
+ "selfAnalysis.rec.errorRate": "降低错误率:为不稳定的任务添加 retryCount",
900
+ "selfAnalysis.rec.duration": "优化耗时:拆分长任务或增加 timeoutSeconds",
901
+ "selfAnalysis.rec.timeouts": "减少超时:增加 timeoutSeconds 或简化提示词",
902
+ "selfAnalysis.rec.crashes": "减少中断的运行:检查系统稳定性"
864
903
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-steward",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "OpenCode plugin for V1 and V2: scheduling and orchestrating AI agent jobs — cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
5
5
  "license": "MIT",
6
6
  "author": "agent-steward contributors",
@@ -80,13 +80,16 @@
80
80
  "build": "tsc",
81
81
  "lint": "eslint src",
82
82
  "lint-job": "eslint src",
83
+ "lint:strict": "eslint src --max-warnings=0",
84
+ "lint:baseline": "node scripts/check-eslint-baseline.mjs",
85
+ "lint:baseline:update": "node scripts/check-eslint-baseline.mjs --update",
83
86
  "build:gui": "vite build",
84
87
  "demo": "node scripts/demo-dashboard.mjs",
85
88
  "bench:local": "node scripts/bench-local.mjs",
86
89
  "prepare": "npm run build",
87
90
  "prepublishOnly": "npm run build && npm run build:gui",
88
91
  "pretest": "npm run build",
89
- "test": "node test-sqlite.mjs && node test-user-version.mjs && node test-run-state.mjs && node test-run-journal.mjs && node test-run-resume.mjs && node test-step-idempotency.mjs && node test-run-dlq.mjs && node test-run-context.mjs && node test-dlq-gui.mjs && node test-pause-gui.mjs && node test-router-rules.mjs && node test-capability-map.mjs && node test-planner.mjs && node test-escalation.mjs && node test-router-dispatch.mjs && node test-execution-pipeline.mjs && node test-mission-run.mjs && node test-crash-recovery.mjs && node test-prompt-argv.mjs && node test-ps-watchdog.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-permissions-policy.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-savings.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-dedup.mjs && node test-notifications-embedding.mjs && node test-notifications-summary.mjs && node test-settings.mjs && node test-notifications-v3.mjs && node test-triage.mjs && node test-triage-rules.mjs && node test-triage-compare.mjs && node test-triage-chain.mjs && node test-triage-shadow.mjs && node test-triage-audit.mjs && node test-triage-async.mjs && node test-local-ai.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-self-analysis.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-trust.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-dashboard-xss.mjs && node test-profile-isolation.mjs && node test-docs.mjs && node test-glob.mjs && node test-git-trigger.mjs && node test-window-v3.mjs && node test-i18n.mjs && node test-gui-bundle.mjs && node test-lock-format.mjs && node test-stale-lock.mjs && node test-task-name-limit.mjs && node test-task-name-limit-profile.mjs && node test-delete-profile.mjs && node test-execution-hardening.mjs && node test-path-safety.mjs && node test-watch-paths.mjs && node test-windows-oem.mjs && node test-schtasks-errors.mjs && node test-schtasks-locales.mjs && node test-cron-to-schtasks.mjs && node test-mac-cron.mjs && node test-mac-launchctl.mjs && node test-at-fallback.mjs && node test-shutdown.mjs && node test-dual-entry.mjs && node test-v1-integration.mjs && node test-usage-from-log.mjs && node test-posix-e2e.mjs && node test-model-validation.mjs && node test-run-now.mjs && node test-task-name-collision.mjs && node test-pause-one-shot.mjs && node test-package-exports.mjs && node test-registry-resilience.mjs && node test-posix-create-rollback.mjs && node test-workflows.mjs && node test-dag-latest-history.mjs && node test-retry-counter.mjs && node test-models-config.mjs && node test-posix-cron.mjs && node test-migrate-partial.mjs && node test-windows-locales.mjs && node test-pipeline.mjs && node test-at-e2e.mjs && node test-worktree.mjs && node test-guards.mjs && node test-w4.mjs",
92
+ "test": "node test-sqlite.mjs && node test-user-version.mjs && node test-run-state.mjs && node test-run-journal.mjs && node test-run-resume.mjs && node test-step-idempotency.mjs && node test-run-dlq.mjs && node test-run-context.mjs && node test-dlq-gui.mjs && node test-pause-gui.mjs && node test-router-rules.mjs && node test-capability-map.mjs && node test-planner.mjs && node test-escalation.mjs && node test-router-dispatch.mjs && node test-execution-pipeline.mjs && node test-mission-run.mjs && node test-crash-recovery.mjs && node test-prompt-argv.mjs && node test-ps-watchdog.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-permissions-policy.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-budget.mjs && node test-savings.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-dedup.mjs && node test-notifications-embedding.mjs && node test-notifications-summary.mjs && node test-settings.mjs && node test-notifications-v3.mjs && node test-triage.mjs && node test-triage-rules.mjs && node test-triage-compare.mjs && node test-triage-chain.mjs && node test-triage-shadow.mjs && node test-triage-audit.mjs && node test-triage-async.mjs && node test-local-ai.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-self-analysis.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-trust.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-dashboard-xss.mjs && node test-profile-isolation.mjs && node test-docs.mjs && node test-feedback.mjs && node test-feedback-worker.mjs && node test-glob.mjs && node test-git-trigger.mjs && node test-window-v3.mjs && node test-i18n.mjs && node test-gui-bundle.mjs && node test-lock-format.mjs && node test-stale-lock.mjs && node test-task-name-limit.mjs && node test-task-name-limit-profile.mjs && node test-delete-profile.mjs && node test-execution-hardening.mjs && node test-path-safety.mjs && node test-watch-paths.mjs && node test-windows-oem.mjs && node test-schtasks-errors.mjs && node test-schtasks-locales.mjs && node test-cron-to-schtasks.mjs && node test-mac-cron.mjs && node test-mac-launchctl.mjs && node test-at-fallback.mjs && node test-shutdown.mjs && node test-dual-entry.mjs && node test-v1-integration.mjs && node test-usage-from-log.mjs && node test-posix-e2e.mjs && node test-model-validation.mjs && node test-run-now.mjs && node test-task-name-collision.mjs && node test-pause-one-shot.mjs && node test-package-exports.mjs && node test-registry-resilience.mjs && node test-posix-create-rollback.mjs && node test-workflows.mjs && node test-dag-latest-history.mjs && node test-retry-counter.mjs && node test-models-config.mjs && node test-posix-cron.mjs && node test-migrate-partial.mjs && node test-windows-locales.mjs && node test-pipeline.mjs && node test-at-e2e.mjs && node test-worktree.mjs && node test-guards.mjs && node test-w4.mjs && node test-validation.mjs && node test-eslint-baseline.mjs && node test-test-plan.mjs",
90
93
  "test:sqlite": "node test-sqlite.mjs",
91
94
  "test:user-version": "node test-user-version.mjs",
92
95
  "test:run-state": "node test-run-state.mjs",
@@ -115,7 +118,10 @@
115
118
  "test:matrix-lifecycle": "node test-matrix-lifecycle.mjs",
116
119
  "test:matrix-sync": "node test-matrix-sync.mjs",
117
120
  "test:retention": "node test-retention.mjs",
121
+ "test:history-load": "node test-history-load.mjs",
118
122
  "test:metrics": "node test-metrics.mjs",
123
+ "test:budget": "node test-budget.mjs",
124
+ "test:validation": "node test-validation.mjs",
119
125
  "test:schedule-v2": "node test-schedule-v2.mjs",
120
126
  "test:posix-cron": "node test-posix-cron.mjs",
121
127
  "test:migrate-partial": "node test-migrate-partial.mjs",
@@ -139,6 +145,7 @@
139
145
  "test:profiles": "node test-profiles.mjs",
140
146
  "test:env": "node test-env.mjs",
141
147
  "test:agent": "node test-agent-tools.mjs",
148
+ "test:shutdown-gate": "node test-shutdown-gate.mjs",
142
149
  "test:skill": "node test-skill.mjs",
143
150
  "test:integrations": "node test-integrations.mjs",
144
151
  "test:session-continuity": "node test-session-continuity.mjs",
@@ -149,12 +156,16 @@
149
156
  "test:dag-latest-history": "node test-dag-latest-history.mjs",
150
157
  "test:retry-counter": "node test-retry-counter.mjs",
151
158
  "test:models-config": "node test-models-config.mjs",
159
+ "test:models-analysis": "node test-models-analysis.mjs",
152
160
  "test:dashboard": "node test-dashboard.mjs",
153
161
  "test:dashboard-dag": "node test-dashboard-dag.mjs",
154
162
  "test:dashboard-json": "node test-dashboard-json.mjs",
155
163
  "test:dashboard-xss": "node test-dashboard-xss.mjs",
156
164
  "test:profile-isolation": "node test-profile-isolation.mjs",
157
165
  "test:docs": "node test-docs.mjs",
166
+ "test:feedback": "node test-feedback.mjs",
167
+ "test:feedback-worker": "node test-feedback-worker.mjs",
168
+ "test:eslint-baseline": "node test-eslint-baseline.mjs",
158
169
  "test:glob": "node test-glob.mjs",
159
170
  "test:git-trigger": "node test-git-trigger.mjs",
160
171
  "test:window-v3": "node test-window-v3.mjs",
@@ -180,6 +191,7 @@
180
191
  "test:task-name-collision": "node test-task-name-collision.mjs",
181
192
  "test:pause-one-shot": "node test-pause-one-shot.mjs",
182
193
  "test:package-exports": "node test-package-exports.mjs",
194
+ "test:prod-install": "node test-prod-install.mjs",
183
195
  "test:registry-resilience": "node test-registry-resilience.mjs",
184
196
  "test:posix-create-rollback": "node test-posix-create-rollback.mjs",
185
197
  "test:workflows": "node test-workflows.mjs",
@@ -207,6 +219,7 @@
207
219
  "@typescript-eslint/eslint-plugin": "^8.73.0",
208
220
  "@typescript-eslint/parser": "^8.73.0",
209
221
  "eslint": "^10.15.0",
222
+ "gpt-tokenizer": "^4.1.2",
210
223
  "solid-js": "^1.9.0",
211
224
  "typescript": "^5.9.3",
212
225
  "typescript-eslint": "^8.73.0",
@@ -0,0 +1,139 @@
1
+ /**
2
+ * QA-A2.0 — храповик (ratchet) для предупреждений ESLint.
3
+ *
4
+ * Сравнивает текущие счётчики `eslint src` с зафиксированными в
5
+ * `eslint-baseline.json` и падает, если где-то появилось НОВОЕ предупреждение.
6
+ * Уменьшения разрешены и по ним baseline обновляется вручную:
7
+ *
8
+ * npm run lint:baseline # проверить (используется в CI)
9
+ * npm run lint:baseline:update # перезаписать baseline после уменьшения
10
+ *
11
+ * Исторический старт эпика QA-A2 — 826 предупреждений; он лежит в поле
12
+ * epicStartWarnings как справка. Гейт сравнивает с актуальными числами:
13
+ * после QA-A2.1 их 543, и каждая следующая подзадача (A2.2-A2.5) опускает
14
+ * планку. Гейт снимается в QA-A2.7.
15
+ *
16
+ * Запуск: node scripts/check-eslint-baseline.mjs [--update]
17
+ */
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import url from "node:url";
21
+ import { ESLint } from "eslint";
22
+
23
+ const root = path.dirname(path.dirname(url.fileURLToPath(import.meta.url)));
24
+ export const baselinePath = path.join(root, "eslint-baseline.json");
25
+ export const EPIC_START_WARNINGS = 826;
26
+
27
+ /** Путь файла в baseline — всегда относительно корня и с прямыми слешами. */
28
+ export function relativePath(filePath) {
29
+ return path.relative(root, filePath).split(path.sep).join("/");
30
+ }
31
+
32
+ /** Собирает счётчики из результатов ESLint. Чистая функция — тестируется отдельно. */
33
+ export function collect(results) {
34
+ const byFile = {};
35
+ const byRule = {};
36
+ const byFileRule = {};
37
+ let warnings = 0;
38
+ let errors = 0;
39
+
40
+ for (const result of results) {
41
+ const file = relativePath(result.filePath);
42
+ for (const message of result.messages) {
43
+ if (message.severity === 2) errors += 1;
44
+ else if (message.severity === 1) warnings += 1;
45
+
46
+ const rule = message.ruleId ?? "(fatal)";
47
+ byRule[rule] = (byRule[rule] ?? 0) + 1;
48
+ byFile[file] = (byFile[file] ?? 0) + 1;
49
+ byFileRule[file] ??= {};
50
+ byFileRule[file][rule] = (byFileRule[file][rule] ?? 0) + 1;
51
+ }
52
+ }
53
+
54
+ return { warnings, errors, byRule, byFile, byFileRule };
55
+ }
56
+
57
+ /**
58
+ * Сравнивает текущие счётчики с baseline. Любой рост — регрессия.
59
+ * Уменьшения разрешены и по ним baseline обновляется вручную.
60
+ */
61
+ export function compare(current, baseline) {
62
+ const problems = [];
63
+ const allowedTotals = baseline.totals ?? { warnings: 0, errors: 0 };
64
+
65
+ if (current.errors > 0) {
66
+ problems.push(`ESLint errors: ${current.errors} (в baseline ${allowedTotals.errors})`);
67
+ }
68
+ if (current.warnings > allowedTotals.warnings) {
69
+ problems.push(
70
+ `всего warning: ${current.warnings} > baseline ${allowedTotals.warnings}`
71
+ );
72
+ }
73
+ for (const [rule, count] of Object.entries(current.byRule ?? {})) {
74
+ const allowed = baseline.byRule?.[rule] ?? 0;
75
+ if (count > allowed) problems.push(`${rule}: ${count} > baseline ${allowed}`);
76
+ }
77
+ for (const [file, count] of Object.entries(current.byFile ?? {})) {
78
+ const allowed = baseline.byFile?.[file] ?? 0;
79
+ if (count > allowed) problems.push(`${file}: ${count} > baseline ${allowed}`);
80
+ }
81
+ for (const [file, rules] of Object.entries(current.byFileRule ?? {})) {
82
+ for (const [rule, count] of Object.entries(rules)) {
83
+ const allowed = baseline.byFileRule?.[file]?.[rule] ?? 0;
84
+ if (count > allowed) {
85
+ problems.push(`${file} [${rule}]: ${count} > baseline ${allowed}`);
86
+ }
87
+ }
88
+ }
89
+
90
+ return { ok: problems.length === 0, problems };
91
+ }
92
+
93
+ /** Собирает документ baseline из текущих результатов линтера. */
94
+ export function makeBaseline(current) {
95
+ return {
96
+ task: "QA-A2.0",
97
+ epicStartWarnings: EPIC_START_WARNINGS,
98
+ note:
99
+ "Ratchet: новое предупреждение — красный CI. После уменьшения счётчика " +
100
+ "обновить через npm run lint:baseline:update. Гейт снимается в QA-A2.7.",
101
+ totals: { warnings: current.warnings, errors: current.errors },
102
+ byRule: current.byRule,
103
+ byFile: current.byFile,
104
+ byFileRule: current.byFileRule,
105
+ };
106
+ }
107
+
108
+ const isMain =
109
+ process.argv[1] &&
110
+ path.resolve(process.argv[1]) === url.fileURLToPath(import.meta.url);
111
+
112
+ if (isMain) {
113
+ const eslint = new ESLint();
114
+ const results = await eslint.lintFiles(["src"]);
115
+ const current = collect(results);
116
+
117
+ if (process.argv.includes("--update")) {
118
+ fs.writeFileSync(baselinePath, JSON.stringify(makeBaseline(current), null, 2) + "\n");
119
+ console.log(
120
+ `QA-A2.0: baseline обновлён — ${current.warnings} warning, ${current.errors} error`
121
+ );
122
+ process.exit(0);
123
+ }
124
+
125
+ const baseline = JSON.parse(fs.readFileSync(baselinePath, "utf8"));
126
+ const { ok, problems } = compare(current, baseline);
127
+ if (ok) {
128
+ const saved = baseline.totals.warnings - current.warnings;
129
+ console.log(
130
+ `QA-A2.0: новых предупреждений нет — ${current.warnings} warning ` +
131
+ `(baseline ${baseline.totals.warnings}${saved > 0 ? `, -${saved}` : ""})`
132
+ );
133
+ process.exit(0);
134
+ }
135
+ console.error("QA-A2.0: обнаружены новые предупреждения ESLint:");
136
+ for (const problem of problems) console.error(` - ${problem}`);
137
+ console.error("Если уменьшение осознанное — npm run lint:baseline:update");
138
+ process.exit(1);
139
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * TP-6.2 — генератор счётчиков TEST-PLAN.md по маркерам.
3
+ *
4
+ * node scripts/gen-test-plan-counters.mjs # JSON в stdout
5
+ * node scripts/gen-test-plan-counters.mjs --write # обновить блок между маркерами
6
+ * node scripts/gen-test-plan-counters.mjs --out <file> # записать JSON в файл
7
+ *
8
+ * Маркеры в TEST-PLAN.md:
9
+ * <!-- counters:start -->
10
+ * <!-- counters:end -->
11
+ *
12
+ * Скрипт только считает фактические значения из кода/плана и не меняет остальной текст.
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import url from "node:url";
17
+
18
+ const root = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..");
19
+ const planPath = path.join(root, "TEST-PLAN.md");
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
21
+ const plan = fs.readFileSync(planPath, "utf8");
22
+
23
+ const section = (title, next) => {
24
+ const from = plan.indexOf(title);
25
+ if (from < 0) return "";
26
+ const to = next ? plan.indexOf(next, from + title.length) : plan.length;
27
+ return plan.slice(from, to < 0 ? plan.length : to);
28
+ };
29
+
30
+ const appendixA = section("## Приложение A.", "## Приложение B.");
31
+ const appendixB = section("## Приложение B.", "## Приложение C.");
32
+ const appendixC = section("## Приложение C.", "---");
33
+ const coverage = section("## 5. Матрица покрытия автотестами", "## 6.");
34
+
35
+ const backtickNames = (text) =>
36
+ [...text.matchAll(/`([a-z][a-z0-9_-]+)`/g)].map((m) => m[1]);
37
+ const unique = (xs) => [...new Set(xs)];
38
+
39
+ const testFiles = fs
40
+ .readdirSync(root)
41
+ .filter((f) => /^test-.*\.mjs$/.test(f))
42
+ .sort();
43
+ const npmTestScripts = Object.keys(pkg.scripts ?? {}).filter((k) => k.startsWith("test"));
44
+ const rpcMethods = unique(backtickNames(appendixA)).filter((n) => /^[a-z][a-z0-9_]*$/.test(n));
45
+ const mcpTools = unique(backtickNames(appendixB)).filter((n) => /^[a-z][a-z0-9_]*$/.test(n));
46
+ const httpEndpoints = unique(
47
+ [...appendixC.matchAll(/`\s*(?:GET|POST)\s+([^`]+)`/g)].map((m) => m[1].trim()),
48
+ );
49
+ const coverageEntries = unique(
50
+ [...coverage.matchAll(/^\|\s*`([^`]+\.mjs)`/gm)].map((m) => m[1]),
51
+ );
52
+
53
+ const server = fs.readFileSync(path.join(root, "src", "server.ts"), "utf8");
54
+ const literalEndpoints = new Set(
55
+ [...server.matchAll(/pathname\s*===\s*"([^"]+)"/g)].map((m) => m[1]),
56
+ );
57
+ const paramEndpoints = new Set(
58
+ [...server.matchAll(/pathname\.startsWith\("([^"]+)"\)/g)].map((m) => m[1]),
59
+ );
60
+ const codeEndpoints = unique([...literalEndpoints, ...paramEndpoints]);
61
+
62
+ const counters = {
63
+ generatedAt: new Date().toISOString(),
64
+ pluginVersion: pkg.version,
65
+ schemaVersion:
66
+ Number(
67
+ /export const SCHEMA_VERSION = (\d+)/.exec(
68
+ fs.readFileSync(path.join(root, "src", "db", "schema.ts"), "utf8"),
69
+ )?.[1],
70
+ ) ?? null,
71
+ testFiles: testFiles.length,
72
+ npmTestScripts: npmTestScripts.length,
73
+ mcpToolsPlan: mcpTools.length,
74
+ rpcMethodsPlan: rpcMethods.length,
75
+ httpEndpointsAppendix: httpEndpoints.length,
76
+ httpEndpointsCode: codeEndpoints.length,
77
+ coverageEntries: coverageEntries.length,
78
+ };
79
+
80
+ const json = JSON.stringify(counters, null, 2);
81
+ const args = process.argv.slice(2);
82
+
83
+ if (args.includes("--write")) {
84
+ const start = "<!-- counters:start -->";
85
+ const end = "<!-- counters:end -->";
86
+ if (!plan.includes(start) || !plan.includes(end)) {
87
+ console.error("В TEST-PLAN.md нет маркеров counters:start / counters:end");
88
+ process.exit(2);
89
+ }
90
+ const before = plan.slice(0, plan.indexOf(start) + start.length);
91
+ const after = plan.slice(plan.indexOf(end));
92
+ const table = [
93
+ "",
94
+ "| Счётчик | Значение | Источник |",
95
+ "|---|---|---|",
96
+ `| MCP-инструментов | ${counters.mcpToolsPlan} | Приложение B |`,
97
+ `| RPC-методов | ${counters.rpcMethodsPlan} | Приложение A |`,
98
+ `| HTTP-эндпоинтов | ${counters.httpEndpointsAppendix} | Приложение C |`,
99
+ `| Файлов test-*.mjs | ${counters.testFiles} | корень репозитория |`,
100
+ `| npm-скриптов test* | ${counters.npmTestScripts} | package.json |`,
101
+ `| Покрытие в §5 | ${counters.coverageEntries} | TEST-PLAN §5 |`,
102
+ `| SCHEMA_VERSION | ${counters.schemaVersion} | src/db/schema.ts |`,
103
+ "",
104
+ ].join("\n");
105
+ fs.writeFileSync(planPath, before + table + after, "utf8");
106
+ console.log(`Счётчики обновлены в TEST-PLAN.md:\n${table}`);
107
+ } else {
108
+ const outIdx = args.indexOf("--out");
109
+ if (outIdx >= 0 && args[outIdx + 1]) {
110
+ const out = path.resolve(root, args[outIdx + 1]);
111
+ fs.mkdirSync(path.dirname(out), { recursive: true });
112
+ fs.writeFileSync(out, json + "\n", "utf8");
113
+ console.log(`Записано: ${out}`);
114
+ } else {
115
+ console.log(json);
116
+ }
117
+ }
@@ -0,0 +1,37 @@
1
+ # QA-3.8.2: resilient GitHub Actions fetch (ECONNRESET retry + timeout).
2
+ $ErrorActionPreference = 'Stop'
3
+ $out = Join-Path (Get-Location) 'github-ci-runs.json'
4
+ $headers = @{ 'User-Agent' = 'agent-steward-github-ci-check'; 'Accept' = 'application/vnd.github+json' }
5
+ $uri = 'https://api.github.com/repos/DeadSno/agent-steward/actions/runs?per_page=5'
6
+ $body = $null
7
+ for ($i = 1; $i -le 4; $i++) {
8
+ try {
9
+ $body = Invoke-RestMethod -Uri $uri -Headers $headers -TimeoutSec 30
10
+ break
11
+ } catch {
12
+ Write-Warning "GitHub fetch attempt ${i}: $($_.Exception.Message)"
13
+ if ($i -eq 4) { throw }
14
+ Start-Sleep -Seconds (2 * $i)
15
+ }
16
+ }
17
+ $since = (Get-Date).ToUniversalTime().AddHours(-24)
18
+ $runs = @($body.workflow_runs | Where-Object { [datetime]::Parse($_.created_at).ToUniversalTime() -ge $since })
19
+ $jobs = @()
20
+ foreach ($run in $runs) {
21
+ $j = $null
22
+ for ($k = 1; $k -le 3; $k++) {
23
+ try {
24
+ $j = Invoke-RestMethod -Uri ("https://api.github.com/repos/DeadSno/agent-steward/actions/runs/$($run.id)/jobs") -Headers $headers -TimeoutSec 30
25
+ break
26
+ } catch {
27
+ Write-Warning "Jobs fetch attempt ${k}: $($_.Exception.Message)"
28
+ if ($k -eq 3) { $j = @{ jobs = @() }; break }
29
+ Start-Sleep -Seconds (2 * $k)
30
+ }
31
+ }
32
+ foreach ($job in $j.jobs) {
33
+ $jobs += [pscustomobject]@{ runId = $run.id; name = $job.name; conclusion = $job.conclusion; url = $job.html_url; createdAt = $run.created_at }
34
+ }
35
+ }
36
+ $jobs | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $out -Encoding UTF8
37
+ Write-Output "Fetched $($jobs.Count) jobs into $out"