opencode-windows-scheduler 1.5.2 → 1.5.5
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 +107 -2
- package/CROSS_PLATFORM.md +107 -71
- package/LICENSE +21 -21
- package/README.md +74 -26
- package/ROADMAP-STRATEGY.md +11 -4
- package/ROADMAP.md +322 -112
- package/dist/core/analytics.d.ts +3 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +4 -0
- package/dist/core/audit.d.ts +2 -1
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +32 -1
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +21 -4
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +16 -1
- package/dist/core/git-trigger.d.ts +4 -2
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +34 -16
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +14 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +81 -4
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +3 -2
- package/dist/core/native-notify.d.ts.map +1 -1
- package/dist/core/native-notify.js +3 -0
- package/dist/core/one-shot.d.ts +7 -1
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +15 -2
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/ps-wrapper.d.ts +9 -30
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +477 -108
- package/dist/core/record-history.d.ts +11 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +106 -4
- package/dist/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.js +7 -3
- package/dist/core/schedule-v2.js +1 -1
- package/dist/core/scheduler/index.d.ts +13 -1
- package/dist/core/scheduler/index.d.ts.map +1 -1
- package/dist/core/scheduler/index.js +35 -4
- package/dist/core/scheduler/linux.d.ts +4 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +53 -20
- package/dist/core/scheduler/mac.d.ts +2 -1
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +24 -6
- package/dist/core/scheduler/posix.d.ts +1 -1
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +2 -2
- package/dist/core/scheduler/registry.d.ts +3 -2
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +6 -5
- package/dist/core/scheduler/windows.d.ts +49 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +219 -34
- package/dist/core/secrets.d.ts +5 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +86 -8
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/session.d.ts +11 -3
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +34 -5
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +10 -0
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +228 -47
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +15 -3
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +153 -120
- package/dist/db/history-repo.d.ts +1 -1
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +29 -14
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +31 -0
- package/dist/history.d.ts +2 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +3 -3
- package/dist/i18n.d.ts +25 -2
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +75 -10
- package/dist/index.d.ts +66 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +527 -68
- package/dist/integrations.d.ts +9 -1
- package/dist/integrations.d.ts.map +1 -1
- package/dist/integrations.js +34 -6
- package/dist/notifications.d.ts +30 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +289 -10
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +21 -3
- package/dist/rpc.d.ts +401 -5
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +138 -5
- package/dist/server.d.ts +20 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +136 -14
- package/dist/settings.d.ts +167 -3
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +322 -3
- package/dist/task-transfer.d.ts +8 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +2 -2
- package/dist/types.d.ts +8 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +23 -5
- package/dist/workspaces.d.ts +9 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +25 -0
- package/docs/ARCHITECTURE.md +48 -28
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +141 -44
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +17 -0
- package/docs/README.ru.md +22 -16
- package/docs/README.zh.md +286 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +8 -8
- package/locales/en.json +85 -0
- package/locales/ru.json +85 -0
- package/locales/zh.json +780 -0
- package/package.json +31 -7
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +4 -3
- package/skills/scheduled-job-best-practices/SKILL.md +6 -3
- package/skills/scheduled-job-best-practices/references/recipes.md +40 -0
- package/src/core/analytics.ts +10 -0
- package/src/core/audit.ts +39 -1
- package/src/core/cron-to-schtasks.ts +23 -4
- package/src/core/file-watcher.ts +20 -1
- package/src/core/git-trigger.ts +34 -16
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +88 -3
- package/src/core/matrix.ts +5 -1
- package/src/core/native-notify.ts +3 -0
- package/src/core/one-shot.ts +18 -2
- package/src/core/permissions.ts +200 -0
- package/src/core/ps-wrapper.ts +492 -108
- package/src/core/record-history.ts +111 -4
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +9 -3
- package/src/core/schedule-v2.ts +1 -1
- package/src/core/scheduler/index.ts +41 -3
- package/src/core/scheduler/linux.ts +67 -22
- package/src/core/scheduler/mac.ts +24 -7
- package/src/core/scheduler/posix.ts +2 -2
- package/src/core/scheduler/registry.ts +7 -5
- package/src/core/scheduler/windows.ts +237 -32
- package/src/core/secrets.ts +101 -7
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +40 -5
- package/src/core/shutdown.ts +69 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +266 -55
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +181 -138
- package/src/db/history-repo.ts +31 -18
- package/src/db/schema.ts +31 -0
- package/src/gui.tsx +551 -14
- package/src/history.ts +7 -3
- package/src/i18n.ts +87 -13
- package/src/index.ts +649 -71
- package/src/integrations.ts +50 -6
- package/src/notifications.ts +468 -5
- package/src/profiles.ts +21 -3
- package/src/rpc.ts +143 -5
- package/src/server.ts +135 -16
- package/src/settings.ts +582 -5
- package/src/task-transfer.ts +10 -3
- package/src/types.ts +24 -5
- package/src/workspaces.ts +22 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Параллельный прогон того же набора сюит, что `npm test`.
|
|
3
|
+
*
|
|
4
|
+
* Читает `scripts.test` из package.json, разбивает цепочку по `&&` и запускает
|
|
5
|
+
* наборы пулом воркеров. Последовательный `npm test` остаётся как есть — он
|
|
6
|
+
* нужен для воспроизводимости и отладки.
|
|
7
|
+
*
|
|
8
|
+
* Запуск:
|
|
9
|
+
* node scripts/run-tests.mjs
|
|
10
|
+
* node scripts/run-tests.mjs --concurrency=2
|
|
11
|
+
* node scripts/run-tests.mjs --locale=en
|
|
12
|
+
* node scripts/run-tests.mjs --only=dashboard
|
|
13
|
+
*/
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
|
|
20
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
21
|
+
|
|
22
|
+
function parseArgs(argv) {
|
|
23
|
+
const options = {
|
|
24
|
+
concurrency: Math.max(1, Math.min(8, os.cpus().length || 4)),
|
|
25
|
+
locale: null,
|
|
26
|
+
only: null,
|
|
27
|
+
timeoutMs: 15 * 60 * 1000,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
for (const arg of argv) {
|
|
31
|
+
if (arg === "--serial") options.concurrency = 1;
|
|
32
|
+
else if (arg.startsWith("--concurrency=")) {
|
|
33
|
+
const value = Number(arg.slice("--concurrency=".length));
|
|
34
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
35
|
+
console.error(`Некорректная конкурентность: ${arg}`);
|
|
36
|
+
process.exit(2);
|
|
37
|
+
}
|
|
38
|
+
options.concurrency = Math.min(8, value);
|
|
39
|
+
} else if (arg.startsWith("--locale=")) {
|
|
40
|
+
options.locale = arg.slice("--locale=".length);
|
|
41
|
+
if (!["ru", "en", "zh"].includes(options.locale)) {
|
|
42
|
+
console.error(`Неизвестная локаль: ${options.locale}. Ожидается ru, en или zh.`);
|
|
43
|
+
process.exit(2);
|
|
44
|
+
}
|
|
45
|
+
} else if (arg.startsWith("--only=")) {
|
|
46
|
+
options.only = arg.slice("--only=".length);
|
|
47
|
+
} else if (arg.startsWith("--timeout=")) {
|
|
48
|
+
const seconds = Number(arg.slice("--timeout=".length));
|
|
49
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
50
|
+
console.error(`Некорректный таймаут: ${arg}`);
|
|
51
|
+
process.exit(2);
|
|
52
|
+
}
|
|
53
|
+
options.timeoutMs = seconds * 1000;
|
|
54
|
+
} else if (arg === "--help" || arg === "-h") {
|
|
55
|
+
console.log(
|
|
56
|
+
[
|
|
57
|
+
"node scripts/run-tests.mjs [--concurrency=N] [--serial] [--locale=ru|en|zh]",
|
|
58
|
+
" [--only=substring] [--timeout=seconds]",
|
|
59
|
+
].join("\n")
|
|
60
|
+
);
|
|
61
|
+
process.exit(0);
|
|
62
|
+
} else {
|
|
63
|
+
console.error(`Неизвестный аргумент: ${arg}`);
|
|
64
|
+
process.exit(2);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return options;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const options = parseArgs(process.argv.slice(2));
|
|
72
|
+
|
|
73
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
74
|
+
let suites = pkg.scripts.test
|
|
75
|
+
.split("&&")
|
|
76
|
+
.map((part) => part.trim().replace(/^node\s+/, ""))
|
|
77
|
+
.filter(Boolean);
|
|
78
|
+
|
|
79
|
+
if (options.only) {
|
|
80
|
+
suites = suites.filter((suite) => suite.includes(options.only));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (suites.length === 0) {
|
|
84
|
+
console.error("Не найдено ни одного набора для запуска.");
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const total = suites.length;
|
|
89
|
+
const results = new Array(total);
|
|
90
|
+
let completed = 0;
|
|
91
|
+
let failed = 0;
|
|
92
|
+
|
|
93
|
+
const startedAt = Date.now();
|
|
94
|
+
|
|
95
|
+
function formatDuration(ms) {
|
|
96
|
+
return `${(ms / 1000).toFixed(1)}s`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function runSuite(suite, index) {
|
|
100
|
+
return new Promise((resolve) => {
|
|
101
|
+
const suiteStartedAt = Date.now();
|
|
102
|
+
const child = spawn(process.execPath, [suite], {
|
|
103
|
+
cwd: root,
|
|
104
|
+
env: {
|
|
105
|
+
...process.env,
|
|
106
|
+
...(options.locale ? { OPENCODE_SCHEDULER_LOCALE: options.locale } : {}),
|
|
107
|
+
},
|
|
108
|
+
windowsHide: true,
|
|
109
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
let stdout = "";
|
|
113
|
+
let stderr = "";
|
|
114
|
+
let timedOut = false;
|
|
115
|
+
|
|
116
|
+
child.stdout.on("data", (chunk) => {
|
|
117
|
+
stdout += chunk.toString();
|
|
118
|
+
});
|
|
119
|
+
child.stderr.on("data", (chunk) => {
|
|
120
|
+
stderr += chunk.toString();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
timedOut = true;
|
|
125
|
+
child.kill("SIGKILL");
|
|
126
|
+
}, options.timeoutMs);
|
|
127
|
+
|
|
128
|
+
child.on("error", (error) => {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
const result = {
|
|
131
|
+
suite,
|
|
132
|
+
index,
|
|
133
|
+
ok: false,
|
|
134
|
+
code: null,
|
|
135
|
+
durationMs: Date.now() - suiteStartedAt,
|
|
136
|
+
stdout,
|
|
137
|
+
stderr: `${stderr}\n${error instanceof Error ? error.message : String(error)}`,
|
|
138
|
+
timedOut,
|
|
139
|
+
};
|
|
140
|
+
finish(result);
|
|
141
|
+
resolve(result);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
child.on("close", (code) => {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
const result = {
|
|
147
|
+
suite,
|
|
148
|
+
index,
|
|
149
|
+
ok: code === 0 && !timedOut,
|
|
150
|
+
code,
|
|
151
|
+
durationMs: Date.now() - suiteStartedAt,
|
|
152
|
+
stdout,
|
|
153
|
+
stderr,
|
|
154
|
+
timedOut,
|
|
155
|
+
};
|
|
156
|
+
finish(result);
|
|
157
|
+
resolve(result);
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function finish(result) {
|
|
163
|
+
results[result.index] = result;
|
|
164
|
+
completed++;
|
|
165
|
+
if (!result.ok) failed++;
|
|
166
|
+
|
|
167
|
+
const status = result.ok ? "OK " : result.timedOut ? "TIME" : "FAIL";
|
|
168
|
+
console.log(
|
|
169
|
+
`[${String(completed).padStart(3)}/${total}] ${status} ${result.suite} (${formatDuration(
|
|
170
|
+
result.durationMs
|
|
171
|
+
)})`
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
if (!result.ok) {
|
|
175
|
+
const output = `${result.stdout}${result.stderr}`.trim();
|
|
176
|
+
if (output) {
|
|
177
|
+
console.error(`--- вывод ${result.suite} ---`);
|
|
178
|
+
console.error(output);
|
|
179
|
+
console.error(`--- конец ${result.suite} ---`);
|
|
180
|
+
}
|
|
181
|
+
if (result.timedOut) {
|
|
182
|
+
console.error(`Таймаут ${formatDuration(options.timeoutMs)}: ${result.suite}`);
|
|
183
|
+
}
|
|
184
|
+
// GitHub Actions: логи job недоступны анонимно, поэтому дублируем хвост
|
|
185
|
+
// вывода в аннотацию. Она читается через публичный check-runs API.
|
|
186
|
+
if (process.env.GITHUB_ACTIONS === "true") {
|
|
187
|
+
const escape = (value) =>
|
|
188
|
+
value.replace(/%/g, "%25").replace(/\r/g, "").replace(/\n/g, "%0A");
|
|
189
|
+
const tail = output.split(/\r?\n/).slice(-20).join("\n");
|
|
190
|
+
const detail = `${result.timedOut ? "timeout " : ""}${tail}`.slice(0, 4000);
|
|
191
|
+
console.log(`::error title=${escape(result.suite)}::${escape(detail)}`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function main() {
|
|
197
|
+
console.log(
|
|
198
|
+
`Параллельный прогон: ${total} наборов, конкурентность ${options.concurrency}${
|
|
199
|
+
options.locale ? `, локаль ${options.locale}` : ""
|
|
200
|
+
}`
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
let nextIndex = 0;
|
|
204
|
+
const workers = Array.from({ length: Math.min(options.concurrency, total) }, async () => {
|
|
205
|
+
while (true) {
|
|
206
|
+
const index = nextIndex++;
|
|
207
|
+
if (index >= total) return;
|
|
208
|
+
await runSuite(suites[index], index);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
await Promise.all(workers);
|
|
213
|
+
|
|
214
|
+
const durationMs = Date.now() - startedAt;
|
|
215
|
+
const failedSuites = results.filter((result) => !result.ok);
|
|
216
|
+
|
|
217
|
+
console.log("");
|
|
218
|
+
console.log(
|
|
219
|
+
`Итого: ${total - failedSuites.length}/${total} наборов за ${formatDuration(durationMs)}`
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
if (failedSuites.length > 0) {
|
|
223
|
+
console.error("Провалены:");
|
|
224
|
+
for (const result of failedSuites) {
|
|
225
|
+
console.error(` - ${result.suite}${result.timedOut ? " (таймаут)" : ""}`);
|
|
226
|
+
}
|
|
227
|
+
process.exit(1);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
process.exit(0);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
main().catch((error) => {
|
|
234
|
+
console.error(error);
|
|
235
|
+
process.exit(1);
|
|
236
|
+
});
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Спайк structured output локальной модели через Ollama.
|
|
3
|
+
*
|
|
4
|
+
* Запуск:
|
|
5
|
+
* node scripts/spike-local-structured.mjs --model qwen3:4b --runs 10
|
|
6
|
+
*
|
|
7
|
+
* Скрипт не входит в `npm test`: он требует запущенную Ollama и скачанную
|
|
8
|
+
* модель. Цель — получить воспроизводимый ответ на вопрос, можно ли доверять
|
|
9
|
+
* JSON 4B-модели без retry. Результат печатается в stdout и, если указан
|
|
10
|
+
* `--out`, сохраняется в JSON.
|
|
11
|
+
*/
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
const DEFAULTS = {
|
|
16
|
+
baseUrl: "http://127.0.0.1:11434",
|
|
17
|
+
model: "qwen3:4b",
|
|
18
|
+
runs: 10,
|
|
19
|
+
timeoutMs: 60000,
|
|
20
|
+
out: "",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function parseArgs(argv) {
|
|
24
|
+
const args = { ...DEFAULTS };
|
|
25
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
26
|
+
const key = argv[i];
|
|
27
|
+
const value = argv[i + 1];
|
|
28
|
+
if (key === "--base-url") args.baseUrl = value;
|
|
29
|
+
else if (key === "--model") args.model = value;
|
|
30
|
+
else if (key === "--runs") args.runs = Number(value);
|
|
31
|
+
else if (key === "--timeout") args.timeoutMs = Number(value);
|
|
32
|
+
else if (key === "--out") args.out = value;
|
|
33
|
+
else if (key === "--help" || key === "-h") {
|
|
34
|
+
console.log("node scripts/spike-local-structured.mjs [--model qwen3:4b] [--runs 10] [--base-url URL] [--timeout MS] [--out FILE]");
|
|
35
|
+
process.exit(0);
|
|
36
|
+
} else {
|
|
37
|
+
console.error(`Неизвестный аргумент: ${key}`);
|
|
38
|
+
process.exit(2);
|
|
39
|
+
}
|
|
40
|
+
i += 1;
|
|
41
|
+
}
|
|
42
|
+
if (!Number.isInteger(args.runs) || args.runs < 1 || args.runs > 100) {
|
|
43
|
+
console.error("--runs должен быть целым числом от 1 до 100.");
|
|
44
|
+
process.exit(2);
|
|
45
|
+
}
|
|
46
|
+
return args;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const schema = {
|
|
50
|
+
type: "object",
|
|
51
|
+
properties: {
|
|
52
|
+
category: { type: "string", enum: ["quality", "timeout", "permission", "network", "unknown"] },
|
|
53
|
+
severity: { type: "string", enum: ["low", "medium", "high"] },
|
|
54
|
+
confidence: { type: "number", minimum: 0, maximum: 1 },
|
|
55
|
+
reason: { type: "string" },
|
|
56
|
+
},
|
|
57
|
+
required: ["category", "severity", "confidence", "reason"],
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const prompt = `Ты классифицируешь уведомление планировщика задач.
|
|
61
|
+
Верни только JSON без markdown и пояснений по схеме:
|
|
62
|
+
{"category":"quality|timeout|permission|network|unknown","severity":"low|medium|high","confidence":0..1,"reason":"кратко"}
|
|
63
|
+
|
|
64
|
+
Уведомление:
|
|
65
|
+
Задача "nightly-tests" упала за 2.3s. Quality Gate вернул код 1: 3 теста не прошли в auth-модуле.`;
|
|
66
|
+
|
|
67
|
+
function validate(value) {
|
|
68
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return "not an object";
|
|
69
|
+
for (const key of schema.required) {
|
|
70
|
+
if (!(key in value)) return `missing ${key}`;
|
|
71
|
+
}
|
|
72
|
+
if (!schema.properties.category.enum.includes(value.category)) return "bad category";
|
|
73
|
+
if (!schema.properties.severity.enum.includes(value.severity)) return "bad severity";
|
|
74
|
+
if (typeof value.confidence !== "number" || value.confidence < 0 || value.confidence > 1) return "bad confidence";
|
|
75
|
+
if (typeof value.reason !== "string" || value.reason.trim() === "") return "bad reason";
|
|
76
|
+
return "";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function loadModel(baseUrl, model) {
|
|
80
|
+
const response = await fetch(`${baseUrl}/api/tags`, { signal: AbortSignal.timeout(10000) });
|
|
81
|
+
if (!response.ok) throw new Error(`/api/tags: HTTP ${response.status}`);
|
|
82
|
+
const data = await response.json();
|
|
83
|
+
const names = (data.models ?? []).map((item) => item.name);
|
|
84
|
+
if (names.length === 0) throw new Error("Ollama запущена, но моделей нет: выполните ollama pull " + model);
|
|
85
|
+
if (!names.some((name) => name === model || name === `${model}:latest`)) {
|
|
86
|
+
throw new Error(`Модель "${model}" не найдена. Доступны: ${names.join(", ")}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function runOnce(args, index) {
|
|
91
|
+
const started = Date.now();
|
|
92
|
+
const body = {
|
|
93
|
+
model: args.model,
|
|
94
|
+
messages: [{ role: "user", content: prompt }],
|
|
95
|
+
stream: false,
|
|
96
|
+
format: schema,
|
|
97
|
+
options: { temperature: 0, seed: index + 1 },
|
|
98
|
+
};
|
|
99
|
+
const response = await fetch(`${args.baseUrl}/api/chat`, {
|
|
100
|
+
method: "POST",
|
|
101
|
+
headers: { "content-type": "application/json" },
|
|
102
|
+
body: JSON.stringify(body),
|
|
103
|
+
signal: AbortSignal.timeout(args.timeoutMs),
|
|
104
|
+
});
|
|
105
|
+
const latencyMs = Date.now() - started;
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
return { run: index + 1, ok: false, jsonValid: false, schemaValid: false, latencyMs, error: `HTTP ${response.status}` };
|
|
108
|
+
}
|
|
109
|
+
const data = await response.json();
|
|
110
|
+
const content = data?.message?.content ?? "";
|
|
111
|
+
let parsed;
|
|
112
|
+
try {
|
|
113
|
+
parsed = JSON.parse(content);
|
|
114
|
+
} catch {
|
|
115
|
+
return { run: index + 1, ok: false, jsonValid: false, schemaValid: false, latencyMs, content, error: "invalid JSON" };
|
|
116
|
+
}
|
|
117
|
+
const error = validate(parsed);
|
|
118
|
+
return {
|
|
119
|
+
run: index + 1,
|
|
120
|
+
ok: !error,
|
|
121
|
+
jsonValid: true,
|
|
122
|
+
schemaValid: !error,
|
|
123
|
+
latencyMs,
|
|
124
|
+
content,
|
|
125
|
+
parsed,
|
|
126
|
+
error,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const args = parseArgs(process.argv.slice(2));
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
await loadModel(args.baseUrl, args.model);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
console.error(`Не удалось подключиться к Ollama: ${error.message}`);
|
|
136
|
+
console.error("Спайк заблокирован: установите Ollama, выполните `ollama serve` и `ollama pull " + args.model + "`.");
|
|
137
|
+
process.exit(2);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const results = [];
|
|
141
|
+
for (let i = 0; i < args.runs; i += 1) {
|
|
142
|
+
const result = await runOnce(args, i);
|
|
143
|
+
results.push(result);
|
|
144
|
+
const mark = result.schemaValid ? "OK" : "FAIL";
|
|
145
|
+
console.log(`${result.run}/${args.runs} ${mark} ${result.latencyMs}ms${result.error ? ` — ${result.error}` : ""}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const jsonValid = results.filter((item) => item.jsonValid).length;
|
|
149
|
+
const schemaValid = results.filter((item) => item.schemaValid).length;
|
|
150
|
+
const latencies = results.map((item) => item.latencyMs).sort((a, b) => a - b);
|
|
151
|
+
const avg = Math.round(latencies.reduce((sum, value) => sum + value, 0) / latencies.length);
|
|
152
|
+
const p95 = latencies[Math.max(0, Math.ceil(latencies.length * 0.95) - 1)];
|
|
153
|
+
|
|
154
|
+
const summary = {
|
|
155
|
+
generatedAt: new Date().toISOString(),
|
|
156
|
+
baseUrl: args.baseUrl,
|
|
157
|
+
model: args.model,
|
|
158
|
+
runs: args.runs,
|
|
159
|
+
jsonValid,
|
|
160
|
+
schemaValid,
|
|
161
|
+
schemaValidRate: Number((schemaValid / args.runs).toFixed(2)),
|
|
162
|
+
avgLatencyMs: avg,
|
|
163
|
+
p95LatencyMs: p95,
|
|
164
|
+
results,
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
console.log("");
|
|
168
|
+
console.log(`Модель: ${args.model}`);
|
|
169
|
+
console.log(`JSON валиден: ${jsonValid}/${args.runs}; схема: ${schemaValid}/${args.runs} (${Math.round(summary.schemaValidRate * 100)}%)`);
|
|
170
|
+
console.log(`Латентность: avg ${avg}ms, p95 ${p95}ms`);
|
|
171
|
+
if (schemaValid >= 9) console.log("Вывод: 4B можно использовать без retry, но валидацию схемы оставить.");
|
|
172
|
+
else if (schemaValid >= 7) console.log("Вывод: нужен ровно один retry и fallback на правила.");
|
|
173
|
+
else console.log("Вывод: 4B нельзя использовать для критичных вердиктов; только правила или модель крупнее.");
|
|
174
|
+
|
|
175
|
+
if (args.out) {
|
|
176
|
+
const target = path.resolve(args.out);
|
|
177
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
178
|
+
fs.writeFileSync(target, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
|
|
179
|
+
console.log(`Результат: ${target}`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
process.exit(schemaValid >= 7 ? 0 : 1);
|
package/scripts/test-locale.mjs
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* Прогоняет тот же набор сюит, что `npm test`, с заданной локалью.
|
|
3
3
|
*
|
|
4
4
|
* Локаль задаётся переменной `OPENCODE_SCHEDULER_LOCALE`, которую читает
|
|
5
|
-
* `src/i18n.ts` при загрузке: так один и тот же код проверяется в ru и
|
|
5
|
+
* `src/i18n.ts` при загрузке: так один и тот же код проверяется в ru, en и zh
|
|
6
6
|
* без правки settings.json.
|
|
7
7
|
*
|
|
8
8
|
* Запуск: node scripts/test-locale.mjs en
|
|
9
|
+
* Локали: ru (по умолчанию), en, zh.
|
|
9
10
|
*/
|
|
10
11
|
import fs from "node:fs";
|
|
11
12
|
import path from "node:path";
|
|
@@ -15,8 +16,8 @@ import { fileURLToPath } from "node:url";
|
|
|
15
16
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
16
17
|
const locale = process.argv[2] ?? "en";
|
|
17
18
|
|
|
18
|
-
if (locale !== "ru" && locale !== "en") {
|
|
19
|
-
console.error(`Неизвестная локаль: ${locale}. Ожидается ru или
|
|
19
|
+
if (locale !== "ru" && locale !== "en" && locale !== "zh") {
|
|
20
|
+
console.error(`Неизвестная локаль: ${locale}. Ожидается ru, en или zh.`);
|
|
20
21
|
process.exit(2);
|
|
21
22
|
}
|
|
22
23
|
|
|
@@ -55,8 +55,11 @@ is genuinely ambiguous, tell it to stop and write the question into the report.
|
|
|
55
55
|
|
|
56
56
|
## 4. Safety defaults
|
|
57
57
|
|
|
58
|
-
- **Least privilege**:
|
|
59
|
-
not be allowed to `write` or run
|
|
58
|
+
- **Least privilege**: the default `hybrid` policy already denies `shell` and `question`; keep it
|
|
59
|
+
that way. Read-only monitoring jobs should not be allowed to `write` or run shell. Do not ask
|
|
60
|
+
for `shell` just to run `git commit`, a build or tests — put those in `qualityGate`/`afterScript`,
|
|
61
|
+
which the wrapper runs outside the agent. If a job truly needs shell, list `shell` in
|
|
62
|
+
`allowedTools` (or set `legacyShell: true` for a migrated task) and explain why.
|
|
60
63
|
- **Timeout**: always set `timeoutSeconds` for jobs that call networks or models. Default
|
|
61
64
|
timeouts are a safety net, not a plan.
|
|
62
65
|
- **Quality Gate**: pass `qualityGate` whenever a machine-checkable success criterion exists
|
|
@@ -146,7 +149,7 @@ Before saying the job is done, confirm:
|
|
|
146
149
|
- [ ] Trigger type matches the need (cron / file / MCP event).
|
|
147
150
|
- [ ] Prompt states goal, scope, constraints, verification and output.
|
|
148
151
|
- [ ] `timeoutSeconds` set; `qualityGate` set when checkable.
|
|
149
|
-
- [ ] `allowedTools` / `deniedTools` follow least privilege.
|
|
152
|
+
- [ ] `allowedTools` / `deniedTools` follow least privilege; shell is absent unless justified.
|
|
150
153
|
- [ ] Matrix: workspaces correct, concurrency capped, failure mode justified.
|
|
151
154
|
- [ ] `dry_run` reviewed.
|
|
152
155
|
- [ ] One successful `run_task_now` with clean `get_history`.
|
|
@@ -121,3 +121,43 @@ Why: explicit protected list, dry-run first, auditable report. Ask the user to r
|
|
|
121
121
|
4. Fix the cause (`update_task` on the parent for a definition bug, or the repository itself).
|
|
122
122
|
5. Re-run only the failed clone with `run_task_now`, then confirm the aggregate becomes
|
|
123
123
|
`success`.
|
|
124
|
+
|
|
125
|
+
## 8. Safe rollout of local triage
|
|
126
|
+
|
|
127
|
+
Start in shadow mode so the model logs decisions without suppressing notifications,
|
|
128
|
+
then verify with the benchmark and the shadow report before enforcing.
|
|
129
|
+
|
|
130
|
+
```json
|
|
131
|
+
{
|
|
132
|
+
"action": "update",
|
|
133
|
+
"mode": "auto",
|
|
134
|
+
"baseUrl": "http://127.0.0.1:11434",
|
|
135
|
+
"model": "qwen3:4b",
|
|
136
|
+
"timeoutMs": 60000,
|
|
137
|
+
"fallback": "rules",
|
|
138
|
+
"confidenceThreshold": 0.6,
|
|
139
|
+
"shadow": { "enabled": true, "days": 14 }
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
Check readiness and run one classification request:
|
|
144
|
+
|
|
145
|
+
```json
|
|
146
|
+
{ "action": "get" }
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
```json
|
|
150
|
+
{ "action": "test", "model": "qwen3:4b" }
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Measure the machine before trusting the model:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
npm run bench:local -- --model qwen3:4b --runs 3 --out bench.json
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Why: `auto` keeps the rules engine as a fallback, `fallback: "rules"` is
|
|
160
|
+
fail-open, and shadow mode makes false skips visible. Only disable shadow mode
|
|
161
|
+
after the shadow report shows no false positives. See `docs/LOCAL-AI.md` for
|
|
162
|
+
model tiers by RAM, `OLLAMA_CONTEXT_LENGTH` troubleshooting and the full JSON
|
|
163
|
+
report format.
|
package/src/core/analytics.ts
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
* Чистые функции без БД и HTTP: дашборд и RPC отдают JSON, экспорт — CSV.
|
|
5
5
|
* Так агрегаты легко тестировать без запуска сервера.
|
|
6
6
|
*/
|
|
7
|
+
import {
|
|
8
|
+
computeSavings,
|
|
9
|
+
type SavingsRecord,
|
|
10
|
+
type SavingsReport,
|
|
11
|
+
} from "./savings.js";
|
|
7
12
|
|
|
8
13
|
/** Оценка стоимости, если запись истории не содержит costUsd. */
|
|
9
14
|
export const ESTIMATED_COST_PER_1K_TOKENS_USD = 0.003;
|
|
@@ -102,6 +107,8 @@ export interface AnalyticsReport {
|
|
|
102
107
|
byModel: ModelAnalyticsRow[];
|
|
103
108
|
/** Топ ошибок по частоте (Спринт 20). */
|
|
104
109
|
errors: ErrorAnalyticsRow[];
|
|
110
|
+
/** Оценка экономии по контрфактике (Спринт 31.6). */
|
|
111
|
+
savings: SavingsReport;
|
|
105
112
|
sources: {
|
|
106
113
|
historyRecords: number;
|
|
107
114
|
/** Сколько записей попало в окно. */
|
|
@@ -198,6 +205,7 @@ export function buildAnalytics(
|
|
|
198
205
|
let durationsSum = 0;
|
|
199
206
|
let durationsCount = 0;
|
|
200
207
|
let recordsInWindow = 0;
|
|
208
|
+
const windowRecords: SavingsRecord[] = [];
|
|
201
209
|
|
|
202
210
|
for (const record of records) {
|
|
203
211
|
const date = recordDate(record);
|
|
@@ -212,6 +220,7 @@ export function buildAnalytics(
|
|
|
212
220
|
const status = String(record.status ?? "");
|
|
213
221
|
// Незавершённые запуски не участвуют в аналитике: их ещё нельзя оценить.
|
|
214
222
|
if (status === "running") continue;
|
|
223
|
+
windowRecords.push(record);
|
|
215
224
|
const duration = toNumber(record.durationMs);
|
|
216
225
|
|
|
217
226
|
bucket.total += 1;
|
|
@@ -358,6 +367,7 @@ export function buildAnalytics(
|
|
|
358
367
|
errors: [...byError.values()]
|
|
359
368
|
.sort((a, b) => b.count - a.count || a.message.localeCompare(b.message))
|
|
360
369
|
.slice(0, topLimit),
|
|
370
|
+
savings: computeSavings(windowRecords, { topLimit }),
|
|
361
371
|
sources: {
|
|
362
372
|
historyRecords: records.length,
|
|
363
373
|
recordsInWindow,
|
package/src/core/audit.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { getDb } from "../db/index.js";
|
|
2
2
|
import { redactSecretsInText } from "./secrets.js";
|
|
3
|
+
import {
|
|
4
|
+
resolvePermissions,
|
|
5
|
+
type PermissionPolicy,
|
|
6
|
+
} from "./permissions.js";
|
|
3
7
|
|
|
4
8
|
/**
|
|
5
9
|
* Журнал аудита мутаций (Спринт 26).
|
|
@@ -216,7 +220,9 @@ export function recordTaskToolBlocks(
|
|
|
216
220
|
allowedTools: readonly string[] | null | undefined,
|
|
217
221
|
deniedTools: readonly string[] | null | undefined,
|
|
218
222
|
actor: AuditActor = "system",
|
|
219
|
-
source = "policy"
|
|
223
|
+
source = "policy",
|
|
224
|
+
policy?: PermissionPolicy,
|
|
225
|
+
legacyShell?: boolean
|
|
220
226
|
): number {
|
|
221
227
|
const normalizedDenied = Array.from(
|
|
222
228
|
new Set(
|
|
@@ -260,6 +266,38 @@ export function recordTaskToolBlocks(
|
|
|
260
266
|
written++;
|
|
261
267
|
}
|
|
262
268
|
}
|
|
269
|
+
// Спринт 32 / релиз 1.6: фиксируем инструменты, запрещённые политикой по
|
|
270
|
+
// умолчанию (hybrid: shell/question; secure: ещё edit/webfetch/websearch/
|
|
271
|
+
// subagent). Это политика на момент сохранения задачи, а не попытки вызова:
|
|
272
|
+
// detached-обёртка не имеет доступа к SQLite.
|
|
273
|
+
if (policy) {
|
|
274
|
+
const effective = resolvePermissions({
|
|
275
|
+
policy,
|
|
276
|
+
legacyShell,
|
|
277
|
+
allowedTools: normalizedAllowed,
|
|
278
|
+
deniedTools: normalizedDenied,
|
|
279
|
+
});
|
|
280
|
+
for (const denied of effective.deniedByPolicy) {
|
|
281
|
+
if (
|
|
282
|
+
recordToolBlocked({
|
|
283
|
+
task,
|
|
284
|
+
tool: denied.action,
|
|
285
|
+
actor,
|
|
286
|
+
source,
|
|
287
|
+
details: {
|
|
288
|
+
reason: "default-policy",
|
|
289
|
+
policy: effective.policy,
|
|
290
|
+
legacyShell: effective.legacyShell,
|
|
291
|
+
hint: denied.hint,
|
|
292
|
+
allowedTools: normalizedAllowed.length > 0 ? normalizedAllowed : null,
|
|
293
|
+
deniedTools: normalizedDenied.length > 0 ? normalizedDenied : null,
|
|
294
|
+
},
|
|
295
|
+
}) != null
|
|
296
|
+
) {
|
|
297
|
+
written++;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
263
301
|
return written;
|
|
264
302
|
}
|
|
265
303
|
|
|
@@ -11,11 +11,15 @@ const UNSUPPORTED_ERROR =
|
|
|
11
11
|
"Поддерживаемое подмножество cron (5 полей: минута час день_месяца месяц день_недели):\n" +
|
|
12
12
|
" * * * * * -> MINUTE, каждую минуту (/mo 1)\n" +
|
|
13
13
|
" */N * * * * -> MINUTE, каждые N минут (/mo N)\n" +
|
|
14
|
+
" M * * * * -> HOURLY, ежечасно в MM минут (/st 00:MM)\n" +
|
|
14
15
|
" M H * * * -> DAILY, ежедневно в HH:MM (/st HH:MM)\n" +
|
|
15
16
|
" M H * * D -> WEEKLY, по неделям в день D в HH:MM (/d D /st HH:MM)\n" +
|
|
16
17
|
"\n" +
|
|
17
18
|
"Не поддерживаются: диапазоны (1-5), списки (1,2,3), комбинации месяца и дня недели,\n" +
|
|
18
|
-
"*/N
|
|
19
|
+
"*/N в поле дня месяца или дня недели, а также любые другие сложные выражения.\n" +
|
|
20
|
+
"Выражение `M H */N * *` намеренно не превращается в DAILY /mo N: cron отсчитывает\n" +
|
|
21
|
+
"дни от 1-го числа месяца, а /mo N — от даты создания задачи, поэтому расписания\n" +
|
|
22
|
+
"не совпадают. Такие задачи выполняются в режиме минутного опроса (minute-poll).\n" +
|
|
19
23
|
"Пожалуйста, упростите расписание, используя одно из поддерживаемых выше выражений.";
|
|
20
24
|
|
|
21
25
|
/** Дни недели для schtasks /d (0 и 7 = воскресенье). */
|
|
@@ -107,6 +111,18 @@ export function convertCronToSchTasks(cron: string): CronConversion {
|
|
|
107
111
|
UNSUPPORTED_ERROR
|
|
108
112
|
);
|
|
109
113
|
}
|
|
114
|
+
// schtasks /mo N запускает задачу каждые N минут начиная с момента создания
|
|
115
|
+
// задачи, а cron */N — в минуты 0, N, 2N внутри каждого часа. Семантики
|
|
116
|
+
// совпадают только когда N делит 60 без остатка; иначе отдаём задачу в
|
|
117
|
+
// минутный опрос с gate во враппере (needsPollMode).
|
|
118
|
+
if (60 % stepN !== 0) {
|
|
119
|
+
throw new Error(
|
|
120
|
+
"Интервал */" +
|
|
121
|
+
stepN +
|
|
122
|
+
" не делит час нацело: cron и schtasks понимают его по-разному.\n\n" +
|
|
123
|
+
UNSUPPORTED_ERROR
|
|
124
|
+
);
|
|
125
|
+
}
|
|
110
126
|
return {
|
|
111
127
|
sc: "MINUTE",
|
|
112
128
|
extraFlags: ["/mo", String(stepN)],
|
|
@@ -195,13 +211,16 @@ export function previousRunTime(cron: string, now: Date = new Date()): Date | nu
|
|
|
195
211
|
return new Date(Math.floor(nowMs / 60000) * 60000);
|
|
196
212
|
}
|
|
197
213
|
|
|
198
|
-
// */N * * * * — каждые N минут
|
|
214
|
+
// */N * * * * — каждые N минут внутри часа (минуты 0, N, 2N...).
|
|
199
215
|
const step = /^\*\/(\d+)$/.exec(minute);
|
|
200
216
|
if (step && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
|
|
201
217
|
const n = parseInt(step[1], 10);
|
|
202
218
|
if (n > 0) {
|
|
203
|
-
const
|
|
204
|
-
|
|
219
|
+
const result = new Date(now);
|
|
220
|
+
result.setSeconds(0, 0);
|
|
221
|
+
const minuteOfHour = result.getMinutes();
|
|
222
|
+
result.setMinutes(n >= 60 ? 0 : minuteOfHour - (minuteOfHour % n));
|
|
223
|
+
return result;
|
|
205
224
|
}
|
|
206
225
|
return null;
|
|
207
226
|
}
|