opencode-windows-scheduler 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +18 -8
  3. package/README.ru.md +13 -3
  4. package/ROADMAP-STRATEGY.md +2 -2
  5. package/ROADMAP.md +51 -18
  6. package/dist/core/analytics.d.ts +10 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +21 -0
  9. package/dist/core/dry-run.d.ts +18 -1
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +49 -3
  12. package/dist/core/matrix.d.ts.map +1 -1
  13. package/dist/core/matrix.js +10 -0
  14. package/dist/core/one-shot.d.ts +62 -0
  15. package/dist/core/one-shot.d.ts.map +1 -0
  16. package/dist/core/one-shot.js +126 -0
  17. package/dist/core/otel.d.ts +4 -0
  18. package/dist/core/otel.d.ts.map +1 -0
  19. package/dist/core/otel.js +98 -0
  20. package/dist/core/prometheus.d.ts +23 -0
  21. package/dist/core/prometheus.d.ts.map +1 -0
  22. package/dist/core/prometheus.js +146 -0
  23. package/dist/core/ps-wrapper.d.ts +36 -2
  24. package/dist/core/ps-wrapper.d.ts.map +1 -1
  25. package/dist/core/ps-wrapper.js +124 -4
  26. package/dist/core/record-history.d.ts.map +1 -1
  27. package/dist/core/record-history.js +9 -0
  28. package/dist/core/schedule-gate.d.ts +2 -0
  29. package/dist/core/schedule-gate.d.ts.map +1 -0
  30. package/dist/core/schedule-gate.js +182 -0
  31. package/dist/core/schedule-v2.d.ts +88 -0
  32. package/dist/core/schedule-v2.d.ts.map +1 -0
  33. package/dist/core/schedule-v2.js +496 -0
  34. package/dist/core/scheduler/linux.d.ts +12 -3
  35. package/dist/core/scheduler/linux.d.ts.map +1 -1
  36. package/dist/core/scheduler/linux.js +80 -3
  37. package/dist/core/scheduler/mac.d.ts.map +1 -1
  38. package/dist/core/scheduler/mac.js +17 -3
  39. package/dist/core/scheduler/posix.d.ts.map +1 -1
  40. package/dist/core/scheduler/posix.js +3 -0
  41. package/dist/core/scheduler/registry.d.ts +4 -0
  42. package/dist/core/scheduler/registry.d.ts.map +1 -1
  43. package/dist/core/scheduler/types.d.ts +20 -3
  44. package/dist/core/scheduler/types.d.ts.map +1 -1
  45. package/dist/core/scheduler/windows.d.ts.map +1 -1
  46. package/dist/core/scheduler/windows.js +23 -2
  47. package/dist/core/session.d.ts +34 -0
  48. package/dist/core/session.d.ts.map +1 -0
  49. package/dist/core/session.js +105 -0
  50. package/dist/core/structured-log.d.ts +84 -0
  51. package/dist/core/structured-log.d.ts.map +1 -0
  52. package/dist/core/structured-log.js +137 -0
  53. package/dist/core/wrappers/bash.d.ts +24 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -1
  55. package/dist/core/wrappers/bash.js +70 -3
  56. package/dist/db/history-repo.d.ts +8 -0
  57. package/dist/db/history-repo.d.ts.map +1 -1
  58. package/dist/db/history-repo.js +76 -6
  59. package/dist/db/metrics-repo.d.ts +3 -0
  60. package/dist/db/metrics-repo.d.ts.map +1 -1
  61. package/dist/db/metrics-repo.js +16 -8
  62. package/dist/db/migrate.d.ts.map +1 -1
  63. package/dist/db/migrate.js +8 -1
  64. package/dist/db/schema.d.ts +1 -1
  65. package/dist/db/schema.d.ts.map +1 -1
  66. package/dist/db/schema.js +19 -0
  67. package/dist/gui-experimental.cjs +1 -0
  68. package/dist/history.d.ts +7 -0
  69. package/dist/history.d.ts.map +1 -1
  70. package/dist/history.js +13 -0
  71. package/dist/index.d.ts +137 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1323 -78
  74. package/dist/integrations.d.ts +64 -0
  75. package/dist/integrations.d.ts.map +1 -0
  76. package/dist/integrations.js +205 -0
  77. package/dist/notifications.d.ts +112 -6
  78. package/dist/notifications.d.ts.map +1 -1
  79. package/dist/notifications.js +396 -34
  80. package/dist/profiles.d.ts +60 -0
  81. package/dist/profiles.d.ts.map +1 -0
  82. package/dist/profiles.js +209 -0
  83. package/dist/rpc.d.ts +592 -4
  84. package/dist/rpc.d.ts.map +1 -1
  85. package/dist/rpc.js +233 -6
  86. package/dist/server.d.ts +2 -0
  87. package/dist/server.d.ts.map +1 -1
  88. package/dist/server.js +473 -58
  89. package/dist/settings.d.ts +95 -0
  90. package/dist/settings.d.ts.map +1 -1
  91. package/dist/settings.js +186 -8
  92. package/dist/shared/jobs-view.d.ts +43 -5
  93. package/dist/shared/jobs-view.d.ts.map +1 -1
  94. package/dist/shared/jobs-view.js +125 -7
  95. package/dist/task-transfer.d.ts +32 -3
  96. package/dist/task-transfer.d.ts.map +1 -1
  97. package/dist/task-transfer.js +101 -3
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/types.js +3 -11
  100. package/dist/workspaces.d.ts +43 -0
  101. package/dist/workspaces.d.ts.map +1 -1
  102. package/dist/workspaces.js +174 -8
  103. package/docs/ARCHITECTURE.md +32 -12
  104. package/docs/FEATURES.md +186 -10
  105. package/gui-experimental.cjs +4 -2
  106. package/package.json +15 -2
  107. package/scripts/demo-dashboard.mjs +12 -2
  108. package/src/core/analytics.ts +36 -0
  109. package/src/core/dry-run.ts +65 -4
  110. package/src/core/matrix.ts +10 -0
  111. package/src/core/one-shot.ts +173 -0
  112. package/src/core/otel.ts +128 -0
  113. package/src/core/prometheus.ts +215 -0
  114. package/src/core/ps-wrapper.ts +144 -4
  115. package/src/core/record-history.ts +13 -0
  116. package/src/core/schedule-gate.ts +213 -0
  117. package/src/core/schedule-v2.ts +533 -0
  118. package/src/core/scheduler/linux.ts +90 -3
  119. package/src/core/scheduler/mac.ts +35 -4
  120. package/src/core/scheduler/posix.ts +3 -0
  121. package/src/core/scheduler/registry.ts +4 -0
  122. package/src/core/scheduler/types.ts +20 -3
  123. package/src/core/scheduler/windows.ts +24 -2
  124. package/src/core/session.ts +115 -0
  125. package/src/core/structured-log.ts +205 -0
  126. package/src/core/wrappers/bash.ts +98 -2
  127. package/src/db/history-repo.ts +90 -7
  128. package/src/db/metrics-repo.ts +19 -7
  129. package/src/db/migrate.ts +7 -1
  130. package/src/db/schema.ts +25 -0
  131. package/src/gui.tsx +3832 -2868
  132. package/src/history.ts +17 -0
  133. package/src/index.ts +1670 -117
  134. package/src/integrations.ts +253 -0
  135. package/src/notifications.ts +516 -40
  136. package/src/profiles.ts +236 -0
  137. package/src/rpc.ts +244 -6
  138. package/src/server.ts +506 -58
  139. package/src/settings.ts +336 -9
  140. package/src/shared/jobs-view.ts +158 -8
  141. package/src/task-transfer.ts +151 -5
  142. package/src/tui.tsx +290 -14
  143. package/src/types.ts +3 -13
  144. package/src/workspaces.ts +214 -8
package/dist/index.js CHANGED
@@ -5,9 +5,11 @@ 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 { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
11
+ import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
12
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
11
13
  import { getSchedulerBackend } from "./core/scheduler/index.js";
12
14
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
13
15
  import { getTaskLogs } from "./core/scheduler/logs.js";
@@ -15,21 +17,23 @@ import { writeBashWrapper } from "./core/wrappers/bash.js";
15
17
  import { simulatePipeline } from "./core/dry-run.js";
16
18
  import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
17
19
  import { SchedulerRpc } from "./rpc.js";
18
- import { loadHistory, loadMetrics } from "./history.js";
20
+ import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
19
21
  import { loadSettings, saveSettings } from "./settings.js";
20
22
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
21
23
  import { buildAnalytics } from "./core/analytics.js";
22
- import { getHistory } from "./db/history-repo.js";
23
- import { sendTestNotification } from "./notifications.js";
24
+ import { getHistory, listRunningRecords } from "./db/history-repo.js";
25
+ import { getAllMetrics } from "./db/metrics-repo.js";
26
+ import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
24
27
  import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
25
28
  import { FileWatchManager } from "./core/file-watcher.js";
26
29
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
27
30
  import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
31
+ import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
28
32
  import { closeDb, initDb } from "./db/index.js";
29
33
  import { migrateJsonToDb } from "./db/migrate.js";
30
34
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
31
- import { getTask, listMatrixClones } from "./db/tasks-repo.js";
32
- import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, } from "./workspaces.js";
35
+ import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
36
+ import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
33
37
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
34
38
  const require = createRequire(import.meta.url);
35
39
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -50,6 +54,23 @@ const recorderPath = (() => {
50
54
  `${distPath}. История/метрики не будут записываться. Выполните npm run build.`);
51
55
  return distPath;
52
56
  })();
57
+ /**
58
+ * Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
59
+ * перед opencode и выходит, если cron не сработал или запуск перенесён.
60
+ */
61
+ const gatePath = (() => {
62
+ const resolved = require.resolve("./core/schedule-gate.js");
63
+ if (!resolved.endsWith(".ts"))
64
+ return resolved;
65
+ const distPath = resolved
66
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
67
+ .replace(/\.ts$/, ".js");
68
+ if (existsSync(distPath))
69
+ return distPath;
70
+ console.warn("[windows-scheduler] Не найден собранный schedule-gate.js: " +
71
+ `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`);
72
+ return distPath;
73
+ })();
53
74
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
54
75
  const scheduler = getSchedulerBackend();
55
76
  /** Per-workspace overrides for matrix clones (Sprint 17). */
