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,212 @@
1
+ import { getDb, withTransaction } from "./index.js";
2
+ import {
3
+ finishStep,
4
+ getRun,
5
+ getStep,
6
+ retryStep,
7
+ startRun,
8
+ startStep,
9
+ type FinishOptions,
10
+ type RunRecord,
11
+ type RunStepRecord,
12
+ } from "./runs-repo.js";
13
+
14
+ /**
15
+ * Журнал выполнения шагов (Sprint 36.1.b).
16
+ *
17
+ * Каждый переход шага пишется отдельной транзакцией и фиксируется в WAL
18
+ * **до** запуска тела шага и **после** него. Если процесс убьют посреди шага,
19
+ * в БД останется строка `running` с номером попытки `attempt`: её помечает
20
+ * `recoverInterruptedSteps()`, а повтор идёт через `retryStep()` с `attempt + 1`.
21
+ */
22
+
23
+ /** Текст ошибки, которым помечается шаг, прерванный падением процесса. */
24
+ export const STEP_INTERRUPTED_ERROR = "Прервано падением процесса";
25
+
26
+ /** Опции начала попытки. */
27
+ export interface BeginStepOptions {
28
+ /** Начать запуск, если он ещё в статусе pending (по умолчанию true). */
29
+ startRun?: boolean;
30
+ }
31
+
32
+ /** Результат выполнения шага через `runStepStatefully`. */
33
+ export interface StepExecution<T> {
34
+ /** Состояние шага после завершения. */
35
+ step: RunStepRecord;
36
+ /** Значение, которое вернуло тело шага. */
37
+ result: T;
38
+ /** Номер попытки, с которым выполнялся шаг. */
39
+ attempt: number;
40
+ }
41
+
42
+ function nowIso(): string {
43
+ return new Date().toISOString();
44
+ }
45
+
46
+ function errorMessage(err: unknown): string {
47
+ if (err instanceof Error) return err.message;
48
+ return String(err);
49
+ }
50
+
51
+ /**
52
+ * Открывает попытку шага: run pending → running (если нужно), шаг pending → running.
53
+ *
54
+ * Запись коммитится до возврата управления, поэтому вызывающий код может
55
+ * безопасно запускать побочные эффекты: факт старта уже на диске.
56
+ *
57
+ * Если шаг остался `failed` после падения — выполняется `retryStep`, и номер
58
+ * попытки увеличивается, а не начинается заново.
59
+ */
60
+ export function beginStepAttempt(
61
+ runId: string,
62
+ stepName: string,
63
+ options: BeginStepOptions = {},
64
+ ): RunStepRecord {
65
+ if (options.startRun !== false) {
66
+ const run = requireRun(runId);
67
+ if (run.status === "pending") startRun(runId);
68
+ }
69
+
70
+ const step = requireStep(runId, stepName);
71
+ if (step.status === "failed") {
72
+ retryStep(step.id);
73
+ } else {
74
+ startStep(step.id);
75
+ }
76
+
77
+ return requireStep(runId, stepName);
78
+ }
79
+
80
+ /** Закрывает попытку успехом: running → passed, сохраняет output. */
81
+ export function recordStepSuccess(
82
+ runId: string,
83
+ stepName: string,
84
+ output?: unknown,
85
+ ): RunStepRecord {
86
+ completeStep(runId, stepName, "passed", { output });
87
+ return requireStep(runId, stepName);
88
+ }
89
+
90
+ /** Закрывает попытку ошибкой: running → failed, сохраняет текст ошибки. */
91
+ export function recordStepFailure(
92
+ runId: string,
93
+ stepName: string,
94
+ error: unknown,
95
+ ): RunStepRecord {
96
+ completeStep(runId, stepName, "failed", { error: errorMessage(error) });
97
+ return requireStep(runId, stepName);
98
+ }
99
+
100
+ /**
101
+ * Выполняет шаг с журналированием: состояние `running` фиксируется до вызова
102
+ * `body`, результат (`passed`/`failed`) — после. Ошибка тела не теряется:
103
+ * шаг помечается failed, исключение пробрасывается дальше.
104
+ */
105
+ export function runStepStatefully<T>(
106
+ runId: string,
107
+ stepName: string,
108
+ body: () => T,
109
+ options: BeginStepOptions = {},
110
+ ): StepExecution<T> {
111
+ const attempt = beginStepAttempt(runId, stepName, options).attempt;
112
+ let result: T;
113
+ try {
114
+ result = body();
115
+ } catch (err) {
116
+ recordStepFailure(runId, stepName, err);
117
+ throw err;
118
+ }
119
+ const step = recordStepSuccess(runId, stepName, result);
120
+ return { step, result, attempt };
121
+ }
122
+
123
+ /** Асинхронный вариант `runStepStatefully` для шагов с I/O. */
124
+ export async function runStepStatefullyAsync<T>(
125
+ runId: string,
126
+ stepName: string,
127
+ body: () => Promise<T> | T,
128
+ options: BeginStepOptions = {},
129
+ ): Promise<StepExecution<T>> {
130
+ const attempt = beginStepAttempt(runId, stepName, options).attempt;
131
+ let result: T;
132
+ try {
133
+ result = await body();
134
+ } catch (err) {
135
+ recordStepFailure(runId, stepName, err);
136
+ throw err;
137
+ }
138
+ const step = recordStepSuccess(runId, stepName, result);
139
+ return { step, result, attempt };
140
+ }
141
+
142
+ /**
143
+ * Помечает все зависшие `running`-шаги как failed, сохраняя `attempt`.
144
+ *
145
+ * Возвращает обновлённые записи. `attempt` не сбрасывается — следующая попытка
146
+ * получит `attempt + 1` через `retryStep`, поэтому номер попытки переживает
147
+ * падение процесса и восстановление.
148
+ */
149
+ export function recoverInterruptedSteps(runId?: string): RunStepRecord[] {
150
+ const running = listRunningSteps(runId);
151
+ if (running.length === 0) return [];
152
+
153
+ return withTransaction(() => {
154
+ const timestamp = nowIso();
155
+ const update = getDb().prepare(
156
+ `UPDATE run_steps SET status = 'failed', error = ?, finished_at = ?,
157
+ updated_at = ? WHERE id = ? AND status = 'running'`,
158
+ );
159
+ for (const step of running) {
160
+ update.run(STEP_INTERRUPTED_ERROR, timestamp, timestamp, step.id);
161
+ }
162
+ return running.map((step) => requireStep(step.runId, step.stepName));
163
+ });
164
+ }
165
+
166
+ /** Список шагов в статусе running (для диагностики и восстановления). */
167
+ export function listRunningSteps(runId?: string): RunStepRecord[] {
168
+ const sql = runId
169
+ ? "SELECT run_id, step_name FROM run_steps WHERE status = 'running' AND run_id = ? ORDER BY created_at"
170
+ : "SELECT run_id, step_name FROM run_steps WHERE status = 'running' ORDER BY created_at";
171
+ const statement = getDb().prepare(sql);
172
+ const rows = (runId ? statement.all(runId) : statement.all()) as {
173
+ run_id: string;
174
+ step_name: string;
175
+ }[];
176
+
177
+ const steps: RunStepRecord[] = [];
178
+ for (const row of rows) {
179
+ const step = getStep(String(row.run_id), String(row.step_name));
180
+ if (step && step.status === "running") steps.push(step);
181
+ }
182
+ return steps;
183
+ }
184
+
185
+ /** Запуск по id либо ошибка (удобно для журнала и тестов). */
186
+ export function requireRun(runId: string): RunRecord {
187
+ const run = getRun(runId);
188
+ if (!run) throw new Error(`Запуск не найден: ${runId}`);
189
+ return run;
190
+ }
191
+
192
+ function requireStep(runId: string, stepName: string): RunStepRecord {
193
+ const step = getStep(runId, stepName);
194
+ if (!step) throw new Error(`Шаг не найден: ${runId}/${stepName}`);
195
+ return step;
196
+ }
197
+
198
+ function completeStep(
199
+ runId: string,
200
+ stepName: string,
201
+ status: "passed" | "failed",
202
+ options: FinishOptions,
203
+ ): void {
204
+ const step = requireStep(runId, stepName);
205
+ if (step.status !== "running") {
206
+ // Повторная запись результата — ошибка вызывающего кода, а не «тихий» пропуск.
207
+ throw new Error(
208
+ `Шаг ${runId}/${stepName} не выполняется (статус ${step.status}), запись ${status} невозможна.`,
209
+ );
210
+ }
211
+ finishStep(step.id, status, options);
212
+ }
@@ -0,0 +1,256 @@
1
+ import {
2
+ finishRun,
3
+ getRun,
4
+ listRunSteps,
5
+ reopenRun,
6
+ startRun,
7
+ type RunRecord,
8
+ type RunStepRecord,
9
+ } from "./runs-repo.js";
10
+ import {
11
+ recoverInterruptedSteps,
12
+ requireRun,
13
+ runStepStatefully,
14
+ runStepStatefullyAsync,
15
+ } from "./run-journal.js";
16
+ import {
17
+ consumeInjections,
18
+ consumeOrphanInjections,
19
+ pendingInjectionsForStep,
20
+ type StepContext,
21
+ } from "./run-context.js";
22
+
23
+ /**
24
+ * Resume с середины (Sprint 36.2).
25
+ *
26
+ * Линейная цепочка шагов хранится в `run_steps` в порядке создания. Возобновление
27
+ * находит первый незавершённый шаг (не `passed`/`skipped`), помечает зависшие
28
+ * `running` как прерванные и выполняет остаток цепочки через журнал 36.1.b.
29
+ * Уже успешные шаги повторно не запускаются, а `attempt` упавших растёт.
30
+ */
31
+
32
+ /** Обработчик тела шага. Получает актуальную запись шага и контекст паузы. */
33
+ export type StepHandler = (step: RunStepRecord, context: StepContext) => unknown;
34
+
35
+ /** Опции возобновления. */
36
+ export interface ResumeOptions {
37
+ /** Тела шагов по имени. Отсутствие обработчика — ошибка до запуска цепочки. */
38
+ handlers: Record<string, StepHandler>;
39
+ /** Восстанавливать зависшие `running`-шаги перед продолжением (по умолчанию true). */
40
+ recover?: boolean;
41
+ /** Останавливаться на первой ошибке (по умолчанию true). */
42
+ stopOnError?: boolean;
43
+ }
44
+
45
+ /** Результат возобновления прогона. */
46
+ export interface ResumeResult {
47
+ /** Состояние запуска после возобновления. */
48
+ run: RunRecord;
49
+ /** С какого шага продолжили (`null`, если продолжать нечего). */
50
+ resumedFrom: string | null;
51
+ /** Номер попытки, с которым выполнялся первый возобновлённый шаг. */
52
+ resumedFromAttempt: number | null;
53
+ /** Шаги, выполненные в этот раз. */
54
+ executed: string[];
55
+ /** Шаги, пропущенные как уже завершённые. */
56
+ skipped: string[];
57
+ /** Идентификаторы вставок контекста, переданных шагам в этот раз. */
58
+ injected: string[];
59
+ /** Первый упавший шаг, если цепочка остановилась. */
60
+ failedStep: string | null;
61
+ /** Текст ошибки упавшего шага. */
62
+ error: string | null;
63
+ }
64
+
65
+ /** Завершён ли шаг успешно (повторять не нужно). */
66
+ function isStepDone(status: RunStepRecord["status"]): boolean {
67
+ return status === "passed" || status === "skipped";
68
+ }
69
+
70
+ /** Первый незавершённый шаг цепочки либо null. Без восстановления состояния. */
71
+ export function findResumeStep(runId: string): RunStepRecord | null {
72
+ const steps = listRunSteps(runId);
73
+ return steps.find((step) => !isStepDone(step.status)) ?? null;
74
+ }
75
+
76
+ interface ResumePlan {
77
+ steps: RunStepRecord[];
78
+ startIndex: number;
79
+ }
80
+
81
+ function prepareResume(runId: string, options: ResumeOptions): ResumePlan {
82
+ const run = requireRun(runId);
83
+ if (run.status === "cancelled") {
84
+ throw new Error(`Запуск отменён, возобновление невозможно: ${runId}`);
85
+ }
86
+
87
+ if (options.recover !== false) recoverInterruptedSteps(runId);
88
+
89
+ const steps = listRunSteps(runId);
90
+ const startIndex = steps.findIndex((step) => !isStepDone(step.status));
91
+
92
+ if (startIndex >= 0) {
93
+ for (const step of steps.slice(startIndex)) {
94
+ if (isStepDone(step.status)) continue;
95
+ if (typeof options.handlers[step.stepName] !== "function") {
96
+ throw new Error(`Нет обработчика шага: ${step.stepName}`);
97
+ }
98
+ }
99
+ // Упавший запуск открываем заново: шаги можно перезапускать, attempt не сбрасывается.
100
+ // Паузу снимаем тем же переходом paused → running (36.7).
101
+ const current = requireRun(runId);
102
+ if (current.status === "failed" || current.status === "paused") reopenRun(runId);
103
+ }
104
+
105
+ return { steps, startIndex };
106
+ }
107
+
108
+ /**
109
+ * Возобновляет линейную цепочку шагов синхронно.
110
+ *
111
+ * Все проверки (наличие обработчиков) выполняются до первого побочного эффекта.
112
+ */
113
+ export function resumeRunSync(runId: string, options: ResumeOptions): ResumeResult {
114
+ const { steps, startIndex } = prepareResume(runId, options);
115
+ if (startIndex === -1) {
116
+ return finalize(runId, null, null, [], steps.map((step) => step.stepName), []);
117
+ }
118
+
119
+ const resumedFrom = steps[startIndex].stepName;
120
+ const executed: string[] = [];
121
+ const skipped: string[] = steps
122
+ .slice(0, startIndex)
123
+ .filter((step) => isStepDone(step.status))
124
+ .map((step) => step.stepName);
125
+ const injected: string[] = [];
126
+ let resumedFromAttempt: number | null = null;
127
+
128
+ for (let index = startIndex; index < steps.length; index += 1) {
129
+ const step = steps[index];
130
+ if (isStepDone(step.status)) {
131
+ skipped.push(step.stepName);
132
+ continue;
133
+ }
134
+
135
+ executed.push(step.stepName);
136
+ const context = pendingInjectionsForStep(runId, step.stepName);
137
+ try {
138
+ const execution = runStepStatefully(runId, step.stepName, () =>
139
+ options.handlers[step.stepName](step, { injections: context }),
140
+ );
141
+ if (resumedFromAttempt === null) resumedFromAttempt = execution.attempt;
142
+ if (context.length > 0) {
143
+ consumeInjections(
144
+ context.map((injection) => injection.id),
145
+ step.stepName,
146
+ execution.attempt,
147
+ );
148
+ injected.push(...context.map((injection) => injection.id));
149
+ }
150
+ } catch {
151
+ if (options.stopOnError === false) continue;
152
+ return finalize(runId, resumedFrom, resumedFromAttempt, executed, skipped, injected);
153
+ }
154
+ }
155
+
156
+ return finalize(runId, resumedFrom, resumedFromAttempt, executed, skipped, injected);
157
+ }
158
+
159
+ /** Асинхронный вариант `resumeRunSync` для шагов с I/O. */
160
+ export async function resumeRun(
161
+ runId: string,
162
+ options: ResumeOptions,
163
+ ): Promise<ResumeResult> {
164
+ const { steps, startIndex } = prepareResume(runId, options);
165
+ if (startIndex === -1) {
166
+ return finalize(runId, null, null, [], steps.map((step) => step.stepName), []);
167
+ }
168
+
169
+ const resumedFrom = steps[startIndex].stepName;
170
+ const executed: string[] = [];
171
+ const skipped: string[] = steps
172
+ .slice(0, startIndex)
173
+ .filter((step) => isStepDone(step.status))
174
+ .map((step) => step.stepName);
175
+ const injected: string[] = [];
176
+ let resumedFromAttempt: number | null = null;
177
+
178
+ for (let index = startIndex; index < steps.length; index += 1) {
179
+ const step = steps[index];
180
+ if (isStepDone(step.status)) {
181
+ skipped.push(step.stepName);
182
+ continue;
183
+ }
184
+
185
+ executed.push(step.stepName);
186
+ const context = pendingInjectionsForStep(runId, step.stepName);
187
+ try {
188
+ const execution = await runStepStatefullyAsync(runId, step.stepName, () =>
189
+ options.handlers[step.stepName](step, { injections: context }),
190
+ );
191
+ if (resumedFromAttempt === null) resumedFromAttempt = execution.attempt;
192
+ if (context.length > 0) {
193
+ consumeInjections(
194
+ context.map((injection) => injection.id),
195
+ step.stepName,
196
+ execution.attempt,
197
+ );
198
+ injected.push(...context.map((injection) => injection.id));
199
+ }
200
+ } catch {
201
+ if (options.stopOnError === false) continue;
202
+ return finalize(runId, resumedFrom, resumedFromAttempt, executed, skipped, injected);
203
+ }
204
+ }
205
+
206
+ return finalize(runId, resumedFrom, resumedFromAttempt, executed, skipped, injected);
207
+ }
208
+
209
+ /** Закрывает прогон по фактическому состоянию шагов и собирает результат. */
210
+ function finalize(
211
+ runId: string,
212
+ resumedFrom: string | null,
213
+ resumedFromAttempt: number | null,
214
+ executed: string[],
215
+ skipped: string[],
216
+ injected: string[],
217
+ ): ResumeResult {
218
+ // Вставки, адресованные уже завершённым шагам, не должны висеть в истории.
219
+ consumeOrphanInjections(runId);
220
+
221
+ let steps = listRunSteps(runId);
222
+ const failed = steps.find((step) => step.status === "failed") ?? null;
223
+ const unfinished = steps.some(
224
+ (step) => step.status === "pending" || step.status === "running",
225
+ );
226
+ let run = requireRun(runId);
227
+
228
+ if (!failed && !unfinished) {
229
+ if (run.status === "pending") {
230
+ startRun(runId);
231
+ run = requireRun(runId);
232
+ }
233
+ // Пауза после последнего шага: продолжать нечего, запуск успешен.
234
+ if (run.status === "running" || run.status === "paused") {
235
+ finishRun(runId, "passed");
236
+ run = requireRun(runId);
237
+ }
238
+ } else if (failed && run.status === "running") {
239
+ finishRun(runId, "failed", {
240
+ error: failed.error ?? `Шаг ${failed.stepName} завершился ошибкой`,
241
+ });
242
+ run = requireRun(runId);
243
+ }
244
+
245
+ steps = listRunSteps(runId);
246
+ return {
247
+ run,
248
+ resumedFrom,
249
+ resumedFromAttempt,
250
+ executed,
251
+ skipped,
252
+ injected,
253
+ failedStep: failed?.stepName ?? null,
254
+ error: failed?.error ?? null,
255
+ };
256
+ }