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.
- package/CHANGELOG.md +58 -7
- package/README.md +14 -4
- package/README.ru.md +14 -4
- package/ROADMAP.md +30 -20
- package/dist/core/analytics.d.ts +129 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +286 -0
- package/dist/core/dry-run.d.ts +13 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +30 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +10 -0
- package/dist/core/ps-wrapper.d.ts +32 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +101 -3
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +182 -0
- package/dist/core/schedule-v2.d.ts +88 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +496 -0
- package/dist/core/scheduler/types.d.ts +15 -0
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +13 -1
- package/dist/core/wrappers/bash.d.ts +15 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +44 -1
- package/dist/db/history-repo.d.ts +41 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +78 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +11 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1094 -56
- package/dist/notifications.d.ts +112 -6
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +396 -34
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +209 -0
- package/dist/rpc.d.ts +645 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +251 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +200 -7
- package/dist/settings.d.ts +80 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +159 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -11
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +43 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +174 -8
- package/docs/ARCHITECTURE.md +45 -13
- package/docs/FEATURES.md +103 -12
- package/gui-experimental.cjs +4 -2
- package/package.json +8 -2
- package/src/core/analytics.ts +414 -0
- package/src/core/dry-run.ts +42 -0
- package/src/core/matrix.ts +10 -0
- package/src/core/ps-wrapper.ts +117 -3
- package/src/core/retention.ts +141 -0
- package/src/core/schedule-gate.ts +213 -0
- package/src/core/schedule-v2.ts +533 -0
- package/src/core/scheduler/types.ts +15 -0
- package/src/core/scheduler/windows.ts +13 -1
- package/src/core/wrappers/bash.ts +60 -0
- package/src/db/history-repo.ts +116 -0
- package/src/db/schema.ts +14 -0
- package/src/gui.tsx +3613 -2725
- package/src/index.ts +1325 -55
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +267 -2
- package/src/server.ts +226 -7
- package/src/settings.ts +285 -9
- package/src/task-transfer.ts +44 -0
- package/src/types.ts +3 -13
- package/src/version.ts +27 -0
- package/src/workspaces.ts +214 -8
- package/dist/gui-experimental.cjs +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-windows-scheduler",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Local-first scheduling and orchestration for OpenCode v2 agent jobs: cron, DAG pipelines, matrix fan-out, quality gates and observability. Free and open source (MIT).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "opencode-windows-scheduler contributors",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"demo": "node scripts/demo-dashboard.mjs",
|
|
63
63
|
"prepare": "npm run build",
|
|
64
64
|
"prepublishOnly": "npm run build && npm run build:gui",
|
|
65
|
-
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-docs.mjs",
|
|
65
|
+
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-docs.mjs",
|
|
66
66
|
"test:sqlite": "node test-sqlite.mjs",
|
|
67
67
|
"test:crash": "node test-crash-recovery.mjs",
|
|
68
68
|
"test:workspaces": "node test-workspaces.mjs",
|
|
@@ -71,6 +71,12 @@
|
|
|
71
71
|
"test:matrix": "node test-matrix.mjs",
|
|
72
72
|
"test:matrix-lifecycle": "node test-matrix-lifecycle.mjs",
|
|
73
73
|
"test:matrix-sync": "node test-matrix-sync.mjs",
|
|
74
|
+
"test:retention": "node test-retention.mjs",
|
|
75
|
+
"test:metrics": "node test-metrics.mjs",
|
|
76
|
+
"test:schedule-v2": "node test-schedule-v2.mjs",
|
|
77
|
+
"test:notifications-v2": "node test-notifications-v2.mjs",
|
|
78
|
+
"test:profiles": "node test-profiles.mjs",
|
|
79
|
+
"test:env": "node test-env.mjs",
|
|
74
80
|
"test:agent": "node test-agent-tools.mjs",
|
|
75
81
|
"test:skill": "node test-skill.mjs",
|
|
76
82
|
"test:docs": "node test-docs.mjs"
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Аналитика по истории запусков (Спринт 18).
|
|
3
|
+
*
|
|
4
|
+
* Чистые функции без БД и HTTP: дашборд и RPC отдают JSON, экспорт — CSV.
|
|
5
|
+
* Так агрегаты легко тестировать без запуска сервера.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Оценка стоимости, если запись истории не содержит costUsd. */
|
|
9
|
+
export const ESTIMATED_COST_PER_1K_TOKENS_USD = 0.003;
|
|
10
|
+
|
|
11
|
+
/** Минимальный вид записи истории, нужный аналитике. */
|
|
12
|
+
export interface AnalyticsRecord {
|
|
13
|
+
taskName: string;
|
|
14
|
+
status: string;
|
|
15
|
+
startedAt: string;
|
|
16
|
+
finishedAt?: string | null;
|
|
17
|
+
durationMs?: number | null;
|
|
18
|
+
error?: string | null;
|
|
19
|
+
tokens?: number;
|
|
20
|
+
costUsd?: number;
|
|
21
|
+
model?: string;
|
|
22
|
+
workspaceId?: string | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Описание задачи для группировки по матрицам. */
|
|
26
|
+
export interface AnalyticsTaskRef {
|
|
27
|
+
name: string;
|
|
28
|
+
matrixParentId?: string | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DailyBucket {
|
|
32
|
+
/** YYYY-MM-DD (UTC). */
|
|
33
|
+
date: string;
|
|
34
|
+
total: number;
|
|
35
|
+
success: number;
|
|
36
|
+
error: number;
|
|
37
|
+
partial: number;
|
|
38
|
+
tokens: number;
|
|
39
|
+
costUsd: number;
|
|
40
|
+
avgDurationMs: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface TaskAnalyticsRow {
|
|
44
|
+
taskName: string;
|
|
45
|
+
total: number;
|
|
46
|
+
success: number;
|
|
47
|
+
error: number;
|
|
48
|
+
/** Процент успешных запусков (0..100, один знак после запятой). */
|
|
49
|
+
successRate: number;
|
|
50
|
+
avgDurationMs: number;
|
|
51
|
+
tokens: number;
|
|
52
|
+
costUsd: number;
|
|
53
|
+
/** Задача — клон матрицы (matrixParentId задан). */
|
|
54
|
+
isMatrixClone: boolean;
|
|
55
|
+
matrixParentId: string | null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface MatrixAnalyticsRow {
|
|
59
|
+
parentId: string;
|
|
60
|
+
clones: number;
|
|
61
|
+
total: number;
|
|
62
|
+
success: number;
|
|
63
|
+
error: number;
|
|
64
|
+
successRate: number;
|
|
65
|
+
tokens: number;
|
|
66
|
+
costUsd: number;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface ModelAnalyticsRow {
|
|
70
|
+
model: string;
|
|
71
|
+
total: number;
|
|
72
|
+
costUsd: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Агрегат по тексту ошибки — топ ошибок для дайджеста (Спринт 20). */
|
|
76
|
+
export interface ErrorAnalyticsRow {
|
|
77
|
+
/** Текст ошибки (обрезан до 160 символов). */
|
|
78
|
+
message: string;
|
|
79
|
+
count: number;
|
|
80
|
+
/** Последнее появление (ISO). */
|
|
81
|
+
lastAt: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface AnalyticsReport {
|
|
85
|
+
generatedAt: string;
|
|
86
|
+
/** Окно анализа в днях. */
|
|
87
|
+
windowDays: number;
|
|
88
|
+
totals: {
|
|
89
|
+
total: number;
|
|
90
|
+
success: number;
|
|
91
|
+
error: number;
|
|
92
|
+
partial: number;
|
|
93
|
+
successRate: number;
|
|
94
|
+
avgDurationMs: number;
|
|
95
|
+
tokens: number;
|
|
96
|
+
costUsd: number;
|
|
97
|
+
};
|
|
98
|
+
daily: DailyBucket[];
|
|
99
|
+
tasks: TaskAnalyticsRow[];
|
|
100
|
+
topByCost: TaskAnalyticsRow[];
|
|
101
|
+
matrices: MatrixAnalyticsRow[];
|
|
102
|
+
byModel: ModelAnalyticsRow[];
|
|
103
|
+
/** Топ ошибок по частоте (Спринт 20). */
|
|
104
|
+
errors: ErrorAnalyticsRow[];
|
|
105
|
+
sources: {
|
|
106
|
+
historyRecords: number;
|
|
107
|
+
/** Сколько записей попало в окно. */
|
|
108
|
+
recordsInWindow: number;
|
|
109
|
+
/** Ограничение по количеству строк в топах. */
|
|
110
|
+
topLimit: number;
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface BuildAnalyticsOptions {
|
|
115
|
+
/** Окно анализа в днях (по умолчанию 14). */
|
|
116
|
+
days?: number;
|
|
117
|
+
/** Опорный момент (для тестов). */
|
|
118
|
+
now?: Date;
|
|
119
|
+
/** Сколько строк оставлять в топах (по умолчанию 10). */
|
|
120
|
+
topLimit?: number;
|
|
121
|
+
/** Известные задачи — нужны для группировки матриц. */
|
|
122
|
+
tasks?: AnalyticsTaskRef[];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function toNumber(value: unknown): number {
|
|
126
|
+
const n = Number(value);
|
|
127
|
+
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Стоимость записи: явная цена, иначе оценка по токенам. */
|
|
131
|
+
export function recordCost(record: AnalyticsRecord): number {
|
|
132
|
+
const cost = toNumber(record.costUsd);
|
|
133
|
+
if (cost > 0) return cost;
|
|
134
|
+
const tokens = toNumber(record.tokens);
|
|
135
|
+
return tokens > 0 ? (tokens / 1000) * ESTIMATED_COST_PER_1K_TOKENS_USD : 0;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Дата записи в UTC-формате YYYY-MM-DD. */
|
|
139
|
+
export function recordDate(record: AnalyticsRecord): string {
|
|
140
|
+
const time = new Date(record.startedAt).getTime();
|
|
141
|
+
if (!Number.isFinite(time)) return "";
|
|
142
|
+
return new Date(time).toISOString().slice(0, 10);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function utcDayKey(date: Date): string {
|
|
146
|
+
return date.toISOString().slice(0, 10);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function percent(part: number, total: number): number {
|
|
150
|
+
if (total <= 0) return 0;
|
|
151
|
+
return Math.round((part / total) * 1000) / 10;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Строит отчёт по истории: итоги, дневные бакеты, разбивка по задачам,
|
|
156
|
+
* матрицам и моделям.
|
|
157
|
+
*/
|
|
158
|
+
export function buildAnalytics(
|
|
159
|
+
records: AnalyticsRecord[],
|
|
160
|
+
options: BuildAnalyticsOptions = {}
|
|
161
|
+
): AnalyticsReport {
|
|
162
|
+
const windowDays = Math.max(1, Math.floor(options.days ?? 14));
|
|
163
|
+
const topLimit = Math.max(1, Math.floor(options.topLimit ?? 10));
|
|
164
|
+
const now = options.now ?? new Date();
|
|
165
|
+
|
|
166
|
+
const dayKeys: string[] = [];
|
|
167
|
+
const dayBuckets = new Map<string, DailyBucket>();
|
|
168
|
+
for (let i = windowDays - 1; i >= 0; i -= 1) {
|
|
169
|
+
const key = utcDayKey(new Date(now.getTime() - i * 24 * 60 * 60 * 1000));
|
|
170
|
+
dayKeys.push(key);
|
|
171
|
+
dayBuckets.set(key, {
|
|
172
|
+
date: key,
|
|
173
|
+
total: 0,
|
|
174
|
+
success: 0,
|
|
175
|
+
error: 0,
|
|
176
|
+
partial: 0,
|
|
177
|
+
tokens: 0,
|
|
178
|
+
costUsd: 0,
|
|
179
|
+
avgDurationMs: 0,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const byTask = new Map<string, TaskAnalyticsRow>();
|
|
184
|
+
const byModel = new Map<string, ModelAnalyticsRow>();
|
|
185
|
+
const byError = new Map<string, ErrorAnalyticsRow>();
|
|
186
|
+
const cloneParent = new Map<string, string>();
|
|
187
|
+
for (const task of options.tasks ?? []) {
|
|
188
|
+
const parentId = task.matrixParentId?.trim();
|
|
189
|
+
if (parentId) cloneParent.set(task.name.toLowerCase(), parentId);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let totalsTotal = 0;
|
|
193
|
+
let totalsSuccess = 0;
|
|
194
|
+
let totalsError = 0;
|
|
195
|
+
let totalsPartial = 0;
|
|
196
|
+
let totalsTokens = 0;
|
|
197
|
+
let totalsCost = 0;
|
|
198
|
+
let durationsSum = 0;
|
|
199
|
+
let durationsCount = 0;
|
|
200
|
+
let recordsInWindow = 0;
|
|
201
|
+
|
|
202
|
+
for (const record of records) {
|
|
203
|
+
const date = recordDate(record);
|
|
204
|
+
if (!date) continue;
|
|
205
|
+
const bucket = dayBuckets.get(date);
|
|
206
|
+
// Итоги считаются только по окну — это «аналитика за период».
|
|
207
|
+
if (!bucket) continue;
|
|
208
|
+
recordsInWindow += 1;
|
|
209
|
+
|
|
210
|
+
const tokens = toNumber(record.tokens);
|
|
211
|
+
const cost = recordCost(record);
|
|
212
|
+
const status = String(record.status ?? "");
|
|
213
|
+
// Незавершённые запуски не участвуют в аналитике: их ещё нельзя оценить.
|
|
214
|
+
if (status === "running") continue;
|
|
215
|
+
const duration = toNumber(record.durationMs);
|
|
216
|
+
|
|
217
|
+
bucket.total += 1;
|
|
218
|
+
bucket.tokens += tokens;
|
|
219
|
+
bucket.costUsd += cost;
|
|
220
|
+
if (status === "success") bucket.success += 1;
|
|
221
|
+
else if (status === "partial") bucket.partial += 1;
|
|
222
|
+
else bucket.error += 1;
|
|
223
|
+
if (duration > 0) {
|
|
224
|
+
bucket.avgDurationMs =
|
|
225
|
+
(bucket.avgDurationMs * (bucket.total - 1) + duration) / bucket.total;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
totalsTotal += 1;
|
|
229
|
+
totalsTokens += tokens;
|
|
230
|
+
totalsCost += cost;
|
|
231
|
+
if (status === "success") totalsSuccess += 1;
|
|
232
|
+
else if (status === "partial") totalsPartial += 1;
|
|
233
|
+
else totalsError += 1;
|
|
234
|
+
if (duration > 0) {
|
|
235
|
+
durationsSum += duration;
|
|
236
|
+
durationsCount += 1;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const taskKey = record.taskName.toLowerCase();
|
|
240
|
+
const existing = byTask.get(taskKey) ?? {
|
|
241
|
+
taskName: record.taskName,
|
|
242
|
+
total: 0,
|
|
243
|
+
success: 0,
|
|
244
|
+
error: 0,
|
|
245
|
+
successRate: 0,
|
|
246
|
+
avgDurationMs: 0,
|
|
247
|
+
tokens: 0,
|
|
248
|
+
costUsd: 0,
|
|
249
|
+
isMatrixClone: cloneParent.has(taskKey),
|
|
250
|
+
matrixParentId: cloneParent.get(taskKey) ?? null,
|
|
251
|
+
};
|
|
252
|
+
existing.total += 1;
|
|
253
|
+
if (status === "success") existing.success += 1;
|
|
254
|
+
else existing.error += 1;
|
|
255
|
+
existing.tokens += tokens;
|
|
256
|
+
existing.costUsd += cost;
|
|
257
|
+
if (duration > 0) {
|
|
258
|
+
existing.avgDurationMs =
|
|
259
|
+
(existing.avgDurationMs * (existing.total - 1) + duration) / existing.total;
|
|
260
|
+
}
|
|
261
|
+
byTask.set(taskKey, existing);
|
|
262
|
+
|
|
263
|
+
const model = record.model?.trim() || "(default)";
|
|
264
|
+
const modelRow = byModel.get(model) ?? { model, total: 0, costUsd: 0 };
|
|
265
|
+
modelRow.total += 1;
|
|
266
|
+
modelRow.costUsd += cost;
|
|
267
|
+
byModel.set(model, modelRow);
|
|
268
|
+
|
|
269
|
+
// Топ ошибок: группируем по тексту, чтобы дайджест показывал частые причины.
|
|
270
|
+
if (status !== "success" && status !== "partial") {
|
|
271
|
+
const message =
|
|
272
|
+
typeof record.error === "string" && record.error.trim()
|
|
273
|
+
? record.error.trim().slice(0, 160)
|
|
274
|
+
: "(без текста)";
|
|
275
|
+
const errorRow = byError.get(message) ?? {
|
|
276
|
+
message,
|
|
277
|
+
count: 0,
|
|
278
|
+
lastAt: record.startedAt,
|
|
279
|
+
};
|
|
280
|
+
errorRow.count += 1;
|
|
281
|
+
if (
|
|
282
|
+
new Date(record.startedAt).getTime() >
|
|
283
|
+
new Date(errorRow.lastAt).getTime()
|
|
284
|
+
) {
|
|
285
|
+
errorRow.lastAt = record.startedAt;
|
|
286
|
+
}
|
|
287
|
+
byError.set(message, errorRow);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const tasks = [...byTask.values()]
|
|
292
|
+
.map((row) => ({
|
|
293
|
+
...row,
|
|
294
|
+
successRate: percent(row.success, row.total),
|
|
295
|
+
avgDurationMs: Math.round(row.avgDurationMs),
|
|
296
|
+
costUsd: Math.round(row.costUsd * 1e6) / 1e6,
|
|
297
|
+
}))
|
|
298
|
+
.sort((a, b) => b.total - a.total || a.taskName.localeCompare(b.taskName));
|
|
299
|
+
|
|
300
|
+
const matrices = new Map<string, MatrixAnalyticsRow>();
|
|
301
|
+
for (const row of tasks) {
|
|
302
|
+
if (!row.matrixParentId) continue;
|
|
303
|
+
const key = row.matrixParentId.toLowerCase();
|
|
304
|
+
const matrix = matrices.get(key) ?? {
|
|
305
|
+
parentId: row.matrixParentId,
|
|
306
|
+
clones: 0,
|
|
307
|
+
total: 0,
|
|
308
|
+
success: 0,
|
|
309
|
+
error: 0,
|
|
310
|
+
successRate: 0,
|
|
311
|
+
tokens: 0,
|
|
312
|
+
costUsd: 0,
|
|
313
|
+
};
|
|
314
|
+
matrix.clones += 1;
|
|
315
|
+
matrix.total += row.total;
|
|
316
|
+
matrix.success += row.success;
|
|
317
|
+
matrix.error += row.error;
|
|
318
|
+
matrix.tokens += row.tokens;
|
|
319
|
+
matrix.costUsd += row.costUsd;
|
|
320
|
+
matrices.set(key, matrix);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const daily = dayKeys.map((key) => {
|
|
324
|
+
const bucket = dayBuckets.get(key)!;
|
|
325
|
+
return {
|
|
326
|
+
...bucket,
|
|
327
|
+
avgDurationMs: Math.round(bucket.avgDurationMs),
|
|
328
|
+
costUsd: Math.round(bucket.costUsd * 1e6) / 1e6,
|
|
329
|
+
};
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
generatedAt: new Date().toISOString(),
|
|
334
|
+
windowDays,
|
|
335
|
+
totals: {
|
|
336
|
+
total: totalsTotal,
|
|
337
|
+
success: totalsSuccess,
|
|
338
|
+
error: totalsError,
|
|
339
|
+
partial: totalsPartial,
|
|
340
|
+
successRate: percent(totalsSuccess, totalsTotal),
|
|
341
|
+
avgDurationMs: durationsCount > 0 ? Math.round(durationsSum / durationsCount) : 0,
|
|
342
|
+
tokens: totalsTokens,
|
|
343
|
+
costUsd: Math.round(totalsCost * 1e6) / 1e6,
|
|
344
|
+
},
|
|
345
|
+
daily,
|
|
346
|
+
tasks,
|
|
347
|
+
topByCost: [...tasks].sort((a, b) => b.costUsd - a.costUsd).slice(0, topLimit),
|
|
348
|
+
matrices: [...matrices.values()]
|
|
349
|
+
.map((row) => ({
|
|
350
|
+
...row,
|
|
351
|
+
successRate: percent(row.success, row.total),
|
|
352
|
+
costUsd: Math.round(row.costUsd * 1e6) / 1e6,
|
|
353
|
+
}))
|
|
354
|
+
.sort((a, b) => b.costUsd - a.costUsd),
|
|
355
|
+
byModel: [...byModel.values()]
|
|
356
|
+
.map((row) => ({ ...row, costUsd: Math.round(row.costUsd * 1e6) / 1e6 }))
|
|
357
|
+
.sort((a, b) => b.costUsd - a.costUsd),
|
|
358
|
+
errors: [...byError.values()]
|
|
359
|
+
.sort((a, b) => b.count - a.count || a.message.localeCompare(b.message))
|
|
360
|
+
.slice(0, topLimit),
|
|
361
|
+
sources: {
|
|
362
|
+
historyRecords: records.length,
|
|
363
|
+
recordsInWindow,
|
|
364
|
+
topLimit,
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Экранирование значения для CSV (RFC 4180). */
|
|
370
|
+
export function csvCell(value: unknown): string {
|
|
371
|
+
if (value === null || value === undefined) return "";
|
|
372
|
+
const text = String(value);
|
|
373
|
+
if (/[",\r\n;]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
|
|
374
|
+
return text;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Заголовок CSV-экспорта истории. */
|
|
378
|
+
export const HISTORY_CSV_HEADER = [
|
|
379
|
+
"startedAt",
|
|
380
|
+
"finishedAt",
|
|
381
|
+
"taskName",
|
|
382
|
+
"status",
|
|
383
|
+
"durationMs",
|
|
384
|
+
"tokens",
|
|
385
|
+
"costUsd",
|
|
386
|
+
"model",
|
|
387
|
+
"workspaceId",
|
|
388
|
+
"error",
|
|
389
|
+
] as const;
|
|
390
|
+
|
|
391
|
+
/** История в CSV: точки с запятой как разделитель — дружелюбно к Excel (RU). */
|
|
392
|
+
export function historyToCsv(records: AnalyticsRecord[]): string {
|
|
393
|
+
const rows = [HISTORY_CSV_HEADER.join(";")];
|
|
394
|
+
for (const record of records) {
|
|
395
|
+
rows.push(
|
|
396
|
+
[
|
|
397
|
+
record.startedAt,
|
|
398
|
+
record.finishedAt ?? "",
|
|
399
|
+
record.taskName,
|
|
400
|
+
record.status,
|
|
401
|
+
record.durationMs ?? "",
|
|
402
|
+
record.tokens ?? "",
|
|
403
|
+
record.costUsd ?? "",
|
|
404
|
+
record.model ?? "",
|
|
405
|
+
record.workspaceId ?? "",
|
|
406
|
+
record.error ?? "",
|
|
407
|
+
]
|
|
408
|
+
.map(csvCell)
|
|
409
|
+
.join(";")
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
// BOM, чтобы Excel корректно открыл UTF-8 с кириллицей.
|
|
413
|
+
return `\uFEFF${rows.join("\r\n")}`;
|
|
414
|
+
}
|
package/src/core/dry-run.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { loadTaskDefinitions } from "../task-transfer.js";
|
|
|
10
10
|
import { getHistory } from "../db/history-repo.js";
|
|
11
11
|
import { getWorkspace } from "../workspaces.js";
|
|
12
12
|
import { expandMatrixTask } from "./matrix.js";
|
|
13
|
+
import { nextRun } from "./schedule-v2.js";
|
|
13
14
|
import type { TaskDefinition } from "../task-transfer.js";
|
|
14
15
|
|
|
15
16
|
export interface DryRunRoleScoped {
|
|
@@ -33,6 +34,19 @@ export interface DryRunTaskItem {
|
|
|
33
34
|
estimatedTokens?: number | null;
|
|
34
35
|
/** Для клона матрицы — имя родителя-шаблона (Спринт 15). */
|
|
35
36
|
matrixParent?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Эффективное расписание cron-задачи (Спринт 19): пояс, окно запуска и
|
|
39
|
+
* ближайшие срабатывания с учётом часового пояса. Позволяет проверить
|
|
40
|
+
* пересчёт cron до регистрации в ОС.
|
|
41
|
+
*/
|
|
42
|
+
scheduleDetails?: {
|
|
43
|
+
cron: string;
|
|
44
|
+
timezone: string | null;
|
|
45
|
+
notBefore: string | null;
|
|
46
|
+
notAfter: string | null;
|
|
47
|
+
pausedUntil: string | null;
|
|
48
|
+
nextRuns: string[];
|
|
49
|
+
};
|
|
36
50
|
}
|
|
37
51
|
|
|
38
52
|
export interface DryRunTotals {
|
|
@@ -253,6 +267,33 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
|
|
|
253
267
|
? { allowed: undefined, denied: def.deniedTools }
|
|
254
268
|
: null;
|
|
255
269
|
|
|
270
|
+
// Эффективное расписание cron-задачи (Спринт 19): ближайшие срабатывания
|
|
271
|
+
// считаем в часовом поясе задачи, чтобы dry-run показывал то же время, что
|
|
272
|
+
// увидит планировщик после регистрации.
|
|
273
|
+
let scheduleDetails: DryRunTaskItem["scheduleDetails"];
|
|
274
|
+
if ((def.triggerType ?? "cron") === "cron" && def.schedule) {
|
|
275
|
+
const runs: string[] = [];
|
|
276
|
+
try {
|
|
277
|
+
let cursor = new Date();
|
|
278
|
+
for (let i = 0; i < 3; i++) {
|
|
279
|
+
const next = nextRun(def.schedule, cursor, def.timezone);
|
|
280
|
+
if (!next) break;
|
|
281
|
+
runs.push(next.toISOString());
|
|
282
|
+
cursor = next;
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
taskWarnings.push(`Не удалось разобрать cron "${def.schedule}" для расчёта ближайших запусков.`);
|
|
286
|
+
}
|
|
287
|
+
scheduleDetails = {
|
|
288
|
+
cron: def.schedule,
|
|
289
|
+
timezone: def.timezone ?? null,
|
|
290
|
+
notBefore: def.notBefore ?? null,
|
|
291
|
+
notAfter: def.notAfter ?? null,
|
|
292
|
+
pausedUntil: def.pausedUntil ?? null,
|
|
293
|
+
nextRuns: runs,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
256
297
|
tasks.push({
|
|
257
298
|
name: def.name,
|
|
258
299
|
order: index,
|
|
@@ -268,6 +309,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
|
|
|
268
309
|
estimatedCostUsd: estimatedCostUsd != null ? Math.round(estimatedCostUsd * 10000) / 10000 : null,
|
|
269
310
|
estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
|
|
270
311
|
...(matrixParent ? { matrixParent } : {}),
|
|
312
|
+
...(scheduleDetails ? { scheduleDetails } : {}),
|
|
271
313
|
});
|
|
272
314
|
|
|
273
315
|
if (taskWarnings.length > 0) {
|
package/src/core/matrix.ts
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
saveTask,
|
|
19
19
|
} from "../db/tasks-repo.js";
|
|
20
20
|
import { getHistory, recordRun } from "../db/history-repo.js";
|
|
21
|
+
import { notifyMatrixCompletion } from "../notifications.js";
|
|
21
22
|
import { getWorkspace } from "../workspaces.js";
|
|
22
23
|
import { createSchedulerBackend } from "./scheduler/index.js";
|
|
23
24
|
|
|
@@ -879,6 +880,15 @@ export async function finalizeMatrixIfComplete(
|
|
|
879
880
|
"skipped",
|
|
880
881
|
"skipped"
|
|
881
882
|
);
|
|
883
|
+
// Спринт 20: уведомление о завершении матрицы (partial / все упали / успех).
|
|
884
|
+
void notifyMatrixCompletion({
|
|
885
|
+
parentName: parent.name,
|
|
886
|
+
status: finalStatus,
|
|
887
|
+
total: aggregate.totalCount,
|
|
888
|
+
success: aggregate.successCount,
|
|
889
|
+
error: aggregate.errorCount,
|
|
890
|
+
message: aggregate.message,
|
|
891
|
+
});
|
|
882
892
|
} catch (err: any) {
|
|
883
893
|
console.log(
|
|
884
894
|
`[matrix] ${parent.name}: не удалось записать агрегат: ${
|