opencode-windows-scheduler 1.0.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 (93) hide show
  1. package/CHANGELOG.md +58 -7
  2. package/README.md +14 -4
  3. package/README.ru.md +14 -4
  4. package/ROADMAP.md +30 -20
  5. package/dist/core/analytics.d.ts +129 -0
  6. package/dist/core/analytics.d.ts.map +1 -0
  7. package/dist/core/analytics.js +286 -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/retention.d.ts +29 -0
  17. package/dist/core/retention.d.ts.map +1 -0
  18. package/dist/core/retention.js +98 -0
  19. package/dist/core/schedule-gate.d.ts +2 -0
  20. package/dist/core/schedule-gate.d.ts.map +1 -0
  21. package/dist/core/schedule-gate.js +182 -0
  22. package/dist/core/schedule-v2.d.ts +88 -0
  23. package/dist/core/schedule-v2.d.ts.map +1 -0
  24. package/dist/core/schedule-v2.js +496 -0
  25. package/dist/core/scheduler/types.d.ts +15 -0
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/scheduler/windows.d.ts.map +1 -1
  28. package/dist/core/scheduler/windows.js +13 -1
  29. package/dist/core/wrappers/bash.d.ts +15 -0
  30. package/dist/core/wrappers/bash.d.ts.map +1 -1
  31. package/dist/core/wrappers/bash.js +44 -1
  32. package/dist/db/history-repo.d.ts +41 -0
  33. package/dist/db/history-repo.d.ts.map +1 -1
  34. package/dist/db/history-repo.js +78 -0
  35. package/dist/db/schema.d.ts +1 -1
  36. package/dist/db/schema.d.ts.map +1 -1
  37. package/dist/db/schema.js +11 -0
  38. package/dist/index.d.ts +117 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1094 -56
  41. package/dist/notifications.d.ts +112 -6
  42. package/dist/notifications.d.ts.map +1 -1
  43. package/dist/notifications.js +396 -34
  44. package/dist/profiles.d.ts +60 -0
  45. package/dist/profiles.d.ts.map +1 -0
  46. package/dist/profiles.js +209 -0
  47. package/dist/rpc.d.ts +645 -0
  48. package/dist/rpc.d.ts.map +1 -1
  49. package/dist/rpc.js +251 -2
  50. package/dist/server.d.ts.map +1 -1
  51. package/dist/server.js +200 -7
  52. package/dist/settings.d.ts +80 -0
  53. package/dist/settings.d.ts.map +1 -1
  54. package/dist/settings.js +159 -8
  55. package/dist/task-transfer.d.ts +13 -0
  56. package/dist/task-transfer.d.ts.map +1 -1
  57. package/dist/task-transfer.js +26 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js +3 -11
  60. package/dist/version.d.ts +8 -0
  61. package/dist/version.d.ts.map +1 -0
  62. package/dist/version.js +27 -0
  63. package/dist/workspaces.d.ts +43 -0
  64. package/dist/workspaces.d.ts.map +1 -1
  65. package/dist/workspaces.js +174 -8
  66. package/docs/ARCHITECTURE.md +45 -13
  67. package/docs/FEATURES.md +103 -12
  68. package/gui-experimental.cjs +4 -2
  69. package/package.json +8 -2
  70. package/src/core/analytics.ts +414 -0
  71. package/src/core/dry-run.ts +42 -0
  72. package/src/core/matrix.ts +10 -0
  73. package/src/core/ps-wrapper.ts +117 -3
  74. package/src/core/retention.ts +141 -0
  75. package/src/core/schedule-gate.ts +213 -0
  76. package/src/core/schedule-v2.ts +533 -0
  77. package/src/core/scheduler/types.ts +15 -0
  78. package/src/core/scheduler/windows.ts +13 -1
  79. package/src/core/wrappers/bash.ts +60 -0
  80. package/src/db/history-repo.ts +116 -0
  81. package/src/db/schema.ts +14 -0
  82. package/src/gui.tsx +3613 -2725
  83. package/src/index.ts +1325 -55
  84. package/src/notifications.ts +516 -40
  85. package/src/profiles.ts +236 -0
  86. package/src/rpc.ts +267 -2
  87. package/src/server.ts +226 -7
  88. package/src/settings.ts +285 -9
  89. package/src/task-transfer.ts +44 -0
  90. package/src/types.ts +3 -13
  91. package/src/version.ts +27 -0
  92. package/src/workspaces.ts +214 -8
  93. package/dist/gui-experimental.cjs +0 -1
package/dist/index.js CHANGED
@@ -5,9 +5,9 @@ import { existsSync } from "node:fs";
5
5
  import fs from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { LockManager } from "./core/lock.js";
8
- import { LOCK_DIR, LOG_DIR, sanitizeName } from "./types.js";
9
- import { convertCronToSchTasks, previousRunTime } from "./core/cron-to-schtasks.js";
10
- import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath } from "./core/ps-wrapper.js";
8
+ import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
9
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
10
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
11
11
  import { getSchedulerBackend } from "./core/scheduler/index.js";
12
12
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
13
13
  import { getTaskLogs } from "./core/scheduler/logs.js";
@@ -17,16 +17,21 @@ import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, fi
17
17
  import { SchedulerRpc } from "./rpc.js";
18
18
  import { loadHistory, loadMetrics } from "./history.js";
19
19
  import { loadSettings, saveSettings } from "./settings.js";
20
- import { sendTestNotification } from "./notifications.js";
20
+ import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
21
+ import { buildAnalytics } from "./core/analytics.js";
22
+ import { getHistory, listRunningRecords } from "./db/history-repo.js";
23
+ import { getAllMetrics } from "./db/metrics-repo.js";
24
+ import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
21
25
  import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
22
26
  import { FileWatchManager } from "./core/file-watcher.js";
23
27
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
24
28
  import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
29
+ import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
25
30
  import { closeDb, initDb } from "./db/index.js";
26
31
  import { migrateJsonToDb } from "./db/migrate.js";
27
32
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
28
- import { getTask, listMatrixClones } from "./db/tasks-repo.js";
29
- import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, } from "./workspaces.js";
33
+ import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
34
+ import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
30
35
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
31
36
  const require = createRequire(import.meta.url);
32
37
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -47,6 +52,23 @@ const recorderPath = (() => {
47
52
  `${distPath}. История/метрики не будут записываться. Выполните npm run build.`);
48
53
  return distPath;
49
54
  })();
55
+ /**
56
+ * Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
57
+ * перед opencode и выходит, если cron не сработал или запуск перенесён.
58
+ */
59
+ const gatePath = (() => {
60
+ const resolved = require.resolve("./core/schedule-gate.js");
61
+ if (!resolved.endsWith(".ts"))
62
+ return resolved;
63
+ const distPath = resolved
64
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
65
+ .replace(/\.ts$/, ".js");
66
+ if (existsSync(distPath))
67
+ return distPath;
68
+ console.warn("[windows-scheduler] Не найден собранный schedule-gate.js: " +
69
+ `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`);
70
+ return distPath;
71
+ })();
50
72
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
51
73
  const scheduler = getSchedulerBackend();
52
74
  /** Per-workspace overrides for matrix clones (Sprint 17). */
