opencode-windows-scheduler 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +58 -7
  2. package/README.md +14 -4
  3. package/README.ru.md +14 -4
  4. package/ROADMAP.md +30 -20
  5. package/dist/core/analytics.d.ts +129 -0
  6. package/dist/core/analytics.d.ts.map +1 -0
  7. package/dist/core/analytics.js +286 -0
  8. package/dist/core/dry-run.d.ts +13 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +30 -0
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +10 -0
  13. package/dist/core/ps-wrapper.d.ts +32 -2
  14. package/dist/core/ps-wrapper.d.ts.map +1 -1
  15. package/dist/core/ps-wrapper.js +101 -3
  16. package/dist/core/retention.d.ts +29 -0
  17. package/dist/core/retention.d.ts.map +1 -0
  18. package/dist/core/retention.js +98 -0
  19. package/dist/core/schedule-gate.d.ts +2 -0
  20. package/dist/core/schedule-gate.d.ts.map +1 -0
  21. package/dist/core/schedule-gate.js +182 -0
  22. package/dist/core/schedule-v2.d.ts +88 -0
  23. package/dist/core/schedule-v2.d.ts.map +1 -0
  24. package/dist/core/schedule-v2.js +496 -0
  25. package/dist/core/scheduler/types.d.ts +15 -0
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/scheduler/windows.d.ts.map +1 -1
  28. package/dist/core/scheduler/windows.js +13 -1
  29. package/dist/core/wrappers/bash.d.ts +15 -0
  30. package/dist/core/wrappers/bash.d.ts.map +1 -1
  31. package/dist/core/wrappers/bash.js +44 -1
  32. package/dist/db/history-repo.d.ts +41 -0
  33. package/dist/db/history-repo.d.ts.map +1 -1
  34. package/dist/db/history-repo.js +78 -0
  35. package/dist/db/schema.d.ts +1 -1
  36. package/dist/db/schema.d.ts.map +1 -1
  37. package/dist/db/schema.js +11 -0
  38. package/dist/index.d.ts +117 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1094 -56
  41. package/dist/notifications.d.ts +112 -6
  42. package/dist/notifications.d.ts.map +1 -1
  43. package/dist/notifications.js +396 -34
  44. package/dist/profiles.d.ts +60 -0
  45. package/dist/profiles.d.ts.map +1 -0
  46. package/dist/profiles.js +209 -0
  47. package/dist/rpc.d.ts +645 -0
  48. package/dist/rpc.d.ts.map +1 -1
  49. package/dist/rpc.js +251 -2
  50. package/dist/server.d.ts.map +1 -1
  51. package/dist/server.js +200 -7
  52. package/dist/settings.d.ts +80 -0
  53. package/dist/settings.d.ts.map +1 -1
  54. package/dist/settings.js +159 -8
  55. package/dist/task-transfer.d.ts +13 -0
  56. package/dist/task-transfer.d.ts.map +1 -1
  57. package/dist/task-transfer.js +26 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js +3 -11
  60. package/dist/version.d.ts +8 -0
  61. package/dist/version.d.ts.map +1 -0
  62. package/dist/version.js +27 -0
  63. package/dist/workspaces.d.ts +43 -0
  64. package/dist/workspaces.d.ts.map +1 -1
  65. package/dist/workspaces.js +174 -8
  66. package/docs/ARCHITECTURE.md +45 -13
  67. package/docs/FEATURES.md +103 -12
  68. package/gui-experimental.cjs +4 -2
  69. package/package.json +8 -2
  70. package/src/core/analytics.ts +414 -0
  71. package/src/core/dry-run.ts +42 -0
  72. package/src/core/matrix.ts +10 -0
  73. package/src/core/ps-wrapper.ts +117 -3
  74. package/src/core/retention.ts +141 -0
  75. package/src/core/schedule-gate.ts +213 -0
  76. package/src/core/schedule-v2.ts +533 -0
  77. package/src/core/scheduler/types.ts +15 -0
  78. package/src/core/scheduler/windows.ts +13 -1
  79. package/src/core/wrappers/bash.ts +60 -0
  80. package/src/db/history-repo.ts +116 -0
  81. package/src/db/schema.ts +14 -0
  82. package/src/gui.tsx +3613 -2725
  83. package/src/index.ts +1325 -55
  84. package/src/notifications.ts +516 -40
  85. package/src/profiles.ts +236 -0
  86. package/src/rpc.ts +267 -2
  87. package/src/server.ts +226 -7
  88. package/src/settings.ts +285 -9
  89. package/src/task-transfer.ts +44 -0
  90. package/src/types.ts +3 -13
  91. package/src/version.ts +27 -0
  92. package/src/workspaces.ts +214 -8
  93. package/dist/gui-experimental.cjs +0 -1
package/dist/server.js CHANGED
@@ -3,9 +3,13 @@ import fs from "node:fs/promises";
3
3
  import { execFile } from "node:child_process";
4
4
  import { promisify } from "node:util";
5
5
  import { loadHistory, loadMetrics } from "./history.js";
6
+ import { getHistory, countRunningRecords } from "./db/history-repo.js";
7
+ import { buildAnalytics, historyToCsv } from "./core/analytics.js";
6
8
  import { getSchedulerTitle } from "./core/scheduler/index.js";
