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
@@ -1,6 +1,7 @@
1
1
  import { getDb, withTransaction } from "./index.js";
2
2
  import { incrementMetricsUnsafe } from "./metrics-repo.js";
3
3
  import { appendStructuredLog } from "../core/structured-log.js";
4
+ import os from "node:os";
4
5
  import type { TaskStatus } from "../history.js";
5
6
 
6
7
  /**
@@ -13,6 +14,18 @@ import type { TaskStatus } from "../history.js";
13
14
 
14
15
  export type HistoryStatus = TaskStatus | "running";
15
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
+
16
29
  export interface StoredHistoryRecord {
17
30
  id?: number;
18
31
  taskName: string;
@@ -30,6 +43,10 @@ export interface StoredHistoryRecord {
30
43
  workspaceId?: string | null;
31
44
  allowedTools?: string[] | null;
32
45
  deniedTools?: string[] | null;
46
+ /** Владелец незавершённого запуска (схема v8). */
47
+ ownerPid?: number | null;
48
+ ownerHost?: string | null;
49
+ ownerStartedAt?: string | null;
33
50
  }
34
51
 
35
52
  /** Поля, которые пишутся в history при завершении запуска. */
@@ -48,7 +65,39 @@ export interface RunResult {
48
65
  finishedAt?: string;
49
66
  }
50
67
 