@@ -95,7 +116,41 @@ export const scheduleTaskSchema = z.object({
95
116
  name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
96
117
  schedule: z
97
118
  .string()
98
- .describe("5-field cron expression (minute hour day-of-month month day-of-week). Supported patterns: * * * * *, */N * * * *, M H * * *, M H * * D."),
119
+ .optional()
120
+ .describe("Cron expression (5 fields: minute hour day-of-month month day-of-week). Required for triggerType=cron; ignored for file/mcp-event. 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."),
121
+ runAt: z
122
+ .string()
123
+ .optional()
124
+ .describe("Absolute one-shot start time in ISO-8601 (e.g. 2026-12-01T09:00:00Z). Requires triggerType=once; mutually exclusive with delaySeconds (runAt wins)."),
125
+ delaySeconds: z
126
+ .number()
127
+ .int()
128
+ .positive()
129
+ .optional()
130
+ .describe("One-shot delay in seconds from now. Requires triggerType=once. Convenient alternative to runAt."),
131
+ session: z
132
+ .enum(["new", "reuse", "last"])
133
+ .optional()
134
+ .describe("OpenCode session mode for the task: new (default, fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."),
135
+ sessionMaxRuns: z
136
+ .number()
137
+ .int()
138
+ .min(1)
139
+ .max(10000)
140
+ .optional()
141
+ .describe("Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."),
142
+ timezone: z
143
+ .string()
144
+ .optional()
145
+ .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)."),
146
+ notBefore: z
147
+ .string()
148
+ .optional()
149
+ .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."),
150
+ notAfter: z
151
+ .string()
152
+ .optional()
153
+ .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
99
154
  prompt: z
100
155
  .string()
101
156
  .describe("Prompt passed to the agent on every run."),
@@ -144,9 +199,9 @@ export const scheduleTaskSchema = z.object({
144
199
  .optional()
145
200
  .describe("Compensation/rollback task started after a failed run."),
146
201
  triggerType: z
147
- .enum(["cron", "file", "mcp-event"])
202
+ .enum(["cron", "file", "mcp-event", "once"])
148
203
  .optional()
149
- .describe("Trigger type: cron (default), file or mcp-event."),
204
+ .describe("Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."),
150
205
  mcpEvent: z
151
206
  .object({
152
207
  server: z.string(),
@@ -155,6 +210,10 @@ export const scheduleTaskSchema = z.object({
155
210
  })
156
211
  .optional()
157
212
  .describe("MCP event trigger: server, event name and an optional filter (key=value or regex)."),
213
+ watchPath: z
214
+ .string()
215
+ .optional()
216
+ .describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
158
217
  workingDirectory: z
159
218
  .string()
160
219
  .optional()
@@ -174,6 +233,38 @@ export const scheduleTaskSchema = z.object({
174
233
  matrix: matrixSchema
175
234
  .optional()
176
235
  .describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
236
+ }).superRefine((value, ctx) => {
237
+ const trigger = value.triggerType ?? "cron";
238
+ if (trigger === "cron" && !value.schedule?.trim()) {
239
+ ctx.addIssue({
240
+ code: z.ZodIssueCode.custom,
241
+ path: ["schedule"],
242
+ message: "Для triggerType=cron нужно cron-выражение schedule.",
243
+ });
244
+ }
245
+ if (trigger === "once" &&
246
+ !value.runAt &&
247
+ value.delaySeconds === undefined) {
248
+ ctx.addIssue({
249
+ code: z.ZodIssueCode.custom,
250
+ path: ["runAt"],
251
+ message: "Для triggerType=once нужен runAt (ISO-8601) или delaySeconds.",
252
+ });
253
+ }
254
+ if (trigger === "once" && value.matrix) {
255
+ ctx.addIssue({
256
+ code: z.ZodIssueCode.custom,
257
+ path: ["matrix"],
258
+ message: "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
259
+ });
260
+ }
261
+ if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
262
+ ctx.addIssue({
263
+ code: z.ZodIssueCode.custom,
264
+ path: ["runAt"],
265
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
266
+ });
267
+ }
177
268
  });
178
269
  const listTasksSchema = z.object({});
179
270
  const deleteTaskSchema = z.object({
@@ -187,7 +278,40 @@ export const updateTaskSchema = z.object({
187
278
  schedule: z
188
279
  .string()
189
280
  .optional()
190
- .describe("New 5-field cron expression. Keeps the current value when omitted."),
281
+ .describe("New cron expression. Keeps the current value when omitted."),
282
+ runAt: z
283
+ .string()
284
+ .optional()
285
+ .describe("New one-shot time in ISO-8601. Requires triggerType=once. Empty string clears it."),
286
+ delaySeconds: z
287
+ .number()
288
+ .int()
289
+ .positive()
290
+ .optional()
291
+ .describe("New one-shot delay in seconds from now. Requires triggerType=once."),
292
+ session: z
293
+ .enum(["new", "reuse", "last"])
294
+ .optional()
295
+ .describe("OpenCode session mode for the task: new (fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."),
296
+ sessionMaxRuns: z
297
+ .number()
298
+ .int()
299
+ .min(1)
300
+ .max(10000)
301
+ .optional()
302
+ .describe("Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."),
303
+ timezone: z
304
+ .string()
305
+ .optional()
306
+ .describe("New IANA timezone. Empty string clears it (system timezone)."),
307
+ notBefore: z
308
+ .string()
309
+ .optional()
310
+ .describe("New launch window start HH:MM. Empty string clears the window."),
311
+ notAfter: z
312
+ .string()
313
+ .optional()
314
+ .describe("New launch window end HH:MM. Empty string clears the window."),
191
315
  prompt: z
192
316
  .string()
193
317
  .optional()
@@ -225,7 +349,7 @@ export const updateTaskSchema = z.object({
225
349
  .optional()
226
350
  .describe("New error-chain task. Empty string clears it."),
227
351
  triggerType: z
228
- .enum(["cron", "file", "mcp-event"])
352
+ .enum(["cron", "file", "mcp-event", "once"])
229
353
  .optional()
230
354
  .describe("New trigger type."),
231
355
  mcpEvent: z
@@ -260,9 +384,30 @@ export const updateTaskSchema = z.object({
260
384
  .nullable()
261
385
  .optional()
262
386
  .describe("New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed)."),
387
+ }).superRefine((value, ctx) => {
388
+ if (value.triggerType !== undefined &&
389
+ value.triggerType !== "once" &&
390
+ (value.runAt || value.delaySeconds !== undefined)) {
391
+ ctx.addIssue({
392
+ code: z.ZodIssueCode.custom,
393
+ path: ["runAt"],
394
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
395
+ });
396
+ }
397
+ if (value.triggerType === "once" && value.matrix) {
398
+ ctx.addIssue({
399
+ code: z.ZodIssueCode.custom,
400
+ path: ["matrix"],
401
+ message: "One-shot нельзя комбинировать с matrix.",
402
+ });
403
+ }
263
404
  });
264
405
  const pauseTaskSchema = z.object({
265
406
  name: z.string().describe("Task name to pause."),
407
+ until: z
408
+ .string()
409
+ .optional()
410
+ .describe("Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."),
266
411
  });
267
412
  const resumeTaskSchema = z.object({
268
413
  name: z.string().describe("Task name to resume."),
@@ -302,15 +447,156 @@ const manageWorkspacesSchema = z.object({
302
447
  name: z.string().optional().describe("Workspace display name (add/update)."),
303
448
  path: z.string().optional().describe("Absolute workspace path (add/update)."),
304
449
  color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
450
+ env: z
451
+ .record(z.string(), z.string())
452
+ .nullable()
453
+ .optional()
454
+ .describe("Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."),
455
+ envFile: z
456
+ .string()
457
+ .nullable()
458
+ .optional()
459
+ .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
305
460
  });
306
461
  export const matrixControlSchema = z.object({
307
462
  action: z
308
- .enum(["results", "cancel", "cleanup"])
309
- .describe("results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."),
463
+ .enum(["results", "cancel", "cleanup", "preview"])
464
+ .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."),
310
465
  name: z
311
466
  .string()
312
467
  .optional()
313
- .describe("Matrix parent name (required for results and cancel)."),
468
+ .describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
469
+ workspaceIds: z
470
+ .array(z.string())
471
+ .optional()
472
+ .describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
473
+ strategy: z
474
+ .enum(["parallel", "sequential"])
475
+ .optional()
476
+ .describe("Preview only: clone execution strategy."),
477
+ failureMode: z
478
+ .enum(["continue", "stop"])
479
+ .optional()
480
+ .describe("Preview only: what to do when one clone fails."),
481
+ aggregation: z
482
+ .enum(["summary", "per-task"])
483
+ .optional()
484
+ .describe("Preview only: how clone results are aggregated."),
485
+ });
486
+ /** get_metrics — общая статистика запусков. */
487
+ export const getMetricsSchema = z.object({});
488
+ /** get_analytics — аналитика за период. */
489
+ export const getAnalyticsSchema = z.object({
490
+ days: z
491
+ .number()
492
+ .int()
493
+ .min(1)
494
+ .max(365)
495
+ .optional()
496
+ .describe("Analysis window in days (default 14)."),
497
+ topLimit: z
498
+ .number()
499
+ .int()
500
+ .min(1)
501
+ .max(50)
502
+ .optional()
503
+ .describe("How many top tasks to include (default 10)."),
504
+ });
505
+ /** manage_settings — глобальные настройки планировщика. */
506
+ export const manageSettingsSchema = z.object({
507
+ action: z
508
+ .enum(["get", "update"])
509
+ .describe("get — current settings; update — merge the provided fields and save."),
510
+ maxConcurrent: z
511
+ .number()
512
+ .int()
513
+ .min(1)
514
+ .max(16)
515
+ .optional()
516
+ .describe("How many task runs may execute at the same time."),
517
+ winterMode: z
518
+ .boolean()
519
+ .optional()
520
+ .describe("Winter mode: gentler scheduling of deferred runs."),
521
+ notifications: z
522
+ .any()
523
+ .optional()
524
+ .describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
525
+ history: z
526
+ .object({
527
+ retentionDays: z.number().int().min(1).max(3650).optional(),
528
+ maxRecords: z.number().int().min(100).max(1000000).optional(),
529
+ })
530
+ .optional()
531
+ .describe("History retention policy."),
532
+ integrations: z
533
+ .any()
534
+ .optional()
535
+ .describe("Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."),
536
+ });
537
+ /** manage_templates — пользовательские шаблоны задач. */
538
+ export const manageTemplatesSchema = z.object({
539
+ action: z
540
+ .enum(["list", "save", "delete"])
541
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
542
+ id: z.string().optional().describe("Template id for update/delete."),
543
+ name: z.string().optional().describe("Template name."),
544
+ prompt: z.string().optional().describe("Prompt text stored in the template."),
545
+ schedule: z.string().optional().describe("Cron expression."),
546
+ timeoutSeconds: z.number().int().positive().optional(),
547
+ model: z.string().optional(),
548
+ priority: z.number().int().min(0).max(10).optional(),
549
+ retryCount: z.number().int().min(0).optional(),
550
+ retryDelay: z.number().int().min(0).optional(),
551
+ qualityGate: z.string().optional(),
552
+ beforeScript: z.string().optional(),
553
+ afterScript: z.string().optional(),
554
+ nextTaskOnSuccess: z.string().optional(),
555
+ nextTaskOnError: z.string().optional(),
556
+ dependsOn: z.array(z.string()).optional(),
557
+ triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
558
+ mcpEvent: z
559
+ .object({
560
+ server: z.string(),
561
+ event: z.string(),
562
+ filter: z.string().optional(),
563
+ })
564
+ .optional(),
565
+ watchPath: z.string().optional(),
566
+ workingDirectory: z.string().optional(),
567
+ allowedTools: z.array(z.string()).optional(),
568
+ deniedTools: z.array(z.string()).optional(),
569
+ });
570
+ /** manage_profiles — изолированные профили планировщика. */
571
+ export const manageProfilesSchema = z.object({
572
+ action: z
573
+ .enum(["list", "create", "switch", "delete"])
574
+ .describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
575
+ name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
576
+ port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
577
+ });
578
+ /** transfer_tasks — экспорт и импорт задач. */
579
+ export const transferTasksSchema = z.object({
580
+ action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
581
+ data: z.string().optional().describe("JSON produced by export (required for import)."),
582
+ });
583
+ /** send_notification — проверка уведомлений и дайджест. */
584
+ export const sendNotificationSchema = z.object({
585
+ action: z
586
+ .enum(["test", "digest"])
587
+ .describe("test — send a test message through the configured channel; digest — send the digest now."),
588
+ });
589
+ /** get_dashboard_info — сведения о панели управления. */
590
+ export const getDashboardInfoSchema = z.object({});
591
+ /** cleanup_history — удаление старой истории. */
592
+ export const cleanupHistorySchema = z.object({
593
+ retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
594
+ maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
595
+ });
596
+ /** emit_event — запуск задач по MCP-событию. */
597
+ export const emitEventSchema = z.object({
598
+ eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
599
+ payload: z.any().optional().describe("Event payload passed to trigger filters."),
314
600
  });
315
601
  /**
316
602
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -339,9 +625,23 @@ function wrapExecute(fn) {
339
625
  }
340
626
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
341
627
  const scheduleTaskExecute = wrapExecute(async (args) => {
342
- const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, } = args;
628
+ const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, } = args;
629
+ let effectiveRunAt;
630
+ if ((triggerType ?? "cron") === "once") {
631
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
632
+ if (!normalized.ok) {
633
+ return {
634
+ content: JSON.stringify({ success: false, error: normalized.error }),
635
+ };
636
+ }
637
+ effectiveRunAt = normalized.runAt;
638
+ }
639
+ // Спринт 24: режим сессии. По умолчанию "new" (старое поведение).
640
+ // sessionId пользователя никогда не принимаем — он создаётся автоматически.
641
+ const effectiveSession = normalizeSessionMode(session) ?? "new";
642
+ const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
343
643
  try {
344
- await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, undefined, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
644
+ 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, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
345
645
  }
346
646
  catch (err) {
347
647
  return {
@@ -351,6 +651,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
351
651
  }),
352
652
  };
353
653
  }
654
+ // Новый файловый триггер должен начать работать сразу, без перезапуска
655
+ // OpenCode: пересобираем набор watcher-ов после создания задачи.
656
+ await refreshFileTriggers();
354
657
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
355
658
  const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
356
659
  return {
@@ -372,6 +675,13 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
372
675
  nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
373
676
  nextTaskOnError: nextTaskOnError?.trim() || null,
374
677
  triggerType: triggerType ?? "cron",
678
+ runAt: effectiveRunAt ?? null,
679
+ session: effectiveSession,
680
+ sessionId: effectiveSessionId ?? null,
681
+ sessionMaxRuns: sessionMaxRuns ?? null,
682
+ timezone: timezone?.trim() || null,
683
+ notBefore: notBefore?.trim() || null,
684
+ notAfter: notAfter?.trim() || null,
375
685
  mcpEvent: mcpEvent ?? null,
376
686
  workingDirectory: effectiveWorkdir,
377
687
  workspaceId: workspace?.id ?? null,
@@ -428,7 +738,7 @@ async function cancelMatrixRun(name) {
428
738
  }
429
739
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
430
740
  try {
431
- 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);
741
+ 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);
432
742
  }
433
743
  catch (err) {
434
744
  warnings.push(`${clone.name}: не удалось пересоздать — ${err instanceof Error ? err.message : String(err)}`);
@@ -491,6 +801,20 @@ async function deleteTaskWithFamily(name) {
491
801
  throw new Error(guard);
492
802
  const plan = planMatrixFamilyDelete(trimmed);
493
803
  const removed = [];
804
+ // Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
805
+ // отвечал success даже на имя, которого никогда не существовало.
806
+ let existed = Boolean(getTask(trimmed));
807
+ if (!existed) {
808
+ try {
809
+ const osTasks = await scheduler.listTasks();
810
+ existed = osTasks.some((task) => task.taskName.toLowerCase() === trimmed.toLowerCase());
811
+ }
812
+ catch {
813
+ // ОС-планировщик недоступен — довольствуемся данными БД.
814
+ }
815
+ }
816
+ if (plan && plan.children.length > 0)
817
+ existed = true;
494
818
  if (plan) {
495
819
  for (const child of plan.children) {
496
820
  try {
@@ -515,13 +839,23 @@ async function deleteTaskWithFamily(name) {
515
839
  catch {
516
840
  // Определения могло уже не быть — задача всё равно удалена из ОС.
517
841
  }
518
- return { removed };
842
+ return { removed, existed };
519
843
  }
520
844
  /** delete_task — удаление задачи по имени (/f) */
521
845
  const deleteTaskExecute = wrapExecute(async (args) => {
522
846
  const { name } = args;
523
847
  try {
524
- const { removed } = await deleteTaskWithFamily(name);
848
+ const { removed, existed } = await deleteTaskWithFamily(name);
849
+ // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
850
+ await refreshFileTriggers();
851
+ if (!existed && removed.length === 0) {
852
+ return {
853
+ content: JSON.stringify({
854
+ success: false,
855
+ error: `Задача "${name}" не найдена — удалять нечего.`,
856
+ }),
857
+ };
858
+ }
525
859
  return {
526
860
  content: JSON.stringify({
527
861
  success: true,
@@ -545,7 +879,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
545
879
  const { name } = args;
546
880
  let alreadyRunning = false;
547
881
  try {
548
- const result = await scheduler.runTask(name);
882
+ const result = await runTaskEntry(name);
549
883
  alreadyRunning = result.alreadyRunning;
550
884
  }
551
885
  catch (err) {
@@ -617,6 +951,9 @@ async function updateTaskFromInput(input) {
617
951
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
618
952
  const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
619
953
  const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
954
+ const timezone = clearableString(input.timezone, previous.timezone);
955
+ const notBefore = clearableString(input.notBefore, previous.notBefore);
956
+ const notAfter = clearableString(input.notAfter, previous.notAfter);
620
957
  if (triggerType === "cron" && !schedule) {
621
958
  return {
622
959
  success: false,
@@ -629,19 +966,81 @@ async function updateTaskFromInput(input) {
629
966
  message: `Для обновления задачи "${name}" нужен промпт.`,
630
967
  };
631
968
  }
969
+ // One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
970
+ // При смене триггера на once время обязательно, иначе задача не запустится.
971
+ let runAt;
972
+ if (triggerType === "once") {
973
+ const candidateRunAt = input.runAt !== undefined
974
+ ? input.runAt
975
+ : input.delaySeconds !== undefined
976
+ ? undefined
977
+ : previous.runAt;
978
+ const normalized = normalizeOneShotRunAt({
979
+ runAt: candidateRunAt,
980
+ delaySeconds: input.delaySeconds,
981
+ });
982
+ if (!normalized.ok) {
983
+ return {
984
+ success: false,
985
+ message: `Задача "${name}": ${normalized.error}`,
986
+ };
987
+ }
988
+ runAt = normalized.runAt;
989
+ }
990
+ // Спринт 24: режим сессии. Без новых session/sessionMaxRuns сохраняем прежние.
991
+ // sessionId пользователя не принимаем — генерируем сами при переходе на reuse.
992
+ let session = "new";
993
+ if (input.session !== undefined) {
994
+ const normalizedSession = normalizeSessionMode(input.session);
995
+ if (!normalizedSession) {
996
+ return {
997
+ success: false,
998
+ message: `Задача "${name}": неизвестный режим сессии "${String(input.session)}".`,
999
+ };
1000
+ }
1001
+ session = normalizedSession;
1002
+ }
1003
+ else if (previous.session) {
1004
+ session = previous.session;
1005
+ }
1006
+ const sessionMaxRuns = input.sessionMaxRuns !== undefined ? input.sessionMaxRuns : previous.sessionMaxRuns;
1007
+ if (sessionMaxRuns !== undefined &&
1008
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
1009
+ return {
1010
+ success: false,
1011
+ message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.`,
1012
+ };
1013
+ }
1014
+ let sessionId = previous.sessionId;
1015
+ if (session === "reuse" && !sessionId) {
1016
+ sessionId = generateSessionId();
1017
+ }
1018
+ if (session !== "reuse") {
1019
+ sessionId = undefined;
1020
+ }
632
1021
  const matrixWas = previous.matrix;
633
1022
  const matrixNext = input.matrix === undefined ? matrixWas : input.matrix ?? undefined;
1023
+ if (triggerType === "once" && matrixNext) {
1024
+ return {
1025
+ success: false,
1026
+ message: `Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
1027
+ `Запустите матрицу вручную или используйте cron/file-триггер.`,
1028
+ };
1029
+ }
634
1030
  try {
635
1031
  // Обновление = пересоздание в планировщике с сохранением старых значений.
636
1032
  await scheduler.deleteTask(name);
637
- 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,
1033
+ 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,
638
1034
  // Если задача была матрицей — синхронизируем клонов, а не
639
1035
  // пересоздаём их с нуля (Спринт 17).
640
- matrixWas && matrixNext ? "sync" : "create");
1036
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns);
641
1037
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
642
1038
  if (matrixWas && !matrixNext) {
643
1039
  await removeMatrixChildrenFromScheduler(name);
644
1040
  }
1041
+ // Пересоздание могло изменить triggerType/watchPath — сразу
1042
+ // пересобираем набор файловых watcher-ов.
1043
+ await refreshFileTriggers();
645
1044
  return { success: true, message: `Задача "${name}" обновлена.` };
646
1045
  }
647
1046
  catch (err) {
@@ -660,7 +1059,7 @@ const updateTaskExecute = wrapExecute(async (args) => {
660
1059
  * Пауза/возобновление задачи. Для матрицы операция применяется ко всем
661
1060
  * клонам: сам родитель никогда не выполняется.
662
1061
  */
663
- async function pauseOrResumeTask(name, paused) {
1062
+ async function pauseOrResumeTask(name, paused, until) {
664
1063
  const trimmed = name.trim();
665
1064
  const definition = getTask(trimmed);
666
1065
  if (!definition) {
@@ -671,6 +1070,28 @@ async function pauseOrResumeTask(name, paused) {
671
1070
  warnings: [],
672
1071
  };
673
1072
  }
1073
+ // Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
1074
+ let pausedUntil;
1075
+ if (paused && until?.trim()) {
1076
+ const parsed = Date.parse(until.trim());
1077
+ if (Number.isNaN(parsed)) {
1078
+ return {
1079
+ success: false,
1080
+ message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
1081
+ affected: [],
1082
+ warnings: [],
1083
+ };
1084
+ }
1085
+ if (parsed <= Date.now()) {
1086
+ return {
1087
+ success: false,
1088
+ message: `Задача "${trimmed}": дата паузы уже прошла.`,
1089
+ affected: [],
1090
+ warnings: [],
1091
+ };
1092
+ }
1093
+ pausedUntil = new Date(parsed).toISOString();
1094
+ }
674
1095
  const targets = definition.matrix
675
1096
  ? listMatrixClones(trimmed).map((clone) => clone.name)
676
1097
  : [trimmed];
@@ -698,11 +1119,31 @@ async function pauseOrResumeTask(name, paused) {
698
1119
  warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
699
1120
  }
700
1121
  }
1122
+ // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
1123
+ // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
1124
+ const definitionUpdates = paused
1125
+ ? pausedUntil
1126
+ ? { pausedUntil }
1127
+ : undefined
1128
+ : definition.pausedUntil
1129
+ ? { pausedUntil: undefined }
1130
+ : undefined;
1131
+ if (definitionUpdates && affected.length > 0) {
1132
+ try {
1133
+ saveTask({ ...definition, ...definitionUpdates });
1134
+ }
1135
+ catch (err) {
1136
+ warnings.push(`не удалось сохранить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1137
+ }
1138
+ }
1139
+ const untilText = pausedUntil
1140
+ ? ` до ${new Date(pausedUntil).toLocaleString()}`
1141
+ : "";
701
1142
  const verb = paused ? "поставлена на паузу" : "возобновлена";
702
1143
  const message = definition.matrix
703
- ? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
1144
+ ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
704
1145
  (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
705
- : `Задача "${trimmed}" ${verb}.` +
1146
+ : `Задача "${trimmed}" ${verb}${untilText}.` +
706
1147
  (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
707
1148
  return {
708
1149
  success: warnings.length === 0,
@@ -712,13 +1153,90 @@ async function pauseOrResumeTask(name, paused) {
712
1153
  };
713
1154
  }
714
1155
  const pauseTaskExecute = wrapExecute(async (args) => {
715
- const result = await pauseOrResumeTask(args.name, true);
1156
+ const result = await pauseOrResumeTask(args.name, true, args.until);
716
1157
  return { content: JSON.stringify(result) };
717
1158
  });
718
1159
  const resumeTaskExecute = wrapExecute(async (args) => {
719
1160
  const result = await pauseOrResumeTask(args.name, false);
720
1161
  return { content: JSON.stringify(result) };
721
1162
  });
1163
+ /** Периодичность проверки автопродолжения задач (Спринт 19). */
1164
+ const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
1165
+ /** Период проверки дайджеста и зависших матриц (Спринт 20). */
1166
+ const NOTIFICATION_CHECK_MS = 60 * 1000;
1167
+ /**
1168
+ * Спринт 19: автопродолжение задач, поставленных на паузу до даты.
1169
+ * Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
1170
+ * Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
1171
+ */
1172
+ async function resumeExpiredPauses() {
1173
+ const now = Date.now();
1174
+ const definitions = await loadTaskDefinitions();
1175
+ for (const definition of definitions) {
1176
+ if (!definition.pausedUntil)
1177
+ continue;
1178
+ if (definition.matrixParentId)
1179
+ continue;
1180
+ const untilMs = Date.parse(definition.pausedUntil);
1181
+ if (!Number.isFinite(untilMs) || untilMs > now)
1182
+ continue;
1183
+ try {
1184
+ const targets = definition.matrix
1185
+ ? listMatrixClones(definition.name).map((clone) => clone.name)
1186
+ : [definition.name];
1187
+ for (const target of targets) {
1188
+ await scheduler.resumeTask(target);
1189
+ }
1190
+ await saveTaskDefinition({ ...definition, pausedUntil: undefined });
1191
+ console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
1192
+ }
1193
+ catch (err) {
1194
+ console.error(`[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${err instanceof Error ? err.message : String(err)}`);
1195
+ }
1196
+ }
1197
+ }
1198
+ /** Уже отправленные уведомления о зависших клонах (id записи истории). */
1199
+ const notifiedStuckRecords = new Set();
1200
+ /**
1201
+ * Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
1202
+ * `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
1203
+ */
1204
+ async function checkStuckMatrices() {
1205
+ const settings = await loadSettings();
1206
+ const config = settings.notifications;
1207
+ if (!config?.enabled)
1208
+ return;
1209
+ const matrix = config.matrix;
1210
+ if (!matrix?.enabled)
1211
+ return;
1212
+ const threshold = matrix.stuckAfterMinutes;
1213
+ if (!Number.isFinite(threshold) || threshold <= 0)
1214
+ return;
1215
+ const running = listRunningRecords();
1216
+ if (running.length === 0) {
1217
+ notifiedStuckRecords.clear();
1218
+ return;
1219
+ }
1220
+ // Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
1221
+ const runningIds = new Set(running.map((record) => record.id));
1222
+ for (const id of notifiedStuckRecords) {
1223
+ if (!runningIds.has(id))
1224
+ notifiedStuckRecords.delete(id);
1225
+ }
1226
+ const parentByClone = new Map();
1227
+ for (const definition of await loadTaskDefinitions()) {
1228
+ if (definition.matrixParentId) {
1229
+ parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
1230
+ }
1231
+ }
1232
+ const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
1233
+ for (const item of stuck) {
1234
+ if (notifiedStuckRecords.has(item.id))
1235
+ continue;
1236
+ notifiedStuckRecords.add(item.id);
1237
+ await notifyStuckMatrix(item);
1238
+ }
1239
+ }
722
1240
  /** get_history — история запусков с фильтрами по задаче и статусу. */
723
1241
  const getHistoryExecute = wrapExecute(async (args) => {
724
1242
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
@@ -783,6 +1301,23 @@ const dryRunExecute = wrapExecute(async (args) => {
783
1301
  }),
784
1302
  };
785
1303
  });
1304
+ /**
1305
+ * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1306
+ * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
1307
+ */
1308
+ async function refreshWorkspaceEnvFiles(workspaceId) {
1309
+ const workspace = getWorkspace(workspaceId);
1310
+ if (!workspace)
1311
+ return 0;
1312
+ let refreshed = 0;
1313
+ for (const task of await loadTaskDefinitions()) {
1314
+ if (task.workspaceId !== workspaceId)
1315
+ continue;
1316
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
1317
+ refreshed += 1;
1318
+ }
1319
+ return refreshed;
1320
+ }
786
1321
  /** manage_workspaces — CRUD multi-repo workspace-ов. */
787
1322
  const manageWorkspacesExecute = wrapExecute(async (args) => {
788
1323
  try {
@@ -790,6 +1325,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
790
1325
  case "list": {
791
1326
  const workspaces = listWorkspaces().map((workspace) => ({
792
1327
  ...workspace,
1328
+ env: maskEnvForLog(workspace.env),
793
1329
  gitBranch: readGitBranch(workspace.path) ?? null,
794
1330
  }));
795
1331
  return {
@@ -813,12 +1349,15 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
813
1349
  name: args.name,
814
1350
  path: args.path,
815
1351
  color: args.color,
1352
+ env: args.env,
1353
+ envFile: args.envFile,
816
1354
  });
817
1355
  return {
818
1356
  content: JSON.stringify({
819
1357
  success: true,
820
1358
  workspace: {
821
1359
  ...workspace,
1360
+ env: maskEnvForLog(workspace.env),
822
1361
  gitBranch: readGitBranch(workspace.path) ?? null,
823
1362
  },
824
1363
  }),
@@ -837,6 +1376,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
837
1376
  name: args.name,
838
1377
  path: args.path,
839
1378
  color: args.color,
1379
+ env: args.env,
1380
+ envFile: args.envFile,
840
1381
  });
841
1382
  if (!workspace) {
842
1383
  return {
@@ -846,11 +1387,16 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
846
1387
  }),
847
1388
  };
848
1389
  }
1390
+ // Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
1391
+ // файл при запуске, поэтому ждать обновления задачи не нужно.
1392
+ const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
849
1393
  return {
850
1394
  content: JSON.stringify({
851
1395
  success: true,
1396
+ refreshedTasks,
852
1397
  workspace: {
853
1398
  ...workspace,
1399
+ env: maskEnvForLog(workspace.env),
854
1400
  gitBranch: readGitBranch(workspace.path) ?? null,
855
1401
  },
856
1402
  }),
@@ -886,8 +1432,31 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
886
1432
  };
887
1433
  }
888
1434
  });
889
- /** matrix_control — результаты, отмена и очистка матриц. */
1435
+ /** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
890
1436
  const matrixControlExecute = wrapExecute(async (args) => {
1437
+ if (args.action === "preview") {
1438
+ const clones = expandMatrixTask({
1439
+ name: (args.name ?? "").trim() || "task",
1440
+ schedule: "* * * * *",
1441
+ prompt: "preview",
1442
+ matrix: {
1443
+ workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
1444
+ strategy: args.strategy,
1445
+ failureMode: args.failureMode,
1446
+ aggregation: args.aggregation,
1447
+ },
1448
+ });
1449
+ return {
1450
+ content: JSON.stringify({
1451
+ success: true,
1452
+ clones: clones.map((clone) => ({
1453
+ name: clone.name,
1454
+ workspaceId: clone.workspaceId ?? "",
1455
+ workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
1456
+ })),
1457
+ }),
1458
+ };
1459
+ }
891
1460
  if (args.action === "cleanup") {
892
1461
  const removed = await cleanupOrphanedMatrixTasks();
893
1462
  return {
@@ -942,6 +1511,272 @@ const matrixControlExecute = wrapExecute(async (args) => {
942
1511
  };
943
1512
  }
944
1513
  });
1514
+ /** get_metrics — суммарная статистика запусков. */
1515
+ const getMetricsExecute = wrapExecute(async () => {
1516
+ const metrics = await loadMetrics();
1517
+ return { content: JSON.stringify({ success: true, metrics }) };
1518
+ });
1519
+ /** get_analytics — аналитика запусков и стоимости за период. */
1520
+ const getAnalyticsExecute = wrapExecute(async (args) => {
1521
+ const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
1522
+ const records = getHistory(null, 20000);
1523
+ const definitions = await loadTaskDefinitions();
1524
+ const report = buildAnalytics(records, {
1525
+ days: windowDays,
1526
+ topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
1527
+ tasks: definitions.map((definition) => ({
1528
+ name: definition.name,
1529
+ matrixParentId: definition.matrixParentId,
1530
+ })),
1531
+ });
1532
+ return { content: JSON.stringify({ success: true, report }) };
1533
+ });
1534
+ /** manage_settings — чтение и изменение глобальных настроек. */
1535
+ const manageSettingsExecute = wrapExecute(async (args) => {
1536
+ const current = await loadSettings();
1537
+ if (args.action === "get") {
1538
+ return { content: JSON.stringify({ success: true, settings: current }) };
1539
+ }
1540
+ if (args.maxConcurrent === undefined &&
1541
+ args.winterMode === undefined &&
1542
+ args.notifications === undefined &&
1543
+ args.history === undefined &&
1544
+ args.integrations === undefined) {
1545
+ return {
1546
+ content: JSON.stringify({
1547
+ success: false,
1548
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
1549
+ settings: current,
1550
+ }),
1551
+ };
1552
+ }
1553
+ const settings = await saveSettings({
1554
+ maxConcurrent: args.maxConcurrent,
1555
+ winterMode: args.winterMode,
1556
+ notifications: args.notifications,
1557
+ history: args.history,
1558
+ integrations: args.integrations,
1559
+ });
1560
+ return { content: JSON.stringify({ success: true, settings }) };
1561
+ });
1562
+ /** manage_templates — список, сохранение и удаление шаблонов задач. */
1563
+ const manageTemplatesExecute = wrapExecute(async (args) => {
1564
+ if (args.action === "list") {
1565
+ return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
1566
+ }
1567
+ if (args.action === "delete") {
1568
+ const id = args.id?.trim();
1569
+ if (!id) {
1570
+ return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
1571
+ }
1572
+ const before = await loadTemplates();
1573
+ const existed = before.some((template) => template.id === id);
1574
+ await deleteTemplate(id);
1575
+ return {
1576
+ content: JSON.stringify({
1577
+ success: existed,
1578
+ message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
1579
+ }),
1580
+ };
1581
+ }
1582
+ const { action, ...fields } = args;
1583
+ if (!fields.name?.trim() || !fields.prompt?.trim()) {
1584
+ return {
1585
+ content: JSON.stringify({
1586
+ success: false,
1587
+ error: "Для action=save нужны непустые name и prompt.",
1588
+ }),
1589
+ };
1590
+ }
1591
+ const template = await saveTemplate(fields);
1592
+ return { content: JSON.stringify({ success: true, template }) };
1593
+ });
1594
+ /** manage_profiles — список, создание, переключение и удаление профилей. */
1595
+ const manageProfilesExecute = wrapExecute(async (args) => {
1596
+ if (args.action === "list") {
1597
+ return {
1598
+ content: JSON.stringify({
1599
+ success: true,
1600
+ current: getProfileName(),
1601
+ pinnedByEnv: isProfilePinnedByEnv(),
1602
+ profiles: listProfiles(),
1603
+ }),
1604
+ };
1605
+ }
1606
+ const name = args.name?.trim();
1607
+ if (!name) {
1608
+ return {
1609
+ content: JSON.stringify({
1610
+ success: false,
1611
+ error: `Для action=${args.action} нужно имя профиля.`,
1612
+ }),
1613
+ };
1614
+ }
1615
+ if (args.action === "create") {
1616
+ const meta = createProfile(name, args.port);
1617
+ const profile = listProfiles().find((item) => item.name === meta.name);
1618
+ return {
1619
+ content: JSON.stringify({
1620
+ success: true,
1621
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
1622
+ profile: profile ?? {
1623
+ name: meta.name,
1624
+ dir: getProfileDir(meta.name),
1625
+ port: meta.port,
1626
+ isDefault: meta.name === DEFAULT_PROFILE,
1627
+ active: meta.name === getProfileName(),
1628
+ },
1629
+ }),
1630
+ };
1631
+ }
1632
+ if (args.action === "switch") {
1633
+ setActiveProfile(name);
1634
+ const current = getProfileName();
1635
+ return {
1636
+ content: JSON.stringify({
1637
+ success: true,
1638
+ current,
1639
+ restartRequired: true,
1640
+ message: isProfilePinnedByEnv()
1641
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
1642
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
1643
+ }),
1644
+ };
1645
+ }
1646
+ const removed = deleteProfile(name);
1647
+ return {
1648
+ content: JSON.stringify({
1649
+ success: removed,
1650
+ message: removed
1651
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
1652
+ : "Профиль не найден.",
1653
+ }),
1654
+ };
1655
+ });
1656
+ /** transfer_tasks — экспорт и импорт задач. */
1657
+ const transferTasksExecute = wrapExecute(async (args) => {
1658
+ if (args.action === "export") {
1659
+ const tasks = await scheduler.listTasks();
1660
+ const { data, count } = await buildExportJson(tasks.map((task) => ({ ...task, name: task.taskName || "" })));
1661
+ return { content: JSON.stringify({ success: true, data, count }) };
1662
+ }
1663
+ if (!args.data) {
1664
+ return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
1665
+ }
1666
+ const parsed = parseImportJson(args.data);
1667
+ if (parsed.tasks.length === 0) {
1668
+ return {
1669
+ content: JSON.stringify({
1670
+ success: false,
1671
+ error: "В данных нет задач для импорта.",
1672
+ errors: parsed.errors,
1673
+ }),
1674
+ };
1675
+ }
1676
+ const imported = [];
1677
+ const errors = [...parsed.errors];
1678
+ for (const def of parsed.tasks) {
1679
+ try {
1680
+ 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, def.runAt);
1681
+ await saveTaskDefinition(def);
1682
+ imported.push(def.name);
1683
+ }
1684
+ catch (err) {
1685
+ errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
1686
+ }
1687
+ }
1688
+ await refreshFileTriggers();
1689
+ return {
1690
+ content: JSON.stringify({ success: errors.length === 0, imported, errors }),
1691
+ };
1692
+ });
1693
+ /** send_notification — тестовое уведомление или дайджест. */
1694
+ const sendNotificationExecute = wrapExecute(async (args) => {
1695
+ const result = args.action === "test"
1696
+ ? await sendTestNotification()
1697
+ : await sendDigestNow({ updateLastSentAt: false });
1698
+ return { content: JSON.stringify(result) };
1699
+ });
1700
+ /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
1701
+ const getDashboardInfoExecute = wrapExecute(async () => {
1702
+ const port = getDashboardPort();
1703
+ return {
1704
+ content: JSON.stringify({
1705
+ success: true,
1706
+ port,
1707
+ url: port ? `http://127.0.0.1:${port}` : null,
1708
+ platform: scheduler.platform,
1709
+ title: scheduler.title,
1710
+ profile: getProfileName(),
1711
+ }),
1712
+ };
1713
+ });
1714
+ /** cleanup_history — удаление старых записей истории. */
1715
+ const cleanupHistoryExecute = wrapExecute(async (args) => {
1716
+ const report = await runHistoryRetention({
1717
+ retentionDays: args.retentionDays,
1718
+ maxRecords: args.maxRecords,
1719
+ });
1720
+ return {
1721
+ content: JSON.stringify({
1722
+ success: true,
1723
+ message: report.skipped
1724
+ ? report.skipped
1725
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
1726
+ report,
1727
+ }),
1728
+ };
1729
+ });
1730
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
1731
+ const emitEventExecute = wrapExecute(async (args) => {
1732
+ const eventName = args.eventName?.trim();
1733
+ if (!eventName) {
1734
+ return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
1735
+ }
1736
+ const payload = args.payload ?? {};
1737
+ const definitions = await loadTaskDefinitions();
1738
+ const matched = definitions
1739
+ .filter((def) => def.triggerType === "mcp-event" &&
1740
+ def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
1741
+ matchesEventFilter(def.mcpEvent?.filter, payload))
1742
+ .sort((a, b) => (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0));
1743
+ const triggered = [];
1744
+ for (const def of matched) {
1745
+ try {
1746
+ await runTaskEntry(def.name);
1747
+ triggered.push(def.name);
1748
+ }
1749
+ catch (err) {
1750
+ console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
1751
+ }
1752
+ }
1753
+ return {
1754
+ content: JSON.stringify({
1755
+ success: true,
1756
+ message: triggered.length > 0
1757
+ ? `Запущено задач: ${triggered.length}.`
1758
+ : `Нет задач, подписанных на событие "${eventName}".`,
1759
+ triggered,
1760
+ }),
1761
+ };
1762
+ });
1763
+ /**
1764
+ * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
1765
+ * обновлять после создания/изменения/удаления задачи. Раньше refresh()
1766
+ * вызывался только при старте плагина, из-за чего новые watchPath начинали
1767
+ * работать лишь после перезапуска OpenCode.
1768
+ */
1769
+ let fileWatcherManager = null;
1770
+ async function refreshFileTriggers() {
1771
+ if (!fileWatcherManager)
1772
+ return;
1773
+ try {
1774
+ await fileWatcherManager.refresh();
1775
+ }
1776
+ catch (err) {
1777
+ console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
1778
+ }
1779
+ }
945
1780
  export default Plugin.define({
946
1781
  id: "opencode-windows-scheduler",
947
1782
  setup: async (ctx) => {
@@ -978,6 +1813,28 @@ export default Plugin.define({
978
1813
  .catch((err) => {
979
1814
  console.error(`[retention] Не удалось очистить историю: ${err instanceof Error ? err.message : String(err)}`);
980
1815
  });
1816
+ // Спринт 19: автопродолжение задач, поставленных на паузу до даты.
1817
+ // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
1818
+ void resumeExpiredPauses().catch((err) => {
1819
+ console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1820
+ });
1821
+ const pausedUntilTimer = setInterval(() => {
1822
+ void resumeExpiredPauses().catch((err) => {
1823
+ console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1824
+ });
1825
+ }, PAUSED_UNTIL_CHECK_MS);
1826
+ pausedUntilTimer.unref?.();
1827
+ // Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
1828
+ // старте и далее раз в минуту; таймер не держит процесс Node живым.
1829
+ const notificationTimer = setInterval(() => {
1830
+ void maybeSendDigest().catch(() => undefined);
1831
+ void checkStuckMatrices().catch((err) => {
1832
+ console.error(`[windows-scheduler] Детектор зависших матриц: ${err instanceof Error ? err.message : String(err)}`);
1833
+ });
1834
+ }, NOTIFICATION_CHECK_MS);
1835
+ notificationTimer.unref?.();
1836
+ void maybeSendDigest().catch(() => undefined);
1837
+ void checkStuckMatrices().catch(() => undefined);
981
1838
  // Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
982
1839
  const lockManager = new LockManager(LOCK_DIR);
983
1840
  await lockManager.initialize();
@@ -998,20 +1855,23 @@ export default Plugin.define({
998
1855
  continue;
999
1856
  if (!def.schedule)
1000
1857
  continue;
1001
- const prevRun = previousRunTime(def.schedule, now);
1002
- if (!prevRun)
1858
+ // Задача на паузе до даты — её включит авто-продолжение.
1859
+ if (def.pausedUntil)
1003
1860
  continue;
1004
- const ageMs = now.getTime() - prevRun.getTime();
1861
+ const prev = prevRun(def.schedule, now, def.timezone);
1862
+ if (!prev)
1863
+ continue;
1864
+ const ageMs = now.getTime() - prev.getTime();
1005
1865
  if (ageMs < catchUpThresholdMs)
1006
1866
  continue;
1007
1867
  // Есть ли запись в истории после предполагаемого времени запуска?
1008
1868
  const ranAfter = history.some((r) => r.taskName.toLowerCase() === def.name.toLowerCase() &&
1009
- new Date(r.startedAt).getTime() >= prevRun.getTime());
1869
+ new Date(r.startedAt).getTime() >= prev.getTime());
1010
1870
  if (ranAfter)
1011
1871
  continue;
1012
1872
  // Запускаем задачу и пишем в лог.
1013
1873
  try {
1014
- await scheduler.runTask(def.name);
1874
+ await runTaskEntry(def.name);
1015
1875
  console.log(`[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`);
1016
1876
  }
1017
1877
  catch (err) {
@@ -1025,16 +1885,16 @@ export default Plugin.define({
1025
1885
  })();
1026
1886
  // Файловые триггеры (File Watchers): задачи с triggerType === "file"
1027
1887
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
1028
- const fileWatcherManager = new FileWatchManager(async (taskName) => {
1888
+ fileWatcherManager = new FileWatchManager(async (taskName) => {
1029
1889
  try {
1030
- await scheduler.runTask(taskName);
1890
+ await runTaskEntry(taskName);
1031
1891
  console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
1032
1892
  }
1033
1893
  catch (err) {
1034
1894
  console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
1035
1895
  }
1036
1896
  });
1037
- void fileWatcherManager.refresh();
1897
+ void refreshFileTriggers();
1038
1898
  const registration = await ctx.tool.transform((editor) => {
1039
1899
  // editor.add регистрирует новые инструменты плагина с codemode: true,
1040
1900
  // чтобы они были видны в Code Mode. Встроенные schedule_* отключены
@@ -1126,10 +1986,80 @@ export default Plugin.define({
1126
1986
  editor.add({
1127
1987
  name: "matrix_control",
1128
1988
  input: matrixControlSchema,
1129
- 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).",
1989
+ 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).",
1130
1990
  options: { codemode: true },
1131
1991
  execute: matrixControlExecute,
1132
1992
  });
1993
+ editor.add({
1994
+ name: "get_metrics",
1995
+ input: getMetricsSchema,
1996
+ description: "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
1997
+ options: { codemode: true },
1998
+ execute: getMetricsExecute,
1999
+ });
2000
+ editor.add({
2001
+ name: "get_analytics",
2002
+ input: getAnalyticsSchema,
2003
+ description: "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
2004
+ options: { codemode: true },
2005
+ execute: getAnalyticsExecute,
2006
+ });
2007
+ editor.add({
2008
+ name: "manage_settings",
2009
+ input: manageSettingsSchema,
2010
+ 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.",
2011
+ options: { codemode: true },
2012
+ execute: manageSettingsExecute,
2013
+ });
2014
+ editor.add({
2015
+ name: "manage_templates",
2016
+ input: manageTemplatesSchema,
2017
+ description: "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2018
+ options: { codemode: true },
2019
+ execute: manageTemplatesExecute,
2020
+ });
2021
+ editor.add({
2022
+ name: "manage_profiles",
2023
+ input: manageProfilesSchema,
2024
+ description: "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2025
+ options: { codemode: true },
2026
+ execute: manageProfilesExecute,
2027
+ });
2028
+ editor.add({
2029
+ name: "transfer_tasks",
2030
+ input: transferTasksSchema,
2031
+ description: "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2032
+ options: { codemode: true },
2033
+ execute: transferTasksExecute,
2034
+ });
2035
+ editor.add({
2036
+ name: "send_notification",
2037
+ input: sendNotificationSchema,
2038
+ description: "Sends a test notification through the configured channel or sends the digest immediately.",
2039
+ options: { codemode: true },
2040
+ execute: sendNotificationExecute,
2041
+ });
2042
+ editor.add({
2043
+ name: "get_dashboard_info",
2044
+ input: getDashboardInfoSchema,
2045
+ description: "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
2046
+ options: { codemode: true },
2047
+ execute: getDashboardInfoExecute,
2048
+ });
2049
+ editor.add({
2050
+ name: "cleanup_history",
2051
+ input: cleanupHistorySchema,
2052
+ description: "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2053
+ options: { codemode: true },
2054
+ execute: cleanupHistoryExecute,
2055
+ });
2056
+ editor.add({
2057
+ name: "emit_event",
2058
+ input: emitEventSchema,
2059
+ description: "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
2060
+ options: { codemode: true },
2061
+ execute: emitEventExecute,
2062
+ });
1133
2063
  });
1134
2064
  // Нативный скилл плагина: агент видит краткое описание в списке доступных
1135
2065
  // скиллов и подгружает инструкцию только когда задача действительно про
@@ -1162,9 +2092,30 @@ export default Plugin.define({
1162
2092
  },
1163
2093
  create_task: async (input) => {
1164
2094
  console.log("[windows-scheduler] create_task input:", input);
1165
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, } = input;
2095
+ 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, runAt, delaySeconds, session, sessionMaxRuns, } = input;
2096
+ let effectiveRunAt;
2097
+ if (triggerType === "once") {
2098
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
2099
+ if (!normalized.ok) {
2100
+ return { success: false, message: `Задача "${name}": ${normalized.error}` };
2101
+ }
2102
+ effectiveRunAt = normalized.runAt;
2103
+ }
2104
+ let effectiveSession = "new";
2105
+ if (session !== undefined) {
2106
+ const normalizedSession = normalizeSessionMode(session);
2107
+ if (!normalizedSession) {
2108
+ return { success: false, message: `Задача "${name}": неизвестный режим сессии "${String(session)}".` };
2109
+ }
2110
+ effectiveSession = normalizedSession;
2111
+ }
2112
+ if (sessionMaxRuns !== undefined &&
2113
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
2114
+ return { success: false, message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.` };
2115
+ }
2116
+ const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
1166
2117
  try {
1167
- await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
2118
+ 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, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
1168
2119
  return { success: true, message: `Задача "${name}" успешно создана.` };
1169
2120
  }
1170
2121
  catch (err) {
@@ -1279,7 +2230,7 @@ export default Plugin.define({
1279
2230
  const triggered = [];
1280
2231
  for (const def of matched) {
1281
2232
  try {
1282
- await scheduler.runTask(def.name);
2233
+ await runTaskEntry(def.name);
1283
2234
  triggered.push(def.name);
1284
2235
  console.log(`[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
1285
2236
  }
@@ -1294,8 +2245,8 @@ export default Plugin.define({
1294
2245
  };
1295
2246
  },
1296
2247
  pause_task: async (input) => {
1297
- const { name } = input;
1298
- const result = await pauseOrResumeTask(name, true);
2248
+ const { name, until } = input;
2249
+ const result = await pauseOrResumeTask(name, true, until);
1299
2250
  return { success: result.success, message: result.message };
1300
2251
  },
1301
2252
  resume_task: async (input) => {
@@ -1315,9 +2266,16 @@ export default Plugin.define({
1315
2266
  return { success: true, logs: result.logs };
1316
2267
  },
1317
2268
  get_history: async (input) => {
1318
- const { limit } = input;
1319
- const records = await loadHistory();
1320
- return { records: records.slice(0, limit ?? 10) };
2269
+ // Контракт совпадает с агентским инструментом get_history:
2270
+ // limit по умолчанию 20 (максимум 200), фильтры taskName и status.
2271
+ const { limit, taskName, status } = input;
2272
+ const filter = taskName?.trim().toLowerCase();
2273
+ const statusFilter = status?.trim().toLowerCase();
2274
+ const max = Math.max(1, Math.min(Math.floor(limit ?? 20), 200));
2275
+ const records = (await loadHistory())
2276
+ .filter((record) => !filter || record.taskName.toLowerCase() === filter)
2277
+ .filter((record) => !statusFilter || String(record.status).toLowerCase() === statusFilter);
2278
+ return { records: records.slice(0, max) };
1321
2279
  },
1322
2280
  get_metrics: async () => {
1323
2281
  return await loadMetrics();
@@ -1479,15 +2437,23 @@ export default Plugin.define({
1479
2437
  return {
1480
2438
  workspaces: listWorkspaces().map((workspace) => ({
1481
2439
  ...workspace,
2440
+ env: maskEnvForLog(workspace.env),
1482
2441
  gitBranch: readGitBranch(workspace.path) ?? null,
1483
2442
  })),
1484
2443
  };
1485
2444
  },
1486
2445
  add_workspace: async (input) => {
1487
2446
  try {
1488
- const { name, path: workspacePath, color } = input;
1489
- const workspace = addWorkspace({ name, path: workspacePath, color });
1490
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
2447
+ const { name, path: workspacePath, color, env, envFile } = input;
2448
+ const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
2449
+ return {
2450
+ success: true,
2451
+ workspace: {
2452
+ ...workspace,
2453
+ env: maskEnvForLog(workspace.env),
2454
+ gitBranch: readGitBranch(workspace.path) ?? null,
2455
+ },
2456
+ };
1491
2457
  }
1492
2458
  catch (err) {
1493
2459
  return { success: false, error: err instanceof Error ? err.message : String(err) };
@@ -1495,12 +2461,21 @@ export default Plugin.define({
1495
2461
  },
1496
2462
  update_workspace: async (input) => {
1497
2463
  try {
1498
- const { id, name, path: workspacePath, color } = input;
1499
- const workspace = updateWorkspace(id, { name, path: workspacePath, color });
2464
+ const { id, name, path: workspacePath, color, env, envFile } = input;
2465
+ const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
1500
2466
  if (!workspace) {
1501
2467
  return { success: false, error: "Workspace не найден." };
1502
2468
  }
1503
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
2469
+ // env-файлы существующих задач перегенерируются сразу (Спринт 21).
2470
+ await refreshWorkspaceEnvFiles(workspace.id);
2471
+ return {
2472
+ success: true,
2473
+ workspace: {
2474
+ ...workspace,
2475
+ env: maskEnvForLog(workspace.env),
2476
+ gitBranch: readGitBranch(workspace.path) ?? null,
2477
+ },
2478
+ };
1504
2479
  }
1505
2480
  catch (err) {
1506
2481
  return { success: false, error: err instanceof Error ? err.message : String(err) };
@@ -1521,22 +2496,93 @@ export default Plugin.define({
1521
2496
  return { success: false, message: err instanceof Error ? err.message : String(err) };
1522
2497
  }
1523
2498
  },
2499
+ get_profiles: async () => {
2500
+ return {
2501
+ current: getProfileName(),
2502
+ pinnedByEnv: isProfilePinnedByEnv(),
2503
+ profiles: listProfiles(),
2504
+ };
2505
+ },
2506
+ set_profile: async (input) => {
2507
+ const { name } = input;
2508
+ try {
2509
+ setActiveProfile(name);
2510
+ const current = getProfileName();
2511
+ return {
2512
+ success: true,
2513
+ current,
2514
+ restartRequired: true,
2515
+ message: isProfilePinnedByEnv()
2516
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
2517
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
2518
+ };
2519
+ }
2520
+ catch (err) {
2521
+ return {
2522
+ success: false,
2523
+ current: getProfileName(),
2524
+ restartRequired: false,
2525
+ message: err instanceof Error ? err.message : String(err),
2526
+ };
2527
+ }
2528
+ },
2529
+ create_profile: async (input) => {
2530
+ const { name, port } = input;
2531
+ try {
2532
+ const meta = createProfile(name, port);
2533
+ const profile = listProfiles().find((item) => item.name === meta.name);
2534
+ return {
2535
+ success: true,
2536
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2537
+ profile: profile ?? {
2538
+ name: meta.name,
2539
+ dir: getProfileDir(meta.name),
2540
+ port: meta.port,
2541
+ isDefault: meta.name === DEFAULT_PROFILE,
2542
+ active: meta.name === getProfileName(),
2543
+ },
2544
+ };
2545
+ }
2546
+ catch (err) {
2547
+ return {
2548
+ success: false,
2549
+ error: err instanceof Error ? err.message : String(err),
2550
+ };
2551
+ }
2552
+ },
2553
+ delete_profile: async (input) => {
2554
+ const { name } = input;
2555
+ try {
2556
+ const removed = deleteProfile(name);
2557
+ return {
2558
+ success: removed,
2559
+ message: removed
2560
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2561
+ : "Профиль не найден.",
2562
+ };
2563
+ }
2564
+ catch (err) {
2565
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
2566
+ }
2567
+ },
1524
2568
  get_settings: async () => {
1525
2569
  return await loadSettings();
1526
2570
  },
1527
2571
  save_settings: async (input) => {
1528
- const { maxConcurrent, winterMode, notifications, history } = input;
2572
+ const { maxConcurrent, winterMode, notifications, history, integrations } = input;
1529
2573
  const current = await loadSettings();
1530
2574
  if (maxConcurrent === undefined &&
1531
2575
  winterMode === undefined &&
1532
2576
  notifications === undefined &&
1533
- history === undefined) {
2577
+ history === undefined &&
2578
+ integrations === undefined) {
1534
2579
  return {
1535
2580
  success: false,
1536
2581
  maxConcurrent: current.maxConcurrent,
1537
2582
  winterMode: current.winterMode,
1538
2583
  notifications: current.notifications,
1539
2584
  history: current.history,
2585
+ integrations: current.integrations,
1540
2586
  };
1541
2587
  }
1542
2588
  const settings = await saveSettings({
@@ -1544,6 +2590,7 @@ export default Plugin.define({
1544
2590
  winterMode,
1545
2591
  notifications,
1546
2592
  history,
2593
+ integrations,
1547
2594
  });
1548
2595
  return {
1549
2596
  success: true,
@@ -1551,11 +2598,16 @@ export default Plugin.define({
1551
2598
  winterMode: settings.winterMode,
1552
2599
  notifications: settings.notifications,
1553
2600
  history: settings.history,
2601
+ integrations: settings.integrations,
1554
2602
  };
1555
2603
  },
1556
2604
  test_notification: async () => {
1557
2605
  return await sendTestNotification();
1558
2606
  },
2607
+ send_digest: async () => {
2608
+ // Ручная отправка не сдвигает плановое расписание дайджеста.
2609
+ return await sendDigestNow({ updateLastSentAt: false });
2610
+ },
1559
2611
  get_templates: async () => {
1560
2612
  try {
1561
2613
  return { templates: await loadTemplates() };
@@ -1643,7 +2695,7 @@ export default Plugin.define({
1643
2695
  const errors = [...parsed.errors];
1644
2696
  for (const def of parsed.tasks) {
1645
2697
  try {
1646
- 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);
2698
+ 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, def.runAt);
1647
2699
  await saveTaskDefinition(def);
1648
2700
  imported.push(def.name);
1649
2701
  }
@@ -1683,10 +2735,13 @@ export default Plugin.define({
1683
2735
  console.log(`[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`);
1684
2736
  }
1685
2737
  return () => {
2738
+ clearInterval(pausedUntilTimer);
2739
+ clearInterval(notificationTimer);
1686
2740
  rpcRegistration.dispose();
1687
2741
  registration.dispose();
1688
2742
  void skillRegistration?.dispose();
1689
- void fileWatcherManager.stop();
2743
+ if (fileWatcherManager)
2744
+ void fileWatcherManager.stop();
1690
2745
  // При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
1691
2746
  // затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
1692
2747
  void closeDashboardServer().finally(() => closeDb());
@@ -1744,11 +2799,31 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
1744
2799
  */
1745
2800
  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,
1746
2801
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
1747
- matrixMode = "create") {
2802
+ matrixMode = "create",
2803
+ /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
2804
+ timezone,
2805
+ /** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
2806
+ notBefore,
2807
+ /** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
2808
+ notAfter,
2809
+ /** Пауза до момента ISO; после него задача возобновляется автоматически. */
2810
+ pausedUntil,
2811
+ /** Абсолютное время однократного запуска (ISO, только triggerType=once). */
2812
+ runAt,
2813
+ /** Режим сессии OpenCode (Спринт 24): new (по умолчанию), reuse, last. */
2814
+ session,
2815
+ /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
2816
+ sessionId,
2817
+ /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
2818
+ sessionMaxRuns) {
1748
2819
  const normalizedModel = model?.trim() || undefined;
1749
2820
  const normalizedPriority = normalizePriority(priority);
1750
2821
  const normalizedBefore = beforeScript?.trim() || undefined;
1751
2822
  const normalizedAfter = afterScript?.trim() || undefined;
2823
+ const normalizedTz = timezone?.trim() || undefined;
2824
+ const normalizedNotBefore = notBefore?.trim() || undefined;
2825
+ const normalizedNotAfter = notAfter?.trim() || undefined;
2826
+ const normalizedPausedUntil = pausedUntil?.trim() || undefined;
1752
2827
  const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
1753
2828
  ? {
1754
2829
  server: mcpEvent.server?.trim() || "",
@@ -1757,6 +2832,30 @@ matrixMode = "create") {
1757
2832
  }
1758
2833
  : undefined;
1759
2834
  let effectiveTriggerType = triggerType ?? "cron";
2835
+ // One-shot: нормализуем время до создания файлов и задачи в ОС.
2836
+ // Для остальных триггеров runAt не имеет смысла и отбрасывается.
2837
+ let effectiveRunAt;
2838
+ if (effectiveTriggerType === "once") {
2839
+ const normalized = normalizeOneShotRunAt({ runAt });
2840
+ if (!normalized.ok) {
2841
+ throw new Error(`Задача "${name}": ${normalized.error}`);
2842
+ }
2843
+ effectiveRunAt = normalized.runAt;
2844
+ }
2845
+ // Спринт 24: режим сессии. sessionId генерируется автоматически для reuse;
2846
+ // значение пользователя никогда не принимаем.
2847
+ let effectiveSession = "new";
2848
+ let effectiveSessionId;
2849
+ if (session !== undefined) {
2850
+ const normalizedSession = normalizeSessionMode(session);
2851
+ if (!normalizedSession) {
2852
+ throw new Error(`Задача "${name}": неизвестный режим сессии "${String(session)}".`);
2853
+ }
2854
+ effectiveSession = normalizedSession;
2855
+ }
2856
+ if (effectiveSession === "reuse") {
2857
+ effectiveSessionId = sessionId?.trim() || generateSessionId();
2858
+ }
1760
2859
  // Role-scoped: нормализуем списки инструментов (trim, дедуп без регистра).
1761
2860
  // Пустой allowedTools — осознанная блокировка: «белый список из нуля
1762
2861
  // инструментов» это почти наверняка ошибка конфигурации.
@@ -1823,15 +2922,38 @@ matrixMode = "create") {
1823
2922
  // расписание не используется вовсе.
1824
2923
  if (effectiveTriggerType === "cron") {
1825
2924
  try {
1826
- convertCronToSchTasks(schedule);
2925
+ // Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
2926
+ // имена месяцев/дней, @every, L и FRI#3.
2927
+ parseCron(schedule);
1827
2928
  }
1828
2929
  catch (err) {
1829
2930
  throw new Error(err.message || String(err));
1830
2931
  }
2932
+ if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
2933
+ throw new Error(`Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
2934
+ `Укажите IANA-зону, например Europe/Moscow.`);
2935
+ }
2936
+ const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
2937
+ if (windowError) {
2938
+ throw new Error(`Задача "${name}": ${windowError}`);
2939
+ }
1831
2940
  }
1832
2941
  const sanitized = sanitizeName(name);
1833
2942
  const lockFile = lockFilePath(sanitized);
1834
2943
  const logFile = path.join(LOG_DIR, `${sanitized}.log`);
2944
+ // Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
2945
+ // (нестандартный cron или чужая IANA-зона) либо при окне запуска.
2946
+ const gate = effectiveTriggerType === "cron"
2947
+ ? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter)
2948
+ : undefined;
2949
+ const wrapperGate = gate
2950
+ ? {
2951
+ ...gate,
2952
+ gateFile: gatePath,
2953
+ deferFile: `${lockFile}.defer`,
2954
+ forceFile: `${lockFile}.force`,
2955
+ }
2956
+ : undefined;
1835
2957
  // Workspace имеет приоритет над workingDirectory: одна задача = один repo
1836
2958
  // = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
1837
2959
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
@@ -1852,6 +2974,12 @@ matrixMode = "create") {
1852
2974
  }
1853
2975
  }
1854
2976
  const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
2977
+ // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
2978
+ // Значения не логируются; в лог попадает только факт загрузки.
2979
+ const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
2980
+ if (taskEnvFile) {
2981
+ console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
2982
+ }
1855
2983
  let promptFile;
1856
2984
  try {
1857
2985
  promptFile = await writePromptFile(sanitized, prompt);
@@ -1868,7 +2996,7 @@ matrixMode = "create") {
1868
2996
  try {
1869
2997
  if (scheduler.platform === "win32") {
1870
2998
  await ensureWrapper();
1871
- wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools);
2999
+ wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId);
1872
3000
  }
1873
3001
  else {
1874
3002
  wrapperPath = await writeBashWrapper({
@@ -1887,6 +3015,13 @@ matrixMode = "create") {
1887
3015
  workspaceName: workspace?.name,
1888
3016
  allowedTools: normalizedAllowedTools,
1889
3017
  deniedTools: normalizedDeniedTools,
3018
+ scheduleGate: wrapperGate,
3019
+ envFile: taskEnvFile,
3020
+ sessionMode: effectiveSession,
3021
+ sessionId: effectiveSessionId,
3022
+ ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
3023
+ ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized) }
3024
+ : {}),
1890
3025
  });
1891
3026
  }
1892
3027
  }
@@ -1901,17 +3036,23 @@ matrixMode = "create") {
1901
3036
  schedule,
1902
3037
  timeoutSeconds: timeoutSeconds ?? 3600,
1903
3038
  triggerType: effectiveTriggerType,
3039
+ ...(effectiveRunAt ? { runAt: effectiveRunAt } : {}),
1904
3040
  workingDirectory: effectiveWorkingDirectory,
1905
3041
  logFile,
1906
3042
  model: normalizedModel,
1907
3043
  priority: normalizedPriority,
3044
+ timezone: normalizedTz,
3045
+ notBefore: normalizedNotBefore,
3046
+ notAfter: normalizedNotAfter,
1908
3047
  });
1909
3048
  }
1910
3049
  catch (err) {
1911
3050
  throw new Error(err instanceof Error ? err.message : String(err));
1912
3051
  }
1913
3052
  // Сохраняем определение задачи для последующего экспорта/импорта.
1914
- const existingQueue = matrixMode === "sync" ? getTask(name)?.matrixQueue : undefined;
3053
+ // Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
3054
+ const previousDefinition = getTask(name);
3055
+ const existingQueue = matrixMode === "sync" ? previousDefinition?.matrixQueue : undefined;
1915
3056
  const taskDefinition = {
1916
3057
  name,
1917
3058
  schedule,
@@ -1930,7 +3071,20 @@ matrixMode = "create") {
1930
3071
  nextTaskOnSuccess,
1931
3072
  nextTaskOnError,
1932
3073
  triggerType: effectiveTriggerType,
3074
+ runAt: effectiveRunAt,
3075
+ // Спринт 24: сессия. sessionRunCount не экспортируется (internal).
3076
+ session: effectiveSession,
3077
+ sessionId: effectiveSessionId,
3078
+ sessionMaxRuns,
3079
+ // Раньше редактирование всегда сбрасывало счётчик в 0, из-за чего лимит
3080
+ // sessionMaxRuns обходился правкой любого поля задачи. Сохраняем счётчик,
3081
+ // только если сессия и её id не изменились.
3082
+ sessionRunCount: preservedSessionRunCount(previousDefinition, effectiveSession, effectiveSessionId),
1933
3083
  watchPath: normalizedMatrix ? undefined : watchPath,
3084
+ timezone: normalizedTz,
3085
+ notBefore: normalizedNotBefore,
3086
+ notAfter: normalizedNotAfter,
3087
+ pausedUntil: normalizedPausedUntil,
1934
3088
  allowedTools: normalizedAllowedTools,
1935
3089
  deniedTools: normalizedDeniedTools,
1936
3090
  matrix: normalizedMatrix,
@@ -1959,7 +3113,7 @@ matrixMode = "create") {
1959
3113
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
1960
3114
  if (normalizedMatrix) {
1961
3115
  const createClone = async (clone) => {
1962
- 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);
3116
+ 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);
1963
3117
  };
1964
3118
  const removeChild = async (child) => {
1965
3119
  try {
@@ -2030,7 +3184,22 @@ async function runTaskEntry(name) {
2030
3184
  await runMatrix(definition);
2031
3185
  return { alreadyRunning: false };
2032
3186
  }
2033
- return scheduler.runTask(name);
3187
+ // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
3188
+ // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
3189
+ // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
3190
+ // запуск молча отменялся бы schedule-gate с кодом 3.
3191
+ const forceFile = await requestImmediateRun(name);
3192
+ try {
3193
+ return await scheduler.runTask(name);
3194
+ }
3195
+ catch (err) {
3196
+ // Планировщик не принял запуск — маркер не нужен, иначе он мог бы
3197
+ // «разрешить» следующий плановый тик в обход расписания.
3198
+ await fs.unlink(forceFile).catch(() => {
3199
+ /* не критично */
3200
+ });
3201
+ throw err;
3202
+ }
2034
3203
  }
2035
3204
  /**
2036
3205
  * Собирает задачи плагина в формате, который отдают оба потребителя:
@@ -2040,29 +3209,65 @@ async function collectTasksView() {
2040
3209
  const tasks = await scheduler.listTasks();
2041
3210
  // Читаем историю один раз, чтобы определить финальный статус по последней записи.
2042
3211
  const history = await loadHistory();
2043
- const lastByTask = new Map();
2044
- for (const record of history) {
2045
- lastByTask.set(record.taskName, {
2046
- status: record.status,
2047
- error: record.error,
2048
- });
2049
- }
3212
+ // loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
3213
+ const lastByTask = latestHistoryByTask(history);
2050
3214
  // Читаем определения задач один раз (расписание, повторы, цепочки, директория).
2051
3215
  const defs = await loadTaskDefinitions();
2052
3216
  const workspaces = listWorkspaces();
2053
3217
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
2054
- return tasks.map((t) => {
3218
+ // Счётчики запусков по задачам. Основной источник — таблица metrics
3219
+ // (накопительные итоги, не зависят от retention истории). Для задач, у
3220
+ // которых метрик ещё нет, считаем по загруженной истории.
3221
+ const metricsByName = new Map(getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row]));
3222
+ const historyCounts = new Map();
3223
+ for (const record of history) {
3224
+ const key = record.taskName.toLowerCase();
3225
+ const counts = historyCounts.get(key) ?? {
3226
+ total: 0,
3227
+ success: 0,
3228
+ error: 0,
3229
+ partial: 0,
3230
+ };
3231
+ counts.total += 1;
3232
+ if (record.status === "success")
3233
+ counts.success += 1;
3234
+ else if (record.status === "partial")
3235
+ counts.partial += 1;
3236
+ else
3237
+ counts.error += 1;
3238
+ historyCounts.set(key, counts);
3239
+ }
3240
+ // ОС-планировщик — источник истины о запуске, но определения в БД могут
3241
+ // существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
3242
+ // Показываем и их, помечая orphaned: раньше такие задачи были невидимы
3243
+ // для list_tasks, хотя dry_run/история их видели.
3244
+ const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
3245
+ const orphanNames = defs
3246
+ .filter((def) => !osNames.has(def.name.toLowerCase()))
3247
+ .map((def) => def.name);
3248
+ const sources = [
3249
+ ...tasks.map((task) => ({ task, orphaned: false })),
3250
+ ...orphanNames.map((name) => ({
3251
+ task: { taskName: name },
3252
+ orphaned: true,
3253
+ })),
3254
+ ];
3255
+ return sources.map(({ task: t, orphaned }) => {
2055
3256
  // Все бэкенды возвращают короткие имена (без папки планировщика).
2056
3257
  const name = t.taskName || "";
2057
3258
  // Приоритет 1: статус, который сообщает планировщик ОС.
2058
3259
  let status = mapStatus(t.status);
2059
3260
  // Приоритет 2: если последняя запись в истории — error/timeout, перебиваем на error.
2060
- const last = lastByTask.get(name);
2061
- if (last && (last.status === "error" || last.status === "timeout")) {
2062
- status = "error";
2063
- }
2064
- else if (last && last.status === "success") {
2065
- status = "success";
3261
+ const last = lastByTask.get(name.toLowerCase());
3262
+ if (last) {
3263
+ if (last.status === "error" || last.status === "timeout")
3264
+ status = "error";
3265
+ else if (last.status === "success")
3266
+ status = "success";
3267
+ // partial раньше терялся: задача после частичного запуска выглядела
3268
+ // как «готова»/«не запускалась», хотя запуск был неуспешным.
3269
+ else if (last.status === "partial")
3270
+ status = "partial";
2066
3271
  }
2067
3272
  const def = defs.find((d) => d.name.toLowerCase() === name.toLowerCase());
2068
3273
  const workspace = def?.workspaceId ? workspaceById.get(def.workspaceId) : undefined;
@@ -2071,11 +3276,44 @@ async function collectTasksView() {
2071
3276
  if (matrixAggregate && matrixAggregate.status !== "empty") {
2072
3277
  status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
2073
3278
  }
3279
+ // Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
3280
+ // общие итоги по всем задачам — отсюда одинаковые 201/130/71).
3281
+ const metricsRow = metricsByName.get(name.toLowerCase());
3282
+ const counts = metricsRow
3283
+ ? {
3284
+ total: metricsRow.total,
3285
+ success: metricsRow.success,
3286
+ error: metricsRow.error,
3287
+ partial: metricsRow.partial,
3288
+ }
3289
+ : historyCounts.get(name.toLowerCase()) ?? {
3290
+ total: 0,
3291
+ success: 0,
3292
+ error: 0,
3293
+ partial: 0,
3294
+ };
2074
3295
  return {
2075
3296
  name,
2076
3297
  schedule: def?.schedule ?? "",
2077
3298
  status,
2078
- nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
3299
+ orphaned,
3300
+ // Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
3301
+ // из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
3302
+ // поэтому кнопка «возобновить» была недоступна.
3303
+ paused: Boolean(t.paused),
3304
+ runsTotal: counts.total,
3305
+ runsSuccess: counts.success,
3306
+ runsError: counts.error,
3307
+ runsPartial: counts.partial,
3308
+ // Для разовой задачи показываем запланированное время, а не пустое расписание.
3309
+ nextRun: def?.triggerType === "once"
3310
+ ? def?.runAt ?? (t.nextRunTime ? String(t.nextRunTime) : null)
3311
+ : t.nextRunTime ? String(t.nextRunTime) : null,
3312
+ runAt: def?.runAt ?? null,
3313
+ session: def?.session ?? "new",
3314
+ sessionId: def?.sessionId ?? null,
3315
+ sessionMaxRuns: def?.sessionMaxRuns ?? null,
3316
+ sessionRunCount: def?.sessionRunCount ?? 0,
2079
3317
  model: def?.model ?? null,
2080
3318
  priority: def?.priority ?? 5,
2081
3319
  beforeScript: def?.beforeScript ?? null,
@@ -2089,6 +3327,10 @@ async function collectTasksView() {
2089
3327
  dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
2090
3328
  triggerType: def?.triggerType ?? "cron",
2091
3329
  watchPath: def?.watchPath ?? null,
3330
+ timezone: def?.timezone ?? null,
3331
+ notBefore: def?.notBefore ?? null,
3332
+ notAfter: def?.notAfter ?? null,
3333
+ pausedUntil: def?.pausedUntil ?? null,
2092
3334
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
2093
3335
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
2094
3336
  workspaceName: workspace?.name ?? null,
@@ -2151,8 +3393,11 @@ function mapStatus(status) {
2151
3393
  const s = status.toLowerCase();
2152
3394
  if (s.includes("running") || s.includes("выполняется"))
2153
3395
  return "running";
3396
+ // "Ready" в планировщике Windows означает лишь «готова к запуску», а не
3397
+ // успешное выполнение. Раньше такие задачи показывались зелёными, хотя
3398
+ // могли ни разу не запускаться.
2154
3399
  if (s.includes("ready") || s.includes("готов"))
2155
- return "success";
3400
+ return "idle";
2156
3401
  if (s.includes("disabled"))
2157
3402
  return "unknown";
2158
3403
  return "unknown";