9
+ import { getPluginVersion } from "./version.js";
7
10
  import { checkpointDb, getDbFile, getDbStatus } from "./db/index.js";
8
11
  import { listWorkspaces } from "./workspaces.js";
12
+ import { getProfileName, getProfilePort } from "./profiles.js";
9
13
  import { simulatePipeline } from "./core/dry-run.js";
10
14
  /**
11
15
  * Локальный веб-дашборд (Спринт 5).
@@ -122,7 +126,8 @@ export async function startDashboardServer(deps, ports) {
122
126
  return { port: running.port };
123
127
  if (starting)
124
128
  return starting;
125
- const preferred = ports?.preferred ?? PREFERRED_PORT;
129
+ // Спринт 21: у профиля может быть свой порт (profile.json / OPENCODE_SCHEDULER_PORT).
130
+ const preferred = ports?.preferred ?? getProfilePort(getProfileName()) ?? PREFERRED_PORT;
126
131
  const fallback = ports?.fallback ?? FALLBACK_PORT;
127
132
  // Последний кандидат — порт 0: ОС сама выдаст гарантированно свободный порт.
128
133
  const candidates = ports
@@ -331,6 +336,8 @@ async function handleRequest(req, res, deps) {
331
336
  pathname === "/api/history" ||
332
337
  pathname === "/api/metrics" ||
333
338
  pathname === "/api/models-analysis" ||
339
+ pathname === "/api/analytics" ||
340
+ pathname === "/api/history/export" ||
334
341
  pathname === "/api/export-db" ||
335
342
  pathname === "/api/workspaces" ||
336
343
  pathname === "/api/health" ||
@@ -356,6 +363,10 @@ async function handleRequest(req, res, deps) {
356
363
  ok: true,
357
364
  app: DASHBOARD_MARKER,
358
365
  port: getDashboardPort(),
366
+ version: getPluginVersion(),
367
+ scheduler: getSchedulerTitle(),
368
+ profile: getProfileName(),
369
+ queueDepth: countRunningRecords(),
359
370
  db: getDbStatus(),
360
371
  });
361
372
  return;
@@ -454,6 +465,40 @@ async function handleRequest(req, res, deps) {
454
465
  sendJson(res, 200, aggregateModels(history));
455
466
  return;
456
467
  }
468
+ // Аналитика за период (Спринт 18): итоги, дневные бакеты, топ по стоимости.
469
+ if (req.method === "GET" && pathname === "/api/analytics") {
470
+ const days = Math.min(365, Math.max(1, Math.floor(Number(url.searchParams.get("days")) || 14)));
471
+ const topLimit = Math.max(1, Math.floor(Number(url.searchParams.get("top")) || 10));
472
+ const records = getHistory(null, 20000);
473
+ const tasks = await deps.getTasks();
474
+ const report = buildAnalytics(records, {
475
+ days,
476
+ topLimit,
477
+ tasks: tasks.map((task) => ({
478
+ name: task.name,
479
+ matrixParentId: task.matrixParentId ?? null,
480
+ })),
481
+ });
482
+ sendJson(res, 200, report);
483
+ return;
484
+ }
485
+ // Экспорт истории: CSV (для Excel) или JSON (для скриптов).
486
+ if (req.method === "GET" && pathname === "/api/history/export") {
487
+ const format = (url.searchParams.get("format") || "csv").toLowerCase();
488
+ if (format !== "csv" && format !== "json") {
489
+ sendJson(res, 400, { error: "Неподдерживаемый формат экспорта. Допустимые: csv, json." });
490
+ return;
491
+ }
492
+ const records = getHistory(null, 100000);
493
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
494
+ if (format === "json") {
495
+ sendAttachment(res, 200, "application/json; charset=utf-8", JSON.stringify({ exportedAt: new Date().toISOString(), records }, null, 2), `history-${stamp}.json`);
496
+ }
497
+ else {
498
+ sendAttachment(res, 200, "text/csv; charset=utf-8", historyToCsv(records), `history-${stamp}.csv`);
499
+ }
500
+ return;
501
+ }
457
502
  if (req.method === "GET" && (pathname === "/api/metrics" || pathname === "/api/summary")) {
458
503
  const metrics = await loadMetrics();
459
504
  // Токены и стоимость суммируем по history.json (как требует спринт):
@@ -637,6 +682,22 @@ function sendBuffer(res, status, contentType, body, filename) {
637
682
  });
638
683
  res.end(body);
639
684
  }
685
+ /** Отправляет текстовый файл (CSV/JSON-экспорт истории). */
686
+ function sendAttachment(res, status, contentType, body, filename) {
687
+ if (res.headersSent) {
688
+ res.end();
689
+ return;
690
+ }
691
+ res.writeHead(status, {
692
+ "Content-Type": contentType,
693
+ "Content-Length": String(Buffer.byteLength(body, "utf8")),
694
+ "Content-Disposition": `attachment; filename="${filename}"`,
695
+ "Cache-Control": "no-store",
696
+ "X-Content-Type-Options": "nosniff",
697
+ [DASHBOARD_HEADER]: DASHBOARD_MARKER,
698
+ });
699
+ res.end(body);
700
+ }
640
701
  /**
641
702
  * Список задач + метрики по каждой задаче, посчитанные из history.json
642
703
  * (колонка «Метрики» в таблице дашборда).
@@ -733,6 +794,24 @@ function renderPage() {
733
794
  .prio { font-size: 12px; color: #f5a623; white-space: nowrap; }
734
795
  .hist { margin-top: 18px; background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 14px 18px; }
735
796
  .hist h2 { margin: 0 0 10px; font-size: 14px; font-weight: 600; }
797
+ .an-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
798
+ .an-actions { display: flex; gap: 6px; }
799
+ .an-actions .btn { padding: 3px 8px; font-size: 11px; }
800
+ .an-kpis { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 12px; font-size: 12px; color: var(--muted); }
801
+ .an-kpis b { color: var(--text); font-size: 14px; }
802
+ .an-chart { display: flex; align-items: flex-end; gap: 4px; height: 120px; padding: 6px 0 0; border-bottom: 1px solid var(--border); overflow-x: auto; }
803
+ .an-bar { flex: 1 1 0; min-width: 14px; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; height: 100%; cursor: default; }
804
+ .an-bar-fill { width: 100%; border-radius: 3px 3px 0 0; background: var(--accent); opacity: .85; }
805
+ .an-label { font-size: 9px; color: var(--muted); margin-top: 4px; white-space: nowrap; }
806
+ .an-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 14px; }
807
+ .an-grid h3 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; }
808
+ .an-table { width: 100%; border-collapse: collapse; font-size: 12px; }
809
+ .an-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 3px 6px; border-bottom: 1px solid var(--border); }
810
+ .an-table td { padding: 3px 6px; border-bottom: 1px solid var(--border); color: var(--text); }
811
+ .an-table tr:last-child td { border-bottom: none; }
812
+ .an-rate.okr { color: var(--ok); }
813
+ .an-rate.midr { color: var(--run); }
814
+ .an-rate.errr { color: var(--err); }
736
815
  .hist-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; padding: 5px 0; border-bottom: 1px solid var(--border); font-size: 12px; }
737
816
  .hist-row:last-child { border-bottom: none; }
738
817
  .hist-time { color: var(--muted); white-space: nowrap; }
@@ -741,8 +820,7 @@ function renderPage() {
741
820
  .hist-hook { white-space: nowrap; }
742
821
  .hist-hook.okh { color: #34c759; }
743
822
  .hist-hook.errh { color: #ff3b30; }
744
- .whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; }
745
- .whatif-text b { color: var(--text); }
823
+ .whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; } .whatif-text b { color: var(--text); }
746
824
  .wi-table { width: 100%; border-collapse: collapse; font-size: 12px; }
747
825
  .wi-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 4px 8px; border-bottom: 1px solid var(--border); }
748
826
  .wi-table td { padding: 4px 8px; border-bottom: 1px solid var(--border); color: var(--text); }
@@ -789,7 +867,7 @@ function renderPage() {
789
867
  <header>
790
868
  <div>
791
869
  <h1>❄️ ${getSchedulerTitle()} ❄️</h1>
792
- <div class="sub">Локальный веб-дашборд · Local AI CI/CD Orchestrator</div>
870
+ <div class="sub">Локальный веб-дашборд · Local AI CI/CD Orchestrator · профиль <b>${getProfileName()}</b></div>
793
871
  </div>
794
872
  <div style="text-align:right">
795
873
  <a class="btn btn-db" href="/api/export-db" download>💾 Скачать БД</a>
@@ -833,6 +911,22 @@ function renderPage() {
833
911
  <div id="history"><div class="empty">Загрузка…</div></div>
834
912
  </div>
835
913
 
914
+ <div class="hist">
915
+ <div class="an-head">
916
+ <h2>📊 Аналитика за период</h2>
917
+ <div class="an-actions">
918
+ <a class="btn" href="/api/history/export?format=csv" download>⬇️ CSV</a>
919
+ <a class="btn" href="/api/history/export?format=json" download>⬇️ JSON</a>
920
+ </div>
921
+ </div>
922
+ <div class="an-kpis" id="an-kpis"><span>Загрузка…</span></div>
923
+ <div class="an-chart" id="an-chart"></div>
924
+ <div class="an-grid">
925
+ <div><h3>Топ задач по стоимости</h3><div id="an-top"></div></div>
926
+ <div><h3>Матрицы</h3><div id="an-matrices"></div></div>
927
+ </div>
928
+ </div>
929
+
836
930
  <div class="hist">
837
931
  <h2>📊 What-If: Анализ моделей</h2>
838
932
  <div id="whatif-table"><div class="empty">Загрузка…</div></div>
@@ -1027,8 +1121,105 @@ function renderPage() {
1027
1121
  box.innerHTML = html;
1028
1122
  }
1029
1123
 
1030
- function renderModelsAnalysis(data) {
1031
- var box = document.getElementById('whatif-table');
1124
+ function rateClass(rate) {
1125
+ if (rate >= 90) return 'okr';
1126
+ if (rate >= 60) return 'midr';
1127
+ return 'errr';
1128
+ }
1129
+
1130
+ function money(value) {
1131
+ var n = Number(value) || 0;
1132
+ return '$' + n.toFixed(n >= 1 ? 2 : 4);
1133
+ }
1134
+
1135
+ function durationText(ms) {
1136
+ var n = Number(ms) || 0;
1137
+ if (n <= 0) return '—';
1138
+ if (n < 1000) return n + ' мс';
1139
+ if (n < 60000) return (n / 1000).toFixed(1) + ' с';
1140
+ return Math.round(n / 60000) + ' мин';
1141
+ }
1142
+
1143
+ function renderAnalytics(an) {
1144
+ var kpis = document.getElementById('an-kpis');
1145
+ var chart = document.getElementById('an-chart');
1146
+ var top = document.getElementById('an-top');
1147
+ var matrices = document.getElementById('an-matrices');
1148
+ if (!kpis || !chart || !top || !matrices) return;
1149
+
1150
+ if (!an || !an.totals) {
1151
+ kpis.innerHTML = '<span>Аналитика недоступна.</span>';
1152
+ chart.innerHTML = '';
1153
+ top.innerHTML = '<div class="empty" style="padding:10px">—</div>';
1154
+ matrices.innerHTML = '<div class="empty" style="padding:10px">—</div>';
1155
+ return;
1156
+ }
1157
+
1158
+ var t = an.totals;
1159
+ kpis.innerHTML =
1160
+ '<span>Запусков: <b>' + t.total + '</b></span>' +
1161
+ '<span>Успех: <b class="an-rate ' + rateClass(t.successRate) + '">' + t.successRate + '%</b></span>' +
1162
+ '<span>Средняя длительность: <b>' + durationText(t.avgDurationMs) + '</b></span>' +
1163
+ '<span>Токены: <b>' + Number(t.tokens || 0).toLocaleString('ru-RU') + '</b></span>' +
1164
+ '<span>Стоимость: <b>' + money(t.costUsd) + '</b></span>' +
1165
+ '<span>Окно: <b>' + an.windowDays + ' дн.</b></span>' +
1166
+ (t.partial ? '<span>Частично: <b>' + t.partial + '</b></span>' : '');
1167
+
1168
+ var daily = an.daily || [];
1169
+ var max = 1;
1170
+ for (var i = 0; i < daily.length; i++) {
1171
+ if (daily[i].total > max) max = daily[i].total;
1172
+ }
1173
+ var bars = '';
1174
+ for (var j = 0; j < daily.length; j++) {
1175
+ var d = daily[j];
1176
+ var h = d.total > 0 ? Math.max(3, Math.round((d.total / max) * 92)) : 2;
1177
+ var color = d.total === 0 ? 'var(--border)' : (d.error > 0 ? 'var(--err)' : 'var(--ok)');
1178
+ var tip = d.date + ': всего ' + d.total + ', успех ' + d.success + ', ошибок ' + d.error + ', ' + money(d.costUsd);
1179
+ bars += '<div class="an-bar" title="' + esc(tip) + '">' +
1180
+ '<div class="an-bar-fill" style="height:' + h + '%' + ';background:' + esc(color) + '"></div>' +
1181
+ '<div class="an-label">' + esc(String(d.date).slice(5)) + '</div>' +
1182
+ '</div>';
1183
+ }
1184
+ chart.innerHTML = bars || '<div class="empty" style="padding:10px">Нет данных за период.</div>';
1185
+
1186
+ var topRows = an.topByCost || [];
1187
+ if (topRows.length === 0) {
1188
+ top.innerHTML = '<div class="empty" style="padding:10px">Нет запусков за период.</div>';
1189
+ } else {
1190
+ var html = '<table class="an-table"><thead><tr><th>Задача</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
1191
+ for (var k = 0; k < topRows.length; k++) {
1192
+ var row = topRows[k];
1193
+ html += '<tr>' +
1194
+ '<td>' + (row.isMatrixClone ? '↳ ' : '') + esc(row.taskName) + '</td>' +
1195
+ '<td>' + row.total + '</td>' +
1196
+ '<td class="an-rate ' + rateClass(row.successRate) + '">' + row.successRate + '%</td>' +
1197
+ '<td>' + money(row.costUsd) + '</td>' +
1198
+ '</tr>';
1199
+ }
1200
+ top.innerHTML = html + '</tbody></table>';
1201
+ }
1202
+
1203
+ var matrixRows = an.matrices || [];
1204
+ if (matrixRows.length === 0) {
1205
+ matrices.innerHTML = '<div class="empty" style="padding:10px">Матриц за период не запускалось.</div>';
1206
+ } else {
1207
+ var mhtml = '<table class="an-table"><thead><tr><th>Матрица</th><th>Клонов</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
1208
+ for (var q = 0; q < matrixRows.length; q++) {
1209
+ var m = matrixRows[q];
1210
+ mhtml += '<tr>' +
1211
+ '<td>📦 ' + esc(m.parentId) + '</td>' +
1212
+ '<td>' + m.clones + '</td>' +
1213
+ '<td>' + m.total + '</td>' +
1214
+ '<td class="an-rate ' + rateClass(m.successRate) + '">' + m.successRate + '%</td>' +
1215
+ '<td>' + money(m.costUsd) + '</td>' +
1216
+ '</tr>';
1217
+ }
1218
+ matrices.innerHTML = mhtml + '</tbody></table>';
1219
+ }
1220
+ }
1221
+
1222
+ function renderModelsAnalysis(data) { var box = document.getElementById('whatif-table');
1032
1223
  var text = document.getElementById('whatif-text');
1033
1224
  if (!box || !text) return;
1034
1225
  var models = (data && data.models) || [];
@@ -1270,7 +1461,8 @@ function renderPage() {
1270
1461
  loadMetricsJson(),
1271
1462
  safeJson('/api/history', { records: [] }),
1272
1463
  safeJson('/api/models-analysis', { models: [], totals: {}, whatIf: [] }),
1273
- safeJson('/api/workspaces', { workspaces: [] })
1464
+ safeJson('/api/workspaces', { workspaces: [] }),
1465
+ safeJson('/api/analytics?days=14', null)
1274
1466
  ]);
1275
1467
  var tasks = (results[0] && results[0].tasks) || [];
1276
1468
  var m = results[1] || {};
@@ -1289,6 +1481,7 @@ function renderPage() {
1289
1481
  renderGraph(tasks);
1290
1482
  renderHistory(history);
1291
1483
  renderModelsAnalysis(modelsAnalysis);
1484
+ renderAnalytics(results[5]);
1292
1485
  showServerWarn(results[0] ? null : 'Не удалось загрузить список задач — остальные блоки обновлены. Подробности в консоли (F12).');
1293
1486
  updated.textContent = 'Обновлено: ' + new Date().toLocaleTimeString();
1294
1487
  } catch (err) {
@@ -4,6 +4,50 @@ export interface WebhookNotificationSettings {
4
4
  enabled: boolean;
5
5
  /** URL вебхука. */
