opencode-windows-scheduler 1.1.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 +45 -1
- package/README.md +13 -3
- package/README.ru.md +13 -3
- package/ROADMAP.md +20 -13
- package/dist/core/analytics.d.ts +10 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +21 -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/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 +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +13 -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 +1010 -54
- 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 +511 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +190 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +5 -2
- package/dist/settings.d.ts +57 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +118 -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/workspaces.d.ts +43 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +174 -8
- package/docs/ARCHITECTURE.md +32 -12
- package/docs/FEATURES.md +86 -7
- package/gui-experimental.cjs +4 -2
- package/package.json +6 -2
- package/src/core/analytics.ts +36 -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/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 +23 -0
- package/src/db/schema.ts +14 -0
- package/src/gui.tsx +767 -22
- package/src/index.ts +1226 -52
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +201 -2
- package/src/server.ts +5 -2
- package/src/settings.ts +214 -9
- package/src/task-transfer.ts +44 -0
- package/src/types.ts +3 -13
- package/src/workspaces.ts +214 -8
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-retention.mjs && node test-metrics.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",
|
|
@@ -73,6 +73,10 @@
|
|
|
73
73
|
"test:matrix-sync": "node test-matrix-sync.mjs",
|
|
74
74
|
"test:retention": "node test-retention.mjs",
|
|
75
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",
|
|
76
80
|
"test:agent": "node test-agent-tools.mjs",
|
|
77
81
|
"test:skill": "node test-skill.mjs",
|
|
78
82
|
"test:docs": "node test-docs.mjs"
|
package/src/core/analytics.ts
CHANGED
|
@@ -72,6 +72,15 @@ export interface ModelAnalyticsRow {
|
|
|
72
72
|
costUsd: number;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/** Агрегат по тексту ошибки — топ ошибок для дайджеста (Спринт 20). */
|
|
76
|
+
export interface ErrorAnalyticsRow {
|
|
77
|
+
/** Текст ошибки (обрезан до 160 символов). */
|
|
78
|
+
message: string;
|
|
79
|
+
count: number;
|
|
80
|
+
/** Последнее появление (ISO). */
|
|
81
|
+
lastAt: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
75
84
|
export interface AnalyticsReport {
|
|
76
85
|
generatedAt: string;
|
|
77
86
|
/** Окно анализа в днях. */
|
|
@@ -91,6 +100,8 @@ export interface AnalyticsReport {
|
|
|
91
100
|
topByCost: TaskAnalyticsRow[];
|
|
92
101
|
matrices: MatrixAnalyticsRow[];
|
|
93
102
|
byModel: ModelAnalyticsRow[];
|
|
103
|
+
/** Топ ошибок по частоте (Спринт 20). */
|
|
104
|
+
errors: ErrorAnalyticsRow[];
|
|
94
105
|
sources: {
|
|
95
106
|
historyRecords: number;
|
|
96
107
|
/** Сколько записей попало в окно. */
|
|
@@ -171,6 +182,7 @@ export function buildAnalytics(
|
|
|
171
182
|
|
|
172
183
|
const byTask = new Map<string, TaskAnalyticsRow>();
|
|
173
184
|
const byModel = new Map<string, ModelAnalyticsRow>();
|
|
185
|
+
const byError = new Map<string, ErrorAnalyticsRow>();
|
|
174
186
|
const cloneParent = new Map<string, string>();
|
|
175
187
|
for (const task of options.tasks ?? []) {
|
|
176
188
|
const parentId = task.matrixParentId?.trim();
|
|
@@ -253,6 +265,27 @@ export function buildAnalytics(
|
|
|
253
265
|
modelRow.total += 1;
|
|
254
266
|
modelRow.costUsd += cost;
|
|
255
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
|
+
}
|
|
256
289
|
}
|
|
257
290
|
|
|
258
291
|
const tasks = [...byTask.values()]
|
|
@@ -322,6 +355,9 @@ export function buildAnalytics(
|
|
|
322
355
|
byModel: [...byModel.values()]
|
|
323
356
|
.map((row) => ({ ...row, costUsd: Math.round(row.costUsd * 1e6) / 1e6 }))
|
|
324
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),
|
|
325
361
|
sources: {
|
|
326
362
|
historyRecords: records.length,
|
|
327
363
|
recordsInWindow,
|
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}: не удалось записать агрегат: ${
|
package/src/core/ps-wrapper.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { PLUGIN_DIR, LOG_DIR, WRAPPER_DIR } from "../types.js";
|
|
3
|
+
import { PLUGIN_DIR, LOG_DIR, LOCK_DIR, WRAPPER_DIR, sanitizeName } from "../types.js";
|
|
4
|
+
import type { ScheduleGateSpec } from "./schedule-v2.js";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
|
|
@@ -44,7 +45,8 @@ export const WRAPPER_SCRIPT = `param(
|
|
|
44
45
|
[string]$RecorderFile,
|
|
45
46
|
[string]$QualityGate,
|
|
46
47
|
[string]$BeforeScript,
|
|
47
|
-
[string]$AfterScript
|
|
48
|
+
[string]$AfterScript,
|
|
49
|
+
[string]$EnvFile
|
|
48
50
|
)
|
|
49
51
|
|
|
50
52
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
@@ -289,6 +291,21 @@ try {
|
|
|
289
291
|
if (-not $script:skipMainTask) {
|
|
290
292
|
$prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
|
|
291
293
|
|
|
294
|
+
# Спринт 21: env-переменные workspace. Файл пишет плагин, значения не логируются.
|
|
295
|
+
if ($EnvFile -and (Test-Path -LiteralPath $EnvFile)) {
|
|
296
|
+
try {
|
|
297
|
+
Get-Content -Path $EnvFile -Encoding UTF8 | ForEach-Object {
|
|
298
|
+
$line = $_.Trim()
|
|
299
|
+
if ($line -and -not $line.StartsWith("#") -and $line -match "^([A-Za-z_][A-Za-z0-9_]*)=(.*)$") {
|
|
300
|
+
Set-Item -Path ("env:" + $matches[1]) -Value $matches[2]
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
Write-Log "[windows-scheduler] Переменные окружения workspace загружены."
|
|
304
|
+
} catch {
|
|
305
|
+
Write-Log "[windows-scheduler] Не удалось загрузить env-файл workspace: $($_.Exception.Message)"
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
292
309
|
# Получаем путь к скрипту opencode (.ps1 или .cmd)
|
|
293
310
|
$opencodeCmd = Get-Command opencode | Select-Object -ExpandProperty Source
|
|
294
311
|
|
|
@@ -467,6 +484,8 @@ export function lockFilePath(taskName: string): string {
|
|
|
467
484
|
* @param workspaceName имя workspace для git-контекста в логе (опционально)
|
|
468
485
|
* @param allowedTools список разрешённых инструментов (спринт 14, опционально)
|
|
469
486
|
* @param deniedTools список запрещённых инструментов (спринт 14, опционально)
|
|
487
|
+
* @param scheduleGate гейт расписания (спринт 19): проверка cron в таймзоне
|
|
488
|
+
* и окна запуска перед стартом PowerShell-обёртки.
|
|
470
489
|
*/
|
|
471
490
|
export async function writeWrapperCmd(
|
|
472
491
|
sanitizedName: string,
|
|
@@ -483,7 +502,14 @@ export async function writeWrapperCmd(
|
|
|
483
502
|
afterScript?: string,
|
|
484
503
|
workspaceName?: string,
|
|
485
504
|
allowedTools?: string[],
|
|
486
|
-
deniedTools?: string[]
|
|
505
|
+
deniedTools?: string[],
|
|
506
|
+
scheduleGate?: ScheduleGateSpec & {
|
|
507
|
+
gateFile: string;
|
|
508
|
+
deferFile?: string;
|
|
509
|
+
forceFile?: string;
|
|
510
|
+
forceTtlMs?: number;
|
|
511
|
+
},
|
|
512
|
+
envFile?: string
|
|
487
513
|
): Promise<string> {
|
|
488
514
|
await fs.mkdir(WRAPPER_DIR, { recursive: true });
|
|
489
515
|
const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
|
|
@@ -557,6 +583,14 @@ export async function writeWrapperCmd(
|
|
|
557
583
|
}
|
|
558
584
|
}
|
|
559
585
|
|
|
586
|
+
// Спринт 21: env-файл workspace (пары KEY=VALUE). Значения не логируются.
|
|
587
|
+
if (envFile?.trim()) {
|
|
588
|
+
const safeEnvFile = envFile.replace(/[\r\n"]+/g, "").trim();
|
|
589
|
+
if (safeEnvFile) {
|
|
590
|
+
psArgs.push(`-EnvFile "${safeEnvFile}"`);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
560
594
|
const lines: string[] = ["@echo off", "chcp 65001 >nul"];
|
|
561
595
|
|
|
562
596
|
// Рабочая директория: всегда переходим в неё ДО запуска PowerShell.
|
|
@@ -565,8 +599,88 @@ export async function writeWrapperCmd(
|
|
|
565
599
|
const effectiveWorkdir = workdir?.trim() || process.cwd();
|
|
566
600
|
lines.push(`cd /d "${effectiveWorkdir}"`);
|
|
567
601
|
|
|
602
|
+
// Спринт 19: гейт расписания ДО PowerShell. Проверяет, что cron реально
|
|
603
|
+
// сработал сейчас (для poll-режима и чужих таймзон), и при необходимости
|
|
604
|
+
// переносит запуск до открытия окна notBefore..notAfter.
|
|
605
|
+
// Exit 3 — «не сейчас», выходим тихо, не считая это запуском задачи.
|
|
606
|
+
if (scheduleGate?.gateFile) {
|
|
607
|
+
const gateArgs = [`node "${scheduleGate.gateFile}"`];
|
|
608
|
+
if (scheduleGate.cron?.trim()) {
|
|
609
|
+
gateArgs.push(`--cron "${scheduleGate.cron.replace(/[\r\n"]+/g, " ").trim()}"`);
|
|
610
|
+
}
|
|
611
|
+
if (scheduleGate.tz?.trim()) {
|
|
612
|
+
gateArgs.push(`--tz "${scheduleGate.tz.trim()}"`);
|
|
613
|
+
}
|
|
614
|
+
if (scheduleGate.notBefore?.trim()) {
|
|
615
|
+
gateArgs.push(`--not-before ${scheduleGate.notBefore.trim()}`);
|
|
616
|
+
}
|
|
617
|
+
if (scheduleGate.notAfter?.trim()) {
|
|
618
|
+
gateArgs.push(`--not-after ${scheduleGate.notAfter.trim()}`);
|
|
619
|
+
}
|
|
620
|
+
if (scheduleGate.deferFile?.trim()) {
|
|
621
|
+
gateArgs.push(`--defer-file "${scheduleGate.deferFile.trim()}"`);
|
|
622
|
+
}
|
|
623
|
+
// Маркер ручного запуска: run_task_now/файловый триггер/MCP-событие
|
|
624
|
+
// создают его перед вызовом schtasks /run, чтобы gate не отсекал запуск
|
|
625
|
+
// по cron. Без этого run_task_now был тихим no-op для poll-режима.
|
|
626
|
+
if (scheduleGate.forceFile?.trim()) {
|
|
627
|
+
gateArgs.push(`--force-file "${scheduleGate.forceFile.trim()}"`);
|
|
628
|
+
}
|
|
629
|
+
// append к логу задачи, чтобы перенос/пропуск был виден в истории запусков
|
|
630
|
+
if (logFile?.trim()) {
|
|
631
|
+
gateArgs.push(`>> "${logFile.trim()}" 2>&1`);
|
|
632
|
+
}
|
|
633
|
+
lines.push(gateArgs.join(" "));
|
|
634
|
+
lines.push(`if "%errorlevel%"=="3" exit /b 0`);
|
|
635
|
+
}
|
|
636
|
+
|
|
568
637
|
lines.push(psArgs.join(" "));
|
|
569
638
|
|
|
570
639
|
await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
|
|
571
640
|
return cmdPath;
|
|
572
641
|
}
|
|
642
|
+
|
|
643
|
+
// ---------------------------------------------------------------------------
|
|
644
|
+
// Маркер ручного запуска.
|
|
645
|
+
|
|
646
|
+
/** Сколько живёт маркер ручного запуска (должно совпадать с schedule-gate.ts). */
|
|
647
|
+
export const FORCE_FILE_TTL_MS = 2 * 60 * 1000;
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Путь к маркеру немедленного запуска задачи.
|
|
651
|
+
*
|
|
652
|
+
* Лежит рядом с lock-файлом и вычисляется из того же санитизированного имени,
|
|
653
|
+
* поэтому обёртка (--force-file) и агент указывают на один и тот же файл.
|
|
654
|
+
*/
|
|
655
|
+
export function forceFilePath(taskName: string): string {
|
|
656
|
+
return `${lockFilePath(sanitizeName(taskName))}.force`;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Создаёт маркер «запустить сейчас» перед вызовом планировщика ОС.
|
|
661
|
+
*
|
|
662
|
+
* Зачем: для poll-режима (нестандартный cron/чужая таймзона/окно запуска)
|
|
663
|
+
* обёртка всегда прогоняет schedule-gate, и ручной запуск вне cron-окна
|
|
664
|
+
* молча завершался с exit 3 — инструмент рапортовал success, но задача не
|
|
665
|
+
* выполнялась. Gate поглощает свежий маркер и пропускает проверку расписания.
|
|
666
|
+
*
|
|
667
|
+
* Маркер самоуничтожается через FORCE_FILE_TTL_MS, если задача так и не
|
|
668
|
+
* стартовала (например, отключена в планировщике), чтобы не влиять на
|
|
669
|
+
* последующие плановые запуски.
|
|
670
|
+
*/
|
|
671
|
+
export async function requestImmediateRun(taskName: string): Promise<string> {
|
|
672
|
+
const file = forceFilePath(taskName);
|
|
673
|
+
await fs.mkdir(LOCK_DIR, { recursive: true });
|
|
674
|
+
await fs.writeFile(file, new Date().toISOString(), "utf8");
|
|
675
|
+
|
|
676
|
+
const timer = setTimeout(() => {
|
|
677
|
+
void fs.unlink(file).catch(() => {
|
|
678
|
+
/* маркер уже поглощён gate'ом или удалён вручную */
|
|
679
|
+
});
|
|
680
|
+
}, FORCE_FILE_TTL_MS);
|
|
681
|
+
// Таймер не должен удерживать процесс хоста.
|
|
682
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
683
|
+
|
|
684
|
+
return file;
|
|
685
|
+
}
|
|
686
|
+
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* schedule-gate: вызывается враппером (.cmd / bash) сразу после срабатывания
|
|
3
|
+
* планировщика, ДО запуска агента.
|
|
4
|
+
*
|
|
5
|
+
* Проверяет расширенное cron-выражение и окно запуска (notBefore/notAfter):
|
|
6
|
+
* node dist/core/schedule-gate.js --cron "0 9 * * *" [--tz "Europe/Moscow"]
|
|
7
|
+
* [--not-before 22:00 --not-after 06:00]
|
|
8
|
+
* [--defer-file "C:\...\name.lock.defer"]
|
|
9
|
+
* [--force-file "C:\...\name.lock.force"]
|
|
10
|
+
* [--now 2026-11-13T12:00:00.000Z] (для тестов)
|
|
11
|
+
*
|
|
12
|
+
* --force-file — маркер ручного запуска (run_task_now, файловый триггер,
|
|
13
|
+
* catch-up). Если файл существует и моложе FORCE_TTL_MS, проверка cron/окна
|
|
14
|
+
* пропускается, а маркер удаляется. Протухший маркер не действует — иначе
|
|
15
|
+
* забытый файл однажды обошёл бы расписание.
|
|
16
|
+
*
|
|
17
|
+
* Коды выхода:
|
|
18
|
+
* 0 — можно запускать (wrapper выполняет агента);
|
|
19
|
+
* 3 — не время (cron не совпал, уже есть отложенный запуск или не в окне),
|
|
20
|
+
* wrapper тихо завершается;
|
|
21
|
+
* 1 — некорректные аргументы (ошибка логируется; запуск разрешён, чтобы не
|
|
22
|
+
* ломать задачу из-за опечатки в конфигурации).
|
|
23
|
+
*
|
|
24
|
+
* Окно запуска реализовано как ПЕРЕНОС, а не пропуск: если cron совпал, но
|
|
25
|
+
* сейчас вне окна, gate ждёт открытия окна. Дубликаты отложенных запусков
|
|
26
|
+
* отсекаются по defer-файлу (атомарное создание); файл запись удаляет сам gate
|
|
27
|
+
* после пробуждения; если файл протух (> 25 часов) — считается stale и
|
|
28
|
+
* перезаписывается.
|
|
29
|
+
*/
|
|
30
|
+
import fs from "node:fs";
|
|
31
|
+
import {
|
|
32
|
+
cronMatches,
|
|
33
|
+
isValidIanaTimeZone,
|
|
34
|
+
isInWindow,
|
|
35
|
+
parseCron,
|
|
36
|
+
validateLaunchWindow,
|
|
37
|
+
windowDelayMs,
|
|
38
|
+
} from "./schedule-v2.js";
|
|
39
|
+
|
|
40
|
+
const STALE_DEFER_MS = 25 * 60 * 60 * 1000;
|
|
41
|
+
|
|
42
|
+
/** Сколько живёт маркер ручного запуска. */
|
|
43
|
+
const FORCE_TTL_MS = 2 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
function argValue(args: string[], name: string): string | undefined {
|
|
46
|
+
const idx = args.indexOf(name);
|
|
47
|
+
if (idx === -1 || idx + 1 >= args.length) return undefined;
|
|
48
|
+
return args[idx + 1];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function sleepMs(ms: number): Promise<void> {
|
|
52
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** true, если defer-файл сейчас занят другим отложенным запуском. */
|
|
56
|
+
function deferFileBusy(path: string, nowMs: number): boolean {
|
|
57
|
+
try {
|
|
58
|
+
const raw = fs.readFileSync(path, "utf8").trim();
|
|
59
|
+
const ts = Date.parse(raw);
|
|
60
|
+
if (Number.isFinite(ts) && nowMs - ts < STALE_DEFER_MS) return true;
|
|
61
|
+
// Протухший файл — удаляем и занимаем сами.
|
|
62
|
+
fs.unlinkSync(path);
|
|
63
|
+
return false;
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Атомарно занимает defer-слот; true, если занят успешно. */
|
|
70
|
+
function acquireDefer(path: string, nowMs: number): boolean {
|
|
71
|
+
try {
|
|
72
|
+
const fd = fs.openSync(path, "wx");
|
|
73
|
+
fs.writeSync(fd, new Date(nowMs).toISOString());
|
|
74
|
+
fs.closeSync(fd);
|
|
75
|
+
return true;
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function releaseDefer(path: string): void {
|
|
82
|
+
try {
|
|
83
|
+
fs.unlinkSync(path);
|
|
84
|
+
} catch {
|
|
85
|
+
/* удалён раньше — не страшно */
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Проверяет и поглощает маркер ручного запуска.
|
|
91
|
+
*
|
|
92
|
+
* Возвращает true, если маркер свежий (значит, запуск инициирован вручную:
|
|
93
|
+
* инструментом, файловым триггером, MCP-событием или catch-up) — тогда гейт
|
|
94
|
+
* расписания не должен блокировать запуск. Маркер удаляется в любом случае.
|
|
95
|
+
*
|
|
96
|
+
* Возраст считается по реальным часам, а не по --now, иначе тестовый --now
|
|
97
|
+
* ломал бы проверку. Протухший маркер (например, задача не стартовала)
|
|
98
|
+
* просто удаляется и не влияет на расписание.
|
|
99
|
+
*/
|
|
100
|
+
function consumeForceMarker(path: string): boolean {
|
|
101
|
+
try {
|
|
102
|
+
const stat = fs.statSync(path);
|
|
103
|
+
fs.unlinkSync(path);
|
|
104
|
+
return Date.now() - stat.mtimeMs <= FORCE_TTL_MS;
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function main(): Promise<number> {
|
|
111
|
+
const args = process.argv.slice(2);
|
|
112
|
+
const cronExpr = argValue(args, "--cron");
|
|
113
|
+
const tz = argValue(args, "--tz");
|
|
114
|
+
const notBefore = argValue(args, "--not-before");
|
|
115
|
+
const notAfter = argValue(args, "--not-after");
|
|
116
|
+
const deferFile = argValue(args, "--defer-file");
|
|
117
|
+
const forceFile = argValue(args, "--force-file");
|
|
118
|
+
const nowArg = argValue(args, "--now");
|
|
119
|
+
|
|
120
|
+
const now = nowArg ? new Date(nowArg) : new Date();
|
|
121
|
+
if (Number.isNaN(now.getTime())) {
|
|
122
|
+
console.error(`[schedule-gate] Некорректное значение --now: ${nowArg}`);
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Ручной запуск (run_task_now, файловый триггер, MCP-событие, catch-up):
|
|
127
|
+
// маркер свежий — расписание и окно не проверяем.
|
|
128
|
+
if (forceFile && consumeForceMarker(forceFile)) {
|
|
129
|
+
console.error("[schedule-gate] Ручной запуск — проверка расписания пропущена.");
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Невалидный timezone/окно — не блокируем задачу, логируем и продолжаем.
|
|
134
|
+
const zone = tz && isValidIanaTimeZone(tz) ? tz : undefined;
|
|
135
|
+
if (tz && !zone) {
|
|
136
|
+
console.error(`[schedule-gate] Неизвестный timezone «${tz}» — игнорируем его.`);
|
|
137
|
+
}
|
|
138
|
+
const windowError = validateLaunchWindow(notBefore, notAfter);
|
|
139
|
+
if (windowError) {
|
|
140
|
+
console.error(`[schedule-gate] Окно запуска игнорируется: ${windowError}`);
|
|
141
|
+
}
|
|
142
|
+
const windowOk = !windowError && !!notBefore && !!notAfter;
|
|
143
|
+
|
|
144
|
+
let spec = null;
|
|
145
|
+
if (cronExpr) {
|
|
146
|
+
try {
|
|
147
|
+
spec = parseCron(cronExpr);
|
|
148
|
+
} catch (err: any) {
|
|
149
|
+
console.error(
|
|
150
|
+
`[schedule-gate] Невалидный cron «${cronExpr}»: ${
|
|
151
|
+
err instanceof Error ? err.message : String(err)
|
|
152
|
+
} — пропускаем проверку cron.`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (spec && !cronMatches(spec, now, zone)) {
|
|
158
|
+
// По расширенному cron сейчас не время.
|
|
159
|
+
return 3;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (windowOk && !isInWindow(now, notBefore, notAfter, zone)) {
|
|
163
|
+
const wait = windowDelayMs(now, notBefore, notAfter, zone);
|
|
164
|
+
if (wait <= 0) return 0;
|
|
165
|
+
|
|
166
|
+
// ПЕРЕНОС: ждём открытия окна. Откладываем один запуск, остальные тики
|
|
167
|
+
// отсекаются по defer-файлу.
|
|
168
|
+
if (deferFile) {
|
|
169
|
+
if (deferFileBusy(deferFile, now.getTime())) {
|
|
170
|
+
console.error("[schedule-gate] Отложенный запуск уже ожидает открытия окна.");
|
|
171
|
+
return 3;
|
|
172
|
+
}
|
|
173
|
+
if (!acquireDefer(deferFile, now.getTime())) {
|
|
174
|
+
console.error("[schedule-gate] Не удалось захватить defer-файл — пропускаем.");
|
|
175
|
+
return 3;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
console.error(
|
|
180
|
+
`[schedule-gate] Вне окна ${notBefore}–${notAfter} — запуск перенесён на ~${Math.round(
|
|
181
|
+
wait / 60000
|
|
182
|
+
)} мин.`
|
|
183
|
+
);
|
|
184
|
+
let remaining = wait;
|
|
185
|
+
let woke = now;
|
|
186
|
+
while (remaining > 0) {
|
|
187
|
+
const chunk = Math.min(remaining, 60_000);
|
|
188
|
+
await sleepMs(chunk);
|
|
189
|
+
remaining -= chunk;
|
|
190
|
+
woke = new Date();
|
|
191
|
+
if (isInWindow(woke, notBefore, notAfter, zone)) break;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (deferFile) releaseDefer(deferFile);
|
|
195
|
+
|
|
196
|
+
if (!isInWindow(woke, notBefore, notAfter, zone)) {
|
|
197
|
+
console.error("[schedule-gate] Окно не открылось за отведённое время — не запускаем.");
|
|
198
|
+
return 3;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
main().then(
|
|
206
|
+
(code) => process.exit(code),
|
|
207
|
+
(err) => {
|
|
208
|
+
console.error(
|
|
209
|
+
`[schedule-gate] Непредвиденная ошибка: ${err instanceof Error ? err.message : String(err)} — запускаем.`
|
|
210
|
+
);
|
|
211
|
+
process.exit(1);
|
|
212
|
+
}
|
|
213
|
+
);
|