opencode-windows-scheduler 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +11 -5
  3. package/ROADMAP-STRATEGY.md +45 -26
  4. package/ROADMAP.md +279 -35
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/dry-run.d.ts +31 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +129 -1
  11. package/dist/core/file-watcher.d.ts.map +1 -1
  12. package/dist/core/file-watcher.js +53 -10
  13. package/dist/core/git-trigger.d.ts +80 -0
  14. package/dist/core/git-trigger.d.ts.map +1 -0
  15. package/dist/core/git-trigger.js +288 -0
  16. package/dist/core/glob.d.ts +38 -0
  17. package/dist/core/glob.d.ts.map +1 -0
  18. package/dist/core/glob.js +233 -0
  19. package/dist/core/ps-wrapper.d.ts.map +1 -1
  20. package/dist/core/ps-wrapper.js +7 -0
  21. package/dist/core/schedule-gate.js +55 -30
  22. package/dist/core/schedule-v2.d.ts +29 -1
  23. package/dist/core/schedule-v2.d.ts.map +1 -1
  24. package/dist/core/schedule-v2.js +81 -3
  25. package/dist/core/scheduler/types.d.ts +1 -1
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/secrets.d.ts +57 -0
  28. package/dist/core/secrets.d.ts.map +1 -0
  29. package/dist/core/secrets.js +331 -0
  30. package/dist/core/structured-log.d.ts.map +1 -1
  31. package/dist/core/structured-log.js +9 -0
  32. package/dist/core/wrappers/bash.d.ts.map +1 -1
  33. package/dist/core/wrappers/bash.js +4 -0
  34. package/dist/db/git-state-repo.d.ts +16 -0
  35. package/dist/db/git-state-repo.d.ts.map +1 -0
  36. package/dist/db/git-state-repo.js +38 -0
  37. package/dist/db/schema.d.ts +1 -1
  38. package/dist/db/schema.d.ts.map +1 -1
  39. package/dist/db/schema.js +23 -0
  40. package/dist/index.d.ts +68 -4
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +589 -45
  43. package/dist/rpc.d.ts +623 -0
  44. package/dist/rpc.d.ts.map +1 -1
  45. package/dist/rpc.js +219 -0
  46. package/dist/server.d.ts.map +1 -1
  47. package/dist/server.js +67 -0
  48. package/dist/settings.d.ts +16 -0
  49. package/dist/settings.d.ts.map +1 -1
  50. package/dist/settings.js +29 -0
  51. package/dist/task-transfer.d.ts +30 -3
  52. package/dist/task-transfer.d.ts.map +1 -1
  53. package/dist/task-transfer.js +83 -6
  54. package/dist/templates.d.ts +1 -1
  55. package/dist/templates.d.ts.map +1 -1
  56. package/dist/workspaces.d.ts +8 -2
  57. package/dist/workspaces.d.ts.map +1 -1
  58. package/dist/workspaces.js +21 -4
  59. package/docs/ARCHITECTURE.md +14 -5
  60. package/docs/FEATURES.md +80 -1
  61. package/docs/README.ru.md +15 -5
  62. package/gui-experimental.cjs +9 -4
  63. package/package.json +8 -3
  64. package/src/core/audit.ts +291 -0
  65. package/src/core/dry-run.ts +188 -1
  66. package/src/core/file-watcher.ts +65 -10
  67. package/src/core/git-trigger.ts +367 -0
  68. package/src/core/glob.ts +226 -0
  69. package/src/core/ps-wrapper.ts +7 -0
  70. package/src/core/schedule-gate.ts +67 -33
  71. package/src/core/schedule-v2.ts +108 -3
  72. package/src/core/scheduler/types.ts +1 -1
  73. package/src/core/secrets.ts +385 -0
  74. package/src/core/structured-log.ts +9 -0
  75. package/src/core/wrappers/bash.ts +4 -0
  76. package/src/db/git-state-repo.ts +62 -0
  77. package/src/db/schema.ts +23 -0
  78. package/src/gui.tsx +548 -4
  79. package/src/index.ts +790 -47
  80. package/src/rpc.ts +230 -0
  81. package/src/server.ts +67 -0
  82. package/src/settings.ts +51 -0
  83. package/src/task-transfer.ts +124 -5
  84. package/src/templates.ts +1 -1
  85. package/src/workspaces.ts +22 -4
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import fs from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { LockManager } from "./core/lock.js";
8
8
  import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
9
- import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
9
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
10
10
  import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
11
11
  import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
12
12
  import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
@@ -26,6 +26,7 @@ import { getAllMetrics } from "./db/metrics-repo.js";
26
26
  import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
27
27
  import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
28
28
  import { FileWatchManager } from "./core/file-watcher.js";
29
+ import { GitTriggerManager } from "./core/git-trigger.js";
29
30
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
30
31
  import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
31
32
  import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
@@ -34,6 +35,8 @@ import { migrateJsonToDb } from "./db/migrate.js";
34
35
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
35
36
  import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
36
37
  import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