6
6
  url: string;
7
+ /** Таймаут запроса в мс (1000..120000). */
8
+ timeoutMs: number;
9
+ /** Сколько раз повторить при сетевой ошибке / 5xx / 429 (0..5). */
10
+ retryCount: number;
11
+ /** Базовая задержка backoff в мс; каждая следующая попытка ждёт вдвое дольше. */
12
+ retryDelayMs: number;
13
+ }
14
+ /** Настраиваемые шаблоны сообщений о завершении задачи. */
15
+ export interface NotificationTemplates {
16
+ /** Шаблон успеха. Плейсхолдеры: {task} {status} {duration} {error} {emoji}. */
17
+ success: string;
18
+ /** Шаблон ошибки. {error} разворачивается в «: текст» или пустую строку. */
19
+ error: string;
20
+ }
21
+ /** Фильтры по задачам: include имеет приоритет, exclude сильнее include. */
22
+ export interface NotificationFilters {
23
+ /** Уведомлять только эти задачи (пусто — все). Поддерживает `*`. */
24
+ include: string[];
25
+ /** Никогда не уведомлять эти задачи. Поддерживает `*`. */
26
+ exclude: string[];
27
+ }
28
+ /** Уведомления о матрицах (Спринт 20). */
29
+ export interface MatrixNotificationSettings {
30
+ /** Включены ли уведомления о матрицах. */
31
+ enabled: boolean;
32
+ /** Сообщать о partial (часть клонов упала). */
33
+ onPartial: boolean;
34
+ /** Сообщать, когда упали все клоны. */
35
+ onAllFailed: boolean;
36
+ /** Порог «матрица зависла» в минутах (0 — детектор выключен). */
37
+ stuckAfterMinutes: number;
38
+ }
39
+ /** Периодичность дайджеста. */
40
+ export type DigestFrequency = "daily" | "weekly";
41
+ /** Дайджест по истории запусков (Спринт 20). */
42
+ export interface DigestSettings {
43
+ /** Включён ли дайджест. */
44
+ enabled: boolean;
45
+ /** Ежедневно или еженедельно (по понедельникам). */
46
+ frequency: DigestFrequency;
47
+ /** Время отправки в формате HH:MM (локальное время сервера). */
48
+ time: string;
49
+ /** ISO-момент последней отправки — дедуп между перезапусками плагина. */
50
+ lastSentAt: string | null;
7
51
  }
