agent-steward 0.0.2 → 0.0.4

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 (263) hide show
  1. package/CHANGELOG.md +45 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +11 -10
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +148 -1017
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +19 -2
  14. package/dist/core/file-watcher.js +9 -9
  15. package/dist/core/git-trigger.js +4 -4
  16. package/dist/core/lock.d.ts +20 -4
  17. package/dist/core/lock.d.ts.map +1 -1
  18. package/dist/core/lock.js +99 -26
  19. package/dist/core/one-shot.d.ts +31 -5
  20. package/dist/core/one-shot.d.ts.map +1 -1
  21. package/dist/core/one-shot.js +78 -10
  22. package/dist/core/opencode-cli.d.ts +28 -0
  23. package/dist/core/opencode-cli.d.ts.map +1 -0
  24. package/dist/core/opencode-cli.js +74 -0
  25. package/dist/core/opencode-models.d.ts +62 -0
  26. package/dist/core/opencode-models.d.ts.map +1 -0
  27. package/dist/core/opencode-models.js +277 -0
  28. package/dist/core/otel.js +2 -2
  29. package/dist/core/ps-wrapper.d.ts +1 -1
  30. package/dist/core/ps-wrapper.d.ts.map +1 -1
  31. package/dist/core/ps-wrapper.js +66 -36
  32. package/dist/core/record-history.d.ts +15 -0
  33. package/dist/core/record-history.d.ts.map +1 -1
  34. package/dist/core/record-history.js +78 -54
  35. package/dist/core/router/dispatch.d.ts +36 -0
  36. package/dist/core/router/dispatch.d.ts.map +1 -0
  37. package/dist/core/router/dispatch.js +59 -0
  38. package/dist/core/router/escalation.d.ts +47 -0
  39. package/dist/core/router/escalation.d.ts.map +1 -0
  40. package/dist/core/router/escalation.js +87 -0
  41. package/dist/core/router/planner.d.ts +53 -0
  42. package/dist/core/router/planner.d.ts.map +1 -0
  43. package/dist/core/router/planner.js +113 -0
  44. package/dist/core/router/rules.d.ts +46 -0
  45. package/dist/core/router/rules.d.ts.map +1 -0
  46. package/dist/core/router/rules.js +85 -0
  47. package/dist/core/run-panel-api.d.ts +94 -0
  48. package/dist/core/run-panel-api.d.ts.map +1 -0
  49. package/dist/core/run-panel-api.js +169 -0
  50. package/dist/core/schedule-gate.js +5 -1
  51. package/dist/core/schedule-v2.d.ts +36 -2
  52. package/dist/core/schedule-v2.d.ts.map +1 -1
  53. package/dist/core/schedule-v2.js +98 -12
  54. package/dist/core/scheduler/at-fallback.d.ts +95 -0
  55. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  56. package/dist/core/scheduler/at-fallback.js +200 -0
  57. package/dist/core/scheduler/linux.d.ts +13 -2
  58. package/dist/core/scheduler/linux.d.ts.map +1 -1
  59. package/dist/core/scheduler/linux.js +67 -13
  60. package/dist/core/scheduler/mac.d.ts +14 -8
  61. package/dist/core/scheduler/mac.d.ts.map +1 -1
  62. package/dist/core/scheduler/mac.js +71 -22
  63. package/dist/core/scheduler/posix.d.ts.map +1 -1
  64. package/dist/core/scheduler/posix.js +37 -2
  65. package/dist/core/scheduler/registry.d.ts +13 -0
  66. package/dist/core/scheduler/registry.d.ts.map +1 -1
  67. package/dist/core/scheduler/registry.js +83 -21
  68. package/dist/core/scheduler/run-now.d.ts +16 -0
  69. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  70. package/dist/core/scheduler/run-now.js +28 -0
  71. package/dist/core/scheduler/windows.d.ts +16 -3
  72. package/dist/core/scheduler/windows.d.ts.map +1 -1
  73. package/dist/core/scheduler/windows.js +249 -96
  74. package/dist/core/secrets.d.ts.map +1 -1
  75. package/dist/core/secrets.js +127 -30
  76. package/dist/core/self-analysis.js +55 -55
  77. package/dist/core/session.d.ts.map +1 -1
  78. package/dist/core/session.js +18 -11
  79. package/dist/core/summary.js +1 -1
  80. package/dist/core/task-name.d.ts +24 -0
  81. package/dist/core/task-name.d.ts.map +1 -0
  82. package/dist/core/task-name.js +40 -0
  83. package/dist/core/triage-chain.js +1 -1
  84. package/dist/core/triage-worker.js +2 -2
  85. package/dist/core/triage.js +1 -1
  86. package/dist/core/wrappers/bash.d.ts.map +1 -1
  87. package/dist/core/wrappers/bash.js +82 -37
  88. package/dist/db/capability-repo.d.ts +83 -0
  89. package/dist/db/capability-repo.d.ts.map +1 -0
  90. package/dist/db/capability-repo.js +182 -0
  91. package/dist/db/history-repo.d.ts +8 -0
  92. package/dist/db/history-repo.d.ts.map +1 -1
  93. package/dist/db/history-repo.js +19 -0
  94. package/dist/db/index.d.ts +6 -0
  95. package/dist/db/index.d.ts.map +1 -1
  96. package/dist/db/index.js +48 -2
  97. package/dist/db/migrate.d.ts.map +1 -1
  98. package/dist/db/migrate.js +3 -1
  99. package/dist/db/run-context.d.ts +103 -0
  100. package/dist/db/run-context.d.ts.map +1 -0
  101. package/dist/db/run-context.js +224 -0
  102. package/dist/db/run-dlq.d.ts +100 -0
  103. package/dist/db/run-dlq.d.ts.map +1 -0
  104. package/dist/db/run-dlq.js +191 -0
  105. package/dist/db/run-journal.d.ts +60 -0
  106. package/dist/db/run-journal.d.ts.map +1 -0
  107. package/dist/db/run-journal.js +143 -0
  108. package/dist/db/run-resume.d.ts +51 -0
  109. package/dist/db/run-resume.d.ts.map +1 -0
  110. package/dist/db/run-resume.js +156 -0
  111. package/dist/db/runs-repo.d.ts +128 -0
  112. package/dist/db/runs-repo.d.ts.map +1 -0
  113. package/dist/db/runs-repo.js +342 -0
  114. package/dist/db/schema.d.ts +16 -2
  115. package/dist/db/schema.d.ts.map +1 -1
  116. package/dist/db/schema.js +342 -35
  117. package/dist/db/settings-repo.d.ts +11 -0
  118. package/dist/db/settings-repo.d.ts.map +1 -1
  119. package/dist/db/settings-repo.js +25 -0
  120. package/dist/db/step-idempotency.d.ts +51 -0
  121. package/dist/db/step-idempotency.d.ts.map +1 -0
  122. package/dist/db/step-idempotency.js +136 -0
  123. package/dist/index.d.ts +5 -5
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +168 -40
  126. package/dist/notifications.js +18 -18
  127. package/dist/profiles.d.ts +7 -3
  128. package/dist/profiles.d.ts.map +1 -1
  129. package/dist/profiles.js +85 -7
  130. package/dist/rpc.d.ts +787 -0
  131. package/dist/rpc.d.ts.map +1 -1
  132. package/dist/rpc.js +324 -0
  133. package/dist/server.d.ts +33 -2
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +115 -54
  136. package/dist/shared/jobs-view.d.ts.map +1 -1
  137. package/dist/skill.js +1 -1
  138. package/dist/task-transfer.d.ts +1 -1
  139. package/dist/task-transfer.d.ts.map +1 -1
  140. package/dist/task-transfer.js +14 -10
  141. package/dist/types.d.ts +20 -4
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +44 -9
  144. package/dist/workspaces.d.ts +25 -3
  145. package/dist/workspaces.d.ts.map +1 -1
  146. package/dist/workspaces.js +44 -9
  147. package/docs/ARCHITECTURE.md +335 -9
  148. package/docs/COMPATIBILITY.md +10 -6
  149. package/docs/CONCEPT.md +183 -91
  150. package/docs/CROSS_PLATFORM.ru.md +11 -9
  151. package/docs/CROSS_PLATFORM.zh.md +11 -9
  152. package/docs/EXECUTION-LOOP.md +196 -0
  153. package/docs/FAQ.md +2 -2
  154. package/docs/FAQ.ru.md +2 -2
  155. package/docs/FAQ.zh.md +2 -2
  156. package/docs/FEATURES.md +5 -4
  157. package/docs/FEATURES.zh.md +5 -4
  158. package/docs/MIGRATION.md +34 -26
  159. package/docs/README.ru.md +27 -8
  160. package/docs/README.zh.md +11 -10
  161. package/docs/SAFETY.md +122 -0
  162. package/docs/SAVINGS.md +29 -0
  163. package/docs/SAVINGS.ru.md +29 -0
  164. package/docs/SAVINGS.zh.md +18 -0
  165. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  166. package/gui-experimental.cjs +8 -8
  167. package/index.js +1 -0
  168. package/locales/en.json +68 -0
  169. package/locales/ru.json +68 -0
  170. package/locales/zh.json +68 -0
  171. package/package.json +57 -11
  172. package/scripts/audit-bundle.mjs +215 -0
  173. package/src/core/analytics.ts +2 -2
  174. package/src/core/audit.ts +17 -17
  175. package/src/core/cron-to-schtasks.ts +14 -93
  176. package/src/core/dlq-api.ts +98 -0
  177. package/src/core/dry-run.ts +51 -27
  178. package/src/core/file-watcher.ts +17 -17
  179. package/src/core/git-trigger.ts +9 -9
  180. package/src/core/glob.ts +1 -1
  181. package/src/core/local-ai.ts +2 -2
  182. package/src/core/lock.ts +104 -31
  183. package/src/core/matrix.ts +31 -31
  184. package/src/core/native-notify.ts +2 -2
  185. package/src/core/one-shot.ts +91 -13
  186. package/src/core/opencode-cli.ts +103 -0
  187. package/src/core/opencode-models.ts +315 -0
  188. package/src/core/otel.ts +4 -4
  189. package/src/core/permissions.ts +5 -5
  190. package/src/core/prometheus.ts +17 -17
  191. package/src/core/ps-wrapper.ts +68 -38
  192. package/src/core/record-history.ts +114 -76
  193. package/src/core/retention.ts +3 -3
  194. package/src/core/router/dispatch.ts +94 -0
  195. package/src/core/router/escalation.ts +129 -0
  196. package/src/core/router/planner.ts +166 -0
  197. package/src/core/router/rules.ts +109 -0
  198. package/src/core/run-panel-api.ts +262 -0
  199. package/src/core/savings.ts +1 -1
  200. package/src/core/schedule-gate.ts +17 -13
  201. package/src/core/schedule-v2.ts +138 -29
  202. package/src/core/scheduler/at-fallback.ts +298 -0
  203. package/src/core/scheduler/index.ts +3 -3
  204. package/src/core/scheduler/linux.ts +92 -19
  205. package/src/core/scheduler/logs.ts +1 -1
  206. package/src/core/scheduler/mac.ts +112 -60
  207. package/src/core/scheduler/posix.ts +35 -2
  208. package/src/core/scheduler/registry.ts +109 -26
  209. package/src/core/scheduler/run-now.ts +32 -0
  210. package/src/core/scheduler/windows.ts +295 -125
  211. package/src/core/secrets.ts +139 -39
  212. package/src/core/self-analysis.ts +61 -61
  213. package/src/core/session.ts +26 -13
  214. package/src/core/structured-log.ts +3 -3
  215. package/src/core/summary.ts +25 -25
  216. package/src/core/task-name.ts +67 -0
  217. package/src/core/telegram.ts +16 -16
  218. package/src/core/triage-chain.ts +4 -4
  219. package/src/core/triage-compare.ts +8 -8
  220. package/src/core/triage-rules.ts +4 -4
  221. package/src/core/triage-shadow.ts +7 -7
  222. package/src/core/triage-worker.ts +6 -6
  223. package/src/core/triage.ts +23 -23
  224. package/src/core/watch-paths.ts +1 -1
  225. package/src/core/wrappers/bash.ts +90 -45
  226. package/src/db/capability-repo.ts +285 -0
  227. package/src/db/git-state-repo.ts +1 -1
  228. package/src/db/history-repo.ts +44 -22
  229. package/src/db/index.ts +53 -7
  230. package/src/db/metrics-repo.ts +10 -10
  231. package/src/db/migrate.ts +13 -11
  232. package/src/db/recovery.ts +3 -3
  233. package/src/db/run-context.ts +370 -0
  234. package/src/db/run-dlq.ts +310 -0
  235. package/src/db/run-journal.ts +212 -0
  236. package/src/db/run-resume.ts +256 -0
  237. package/src/db/runs-repo.ts +504 -0
  238. package/src/db/schema.ts +357 -44
  239. package/src/db/settings-repo.ts +33 -2
  240. package/src/db/step-idempotency.ts +185 -0
  241. package/src/db/tasks-repo.ts +10 -10
  242. package/src/db/templates-repo.ts +7 -7
  243. package/src/gui.tsx +516 -1
  244. package/src/history.ts +4 -4
  245. package/src/i18n.ts +7 -7
  246. package/src/index.ts +465 -308
  247. package/src/integrations.ts +6 -6
  248. package/src/notifications.ts +76 -76
  249. package/src/profiles.ts +98 -7
  250. package/src/rpc.ts +347 -1
  251. package/src/schtasks.ts +2 -2
  252. package/src/server.ts +155 -78
  253. package/src/settings.ts +44 -44
  254. package/src/shared/jobs-view.ts +60 -60
  255. package/src/skill.ts +1 -1
  256. package/src/task-transfer.ts +58 -56
  257. package/src/templates.ts +1 -1
  258. package/src/types.ts +54 -10
  259. package/src/workspaces.ts +73 -24
  260. package/dist/core/self-analysis.test.d.ts +0 -2
  261. package/dist/core/self-analysis.test.d.ts.map +0 -1
  262. package/dist/core/self-analysis.test.js +0 -219
  263. package/dist/gui-experimental.cjs +0 -1
