opencode-windows-scheduler 1.4.0 → 1.5.1

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 (95) hide show
  1. package/CHANGELOG.md +61 -1
  2. package/LICENSE +21 -21
  3. package/README.md +26 -4
  4. package/ROADMAP-STRATEGY.md +43 -24
  5. package/ROADMAP.md +549 -31
  6. package/dist/core/dry-run.d.ts +41 -0
  7. package/dist/core/dry-run.d.ts.map +1 -1
  8. package/dist/core/dry-run.js +165 -16
  9. package/dist/core/file-watcher.d.ts.map +1 -1
  10. package/dist/core/file-watcher.js +53 -10
  11. package/dist/core/git-trigger.d.ts +80 -0
  12. package/dist/core/git-trigger.d.ts.map +1 -0
  13. package/dist/core/git-trigger.js +294 -0
  14. package/dist/core/glob.d.ts +38 -0
  15. package/dist/core/glob.d.ts.map +1 -0
  16. package/dist/core/glob.js +233 -0
  17. package/dist/core/matrix.d.ts.map +1 -1
  18. package/dist/core/matrix.js +48 -22
  19. package/dist/core/ps-wrapper.d.ts.map +1 -1
  20. package/dist/core/ps-wrapper.js +7 -0
  21. package/dist/core/schedule-gate.js +55 -30
  22. package/dist/core/schedule-v2.d.ts +29 -1
  23. package/dist/core/schedule-v2.d.ts.map +1 -1
  24. package/dist/core/schedule-v2.js +107 -17
  25. package/dist/core/scheduler/types.d.ts +7 -1
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/scheduler/windows.d.ts +6 -2
  28. package/dist/core/scheduler/windows.d.ts.map +1 -1
  29. package/dist/core/scheduler/windows.js +25 -10
  30. package/dist/core/telegram.d.ts.map +1 -1
  31. package/dist/core/telegram.js +13 -10
  32. package/dist/core/wrappers/bash.d.ts.map +1 -1
  33. package/dist/core/wrappers/bash.js +4 -0
  34. package/dist/db/git-state-repo.d.ts +16 -0
  35. package/dist/db/git-state-repo.d.ts.map +1 -0
  36. package/dist/db/git-state-repo.js +38 -0
  37. package/dist/db/schema.d.ts +1 -1
  38. package/dist/db/schema.d.ts.map +1 -1
  39. package/dist/db/schema.js +8 -0
  40. package/dist/i18n.d.ts +52 -0
  41. package/dist/i18n.d.ts.map +1 -0
  42. package/dist/i18n.js +292 -0
  43. package/dist/index.d.ts +50 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1020 -197
  46. package/dist/notifications.d.ts.map +1 -1
  47. package/dist/notifications.js +74 -40
  48. package/dist/rpc.d.ts +238 -2
  49. package/dist/rpc.d.ts.map +1 -1
  50. package/dist/rpc.js +79 -2
  51. package/dist/server.d.ts.map +1 -1
  52. package/dist/server.js +89 -48
  53. package/dist/settings.d.ts +3 -0
  54. package/dist/settings.d.ts.map +1 -1
  55. package/dist/settings.js +20 -8
  56. package/dist/task-transfer.d.ts +43 -3
  57. package/dist/task-transfer.d.ts.map +1 -1
  58. package/dist/task-transfer.js +94 -6
  59. package/dist/templates.d.ts +1 -1
  60. package/dist/templates.d.ts.map +1 -1
  61. package/dist/types.d.ts +11 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js +32 -0
  64. package/docs/ARCHITECTURE.md +37 -1
  65. package/docs/FEATURES.md +70 -0
  66. package/docs/README.ru.md +19 -3
  67. package/gui-experimental.cjs +9 -4
  68. package/locales/en.json +695 -0
  69. package/locales/ru.json +695 -0
  70. package/package.json +9 -3
  71. package/scripts/test-locale.mjs +44 -0
  72. package/src/core/dry-run.ts +244 -19
  73. package/src/core/file-watcher.ts +65 -10
  74. package/src/core/git-trigger.ts +373 -0
  75. package/src/core/glob.ts +226 -0
  76. package/src/core/matrix.ts +52 -26
  77. package/src/core/ps-wrapper.ts +7 -0
  78. package/src/core/schedule-gate.ts +67 -33
  79. package/src/core/schedule-v2.ts +152 -17
  80. package/src/core/scheduler/types.ts +7 -1
  81. package/src/core/scheduler/windows.ts +25 -10
  82. package/src/core/telegram.ts +16 -10
  83. package/src/core/wrappers/bash.ts +4 -0
  84. package/src/db/git-state-repo.ts +62 -0
  85. package/src/db/schema.ts +8 -0
  86. package/src/gui.tsx +772 -456
  87. package/src/i18n.ts +339 -0
  88. package/src/index.ts +1274 -212
  89. package/src/notifications.ts +83 -42
  90. package/src/rpc.ts +79 -2
  91. package/src/server.ts +89 -48
  92. package/src/settings.ts +38 -10
  93. package/src/task-transfer.ts +148 -5
  94. package/src/templates.ts +1 -1
  95. package/src/types.ts +37 -0