8
52
  /**
9
53
  * Уведомления о завершении задач.
@@ -18,6 +62,31 @@ export interface NotificationSettings {
18
62
  onlyOnError: boolean;
19
63
  /** Webhook-канал. */
20
64
  webhook?: WebhookNotificationSettings;
65
+ /** Шаблоны сообщений. */
66
+ templates?: NotificationTemplates;
67
+ /** Фильтры по задачам. */
68
+ filters?: NotificationFilters;
69
+ /** Уведомления о матрицах. */
70
+ matrix?: MatrixNotificationSettings;
71
+ /** Периодический дайджест. */
72
+ digest?: DigestSettings;
73
+ }
74
+ /**
75
+ * Ретеншн истории (Спринт 18).
76
+ *
77
+ * Дашборд и метрики живут на агрегатах, поэтому удаление старых записей
78
+ * не искажает «Всего запусков» и стоимость: чистится только сырая история.
79
+ * 0 — соответствующее ограничение выключено.
80
+ */
81
+ export interface HistorySettings {
82
+ /** Удалять завершённые записи старше N дней (0 — не удалять по возрасту). */
83
+ retentionDays: number;
84
+ /** Хранить не более N последних записей (0 — без ограничения). */
85
+ maxRecords: number;
86
+ /** Когда последний раз запускалась автоочистка (ISO). */
87
+ lastCleanupAt: string | null;
88
+ /** Сколько записей удалила последняя очистка (для дашборда). */
89
+ lastCleanupDeleted: number;
21
90
  }
