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/src/index.ts CHANGED
@@ -7,7 +7,7 @@ import fs from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import { LockManager } from "./core/lock.js";
9
9
  import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
10
- import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
10
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
11
11
  import {
12
12
  buildLaunchdOneShotCleanup,
13
13
  normalizeOneShotRunAt,
@@ -40,6 +40,7 @@ import { SchedulerRpc } from "./rpc.js";
40
40
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
41
41
  import { loadSettings, saveSettings } from "./settings.js";
42
42
  import type {
43
+ AuditSettings,
43
44
  HistorySettings,
44
45
  IntegrationSettings,
45
46
  NotificationSettings,
@@ -64,6 +65,7 @@ import {
64
65
  normalizePriority,
65
66
  } from "./task-transfer.js";
66
67
  import { FileWatchManager } from "./core/file-watcher.js";
68
+ import { GitTriggerManager } from "./core/git-trigger.js";
67
69
  import type {
68
70
  McpEventTrigger,
69
71
  MatrixConfig,
@@ -99,6 +101,18 @@ import {
99
101
  writeWorkspaceEnvFile,
100
102
  maskEnvForLog,
101
103
  } from "./workspaces.js";
104
+ import {
105
+ deleteSecret,
106
+ hasSecret,
107
+ listSecrets,
108
+ setSecret,
109
+ } from "./core/secrets.js";
110
+ import {
111
+ cleanupAuditLog,
112
+ readAuditLog,
113
+ recordAudit,
114
+ } from "./core/audit.js";
115
+ import type { AuditEntryInput } from "./core/audit.js";
102
116
 
103
117
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
104
118
  const require = createRequire(import.meta.url);
@@ -307,10 +321,10 @@ export const scheduleTaskSchema = z.object({
307
321
  .optional()
308
322
  .describe("Compensation/rollback task started after a failed run."),
309
323
  triggerType: z
310
- .enum(["cron", "file", "mcp-event", "once"])
324
+ .enum(["cron", "file", "git", "mcp-event", "once"])
311
325
  .optional()
312
326
  .describe(
313
- "Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."
327
+ "Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds)."
314
328
  ),
315
329
  mcpEvent: z
316
330
  .object({
@@ -328,6 +342,52 @@ export const scheduleTaskSchema = z.object({
328
342
  .describe(
329
343
  "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
330
344
  ),
345
+ watchGlobs: z
346
+ .array(z.string())
347
+ .optional()
348
+ .describe(
349
+ "Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."
350
+ ),
351
+ watchIgnore: z
352
+ .array(z.string())
353
+ .optional()
354
+ .describe(
355
+ "Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."
356
+ ),
357
+ gitBranch: z
358
+ .string()
359
+ .optional()
360
+ .describe(
361
+ "Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."
362
+ ),
363
+ gitPaths: z
364
+ .array(z.string())
365
+ .optional()
366
+ .describe(
367
+ "Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."
368
+ ),
369
+ gitIgnore: z
370
+ .array(z.string())
371
+ .optional()
372
+ .describe("Only for triggerType=git: glob masks of changed files to ignore."),
373
+ gitPollSeconds: z
374
+ .number()
375
+ .int()
376
+ .min(5)
377
+ .optional()
378
+ .describe("Only for triggerType=git: polling interval in seconds (default 60, minimum 5)."),
379
+ activeDays: z
380
+ .array(z.number().int().min(0).max(6))
381
+ .optional()
382
+ .describe(
383
+ "Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day."
384
+ ),
385
+ windowPolicy: z
386
+ .enum(["skip", "postpone", "run"])
387
+ .optional()
388
+ .describe(
389
+ "Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway."
390
+ ),
331
391
  workingDirectory: z
332
392
  .string()
333
393
  .optional()
@@ -450,6 +510,42 @@ export const updateTaskSchema = z.object({
450
510
  .string()
451
511
  .optional()
452
512
  .describe("New launch window end HH:MM. Empty string clears the window."),
513
+ activeDays: z
514
+ .array(z.number().int().min(0).max(6))
515
+ .optional()
516
+ .describe(
517
+ "New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction."
518
+ ),
519
+ windowPolicy: z
520
+ .enum(["skip", "postpone", "run"])
521
+ .optional()
522
+ .describe("New behaviour outside the window: postpone (default), skip or run."),
523
+ watchGlobs: z
524
+ .array(z.string())
525
+ .optional()
526
+ .describe("New glob masks for a file trigger. Empty array clears them."),
527
+ watchIgnore: z
528
+ .array(z.string())
529
+ .optional()
530
+ .describe("New ignore masks for a file trigger. Empty array clears them."),
531
+ gitBranch: z
532
+ .string()
533
+ .optional()
534
+ .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
535
+ gitPaths: z
536
+ .array(z.string())
537
+ .optional()
538
+ .describe("New changed-file masks for a git trigger. Empty array clears them."),
539
+ gitIgnore: z
540
+ .array(z.string())
541
+ .optional()
542
+ .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
543
+ gitPollSeconds: z
544
+ .number()
545
+ .int()
546
+ .min(5)
547
+ .optional()
548
+ .describe("New git polling interval in seconds."),
453
549
  prompt: z
454
550
  .string()
455
551
  .optional()
@@ -487,7 +583,7 @@ export const updateTaskSchema = z.object({
487
583
  .optional()
488
584
  .describe("New error-chain task. Empty string clears it."),
489
585
  triggerType: z
490
- .enum(["cron", "file", "mcp-event", "once"])
586
+ .enum(["cron", "file", "git", "mcp-event", "once"])
491
587
  .optional()
492
588
  .describe("New trigger type."),
493
589
  mcpEvent: z
@@ -695,6 +791,10 @@ export const manageSettingsSchema = z.object({
695
791
  .describe(
696
792
  "Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."
697
793
  ),
794
+ audit: z
795
+ .any()
796
+ .optional()
797
+ .describe("Audit log settings patch (enabled, retentionDays, maxRecords)."),
698
798
  });
699
799
 
700
800
  /** manage_templates — пользовательские шаблоны задач. */
@@ -772,6 +872,31 @@ export const emitEventSchema = z.object({
772
872
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
773
873
  });
774
874
 
875
+ /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
876
+ export const manageSecretsSchema = z.object({
877
+ action: z
878
+ .enum(["list", "set", "delete"])
879
+ .describe("list — secret names and previews; set — create or replace; delete — remove by name."),
880
+ name: z
881
+ .string()
882
+ .optional()
883
+ .describe("Secret name ([A-Za-z0-9_.-], max 64 chars). Required for set/delete."),
884
+ value: z.string().optional().describe("Secret value (required for set). Never returned by list."),
885
+ });
886
+
887
+ /** get_audit_log — журнал мутаций задач и настроек (Спринт 26). */
888
+ export const getAuditLogSchema = z.object({
889
+ action: z.string().optional().describe("Filter by action, for example task.create."),
890
+ target: z.string().optional().describe("Filter by target name or id."),
891
+ actor: z
892
+ .string()
893
+ .optional()
894
+ .describe("Filter by actor: mcp (agent), gui (dashboard), http (webhook/API)."),
895
+ since: z.string().optional().describe("ISO timestamp lower bound."),
896
+ until: z.string().optional().describe("ISO timestamp upper bound."),
897
+ limit: z.number().int().min(1).max(5000).optional().describe("Max records (default 200)."),
898
+ });
899
+
775
900
  type ScheduleArgs = z.infer<typeof scheduleTaskSchema>;
776
901
  type ListArgs = z.infer<typeof listTasksSchema>;
777
902
  type DeleteArgs = z.infer<typeof deleteTaskSchema>;
@@ -794,6 +919,8 @@ type NotificationArgs = z.infer<typeof sendNotificationSchema>;
794
919
  type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
795
920
  type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
796
921
  type EmitEventArgs = z.infer<typeof emitEventSchema>;
922
+ type SecretsArgs = z.infer<typeof manageSecretsSchema>;
923
+ type AuditLogArgs = z.infer<typeof getAuditLogSchema>;
797
924
 
798
925
  /**
799
926
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -855,6 +982,14 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
855
982
  notAfter,
856
983
  session,
857
984
  sessionMaxRuns,
985
+ activeDays,
986
+ windowPolicy,
987
+ watchGlobs,
988
+ watchIgnore,
989
+ gitBranch,
990
+ gitPaths,
991
+ gitIgnore,
992
+ gitPollSeconds,
858
993
  } = args;
859
994
 
860
995
  let effectiveRunAt: string | undefined;
@@ -908,7 +1043,17 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
908
1043
  effectiveRunAt,
909
1044
  effectiveSession,
910
1045
  effectiveSessionId,
911
- sessionMaxRuns
1046
+ sessionMaxRuns,
1047
+ {
1048
+ activeDays,
1049
+ windowPolicy,
1050
+ watchGlobs,
1051
+ watchIgnore,
1052
+ gitBranch,
1053
+ gitPaths,
1054
+ gitIgnore,
1055
+ gitPollSeconds,
1056
+ }
912
1057
  );
913
1058
  } catch (err: any) {
914
1059
  return {
@@ -921,7 +1066,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
921
1066
 
922
1067
  // Новый файловый триггер должен начать работать сразу, без перезапуска
923
1068
  // OpenCode: пересобираем набор watcher-ов после создания задачи.
924
- await refreshFileTriggers();
1069
+ await refreshTriggers();
925
1070
 
926
1071
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
927
1072
  const effectiveWorkdir =
@@ -1178,7 +1323,7 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
1178
1323
  try {
1179
1324
  const { removed, existed } = await deleteTaskWithFamily(name);
1180
1325
  // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
1181
- await refreshFileTriggers();
1326
+ await refreshTriggers();
1182
1327
  if (!existed && removed.length === 0) {
1183
1328
  return {
1184
1329
  content: JSON.stringify({
@@ -1380,6 +1525,34 @@ async function updateTaskFromInput(
1380
1525
  };
1381
1526
  }
1382
1527
 
1528
+ // Спринт 27: параметры триггеров сохраняются, если поле не передано.
1529
+ const mergeStringList = (
1530
+ next: string[] | undefined,
1531
+ prev: string[] | undefined
1532
+ ): string[] | undefined => {
1533
+ if (next === undefined) return prev;
1534
+ const cleaned = next
1535
+ .filter((item): item is string => typeof item === "string")
1536
+ .map((item) => item.trim())
1537
+ .filter(Boolean);
1538
+ return cleaned.length > 0 ? cleaned : undefined;
1539
+ };
1540
+ const triggerExtras: TriggerExtras = {
1541
+ activeDays:
1542
+ input.activeDays === undefined
1543
+ ? previous.activeDays
1544
+ : input.activeDays.length > 0
1545
+ ? input.activeDays
1546
+ : undefined,
1547
+ windowPolicy: input.windowPolicy ?? previous.windowPolicy,
1548
+ watchGlobs: mergeStringList(input.watchGlobs, previous.watchGlobs),
1549
+ watchIgnore: mergeStringList(input.watchIgnore, previous.watchIgnore),
1550
+ gitBranch: clearableString(input.gitBranch, previous.gitBranch),
1551
+ gitPaths: mergeStringList(input.gitPaths, previous.gitPaths),
1552
+ gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
1553
+ gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
1554
+ };
1555
+
1383
1556
  try {
1384
1557
  // Обновление = пересоздание в планировщике с сохранением старых значений.
1385
1558
  await scheduler.deleteTask(name);
@@ -1417,7 +1590,8 @@ async function updateTaskFromInput(
1417
1590
  runAt,
1418
1591
  session,
1419
1592
  sessionId,
1420
- sessionMaxRuns
1593
+ sessionMaxRuns,
1594
+ triggerExtras
1421
1595
  );
1422
1596
 
1423
1597
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -1427,7 +1601,7 @@ async function updateTaskFromInput(
1427
1601
 
1428
1602
  // Пересоздание могло изменить triggerType/watchPath — сразу
1429
1603
  // пересобираем набор файловых watcher-ов.
1430
- await refreshFileTriggers();
1604
+ await refreshTriggers();
1431
1605
 
1432
1606
  return { success: true, message: `Задача "${name}" обновлена.` };
1433
1607
  } catch (err: any) {
@@ -1966,13 +2140,14 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1966
2140
  args.winterMode === undefined &&
1967
2141
  args.notifications === undefined &&
1968
2142
  args.history === undefined &&
1969
- args.integrations === undefined
2143
+ args.integrations === undefined &&
2144
+ args.audit === undefined
1970
2145
  ) {
1971
2146
  return {
1972
2147
  content: JSON.stringify({
1973
2148
  success: false,
1974
2149
  error:
1975
- "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
2150
+ "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
1976
2151
  settings: current,
1977
2152
  }),
1978
2153
  };
@@ -1984,6 +2159,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1984
2159
  notifications: args.notifications as NotificationSettings | undefined,
1985
2160
  history: args.history as HistorySettings | undefined,
1986
2161
  integrations: args.integrations as IntegrationSettings | undefined,
2162
+ audit: args.audit as AuditSettings | undefined,
1987
2163
  });
1988
2164
  return { content: JSON.stringify({ success: true, settings }) };
1989
2165
  });
@@ -2155,7 +2331,7 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2155
2331
  errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
2156
2332
  }
2157
2333
  }
2158
- await refreshFileTriggers();
2334
+ await refreshTriggers();
2159
2335
  return {
2160
2336
  content: JSON.stringify({ success: errors.length === 0, imported, errors }),
2161
2337
  };
@@ -2243,6 +2419,197 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2243
2419
  };
2244
2420
  });
2245
2421
 
2422
+ /** manage_secrets — зашифрованное хранилище секретов. */
2423
+ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
2424
+ if (args.action === "list") {
2425
+ return { content: JSON.stringify({ success: true, secrets: listSecrets() }) };
2426
+ }
2427
+
2428
+ const name = (args.name ?? "").trim();
2429
+ if (!name) {
2430
+ return {
2431
+ content: JSON.stringify({
2432
+ success: false,
2433
+ error: "Для set/delete нужно имя секрета.",
2434
+ }),
2435
+ };
2436
+ }
2437
+
2438
+ if (args.action === "delete") {
2439
+ const existed = hasSecret(name);
2440
+ deleteSecret(name);
2441
+ return {
2442
+ content: JSON.stringify({
2443
+ success: existed,
2444
+ message: existed
2445
+ ? `Секрет ${name} удалён.`
2446
+ : `Секрет ${name} не найден.`,
2447
+ }),
2448
+ };
2449
+ }
2450
+
2451
+ const value = args.value;
2452
+ if (typeof value !== "string" || value.length === 0) {
2453
+ return {
2454
+ content: JSON.stringify({
2455
+ success: false,
2456
+ error: "Для action=set нужно непустое значение value.",
2457
+ }),
2458
+ };
2459
+ }
2460
+
2461
+ const item = setSecret(name, value);
2462
+ return {
2463
+ content: JSON.stringify({
2464
+ success: true,
2465
+ message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
2466
+ secret: item,
2467
+ }),
2468
+ };
2469
+ });
2470
+
2471
+ /** get_audit_log — чтение журнала мутаций. */
2472
+ const getAuditLogExecute = wrapExecute<AuditLogArgs>(async (args) => {
2473
+ const result = readAuditLog({
2474
+ action: args.action,
2475
+ target: args.target,
2476
+ actor: args.actor,
2477
+ since: args.since,
2478
+ until: args.until,
2479
+ limit: args.limit,
2480
+ });
2481
+ return { content: JSON.stringify({ success: true, ...result }) };
2482
+ });
2483
+
2484
+ /**
2485
+ * Оборачивает execute инструмента, записывая успешную мутацию в audit log.
2486
+ * Аудит не должен ломать сам инструмент, поэтому ошибки проглатываются.
2487
+ */
2488
+ function withAudit<A>(
2489
+ toolName: string,
2490
+ describe: (args: A) => Omit<AuditEntryInput, "actor"> | null,
2491
+ execute: (args: A, context: Tool.Context) => Promise<Tool.Result>
2492
+ ): (args: A, context: Tool.Context) => Promise<Tool.Result> {
2493
+ return async (args: A, context: Tool.Context) => {
2494
+ const result = await execute(args, context);
2495
+ try {
2496
+ const raw = String((result as any)?.content ?? "");
2497
+ const parsed = raw ? JSON.parse(raw) : null;
2498
+ if (parsed?.success === false) return result;
2499
+ const entry = describe(args);
2500
+ if (entry) {
2501
+ recordAudit({ ...entry, actor: "mcp", source: toolName });
2502
+ }
2503
+ } catch {
2504
+ // Аудит — вспомогательная функция: не мешает основной операции.
2505
+ }
2506
+ return result;
2507
+ };
2508
+ }
2509
+
2510
+ /** Правила аудита для RPC-методов GUI (Спринт 26). */
2511
+ const RPC_AUDIT_RULES: Record<
2512
+ string,
2513
+ {
2514
+ action: string;
2515
+ targetType: string;
2516
+ target: (input: any) => string;
2517
+ }
2518
+ > = {
2519
+ create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
2520
+ update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
2521
+ delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
2522
+ run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
2523
+ pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
2524
+ resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
2525
+ cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
2526
+ cleanup_matrix_orphans: {
2527
+ action: "matrix.cleanup",
2528
+ targetType: "matrix",
2529
+ target: () => "orphans",
2530
+ },
2531
+ cleanup_history: {
2532
+ action: "history.cleanup",
2533
+ targetType: "history",
2534
+ target: () => "runs",
2535
+ },
2536
+ emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
2537
+ add_workspace: {
2538
+ action: "workspace.add",
2539
+ targetType: "workspace",
2540
+ target: (i) => i.name ?? i.path ?? "",
2541
+ },
2542
+ update_workspace: {
2543
+ action: "workspace.update",
2544
+ targetType: "workspace",
2545
+ target: (i) => i.id ?? "",
2546
+ },
2547
+ delete_workspace: {
2548
+ action: "workspace.delete",
2549
+ targetType: "workspace",
2550
+ target: (i) => i.id ?? "",
2551
+ },
2552
+ set_profile: { action: "profile.switch", targetType: "profile", target: (i) => i.name ?? "" },
2553
+ create_profile: {
2554
+ action: "profile.create",
2555
+ targetType: "profile",
2556
+ target: (i) => i.name ?? "",
2557
+ },
2558
+ delete_profile: {
2559
+ action: "profile.delete",
2560
+ targetType: "profile",
2561
+ target: (i) => i.name ?? "",
2562
+ },
2563
+ import_tasks: { action: "tasks.import", targetType: "tasks", target: () => "snapshot" },
2564
+ save_settings: { action: "settings.update", targetType: "settings", target: () => "global" },
2565
+ save_template: {
2566
+ action: "template.save",
2567
+ targetType: "template",
2568
+ target: (i) => i.id ?? i.name ?? "",
2569
+ },
2570
+ delete_template: {
2571
+ action: "template.delete",
2572
+ targetType: "template",
2573
+ target: (i) => i.id ?? "",
2574
+ },
2575
+ save_secret: { action: "secret.set", targetType: "secret", target: (i) => i.name ?? "" },
2576
+ delete_secret: { action: "secret.delete", targetType: "secret", target: (i) => i.name ?? "" },
2577
+ };
2578
+
2579
+ /**
2580
+ * Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
2581
+ * с actor=gui. Ошибки аудита не влияют на ответ GUI.
2582
+ */
2583
+ function withRpcAudit<T extends Record<string, (...args: any[]) => any>>(handlers: T): T {
2584
+ const wrapped: Record<string, (...args: any[]) => any> = {};
2585
+ for (const [name, handler] of Object.entries(handlers)) {
2586
+ const rule = RPC_AUDIT_RULES[name];
2587
+ if (!rule || typeof handler !== "function") {
2588
+ wrapped[name] = handler;
2589
+ continue;
2590
+ }
2591
+ wrapped[name] = async (...args: any[]) => {
2592
+ const input = args[0] ?? {};
2593
+ const result = await handler(...args);
2594
+ try {
2595
+ if ((result as any)?.success !== false) {
2596
+ recordAudit({
2597
+ action: rule.action,
2598
+ targetType: rule.targetType,
2599
+ target: rule.target(input),
2600
+ actor: "gui",
2601
+ source: name,
2602
+ });
2603
+ }
2604
+ } catch {
2605
+ // Журнал не должен ломать GUI-операцию.
2606
+ }
2607
+ return result;
2608
+ };
2609
+ }
2610
+ return wrapped as T;
2611
+ }
2612
+
2246
2613
  /**
2247
2614
  * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
2248
2615
  * обновлять после создания/изменения/удаления задачи. Раньше refresh()
@@ -2251,17 +2618,105 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2251
2618
  */
2252
2619
  let fileWatcherManager: FileWatchManager | null = null;
2253
2620
 
2254
- async function refreshFileTriggers(): Promise<void> {
2255
- if (!fileWatcherManager) return;
2256
- try {
2257
- await fileWatcherManager.refresh();
2258
- } catch (err: any) {
2259
- console.error(
2260
- `[windows-scheduler] Не удалось обновить файловые триггеры: ${
2261
- err instanceof Error ? err.message : String(err)
2262
- }`
2621
+ /**
2622
+ * Спринт 27: менеджер git-триггеров. Опрашивает HEAD задач с
2623
+ * triggerType === "git" и запускает их при новых подходящих коммитах.
2624
+ */
2625
+ let gitTriggerManager: GitTriggerManager | null = null;
2626
+
2627
+ /**
2628
+ * Приводит в актуальное состояние все событийные триггеры (файлы и git).
2629
+ * Вызывается после создания, изменения и удаления задачи.
2630
+ */
2631
+ async function refreshTriggers(): Promise<void> {
2632
+ if (fileWatcherManager) {
2633
+ try {
2634
+ await fileWatcherManager.refresh();
2635
+ } catch (err: any) {
2636
+ console.error(
2637
+ `[windows-scheduler] Не удалось обновить файловые триггеры: ${
2638
+ err instanceof Error ? err.message : String(err)
2639
+ }`
2640
+ );
2641
+ }
2642
+ }
2643
+ if (gitTriggerManager) {
2644
+ try {
2645
+ await gitTriggerManager.refresh();
2646
+ } catch (err: any) {
2647
+ console.error(
2648
+ `[windows-scheduler] Не удалось обновить git-триггеры: ${
2649
+ err instanceof Error ? err.message : String(err)
2650
+ }`
2651
+ );
2652
+ }
2653
+ }
2654
+ }
2655
+
2656
+ /** Максимальная задержка переноса событийного запуска (12 часов). */
2657
+ const EVENT_POSTPONE_MAX_MS = 12 * 60 * 60 * 1000;
2658
+
2659
+ /**
2660
+ * Спринт 27: запуск задачи по событию (файл, git, MCP) с учётом окна запуска
2661
+ * и разрешённых дней недели. Вне окна: skip — пишем причину и выходим,
2662
+ * postpone — таймер до ближайшего открытия, run — запускаем сразу.
2663
+ */
2664
+ async function scheduleEventRun(taskName: string, reason: string): Promise<void> {
2665
+ const definition = getTask(taskName);
2666
+ if (!definition) return;
2667
+
2668
+ const policy = definition.windowPolicy ?? "postpone";
2669
+ const options = {
2670
+ notBefore: definition.notBefore,
2671
+ notAfter: definition.notAfter,
2672
+ days: definition.activeDays,
2673
+ timeZone: definition.timezone,
2674
+ };
2675
+ const now = new Date();
2676
+ const state = activeWindowState(now, options);
2677
+
2678
+ if (state.active || policy === "run") {
2679
+ await runTaskEntry(taskName);
2680
+ console.log(
2681
+ `[windows-scheduler] Запуск задачи "${taskName}" (${reason}).`
2682
+ );
2683
+ return;
2684
+ }
2685
+
2686
+ if (policy === "skip") {
2687
+ console.log(
2688
+ `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
2689
+ state.reason ?? "вне окна"
2690
+ } — политика skip.`
2263
2691
  );
2692
+ return;
2264
2693
  }
2694
+
2695
+ const delay = nextWindowOpenDelayMs(now, options);
2696
+ if (delay <= 0 || delay > EVENT_POSTPONE_MAX_MS) {
2697
+ console.log(
2698
+ `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
2699
+ state.reason ?? "вне окна"
2700
+ } — до открытия окна больше 12 ч.`
2701
+ );
2702
+ return;
2703
+ }
2704
+
2705
+ console.log(
2706
+ `[windows-scheduler] Задача "${taskName}" (${reason}) отложена на ~${Math.round(
2707
+ delay / 60000
2708
+ )} мин: ${state.reason ?? "вне окна"}.`
2709
+ );
2710
+ const timer = setTimeout(() => {
2711
+ void scheduleEventRun(taskName, reason).catch((err: any) => {
2712
+ console.error(
2713
+ `[windows-scheduler] Не удалось запустить отложенную задачу "${taskName}": ${
2714
+ err instanceof Error ? err.message : String(err)
2715
+ }`
2716
+ );
2717
+ });
2718
+ }, delay);
2719
+ timer.unref?.();
2265
2720
  }
2266
2721
 
2267
2722
  export default Plugin.define({
@@ -2414,10 +2869,7 @@ export default Plugin.define({
2414
2869
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
2415
2870
  fileWatcherManager = new FileWatchManager(async (taskName) => {
2416
2871
  try {
2417
- await runTaskEntry(taskName);
2418
- console.log(
2419
- `[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`
2420
- );
2872
+ await scheduleEventRun(taskName, "изменение отслеживаемого файла");
2421
2873
  } catch (err: any) {
2422
2874
  console.error(
2423
2875
  `[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
@@ -2426,7 +2878,21 @@ export default Plugin.define({
2426
2878
  );
2427
2879
  }
2428
2880
  });
2429
- void refreshFileTriggers();
2881
+
2882
+ // Спринт 27: git-триггеры — опрос HEAD и запуск при новых коммитах,
2883
+ // затронувших подходящие файлы.
2884
+ gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
2885
+ try {
2886
+ await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
2887
+ } catch (err: any) {
2888
+ console.error(
2889
+ `[windows-scheduler] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
2890
+ err instanceof Error ? err.message : String(err)
2891
+ }`
2892
+ );
2893
+ }
2894
+ });
2895
+ void refreshTriggers();
2430
2896
 
2431
2897
  const registration = await ctx.tool.transform((editor) => {
2432
2898
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -2440,7 +2906,11 @@ export default Plugin.define({
2440
2906
  "Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
2441
2907
  "Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
2442
2908
  options: { codemode: true },
2443
- execute: scheduleTaskExecute as any,
2909
+ execute: withAudit<ScheduleArgs>(
2910
+ "schedule_task",
2911
+ (args) => ({ action: "task.create", targetType: "task", target: args.name }),
2912
+ scheduleTaskExecute as any
2913
+ ) as any,
2444
2914
  });
2445
2915
 
2446
2916
  editor.add({
@@ -2460,7 +2930,11 @@ export default Plugin.define({
2460
2930
  "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
2461
2931
  "Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
2462
2932
  options: { codemode: true },
2463
- execute: updateTaskExecute as any,
2933
+ execute: withAudit<UpdateArgs>(
2934
+ "update_task",
2935
+ (args) => ({ action: "task.update", targetType: "task", target: args.name }),
2936
+ updateTaskExecute as any
2937
+ ) as any,
2464
2938
  });
2465
2939
 
2466
2940
  editor.add({
@@ -2470,7 +2944,11 @@ export default Plugin.define({
2470
2944
  `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
2471
2945
  "Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
2472
2946
  options: { codemode: true },
2473
- execute: deleteTaskExecute as any,
2947
+ execute: withAudit<DeleteArgs>(
2948
+ "delete_task",
2949
+ (args) => ({ action: "task.delete", targetType: "task", target: args.name }),
2950
+ deleteTaskExecute as any
2951
+ ) as any,
2474
2952
  });
2475
2953
 
2476
2954
  editor.add({
@@ -2480,7 +2958,11 @@ export default Plugin.define({
2480
2958
  `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
2481
2959
  "Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
2482
2960
  options: { codemode: true },
2483
- execute: runTaskNowExecute as any,
2961
+ execute: withAudit<RunNowArgs>(
2962
+ "run_task_now",
2963
+ (args) => ({ action: "task.run", targetType: "task", target: args.name }),
2964
+ runTaskNowExecute as any
2965
+ ) as any,
2484
2966
  });
2485
2967
 
2486
2968
  editor.add({
@@ -2489,7 +2971,11 @@ export default Plugin.define({
2489
2971
  description:
2490
2972
  "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
2491
2973
  options: { codemode: true },
2492
- execute: pauseTaskExecute as any,
2974
+ execute: withAudit<PauseArgs>(
2975
+ "pause_task",
2976
+ (args) => ({ action: "task.pause", targetType: "task", target: args.name }),
2977
+ pauseTaskExecute as any
2978
+ ) as any,
2493
2979
  });
2494
2980
 
2495
2981
  editor.add({
@@ -2498,7 +2984,11 @@ export default Plugin.define({
2498
2984
  description:
2499
2985
  "Resumes a previously paused task. For a matrix parent every clone is resumed.",
2500
2986
  options: { codemode: true },
2501
- execute: resumeTaskExecute as any,
2987
+ execute: withAudit<ResumeArgs>(
2988
+ "resume_task",
2989
+ (args) => ({ action: "task.resume", targetType: "task", target: args.name }),
2990
+ resumeTaskExecute as any
2991
+ ) as any,
2502
2992
  });
2503
2993
 
2504
2994
  editor.add({
@@ -2535,7 +3025,18 @@ export default Plugin.define({
2535
3025
  description:
2536
3026
  "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.",
2537
3027
  options: { codemode: true },
2538
- execute: manageWorkspacesExecute as any,
3028
+ execute: withAudit<WorkspacesArgs>(
3029
+ "manage_workspaces",
3030
+ (args) =>
3031
+ args.action === "list"
3032
+ ? null
3033
+ : {
3034
+ action: `workspace.${args.action}`,
3035
+ targetType: "workspace",
3036
+ target: args.id || args.name || "",
3037
+ },
3038
+ manageWorkspacesExecute as any
3039
+ ) as any,
2539
3040
  });
2540
3041
 
2541
3042
  editor.add({
@@ -2544,7 +3045,18 @@ export default Plugin.define({
2544
3045
  description:
2545
3046
  "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).",
2546
3047
  options: { codemode: true },
2547
- execute: matrixControlExecute as any,
3048
+ execute: withAudit<MatrixControlArgs>(
3049
+ "matrix_control",
3050
+ (args) =>
3051
+ args.action === "cancel" || args.action === "cleanup"
3052
+ ? {
3053
+ action: `matrix.${args.action}`,
3054
+ targetType: "matrix",
3055
+ target: args.name || "",
3056
+ }
3057
+ : null,
3058
+ matrixControlExecute as any
3059
+ ) as any,
2548
3060
  });
2549
3061
 
2550
3062
  editor.add({
@@ -2571,7 +3083,14 @@ export default Plugin.define({
2571
3083
  description:
2572
3084
  "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.",
2573
3085
  options: { codemode: true },
2574
- execute: manageSettingsExecute as any,
3086
+ execute: withAudit<SettingsArgs>(
3087
+ "manage_settings",
3088
+ (args) =>
3089
+ args.action === "update"
3090
+ ? { action: "settings.update", targetType: "settings", target: "global" }
3091
+ : null,
3092
+ manageSettingsExecute as any
3093
+ ) as any,
2575
3094
  });
2576
3095
 
2577
3096
  editor.add({
@@ -2580,7 +3099,18 @@ export default Plugin.define({
2580
3099
  description:
2581
3100
  "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2582
3101
  options: { codemode: true },
2583
- execute: manageTemplatesExecute as any,
3102
+ execute: withAudit<TemplatesArgs>(
3103
+ "manage_templates",
3104
+ (args) =>
3105
+ args.action === "list"
3106
+ ? null
3107
+ : {
3108
+ action: `template.${args.action}`,
3109
+ targetType: "template",
3110
+ target: args.id || args.name || "",
3111
+ },
3112
+ manageTemplatesExecute as any
3113
+ ) as any,
2584
3114
  });
2585
3115
 
2586
3116
  editor.add({
@@ -2589,7 +3119,18 @@ export default Plugin.define({
2589
3119
  description:
2590
3120
  "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2591
3121
  options: { codemode: true },
2592
- execute: manageProfilesExecute as any,
3122
+ execute: withAudit<ProfilesArgs>(
3123
+ "manage_profiles",
3124
+ (args) =>
3125
+ args.action === "list"
3126
+ ? null
3127
+ : {
3128
+ action: `profile.${args.action}`,
3129
+ targetType: "profile",
3130
+ target: args.name || "",
3131
+ },
3132
+ manageProfilesExecute as any
3133
+ ) as any,
2593
3134
  });
2594
3135
 
2595
3136
  editor.add({
@@ -2598,7 +3139,14 @@ export default Plugin.define({
2598
3139
  description:
2599
3140
  "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2600
3141
  options: { codemode: true },
2601
- execute: transferTasksExecute as any,
3142
+ execute: withAudit<TransferArgs>(
3143
+ "transfer_tasks",
3144
+ (args) =>
3145
+ args.action === "import"
3146
+ ? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
3147
+ : null,
3148
+ transferTasksExecute as any
3149
+ ) as any,
2602
3150
  });
2603
3151
 
2604
3152
  editor.add({
@@ -2625,7 +3173,43 @@ export default Plugin.define({
2625
3173
  description:
2626
3174
  "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2627
3175
  options: { codemode: true },
2628
- execute: cleanupHistoryExecute as any,
3176
+ execute: withAudit<CleanupHistoryArgs>(
3177
+ "cleanup_history",
3178
+ () => ({ action: "history.cleanup", targetType: "history", target: "runs" }),
3179
+ cleanupHistoryExecute as any
3180
+ ) as any,
3181
+ });
3182
+
3183
+ editor.add({
3184
+ name: "manage_secrets",
3185
+ input: manageSecretsSchema,
3186
+ description:
3187
+ "Manages the encrypted secret store: list (names and masked previews), set (create or replace) or delete. " +
3188
+ "Secrets are encrypted with AES-256-GCM at rest and referenced from workspace env as ${secret:NAME}; " +
3189
+ "values are never returned by list and are redacted from logs and audit details.",
3190
+ options: { codemode: true },
3191
+ execute: withAudit<SecretsArgs>(
3192
+ "manage_secrets",
3193
+ (args) =>
3194
+ args.action === "list"
3195
+ ? null
3196
+ : {
3197
+ action: `secret.${args.action}`,
3198
+ targetType: "secret",
3199
+ target: (args.name ?? "").trim(),
3200
+ },
3201
+ manageSecretsExecute as any
3202
+ ) as any,
3203
+ });
3204
+
3205
+ editor.add({
3206
+ name: "get_audit_log",
3207
+ input: getAuditLogSchema,
3208
+ description:
3209
+ "Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
3210
+ "Filter by action, target, actor, time range and limit. Secret values are redacted.",
3211
+ options: { codemode: true },
3212
+ execute: getAuditLogExecute as any,
2629
3213
  });
2630
3214
 
2631
3215
  editor.add({
@@ -2667,7 +3251,7 @@ export default Plugin.define({
2667
3251
  // Регистрируем RPC-методы, вызываемые из GUI-панели.
2668
3252
  // Общая логика создания задачи вынесена в schedulerCreateTask, чтобы
2669
3253
  // schedule_task и create_task использовали один и тот же путь.
2670
- const rpcRegistration = await ctx.rpc.register(SchedulerRpc, {
3254
+ const rpcHandlers = {
2671
3255
  get_tasks: async () => {
2672
3256
  return { tasks: await collectTasksView() };
2673
3257
  },
@@ -2712,7 +3296,7 @@ export default Plugin.define({
2712
3296
  nextTaskOnSuccess?: string;
2713
3297
  nextTaskOnError?: string;
2714
3298
  dependsOn?: string[];
2715
- triggerType?: "cron" | "file" | "mcp-event" | "once";
3299
+ triggerType?: "cron" | "file" | "git" | "mcp-event" | "once";
2716
3300
  watchPath?: string;
2717
3301
  workingDirectory?: string;
2718
3302
  model?: string;
@@ -3286,12 +3870,13 @@ export default Plugin.define({
3286
3870
  return await loadSettings();
3287
3871
  },
3288
3872
  save_settings: async (input: unknown) => {
3289
- const { maxConcurrent, winterMode, notifications, history, integrations } = input as {
3873
+ const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input as {
3290
3874
  maxConcurrent?: number;
3291
3875
  winterMode?: boolean;
3292
3876
  notifications?: NotificationSettings;
3293
3877
  history?: HistorySettings;
3294
3878
  integrations?: IntegrationSettings;
3879
+ audit?: AuditSettings;
3295
3880
  };
3296
3881
  const current = await loadSettings();
3297
3882
  if (
@@ -3299,7 +3884,8 @@ export default Plugin.define({
3299
3884
  winterMode === undefined &&
3300
3885
  notifications === undefined &&
3301
3886
  history === undefined &&
3302
- integrations === undefined
3887
+ integrations === undefined &&
3888
+ audit === undefined
3303
3889
  ) {
3304
3890
  return {
3305
3891
  success: false,
@@ -3308,6 +3894,7 @@ export default Plugin.define({
3308
3894
  notifications: current.notifications,
3309
3895
  history: current.history,
3310
3896
  integrations: current.integrations,
3897
+ audit: current.audit,
3311
3898
  };
3312
3899
  }
3313
3900
  const settings = await saveSettings({
@@ -3316,6 +3903,7 @@ export default Plugin.define({
3316
3903
  notifications,
3317
3904
  history,
3318
3905
  integrations,
3906
+ audit,
3319
3907
  });
3320
3908
  return {
3321
3909
  success: true,
@@ -3324,6 +3912,7 @@ export default Plugin.define({
3324
3912
  notifications: settings.notifications,
3325
3913
  history: settings.history,
3326
3914
  integrations: settings.integrations,
3915
+ audit: settings.audit,
3327
3916
  };
3328
3917
  },
3329
3918
  test_notification: async () => {
@@ -3333,6 +3922,74 @@ export default Plugin.define({
3333
3922
  // Ручная отправка не сдвигает плановое расписание дайджеста.
3334
3923
  return await sendDigestNow({ updateLastSentAt: false });
3335
3924
  },
3925
+
3926
+ // --- Спринт 26: секреты и аудит -------------------------------------
3927
+ list_secrets: async () => {
3928
+ return { success: true, secrets: listSecrets() };
3929
+ },
3930
+ save_secret: async (input: unknown) => {
3931
+ try {
3932
+ const source = (input ?? {}) as { name?: string; value?: string };
3933
+ const name = (source.name ?? "").trim();
3934
+ if (!name) {
3935
+ return { success: false, message: "Нужно имя секрета." };
3936
+ }
3937
+ if (typeof source.value !== "string" || source.value.length === 0) {
3938
+ return { success: false, message: "Нужно непустое значение секрета." };
3939
+ }
3940
+ const secret = setSecret(name, source.value);
3941
+ return {
3942
+ success: true,
3943
+ message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
3944
+ secret,
3945
+ };
3946
+ } catch (err: any) {
3947
+ return {
3948
+ success: false,
3949
+ message: err instanceof Error ? err.message : String(err),
3950
+ };
3951
+ }
3952
+ },
3953
+ delete_secret: async (input: unknown) => {
3954
+ try {
3955
+ const name = (((input ?? {}) as { name?: string }).name ?? "").trim();
3956
+ if (!name) {
3957
+ return { success: false, message: "Нужно имя секрета." };
3958
+ }
3959
+ const existed = hasSecret(name);
3960
+ deleteSecret(name);
3961
+ return {
3962
+ success: existed,
3963
+ message: existed
3964
+ ? `Секрет ${name} удалён.`
3965
+ : `Секрет ${name} не найден.`,
3966
+ };
3967
+ } catch (err: any) {
3968
+ return {
3969
+ success: false,
3970
+ message: err instanceof Error ? err.message : String(err),
3971
+ };
3972
+ }
3973
+ },
3974
+ get_audit: async (input: unknown) => {
3975
+ const source = (input ?? {}) as {
3976
+ action?: string;
3977
+ target?: string;
3978
+ actor?: string;
3979
+ since?: string;
3980
+ until?: string;
3981
+ limit?: number;
3982
+ };
3983
+ const result = readAuditLog({
3984
+ action: source.action,
3985
+ target: source.target,
3986
+ actor: source.actor,
3987
+ since: source.since,
3988
+ until: source.until,
3989
+ limit: source.limit,
3990
+ });
3991
+ return { success: true, ...result };
3992
+ },
3336
3993
  get_templates: async () => {
3337
3994
  try {
3338
3995
  return { templates: await loadTemplates() };
@@ -3469,7 +4126,12 @@ export default Plugin.define({
3469
4126
  return { success: false, error: err instanceof Error ? err.message : String(err) };
3470
4127
  }
3471
4128
  },
3472
- });
4129
+ };
4130
+
4131
+ const rpcRegistration = await ctx.rpc.register(
4132
+ SchedulerRpc,
4133
+ withRpcAudit(rpcHandlers) as typeof rpcHandlers
4134
+ );
3473
4135
 
3474
4136
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
3475
4137
  // чьи родители были удалены в прошлых сессиях.
@@ -3575,6 +4237,21 @@ function resolveMatrixExtraConfig(
3575
4237
  * Общая логика создания задачи: используется и schedule_task (инструмент),
3576
4238
  * и create_task (RPC-метод для GUI).
3577
4239
  */
4240
+ /**
4241
+ * Спринт 27: дополнительные параметры триггеров (дни недели, политика окна,
4242
+ * glob-фильтры файловых триггеров и git-триггеры).
4243
+ */
4244
+ export interface TriggerExtras {
4245
+ activeDays?: number[];
4246
+ windowPolicy?: "skip" | "postpone" | "run";
4247
+ watchGlobs?: string[];
4248
+ watchIgnore?: string[];
4249
+ gitBranch?: string;
4250
+ gitPaths?: string[];
4251
+ gitIgnore?: string[];
4252
+ gitPollSeconds?: number;
4253
+ }
4254
+
3578
4255
  async function schedulerCreateTask(
3579
4256
  name: string,
3580
4257
  schedule: string,
@@ -3586,7 +4263,7 @@ async function schedulerCreateTask(
3586
4263
  qualityGate?: string,
3587
4264
  nextTaskOnSuccess?: string,
3588
4265
  nextTaskOnError?: string,
3589
- triggerType?: "cron" | "file" | "mcp-event" | "once",
4266
+ triggerType?: "cron" | "file" | "git" | "mcp-event" | "once",
3590
4267
  watchPath?: string,
3591
4268
  dependsOn?: string[],
3592
4269
  model?: string,
@@ -3616,7 +4293,9 @@ async function schedulerCreateTask(
3616
4293
  /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
3617
4294
  sessionId?: string,
3618
4295
  /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
3619
- sessionMaxRuns?: number
4296
+ sessionMaxRuns?: number,
4297
+ /** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
4298
+ triggerExtras?: TriggerExtras
3620
4299
  ): Promise<void> {
3621
4300
  const normalizedModel = model?.trim() || undefined;
3622
4301
  const normalizedPriority = normalizePriority(priority);
@@ -3626,6 +4305,35 @@ async function schedulerCreateTask(
3626
4305
  const normalizedNotBefore = notBefore?.trim() || undefined;
3627
4306
  const normalizedNotAfter = notAfter?.trim() || undefined;
3628
4307
  const normalizedPausedUntil = pausedUntil?.trim() || undefined;
4308
+ // Спринт 27: дни недели, политика окна и glob/git-фильтры.
4309
+ const normalizeGlobList = (raw?: string[]): string[] | undefined => {
4310
+ if (!Array.isArray(raw)) return undefined;
4311
+ const cleaned = Array.from(
4312
+ new Set(
4313
+ raw
4314
+ .filter((item): item is string => typeof item === "string")
4315
+ .map((item) => item.trim())
4316
+ .filter(Boolean)
4317
+ )
4318
+ );
4319
+ return cleaned.length > 0 ? cleaned : undefined;
4320
+ };
4321
+ const normalizedActiveDays = normalizeActiveDays(triggerExtras?.activeDays);
4322
+ const normalizedWindowPolicy =
4323
+ triggerExtras?.windowPolicy === "skip" || triggerExtras?.windowPolicy === "run"
4324
+ ? triggerExtras.windowPolicy
4325
+ : undefined;
4326
+ const normalizedWatchGlobs = normalizeGlobList(triggerExtras?.watchGlobs);
4327
+ const normalizedWatchIgnore = normalizeGlobList(triggerExtras?.watchIgnore);
4328
+ const normalizedGitBranch = triggerExtras?.gitBranch?.trim() || undefined;
4329
+ const normalizedGitPaths = normalizeGlobList(triggerExtras?.gitPaths);
4330
+ const normalizedGitIgnore = normalizeGlobList(triggerExtras?.gitIgnore);
4331
+ const normalizedGitPollSeconds =
4332
+ typeof triggerExtras?.gitPollSeconds === "number" &&
4333
+ Number.isFinite(triggerExtras.gitPollSeconds) &&
4334
+ triggerExtras.gitPollSeconds >= 5
4335
+ ? Math.floor(triggerExtras.gitPollSeconds)
4336
+ : undefined;
3629
4337
  const normalizedMcpEvent =
3630
4338
  mcpEvent && mcpEvent.event?.trim()
3631
4339
  ? {
@@ -3736,6 +4444,22 @@ async function schedulerCreateTask(
3736
4444
  if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
3737
4445
  throw new Error("Для MCP-триггера нужно указать имя события (mcpEvent.event).");
3738
4446
  }
4447
+ // Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
4448
+ if (effectiveTriggerType === "git") {
4449
+ const gitCwd = workspaceId?.trim()
4450
+ ? getWorkspace(workspaceId.trim())?.path
4451
+ : workingDirectory?.trim() || projectDirectory || process.cwd();
4452
+ if (!gitCwd) {
4453
+ throw new Error(
4454
+ `Задача "${name}": для git-триггера нужна рабочая директория или workspace.`
4455
+ );
4456
+ }
4457
+ if (!readGitBranch(gitCwd)) {
4458
+ throw new Error(
4459
+ `Задача "${name}": git-триггер требует git-репозиторий в "${gitCwd}".`
4460
+ );
4461
+ }
4462
+ }
3739
4463
  // Валидируем cron-выражение до создания файлов. Для file/mcp-event
3740
4464
  // расписание не используется вовсе.
3741
4465
  if (effectiveTriggerType === "cron") {
@@ -3760,6 +4484,14 @@ async function schedulerCreateTask(
3760
4484
  throw new Error(`Задача "${name}": ${windowError}`);
3761
4485
  }
3762
4486
  }
4487
+ // Спринт 27: окно и дни недели применимы и к событийным триггерам
4488
+ // (file/git/mcp-event/once) — проверяем корректность до создания задачи.
4489
+ if (effectiveTriggerType !== "cron") {
4490
+ const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
4491
+ if (windowError) {
4492
+ throw new Error(`Задача "${name}": ${windowError}`);
4493
+ }
4494
+ }
3763
4495
 
3764
4496
  const sanitized = sanitizeName(name);
3765
4497
  const lockFile = lockFilePath(sanitized);
@@ -3772,7 +4504,9 @@ async function schedulerCreateTask(
3772
4504
  schedule,
3773
4505
  normalizedTz,
3774
4506
  normalizedNotBefore,
3775
- normalizedNotAfter
4507
+ normalizedNotAfter,
4508
+ normalizedActiveDays,
4509
+ normalizedWindowPolicy
3776
4510
  )
3777
4511
  : undefined;
3778
4512
  const wrapperGate = gate
@@ -3941,6 +4675,15 @@ async function schedulerCreateTask(
3941
4675
  timezone: normalizedTz,
3942
4676
  notBefore: normalizedNotBefore,
3943
4677
  notAfter: normalizedNotAfter,
4678
+ // Спринт 27: дни недели, политика окна, glob- и git-фильтры.
4679
+ activeDays: normalizedActiveDays,
4680
+ windowPolicy: normalizedWindowPolicy,
4681
+ watchGlobs: normalizedWatchGlobs,
4682
+ watchIgnore: normalizedWatchIgnore,
4683
+ gitBranch: normalizedGitBranch,
4684
+ gitPaths: normalizedGitPaths,
4685
+ gitIgnore: normalizedGitIgnore,
4686
+ gitPollSeconds: normalizedGitPollSeconds,
3944
4687
  pausedUntil: normalizedPausedUntil,
3945
4688
  allowedTools: normalizedAllowedTools,
3946
4689
  deniedTools: normalizedDeniedTools,