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
@@ -14,6 +14,18 @@ import type { TaskStatus } from "../history.js";
14
14
 
15
15
  export type HistoryStatus = TaskStatus | "running";
16
16
 
17
+ /**
18
+ * QA-P1.5: прочерк и пустая строка — не текст ошибки, а маркер «нет данных».
19
+ * PowerShell-обёртка исторически передавала "-" для успешных запусков, и он
20
+ * попадал в history и структурированные логи как сообщение об ошибке.
21
+ * Нормализуем и при записи, и при чтении (легаси-записи уже есть в БД).
22
+ */
23
+ export function normalizeErrorText(error: string | null | undefined): string | null {
24
+ if (error == null) return null;
25
+ const trimmed = String(error).trim();
26
+ return !trimmed || trimmed === "-" ? null : trimmed;
27
+ }
28
+
17
29
  export interface StoredHistoryRecord {
18
30
  id?: number;
19
31
  taskName: string;
@@ -53,7 +65,39 @@ export interface RunResult {
53
65
  finishedAt?: string;
54
66
  }
55
67
 
56
- function rowToRecord(row: any): StoredHistoryRecord {
68
+ /**
69
+ * QA-A2-T3: сырая строка таблицы history на границе `node:sqlite`.
70
+ *
71
+ * `SqliteStatement.get()/all()` в src/db/index.ts объявлены как `any`/`any[]`
72
+ * (модуль грузится через createRequire без статических типов). Это граница БД:
73
+ * сужаем `unknown` к доменному типу строки здесь и не пускаем `any` дальше.
74
+ * Типы полей соответствуют схеме: TEXT → string|null, INTEGER/REAL →
75
+ * number|bigint|null. Приведение не меняет поведение — 기존ные String()/Number()/
76
+ * JSON.parse() в rowToRecord остаются без изменений.
77
+ */
78
+ interface HistoryRow {
79
+ id: number | bigint;
80
+ task_name: string;
81
+ status: string;
82
+ started_at: string;
83
+ finished_at: string | null;
84
+ duration_ms: number | bigint | null;
85
+ error: string | null;
86
+ tokens: number | bigint | null;
87
+ cost_usd: number | null;
88
+ model: string | null;
89
+ pre_flight_status: string | null;
90
+ post_flight_status: string | null;
91
+ next_task: string | null;
92
+ workspace_id: string | null;
93
+ allowed_tools: string | null;
94
+ denied_tools: string | null;
95
+ owner_pid: number | bigint | null;
96
+ owner_host: string | null;
97
+ owner_started_at: string | null;
98
+ }
99
+
100
+ function rowToRecord(row: HistoryRow): StoredHistoryRecord {
57
101
  const status = String(row.status) as HistoryStatus;
58
102
  return {
59
103
  id: Number(row.id),
@@ -62,7 +106,7 @@ function rowToRecord(row: any): StoredHistoryRecord {
62
106
  startedAt: String(row.started_at),
63
107
  finishedAt: row.finished_at == null ? null : String(row.finished_at),
64
108
  durationMs: row.duration_ms == null ? null : Number(row.duration_ms),
65
- error: row.error == null ? null : String(row.error),
109
+ error: normalizeErrorText(row.error == null ? null : String(row.error)),
66
110
  nextTask: row.next_task == null ? null : String(row.next_task),
67
111
  tokens: row.tokens == null ? undefined : Number(row.tokens),
68
112
  costUsd: row.cost_usd == null ? undefined : Number(row.cost_usd),
@@ -76,8 +120,11 @@ function rowToRecord(row: any): StoredHistoryRecord {
76
120
  ? undefined
77
121
  : (String(row.post_flight_status) as "success" | "error" | "skipped"),
78
122
  workspaceId: row.workspace_id == null ? null : String(row.workspace_id),
79
- allowedTools: row.allowed_tools == null ? null : JSON.parse(String(row.allowed_tools)),
80
- deniedTools: row.denied_tools == null ? null : JSON.parse(String(row.denied_tools)),
123
+ // QA-A2-T3: JSON.parse возвращает any — сужаем к доменному типу без as any.
124
+ allowedTools:
125
+ row.allowed_tools == null ? null : (JSON.parse(String(row.allowed_tools)) as string[]),
126
+ deniedTools:
127
+ row.denied_tools == null ? null : (JSON.parse(String(row.denied_tools)) as string[]),
81
128
  ownerPid: row.owner_pid == null ? null : Number(row.owner_pid),
82
129
  ownerHost: row.owner_host == null ? null : String(row.owner_host),
83
130
  ownerStartedAt: row.owner_started_at == null ? null : String(row.owner_started_at),
@@ -104,7 +151,7 @@ export function insertHistory(record: StoredHistoryRecord): number {
104
151
  record.startedAt,
105
152
  record.finishedAt ?? null,
106
153
  record.durationMs ?? null,
107
- record.error ?? null,
154
+ normalizeErrorText(record.error),
108
155
  record.tokens ?? null,
109
156
  record.costUsd ?? null,
110
157
  record.model ?? null,
@@ -172,13 +219,15 @@ export function finishRun(
172
219
  ): boolean {
173
220
  const safeDuration = Number.isFinite(durationMs) ? Math.max(0, Math.floor(durationMs)) : 0;
174
221
  const finishedAt = new Date().toISOString();
222
+ const cleanError = normalizeErrorText(error);
175
223
  let completed: { taskName: string; startedAt: string } | null = null;
176
224
 
177
225
  const ok = withTransaction(() => {
178
226
  const instance = getDb();
227
+ // QA-A2-T3: граница node:sqlite — get() возвращает any, сужаем к доменному типу.
179
228
  const row = instance
180
229
  .prepare("SELECT finished_at FROM history WHERE id = ?")
181
- .get(id);
230
+ .get(id) as unknown as Pick<HistoryRow, "finished_at"> | undefined;
182
231
  if (!row || row.finished_at != null) return false;
183
232
 
184
233
  instance
@@ -193,7 +242,7 @@ export function finishRun(
193
242
  status,
194
243
  finishedAt,
195
244
  safeDuration,
196
- error ?? null,
245
+ cleanError,
197
246
  nextTask ?? null,
198
247
  tokens ?? null,
199
248
  costUsd ?? null,
@@ -205,7 +254,7 @@ export function finishRun(
205
254
 
206
255
  const taskRow = instance
207
256
  .prepare("SELECT task_name, started_at FROM history WHERE id = ?")
208
- .get(id);
257
+ .get(id) as unknown as Pick<HistoryRow, "task_name" | "started_at">;
209
258
  incrementMetricsUnsafe(String(taskRow.task_name), status, tokens, costUsd);
210
259
  completed = {
211
260
  taskName: String(taskRow.task_name),
@@ -224,7 +273,7 @@ export function finishRun(
224
273
  startedAt: done.startedAt,
225
274
  finishedAt,
226
275
  durationMs: safeDuration,
227
- error: error ?? null,
276
+ error: cleanError,
228
277
  nextTask: nextTask ?? null,
229
278
  tokens,
230
279
  costUsd,
@@ -258,6 +307,7 @@ export function recordRun(
258
307
  deniedTools?: string[] | null,
259
308
  ): number {
260
309
  const safeDuration = Math.max(0, Math.floor(Number(durationMs) || 0));
310
+ const cleanError = normalizeErrorText(error);
261
311
  const id = withTransaction(() => {
262
312
  const result = getDb()
263
313
  .prepare(INSERT_SQL)
@@ -267,7 +317,7 @@ export function recordRun(
267
317
  startedAt,
268
318
  finishedAt,
269
319
  safeDuration,
270
- error ?? null,
320
+ cleanError,
271
321
  tokens ?? null,
272
322
  costUsd ?? null,
273
323
  model ?? null,
@@ -294,7 +344,7 @@ export function recordRun(
294
344
  startedAt,
295
345
  finishedAt,
296
346
  durationMs: safeDuration,
297
- error: error ?? null,
347
+ error: cleanError,
298
348
  nextTask: nextTask ?? null,
299
349
  tokens,
300
350
  costUsd,
@@ -314,7 +364,8 @@ export function getHistory(
314
364
  ): StoredHistoryRecord[] {
315
365
  const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
316
366
  const clauses: string[] = [];
317
- const params: any[] = [];
367
+ // QA-A2-T3: параметры привязки — только string/number (domain type вместо any[]).
368
+ const params: (string | number)[] = [];
318
369
  if (taskName) {
319
370
  clauses.push("lower(task_name) = lower(?)");
320
371
  params.push(taskName);
@@ -341,7 +392,32 @@ export function getHistory(
341
392
  ORDER BY started_at DESC, id DESC
342
393
  LIMIT ?`,
343
394
  )
344
- .all(...params);
395
+ // QA-A2-T3: граница node:sqlite — all() возвращает any[], сужаем к HistoryRow[].
396
+ .all(...params) as unknown as HistoryRow[];
397
+ return rows.map(rowToRecord);
398
+ }
399
+
400
+ /**
401
+ * История для проверки бюджетов: записи, учётный момент которых
402
+ * (`finished_at`, при отсутствии `started_at`) не раньше `periodStart`.
403
+ *
404
+ * В отличие от `getHistorySince()` учитывает запуски, начатые в предыдущем
405
+ * периоде, но завершённые в текущем — именно по ним считается расход в
406
+ * `src/core/budget.ts`. Лимит 100000 совпадает с максимумом `getHistory`.
407
+ */
408
+ export function getHistoryForBudget(
409
+ periodStart: string,
410
+ limit = 100000,
411
+ ): StoredHistoryRecord[] {
412
+ const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
413
+ const rows = getDb()
414
+ .prepare(
415
+ `SELECT * FROM history
416
+ WHERE COALESCE(finished_at, started_at) >= ?
417
+ ORDER BY started_at DESC, id DESC
418
+ LIMIT ?`,
419
+ )
420
+ .all(periodStart, safeLimit) as unknown as HistoryRow[];
345
421
  return rows.map(rowToRecord);
346
422
  }
347
423
 
@@ -363,10 +439,29 @@ export function getLatestHistoryByTask(limit = 5000): StoredHistoryRecord[] {
363
439
  ORDER BY started_at DESC, id DESC
364
440
  LIMIT ?`,
365
441
  )
366
- .all(safeLimit);
442
+ .all(safeLimit) as unknown as HistoryRow[];
367
443
  return rows.map(rowToRecord);
368
444
  }
369
445
 
446
+ /**
447
+ * История для аналитики за окно `days` дней: все запуски, которые могут
448
+ * попасть в период по времени начала. Окно на один день шире запрашиваемого,
449
+ * чтобы полностью покрыть самый ранний UTC-день (buildAnalytics всё равно
450
+ * отфильтрует лишнее по дате). Лимит 100000 снимает потолок в 20000 записей,
451
+ * из-за которого отчёты за 365 дней молча недосчитывали запуски и расход.
452
+ */
453
+ export function getHistoryForAnalytics(
454
+ days: number,
455
+ now: Date = new Date(),
456
+ includeInternal = false,
457
+ ): StoredHistoryRecord[] {
458
+ const safeDays = Math.max(1, Math.min(365, Math.floor(days) || 1));
459
+ const since = new Date(now.getTime() - (safeDays + 1) * 24 * 60 * 60 * 1000);
460
+ const records = getHistorySince(since.toISOString(), 100000);
461
+ // PL-37: служебные задачи (__*) — артефакты тестов/проб, не пользовательская аналитика.
462
+ return includeInternal ? records : records.filter((record) => !record.taskName.startsWith("__"));
463
+ }
464
+
370
465
  /** История запусков, начатых не раньше timestamp (ISO-строка). */
371
466
  export function getHistorySince(
372
467
  timestamp: string,
@@ -380,7 +475,7 @@ export function getHistorySince(
380
475
  ORDER BY started_at DESC, id DESC
381
476
  LIMIT ?`,
382
477
  )
383
- .all(timestamp, safeLimit);
478
+ .all(timestamp, safeLimit) as unknown as HistoryRow[];
384
479
  return rows.map(rowToRecord);
385
480
  }
386
481
 
@@ -410,6 +505,14 @@ export interface RecoverInterruptedOptions {
410
505
  now?: Date;
411
506
  /** Порог возраста для записей с непроверяемым владельцем. */
412
507
  maxUnverifiableAgeMs?: number;
508
+ /**
509
+ * PL-46: порог, после которого запись живого владельца считается
510
+ * «зависшей» (например, процесс убит через schtasks /End) и финализируется
511
+ * как timeout. 0 отключает проверку. По умолчанию 0 — прямой вызов
512
+ * recoverInterrupted() сохраняет crash-recovery-поведение; порог задаёт
513
+ * recoverInterruptedRuns() (см. db/recovery.ts).
514
+ */
515
+ staleAfterMs?: number;
413
516
  /** Имя текущего хоста (для тестов). */
414
517
  hostname?: string;
415
518
  /** Проверка живости PID (для тестов). */
@@ -468,6 +571,26 @@ export function recoverInterrupted(
468
571
  )
469
572
  WHERE id = ? AND finished_at IS NULL`,
470
573
  );
574
+ // PL-46: «живой» владелец может быть мёртвой записью после schtasks /End —
575
+ // такой прогон помечается timeout, а не error crash recovery.
576
+ const staleUpdate = db.prepare(
577
+ `UPDATE history SET
578
+ status = 'timeout',
579
+ error = CASE
580
+ WHEN error IS NULL OR error = '' THEN 'Запуск прерван: владелец завершён (schtasks /End или аналог)'
581
+ ELSE error
582
+ END,
583
+ finished_at = COALESCE(finished_at, ?),
584
+ duration_ms = COALESCE(
585
+ duration_ms,
586
+ CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
587
+ )
588
+ WHERE id = ? AND finished_at IS NULL`,
589
+ );
590
+ const staleAfter =
591
+ typeof options.staleAfterMs === "number" && Number.isFinite(options.staleAfterMs)
592
+ ? Math.max(0, options.staleAfterMs)
593
+ : 0;
471
594
 
472
595
  let recovered = 0;
473
596
  let keptAlive = 0;
@@ -479,7 +602,14 @@ export function recoverInterrupted(
479
602
  ownerPid != null && ownerPid > 0 && ownerHost != null && ownerHost === hostname;
480
603
 
481
604
  if (verifiable && ownerPid != null && isAlive(ownerPid)) {
482
- keptAlive += 1;
605
+ const since = Date.parse(String(row.started_at ?? ""));
606
+ const age = Number.isFinite(since) ? now.getTime() - since : 0;
607
+ if (staleAfter > 0 && age >= staleAfter) {
608
+ const result = staleUpdate.run(nowIso, nowIso, row.id);
609
+ if (Number(result.changes) > 0) recovered += 1;
610
+ } else {
611
+ keptAlive += 1;
612
+ }
483
613
  continue;
484
614
  }
485
615
  if (!verifiable) {
@@ -500,7 +630,10 @@ export function recoverInterrupted(
500
630
 
501
631
  /** Количество записей истории (для миграции и тестов). */
502
632
  export function countHistory(): number {
503
- const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get();
633
+ // QA-A2-T3: граница node:sqlite — get() возвращает any, сужаем к строке счётчика.
634
+ const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get() as unknown as
635
+ | { count: unknown }
636
+ | undefined;
504
637
  return Number(row?.count) || 0;
505
638
  }
506
639
 
@@ -508,7 +641,7 @@ export function countHistory(): number {
508
641
  export function countRunningRecords(): number {
509
642
  const row = getDb()
510
643
  .prepare("SELECT COUNT(*) AS count FROM history WHERE finished_at IS NULL")
511
- .get();
644
+ .get() as unknown as { count: unknown } | undefined;
512
645
  return Number(row?.count) || 0;
513
646
  }
514
647
 
@@ -527,7 +660,8 @@ export function listRunningRecords(): RunningHistoryRecord[] {
527
660
  WHERE finished_at IS NULL
528
661
  ORDER BY started_at ASC, id ASC`,
529
662
  )
530
- .all();
663
+ // QA-A2-T3: граница node:sqlite — all() возвращает any[], сужаем к доменному типу.
664
+ .all() as unknown as Pick<HistoryRow, "id" | "task_name" | "started_at">[];
531
665
  return rows.map((row) => ({
532
666
  id: Number(row.id) || 0,
533
667
  taskName: String(row.task_name ?? ""),
@@ -25,7 +25,12 @@ export interface TaskMetricsRow {
25
25
  export interface MetricsTotals {
26
26
  total: number;
27
27
  success: number;
28
+ /** Реальные отказы (error/timeout/неизвестный статус) без прерванных и пропусков. */
28
29
  error: number;
30
+ /** Пропуски (status=skipped) — не падения. */
31
+ skipped: number;
32
+ /** Прерванные crash recovery (error с текстом «Прервано …»). */
33
+ interrupted: number;
29
34
  partial: number;
30
35
  tokens: number;
31
36
  costUsd: number;
@@ -34,7 +39,7 @@ export interface MetricsTotals {
34
39
  const GLOBAL_TASK = "__global__";
35
40
  export const LEGACY_METRICS_TASK = "__legacy__";
36
41
 
37
- function isInternal(taskName: string): boolean {
42
+ export function isInternalTaskName(taskName: string): boolean {
38
43
  return taskName.startsWith("__");
39
44
  }
40
45
 
@@ -106,27 +111,49 @@ export function getAllMetrics(includeInternal = false): TaskMetricsRow[] {
106
111
  const rows = getDb()
107
112
  .prepare("SELECT * FROM metrics ORDER BY task_name COLLATE NOCASE ASC")
108
113
  .all();
109
- return rows.map(rowToMetrics).filter((row) => includeInternal || !isInternal(row.taskName));
114
+ return rows.map(rowToMetrics).filter((row) => includeInternal || !isInternalTaskName(row.taskName));
110
115
  }
111
116
 
112
- /** Суммарные метрики (включая служебные строки). */
113
- export function getTotals(): MetricsTotals {
117
+ /**
118
+ * Суммарные метрики по единой выборке истории (QA-P1.1).
119
+ *
120
+ * Раньше итоги брались из таблицы metrics. Но crash recovery помечает
121
+ * незавершённые запуски прямо в history (UPDATE ... status='error') без
122
+ * инкремента metrics, поэтому get_metrics расходился с analytics и
123
+ * self_analysis на число прерванных запусков. Теперь все три источника
124
+ * считают по одной и той же истории: success/partial явные, всё остальное
125
+ * (error/timeout/skipped) — error, running не участвует.
126
+ *
127
+ * Примечание: поточечные метрики getMetrics()/getAllMetrics() остаются
128
+ * таблицей metrics — там хранится в том числе legacy-хвост без истории.
129
+ */
130
+ export function getTotals(includeInternal = false): MetricsTotals {
131
+ // PL-37: служебные задачи (__*), используемые тестами/пробами, не должны
132
+ // попадать в агрегированные метрики — getAllMetrics их уже фильтрует.
133
+ const internalFilter = includeInternal ? "" : "AND task_name NOT LIKE '\\_\\_%' ESCAPE '\\'";
114
134
  const row = getDb()
115
135
  .prepare(
116
136
  `SELECT
117
- COALESCE(SUM(total), 0) AS total,
118
- COALESCE(SUM(success), 0) AS success,
119
- COALESCE(SUM(error), 0) AS error,
120
- COALESCE(SUM(partial), 0) AS partial,
121
- COALESCE(SUM(total_tokens), 0) AS tokens,
122
- COALESCE(SUM(total_cost), 0) AS cost_usd
123
- FROM metrics`,
137
+ COUNT(*) AS total,
138
+ COALESCE(SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END), 0) AS success,
139
+ COALESCE(SUM(CASE WHEN status = 'partial' THEN 1 ELSE 0 END), 0) AS partial,
140
+ COALESCE(SUM(CASE WHEN status = 'skipped' THEN 1 ELSE 0 END), 0) AS skipped,
141
+ COALESCE(SUM(CASE WHEN status NOT IN ('success', 'partial', 'running', 'skipped')
142
+ AND COALESCE(error, '') NOT LIKE '%Прервано%' THEN 1 ELSE 0 END), 0) AS error,
143
+ COALESCE(SUM(CASE WHEN status NOT IN ('success', 'partial', 'running', 'skipped')
144
+ AND COALESCE(error, '') LIKE '%Прервано%' THEN 1 ELSE 0 END), 0) AS interrupted,
145
+ COALESCE(SUM(CASE WHEN tokens > 0 THEN CAST(tokens AS INTEGER) ELSE 0 END), 0) AS tokens,
146
+ COALESCE(SUM(CASE WHEN cost_usd > 0 THEN cost_usd ELSE 0 END), 0) AS cost_usd
147
+ FROM history
148
+ WHERE status <> 'running' ${internalFilter}`,
124
149
  )
125
150
  .get();
126
151
  return {
127
152
  total: Number(row?.total) || 0,
128
153
  success: Number(row?.success) || 0,
129
154
  error: Number(row?.error) || 0,
155
+ skipped: Number((row as { skipped?: number } | undefined)?.skipped) || 0,
156
+ interrupted: Number((row as { interrupted?: number } | undefined)?.interrupted) || 0,
130
157
  partial: Number(row?.partial) || 0,
131
158
  tokens: Number(row?.tokens) || 0,
132
159
  costUsd: Number(row?.cost_usd) || 0,
package/src/db/migrate.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- import { PLUGIN_DIR } from "../types.js";
4
+ import { PLUGIN_DIR, type MigrationHistoryRow } from "../types.js";
5
5
  import { getDb, isDatabaseEmpty, withTransaction } from "./index.js";
6
6
  import {
7
7
  LEGACY_METRICS_TASK,
@@ -40,6 +40,34 @@ const EMPTY_RESULT: MigrationResult = {
40
40
 
41
41
  const JSON_FILES = ["tasks.json", "history.json", "metrics.json", "templates.json"] as const;
42
42
 
43
+ /**
44
+ * JSON читается как unknown: доверяем только форме (объект/массив), а не
45
+ * содержимому. Значения проверяются type guard'ами перед записью в БД (QA-A2.4).
46
+ */
47
+ type JsonRecord = Record<string, unknown>;
48
+
49
+ function isRecord(value: unknown): value is JsonRecord {
50
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51
+ }
52
+
53
+ /** Встроенный Array.isArray возвращает слабый тип массива; свой guard даёт unknown[] (QA-A2.4). */
54
+ function isUnknownArray(value: unknown): value is unknown[] {
55
+ return Array.isArray(value);
56
+ }
57
+
58
+ /**
59
+ * Граница внешнего API (node:fs, JSON.parse, node:sqlite): выброшенное значение
60
+ * не гарантированно Error. Извлечение сообщения сохранено как в legacy-коде.
61
+ */
62
+ function errorText(err: unknown): string {
63
+ return err instanceof Error ? err.message : String(err);
64
+ }
65
+
66
+ /** node:fs сообщает «файл не найден» через свойство code (внешняя граница API). */
67
+ function isErrnoException(err: unknown): err is NodeJS.ErrnoException {
68
+ return err instanceof Error && "code" in err && typeof err.code === "string";
69
+ }
70
+
43
71
  interface LoadedFile {
44
72
  path: string;
45
73
  exists: boolean;
@@ -51,24 +79,22 @@ async function loadJsonFile(file: string): Promise<LoadedFile> {
51
79
  const raw = await fs.readFile(file, "utf8");
52
80
  try {
53
81
  return { path: file, exists: true, value: JSON.parse(raw) };
54
- } catch (err: any) {
82
+ } catch (err: unknown) {
55
83
  throw new Error(
56
- `Некорректный JSON в ${path.basename(file)}: ${
57
- err instanceof Error ? err.message : String(err)
58
- }`,
84
+ `Некорректный JSON в ${path.basename(file)}: ${errorText(err)}`,
59
85
  );
60
86
  }
61
- } catch (err: any) {
62
- if (err?.code === "ENOENT") return { path: file, exists: false, value: null };
87
+ } catch (err: unknown) {
88
+ if (isErrnoException(err) && err.code === "ENOENT") {
89
+ return { path: file, exists: false, value: null };
90
+ }
63
91
  throw err;
64
92
  }
65
93
  }
66
94
 
67
- function asArray(value: unknown): any[] {
68
- if (Array.isArray(value)) return value;
69
- if (value && typeof value === "object" && Array.isArray((value as any).tasks)) {
70
- return (value as any).tasks;
71
- }
95
+ function asArray(value: unknown): unknown[] {
96
+ if (isUnknownArray(value)) return value;
97
+ if (isRecord(value) && isUnknownArray(value.tasks)) return value.tasks;
72
98
  return [];
73
99
  }
74
100
 
@@ -83,8 +109,8 @@ function toStringOrNull(value: unknown): string | null {
83
109
  }
84
110
 
85
111
  /** Приводит старую запись истории к колонкам БД. */
86
- function normalizeHistoryRow(raw: any): any | null {
87
- if (!raw || typeof raw !== "object") return null;
112
+ function normalizeHistoryRow(raw: unknown): MigrationHistoryRow | null {
113
+ if (!isRecord(raw)) return null;
88
114
  const taskName = typeof raw.taskName === "string" ? raw.taskName.trim() : "";
89
115
  const startedAt = typeof raw.startedAt === "string" ? raw.startedAt : "";
90
116
  if (!taskName || !startedAt) return null;
@@ -130,13 +156,10 @@ export async function migrateJsonToDb(
130
156
  const taskItems = asArray(byName.get("tasks.json")?.value);
131
157
  const historyItems = asArray(byName.get("history.json")?.value)
132
158
  .map(normalizeHistoryRow)
133
- .filter((row): row is any => row !== null);
159
+ .filter((row): row is MigrationHistoryRow => row !== null);
134
160
  const templateItems = asArray(byName.get("templates.json")?.value);
135
- const legacyMetrics =
136
- byName.get("metrics.json")?.value &&
137
- typeof byName.get("metrics.json")?.value === "object"
138
- ? (byName.get("metrics.json")!.value as any)
139
- : null;
161
+ const metricsValue = byName.get("metrics.json")?.value;
162
+ const legacyMetrics: JsonRecord | null = isRecord(metricsValue) ? metricsValue : null;
140
163
 
141
164
  const now = new Date().toISOString();
142
165
  let insertedTasks = 0;
@@ -148,24 +171,27 @@ export async function migrateJsonToDb(
148
171
  const db = getDb();
149
172
 
150
173
  // --- tasks ---
174
+ // Сырой SQL и node:sqlite — граница внешнего API: в БД попадают только
175
+ // значения, прошедшие проверки выше (name/createdAt — string, остальное — JSON).
151
176
  const insertTask = db.prepare(
152
177
  "INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)",
153
178
  );
154
179
  const seenTasks = new Set<string>();
155
180
  for (const item of taskItems) {
156
- if (!item || typeof item !== "object") continue;
181
+ if (!isRecord(item)) continue;
157
182
  const name = typeof item.name === "string" ? item.name.trim() : "";
158
183
  if (!name || seenTasks.has(name.toLowerCase())) continue;
159
184
  seenTasks.add(name.toLowerCase());
160
185
 
161
186
  // workdir → workingDirectory, как в старом loadTaskDefinitions().
162
- const definition: any = { ...item, name };
187
+ const definition: JsonRecord = { ...item, name };
188
+ const legacyWorkdir = definition.workdir;
163
189
  if (
164
190
  definition.workingDirectory === undefined &&
165
- typeof definition.workdir === "string" &&
166
- definition.workdir.trim()
191
+ typeof legacyWorkdir === "string" &&
192
+ legacyWorkdir.trim()
167
193
  ) {
168
- definition.workingDirectory = definition.workdir.trim();
194
+ definition.workingDirectory = legacyWorkdir.trim();
169
195
  }
170
196
  delete definition.workdir;
171
197
 
@@ -210,17 +236,18 @@ export async function migrateJsonToDb(
210
236
  );
211
237
  const seenTemplates = new Set<string>();
212
238
  for (const item of templateItems) {
213
- if (!item || typeof item !== "object") continue;
239
+ if (!isRecord(item)) continue;
214
240
  if (typeof item.prompt !== "string") continue;
215
241
  const name = typeof item.name === "string" ? item.name.trim() : "";
216
242
  if (!name) continue;
243
+ const legacyId = item.id;
217
244
  const id =
218
- typeof item.id === "string" && item.id.trim() ? item.id.trim() : randomUUID();
245
+ typeof legacyId === "string" && legacyId.trim() ? legacyId.trim() : randomUUID();
219
246
  const key = id.toLowerCase();
220
247
  if (seenTemplates.has(key)) continue;
221
248
  seenTemplates.add(key);
222
249
 
223
- const template = { ...item, id, name };
250
+ const template: JsonRecord = { ...item, id, name };
224
251
  insertTemplate.run(id, name, JSON.stringify(template));
225
252
  insertedTemplates += 1;
226
253
  }
@@ -306,11 +333,9 @@ export async function migrateJsonToDb(
306
333
  await fs.rm(backup, { force: true });
307
334
  await fs.rename(file.path, backup);
308
335
  backups.push(path.basename(backup));
309
- } catch (err: any) {
336
+ } catch (err: unknown) {
310
337
  console.error(
311
- `[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${
312
- err instanceof Error ? err.message : String(err)
313
- }`,
338
+ `[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${errorText(err)}`,
314
339
  );
315
340
  }
316
341
  }
@@ -9,13 +9,19 @@ const JSON_FILES = ["tasks.json", "history.json", "metrics.json", "templates.jso
9
9
 
10
10
  /**
11
11
  * Crash recovery: помечает незавершённые записи истории как error.
12
- * Вызывается при setup() до запуска catch-up и файловых триггеров.
12
+ * Вызывается при setup() до запуска catch-up и файловых триггеров, а также
13
+ * перед выдачей истории (PL-46), чтобы «висящие» запуски не оставались
14
+ * running после schtasks /End.
13
15
  */
14
16
  export function recoverInterruptedRuns(): number {
15
- const { recovered, keptAlive } = recoverInterrupted();
16
- if (recovered > 0 || keptAlive > 0) {
17
+ // Порог можно переопределить: 0 отключает финализацию живого владельца.
18
+ const configured = Number(process.env.AGENT_STEWARD_STALE_RUN_MS);
19
+ const staleAfterMs =
20
+ Number.isFinite(configured) && configured > 0 ? configured : 2 * 60 * 60 * 1000;
21
+ const { recovered, keptAlive } = recoverInterrupted({ staleAfterMs });
22
+ if (recovered > 0) {
17
23
  console.log(
18
- `[recovery] Восстановлено ${recovered} незавершённых записей истории — помечены как error.` +
24
+ `[recovery] Восстановлено ${recovered} незавершённых записей истории (error/timeout).` +
19
25
  (keptAlive > 0 ? ` Оставлено живым владельцам: ${keptAlive}.` : ""),
20
26
  );
21
27
  }