@@ -21,6 +21,7 @@ import { getHistory, recordRun } from "../db/history-repo.js";
21
21
  import { notifyMatrixCompletion } from "../notifications.js";
22
22
  import { getWorkspace } from "../workspaces.js";
23
23
  import { createSchedulerBackend } from "./scheduler/index.js";
24
+ import { t } from "../i18n.js";
24
25
 
25
26
  /** Суффикс агрегирующей задачи, запускаемой после всех клонов. */
26
27
  export const MATRIX_COMPLETE_SUFFIX = "-matrix-complete";
@@ -29,7 +30,11 @@ export const MATRIX_COMPLETE_SUFFIX = "-matrix-complete";
29
30
  export function matrixCloneName(parentName: string, workspaceName: string): string {
30
31
  const parent = parentName.trim();
31
32
  const ws = workspaceName.trim() || "workspace";
32
- const safeWs = ws.replace(/[\\/:*?"<>|]+/g, "-").replace(/\s+/g, "-");
33
+ const safeWs = ws
34
+ // Спринт 27.5: метасимволы оболочки и недопустимые для имени задачи
35
+ // символы заменяем на дефис, чтобы имя клона проходило validateTaskName.
36
+ .replace(/[\\/:*?"<>|&^%'`;()]+/g, "-")
37
+ .replace(/\s+/g, "-");
33
38
  return `${parent}-matrix-${safeWs}`;
34
39
  }
35
40
 
@@ -50,7 +55,9 @@ export function isMatrixCompleteName(name: string): boolean {
50
55
  export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
51
56
  const matrix = task.matrix;
52
57
  if (!matrix || !Array.isArray(matrix.workspaceIds) || matrix.workspaceIds.length === 0) {
53
- throw new Error(`Задача "${task.name}": matrix.workspaceIds не может быть пустым.`);
58
+ throw new Error(
59
+ t("matrix.error.workspaceIdsEmpty", { task: task.name })
60
+ );
54
61
  }
55
62
 
56
63
  const clones: TaskDefinition[] = [];
@@ -60,7 +67,10 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
60
67
  const workspace = getWorkspace(workspaceId);
61
68
  if (!workspace) {
62
69
  throw new Error(
63
- `Задача "${task.name}": workspace "${workspaceId}" не найден.`
70
+ t("matrix.error.workspaceMissing", {
71
+ task: task.name,
72
+ workspace: workspaceId,
73
+ })
64
74
  );
65
75
  }
66
76
  const name = matrixCloneName(task.name, workspace.name);
@@ -108,7 +118,9 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
108
118
  }
109
119
 
110
120
  if (clones.length === 0) {
111
- throw new Error(`Задача "${task.name}": не удалось создать ни одного клона матрицы.`);
121
+ throw new Error(
122
+ t("matrix.error.cloneCreation", { task: task.name })
123
+ );
112
124
  }
113
125
  return clones;
114
126
  }
@@ -181,22 +193,37 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
181
193
 
182
194
  if (totalCount === 0) {
183
195
  status = "empty";
184
- message = `У матрицы "${parentId}" нет клонов.`;
196
+ message = t("matrix.aggregate.empty", { parent: parentId });
185
197
  } else if (pendingCount > 0) {
186
198
  status = "running";
187
- message = `Выполняется: ${totalCount - pendingCount} из ${totalCount}.`;
199
+ message = t("matrix.aggregate.running", {
200
+ done: totalCount - pendingCount,
201
+ total: totalCount,
202
+ });
188
203
  } else if (errorCount === 0) {
189
204
  status = "success";
190
- message = `Все ${totalCount} клонов завершились успешно.`;
205
+ message = t("matrix.aggregate.success", { total: totalCount });
191
206
  } else if (failureMode === "stop") {
192
207
  const firstError = results.find((r) => r.status === "error");
193
208
  status = "error";
194
209
  message =
195
- `Остановлено после первой ошибки: ${errorCount} из ${totalCount} с ошибкой.` +
196
- (firstError?.error ? ` Первая ошибка (${firstError.name}): ${firstError.error}` : "");
210
+ t("matrix.aggregate.stopped", {
211
+ errors: errorCount,
212
+ total: totalCount,
213
+ }) +
214
+ (firstError?.error
215
+ ? t("matrix.aggregate.stoppedFirst", {
216
+ name: firstError.name,
217
+ error: firstError.error,
218
+ })
219
+ : "");
197
220
  } else {
198
221
  status = "partial";
199
- message = `Частичный успех: ${successCount} из ${totalCount} успешно, ${errorCount} с ошибкой.`;
222
+ message = t("matrix.aggregate.partial", {
223
+ success: successCount,
224
+ total: totalCount,
225
+ errors: errorCount,
226
+ });
200
227
  }
201
228
 
202
229
  return {
@@ -250,13 +277,11 @@ export function resolveMatrixConcurrency(
250
277
  export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult> {
251
278
  const matrix = task.matrix;
252
279
  if (!matrix) {
253
- throw new Error(`Задача "${task.name}" не является матрицей.`);
280
+ throw new Error(t("matrix.error.notMatrix", { task: task.name }));
254
281
  }
255
282
  const clones = listMatrixClones(task.name);
256
283
  if (clones.length === 0) {
257
- throw new Error(
258
- `У матрицы "${task.name}" нет клонов — пересоздайте задачу, чтобы развернуть её по workspace.`
259
- );
284
+ throw new Error(t("matrix.error.noClones", { task: task.name }));
260
285
  }
261
286
 
262
287
  const strategy = matrix.strategy === "sequential" ? "sequential" : "parallel";
@@ -467,8 +492,10 @@ export function ensureMatrixCompleteTask(parent: TaskDefinition): TaskDefinition
467
492
  schedule: parent.schedule,
468
493
  prompt:
469
494
  existing?.prompt ??
470
- `Все клоны матрицы "${parent.name}" завершились. Проверь результаты: ` +
471
- `${clones.map((c) => c.name).join(", ")}.`,
495
+ t("matrix.aggregator.prompt", {
496
+ parent: parent.name,
497
+ clones: clones.map((c) => c.name).join(", "),
498
+ }),
472
499
  triggerType: "file",
473
500
  watchPath: undefined,
474
501
  mcpEvent: undefined,
@@ -542,7 +569,7 @@ export interface MatrixSyncPlan {
542
569
  */
543
570
  export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
544
571
  if (!parent.matrix) {
545
- throw new Error(`Задача "${parent.name}" не является матрицей.`);
572
+ throw new Error(t("matrix.error.notMatrix", { task: parent.name }));
546
573
  }
547
574
  const desired = expandMatrixTask(parent);
548
575
  const existing = listMatrixClones(parent.name);
@@ -570,7 +597,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
570
597
  running.push(current.name);
571
598
  if (cloneSignature(current) !== cloneSignature(wanted)) {
572
599
  warnings.push(
573
- `Клон "${current.name}" выполняется — изменения применятся после завершения.`
600
+ t("matrix.clone.runningChanges", { name: current.name })
574
601
  );
575
602
  }
576
603
  continue;
@@ -586,7 +613,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
586
613
  if (latest.status === "running") {
587
614
  running.push(current.name);
588
615
  warnings.push(
589
- `Клон "${current.name}" выполняется — удаление отложено до завершения.`
616
+ t("matrix.clone.runningDeletion", { name: current.name })
590
617
  );
591
618
  continue;
592
619
  }
@@ -689,11 +716,10 @@ export function getMatrixDeletionGuard(
689
716
  const definition = getTask(taskName);
690
717
  const parentId = definition?.matrixParentId?.trim();
691
718
  if (!parentId) return undefined;
692
- return (
693
- `Задача "${definition?.name ?? taskName}" — клон матрицы "${parentId}". ` +
694
- `Удалите матрицу целиком (родитель + все клоны) или измените список ` +
695
- `workspace-ов родителя.`
696
- );
719
+ return t("matrix.deletionGuard", {
720
+ name: definition?.name ?? taskName,
721
+ parent: parentId,
722
+ });
697
723
  }
698
724
 
699
725
  /**
@@ -743,11 +769,11 @@ export interface MatrixCancelResult {
743
769
  */
744
770
  export async function cancelPendingMatrixClones(
745
771
  parentName: string,
746
- reason = "Отменено пользователем."
772
+ reason = t("matrix.cancel.defaultReason")
747
773
  ): Promise<MatrixCancelResult> {
748
774
  const parent = getTask(parentName);
749
775
  if (!parent?.matrix) {
750
- throw new Error(`Задача "${parentName}" не является матрицей.`);
776
+ throw new Error(t("matrix.error.notMatrix", { task: parentName }));
751
777
  }
752
778
 
753
779
  const clones = listMatrixClones(parent.name);
@@ -643,6 +643,13 @@ export async function writeWrapperCmd(
643
643
  if (scheduleGate.notAfter?.trim()) {
644
644
  gateArgs.push(`--not-after ${scheduleGate.notAfter.trim()}`);
645
645
  }
646
+ // Спринт 27: дни недели и политика окна.
647
+ if (Array.isArray(scheduleGate.days) && scheduleGate.days.length > 0) {
648
+ gateArgs.push(`--days ${scheduleGate.days.join(",")}`);
649
+ }
650
+ if (scheduleGate.windowPolicy) {
651
+ gateArgs.push(`--window-policy ${scheduleGate.windowPolicy}`);
652
+ }
646
653
  if (scheduleGate.deferFile?.trim()) {
647
654
  gateArgs.push(`--defer-file "${scheduleGate.deferFile.trim()}"`);
648
655
  }
@@ -29,12 +29,12 @@
29
29
  */
30
30
  import fs from "node:fs";
31
31
  import {
32
+ activeWindowState,
32
33
  cronMatches,
33
34
  isValidIanaTimeZone,
34
- isInWindow,
35
+ normalizeActiveDays,
35
36
  parseCron,
36
37
  validateLaunchWindow,
37
- windowDelayMs,
38
38
  } from "./schedule-v2.js";
39
39
 
40
40
  const STALE_DEFER_MS = 25 * 60 * 60 * 1000;
@@ -42,6 +42,9 @@ const STALE_DEFER_MS = 25 * 60 * 60 * 1000;
42
42
  /** Сколько живёт маркер ручного запуска. */
43
43
  const FORCE_TTL_MS = 2 * 60 * 1000;
44
44
 
45
+ /** Дольше 12 часов перенос не ждём — тик просто пропускается. */
46
+ const MAX_POSTPONE_MS = 12 * 60 * 60 * 1000;
47
+
45
48
  function argValue(args: string[], name: string): string | undefined {
46
49
  const idx = args.indexOf(name);
47
50
  if (idx === -1 || idx + 1 >= args.length) return undefined;
@@ -113,10 +116,23 @@ async function main(): Promise<number> {
113
116
  const tz = argValue(args, "--tz");
114
117
  const notBefore = argValue(args, "--not-before");
115
118
  const notAfter = argValue(args, "--not-after");
119
+ const daysArg = argValue(args, "--days");
120
+ const policyArg = argValue(args, "--window-policy");
116
121
  const deferFile = argValue(args, "--defer-file");
117
122
  const forceFile = argValue(args, "--force-file");
118
123
  const nowArg = argValue(args, "--now");
119
124
 
125
+ const days = daysArg
126
+ ? normalizeActiveDays(
127
+ daysArg
128
+ .split(",")
129
+ .map((value) => Number(value.trim()))
130
+ .filter((value) => Number.isFinite(value))
131
+ )
132
+ : undefined;
133
+ const policy: "skip" | "postpone" | "run" =
134
+ policyArg === "skip" || policyArg === "run" ? policyArg : "postpone";
135
+
120
136
  const now = nowArg ? new Date(nowArg) : new Date();
121
137
  if (Number.isNaN(now.getTime())) {
122
138
  console.error(`[schedule-gate] Некорректное значение --now: ${nowArg}`);
@@ -139,7 +155,6 @@ async function main(): Promise<number> {
139
155
  if (windowError) {
140
156
  console.error(`[schedule-gate] Окно запуска игнорируется: ${windowError}`);
141
157
  }
142
- const windowOk = !windowError && !!notBefore && !!notAfter;
143
158
 
144
159
  let spec = null;
145
160
  if (cronExpr) {
@@ -159,43 +174,62 @@ async function main(): Promise<number> {
159
174
  return 3;
160
175
  }
161
176
 
162
- if (windowOk && !isInWindow(now, notBefore, notAfter, zone)) {
163
- const wait = windowDelayMs(now, notBefore, notAfter, zone);
164
- if (wait <= 0) return 0;
165
-
166
- // ПЕРЕНОС: ждём открытия окна. Откладываем один запуск, остальные тики
167
- // отсекаются по defer-файлу.
168
- if (deferFile) {
169
- if (deferFileBusy(deferFile, now.getTime())) {
170
- console.error("[schedule-gate] Отложенный запуск уже ожидает открытия окна.");
177
+ // Дни недели и окно запуска (Спринт 27). Политика вне окна:
178
+ // postpone (по умолчанию) — ждём открытия окна;
179
+ // skip — тихо пропускаем тик;
180
+ // run — выполняем, несмотря на окно.
181
+ const windowOptions = { notBefore, notAfter, days, timeZone: zone };
182
+ if (policy !== "run") {
183
+ const state = activeWindowState(now, windowOptions);
184
+ if (!state.active) {
185
+ if (policy === "skip") {
186
+ console.error(`[schedule-gate] Пропуск: ${state.reason ?? "вне окна"}.`);
171
187
  return 3;
172
188
  }
173
- if (!acquireDefer(deferFile, now.getTime())) {
174
- console.error("[schedule-gate] Не удалось захватить defer-файл — пропускаем.");
189
+
190
+ const wait = state.nextOpenAt
191
+ ? Math.max(0, state.nextOpenAt.getTime() - now.getTime())
192
+ : 0;
193
+ if (wait <= 0) return 0;
194
+ if (wait > MAX_POSTPONE_MS) {
195
+ console.error(
196
+ `[schedule-gate] ${state.reason ?? "вне окна"} — до открытия больше 12 часов, тик пропущен.`
197
+ );
175
198
  return 3;
176
199
  }
177
- }
178
200
 
179
- console.error(
180
- `[schedule-gate] Вне окна ${notBefore}–${notAfter} — запуск перенесён на ~${Math.round(
181
- wait / 60000
182
- )} мин.`
183
- );
184
- let remaining = wait;
185
- let woke = now;
186
- while (remaining > 0) {
187
- const chunk = Math.min(remaining, 60_000);
188
- await sleepMs(chunk);
189
- remaining -= chunk;
190
- woke = new Date();
191
- if (isInWindow(woke, notBefore, notAfter, zone)) break;
192
- }
201
+ // ПЕРЕНОС: ждём открытия окна. Откладываем один запуск, остальные тики
202
+ // отсекаются по defer-файлу.
203
+ if (deferFile) {
204
+ if (deferFileBusy(deferFile, now.getTime())) {
205
+ console.error("[schedule-gate] Отложенный запуск уже ожидает открытия окна.");
206
+ return 3;
207
+ }
208
+ if (!acquireDefer(deferFile, now.getTime())) {
209
+ console.error("[schedule-gate] Не удалось захватить defer-файл — пропускаем.");
210
+ return 3;
211
+ }
212
+ }
193
213
 
194
- if (deferFile) releaseDefer(deferFile);
214
+ console.error(
215
+ `[schedule-gate] ${state.reason ?? "Вне окна"} — запуск перенесён на ~${Math.round(
216
+ wait / 60000
217
+ )} мин.`
218
+ );
219
+ let remaining = wait;
220
+ while (remaining > 0) {
221
+ const chunk = Math.min(remaining, 60_000);
222
+ await sleepMs(chunk);
223
+ remaining -= chunk;
224
+ }
195
225
 
196
- if (!isInWindow(woke, notBefore, notAfter, zone)) {
197
- console.error("[schedule-gate] Окно не открылось за отведённое время — не запускаем.");
198
- return 3;
226
+ const woke = new Date();
227
+ if (deferFile) releaseDefer(deferFile);
228
+
229
+ if (!activeWindowState(woke, windowOptions).active) {
230
+ console.error("[schedule-gate] Окно не открылось за отведённое время — не запускаем.");
231
+ return 3;
232
+ }
199
233
  }
200
234
  }
201
235
 
@@ -12,6 +12,7 @@
12
12
  * Никакого I/O и обращения к ОС.
13
13
  */
14
14
  import { convertCronToSchTasks } from "./cron-to-schtasks.js";
15
+ import { t } from "../i18n.js";
15
16
  import type { CronConversion } from "../types.js";
16
17
 
17
18
  /** Ограничение на поиск ближайшего запуска. */
@@ -139,7 +140,8 @@ function expandField(token: string, min: number, max: number, names?: Record<str
139
140
  const items = token.split(",");
140
141
  for (const raw of items) {
141
142
  let item = raw.trim().toUpperCase();
142
- if (!item) throw new Error(`Пустой элемент в списке «${token}».`);
143
+ if (!item)
144
+ throw new Error(t("schedule.error.cronEmptyItem", { token }));
143
145
  if (names && names[item] !== undefined) item = String(names[item]);
144
146
  // шаг: a-b/n или */n
145
147
  const stepMatch = item.match(/^(.*)\/([0-9]+)$/);
@@ -148,9 +150,15 @@ function expandField(token: string, min: number, max: number, names?: Record<str
148
150
  item = (stepMatch[1] ?? "").trim();
149
151
  step = Number(stepMatch[2]);
150
152
  if (!Number.isInteger(step) || step < 1) {
151
- throw new Error(`Недопустимый шаг «/${stepMatch[2]}» в «${raw}».`);
153
+ throw new Error(
154
+ t("schedule.error.cronStepInvalid", {
155
+ step: stepMatch[2],
156
+ raw,
157
+ })
158
+ );
152
159
  }
153
- if (item === "") throw new Error(`Некорректный шаг в «${raw}»: перед «/» ничего нет.`);
160
+ if (item === "")
161
+ throw new Error(t("schedule.error.cronStepMissing", { raw }));
154
162
  }
155
163
  if (item === "*" || item === "") {
156
164
  for (let v = min; v <= max; v += step) result.add(v);
@@ -165,17 +173,21 @@ function expandField(token: string, min: number, max: number, names?: Record<str
165
173
  const a = Number(aToken);
166
174
  const b = Number(bToken);
167
175
  if (!Number.isFinite(a) || !Number.isFinite(b)) {
168
- throw new Error(`Недопустимый диапазон «${item}».`);
176
+ throw new Error(t("schedule.error.cronRangeInvalid", { item }));
169
177
  }
170
178
  if (a < min || b > max || a > b) {
171
- throw new Error(`Диапазон «${item}» вне границ ${min}..${max}.`);
179
+ throw new Error(
180
+ t("schedule.error.cronRangeBounds", { item, min, max })
181
+ );
172
182
  }
173
183
  for (let v = a; v <= b; v += step) result.add(v);
174
184
  continue;
175
185
  }
176
186
  const num = Number(item);
177
187
  if (!Number.isInteger(num) || num < min || num > max) {
178
- throw new Error(`Значение «${raw}» вне границ ${min}..${max}.`);
188
+ throw new Error(
189
+ t("schedule.error.cronValueBounds", { raw, min, max })
190
+ );
179
191
  }
180
192
  result.add(num);
181
193
  }
@@ -208,7 +220,9 @@ export function normalizeCron(expr: string): string {
208
220
  if (unit === "m" && n >= 1 && n < 60) return `*/${n} * * * *`;
209
221
  if (unit === "h" && n >= 1 && n <= 23) return `0 */${n} * * *`;
210
222
  if (unit === "d" && n >= 1 && n <= 31) return `0 0 */${n} * *`;
211
- throw new Error(`Неподдерживаемый интервал «@every ${n}${unit}» (m: 1..59, h: 1..23, d: 1..31).`);
223
+ throw new Error(
224
+ t("schedule.error.everyInterval", { value: `${n}${unit}` })
225
+ );
212
226
  }
213
227
 
214
228
  /** Парсит cron-выражение; бросает Error с понятным сообщением. */
@@ -216,7 +230,9 @@ export function parseCron(expr: string): ParsedCron {
216
230
  const raw = normalizeCron(expr);
217
231
  const fields = raw.split(/\s+/);
218
232
  if (fields.length !== 5) {
219
- throw new Error(`Ожидается 5 полей cron, получено ${fields.length}: «${raw}».`);
233
+ throw new Error(
234
+ t("schedule.error.cronFields", { count: fields.length, raw })
235
+ );
220
236
  }
221
237
  const [minF, hourF, domF, monthF, dowF] = fields;
222
238
 
@@ -252,13 +268,18 @@ export function parseCron(expr: string): ParsedCron {
252
268
  if (DOW_NAMES[dToken] !== undefined) dToken = String(DOW_NAMES[dToken]);
253
269
  const weekday = Number(dToken);
254
270
  if (!Number.isInteger(weekday) || weekday < 0 || weekday > 7) {
255
- throw new Error(`День недели «${hash[1]}» вне границ 0..7 в «${dowF}».`);
271
+ throw new Error(
272
+ t("schedule.error.weekdayBounds", {
273
+ value: hash[1],
274
+ field: dowF,
275
+ })
276
+ );
256
277
  }
257
278
  nthWeekday.push({ weekday: weekday % 7, n: Number(hash[2]) });
258
279
  continue;
259
280
  }
260
281
  if (token === "L") {
261
- throw new Error("«L» поддерживается только в поле дня месяца.");
282
+ throw new Error(t("schedule.error.lastDomOnly"));
262
283
  }
263
284
  kept.push(token);
264
285
  }
@@ -431,10 +452,12 @@ export function validateLaunchWindow(notBefore?: string | null, notAfter?: strin
431
452
  const nb = notBefore?.trim() ?? "";
432
453
  const na = notAfter?.trim() ?? "";
433
454
  if (!nb && !na) return null;
434
- if (nb && !isValidDailyTime(nb)) return `notBefore должен быть в формате HH:MM, не "${nb}".`;
435
- if (na && !isValidDailyTime(na)) return `notAfter должен быть в формате HH:MM, не "${na}".`;
436
- if (!nb || !na) return "notBefore и notAfter задаются вместе.";
437
- if (nb === na) return "notBefore и notAfter не могут совпадать (пустое окно).";
455
+ if (nb && !isValidDailyTime(nb))
456
+ return t("schedule.error.notBeforeFormat", { value: nb });
457
+ if (na && !isValidDailyTime(na))
458
+ return t("schedule.error.notAfterFormat", { value: na });
459
+ if (!nb || !na) return t("schedule.error.windowTogether");
460
+ if (nb === na) return t("schedule.error.windowEmpty");
438
461
  return null;
439
462
  }
440
463
 
@@ -466,6 +489,103 @@ export function windowDelayMs(now: Date, notBefore?: string | null, notAfter?: s
466
489
  return Math.max(0, deltaSec * 1000 - ms);
467
490
  }
468
491
 
492
+ // ---------------------------------------------------------------------------
493
+ // Дни недели и политика вне окна (Спринт 27).
494
+
495
+ /** 0=Вс..6=Сб. Пустой/полный список трактуется как «все дни» (undefined). */
496
+ export function normalizeActiveDays(days?: number[] | null): number[] | undefined {
497
+ if (!Array.isArray(days)) return undefined;
498
+ const unique = [
499
+ ...new Set(
500
+ days
501
+ .map((value) => Math.floor(Number(value)))
502
+ .filter((value) => Number.isInteger(value) && value >= 0 && value <= 6)
503
+ ),
504
+ ].sort((a, b) => a - b);
505
+ if (unique.length === 0 || unique.length === 7) return undefined;
506
+ return unique;
507
+ }
508
+
509
+ /** Разрешён ли день недели (в поясе задачи). */
510
+ export function isActiveDay(now: Date, days?: number[] | null, timeZone?: string): boolean {
511
+ const normalized = normalizeActiveDays(days);
512
+ if (!normalized) return true;
513
+ return normalized.includes(zonedParts(now, timeZone).weekday);
514
+ }
515
+
516
+ export interface ActiveWindowOptions {
517
+ notBefore?: string | null;
518
+ notAfter?: string | null;
519
+ days?: number[] | null;
520
+ timeZone?: string;
521
+ }
522
+
523
+ export interface ActiveWindowState {
524
+ /** Можно запускать сейчас. */
525
+ active: boolean;
526
+ /** Почему нельзя (человекочитаемо, для dry-run и логов). */
527
+ reason?: string;
528
+ /** Ближайшее открытие окна; null — не требуется или не найдено. */
529
+ nextOpenAt: Date | null;
530
+ }
531
+
532
+ const WINDOW_SCAN_MINUTES = 8 * 24 * 60;
533
+
534
+ /** Ближайшая минута, когда и день, и окно разрешают запуск. */
535
+ export function nextWindowOpenAt(now: Date, options: ActiveWindowOptions): Date | null {
536
+ const { notBefore, notAfter, timeZone } = options;
537
+ const normalizedDays = normalizeActiveDays(options.days);
538
+ const hasWindow = Boolean((notBefore || "").trim() || (notAfter || "").trim());
539
+ if (!hasWindow && !normalizedDays) return null;
540
+ const invalidWindow = validateLaunchWindow(notBefore, notAfter) !== null;
541
+ for (let i = 1; i <= WINDOW_SCAN_MINUTES; i++) {
542
+ const candidate = new Date(now.getTime() + i * 60_000);
543
+ const dayOk =
544
+ !normalizedDays || normalizedDays.includes(zonedParts(candidate, timeZone).weekday);
545
+ const windowOk = invalidWindow || isInWindow(candidate, notBefore, notAfter, timeZone);
546
+ if (dayOk && windowOk) return candidate;
547
+ }
548
+ return null;
549
+ }
550
+
551
+ /** Состояние окна с учётом дней недели. */
552
+ export function activeWindowState(now: Date, options: ActiveWindowOptions = {}): ActiveWindowState {
553
+ const normalizedDays = normalizeActiveDays(options.days);
554
+ const dayOk =
555
+ !normalizedDays ||
556
+ normalizedDays.includes(zonedParts(now, options.timeZone).weekday);
557
+ const windowOk = isInWindow(now, options.notBefore, options.notAfter, options.timeZone);
558
+ if (dayOk && windowOk) return { active: true, nextOpenAt: null };
559
+
560
+ const reasons: string[] = [];
561
+ if (!dayOk) {
562
+ const days = (normalizedDays ?? [])
563
+ .map((d) => t(`schedule.weekday.${d}`))
564
+ .join(", ");
565
+ reasons.push(t("schedule.reason.dayNotAllowed", { days }));
566
+ }
567
+ if (!windowOk) {
568
+ reasons.push(
569
+ t("schedule.reason.outsideWindow", {
570
+ notBefore: options.notBefore,
571
+ notAfter: options.notAfter,
572
+ })
573
+ );
574
+ }
575
+ return {
576
+ active: false,
577
+ reason: reasons.join("; "),
578
+ nextOpenAt: nextWindowOpenAt(now, options),
579
+ };
580
+ }
581
+
582
+ /** Сколько мс до следующего разрешённого окна (0 — можно запускать). */
583
+ export function nextWindowOpenDelayMs(now: Date, options: ActiveWindowOptions = {}): number {
584
+ const state = activeWindowState(now, options);
585
+ if (state.active) return 0;
586
+ return state.nextOpenAt ? Math.max(0, state.nextOpenAt.getTime() - now.getTime()) : 0;
587
+ }
588
+
469
589
  // ---------------------------------------------------------------------------
470
590
  // Проверка совместимости с schtasks (родной режим).
471
591
 
@@ -502,6 +622,10 @@ export interface ScheduleGateSpec {
502
622
  tz?: string;
503
623
  notBefore?: string;
504
624
  notAfter?: string;
625
+ /** Разрешённые дни недели (0=Вс..6=Сб); пусто — все дни. */
626
+ days?: number[];
627
+ /** Поведение вне окна: skip — пропустить, run — выполнить всё равно. */
628
+ windowPolicy?: "skip" | "run";
505
629
  }
506
630
 
507
631
  /**
@@ -523,11 +647,22 @@ export function buildScheduleGate(
523
647
  expr: string,
524
648
  timezone?: string | null,
525
649
  notBefore?: string,
526
- notAfter?: string
650
+ notAfter?: string,
651
+ days?: number[] | null,
652
+ windowPolicy?: string | null
527
653
  ): ScheduleGateSpec | undefined {
528
654
  const tz = (timezone || "").trim() || undefined;
529
655
  const poll = needsPollMode(expr, tz);
530
- if (!poll && !(notBefore && notAfter)) return undefined;
656
+ const normalizedDays = normalizeActiveDays(days);
657
+ const policy = windowPolicy === "skip" || windowPolicy === "run" ? windowPolicy : undefined;
658
+ if (!poll && !(notBefore && notAfter) && !normalizedDays) return undefined;
531
659
  // cron проверяем только в poll-режиме (см. комментарий у ScheduleGateSpec).
532
- return { ...(poll ? { cron: expr } : {}), tz, notBefore, notAfter };
660
+ return {
661
+ ...(poll ? { cron: expr } : {}),
662
+ tz,
663
+ notBefore,
664
+ notAfter,
665
+ ...(normalizedDays ? { days: normalizedDays } : {}),
666
+ ...(policy ? { windowPolicy: policy } : {}),
667
+ };
533
668
  }
@@ -1,7 +1,7 @@
1
1
  import type { ScheduledTaskInfo } from "../../types.js";
2
2
 
3
3
  /** Чем запускается задача. */
4
- export type TriggerType = "cron" | "file" | "mcp-event" | "once";
4
+ export type TriggerType = "cron" | "file" | "git" | "mcp-event" | "once";
5
5
 
6
6
  /**
7
7
  * Параметры создания задачи. Бэкенд сам решает, как преобразовать cron
@@ -38,6 +38,12 @@ export interface CreateTaskOptions {
38
38
  notBefore?: string;
39
39
  /** Окно запуска «не позже» (HH:MM, 24ч). Парно с notBefore. */
40
40
  notAfter?: string;
41
+ /**
42
+ * Windows: запускать задачу и без входа пользователя (/ru SYSTEM).
43
+ * По умолчанию задача интерактивная — выполняется только при активном входе.
44
+ * На Linux/macOS не используется: cron и так работает без входа, launchd-агент — только при входе.
45
+ */
46
+ runWhenLoggedOff?: boolean;
41
47
  /** Аргументы schedule-gate для обёртки (расширенный cron / окно). */
42
48
  scheduleGate?: {
43
49
  cron?: string;