22
91
  /**
23
92
  * Глобальные настройки плагина, которые меняются из GUI.
@@ -30,10 +99,21 @@ export interface SchedulerSettings {
30
99
  winterMode: boolean;
31
100
  /** Уведомления о завершении задач. */
32
101
  notifications: NotificationSettings;
102
+ /** Ретеншн истории запусков. */
103
+ history: HistorySettings;
33
104
  }
34
105
  export declare const SETTINGS_FILE: string;
35
106
  export declare const DEFAULT_MAX_CONCURRENT = 1;
36
107
  export declare const DEFAULT_WINTER_MODE = false;
108
+ export declare const DEFAULT_RETENTION_DAYS = 30;
109
+ export declare const DEFAULT_MAX_RECORDS = 5000;
110
+ /** Уведомления (Спринт 20): таймаут webhook, повторы и порог «зависшей» матрицы. */
111
+ export declare const DEFAULT_WEBHOOK_TIMEOUT_MS = 10000;
112
+ export declare const DEFAULT_WEBHOOK_RETRY_COUNT = 2;
113
+ export declare const DEFAULT_WEBHOOK_RETRY_DELAY_MS = 1000;
114
+ export declare const DEFAULT_STUCK_AFTER_MINUTES = 60;
115
+ /** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
116
+ export declare function defaultHistorySettings(): HistorySettings;
37
117
  /** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
38
118
  export declare function defaultNotifications(): NotificationSettings;
39
119
  /** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
@@ -1 +1 @@
1
- {"version":3,"file":"settings.d.ts","sourceRoot":"","sources":["../src/settings.ts"],"names":[],"mappings":"AAIA,6DAA6D;AAC7D,MAAM,WAAW,2BAA2B;IAC1C,wBAAwB;IACxB,OAAO,EAAE,OAAO,CAAC;IACjB,mBAAmB;IACnB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACnC,uCAAuC;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,yEAAyE;IACzE,WAAW,EAAE,OAAO,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BAAiB;IAChC,sEAAsE;IACtE,aAAa,EAAE,MAAM,CAAC;IACtB,uEAAuE;IACvE,UAAU,EAAE,OAAO,CAAC;IACpB,sCAAsC;IACtC,aAAa,EAAE,oBAAoB,CAAC;IACpC,gCAAgC;IAChC,OAAO,EAAE,eAAe,CAAC;CAC1B;AAED,eAAO,MAAM,aAAa,QAAyC,CAAC;AACpE,eAAO,MAAM,sBAAsB,IAAI,CAAC;AACxC,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAExC,oFAAoF;AACpF,eAAO,MAAM,0BAA0B,QAAS,CAAC;AACjD,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,eAAO,MAAM,8BAA8B,OAAQ,CAAC;AACpD,eAAO,MAAM,2BAA2B,KAAK,CAAC;AAE9C,8DAA8D;AAC9D,wBAAgB,sBAAsB,IAAI,eAAe,CAOxD;AAkCD,uEAAuE;AACvE,wBAAgB,oBAAoB,IAAI,oBAAoB,CA6B3D;AA6KD,0EAA0E;AAC1E,wBAAsB,YAAY,IAAI,OAAO,CAAC,iBAAiB,CAAC,CA6B/D;AAED,iEAAiE;AACjE,wBAAsB,YAAY,CAChC,KAAK,EAAE,OAAO,CAAC,iBAAiB,CAAC,GAChC,OAAO,CAAC,iBAAiB,CAAC,CAuB5B"}
package/dist/settings.js CHANGED
@@ -4,12 +4,75 @@ import { PLUGIN_DIR } from "./types.js";
4
4
  export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
5
5
  export const DEFAULT_MAX_CONCURRENT = 1;
6
6
  export const DEFAULT_WINTER_MODE = false;
7
+ export const DEFAULT_RETENTION_DAYS = 30;
8
+ export const DEFAULT_MAX_RECORDS = 5000;
9
+ /** Уведомления (Спринт 20): таймаут webhook, повторы и порог «зависшей» матрицы. */
10
+ export const DEFAULT_WEBHOOK_TIMEOUT_MS = 10000;
11
+ export const DEFAULT_WEBHOOK_RETRY_COUNT = 2;
12
+ export const DEFAULT_WEBHOOK_RETRY_DELAY_MS = 1000;
13
+ export const DEFAULT_STUCK_AFTER_MINUTES = 60;
14
+ /** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
15
+ export function defaultHistorySettings() {
16
+ return {
17
+ retentionDays: DEFAULT_RETENTION_DAYS,
18
+ maxRecords: DEFAULT_MAX_RECORDS,
19
+ lastCleanupAt: null,
20
+ lastCleanupDeleted: 0,
21
+ };
22
+ }
23
+ /** Приводит счётчик ретеншна к безопасному целому (>= 0). */
24
+ function normalizeRetentionLimit(value, fallback) {
25
+ const n = Number(value);
26
+ if (!Number.isFinite(n))
27
+ return fallback;
28
+ const int = Math.floor(n);
29
+ return int >= 0 ? int : fallback;
30
+ }
31
+ /** Приводит настройки ретеншна к безопасному виду. */
32
+ function normalizeHistorySettings(value, fallback) {
33
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
34
+ return { ...fallback };
35
+ }
36
+ const raw = value;
37
+ const lastCleanupAt = typeof raw.lastCleanupAt === "string" && raw.lastCleanupAt.trim()
38
+ ? raw.lastCleanupAt.trim()
39
+ : null;
40
+ return {
41
+ retentionDays: normalizeRetentionLimit(raw.retentionDays, fallback.retentionDays),
42
+ maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
43
+ lastCleanupAt,
44
+ lastCleanupDeleted: normalizeRetentionLimit(raw.lastCleanupDeleted, fallback.lastCleanupDeleted),
45
+ };
46
+ }
7
47
  /** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
8
48
  export function defaultNotifications() {
9
49
  return {
10
50
  enabled: false,
11
51
  onlyOnError: true,
12
- webhook: { enabled: false, url: "" },
52
+ webhook: {
53
+ enabled: false,
54
+ url: "",
55
+ timeoutMs: DEFAULT_WEBHOOK_TIMEOUT_MS,
56
+ retryCount: DEFAULT_WEBHOOK_RETRY_COUNT,
57
+ retryDelayMs: DEFAULT_WEBHOOK_RETRY_DELAY_MS,
58
+ },
59
+ templates: {
60
+ success: '✅ Задача "{task}" выполнена ({duration})',
61
+ error: '❌ Задача "{task}" упала ({duration}){error}',
62
+ },
63
+ filters: { include: [], exclude: [] },
64
+ matrix: {
65
+ enabled: true,
66
+ onPartial: true,
67
+ onAllFailed: true,
68
+ stuckAfterMinutes: DEFAULT_STUCK_AFTER_MINUTES,
69
+ },
70
+ digest: {
71
+ enabled: false,
72
+ frequency: "daily",
73
+ time: "09:00",
74
+ lastSentAt: null,
75
+ },
13
76
  };
14
77
  }
15
78
  /** Приводит значение лимита к безопасному целому (>= 0). */
