agent-steward 0.0.4 → 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 (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -15,6 +15,7 @@ import {
15
15
  type SavingsRecord,
16
16
  type SavingsReport,
17
17
  } from "./savings.js";
18
+ import { t } from "../i18n.js";
18
19
 
19
20
  // ==================== Типы ====================
20
21
 
@@ -24,13 +25,38 @@ export interface HealthScore {
24
25
  score: number;
25
26
  /** Описание уровня здоровья. */
26
27
  level: "excellent" | "good" | "fair" | "poor" | "critical";
27
- /** Детальные метрики, из которых сложился балл. */
28
+ /**
29
+ * Детальные метрики, из которых сложился балл.
30
+ *
31
+ * ВАЖНО (QA 2026-11-19, roadmap-qa-01; уточнено QA-P1.4): successRate/errorRate —
32
+ * это НОРМАЛИЗОВАННЫЕ БАЛЛЫ 0..100 (чем выше, тем лучше; обратная совместимость
33
+ * с self_analysis tool), а avgDurationMs/timeoutRate/crashRecoveryRate —
34
+ * РЕАЛЬНЫЕ значения из отчёта (мс и доли 0..1), ранее сюда ошибочно писались
35
+ * score-значения, из-за чего avgDurationMs показывал 66 вместо 101597.
36
+ *
37
+ * QA-P1.4: `errorRate` — НЕ доля ошибок, а инвертированный балл
38
+ * `100 - 100 * error / total`. Поэтому при 322 success / 250 error из 573
39
+ * получаются `successRate=56.2` и `errorRate=56.37` — это согласуемые значения:
40
+ * доля ошибок 43.63%, а балл ошибок 56.37. Не путать с `totals.errorRate`,
41
+ * если он когда-либо будет добавлен как реальная доля.
42
+ */
28
43
  components: {
44
+ /** Балл успешности 0..100 (нормализованный). */
29
45
  successRate: number;
46
+ /** Балл частоты ошибок 0..100 (нормализованный, чем выше, тем меньше ошибок). */
30
47
  errorRate: number;
48
+ /** Реальная средняя длительность запуска в мс. */
31
49
  avgDurationMs: number;
50
+ /** Реальная доля таймаутов 0..1. */
32
51
  timeoutRate: number;
52
+ /** Реальная доля прерванных (crash recovery) запусков 0..1. */
33
53
  crashRecoveryRate: number;
54
+ /** Балл длительности 0..100 (нормализованный, использовался в score). */
55
+ avgDurationScore: number;
56
+ /** Балл таймаутов 0..100 (нормализованный). */
57
+ timeoutScore: number;
58
+ /** Балл восстановления после сбоев 0..100 (нормализованный). */
59
+ crashRecoveryScore: number;
34
60
  };
35
61
  /** Рекомендации по улучшению. */
36
62
  recommendations: string[];
@@ -112,11 +138,16 @@ export interface SelfAnalysisReport {
112
138
  recommendations: Recommendation[];
113
139
  /** Краткое резюме. */
114
140
  summary: string;
115
- /** Метаданные источников данных. */
141
+ /** Метаданные источников данных (PL-13/PL-29/PL-31: единицы указаны в комментариях). */
116
142
  sources: {
143
+ /** Записей истории всего (до фильтрации по окну). */
117
144
  historyRecords: number;
145
+ /** Записей истории внутри окна days. */
118
146
  recordsInWindow: number;
147
+ /** Число definition задач (НЕ уникальных имён в истории). */
119
148
  tasksAnalyzed: number;
149
+ /** Явное имя того же счётчика definition — без двусмысленности «analyzed». */
150
+ taskDefinitions: number;
120
151
  };
121
152
  }
122
153
 
@@ -138,12 +169,21 @@ export interface SelfAnalysisOptions {
138
169
  export function calculateHealthScore(report: AnalyticsReport): HealthScore {
139
170
  const { totals, tasks, errors } = report;
140
171
 
141
- // Компоненты здоровья (0-100)
172
+ // Реальные метрики (то, что видит пользователь в self_analysis).
173
+ const realAvgDurationMs = totals.avgDurationMs;
174
+ const realTimeoutRate =
175
+ errors.filter((e) => e.message.includes("timeout")).length /
176
+ Math.max(1, totals.total);
177
+ const realCrashRecoveryRate =
178
+ errors.filter((e) => e.message.includes("Прервано")).length /
179
+ Math.max(1, totals.total);
180
+
181
+ // Компоненты здоровья — нормализованные баллы 0..100 (обратная совместимость).
142
182
  const successRateScore = totals.successRate;
143
183
  const errorRateScore = Math.max(0, 100 - (totals.error / Math.max(1, totals.total)) * 100);
144
- const avgDurationScore = Math.min(100, Math.max(0, 100 - (totals.avgDurationMs / 300000) * 100)); // 5 минут = 0 баллов
145
- const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("timeout")).length / Math.max(1, totals.total)) * 100));
146
- const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("Прервано")).length / Math.max(1, totals.total)) * 100));
184
+ const avgDurationScore = Math.min(100, Math.max(0, 100 - (realAvgDurationMs / 300000) * 100)); // 5 минут = 0 баллов
185
+ const timeoutRateScore = Math.min(100, Math.max(0, 100 - realTimeoutRate * 100));
186
+ const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - realCrashRecoveryRate * 100));
147
187
 
