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
package/src/index.ts CHANGED
@@ -6,8 +6,16 @@ import { existsSync } from "node:fs";
6
6
  import fs from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { LockManager } from "./core/lock.js";
9
- import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
10
- import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
9
+ import {
10
+ LOCK_DIR,
11
+ LOG_DIR,
12
+ PLUGIN_DIR,
13
+ STALE_LOCK_MAX_AGE_MS,
14
+ WRAPPER_DIR,
15
+ sanitizeName,
16
+ validateTaskName,
17
+ } from "./types.js";
18
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
11
19
  import {
12
20
  buildLaunchdOneShotCleanup,
13
21
  normalizeOneShotRunAt,
@@ -39,6 +47,7 @@ import {
39
47
  import { SchedulerRpc } from "./rpc.js";
40
48
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
41
49
  import { loadSettings, saveSettings } from "./settings.js";
50
+ import { setLocale, t, type Locale } from "./i18n.js";
42
51
  import type {
43
52
  AuditSettings,
44
53
  HistorySettings,
@@ -65,6 +74,7 @@ import {
65
74
  normalizePriority,
66
75
  } from "./task-transfer.js";
67
76
  import { FileWatchManager } from "./core/file-watcher.js";
77
+ import { GitTriggerManager } from "./core/git-trigger.js";
68
78
  import type {
69
79
  McpEventTrigger,
70
80
  MatrixConfig,
@@ -88,7 +98,7 @@ import {
88
98
  import { closeDb, initDb } from "./db/index.js";
89
99
  import { migrateJsonToDb } from "./db/migrate.js";
90
100
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
91
- import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
101
+ import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
92
102
  import {
93
103
  addWorkspace,
94
104
  deleteWorkspace,
@@ -210,7 +220,11 @@ export const matrixSchema = z.object({
210
220
 
211
221
  /** Zod-схема аргументов schedule_task */
212
222
  export const scheduleTaskSchema = z.object({
213
- name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
223
+ name: z
224
+ .string()
225
+ .describe(
226
+ "Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."
227
+ ),
214
228
  schedule: z
215
229
  .string()
216
230
  .optional()
@@ -320,10 +334,10 @@ export const scheduleTaskSchema = z.object({
320
334
  .optional()
321
335
  .describe("Compensation/rollback task started after a failed run."),
322
336
  triggerType: z
323
- .enum(["cron", "file", "mcp-event", "once"])
337
+ .enum(["cron", "file", "git", "mcp-event", "once"])
324
338
  .optional()
325
339
  .describe(
326
- "Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."
340
+ "Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds)."
327
341
  ),
328
342
  mcpEvent: z
329
343
  .object({
@@ -341,6 +355,52 @@ export const scheduleTaskSchema = z.object({
341
355
  .describe(
342
356
  "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
343
357
  ),
358
+ watchGlobs: z
359
+ .array(z.string())
360
+ .optional()
361
+ .describe(
362
+ "Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."
363
+ ),
364
+ watchIgnore: z
365
+ .array(z.string())
366
+ .optional()
367
+ .describe(
368
+ "Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."
369
+ ),
370
+ gitBranch: z
371
+ .string()
372
+ .optional()
373
+ .describe(
374
+ "Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."
375
+ ),
376
+ gitPaths: z
377
+ .array(z.string())
378
+ .optional()
379
+ .describe(
380
+ "Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."
381
+ ),
382
+ gitIgnore: z
383
+ .array(z.string())
384
+ .optional()
385
+ .describe("Only for triggerType=git: glob masks of changed files to ignore."),
386
+ gitPollSeconds: z
387
+ .number()
388
+ .int()
389
+ .min(5)
390
+ .optional()
391
+ .describe("Only for triggerType=git: polling interval in seconds (default 60, minimum 5)."),
392
+ activeDays: z
393
+ .array(z.number().int().min(0).max(6))
394
+ .optional()
395
+ .describe(
396
+ "Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day."
397
+ ),
398
+ windowPolicy: z
399
+ .enum(["skip", "postpone", "run"])
400
+ .optional()
401
+ .describe(
402
+ "Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway."
403
+ ),
344
404
  workingDirectory: z
345
405
  .string()
346
406
  .optional()
@@ -365,6 +425,12 @@ export const scheduleTaskSchema = z.object({
365
425
  .describe(
366
426
  "Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."
367
427
  ),
428
+ runWhenLoggedOff: z
429
+ .boolean()
430
+ .optional()
431
+ .describe(
432
+ "Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."
433
+ ),
368
434
  matrix: matrixSchema
369
435
  .optional()
370
436
  .describe(
@@ -376,7 +442,7 @@ export const scheduleTaskSchema = z.object({
376
442
  ctx.addIssue({
377
443
  code: z.ZodIssueCode.custom,
378
444
  path: ["schedule"],
379
- message: "Для triggerType=cron нужно cron-выражение schedule.",
445
+ message: t("tool.error.cronSchedule"),
380
446
  });
381
447
  }
382
448
  if (
@@ -387,21 +453,21 @@ export const scheduleTaskSchema = z.object({
387
453
  ctx.addIssue({
388
454
  code: z.ZodIssueCode.custom,
389
455
  path: ["runAt"],
390
- message: "Для triggerType=once нужен runAt (ISO-8601) или delaySeconds.",
456
+ message: t("tool.error.onceSchedule"),
391
457
  });
392
458
  }
393
459
  if (trigger === "once" && value.matrix) {
394
460
  ctx.addIssue({
395
461
  code: z.ZodIssueCode.custom,
396
462
  path: ["matrix"],
397
- message: "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
463
+ message: t("tool.error.onceMatrixSchema"),
398
464
  });
399
465
  }
400
466
  if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
401
467
  ctx.addIssue({
402
468
  code: z.ZodIssueCode.custom,
403
469
  path: ["runAt"],
404
- message: "runAt/delaySeconds допустимы только при triggerType=once.",
470
+ message: t("tool.error.onceFields"),
405
471
  });
406
472
  }
407
473
  });
@@ -463,6 +529,48 @@ export const updateTaskSchema = z.object({
463
529
  .string()
464
530
  .optional()
465
531
  .describe("New launch window end HH:MM. Empty string clears the window."),
532
+ activeDays: z
533
+ .array(z.number().int().min(0).max(6))
534
+ .optional()
535
+ .describe(
536
+ "New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction."
537
+ ),
538
+ windowPolicy: z
539
+ .enum(["skip", "postpone", "run"])
540
+ .optional()
541
+ .describe("New behaviour outside the window: postpone (default), skip or run."),
542
+ runWhenLoggedOff: z
543
+ .boolean()
544
+ .optional()
545
+ .describe(
546
+ "Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only."
547
+ ),
548
+ watchGlobs: z
549
+ .array(z.string())
550
+ .optional()
551
+ .describe("New glob masks for a file trigger. Empty array clears them."),
552
+ watchIgnore: z
553
+ .array(z.string())
554
+ .optional()
555
+ .describe("New ignore masks for a file trigger. Empty array clears them."),
556
+ gitBranch: z
557
+ .string()
558
+ .optional()
559
+ .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
560
+ gitPaths: z
561
+ .array(z.string())
562
+ .optional()
563
+ .describe("New changed-file masks for a git trigger. Empty array clears them."),
564
+ gitIgnore: z
565
+ .array(z.string())
566
+ .optional()
567
+ .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
568
+ gitPollSeconds: z
569
+ .number()
570
+ .int()
571
+ .min(5)
572
+ .optional()
573
+ .describe("New git polling interval in seconds."),
466
574
  prompt: z
467
575
  .string()
468
576
  .optional()
@@ -500,7 +608,7 @@ export const updateTaskSchema = z.object({
500
608
  .optional()
501
609
  .describe("New error-chain task. Empty string clears it."),
502
610
  triggerType: z
503
- .enum(["cron", "file", "mcp-event", "once"])
611
+ .enum(["cron", "file", "git", "mcp-event", "once"])
504
612
  .optional()
505
613
  .describe("New trigger type."),
506
614
  mcpEvent: z
@@ -546,14 +654,14 @@ export const updateTaskSchema = z.object({
546
654
  ctx.addIssue({
547
655
  code: z.ZodIssueCode.custom,
548
656
  path: ["runAt"],
549
- message: "runAt/delaySeconds допустимы только при triggerType=once.",
657
+ message: t("tool.error.onceFields"),
550
658
  });
551
659
  }
552
660
  if (value.triggerType === "once" && value.matrix) {
553
661
  ctx.addIssue({
554
662
  code: z.ZodIssueCode.custom,
555
663
  path: ["matrix"],
556
- message: "One-shot нельзя комбинировать с matrix.",
664
+ message: t("tool.error.onceMatrixUpdate"),
557
665
  });
558
666
  }
559
667
  });
@@ -617,13 +725,13 @@ const manageWorkspacesSchema = z.object({
617
725
  .nullable()
618
726
  .optional()
619
727
  .describe(
620
- "Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."
728
+ "Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."
621
729
  ),
622
730
  envFile: z
623
731
  .string()
624
732
  .nullable()
625
733
  .optional()
626
- .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
734
+ .describe("Path to the workspace .env file (add/update, null clears it)."),
627
735
  });
628
736
 
629
737
  export const matrixControlSchema = z.object({
@@ -687,6 +795,12 @@ export const manageSettingsSchema = z.object({
687
795
  .max(16)
688
796
  .optional()
689
797
  .describe("How many task runs may execute at the same time."),
798
+ locale: z
799
+ .enum(["ru", "en"])
800
+ .optional()
801
+ .describe(
802
+ "Interface language: ru (default) or en. Applies without restart."
803
+ ),
690
804
  winterMode: z
691
805
  .boolean()
692
806
  .optional()
@@ -867,6 +981,90 @@ function wrapExecute<Args>(
867
981
  };
868
982
  }
869
983
 
984
+ /**
985
+ * Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
986
+ *
987
+ * - `once` → `runAt` (запланированный момент);
988
+ * - пауза (`paused` или будущий `pausedUntil`) → null;
989
+ * - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
990
+ * * `run` — окно игнорируется;
991
+ * * `skip` — ищем следующее совпадение внутри окна;
992
+ * * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
993
+ * - `file`/`git`/`mcp-event` → null (расписания нет).
994
+ */
995
+ function computeTaskNextRun(
996
+ def:
997
+ | Pick<
998
+ TaskDefinition,
999
+ | "schedule"
1000
+ | "triggerType"
1001
+ | "runAt"
1002
+ | "timezone"
1003
+ | "notBefore"
1004
+ | "notAfter"
1005
+ | "activeDays"
1006
+ | "windowPolicy"
1007
+ | "pausedUntil"
1008
+ >
1009
+ | undefined,
1010
+ options: { paused?: boolean; now?: Date } = {}
1011
+ ): string | null {
1012
+ if (!def) return null;
1013
+ if (options.paused) return null;
1014
+
1015
+ const now = options.now ?? new Date();
1016
+ if (def.pausedUntil) {
1017
+ const until = Date.parse(def.pausedUntil);
1018
+ if (Number.isFinite(until) && until > now.getTime()) return null;
1019
+ }
1020
+
1021
+ const type = def.triggerType ?? "cron";
1022
+ if (type === "once") {
1023
+ if (!def.runAt) return null;
1024
+ const at = Date.parse(def.runAt);
1025
+ return Number.isFinite(at) ? new Date(at).toISOString() : null;
1026
+ }
1027
+ if (type !== "cron") return null;
1028
+
1029
+ const schedule = (def.schedule || "").trim();
1030
+ if (!schedule) return null;
1031
+
1032
+ const timeZone = def.timezone?.trim() || undefined;
1033
+ const policy =
1034
+ def.windowPolicy === "skip" || def.windowPolicy === "run"
1035
+ ? def.windowPolicy
1036
+ : "postpone";
1037
+ const windowOptions = {
1038
+ notBefore: def.notBefore,
1039
+ notAfter: def.notAfter,
1040
+ days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
1041
+ timeZone,
1042
+ };
1043
+
1044
+ let tick: Date | null;
1045
+ try {
1046
+ tick = cronNextRun(schedule, now, timeZone);
1047
+ } catch {
1048
+ // Некорректное выражение не должно ломать ответ инструмента.
1049
+ return null;
1050
+ }
1051
+
1052
+ // skip-политика может пропустить сколько угодно тиков вне окна;
1053
+ // ограничение защищает от бесконечного перебора (5-летнее окно cron).
1054
+ for (let guard = 0; tick && guard < 600; guard += 1) {
1055
+ if (policy === "run") return tick.toISOString();
1056
+ const state = activeWindowState(tick, windowOptions);
1057
+ if (state.active) return tick.toISOString();
1058
+ if (policy === "skip") {
1059
+ tick = cronNextRun(schedule, tick, timeZone);
1060
+ continue;
1061
+ }
1062
+ // postpone: gate ждёт открытия окна и запускает задачу тогда же.
1063
+ return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
1064
+ }
1065
+ return null;
1066
+ }
1067
+
870
1068
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
871
1069
  const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
872
1070
  const {
@@ -899,6 +1097,15 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
899
1097
  notAfter,
900
1098
  session,
901
1099
  sessionMaxRuns,
1100
+ activeDays,
1101
+ windowPolicy,
1102
+ watchGlobs,
1103
+ watchIgnore,
1104
+ gitBranch,
1105
+ gitPaths,
1106
+ gitIgnore,
1107
+ gitPollSeconds,
1108
+ runWhenLoggedOff,
902
1109
  } = args;
903
1110
 
904
1111
  let effectiveRunAt: string | undefined;
@@ -952,7 +1159,19 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
952
1159
  effectiveRunAt,
953
1160
  effectiveSession,
954
1161
  effectiveSessionId,
955
- sessionMaxRuns
1162
+ sessionMaxRuns,
1163
+ {
1164
+ activeDays,
1165
+ windowPolicy,
1166
+ watchGlobs,
1167
+ watchIgnore,
1168
+ gitBranch,
1169
+ gitPaths,
1170
+ gitIgnore,
1171
+ gitPollSeconds,
1172
+ },
1173
+ // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
1174
+ runWhenLoggedOff === true
956
1175
  );
957
1176
  } catch (err: any) {
958
1177
  return {
@@ -965,18 +1184,36 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
965
1184
 
966
1185
  // Новый файловый триггер должен начать работать сразу, без перезапуска
967
1186
  // OpenCode: пересобираем набор watcher-ов после создания задачи.
968
- await refreshFileTriggers();
1187
+ await refreshTriggers();
969
1188
 
970
1189
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
971
1190
  const effectiveWorkdir =
972
1191
  workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
1192
+ // Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
1193
+ // списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
1194
+ const nextRun = computeTaskNextRun({
1195
+ schedule: schedule ?? "",
1196
+ triggerType: triggerType ?? "cron",
1197
+ runAt: effectiveRunAt,
1198
+ timezone,
1199
+ notBefore,
1200
+ notAfter,
1201
+ activeDays,
1202
+ windowPolicy,
1203
+ });
973
1204
  return {
974
1205
  content: JSON.stringify({
975
1206
  success: true,
976
- message: `Задача "${name}" успешно создана.`,
1207
+ paused: false,
1208
+ nextRun,
1209
+ runWhenLoggedOff: runWhenLoggedOff === true,
1210
+ message: t("tool.task.created", { name }),
977
1211
  task: {
978
1212
  name,
979
1213
  schedule,
1214
+ nextRun,
1215
+ paused: false,
1216
+ runWhenLoggedOff: runWhenLoggedOff === true,
980
1217
  timeoutSeconds: timeoutSeconds ?? 3600,
981
1218
  model: model?.trim() || null,
982
1219
  priority: priority ?? 5,
@@ -1008,14 +1245,18 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1008
1245
 
1009
1246
  /** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
1010
1247
  const listTasksExecute = wrapExecute<ListArgs>(async () => {
1011
- const tasks = await collectTasksView();
1248
+ const { tasks, osAvailable, osError } = await collectTasksView();
1012
1249
 
1013
1250
  if (tasks.length === 0) {
1014
1251
  return {
1015
1252
  content: JSON.stringify({
1016
1253
  success: true,
1017
- message: "Задачи плагина не найдены.",
1254
+ message: osAvailable
1255
+ ? t("tool.task.listEmpty")
1256
+ : t("tool.task.listOsUnavailable"),
1018
1257
  tasks: [],
1258
+ osAvailable,
1259
+ ...(osError ? { osError } : {}),
1019
1260
  }),
1020
1261
  };
1021
1262
  }
@@ -1023,8 +1264,12 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
1023
1264
  return {
1024
1265
  content: JSON.stringify({
1025
1266
  success: true,
1026
- message: `Найдено задач: ${tasks.length}.`,
1267
+ message: osAvailable
1268
+ ? t("tool.task.found", { count: tasks.length })
1269
+ : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1027
1270
  tasks,
1271
+ osAvailable,
1272
+ ...(osError ? { osError } : {}),
1028
1273
  }),
1029
1274
  };
1030
1275
  });
@@ -1042,7 +1287,7 @@ async function cancelMatrixRun(
1042
1287
  (def) => def.name.toLowerCase() === name.trim().toLowerCase()
1043
1288
  );
1044
1289
  if (!definition?.matrix) {
1045
- throw new Error(`Задача "${name}" не является матрицей.`);
1290
+ throw new Error(t("tool.error.matrixNotMatrix", { name }));
1046
1291
  }
1047
1292
 
1048
1293
  const result = await cancelPendingMatrixClones(definition.name);
@@ -1059,9 +1304,10 @@ async function cancelMatrixRun(
1059
1304
  await scheduler.deleteTask(clone.name);
1060
1305
  } catch (err: any) {
1061
1306
  warnings.push(
1062
- `${clone.name}: не удалось остановить — ${
1063
- err instanceof Error ? err.message : String(err)
1064
- }`
1307
+ t("tool.matrix.stopFailed", {
1308
+ clone: clone.name,
1309
+ error: err instanceof Error ? err.message : String(err),
1310
+ })
1065
1311
  );
1066
1312
  continue;
1067
1313
  }
@@ -1096,30 +1342,40 @@ async function cancelMatrixRun(
1096
1342
  clone.timezone,
1097
1343
  clone.notBefore,
1098
1344
  clone.notAfter,
1099
- clone.pausedUntil
1345
+ clone.pausedUntil,
1346
+ clone.runAt,
1347
+ clone.session,
1348
+ clone.sessionId,
1349
+ clone.sessionMaxRuns,
1350
+ undefined,
1351
+ clone.runWhenLoggedOff,
1352
+ clone.paused
1100
1353
  );
1101
1354
  } catch (err: any) {
1102
1355
  warnings.push(
1103
- `${clone.name}: не удалось пересоздать — ${
1104
- err instanceof Error ? err.message : String(err)
1105
- }`
1356
+ t("tool.matrix.recreateFailed", {
1357
+ clone: clone.name,
1358
+ error: err instanceof Error ? err.message : String(err),
1359
+ })
1106
1360
  );
1107
1361
  }
1108
1362
  }
1109
1363
 
1110
1364
  const parts = [
1111
- `Матрица "${definition.name}": отменено ${result.cancelled.length} из ${
1112
- result.aggregate.totalCount
1113
- } клонов.`,
1365
+ t("tool.matrix.cancelSummary", {
1366
+ matrix: definition.name,
1367
+ cancelled: result.cancelled.length,
1368
+ total: result.aggregate.totalCount,
1369
+ }),
1114
1370
  ];
1115
1371
  if (result.running.length > 0) {
1116
- parts.push(`Остановлено выполнявшихся: ${result.running.length}.`);
1372
+ parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
1117
1373
  }
1118
1374
  if (result.alreadyFinished.length > 0) {
1119
- parts.push(`Уже завершены и не тронуты: ${result.alreadyFinished.length}.`);
1375
+ parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
1120
1376
  }
1121
1377
  if (warnings.length > 0) {
1122
- parts.push(`Предупреждения: ${warnings.join("; ")}.`);
1378
+ parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
1123
1379
  }
1124
1380
 
1125
1381
  return {
@@ -1164,6 +1420,83 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
1164
1420
  * - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
1165
1421
  * - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
1166
1422
  */
1423
+ /**
1424
+ * Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
1425
+ * Отсутствующие файлы игнорируются — операция идемпотентна.
1426
+ */
1427
+ async function removeTaskArtifacts(name: string): Promise<void> {
1428
+ const sanitized = sanitizeName(name);
1429
+ const candidates = [
1430
+ path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
1431
+ path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
1432
+ path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
1433
+ path.join(LOG_DIR, `${sanitized}.log`),
1434
+ path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
1435
+ path.join(LOCK_DIR, `${sanitized}.lock`),
1436
+ path.join(LOCK_DIR, `${sanitized}.lock.defer`),
1437
+ path.join(LOCK_DIR, `${sanitized}.lock.force`),
1438
+ ];
1439
+ await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
1440
+ }
1441
+
1442
+ /**
1443
+ * Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
1444
+ * больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
1445
+ */
1446
+ async function garbageCollectTaskArtifacts(): Promise<void> {
1447
+ let entries: string[];
1448
+ try {
1449
+ entries = await fs.readdir(WRAPPER_DIR);
1450
+ } catch {
1451
+ return;
1452
+ }
1453
+ const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
1454
+ if (wrappers.length === 0) return;
1455
+
1456
+ const known = new Set<string>();
1457
+ try {
1458
+ for (const task of listTaskDefinitions()) known.add(sanitizeName(task.name));
1459
+ } catch {
1460
+ // БД может быть ещё не готова — тогда опираемся на ОС.
1461
+ }
1462
+ try {
1463
+ for (const task of await scheduler.listTasks()) {
1464
+ known.add(sanitizeName(task.taskName || ""));
1465
+ }
1466
+ } catch {
1467
+ // Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
1468
+ return;
1469
+ }
1470
+
1471
+ let cleaned = 0;
1472
+ for (const file of wrappers) {
1473
+ const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
1474
+ const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
1475
+ if (known.has(stem)) continue;
1476
+ try {
1477
+ const stat = await fs.stat(lockPath);
1478
+ if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS) continue;
1479
+ } catch {
1480
+ // lock-файла нет — можно удалять.
1481
+ }
1482
+ const candidates = [
1483
+ path.join(WRAPPER_DIR, `run-${stem}.cmd`),
1484
+ path.join(WRAPPER_DIR, `run-${stem}.sh`),
1485
+ path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
1486
+ path.join(LOG_DIR, `${stem}.log`),
1487
+ path.join(PLUGIN_DIR, "env", `${stem}.env`),
1488
+ path.join(LOCK_DIR, `${stem}.lock`),
1489
+ path.join(LOCK_DIR, `${stem}.lock.defer`),
1490
+ path.join(LOCK_DIR, `${stem}.lock.force`),
1491
+ ];
1492
+ await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
1493
+ cleaned += 1;
1494
+ }
1495
+ if (cleaned > 0) {
1496
+ console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
1497
+ }
1498
+ }
1499
+
1167
1500
  async function deleteTaskWithFamily(
1168
1501
  name: string
1169
1502
  ): Promise<{ removed: string[]; existed: boolean }> {
@@ -1201,6 +1534,8 @@ async function deleteTaskWithFamily(
1201
1534
  } catch {
1202
1535
  // Не критично.
1203
1536
  }
1537
+ removeTaskArtifacts(child);
1538
+
1204
1539
  removed.push(child);
1205
1540
  }
1206
1541
  }
@@ -1211,6 +1546,7 @@ async function deleteTaskWithFamily(
1211
1546
  } catch {
1212
1547
  // Определения могло уже не быть — задача всё равно удалена из ОС.
1213
1548
  }
1549
+ removeTaskArtifacts(trimmed);
1214
1550
 
1215
1551
  return { removed, existed };
1216
1552
  }
@@ -1222,12 +1558,12 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
1222
1558
  try {
1223
1559
  const { removed, existed } = await deleteTaskWithFamily(name);
1224
1560
  // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
1225
- await refreshFileTriggers();
1561
+ await refreshTriggers();
1226
1562
  if (!existed && removed.length === 0) {
1227
1563
  return {
1228
1564
  content: JSON.stringify({
1229
- success: false,
1230
- error: `Задача "${name}" не найдена — удалять нечего.`,
1565
+ success: true,
1566
+ message: t("tool.task.alreadyAbsent", { name }),
1231
1567
  }),
1232
1568
  };
1233
1569
  }
@@ -1236,8 +1572,8 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
1236
1572
  success: true,
1237
1573
  message:
1238
1574
  removed.length > 0
1239
- ? `Матрица "${name}" удалена вместе с клонами: ${removed.join(", ")}.`
1240
- : `Задача "${name}" успешно удалена.`,
1575
+ ? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
1576
+ : t("tool.task.deleted", { name }),
1241
1577
  }),
1242
1578
  };
1243
1579
  } catch (err: any) {
@@ -1271,8 +1607,8 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
1271
1607
  content: JSON.stringify({
1272
1608
  success: true,
1273
1609
  message: alreadyRunning
1274
- ? `Задача "${name}" уже выполняется.`
1275
- : `Задача "${name}" запущена.`,
1610
+ ? t("tool.task.alreadyRunning", { name })
1611
+ : t("tool.task.started", { name }),
1276
1612
  }),
1277
1613
  };
1278
1614
  });
@@ -1324,15 +1660,26 @@ async function removeMatrixChildrenFromScheduler(name: string): Promise<string[]
1324
1660
  */
1325
1661
  async function updateTaskFromInput(
1326
1662
  input: UpdateArgs & { newSchedule?: string; newPrompt?: string }
1327
- ): Promise<{ success: boolean; message: string }> {
1663
+ ): Promise<{
1664
+ success: boolean;
1665
+ message: string;
1666
+ /** Спринт 27.5.2: состояние и ближайший запуск после обновления. */
1667
+ paused?: boolean;
1668
+ nextRun?: string | null;
1669
+ /**
1670
+ * Спринт 27.5.6: при ошибке обновления — удалось ли сохранить прежнюю
1671
+ * версию задачи в планировщике (true — старая версия на месте).
1672
+ */
1673
+ restored?: boolean;
1674
+ }> {
1328
1675
  const name = input.name?.trim();
1329
1676
  if (!name) {
1330
- return { success: false, message: "Не передано имя задачи." };
1677
+ return { success: false, message: t("tool.error.taskNameMissing") };
1331
1678
  }
1332
1679
 
1333
1680
  const previous = getTask(name);
1334
1681
  if (!previous) {
1335
- return { success: false, message: `Задача "${name}" не найдена.` };
1682
+ return { success: false, message: t("tool.error.taskNotFound", { name }) };
1336
1683
  }
1337
1684
 
1338
1685
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
@@ -1345,13 +1692,13 @@ async function updateTaskFromInput(
1345
1692
  if (triggerType === "cron" && !schedule) {
1346
1693
  return {
1347
1694
  success: false,
1348
- message: `Для обновления задачи "${name}" нужен cron-график.`,
1695
+ message: t("tool.error.updateCron", { name }),
1349
1696
  };
1350
1697
  }
1351
1698
  if (!prompt) {
1352
1699
  return {
1353
1700
  success: false,
1354
- message: `Для обновления задачи "${name}" нужен промпт.`,
1701
+ message: t("tool.error.updatePrompt", { name }),
1355
1702
  };
1356
1703
  }
1357
1704
 
@@ -1372,7 +1719,7 @@ async function updateTaskFromInput(
1372
1719
  if (!normalized.ok) {
1373
1720
  return {
1374
1721
  success: false,
1375
- message: `Задача "${name}": ${normalized.error}`,
1722
+ message: t("tool.error.taskReason", { name, error: normalized.error }),
1376
1723
  };
1377
1724
  }
1378
1725
  runAt = normalized.runAt;
@@ -1386,7 +1733,7 @@ async function updateTaskFromInput(
1386
1733
  if (!normalizedSession) {
1387
1734
  return {
1388
1735
  success: false,
1389
- message: `Задача "${name}": неизвестный режим сессии "${String(input.session)}".`,
1736
+ message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
1390
1737
  };
1391
1738
  }
1392
1739
  session = normalizedSession;
@@ -1401,7 +1748,7 @@ async function updateTaskFromInput(
1401
1748
  ) {
1402
1749
  return {
1403
1750
  success: false,
1404
- message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.`,
1751
+ message: t("tool.error.sessionMaxRuns", { name }),
1405
1752
  };
1406
1753
  }
1407
1754
  let sessionId = previous.sessionId;
@@ -1418,15 +1765,50 @@ async function updateTaskFromInput(
1418
1765
  if (triggerType === "once" && matrixNext) {
1419
1766
  return {
1420
1767
  success: false,
1421
- message:
1422
- `Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
1423
- `Запустите матрицу вручную или используйте cron/file-триггер.`,
1768
+ message: t("tool.error.oneShotMatrix", { name }),
1424
1769
  };
1425
1770
  }
1426
1771
 
1772
+ // Спринт 27: параметры триггеров сохраняются, если поле не передано.
1773
+ const mergeStringList = (
1774
+ next: string[] | undefined,
1775
+ prev: string[] | undefined
1776
+ ): string[] | undefined => {
1777
+ if (next === undefined) return prev;
1778
+ const cleaned = next
1779
+ .filter((item): item is string => typeof item === "string")
1780
+ .map((item) => item.trim())
1781
+ .filter(Boolean);
1782
+ return cleaned.length > 0 ? cleaned : undefined;
1783
+ };
1784
+ const triggerExtras: TriggerExtras = {
1785
+ activeDays:
1786
+ input.activeDays === undefined
1787
+ ? previous.activeDays
1788
+ : input.activeDays.length > 0
1789
+ ? input.activeDays
1790
+ : undefined,
1791
+ windowPolicy: input.windowPolicy ?? previous.windowPolicy,
1792
+ watchGlobs: mergeStringList(input.watchGlobs, previous.watchGlobs),
1793
+ watchIgnore: mergeStringList(input.watchIgnore, previous.watchIgnore),
1794
+ gitBranch: clearableString(input.gitBranch, previous.gitBranch),
1795
+ gitPaths: mergeStringList(input.gitPaths, previous.gitPaths),
1796
+ gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
1797
+ gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
1798
+ };
1799
+
1800
+ // Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
1801
+ // после create — иначе задача молча начинает выполняться по расписанию.
1802
+ const wasPaused = Boolean(
1803
+ previous.paused === true ||
1804
+ (previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now())
1805
+ );
1806
+
1807
+ let previousDeleted = false;
1427
1808
  try {
1428
1809
  // Обновление = пересоздание в планировщике с сохранением старых значений.
1429
1810
  await scheduler.deleteTask(name);
1811
+ previousDeleted = true;
1430
1812
  await schedulerCreateTask(
1431
1813
  name,
1432
1814
  schedule ?? "",
@@ -1461,7 +1843,10 @@ async function updateTaskFromInput(
1461
1843
  runAt,
1462
1844
  session,
1463
1845
  sessionId,
1464
- sessionMaxRuns
1846
+ sessionMaxRuns,
1847
+ triggerExtras,
1848
+ input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
1849
+ wasPaused
1465
1850
  );
1466
1851
 
1467
1852
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -1471,14 +1856,61 @@ async function updateTaskFromInput(
1471
1856
 
1472
1857
  // Пересоздание могло изменить triggerType/watchPath — сразу
1473
1858
  // пересобираем набор файловых watcher-ов.
1474
- await refreshFileTriggers();
1859
+ await refreshTriggers();
1475
1860
 
1476
- return { success: true, message: `Задача "${name}" обновлена.` };
1477
- } catch (err: any) {
1861
+ // Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
1862
+ // рассчитанный из нового определения, не дожидаясь ОС.
1863
+ const updated = getTask(name);
1864
+ const paused = wasPaused;
1478
1865
  return {
1479
- success: false,
1480
- message: err instanceof Error ? err.message : String(err),
1866
+ success: true,
1867
+ paused,
1868
+ nextRun: computeTaskNextRun(updated, { paused }),
1869
+ message: t("tool.task.updated", { name }),
1481
1870
  };
1871
+ } catch (err: any) {
1872
+ const cause = err instanceof Error ? err.message : String(err);
1873
+
1874
+ // Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
1875
+ if (!previousDeleted) {
1876
+ return {
1877
+ success: false,
1878
+ restored: true,
1879
+ message: t("tool.task.rollbackKept", { cause }),
1880
+ };
1881
+ }
1882
+
1883
+ // Убираем возможный частичный результат новой попытки: обёртка могла
1884
+ // успеть зарегистрироваться, хотя create вернул ошибку.
1885
+ try {
1886
+ await scheduler.deleteTask(name);
1887
+ } catch {
1888
+ // Задачи могло не быть — это ожидаемо.
1889
+ }
1890
+
1891
+ // Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
1892
+ // прежнюю версию: расписание, промпт, обёртку и паузу.
1893
+ try {
1894
+ await recreateTaskFromDefinition(previous);
1895
+ await refreshTriggers().catch(() => undefined);
1896
+ return {
1897
+ success: false,
1898
+ restored: true,
1899
+ message: t("tool.task.rollbackRestored", { cause }),
1900
+ };
1901
+ } catch (restoreErr: any) {
1902
+ const restoreMessage =
1903
+ restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
1904
+ return {
1905
+ success: false,
1906
+ restored: false,
1907
+ message: t("tool.task.rollbackFailed", {
1908
+ cause,
1909
+ restore: restoreMessage,
1910
+ name,
1911
+ }),
1912
+ };
1913
+ }
1482
1914
  }
1483
1915
  }
1484
1916
 
@@ -1496,15 +1928,27 @@ async function pauseOrResumeTask(
1496
1928
  name: string,
1497
1929
  paused: boolean,
1498
1930
  until?: string
1499
- ): Promise<{ success: boolean; message: string; affected: string[]; warnings: string[] }> {
1931
+ ): Promise<{
1932
+ success: boolean;
1933
+ message: string;
1934
+ affected: string[];
1935
+ warnings: string[];
1936
+ /** Спринт 27.5.2: состояние и ближайший запуск после мутации. */
1937
+ paused: boolean;
1938
+ nextRun: string | null;
1939
+ pausedUntil: string | null;
1940
+ }> {
1500
1941
  const trimmed = name.trim();
1501
1942
  const definition = getTask(trimmed);
1502
1943
  if (!definition) {
1503
1944
  return {
1504
1945
  success: false,
1505
- message: `Задача "${trimmed}" не найдена.`,
1946
+ message: t("tool.error.taskNotFound", { name: trimmed }),
1506
1947
  affected: [],
1507
1948
  warnings: [],
1949
+ paused,
1950
+ nextRun: null,
1951
+ pausedUntil: null,
1508
1952
  };
1509
1953
  }
1510
1954
 
@@ -1515,17 +1959,23 @@ async function pauseOrResumeTask(
1515
1959
  if (Number.isNaN(parsed)) {
1516
1960
  return {
1517
1961
  success: false,
1518
- message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
1962
+ message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
1519
1963
  affected: [],
1520
1964
  warnings: [],
1965
+ paused,
1966
+ nextRun: null,
1967
+ pausedUntil: definition.pausedUntil ?? null,
1521
1968
  };
1522
1969
  }
1523
1970
  if (parsed <= Date.now()) {
1524
1971
  return {
1525
1972
  success: false,
1526
- message: `Задача "${trimmed}": дата паузы уже прошла.`,
1973
+ message: t("tool.error.pauseDatePast", { name: trimmed }),
1527
1974
  affected: [],
1528
1975
  warnings: [],
1976
+ paused,
1977
+ nextRun: null,
1978
+ pausedUntil: definition.pausedUntil ?? null,
1529
1979
  };
1530
1980
  }
1531
1981
  pausedUntil = new Date(parsed).toISOString();
@@ -1537,9 +1987,12 @@ async function pauseOrResumeTask(
1537
1987
  if (targets.length === 0 && definition.matrix) {
1538
1988
  return {
1539
1989
  success: false,
1540
- message: `У матрицы "${trimmed}" нет клонов.`,
1990
+ message: t("tool.error.matrixNoClones", { name: trimmed }),
1541
1991
  affected: [],
1542
1992
  warnings: [],
1993
+ paused,
1994
+ nextRun: null,
1995
+ pausedUntil: definition.pausedUntil ?? null,
1543
1996
  };
1544
1997
  }
1545
1998
 
@@ -1560,42 +2013,69 @@ async function pauseOrResumeTask(
1560
2013
  }
1561
2014
  }
1562
2015
 
1563
- // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
2016
+ // Фиксируем (или снимаем) паузу в определении задачи. У матрицы
1564
2017
  // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
1565
- const definitionUpdates = paused
1566
- ? pausedUntil
1567
- ? { pausedUntil }
1568
- : undefined
1569
- : definition.pausedUntil
1570
- ? { pausedUntil: undefined }
2018
+ // Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
2019
+ // update_task пересоздаёт задачу включённой и пауза теряется.
2020
+ const definitionUpdates: Partial<TaskDefinition> | undefined = paused
2021
+ ? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
2022
+ : definition.paused || definition.pausedUntil
2023
+ ? { paused: false, pausedUntil: undefined }
1571
2024
  : undefined;
1572
2025
  if (definitionUpdates && affected.length > 0) {
1573
2026
  try {
1574
2027
  saveTask({ ...definition, ...definitionUpdates });
1575
2028
  } catch (err: any) {
1576
2029
  warnings.push(
1577
- `не удалось сохранить автопродолжение: ${
1578
- err instanceof Error ? err.message : String(err)
1579
- }`
2030
+ t("tool.task.autosave", {
2031
+ error: err instanceof Error ? err.message : String(err),
2032
+ })
1580
2033
  );
1581
2034
  }
1582
2035
  }
1583
2036
 
1584
2037
  const untilText = pausedUntil
1585
- ? ` до ${new Date(pausedUntil).toLocaleString()}`
2038
+ ? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
1586
2039
  : "";
1587
- const verb = paused ? "поставлена на паузу" : "возобновлена";
2040
+ const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
1588
2041
  const message = definition.matrix
1589
- ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
1590
- (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
1591
- : `Задача "${trimmed}" ${verb}${untilText}.` +
1592
- (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
2042
+ ? t("tool.task.matrixPaused", {
2043
+ name: trimmed,
2044
+ verb,
2045
+ until: untilText,
2046
+ affected: affected.length,
2047
+ total: targets.length,
2048
+ }) +
2049
+ (warnings.length > 0
2050
+ ? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
2051
+ : "")
2052
+ : t("tool.task.pausedText", {
2053
+ name: trimmed,
2054
+ verb,
2055
+ until: untilText,
2056
+ }) +
2057
+ (warnings.length > 0
2058
+ ? t("tool.task.pauseError", { warnings: warnings.join("; ") })
2059
+ : "");
2060
+
2061
+ // Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
2062
+ // schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
2063
+ const effectivePausedUntil = paused
2064
+ ? pausedUntil ?? definition.pausedUntil ?? null
2065
+ : null;
2066
+ const after = definitionUpdates
2067
+ ? { ...definition, ...definitionUpdates }
2068
+ : { ...definition, paused: false, pausedUntil: undefined };
2069
+ const nextRun = paused ? null : computeTaskNextRun(after);
1593
2070
 
1594
2071
  return {
1595
2072
  success: warnings.length === 0,
1596
2073
  message,
1597
2074
  affected,
1598
2075
  warnings,
2076
+ paused,
2077
+ nextRun,
2078
+ pausedUntil: effectivePausedUntil,
1599
2079
  };
1600
2080
  }
1601
2081
 
@@ -1635,7 +2115,11 @@ async function resumeExpiredPauses(): Promise<void> {
1635
2115
  for (const target of targets) {
1636
2116
  await scheduler.resumeTask(target);
1637
2117
  }
1638
- await saveTaskDefinition({ ...definition, pausedUntil: undefined });
2118
+ await saveTaskDefinition({
2119
+ ...definition,
2120
+ pausedUntil: undefined,
2121
+ paused: false,
2122
+ });
1639
2123
  console.log(
1640
2124
  `[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
1641
2125
  );
@@ -1802,7 +2286,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1802
2286
  return {
1803
2287
  content: JSON.stringify({
1804
2288
  success: false,
1805
- error: "Для action=add нужен path.",
2289
+ error: t("tool.workspace.needPath"),
1806
2290
  }),
1807
2291
  };
1808
2292
  }
@@ -1829,7 +2313,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1829
2313
  return {
1830
2314
  content: JSON.stringify({
1831
2315
  success: false,
1832
- error: "Для action=update нужен id.",
2316
+ error: t("tool.workspace.needUpdateId"),
1833
2317
  }),
1834
2318
  };
1835
2319
  }
@@ -1844,7 +2328,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1844
2328
  return {
1845
2329
  content: JSON.stringify({
1846
2330
  success: false,
1847
- error: "Workspace не найден.",
2331
+ error: t("tool.workspace.notFound"),
1848
2332
  }),
1849
2333
  };
1850
2334
  }
@@ -1868,7 +2352,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1868
2352
  return {
1869
2353
  content: JSON.stringify({
1870
2354
  success: false,
1871
- error: "Для action=delete нужен id.",
2355
+ error: t("tool.workspace.needDeleteId"),
1872
2356
  }),
1873
2357
  };
1874
2358
  }
@@ -1877,8 +2361,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1877
2361
  content: JSON.stringify({
1878
2362
  success: deleted,
1879
2363
  message: deleted
1880
- ? "Workspace удалён. Задачи сохранены, привязка очищена."
1881
- : "Workspace не найден.",
2364
+ ? t("tool.workspace.deleted")
2365
+ : t("tool.workspace.notFound"),
1882
2366
  }),
1883
2367
  };
1884
2368
  }
@@ -1926,8 +2410,8 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1926
2410
  success: true,
1927
2411
  message:
1928
2412
  removed.length > 0
1929
- ? `Удалено осиротевших задач: ${removed.length}.`
1930
- : "Осиротевших задач не найдено.",
2413
+ ? t("tool.matrix.orphansRemoved", { count: removed.length })
2414
+ : t("tool.matrix.orphansNone"),
1931
2415
  removed,
1932
2416
  }),
1933
2417
  };
@@ -1938,7 +2422,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1938
2422
  return {
1939
2423
  content: JSON.stringify({
1940
2424
  success: false,
1941
- error: `Для action=${args.action} нужен name матрицы.`,
2425
+ error: t("tool.matrix.actionName", { action: args.action }),
1942
2426
  }),
1943
2427
  };
1944
2428
  }
@@ -2007,6 +2491,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2007
2491
 
2008
2492
  if (
2009
2493
  args.maxConcurrent === undefined &&
2494
+ args.locale === undefined &&
2010
2495
  args.winterMode === undefined &&
2011
2496
  args.notifications === undefined &&
2012
2497
  args.history === undefined &&
@@ -2016,8 +2501,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2016
2501
  return {
2017
2502
  content: JSON.stringify({
2018
2503
  success: false,
2019
- error:
2020
- "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
2504
+ error: t("tool.settings.updateFields"),
2021
2505
  settings: current,
2022
2506
  }),
2023
2507
  };
@@ -2025,12 +2509,15 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2025
2509
 
2026
2510
  const settings = await saveSettings({
2027
2511
  maxConcurrent: args.maxConcurrent,
2512
+ locale: args.locale,
2028
2513
  winterMode: args.winterMode,
2029
2514
  notifications: args.notifications as NotificationSettings | undefined,
2030
2515
  history: args.history as HistorySettings | undefined,
2031
2516
  integrations: args.integrations as IntegrationSettings | undefined,
2032
2517
  audit: args.audit as AuditSettings | undefined,
2033
2518
  });
2519
+ // Локаль процесса меняется сразу — перезапуск плагина не нужен.
2520
+ setLocale(settings.locale);
2034
2521
  return { content: JSON.stringify({ success: true, settings }) };
2035
2522
  });
2036
2523
 
@@ -2043,7 +2530,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
2043
2530
  if (args.action === "delete") {
2044
2531
  const id = args.id?.trim();
2045
2532
  if (!id) {
2046
- return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
2533
+ return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
2047
2534
  }
2048
2535
  const before = await loadTemplates();
2049
2536
  const existed = before.some((template) => template.id === id);
@@ -2051,7 +2538,9 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
2051
2538
  return {
2052
2539
  content: JSON.stringify({
2053
2540
  success: existed,
2054
- message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
2541
+ message: existed
2542
+ ? t("tool.template.deleted", { id })
2543
+ : t("tool.template.notFound", { id }),
2055
2544
  }),
2056
2545
  };
2057
2546
  }
@@ -2061,7 +2550,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
2061
2550
  return {
2062
2551
  content: JSON.stringify({
2063
2552
  success: false,
2064
- error: "Для action=save нужны непустые name и prompt.",
2553
+ error: t("tool.template.saveRequired"),
2065
2554
  }),
2066
2555
  };
2067
2556
  }
@@ -2087,7 +2576,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
2087
2576
  return {
2088
2577
  content: JSON.stringify({
2089
2578
  success: false,
2090
- error: `Для action=${args.action} нужно имя профиля.`,
2579
+ error: t("tool.profile.nameRequired", { action: args.action }),
2091
2580
  }),
2092
2581
  };
2093
2582
  }
@@ -2098,7 +2587,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
2098
2587
  return {
2099
2588
  content: JSON.stringify({
2100
2589
  success: true,
2101
- message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2590
+ message: t("tool.profile.created", { name: meta.name, port: meta.port }),
2102
2591
  profile: profile ?? {
2103
2592
  name: meta.name,
2104
2593
  dir: getProfileDir(meta.name),
@@ -2119,8 +2608,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
2119
2608
  current,
2120
2609
  restartRequired: true,
2121
2610
  message: isProfilePinnedByEnv()
2122
- ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
2123
- : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
2611
+ ? t("tool.profile.envVar", { name: current })
2612
+ : t("tool.profile.active", { name: sanitizeProfileName(name) }),
2124
2613
  }),
2125
2614
  };
2126
2615
  }
@@ -2130,8 +2619,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
2130
2619
  content: JSON.stringify({
2131
2620
  success: removed,
2132
2621
  message: removed
2133
- ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2134
- : "Профиль не найден.",
2622
+ ? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
2623
+ : t("tool.profile.notFound"),
2135
2624
  }),
2136
2625
  };
2137
2626
  });
@@ -2147,14 +2636,14 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2147
2636
  }
2148
2637
 
2149
2638
  if (!args.data) {
2150
- return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
2639
+ return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
2151
2640
  }
2152
2641
  const parsed = parseImportJson(args.data);
2153
2642
  if (parsed.tasks.length === 0) {
2154
2643
  return {
2155
2644
  content: JSON.stringify({
2156
2645
  success: false,
2157
- error: "В данных нет задач для импорта.",
2646
+ error: t("tool.transfer.noTasks"),
2158
2647
  errors: parsed.errors,
2159
2648
  }),
2160
2649
  };
@@ -2201,7 +2690,7 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2201
2690
  errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
2202
2691
  }
2203
2692
  }
2204
- await refreshFileTriggers();
2693
+ await refreshTriggers();
2205
2694
  return {
2206
2695
  content: JSON.stringify({ success: errors.length === 0, imported, errors }),
2207
2696
  };
@@ -2242,7 +2731,12 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
2242
2731
  success: true,
2243
2732
  message: report.skipped
2244
2733
  ? report.skipped
2245
- : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
2734
+ : t("tool.history.cleaned", {
2735
+ deleted: report.deleted,
2736
+ byAge: report.deletedByAge,
2737
+ byCount: report.deletedByCount,
2738
+ kept: report.kept,
2739
+ }),
2246
2740
  report,
2247
2741
  }),
2248
2742
  };
@@ -2252,7 +2746,7 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
2252
2746
  const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2253
2747
  const eventName = args.eventName?.trim();
2254
2748
  if (!eventName) {
2255
- return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
2749
+ return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
2256
2750
  }
2257
2751
  const payload = args.payload ?? {};
2258
2752
  const definitions = await loadTaskDefinitions();
@@ -2282,8 +2776,8 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2282
2776
  success: true,
2283
2777
  message:
2284
2778
  triggered.length > 0
2285
- ? `Запущено задач: ${triggered.length}.`
2286
- : `Нет задач, подписанных на событие "${eventName}".`,
2779
+ ? t("tool.event.triggered", { count: triggered.length })
2780
+ : t("tool.event.none", { event: eventName }),
2287
2781
  triggered,
2288
2782
  }),
2289
2783
  };
@@ -2300,7 +2794,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2300
2794
  return {
2301
2795
  content: JSON.stringify({
2302
2796
  success: false,
2303
- error: "Для set/delete нужно имя секрета.",
2797
+ error: t("tool.secret.nameRequired"),
2304
2798
  }),
2305
2799
  };
2306
2800
  }
@@ -2312,8 +2806,8 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2312
2806
  content: JSON.stringify({
2313
2807
  success: existed,
2314
2808
  message: existed
2315
- ? `Секрет ${name} удалён.`
2316
- : `Секрет ${name} не найден.`,
2809
+ ? t("tool.secret.deleted", { name })
2810
+ : t("tool.secret.notFound", { name }),
2317
2811
  }),
2318
2812
  };
2319
2813
  }
@@ -2323,7 +2817,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2323
2817
  return {
2324
2818
  content: JSON.stringify({
2325
2819
  success: false,
2326
- error: "Для action=set нужно непустое значение value.",
2820
+ error: t("tool.secret.valueRequired"),
2327
2821
  }),
2328
2822
  };
2329
2823
  }
@@ -2332,7 +2826,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2332
2826
  return {
2333
2827
  content: JSON.stringify({
2334
2828
  success: true,
2335
- message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
2829
+ message: t("tool.secret.saved", { name: item.name }),
2336
2830
  secret: item,
2337
2831
  }),
2338
2832
  };
@@ -2488,17 +2982,105 @@ function withRpcAudit<T extends Record<string, (...args: any[]) => any>>(handler
2488
2982
  */
2489
2983
  let fileWatcherManager: FileWatchManager | null = null;
2490
2984
 
2491
- async function refreshFileTriggers(): Promise<void> {
2492
- if (!fileWatcherManager) return;
2493
- try {
2494
- await fileWatcherManager.refresh();
2495
- } catch (err: any) {
2496
- console.error(
2497
- `[windows-scheduler] Не удалось обновить файловые триггеры: ${
2498
- err instanceof Error ? err.message : String(err)
2499
- }`
2985
+ /**
2986
+ * Спринт 27: менеджер git-триггеров. Опрашивает HEAD задач с
2987
+ * triggerType === "git" и запускает их при новых подходящих коммитах.
2988
+ */
2989
+ let gitTriggerManager: GitTriggerManager | null = null;
2990
+
2991
+ /**
2992
+ * Приводит в актуальное состояние все событийные триггеры (файлы и git).
2993
+ * Вызывается после создания, изменения и удаления задачи.
2994
+ */
2995
+ async function refreshTriggers(): Promise<void> {
2996
+ if (fileWatcherManager) {
2997
+ try {
2998
+ await fileWatcherManager.refresh();
2999
+ } catch (err: any) {
3000
+ console.error(
3001
+ `[windows-scheduler] Не удалось обновить файловые триггеры: ${
3002
+ err instanceof Error ? err.message : String(err)
3003
+ }`
3004
+ );
3005
+ }
3006
+ }
3007
+ if (gitTriggerManager) {
3008
+ try {
3009
+ await gitTriggerManager.refresh();
3010
+ } catch (err: any) {
3011
+ console.error(
3012
+ `[windows-scheduler] Не удалось обновить git-триггеры: ${
3013
+ err instanceof Error ? err.message : String(err)
3014
+ }`
3015
+ );
3016
+ }
3017
+ }
3018
+ }
3019
+
3020
+ /** Максимальная задержка переноса событийного запуска (12 часов). */
3021
+ const EVENT_POSTPONE_MAX_MS = 12 * 60 * 60 * 1000;
3022
+
3023
+ /**
3024
+ * Спринт 27: запуск задачи по событию (файл, git, MCP) с учётом окна запуска
3025
+ * и разрешённых дней недели. Вне окна: skip — пишем причину и выходим,
3026
+ * postpone — таймер до ближайшего открытия, run — запускаем сразу.
3027
+ */
3028
+ async function scheduleEventRun(taskName: string, reason: string): Promise<void> {
3029
+ const definition = getTask(taskName);
3030
+ if (!definition) return;
3031
+
3032
+ const policy = definition.windowPolicy ?? "postpone";
3033
+ const options = {
3034
+ notBefore: definition.notBefore,
3035
+ notAfter: definition.notAfter,
3036
+ days: definition.activeDays,
3037
+ timeZone: definition.timezone,
3038
+ };
3039
+ const now = new Date();
3040
+ const state = activeWindowState(now, options);
3041
+
3042
+ if (state.active || policy === "run") {
3043
+ await runTaskEntry(taskName);
3044
+ console.log(
3045
+ `[windows-scheduler] Запуск задачи "${taskName}" (${reason}).`
2500
3046
  );
3047
+ return;
2501
3048
  }
3049
+
3050
+ if (policy === "skip") {
3051
+ console.log(
3052
+ `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
3053
+ state.reason ?? "вне окна"
3054
+ } — политика skip.`
3055
+ );
3056
+ return;
3057
+ }
3058
+
3059
+ const delay = nextWindowOpenDelayMs(now, options);
3060
+ if (delay <= 0 || delay > EVENT_POSTPONE_MAX_MS) {
3061
+ console.log(
3062
+ `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
3063
+ state.reason ?? "вне окна"
3064
+ } — до открытия окна больше 12 ч.`
3065
+ );
3066
+ return;
3067
+ }
3068
+
3069
+ console.log(
3070
+ `[windows-scheduler] Задача "${taskName}" (${reason}) отложена на ~${Math.round(
3071
+ delay / 60000
3072
+ )} мин: ${state.reason ?? "вне окна"}.`
3073
+ );
3074
+ const timer = setTimeout(() => {
3075
+ void scheduleEventRun(taskName, reason).catch((err: any) => {
3076
+ console.error(
3077
+ `[windows-scheduler] Не удалось запустить отложенную задачу "${taskName}": ${
3078
+ err instanceof Error ? err.message : String(err)
3079
+ }`
3080
+ );
3081
+ });
3082
+ }, delay);
3083
+ timer.unref?.();
2502
3084
  }
2503
3085
 
2504
3086
  export default Plugin.define({
@@ -2508,6 +3090,14 @@ export default Plugin.define({
2508
3090
  // `opencode run` подхватывает opencode.json с MCP-серверами проекта.
2509
3091
  projectDirectory = ctx.location?.directory || process.cwd();
2510
3092
 
3093
+ // Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
3094
+ // мешать старту — в этом случае остаётся локаль по умолчанию (ru).
3095
+ try {
3096
+ setLocale((await loadSettings()).locale);
3097
+ } catch {
3098
+ // Локаль по умолчанию уже активна.
3099
+ }
3100
+
2511
3101
  // Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
2512
3102
  // автоматически переносим данные из JSON, затем восстанавливаем прерванные
2513
3103
  // запуски. Ошибки миграции не должны мешать плагину стартовать.
@@ -2531,6 +3121,9 @@ export default Plugin.define({
2531
3121
  );
2532
3122
  }
2533
3123
  checkJsonBackups();
3124
+ void garbageCollectTaskArtifacts().catch((err) => {
3125
+ console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
3126
+ });
2534
3127
 
2535
3128
  // Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
2536
3129
  // плагину стартовать — пишем в лог и продолжаем.
@@ -2651,10 +3244,7 @@ export default Plugin.define({
2651
3244
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
2652
3245
  fileWatcherManager = new FileWatchManager(async (taskName) => {
2653
3246
  try {
2654
- await runTaskEntry(taskName);
2655
- console.log(
2656
- `[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`
2657
- );
3247
+ await scheduleEventRun(taskName, "изменение отслеживаемого файла");
2658
3248
  } catch (err: any) {
2659
3249
  console.error(
2660
3250
  `[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
@@ -2663,7 +3253,21 @@ export default Plugin.define({
2663
3253
  );
2664
3254
  }
2665
3255
  });
2666
- void refreshFileTriggers();
3256
+
3257
+ // Спринт 27: git-триггеры — опрос HEAD и запуск при новых коммитах,
3258
+ // затронувших подходящие файлы.
3259
+ gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
3260
+ try {
3261
+ await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
3262
+ } catch (err: any) {
3263
+ console.error(
3264
+ `[windows-scheduler] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
3265
+ err instanceof Error ? err.message : String(err)
3266
+ }`
3267
+ );
3268
+ }
3269
+ });
3270
+ void refreshTriggers();
2667
3271
 
2668
3272
  const registration = await ctx.tool.transform((editor) => {
2669
3273
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -3024,7 +3628,12 @@ export default Plugin.define({
3024
3628
  // schedule_task и create_task использовали один и тот же путь.
3025
3629
  const rpcHandlers = {
3026
3630
  get_tasks: async () => {
3027
- return { tasks: await collectTasksView() };
3631
+ const view = await collectTasksView();
3632
+ return {
3633
+ tasks: view.tasks,
3634
+ osAvailable: view.osAvailable,
3635
+ ...(view.osError ? { osError: view.osError } : {}),
3636
+ };
3028
3637
  },
3029
3638
  create_task: async (input: unknown) => {
3030
3639
  console.log("[windows-scheduler] create_task input:", input);
@@ -3057,6 +3666,7 @@ export default Plugin.define({
3057
3666
  delaySeconds,
3058
3667
  session,
3059
3668
  sessionMaxRuns,
3669
+ runWhenLoggedOff,
3060
3670
  } = input as {
3061
3671
  name: string;
3062
3672
  schedule?: string;
@@ -3067,7 +3677,7 @@ export default Plugin.define({
3067
3677
  nextTaskOnSuccess?: string;
3068
3678
  nextTaskOnError?: string;
3069
3679
  dependsOn?: string[];
3070
- triggerType?: "cron" | "file" | "mcp-event" | "once";
3680
+ triggerType?: "cron" | "file" | "git" | "mcp-event" | "once";
3071
3681
  watchPath?: string;
3072
3682
  workingDirectory?: string;
3073
3683
  model?: string;
@@ -3086,12 +3696,13 @@ export default Plugin.define({
3086
3696
  delaySeconds?: number;
3087
3697
  session?: "new" | "reuse" | "last";
3088
3698
  sessionMaxRuns?: number;
3699
+ runWhenLoggedOff?: boolean;
3089
3700
  };
3090
3701
  let effectiveRunAt: string | undefined;
3091
3702
  if (triggerType === "once") {
3092
3703
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
3093
3704
  if (!normalized.ok) {
3094
- return { success: false, message: `Задача "${name}": ${normalized.error}` };
3705
+ return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
3095
3706
  }
3096
3707
  effectiveRunAt = normalized.runAt;
3097
3708
  }
@@ -3099,7 +3710,7 @@ export default Plugin.define({
3099
3710
  if (session !== undefined) {
3100
3711
  const normalizedSession = normalizeSessionMode(session);
3101
3712
  if (!normalizedSession) {
3102
- return { success: false, message: `Задача "${name}": неизвестный режим сессии "${String(session)}".` };
3713
+ return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
3103
3714
  }
3104
3715
  effectiveSession = normalizedSession;
3105
3716
  }
@@ -3107,7 +3718,7 @@ export default Plugin.define({
3107
3718
  sessionMaxRuns !== undefined &&
3108
3719
  (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)
3109
3720
  ) {
3110
- return { success: false, message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.` };
3721
+ return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
3111
3722
  }
3112
3723
  const effectiveSessionId =
3113
3724
  effectiveSession === "reuse" ? generateSessionId() : undefined;
@@ -3144,9 +3755,24 @@ export default Plugin.define({
3144
3755
  effectiveRunAt,
3145
3756
  effectiveSession,
3146
3757
  effectiveSessionId,
3147
- sessionMaxRuns
3758
+ sessionMaxRuns,
3759
+ undefined,
3760
+ runWhenLoggedOff === true
3148
3761
  );
3149
- return { success: true, message: `Задача "${name}" успешно создана.` };
3762
+ const nextRun = computeTaskNextRun({
3763
+ schedule: schedule ?? "",
3764
+ triggerType: triggerType ?? "cron",
3765
+ runAt: effectiveRunAt,
3766
+ timezone,
3767
+ notBefore,
3768
+ notAfter,
3769
+ });
3770
+ return {
3771
+ success: true,
3772
+ paused: false,
3773
+ nextRun,
3774
+ message: t("tool.task.created", { name }),
3775
+ };
3150
3776
  } catch (err: any) {
3151
3777
  const message = err instanceof Error ? err.message : String(err);
3152
3778
  return { success: false, message };
@@ -3160,8 +3786,11 @@ export default Plugin.define({
3160
3786
  success: true,
3161
3787
  message:
3162
3788
  removed.length > 0
3163
- ? `Матрица "${name}" удалена вместе с ${removed.length} задачами (клоны и агрегатор).`
3164
- : `Задача "${name}" успешно удалена.`,
3789
+ ? t("tool.task.matrixDeletedCount", {
3790
+ name,
3791
+ count: removed.length,
3792
+ })
3793
+ : t("tool.task.deleted", { name }),
3165
3794
  };
3166
3795
  } catch (err: any) {
3167
3796
  return { success: false, message: err instanceof Error ? err.message : String(err) };
@@ -3191,8 +3820,8 @@ export default Plugin.define({
3191
3820
  success: true,
3192
3821
  message:
3193
3822
  removed.length > 0
3194
- ? `Удалено осиротевших задач: ${removed.length}.`
3195
- : "Осиротевших задач не найдено.",
3823
+ ? t("tool.matrix.orphansRemoved", { count: removed.length })
3824
+ : t("tool.matrix.orphansNone"),
3196
3825
  removed,
3197
3826
  };
3198
3827
  } catch (err: any) {
@@ -3214,9 +3843,21 @@ export default Plugin.define({
3214
3843
  const matrixResult = await runMatrix(definition);
3215
3844
  const total = definition.matrix.workspaceIds.length;
3216
3845
  const message =
3217
- `Матрица "${name}": запущено ${matrixResult.started.length} из ${total}` +
3218
- (matrixResult.skipped.length ? `, пропущено ${matrixResult.skipped.length}` : "") +
3219
- (matrixResult.errors.length ? `. Ошибки: ${matrixResult.errors.join("; ")}` : ".");
3846
+ t("tool.matrix.started", {
3847
+ name,
3848
+ started: matrixResult.started.length,
3849
+ total,
3850
+ }) +
3851
+ (matrixResult.skipped.length
3852
+ ? t("tool.matrix.startedSkipped", {
3853
+ count: matrixResult.skipped.length,
3854
+ })
3855
+ : "") +
3856
+ (matrixResult.errors.length
3857
+ ? t("tool.matrix.startedErrors", {
3858
+ errors: matrixResult.errors.join("; "),
3859
+ })
3860
+ : ".");
3220
3861
  return { success: matrixResult.success, message };
3221
3862
  }
3222
3863
  // Контроль параллелизма: не позволяем запускать новую задачу,
@@ -3231,7 +3872,7 @@ export default Plugin.define({
3231
3872
  return {
3232
3873
  success: false,
3233
3874
  message:
3234
- "Достигнут лимит одновременных задач. Дождитесь завершения текущих.",
3875
+ t("tool.matrix.limit"),
3235
3876
  };
3236
3877
  }
3237
3878
  }
@@ -3241,9 +3882,9 @@ export default Plugin.define({
3241
3882
  // в том числе инициированном из GUI, — дублировать запись здесь не нужно.
3242
3883
  if (result.alreadyRunning) {
3243
3884
  // Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
3244
- return { success: true, message: `Задача "${name}" уже выполняется.` };
3885
+ return { success: true, message: t("tool.task.alreadyRunning", { name }) };
3245
3886
  }
3246
- return { success: true, message: `Задача "${name}" запущена.` };
3887
+ return { success: true, message: t("tool.task.started", { name }) };
3247
3888
  } catch (err: any) {
3248
3889
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
3249
3890
  }
@@ -3255,7 +3896,7 @@ export default Plugin.define({
3255
3896
  };
3256
3897
  const normalized = eventName?.trim();
3257
3898
  if (!normalized) {
3258
- return { success: false, message: "Не передано имя события (eventName).", triggered: [] };
3899
+ return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
3259
3900
  }
3260
3901
 
3261
3902
  // Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
@@ -3292,18 +3933,18 @@ export default Plugin.define({
3292
3933
  return {
3293
3934
  success: true,
3294
3935
  triggered,
3295
- message: `Событие "${normalized}" обработано. Запущено задач: ${triggered.length}.`,
3936
+ message: t("tool.event.processed", { event: normalized, count: triggered.length }),
3296
3937
  };
3297
3938
  },
3298
3939
  pause_task: async (input: unknown) => {
3299
3940
  const { name, until } = input as { name: string; until?: string };
3300
3941
  const result = await pauseOrResumeTask(name, true, until);
3301
- return { success: result.success, message: result.message };
3942
+ return result;
3302
3943
  },
3303
3944
  resume_task: async (input: unknown) => {
3304
3945
  const { name } = input as { name: string };
3305
3946
  const result = await pauseOrResumeTask(name, false);
3306
- return { success: result.success, message: result.message };
3947
+ return result;
3307
3948
  },
3308
3949
  update_task: async (input: unknown) => {
3309
3950
  return await updateTaskFromInput(input as UpdateArgs);
@@ -3346,8 +3987,12 @@ export default Plugin.define({
3346
3987
  const report = await runHistoryRetention({ retentionDays, maxRecords });
3347
3988
  const message = report.skipped
3348
3989
  ? report.skipped
3349
- : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ` +
3350
- `${report.deletedByCount}), осталось ${report.kept}.`;
3990
+ : t("tool.history.cleaned", {
3991
+ deleted: report.deleted,
3992
+ byAge: report.deletedByAge,
3993
+ byCount: report.deletedByCount,
3994
+ kept: report.kept,
3995
+ });
3351
3996
  return {
3352
3997
  success: true,
3353
3998
  message,
@@ -3362,9 +4007,9 @@ export default Plugin.define({
3362
4007
  } catch (err: any) {
3363
4008
  return {
3364
4009
  success: false,
3365
- message: `Не удалось очистить историю: ${
3366
- err instanceof Error ? err.message : String(err)
3367
- }`,
4010
+ message: t("tool.history.cleanFailed", {
4011
+ error: err instanceof Error ? err.message : String(err),
4012
+ }),
3368
4013
  deleted: 0,
3369
4014
  deletedByAge: 0,
3370
4015
  deletedByCount: 0,
@@ -3448,7 +4093,7 @@ export default Plugin.define({
3448
4093
  const { parentId } = input as { parentId?: string; name?: string };
3449
4094
  const target = (parentId ?? "").trim();
3450
4095
  if (!target) {
3451
- return { success: false, error: "Не передан parentId матрицы." };
4096
+ return { success: false, error: t("tool.matrix.parentMissing") };
3452
4097
  }
3453
4098
  try {
3454
4099
  const report = aggregateMatrixResults(target);
@@ -3541,7 +4186,7 @@ export default Plugin.define({
3541
4186
  };
3542
4187
  const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
3543
4188
  if (!workspace) {
3544
- return { success: false, error: "Workspace не найден." };
4189
+ return { success: false, error: t("tool.workspace.notFound") };
3545
4190
  }
3546
4191
  // env-файлы существующих задач перегенерируются сразу (Спринт 21).
3547
4192
  await refreshWorkspaceEnvFiles(workspace.id);
@@ -3564,8 +4209,8 @@ export default Plugin.define({
3564
4209
  return {
3565
4210
  success: deleted,
3566
4211
  message: deleted
3567
- ? "Workspace удалён. Задачи сохранены, привязка очищена."
3568
- : "Workspace не найден.",
4212
+ ? t("tool.workspace.deleted")
4213
+ : t("tool.workspace.notFound"),
3569
4214
  };
3570
4215
  } catch (err: any) {
3571
4216
  return { success: false, message: err instanceof Error ? err.message : String(err) };
@@ -3588,8 +4233,8 @@ export default Plugin.define({
3588
4233
  current,
3589
4234
  restartRequired: true,
3590
4235
  message: isProfilePinnedByEnv()
3591
- ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
3592
- : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
4236
+ ? t("tool.profile.envVarLong", { name: current })
4237
+ : t("tool.profile.active", { name: sanitizeProfileName(name) }),
3593
4238
  };
3594
4239
  } catch (err: any) {
3595
4240
  return {
@@ -3607,7 +4252,7 @@ export default Plugin.define({
3607
4252
  const profile = listProfiles().find((item) => item.name === meta.name);
3608
4253
  return {
3609
4254
  success: true,
3610
- message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
4255
+ message: t("tool.profile.created", { name: meta.name, port: meta.port }),
3611
4256
  profile: profile ?? {
3612
4257
  name: meta.name,
3613
4258
  dir: getProfileDir(meta.name),
@@ -3630,8 +4275,8 @@ export default Plugin.define({
3630
4275
  return {
3631
4276
  success: removed,
3632
4277
  message: removed
3633
- ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
3634
- : "Профиль не найден.",
4278
+ ? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
4279
+ : t("tool.profile.notFound"),
3635
4280
  };
3636
4281
  } catch (err: any) {
3637
4282
  return { success: false, message: err instanceof Error ? err.message : String(err) };
@@ -3641,8 +4286,9 @@ export default Plugin.define({
3641
4286
  return await loadSettings();
3642
4287
  },
3643
4288
  save_settings: async (input: unknown) => {
3644
- const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input as {
4289
+ const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input as {
3645
4290
  maxConcurrent?: number;
4291
+ locale?: Locale;
3646
4292
  winterMode?: boolean;
3647
4293
  notifications?: NotificationSettings;
3648
4294
  history?: HistorySettings;
@@ -3652,6 +4298,7 @@ export default Plugin.define({
3652
4298
  const current = await loadSettings();
3653
4299
  if (
3654
4300
  maxConcurrent === undefined &&
4301
+ locale === undefined &&
3655
4302
  winterMode === undefined &&
3656
4303
  notifications === undefined &&
3657
4304
  history === undefined &&
@@ -3661,6 +4308,7 @@ export default Plugin.define({
3661
4308
  return {
3662
4309
  success: false,
3663
4310
  maxConcurrent: current.maxConcurrent,
4311
+ locale: current.locale,
3664
4312
  winterMode: current.winterMode,
3665
4313
  notifications: current.notifications,
3666
4314
  history: current.history,
@@ -3670,15 +4318,19 @@ export default Plugin.define({
3670
4318
  }
3671
4319
  const settings = await saveSettings({
3672
4320
  maxConcurrent,
4321
+ locale,
3673
4322
  winterMode,
3674
4323
  notifications,
3675
4324
  history,
3676
4325
  integrations,
3677
4326
  audit,
3678
4327
  });
4328
+ // Локаль процесса меняется сразу — перезапуск не нужен.
4329
+ setLocale(settings.locale);
3679
4330
  return {
3680
4331
  success: true,
3681
4332
  maxConcurrent: settings.maxConcurrent,
4333
+ locale: settings.locale,
3682
4334
  winterMode: settings.winterMode,
3683
4335
  notifications: settings.notifications,
3684
4336
  history: settings.history,
@@ -3703,15 +4355,15 @@ export default Plugin.define({
3703
4355
  const source = (input ?? {}) as { name?: string; value?: string };
3704
4356
  const name = (source.name ?? "").trim();
3705
4357
  if (!name) {
3706
- return { success: false, message: "Нужно имя секрета." };
4358
+ return { success: false, message: t("tool.secret.needName") };
3707
4359
  }
3708
4360
  if (typeof source.value !== "string" || source.value.length === 0) {
3709
- return { success: false, message: "Нужно непустое значение секрета." };
4361
+ return { success: false, message: t("tool.secret.needValue") };
3710
4362
  }
3711
4363
  const secret = setSecret(name, source.value);
3712
4364
  return {
3713
4365
  success: true,
3714
- message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
4366
+ message: t("tool.secret.saved", { name: secret.name }),
3715
4367
  secret,
3716
4368
  };
3717
4369
  } catch (err: any) {
@@ -3725,15 +4377,15 @@ export default Plugin.define({
3725
4377
  try {
3726
4378
  const name = (((input ?? {}) as { name?: string }).name ?? "").trim();
3727
4379
  if (!name) {
3728
- return { success: false, message: "Нужно имя секрета." };
4380
+ return { success: false, message: t("tool.secret.needName") };
3729
4381
  }
3730
4382
  const existed = hasSecret(name);
3731
4383
  deleteSecret(name);
3732
4384
  return {
3733
4385
  success: existed,
3734
4386
  message: existed
3735
- ? `Секрет ${name} удалён.`
3736
- : `Секрет ${name} не найден.`,
4387
+ ? t("tool.secret.deleted", { name })
4388
+ : t("tool.secret.notFound", { name }),
3737
4389
  };
3738
4390
  } catch (err: any) {
3739
4391
  return {
@@ -3778,7 +4430,7 @@ export default Plugin.define({
3778
4430
  if (!source?.name?.trim() || !source?.prompt?.trim()) {
3779
4431
  return {
3780
4432
  success: false,
3781
- error: "Нужны непустые название шаблона и промпт.",
4433
+ error: t("tool.template.namePromptRequired"),
3782
4434
  };
3783
4435
  }
3784
4436
  const template = await saveTemplate({
@@ -3805,7 +4457,7 @@ export default Plugin.define({
3805
4457
  delete_template: async (input: unknown) => {
3806
4458
  const { id } = input as { id?: string };
3807
4459
  if (!id) {
3808
- return { success: false, error: "Не передан id шаблона." };
4460
+ return { success: false, error: t("tool.template.needId") };
3809
4461
  }
3810
4462
  try {
3811
4463
  await deleteTemplate(id);
@@ -3833,14 +4485,14 @@ export default Plugin.define({
3833
4485
  import_tasks: async (input: unknown) => {
3834
4486
  const { data } = input as { data?: string };
3835
4487
  if (!data) {
3836
- return { success: false, error: "Не переданы данные для импорта." };
4488
+ return { success: false, error: t("tool.transfer.noData") };
3837
4489
  }
3838
4490
  try {
3839
4491
  const parsed = parseImportJson(data);
3840
4492
  if (parsed.tasks.length === 0) {
3841
4493
  return {
3842
4494
  success: false,
3843
- error: "В файле нет задач для импорта.",
4495
+ error: t("tool.transfer.noTasksInFile"),
3844
4496
  errors: parsed.errors,
3845
4497
  };
3846
4498
  }
@@ -3879,7 +4531,22 @@ export default Plugin.define({
3879
4531
  def.notBefore,
3880
4532
  def.notAfter,
3881
4533
  def.pausedUntil,
3882
- def.runAt
4534
+ def.runAt,
4535
+ def.session ?? "new",
4536
+ def.sessionId,
4537
+ def.sessionMaxRuns,
4538
+ {
4539
+ activeDays: def.activeDays,
4540
+ windowPolicy: def.windowPolicy,
4541
+ watchGlobs: def.watchGlobs,
4542
+ watchIgnore: def.watchIgnore,
4543
+ gitBranch: def.gitBranch,
4544
+ gitPaths: def.gitPaths,
4545
+ gitIgnore: def.gitIgnore,
4546
+ gitPollSeconds: def.gitPollSeconds,
4547
+ },
4548
+ def.runWhenLoggedOff === true,
4549
+ def.paused === true
3883
4550
  );
3884
4551
  await saveTaskDefinition(def);
3885
4552
  imported.push(def.name);
@@ -3918,7 +4585,7 @@ export default Plugin.define({
3918
4585
  // Повторный вызов не создаёт второй сервер — защита от двойного запуска
3919
4586
  // реализована внутри startDashboardServer.
3920
4587
  const dashboard = await startDashboardServer({
3921
- getTasks: collectTasksView,
4588
+ getTasks: async () => (await collectTasksView()).tasks,
3922
4589
  runTask: (name) => runTaskEntry(name),
3923
4590
  deleteTask: async (name) => {
3924
4591
  await deleteTaskWithFamily(name);
@@ -3967,7 +4634,7 @@ function resolveMatrixExtraConfig(
3967
4634
  matrix.concurrency < 1
3968
4635
  ) {
3969
4636
  throw new Error(
3970
- `Задача "${name}": matrix.concurrency должен быть числом не меньше 1.`
4637
+ t("tool.error.matrixConcurrency", { task: name })
3971
4638
  );
3972
4639
  }
3973
4640
  extra.concurrency = Math.floor(matrix.concurrency);
@@ -3980,8 +4647,10 @@ function resolveMatrixExtraConfig(
3980
4647
  const workspaceKey = key.trim();
3981
4648
  if (!allowed.has(workspaceKey)) {
3982
4649
  throw new Error(
3983
- `Задача "${name}": matrix.overrides содержит workspace "${workspaceKey}", ` +
3984
- `которого нет в workspaceIds.`
4650
+ t("tool.error.matrixOverride", {
4651
+ task: name,
4652
+ workspace: workspaceKey,
4653
+ })
3985
4654
  );
3986
4655
  }
3987
4656
  if (!value || typeof value !== "object") continue;
@@ -4008,6 +4677,21 @@ function resolveMatrixExtraConfig(
4008
4677
  * Общая логика создания задачи: используется и schedule_task (инструмент),
4009
4678
  * и create_task (RPC-метод для GUI).
4010
4679
  */
4680
+ /**
4681
+ * Спринт 27: дополнительные параметры триггеров (дни недели, политика окна,
4682
+ * glob-фильтры файловых триггеров и git-триггеры).
4683
+ */
4684
+ export interface TriggerExtras {
4685
+ activeDays?: number[];
4686
+ windowPolicy?: "skip" | "postpone" | "run";
4687
+ watchGlobs?: string[];
4688
+ watchIgnore?: string[];
4689
+ gitBranch?: string;
4690
+ gitPaths?: string[];
4691
+ gitIgnore?: string[];
4692
+ gitPollSeconds?: number;
4693
+ }
4694
+
4011
4695
  async function schedulerCreateTask(
4012
4696
  name: string,
4013
4697
  schedule: string,
@@ -4019,7 +4703,7 @@ async function schedulerCreateTask(
4019
4703
  qualityGate?: string,
4020
4704
  nextTaskOnSuccess?: string,
4021
4705
  nextTaskOnError?: string,
4022
- triggerType?: "cron" | "file" | "mcp-event" | "once",
4706
+ triggerType?: "cron" | "file" | "git" | "mcp-event" | "once",
4023
4707
  watchPath?: string,
4024
4708
  dependsOn?: string[],
4025
4709
  model?: string,
@@ -4049,8 +4733,30 @@ async function schedulerCreateTask(
4049
4733
  /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
4050
4734
  sessionId?: string,
4051
4735
  /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
4052
- sessionMaxRuns?: number
4736
+ sessionMaxRuns?: number,
4737
+ /** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
4738
+ triggerExtras?: TriggerExtras,
4739
+ /** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
4740
+ runWhenLoggedOff?: boolean,
4741
+ /**
4742
+ * Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
4743
+ * update). Для матрицы пауза применяется к клонам.
4744
+ */
4745
+ paused?: boolean
4053
4746
  ): Promise<void> {
4747
+ // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
4748
+ // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
4749
+ // schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
4750
+ const normalizedName = name.trim();
4751
+ const nameError = validateTaskName(normalizedName);
4752
+ if (nameError) {
4753
+ throw new Error(nameError);
4754
+ }
4755
+ name = normalizedName;
4756
+ // Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
4757
+ // удалять их при сбое нельзя — в БД остаётся прежнее определение.
4758
+ const definitionExisted = Boolean(getTask(normalizedName));
4759
+
4054
4760
  const normalizedModel = model?.trim() || undefined;
4055
4761
  const normalizedPriority = normalizePriority(priority);
4056
4762
  const normalizedBefore = beforeScript?.trim() || undefined;
@@ -4059,6 +4765,39 @@ async function schedulerCreateTask(
4059
4765
  const normalizedNotBefore = notBefore?.trim() || undefined;
4060
4766
  const normalizedNotAfter = notAfter?.trim() || undefined;
4061
4767
  const normalizedPausedUntil = pausedUntil?.trim() || undefined;
4768
+ // Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
4769
+ const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
4770
+ // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
4771
+ const normalizedPaused = paused === true ? true : undefined;
4772
+ // Спринт 27: дни недели, политика окна и glob/git-фильтры.
4773
+ const normalizeGlobList = (raw?: string[]): string[] | undefined => {
4774
+ if (!Array.isArray(raw)) return undefined;
4775
+ const cleaned = Array.from(
4776
+ new Set(
4777
+ raw
4778
+ .filter((item): item is string => typeof item === "string")
4779
+ .map((item) => item.trim())
4780
+ .filter(Boolean)
4781
+ )
4782
+ );
4783
+ return cleaned.length > 0 ? cleaned : undefined;
4784
+ };
4785
+ const normalizedActiveDays = normalizeActiveDays(triggerExtras?.activeDays);
4786
+ const normalizedWindowPolicy =
4787
+ triggerExtras?.windowPolicy === "skip" || triggerExtras?.windowPolicy === "run"
4788
+ ? triggerExtras.windowPolicy
4789
+ : undefined;
4790
+ const normalizedWatchGlobs = normalizeGlobList(triggerExtras?.watchGlobs);
4791
+ const normalizedWatchIgnore = normalizeGlobList(triggerExtras?.watchIgnore);
4792
+ const normalizedGitBranch = triggerExtras?.gitBranch?.trim() || undefined;
4793
+ const normalizedGitPaths = normalizeGlobList(triggerExtras?.gitPaths);
4794
+ const normalizedGitIgnore = normalizeGlobList(triggerExtras?.gitIgnore);
4795
+ const normalizedGitPollSeconds =
4796
+ typeof triggerExtras?.gitPollSeconds === "number" &&
4797
+ Number.isFinite(triggerExtras.gitPollSeconds) &&
4798
+ triggerExtras.gitPollSeconds >= 5
4799
+ ? Math.floor(triggerExtras.gitPollSeconds)
4800
+ : undefined;
4062
4801
  const normalizedMcpEvent =
4063
4802
  mcpEvent && mcpEvent.event?.trim()
4064
4803
  ? {
@@ -4074,7 +4813,7 @@ async function schedulerCreateTask(
4074
4813
  if (effectiveTriggerType === "once") {
4075
4814
  const normalized = normalizeOneShotRunAt({ runAt });
4076
4815
  if (!normalized.ok) {
4077
- throw new Error(`Задача "${name}": ${normalized.error}`);
4816
+ throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
4078
4817
  }
4079
4818
  effectiveRunAt = normalized.runAt;
4080
4819
  }
@@ -4085,7 +4824,12 @@ async function schedulerCreateTask(
4085
4824
  if (session !== undefined) {
4086
4825
  const normalizedSession = normalizeSessionMode(session);
4087
4826
  if (!normalizedSession) {
4088
- throw new Error(`Задача "${name}": неизвестный режим сессии "${String(session)}".`);
4827
+ throw new Error(
4828
+ t("tool.error.sessionUnknown", {
4829
+ name,
4830
+ session: String(session),
4831
+ })
4832
+ );
4089
4833
  }
4090
4834
  effectiveSession = normalizedSession;
4091
4835
  }
@@ -4110,7 +4854,7 @@ async function schedulerCreateTask(
4110
4854
  };
4111
4855
  if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
4112
4856
  throw new Error(
4113
- `Задача "${name}": пустой allowedTools запрещён — задайте список инструментов или уберите поле.`
4857
+ t("tool.error.allowedToolsEmpty", { task: name })
4114
4858
  );
4115
4859
  }
4116
4860
  const normalizedAllowedTools = normalizeToolList(allowedTools);
@@ -4122,7 +4866,7 @@ async function schedulerCreateTask(
4122
4866
  if (matrix) {
4123
4867
  if (workspaceId?.trim()) {
4124
4868
  throw new Error(
4125
- `Задача "${name}": нельзя одновременно workspaceId и matrix.workspaceIds.`
4869
+ t("tool.error.workspaceIdConflict", { task: name })
4126
4870
  );
4127
4871
  }
4128
4872
  const ids = Array.from(
@@ -4134,18 +4878,26 @@ async function schedulerCreateTask(
4134
4878
  )
4135
4879
  );
4136
4880
  if (ids.length === 0) {
4137
- throw new Error(`Задача "${name}": matrix.workspaceIds не может быть пустым.`);
4881
+ throw new Error(
4882
+ t("tool.error.workspaceIdsEmpty", { task: name })
4883
+ );
4138
4884
  }
4139
4885
  for (const id of ids) {
4140
4886
  const ws = getWorkspace(id);
4141
4887
  if (!ws) {
4142
- throw new Error(`Задача "${name}": workspace "${id}" не найден.`);
4888
+ throw new Error(
4889
+ t("tool.error.workspaceMissing", { task: name, id })
4890
+ );
4143
4891
  }
4144
4892
  try {
4145
4893
  validateWorkspacePath(ws.path);
4146
4894
  } catch {
4147
4895
  throw new Error(
4148
- `Задача "${name}": workspace "${ws.name}" недоступен по пути "${ws.path}".`
4896
+ t("tool.error.workspaceUnavailable", {
4897
+ task: name,
4898
+ workspace: ws.name,
4899
+ path: ws.path,
4900
+ })
4149
4901
  );
4150
4902
  }
4151
4903
  }
@@ -4167,7 +4919,23 @@ async function schedulerCreateTask(
4167
4919
 
4168
4920
  // MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
4169
4921
  if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
4170
- throw new Error("Для MCP-триггера нужно указать имя события (mcpEvent.event).");
4922
+ throw new Error(t("tool.error.mcpEventRequired"));
4923
+ }
4924
+ // Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
4925
+ if (effectiveTriggerType === "git") {
4926
+ const gitCwd = workspaceId?.trim()
4927
+ ? getWorkspace(workspaceId.trim())?.path
4928
+ : workingDirectory?.trim() || projectDirectory || process.cwd();
4929
+ if (!gitCwd) {
4930
+ throw new Error(
4931
+ t("tool.error.gitCwdRequired", { task: name })
4932
+ );
4933
+ }
4934
+ if (!readGitBranch(gitCwd)) {
4935
+ throw new Error(
4936
+ t("tool.error.gitNoRepo", { task: name, path: gitCwd })
4937
+ );
4938
+ }
4171
4939
  }
4172
4940
  // Валидируем cron-выражение до создания файлов. Для file/mcp-event
4173
4941
  // расписание не используется вовсе.
@@ -4181,8 +4949,10 @@ async function schedulerCreateTask(
4181
4949
  }
4182
4950
  if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
4183
4951
  throw new Error(
4184
- `Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
4185
- `Укажите IANA-зону, например Europe/Moscow.`
4952
+ t("tool.error.timezone", {
4953
+ task: name,
4954
+ timezone: normalizedTz,
4955
+ })
4186
4956
  );
4187
4957
  }
4188
4958
  const windowError = validateLaunchWindow(
@@ -4190,7 +4960,15 @@ async function schedulerCreateTask(
4190
4960
  normalizedNotAfter
4191
4961
  );
4192
4962
  if (windowError) {
4193
- throw new Error(`Задача "${name}": ${windowError}`);
4963
+ throw new Error(t("tool.error.window", { task: name, error: windowError }));
4964
+ }
4965
+ }
4966
+ // Спринт 27: окно и дни недели применимы и к событийным триггерам
4967
+ // (file/git/mcp-event/once) — проверяем корректность до создания задачи.
4968
+ if (effectiveTriggerType !== "cron") {
4969
+ const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
4970
+ if (windowError) {
4971
+ throw new Error(t("tool.error.window", { task: name, error: windowError }));
4194
4972
  }
4195
4973
  }
4196
4974
 
@@ -4205,7 +4983,9 @@ async function schedulerCreateTask(
4205
4983
  schedule,
4206
4984
  normalizedTz,
4207
4985
  normalizedNotBefore,
4208
- normalizedNotAfter
4986
+ normalizedNotAfter,
4987
+ normalizedActiveDays,
4988
+ normalizedWindowPolicy
4209
4989
  )
4210
4990
  : undefined;
4211
4991
  const wrapperGate = gate
@@ -4221,13 +5001,22 @@ async function schedulerCreateTask(
4221
5001
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
4222
5002
  const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
4223
5003
  if (normalizedWorkspaceId && !workspace) {
4224
- throw new Error(`Workspace '${normalizedWorkspaceId}' не найден.`);
5004
+ throw new Error(
5005
+ t("tool.error.workspaceIdMissing", {
5006
+ id: normalizedWorkspaceId,
5007
+ })
5008
+ );
4225
5009
  }
4226
5010
  if (workspace) {
4227
5011
  try {
4228
5012
  validateWorkspacePath(workspace.path);
4229
5013
  } catch {
4230
- throw new Error(`Workspace '${workspace.name}' недоступен по пути '${workspace.path}'`);
5014
+ throw new Error(
5015
+ t("tool.error.workspacePathMissing", {
5016
+ name: workspace.name,
5017
+ path: workspace.path,
5018
+ })
5019
+ );
4231
5020
  }
4232
5021
  if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
4233
5022
  console.warn(
@@ -4252,7 +5041,11 @@ async function schedulerCreateTask(
4252
5041
  await fs.mkdir(LOG_DIR, { recursive: true });
4253
5042
  await fs.writeFile(logFile, "", "utf8");
4254
5043
  } catch (err: any) {
4255
- throw new Error(`Не удалось подготовить файлы задачи: ${err.message || String(err)}`);
5044
+ throw new Error(
5045
+ t("tool.error.prepareFiles", {
5046
+ error: err.message || String(err),
5047
+ })
5048
+ );
4256
5049
  }
4257
5050
 
4258
5051
  // Обёртка зависит от платформы:
@@ -4310,9 +5103,24 @@ async function schedulerCreateTask(
4310
5103
  });
4311
5104
  }
4312
5105
  } catch (err: any) {
4313
- throw new Error(`Не удалось создать обёртку задачи: ${err.message || String(err)}`);
5106
+ throw new Error(
5107
+ t("tool.error.wrapper", {
5108
+ error: err.message || String(err),
5109
+ })
5110
+ );
4314
5111
  }
4315
5112
 
5113
+ // 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
5114
+ // При обновлении файлы переиспользуются существующей задачей — не удаляем.
5115
+ const rollbackArtifacts = async (): Promise<void> => {
5116
+ if (definitionExisted) return;
5117
+ await Promise.all(
5118
+ [wrapperPath, promptFile, logFile, taskEnvFile].map((file) =>
5119
+ file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()
5120
+ )
5121
+ );
5122
+ };
5123
+
4316
5124
  try {
4317
5125
  // Бэкенд сам преобразует cron в родное расписание ОС.
4318
5126
  await scheduler.createTask({
@@ -4329,11 +5137,55 @@ async function schedulerCreateTask(
4329
5137
  timezone: normalizedTz,
4330
5138
  notBefore: normalizedNotBefore,
4331
5139
  notAfter: normalizedNotAfter,
5140
+ runWhenLoggedOff: normalizedRunWhenLoggedOff,
4332
5141
  });
4333
5142
  } catch (err: any) {
5143
+ await rollbackArtifacts();
4334
5144
  throw new Error(err instanceof Error ? err.message : String(err));
4335
5145
  }
4336
5146
 
5147
+ // Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
5148
+ // 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
5149
+ const isListed = (tasks: Awaited<ReturnType<typeof scheduler.listTasks>>): boolean =>
5150
+ tasks.some(
5151
+ (task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase()
5152
+ );
5153
+ let listedTasks: Awaited<ReturnType<typeof scheduler.listTasks>> | undefined;
5154
+ let verifyQueryError: unknown;
5155
+ for (let attempt = 0; attempt < 3; attempt += 1) {
5156
+ try {
5157
+ listedTasks = await scheduler.listTasks();
5158
+ if (isListed(listedTasks)) break;
5159
+ } catch (err) {
5160
+ verifyQueryError = err;
5161
+ }
5162
+ if (attempt < 2) {
5163
+ await new Promise((resolve) => setTimeout(resolve, 200));
5164
+ }
5165
+ }
5166
+ if (listedTasks && !isListed(listedTasks)) {
5167
+ await rollbackArtifacts();
5168
+ throw new Error(
5169
+ t("tool.error.schedulerNotConfirmed", {
5170
+ task: name,
5171
+ scheduler: scheduler.title,
5172
+ }) +
5173
+ " " +
5174
+ (definitionExisted
5175
+ ? t("tool.error.schedulerKeptFiles")
5176
+ : t("tool.error.schedulerRemovedFiles"))
5177
+ );
5178
+ }
5179
+ if (!listedTasks && verifyQueryError) {
5180
+ // Список получить не удалось — не удаляем возможно созданную задачу,
5181
+ // но явно предупреждаем: проверка наличия не выполнена.
5182
+ console.warn(
5183
+ `[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${
5184
+ verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)
5185
+ }`
5186
+ );
5187
+ }
5188
+
4337
5189
  // Сохраняем определение задачи для последующего экспорта/импорта.
4338
5190
  // Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
4339
5191
  const previousDefinition = getTask(name);
@@ -4374,6 +5226,19 @@ async function schedulerCreateTask(
4374
5226
  timezone: normalizedTz,
4375
5227
  notBefore: normalizedNotBefore,
4376
5228
  notAfter: normalizedNotAfter,
5229
+ // Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
5230
+ runWhenLoggedOff: normalizedRunWhenLoggedOff,
5231
+ // Спринт 27.5.8: бессрочная пауза переживает пересоздание.
5232
+ paused: normalizedPaused,
5233
+ // Спринт 27: дни недели, политика окна, glob- и git-фильтры.
5234
+ activeDays: normalizedActiveDays,
5235
+ windowPolicy: normalizedWindowPolicy,
5236
+ watchGlobs: normalizedWatchGlobs,
5237
+ watchIgnore: normalizedWatchIgnore,
5238
+ gitBranch: normalizedGitBranch,
5239
+ gitPaths: normalizedGitPaths,
5240
+ gitIgnore: normalizedGitIgnore,
5241
+ gitPollSeconds: normalizedGitPollSeconds,
4377
5242
  pausedUntil: normalizedPausedUntil,
4378
5243
  allowedTools: normalizedAllowedTools,
4379
5244
  deniedTools: normalizedDeniedTools,
@@ -4436,7 +5301,14 @@ async function schedulerCreateTask(
4436
5301
  clone.timezone,
4437
5302
  clone.notBefore,
4438
5303
  clone.notAfter,
4439
- clone.pausedUntil
5304
+ clone.pausedUntil,
5305
+ clone.runAt,
5306
+ clone.session,
5307
+ clone.sessionId,
5308
+ clone.sessionMaxRuns,
5309
+ undefined,
5310
+ clone.runWhenLoggedOff,
5311
+ clone.paused
4440
5312
  );
4441
5313
  };
4442
5314
 
@@ -4451,6 +5323,8 @@ async function schedulerCreateTask(
4451
5323
  } catch {
4452
5324
  // Не критично.
4453
5325
  }
5326
+ // Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
5327
+ await removeTaskArtifacts(child);
4454
5328
  };
4455
5329
 
4456
5330
  // Создаёт/обновляет/удаляет matrix-complete по текущему определению.
@@ -4465,8 +5339,10 @@ async function schedulerCreateTask(
4465
5339
  await schedulerCreateTask(
4466
5340
  aggregatorName,
4467
5341
  schedule,
4468
- `Матрица "${name}" завершена. Проверь результаты клонов: ` +
4469
- `${cloneNames.join(", ")}.`,
5342
+ t("tool.matrix.completed", {
5343
+ name,
5344
+ clones: cloneNames.join(", "),
5345
+ }),
4470
5346
  timeoutSeconds,
4471
5347
  undefined,
4472
5348
  undefined,
@@ -4508,15 +5384,146 @@ async function schedulerCreateTask(
4508
5384
  for (const child of removeMatrixChildren(name)) {
4509
5385
  await removeChild(child);
4510
5386
  }
4511
- const clones = expandMatrixTask(taskDefinition);
4512
- for (const clone of clones) {
4513
- await createClone(clone);
5387
+ // Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
5388
+ // остаётся родитель с половиной клонов — он выглядит рабочим, но часть
5389
+ // workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
5390
+ // workspace) обрабатываем там же: родитель уже записан в БД.
5391
+ const createdInRun: string[] = [];
5392
+ try {
5393
+ const clones = expandMatrixTask(taskDefinition);
5394
+ for (const clone of clones) {
5395
+ try {
5396
+ await createClone(clone);
5397
+ createdInRun.push(clone.name);
5398
+ } catch (err: any) {
5399
+ const workspaceLabel = clone.workspaceId
5400
+ ? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
5401
+ : "без workspace";
5402
+ throw new Error(
5403
+ t("tool.error.matrixCloneFailed", {
5404
+ clone: clone.name,
5405
+ workspace: workspaceLabel,
5406
+ error: err instanceof Error ? err.message : String(err),
5407
+ })
5408
+ );
5409
+ }
5410
+ }
5411
+ await syncAggregator();
5412
+ } catch (err: any) {
5413
+ for (const child of [...createdInRun].reverse()) {
5414
+ await removeChild(child);
5415
+ }
5416
+ const aggregatorName = matrixCompleteName(name);
5417
+ if (getTask(aggregatorName)) {
5418
+ await removeChild(aggregatorName);
5419
+ }
5420
+ // Новая матрица: без клонов родитель бесполезен — убираем и его,
5421
+ // вместе с подготовленными файлами обёртки.
5422
+ if (!definitionExisted) {
5423
+ try {
5424
+ await scheduler.deleteTask(name);
5425
+ } catch {
5426
+ // Задачи могло не быть: бэкенд уже вернул ошибку.
5427
+ }
5428
+ try {
5429
+ await removeTaskDefinition(name);
5430
+ } catch {
5431
+ // Не критично: запись могла не сохраниться.
5432
+ }
5433
+ await rollbackArtifacts();
5434
+ }
5435
+ throw new Error(
5436
+ t("tool.error.matrixExpandRuntime", {
5437
+ name,
5438
+ error: err instanceof Error ? err.message : String(err),
5439
+ })
5440
+ );
5441
+ }
5442
+ }
5443
+ }
5444
+
5445
+ // Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
5446
+ // пауза применяется к клонам — родитель сам никогда не выполняется.
5447
+ if (normalizedPaused) {
5448
+ const pauseTargets = normalizedMatrix
5449
+ ? listMatrixClones(name).map((clone) => clone.name)
5450
+ : [name];
5451
+ for (const target of pauseTargets) {
5452
+ try {
5453
+ await scheduler.pauseTask(target);
5454
+ } catch (err: any) {
5455
+ console.warn(
5456
+ `[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${
5457
+ err instanceof Error ? err.message : String(err)
5458
+ }`
5459
+ );
4514
5460
  }
4515
- await syncAggregator();
4516
5461
  }
4517
5462
  }
4518
5463
  }
4519
5464
 
5465
+ /**
5466
+ * Спринт 27.5.6: восстановление задачи из определения в БД.
5467
+ *
5468
+ * update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
5469
+ * сбое create после успешного delete старая версия терялась навсегда: в ОС её
5470
+ * уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
5471
+ * создаём задачу из прежнего определения — обёртка, промпт, расписание и
5472
+ * пауза восстанавливаются тем же путём, что и при обычном create.
5473
+ */
5474
+ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<void> {
5475
+ const paused = Boolean(
5476
+ definition.paused === true ||
5477
+ (definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now())
5478
+ );
5479
+ await schedulerCreateTask(
5480
+ definition.name,
5481
+ definition.schedule ?? "",
5482
+ definition.prompt,
5483
+ definition.timeoutSeconds,
5484
+ definition.workingDirectory,
5485
+ definition.retryCount,
5486
+ definition.retryDelay,
5487
+ definition.qualityGate,
5488
+ definition.nextTaskOnSuccess,
5489
+ definition.nextTaskOnError,
5490
+ definition.triggerType ?? "cron",
5491
+ definition.watchPath,
5492
+ Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined,
5493
+ definition.model,
5494
+ definition.priority,
5495
+ definition.beforeScript,
5496
+ definition.afterScript,
5497
+ definition.mcpEvent,
5498
+ definition.workspaceId,
5499
+ definition.allowedTools,
5500
+ definition.deniedTools,
5501
+ definition.matrix,
5502
+ definition.matrixParentId,
5503
+ "create",
5504
+ definition.timezone,
5505
+ definition.notBefore,
5506
+ definition.notAfter,
5507
+ definition.pausedUntil,
5508
+ definition.runAt,
5509
+ definition.session ?? "new",
5510
+ definition.sessionId,
5511
+ definition.sessionMaxRuns,
5512
+ {
5513
+ activeDays: definition.activeDays,
5514
+ windowPolicy: definition.windowPolicy,
5515
+ watchGlobs: definition.watchGlobs,
5516
+ watchIgnore: definition.watchIgnore,
5517
+ gitBranch: definition.gitBranch,
5518
+ gitPaths: definition.gitPaths,
5519
+ gitIgnore: definition.gitIgnore,
5520
+ gitPollSeconds: definition.gitPollSeconds,
5521
+ },
5522
+ definition.runWhenLoggedOff,
5523
+ paused
5524
+ );
5525
+ }
5526
+
4520
5527
  /**
4521
5528
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
4522
5529
  * на клоны, а не выполняет свой промпт.
@@ -4547,20 +5554,60 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
4547
5554
  }
4548
5555
  }
4549
5556
 
5557
+ /**
5558
+ * Спринт 27.5.3: чтение задач ОС с одним повтором.
5559
+ *
5560
+ * Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
5561
+ * отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
5562
+ * retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
5563
+ * возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
5564
+ */
5565
+ async function readOsTasksWithRetry(
5566
+ expectNonEmpty: boolean,
5567
+ delayMs = 300
5568
+ ): Promise<{
5569
+ tasks: Awaited<ReturnType<typeof scheduler.listTasks>>;
5570
+ osAvailable: boolean;
5571
+ osError?: string;
5572
+ }> {
5573
+ let lastError: string | undefined;
5574
+ for (let attempt = 0; attempt < 2; attempt += 1) {
5575
+ if (attempt > 0) {
5576
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
5577
+ }
5578
+ try {
5579
+ const tasks = await scheduler.listTasks();
5580
+ if (tasks.length > 0 || !expectNonEmpty) {
5581
+ return { tasks, osAvailable: true };
5582
+ }
5583
+ lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
5584
+ } catch (err) {
5585
+ lastError = err instanceof Error ? err.message : String(err);
5586
+ }
5587
+ }
5588
+ return { tasks: [], osAvailable: false, osError: lastError };
5589
+ }
5590
+
4550
5591
  /**
4551
5592
  * Собирает задачи плагина в формате, который отдают оба потребителя:
4552
5593
  * RPC get_tasks (GUI) и инструмент list_tasks (агент).
5594
+ *
5595
+ * Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
5596
+ * `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
5597
+ * массив: иначе GUI и агент решали бы, что задач нет.
4553
5598
  */
4554
5599
  async function collectTasksView() {
4555
- const tasks = await scheduler.listTasks();
5600
+ const defs = await loadTaskDefinitions();
5601
+ const osRead = await readOsTasksWithRetry(defs.length > 0);
5602
+ const tasks = osRead.tasks;
4556
5603
 
4557
5604
  // Читаем историю один раз, чтобы определить финальный статус по последней записи.
4558
5605
  const history = await loadHistory();
4559
5606
  // loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
4560
5607
  const lastByTask = latestHistoryByTask(history);
4561
5608
 
4562
- // Читаем определения задач один раз (расписание, повторы, цепочки, директория).
4563
- const defs = await loadTaskDefinitions();
5609
+ // Определения задач читаются один раз заранее (см. выше) — расписание,
5610
+ // повторы, цепочки, директория.
4564
5611
  const workspaces = listWorkspaces();
4565
5612
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
4566
5613
 
@@ -4605,7 +5652,7 @@ async function collectTasksView() {
4605
5652
  })),
4606
5653
  ];
4607
5654
 
4608
- return sources.map(({ task: t, orphaned }) => {
5655
+ const view = sources.map(({ task: t, orphaned }) => {
4609
5656
  // Все бэкенды возвращают короткие имена (без папки планировщика).
4610
5657
  const name = t.taskName || "";
4611
5658
 
@@ -4648,6 +5695,15 @@ async function collectTasksView() {
4648
5695
  partial: 0,
4649
5696
  };
4650
5697
 
5698
+ // Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
5699
+ // nextRun считаем из определения — schtasks после мутации отдаёт
5700
+ // nextRunTime с задержкой, из-за чего API показывал null после resume.
5701
+ const pausedUntil = def?.pausedUntil ?? null;
5702
+ const paused =
5703
+ Boolean(t.paused) ||
5704
+ def?.paused === true ||
5705
+ Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
5706
+
4651
5707
  return {
4652
5708
  name,
4653
5709
  schedule: def?.schedule ?? "",
@@ -4656,15 +5712,15 @@ async function collectTasksView() {
4656
5712
  // Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
4657
5713
  // из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
4658
5714
  // поэтому кнопка «возобновить» была недоступна.
4659
- paused: Boolean(t.paused),
5715
+ paused,
4660
5716
  runsTotal: counts.total,
4661
5717
  runsSuccess: counts.success,
4662
5718
  runsError: counts.error,
4663
5719
  runsPartial: counts.partial,
4664
- // Для разовой задачи показываем запланированное время, а не пустое расписание.
4665
- nextRun: def?.triggerType === "once"
4666
- ? def?.runAt ?? (t.nextRunTime ? String(t.nextRunTime) : null)
4667
- : t.nextRunTime ? String(t.nextRunTime) : null,
5720
+ nextRun: paused
5721
+ ? null
5722
+ : computeTaskNextRun(def) ??
5723
+ (t.nextRunTime ? String(t.nextRunTime) : null),
4668
5724
  runAt: def?.runAt ?? null,
4669
5725
  session: def?.session ?? "new",
4670
5726
  sessionId: def?.sessionId ?? null,
@@ -4687,6 +5743,10 @@ async function collectTasksView() {
4687
5743
  notBefore: def?.notBefore ?? null,
4688
5744
  notAfter: def?.notAfter ?? null,
4689
5745
  pausedUntil: def?.pausedUntil ?? null,
5746
+ // Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
5747
+ // определения (запуск без входа через /ru SYSTEM).
5748
+ logonMode: t.logonMode ?? null,
5749
+ runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
4690
5750
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
4691
5751
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
4692
5752
  workspaceName: workspace?.name ?? null,
@@ -4709,6 +5769,8 @@ async function collectTasksView() {
4709
5769
  prompt: def?.prompt ?? "",
4710
5770
  };
4711
5771
  });
5772
+
5773
+ return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
4712
5774
  }
4713
5775
 
4714
5776
  /**