@@ -92,7 +114,19 @@ export const scheduleTaskSchema = z.object({
92
114
  name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
93
115
  schedule: z
94
116
  .string()
95
- .describe("5-field cron expression (minute hour day-of-month month day-of-week). Supported patterns: * * * * *, */N * * * *, M H * * *, M H * * D."),
117
+ .describe("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."),
118
+ timezone: z
119
+ .string()
120
+ .optional()
121
+ .describe("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)."),
122
+ notBefore: z
123
+ .string()
124
+ .optional()
125
+ .describe("Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."),
126
+ notAfter: z
127
+ .string()
128
+ .optional()
129
+ .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
96
130
  prompt: z
97
131
  .string()
98
132
  .describe("Prompt passed to the agent on every run."),
@@ -152,6 +186,10 @@ export const scheduleTaskSchema = z.object({
152
186
  })
153
187
  .optional()
154
188
  .describe("MCP event trigger: server, event name and an optional filter (key=value or regex)."),
189
+ watchPath: z
190
+ .string()
191
+ .optional()
192
+ .describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
155
193
  workingDirectory: z
156
194
  .string()
157
195
  .optional()
@@ -184,7 +222,19 @@ export const updateTaskSchema = z.object({
184
222
  schedule: z
185
223
  .string()
186
224
  .optional()
187
- .describe("New 5-field cron expression. Keeps the current value when omitted."),
225
+ .describe("New cron expression. Keeps the current value when omitted."),
226
+ timezone: z
227
+ .string()
228
+ .optional()
229
+ .describe("New IANA timezone. Empty string clears it (system timezone)."),
230
+ notBefore: z
231
+ .string()
232
+ .optional()
233
+ .describe("New launch window start HH:MM. Empty string clears the window."),
234
+ notAfter: z
235
+ .string()
236
+ .optional()
237
+ .describe("New launch window end HH:MM. Empty string clears the window."),
188
238
  prompt: z
189
239
  .string()
190
240
  .optional()
@@ -260,6 +310,10 @@ export const updateTaskSchema = z.object({
260
310
  });
261
311
  const pauseTaskSchema = z.object({
262
312
  name: z.string().describe("Task name to pause."),
313
+ until: z
314
+ .string()
315
+ .optional()
316
+ .describe("Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."),
263
317
  });
264
318
  const resumeTaskSchema = z.object({
265
319
  name: z.string().describe("Task name to resume."),
@@ -299,15 +353,152 @@ const manageWorkspacesSchema = z.object({
299
353
  name: z.string().optional().describe("Workspace display name (add/update)."),
300
354
  path: z.string().optional().describe("Absolute workspace path (add/update)."),
301
355
  color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
356
+ env: z
357
+ .record(z.string(), z.string())
358
+ .nullable()
359
+ .optional()
360
+ .describe("Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."),
361
+ envFile: z
362
+ .string()
363
+ .nullable()
364
+ .optional()
365
+ .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
302
366
  });
303
367
  export const matrixControlSchema = z.object({
304
368
  action: z
305
- .enum(["results", "cancel", "cleanup"])
306
- .describe("results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."),
369
+ .enum(["results", "cancel", "cleanup", "preview"])
370
+ .describe("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."),
307
371
  name: z
308
372
  .string()
309
373
  .optional()
310
- .describe("Matrix parent name (required for results and cancel)."),
374
+ .describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
375
+ workspaceIds: z
376
+ .array(z.string())
377
+ .optional()
378
+ .describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
379
+ strategy: z
380
+ .enum(["parallel", "sequential"])
381
+ .optional()
382
+ .describe("Preview only: clone execution strategy."),
383
+ failureMode: z
384
+ .enum(["continue", "stop"])
385
+ .optional()
386
+ .describe("Preview only: what to do when one clone fails."),
387
+ aggregation: z
388
+ .enum(["summary", "per-task"])
389
+ .optional()
390
+ .describe("Preview only: how clone results are aggregated."),
391
+ });
392
+ /** get_metrics — общая статистика запусков. */
393
+ export const getMetricsSchema = z.object({});
394
+ /** get_analytics — аналитика за период. */
395
+ export const getAnalyticsSchema = z.object({
396
+ days: z
397
+ .number()
398
+ .int()
399
+ .min(1)
400
+ .max(365)
401
+ .optional()
402
+ .describe("Analysis window in days (default 14)."),
403
+ topLimit: z
404
+ .number()
405
+ .int()
406
+ .min(1)
407
+ .max(50)
408
+ .optional()
409
+ .describe("How many top tasks to include (default 10)."),
410
+ });
411
+ /** manage_settings — глобальные настройки планировщика. */
412
+ export const manageSettingsSchema = z.object({
413
+ action: z
414
+ .enum(["get", "update"])
415
+ .describe("get — current settings; update — merge the provided fields and save."),
416
+ maxConcurrent: z
417
+ .number()
418
+ .int()
419
+ .min(1)
420
+ .max(16)
421
+ .optional()
422
+ .describe("How many task runs may execute at the same time."),
423
+ winterMode: z
424
+ .boolean()
425
+ .optional()
426
+ .describe("Winter mode: gentler scheduling of deferred runs."),
427
+ notifications: z
428
+ .any()
429
+ .optional()
430
+ .describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
431
+ history: z
432
+ .object({
433
+ retentionDays: z.number().int().min(1).max(3650).optional(),
434
+ maxRecords: z.number().int().min(100).max(1000000).optional(),
435
+ })
436
+ .optional()
437
+ .describe("History retention policy."),
438
+ });
439
+ /** manage_templates — пользовательские шаблоны задач. */
440
+ export const manageTemplatesSchema = z.object({
441
+ action: z
442
+ .enum(["list", "save", "delete"])
443
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
444
+ id: z.string().optional().describe("Template id for update/delete."),
445
+ name: z.string().optional().describe("Template name."),
446
+ prompt: z.string().optional().describe("Prompt text stored in the template."),
447
+ schedule: z.string().optional().describe("Cron expression."),
448
+ timeoutSeconds: z.number().int().positive().optional(),
449
+ model: z.string().optional(),
450
+ priority: z.number().int().min(0).max(10).optional(),
451
+ retryCount: z.number().int().min(0).optional(),
452
+ retryDelay: z.number().int().min(0).optional(),
453
+ qualityGate: z.string().optional(),
454
+ beforeScript: z.string().optional(),
455
+ afterScript: z.string().optional(),
456
+ nextTaskOnSuccess: z.string().optional(),
457
+ nextTaskOnError: z.string().optional(),
458
+ dependsOn: z.array(z.string()).optional(),
459
+ triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
460
+ mcpEvent: z
461
+ .object({
462
+ server: z.string(),
463
+ event: z.string(),
464
+ filter: z.string().optional(),
465
+ })
466
+ .optional(),
467
+ watchPath: z.string().optional(),
468
+ workingDirectory: z.string().optional(),
469
+ allowedTools: z.array(z.string()).optional(),
470
+ deniedTools: z.array(z.string()).optional(),
471
+ });
472
+ /** manage_profiles — изолированные профили планировщика. */
473
+ export const manageProfilesSchema = z.object({
474
+ action: z
475
+ .enum(["list", "create", "switch", "delete"])
476
+ .describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
477
+ name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
478
+ port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
479
+ });
480
+ /** transfer_tasks — экспорт и импорт задач. */
481
+ export const transferTasksSchema = z.object({
482
+ action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
483
+ data: z.string().optional().describe("JSON produced by export (required for import)."),
484
+ });
485
+ /** send_notification — проверка уведомлений и дайджест. */
486
+ export const sendNotificationSchema = z.object({
487
+ action: z
488
+ .enum(["test", "digest"])
489
+ .describe("test — send a test message through the configured channel; digest — send the digest now."),
490
+ });
491
+ /** get_dashboard_info — сведения о панели управления. */
492
+ export const getDashboardInfoSchema = z.object({});
493
+ /** cleanup_history — удаление старой истории. */
494
+ export const cleanupHistorySchema = z.object({
495
+ retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
496
+ maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
497
+ });
498
+ /** emit_event — запуск задач по MCP-событию. */
499
+ export const emitEventSchema = z.object({
500
+ eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
501
+ payload: z.any().optional().describe("Event payload passed to trigger filters."),
311
502
  });
312
503
  /**
313
504
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -336,9 +527,9 @@ function wrapExecute(fn) {
336
527
  }
337
528
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
338
529
  const scheduleTaskExecute = wrapExecute(async (args) => {
339
- const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, } = args;
530
+ const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, } = args;
340
531
  try {
341
- await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, undefined, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
532
+ await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter);
342
533
  }
343
534
  catch (err) {
344
535
  return {
@@ -348,6 +539,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
348
539
  }),
349
540
  };
350
541
  }
542
+ // Новый файловый триггер должен начать работать сразу, без перезапуска
543
+ // OpenCode: пересобираем набор watcher-ов после создания задачи.
544
+ await refreshFileTriggers();
351
545
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
352
546
  const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
353
547
  return {
@@ -369,6 +563,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
369
563
  nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
370
564
  nextTaskOnError: nextTaskOnError?.trim() || null,
371
565
  triggerType: triggerType ?? "cron",
566
+ timezone: timezone?.trim() || null,
567
+ notBefore: notBefore?.trim() || null,
568
+ notAfter: notAfter?.trim() || null,
372
569
  mcpEvent: mcpEvent ?? null,
373
570
  workingDirectory: effectiveWorkdir,
374
571
  workspaceId: workspace?.id ?? null,
@@ -425,7 +622,7 @@ async function cancelMatrixRun(name) {
425
622
  }
426
623
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
427
624
  try {
428
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name);
625
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
429
626
  }
430
627
  catch (err) {
431
628
  warnings.push(`${clone.name}: не удалось пересоздать — ${err instanceof Error ? err.message : String(err)}`);
@@ -488,6 +685,20 @@ async function deleteTaskWithFamily(name) {
488
685
  throw new Error(guard);
489
686
  const plan = planMatrixFamilyDelete(trimmed);
490
687
  const removed = [];
688
+ // Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
689
+ // отвечал success даже на имя, которого никогда не существовало.
690
+ let existed = Boolean(getTask(trimmed));
691
+ if (!existed) {
692
+ try {
693
+ const osTasks = await scheduler.listTasks();
694
+ existed = osTasks.some((task) => task.taskName.toLowerCase() === trimmed.toLowerCase());
695
+ }
696
+ catch {
697
+ // ОС-планировщик недоступен — довольствуемся данными БД.
698
+ }
699
+ }
700
+ if (plan && plan.children.length > 0)
701
+ existed = true;
491
702
  if (plan) {
492
703
  for (const child of plan.children) {
493
704
  try {
@@ -512,13 +723,23 @@ async function deleteTaskWithFamily(name) {
512
723
  catch {
513
724
  // Определения могло уже не быть — задача всё равно удалена из ОС.
514
725
  }
515
- return { removed };
726
+ return { removed, existed };
516
727
  }
517
728
  /** delete_task — удаление задачи по имени (/f) */
518
729
  const deleteTaskExecute = wrapExecute(async (args) => {
519
730
  const { name } = args;
520
731
  try {
521
- const { removed } = await deleteTaskWithFamily(name);
732
+ const { removed, existed } = await deleteTaskWithFamily(name);
733
+ // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
734
+ await refreshFileTriggers();
735
+ if (!existed && removed.length === 0) {
736
+ return {
737
+ content: JSON.stringify({
738
+ success: false,
739
+ error: `Задача "${name}" не найдена — удалять нечего.`,
740
+ }),
741
+ };
742
+ }
522
743
  return {
523
744
  content: JSON.stringify({
524
745
  success: true,
@@ -542,7 +763,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
542
763
  const { name } = args;
543
764
  let alreadyRunning = false;
544
765
  try {
545
- const result = await scheduler.runTask(name);
766
+ const result = await runTaskEntry(name);
546
767
  alreadyRunning = result.alreadyRunning;
547
768
  }
548
769
  catch (err) {
@@ -614,6 +835,9 @@ async function updateTaskFromInput(input) {
614
835
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
615
836
  const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
616
837
  const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
838
+ const timezone = clearableString(input.timezone, previous.timezone);
839
+ const notBefore = clearableString(input.notBefore, previous.notBefore);
840
+ const notAfter = clearableString(input.notAfter, previous.notAfter);
617
841
  if (triggerType === "cron" && !schedule) {
618
842
  return {
619
843
  success: false,
@@ -634,11 +858,14 @@ async function updateTaskFromInput(input) {
634
858
  await schedulerCreateTask(name, schedule ?? "* * * * *", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
635
859
  // Если задача была матрицей — синхронизируем клонов, а не
636
860
  // пересоздаём их с нуля (Спринт 17).
637
- matrixWas && matrixNext ? "sync" : "create");
861
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil);
638
862
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
639
863
  if (matrixWas && !matrixNext) {
640
864
  await removeMatrixChildrenFromScheduler(name);
641
865
  }
866
+ // Пересоздание могло изменить triggerType/watchPath — сразу
867
+ // пересобираем набор файловых watcher-ов.
868
+ await refreshFileTriggers();
642
869
  return { success: true, message: `Задача "${name}" обновлена.` };
643
870
  }
644
871
  catch (err) {
@@ -657,7 +884,7 @@ const updateTaskExecute = wrapExecute(async (args) => {
657
884
  * Пауза/возобновление задачи. Для матрицы операция применяется ко всем
658
885
  * клонам: сам родитель никогда не выполняется.
659
886
  */
660
- async function pauseOrResumeTask(name, paused) {
887
+ async function pauseOrResumeTask(name, paused, until) {
661
888
  const trimmed = name.trim();
662
889
  const definition = getTask(trimmed);
663
890
  if (!definition) {
@@ -668,6 +895,28 @@ async function pauseOrResumeTask(name, paused) {
668
895
  warnings: [],
669
896
  };
670
897
  }
898
+ // Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
899
+ let pausedUntil;
900
+ if (paused && until?.trim()) {
901
+ const parsed = Date.parse(until.trim());
902
+ if (Number.isNaN(parsed)) {
903
+ return {
904
+ success: false,
905
+ message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
906
+ affected: [],
907
+ warnings: [],
908
+ };
909
+ }
910
+ if (parsed <= Date.now()) {
911
+ return {
912
+ success: false,
913
+ message: `Задача "${trimmed}": дата паузы уже прошла.`,
914
+ affected: [],
915
+ warnings: [],
916
+ };
917
+ }
918
+ pausedUntil = new Date(parsed).toISOString();
919
+ }
671
920
  const targets = definition.matrix
672
921
  ? listMatrixClones(trimmed).map((clone) => clone.name)
673
922
  : [trimmed];
@@ -695,11 +944,31 @@ async function pauseOrResumeTask(name, paused) {
695
944
  warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
696
945
  }
697
946
  }
947
+ // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
948
+ // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
949
+ const definitionUpdates = paused
950
+ ? pausedUntil
951
+ ? { pausedUntil }
952
+ : undefined
953
+ : definition.pausedUntil
954
+ ? { pausedUntil: undefined }
955
+ : undefined;
956
+ if (definitionUpdates && affected.length > 0) {
957
+ try {
958
+ saveTask({ ...definition, ...definitionUpdates });
959
+ }
960
+ catch (err) {
961
+ warnings.push(`не удалось сохранить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
962
+ }
963
+ }
964
+ const untilText = pausedUntil
965
+ ? ` до ${new Date(pausedUntil).toLocaleString()}`
966
+ : "";
698
967
  const verb = paused ? "поставлена на паузу" : "возобновлена";
699
968
  const message = definition.matrix
700
- ? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
969
+ ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
701
970
  (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
702
- : `Задача "${trimmed}" ${verb}.` +
971
+ : `Задача "${trimmed}" ${verb}${untilText}.` +
703
972
  (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
704
973
  return {
705
974
  success: warnings.length === 0,
@@ -709,13 +978,90 @@ async function pauseOrResumeTask(name, paused) {
709
978
  };
710
979
  }
711
980
  const pauseTaskExecute = wrapExecute(async (args) => {
712
- const result = await pauseOrResumeTask(args.name, true);
981
+ const result = await pauseOrResumeTask(args.name, true, args.until);
713
982
  return { content: JSON.stringify(result) };
714
983
  });
715
984
  const resumeTaskExecute = wrapExecute(async (args) => {
716
985
  const result = await pauseOrResumeTask(args.name, false);
717
986
  return { content: JSON.stringify(result) };
718
987
  });
988
+ /** Периодичность проверки автопродолжения задач (Спринт 19). */
989
+ const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
990
+ /** Период проверки дайджеста и зависших матриц (Спринт 20). */
991
+ const NOTIFICATION_CHECK_MS = 60 * 1000;
992
+ /**
993
+ * Спринт 19: автопродолжение задач, поставленных на паузу до даты.
994
+ * Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
995
+ * Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
996
+ */
997
+ async function resumeExpiredPauses() {
998
+ const now = Date.now();
999
+ const definitions = await loadTaskDefinitions();
1000
+ for (const definition of definitions) {
1001
+ if (!definition.pausedUntil)
1002
+ continue;
1003
+ if (definition.matrixParentId)
1004
+ continue;
1005
+ const untilMs = Date.parse(definition.pausedUntil);
1006
+ if (!Number.isFinite(untilMs) || untilMs > now)
1007
+ continue;
1008
+ try {
1009
+ const targets = definition.matrix
1010
+ ? listMatrixClones(definition.name).map((clone) => clone.name)
1011
+ : [definition.name];
1012
+ for (const target of targets) {
1013
+ await scheduler.resumeTask(target);
1014
+ }
1015
+ await saveTaskDefinition({ ...definition, pausedUntil: undefined });
1016
+ console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
1017
+ }
1018
+ catch (err) {
1019
+ console.error(`[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${err instanceof Error ? err.message : String(err)}`);
1020
+ }
1021
+ }
1022
+ }
1023
+ /** Уже отправленные уведомления о зависших клонах (id записи истории). */
1024
+ const notifiedStuckRecords = new Set();
1025
+ /**
1026
+ * Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
1027
+ * `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
1028
+ */
1029
+ async function checkStuckMatrices() {
1030
+ const settings = await loadSettings();
1031
+ const config = settings.notifications;
1032
+ if (!config?.enabled)
1033
+ return;
1034
+ const matrix = config.matrix;
1035
+ if (!matrix?.enabled)
1036
+ return;
1037
+ const threshold = matrix.stuckAfterMinutes;
1038
+ if (!Number.isFinite(threshold) || threshold <= 0)
1039
+ return;
1040
+ const running = listRunningRecords();
1041
+ if (running.length === 0) {
1042
+ notifiedStuckRecords.clear();
1043
+ return;
1044
+ }
1045
+ // Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
1046
+ const runningIds = new Set(running.map((record) => record.id));
1047
+ for (const id of notifiedStuckRecords) {
1048
+ if (!runningIds.has(id))
1049
+ notifiedStuckRecords.delete(id);
1050
+ }
1051
+ const parentByClone = new Map();
1052
+ for (const definition of await loadTaskDefinitions()) {
1053
+ if (definition.matrixParentId) {
1054
+ parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
1055
+ }
1056
+ }
1057
+ const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
1058
+ for (const item of stuck) {
1059
+ if (notifiedStuckRecords.has(item.id))
1060
+ continue;
1061
+ notifiedStuckRecords.add(item.id);
1062
+ await notifyStuckMatrix(item);
1063
+ }
1064
+ }
719
1065
  /** get_history — история запусков с фильтрами по задаче и статусу. */
720
1066
  const getHistoryExecute = wrapExecute(async (args) => {
721
1067
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
@@ -780,6 +1126,23 @@ const dryRunExecute = wrapExecute(async (args) => {
780
1126
  }),
781
1127
  };
782
1128
  });
1129
+ /**
1130
+ * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1131
+ * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
1132
+ */
1133
+ async function refreshWorkspaceEnvFiles(workspaceId) {
1134
+ const workspace = getWorkspace(workspaceId);
1135
+ if (!workspace)
1136
+ return 0;
1137
+ let refreshed = 0;
1138
+ for (const task of await loadTaskDefinitions()) {
1139
+ if (task.workspaceId !== workspaceId)
1140
+ continue;
1141
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
1142
+ refreshed += 1;
1143
+ }
1144
+ return refreshed;
1145
+ }
783
1146
  /** manage_workspaces — CRUD multi-repo workspace-ов. */
784
1147
  const manageWorkspacesExecute = wrapExecute(async (args) => {
785
1148
  try {
@@ -787,6 +1150,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
787
1150
  case "list": {
788
1151
  const workspaces = listWorkspaces().map((workspace) => ({
789
1152
  ...workspace,
1153
+ env: maskEnvForLog(workspace.env),
790
1154
  gitBranch: readGitBranch(workspace.path) ?? null,
791
1155
  }));
792
1156
  return {
@@ -810,12 +1174,15 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
810
1174
  name: args.name,
811
1175
  path: args.path,
812
1176
  color: args.color,
1177
+ env: args.env,
1178
+ envFile: args.envFile,
813
1179
  });
814
1180
  return {
815
1181
  content: JSON.stringify({
816
1182
  success: true,
817
1183
  workspace: {
818
1184
  ...workspace,
1185
+ env: maskEnvForLog(workspace.env),
819
1186
  gitBranch: readGitBranch(workspace.path) ?? null,
820
1187
  },
821
1188
  }),
@@ -834,6 +1201,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
834
1201
  name: args.name,
835
1202
  path: args.path,
836
1203
  color: args.color,
1204
+ env: args.env,
1205
+ envFile: args.envFile,
837
1206
  });
838
1207
  if (!workspace) {
839
1208
  return {
@@ -843,11 +1212,16 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
843
1212
  }),
844
1213
  };
845
1214
  }
1215
+ // Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
1216
+ // файл при запуске, поэтому ждать обновления задачи не нужно.
1217
+ const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
846
1218
  return {
847
1219
  content: JSON.stringify({
848
1220
  success: true,
1221
+ refreshedTasks,
849
1222
  workspace: {
850
1223
  ...workspace,
1224
+ env: maskEnvForLog(workspace.env),
851
1225
  gitBranch: readGitBranch(workspace.path) ?? null,
852
1226
  },
853
1227
  }),
@@ -883,8 +1257,31 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
883
1257
  };
884
1258
  }
885
1259
  });
886
- /** matrix_control — результаты, отмена и очистка матриц. */
1260
+ /** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
887
1261
  const matrixControlExecute = wrapExecute(async (args) => {
1262
+ if (args.action === "preview") {
1263
+ const clones = expandMatrixTask({
1264
+ name: (args.name ?? "").trim() || "task",
1265
+ schedule: "* * * * *",
1266
+ prompt: "preview",
1267
+ matrix: {
1268
+ workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
1269
+ strategy: args.strategy,
1270
+ failureMode: args.failureMode,
1271
+ aggregation: args.aggregation,
1272
+ },
1273
+ });
1274
+ return {
1275
+ content: JSON.stringify({
1276
+ success: true,
1277
+ clones: clones.map((clone) => ({
1278
+ name: clone.name,
1279
+ workspaceId: clone.workspaceId ?? "",
1280
+ workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
1281
+ })),
1282
+ }),
1283
+ };
1284
+ }
888
1285
  if (args.action === "cleanup") {
889
1286
  const removed = await cleanupOrphanedMatrixTasks();
890
1287
  return {
@@ -939,6 +1336,270 @@ const matrixControlExecute = wrapExecute(async (args) => {
939
1336
  };
940
1337
  }
941
1338
  });
1339
+ /** get_metrics — суммарная статистика запусков. */
1340
+ const getMetricsExecute = wrapExecute(async () => {
1341
+ const metrics = await loadMetrics();
1342
+ return { content: JSON.stringify({ success: true, metrics }) };
1343
+ });
1344
+ /** get_analytics — аналитика запусков и стоимости за период. */
1345
+ const getAnalyticsExecute = wrapExecute(async (args) => {
1346
+ const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
1347
+ const records = getHistory(null, 20000);
1348
+ const definitions = await loadTaskDefinitions();
1349
+ const report = buildAnalytics(records, {
1350
+ days: windowDays,
1351
+ topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
1352
+ tasks: definitions.map((definition) => ({
1353
+ name: definition.name,
1354
+ matrixParentId: definition.matrixParentId,
1355
+ })),
1356
+ });
1357
+ return { content: JSON.stringify({ success: true, report }) };
1358
+ });
1359
+ /** manage_settings — чтение и изменение глобальных настроек. */
1360
+ const manageSettingsExecute = wrapExecute(async (args) => {
1361
+ const current = await loadSettings();
1362
+ if (args.action === "get") {
1363
+ return { content: JSON.stringify({ success: true, settings: current }) };
1364
+ }
1365
+ if (args.maxConcurrent === undefined &&
1366
+ args.winterMode === undefined &&
1367
+ args.notifications === undefined &&
1368
+ args.history === undefined) {
1369
+ return {
1370
+ content: JSON.stringify({
1371
+ success: false,
1372
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications или history.",
1373
+ settings: current,
1374
+ }),
1375
+ };
1376
+ }
1377
+ const settings = await saveSettings({
1378
+ maxConcurrent: args.maxConcurrent,
1379
+ winterMode: args.winterMode,
1380
+ notifications: args.notifications,
1381
+ history: args.history,
1382
+ });
1383
+ return { content: JSON.stringify({ success: true, settings }) };
1384
+ });
1385
+ /** manage_templates — список, сохранение и удаление шаблонов задач. */
1386
+ const manageTemplatesExecute = wrapExecute(async (args) => {
1387
+ if (args.action === "list") {
1388
+ return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
1389
+ }
1390
+ if (args.action === "delete") {
1391
+ const id = args.id?.trim();
1392
+ if (!id) {
1393
+ return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
1394
+ }
1395
+ const before = await loadTemplates();
1396
+ const existed = before.some((template) => template.id === id);
1397
+ await deleteTemplate(id);
1398
+ return {
1399
+ content: JSON.stringify({
1400
+ success: existed,
1401
+ message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
1402
+ }),
1403
+ };
1404
+ }
1405
+ const { action, ...fields } = args;
1406
+ if (!fields.name?.trim() || !fields.prompt?.trim()) {
1407
+ return {
1408
+ content: JSON.stringify({
1409
+ success: false,
1410
+ error: "Для action=save нужны непустые name и prompt.",
1411
+ }),
1412
+ };
1413
+ }
1414
+ const template = await saveTemplate(fields);
1415
+ return { content: JSON.stringify({ success: true, template }) };
1416
+ });
1417
+ /** manage_profiles — список, создание, переключение и удаление профилей. */
1418
+ const manageProfilesExecute = wrapExecute(async (args) => {
1419
+ if (args.action === "list") {
1420
+ return {
1421
+ content: JSON.stringify({
1422
+ success: true,
1423
+ current: getProfileName(),
1424
+ pinnedByEnv: isProfilePinnedByEnv(),
1425
+ profiles: listProfiles(),
1426
+ }),
1427
+ };
1428
+ }
1429
+ const name = args.name?.trim();
1430
+ if (!name) {
1431
+ return {
1432
+ content: JSON.stringify({
1433
+ success: false,
1434
+ error: `Для action=${args.action} нужно имя профиля.`,
1435
+ }),
1436
+ };
1437
+ }
1438
+ if (args.action === "create") {
1439
+ const meta = createProfile(name, args.port);
1440
+ const profile = listProfiles().find((item) => item.name === meta.name);
1441
+ return {
1442
+ content: JSON.stringify({
1443
+ success: true,
1444
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
1445
+ profile: profile ?? {
1446
+ name: meta.name,
1447
+ dir: getProfileDir(meta.name),
1448
+ port: meta.port,
1449
+ isDefault: meta.name === DEFAULT_PROFILE,
1450
+ active: meta.name === getProfileName(),
1451
+ },
1452
+ }),
1453
+ };
1454
+ }
1455
+ if (args.action === "switch") {
1456
+ setActiveProfile(name);
1457
+ const current = getProfileName();
1458
+ return {
1459
+ content: JSON.stringify({
1460
+ success: true,
1461
+ current,
1462
+ restartRequired: true,
1463
+ message: isProfilePinnedByEnv()
1464
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
1465
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
1466
+ }),
1467
+ };
1468
+ }
1469
+ const removed = deleteProfile(name);
1470
+ return {
1471
+ content: JSON.stringify({
1472
+ success: removed,
1473
+ message: removed
1474
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
1475
+ : "Профиль не найден.",
1476
+ }),
1477
+ };
1478
+ });
1479
+ /** transfer_tasks — экспорт и импорт задач. */
1480
+ const transferTasksExecute = wrapExecute(async (args) => {
1481
+ if (args.action === "export") {
1482
+ const tasks = await scheduler.listTasks();
1483
+ const { data, count } = await buildExportJson(tasks.map((task) => ({ ...task, name: task.taskName || "" })));
1484
+ return { content: JSON.stringify({ success: true, data, count }) };
1485
+ }
1486
+ if (!args.data) {
1487
+ return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
1488
+ }
1489
+ const parsed = parseImportJson(args.data);
1490
+ if (parsed.tasks.length === 0) {
1491
+ return {
1492
+ content: JSON.stringify({
1493
+ success: false,
1494
+ error: "В данных нет задач для импорта.",
1495
+ errors: parsed.errors,
1496
+ }),
1497
+ };
1498
+ }
1499
+ const imported = [];
1500
+ const errors = [...parsed.errors];
1501
+ for (const def of parsed.tasks) {
1502
+ try {
1503
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil);
1504
+ await saveTaskDefinition(def);
1505
+ imported.push(def.name);
1506
+ }
1507
+ catch (err) {
1508
+ errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
1509
+ }
1510
+ }
1511
+ await refreshFileTriggers();
1512
+ return {
1513
+ content: JSON.stringify({ success: errors.length === 0, imported, errors }),
1514
+ };
1515
+ });
1516
+ /** send_notification — тестовое уведомление или дайджест. */
1517
+ const sendNotificationExecute = wrapExecute(async (args) => {
1518
+ const result = args.action === "test"
1519
+ ? await sendTestNotification()
1520
+ : await sendDigestNow({ updateLastSentAt: false });
1521
+ return { content: JSON.stringify(result) };
1522
+ });
1523
+ /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
1524
+ const getDashboardInfoExecute = wrapExecute(async () => {
1525
+ const port = getDashboardPort();
1526
+ return {
1527
+ content: JSON.stringify({
1528
+ success: true,
1529
+ port,
1530
+ url: port ? `http://127.0.0.1:${port}` : null,
1531
+ platform: scheduler.platform,
1532
+ title: scheduler.title,
1533
+ profile: getProfileName(),
1534
+ }),
1535
+ };
1536
+ });
1537
+ /** cleanup_history — удаление старых записей истории. */
1538
+ const cleanupHistoryExecute = wrapExecute(async (args) => {
1539
+ const report = await runHistoryRetention({
1540
+ retentionDays: args.retentionDays,
1541
+ maxRecords: args.maxRecords,
1542
+ });
1543
+ return {
1544
+ content: JSON.stringify({
1545
+ success: true,
1546
+ message: report.skipped
1547
+ ? report.skipped
1548
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
1549
+ report,
1550
+ }),
1551
+ };
1552
+ });
1553
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
1554
+ const emitEventExecute = wrapExecute(async (args) => {
1555
+ const eventName = args.eventName?.trim();
1556
+ if (!eventName) {
1557
+ return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
1558
+ }
1559
+ const payload = args.payload ?? {};
1560
+ const definitions = await loadTaskDefinitions();
1561
+ const matched = definitions
1562
+ .filter((def) => def.triggerType === "mcp-event" &&
1563
+ def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
1564
+ matchesEventFilter(def.mcpEvent?.filter, payload))
1565
+ .sort((a, b) => (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0));
1566
+ const triggered = [];
1567
+ for (const def of matched) {
1568
+ try {
1569
+ await runTaskEntry(def.name);
1570
+ triggered.push(def.name);
1571
+ }
1572
+ catch (err) {
1573
+ console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
1574
+ }
1575
+ }
1576
+ return {
1577
+ content: JSON.stringify({
1578
+ success: true,
1579
+ message: triggered.length > 0
1580
+ ? `Запущено задач: ${triggered.length}.`
1581
+ : `Нет задач, подписанных на событие "${eventName}".`,
1582
+ triggered,
1583
+ }),
1584
+ };
1585
+ });
1586
+ /**
1587
+ * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
1588
+ * обновлять после создания/изменения/удаления задачи. Раньше refresh()
1589
+ * вызывался только при старте плагина, из-за чего новые watchPath начинали
1590
+ * работать лишь после перезапуска OpenCode.
1591
+ */
1592
+ let fileWatcherManager = null;
1593
+ async function refreshFileTriggers() {
1594
+ if (!fileWatcherManager)
1595
+ return;
1596
+ try {
1597
+ await fileWatcherManager.refresh();
1598
+ }
1599
+ catch (err) {
1600
+ console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
1601
+ }
1602
+ }
942
1603
  export default Plugin.define({
943
1604
  id: "opencode-windows-scheduler",
944
1605
  setup: async (ctx) => {
@@ -962,6 +1623,41 @@ export default Plugin.define({
962
1623
  console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
963
1624
  }
964
1625
  checkJsonBackups();
1626
+ // Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
1627
+ // плагину стартовать — пишем в лог и продолжаем.
1628
+ void maybeRunHistoryRetention()
1629
+ .then((report) => {
1630
+ if (report && report.deleted > 0) {
1631
+ console.log(`[retention] Удалено ${report.deleted} записей истории ` +
1632
+ `(по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}); ` +
1633
+ `осталось ${report.kept}.`);
1634
+ }
1635
+ })
1636
+ .catch((err) => {
1637
+ console.error(`[retention] Не удалось очистить историю: ${err instanceof Error ? err.message : String(err)}`);
1638
+ });
1639
+ // Спринт 19: автопродолжение задач, поставленных на паузу до даты.
1640
+ // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
1641
+ void resumeExpiredPauses().catch((err) => {
1642
+ console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1643
+ });
1644
+ const pausedUntilTimer = setInterval(() => {
1645
+ void resumeExpiredPauses().catch((err) => {
1646
+ console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1647
+ });
1648
+ }, PAUSED_UNTIL_CHECK_MS);
1649
+ pausedUntilTimer.unref?.();
1650
+ // Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
1651
+ // старте и далее раз в минуту; таймер не держит процесс Node живым.
1652
+ const notificationTimer = setInterval(() => {
1653
+ void maybeSendDigest().catch(() => undefined);
1654
+ void checkStuckMatrices().catch((err) => {
1655
+ console.error(`[windows-scheduler] Детектор зависших матриц: ${err instanceof Error ? err.message : String(err)}`);
1656
+ });
1657
+ }, NOTIFICATION_CHECK_MS);
1658
+ notificationTimer.unref?.();
1659
+ void maybeSendDigest().catch(() => undefined);
1660
+ void checkStuckMatrices().catch(() => undefined);
965
1661
  // Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
966
1662
  const lockManager = new LockManager(LOCK_DIR);
967
1663
  await lockManager.initialize();
@@ -982,20 +1678,23 @@ export default Plugin.define({
982
1678
  continue;
983
1679
  if (!def.schedule)
984
1680
  continue;
985
- const prevRun = previousRunTime(def.schedule, now);
986
- if (!prevRun)
1681
+ // Задача на паузе до даты — её включит авто-продолжение.
1682
+ if (def.pausedUntil)
1683
+ continue;
1684
+ const prev = prevRun(def.schedule, now, def.timezone);
1685
+ if (!prev)
987
1686
  continue;
988
- const ageMs = now.getTime() - prevRun.getTime();
1687
+ const ageMs = now.getTime() - prev.getTime();
989
1688
  if (ageMs < catchUpThresholdMs)
990
1689
  continue;
991
1690
  // Есть ли запись в истории после предполагаемого времени запуска?
992
1691
  const ranAfter = history.some((r) => r.taskName.toLowerCase() === def.name.toLowerCase() &&
993
- new Date(r.startedAt).getTime() >= prevRun.getTime());
1692
+ new Date(r.startedAt).getTime() >= prev.getTime());
994
1693
  if (ranAfter)
995
1694
  continue;
996
1695
  // Запускаем задачу и пишем в лог.
997
1696
  try {
998
- await scheduler.runTask(def.name);
1697
+ await runTaskEntry(def.name);
999
1698
  console.log(`[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`);
1000
1699
  }
1001
1700
  catch (err) {
@@ -1009,16 +1708,16 @@ export default Plugin.define({
1009
1708
  })();
1010
1709
  // Файловые триггеры (File Watchers): задачи с triggerType === "file"
1011
1710
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
1012
- const fileWatcherManager = new FileWatchManager(async (taskName) => {
1711
+ fileWatcherManager = new FileWatchManager(async (taskName) => {
1013
1712
  try {
1014
- await scheduler.runTask(taskName);
1713
+ await runTaskEntry(taskName);
1015
1714
  console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
1016
1715
  }
1017
1716
  catch (err) {
1018
1717
  console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
1019
1718
  }
1020
1719
  });
1021
- void fileWatcherManager.refresh();
1720
+ void refreshFileTriggers();
1022
1721
  const registration = await ctx.tool.transform((editor) => {
1023
1722
  // editor.add регистрирует новые инструменты плагина с codemode: true,
1024
1723
  // чтобы они были видны в Code Mode. Встроенные schedule_* отключены
@@ -1110,10 +1809,80 @@ export default Plugin.define({
1110
1809
  editor.add({
1111
1810
  name: "matrix_control",
1112
1811
  input: matrixControlSchema,
1113
- description: "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).",
1812
+ description: "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).",
1114
1813
  options: { codemode: true },
1115
1814
  execute: matrixControlExecute,
1116
1815
  });
1816
+ editor.add({
1817
+ name: "get_metrics",
1818
+ input: getMetricsSchema,
1819
+ description: "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
1820
+ options: { codemode: true },
1821
+ execute: getMetricsExecute,
1822
+ });
1823
+ editor.add({
1824
+ name: "get_analytics",
1825
+ input: getAnalyticsSchema,
1826
+ description: "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
1827
+ options: { codemode: true },
1828
+ execute: getAnalyticsExecute,
1829
+ });
1830
+ editor.add({
1831
+ name: "manage_settings",
1832
+ input: manageSettingsSchema,
1833
+ description: "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
1834
+ options: { codemode: true },
1835
+ execute: manageSettingsExecute,
1836
+ });
1837
+ editor.add({
1838
+ name: "manage_templates",
1839
+ input: manageTemplatesSchema,
1840
+ description: "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
1841
+ options: { codemode: true },
1842
+ execute: manageTemplatesExecute,
1843
+ });
1844
+ editor.add({
1845
+ name: "manage_profiles",
1846
+ input: manageProfilesSchema,
1847
+ description: "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
1848
+ options: { codemode: true },
1849
+ execute: manageProfilesExecute,
1850
+ });
1851
+ editor.add({
1852
+ name: "transfer_tasks",
1853
+ input: transferTasksSchema,
1854
+ description: "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
1855
+ options: { codemode: true },
1856
+ execute: transferTasksExecute,
1857
+ });
1858
+ editor.add({
1859
+ name: "send_notification",
1860
+ input: sendNotificationSchema,
1861
+ description: "Sends a test notification through the configured channel or sends the digest immediately.",
1862
+ options: { codemode: true },
1863
+ execute: sendNotificationExecute,
1864
+ });
1865
+ editor.add({
1866
+ name: "get_dashboard_info",
1867
+ input: getDashboardInfoSchema,
1868
+ description: "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
1869
+ options: { codemode: true },
1870
+ execute: getDashboardInfoExecute,
1871
+ });
1872
+ editor.add({
1873
+ name: "cleanup_history",
1874
+ input: cleanupHistorySchema,
1875
+ description: "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
1876
+ options: { codemode: true },
1877
+ execute: cleanupHistoryExecute,
1878
+ });
1879
+ editor.add({
1880
+ name: "emit_event",
1881
+ input: emitEventSchema,
1882
+ description: "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
1883
+ options: { codemode: true },
1884
+ execute: emitEventExecute,
1885
+ });
1117
1886
  });
1118
1887
  // Нативный скилл плагина: агент видит краткое описание в списке доступных
1119
1888
  // скиллов и подгружает инструкцию только когда задача действительно про
@@ -1146,9 +1915,9 @@ export default Plugin.define({
1146
1915
  },
1147
1916
  create_task: async (input) => {
1148
1917
  console.log("[windows-scheduler] create_task input:", input);
1149
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, } = input;
1918
+ const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, } = input;
1150
1919
  try {
1151
- await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
1920
+ await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter);
1152
1921
  return { success: true, message: `Задача "${name}" успешно создана.` };
1153
1922
  }
1154
1923
  catch (err) {
@@ -1263,7 +2032,7 @@ export default Plugin.define({
1263
2032
  const triggered = [];
1264
2033
  for (const def of matched) {
1265
2034
  try {
1266
- await scheduler.runTask(def.name);
2035
+ await runTaskEntry(def.name);
1267
2036
  triggered.push(def.name);
1268
2037
  console.log(`[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
1269
2038
  }
@@ -1278,8 +2047,8 @@ export default Plugin.define({
1278
2047
  };
1279
2048
  },
1280
2049
  pause_task: async (input) => {
1281
- const { name } = input;
1282
- const result = await pauseOrResumeTask(name, true);
2050
+ const { name, until } = input;
2051
+ const result = await pauseOrResumeTask(name, true, until);
1283
2052
  return { success: result.success, message: result.message };
1284
2053
  },
1285
2054
  resume_task: async (input) => {
@@ -1299,13 +2068,72 @@ export default Plugin.define({
1299
2068
  return { success: true, logs: result.logs };
1300
2069
  },
1301
2070
  get_history: async (input) => {
1302
- const { limit } = input;
1303
- const records = await loadHistory();
2071
+ const { limit, taskName } = input;
2072
+ const filter = taskName?.trim().toLowerCase();
2073
+ const records = (await loadHistory()).filter((record) => !filter || record.taskName.toLowerCase() === filter);
1304
2074
  return { records: records.slice(0, limit ?? 10) };
1305
2075
  },
1306
2076
  get_metrics: async () => {
1307
2077
  return await loadMetrics();
1308
2078
  },
2079
+ cleanup_history: async (input) => {
2080
+ const { retentionDays, maxRecords } = input;
2081
+ try {
2082
+ const report = await runHistoryRetention({ retentionDays, maxRecords });
2083
+ const message = report.skipped
2084
+ ? report.skipped
2085
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ` +
2086
+ `${report.deletedByCount}), осталось ${report.kept}.`;
2087
+ return {
2088
+ success: true,
2089
+ message,
2090
+ deleted: report.deleted,
2091
+ deletedByAge: report.deletedByAge,
2092
+ deletedByCount: report.deletedByCount,
2093
+ kept: report.kept,
2094
+ retentionDays: report.retentionDays,
2095
+ maxRecords: report.maxRecords,
2096
+ vacuumed: report.vacuumed,
2097
+ };
2098
+ }
2099
+ catch (err) {
2100
+ return {
2101
+ success: false,
2102
+ message: `Не удалось очистить историю: ${err instanceof Error ? err.message : String(err)}`,
2103
+ deleted: 0,
2104
+ deletedByAge: 0,
2105
+ deletedByCount: 0,
2106
+ kept: 0,
2107
+ retentionDays: 0,
2108
+ maxRecords: 0,
2109
+ vacuumed: false,
2110
+ };
2111
+ }
2112
+ },
2113
+ get_analytics: async (input) => {
2114
+ const { days, topLimit } = input;
2115
+ try {
2116
+ const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
2117
+ const records = getHistory(null, 20000);
2118
+ const definitions = await loadTaskDefinitions();
2119
+ const report = buildAnalytics(records, {
2120
+ days: windowDays,
2121
+ topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
2122
+ tasks: definitions.map((definition) => ({
2123
+ name: definition.name,
2124
+ matrixParentId: definition.matrixParentId,
2125
+ })),
2126
+ });
2127
+ return { success: true, report };
2128
+ }
2129
+ catch (err) {
2130
+ return {
2131
+ success: false,
2132
+ report: null,
2133
+ error: err instanceof Error ? err.message : String(err),
2134
+ };
2135
+ }
2136
+ },
1309
2137
  get_dashboard_port: async () => {
1310
2138
  return { port: getDashboardPort() };
1311
2139
  },
@@ -1405,15 +2233,23 @@ export default Plugin.define({
1405
2233
  return {
1406
2234
  workspaces: listWorkspaces().map((workspace) => ({
1407
2235
  ...workspace,
2236
+ env: maskEnvForLog(workspace.env),
1408
2237
  gitBranch: readGitBranch(workspace.path) ?? null,
1409
2238
  })),
1410
2239
  };
1411
2240
  },
1412
2241
  add_workspace: async (input) => {
1413
2242
  try {
1414
- const { name, path: workspacePath, color } = input;
1415
- const workspace = addWorkspace({ name, path: workspacePath, color });
1416
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
2243
+ const { name, path: workspacePath, color, env, envFile } = input;
2244
+ const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
2245
+ return {
2246
+ success: true,
2247
+ workspace: {
2248
+ ...workspace,
2249
+ env: maskEnvForLog(workspace.env),
2250
+ gitBranch: readGitBranch(workspace.path) ?? null,
2251
+ },
2252
+ };
1417
2253
  }
1418
2254
  catch (err) {
1419
2255
  return { success: false, error: err instanceof Error ? err.message : String(err) };
@@ -1421,12 +2257,21 @@ export default Plugin.define({
1421
2257
  },
1422
2258
  update_workspace: async (input) => {
1423
2259
  try {
1424
- const { id, name, path: workspacePath, color } = input;
1425
- const workspace = updateWorkspace(id, { name, path: workspacePath, color });
2260
+ const { id, name, path: workspacePath, color, env, envFile } = input;
2261
+ const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
1426
2262
  if (!workspace) {
1427
2263
  return { success: false, error: "Workspace не найден." };
1428
2264
  }
1429
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
2265
+ // env-файлы существующих задач перегенерируются сразу (Спринт 21).
2266
+ await refreshWorkspaceEnvFiles(workspace.id);
2267
+ return {
2268
+ success: true,
2269
+ workspace: {
2270
+ ...workspace,
2271
+ env: maskEnvForLog(workspace.env),
2272
+ gitBranch: readGitBranch(workspace.path) ?? null,
2273
+ },
2274
+ };
1430
2275
  }
1431
2276
  catch (err) {
1432
2277
  return { success: false, error: err instanceof Error ? err.message : String(err) };
@@ -1447,33 +2292,114 @@ export default Plugin.define({
1447
2292
  return { success: false, message: err instanceof Error ? err.message : String(err) };
1448
2293
  }
1449
2294
  },
2295
+ get_profiles: async () => {
2296
+ return {
2297
+ current: getProfileName(),
2298
+ pinnedByEnv: isProfilePinnedByEnv(),
2299
+ profiles: listProfiles(),
2300
+ };
2301
+ },
2302
+ set_profile: async (input) => {
2303
+ const { name } = input;
2304
+ try {
2305
+ setActiveProfile(name);
2306
+ const current = getProfileName();
2307
+ return {
2308
+ success: true,
2309
+ current,
2310
+ restartRequired: true,
2311
+ message: isProfilePinnedByEnv()
2312
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
2313
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
2314
+ };
2315
+ }
2316
+ catch (err) {
2317
+ return {
2318
+ success: false,
2319
+ current: getProfileName(),
2320
+ restartRequired: false,
2321
+ message: err instanceof Error ? err.message : String(err),
2322
+ };
2323
+ }
2324
+ },
2325
+ create_profile: async (input) => {
2326
+ const { name, port } = input;
2327
+ try {
2328
+ const meta = createProfile(name, port);
2329
+ const profile = listProfiles().find((item) => item.name === meta.name);
2330
+ return {
2331
+ success: true,
2332
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2333
+ profile: profile ?? {
2334
+ name: meta.name,
2335
+ dir: getProfileDir(meta.name),
2336
+ port: meta.port,
2337
+ isDefault: meta.name === DEFAULT_PROFILE,
2338
+ active: meta.name === getProfileName(),
2339
+ },
2340
+ };
2341
+ }
2342
+ catch (err) {
2343
+ return {
2344
+ success: false,
2345
+ error: err instanceof Error ? err.message : String(err),
2346
+ };
2347
+ }
2348
+ },
2349
+ delete_profile: async (input) => {
2350
+ const { name } = input;
2351
+ try {
2352
+ const removed = deleteProfile(name);
2353
+ return {
2354
+ success: removed,
2355
+ message: removed
2356
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2357
+ : "Профиль не найден.",
2358
+ };
2359
+ }
2360
+ catch (err) {
2361
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
2362
+ }
2363
+ },
1450
2364
  get_settings: async () => {
1451
2365
  return await loadSettings();
1452
2366
  },
1453
2367
  save_settings: async (input) => {
1454
- const { maxConcurrent, winterMode, notifications } = input;
2368
+ const { maxConcurrent, winterMode, notifications, history } = input;
1455
2369
  const current = await loadSettings();
1456
2370
  if (maxConcurrent === undefined &&
1457
2371
  winterMode === undefined &&
1458
- notifications === undefined) {
2372
+ notifications === undefined &&
2373
+ history === undefined) {
1459
2374
  return {
1460
2375
  success: false,
1461
2376
  maxConcurrent: current.maxConcurrent,
1462
2377
  winterMode: current.winterMode,
1463
2378
  notifications: current.notifications,
2379
+ history: current.history,
1464
2380
  };
1465
2381
  }
1466
- const settings = await saveSettings({ maxConcurrent, winterMode, notifications });
2382
+ const settings = await saveSettings({
2383
+ maxConcurrent,
2384
+ winterMode,
2385
+ notifications,
2386
+ history,
2387
+ });
1467
2388
  return {
1468
2389
  success: true,
1469
2390
  maxConcurrent: settings.maxConcurrent,
1470
2391
  winterMode: settings.winterMode,
1471
2392
  notifications: settings.notifications,
2393
+ history: settings.history,
1472
2394
  };
1473
2395
  },
1474
2396
  test_notification: async () => {
1475
2397
  return await sendTestNotification();
1476
2398
  },
2399
+ send_digest: async () => {
2400
+ // Ручная отправка не сдвигает плановое расписание дайджеста.
2401
+ return await sendDigestNow({ updateLastSentAt: false });
2402
+ },
1477
2403
  get_templates: async () => {
1478
2404
  try {
1479
2405
  return { templates: await loadTemplates() };
@@ -1561,7 +2487,7 @@ export default Plugin.define({
1561
2487
  const errors = [...parsed.errors];
1562
2488
  for (const def of parsed.tasks) {
1563
2489
  try {
1564
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId);
2490
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil);
1565
2491
  await saveTaskDefinition(def);
1566
2492
  imported.push(def.name);
1567
2493
  }
@@ -1601,10 +2527,13 @@ export default Plugin.define({
1601
2527
  console.log(`[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`);
1602
2528
  }
1603
2529
  return () => {
2530
+ clearInterval(pausedUntilTimer);
2531
+ clearInterval(notificationTimer);
1604
2532
  rpcRegistration.dispose();
1605
2533
  registration.dispose();
1606
2534
  void skillRegistration?.dispose();
1607
- void fileWatcherManager.stop();
2535
+ if (fileWatcherManager)
2536
+ void fileWatcherManager.stop();
1608
2537
  // При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
1609
2538
  // затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
1610
2539
  void closeDashboardServer().finally(() => closeDb());
@@ -1662,11 +2591,23 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
1662
2591
  */
1663
2592
  async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
1664
2593
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
1665
- matrixMode = "create") {
2594
+ matrixMode = "create",
2595
+ /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
2596
+ timezone,
2597
+ /** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
2598
+ notBefore,
2599
+ /** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
2600
+ notAfter,
2601
+ /** Пауза до момента ISO; после него задача возобновляется автоматически. */
2602
+ pausedUntil) {
1666
2603
  const normalizedModel = model?.trim() || undefined;
1667
2604
  const normalizedPriority = normalizePriority(priority);
1668
2605
  const normalizedBefore = beforeScript?.trim() || undefined;
1669
2606
  const normalizedAfter = afterScript?.trim() || undefined;
2607
+ const normalizedTz = timezone?.trim() || undefined;
2608
+ const normalizedNotBefore = notBefore?.trim() || undefined;
2609
+ const normalizedNotAfter = notAfter?.trim() || undefined;
2610
+ const normalizedPausedUntil = pausedUntil?.trim() || undefined;
1670
2611
  const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
1671
2612
  ? {
1672
2613
  server: mcpEvent.server?.trim() || "",
@@ -1741,15 +2682,38 @@ matrixMode = "create") {
1741
2682
  // расписание не используется вовсе.
1742
2683
  if (effectiveTriggerType === "cron") {
1743
2684
  try {
1744
- convertCronToSchTasks(schedule);
2685
+ // Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
2686
+ // имена месяцев/дней, @every, L и FRI#3.
2687
+ parseCron(schedule);
1745
2688
  }
1746
2689
  catch (err) {
1747
2690
  throw new Error(err.message || String(err));
1748
2691
  }
2692
+ if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
2693
+ throw new Error(`Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
2694
+ `Укажите IANA-зону, например Europe/Moscow.`);
2695
+ }
2696
+ const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
2697
+ if (windowError) {
2698
+ throw new Error(`Задача "${name}": ${windowError}`);
2699
+ }
1749
2700
  }
1750
2701
  const sanitized = sanitizeName(name);
1751
2702
  const lockFile = lockFilePath(sanitized);
1752
2703
  const logFile = path.join(LOG_DIR, `${sanitized}.log`);
2704
+ // Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
2705
+ // (нестандартный cron или чужая IANA-зона) либо при окне запуска.
2706
+ const gate = effectiveTriggerType === "cron"
2707
+ ? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter)
2708
+ : undefined;
2709
+ const wrapperGate = gate
2710
+ ? {
2711
+ ...gate,
2712
+ gateFile: gatePath,
2713
+ deferFile: `${lockFile}.defer`,
2714
+ forceFile: `${lockFile}.force`,
2715
+ }
2716
+ : undefined;
1753
2717
  // Workspace имеет приоритет над workingDirectory: одна задача = один repo
1754
2718
  // = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
1755
2719
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
@@ -1770,6 +2734,12 @@ matrixMode = "create") {
1770
2734
  }
1771
2735
  }
1772
2736
  const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
2737
+ // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
2738
+ // Значения не логируются; в лог попадает только факт загрузки.
2739
+ const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
2740
+ if (taskEnvFile) {
2741
+ console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
2742
+ }
1773
2743
  let promptFile;
1774
2744
  try {
1775
2745
  promptFile = await writePromptFile(sanitized, prompt);
@@ -1786,7 +2756,7 @@ matrixMode = "create") {
1786
2756
  try {
1787
2757
  if (scheduler.platform === "win32") {
1788
2758
  await ensureWrapper();
1789
- wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools);
2759
+ wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile);
1790
2760
  }
1791
2761
  else {
1792
2762
  wrapperPath = await writeBashWrapper({
@@ -1805,6 +2775,8 @@ matrixMode = "create") {
1805
2775
  workspaceName: workspace?.name,
1806
2776
  allowedTools: normalizedAllowedTools,
1807
2777
  deniedTools: normalizedDeniedTools,
2778
+ scheduleGate: wrapperGate,
2779
+ envFile: taskEnvFile,
1808
2780
  });
1809
2781
  }
1810
2782
  }
@@ -1823,6 +2795,9 @@ matrixMode = "create") {
1823
2795
  logFile,
1824
2796
  model: normalizedModel,
1825
2797
  priority: normalizedPriority,
2798
+ timezone: normalizedTz,
2799
+ notBefore: normalizedNotBefore,
2800
+ notAfter: normalizedNotAfter,
1826
2801
  });
1827
2802
  }
1828
2803
  catch (err) {
@@ -1849,6 +2824,10 @@ matrixMode = "create") {
1849
2824
  nextTaskOnError,
1850
2825
  triggerType: effectiveTriggerType,
1851
2826
  watchPath: normalizedMatrix ? undefined : watchPath,
2827
+ timezone: normalizedTz,
2828
+ notBefore: normalizedNotBefore,
2829
+ notAfter: normalizedNotAfter,
2830
+ pausedUntil: normalizedPausedUntil,
1852
2831
  allowedTools: normalizedAllowedTools,
1853
2832
  deniedTools: normalizedDeniedTools,
1854
2833
  matrix: normalizedMatrix,
@@ -1877,7 +2856,7 @@ matrixMode = "create") {
1877
2856
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
1878
2857
  if (normalizedMatrix) {
1879
2858
  const createClone = async (clone) => {
1880
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name);
2859
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
1881
2860
  };
1882
2861
  const removeChild = async (child) => {
1883
2862
  try {
@@ -1948,7 +2927,22 @@ async function runTaskEntry(name) {
1948
2927
  await runMatrix(definition);
1949
2928
  return { alreadyRunning: false };
1950
2929
  }
1951
- return scheduler.runTask(name);
2930
+ // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
2931
+ // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
2932
+ // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
2933
+ // запуск молча отменялся бы schedule-gate с кодом 3.
2934
+ const forceFile = await requestImmediateRun(name);
2935
+ try {
2936
+ return await scheduler.runTask(name);
2937
+ }
2938
+ catch (err) {
2939
+ // Планировщик не принял запуск — маркер не нужен, иначе он мог бы
2940
+ // «разрешить» следующий плановый тик в обход расписания.
2941
+ await fs.unlink(forceFile).catch(() => {
2942
+ /* не критично */
2943
+ });
2944
+ throw err;
2945
+ }
1952
2946
  }
1953
2947
  /**
1954
2948
  * Собирает задачи плагина в формате, который отдают оба потребителя:
@@ -1969,7 +2963,37 @@ async function collectTasksView() {
1969
2963
  const defs = await loadTaskDefinitions();
1970
2964
  const workspaces = listWorkspaces();
1971
2965
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
1972
- return tasks.map((t) => {
2966
+ // Счётчики запусков по задачам. Основной источник — таблица metrics
2967
+ // (накопительные итоги, не зависят от retention истории). Для задач, у
2968
+ // которых метрик ещё нет, считаем по загруженной истории.
2969
+ const metricsByName = new Map(getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row]));
2970
+ const historyCounts = new Map();
2971
+ for (const record of history) {
2972
+ const key = record.taskName.toLowerCase();
2973
+ const counts = historyCounts.get(key) ?? { total: 0, success: 0, error: 0 };
2974
+ counts.total += 1;
2975
+ if (record.status === "success")
2976
+ counts.success += 1;
2977
+ else
2978
+ counts.error += 1;
2979
+ historyCounts.set(key, counts);
2980
+ }
2981
+ // ОС-планировщик — источник истины о запуске, но определения в БД могут
2982
+ // существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
2983
+ // Показываем и их, помечая orphaned: раньше такие задачи были невидимы
2984
+ // для list_tasks, хотя dry_run/история их видели.
2985
+ const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
2986
+ const orphanNames = defs
2987
+ .filter((def) => !osNames.has(def.name.toLowerCase()))
2988
+ .map((def) => def.name);
2989
+ const sources = [
2990
+ ...tasks.map((task) => ({ task, orphaned: false })),
2991
+ ...orphanNames.map((name) => ({
2992
+ task: { taskName: name },
2993
+ orphaned: true,
2994
+ })),
2995
+ ];
2996
+ return sources.map(({ task: t, orphaned }) => {
1973
2997
  // Все бэкенды возвращают короткие имена (без папки планировщика).
1974
2998
  const name = t.taskName || "";
1975
2999
  // Приоритет 1: статус, который сообщает планировщик ОС.
@@ -1989,10 +3013,20 @@ async function collectTasksView() {
1989
3013
  if (matrixAggregate && matrixAggregate.status !== "empty") {
1990
3014
  status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
1991
3015
  }
3016
+ // Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
3017
+ // общие итоги по всем задачам — отсюда одинаковые 201/130/71).
3018
+ const metricsRow = metricsByName.get(name.toLowerCase());
3019
+ const counts = metricsRow
3020
+ ? { total: metricsRow.total, success: metricsRow.success, error: metricsRow.error }
3021
+ : historyCounts.get(name.toLowerCase()) ?? { total: 0, success: 0, error: 0 };
1992
3022
  return {
1993
3023
  name,
1994
3024
  schedule: def?.schedule ?? "",
1995
3025
  status,
3026
+ orphaned,
3027
+ runsTotal: counts.total,
3028
+ runsSuccess: counts.success,
3029
+ runsError: counts.error,
1996
3030
  nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
1997
3031
  model: def?.model ?? null,
1998
3032
  priority: def?.priority ?? 5,
@@ -2007,6 +3041,10 @@ async function collectTasksView() {
2007
3041
  dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
2008
3042
  triggerType: def?.triggerType ?? "cron",
2009
3043
  watchPath: def?.watchPath ?? null,
3044
+ timezone: def?.timezone ?? null,
3045
+ notBefore: def?.notBefore ?? null,
3046
+ notAfter: def?.notAfter ?? null,
3047
+ pausedUntil: def?.pausedUntil ?? null,
2010
3048
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
2011
3049
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
2012
3050
  workspaceName: workspace?.name ?? null,