148
188
  // Взвешенная сумма
149
189
  const score = Math.round(
@@ -165,19 +205,19 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
165
205
  // Рекомендации
166
206
  const recommendations: string[] = [];
167
207
  if (successRateScore < 80) {
168
- recommendations.push("Повысьте успешность запусков: проверьте Quality Gate и логи ошибок");
208
+ recommendations.push(t("selfAnalysis.rec.successRate"));
169
209
  }
170
210
  if (errorRateScore < 80) {
171
- recommendations.push("Снизьте частоту ошибок: добавьте retryCount для флакких задач");
211
+ recommendations.push(t("selfAnalysis.rec.errorRate"));
172
212
  }
173
213
  if (avgDurationScore < 70) {
174
- recommendations.push("Оптимизируйте длительность: разбейте длинные задачи или увеличьте timeoutSeconds");
214
+ recommendations.push(t("selfAnalysis.rec.duration"));
175
215
  }
176
216
  if (timeoutRateScore < 80) {
177
- recommendations.push("Уменьшите количество таймаутов: увеличьте timeoutSeconds или упростите промпты");
217
+ recommendations.push(t("selfAnalysis.rec.timeouts"));
178
218
  }
179
219
  if (crashRecoveryRateScore < 90) {
180
- recommendations.push("Снизьте количество прерванных запусков: проверьте стабильность системы");
220
+ recommendations.push(t("selfAnalysis.rec.crashes"));
181
221
  }
182
222
 
183
223
  return {
@@ -186,9 +226,14 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
186
226
  components: {
187
227
  successRate: successRateScore,
188
228
  errorRate: errorRateScore,
189
- avgDurationMs: avgDurationScore,
190
- timeoutRate: timeoutRateScore,
191
- crashRecoveryRate: crashRecoveryRateScore,
229
+ // Реальные значения (исправление roadmap-qa-01).
230
+ avgDurationMs: realAvgDurationMs,
231
+ timeoutRate: realTimeoutRate,
232
+ crashRecoveryRate: realCrashRecoveryRate,
233
+ // Нормализованные баллы (прежняя семантика этих трёх полей).
234
+ avgDurationScore,
235
+ timeoutScore: timeoutRateScore,
236
+ crashRecoveryScore: crashRecoveryRateScore,
192
237
  },
193
238
  recommendations,
194
239
  };
@@ -691,7 +736,10 @@ export function generateSelfAnalysisReport(
691
736
  sources: {
692
737
  historyRecords: records.length,
693
738
  recordsInWindow: analyticsReport.sources.recordsInWindow,
694
- tasksAnalyzed: analyticsReport.tasks.length,
739
+ // PL-13/PL-29/PL-31: options.tasks — это definitions, а analyticsReport.tasks —
740
+ // задачи, попавшие в историю; последнее число могло быть больше на 15+.
741
+ tasksAnalyzed: options.tasks?.length ?? analyticsReport.tasks.length,
742
+ taskDefinitions: options.tasks?.length ?? analyticsReport.tasks.length,
695
743
  },
696
744
  };
697
745
  }