@@ -0,0 +1,504 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { getDb, withTransaction } from "./index.js";
3
+
4
+ /**
5
+ * Репозиторий durable-состояния запуска (Спринт 36.1).
6
+ *
7
+ * `runs` — единица выполнения, `run_steps` — её шаги. Строки создаются до
8
+ * старта работы и обновляются на каждом переходе, поэтому после сбоя процесса
9
+ * можно понять, где именно остановился запуск (основа resume в 36.2).
10
+ *
11
+ * Переходы статусов проверяются здесь, а не в SQL: CHECK-ограничения в SQLite
12
+ * пришлось бы переписывать при каждом новом статусе (например, DLQ в 36.4).
13
+ */
14
+
15
+ /** Статусы запуска: pending → running → passed/failed; paused — пауза с контекстом (36.7). */
16
+ export type RunStatus = "pending" | "running" | "paused" | "passed" | "failed" | "cancelled";
17
+
18
+ /** Статусы шага: pending → running → passed/failed; skipped — осознанный пропуск. */
19
+ export type StepStatus = "pending" | "running" | "passed" | "failed" | "skipped";
20
+
21
+ /** Финальные статусы шага — из них нет переходов, кроме явного retry. */
22
+ const TERMINAL_STEP_STATUSES: ReadonlySet<StepStatus> = new Set([
23
+ "passed",
24
+ "failed",
25
+ "skipped",
26
+ ]);
27
+
28
+ const RUN_TRANSITIONS: Record<RunStatus, readonly RunStatus[]> = {
29
+ // Из pending можно как стартовать, так и сразу поставить на паузу (36.7).
30
+ pending: ["running", "paused", "cancelled"],
31
+ // paused → running — явное возобновление; paused → passed — пауза после
32
+ // последнего шага, когда продолжать уже нечего.
33
+ running: ["paused", "passed", "failed", "cancelled"],
34
+ paused: ["running", "passed", "cancelled"],
35
+ passed: [],
36
+ // failed → running — явное возобновление после краха (36.2), только через reopenRun.
37
+ failed: ["running"],
38
+ cancelled: [],
39
+ };
40
+
41
+ const STEP_TRANSITIONS: Record<StepStatus, readonly StepStatus[]> = {
42
+ pending: ["running", "failed", "skipped"],
43
+ running: ["passed", "failed"],
44
+ passed: [],
45
+ failed: [],
46
+ skipped: [],
47
+ };
48
+
49
+ export class InvalidTransitionError extends Error {
50
+ constructor(
51
+ readonly entity: "run" | "step",
52
+ readonly from: string,
53
+ readonly to: string,
54
+ ) {
55
+ super(`Недопустимый переход ${entity}: ${from} → ${to}`);
56
+ this.name = "InvalidTransitionError";
57
+ }
58
+ }
59
+
60
+ export interface RunRecord {
61
+ id: string;
62
+ taskName: string;
63
+ status: RunStatus;
64
+ parentRunId: string | null;
65
+ workspaceId: string | null;
66
+ startedAt: string | null;
67
+ finishedAt: string | null;
68
+ error: string | null;
69
+ metadata: unknown;
70
+ createdAt: string;
71
+ updatedAt: string;
72
+ }
73
+
74
+ export interface RunStepRecord {
75
+ id: string;
76
+ runId: string;
77
+ stepName: string;
78
+ /** Порядок шага в линейной цепочке (0, 1, 2...). */
79
+ position: number;
80
+ status: StepStatus;
81
+ attempt: number;
82
+ idempotencyKey: string | null;
83
+ startedAt: string | null;
84
+ finishedAt: string | null;
85
+ error: string | null;
86
+ output: unknown;
87
+ createdAt: string;
88
+ updatedAt: string;
89
+ }
90
+
91
+ export interface CreateRunOptions {
92
+ /** Имя задачи; для ручного/DAG-запуска может быть синтетическим. */
93
+ taskName: string;
94
+ parentRunId?: string | null;
95
+ workspaceId?: string | null;
96
+ metadata?: unknown;
97
+ /** Начальный статус; по умолчанию pending. */
98
+ status?: Extract<RunStatus, "pending" | "running">;
99
+ /** Момент старта; по умолчанию now, если статус running. */
100
+ startedAt?: string;
101
+ /** Шаги создаются в той же транзакции, что и запуск. */
102
+ steps?: CreateStepOptions[];
103
+ }
104
+
105
+ export interface CreateStepOptions {
106
+ stepName: string;
107
+ idempotencyKey?: string | null;
108
+ status?: StepStatus;
109
+ /** Полезная нагрузка (JSON-сериализуемая). */
110
+ output?: unknown;
111
+ }
112
+
113
+ export interface FinishOptions {
114
+ error?: string | null;
115
+ output?: unknown;
116
+ }
117
+
118
+ function nowIso(): string {
119
+ return new Date().toISOString();
120
+ }
121
+
122
+ function parseJson(value: unknown): unknown {
123
+ if (value == null) return null;
124
+ try {
125
+ return JSON.parse(String(value));
126
+ } catch {
127
+ return String(value);
128
+ }
129
+ }
130
+
131
+ function serializeJson(value: unknown): string | null {
132
+ if (value === undefined) return null;
133
+ try {
134
+ return JSON.stringify(value);
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ function runRowToRecord(row: any): RunRecord {
141
+ return {
142
+ id: String(row.id),
143
+ taskName: String(row.task_name),
144
+ status: String(row.status) as RunStatus,
145
+ parentRunId: row.parent_run_id == null ? null : String(row.parent_run_id),
146
+ workspaceId: row.workspace_id == null ? null : String(row.workspace_id),
147
+ startedAt: row.started_at == null ? null : String(row.started_at),
148
+ finishedAt: row.finished_at == null ? null : String(row.finished_at),
149
+ error: row.error == null ? null : String(row.error),
150
+ metadata: parseJson(row.metadata_json),
151
+ createdAt: String(row.created_at),
152
+ updatedAt: String(row.updated_at),
153
+ };
154
+ }
155
+
156
+ function stepRowToRecord(row: any): RunStepRecord {
157
+ return {
158
+ id: String(row.id),
159
+ runId: String(row.run_id),
160
+ stepName: String(row.step_name),
161
+ position: Number(row.position) || 0,
162
+ status: String(row.status) as StepStatus,
163
+ attempt: Number(row.attempt) || 1,
164
+ idempotencyKey: row.idempotency_key == null ? null : String(row.idempotency_key),
165
+ startedAt: row.started_at == null ? null : String(row.started_at),
166
+ finishedAt: row.finished_at == null ? null : String(row.finished_at),
167
+ error: row.error == null ? null : String(row.error),
168
+ output: parseJson(row.output_json),
169
+ createdAt: String(row.created_at),
170
+ updatedAt: String(row.updated_at),
171
+ };
172
+ }
173
+
174
+ function assertTransition(
175
+ entity: "run" | "step",
176
+ from: string,
177
+ to: string,
178
+ allowed: readonly string[],
179
+ ): void {
180
+ if (!allowed.includes(to)) throw new InvalidTransitionError(entity, from, to);
181
+ }
182
+
183
+ const INSERT_RUN_SQL = `INSERT INTO runs (
184
+ id, task_name, status, parent_run_id, workspace_id,
185
+ started_at, finished_at, error, metadata_json, created_at, updated_at
186
+ ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)`;
187
+
188
+ const INSERT_STEP_SQL = `INSERT INTO run_steps (
189
+ id, run_id, step_name, position, status, attempt, idempotency_key,
190
+ started_at, finished_at, error, output_json, created_at, updated_at
191
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)`;
192
+
193
+ /** Создаёт запуск и (опционально) его шаги одной транзакцией. */
194
+ export function createRun(options: CreateRunOptions): RunRecord {
195
+ const id = randomUUID();
196
+ const timestamp = nowIso();
197
+ const status: RunStatus = options.status ?? "pending";
198
+ const startedAt =
199
+ options.startedAt ?? (status === "running" ? timestamp : null);
200
+
201
+ withTransaction(() => {
202
+ getDb()
203
+ .prepare(INSERT_RUN_SQL)
204
+ .run(
205
+ id,
206
+ options.taskName,
207
+ status,
208
+ options.parentRunId ?? null,
209
+ options.workspaceId ?? null,
210
+ startedAt,
211
+ serializeJson(options.metadata),
212
+ timestamp,
213
+ timestamp,
214
+ );
215
+
216
+ let position = 0;
217
+ for (const step of options.steps ?? []) {
218
+ insertStepUnsafe(id, step, timestamp, position);
219
+ position += 1;
220
+ }
221
+ });
222
+
223
+ const created = getRun(id);
224
+ if (!created) throw new Error("Запуск не найден сразу после создания");
225
+ return created;
226
+ }
227
+
228
+ function insertStepUnsafe(
229
+ runId: string,
230
+ options: CreateStepOptions,
231
+ timestamp: string,
232
+ position: number,
233
+ ): string {
234
+ const id = randomUUID();
235
+ const status: StepStatus = options.status ?? "pending";
236
+ const startedAt = status === "running" ? timestamp : null;
237
+ getDb()
238
+ .prepare(INSERT_STEP_SQL)
239
+ .run(
240
+ id,
241
+ runId,
242
+ options.stepName,
243
+ position,
244
+ status,
245
+ 1,
246
+ options.idempotencyKey ?? null,
247
+ startedAt,
248
+ serializeJson(options.output),
249
+ timestamp,
250
+ timestamp,
251
+ );
252
+ return id;
253
+ }
254
+
255
+ /** Следующая позиция шага в цепочке запуска. */
256
+ function nextStepPosition(runId: string): number {
257
+ const row = getDb()
258
+ .prepare("SELECT COALESCE(MAX(position), -1) + 1 AS next FROM run_steps WHERE run_id = ?")
259
+ .get(runId) as { next?: number } | undefined;
260
+ return Number(row?.next) || 0;
261
+ }
262
+
263
+ /** Добавляет шаг в существующий запуск. Имя шага уникально внутри запуска. */
264
+ export function createStep(runId: string, options: CreateStepOptions): RunStepRecord {
265
+ const id = withTransaction(() => insertStepUnsafe(runId, options, nowIso(), nextStepPosition(runId)));
266
+ const step = getStepById(id);
267
+ if (!step) throw new Error("Шаг не найден сразу после создания");
268
+ return step;
269
+ }
270
+
271
+ /** Создаёт все шаги запуска в одной транзакции (для DAG-описания). */
272
+ export function createSteps(runId: string, steps: CreateStepOptions[]): RunStepRecord[] {
273
+ const timestamp = nowIso();
274
+ withTransaction(() => {
275
+ let position = nextStepPosition(runId);
276
+ for (const step of steps) {
277
+ insertStepUnsafe(runId, step, timestamp, position);
278
+ position += 1;
279
+ }
280
+ });
281
+ return listRunSteps(runId);
282
+ }
283
+
284
+ export function getRun(id: string): RunRecord | undefined {
285
+ const row = getDb().prepare("SELECT * FROM runs WHERE id = ?").get(id);
286
+ return row ? runRowToRecord(row) : undefined;
287
+ }
288
+
289
+ /** Список запусков (новые сверху). Без taskName — по всем задачам. */
290
+ export function listRuns(taskName?: string | null, limit = 100): RunRecord[] {
291
+ const safeLimit = Math.max(1, Math.min(10000, Math.floor(limit) || 1));
292
+ if (taskName) {
293
+ return getDb()
294
+ .prepare(
295
+ `SELECT * FROM runs WHERE lower(task_name) = lower(?)
296
+ ORDER BY created_at DESC, id DESC LIMIT ?`,
297
+ )
298
+ .all(taskName, safeLimit)
299
+ .map(runRowToRecord);
300
+ }
301
+ return getDb()
302
+ .prepare("SELECT * FROM runs ORDER BY created_at DESC, id DESC LIMIT ?")
303
+ .all(safeLimit)
304
+ .map(runRowToRecord);
305
+ }
306
+
307
+ /** pending → running. Возвращает false, если запуск не найден. */
308
+ export function startRun(id: string, startedAt = nowIso()): boolean {
309
+ return withTransaction(() => {
310
+ const run = getRun(id);
311
+ if (!run) return false;
312
+ assertTransition("run", run.status, "running", RUN_TRANSITIONS[run.status]);
313
+ getDb()
314
+ .prepare(
315
+ "UPDATE runs SET status = 'running', started_at = ?, updated_at = ? WHERE id = ?",
316
+ )
317
+ .run(startedAt, nowIso(), id);
318
+ return true;
319
+ });
320
+ }
321
+
322
+ /**
323
+ * pending/running → paused (Спринт 36.7).
324
+ *
325
+ * Пауза ставится только между шагами: если шаг уже выполняется, вызывающий
326
+ * код должен дождаться его завершения. `finished_at` не заполняется — запуск
327
+ * не завершён, а приостановлен.
328
+ */
329
+ export function pauseRunRecord(id: string, pausedAt = nowIso()): boolean {
330
+ return withTransaction(() => {
331
+ const run = getRun(id);
332
+ if (!run) return false;
333
+ assertTransition("run", run.status, "paused", RUN_TRANSITIONS[run.status]);
334
+ getDb()
335
+ .prepare("UPDATE runs SET status = 'paused', updated_at = ? WHERE id = ?")
336
+ .run(pausedAt, id);
337
+ return true;
338
+ });
339
+ }
340
+
341
+ /** Завершает запуск (passed/failed/cancelled) и фиксирует finished_at. */
342
+ export function finishRun(
343
+ id: string,
344
+ status: Extract<RunStatus, "passed" | "failed" | "cancelled">,
345
+ options: FinishOptions = {},
346
+ ): boolean {
347
+ return withTransaction(() => {
348
+ const run = getRun(id);
349
+ if (!run) return false;
350
+ assertTransition("run", run.status, status, RUN_TRANSITIONS[run.status]);
351
+ const timestamp = nowIso();
352
+ getDb()
353
+ .prepare("UPDATE runs SET status = ?, finished_at = ?, error = ?, updated_at = ? WHERE id = ?")
354
+ .run(status, timestamp, options.error ?? null, timestamp, id);
355
+ return true;
356
+ });
357
+ }
358
+
359
+ /**
360
+ * failed/paused → running: возобновление прогона после краха или паузы (36.2, 36.7).
361
+ *
362
+ * Не сбрасывает номера попыток шагов — они растут через `retryStep` при
363
+ * повторе конкретного шага.
364
+ */
365
+ export function reopenRun(id: string, startedAt = nowIso()): boolean {
366
+ return withTransaction(() => {
367
+ const run = getRun(id);
368
+ if (!run) return false;
369
+ assertTransition("run", run.status, "running", RUN_TRANSITIONS[run.status]);
370
+ getDb()
371
+ .prepare(
372
+ `UPDATE runs SET status = 'running', started_at = COALESCE(started_at, ?),
373
+ finished_at = NULL, error = NULL, updated_at = ? WHERE id = ?`,
374
+ )
375
+ .run(startedAt, nowIso(), id);
376
+ return true;
377
+ });
378
+ }
379
+
380
+ export function getStepById(id: string): RunStepRecord | undefined {
381
+ const row = getDb().prepare("SELECT * FROM run_steps WHERE id = ?").get(id);
382
+ return row ? stepRowToRecord(row) : undefined;
383
+ }
384
+
385
+ /** Шаг по имени внутри запуска (имя уникально). */
386
+ export function getStep(runId: string, stepName: string): RunStepRecord | undefined {
387
+ const row = getDb()
388
+ .prepare("SELECT * FROM run_steps WHERE run_id = ? AND step_name = ?")
389
+ .get(runId, stepName);
390
+ return row ? stepRowToRecord(row) : undefined;
391
+ }
392
+
393
+ /** Все шаги запуска в порядке создания. */
394
+ export function listRunSteps(runId: string): RunStepRecord[] {
395
+ return getDb()
396
+ .prepare("SELECT * FROM run_steps WHERE run_id = ? ORDER BY position ASC, rowid ASC")
397
+ .all(runId)
398
+ .map(stepRowToRecord);
399
+ }
400
+
401
+ /** Поиск шага по ключу идемпотентности (36.3) в пределах запуска. */
402
+ export function findStepByIdempotencyKey(
403
+ runId: string,
404
+ idempotencyKey: string,
405
+ ): RunStepRecord | undefined {
406
+ const row = getDb()
407
+ .prepare("SELECT * FROM run_steps WHERE run_id = ? AND idempotency_key = ? LIMIT 1")
408
+ .get(runId, idempotencyKey);
409
+ return row ? stepRowToRecord(row) : undefined;
410
+ }
411
+
412
+ /** pending → running. Возвращает false, если шаг не найден. */
413
+ export function startStep(id: string, startedAt = nowIso()): boolean {
414
+ return withTransaction(() => {
415
+ const step = getStepById(id);
416
+ if (!step) return false;
417
+ assertTransition("step", step.status, "running", STEP_TRANSITIONS[step.status]);
418
+ getDb()
419
+ .prepare(
420
+ `UPDATE run_steps SET status = 'running', started_at = ?, finished_at = NULL,
421
+ error = NULL, updated_at = ? WHERE id = ?`,
422
+ )
423
+ .run(startedAt, nowIso(), id);
424
+ return true;
425
+ });
426
+ }
427
+
428
+ /** running → passed/failed; pending → skipped допустим. */
429
+ export function finishStep(
430
+ id: string,
431
+ status: Extract<StepStatus, "passed" | "failed" | "skipped">,
432
+ options: FinishOptions = {},
433
+ ): boolean {
434
+ return withTransaction(() => {
435
+ const step = getStepById(id);
436
+ if (!step) return false;
437
+ assertTransition("step", step.status, status, STEP_TRANSITIONS[step.status]);
438
+ const timestamp = nowIso();
439
+ getDb()
440
+ .prepare(
441
+ `UPDATE run_steps SET status = ?, finished_at = ?, error = ?, output_json = ?,
442
+ updated_at = ? WHERE id = ?`,
443
+ )
444
+ .run(
445
+ status,
446
+ timestamp,
447
+ options.error ?? null,
448
+ options.output === undefined ? null : serializeJson(options.output),
449
+ timestamp,
450
+ id,
451
+ );
452
+ return true;
453
+ });
454
+ }
455
+
456
+ /**
457
+ * Повтор упавшего шага: failed → running, attempt + 1.
458
+ *
459
+ * Это единственный переход из финального статуса шага. Предыдущая попытка
460
+ * остаётся видимой в счётчике attempt; для 36.4 (DLQ) здесь появится лимит.
461
+ */
462
+ export function retryStep(id: string, startedAt = nowIso()): boolean {
463
+ return withTransaction(() => {
464
+ const step = getStepById(id);
465
+ if (!step) return false;
466
+ if (step.status !== "failed") {
467
+ throw new InvalidTransitionError("step", step.status, "running");
468
+ }
469
+ getDb()
470
+ .prepare(
471
+ `UPDATE run_steps SET status = 'running', attempt = attempt + 1,
472
+ started_at = ?, finished_at = NULL, error = NULL, updated_at = ? WHERE id = ?`,
473
+ )
474
+ .run(startedAt, nowIso(), id);
475
+ return true;
476
+ });
477
+ }
478
+
479
+ /** Количество шагов запуска (для health/отчётов). */
480
+ export function countRunSteps(runId: string): number {
481
+ const row = getDb()
482
+ .prepare("SELECT COUNT(*) AS count FROM run_steps WHERE run_id = ?")
483
+ .get(runId);
484
+ return Number(row?.count) || 0;
485
+ }
486
+
487
+ /** Удаляет запуск; шаги удаляются каскадом (ON DELETE CASCADE). */
488
+ export function deleteRun(id: string): boolean {
489
+ const result = getDb().prepare("DELETE FROM runs WHERE id = ?").run(id);
490
+ return Number(result.changes) > 0;
491
+ }
492
+
493
+ /** Готова ли схема к работе с durable DAG (runs + run_steps). */
494
+ export function isRunStateReady(): boolean {
495
+ const rows = getDb()
496
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('runs', 'run_steps')")
497
+ .all();
498
+ return rows.length === 2;
499
+ }
500
+
501
+ /** Терминальный ли статус шага (для resume/cleanup в следующих подзадачах). */
502
+ export function isTerminalStepStatus(status: StepStatus): boolean {
503
+ return TERMINAL_STEP_STATUSES.has(status);
504
+ }