@@ -30,19 +93,66 @@ function normalizeWinterMode(value, fallback) {
30
93
  return false;
31
94
  return fallback;
32
95
  }
96
+ /** Приводит значение к конечному целому в диапазоне [min, max]. */
97
+ function normalizeIntInRange(value, fallback, min, max) {
98
+ const n = Number(value);
99
+ if (!Number.isFinite(n))
100
+ return fallback;
101
+ return Math.min(max, Math.max(min, Math.floor(n)));
102
+ }
103
+ /** Приводит время HH:MM к безопасному виду. */
104
+ function normalizeDailyTime(value, fallback) {
105
+ if (typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value.trim())) {
106
+ return value.trim();
107
+ }
108
+ return fallback;
109
+ }
110
+ /** Список имён задач: массив строк, обрезанных и без пустых значений. */
111
+ function normalizeNameList(value, fallback) {
112
+ if (!Array.isArray(value))
113
+ return [...fallback];
114
+ return value
115
+ .filter((item) => typeof item === "string")
116
+ .map((item) => item.trim())
117
+ .filter((item) => item.length > 0);
118
+ }
119
+ function asRecord(value) {
120
+ return value && typeof value === "object" && !Array.isArray(value)
121
+ ? value
122
+ : undefined;
123
+ }
33
124
  /** Приводит настройки уведомлений к безопасному виду. */
