opencode-windows-scheduler 0.0.0-stage → 1.1.0

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 (183) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/CROSS_PLATFORM.md +113 -0
  3. package/LICENSE +21 -0
  4. package/README.md +173 -2
  5. package/README.ru.md +131 -0
  6. package/ROADMAP-STRATEGY.md +217 -0
  7. package/ROADMAP.md +90 -0
  8. package/dist/core/analytics.d.ts +119 -0
  9. package/dist/core/analytics.d.ts.map +1 -0
  10. package/dist/core/analytics.js +265 -0
  11. package/dist/core/cron-to-schtasks.d.ts +20 -0
  12. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  13. package/dist/core/cron-to-schtasks.js +233 -0
  14. package/dist/core/dry-run.d.ts +44 -0
  15. package/dist/core/dry-run.d.ts.map +1 -0
  16. package/dist/core/dry-run.js +252 -0
  17. package/dist/core/file-watcher.d.ts +31 -0
  18. package/dist/core/file-watcher.d.ts.map +1 -0
  19. package/dist/core/file-watcher.js +128 -0
  20. package/dist/core/lock.d.ts +43 -0
  21. package/dist/core/lock.d.ts.map +1 -0
  22. package/dist/core/lock.js +118 -0
  23. package/dist/core/matrix.d.ts +167 -0
  24. package/dist/core/matrix.d.ts.map +1 -0
  25. package/dist/core/matrix.js +687 -0
  26. package/dist/core/ps-wrapper.d.ts +60 -0
  27. package/dist/core/ps-wrapper.d.ts.map +1 -0
  28. package/dist/core/ps-wrapper.js +538 -0
  29. package/dist/core/record-history.d.ts +14 -0
  30. package/dist/core/record-history.d.ts.map +1 -0
  31. package/dist/core/record-history.js +360 -0
  32. package/dist/core/retention.d.ts +29 -0
  33. package/dist/core/retention.d.ts.map +1 -0
  34. package/dist/core/retention.js +98 -0
  35. package/dist/core/scheduler/index.d.ts +20 -0
  36. package/dist/core/scheduler/index.d.ts.map +1 -0
  37. package/dist/core/scheduler/index.js +32 -0
  38. package/dist/core/scheduler/linux.d.ts +32 -0
  39. package/dist/core/scheduler/linux.d.ts.map +1 -0
  40. package/dist/core/scheduler/linux.js +115 -0
  41. package/dist/core/scheduler/logs.d.ts +11 -0
  42. package/dist/core/scheduler/logs.d.ts.map +1 -0
  43. package/dist/core/scheduler/logs.js +34 -0
  44. package/dist/core/scheduler/mac.d.ts +39 -0
  45. package/dist/core/scheduler/mac.d.ts.map +1 -0
  46. package/dist/core/scheduler/mac.js +175 -0
  47. package/dist/core/scheduler/posix.d.ts +40 -0
  48. package/dist/core/scheduler/posix.d.ts.map +1 -0
  49. package/dist/core/scheduler/posix.js +86 -0
  50. package/dist/core/scheduler/registry.d.ts +36 -0
  51. package/dist/core/scheduler/registry.d.ts.map +1 -0
  52. package/dist/core/scheduler/registry.js +56 -0
  53. package/dist/core/scheduler/types.d.ts +63 -0
  54. package/dist/core/scheduler/types.d.ts.map +1 -0
  55. package/dist/core/scheduler/types.js +1 -0
  56. package/dist/core/scheduler/windows.d.ts +47 -0
  57. package/dist/core/scheduler/windows.d.ts.map +1 -0
  58. package/dist/core/scheduler/windows.js +375 -0
  59. package/dist/core/wrappers/bash.d.ts +58 -0
  60. package/dist/core/wrappers/bash.d.ts.map +1 -0
  61. package/dist/core/wrappers/bash.js +223 -0
  62. package/dist/db/history-repo.d.ts +102 -0
  63. package/dist/db/history-repo.d.ts.map +1 -0
  64. package/dist/db/history-repo.js +215 -0
  65. package/dist/db/index.d.ts +47 -0
  66. package/dist/db/index.d.ts.map +1 -0
  67. package/dist/db/index.js +120 -0
  68. package/dist/db/metrics-repo.d.ts +43 -0
  69. package/dist/db/metrics-repo.d.ts.map +1 -0
  70. package/dist/db/metrics-repo.js +95 -0
  71. package/dist/db/migrate.d.ts +24 -0
  72. package/dist/db/migrate.d.ts.map +1 -0
  73. package/dist/db/migrate.js +237 -0
  74. package/dist/db/recovery.d.ts +11 -0
  75. package/dist/db/recovery.d.ts.map +1 -0
  76. package/dist/db/recovery.js +38 -0
  77. package/dist/db/schema.d.ts +24 -0
  78. package/dist/db/schema.d.ts.map +1 -0
  79. package/dist/db/schema.js +97 -0
  80. package/dist/db/settings-repo.d.ts +8 -0
  81. package/dist/db/settings-repo.d.ts.map +1 -0
  82. package/dist/db/settings-repo.js +27 -0
  83. package/dist/db/tasks-repo.d.ts +26 -0
  84. package/dist/db/tasks-repo.d.ts.map +1 -0
  85. package/dist/db/tasks-repo.js +120 -0
  86. package/dist/db/templates-repo.d.ts +17 -0
  87. package/dist/db/templates-repo.d.ts.map +1 -0
  88. package/dist/db/templates-repo.js +57 -0
  89. package/dist/history.d.ts +53 -0
  90. package/dist/history.d.ts.map +1 -0
  91. package/dist/history.js +57 -0
  92. package/dist/index.d.ts +156 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +2159 -0
  95. package/dist/notifications.d.ts +45 -0
  96. package/dist/notifications.d.ts.map +1 -0
  97. package/dist/notifications.js +135 -0
  98. package/dist/rpc.d.ts +2186 -0
  99. package/dist/rpc.d.ts.map +1 -0
  100. package/dist/rpc.js +924 -0
  101. package/dist/schtasks.d.ts +32 -0
  102. package/dist/schtasks.d.ts.map +1 -0
  103. package/dist/schtasks.js +45 -0
  104. package/dist/server.d.ts +106 -0
  105. package/dist/server.d.ts.map +1 -0
  106. package/dist/server.js +1668 -0
  107. package/dist/settings.d.ts +66 -0
  108. package/dist/settings.d.ts.map +1 -0
  109. package/dist/settings.js +137 -0
  110. package/dist/shared/jobs-view.d.ts +21 -0
  111. package/dist/shared/jobs-view.d.ts.map +1 -0
  112. package/dist/shared/jobs-view.js +28 -0
  113. package/dist/skill.d.ts +15 -0
  114. package/dist/skill.d.ts.map +1 -0
  115. package/dist/skill.js +93 -0
  116. package/dist/task-transfer.d.ts +176 -0
  117. package/dist/task-transfer.d.ts.map +1 -0
  118. package/dist/task-transfer.js +442 -0
  119. package/dist/templates.d.ts +57 -0
  120. package/dist/templates.d.ts.map +1 -0
  121. package/dist/templates.js +16 -0
  122. package/dist/types.d.ts +78 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/dist/types.js +88 -0
  125. package/dist/version.d.ts +8 -0
  126. package/dist/version.d.ts.map +1 -0
  127. package/dist/version.js +27 -0
  128. package/dist/workspaces.d.ts +55 -0
  129. package/dist/workspaces.d.ts.map +1 -0
  130. package/dist/workspaces.js +183 -0
  131. package/docs/ARCHITECTURE.md +314 -0
  132. package/docs/FEATURES.md +300 -0
  133. package/docs/MIGRATION.md +266 -0
  134. package/docs/dashboard.png +0 -0
  135. package/gui-experimental.cjs +2 -0
  136. package/index.js +1 -0
  137. package/package.json +94 -4
  138. package/scripts/demo-dashboard.mjs +199 -0
  139. package/skills/scheduled-job-best-practices/SKILL.md +155 -0
  140. package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
  141. package/src/core/analytics.ts +378 -0
  142. package/src/core/cron-to-schtasks.ts +269 -0
  143. package/src/core/dry-run.ts +315 -0
  144. package/src/core/file-watcher.ts +171 -0
  145. package/src/core/lock.ts +134 -0
  146. package/src/core/matrix.ts +907 -0
  147. package/src/core/ps-wrapper.ts +572 -0
  148. package/src/core/record-history.ts +493 -0
  149. package/src/core/retention.ts +141 -0
  150. package/src/core/scheduler/index.ts +44 -0
  151. package/src/core/scheduler/linux.ts +125 -0
  152. package/src/core/scheduler/logs.ts +37 -0
  153. package/src/core/scheduler/mac.ts +222 -0
  154. package/src/core/scheduler/posix.ts +111 -0
  155. package/src/core/scheduler/registry.ts +93 -0
  156. package/src/core/scheduler/types.ts +67 -0
  157. package/src/core/scheduler/windows.ts +469 -0
  158. package/src/core/wrappers/bash.ts +282 -0
  159. package/src/db/history-repo.ts +396 -0
  160. package/src/db/index.ts +166 -0
  161. package/src/db/metrics-repo.ts +158 -0
  162. package/src/db/migrate.ts +322 -0
  163. package/src/db/recovery.ts +46 -0
  164. package/src/db/schema.ts +109 -0
  165. package/src/db/settings-repo.ts +31 -0
  166. package/src/db/tasks-repo.ts +162 -0
  167. package/src/db/templates-repo.ts +77 -0
  168. package/src/gui.tsx +2868 -0
  169. package/src/history.ts +107 -0
  170. package/src/index.ts +2768 -0
  171. package/src/notifications.ts +174 -0
  172. package/src/rpc.ts +999 -0
  173. package/src/schtasks.ts +75 -0
  174. package/src/server.ts +1879 -0
  175. package/src/settings.ts +228 -0
  176. package/src/shared/jobs-view.ts +38 -0
  177. package/src/skill.ts +113 -0
  178. package/src/task-transfer.ts +648 -0
  179. package/src/templates.ts +67 -0
  180. package/src/tui.tsx +46 -0
  181. package/src/types.ts +145 -0
  182. package/src/version.ts +27 -0
  183. package/src/workspaces.ts +236 -0
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Dry-Run (Спринт 14): симуляция конвейера задачи без реального запуска.
3
+ *
4
+ * Строит топологический порядок зависимостей, показывает фактические команды,
5
+ * cwd, роли (ограничения инструментов) и оценки по последним запускам.
6
+ * Никогда не исполняет команды — только анализ определений.
7
+ */
8
+ import fs from "node:fs";
9
+ import { loadTaskDefinitions } from "../task-transfer.js";
10
+ import { getHistory } from "../db/history-repo.js";
11
+ import { getWorkspace } from "../workspaces.js";
12
+ import { expandMatrixTask } from "./matrix.js";
13
+ import type { TaskDefinition } from "../task-transfer.js";
14
+
15
+ export interface DryRunRoleScoped {
16
+ allowed?: string[];
17
+ denied?: string[];
18
+ }
19
+
20
+ export interface DryRunTaskItem {
21
+ name: string;
22
+ order: number;
23
+ trigger: "manual" | "cron" | "dag";
24
+ cwd: string;
25
+ command: string;
26
+ workspace?: { name: string; path: string };
27
+ preFlight?: string | null;
28
+ postFlight?: string | null;
29
+ qualityGate?: string | null;
30
+ roleScoped?: DryRunRoleScoped | null;
31
+ estimatedDurationSec?: number | null;
32
+ estimatedCostUsd?: number | null;
33
+ estimatedTokens?: number | null;
34
+ /** Для клона матрицы — имя родителя-шаблона (Спринт 15). */
35
+ matrixParent?: string;
36
+ }
37
+
38
+ export interface DryRunTotals {
39
+ estimatedDurationSec?: number | null;
40
+ estimatedCostUsd?: number | null;
41
+ estimatedTokens?: number | null;
42
+ }
43
+
44
+ export interface DryRunReport {
45
+ success: boolean;
46
+ taskName: string;
47
+ tasks: DryRunTaskItem[];
48
+ totals: DryRunTotals;
49
+ warnings: string[];
50
+ }
51
+
52
+ /** Сколько последних успешных/любых запусков усредняем для оценки. */
53
+ const ESTIMATE_SAMPLE = 10;
54
+
55
+ /** Средняя цена за 1K токенов (должна совпадать с dashboards/server.ts). */
56
+ export const ESTIMATED_COST_PER_1K_TOKENS_USD = 0.003;
57
+
58
+ /** Опасные паттерны, о которых обязательно предупреждаем. */
59
+ const DANGEROUS_PATTERNS: Array<{ test: RegExp; message: string }> = [
60
+ { test: /rm\s+-rf\s+\/(?:\s|$)/, message: "возможна рекурсивная очистка корня файловой системы (`rm -rf /`)" },
61
+ { test: /git\s+push\s+.*--force(?:\s|$)/, message: "принудительный push в git (`git push --force`)" },
62
+ ];
63
+
64
+ /**
65
+ * Симулирует конвейер задачи: сама задача + все зависимости (dependsOn)
66
+ * в топологическом порядке. Возвращает отчёт без реального запуска.
67
+ */
68
+ export async function simulatePipeline(taskName: string): Promise<DryRunReport> {
69
+ const warnings: string[] = [];
70
+
71
+ const allDefs = await loadTaskDefinitions();
72
+ const rootLower = taskName.trim().toLowerCase();
73
+ const root = allDefs.find((d) => d.name.toLowerCase() === rootLower);
74
+ if (!root) {
75
+ throw new Error(`Задача "${taskName}" не найдена.`);
76
+ }
77
+
78
+ // Собираем подграф зависимостей рекурсивно, обнаруживая циклы.
79
+ const byLower = new Map<string, TaskDefinition>(allDefs.map((d) => [d.name.toLowerCase(), d]));
80
+ const visited = new Map<string, TaskDefinition>(); // lower -> def
81
+ const visiting = new Set<string>();
82
+ const warningsPerTask = new Map<string, string[]>();
83
+
84
+ const collect = (lowerName: string): TaskDefinition | undefined => {
85
+ if (visiting.has(lowerName)) {
86
+ const list = warningsPerTask.get(lowerName) ?? [];
87
+ list.push(`Обнаружена циклическая зависимость вокруг задачи "${lowerName}" — конвейер разорван на этом узле.`);
88
+ warningsPerTask.set(lowerName, list);
89
+ return undefined;
90
+ }
91
+ const cached = visited.get(lowerName);
92
+ if (cached) return cached;
93
+ const def = byLower.get(lowerName);
94
+ if (!def) {
95
+ const list = warningsPerTask.get(lowerName) ?? [];
96
+ list.push(`Зависимость "${lowerName}" не найдена среди задач — узел пропущен.`);
97
+ warningsPerTask.set(lowerName, list);
98
+ return undefined;
99
+ }
100
+ visiting.add(lowerName);
101
+ for (const dep of def.dependsOn ?? []) {
102
+ const depLower = (dep ?? "").trim().toLowerCase();
103
+ if (depLower) collect(depLower);
104
+ }
105
+ visiting.delete(lowerName);
106
+ visited.set(lowerName, def);
107
+ return def;
108
+ };
109
+
110
+ collect(root.name.toLowerCase());
111
+
112
+ // Топологический порядок: сначала зависимости (Kahn поверх собранного подграфа).
113
+ const ordered: TaskDefinition[] = [];
114
+ {
115
+ const pending = [...visited.values()];
116
+ const emitted = new Set<string>();
117
+ let progress = true;
118
+ while (pending.length > 0 && progress) {
119
+ progress = false;
120
+ for (let i = 0; i < pending.length; i++) {
121
+ const def = pending[i];
122
+ const deps = (def.dependsOn ?? []).map((d) => (d ?? "").trim().toLowerCase()).filter(Boolean);
123
+ const unmet = deps.filter((d) => visited.has(d) && !emitted.has(d));
124
+ if (unmet.length === 0) {
125
+ ordered.push(def);
126
+ emitted.add(def.name.toLowerCase());
127
+ pending.splice(i, 1);
128
+ i--;
129
+ progress = true;
130
+ }
131
+ }
132
+ }
133
+ // Если остались (цикл), добавляем как есть — предупреждение уже записано.
134
+ for (const leftover of pending) ordered.push(leftover);
135
+ }
136
+
137
+ const history = getHistory(null, 1000);
138
+ const historyByTask = new Map<string, typeof history>();
139
+ for (const record of history) {
140
+ const list = historyByTask.get(record.taskName.toLowerCase()) ?? [];
141
+ list.push(record);
142
+ historyByTask.set(record.taskName.toLowerCase(), list);
143
+ }
144
+
145
+ const tasks: DryRunTaskItem[] = [];
146
+ let totalDuration: number | null = 0;
147
+ let totalCost: number | null = 0;
148
+ let totalTokens: number | null = 0;
149
+
150
+ // Matrix (Спринт 15): родитель сам не выполняется — вместо него в отчёте
151
+ // показываем клоны, по одному на workspace, с их cwd и оценками.
152
+ const units: Array<{ def: TaskDefinition; matrixParent?: string }> = [];
153
+ for (const def of ordered) {
154
+ if (def.matrix) {
155
+ try {
156
+ const clones = expandMatrixTask(def);
157
+ warnings.push(
158
+ `[${def.name}] Родитель матрицы не выполняется сам — показаны ${clones.length} клон(а/ов) по workspace.`
159
+ );
160
+ for (const clone of clones) units.push({ def: clone, matrixParent: def.name });
161
+ } catch (err: any) {
162
+ const list = warningsPerTask.get(def.name.toLowerCase()) ?? [];
163
+ list.push(
164
+ `Матрица не может быть развёрнута: ${
165
+ err instanceof Error ? err.message : String(err)
166
+ }`
167
+ );
168
+ warningsPerTask.set(def.name.toLowerCase(), list);
169
+ warnings.push(`[${def.name}] ${list[list.length - 1]}`);
170
+ }
171
+ continue;
172
+ }
173
+ units.push({ def });
174
+ }
175
+
176
+ // Родители матриц с параллельной стратегией: их клоны считаются max, не sum.
177
+ const parallelMatrixParents = new Set(
178
+ allDefs
179
+ .filter((d) => d.matrix && (d.matrix.strategy ?? "parallel") !== "sequential")
180
+ .map((d) => d.name.toLowerCase())
181
+ );
182
+ const parallelGroups = new Map<string, { maxDuration: number }>();
183
+
184
+ for (let index = 0; index < units.length; index++) {
185
+ const { def, matrixParent } = units[index];
186
+ const lower = def.name.toLowerCase();
187
+ const taskWarnings = warningsPerTask.get(lower) ?? [];
188
+
189
+ // cwd: workspace имеет приоритет над workingDirectory (как в schedulerCreateTask).
190
+ const workspace = def.workspaceId ? getWorkspace(def.workspaceId) : undefined;
191
+ const cwd = workspace?.path || def.workingDirectory || def.workdir || "";
192
+ if (!cwd) {
193
+ taskWarnings.push("Рабочая директория не задана явно — будет использована папка текущего проекта.");
194
+ } else {
195
+ try {
196
+ const stat = fs.statSync(cwd);
197
+ if (!stat.isDirectory()) {
198
+ taskWarnings.push(`Путь "${cwd}" существует, но не является директорией.`);
199
+ }
200
+ } catch {
201
+ taskWarnings.push(`Рабочая директория "${cwd}" не существует на диске.`);
202
+ }
203
+ }
204
+
205
+ // Триггер: корневая задача (или клон корневой матрицы) — manual,
206
+ // остальные попали в конвейер через dependsOn — dag.
207
+ const trigger: DryRunTaskItem["trigger"] =
208
+ lower === rootLower || (matrixParent && matrixParent.toLowerCase() === rootLower)
209
+ ? "manual"
210
+ : "dag";
211
+
212
+ // Команда, которую выполнит обёртка.
213
+ const modelArg = def.model ? ` --model ${def.model}` : "";
214
+ const promptPreview = (def.prompt ?? "").replace(/\s+/g, " ").trim();
215
+ const command = `opencode run${modelArg} "${promptPreview}"`;
216
+
217
+ // Оценки: среднее по последним ESTIMATE_SAMPLE записям истории.
218
+ const records = (historyByTask.get(lower) ?? []).filter((r) => r.status === "success");
219
+ let estimatedDurationSec: number | null = null;
220
+ let estimatedCostUsd: number | null = null;
221
+ let estimatedTokens: number | null = null;
222
+ if (records.length === 0) {
223
+ taskWarnings.push("Нет успешных запусков в истории — оценка длительности/токенов/стоимости недоступна.");
224
+ } else {
225
+ const sample = records.slice(0, ESTIMATE_SAMPLE);
226
+ const avg = (pick: (r: (typeof sample)[number]) => number | null | undefined) => {
227
+ const values = sample.map(pick).filter((v): v is number => typeof v === "number" && Number.isFinite(v));
228
+ return values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null;
229
+ };
230
+ const avgMs = avg((r) => r.durationMs);
231
+ if (avgMs != null) estimatedDurationSec = Math.round(avgMs / 100) / 10;
232
+ estimatedTokens = avg((r) => r.tokens) ?? null;
233
+ if (estimatedTokens != null) {
234
+ estimatedCostUsd = (estimatedTokens / 1000) * ESTIMATED_COST_PER_1K_TOKENS_USD;
235
+ }
236
+ }
237
+
238
+ // Проверяем опасные паттерны в промпте и хуках.
239
+ const scanned = [def.prompt, def.beforeScript, def.afterScript, def.qualityGate]
240
+ .filter((s): s is string => typeof s === "string")
241
+ .join("\n")
242
+ .toLowerCase();
243
+ for (const { test, message } of DANGEROUS_PATTERNS) {
244
+ if (test.test(scanned)) {
245
+ taskWarnings.push(`Опасный паттерн: ${message}.`);
246
+ }
247
+ }
248
+
249
+ const roleScoped: DryRunRoleScoped | null =
250
+ Array.isArray(def.allowedTools) && def.allowedTools.length > 0
251
+ ? { allowed: def.allowedTools, denied: def.deniedTools }
252
+ : Array.isArray(def.deniedTools) && def.deniedTools.length > 0
253
+ ? { allowed: undefined, denied: def.deniedTools }
254
+ : null;
255
+
256
+ tasks.push({
257
+ name: def.name,
258
+ order: index,
259
+ trigger,
260
+ cwd,
261
+ command,
262
+ workspace: workspace ? { name: workspace.name, path: workspace.path } : undefined,
263
+ preFlight: def.beforeScript ?? null,
264
+ postFlight: def.afterScript ?? null,
265
+ qualityGate: def.qualityGate ?? null,
266
+ roleScoped,
267
+ estimatedDurationSec,
268
+ estimatedCostUsd: estimatedCostUsd != null ? Math.round(estimatedCostUsd * 10000) / 10000 : null,
269
+ estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
270
+ ...(matrixParent ? { matrixParent } : {}),
271
+ });
272
+
273
+ if (taskWarnings.length > 0) {
274
+ for (const warning of taskWarnings) {
275
+ warnings.push(`[${def.name}] ${warning}`);
276
+ }
277
+ }
278
+
279
+ // Суммируем оценки (null не ломает сумму). Для параллельных матриц
280
+ // длительность берём максимумом по группе, а не суммой клонов.
281
+ if (matrixParent && parallelMatrixParents.has(matrixParent.toLowerCase())) {
282
+ const key = matrixParent.toLowerCase();
283
+ const current = parallelGroups.get(key) ?? { maxDuration: 0 };
284
+ current.maxDuration = Math.max(current.maxDuration, estimatedDurationSec ?? 0);
285
+ parallelGroups.set(key, current);
286
+ } else if (totalDuration != null) {
287
+ totalDuration = totalDuration + (estimatedDurationSec ?? 0);
288
+ }
289
+ if (totalTokens != null) totalTokens = totalTokens + (estimatedTokens ?? 0);
290
+ if (totalCost != null) totalCost = totalCost + (estimatedCostUsd ?? 0);
291
+ }
292
+
293
+ for (const group of parallelGroups.values()) {
294
+ if (totalDuration != null) totalDuration = totalDuration + group.maxDuration;
295
+ }
296
+
297
+ const hasAnyEstimate = tasks.some(
298
+ (t) => t.estimatedDurationSec != null || t.estimatedCostUsd != null || t.estimatedTokens != null
299
+ );
300
+ const totals: DryRunTotals = hasAnyEstimate
301
+ ? {
302
+ estimatedDurationSec: totalDuration != null ? Math.round(totalDuration * 10) / 10 : null,
303
+ estimatedCostUsd: totalCost != null ? Math.round(totalCost * 10000) / 10000 : null,
304
+ estimatedTokens: totalTokens != null ? Math.round(totalTokens) : null,
305
+ }
306
+ : { estimatedDurationSec: null, estimatedCostUsd: null, estimatedTokens: null };
307
+
308
+ return {
309
+ success: true,
310
+ taskName: root.name,
311
+ tasks,
312
+ totals,
313
+ warnings,
314
+ };
315
+ }
@@ -0,0 +1,171 @@
1
+ import { watch, type FSWatcher } from "chokidar";
2
+ import { loadTaskDefinitions } from "../task-transfer.js";
3
+
4
+ /**
5
+ * Задержка между последним изменением файла и запуском задачи.
6
+ * Нужна потому, что редакторы часто пишут файл несколькими порциями
7
+ * (truncate + write + rename) — без дебаунса задача стартовала бы 3-5 раз.
8
+ */
9
+ export const FILE_TRIGGER_DEBOUNCE_MS = 2000;
10
+
11
+ export type FileTriggerHandler = (
12
+ taskName: string,
13
+ changedPath: string
14
+ ) => void | Promise<void>;
15
+
16
+ interface WatchedTask {
17
+ /** Имя задачи так, как оно записано в tasks.json. */
18
+ name: string;
19
+ /** Нормализованный путь, который отслеживаем. */
20
+ path: string;
21
+ watcher: FSWatcher;
22
+ /** Таймер дебаунса (одна задача = один отложенный запуск). */
23
+ timer: NodeJS.Timeout | null;
24
+ }
25
+
26
+ /**
27
+ * Менеджер файловых триггеров: держит по одному chokidar- watcher'у на задачу
28
+ * с triggerType === "file" и пересобирает их при изменении tasks.json.
29
+ */
30
+ export class FileWatchManager {
31
+ private entries = new Map<string, WatchedTask>();
32
+ private stopped = false;
33
+
34
+ constructor(
35
+ private readonly handler: FileTriggerHandler,
36
+ private readonly debounceMs: number = FILE_TRIGGER_DEBOUNCE_MS
37
+ ) {}
38
+
39
+ /** Сколько задач сейчас отслеживается. */
40
+ get size(): number {
41
+ return this.entries.size;
42
+ }
43
+
44
+ /**
45
+ * Перечитывает tasks.json и приводит набор watcher'ов в соответствие:
46
+ * новые задачи добавляются, удалённые/изменённые — закрываются.
47
+ * Возвращает количество активных файловых триггеров.
48
+ */
49
+ async refresh(): Promise<number> {
50
+ if (this.stopped) return 0;
51
+
52
+ const definitions = await loadTaskDefinitions();
53
+ const wanted = definitions
54
+ .filter(
55
+ (d) =>
56
+ d.triggerType === "file" &&
57
+ typeof d.watchPath === "string" &&
58
+ d.watchPath.trim().length > 0
59
+ )
60
+ .map((d) => ({ name: d.name.trim(), path: d.watchPath!.trim() }))
61
+ .filter((d) => d.name.length > 0);
62
+
63
+ const wantedKeys = new Set(wanted.map((d) => d.name.toLowerCase()));
64
+
65
+ // Убираем watcher'ы для задач, которых больше нет или у которых сменился путь.
66
+ for (const [key, entry] of Array.from(this.entries.entries())) {
67
+ const target = wanted.find((d) => d.name.toLowerCase() === key);
68
+ if (!target || target.path !== entry.path) {
69
+ await this.remove(key);
70
+ }
71
+ }
72
+
73
+ // Добавляем новые.
74
+ for (const item of wanted) {
75
+ const key = item.name.toLowerCase();
76
+ if (this.entries.has(key) || !wantedKeys.has(key)) continue;
77
+ this.add(item.name, item.path);
78
+ }
79
+
80
+ return this.entries.size;
81
+ }
82
+
83
+ /** Закрывает все watcher'ы (вызывается при выгрузке плагина). */
84
+ async stop(): Promise<void> {
85
+ this.stopped = true;
86
+ for (const key of Array.from(this.entries.keys())) {
87
+ await this.remove(key);
88
+ }
89
+ }
90
+
91
+ private add(name: string, watchPath: string): void {
92
+ let watcher: FSWatcher;
93
+ try {
94
+ watcher = watch(watchPath, {
95
+ // Не считаем уже существующий файл «изменением» при старте.
96
+ ignoreInitial: true,
97
+ // Следим за одним файлом/папкой, без рекурсии в глубину.
98
+ depth: 0,
99
+ // Файлы могут быть большими: дождёмся, пока запись успокоится.
100
+ awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 },
101
+ ignorePermissionErrors: true,
102
+ });
103
+ } catch (err: any) {
104
+ console.error(
105
+ `[windows-scheduler] Не удалось начать отслеживание "${watchPath}" для задачи "${name}": ${
106
+ err instanceof Error ? err.message : String(err)
107
+ }`
108
+ );
109
+ return;
110
+ }
111
+
112
+ const entry: WatchedTask = { name, path: watchPath, watcher, timer: null };
113
+
114
+ watcher.on("change", (changedPath: string) => {
115
+ if (this.stopped) return;
116
+ if (entry.timer) clearTimeout(entry.timer);
117
+ entry.timer = setTimeout(() => {
118
+ entry.timer = null;
119
+ if (this.stopped) return;
120
+ try {
121
+ const result = this.handler(name, changedPath);
122
+ if (result && typeof (result as Promise<void>).catch === "function") {
123
+ (result as Promise<void>).catch((err: any) => {
124
+ console.error(
125
+ `[windows-scheduler] Ошибка запуска задачи "${name}" по изменению файла: ${
126
+ err instanceof Error ? err.message : String(err)
127
+ }`
128
+ );
129
+ });
130
+ }
131
+ } catch (err: any) {
132
+ console.error(
133
+ `[windows-scheduler] Ошибка запуска задачи "${name}" по изменению файла: ${
134
+ err instanceof Error ? err.message : String(err)
135
+ }`
136
+ );
137
+ }
138
+ }, this.debounceMs);
139
+ // Таймер не должен удерживать процесс, если хост завершается.
140
+ if (typeof entry.timer.unref === "function") entry.timer.unref();
141
+ });
142
+
143
+ watcher.on("error", (err) => {
144
+ console.error(
145
+ `[windows-scheduler] Ошибка наблюдения за "${watchPath}" (задача "${name}"): ${
146
+ (err as any)?.message ?? String(err)
147
+ }`
148
+ );
149
+ });
150
+
151
+ this.entries.set(name.toLowerCase(), entry);
152
+ console.log(
153
+ `[windows-scheduler] Слежу за "${watchPath}" — задача "${name}" запускается при изменении файла.`
154
+ );
155
+ }
156
+
157
+ private async remove(key: string): Promise<void> {
158
+ const entry = this.entries.get(key);
159
+ if (!entry) return;
160
+ this.entries.delete(key);
161
+ if (entry.timer) {
162
+ clearTimeout(entry.timer);
163
+ entry.timer = null;
164
+ }
165
+ try {
166
+ await entry.watcher.close();
167
+ } catch {
168
+ // watcher уже мог быть закрыт — не критично.
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { LOCK_DIR, STALE_LOCK_MAX_AGE_MS } from "../types.js";
4
+
5
+ /**
6
+ * Менеджер файловых блокировок для предотвращения наложения запусков одной задачи.
7
+ *
8
+ * Блокировка реализуется через атомарное создание файла с флагом 'wx' (exclusive create).
9
+ * Если файл уже существует — блокировка удерживается другим запуском.
10
+ * После завершения задачи файл удаляется.
11
+ * Зависшие блокировки (старше STALE_LOCK_MAX_AGE_MS) удаляются при инициализации.
12
+ */
13
+ export class LockManager {
14
+ private readonly lockDir: string;
15
+
16
+ constructor(lockDir: string = LOCK_DIR) {
17
+ this.lockDir = lockDir;
18
+ }
19
+
20
+ /** Имя lock-файла для задачи. */
21
+ private lockFileName(taskName: string): string {
22
+ return `${taskName}.lock`;
23
+ }
24
+
25
+ /** Полный путь к lock-файлу задачи. */
26
+ private lockFilePath(taskName: string): string {
27
+ return path.join(this.lockDir, this.lockFileName(taskName));
28
+ }
29
+
30
+ /**
31
+ * Инициализация директории блокировок и очистка зависших (старых) файлов.
32
+ * Вызывается при старте плагина.
33
+ */
34
+ async initialize(): Promise<void> {
35
+ await fs.mkdir(this.lockDir, { recursive: true });
36
+
37
+ const files = await fs.readdir(this.lockDir).catch(() => []);
38
+ const now = Date.now();
39
+
40
+ for (const file of files) {
41
+ if (!file.endsWith(".lock")) continue;
42
+ const fullPath = path.join(this.lockDir, file);
43
+ try {
44
+ const stat = await fs.stat(fullPath);
45
+ const age = now - stat.mtimeMs;
46
+ if (age > STALE_LOCK_MAX_AGE_MS) {
47
+ await fs.unlink(fullPath).catch(() => {});
48
+ // eslint-disable-next-line no-console
49
+ console.log(
50
+ `[windows-scheduler] Удалён зависший lock-файл: ${file} (возраст ${Math.round(
51
+ age / 1000
52
+ )} с)`
53
+ );
54
+ }
55
+ } catch {
56
+ // Игнорируем ошибки чтения отдельных файлов при очистке.
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Пытается захватить блокировку для задачи.
63
+ * Возвращает true, если блокировка захвачена (файл создан).
64
+ * Возвращает false, если блокировка уже удерживается другим запуском.
65
+ */
66
+ async acquire(taskName: string): Promise<boolean> {
67
+ await fs.mkdir(this.lockDir, { recursive: true });
68
+ const lockPath = this.lockFilePath(taskName);
69
+
70
+ try {
71
+ // 'wx' — exclusive create: ошибка если файл уже существует.
72
+ await fs.writeFile(lockPath, String(Date.now()), { flag: "wx" });
73
+ return true;
74
+ } catch (err: any) {
75
+ if (err.code === "EEXIST") {
76
+ return false;
77
+ }
78
+ throw err;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Освобождает блокировку задачи (удаляет lock-файл).
84
+ * Не выбрасывает ошибку, если файл уже удалён.
85
+ */
86
+ async release(taskName: string): Promise<void> {
87
+ const lockPath = this.lockFilePath(taskName);
88
+ try {
89
+ await fs.unlink(lockPath);
90
+ } catch (err: any) {
91
+ if (err.code !== "ENOENT") throw err;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Проверяет, удерживается ли блокировка задачей в данный момент.
97
+ */
98
+ async isLocked(taskName: string): Promise<boolean> {
99
+ const lockPath = this.lockFilePath(taskName);
100
+ try {
101
+ await fs.stat(lockPath);
102
+ return true;
103
+ } catch (err: any) {
104
+ if (err.code === "ENOENT") return false;
105
+ throw err;
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Выполняет функцию с захватом файловых блокировок.
112
+ * Если блокировка уже удерживается — пропускает выполнение и возвращает null.
113
+ * Гарантирует освобождение блокировки в finally (включая при ошибках).
114
+ */
115
+ export async function withLock<T>(
116
+ lockManager: LockManager,
117
+ taskName: string,
118
+ fn: () => Promise<T>
119
+ ): Promise<T | null> {
120
+ const acquired = await lockManager.acquire(taskName);
121
+ if (!acquired) {
122
+ // eslint-disable-next-line no-console
123
+ console.log(
124
+ `[windows-scheduler] Запуск задачи "${taskName}" пропущен: удерживается активная блокировка.`
125
+ );
126
+ return null;
127
+ }
128
+
129
+ try {
130
+ return await fn();
131
+ } finally {
132
+ await lockManager.release(taskName);
133
+ }
134
+ }