opencode-windows-scheduler 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -3
  3. package/README.ru.md +13 -3
  4. package/ROADMAP.md +20 -13
  5. package/dist/core/analytics.d.ts +10 -0
  6. package/dist/core/analytics.d.ts.map +1 -1
  7. package/dist/core/analytics.js +21 -0
  8. package/dist/core/dry-run.d.ts +13 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +30 -0
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +10 -0
  13. package/dist/core/ps-wrapper.d.ts +32 -2
  14. package/dist/core/ps-wrapper.d.ts.map +1 -1
  15. package/dist/core/ps-wrapper.js +101 -3
  16. package/dist/core/schedule-gate.d.ts +2 -0
  17. package/dist/core/schedule-gate.d.ts.map +1 -0
  18. package/dist/core/schedule-gate.js +182 -0
  19. package/dist/core/schedule-v2.d.ts +88 -0
  20. package/dist/core/schedule-v2.d.ts.map +1 -0
  21. package/dist/core/schedule-v2.js +496 -0
  22. package/dist/core/scheduler/types.d.ts +15 -0
  23. package/dist/core/scheduler/types.d.ts.map +1 -1
  24. package/dist/core/scheduler/windows.d.ts.map +1 -1
  25. package/dist/core/scheduler/windows.js +13 -1
  26. package/dist/core/wrappers/bash.d.ts +15 -0
  27. package/dist/core/wrappers/bash.d.ts.map +1 -1
  28. package/dist/core/wrappers/bash.js +44 -1
  29. package/dist/db/history-repo.d.ts +8 -0
  30. package/dist/db/history-repo.d.ts.map +1 -1
  31. package/dist/db/history-repo.js +13 -0
  32. package/dist/db/schema.d.ts +1 -1
  33. package/dist/db/schema.d.ts.map +1 -1
  34. package/dist/db/schema.js +11 -0
  35. package/dist/index.d.ts +117 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1010 -54
  38. package/dist/notifications.d.ts +112 -6
  39. package/dist/notifications.d.ts.map +1 -1
  40. package/dist/notifications.js +396 -34
  41. package/dist/profiles.d.ts +60 -0
  42. package/dist/profiles.d.ts.map +1 -0
  43. package/dist/profiles.js +209 -0
  44. package/dist/rpc.d.ts +511 -0
  45. package/dist/rpc.d.ts.map +1 -1
  46. package/dist/rpc.js +190 -2
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/server.js +5 -2
  49. package/dist/settings.d.ts +57 -0
  50. package/dist/settings.d.ts.map +1 -1
  51. package/dist/settings.js +118 -8
  52. package/dist/task-transfer.d.ts +13 -0
  53. package/dist/task-transfer.d.ts.map +1 -1
  54. package/dist/task-transfer.js +26 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +3 -11
  57. package/dist/workspaces.d.ts +43 -0
  58. package/dist/workspaces.d.ts.map +1 -1
  59. package/dist/workspaces.js +174 -8
  60. package/docs/ARCHITECTURE.md +32 -12
  61. package/docs/FEATURES.md +86 -7
  62. package/gui-experimental.cjs +4 -2
  63. package/package.json +6 -2
  64. package/src/core/analytics.ts +36 -0
  65. package/src/core/dry-run.ts +42 -0
  66. package/src/core/matrix.ts +10 -0
  67. package/src/core/ps-wrapper.ts +117 -3
  68. package/src/core/schedule-gate.ts +213 -0
  69. package/src/core/schedule-v2.ts +533 -0
  70. package/src/core/scheduler/types.ts +15 -0
  71. package/src/core/scheduler/windows.ts +13 -1
  72. package/src/core/wrappers/bash.ts +60 -0
  73. package/src/db/history-repo.ts +23 -0
  74. package/src/db/schema.ts +14 -0
  75. package/src/gui.tsx +767 -22
  76. package/src/index.ts +1226 -52
  77. package/src/notifications.ts +516 -40
  78. package/src/profiles.ts +236 -0
  79. package/src/rpc.ts +201 -2
  80. package/src/server.ts +5 -2
  81. package/src/settings.ts +214 -9
  82. package/src/task-transfer.ts +44 -0
  83. package/src/types.ts +3 -13
  84. package/src/workspaces.ts +214 -8
package/src/index.ts CHANGED
@@ -7,8 +7,8 @@ import fs from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { LockManager } from "./core/lock.js";
9
9
  import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
10
- import { convertCronToSchTasks, previousRunTime } from "./core/cron-to-schtasks.js";
11
- import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath } from "./core/ps-wrapper.js";
10
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
11
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
12
12
  import { getSchedulerBackend } from "./core/scheduler/index.js";
13
13
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
14
14
  import { getTaskLogs } from "./core/scheduler/logs.js";
@@ -32,8 +32,15 @@ import { loadSettings, saveSettings } from "./settings.js";
32
32
  import type { HistorySettings, NotificationSettings } from "./settings.js";
33
33
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
34
34
  import { buildAnalytics } from "./core/analytics.js";