51
- 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 {
52
101
  const status = String(row.status) as HistoryStatus;
53
102
  return {
54
103
  id: Number(row.id),
@@ -57,7 +106,7 @@ function rowToRecord(row: any): StoredHistoryRecord {
57
106
  startedAt: String(row.started_at),
58
107
  finishedAt: row.finished_at == null ? null : String(row.finished_at),
59
108
  durationMs: row.duration_ms == null ? null : Number(row.duration_ms),
60
- error: row.error == null ? null : String(row.error),
109
+ error: normalizeErrorText(row.error == null ? null : String(row.error)),
61
110
  nextTask: row.next_task == null ? null : String(row.next_task),
62
111
  tokens: row.tokens == null ? undefined : Number(row.tokens),
63
112
  costUsd: row.cost_usd == null ? undefined : Number(row.cost_usd),
@@ -71,16 +120,22 @@ function rowToRecord(row: any): StoredHistoryRecord {
71
120
  ? undefined
72
121
  : (String(row.post_flight_status) as "success" | "error" | "skipped"),
73
122
  workspaceId: row.workspace_id == null ? null : String(row.workspace_id),
74
- allowedTools: row.allowed_tools == null ? null : JSON.parse(String(row.allowed_tools)),
75
- 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[]),
128
+ ownerPid: row.owner_pid == null ? null : Number(row.owner_pid),
129
+ ownerHost: row.owner_host == null ? null : String(row.owner_host),
130
+ ownerStartedAt: row.owner_started_at == null ? null : String(row.owner_started_at),
76
131
  };
77
132
  }
78
133
 
79
134
  const INSERT_SQL = `INSERT INTO history (
80
135
  task_name, status, started_at, finished_at, duration_ms, error,
81
136
  tokens, cost_usd, model, pre_flight_status, post_flight_status, next_task,
82
- workspace_id, allowed_tools, denied_tools
83
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
137
+ workspace_id, allowed_tools, denied_tools, owner_pid, owner_host, owner_started_at
138
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
84
139
 
85
140
  function lastId(result: { lastInsertRowid: number | bigint }): number {
86
141
  return Number(result.lastInsertRowid) || 0;
@@ -96,7 +151,7 @@ export function insertHistory(record: StoredHistoryRecord): number {
96
151
  record.startedAt,
97
152
  record.finishedAt ?? null,
98
153
  record.durationMs ?? null,
99
- record.error ?? null,
154
+ normalizeErrorText(record.error),
100
155
  record.tokens ?? null,
101
156
  record.costUsd ?? null,
102
157
  record.model ?? null,
@@ -106,6 +161,9 @@ export function insertHistory(record: StoredHistoryRecord): number {
106
161
  record.workspaceId ?? null,
107
162
  record.allowedTools == null ? null : JSON.stringify(record.allowedTools),
108
163
  record.deniedTools == null ? null : JSON.stringify(record.deniedTools),
164
+ record.ownerPid ?? null,
165
+ record.ownerHost ?? null,
166
+ record.ownerStartedAt ?? null,
109
167
  );
110
168
  return lastId(result);
111
169
  }
@@ -117,6 +175,7 @@ export function startRun(
117
175
  workspaceId?: string | null,
118
176
  allowedTools?: string[] | null,
119
177
  deniedTools?: string[] | null,
178
+ owner?: { pid?: number | null; host?: string | null; startedAt?: string | null },
120
179
  ): number {
121
180
  const id = insertHistory({
122
181
  taskName,
@@ -126,6 +185,9 @@ export function startRun(
126
185
  workspaceId,
127
186
  allowedTools,
128
187
  deniedTools,
188
+ ownerPid: owner?.pid ?? null,
189
+ ownerHost: owner?.host ?? null,
190
+ ownerStartedAt: owner?.startedAt ?? null,
129
191
  });
130
192
  appendStructuredLog({
131
193
  event: "run.started",
@@ -157,13 +219,15 @@ export function finishRun(
157
219
  ): boolean {
158
220
  const safeDuration = Number.isFinite(durationMs) ? Math.max(0, Math.floor(durationMs)) : 0;
159
221
  const finishedAt = new Date().toISOString();
222
+ const cleanError = normalizeErrorText(error);
160
223
  let completed: { taskName: string; startedAt: string } | null = null;
161
224
 
162
225
  const ok = withTransaction(() => {
163
226
  const instance = getDb();
227
+ // QA-A2-T3: граница node:sqlite — get() возвращает any, сужаем к доменному типу.
164
228
  const row = instance
165
229
  .prepare("SELECT finished_at FROM history WHERE id = ?")
166
- .get(id);
230
+ .get(id) as unknown as Pick<HistoryRow, "finished_at"> | undefined;
167
231
  if (!row || row.finished_at != null) return false;
168
232
 
169
233
  instance
@@ -178,7 +242,7 @@ export function finishRun(
178
242
  status,
179
243
  finishedAt,
180
244
  safeDuration,
181
- error ?? null,
245
+ cleanError,
182
246
  nextTask ?? null,
183
247
  tokens ?? null,
184
248
  costUsd ?? null,
@@ -190,7 +254,7 @@ export function finishRun(
190
254
 
191
255
  const taskRow = instance
192
256
  .prepare("SELECT task_name, started_at FROM history WHERE id = ?")
193
- .get(id);
257
+ .get(id) as unknown as Pick<HistoryRow, "task_name" | "started_at">;
194
258
  incrementMetricsUnsafe(String(taskRow.task_name), status, tokens, costUsd);
195
259
  completed = {
196
260
  taskName: String(taskRow.task_name),
@@ -209,7 +273,7 @@ export function finishRun(
209
273
  startedAt: done.startedAt,
210
274
  finishedAt,
211
275
  durationMs: safeDuration,
212
- error: error ?? null,
276
+ error: cleanError,
213
277
  nextTask: nextTask ?? null,
214
278
  tokens,
215
279
  costUsd,
@@ -243,6 +307,7 @@ export function recordRun(
243
307
  deniedTools?: string[] | null,
244
308
  ): number {
245
309
  const safeDuration = Math.max(0, Math.floor(Number(durationMs) || 0));
310
+ const cleanError = normalizeErrorText(error);
246
311
  const id = withTransaction(() => {
247
312
  const result = getDb()
248
313
  .prepare(INSERT_SQL)
@@ -252,7 +317,7 @@ export function recordRun(
252
317
  startedAt,
253
318
  finishedAt,
254
319
  safeDuration,
255
- error ?? null,
320
+ cleanError,
256
321
  tokens ?? null,
257
322
  costUsd ?? null,
258
323
  model ?? null,
@@ -262,6 +327,10 @@ export function recordRun(
262
327
  workspaceId ?? null,
263
328
  allowedTools == null ? null : JSON.stringify(allowedTools),
264
329
  deniedTools == null ? null : JSON.stringify(deniedTools),
330
+ // owner-колонки относятся только к незавершённым запускам (startRun).
331
+ null,
332
+ null,
333
+ null,
265
334
  );
266
335
  incrementMetricsUnsafe(taskName, status, tokens, costUsd);
267
336
  return lastId(result);
@@ -275,7 +344,7 @@ export function recordRun(
275
344
  startedAt,
276
345
  finishedAt,
277
346
  durationMs: safeDuration,
278
- error: error ?? null,
347
+ error: cleanError,
279
348
  nextTask: nextTask ?? null,
280
349
  tokens,
281
350
  costUsd,
@@ -295,7 +364,8 @@ export function getHistory(
295
364
  ): StoredHistoryRecord[] {
296
365
  const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
297
366
  const clauses: string[] = [];
298
- const params: any[] = [];
367
+ // QA-A2-T3: параметры привязки — только string/number (domain type вместо any[]).
368
+ const params: (string | number)[] = [];
299
369
  if (taskName) {
300
370
  clauses.push("lower(task_name) = lower(?)");
301
371
  params.push(taskName);
@@ -322,7 +392,32 @@ export function getHistory(
322
392
  ORDER BY started_at DESC, id DESC
323
393
  LIMIT ?`,
324
394
  )
