opencode-windows-scheduler 1.0.0 → 1.1.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.
package/src/index.ts CHANGED
@@ -29,7 +29,10 @@ import {
29
29
  import { SchedulerRpc } from "./rpc.js";
30
30
  import { loadHistory, loadMetrics } from "./history.js";
31
31
  import { loadSettings, saveSettings } from "./settings.js";
32
- import type { NotificationSettings } from "./settings.js";
32
+ import type { HistorySettings, NotificationSettings } from "./settings.js";
33
+ import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
34
+ import { buildAnalytics } from "./core/analytics.js";
35
+ import { getHistory } from "./db/history-repo.js";
33
36
  import { sendTestNotification } from "./notifications.js";
34
37
  import {
35
38
  loadTaskDefinitions,
@@ -1247,6 +1250,26 @@ export default Plugin.define({
1247
1250
  }
1248
1251
  checkJsonBackups();
1249
1252
 
1253
+ // Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
1254
+ // плагину стартовать — пишем в лог и продолжаем.
1255
+ void maybeRunHistoryRetention()
1256
+ .then((report) => {
1257
+ if (report && report.deleted > 0) {
1258
+ console.log(
1259
+ `[retention] Удалено ${report.deleted} записей истории ` +
1260
+ `(по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}); ` +
1261
+ `осталось ${report.kept}.`
1262
+ );
1263
+ }
1264
+ })
1265
+ .catch((err: any) => {
1266
+ console.error(
1267
+ `[retention] Не удалось очистить историю: ${
1268
+ err instanceof Error ? err.message : String(err)
1269
+ }`
1270
+ );
1271
+ });
1272
+
1250
1273
  // Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
1251
1274
  const lockManager = new LockManager(LOCK_DIR);
1252
1275
  await lockManager.initialize();
@@ -1725,6 +1748,70 @@ export default Plugin.define({
1725
1748
  get_metrics: async () => {
1726
1749
  return await loadMetrics();
1727
1750
  },
1751
+ cleanup_history: async (input: unknown) => {
1752
+ const { retentionDays, maxRecords } = input as {
1753
+ retentionDays?: number;
1754
+ maxRecords?: number;
1755
+ };
1756
+ try {
1757
+ const report = await runHistoryRetention({ retentionDays, maxRecords });
1758
+ const message = report.skipped
1759
+ ? report.skipped
1760
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ` +
1761
+ `${report.deletedByCount}), осталось ${report.kept}.`;
1762
+ return {
1763
+ success: true,
1764
+ message,
1765
+ deleted: report.deleted,
1766
+ deletedByAge: report.deletedByAge,
1767
+ deletedByCount: report.deletedByCount,
1768
+ kept: report.kept,
1769
+ retentionDays: report.retentionDays,
1770
+ maxRecords: report.maxRecords,
1771
+ vacuumed: report.vacuumed,
1772
+ };
1773
+ } catch (err: any) {
1774
+ return {
1775
+ success: false,
1776
+ message: `Не удалось очистить историю: ${
1777
+ err instanceof Error ? err.message : String(err)
1778
+ }`,
1779
+ deleted: 0,
1780
+ deletedByAge: 0,
1781
+ deletedByCount: 0,
1782
+ kept: 0,
1783
+ retentionDays: 0,
1784
+ maxRecords: 0,
1785
+ vacuumed: false,
1786
+ };
1787
+ }
1788
+ },
1789
+ get_analytics: async (input: unknown) => {
1790
+ const { days, topLimit } = input as { days?: number; topLimit?: number };
1791
+ try {
1792
+ const windowDays = Math.min(
1793
+ 365,
1794
+ Math.max(1, Math.floor(Number(days) || 14))
1795
+ );
1796
+ const records = getHistory(null, 20000);
1797
+ const definitions = await loadTaskDefinitions();
1798
+ const report = buildAnalytics(records, {
1799
+ days: windowDays,
1800
+ topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
1801
+ tasks: definitions.map((definition) => ({
1802
+ name: definition.name,
1803
+ matrixParentId: definition.matrixParentId,
1804
+ })),
1805
+ });
1806
+ return { success: true, report };
1807
+ } catch (err: any) {
1808
+ return {
1809
+ success: false,
1810
+ report: null,
1811
+ error: err instanceof Error ? err.message : String(err),
1812
+ };
1813
+ }
1814
+ },
1728
1815
  get_dashboard_port: async () => {
1729
1816
  return { port: getDashboardPort() };
1730
1817
  },
@@ -1878,30 +1965,39 @@ export default Plugin.define({
1878
1965
  return await loadSettings();
1879
1966
  },
1880
1967
  save_settings: async (input: unknown) => {
1881
- const { maxConcurrent, winterMode, notifications } = input as {
1968
+ const { maxConcurrent, winterMode, notifications, history } = input as {
1882
1969
  maxConcurrent?: number;
1883
1970
  winterMode?: boolean;
1884
1971
  notifications?: NotificationSettings;
1972
+ history?: HistorySettings;
1885
1973
  };
1886
1974
  const current = await loadSettings();
1887
1975
  if (
1888
1976
  maxConcurrent === undefined &&
1889
1977
  winterMode === undefined &&
1890
- notifications === undefined
1978
+ notifications === undefined &&
1979
+ history === undefined
1891
1980
  ) {
1892
1981
  return {
1893
1982
  success: false,
1894
1983
  maxConcurrent: current.maxConcurrent,
1895
1984
  winterMode: current.winterMode,
1896
1985
  notifications: current.notifications,
1986
+ history: current.history,
1897
1987
  };
1898
1988
  }
1899
- const settings = await saveSettings({ maxConcurrent, winterMode, notifications });
1989
+ const settings = await saveSettings({
1990
+ maxConcurrent,
1991
+ winterMode,
1992
+ notifications,
1993
+ history,
1994
+ });
1900
1995
  return {
1901
1996
  success: true,
1902
1997
  maxConcurrent: settings.maxConcurrent,
1903
1998
  winterMode: settings.winterMode,
1904
1999
  notifications: settings.notifications,
2000
+ history: settings.history,
1905
2001
  };
1906
2002
  },
1907
2003
  test_notification: async () => {
package/src/rpc.ts CHANGED
@@ -379,12 +379,25 @@ const NotificationSettingsSchema = {
379
379
  required: ["enabled", "onlyOnError"],
380
380
  } as const;
381
381
 
382
+ /** Ретеншн истории (Спринт 18). */
383
+ const HistorySettingsSchema = {
384
+ type: "object" as const,
385
+ properties: {
386
+ retentionDays: { type: "number" },
387
+ maxRecords: { type: "number" },
388
+ lastCleanupAt: { type: ["string", "null"] },
389
+ lastCleanupDeleted: { type: "number" },
390
+ },
391
+ required: ["retentionDays", "maxRecords"],
392
+ } as const;
393
+
382
394
  const GetSettingsOutput = {
383
395
  type: "object" as const,
384
396
  properties: {
385
397
  maxConcurrent: { type: "number" },
386
398
  winterMode: { type: "boolean" },
387
399
  notifications: NotificationSettingsSchema,
400
+ history: HistorySettingsSchema,
388
401
  },
389
402
  required: ["maxConcurrent", "winterMode", "notifications"],
390
403
  } as const;
@@ -395,6 +408,7 @@ const SaveSettingsInput = {
395
408
  maxConcurrent: { type: "number" },
396
409
  winterMode: { type: "boolean" },
397
410
  notifications: NotificationSettingsSchema,
411
+ history: HistorySettingsSchema,
398
412
  },
399
413
  additionalProperties: false,
400
414
  } as const;
@@ -406,10 +420,60 @@ const SaveSettingsOutput = {
406
420
  maxConcurrent: { type: "number" },
407
421
  winterMode: { type: "boolean" },
408
422
  notifications: NotificationSettingsSchema,
423
+ history: HistorySettingsSchema,
409
424
  },
410
425
  required: ["success", "maxConcurrent", "winterMode", "notifications"],
411
426
  } as const;
412
427
 
428
+ const CleanupHistoryInput = {
429
+ type: "object" as const,
430
+ properties: {
431
+ /** Удалять записи старше N дней (0 — выключить ограничение по возрасту). */
432
+ retentionDays: { type: "number" },
433
+ /** Хранить не более N записей (0 — без ограничения). */
434
+ maxRecords: { type: "number" },
435
+ },
436
+ additionalProperties: false,
437
+ } as const;
438
+
439
+ const CleanupHistoryOutput = {
440
+ type: "object" as const,
441
+ properties: {
442
+ success: { type: "boolean" },
443
+ message: { type: "string" },
444
+ deleted: { type: "number" },
445
+ deletedByAge: { type: "number" },
446
+ deletedByCount: { type: "number" },
447
+ kept: { type: "number" },
448
+ retentionDays: { type: "number" },
449
+ maxRecords: { type: "number" },
450
+ vacuumed: { type: "boolean" },
451
+ },
452
+ required: ["success", "message", "deleted", "kept"],
453
+ } as const;
454
+
455
+ const GetAnalyticsInput = {
456
+ type: "object" as const,
457
+ properties: {
458
+ /** Окно анализа в днях (по умолчанию 14, максимум 365). */
459
+ days: { type: "number" },
460
+ /** Сколько строк в топах (по умолчанию 10). */
461
+ topLimit: { type: "number" },
462
+ },
463
+ additionalProperties: false,
464
+ } as const;
465
+
466
+ const GetAnalyticsOutput = {
467
+ type: "object" as const,
468
+ properties: {
469
+ success: { type: "boolean" },
470
+ // null при ошибке: report формируется только при success=true.
471
+ report: { type: ["object", "null"] as const },
472
+ error: { type: "string" },
473
+ },
474
+ required: ["success", "report"],
475
+ } as const;
476
+
413
477
  const TestNotificationInput = {
414
478
  type: "object" as const,
415
479
  properties: {},
@@ -906,6 +970,8 @@ export const SchedulerRpc = Rpc.define({
906
970
  input: GetTasksInput,
907
971
  output: CleanupMatrixOrphansOutput,
908
972
  },
973
+ cleanup_history: { input: CleanupHistoryInput, output: CleanupHistoryOutput },
974
+ get_analytics: { input: GetAnalyticsInput, output: GetAnalyticsOutput },
909
975
  expand_matrix_preview: {
910
976
  input: ExpandMatrixPreviewInput,
911
977
  output: ExpandMatrixPreviewOutput,
package/src/server.ts CHANGED
@@ -3,7 +3,10 @@ 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";
9
12
  import { simulatePipeline } from "./core/dry-run.js";
@@ -491,6 +494,8 @@ async function handleRequest(
491
494
  pathname === "/api/history" ||
492
495
  pathname === "/api/metrics" ||
493
496
  pathname === "/api/models-analysis" ||
497
+ pathname === "/api/analytics" ||
498
+ pathname === "/api/history/export" ||
494
499
  pathname === "/api/export-db" ||
495
500
  pathname === "/api/workspaces" ||
496
501
  pathname === "/api/health" ||
@@ -518,6 +523,9 @@ async function handleRequest(
518
523
  ok: true,
519
524
  app: DASHBOARD_MARKER,
520
525
  port: getDashboardPort(),
526
+ version: getPluginVersion(),
527
+ scheduler: getSchedulerTitle(),
528
+ queueDepth: countRunningRecords(),
521
529
  db: getDbStatus(),
522
530
  });
523
531
  return;
@@ -618,6 +626,59 @@ async function handleRequest(
618
626
  return;
619
627
  }
620
628
 
629
+ // Аналитика за период (Спринт 18): итоги, дневные бакеты, топ по стоимости.
630
+ if (req.method === "GET" && pathname === "/api/analytics") {
631
+ const days = Math.min(
632
+ 365,
633
+ Math.max(1, Math.floor(Number(url.searchParams.get("days")) || 14))
634
+ );
635
+ const topLimit = Math.max(
636
+ 1,
637
+ Math.floor(Number(url.searchParams.get("top")) || 10)
638
+ );
639
+ const records = getHistory(null, 20000);
640
+ const tasks = await deps.getTasks();
641
+ const report = buildAnalytics(records, {
642
+ days,
643
+ topLimit,
644
+ tasks: tasks.map((task) => ({
645
+ name: task.name,
646
+ matrixParentId: task.matrixParentId ?? null,
647
+ })),
648
+ });
649
+ sendJson(res, 200, report);
650
+ return;
651
+ }
652
+
653
+ // Экспорт истории: CSV (для Excel) или JSON (для скриптов).
654
+ if (req.method === "GET" && pathname === "/api/history/export") {
655
+ const format = (url.searchParams.get("format") || "csv").toLowerCase();
656
+ if (format !== "csv" && format !== "json") {
657
+ sendJson(res, 400, { error: "Неподдерживаемый формат экспорта. Допустимые: csv, json." });
658
+ return;
659
+ }
660
+ const records = getHistory(null, 100000);
661
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
662
+ if (format === "json") {
663
+ sendAttachment(
664
+ res,
665
+ 200,
666
+ "application/json; charset=utf-8",
667
+ JSON.stringify({ exportedAt: new Date().toISOString(), records }, null, 2),
668
+ `history-${stamp}.json`
669
+ );
670
+ } else {
671
+ sendAttachment(
672
+ res,
673
+ 200,
674
+ "text/csv; charset=utf-8",
675
+ historyToCsv(records),
676
+ `history-${stamp}.csv`
677
+ );
678
+ }
679
+ return;
680
+ }
681
+
621
682
  if (req.method === "GET" && (pathname === "/api/metrics" || pathname === "/api/summary")) {
622
683
  const metrics = await loadMetrics();
623
684
  // Токены и стоимость суммируем по history.json (как требует спринт):
@@ -822,6 +883,29 @@ function sendBuffer(
822
883
  res.end(body);
823
884
  }
824
885
 
886
+ /** Отправляет текстовый файл (CSV/JSON-экспорт истории). */
887
+ function sendAttachment(
888
+ res: http.ServerResponse,
889
+ status: number,
890
+ contentType: string,
891
+ body: string,
892
+ filename: string
893
+ ): void {
894
+ if (res.headersSent) {
895
+ res.end();
896
+ return;
897
+ }
898
+ res.writeHead(status, {
899
+ "Content-Type": contentType,
900
+ "Content-Length": String(Buffer.byteLength(body, "utf8")),
901
+ "Content-Disposition": `attachment; filename="${filename}"`,
902
+ "Cache-Control": "no-store",
903
+ "X-Content-Type-Options": "nosniff",
904
+ [DASHBOARD_HEADER]: DASHBOARD_MARKER,
905
+ });
906
+ res.end(body);
907
+ }
908
+
825
909
  /**
826
910
  * Список задач + метрики по каждой задаче, посчитанные из history.json
827
911
  * (колонка «Метрики» в таблице дашборда).
@@ -918,6 +1002,24 @@ function renderPage(): string {
918
1002
  .prio { font-size: 12px; color: #f5a623; white-space: nowrap; }
919
1003
  .hist { margin-top: 18px; background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 14px 18px; }
920
1004
  .hist h2 { margin: 0 0 10px; font-size: 14px; font-weight: 600; }
1005
+ .an-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
1006
+ .an-actions { display: flex; gap: 6px; }
1007
+ .an-actions .btn { padding: 3px 8px; font-size: 11px; }
1008
+ .an-kpis { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 12px; font-size: 12px; color: var(--muted); }
1009
+ .an-kpis b { color: var(--text); font-size: 14px; }
1010
+ .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; }
1011
+ .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; }
1012
+ .an-bar-fill { width: 100%; border-radius: 3px 3px 0 0; background: var(--accent); opacity: .85; }
1013
+ .an-label { font-size: 9px; color: var(--muted); margin-top: 4px; white-space: nowrap; }
1014
+ .an-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 14px; }
1015
+ .an-grid h3 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; }
1016
+ .an-table { width: 100%; border-collapse: collapse; font-size: 12px; }
1017
+ .an-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 3px 6px; border-bottom: 1px solid var(--border); }
1018
+ .an-table td { padding: 3px 6px; border-bottom: 1px solid var(--border); color: var(--text); }
1019
+ .an-table tr:last-child td { border-bottom: none; }
1020
+ .an-rate.okr { color: var(--ok); }
1021
+ .an-rate.midr { color: var(--run); }
1022
+ .an-rate.errr { color: var(--err); }
921
1023
  .hist-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; padding: 5px 0; border-bottom: 1px solid var(--border); font-size: 12px; }
922
1024
  .hist-row:last-child { border-bottom: none; }
923
1025
  .hist-time { color: var(--muted); white-space: nowrap; }
@@ -926,8 +1028,7 @@ function renderPage(): string {
926
1028
  .hist-hook { white-space: nowrap; }
927
1029
  .hist-hook.okh { color: #34c759; }
928
1030
  .hist-hook.errh { color: #ff3b30; }
929
- .whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; }
930
- .whatif-text b { color: var(--text); }
1031
+ .whatif-text { margin-top: 10px; font-size: 12px; color: var(--muted); line-height: 1.5; } .whatif-text b { color: var(--text); }
931
1032
  .wi-table { width: 100%; border-collapse: collapse; font-size: 12px; }
932
1033
  .wi-table th { text-align: left; color: var(--muted); font-weight: 600; padding: 4px 8px; border-bottom: 1px solid var(--border); }
933
1034
  .wi-table td { padding: 4px 8px; border-bottom: 1px solid var(--border); color: var(--text); }
@@ -1018,6 +1119,22 @@ function renderPage(): string {
1018
1119
  <div id="history"><div class="empty">Загрузка…</div></div>
1019
1120
  </div>
1020
1121
 
1122
+ <div class="hist">
1123
+ <div class="an-head">
1124
+ <h2>📊 Аналитика за период</h2>
1125
+ <div class="an-actions">
1126
+ <a class="btn" href="/api/history/export?format=csv" download>⬇️ CSV</a>
1127
+ <a class="btn" href="/api/history/export?format=json" download>⬇️ JSON</a>
1128
+ </div>
1129
+ </div>
1130
+ <div class="an-kpis" id="an-kpis"><span>Загрузка…</span></div>
1131
+ <div class="an-chart" id="an-chart"></div>
1132
+ <div class="an-grid">
1133
+ <div><h3>Топ задач по стоимости</h3><div id="an-top"></div></div>
1134
+ <div><h3>Матрицы</h3><div id="an-matrices"></div></div>
1135
+ </div>
1136
+ </div>
1137
+
1021
1138
  <div class="hist">
1022
1139
  <h2>📊 What-If: Анализ моделей</h2>
1023
1140
  <div id="whatif-table"><div class="empty">Загрузка…</div></div>
@@ -1212,8 +1329,105 @@ function renderPage(): string {
1212
1329
  box.innerHTML = html;
1213
1330
  }
1214
1331
 
1215
- function renderModelsAnalysis(data) {
1216
- var box = document.getElementById('whatif-table');
1332
+ function rateClass(rate) {
1333
+ if (rate >= 90) return 'okr';
1334
+ if (rate >= 60) return 'midr';
1335
+ return 'errr';
1336
+ }
1337
+
1338
+ function money(value) {
1339
+ var n = Number(value) || 0;
1340
+ return '$' + n.toFixed(n >= 1 ? 2 : 4);
1341
+ }
1342
+
1343
+ function durationText(ms) {
1344
+ var n = Number(ms) || 0;
1345
+ if (n <= 0) return '—';
1346
+ if (n < 1000) return n + ' мс';
1347
+ if (n < 60000) return (n / 1000).toFixed(1) + ' с';
1348
+ return Math.round(n / 60000) + ' мин';
1349
+ }
1350
+
1351
+ function renderAnalytics(an) {
1352
+ var kpis = document.getElementById('an-kpis');
1353
+ var chart = document.getElementById('an-chart');
1354
+ var top = document.getElementById('an-top');
1355
+ var matrices = document.getElementById('an-matrices');
1356
+ if (!kpis || !chart || !top || !matrices) return;
1357
+
1358
+ if (!an || !an.totals) {
1359
+ kpis.innerHTML = '<span>Аналитика недоступна.</span>';
1360
+ chart.innerHTML = '';
1361
+ top.innerHTML = '<div class="empty" style="padding:10px">—</div>';
1362
+ matrices.innerHTML = '<div class="empty" style="padding:10px">—</div>';
1363
+ return;
1364
+ }
1365
+
1366
+ var t = an.totals;
1367
+ kpis.innerHTML =
1368
+ '<span>Запусков: <b>' + t.total + '</b></span>' +
1369
+ '<span>Успех: <b class="an-rate ' + rateClass(t.successRate) + '">' + t.successRate + '%</b></span>' +
1370
+ '<span>Средняя длительность: <b>' + durationText(t.avgDurationMs) + '</b></span>' +
1371
+ '<span>Токены: <b>' + Number(t.tokens || 0).toLocaleString('ru-RU') + '</b></span>' +
1372
+ '<span>Стоимость: <b>' + money(t.costUsd) + '</b></span>' +
1373
+ '<span>Окно: <b>' + an.windowDays + ' дн.</b></span>' +
1374
+ (t.partial ? '<span>Частично: <b>' + t.partial + '</b></span>' : '');
1375
+
1376
+ var daily = an.daily || [];
1377
+ var max = 1;
1378
+ for (var i = 0; i < daily.length; i++) {
1379
+ if (daily[i].total > max) max = daily[i].total;
1380
+ }
1381
+ var bars = '';
1382
+ for (var j = 0; j < daily.length; j++) {
1383
+ var d = daily[j];
1384
+ var h = d.total > 0 ? Math.max(3, Math.round((d.total / max) * 92)) : 2;
1385
+ var color = d.total === 0 ? 'var(--border)' : (d.error > 0 ? 'var(--err)' : 'var(--ok)');
1386
+ var tip = d.date + ': всего ' + d.total + ', успех ' + d.success + ', ошибок ' + d.error + ', ' + money(d.costUsd);
1387
+ bars += '<div class="an-bar" title="' + esc(tip) + '">' +
1388
+ '<div class="an-bar-fill" style="height:' + h + '%' + ';background:' + esc(color) + '"></div>' +
1389
+ '<div class="an-label">' + esc(String(d.date).slice(5)) + '</div>' +
1390
+ '</div>';
1391
+ }
1392
+ chart.innerHTML = bars || '<div class="empty" style="padding:10px">Нет данных за период.</div>';
1393
+
1394
+ var topRows = an.topByCost || [];
1395
+ if (topRows.length === 0) {
1396
+ top.innerHTML = '<div class="empty" style="padding:10px">Нет запусков за период.</div>';
1397
+ } else {
1398
+ var html = '<table class="an-table"><thead><tr><th>Задача</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
1399
+ for (var k = 0; k < topRows.length; k++) {
1400
+ var row = topRows[k];
1401
+ html += '<tr>' +
1402
+ '<td>' + (row.isMatrixClone ? '↳ ' : '') + esc(row.taskName) + '</td>' +
1403
+ '<td>' + row.total + '</td>' +
1404
+ '<td class="an-rate ' + rateClass(row.successRate) + '">' + row.successRate + '%</td>' +
1405
+ '<td>' + money(row.costUsd) + '</td>' +
1406
+ '</tr>';
1407
+ }
1408
+ top.innerHTML = html + '</tbody></table>';
1409
+ }
1410
+
1411
+ var matrixRows = an.matrices || [];
1412
+ if (matrixRows.length === 0) {
1413
+ matrices.innerHTML = '<div class="empty" style="padding:10px">Матриц за период не запускалось.</div>';
1414
+ } else {
1415
+ var mhtml = '<table class="an-table"><thead><tr><th>Матрица</th><th>Клонов</th><th>Запусков</th><th>Успех</th><th>Стоимость</th></tr></thead><tbody>';
1416
+ for (var q = 0; q < matrixRows.length; q++) {
1417
+ var m = matrixRows[q];
1418
+ mhtml += '<tr>' +
1419
+ '<td>📦 ' + esc(m.parentId) + '</td>' +
1420
+ '<td>' + m.clones + '</td>' +
1421
+ '<td>' + m.total + '</td>' +
1422
+ '<td class="an-rate ' + rateClass(m.successRate) + '">' + m.successRate + '%</td>' +
1423
+ '<td>' + money(m.costUsd) + '</td>' +
1424
+ '</tr>';
1425
+ }
1426
+ matrices.innerHTML = mhtml + '</tbody></table>';
1427
+ }
1428
+ }
1429
+
1430
+ function renderModelsAnalysis(data) { var box = document.getElementById('whatif-table');
1217
1431
  var text = document.getElementById('whatif-text');
1218
1432
  if (!box || !text) return;
1219
1433
  var models = (data && data.models) || [];
@@ -1455,7 +1669,8 @@ function renderPage(): string {
1455
1669
  loadMetricsJson(),
1456
1670
  safeJson('/api/history', { records: [] }),
1457
1671
  safeJson('/api/models-analysis', { models: [], totals: {}, whatIf: [] }),
1458
- safeJson('/api/workspaces', { workspaces: [] })
1672
+ safeJson('/api/workspaces', { workspaces: [] }),
1673
+ safeJson('/api/analytics?days=14', null)
1459
1674
  ]);
1460
1675
  var tasks = (results[0] && results[0].tasks) || [];
1461
1676
  var m = results[1] || {};
@@ -1474,6 +1689,7 @@ function renderPage(): string {
1474
1689
  renderGraph(tasks);
1475
1690
  renderHistory(history);
1476
1691
  renderModelsAnalysis(modelsAnalysis);
1692
+ renderAnalytics(results[5]);
1477
1693
  showServerWarn(results[0] ? null : 'Не удалось загрузить список задач — остальные блоки обновлены. Подробности в консоли (F12).');
1478
1694
  updated.textContent = 'Обновлено: ' + new Date().toLocaleTimeString();
1479
1695
  } catch (err) {
package/src/settings.ts CHANGED
@@ -25,6 +25,24 @@ export interface NotificationSettings {
25
25
  webhook?: WebhookNotificationSettings;
26
26
  }
27
27
 
28
+ /**
29
+ * Ретеншн истории (Спринт 18).
30
+ *
31
+ * Дашборд и метрики живут на агрегатах, поэтому удаление старых записей
32
+ * не искажает «Всего запусков» и стоимость: чистится только сырая история.
33
+ * 0 — соответствующее ограничение выключено.
34
+ */
35
+ export interface HistorySettings {
36
+ /** Удалять завершённые записи старше N дней (0 — не удалять по возрасту). */
37
+ retentionDays: number;
38
+ /** Хранить не более N последних записей (0 — без ограничения). */
39
+ maxRecords: number;
40
+ /** Когда последний раз запускалась автоочистка (ISO). */
41
+ lastCleanupAt: string | null;
42
+ /** Сколько записей удалила последняя очистка (для дашборда). */
43
+ lastCleanupDeleted: number;
44
+ }
45
+
28
46
  /**
29
47
  * Глобальные настройки плагина, которые меняются из GUI.
30
48
  * Хранятся в settings.json рядом с tasks.json / history.json.
@@ -36,11 +54,57 @@ export interface SchedulerSettings {
36
54
  winterMode: boolean;
37
55
  /** Уведомления о завершении задач. */
38
56
  notifications: NotificationSettings;
57
+ /** Ретеншн истории запусков. */
58
+ history: HistorySettings;
39
59
  }
40
60
 
41
61
  export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
42
62
  export const DEFAULT_MAX_CONCURRENT = 1;
43
63
  export const DEFAULT_WINTER_MODE = false;
64
+ export const DEFAULT_RETENTION_DAYS = 30;
65
+ export const DEFAULT_MAX_RECORDS = 5000;
66
+
67
+ /** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
68
+ export function defaultHistorySettings(): HistorySettings {
69
+ return {
70
+ retentionDays: DEFAULT_RETENTION_DAYS,
71
+ maxRecords: DEFAULT_MAX_RECORDS,
72
+ lastCleanupAt: null,
73
+ lastCleanupDeleted: 0,
74
+ };
75
+ }
76
+
77
+ /** Приводит счётчик ретеншна к безопасному целому (>= 0). */
78
+ function normalizeRetentionLimit(value: unknown, fallback: number): number {
79
+ const n = Number(value);
80
+ if (!Number.isFinite(n)) return fallback;
81
+ const int = Math.floor(n);
82
+ return int >= 0 ? int : fallback;
83
+ }
84
+
85
+ /** Приводит настройки ретеншна к безопасному виду. */
86
+ function normalizeHistorySettings(
87
+ value: unknown,
88
+ fallback: HistorySettings
89
+ ): HistorySettings {
90
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
91
+ return { ...fallback };
92
+ }
93
+ const raw = value as Partial<HistorySettings>;
94
+ const lastCleanupAt =
95
+ typeof raw.lastCleanupAt === "string" && raw.lastCleanupAt.trim()
96
+ ? raw.lastCleanupAt.trim()
97
+ : null;
98
+ return {
99
+ retentionDays: normalizeRetentionLimit(raw.retentionDays, fallback.retentionDays),
100
+ maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
101
+ lastCleanupAt,
102
+ lastCleanupDeleted: normalizeRetentionLimit(
103
+ raw.lastCleanupDeleted,
104
+ fallback.lastCleanupDeleted
105
+ ),
106
+ };
107
+ }
44
108
 
45
109
  /** Значения уведомлений по умолчанию: всё выключено, только ошибки. */
46
110
  export function defaultNotifications(): NotificationSettings {
@@ -106,6 +170,7 @@ function normalizeNotifications(
106
170
  /** Читает настройки. Битый/отсутствующий файл — значения по умолчанию. */
107
171
  export async function loadSettings(): Promise<SchedulerSettings> {
108
172
  const fallbackNotifications = defaultNotifications();
173
+ const fallbackHistory = defaultHistorySettings();
109
174
  try {
110
175
  const raw = await fs.readFile(SETTINGS_FILE, "utf8");
111
176
  const parsed = JSON.parse(raw) as Partial<SchedulerSettings> | null;
@@ -122,12 +187,14 @@ export async function loadSettings(): Promise<SchedulerSettings> {
122
187
  parsed?.notifications,
123
188
  fallbackNotifications
124
189
  ),
190
+ history: normalizeHistorySettings(parsed?.history, fallbackHistory),
125
191
  };
126
192
  } catch {
127
193
  return {
128
194
  maxConcurrent: DEFAULT_MAX_CONCURRENT,
129
195
  winterMode: DEFAULT_WINTER_MODE,
130
196
  notifications: fallbackNotifications,
197
+ history: fallbackHistory,
131
198
  };
132
199
  }
133
200
  }
@@ -150,6 +217,10 @@ export async function saveSettings(
150
217
  patch.notifications !== undefined
151
218
  ? normalizeNotifications(patch.notifications, current.notifications)
152
219
  : current.notifications,
220
+ history:
221
+ patch.history !== undefined
222
+ ? normalizeHistorySettings(patch.history, current.history)
223
+ : current.history,
153
224
  };
154
225
  await fs.mkdir(PLUGIN_DIR, { recursive: true });
155
226
  await fs.writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2), "utf8");