35
- import { getHistory } from "./db/history-repo.js";
36
- import { sendTestNotification } from "./notifications.js";
35
+ import { getHistory, listRunningRecords } from "./db/history-repo.js";
36
+ import { getAllMetrics } from "./db/metrics-repo.js";
37
+ import {
38
+ findStuckMatrixClones,
39
+ maybeSendDigest,
40
+ notifyStuckMatrix,
41
+ sendDigestNow,
42
+ sendTestNotification,
43
+ } from "./notifications.js";
37
44
  import {
38
45
  loadTaskDefinitions,
39
46
  saveTaskDefinition,
@@ -52,10 +59,21 @@ import type {
52
59
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
53
60
  import type { TaskTemplate } from "./templates.js";
54
61
  import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
62
+ import {
63
+ DEFAULT_PROFILE,
64
+ createProfile,
65
+ deleteProfile,
66
+ getProfileDir,
67
+ getProfileName,
68
+ isProfilePinnedByEnv,
69
+ listProfiles,
70
+ sanitizeProfileName,
71
+ setActiveProfile,
72
+ } from "./profiles.js";
55
73
  import { closeDb, initDb } from "./db/index.js";
56
74
  import { migrateJsonToDb } from "./db/migrate.js";
57
75
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
58
- import { getTask, listMatrixClones } from "./db/tasks-repo.js";
76
+ import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
59
77
  import {
60
78
  addWorkspace,
61
79
  deleteWorkspace,
@@ -64,6 +82,8 @@ import {
64
82
  updateWorkspace,
65
83
  validateWorkspacePath,
66
84
  readGitBranch,
85
+ writeWorkspaceEnvFile,
86
+ maskEnvForLog,
67
87
  } from "./workspaces.js";
68
88
 
69
89
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
@@ -88,6 +108,24 @@ const recorderPath = (() => {
88
108
  return distPath;
89
109
  })();
90
110
 
111
+ /**
112
+ * Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
113
+ * перед opencode и выходит, если cron не сработал или запуск перенесён.
114
+ */
115
+ const gatePath = (() => {
116
+ const resolved = require.resolve("./core/schedule-gate.js");
117
+ if (!resolved.endsWith(".ts")) return resolved;
118
+ const distPath = resolved
119
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
120
+ .replace(/\.ts$/, ".js");
121
+ if (existsSync(distPath)) return distPath;
122
+ console.warn(
123
+ "[windows-scheduler] Не найден собранный schedule-gate.js: " +
124
+ `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`
125
+ );
126
+ return distPath;
127
+ })();
128
+
91
129
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
92
130
  const scheduler = getSchedulerBackend();
93
131
 
@@ -149,8 +187,24 @@ export const scheduleTaskSchema = z.object({
149
187
  schedule: z
150
188
  .string()
151
189
  .describe(
152
- "5-field cron expression (minute hour day-of-month month day-of-week). Supported patterns: * * * * *, */N * * * *, M H * * *, M H * * D."
190
+ "Cron expression (5 fields: minute hour day-of-month month day-of-week). Supports ranges, lists, */N steps, month/weekday names, @every 15m|2h|1d, L (last day of month) and FRI#3 (third Friday). Expressions schtasks cannot express are checked every minute inside the wrapper."
153
191
  ),
192
+ timezone: z
193
+ .string()
194
+ .optional()
195
+ .describe(
196
+ "IANA timezone of the schedule, e.g. Europe/Moscow. Defaults to the system timezone. A zone different from the system one is evaluated by the wrapper (poll mode)."
197
+ ),
198
+ notBefore: z
199
+ .string()
200
+ .optional()
201
+ .describe(
202
+ "Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."
203
+ ),
204
+ notAfter: z
205
+ .string()
206
+ .optional()
207
+ .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
154
208
  prompt: z
155
209
  .string()
156
210
  .describe("Prompt passed to the agent on every run."),
@@ -222,6 +276,12 @@ export const scheduleTaskSchema = z.object({
222
276
  .describe(
223
277
  "MCP event trigger: server, event name and an optional filter (key=value or regex)."
224
278
  ),
279
+ watchPath: z
280
+ .string()
281
+ .optional()
282
+ .describe(
283
+ "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
284
+ ),
225
285
  workingDirectory: z
226
286
  .string()
227
287
  .optional()
@@ -268,7 +328,19 @@ export const updateTaskSchema = z.object({
268
328
  schedule: z
269
329
  .string()
270
330
  .optional()
271
- .describe("New 5-field cron expression. Keeps the current value when omitted."),
331
+ .describe("New cron expression. Keeps the current value when omitted."),
332
+ timezone: z
333
+ .string()
334
+ .optional()
335
+ .describe("New IANA timezone. Empty string clears it (system timezone)."),
336
+ notBefore: z
337
+ .string()
338
+ .optional()
339
+ .describe("New launch window start HH:MM. Empty string clears the window."),
340
+ notAfter: z
341
+ .string()
342
+ .optional()
343
+ .describe("New launch window end HH:MM. Empty string clears the window."),
272
344
  prompt: z
273
345
  .string()
274
346
  .optional()
@@ -347,6 +419,12 @@ export const updateTaskSchema = z.object({
347
419
 
348
420
  const pauseTaskSchema = z.object({
349
421
  name: z.string().describe("Task name to pause."),
422
+ until: z
423
+ .string()
424
+ .optional()
425
+ .describe(
426
+ "Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."
427
+ ),
350
428
  });
351
429
 
352
430
  const resumeTaskSchema = z.object({
@@ -393,18 +471,167 @@ const manageWorkspacesSchema = z.object({
393
471
  name: z.string().optional().describe("Workspace display name (add/update)."),
394
472
  path: z.string().optional().describe("Absolute workspace path (add/update)."),
395
473
  color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
474
+ env: z
475
+ .record(z.string(), z.string())
476
+ .nullable()
477
+ .optional()
478
+ .describe(
479
+ "Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."
480
+ ),
481
+ envFile: z
482
+ .string()
483
+ .nullable()
484
+ .optional()
485
+ .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
396
486
  });
397
487
 
398
488
  export const matrixControlSchema = z.object({
399
489
  action: z
400
- .enum(["results", "cancel", "cleanup"])
490
+ .enum(["results", "cancel", "cleanup", "preview"])
401
491
  .describe(
402
- "results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."
492
+ "results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators; preview — dry-expand a matrix config into clone names without creating anything."
403
493
  ),
404
494
  name: z
405
495
  .string()
406
496
  .optional()
407
- .describe("Matrix parent name (required for results and cancel)."),
497
+ .describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
498
+ workspaceIds: z
499
+ .array(z.string())
500
+ .optional()
501
+ .describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
502
+ strategy: z
503
+ .enum(["parallel", "sequential"])
504
+ .optional()
505
+ .describe("Preview only: clone execution strategy."),
506
+ failureMode: z
507
+ .enum(["continue", "stop"])
508
+ .optional()
509
+ .describe("Preview only: what to do when one clone fails."),
510
+ aggregation: z
511
+ .enum(["summary", "per-task"])
512
+ .optional()
513
+ .describe("Preview only: how clone results are aggregated."),
514
+ });
515
+
516
+ /** get_metrics — общая статистика запусков. */
517
+ export const getMetricsSchema = z.object({});
518
+
519
+ /** get_analytics — аналитика за период. */
520
+ export const getAnalyticsSchema = z.object({
521
+ days: z
522
+ .number()
523
+ .int()
524
+ .min(1)
525
+ .max(365)
526
+ .optional()
527
+ .describe("Analysis window in days (default 14)."),
528
+ topLimit: z
529
+ .number()
530
+ .int()
531
+ .min(1)
532
+ .max(50)
533
+ .optional()
534
+ .describe("How many top tasks to include (default 10)."),
535
+ });
536
+
537
+ /** manage_settings — глобальные настройки планировщика. */
538
+ export const manageSettingsSchema = z.object({
539
+ action: z
540
+ .enum(["get", "update"])
541
+ .describe("get — current settings; update — merge the provided fields and save."),
542
+ maxConcurrent: z
543
+ .number()
544
+ .int()
545
+ .min(1)
546
+ .max(16)
547
+ .optional()
548
+ .describe("How many task runs may execute at the same time."),
549
+ winterMode: z
550
+ .boolean()
551
+ .optional()
552
+ .describe("Winter mode: gentler scheduling of deferred runs."),
553
+ notifications: z
554
+ .any()
555
+ .optional()
556
+ .describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
557
+ history: z
558
+ .object({
559
+ retentionDays: z.number().int().min(1).max(3650).optional(),
560
+ maxRecords: z.number().int().min(100).max(1000000).optional(),
561
+ })
562
+ .optional()
563
+ .describe("History retention policy."),
564
+ });
565
+
566
+ /** manage_templates — пользовательские шаблоны задач. */
567
+ export const manageTemplatesSchema = z.object({
568
+ action: z
569
+ .enum(["list", "save", "delete"])
570
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
571
+ id: z.string().optional().describe("Template id for update/delete."),
572
+ name: z.string().optional().describe("Template name."),
573
+ prompt: z.string().optional().describe("Prompt text stored in the template."),
574
+ schedule: z.string().optional().describe("Cron expression."),
575
+ timeoutSeconds: z.number().int().positive().optional(),
576
+ model: z.string().optional(),
577
+ priority: z.number().int().min(0).max(10).optional(),
578
+ retryCount: z.number().int().min(0).optional(),
579
+ retryDelay: z.number().int().min(0).optional(),
580
+ qualityGate: z.string().optional(),
581
+ beforeScript: z.string().optional(),
582
+ afterScript: z.string().optional(),
583
+ nextTaskOnSuccess: z.string().optional(),
584
+ nextTaskOnError: z.string().optional(),
585
+ dependsOn: z.array(z.string()).optional(),
586
+ triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
587
+ mcpEvent: z
588
+ .object({
589
+ server: z.string(),
590
+ event: z.string(),
591
+ filter: z.string().optional(),
592
+ })
593
+ .optional(),
594
+ watchPath: z.string().optional(),
595
+ workingDirectory: z.string().optional(),
596
+ allowedTools: z.array(z.string()).optional(),
597
+ deniedTools: z.array(z.string()).optional(),
598
+ });
599
+
600
+ /** manage_profiles — изолированные профили планировщика. */
601
+ export const manageProfilesSchema = z.object({
602
+ action: z
603
+ .enum(["list", "create", "switch", "delete"])
604
+ .describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
605
+ name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
606
+ port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
607
+ });
608
+
609
+ /** transfer_tasks — экспорт и импорт задач. */
610
+ export const transferTasksSchema = z.object({
611
+ action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
612
+ data: z.string().optional().describe("JSON produced by export (required for import)."),
613
+ });
614
+
615
+ /** send_notification — проверка уведомлений и дайджест. */
616
+ export const sendNotificationSchema = z.object({
617
+ action: z
618
+ .enum(["test", "digest"])
619
+ .describe("test — send a test message through the configured channel; digest — send the digest now."),
620
+ });
621
+
622
+ /** get_dashboard_info — сведения о панели управления. */
623
+ export const getDashboardInfoSchema = z.object({});
624
+
625
+ /** cleanup_history — удаление старой истории. */
626
+ export const cleanupHistorySchema = z.object({
627
+ retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
628
+ maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
629
+ });
630
+
631
+ /** emit_event — запуск задач по MCP-событию. */
632
+ export const emitEventSchema = z.object({
633
+ eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
634
+ payload: z.any().optional().describe("Event payload passed to trigger filters."),
408
635
  });
409
636
 
410
637
  type ScheduleArgs = z.infer<typeof scheduleTaskSchema>;
@@ -419,6 +646,16 @@ type TaskLogsArgs = z.infer<typeof getTaskLogsSchema>;
419
646
  type DryRunArgs = z.infer<typeof dryRunSchema>;
420
647
  type WorkspacesArgs = z.infer<typeof manageWorkspacesSchema>;
421
648
  type MatrixControlArgs = z.infer<typeof matrixControlSchema>;
649
+ type MetricsArgs = z.infer<typeof getMetricsSchema>;
650
+ type AnalyticsArgs = z.infer<typeof getAnalyticsSchema>;
651
+ type SettingsArgs = z.infer<typeof manageSettingsSchema>;
652
+ type TemplatesArgs = z.infer<typeof manageTemplatesSchema>;
653
+ type ProfilesArgs = z.infer<typeof manageProfilesSchema>;
654
+ type TransferArgs = z.infer<typeof transferTasksSchema>;
655
+ type NotificationArgs = z.infer<typeof sendNotificationSchema>;
656
+ type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
657
+ type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
658
+ type EmitEventArgs = z.infer<typeof emitEventSchema>;
422
659
 
423
660
  /**
424
661
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -467,11 +704,15 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
467
704
  nextTaskOnError,
468
705
  triggerType,
469
706
  mcpEvent,
707
+ watchPath,
470
708
  workingDirectory,
471
709
  workspaceId,
472
710
  allowedTools,
473
711
  deniedTools,
474
712
  matrix,
713
+ timezone,
714
+ notBefore,
715
+ notAfter,
475
716
  } = args;
476
717
 
477
718
  try {
@@ -487,7 +728,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
487
728
  nextTaskOnSuccess,
488
729
  nextTaskOnError,
489
730
  triggerType,
490
- undefined,
731
+ watchPath,
491
732
  dependsOn,
492
733
  model,
493
734
  priority,
@@ -497,7 +738,12 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
497
738
  workspaceId,
498
739
  allowedTools,
499
740
  deniedTools,
500
- matrix
741
+ matrix,
742
+ undefined,
743
+ "create",
744
+ timezone,
745
+ notBefore,
746
+ notAfter
501
747
  );
502
748
  } catch (err: any) {
503
749
  return {
@@ -508,6 +754,10 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
508
754
  };
509
755
  }
510
756
 
757
+ // Новый файловый триггер должен начать работать сразу, без перезапуска
758
+ // OpenCode: пересобираем набор watcher-ов после создания задачи.
759
+ await refreshFileTriggers();
760
+
511
761
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
512
762
  const effectiveWorkdir =
513
763
  workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
@@ -530,6 +780,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
530
780
  nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
531
781
  nextTaskOnError: nextTaskOnError?.trim() || null,
532
782
  triggerType: triggerType ?? "cron",
783
+ timezone: timezone?.trim() || null,
784
+ notBefore: notBefore?.trim() || null,
785
+ notAfter: notAfter?.trim() || null,
533
786
  mcpEvent: mcpEvent ?? null,
534
787
  workingDirectory: effectiveWorkdir,
535
788
  workspaceId: workspace?.id ?? null,
@@ -625,7 +878,12 @@ async function cancelMatrixRun(
625
878
  clone.allowedTools,
626
879
  clone.deniedTools,
627
880
  undefined,
628
- definition.name
881
+ definition.name,
882
+ "create",
883
+ clone.timezone,
884
+ clone.notBefore,
885
+ clone.notAfter,
886
+ clone.pausedUntil
629
887
  );
630
888
  } catch (err: any) {
631
889
  warnings.push(
@@ -695,7 +953,7 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
695
953
  */
696
954
  async function deleteTaskWithFamily(
697
955
  name: string
698
- ): Promise<{ removed: string[] }> {
956
+ ): Promise<{ removed: string[]; existed: boolean }> {
699
957
  const trimmed = name.trim();
700
958
  const guard = getMatrixDeletionGuard(trimmed);
701
959
  if (guard) throw new Error(guard);
@@ -703,6 +961,21 @@ async function deleteTaskWithFamily(
703
961
  const plan = planMatrixFamilyDelete(trimmed);
704
962
  const removed: string[] = [];
705
963
 
964
+ // Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
965
+ // отвечал success даже на имя, которого никогда не существовало.
966
+ let existed = Boolean(getTask(trimmed));
967
+ if (!existed) {
968
+ try {
969
+ const osTasks = await scheduler.listTasks();
970
+ existed = osTasks.some(
971
+ (task) => task.taskName.toLowerCase() === trimmed.toLowerCase()
972
+ );
973
+ } catch {
974
+ // ОС-планировщик недоступен — довольствуемся данными БД.
975
+ }
976
+ }
977
+ if (plan && plan.children.length > 0) existed = true;
978
+
706
979
  if (plan) {
707
980
  for (const child of plan.children) {
708
981
  try {
@@ -726,7 +999,7 @@ async function deleteTaskWithFamily(
726
999
  // Определения могло уже не быть — задача всё равно удалена из ОС.
727
1000
  }
728
1001
 
729
- return { removed };
1002
+ return { removed, existed };
730
1003
  }
731
1004
 
732
1005
  /** delete_task — удаление задачи по имени (/f) */
@@ -734,7 +1007,17 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
734
1007
  const { name } = args;
735
1008
 
736
1009
  try {
737
- const { removed } = await deleteTaskWithFamily(name);
1010
+ const { removed, existed } = await deleteTaskWithFamily(name);
1011
+ // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
1012
+ await refreshFileTriggers();
1013
+ if (!existed && removed.length === 0) {
1014
+ return {
1015
+ content: JSON.stringify({
1016
+ success: false,
1017
+ error: `Задача "${name}" не найдена — удалять нечего.`,
1018
+ }),
1019
+ };
1020
+ }
738
1021
  return {
739
1022
  content: JSON.stringify({
740
1023
  success: true,
@@ -760,7 +1043,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
760
1043
 
761
1044
  let alreadyRunning = false;
762
1045
  try {
763
- const result = await scheduler.runTask(name);
1046
+ const result = await runTaskEntry(name);
764
1047
  alreadyRunning = result.alreadyRunning;
765
1048
  } catch (err: any) {
766
1049
  return {
@@ -842,6 +1125,9 @@ async function updateTaskFromInput(
842
1125
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
843
1126
  const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
844
1127
  const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
1128
+ const timezone = clearableString(input.timezone, previous.timezone);
1129
+ const notBefore = clearableString(input.notBefore, previous.notBefore);
1130
+ const notAfter = clearableString(input.notAfter, previous.notAfter);
845
1131
 
846
1132
  if (triggerType === "cron" && !schedule) {
847
1133
  return {
@@ -889,7 +1175,11 @@ async function updateTaskFromInput(
889
1175
  undefined,
890
1176
  // Если задача была матрицей — синхронизируем клонов, а не
891
1177
  // пересоздаём их с нуля (Спринт 17).
892
- matrixWas && matrixNext ? "sync" : "create"
1178
+ matrixWas && matrixNext ? "sync" : "create",
1179
+ timezone,
1180
+ notBefore,
1181
+ notAfter,
1182
+ previous.pausedUntil
893
1183
  );
894
1184
 
895
1185
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -897,6 +1187,10 @@ async function updateTaskFromInput(
897
1187
  await removeMatrixChildrenFromScheduler(name);
898
1188
  }
899
1189
 
1190
+ // Пересоздание могло изменить triggerType/watchPath — сразу
1191
+ // пересобираем набор файловых watcher-ов.
1192
+ await refreshFileTriggers();
1193
+
900
1194
  return { success: true, message: `Задача "${name}" обновлена.` };
901
1195
  } catch (err: any) {
902
1196
  return {
@@ -918,7 +1212,8 @@ const updateTaskExecute = wrapExecute<UpdateArgs>(async (args) => {
918
1212
  */
919
1213
  async function pauseOrResumeTask(
920
1214
  name: string,
921
- paused: boolean
1215
+ paused: boolean,
1216
+ until?: string
922
1217
  ): Promise<{ success: boolean; message: string; affected: string[]; warnings: string[] }> {
923
1218
  const trimmed = name.trim();
924
1219
  const definition = getTask(trimmed);
@@ -931,6 +1226,29 @@ async function pauseOrResumeTask(
931
1226
  };
932
1227
  }
933
1228
 
1229
+ // Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
1230
+ let pausedUntil: string | undefined;
1231
+ if (paused && until?.trim()) {
1232
+ const parsed = Date.parse(until.trim());
1233
+ if (Number.isNaN(parsed)) {
1234
+ return {
1235
+ success: false,
1236
+ message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
1237
+ affected: [],
1238
+ warnings: [],
1239
+ };
1240
+ }
1241
+ if (parsed <= Date.now()) {
1242
+ return {
1243
+ success: false,
1244
+ message: `Задача "${trimmed}": дата паузы уже прошла.`,
1245
+ affected: [],
1246
+ warnings: [],
1247
+ };
1248
+ }
1249
+ pausedUntil = new Date(parsed).toISOString();
1250
+ }
1251
+
934
1252
  const targets = definition.matrix
935
1253
  ? listMatrixClones(trimmed).map((clone) => clone.name)
936
1254
  : [trimmed];
@@ -960,11 +1278,35 @@ async function pauseOrResumeTask(
960
1278
  }
961
1279
  }
962
1280
 
1281
+ // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
1282
+ // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
1283
+ const definitionUpdates = paused
1284
+ ? pausedUntil
1285
+ ? { pausedUntil }
1286
+ : undefined
1287
+ : definition.pausedUntil
1288
+ ? { pausedUntil: undefined }
1289
+ : undefined;
1290
+ if (definitionUpdates && affected.length > 0) {
1291
+ try {
1292
+ saveTask({ ...definition, ...definitionUpdates });
1293
+ } catch (err: any) {
1294
+ warnings.push(
1295
+ `не удалось сохранить автопродолжение: ${
1296
+ err instanceof Error ? err.message : String(err)
1297
+ }`
1298
+ );
1299
+ }
1300
+ }
1301
+
1302
+ const untilText = pausedUntil
1303
+ ? ` до ${new Date(pausedUntil).toLocaleString()}`
1304
+ : "";
963
1305
  const verb = paused ? "поставлена на паузу" : "возобновлена";
964
1306
  const message = definition.matrix
965
- ? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
1307
+ ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
966
1308
  (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
967
- : `Задача "${trimmed}" ${verb}.` +
1309
+ : `Задача "${trimmed}" ${verb}${untilText}.` +
968
1310
  (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
969
1311
 
970
1312
  return {
@@ -976,7 +1318,7 @@ async function pauseOrResumeTask(
976
1318
  }
977
1319
 
978
1320
  const pauseTaskExecute = wrapExecute<PauseArgs>(async (args) => {
979
- const result = await pauseOrResumeTask(args.name, true);
1321
+ const result = await pauseOrResumeTask(args.name, true, args.until);
980
1322
  return { content: JSON.stringify(result) };
981
1323
  });
982
1324
 
@@ -985,6 +1327,88 @@ const resumeTaskExecute = wrapExecute<ResumeArgs>(async (args) => {
985
1327
  return { content: JSON.stringify(result) };
986
1328
  });
987
1329
 
1330
+ /** Периодичность проверки автопродолжения задач (Спринт 19). */
1331
+ const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
1332
+ /** Период проверки дайджеста и зависших матриц (Спринт 20). */
1333
+ const NOTIFICATION_CHECK_MS = 60 * 1000;
1334
+
1335
+ /**
1336
+ * Спринт 19: автопродолжение задач, поставленных на паузу до даты.
1337
+ * Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
1338
+ * Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
1339
+ */
1340
+ async function resumeExpiredPauses(): Promise<void> {
1341
+ const now = Date.now();
1342
+ const definitions = await loadTaskDefinitions();
1343
+ for (const definition of definitions) {
1344
+ if (!definition.pausedUntil) continue;
1345
+ if (definition.matrixParentId) continue;
1346
+ const untilMs = Date.parse(definition.pausedUntil);
1347
+ if (!Number.isFinite(untilMs) || untilMs > now) continue;
1348
+
1349
+ try {
1350
+ const targets = definition.matrix
1351
+ ? listMatrixClones(definition.name).map((clone) => clone.name)
1352
+ : [definition.name];
1353
+ for (const target of targets) {
1354
+ await scheduler.resumeTask(target);
1355
+ }
1356
+ await saveTaskDefinition({ ...definition, pausedUntil: undefined });
1357
+ console.log(
1358
+ `[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
1359
+ );
1360
+ } catch (err: any) {
1361
+ console.error(
1362
+ `[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${
1363
+ err instanceof Error ? err.message : String(err)
1364
+ }`
1365
+ );
1366
+ }
1367
+ }
1368
+ }
1369
+
1370
+ /** Уже отправленные уведомления о зависших клонах (id записи истории). */
1371
+ const notifiedStuckRecords = new Set<number>();
1372
+
1373
+ /**
1374
+ * Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
1375
+ * `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
1376
+ */
1377
+ async function checkStuckMatrices(): Promise<void> {
1378
+ const settings = await loadSettings();
1379
+ const config = settings.notifications;
1380
+ if (!config?.enabled) return;
1381
+ const matrix = config.matrix;
1382
+ if (!matrix?.enabled) return;
1383
+ const threshold = matrix.stuckAfterMinutes;
1384
+ if (!Number.isFinite(threshold) || threshold <= 0) return;
1385
+
1386
+ const running = listRunningRecords();
1387
+ if (running.length === 0) {
1388
+ notifiedStuckRecords.clear();
1389
+ return;
1390
+ }
1391
+ // Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
1392
+ const runningIds = new Set(running.map((record) => record.id));
1393
+ for (const id of notifiedStuckRecords) {
1394
+ if (!runningIds.has(id)) notifiedStuckRecords.delete(id);
1395
+ }
1396
+
1397
+ const parentByClone = new Map<string, string>();
1398
+ for (const definition of await loadTaskDefinitions()) {
1399
+ if (definition.matrixParentId) {
1400
+ parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
1401
+ }
1402
+ }
1403
+
1404
+ const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
1405
+ for (const item of stuck) {
1406
+ if (notifiedStuckRecords.has(item.id)) continue;
1407
+ notifiedStuckRecords.add(item.id);
1408
+ await notifyStuckMatrix(item);
1409
+ }
1410
+ }
1411
+
988
1412
  /** get_history — история запусков с фильтрами по задаче и статусу. */
989
1413
  const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
990
1414
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
@@ -1057,6 +1481,22 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
1057
1481
  };
1058
1482
  });
1059
1483
 
1484
+ /**
1485
+ * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1486
+ * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
1487
+ */
1488
+ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
1489
+ const workspace = getWorkspace(workspaceId);
1490
+ if (!workspace) return 0;
1491
+ let refreshed = 0;
1492
+ for (const task of await loadTaskDefinitions()) {
1493
+ if (task.workspaceId !== workspaceId) continue;
1494
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
1495
+ refreshed += 1;
1496
+ }
1497
+ return refreshed;
1498
+ }
1499
+
1060
1500
  /** manage_workspaces — CRUD multi-repo workspace-ов. */
1061
1501
  const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1062
1502
  try {
@@ -1064,6 +1504,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1064
1504
  case "list": {
1065
1505
  const workspaces = listWorkspaces().map((workspace) => ({
1066
1506
  ...workspace,
1507
+ env: maskEnvForLog(workspace.env),
1067
1508
  gitBranch: readGitBranch(workspace.path) ?? null,
1068
1509
  }));
1069
1510
  return {
@@ -1087,12 +1528,15 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1087
1528
  name: args.name,
1088
1529
  path: args.path,
1089
1530
  color: args.color,
1531
+ env: args.env,
1532
+ envFile: args.envFile,
1090
1533
  });
1091
1534
  return {
1092
1535
  content: JSON.stringify({
1093
1536
  success: true,
1094
1537
  workspace: {
1095
1538
  ...workspace,
1539
+ env: maskEnvForLog(workspace.env),
1096
1540
  gitBranch: readGitBranch(workspace.path) ?? null,
1097
1541
  },
1098
1542
  }),
@@ -1111,6 +1555,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1111
1555
  name: args.name,
1112
1556
  path: args.path,
1113
1557
  color: args.color,
1558
+ env: args.env,
1559
+ envFile: args.envFile,
1114
1560
  });
1115
1561
  if (!workspace) {
1116
1562
  return {
@@ -1120,11 +1566,16 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1120
1566
  }),
1121
1567
  };
1122
1568
  }
1569
+ // Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
1570
+ // файл при запуске, поэтому ждать обновления задачи не нужно.
1571
+ const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
1123
1572
  return {
1124
1573
  content: JSON.stringify({
1125
1574
  success: true,
1575
+ refreshedTasks,
1126
1576
  workspace: {
1127
1577
  ...workspace,
1578
+ env: maskEnvForLog(workspace.env),
1128
1579
  gitBranch: readGitBranch(workspace.path) ?? null,
1129
1580
  },
1130
1581
  }),
@@ -1160,8 +1611,32 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1160
1611
  }
1161
1612
  });
1162
1613
 
1163
- /** matrix_control — результаты, отмена и очистка матриц. */
1614
+ /** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
1164
1615
  const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1616
+ if (args.action === "preview") {
1617
+ const clones = expandMatrixTask({
1618
+ name: (args.name ?? "").trim() || "task",
1619
+ schedule: "* * * * *",
1620
+ prompt: "preview",
1621
+ matrix: {
1622
+ workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
1623
+ strategy: args.strategy,
1624
+ failureMode: args.failureMode,
1625
+ aggregation: args.aggregation,
1626
+ },
1627
+ } as any);
1628
+ return {
1629
+ content: JSON.stringify({
1630
+ success: true,
1631
+ clones: clones.map((clone) => ({
1632
+ name: clone.name,
1633
+ workspaceId: clone.workspaceId ?? "",
1634
+ workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
1635
+ })),
1636
+ }),
1637
+ };
1638
+ }
1639
+
1165
1640
  if (args.action === "cleanup") {
1166
1641
  const removed = await cleanupOrphanedMatrixTasks();
1167
1642
  return {
@@ -1219,6 +1694,334 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1219
1694
  }
1220
1695
  });
1221
1696
 
1697
+ /** get_metrics — суммарная статистика запусков. */
1698
+ const getMetricsExecute = wrapExecute<MetricsArgs>(async () => {
1699
+ const metrics = await loadMetrics();
1700
+ return { content: JSON.stringify({ success: true, metrics }) };
1701
+ });
1702
+
1703
+ /** get_analytics — аналитика запусков и стоимости за период. */
1704
+ const getAnalyticsExecute = wrapExecute<AnalyticsArgs>(async (args) => {
1705
+ const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
1706
+ const records = getHistory(null, 20000);
1707
+ const definitions = await loadTaskDefinitions();
1708
+ const report = buildAnalytics(records, {
1709
+ days: windowDays,
1710
+ topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
1711
+ tasks: definitions.map((definition) => ({
1712
+ name: definition.name,
1713
+ matrixParentId: definition.matrixParentId,
1714
+ })),
1715
+ });
1716
+ return { content: JSON.stringify({ success: true, report }) };
1717
+ });
1718
+
1719
+ /** manage_settings — чтение и изменение глобальных настроек. */
1720
+ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1721
+ const current = await loadSettings();
1722
+ if (args.action === "get") {
1723
+ return { content: JSON.stringify({ success: true, settings: current }) };
1724
+ }
1725
+
1726
+ if (
1727
+ args.maxConcurrent === undefined &&
1728
+ args.winterMode === undefined &&
1729
+ args.notifications === undefined &&
1730
+ args.history === undefined
1731
+ ) {
1732
+ return {
1733
+ content: JSON.stringify({
1734
+ success: false,
1735
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications или history.",
1736
+ settings: current,
1737
+ }),
1738
+ };
1739
+ }
1740
+
1741
+ const settings = await saveSettings({
1742
+ maxConcurrent: args.maxConcurrent,
1743
+ winterMode: args.winterMode,
1744
+ notifications: args.notifications as NotificationSettings | undefined,
1745
+ history: args.history as HistorySettings | undefined,
1746
+ });
1747
+ return { content: JSON.stringify({ success: true, settings }) };
1748
+ });
1749
+
1750
+ /** manage_templates — список, сохранение и удаление шаблонов задач. */
1751
+ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
1752
+ if (args.action === "list") {
1753
+ return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
1754
+ }
1755
+
1756
+ if (args.action === "delete") {
1757
+ const id = args.id?.trim();
1758
+ if (!id) {
1759
+ return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
1760
+ }
1761
+ const before = await loadTemplates();
1762
+ const existed = before.some((template) => template.id === id);
1763
+ await deleteTemplate(id);
1764
+ return {
1765
+ content: JSON.stringify({
1766
+ success: existed,
1767
+ message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
1768
+ }),
1769
+ };
1770
+ }
1771
+
1772
+ const { action, ...fields } = args;
1773
+ if (!fields.name?.trim() || !fields.prompt?.trim()) {
1774
+ return {
1775
+ content: JSON.stringify({
1776
+ success: false,
1777
+ error: "Для action=save нужны непустые name и prompt.",
1778
+ }),
1779
+ };
1780
+ }
1781
+ const template = await saveTemplate(fields as Omit<TaskTemplate, "id"> & { id?: string });
1782
+ return { content: JSON.stringify({ success: true, template }) };
1783
+ });
1784
+
1785
+ /** manage_profiles — список, создание, переключение и удаление профилей. */
1786
+ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
1787
+ if (args.action === "list") {
1788
+ return {
1789
+ content: JSON.stringify({
1790
+ success: true,
1791
+ current: getProfileName(),
1792
+ pinnedByEnv: isProfilePinnedByEnv(),
1793
+ profiles: listProfiles(),
1794
+ }),
1795
+ };
1796
+ }
1797
+
1798
+ const name = args.name?.trim();
1799
+ if (!name) {
1800
+ return {
1801
+ content: JSON.stringify({
1802
+ success: false,
1803
+ error: `Для action=${args.action} нужно имя профиля.`,
1804
+ }),
1805
+ };
1806
+ }
1807
+
1808
+ if (args.action === "create") {
1809
+ const meta = createProfile(name, args.port);
1810
+ const profile = listProfiles().find((item) => item.name === meta.name);
1811
+ return {
1812
+ content: JSON.stringify({
1813
+ success: true,
1814
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
1815
+ profile: profile ?? {
1816
+ name: meta.name,
1817
+ dir: getProfileDir(meta.name),
1818
+ port: meta.port,
1819
+ isDefault: meta.name === DEFAULT_PROFILE,
1820
+ active: meta.name === getProfileName(),
1821
+ },
1822
+ }),
1823
+ };
1824
+ }
1825
+
1826
+ if (args.action === "switch") {
1827
+ setActiveProfile(name);
1828
+ const current = getProfileName();
1829
+ return {
1830
+ content: JSON.stringify({
1831
+ success: true,
1832
+ current,
1833
+ restartRequired: true,
1834
+ message: isProfilePinnedByEnv()
1835
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
1836
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
1837
+ }),
1838
+ };
1839
+ }
1840
+
1841
+ const removed = deleteProfile(name);
1842
+ return {
1843
+ content: JSON.stringify({
1844
+ success: removed,
1845
+ message: removed
1846
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
1847
+ : "Профиль не найден.",
1848
+ }),
1849
+ };
1850
+ });
1851
+
1852
+ /** transfer_tasks — экспорт и импорт задач. */
1853
+ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
1854
+ if (args.action === "export") {
1855
+ const tasks = await scheduler.listTasks();
1856
+ const { data, count } = await buildExportJson(
1857
+ tasks.map((task) => ({ ...task, name: task.taskName || "" }))
1858
+ );
1859
+ return { content: JSON.stringify({ success: true, data, count }) };
1860
+ }
1861
+
1862
+ if (!args.data) {
1863
+ return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
1864
+ }
1865
+ const parsed = parseImportJson(args.data);
1866
+ if (parsed.tasks.length === 0) {
1867
+ return {
1868
+ content: JSON.stringify({
1869
+ success: false,
1870
+ error: "В данных нет задач для импорта.",
1871
+ errors: parsed.errors,
1872
+ }),
1873
+ };
1874
+ }
1875
+
1876
+ const imported: string[] = [];
1877
+ const errors: string[] = [...parsed.errors];
1878
+ for (const def of parsed.tasks) {
1879
+ try {
1880
+ await schedulerCreateTask(
1881
+ def.name,
1882
+ def.schedule,
1883
+ def.prompt,
1884
+ def.timeoutSeconds,
1885
+ def.workingDirectory ?? def.workdir,
1886
+ def.retryCount,
1887
+ def.retryDelay,
1888
+ def.qualityGate,
1889
+ def.nextTaskOnSuccess,
1890
+ def.nextTaskOnError,
1891
+ def.triggerType,
1892
+ def.watchPath,
1893
+ def.dependsOn,
1894
+ def.model,
1895
+ def.priority,
1896
+ def.beforeScript,
1897
+ def.afterScript,
1898
+ def.mcpEvent,
1899
+ def.workspaceId,
1900
+ def.allowedTools,
1901
+ def.deniedTools,
1902
+ def.matrix,
1903
+ def.matrixParentId,
1904
+ "create",
1905
+ def.timezone,
1906
+ def.notBefore,
1907
+ def.notAfter,
1908
+ def.pausedUntil
1909
+ );
1910
+ await saveTaskDefinition(def);
1911
+ imported.push(def.name);
1912
+ } catch (err: any) {
1913
+ errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
1914
+ }
1915
+ }
1916
+ await refreshFileTriggers();
1917
+ return {
1918
+ content: JSON.stringify({ success: errors.length === 0, imported, errors }),
1919
+ };
1920
+ });
1921
+
1922
+ /** send_notification — тестовое уведомление или дайджест. */
1923
+ const sendNotificationExecute = wrapExecute<NotificationArgs>(async (args) => {
1924
+ const result =
1925
+ args.action === "test"
1926
+ ? await sendTestNotification()
1927
+ : await sendDigestNow({ updateLastSentAt: false });
1928
+ return { content: JSON.stringify(result) };
1929
+ });
1930
+
1931
+ /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
1932
+ const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
1933
+ const port = getDashboardPort();
1934
+ return {
1935
+ content: JSON.stringify({
1936
+ success: true,
1937
+ port,
1938
+ url: port ? `http://127.0.0.1:${port}` : null,
1939
+ platform: scheduler.platform,
1940
+ title: scheduler.title,
1941
+ profile: getProfileName(),
1942
+ }),
1943
+ };
1944
+ });
1945
+
1946
+ /** cleanup_history — удаление старых записей истории. */
1947
+ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
1948
+ const report = await runHistoryRetention({
1949
+ retentionDays: args.retentionDays,
1950
+ maxRecords: args.maxRecords,
1951
+ });
1952
+ return {
1953
+ content: JSON.stringify({
1954
+ success: true,
1955
+ message: report.skipped
1956
+ ? report.skipped
1957
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
1958
+ report,
1959
+ }),
1960
+ };
1961
+ });
1962
+
1963
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
1964
+ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
1965
+ const eventName = args.eventName?.trim();
1966
+ if (!eventName) {
1967
+ return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
1968
+ }
1969
+ const payload = args.payload ?? {};
1970
+ const definitions = await loadTaskDefinitions();
1971
+ const matched = definitions
1972
+ .filter(
1973
+ (def) =>
1974
+ def.triggerType === "mcp-event" &&
1975
+ def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
1976
+ matchesEventFilter(def.mcpEvent?.filter, payload)
1977
+ )
1978
+ .sort(
1979
+ (a, b) =>
1980
+ (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0)
1981
+ );
1982
+
1983
+ const triggered: string[] = [];
1984
+ for (const def of matched) {
1985
+ try {
1986
+ await runTaskEntry(def.name);
1987
+ triggered.push(def.name);
1988
+ } catch (err: any) {
1989
+ console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
1990
+ }
1991
+ }
1992
+ return {
1993
+ content: JSON.stringify({
1994
+ success: true,
1995
+ message:
1996
+ triggered.length > 0
1997
+ ? `Запущено задач: ${triggered.length}.`
1998
+ : `Нет задач, подписанных на событие "${eventName}".`,
1999
+ triggered,
2000
+ }),
2001
+ };
2002
+ });
2003
+
2004
+ /**
2005
+ * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
2006
+ * обновлять после создания/изменения/удаления задачи. Раньше refresh()
2007
+ * вызывался только при старте плагина, из-за чего новые watchPath начинали
2008
+ * работать лишь после перезапуска OpenCode.
2009
+ */
2010
+ let fileWatcherManager: FileWatchManager | null = null;
2011
+
2012
+ async function refreshFileTriggers(): Promise<void> {
2013
+ if (!fileWatcherManager) return;
2014
+ try {
2015
+ await fileWatcherManager.refresh();
2016
+ } catch (err: any) {
2017
+ console.error(
2018
+ `[windows-scheduler] Не удалось обновить файловые триггеры: ${
2019
+ err instanceof Error ? err.message : String(err)
2020
+ }`
2021
+ );
2022
+ }
2023
+ }
2024
+
1222
2025
  export default Plugin.define({
1223
2026
  id: "opencode-windows-scheduler",
1224
2027
  setup: async (ctx) => {
@@ -1270,6 +2073,42 @@ export default Plugin.define({
1270
2073
  );
1271
2074
  });
1272
2075
 
2076
+ // Спринт 19: автопродолжение задач, поставленных на паузу до даты.
2077
+ // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
2078
+ void resumeExpiredPauses().catch((err: any) => {
2079
+ console.error(
2080
+ `[windows-scheduler] Не удалось проверить автопродолжение: ${
2081
+ err instanceof Error ? err.message : String(err)
2082
+ }`
2083
+ );
2084
+ });
2085
+ const pausedUntilTimer = setInterval(() => {
2086
+ void resumeExpiredPauses().catch((err: any) => {
2087
+ console.error(
2088
+ `[windows-scheduler] Не удалось проверить автопродолжение: ${
2089
+ err instanceof Error ? err.message : String(err)
2090
+ }`
2091
+ );
2092
+ });
2093
+ }, PAUSED_UNTIL_CHECK_MS);
2094
+ pausedUntilTimer.unref?.();
2095
+
2096
+ // Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
2097
+ // старте и далее раз в минуту; таймер не держит процесс Node живым.
2098
+ const notificationTimer = setInterval(() => {
2099
+ void maybeSendDigest().catch(() => undefined);
2100
+ void checkStuckMatrices().catch((err: any) => {
2101
+ console.error(
2102
+ `[windows-scheduler] Детектор зависших матриц: ${
2103
+ err instanceof Error ? err.message : String(err)
2104
+ }`
2105
+ );
2106
+ });
2107
+ }, NOTIFICATION_CHECK_MS);
2108
+ notificationTimer.unref?.();
2109
+ void maybeSendDigest().catch(() => undefined);
2110
+ void checkStuckMatrices().catch(() => undefined);
2111
+
1273
2112
  // Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
1274
2113
  const lockManager = new LockManager(LOCK_DIR);
1275
2114
  await lockManager.initialize();
@@ -1293,22 +2132,24 @@ export default Plugin.define({
1293
2132
  // Catch-up имеет смысл только для cron-задач.
1294
2133
  if ((def.triggerType ?? "cron") !== "cron") continue;
1295
2134
  if (!def.schedule) continue;
1296
- const prevRun = previousRunTime(def.schedule, now);
1297
- if (!prevRun) continue;
1298
- const ageMs = now.getTime() - prevRun.getTime();
2135
+ // Задача на паузе до даты — её включит авто-продолжение.
2136
+ if (def.pausedUntil) continue;
2137
+ const prev = prevRun(def.schedule, now, def.timezone);
2138
+ if (!prev) continue;
2139
+ const ageMs = now.getTime() - prev.getTime();
1299
2140
  if (ageMs < catchUpThresholdMs) continue;
1300
2141
 
1301
2142
  // Есть ли запись в истории после предполагаемого времени запуска?
1302
2143
  const ranAfter = history.some(
1303
2144
  (r) =>
1304
2145
  r.taskName.toLowerCase() === def.name.toLowerCase() &&
1305
- new Date(r.startedAt).getTime() >= prevRun.getTime()
2146
+ new Date(r.startedAt).getTime() >= prev.getTime()
1306
2147
  );
1307
2148
  if (ranAfter) continue;
1308
2149
 
1309
2150
  // Запускаем задачу и пишем в лог.
1310
2151
  try {
1311
- await scheduler.runTask(def.name);
2152
+ await runTaskEntry(def.name);
1312
2153
  console.log(
1313
2154
  `[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`
1314
2155
  );
@@ -1329,9 +2170,9 @@ export default Plugin.define({
1329
2170
 
1330
2171
  // Файловые триггеры (File Watchers): задачи с triggerType === "file"
1331
2172
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
1332
- const fileWatcherManager = new FileWatchManager(async (taskName) => {
2173
+ fileWatcherManager = new FileWatchManager(async (taskName) => {
1333
2174
  try {
1334
- await scheduler.runTask(taskName);
2175
+ await runTaskEntry(taskName);
1335
2176
  console.log(
1336
2177
  `[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`
1337
2178
  );
@@ -1343,7 +2184,7 @@ export default Plugin.define({
1343
2184
  );
1344
2185
  }
1345
2186
  });
1346
- void fileWatcherManager.refresh();
2187
+ void refreshFileTriggers();
1347
2188
 
1348
2189
  const registration = await ctx.tool.transform((editor) => {
1349
2190
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -1459,10 +2300,100 @@ export default Plugin.define({
1459
2300
  name: "matrix_control",
1460
2301
  input: matrixControlSchema,
1461
2302
  description:
1462
- "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones) or cleanup (delete orphaned clones and aggregators whose parent is gone).",
2303
+ "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones), cleanup (delete orphaned clones and aggregators whose parent is gone) or preview (expand a matrix config into clone names without creating anything).",
1463
2304
  options: { codemode: true },
1464
2305
  execute: matrixControlExecute as any,
1465
2306
  });
2307
+
2308
+ editor.add({
2309
+ name: "get_metrics",
2310
+ input: getMetricsSchema,
2311
+ description:
2312
+ "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
2313
+ options: { codemode: true },
2314
+ execute: getMetricsExecute as any,
2315
+ });
2316
+
2317
+ editor.add({
2318
+ name: "get_analytics",
2319
+ input: getAnalyticsSchema,
2320
+ description:
2321
+ "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
2322
+ options: { codemode: true },
2323
+ execute: getAnalyticsExecute as any,
2324
+ });
2325
+
2326
+ editor.add({
2327
+ name: "manage_settings",
2328
+ input: manageSettingsSchema,
2329
+ description:
2330
+ "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
2331
+ options: { codemode: true },
2332
+ execute: manageSettingsExecute as any,
2333
+ });
2334
+
2335
+ editor.add({
2336
+ name: "manage_templates",
2337
+ input: manageTemplatesSchema,
2338
+ description:
2339
+ "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2340
+ options: { codemode: true },
2341
+ execute: manageTemplatesExecute as any,
2342
+ });
2343
+
2344
+ editor.add({
2345
+ name: "manage_profiles",
2346
+ input: manageProfilesSchema,
2347
+ description:
2348
+ "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2349
+ options: { codemode: true },
2350
+ execute: manageProfilesExecute as any,
2351
+ });
2352
+
2353
+ editor.add({
2354
+ name: "transfer_tasks",
2355
+ input: transferTasksSchema,
2356
+ description:
2357
+ "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2358
+ options: { codemode: true },
2359
+ execute: transferTasksExecute as any,
2360
+ });
2361
+
2362
+ editor.add({
2363
+ name: "send_notification",
2364
+ input: sendNotificationSchema,
2365
+ description:
2366
+ "Sends a test notification through the configured channel or sends the digest immediately.",
2367
+ options: { codemode: true },
2368
+ execute: sendNotificationExecute as any,
2369
+ });
2370
+
2371
+ editor.add({
2372
+ name: "get_dashboard_info",
2373
+ input: getDashboardInfoSchema,
2374
+ description:
2375
+ "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
2376
+ options: { codemode: true },
2377
+ execute: getDashboardInfoExecute as any,
2378
+ });
2379
+
2380
+ editor.add({
2381
+ name: "cleanup_history",
2382
+ input: cleanupHistorySchema,
2383
+ description:
2384
+ "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2385
+ options: { codemode: true },
2386
+ execute: cleanupHistoryExecute as any,
2387
+ });
2388
+
2389
+ editor.add({
2390
+ name: "emit_event",
2391
+ input: emitEventSchema,
2392
+ description:
2393
+ "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
2394
+ options: { codemode: true },
2395
+ execute: emitEventExecute as any,
2396
+ });
1466
2397
  });
1467
2398
 
1468
2399
  // Нативный скилл плагина: агент видит краткое описание в списке доступных
@@ -1522,6 +2453,9 @@ export default Plugin.define({
1522
2453
  allowedTools,
1523
2454
  deniedTools,
1524
2455
  matrix,
2456
+ timezone,
2457
+ notBefore,
2458
+ notAfter,
1525
2459
  } = input as {
1526
2460
  name: string;
1527
2461
  schedule: string;
@@ -1544,6 +2478,9 @@ export default Plugin.define({
1544
2478
  allowedTools?: string[];
1545
2479
  deniedTools?: string[];
1546
2480
  matrix?: MatrixConfig;
2481
+ timezone?: string;
2482
+ notBefore?: string;
2483
+ notAfter?: string;
1547
2484
  };
1548
2485
  try {
1549
2486
  await schedulerCreateTask(
@@ -1568,7 +2505,12 @@ export default Plugin.define({
1568
2505
  workspaceId,
1569
2506
  allowedTools,
1570
2507
  deniedTools,
1571
- matrix
2508
+ matrix,
2509
+ undefined,
2510
+ "create",
2511
+ timezone,
2512
+ notBefore,
2513
+ notAfter
1572
2514
  );
1573
2515
  return { success: true, message: `Задача "${name}" успешно создана.` };
1574
2516
  } catch (err: any) {
@@ -1699,7 +2641,7 @@ export default Plugin.define({
1699
2641
  const triggered: string[] = [];
1700
2642
  for (const def of matched) {
1701
2643
  try {
1702
- await scheduler.runTask(def.name);
2644
+ await runTaskEntry(def.name);
1703
2645
  triggered.push(def.name);
1704
2646
  console.log(
1705
2647
  `[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`
@@ -1720,8 +2662,8 @@ export default Plugin.define({
1720
2662
  };
1721
2663
  },
1722
2664
  pause_task: async (input: unknown) => {
1723
- const { name } = input as { name: string };
1724
- const result = await pauseOrResumeTask(name, true);
2665
+ const { name, until } = input as { name: string; until?: string };
2666
+ const result = await pauseOrResumeTask(name, true, until);
1725
2667
  return { success: result.success, message: result.message };
1726
2668
  },
1727
2669
  resume_task: async (input: unknown) => {
@@ -1741,8 +2683,11 @@ export default Plugin.define({
1741
2683
  return { success: true, logs: result.logs };
1742
2684
  },
1743
2685
  get_history: async (input: unknown) => {
1744
- const { limit } = input as { limit?: number };
1745
- const records = await loadHistory();
2686
+ const { limit, taskName } = input as { limit?: number; taskName?: string };
2687
+ const filter = taskName?.trim().toLowerCase();
2688
+ const records = (await loadHistory()).filter(
2689
+ (record) => !filter || record.taskName.toLowerCase() === filter
2690
+ );
1746
2691
  return { records: records.slice(0, limit ?? 10) };
1747
2692
  },
1748
2693
  get_metrics: async () => {
@@ -1913,36 +2858,57 @@ export default Plugin.define({
1913
2858
  return {
1914
2859
  workspaces: listWorkspaces().map((workspace) => ({
1915
2860
  ...workspace,
2861
+ env: maskEnvForLog(workspace.env),
1916
2862
  gitBranch: readGitBranch(workspace.path) ?? null,
1917
2863
  })),
1918
2864
  };
1919
2865
  },
1920
2866
  add_workspace: async (input: unknown) => {
1921
2867
  try {
1922
- const { name, path: workspacePath, color } = input as {
2868
+ const { name, path: workspacePath, color, env, envFile } = input as {
1923
2869
  name?: string;
1924
2870
  path: string;
1925
2871
  color?: string;
2872
+ env?: Record<string, string> | null;
2873
+ envFile?: string | null;
2874
+ };
2875
+ const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
2876
+ return {
2877
+ success: true,
2878
+ workspace: {
2879
+ ...workspace,
2880
+ env: maskEnvForLog(workspace.env),
2881
+ gitBranch: readGitBranch(workspace.path) ?? null,
2882
+ },
1926
2883
  };
1927
- const workspace = addWorkspace({ name, path: workspacePath, color });
1928
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
1929
2884
  } catch (err: any) {
1930
2885
  return { success: false, error: err instanceof Error ? err.message : String(err) };
1931
2886
  }
1932
2887
  },
1933
2888
  update_workspace: async (input: unknown) => {
1934
2889
  try {
1935
- const { id, name, path: workspacePath, color } = input as {
2890
+ const { id, name, path: workspacePath, color, env, envFile } = input as {
1936
2891
  id: string;
1937
2892
  name?: string;
1938
2893
  path?: string;
1939
2894
  color?: string;
2895
+ env?: Record<string, string> | null;
2896
+ envFile?: string | null;
1940
2897
  };
1941
- const workspace = updateWorkspace(id, { name, path: workspacePath, color });
2898
+ const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
1942
2899
  if (!workspace) {
1943
2900
  return { success: false, error: "Workspace не найден." };
1944
2901
  }
1945
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
2902
+ // env-файлы существующих задач перегенерируются сразу (Спринт 21).
2903
+ await refreshWorkspaceEnvFiles(workspace.id);
2904
+ return {
2905
+ success: true,
2906
+ workspace: {
2907
+ ...workspace,
2908
+ env: maskEnvForLog(workspace.env),
2909
+ gitBranch: readGitBranch(workspace.path) ?? null,
2910
+ },
2911
+ };
1946
2912
  } catch (err: any) {
1947
2913
  return { success: false, error: err instanceof Error ? err.message : String(err) };
1948
2914
  }
@@ -1961,6 +2927,72 @@ export default Plugin.define({
1961
2927
  return { success: false, message: err instanceof Error ? err.message : String(err) };
1962
2928
  }
1963
2929
  },
2930
+ get_profiles: async () => {
2931
+ return {
2932
+ current: getProfileName(),
2933
+ pinnedByEnv: isProfilePinnedByEnv(),
2934
+ profiles: listProfiles(),
2935
+ };
2936
+ },
2937
+ set_profile: async (input: unknown) => {
2938
+ const { name } = input as { name: string };
2939
+ try {
2940
+ setActiveProfile(name);
2941
+ const current = getProfileName();
2942
+ return {
2943
+ success: true,
2944
+ current,
2945
+ restartRequired: true,
2946
+ message: isProfilePinnedByEnv()
2947
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
2948
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
2949
+ };
2950
+ } catch (err: any) {
2951
+ return {
2952
+ success: false,
2953
+ current: getProfileName(),
2954
+ restartRequired: false,
2955
+ message: err instanceof Error ? err.message : String(err),
2956
+ };
2957
+ }
2958
+ },
2959
+ create_profile: async (input: unknown) => {
2960
+ const { name, port } = input as { name: string; port?: number };
2961
+ try {
2962
+ const meta = createProfile(name, port);
2963
+ const profile = listProfiles().find((item) => item.name === meta.name);
2964
+ return {
2965
+ success: true,
2966
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2967
+ profile: profile ?? {
2968
+ name: meta.name,
2969
+ dir: getProfileDir(meta.name),
2970
+ port: meta.port,
2971
+ isDefault: meta.name === DEFAULT_PROFILE,
2972
+ active: meta.name === getProfileName(),
2973
+ },
2974
+ };
2975
+ } catch (err: any) {
2976
+ return {
2977
+ success: false,
2978
+ error: err instanceof Error ? err.message : String(err),
2979
+ };
2980
+ }
2981
+ },
2982
+ delete_profile: async (input: unknown) => {
2983
+ const { name } = input as { name: string };
2984
+ try {
2985
+ const removed = deleteProfile(name);
2986
+ return {
2987
+ success: removed,
2988
+ message: removed
2989
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2990
+ : "Профиль не найден.",
2991
+ };
2992
+ } catch (err: any) {
2993
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
2994
+ }
2995
+ },
1964
2996
  get_settings: async () => {
1965
2997
  return await loadSettings();
1966
2998
  },
@@ -2003,6 +3035,10 @@ export default Plugin.define({
2003
3035
  test_notification: async () => {
2004
3036
  return await sendTestNotification();
2005
3037
  },
3038
+ send_digest: async () => {
3039
+ // Ручная отправка не сдвигает плановое расписание дайджеста.
3040
+ return await sendDigestNow({ updateLastSentAt: false });
3041
+ },
2006
3042
  get_templates: async () => {
2007
3043
  try {
2008
3044
  return { templates: await loadTemplates() };
@@ -2115,7 +3151,12 @@ export default Plugin.define({
2115
3151
  def.allowedTools,
2116
3152
  def.deniedTools,
2117
3153
  def.matrix,
2118
- def.matrixParentId
3154
+ def.matrixParentId,
3155
+ "create",
3156
+ def.timezone,
3157
+ def.notBefore,
3158
+ def.notAfter,
3159
+ def.pausedUntil
2119
3160
  );
2120
3161
  await saveTaskDefinition(def);
2121
3162
  imported.push(def.name);
@@ -2164,10 +3205,12 @@ export default Plugin.define({
2164
3205
  }
2165
3206
 
2166
3207
  return () => {
3208
+ clearInterval(pausedUntilTimer);
3209
+ clearInterval(notificationTimer);
2167
3210
  rpcRegistration.dispose();
2168
3211
  registration.dispose();
2169
3212
  void skillRegistration?.dispose();
2170
- void fileWatcherManager.stop();
3213
+ if (fileWatcherManager) void fileWatcherManager.stop();
2171
3214
  // При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
2172
3215
  // затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
2173
3216
  void closeDashboardServer().finally(() => closeDb());
@@ -2262,12 +3305,24 @@ async function schedulerCreateTask(
2262
3305
  matrix?: MatrixConfig,
2263
3306
  matrixParentId?: string,
2264
3307
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
2265
- matrixMode: "create" | "sync" = "create"
3308
+ matrixMode: "create" | "sync" = "create",
3309
+ /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
3310
+ timezone?: string,
3311
+ /** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
3312
+ notBefore?: string,
3313
+ /** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
3314
+ notAfter?: string,
3315
+ /** Пауза до момента ISO; после него задача возобновляется автоматически. */
3316
+ pausedUntil?: string
2266
3317
  ): Promise<void> {
2267
3318
  const normalizedModel = model?.trim() || undefined;
2268
3319
  const normalizedPriority = normalizePriority(priority);
2269
3320
  const normalizedBefore = beforeScript?.trim() || undefined;
2270
3321
  const normalizedAfter = afterScript?.trim() || undefined;
3322
+ const normalizedTz = timezone?.trim() || undefined;
3323
+ const normalizedNotBefore = notBefore?.trim() || undefined;
3324
+ const normalizedNotAfter = notAfter?.trim() || undefined;
3325
+ const normalizedPausedUntil = pausedUntil?.trim() || undefined;
2271
3326
  const normalizedMcpEvent =
2272
3327
  mcpEvent && mcpEvent.event?.trim()
2273
3328
  ? {
@@ -2358,15 +3413,49 @@ async function schedulerCreateTask(
2358
3413
  // расписание не используется вовсе.
2359
3414
  if (effectiveTriggerType === "cron") {
2360
3415
  try {
2361
- convertCronToSchTasks(schedule);
3416
+ // Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
3417
+ // имена месяцев/дней, @every, L и FRI#3.
3418
+ parseCron(schedule);
2362
3419
  } catch (err: any) {
2363
3420
  throw new Error(err.message || String(err));
2364
3421
  }
3422
+ if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
3423
+ throw new Error(
3424
+ `Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
3425
+ `Укажите IANA-зону, например Europe/Moscow.`
3426
+ );
3427
+ }
3428
+ const windowError = validateLaunchWindow(
3429
+ normalizedNotBefore,
3430
+ normalizedNotAfter
3431
+ );
3432
+ if (windowError) {
3433
+ throw new Error(`Задача "${name}": ${windowError}`);
3434
+ }
2365
3435
  }
2366
3436
 
2367
3437
  const sanitized = sanitizeName(name);
2368
3438
  const lockFile = lockFilePath(sanitized);
2369
3439
  const logFile = path.join(LOG_DIR, `${sanitized}.log`);
3440
+ // Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
3441
+ // (нестандартный cron или чужая IANA-зона) либо при окне запуска.
3442
+ const gate =
3443
+ effectiveTriggerType === "cron"
3444
+ ? buildScheduleGate(
3445
+ schedule,
3446
+ normalizedTz,
3447
+ normalizedNotBefore,
3448
+ normalizedNotAfter
3449
+ )
3450
+ : undefined;
3451
+ const wrapperGate = gate
3452
+ ? {
3453
+ ...gate,
3454
+ gateFile: gatePath,
3455
+ deferFile: `${lockFile}.defer`,
3456
+ forceFile: `${lockFile}.force`,
3457
+ }
3458
+ : undefined;
2370
3459
  // Workspace имеет приоритет над workingDirectory: одна задача = один repo
2371
3460
  // = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
2372
3461
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
@@ -2390,6 +3479,13 @@ async function schedulerCreateTask(
2390
3479
  const effectiveWorkingDirectory =
2391
3480
  workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
2392
3481
 
3482
+ // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
3483
+ // Значения не логируются; в лог попадает только факт загрузки.
3484
+ const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
3485
+ if (taskEnvFile) {
3486
+ console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
3487
+ }
3488
+
2393
3489
  let promptFile: string;
2394
3490
  try {
2395
3491
  promptFile = await writePromptFile(sanitized, prompt);
@@ -2421,7 +3517,9 @@ async function schedulerCreateTask(
2421
3517
  normalizedAfter,
2422
3518
  workspace?.name,
2423
3519
  normalizedAllowedTools,
2424
- normalizedDeniedTools
3520
+ normalizedDeniedTools,
3521
+ wrapperGate,
3522
+ taskEnvFile
2425
3523
  );
2426
3524
  } else {
2427
3525
  wrapperPath = await writeBashWrapper({
@@ -2440,6 +3538,8 @@ async function schedulerCreateTask(
2440
3538
  workspaceName: workspace?.name,
2441
3539
  allowedTools: normalizedAllowedTools,
2442
3540
  deniedTools: normalizedDeniedTools,
3541
+ scheduleGate: wrapperGate,
3542
+ envFile: taskEnvFile,
2443
3543
  });
2444
3544
  }
2445
3545
  } catch (err: any) {
@@ -2458,6 +3558,9 @@ async function schedulerCreateTask(
2458
3558
  logFile,
2459
3559
  model: normalizedModel,
2460
3560
  priority: normalizedPriority,
3561
+ timezone: normalizedTz,
3562
+ notBefore: normalizedNotBefore,
3563
+ notAfter: normalizedNotAfter,
2461
3564
  });
2462
3565
  } catch (err: any) {
2463
3566
  throw new Error(err instanceof Error ? err.message : String(err));
@@ -2484,6 +3587,10 @@ async function schedulerCreateTask(
2484
3587
  nextTaskOnError,
2485
3588
  triggerType: effectiveTriggerType,
2486
3589
  watchPath: normalizedMatrix ? undefined : watchPath,
3590
+ timezone: normalizedTz,
3591
+ notBefore: normalizedNotBefore,
3592
+ notAfter: normalizedNotAfter,
3593
+ pausedUntil: normalizedPausedUntil,
2487
3594
  allowedTools: normalizedAllowedTools,
2488
3595
  deniedTools: normalizedDeniedTools,
2489
3596
  matrix: normalizedMatrix,
@@ -2540,7 +3647,12 @@ async function schedulerCreateTask(
2540
3647
  clone.allowedTools,
2541
3648
  clone.deniedTools,
2542
3649
  undefined,
2543
- name
3650
+ name,
3651
+ "create",
3652
+ clone.timezone,
3653
+ clone.notBefore,
3654
+ clone.notAfter,
3655
+ clone.pausedUntil
2544
3656
  );
2545
3657
  };
2546
3658
 
@@ -2633,7 +3745,22 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
2633
3745
  await runMatrix(definition);
2634
3746
  return { alreadyRunning: false };
2635
3747
  }
2636
- return scheduler.runTask(name);
3748
+
3749
+ // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
3750
+ // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
3751
+ // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
3752
+ // запуск молча отменялся бы schedule-gate с кодом 3.
3753
+ const forceFile = await requestImmediateRun(name);
3754
+ try {
3755
+ return await scheduler.runTask(name);
3756
+ } catch (err) {
3757
+ // Планировщик не принял запуск — маркер не нужен, иначе он мог бы
3758
+ // «разрешить» следующий плановый тик в обход расписания.
3759
+ await fs.unlink(forceFile).catch(() => {
3760
+ /* не критично */
3761
+ });
3762
+ throw err;
3763
+ }
2637
3764
  }
2638
3765
 
2639
3766
  /**
@@ -2658,7 +3785,39 @@ async function collectTasksView() {
2658
3785
  const workspaces = listWorkspaces();
2659
3786
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
2660
3787
 
2661
- return tasks.map((t) => {
3788
+ // Счётчики запусков по задачам. Основной источник — таблица metrics
3789
+ // (накопительные итоги, не зависят от retention истории). Для задач, у
3790
+ // которых метрик ещё нет, считаем по загруженной истории.
3791
+ const metricsByName = new Map(
3792
+ getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row])
3793
+ );
3794
+ const historyCounts = new Map<string, { total: number; success: number; error: number }>();
3795
+ for (const record of history) {
3796
+ const key = record.taskName.toLowerCase();
3797
+ const counts = historyCounts.get(key) ?? { total: 0, success: 0, error: 0 };
3798
+ counts.total += 1;
3799
+ if (record.status === "success") counts.success += 1;
3800
+ else counts.error += 1;
3801
+ historyCounts.set(key, counts);
3802
+ }
3803
+
3804
+ // ОС-планировщик — источник истины о запуске, но определения в БД могут
3805
+ // существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
3806
+ // Показываем и их, помечая orphaned: раньше такие задачи были невидимы
3807
+ // для list_tasks, хотя dry_run/история их видели.
3808
+ const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
3809
+ const orphanNames = defs
3810
+ .filter((def) => !osNames.has(def.name.toLowerCase()))
3811
+ .map((def) => def.name);
3812
+ const sources: Array<{ task: (typeof tasks)[number]; orphaned: boolean }> = [
3813
+ ...tasks.map((task) => ({ task, orphaned: false })),
3814
+ ...orphanNames.map((name) => ({
3815
+ task: { taskName: name } as (typeof tasks)[number],
3816
+ orphaned: true,
3817
+ })),
3818
+ ];
3819
+
3820
+ return sources.map(({ task: t, orphaned }) => {
2662
3821
  // Все бэкенды возвращают короткие имена (без папки планировщика).
2663
3822
  const name = t.taskName || "";
2664
3823
 
@@ -2682,10 +3841,21 @@ async function collectTasksView() {
2682
3841
  status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
2683
3842
  }
2684
3843
 
3844
+ // Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
3845
+ // общие итоги по всем задачам — отсюда одинаковые 201/130/71).
3846
+ const metricsRow = metricsByName.get(name.toLowerCase());
3847
+ const counts = metricsRow
3848
+ ? { total: metricsRow.total, success: metricsRow.success, error: metricsRow.error }
3849
+ : historyCounts.get(name.toLowerCase()) ?? { total: 0, success: 0, error: 0 };
3850
+
2685
3851
  return {
2686
3852
  name,
2687
3853
  schedule: def?.schedule ?? "",
2688
3854
  status,
3855
+ orphaned,
3856
+ runsTotal: counts.total,
3857
+ runsSuccess: counts.success,
3858
+ runsError: counts.error,
2689
3859
  nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
2690
3860
  model: def?.model ?? null,
2691
3861
  priority: def?.priority ?? 5,
@@ -2700,6 +3870,10 @@ async function collectTasksView() {
2700
3870
  dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
2701
3871
  triggerType: def?.triggerType ?? "cron",
2702
3872
  watchPath: def?.watchPath ?? null,
3873
+ timezone: def?.timezone ?? null,
3874
+ notBefore: def?.notBefore ?? null,
3875
+ notAfter: def?.notAfter ?? null,
3876
+ pausedUntil: def?.pausedUntil ?? null,
2703
3877
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
2704
3878
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
2705
3879
  workspaceName: workspace?.name ?? null,