@@ -705,37 +753,35 @@ function generateSummary(
705
753
  const parts: string[] = [];
706
754
 
707
755
  // Здоровье
708
- const levelNames = {
709
- excellent: "отличное",
710
- good: "хорошее",
711
- fair: "удовлетворительное",
712
- poor: "плохое",
713
- critical: "критическое",
714
- };
715
- parts.push(`Здоровье системы: ${levelNames[health.level]} (${health.score}/100)`);
756
+ parts.push(
757
+ t("selfAnalysis.health", {
758
+ level: t(`selfAnalysis.level.${health.level}`),
759
+ score: health.score,
760
+ }),
761
+ );
716
762
 
717
763
  // Аномалии
718
764
  if (anomalies.length > 0) {
719
765
  const highSeverity = anomalies.filter(a => a.severity > 70).length;
720
766
  if (highSeverity > 0) {
721
- parts.push(`Обнаружено ${highSeverity} критических аномалий`);
767
+ parts.push(t("selfAnalysis.anomaliesHigh", { count: highSeverity }));
722
768
  } else {
723
- parts.push(`Обнаружено ${anomalies.length} аномалий (все некритические)`);
769
+ parts.push(t("selfAnalysis.anomaliesAll", { count: anomalies.length }));
724
770
  }
725
771
  } else {
726
- parts.push("Критических аномалий не обнаружено");
772
+ parts.push(t("selfAnalysis.noAnomalies"));
727
773
  }
728
774
 
729
775
  // Тренды
730
- const degradingTrends = trends.filter(t => t.direction === "degrading").length;
776
+ const degradingTrends = trends.filter(trend => trend.direction === "degrading").length;
731
777
  if (degradingTrends > 0) {
732
- parts.push(`${degradingTrends} метрик ухудшаются`);
778
+ parts.push(t("selfAnalysis.degrading", { count: degradingTrends }));
733
779
  }
734
780
 
735
781
  // Рекомендации
736
782
  const highPriority = recommendations.filter(r => r.priority >= 7).length;
737
783
  if (highPriority > 0) {
738
- parts.push(`${highPriority} рекомендаций высокого приоритета`);
784
+ parts.push(t("selfAnalysis.highPriority", { count: highPriority }));
739
785
  }
740
786
 
741
787
  return parts.join(". ") + ".";
@@ -5,18 +5,53 @@
5
5
  * in-process операций (запуск задачи, matrix, DAG-триггер) перед закрытием
6
6
  * SQLite и HTTP-сервера. Внешние процессы планировщика ОС эти ворота не
7
7
  * отслеживают: их жизненным циклом управляет сама ОС.
8
+ *
9
+ * PL-10/QV-2: состояние ворот наблюдаемо (причина, время, PID, активные
10
+ * операции), а «зависшие» ворота (begin без complete, нет активных операций,
11
+ * прошло больше STALE_MS) автоматически открываются при первом же запросе.
12
+ * Так hot-reload каталога инструментов не блокирует in-process запуски,
13
+ * пока ОС-планировщик продолжает тикать.
8
14
  */
9
15
 
16
+ /** Порог «зависших» ворот; переопределяется для тестов через env. */
17
+ const STALE_GATE_MS = Number(process.env.AGENT_STEWARD_SHUTDOWN_STALE_MS ?? 30_000);
18
+
10
19
  export interface ShutdownWaitResult {
11
20
  timedOut: boolean;
12
21
  remaining: number;
13
22
  }
14
23
 
24
+ export interface ShutdownGateState {
25
+ shuttingDown: boolean;
26
+ /** Причина, по которой ворота были закрыты (обычно «plugin unload»). */
27
+ reason: string | null;
28
+ /** ISO-время вызова begin(). */
29
+ startedAt: string | null;
30
+ /** PID процесса, в котором ворота закрыты. */
31
+ pid: number;
32
+ /** Число ещё выполняемых in-process операций. */
33
+ activeCount: number;
34
+ /** true после complete() — выгрузка действительно завершена. */
35
+ unloadCompleted: boolean;
36
+ /** Диагностика последнего автоматического сброса. */
37
+ lastAutoReset: string | null;
38
+ }
39
+
15
40
  export interface ShutdownGate {
16
- /** true после begin(): новые запуски должны отклоняться. */
41
+ /** true после begin(), пока ворота не открылись повторно. */
17
42
  isShuttingDown(): boolean;
18
43
  /** Переводит ворота в режим выгрузки. */
19
- begin(): void;
44
+ begin(reason?: string): void;
45
+ /** Подтверждает, что выгрузка завершена (запрещает автосброс). */
46
+ complete(): void;
47
+ /**
48
+ * PL-45: принудительно открывает ворота. Вызывается при повторной
49
+ * регистрации плагина (V2 setup / V1 hooks), когда хост ранее вызвал
50
+ * begin()+complete(), но модуль остался в памяти (Code Mode / hot-reload).
51
+ */
52
+ reset(): void;
53
+ /** Снимок состояния для диагностики и структурированных ошибок. */
54
+ state(): ShutdownGateState;
20
55
  /** Учитывает промис до его завершения (успех или ошибка). */
21
56
  track<T>(promise: Promise<T>): Promise<T>;
22
57
  /** Сколько операций ещё выполняется. */
@@ -27,13 +62,64 @@ export interface ShutdownGate {
27
62
 
28
63
  export function createShutdownGate(): ShutdownGate {
29
64
  let shuttingDown = false;
65
+ let reason: string | null = null;
66
+ let startedAtMs: number | null = null;
67
+ let unloadCompleted = false;
68
+ let lastAutoReset: string | null = null;
30
69
  const active = new Set<Promise<unknown>>();
31
70
 
71
+ const maybeResetStale = (): void => {
72
+ if (
73
+ !shuttingDown ||
74
+ active.size !== 0 ||
75
+ startedAtMs === null ||
76
+ Date.now() - startedAtMs < STALE_GATE_MS
77
+ ) {
78
+ return;
79
+ }
80
+ const waitedMs = Date.now() - startedAtMs;
81
+ lastAutoReset =
82
+ `ворота оставались закрытыми ${waitedMs} мс без активных операций ` +
83
+ (unloadCompleted
84
+ ? "после complete() без выгрузки модуля — автосброс в Code Mode"
85
+ : "и без complete() — автосброс после hot-reload");
86
+ shuttingDown = false;
87
+ reason = null;
88
+ startedAtMs = null;
89
+ };
90
+
32
91
  return {
33
- isShuttingDown: () => shuttingDown,
34
- begin: () => {
92
+ isShuttingDown: () => {
93
+ maybeResetStale();
94
+ return shuttingDown;
95
+ },
96
+ begin: (why = "plugin unload") => {
35
97
  shuttingDown = true;
98
+ reason = why;
99
+ startedAtMs = Date.now();
100
+ unloadCompleted = false;
101
+ },
102
+ complete: () => {
103
+ unloadCompleted = true;
104
+ },
105
+ reset: () => {
106
+ if (shuttingDown) {
107
+ lastAutoReset = "ворота открыты повторной регистрацией плагина (PL-45)";
108
+ }
109
+ shuttingDown = false;
110
+ reason = null;
111
+ startedAtMs = null;
112
+ unloadCompleted = false;
36
113
  },
114
+ state: () => ({
115
+ shuttingDown,
116
+ reason,
117
+ startedAt: startedAtMs === null ? null : new Date(startedAtMs).toISOString(),
118
+ pid: process.pid,
119
+ activeCount: active.size,
120
+ unloadCompleted,
121
+ lastAutoReset,
122
+ }),
37
123
  track<T>(promise: Promise<T>): Promise<T> {
38
124
  const tracked = promise.finally(() => {
39
125
  active.delete(tracked);
@@ -18,7 +18,18 @@ import { redactSecretsInText } from "./secrets.js";
18
18
  */
19
19
 
20
20
  /** События структурированного лога. */
21
- export type StructuredLogEvent = "run.started" | "run.finished" | "hook.received" | string;
21
+ export type StructuredLogEvent =
22
+ | "run.started"
23
+ | "run.finished"
24
+ | "hook.received"
25
+ | "matrix.started"
26
+ | "matrix.advanced"
27
+ | "matrix.queue_started"
28
+ | "matrix.cancelled"
29
+ | "matrix.aggregated"
30
+ | "matrix.aggregator_started"
31
+ | "matrix.error"
32
+ | string;
22
33
 
23
34
  export interface StructuredLogRecord {
24
35
  /** Время записи (ISO). */
@@ -39,6 +50,22 @@ export interface StructuredLogRecord {
39
50
  workspaceId?: string | null;
40
51
  preFlightStatus?: string;
41
52
  postFlightStatus?: string;
53
+ /**
54
+ * PL-7.2: реальный код завершения хуков. Диагностика Git уходит в stderr
55
+ * даже при успешном push — без разделения потоков «пуш не состоялся» и
56
+ * «Git пишет в stderr» неразличимы.
57
+ */
58
+ preFlightExitCode?: number | null;
59
+ /** PL-7.2: stdout beforeScript — отдельно от диагностики. */
60
+ preFlightStdout?: string;
61
+ /** PL-7.2: stderr beforeScript. */
62
+ preFlightStderr?: string;
63
+ /** PL-7.2: реальный код завершения afterScript (post-flight). */
64
+ postFlightExitCode?: number | null;
65
+ /** PL-7.2: stdout afterScript — отдельно от диагностики. */
66
+ postFlightStdout?: string;
67
+ /** PL-7.2: stderr afterScript — может содержать diagnostics успешного git push. */
68
+ postFlightStderr?: string;
42
69
  /** Источник события: schedule, dashboard, hook, cli, mcp и т.п. */
43
70
  source?: string;
44
71
  /** HTTP-статус ответа на hook.received. */
@@ -49,6 +76,12 @@ export interface StructuredLogRecord {
49
76
  payloadBytes?: number;
50
77
  /** Причина отказа/пропуска. */
51
78
  reason?: string;
79
+ /** Родительская задача матрицы (matrixId === task для событий matrix.*). */
80
+ matrixId?: string;
81
+ /** Имя клона матрицы, к которому относится событие. */
82
+ cloneName?: string;
83
+ /** Шаг матричного сценария: started, advanced, cancelled, aggregated и т.п. */
84
+ step?: string;
52
85
  }
53
86
 
54
87
  export interface ReadStructuredLogsFilter {
@@ -101,9 +134,9 @@ function rotateIfNeeded(): void {
101
134
  // Нет старого архива — не страшно.
102
135
  }
103
136
  fs.renameSync(STRUCTURED_LOG_FILE, STRUCTURED_LOG_ARCHIVE);
104
- } catch (err: any) {
137
+ } catch (err: unknown) {
105
138
  // ENOENT — файла ещё нет, это нормально.
106
- if (err?.code !== "ENOENT") warn("не удалось ротировать лог", err);
139
+ if ((err as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") warn("не удалось ротировать лог", err);
107
140
  }
108
141
  }
109
142
 
@@ -129,6 +162,20 @@ export function appendStructuredLog(
129
162
  if (typeof payload.reason === "string") {
130
163
  payload.reason = redactSecretsInText(payload.reason);
131
164
  }
165
+ // PL-7.2: потоки хуков тоже могут содержать токены/URL — применяем ту же
166
+ // редакцию, что и к error/reason, до записи в JSONL.
167
+ if (typeof payload.preFlightStdout === "string") {
168
+ payload.preFlightStdout = redactSecretsInText(payload.preFlightStdout);
169
+ }
170
+ if (typeof payload.preFlightStderr === "string") {
171
+ payload.preFlightStderr = redactSecretsInText(payload.preFlightStderr);
172
+ }
173
+ if (typeof payload.postFlightStdout === "string") {
174
+ payload.postFlightStdout = redactSecretsInText(payload.postFlightStdout);
175
+ }
176
+ if (typeof payload.postFlightStderr === "string") {
177
+ payload.postFlightStderr = redactSecretsInText(payload.postFlightStderr);
178
+ }
132
179
  fs.appendFileSync(STRUCTURED_LOG_FILE, `${JSON.stringify(payload)}\n`, "utf8");
133
180
  return true;
134
181
  } catch (err) {
@@ -137,14 +184,51 @@ export function appendStructuredLog(
137
184
  }
138
185
  }
139
186
 
187
+ /** PL-7.2: данные одного хука (pre/post-flight) для журнала. */
188
+ export interface HookOutputDetails {
189
+ /** Реальный код завершения процесса, а не «успех/ошибка» обёртки. */
190
+ exitCode: number | null;
191
+ stdout?: string;
192
+ stderr?: string;
193
+ }
194
+
195
+ /**
196
+ * PL-7.2: пишет отдельное событие `hook.output` с разделёнными stdout/stderr и
197
+ * реальным exit code. Обёртка вызывает его, когда хочет отличить «команда не
198
+ * выполнилась» от «команда выполнилась, но написала диагностику в stderr»
199
+ * (типичный случай git push под PowerShell $ErrorActionPreference='Stop').
200
+ */
201
+ export function appendHookOutputLog(
202
+ phase: "preFlight" | "postFlight",
203
+ task: string,
204
+ details: HookOutputDetails,
205
+ runId?: number,
206
+ ): boolean {
207
+ const base = { event: "hook.output", task, runId } as const;
208
+ if (phase === "postFlight") {
209
+ return appendStructuredLog({
210
+ ...base,
211
+ postFlightExitCode: details.exitCode,
212
+ postFlightStdout: details.stdout ?? "",
213
+ postFlightStderr: details.stderr ?? "",
214
+ });
215
+ }
216
+ return appendStructuredLog({
217
+ ...base,
218
+ preFlightExitCode: details.exitCode,
219
+ preFlightStdout: details.stdout ?? "",
220
+ preFlightStderr: details.stderr ?? "",
221
+ });
222
+ }
223
+
140
224
  function readLines(file: string): string[] {
141
225
  try {
142
226
  return fs
143
227
  .readFileSync(file, "utf8")
144
228
  .split(/\r?\n/)
145
229
  .filter((line) => line.trim().length > 0);
146
- } catch (err: any) {
147
- if (err?.code !== "ENOENT") warn(`не удалось прочитать ${file}`, err);
230
+ } catch (err: unknown) {
231
+ if ((err as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") warn(`не удалось прочитать ${file}`, err);
148
232
  return [];
149
233
  }
150
234
  }
@@ -418,8 +418,8 @@ export async function sendTelegramMessage(
418
418
  );
419
419
  }
420
420
  break;
421
- } catch (err: any) {
422
- if (err?.name === "AbortError") {
421
+ } catch (err: unknown) {
422
+ if ((err as Error | undefined)?.name === "AbortError") {
423
423
  throw new Error(
424
424
  t("notify.error.telegramTimeout", {
425
425
  seconds: Math.floor(timeoutMs / 1000),
@@ -65,8 +65,8 @@ function processAlive(pid: number): boolean {
65
65
  try {
66
66
  process.kill(pid, 0);
67
67
  return true;
68
- } catch (err: any) {
69
- return err?.code === "EPERM";
68
+ } catch (err: unknown) {
69
+ return (err as NodeJS.ErrnoException | undefined)?.code === "EPERM";
70
70
  }
71
71
  }
72
72
 
@@ -82,8 +82,8 @@ function acquireWorkerSlot(dir: string): string | null {
82
82
  fs.writeFileSync(fd, String(process.pid));
83
83
  fs.closeSync(fd);
84
84
  return slot;
85
- } catch (err: any) {
86
- if (err?.code !== "EEXIST") continue;
85
+ } catch (err: unknown) {
86
+ if ((err as NodeJS.ErrnoException | undefined)?.code !== "EEXIST") continue;
87
87
  let holder = 0;
88
88
  try {
89
89
  holder = parseInt(fs.readFileSync(slot, "utf8").trim(), 10);
@@ -245,7 +245,7 @@ export function scheduleTriageJob(
245
245
  const dir = options.tmpDir ?? os.tmpdir();
246
246
  pruneTriageArtifacts(dir);
247
247
  file = writeTriageJob(input, triage, { tmpDir: dir });
248
- } catch (err: any) {
248
+ } catch (err: unknown) {
249
249
  return {
250
250
  scheduled: false,
251
251
  error: err instanceof Error ? err.message : String(err),
@@ -267,7 +267,7 @@ export function scheduleTriageJob(
267
267
  // Если процесс не стартовал, файл задания останется сиротой — убираем.
268
268
  child.on?.("error", () => safeUnlink(file));
269
269
  return { scheduled: true, file };
270
- } catch (err: any) {
270
+ } catch (err: unknown) {
271
271
  safeUnlink(file);
272
272
  return {
273
273
  scheduled: false,
@@ -315,7 +315,7 @@ async function drainQueue(first: string): Promise<void> {
315
315
  const file: string = current;
316
316
  try {
317
317
  await runTriageJob(file);
318
- } catch (err: any) {
318
+ } catch (err: unknown) {
319
319
  console.error(
320
320
  `[agent-steward] triage worker: ${
321
321
  err instanceof Error ? err.message : String(err)
@@ -161,7 +161,7 @@ function parseVerdict(raw: string): TriageVerdict {
161
161
  let parsed: unknown;
162
162
  try {
163
163
  parsed = JSON.parse(text.slice(start, end + 1));
164
- } catch (err: any) {
164
+ } catch (err: unknown) {
165
165
  throw new ParseFailure(
166
166
  "invalid-json",
167
167
  `Ответ модели не парсится как JSON: ${err instanceof Error ? err.message : String(err)}`,
@@ -333,7 +333,7 @@ export async function classifyNotification(
333
333
  protocol,
334
334
  };
335
335
  }
336
- } catch (err: any) {
336
+ } catch (err: unknown) {
337
337
  const aborted = controller.signal.aborted;
338
338
  const failure: TriageFailure = aborted
339
339
  ? "timeout"
@@ -0,0 +1,70 @@
1
+ /**
2
+ * QV-11.1: офлайн-оценка размера поверхности инструментов без вызова платной
3
+ * модели. Точный tiktoken не нужен: нам важна сравнимая метрика «было/стало»
4
+ * и число description', чтобы видеть раздувание реестра.
5
+ */
6
+
7
+ export interface ToolSurfaceSpec {
8
+ name: string;
9
+ description?: string;
10
+ input?: unknown;
11
+ }
12
+
13
+ export interface ToolSurfaceMeasurement {
14
+ tools: number;
15
+ descriptionChars: number;
16
+ schemaChars: number;
17
+ descriptionCount: number;
18
+ estimatedTokens: number;
19
+ }
20
+
21
+ /** Резервная грубая оценка: ~4 символа на токен (только без токенайзера). */
22
+ export function estimateTokens(text: string): number {
23
+ return Math.ceil(text.length / 4);
24
+ }
25
+
26
+ export interface MeasureToolSurfaceOptions {
27
+ /** Реальный офлайн-токенайзер (например, encode из gpt-tokenizer). */
28
+ countTokens?: (text: string) => number;
29
+ }
30
+
31
+ export function measureToolSurface(
32
+ specs: readonly ToolSurfaceSpec[],
33
+ options: MeasureToolSurfaceOptions = {},
34
+ ): ToolSurfaceMeasurement {
35
+ let descriptionChars = 0;
36
+ let schemaChars = 0;
37
+ let descriptionCount = 0;
38
+
39
+ for (const spec of specs) {
40
+ if (spec.description) {
41
+ descriptionChars += spec.description.length;
42
+ descriptionCount += 1;
43
+ }
44
+ if (spec.input !== undefined) {
45
+ try {
46
+ schemaChars += JSON.stringify(spec.input).length;
47
+ } catch {
48
+ schemaChars += "[unserializable]".length;
49
+ }
50
+ }
51
+ }
52
+
53
+ return {
54
+ tools: specs.length,
55
+ descriptionChars,
56
+ schemaChars,
57
+ descriptionCount,
58
+ estimatedTokens: options.countTokens
59
+ ? options.countTokens(
60
+ specs
61
+ .map((spec) => `${spec.name} ${spec.description ?? ""} ${JSON.stringify(spec.input ?? null)}`)
62
+ .join("\n"),
63
+ )
64
+ : estimateTokens(
65
+ specs
66
+ .map((spec) => `${spec.name} ${spec.description ?? ""} ${JSON.stringify(spec.input ?? null)}`)
67
+ .join("\n"),
68
+ ),
69
+ };
70
+ }