34
125
  function normalizeNotifications(value, fallback) {
35
- if (!value || typeof value !== "object" || Array.isArray(value)) {
126
+ const fallbackWebhook = fallback.webhook ?? defaultNotifications().webhook;
127
+ const fallbackTemplates = fallback.templates ?? defaultNotifications().templates;
128
+ const fallbackFilters = fallback.filters ?? { include: [], exclude: [] };
129
+ const fallbackMatrix = fallback.matrix ?? defaultNotifications().matrix;
130
+ const fallbackDigest = fallback.digest ?? defaultNotifications().digest;
131
+ const raw = asRecord(value);
132
+ if (!raw) {
36
133
  return {
37
134
  ...fallback,
38
- webhook: fallback.webhook ? { ...fallback.webhook } : { enabled: false, url: "" },
135
+ webhook: { ...fallbackWebhook },
136
+ templates: { ...fallbackTemplates },
137
+ filters: {
138
+ include: [...fallbackFilters.include],
139
+ exclude: [...fallbackFilters.exclude],
140
+ },
141
+ matrix: { ...fallbackMatrix },
142
+ digest: { ...fallbackDigest },
39
143
  };
40
144
  }
41
- const raw = value;
42
- const rawWebhook = raw.webhook && typeof raw.webhook === "object" && !Array.isArray(raw.webhook)
43
- ? raw.webhook
44
- : undefined;
45
- const fallbackWebhook = fallback.webhook ?? { enabled: false, url: "" };
145
+ const rawWebhook = asRecord(raw.webhook);
146
+ const rawTemplates = asRecord(raw.templates);
147
+ const rawFilters = asRecord(raw.filters);
148
+ const rawMatrix = asRecord(raw.matrix);
149
+ const rawDigest = asRecord(raw.digest);
150
+ const frequency = rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
151
+ ? rawDigest.frequency
152
+ : fallbackDigest.frequency;
153
+ const lastSentAt = typeof rawDigest?.lastSentAt === "string" && rawDigest.lastSentAt.trim()
154
+ ? rawDigest.lastSentAt.trim()
155
+ : null;
46
156
  return {
47
157
  enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
48
158
  onlyOnError: typeof raw.onlyOnError === "boolean" ? raw.onlyOnError : fallback.onlyOnError,
@@ -53,12 +163,48 @@ function normalizeNotifications(value, fallback) {
53
163
  url: typeof rawWebhook?.url === "string"
54
164
  ? rawWebhook.url.trim()
55
165
  : fallbackWebhook.url,
166
+ timeoutMs: normalizeIntInRange(rawWebhook?.timeoutMs, fallbackWebhook.timeoutMs, 1000, 120000),
167
+ retryCount: normalizeIntInRange(rawWebhook?.retryCount, fallbackWebhook.retryCount, 0, 5),
168
+ retryDelayMs: normalizeIntInRange(rawWebhook?.retryDelayMs, fallbackWebhook.retryDelayMs, 100, 60000),
169
+ },
170
+ templates: {
171
+ success: typeof rawTemplates?.success === "string" && rawTemplates.success.trim()
172
+ ? rawTemplates.success
173
+ : fallbackTemplates.success,
174
+ error: typeof rawTemplates?.error === "string" && rawTemplates.error.trim()
175
+ ? rawTemplates.error
176
+ : fallbackTemplates.error,
177
+ },
178
+ filters: {
179
+ include: normalizeNameList(rawFilters?.include, fallbackFilters.include),
180
+ exclude: normalizeNameList(rawFilters?.exclude, fallbackFilters.exclude),
181
+ },
182
+ matrix: {
183
+ enabled: typeof rawMatrix?.enabled === "boolean"
184
+ ? rawMatrix.enabled
185
+ : fallbackMatrix.enabled,
186
+ onPartial: typeof rawMatrix?.onPartial === "boolean"
187
+ ? rawMatrix.onPartial
188
+ : fallbackMatrix.onPartial,
189
+ onAllFailed: typeof rawMatrix?.onAllFailed === "boolean"
190
+ ? rawMatrix.onAllFailed
191
+ : fallbackMatrix.onAllFailed,
192
+ stuckAfterMinutes: normalizeIntInRange(rawMatrix?.stuckAfterMinutes, fallbackMatrix.stuckAfterMinutes, 0, 10080),
193
+ },
194
+ digest: {
195
+ enabled: typeof rawDigest?.enabled === "boolean"
196
+ ? rawDigest.enabled
197
+ : fallbackDigest.enabled,
198
+ frequency,
199
+ time: normalizeDailyTime(rawDigest?.time, fallbackDigest.time),
200
+ lastSentAt,
56
201
  },
57
202
  };
58
203
  }
59
204
  /** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
60
205
  export async function loadSettings() {
61
206
  const fallbackNotifications = defaultNotifications();
207
+ const fallbackHistory = defaultHistorySettings();
62
208
  try {
63
209
  const raw = await fs.readFile(SETTINGS_FILE, "utf8");
64
210
  const parsed = JSON.parse(raw);
@@ -66,6 +212,7 @@ export async function loadSettings() {
66
212
  maxConcurrent: normalizeMaxConcurrent(parsed?.maxConcurrent, DEFAULT_MAX_CONCURRENT),
67
213
  winterMode: normalizeWinterMode(parsed?.winterMode, DEFAULT_WINTER_MODE),
68
214
  notifications: normalizeNotifications(parsed?.notifications, fallbackNotifications),
215
+ history: normalizeHistorySettings(parsed?.history, fallbackHistory),
69
216
  };
70
217
  }
71
218
  catch {
@@ -73,6 +220,7 @@ export async function loadSettings() {
73
220
  maxConcurrent: DEFAULT_MAX_CONCURRENT,
74
221
  winterMode: DEFAULT_WINTER_MODE,
75
222
  notifications: fallbackNotifications,
223
+ history: fallbackHistory,
76
224
  };
77
225
  }
78
226
  }
@@ -89,6 +237,9 @@ export async function saveSettings(patch) {
89
237
  notifications: patch.notifications !== undefined
90
238
  ? normalizeNotifications(patch.notifications, current.notifications)
91
239
  : current.notifications,
240
+ history: patch.history !== undefined
241
+ ? normalizeHistorySettings(patch.history, current.history)
242
+ : current.history,
92
243
  };
93
244
  await fs.mkdir(PLUGIN_DIR, { recursive: true });
94
245
  await fs.writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2), "utf8");
@@ -128,6 +128,19 @@ export interface TaskDefinition {
128
128
  matrixQueue?: string[];
129
129
  /** Для родителя матрицы — true (флаг для фильтров/DAG). */
130
130
  isMatrixParent?: boolean;
131
+ /**
132
+ * IANA-часовой пояс задачи (Спринт 19), например "Europe/Moscow".
133
+ * Не задан — системный пояс. Если отличается от системного, задача
134
+ * регистрируется в poll-режиме: ОС будит её каждую минуту, а cron
135
+ * проверяется в обёртке с учётом этого пояса.
136
+ */
137
+ timezone?: string;
138
+ /** Начало окна запуска "HH:MM" (Спринт 19); вне окна запуск переносится. */
139
+ notBefore?: string;
140
+ /** Конец окна запуска "HH:MM"; может быть меньше notBefore (через полночь). */
141
+ notAfter?: string;
142
+ /** Пауза до даты (ISO, Спринт 19): плагин включит задачу автоматически. */
143
+ pausedUntil?: string;
131
144
  /** Когда задача была создана — защита от ложного catch-up сразу после создания. */
132
145
  createdAt?: string;
133
146
  }