325
- .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[];
326
421
  return rows.map(rowToRecord);
327
422
  }
328
423
 
@@ -344,10 +439,29 @@ export function getLatestHistoryByTask(limit = 5000): StoredHistoryRecord[] {
344
439
  ORDER BY started_at DESC, id DESC
345
440
  LIMIT ?`,
346
441
  )
347
- .all(safeLimit);
442
+ .all(safeLimit) as unknown as HistoryRow[];
348
443
  return rows.map(rowToRecord);
349
444
  }
350
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
+
351
465
  /** История запусков, начатых не раньше timestamp (ISO-строка). */
352
466
  export function getHistorySince(
353
467
  timestamp: string,
@@ -361,39 +475,165 @@ export function getHistorySince(
361
475
  ORDER BY started_at DESC, id DESC
362
476
  LIMIT ?`,
363
477
  )
364
- .all(timestamp, safeLimit);
478
+ .all(timestamp, safeLimit) as unknown as HistoryRow[];
365
479
  return rows.map(rowToRecord);
366
480
  }
367
481
 
368
482
  /**
369
- * Crash recovery: все незавершённые записи (finished_at IS NULL) помечаются
370
- * как error. Длительность считается от started_at до текущего момента.
371
- * Возвращает количество восстановленных записей.
483
+ * Crash recovery для истории.
484
+ *
485
+ * Незавершённая запись (finished_at IS NULL) финализируется как error, только
486
+ * если её владелец больше не может её завершить:
487
+ * - владелец известен, жив и на этом же хосте → запись оставляем (B1);
488
+ * - владелец известен и мёртв → финализируем сразу;
489
+ * - владелец неизвестен (legacy-строка или другой хост) → финализируем,
490
+ * только когда запись старше `maxUnverifiableAgeMs`.
372
491
  */