38
+ import { deleteSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
39
+ import { readAuditLog, recordAudit, } from "./core/audit.js";
37
40
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
38
41
  const require = createRequire(import.meta.url);
39
42
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -199,9 +202,9 @@ export const scheduleTaskSchema = z.object({
199
202
  .optional()
200
203
  .describe("Compensation/rollback task started after a failed run."),
201
204
  triggerType: z
202
- .enum(["cron", "file", "mcp-event", "once"])
205
+ .enum(["cron", "file", "git", "mcp-event", "once"])
203
206
  .optional()
204
- .describe("Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."),
207
+ .describe("Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds)."),
205
208
  mcpEvent: z
206
209
  .object({
207
210
  server: z.string(),
@@ -214,6 +217,40 @@ export const scheduleTaskSchema = z.object({
214
217
  .string()
215
218
  .optional()
216
219
  .describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
220
+ watchGlobs: z
221
+ .array(z.string())
222
+ .optional()
223
+ .describe("Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."),
224
+ watchIgnore: z
225
+ .array(z.string())
226
+ .optional()
227
+ .describe("Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."),
228
+ gitBranch: z
229
+ .string()
230
+ .optional()
231
+ .describe("Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."),
232
+ gitPaths: z
233
+ .array(z.string())
234
+ .optional()
235
+ .describe("Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."),
236
+ gitIgnore: z
237
+ .array(z.string())
238
+ .optional()
239
+ .describe("Only for triggerType=git: glob masks of changed files to ignore."),
240
+ gitPollSeconds: z
241
+ .number()
242
+ .int()
243
+ .min(5)
244
+ .optional()
245
+ .describe("Only for triggerType=git: polling interval in seconds (default 60, minimum 5)."),
246
+ activeDays: z
247
+ .array(z.number().int().min(0).max(6))
248
+ .optional()
249
+ .describe("Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day."),
250
+ windowPolicy: z
251
+ .enum(["skip", "postpone", "run"])
252
+ .optional()
253
+ .describe("Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway."),
217
254
  workingDirectory: z
218
255
  .string()
219
256
  .optional()
@@ -312,6 +349,40 @@ export const updateTaskSchema = z.object({
312
349
  .string()
313
350
  .optional()
314
351
  .describe("New launch window end HH:MM. Empty string clears the window."),
352
+ activeDays: z
353
+ .array(z.number().int().min(0).max(6))
354
+ .optional()
355
+ .describe("New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction."),
356
+ windowPolicy: z
357
+ .enum(["skip", "postpone", "run"])
358
+ .optional()
359
+ .describe("New behaviour outside the window: postpone (default), skip or run."),
360
+ watchGlobs: z
361
+ .array(z.string())
362
+ .optional()
363
+ .describe("New glob masks for a file trigger. Empty array clears them."),
364
+ watchIgnore: z
365
+ .array(z.string())
366
+ .optional()
367
+ .describe("New ignore masks for a file trigger. Empty array clears them."),
368
+ gitBranch: z
369
+ .string()
370
+ .optional()
371
+ .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
372
+ gitPaths: z
373
+ .array(z.string())
374
+ .optional()
375
+ .describe("New changed-file masks for a git trigger. Empty array clears them."),
376
+ gitIgnore: z
377
+ .array(z.string())
378
+ .optional()
379
+ .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
380
+ gitPollSeconds: z
381
+ .number()
382
+ .int()
383
+ .min(5)
384
+ .optional()
385
+ .describe("New git polling interval in seconds."),
315
386
  prompt: z
316
387
  .string()
317
388
  .optional()
@@ -349,7 +420,7 @@ export const updateTaskSchema = z.object({
349
420
  .optional()
350
421
  .describe("New error-chain task. Empty string clears it."),
351
422
  triggerType: z
352
- .enum(["cron", "file", "mcp-event", "once"])
423
+ .enum(["cron", "file", "git", "mcp-event", "once"])
353
424
  .optional()
354
425
  .describe("New trigger type."),
355
426
  mcpEvent: z
@@ -533,6 +604,10 @@ export const manageSettingsSchema = z.object({
533
604
  .any()
534
605
  .optional()
535
606
  .describe("Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."),
607
+ audit: z
608
+ .any()
609
+ .optional()
610
+ .describe("Audit log settings patch (enabled, retentionDays, maxRecords)."),
536
611
  });
537
612
  /** manage_templates — пользовательские шаблоны задач. */
538
613
  export const manageTemplatesSchema = z.object({
@@ -602,6 +677,29 @@ export const emitEventSchema = z.object({
602
677
  eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
603
678
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
604
679
  });
680
+ /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
681
+ export const manageSecretsSchema = z.object({
682
+ action: z
683
+ .enum(["list", "set", "delete"])
684
+ .describe("list — secret names and previews; set — create or replace; delete — remove by name."),
685
+ name: z
686
+ .string()
687
+ .optional()
688
+ .describe("Secret name ([A-Za-z0-9_.-], max 64 chars). Required for set/delete."),
689
+ value: z.string().optional().describe("Secret value (required for set). Never returned by list."),
690
+ });
691
+ /** get_audit_log — журнал мутаций задач и настроек (Спринт 26). */
692
+ export const getAuditLogSchema = z.object({
693
+ action: z.string().optional().describe("Filter by action, for example task.create."),
694
+ target: z.string().optional().describe("Filter by target name or id."),
695
+ actor: z
696
+ .string()
697
+ .optional()
698
+ .describe("Filter by actor: mcp (agent), gui (dashboard), http (webhook/API)."),
699
+ since: z.string().optional().describe("ISO timestamp lower bound."),
700
+ until: z.string().optional().describe("ISO timestamp upper bound."),
701
+ limit: z.number().int().min(1).max(5000).optional().describe("Max records (default 200)."),
702
+ });
605
703
  /**
606
704
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
607
705
  * директория задачи по умолчанию, чтобы `opencode run` подхватил opencode.json
@@ -629,7 +727,7 @@ function wrapExecute(fn) {
629
727
  }
630
728
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
631
729
  const scheduleTaskExecute = wrapExecute(async (args) => {
632
- 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;
730
+ 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, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, } = args;
633
731
  let effectiveRunAt;
634
732
  if ((triggerType ?? "cron") === "once") {
635
733
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -645,7 +743,16 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
645
743
  const effectiveSession = normalizeSessionMode(session) ?? "new";
646
744
  const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
647
745
  try {
648
- 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);
746
+ 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, {
747
+ activeDays,
748
+ windowPolicy,
749
+ watchGlobs,
750
+ watchIgnore,
751
+ gitBranch,
752
+ gitPaths,
753
+ gitIgnore,
754
+ gitPollSeconds,
755
+ });
649
756
  }
650
757
  catch (err) {
651
758
  return {
@@ -657,7 +764,7 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
657
764
  }
658
765
  // Новый файловый триггер должен начать работать сразу, без перезапуска
659
766
  // OpenCode: пересобираем набор watcher-ов после создания задачи.
660
- await refreshFileTriggers();
767
+ await refreshTriggers();
661
768
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
662
769
  const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
663
770
  return {
@@ -851,7 +958,7 @@ const deleteTaskExecute = wrapExecute(async (args) => {
851
958
  try {
852
959
  const { removed, existed } = await deleteTaskWithFamily(name);
853
960
  // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
854
- await refreshFileTriggers();
961
+ await refreshTriggers();
855
962
  if (!existed && removed.length === 0) {
856
963
  return {
857
964
  content: JSON.stringify({
@@ -1031,20 +1138,44 @@ async function updateTaskFromInput(input) {
1031
1138
  `Запустите матрицу вручную или используйте cron/file-триггер.`,
1032
1139
  };
1033
1140
  }
1141
+ // Спринт 27: параметры триггеров сохраняются, если поле не передано.
1142
+ const mergeStringList = (next, prev) => {
1143
+ if (next === undefined)
1144
+ return prev;
1145
+ const cleaned = next
1146
+ .filter((item) => typeof item === "string")
1147
+ .map((item) => item.trim())
1148
+ .filter(Boolean);
1149
+ return cleaned.length > 0 ? cleaned : undefined;
1150
+ };
1151
+ const triggerExtras = {
1152
+ activeDays: input.activeDays === undefined
1153
+ ? previous.activeDays
1154
+ : input.activeDays.length > 0
1155
+ ? input.activeDays
1156
+ : undefined,
1157
+ windowPolicy: input.windowPolicy ?? previous.windowPolicy,
1158
+ watchGlobs: mergeStringList(input.watchGlobs, previous.watchGlobs),
1159
+ watchIgnore: mergeStringList(input.watchIgnore, previous.watchIgnore),
1160
+ gitBranch: clearableString(input.gitBranch, previous.gitBranch),
1161
+ gitPaths: mergeStringList(input.gitPaths, previous.gitPaths),
1162
+ gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
1163
+ gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
1164
+ };
1034
1165
  try {
1035
1166
  // Обновление = пересоздание в планировщике с сохранением старых значений.
1036
1167
  await scheduler.deleteTask(name);
1037
1168
  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,
1038
1169
  // Если задача была матрицей — синхронизируем клонов, а не
1039
1170
  // пересоздаём их с нуля (Спринт 17).
1040
- matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns);
1171
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras);
1041
1172
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
1042
1173
  if (matrixWas && !matrixNext) {
1043
1174
  await removeMatrixChildrenFromScheduler(name);
1044
1175
  }
1045
1176
  // Пересоздание могло изменить triggerType/watchPath — сразу
1046
1177
  // пересобираем набор файловых watcher-ов.
1047
- await refreshFileTriggers();
1178
+ await refreshTriggers();
1048
1179
  return { success: true, message: `Задача "${name}" обновлена.` };
1049
1180
  }
1050
1181
  catch (err) {
@@ -1545,11 +1676,12 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1545
1676
  args.winterMode === undefined &&
1546
1677
  args.notifications === undefined &&
1547
1678
  args.history === undefined &&
1548
- args.integrations === undefined) {
1679
+ args.integrations === undefined &&
1680
+ args.audit === undefined) {
1549
1681
  return {
1550
1682
  content: JSON.stringify({
1551
1683
  success: false,
1552
- error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
1684
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
1553
1685
  settings: current,
1554
1686
  }),
1555
1687
  };
@@ -1560,6 +1692,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1560
1692
  notifications: args.notifications,
1561
1693
  history: args.history,
1562
1694
  integrations: args.integrations,
1695
+ audit: args.audit,
1563
1696
  });
1564
1697
  return { content: JSON.stringify({ success: true, settings }) };
1565
1698
  });
@@ -1689,7 +1822,7 @@ const transferTasksExecute = wrapExecute(async (args) => {
1689
1822
  errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
1690
1823
  }
1691
1824
  }
1692
- await refreshFileTriggers();
1825
+ await refreshTriggers();
1693
1826
  return {
1694
1827
  content: JSON.stringify({ success: errors.length === 0, imported, errors }),
1695
1828
  };
@@ -1764,6 +1897,180 @@ const emitEventExecute = wrapExecute(async (args) => {
1764
1897
  }),
1765
1898
  };
1766
1899
  });
1900
+ /** manage_secrets — зашифрованное хранилище секретов. */
1901
+ const manageSecretsExecute = wrapExecute(async (args) => {
1902
+ if (args.action === "list") {
1903
+ return { content: JSON.stringify({ success: true, secrets: listSecrets() }) };
1904
+ }
1905
+ const name = (args.name ?? "").trim();
1906
+ if (!name) {
1907
+ return {
1908
+ content: JSON.stringify({
1909
+ success: false,
1910
+ error: "Для set/delete нужно имя секрета.",
1911
+ }),
1912
+ };
1913
+ }
1914
+ if (args.action === "delete") {
1915
+ const existed = hasSecret(name);
1916
+ deleteSecret(name);
1917
+ return {
1918
+ content: JSON.stringify({
1919
+ success: existed,
1920
+ message: existed
1921
+ ? `Секрет ${name} удалён.`
1922
+ : `Секрет ${name} не найден.`,
1923
+ }),
1924
+ };
1925
+ }
1926
+ const value = args.value;
1927
+ if (typeof value !== "string" || value.length === 0) {
1928
+ return {
1929
+ content: JSON.stringify({
1930
+ success: false,
1931
+ error: "Для action=set нужно непустое значение value.",
1932
+ }),
1933
+ };
1934
+ }
1935
+ const item = setSecret(name, value);
1936
+ return {
1937
+ content: JSON.stringify({
1938
+ success: true,
1939
+ message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
1940
+ secret: item,
1941
+ }),
1942
+ };
1943
+ });
1944
+ /** get_audit_log — чтение журнала мутаций. */
1945
+ const getAuditLogExecute = wrapExecute(async (args) => {
1946
+ const result = readAuditLog({
1947
+ action: args.action,
1948
+ target: args.target,
1949
+ actor: args.actor,
1950
+ since: args.since,
1951
+ until: args.until,
1952
+ limit: args.limit,
1953
+ });
1954
+ return { content: JSON.stringify({ success: true, ...result }) };
1955
+ });
1956
+ /**
1957
+ * Оборачивает execute инструмента, записывая успешную мутацию в audit log.
1958
+ * Аудит не должен ломать сам инструмент, поэтому ошибки проглатываются.
1959
+ */
1960
+ function withAudit(toolName, describe, execute) {
1961
+ return async (args, context) => {
1962
+ const result = await execute(args, context);
1963
+ try {
1964
+ const raw = String(result?.content ?? "");
1965
+ const parsed = raw ? JSON.parse(raw) : null;
1966
+ if (parsed?.success === false)
1967
+ return result;
1968
+ const entry = describe(args);
1969
+ if (entry) {
1970
+ recordAudit({ ...entry, actor: "mcp", source: toolName });
1971
+ }
1972
+ }
1973
+ catch {
1974
+ // Аудит — вспомогательная функция: не мешает основной операции.
1975
+ }
1976
+ return result;
1977
+ };
1978
+ }
1979
+ /** Правила аудита для RPC-методов GUI (Спринт 26). */
1980
+ const RPC_AUDIT_RULES = {
1981
+ create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
1982
+ update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
1983
+ delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
1984
+ run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
1985
+ pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
1986
+ resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
1987
+ cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
1988
+ cleanup_matrix_orphans: {
1989
+ action: "matrix.cleanup",
1990
+ targetType: "matrix",
1991
+ target: () => "orphans",
1992
+ },
1993
+ cleanup_history: {
1994
+ action: "history.cleanup",
1995
+ targetType: "history",
1996
+ target: () => "runs",
1997
+ },
1998
+ emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
1999
+ add_workspace: {
2000
+ action: "workspace.add",
2001
+ targetType: "workspace",
2002
+ target: (i) => i.name ?? i.path ?? "",
2003
+ },
2004
+ update_workspace: {
2005
+ action: "workspace.update",
2006
+ targetType: "workspace",
2007
+ target: (i) => i.id ?? "",
2008
+ },
2009
+ delete_workspace: {
2010
+ action: "workspace.delete",
2011
+ targetType: "workspace",
2012
+ target: (i) => i.id ?? "",
2013
+ },
2014
+ set_profile: { action: "profile.switch", targetType: "profile", target: (i) => i.name ?? "" },
2015
+ create_profile: {
2016
+ action: "profile.create",
2017
+ targetType: "profile",
2018
+ target: (i) => i.name ?? "",
2019
+ },
2020
+ delete_profile: {
2021
+ action: "profile.delete",
2022
+ targetType: "profile",
2023
+ target: (i) => i.name ?? "",
2024
+ },
2025
+ import_tasks: { action: "tasks.import", targetType: "tasks", target: () => "snapshot" },
2026
+ save_settings: { action: "settings.update", targetType: "settings", target: () => "global" },
2027
+ save_template: {
2028
+ action: "template.save",
2029
+ targetType: "template",
2030
+ target: (i) => i.id ?? i.name ?? "",
2031
+ },
2032
+ delete_template: {
2033
+ action: "template.delete",
2034
+ targetType: "template",
2035
+ target: (i) => i.id ?? "",
2036
+ },
2037
+ save_secret: { action: "secret.set", targetType: "secret", target: (i) => i.name ?? "" },
2038
+ delete_secret: { action: "secret.delete", targetType: "secret", target: (i) => i.name ?? "" },
2039
+ };
2040
+ /**
2041
+ * Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
2042
+ * с actor=gui. Ошибки аудита не влияют на ответ GUI.
2043
+ */
2044
+ function withRpcAudit(handlers) {
2045
+ const wrapped = {};
2046
+ for (const [name, handler] of Object.entries(handlers)) {
2047
+ const rule = RPC_AUDIT_RULES[name];
2048
+ if (!rule || typeof handler !== "function") {
2049
+ wrapped[name] = handler;
2050
+ continue;
2051
+ }
2052
+ wrapped[name] = async (...args) => {
2053
+ const input = args[0] ?? {};
2054
+ const result = await handler(...args);
2055
+ try {
2056
+ if (result?.success !== false) {
2057
+ recordAudit({
2058
+ action: rule.action,
2059
+ targetType: rule.targetType,
2060
+ target: rule.target(input),
2061
+ actor: "gui",
2062
+ source: name,
2063
+ });
2064
+ }
2065
+ }
2066
+ catch {
2067
+ // Журнал не должен ломать GUI-операцию.
2068
+ }
2069
+ return result;
2070
+ };
2071
+ }
2072
+ return wrapped;
2073
+ }
1767
2074
  /**
1768
2075
  * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
1769
2076
  * обновлять после создания/изменения/удаления задачи. Раньше refresh()
@@ -1771,15 +2078,74 @@ const emitEventExecute = wrapExecute(async (args) => {
1771
2078
  * работать лишь после перезапуска OpenCode.
1772
2079
  */
1773
2080
  let fileWatcherManager = null;
1774
- async function refreshFileTriggers() {
1775
- if (!fileWatcherManager)
2081
+ /**
2082
+ * Спринт 27: менеджер git-триггеров. Опрашивает HEAD задач с
2083
+ * triggerType === "git" и запускает их при новых подходящих коммитах.
2084
+ */
2085
+ let gitTriggerManager = null;
2086
+ /**
2087
+ * Приводит в актуальное состояние все событийные триггеры (файлы и git).
2088
+ * Вызывается после создания, изменения и удаления задачи.
2089
+ */
2090
+ async function refreshTriggers() {
2091
+ if (fileWatcherManager) {
2092
+ try {
2093
+ await fileWatcherManager.refresh();
2094
+ }
2095
+ catch (err) {
2096
+ console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
2097
+ }
2098
+ }
2099
+ if (gitTriggerManager) {
2100
+ try {
2101
+ await gitTriggerManager.refresh();
2102
+ }
2103
+ catch (err) {
2104
+ console.error(`[windows-scheduler] Не удалось обновить git-триггеры: ${err instanceof Error ? err.message : String(err)}`);
2105
+ }
2106
+ }
2107
+ }
2108
+ /** Максимальная задержка переноса событийного запуска (12 часов). */
2109
+ const EVENT_POSTPONE_MAX_MS = 12 * 60 * 60 * 1000;
2110
+ /**
2111
+ * Спринт 27: запуск задачи по событию (файл, git, MCP) с учётом окна запуска
2112
+ * и разрешённых дней недели. Вне окна: skip — пишем причину и выходим,
2113
+ * postpone — таймер до ближайшего открытия, run — запускаем сразу.
2114
+ */
2115
+ async function scheduleEventRun(taskName, reason) {
2116
+ const definition = getTask(taskName);
2117
+ if (!definition)
2118
+ return;
2119
+ const policy = definition.windowPolicy ?? "postpone";
2120
+ const options = {
2121
+ notBefore: definition.notBefore,
2122
+ notAfter: definition.notAfter,
2123
+ days: definition.activeDays,
2124
+ timeZone: definition.timezone,
2125
+ };
2126
+ const now = new Date();
2127
+ const state = activeWindowState(now, options);
2128
+ if (state.active || policy === "run") {
2129
+ await runTaskEntry(taskName);
2130
+ console.log(`[windows-scheduler] Запуск задачи "${taskName}" (${reason}).`);
1776
2131
  return;
1777
- try {
1778
- await fileWatcherManager.refresh();
1779
2132
  }
1780
- catch (err) {
1781
- console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
2133
+ if (policy === "skip") {
2134
+ console.log(`[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${state.reason ?? "вне окна"} — политика skip.`);
2135
+ return;
2136
+ }
2137
+ const delay = nextWindowOpenDelayMs(now, options);
2138
+ if (delay <= 0 || delay > EVENT_POSTPONE_MAX_MS) {
2139
+ console.log(`[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${state.reason ?? "вне окна"} — до открытия окна больше 12 ч.`);
2140
+ return;
1782
2141
  }
2142
+ console.log(`[windows-scheduler] Задача "${taskName}" (${reason}) отложена на ~${Math.round(delay / 60000)} мин: ${state.reason ?? "вне окна"}.`);
2143
+ const timer = setTimeout(() => {
2144
+ void scheduleEventRun(taskName, reason).catch((err) => {
2145
+ console.error(`[windows-scheduler] Не удалось запустить отложенную задачу "${taskName}": ${err instanceof Error ? err.message : String(err)}`);
2146
+ });
2147
+ }, delay);
2148
+ timer.unref?.();
1783
2149
  }
1784
2150
  export default Plugin.define({
1785
2151
  id: "opencode-windows-scheduler",
@@ -1891,14 +2257,23 @@ export default Plugin.define({
1891
2257
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
1892
2258
  fileWatcherManager = new FileWatchManager(async (taskName) => {
1893
2259
  try {
1894
- await runTaskEntry(taskName);
1895
- console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
2260
+ await scheduleEventRun(taskName, "изменение отслеживаемого файла");
1896
2261
  }
1897
2262
  catch (err) {
1898
2263
  console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
1899
2264
  }
1900
2265
  });
1901
- void refreshFileTriggers();
2266
+ // Спринт 27: git-триггеры — опрос HEAD и запуск при новых коммитах,
2267
+ // затронувших подходящие файлы.
2268
+ gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
2269
+ try {
2270
+ await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
2271
+ }
2272
+ catch (err) {
2273
+ console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по git-триггеру: ${err instanceof Error ? err.message : String(err)}`);
2274
+ }
2275
+ });
2276
+ void refreshTriggers();
1902
2277
  const registration = await ctx.tool.transform((editor) => {
1903
2278
  // editor.add регистрирует новые инструменты плагина с codemode: true,
1904
2279
  // чтобы они были видны в Code Mode. Встроенные schedule_* отключены
@@ -1910,7 +2285,7 @@ export default Plugin.define({
1910
2285
  "Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
1911
2286
  "Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
1912
2287
  options: { codemode: true },
1913
- execute: scheduleTaskExecute,
2288
+ execute: withAudit("schedule_task", (args) => ({ action: "task.create", targetType: "task", target: args.name }), scheduleTaskExecute),
1914
2289
  });
1915
2290
  editor.add({
1916
2291
  name: "list_tasks",
@@ -1926,7 +2301,7 @@ export default Plugin.define({
1926
2301
  description: "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
1927
2302
  "Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
1928
2303
  options: { codemode: true },
1929
- execute: updateTaskExecute,
2304
+ execute: withAudit("update_task", (args) => ({ action: "task.update", targetType: "task", target: args.name }), updateTaskExecute),
1930
2305
  });
1931
2306
  editor.add({
1932
2307
  name: "delete_task",
@@ -1934,7 +2309,7 @@ export default Plugin.define({
1934
2309
  description: `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
1935
2310
  "Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
1936
2311
  options: { codemode: true },
1937
- execute: deleteTaskExecute,
2312
+ execute: withAudit("delete_task", (args) => ({ action: "task.delete", targetType: "task", target: args.name }), deleteTaskExecute),
1938
2313
  });
1939
2314
  editor.add({
1940
2315
  name: "run_task_now",
@@ -1942,21 +2317,21 @@ export default Plugin.define({
1942
2317
  description: `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
1943
2318
  "Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
1944
2319
  options: { codemode: true },
1945
- execute: runTaskNowExecute,
2320
+ execute: withAudit("run_task_now", (args) => ({ action: "task.run", targetType: "task", target: args.name }), runTaskNowExecute),
1946
2321
  });
1947
2322
  editor.add({
1948
2323
  name: "pause_task",
1949
2324
  input: pauseTaskSchema,
1950
2325
  description: "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
1951
2326
  options: { codemode: true },
1952
- execute: pauseTaskExecute,
2327
+ execute: withAudit("pause_task", (args) => ({ action: "task.pause", targetType: "task", target: args.name }), pauseTaskExecute),
1953
2328
  });
1954
2329
  editor.add({
1955
2330
  name: "resume_task",
1956
2331
  input: resumeTaskSchema,
1957
2332
  description: "Resumes a previously paused task. For a matrix parent every clone is resumed.",
1958
2333
  options: { codemode: true },
1959
- execute: resumeTaskExecute,
2334
+ execute: withAudit("resume_task", (args) => ({ action: "task.resume", targetType: "task", target: args.name }), resumeTaskExecute),
1960
2335
  });
1961
2336
  editor.add({
1962
2337
  name: "get_history",
@@ -1985,14 +2360,26 @@ export default Plugin.define({
1985
2360
  input: manageWorkspacesSchema,
1986
2361
  description: "Manages multi-repo workspaces: list, add, update or delete. Tasks can target a workspace by id (cwd = workspace path) or fan out to several with matrix.workspaceIds.",
1987
2362
  options: { codemode: true },
1988
- execute: manageWorkspacesExecute,
2363
+ execute: withAudit("manage_workspaces", (args) => args.action === "list"
2364
+ ? null
2365
+ : {
2366
+ action: `workspace.${args.action}`,
2367
+ targetType: "workspace",
2368
+ target: args.id || args.name || "",
2369
+ }, manageWorkspacesExecute),
1989
2370
  });
1990
2371
  editor.add({
1991
2372
  name: "matrix_control",
1992
2373
  input: matrixControlSchema,
1993
2374
  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).",
1994
2375
  options: { codemode: true },
1995
- execute: matrixControlExecute,
2376
+ execute: withAudit("matrix_control", (args) => args.action === "cancel" || args.action === "cleanup"
2377
+ ? {
2378
+ action: `matrix.${args.action}`,
2379
+ targetType: "matrix",
2380
+ target: args.name || "",
2381
+ }
2382
+ : null, matrixControlExecute),
1996
2383
  });
1997
2384
  editor.add({
1998
2385
  name: "get_metrics",
@@ -2013,28 +2400,44 @@ export default Plugin.define({
2013
2400
  input: manageSettingsSchema,
2014
2401
  description: "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, Telegram, native OS notifications, quiet hours, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
2015
2402
  options: { codemode: true },
2016
- execute: manageSettingsExecute,
2403
+ execute: withAudit("manage_settings", (args) => args.action === "update"
2404
+ ? { action: "settings.update", targetType: "settings", target: "global" }
2405
+ : null, manageSettingsExecute),
2017
2406
  });
2018
2407
  editor.add({
2019
2408
  name: "manage_templates",
2020
2409
  input: manageTemplatesSchema,
2021
2410
  description: "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2022
2411
  options: { codemode: true },
2023
- execute: manageTemplatesExecute,
2412
+ execute: withAudit("manage_templates", (args) => args.action === "list"
2413
+ ? null
2414
+ : {
2415
+ action: `template.${args.action}`,
2416
+ targetType: "template",
2417
+ target: args.id || args.name || "",
2418
+ }, manageTemplatesExecute),
2024
2419
  });
2025
2420
  editor.add({
2026
2421
  name: "manage_profiles",
2027
2422
  input: manageProfilesSchema,
2028
2423
  description: "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2029
2424
  options: { codemode: true },
2030
- execute: manageProfilesExecute,
2425
+ execute: withAudit("manage_profiles", (args) => args.action === "list"
2426
+ ? null
2427
+ : {
2428
+ action: `profile.${args.action}`,
2429
+ targetType: "profile",
2430
+ target: args.name || "",
2431
+ }, manageProfilesExecute),
2031
2432
  });
2032
2433
  editor.add({
2033
2434
  name: "transfer_tasks",
2034
2435
  input: transferTasksSchema,
2035
2436
  description: "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2036
2437
  options: { codemode: true },
2037
- execute: transferTasksExecute,
2438
+ execute: withAudit("transfer_tasks", (args) => args.action === "import"
2439
+ ? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
2440
+ : null, transferTasksExecute),
2038
2441
  });
2039
2442
  editor.add({
2040
2443
  name: "send_notification",
@@ -2055,7 +2458,30 @@ export default Plugin.define({
2055
2458
  input: cleanupHistorySchema,
2056
2459
  description: "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2057
2460
  options: { codemode: true },
2058
- execute: cleanupHistoryExecute,
2461
+ execute: withAudit("cleanup_history", () => ({ action: "history.cleanup", targetType: "history", target: "runs" }), cleanupHistoryExecute),
2462
+ });
2463
+ editor.add({
2464
+ name: "manage_secrets",
2465
+ input: manageSecretsSchema,
2466
+ description: "Manages the encrypted secret store: list (names and masked previews), set (create or replace) or delete. " +
2467
+ "Secrets are encrypted with AES-256-GCM at rest and referenced from workspace env as ${secret:NAME}; " +
2468
+ "values are never returned by list and are redacted from logs and audit details.",
2469
+ options: { codemode: true },
2470
+ execute: withAudit("manage_secrets", (args) => args.action === "list"
2471
+ ? null
2472
+ : {
2473
+ action: `secret.${args.action}`,
2474
+ targetType: "secret",
2475
+ target: (args.name ?? "").trim(),
2476
+ }, manageSecretsExecute),
2477
+ });
2478
+ editor.add({
2479
+ name: "get_audit_log",
2480
+ input: getAuditLogSchema,
2481
+ description: "Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
2482
+ "Filter by action, target, actor, time range and limit. Secret values are redacted.",
2483
+ options: { codemode: true },
2484
+ execute: getAuditLogExecute,
2059
2485
  });
2060
2486
  editor.add({
2061
2487
  name: "emit_event",
@@ -2090,7 +2516,7 @@ export default Plugin.define({
2090
2516
  // Регистрируем RPC-методы, вызываемые из GUI-панели.
2091
2517
  // Общая логика создания задачи вынесена в schedulerCreateTask, чтобы
2092
2518
  // schedule_task и create_task использовали один и тот же путь.
2093
- const rpcRegistration = await ctx.rpc.register(SchedulerRpc, {
2519
+ const rpcHandlers = {
2094
2520
  get_tasks: async () => {
2095
2521
  return { tasks: await collectTasksView() };
2096
2522
  },
@@ -2573,13 +2999,14 @@ export default Plugin.define({
2573
2999
  return await loadSettings();
2574
3000
  },
2575
3001
  save_settings: async (input) => {
2576
- const { maxConcurrent, winterMode, notifications, history, integrations } = input;
3002
+ const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input;
2577
3003
  const current = await loadSettings();
2578
3004
  if (maxConcurrent === undefined &&
2579
3005
  winterMode === undefined &&
2580
3006
  notifications === undefined &&
2581
3007
  history === undefined &&
2582
- integrations === undefined) {
3008
+ integrations === undefined &&
3009
+ audit === undefined) {
2583
3010
  return {
2584
3011
  success: false,
2585
3012
  maxConcurrent: current.maxConcurrent,
@@ -2587,6 +3014,7 @@ export default Plugin.define({
2587
3014
  notifications: current.notifications,
2588
3015
  history: current.history,
2589
3016
  integrations: current.integrations,
3017
+ audit: current.audit,
2590
3018
  };
2591
3019
  }
2592
3020
  const settings = await saveSettings({
@@ -2595,6 +3023,7 @@ export default Plugin.define({
2595
3023
  notifications,
2596
3024
  history,
2597
3025
  integrations,
3026
+ audit,
2598
3027
  });
2599
3028
  return {
2600
3029
  success: true,
@@ -2603,6 +3032,7 @@ export default Plugin.define({
2603
3032
  notifications: settings.notifications,
2604
3033
  history: settings.history,
2605
3034
  integrations: settings.integrations,
3035
+ audit: settings.audit,
2606
3036
  };
2607
3037
  },
2608
3038
  test_notification: async () => {
@@ -2612,6 +3042,68 @@ export default Plugin.define({
2612
3042
  // Ручная отправка не сдвигает плановое расписание дайджеста.
2613
3043
  return await sendDigestNow({ updateLastSentAt: false });
2614
3044
  },
3045
+ // --- Спринт 26: секреты и аудит -------------------------------------
3046
+ list_secrets: async () => {
3047
+ return { success: true, secrets: listSecrets() };
3048
+ },
3049
+ save_secret: async (input) => {
3050
+ try {
3051
+ const source = (input ?? {});
3052
+ const name = (source.name ?? "").trim();
3053
+ if (!name) {
3054
+ return { success: false, message: "Нужно имя секрета." };
3055
+ }
3056
+ if (typeof source.value !== "string" || source.value.length === 0) {
3057
+ return { success: false, message: "Нужно непустое значение секрета." };
3058
+ }
3059
+ const secret = setSecret(name, source.value);
3060
+ return {
3061
+ success: true,
3062
+ message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
3063
+ secret,
3064
+ };
3065
+ }
3066
+ catch (err) {
3067
+ return {
3068
+ success: false,
3069
+ message: err instanceof Error ? err.message : String(err),
3070
+ };
3071
+ }
3072
+ },
3073
+ delete_secret: async (input) => {
3074
+ try {
3075
+ const name = ((input ?? {}).name ?? "").trim();
3076
+ if (!name) {
3077
+ return { success: false, message: "Нужно имя секрета." };
3078
+ }
3079
+ const existed = hasSecret(name);
3080
+ deleteSecret(name);
3081
+ return {
3082
+ success: existed,
3083
+ message: existed
3084
+ ? `Секрет ${name} удалён.`
3085
+ : `Секрет ${name} не найден.`,
3086
+ };
3087
+ }
3088
+ catch (err) {
3089
+ return {
3090
+ success: false,
3091
+ message: err instanceof Error ? err.message : String(err),
3092
+ };
3093
+ }
3094
+ },
3095
+ get_audit: async (input) => {
3096
+ const source = (input ?? {});
3097
+ const result = readAuditLog({
3098
+ action: source.action,
3099
+ target: source.target,
3100
+ actor: source.actor,
3101
+ since: source.since,
3102
+ until: source.until,
3103
+ limit: source.limit,
3104
+ });
3105
+ return { success: true, ...result };
3106
+ },
2615
3107
  get_templates: async () => {
2616
3108
  try {
2617
3109
  return { templates: await loadTemplates() };
@@ -2717,7 +3209,8 @@ export default Plugin.define({
2717
3209
  return { success: false, error: err instanceof Error ? err.message : String(err) };
2718
3210
  }
2719
3211
  },
2720
- });
3212
+ };
3213
+ const rpcRegistration = await ctx.rpc.register(SchedulerRpc, withRpcAudit(rpcHandlers));
2721
3214
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
2722
3215
  // чьи родители были удалены в прошлых сессиях.
2723
3216
  void cleanupOrphanedMatrixTasks().catch((err) => {
@@ -2797,10 +3290,6 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
2797
3290
  }
2798
3291
  return extra;
2799
3292
  }
2800
- /**
2801
- * Общая логика создания задачи: используется и schedule_task (инструмент),
2802
- * и create_task (RPC-метод для GUI).
2803
- */
2804
3293
  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,
2805
3294
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
2806
3295
  matrixMode = "create",
@@ -2819,7 +3308,9 @@ session,
2819
3308
  /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
2820
3309
  sessionId,
2821
3310
  /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
2822
- sessionMaxRuns) {
3311
+ sessionMaxRuns,
3312
+ /** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
3313
+ triggerExtras) {
2823
3314
  const normalizedModel = model?.trim() || undefined;
2824
3315
  const normalizedPriority = normalizePriority(priority);
2825
3316
  const normalizedBefore = beforeScript?.trim() || undefined;
@@ -2828,6 +3319,30 @@ sessionMaxRuns) {
2828
3319
  const normalizedNotBefore = notBefore?.trim() || undefined;
2829
3320
  const normalizedNotAfter = notAfter?.trim() || undefined;
2830
3321
  const normalizedPausedUntil = pausedUntil?.trim() || undefined;
3322
+ // Спринт 27: дни недели, политика окна и glob/git-фильтры.
3323
+ const normalizeGlobList = (raw) => {
3324
+ if (!Array.isArray(raw))
3325
+ return undefined;
3326
+ const cleaned = Array.from(new Set(raw
3327
+ .filter((item) => typeof item === "string")
3328
+ .map((item) => item.trim())
3329
+ .filter(Boolean)));
3330
+ return cleaned.length > 0 ? cleaned : undefined;
3331
+ };
3332
+ const normalizedActiveDays = normalizeActiveDays(triggerExtras?.activeDays);
3333
+ const normalizedWindowPolicy = triggerExtras?.windowPolicy === "skip" || triggerExtras?.windowPolicy === "run"
3334
+ ? triggerExtras.windowPolicy
3335
+ : undefined;
3336
+ const normalizedWatchGlobs = normalizeGlobList(triggerExtras?.watchGlobs);
3337
+ const normalizedWatchIgnore = normalizeGlobList(triggerExtras?.watchIgnore);
3338
+ const normalizedGitBranch = triggerExtras?.gitBranch?.trim() || undefined;
3339
+ const normalizedGitPaths = normalizeGlobList(triggerExtras?.gitPaths);
3340
+ const normalizedGitIgnore = normalizeGlobList(triggerExtras?.gitIgnore);
3341
+ const normalizedGitPollSeconds = typeof triggerExtras?.gitPollSeconds === "number" &&
3342
+ Number.isFinite(triggerExtras.gitPollSeconds) &&
3343
+ triggerExtras.gitPollSeconds >= 5
3344
+ ? Math.floor(triggerExtras.gitPollSeconds)
3345
+ : undefined;
2831
3346
  const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
2832
3347
  ? {
2833
3348
  server: mcpEvent.server?.trim() || "",
@@ -2922,6 +3437,18 @@ sessionMaxRuns) {
2922
3437
  if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
2923
3438
  throw new Error("Для MCP-триггера нужно указать имя события (mcpEvent.event).");
2924
3439
  }
3440
+ // Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
3441
+ if (effectiveTriggerType === "git") {
3442
+ const gitCwd = workspaceId?.trim()
3443
+ ? getWorkspace(workspaceId.trim())?.path
3444
+ : workingDirectory?.trim() || projectDirectory || process.cwd();
3445
+ if (!gitCwd) {
3446
+ throw new Error(`Задача "${name}": для git-триггера нужна рабочая директория или workspace.`);
3447
+ }
3448
+ if (!readGitBranch(gitCwd)) {
3449
+ throw new Error(`Задача "${name}": git-триггер требует git-репозиторий в "${gitCwd}".`);
3450
+ }
3451
+ }
2925
3452
  // Валидируем cron-выражение до создания файлов. Для file/mcp-event
2926
3453
  // расписание не используется вовсе.
2927
3454
  if (effectiveTriggerType === "cron") {
@@ -2942,13 +3469,21 @@ sessionMaxRuns) {
2942
3469
  throw new Error(`Задача "${name}": ${windowError}`);
2943
3470
  }
2944
3471
  }
3472
+ // Спринт 27: окно и дни недели применимы и к событийным триггерам
3473
+ // (file/git/mcp-event/once) — проверяем корректность до создания задачи.
3474
+ if (effectiveTriggerType !== "cron") {
3475
+ const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
3476
+ if (windowError) {
3477
+ throw new Error(`Задача "${name}": ${windowError}`);
3478
+ }
3479
+ }
2945
3480
  const sanitized = sanitizeName(name);
2946
3481
  const lockFile = lockFilePath(sanitized);
2947
3482
  const logFile = path.join(LOG_DIR, `${sanitized}.log`);
2948
3483
  // Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
2949
3484
  // (нестандартный cron или чужая IANA-зона) либо при окне запуска.
2950
3485
  const gate = effectiveTriggerType === "cron"
2951
- ? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter)
3486
+ ? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter, normalizedActiveDays, normalizedWindowPolicy)
2952
3487
  : undefined;
2953
3488
  const wrapperGate = gate
2954
3489
  ? {
@@ -3088,6 +3623,15 @@ sessionMaxRuns) {
3088
3623
  timezone: normalizedTz,
3089
3624
  notBefore: normalizedNotBefore,
3090
3625
  notAfter: normalizedNotAfter,
3626
+ // Спринт 27: дни недели, политика окна, glob- и git-фильтры.
3627
+ activeDays: normalizedActiveDays,
3628
+ windowPolicy: normalizedWindowPolicy,
3629
+ watchGlobs: normalizedWatchGlobs,
3630
+ watchIgnore: normalizedWatchIgnore,
3631
+ gitBranch: normalizedGitBranch,
3632
+ gitPaths: normalizedGitPaths,
3633
+ gitIgnore: normalizedGitIgnore,
3634
+ gitPollSeconds: normalizedGitPollSeconds,
3091
3635
  pausedUntil: normalizedPausedUntil,
3092
3636
  allowedTools: normalizedAllowedTools,
3093
3637
  deniedTools: normalizedDeniedTools,