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
@@ -36,8 +36,9 @@ const KEY_BYTES = 32;
36
36
  * используется из CLI/GUI/плагина, переписывать его на async нельзя.
37
37
  */
38
38
  const SECRETS_LOCK_FILE = `${SECRETS_FILE}.lock`;
39
- const SECRETS_LOCK_STALE_MS = 10_000;
40
- const SECRETS_LOCK_TIMEOUT_MS = 5_000;
39
+ // icacls на Windows под параллельной нагрузкой CI может занять секунды;
40
+ // 5 с приводило к ложным «Не удалось получить блокировку» даже без краша.
41
+ const SECRETS_LOCK_TIMEOUT_MS = 30_000;
41
42
  let secretsLockDepth = 0;
42
43
 
43
44
  function sleepSync(ms: number): void {
@@ -71,16 +72,22 @@ function withSecretsLock<T>(fn: () => T): T {
71
72
  if ((err as NodeJS.ErrnoException | undefined)?.code !== "EEXIST") throw err;
72
73
  try {
73
74
  const stat = fs.statSync(SECRETS_LOCK_FILE);
74
- if (Date.now() - stat.mtimeMs > SECRETS_LOCK_STALE_MS) {
75
- const owner = Number.parseInt(
76
- fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim(),
77
- 10,
78
- );
79
- if (!Number.isInteger(owner) || !isProcessAlive(owner)) {
80
- fs.rmSync(SECRETS_LOCK_FILE, { force: true });
81
- continue;
82
- }
75
+ const rawOwner = fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim();
76
+ const owner = /^\d+$/.test(rawOwner) ? Number(rawOwner) : NaN;
77
+ // Мёртвый владелец — лок осиротел. PID проверяем независимо от времени
78
+ // жизни файла: свежий лок упавшего процесса раньше блокировал запись
79
+ // на 10 с (stale) + 5 с (timeout) и ложно падал на загруженном CI.
80
+ if (Number.isInteger(owner) && owner > 0 && !isProcessAlive(owner)) {
81
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
82
+ continue;
83
83
  }
84
+ // Пустой/битый лок с только что созданным mtime может ещё не содержать
85
+ // PID — даём процессу-создателю окно, прежде чем считать его осиротевшим.
86
+ if (Date.now() - stat.mtimeMs > 1_000 && !Number.isInteger(owner)) {
87
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
88
+ continue;
89
+ }
90
+ // Лок с живым владельцем не крадём, даже если он создан давно.
84
91
  } catch {
85
92
  // Лок исчез между stat и read — повторяем попытку.
86
93
  }
@@ -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);
@@ -50,6 +50,22 @@ export interface StructuredLogRecord {
50
50
  workspaceId?: string | null;
51
51
  preFlightStatus?: string;
52
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;
53
69
  /** Источник события: schedule, dashboard, hook, cli, mcp и т.п. */
54
70
  source?: string;
55
71
  /** HTTP-статус ответа на hook.received. */
@@ -146,6 +162,20 @@ export function appendStructuredLog(
146
162
  if (typeof payload.reason === "string") {
147
163
  payload.reason = redactSecretsInText(payload.reason);
148
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
+ }
149
179
  fs.appendFileSync(STRUCTURED_LOG_FILE, `${JSON.stringify(payload)}\n`, "utf8");
150
180
  return true;
151
181
  } catch (err) {
@@ -154,6 +184,43 @@ export function appendStructuredLog(
154
184
  }
155
185
  }
156
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
+
157
224
  function readLines(file: string): string[] {
158
225
  try {
159
226
  return fs
@@ -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
+ }
@@ -87,6 +87,8 @@ export interface BashWrapperOptions {
87
87
  guards?: TaskGuards;
88
88
  /** Путь к dist/core/guard-run.js (обязателен при guards). */
89
89
  guardHelper?: string;
90
+ /** PL-47: пути, которые задача вправе изменить (из -Files afterScript). */
91
+ gateAllowPaths?: string;
90
92
  }
91
93
 
92
94
  /**
@@ -153,6 +155,7 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
153
155
  worktreeHelper,
154
156
  guards,
155
157
  guardHelper,
158
+ gateAllowPaths,
156
159
  } = options;
157
160
 
158
161
  // G-1.2: фиксируем входы гейта при создании обёртки и передаём путь
@@ -215,6 +218,7 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
215
218
  // G-1.2: путь к snapshot'у и CLI проверки целостности входов гейта.
216
219
  `GATE_SNAPSHOT=${shellQuote(gateSnapshot)}`,
217
220
  `GATE_INTEGRITY=${shellQuote(gateIntegrity)}`,
221
+ `GATE_ALLOW_PATHS=${shellQuote(gateAllowPaths ?? "")}`,
218
222
  `MODEL=${shellQuote(model ?? "")}`,
219
223
  // Спринт 24: режим сессии — "new" (по умолчанию), "reuse" (--session <id>), "last" (--continue).
220
224
  `SESSION_MODE=${shellQuote(sessionMode ?? "new")}`,
@@ -499,6 +503,14 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
499
503
  "fi",
500
504
  'START_EPOCH="$(date +%s)"',
501
505
  'STARTED_AT="$(date -u \'+%Y-%m-%dT%H:%M:%SZ\')"',
506
+ // PL-25: снимаем состояние рабочего дерева до запуска ИИ; перед гейтом сверяем.
507
+ 'WT_SNAPSHOT=""',
508
+ 'if [ -n "$QUALITY_GATE" ] && [ -n "$GATE_SNAPSHOT" ] && [ -n "$GATE_INTEGRITY" ] && [ -n "$WORKDIR" ] && [ -f "$GATE_INTEGRITY" ]; then',
509
+ ' WT_SNAPSHOT="${GATE_SNAPSHOT%.json}.worktree.json"',
510
+ ' ALLOW_ARGS=""',
511
+ ' if [ -n "$GATE_ALLOW_PATHS" ]; then ALLOW_ARGS="--allow $GATE_ALLOW_PATHS"; fi',
512
+ ' node "$GATE_INTEGRITY" worktree-snapshot --dir "$WORKDIR" --out "$WT_SNAPSHOT" $ALLOW_ARGS >> "$LOG_FILE" 2>&1 || true',
513
+ "fi",
502
514
  "EXIT_CODE=0",
503
515
  'ERROR_MESSAGE=""',
504
516
  'PRE_FLIGHT_STATUS="skipped"',
@@ -514,13 +526,37 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
514
526
  ' RUN_ID="$(node "$RECORDER_FILE" --start "$TASK_NAME" "$STARTED_AT" 2>> "$LOG_FILE" | tail -n 1)"',
515
527
  "fi",
516
528
  "",
529
+ // PL-7.2: отдельный вызов хука с разделением stdout/stderr и structured логом.
530
+ "hook_output() {",
531
+ ' local phase="$1" code="$2" out="$3" err="$4" helper',
532
+ ' if [ -z "$RECORDER_FILE" ] || ! command -v node >/dev/null 2>&1; then',
533
+ " return 0",
534
+ " fi",
535
+ ' helper="$(dirname "$RECORDER_FILE")/hook-output.js"',
536
+ ' [ -f "$helper" ] || return 0',
537
+ ' node "$helper" "$phase" "$TASK_NAME" "$code" "$out" "$err" "${RUN_ID:-}" >> "$LOG_FILE" 2>&1 || true',
538
+ "}",
539
+ "run_hook_captured() {",
540
+ ' local phase="$1" command="$2" out err code',
541
+ ' out="$(mktemp)"',
542
+ ' err="$(mktemp)"',
543
+ ' run_with_timeout "$GATE_TIMEOUT_SECONDS" bash -c "$command" >"$out" 2>"$err"',
544
+ " code=$?",
545
+ ' cat "$out" >> "$LOG_FILE"',
546
+ ' cat "$err" >> "$LOG_FILE"',
547
+ ' hook_output "$phase" "$code" "$out" "$err"',
548
+ ' rm -f "$out" "$err"',
549
+ " return $code",
550
+ "}",
551
+ "",
517
552
  "# Pre-flight: выполняется до основной задачи. Ненулевой код отменяет запуск.",
518
553
  'if [ -n "$BEFORE_SCRIPT" ]; then',
519
554
  ' log "[scheduler] Pre-flight: $BEFORE_SCRIPT"',
520
- ' run_with_timeout "$GATE_TIMEOUT_SECONDS" bash -c "$BEFORE_SCRIPT" >> "$LOG_FILE" 2>&1',
555
+ ' run_hook_captured "preFlight" "$BEFORE_SCRIPT"',
521
556
  " PRE_CODE=$?",
522
557
  ' if [ "$PRE_CODE" -ne 0 ]; then',
523
- ' log "[scheduler] ОШИБКА: Pre-flight script failed (код $PRE_CODE)."',
558
+ " # PL-6.1: last command in a hook defines the exit code — add explicit exit 0.",
559
+ ' log "[scheduler] ОШИБКА: Pre-flight script failed (код $PRE_CODE). Завершите хук явным exit 0 (например: rm -f \"$path\" || true; exit 0)."',
524
560
  ' PRE_FLIGHT_STATUS="error"',
525
561
  ' ERROR_MESSAGE="Pre-flight script failed"',
526
562
  " EXIT_CODE=1",
@@ -533,12 +569,20 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
533
569
  "",
534
570
  'if [ "$SKIP_MAIN" -eq 0 ]; then',
535
571
  "",
572
+ // QA-P0.2: маркер границы реального прогона. Пишется без префикса времени,
573
+ // чтобы extractLastRunLog() смог отсечь вывод предыдущих запусков и
574
+ // подготовительные записи. До этой точки запуск мог быть отменён guard-ом
575
+ // или pre-flight, поэтому маркер нельзя ставить раньше.
576
+ 'printf \'[agent-steward] === Run started %s (%s) ===\\n\' "$(date -u \'+%Y-%m-%dT%H:%M:%SZ\')" "$TASK_NAME" >> "$LOG_FILE" 2>/dev/null || true',
577
+ "",
536
578
  "# Модель указывается только если задана — иначе OpenCode берёт свою по умолчанию.",
537
579
  "# exec важен: в фоновом режиме он заменяет подоболочку процессом opencode,",
538
580
  "# поэтому $! — это PID самого opencode, и watchdog убивает именно его.",
539
581
  "# Ветвление вместо массива: bash 3.2 (macOS) с set -u падает на пустом",
540
582
  '# "${ARR[@]}".',
541
583
  "run_opencode() {",
584
+ " # QV-8: дочерний opencode run не загружает инструменты планировщика.",
585
+ " export AGENT_STEWARD_CHILD_RUN=1",
542
586
  ' if [ "$SESSION_MODE" = "reuse" ]; then',
543
587
  ' if [ -n "$SESSION_FILE" ] && [ -f "$SESSION_FILE" ]; then',
544
588
  ' SESSION_ID="$(head -n 1 "$SESSION_FILE" 2>/dev/null | tr -d "\\r")"',
@@ -625,6 +669,7 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
625
669
  'if [ -n "$QUALITY_GATE" ] && [ "$EXIT_CODE" -eq 0 ]; then',
626
670
  // G-1.2: сверяем входы гейта со snapshot'ом, снятым при создании задачи.
627
671
  " GATE_INTEGRITY_OK=1",
672
+ " WORKTREE_FAIL=0",
628
673
  ' if [ -n "$GATE_SNAPSHOT" ] && [ -n "$GATE_INTEGRITY" ] && [ -f "$GATE_SNAPSHOT" ] && [ -f "$GATE_INTEGRITY" ]; then',
629
674
  ' node "$GATE_INTEGRITY" verify --snapshot "$GATE_SNAPSHOT" --gate-command "$QUALITY_GATE" --prompt-file "$PROMPT_FILE" --timeout "$GATE_TIMEOUT_SECONDS" >> "$LOG_FILE" 2>&1',
630
675
  " VERIFY_CODE=$?",
@@ -632,9 +677,19 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
632
677
  " else",
633
678
  " GATE_INTEGRITY_OK=0",
634
679
  " fi",
680
+ ' if [ "$GATE_INTEGRITY_OK" -eq 1 ] && [ -n "$WT_SNAPSHOT" ] && [ -f "$WT_SNAPSHOT" ] && [ -n "$WORKDIR" ]; then',
681
+ ' node "$GATE_INTEGRITY" worktree-verify --dir "$WORKDIR" --snapshot "$WT_SNAPSHOT" $ALLOW_ARGS >> "$LOG_FILE" 2>&1',
682
+ " WT_CODE=$?",
683
+ ' if [ "$WT_CODE" -ne 0 ]; then GATE_INTEGRITY_OK=0; WORKTREE_FAIL=1; fi',
684
+ " fi",
635
685
  ' if [ "$GATE_INTEGRITY_OK" -eq 0 ]; then',
636
- ' log "[scheduler] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."',
637
- ' ERROR_MESSAGE="Quality Gate: целостность входов нарушена (snapshot mismatch)"',
686
+ ' if [ "$WORKTREE_FAIL" -eq 1 ]; then',
687
+ ' log "[scheduler] ОШИБКА: рабочее дерево изменилось во время прогона — гейт не доверяем."',
688
+ ' ERROR_MESSAGE="Quality Gate: рабочее дерево изменилось во время прогона"',
689
+ " else",
690
+ ' log "[scheduler] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."',
691
+ ' ERROR_MESSAGE="Quality Gate: целостность входов нарушена (snapshot mismatch)"',
692
+ " fi",
638
693
  " EXIT_CODE=1",
639
694
  " else",
640
695
  ' log "[scheduler] Запуск Quality Gate: $QUALITY_GATE"',
@@ -655,7 +710,7 @@ export function buildBashWrapperScript(options: BashWrapperOptions): string {
655
710
  "# Post-flight: выполняется ВСЕГДА, даже если основная задача упала.",
656
711
  'if [ -n "$AFTER_SCRIPT" ]; then',
657
712
  ' log "[scheduler] Post-flight: $AFTER_SCRIPT"',
658
- ' run_with_timeout "$GATE_TIMEOUT_SECONDS" bash -c "$AFTER_SCRIPT" >> "$LOG_FILE" 2>&1',
713
+ ' run_hook_captured "postFlight" "$AFTER_SCRIPT"',
659
714
  " POST_CODE=$?",
660
715
  ' if [ "$POST_CODE" -ne 0 ]; then',
661
716
  ' log "[scheduler] ОШИБКА: Post-flight script failed (код $POST_CODE)."',