373
- export function recoverInterrupted(): number {
374
- const now = new Date().toISOString();
375
- const result = getDb()
492
+
493
+ /** Возраст, после которого запись с непроверяемым владельцем считается осиротевшей. */
494
+ export const UNVERIFIABLE_OWNER_MAX_AGE_MS = 24 * 60 * 60 * 1000;
495
+
496
+ export interface RecoverInterruptedResult {
497
+ /** Сколько записей финализировано как error. */
498
+ recovered: number;
499
+ /** Сколько записей оставлено живым владельцам. */
500
+ keptAlive: number;
501
+ }
502
+
503
+ export interface RecoverInterruptedOptions {
504
+ /** Текущий момент (для тестов). */
505
+ now?: Date;
506
+ /** Порог возраста для записей с непроверяемым владельцем. */
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;
516
+ /** Имя текущего хоста (для тестов). */
517
+ hostname?: string;
518
+ /** Проверка живости PID (для тестов). */
519
+ isAlive?: (pid: number) => boolean;
520
+ }
521
+
522
+ /** Проверяет существование процесса: signal 0 не убивает, только пробует. */
523
+ export function isProcessAlive(pid: number): boolean {
524
+ if (!Number.isInteger(pid) || pid <= 0) return false;
525
+ try {
526
+ process.kill(pid, 0);
527
+ return true;
528
+ } catch (error) {
529
+ // EPERM — процесс существует, но сигнал запрещён; ESRCH — процесса нет.
530
+ return (error as NodeJS.ErrnoException)?.code === "EPERM";
531
+ }
532
+ }
533
+
534
+ export function recoverInterrupted(
535
+ options: RecoverInterruptedOptions = {},
536
+ ): RecoverInterruptedResult {
537
+ const now = options.now ?? new Date();
538
+ const nowIso = now.toISOString();
539
+ const maxAge =
540
+ typeof options.maxUnverifiableAgeMs === "number" &&
541
+ Number.isFinite(options.maxUnverifiableAgeMs)
542
+ ? Math.max(0, options.maxUnverifiableAgeMs)
543
+ : UNVERIFIABLE_OWNER_MAX_AGE_MS;
544
+ const hostname = options.hostname ?? os.hostname();
545
+ const isAlive = options.isAlive ?? isProcessAlive;
546
+ const db = getDb();
547
+ interface InterruptedHistoryRow {
548
+ id: number;
549
+ started_at: string | null;
550
+ owner_pid: number | null;
551
+ owner_host: string | null;
552
+ owner_started_at: string | null;
553
+ }
554
+ const rows = db
376
555
  .prepare(
377
- `UPDATE history SET
378
- status = 'error',
379
- error = CASE
380
- WHEN error IS NULL OR error = '' THEN 'Прервано (сбой/перезагрузка)'
381
- ELSE error
382
- END,
383
- finished_at = COALESCE(finished_at, ?),
384
- duration_ms = COALESCE(
385
- duration_ms,
386
- CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
387
- )
388
- WHERE finished_at IS NULL`,
556
+ `SELECT id, started_at, owner_pid, owner_host, owner_started_at
557
+ FROM history WHERE finished_at IS NULL`,
389
558
  )
390
- .run(now, now);
391
- return Number(result.changes) || 0;
559
+ .all() as unknown as InterruptedHistoryRow[];
560
+ const update = db.prepare(
561
+ `UPDATE history SET
562
+ status = 'error',
563
+ error = CASE
564
+ WHEN error IS NULL OR error = '' THEN 'Прервано (сбой/перезагрузка)'
565
+ ELSE error
566
+ END,
567
+ finished_at = COALESCE(finished_at, ?),
568
+ duration_ms = COALESCE(
569
+ duration_ms,
570
+ CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
571
+ )
572
+ WHERE id = ? AND finished_at IS NULL`,
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;
594
+
595
+ let recovered = 0;
596
+ let keptAlive = 0;
597
+ withTransaction(() => {
598
+ for (const row of rows) {
599
+ const ownerPid = row.owner_pid == null ? null : Number(row.owner_pid);
600
+ const ownerHost = row.owner_host == null ? null : String(row.owner_host);
601
+ const verifiable =
602
+ ownerPid != null && ownerPid > 0 && ownerHost != null && ownerHost === hostname;
603
+
604
+ if (verifiable && ownerPid != null && isAlive(ownerPid)) {
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
+ }
613
+ continue;
614
+ }
615
+ if (!verifiable) {
616
+ const since = Date.parse(String(row.owner_started_at ?? row.started_at ?? ""));
617
+ const age = Number.isFinite(since) ? now.getTime() - since : Infinity;
618
+ if (age < maxAge) {
619
+ keptAlive += 1;
620
+ continue;
621
+ }
622
+ }
623
+
624
+ const result = update.run(nowIso, nowIso, row.id);
625
+ if (Number(result.changes) > 0) recovered += 1;
626
+ }
627
+ });
628
+ return { recovered, keptAlive };
392
629
  }
393
630
 
394
631
  /** Количество записей истории (для миграции и тестов). */
395
632
  export function countHistory(): number {
396
- 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;
397
637
  return Number(row?.count) || 0;
398
638
  }
399
639
 
@@ -401,7 +641,7 @@ export function countHistory(): number {
401
641
  export function countRunningRecords(): number {
402
642
  const row = getDb()
403
643
  .prepare("SELECT COUNT(*) AS count FROM history WHERE finished_at IS NULL")
404
- .get();
644
+ .get() as unknown as { count: unknown } | undefined;
405
645
  return Number(row?.count) || 0;
406
646
  }
407
647
 
@@ -420,7 +660,8 @@ export function listRunningRecords(): RunningHistoryRecord[] {
420
660
  WHERE finished_at IS NULL
421
661
  ORDER BY started_at ASC, id ASC`,
422
662
  )
423
- .all();
663
+ // QA-A2-T3: граница node:sqlite — all() возвращает any[], сужаем к доменному типу.
664
+ .all() as unknown as Pick<HistoryRow, "id" | "task_name" | "started_at">[];
424
665
  return rows.map((row) => ({
425
666
  id: Number(row.id) || 0,
426
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
 
@@ -57,8 +62,8 @@ export function incrementMetricsUnsafe(
57
62
  tokens = 0,
58
63
  costUsd = 0,
59
64
  ): void {
60
- // error — только ошибки и таймауты; partial хранится отдельным счётчиком,
61
- // иначе дашборд показывал частичный запуск как обычную ошибку.
65
+ // error — только ошибки и таймауты; partial и skipped хранятся отдельно
66
+ // (skipped увеличивает только total: запуск не расходовал токены и не завершился).
62
67
  const success = status === "success" ? 1 : 0;
63
68
  const partial = status === "partial" ? 1 : 0;
64
69
  const error = status === "error" || status === "timeout" ? 1 : 0;
@@ -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,