agent-steward 0.0.2 → 0.0.3
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 +25 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +9 -8
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +114 -999
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dry-run.js +1 -1
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.js +2 -4
- package/dist/core/one-shot.d.ts +27 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +53 -10
- package/dist/core/otel.js +2 -2
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +55 -35
- package/dist/core/record-history.js +22 -22
- package/dist/core/schedule-v2.d.ts +2 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +7 -7
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/linux.d.ts +3 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +43 -7
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +12 -1
- package/dist/core/scheduler/registry.d.ts +2 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.js +2 -2
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/summary.js +1 -1
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.js +33 -33
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +9 -1
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +190 -35
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -36
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +109 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +89 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +20 -19
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +37 -9
- package/dist/workspaces.js +1 -1
- package/docs/ARCHITECTURE.md +110 -8
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +15 -3
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +26 -7
- package/docs/README.zh.md +9 -8
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +1 -0
- package/locales/ru.json +1 -0
- package/locales/zh.json +1 -0
- package/package.json +31 -10
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dry-run.ts +26 -26
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +9 -9
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +63 -13
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +57 -37
- package/src/core/record-history.ts +40 -40
- package/src/core/retention.ts +3 -3
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +12 -12
- package/src/core/schedule-v2.ts +24 -24
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +64 -13
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +15 -1
- package/src/core/scheduler/registry.ts +6 -4
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +13 -13
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +3 -3
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +41 -41
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +22 -22
- package/src/db/index.ts +16 -6
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +10 -10
- package/src/db/recovery.ts +3 -3
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +205 -44
- package/src/db/settings-repo.ts +2 -2
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +1 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +341 -304
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +96 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +43 -42
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +45 -10
- package/src/workspaces.ts +16 -16
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
package/src/core/file-watcher.ts
CHANGED
|
@@ -39,7 +39,7 @@ export class FileWatchManager {
|
|
|
39
39
|
|
|
40
40
|
constructor(
|
|
41
41
|
private readonly handler: FileTriggerHandler,
|
|
42
|
-
private readonly debounceMs: number = FILE_TRIGGER_DEBOUNCE_MS
|
|
42
|
+
private readonly debounceMs: number = FILE_TRIGGER_DEBOUNCE_MS,
|
|
43
43
|
) {}
|
|
44
44
|
|
|
45
45
|
/** Сколько задач сейчас отслеживается. */
|
|
@@ -61,7 +61,7 @@ export class FileWatchManager {
|
|
|
61
61
|
(d) =>
|
|
62
62
|
d.triggerType === "file" &&
|
|
63
63
|
typeof d.watchPath === "string" &&
|
|
64
|
-
d.watchPath.trim().length > 0
|
|
64
|
+
d.watchPath.trim().length > 0,
|
|
65
65
|
)
|
|
66
66
|
.map((d) => ({
|
|
67
67
|
name: d.name.trim(),
|
|
@@ -79,13 +79,13 @@ export class FileWatchManager {
|
|
|
79
79
|
// watcher на путях с управляющими символами или выходом через `..`.
|
|
80
80
|
if (hasPathControlChars(d.path)) {
|
|
81
81
|
console.error(
|
|
82
|
-
`[
|
|
82
|
+
`[agent-steward] Задача "${d.name}": путь наблюдения содержит управляющие символы — пропущен.`,
|
|
83
83
|
);
|
|
84
84
|
return false;
|
|
85
85
|
}
|
|
86
86
|
if (!isAbsolute(d.path) && d.path.split(/[\\/]/).includes("..")) {
|
|
87
87
|
console.error(
|
|
88
|
-
`[
|
|
88
|
+
`[agent-steward] Задача "${d.name}": относительный путь наблюдения выходит за рабочую директорию — пропущен.`,
|
|
89
89
|
);
|
|
90
90
|
return false;
|
|
91
91
|
}
|
|
@@ -130,7 +130,7 @@ export class FileWatchManager {
|
|
|
130
130
|
name: string,
|
|
131
131
|
watchPath: string,
|
|
132
132
|
globs: string[] = [],
|
|
133
|
-
ignore: string[] = []
|
|
133
|
+
ignore: string[] = [],
|
|
134
134
|
): void {
|
|
135
135
|
// Спринт 27: маски с "**" требуют рекурсивного обхода директории.
|
|
136
136
|
const needsRecursive = globs.some((g) => g.includes("**"));
|
|
@@ -148,9 +148,9 @@ export class FileWatchManager {
|
|
|
148
148
|
});
|
|
149
149
|
} catch (err: any) {
|
|
150
150
|
console.error(
|
|
151
|
-
`[
|
|
151
|
+
`[agent-steward] Не удалось начать отслеживание "${watchPath}" для задачи "${name}": ${
|
|
152
152
|
err instanceof Error ? err.message : String(err)
|
|
153
|
-
}
|
|
153
|
+
}`,
|
|
154
154
|
);
|
|
155
155
|
return;
|
|
156
156
|
}
|
|
@@ -174,7 +174,7 @@ export class FileWatchManager {
|
|
|
174
174
|
const rel = relativeTo(watchPath, changedPath);
|
|
175
175
|
const candidates = rel ? [rel, changedPath] : [changedPath];
|
|
176
176
|
return candidates.some(
|
|
177
|
-
(candidate) => filterPaths([candidate], globs, ignore).length > 0
|
|
177
|
+
(candidate) => filterPaths([candidate], globs, ignore).length > 0,
|
|
178
178
|
);
|
|
179
179
|
};
|
|
180
180
|
|
|
@@ -187,20 +187,20 @@ export class FileWatchManager {
|
|
|
187
187
|
if (this.stopped) return;
|
|
188
188
|
try {
|
|
189
189
|
const result = this.handler(name, changedPath);
|
|
190
|
-
if (result && typeof (result
|
|
191
|
-
(result
|
|
190
|
+
if (result && typeof (result).catch === "function") {
|
|
191
|
+
(result).catch((err: any) => {
|
|
192
192
|
console.error(
|
|
193
|
-
`[
|
|
193
|
+
`[agent-steward] Ошибка запуска задачи "${name}" по изменению файла: ${
|
|
194
194
|
err instanceof Error ? err.message : String(err)
|
|
195
|
-
}
|
|
195
|
+
}`,
|
|
196
196
|
);
|
|
197
197
|
});
|
|
198
198
|
}
|
|
199
199
|
} catch (err: any) {
|
|
200
200
|
console.error(
|
|
201
|
-
`[
|
|
201
|
+
`[agent-steward] Ошибка запуска задачи "${name}" по изменению файла: ${
|
|
202
202
|
err instanceof Error ? err.message : String(err)
|
|
203
|
-
}
|
|
203
|
+
}`,
|
|
204
204
|
);
|
|
205
205
|
}
|
|
206
206
|
}, this.debounceMs);
|
|
@@ -216,15 +216,15 @@ export class FileWatchManager {
|
|
|
216
216
|
|
|
217
217
|
watcher.on("error", (err) => {
|
|
218
218
|
console.error(
|
|
219
|
-
`[
|
|
219
|
+
`[agent-steward] Ошибка наблюдения за "${watchPath}" (задача "${name}"): ${
|
|
220
220
|
(err as any)?.message ?? String(err)
|
|
221
|
-
}
|
|
221
|
+
}`,
|
|
222
222
|
);
|
|
223
223
|
});
|
|
224
224
|
|
|
225
225
|
this.entries.set(name.toLowerCase(), entry);
|
|
226
226
|
console.log(
|
|
227
|
-
`[
|
|
227
|
+
`[agent-steward] Слежу за "${watchPath}" — задача "${name}" запускается при изменении файла.`,
|
|
228
228
|
);
|
|
229
229
|
}
|
|
230
230
|
|
package/src/core/git-trigger.ts
CHANGED
|
@@ -70,11 +70,11 @@ const defaultRunner: GitRunner = (cwd, args) =>
|
|
|
70
70
|
{ timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
|
|
71
71
|
(err, stdout) => {
|
|
72
72
|
if (err) {
|
|
73
|
-
reject(err);
|
|
73
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
74
74
|
return;
|
|
75
75
|
}
|
|
76
76
|
resolve(String(stdout ?? ""));
|
|
77
|
-
}
|
|
77
|
+
},
|
|
78
78
|
);
|
|
79
79
|
});
|
|
80
80
|
|
|
@@ -113,7 +113,7 @@ export async function gitChangedFiles(
|
|
|
113
113
|
cwd: string,
|
|
114
114
|
from: string | null,
|
|
115
115
|
to: string,
|
|
116
|
-
run: GitRunner = defaultRunner
|
|
116
|
+
run: GitRunner = defaultRunner,
|
|
117
117
|
): Promise<string[]> {
|
|
118
118
|
const args = from
|
|
119
119
|
? ["diff", "--name-only", `${from}..${to}`]
|
|
@@ -126,7 +126,7 @@ export async function gitChangedFiles(
|
|
|
126
126
|
}
|
|
127
127
|
|
|
128
128
|
function branchMatches(branch: string | null, pattern?: string): boolean {
|
|
129
|
-
if (!pattern
|
|
129
|
+
if (!pattern?.trim()) return true;
|
|
130
130
|
if (!branch) return false;
|
|
131
131
|
const normalize = (value: string) =>
|
|
132
132
|
process.platform === "win32" ? value.toLowerCase() : value;
|
|
@@ -151,7 +151,7 @@ function branchMatches(branch: string | null, pattern?: string): boolean {
|
|
|
151
151
|
*/
|
|
152
152
|
export async function checkGitTrigger(
|
|
153
153
|
task: GitTriggerTask,
|
|
154
|
-
options: { run?: GitRunner; persist?: boolean } = {}
|
|
154
|
+
options: { run?: GitRunner; persist?: boolean } = {},
|
|
155
155
|
): Promise<GitCheckResult> {
|
|
156
156
|
const run = options.run ?? defaultRunner;
|
|
157
157
|
const persist = options.persist !== false;
|
|
@@ -328,7 +328,7 @@ export class GitTriggerManager {
|
|
|
328
328
|
return checkGitTrigger(this.taskSpec(managed.def), { run: this.run });
|
|
329
329
|
}
|
|
330
330
|
const def = (await loadTaskDefinitions()).find(
|
|
331
|
-
(d) => d.triggerType === "git" && d.name.toLowerCase() === taskName.toLowerCase()
|
|
331
|
+
(d) => d.triggerType === "git" && d.name.toLowerCase() === taskName.toLowerCase(),
|
|
332
332
|
);
|
|
333
333
|
if (!def) return null;
|
|
334
334
|
return checkGitTrigger(this.taskSpec(def), { run: this.run });
|
|
@@ -354,13 +354,13 @@ export class GitTriggerManager {
|
|
|
354
354
|
if (result.status === "changed") {
|
|
355
355
|
await this.handler(managed.def.name, { ...result, cwd: cwdOf(managed.def) });
|
|
356
356
|
} else if (result.status === "error") {
|
|
357
|
-
console.error(`[
|
|
357
|
+
console.error(`[agent-steward] git-триггер «${managed.def.name}»: ${result.message}`);
|
|
358
358
|
}
|
|
359
359
|
} catch (err: any) {
|
|
360
360
|
console.error(
|
|
361
|
-
`[
|
|
361
|
+
`[agent-steward] git-триггер «${managed.def.name}»: ${
|
|
362
362
|
err instanceof Error ? err.message : String(err)
|
|
363
|
-
}
|
|
363
|
+
}`,
|
|
364
364
|
);
|
|
365
365
|
} finally {
|
|
366
366
|
managed.busy = false;
|
package/src/core/glob.ts
CHANGED
|
@@ -196,7 +196,7 @@ export function isIgnored(path: unknown, ignore: unknown): boolean {
|
|
|
196
196
|
export function filterPaths(
|
|
197
197
|
files: string[],
|
|
198
198
|
include?: string[] | null,
|
|
199
|
-
ignore?: string[] | null
|
|
199
|
+
ignore?: string[] | null,
|
|
200
200
|
): string[] {
|
|
201
201
|
const list = Array.isArray(files) ? files : [];
|
|
202
202
|
const includes = Array.isArray(include) ? include.filter(Boolean) : [];
|
package/src/core/local-ai.ts
CHANGED
|
@@ -70,7 +70,7 @@ export function protocolFor(baseUrl: string): "openai" | "ollama" {
|
|
|
70
70
|
*/
|
|
71
71
|
export function applyLocalAiPatch(
|
|
72
72
|
current: TriageSettings,
|
|
73
|
-
patch: LocalAiPatch
|
|
73
|
+
patch: LocalAiPatch,
|
|
74
74
|
): { settings: TriageSettings; changed: string[] } {
|
|
75
75
|
const next: TriageSettings = { ...current, shadow: { ...current.shadow } as TriageShadowSettings };
|
|
76
76
|
const changed: string[] = [];
|
|
@@ -98,7 +98,7 @@ export function applyLocalAiPatch(
|
|
|
98
98
|
patch.timeoutMs,
|
|
99
99
|
LOCAL_AI_TIMEOUT_MIN,
|
|
100
100
|
LOCAL_AI_TIMEOUT_MAX,
|
|
101
|
-
current.timeoutMs
|
|
101
|
+
current.timeoutMs,
|
|
102
102
|
);
|
|
103
103
|
if (timeoutMs !== current.timeoutMs) {
|
|
104
104
|
next.timeoutMs = timeoutMs;
|
package/src/core/lock.ts
CHANGED
|
@@ -72,11 +72,11 @@ export class LockManager {
|
|
|
72
72
|
continue;
|
|
73
73
|
}
|
|
74
74
|
await fs.rm(stalePath, { recursive: true, force: true }).catch(() => {});
|
|
75
|
-
|
|
75
|
+
|
|
76
76
|
console.log(
|
|
77
|
-
`[
|
|
78
|
-
age / 1000
|
|
79
|
-
)} с)
|
|
77
|
+
`[agent-steward] Вытеснен зависший lock: ${file} (возраст ${Math.round(
|
|
78
|
+
age / 1000,
|
|
79
|
+
)} с)`,
|
|
80
80
|
);
|
|
81
81
|
}
|
|
82
82
|
} catch {
|
|
@@ -142,13 +142,13 @@ export class LockManager {
|
|
|
142
142
|
export async function withLock<T>(
|
|
143
143
|
lockManager: LockManager,
|
|
144
144
|
taskName: string,
|
|
145
|
-
fn: () => Promise<T
|
|
145
|
+
fn: () => Promise<T>,
|
|
146
146
|
): Promise<T | null> {
|
|
147
147
|
const acquired = await lockManager.acquire(taskName);
|
|
148
148
|
if (!acquired) {
|
|
149
|
-
|
|
149
|
+
|
|
150
150
|
console.log(
|
|
151
|
-
`[
|
|
151
|
+
`[agent-steward] Запуск задачи "${taskName}" пропущен: удерживается активная блокировка.`,
|
|
152
152
|
);
|
|
153
153
|
return null;
|
|
154
154
|
}
|
|
@@ -171,7 +171,7 @@ export async function withLockWait<T>(
|
|
|
171
171
|
lockManager: LockManager,
|
|
172
172
|
taskName: string,
|
|
173
173
|
fn: () => Promise<T>,
|
|
174
|
-
options: { timeoutMs?: number; retryDelayMs?: number; staleMs?: number } = {}
|
|
174
|
+
options: { timeoutMs?: number; retryDelayMs?: number; staleMs?: number } = {},
|
|
175
175
|
): Promise<T> {
|
|
176
176
|
const timeoutMs = options.timeoutMs ?? 15000;
|
|
177
177
|
const retryDelayMs = options.retryDelayMs ?? 50;
|
|
@@ -205,7 +205,7 @@ export async function withLockWait<T>(
|
|
|
205
205
|
|
|
206
206
|
if (Date.now() >= deadline) {
|
|
207
207
|
throw new Error(
|
|
208
|
-
`Не удалось получить блокировку "${taskName}" за ${timeoutMs}
|
|
208
|
+
`Не удалось получить блокировку "${taskName}" за ${timeoutMs} мс.`,
|
|
209
209
|
);
|
|
210
210
|
}
|
|
211
211
|
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
|
package/src/core/matrix.ts
CHANGED
|
@@ -56,7 +56,7 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
|
56
56
|
const matrix = task.matrix;
|
|
57
57
|
if (!matrix || !Array.isArray(matrix.workspaceIds) || matrix.workspaceIds.length === 0) {
|
|
58
58
|
throw new Error(
|
|
59
|
-
t("matrix.error.workspaceIdsEmpty", { task: task.name })
|
|
59
|
+
t("matrix.error.workspaceIdsEmpty", { task: task.name }),
|
|
60
60
|
);
|
|
61
61
|
}
|
|
62
62
|
|
|
@@ -70,13 +70,13 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
|
70
70
|
t("matrix.error.workspaceMissing", {
|
|
71
71
|
task: task.name,
|
|
72
72
|
workspace: workspaceId,
|
|
73
|
-
})
|
|
73
|
+
}),
|
|
74
74
|
);
|
|
75
75
|
}
|
|
76
76
|
const name = matrixCloneName(task.name, workspace.name);
|
|
77
77
|
if (usedNames.has(name.toLowerCase())) {
|
|
78
78
|
throw new Error(
|
|
79
|
-
t("matrix.error.duplicateCloneName", { task: task.name, name })
|
|
79
|
+
t("matrix.error.duplicateCloneName", { task: task.name, name }),
|
|
80
80
|
);
|
|
81
81
|
}
|
|
82
82
|
usedNames.add(name.toLowerCase());
|
|
@@ -123,7 +123,7 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
|
|
|
123
123
|
|
|
124
124
|
if (clones.length === 0) {
|
|
125
125
|
throw new Error(
|
|
126
|
-
t("matrix.error.cloneCreation", { task: task.name })
|
|
126
|
+
t("matrix.error.cloneCreation", { task: task.name }),
|
|
127
127
|
);
|
|
128
128
|
}
|
|
129
129
|
return clones;
|
|
@@ -189,7 +189,7 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
|
|
|
189
189
|
const successCount = results.filter((r) => r.status === "success").length;
|
|
190
190
|
const errorCount = results.filter((r) => r.status === "error").length;
|
|
191
191
|
const pendingCount = results.filter(
|
|
192
|
-
(r) => r.status !== "success" && r.status !== "error" && r.status !== "partial"
|
|
192
|
+
(r) => r.status !== "success" && r.status !== "error" && r.status !== "partial",
|
|
193
193
|
).length;
|
|
194
194
|
|
|
195
195
|
let status: MatrixAggregate["status"];
|
|
@@ -217,9 +217,9 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
|
|
|
217
217
|
}) +
|
|
218
218
|
(firstError?.error
|
|
219
219
|
? t("matrix.aggregate.stoppedFirst", {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
220
|
+
name: firstError.name,
|
|
221
|
+
error: firstError.error,
|
|
222
|
+
})
|
|
223
223
|
: "");
|
|
224
224
|
} else {
|
|
225
225
|
status = "partial";
|
|
@@ -256,7 +256,7 @@ export interface MatrixRunResult {
|
|
|
256
256
|
/** Эффективный лимит одновременных клонов матрицы (Спринт 17). */
|
|
257
257
|
export function resolveMatrixConcurrency(
|
|
258
258
|
matrix: MatrixConfig | undefined,
|
|
259
|
-
totalClones: number
|
|
259
|
+
totalClones: number,
|
|
260
260
|
): number {
|
|
261
261
|
const total = Math.max(1, totalClones);
|
|
262
262
|
if (!matrix) return total;
|
|
@@ -336,14 +336,14 @@ export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult>
|
|
|
336
336
|
console.log(
|
|
337
337
|
`[matrix] ${task.name}: не удалось сохранить очередь: ${
|
|
338
338
|
err instanceof Error ? err.message : String(err)
|
|
339
|
-
}
|
|
339
|
+
}`,
|
|
340
340
|
);
|
|
341
341
|
}
|
|
342
342
|
|
|
343
343
|
console.log(
|
|
344
344
|
`[matrix] ${task.name}: strategy=${strategy}, failureMode=${failureMode}, ` +
|
|
345
345
|
`concurrency=${concurrency}, started=${started.length}, skipped=${skipped.length}, ` +
|
|
346
|
-
`queued=${queueToSave.length}, errors=${errors.length}
|
|
346
|
+
`queued=${queueToSave.length}, errors=${errors.length}`,
|
|
347
347
|
);
|
|
348
348
|
|
|
349
349
|
return {
|
|
@@ -363,7 +363,7 @@ export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult>
|
|
|
363
363
|
* Возвращает имя запущенного клона или undefined.
|
|
364
364
|
*/
|
|
365
365
|
export async function advanceSequentialMatrix(
|
|
366
|
-
cloneName: string
|
|
366
|
+
cloneName: string,
|
|
367
367
|
): Promise<string | undefined> {
|
|
368
368
|
const clone = getTask(cloneName);
|
|
369
369
|
if (!clone?.matrixParentId) return undefined;
|
|
@@ -415,7 +415,7 @@ export async function advanceSequentialMatrix(
|
|
|
415
415
|
* Возвращает имена запущенных клонов.
|
|
416
416
|
*/
|
|
417
417
|
export async function advanceMatrixAfterClone(
|
|
418
|
-
cloneName: string
|
|
418
|
+
cloneName: string,
|
|
419
419
|
): Promise<string[]> {
|
|
420
420
|
const sequentialNext = await advanceSequentialMatrix(cloneName);
|
|
421
421
|
if (sequentialNext) return [sequentialNext];
|
|
@@ -433,7 +433,7 @@ export async function advanceMatrixAfterClone(
|
|
|
433
433
|
const clones = listMatrixClones(parent.name);
|
|
434
434
|
const concurrency = resolveMatrixConcurrency(parent.matrix, clones.length);
|
|
435
435
|
const running = clones.filter(
|
|
436
|
-
(item) => latestCloneStatus(item.name).status === "running"
|
|
436
|
+
(item) => latestCloneStatus(item.name).status === "running",
|
|
437
437
|
).length;
|
|
438
438
|
let slots = Math.max(0, concurrency - running);
|
|
439
439
|
if (slots === 0) return [];
|
|
@@ -453,7 +453,7 @@ export async function advanceMatrixAfterClone(
|
|
|
453
453
|
} catch (err: any) {
|
|
454
454
|
const message = err instanceof Error ? err.message : String(err);
|
|
455
455
|
console.log(
|
|
456
|
-
`[matrix] ${parent.name}: не удалось запустить из очереди ${nextName}: ${message}
|
|
456
|
+
`[matrix] ${parent.name}: не удалось запустить из очереди ${nextName}: ${message}`,
|
|
457
457
|
);
|
|
458
458
|
// Попытка запуска «съедает» слот: иначе при недоступном бэкенде
|
|
459
459
|
// цикл уйдёт по всей очереди, проигнорировав лимит.
|
|
@@ -471,7 +471,7 @@ export async function advanceMatrixAfterClone(
|
|
|
471
471
|
console.log(
|
|
472
472
|
`[matrix] ${parent.name}: не удалось сохранить очередь: ${
|
|
473
473
|
err instanceof Error ? err.message : String(err)
|
|
474
|
-
}
|
|
474
|
+
}`,
|
|
475
475
|
);
|
|
476
476
|
}
|
|
477
477
|
|
|
@@ -578,7 +578,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
|
578
578
|
const desired = expandMatrixTask(parent);
|
|
579
579
|
const existing = listMatrixClones(parent.name);
|
|
580
580
|
const byName = new Map(
|
|
581
|
-
existing.map((definition) => [definition.name.toLowerCase(), definition])
|
|
581
|
+
existing.map((definition) => [definition.name.toLowerCase(), definition]),
|
|
582
582
|
);
|
|
583
583
|
const desiredNames = new Set(desired.map((definition) => definition.name.toLowerCase()));
|
|
584
584
|
|
|
@@ -601,7 +601,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
|
601
601
|
running.push(current.name);
|
|
602
602
|
if (cloneSignature(current) !== cloneSignature(wanted)) {
|
|
603
603
|
warnings.push(
|
|
604
|
-
t("matrix.clone.runningChanges", { name: current.name })
|
|
604
|
+
t("matrix.clone.runningChanges", { name: current.name }),
|
|
605
605
|
);
|
|
606
606
|
}
|
|
607
607
|
continue;
|
|
@@ -617,7 +617,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
|
|
|
617
617
|
if (latest.status === "running") {
|
|
618
618
|
running.push(current.name);
|
|
619
619
|
warnings.push(
|
|
620
|
-
t("matrix.clone.runningDeletion", { name: current.name })
|
|
620
|
+
t("matrix.clone.runningDeletion", { name: current.name }),
|
|
621
621
|
);
|
|
622
622
|
continue;
|
|
623
623
|
}
|
|
@@ -652,7 +652,7 @@ export interface MatrixSyncResult {
|
|
|
652
652
|
*/
|
|
653
653
|
export async function syncMatrixFamily(
|
|
654
654
|
parent: TaskDefinition,
|
|
655
|
-
hooks: MatrixSyncHooks = {}
|
|
655
|
+
hooks: MatrixSyncHooks = {},
|
|
656
656
|
): Promise<MatrixSyncResult> {
|
|
657
657
|
const plan = planMatrixSync(parent);
|
|
658
658
|
|
|
@@ -680,7 +680,7 @@ export async function syncMatrixFamily(
|
|
|
680
680
|
|
|
681
681
|
/** Имя родителя по имени агрегатора (`<parent>-matrix-complete`). */
|
|
682
682
|
export function matrixParentOfCompleteTask(
|
|
683
|
-
taskName: string
|
|
683
|
+
taskName: string,
|
|
684
684
|
): string | undefined {
|
|
685
685
|
const trimmed = taskName.trim();
|
|
686
686
|
if (!isMatrixCompleteName(trimmed)) return undefined;
|
|
@@ -698,7 +698,7 @@ export interface MatrixFamilyPlan {
|
|
|
698
698
|
}
|
|
699
699
|
|
|
700
700
|
export function planMatrixFamilyDelete(
|
|
701
|
-
taskName: string
|
|
701
|
+
taskName: string,
|
|
702
702
|
): MatrixFamilyPlan | undefined {
|
|
703
703
|
const definition = getTask(taskName);
|
|
704
704
|
if (!definition?.matrix) return undefined;
|
|
@@ -715,7 +715,7 @@ export function planMatrixFamilyDelete(
|
|
|
715
715
|
* Возвращает текст ошибки или undefined, если удаление разрешено.
|
|
716
716
|
*/
|
|
717
717
|
export function getMatrixDeletionGuard(
|
|
718
|
-
taskName: string
|
|
718
|
+
taskName: string,
|
|
719
719
|
): string | undefined {
|
|
720
720
|
const definition = getTask(taskName);
|
|
721
721
|
const parentId = definition?.matrixParentId?.trim();
|
|
@@ -773,7 +773,7 @@ export interface MatrixCancelResult {
|
|
|
773
773
|
*/
|
|
774
774
|
export async function cancelPendingMatrixClones(
|
|
775
775
|
parentName: string,
|
|
776
|
-
reason = t("matrix.cancel.defaultReason")
|
|
776
|
+
reason = t("matrix.cancel.defaultReason"),
|
|
777
777
|
): Promise<MatrixCancelResult> {
|
|
778
778
|
const parent = getTask(parentName);
|
|
779
779
|
if (!parent?.matrix) {
|
|
@@ -793,7 +793,7 @@ export async function cancelPendingMatrixClones(
|
|
|
793
793
|
console.log(
|
|
794
794
|
`[matrix] ${parent.name}: не удалось очистить очередь: ${
|
|
795
795
|
err instanceof Error ? err.message : String(err)
|
|
796
|
-
}
|
|
796
|
+
}`,
|
|
797
797
|
);
|
|
798
798
|
}
|
|
799
799
|
}
|
|
@@ -824,14 +824,14 @@ export async function cancelPendingMatrixClones(
|
|
|
824
824
|
undefined,
|
|
825
825
|
clone.model ?? undefined,
|
|
826
826
|
"skipped",
|
|
827
|
-
"skipped"
|
|
827
|
+
"skipped",
|
|
828
828
|
);
|
|
829
829
|
cancelled.push(clone.name);
|
|
830
830
|
} catch (err: any) {
|
|
831
831
|
console.log(
|
|
832
832
|
`[matrix] ${parent.name}: не удалось записать отмену клона ${clone.name}: ${
|
|
833
833
|
err instanceof Error ? err.message : String(err)
|
|
834
|
-
}
|
|
834
|
+
}`,
|
|
835
835
|
);
|
|
836
836
|
}
|
|
837
837
|
}
|
|
@@ -860,7 +860,7 @@ export function cloneFileKey(cloneName: string): string {
|
|
|
860
860
|
* success/error/partial) и запускает matrix-complete, если он создан.
|
|
861
861
|
*/
|
|
862
862
|
export async function finalizeMatrixIfComplete(
|
|
863
|
-
cloneName: string
|
|
863
|
+
cloneName: string,
|
|
864
864
|
): Promise<MatrixAggregate | undefined> {
|
|
865
865
|
const clone = getTask(cloneName);
|
|
866
866
|
const parentId = clone?.matrixParentId?.trim();
|
|
@@ -908,7 +908,7 @@ export async function finalizeMatrixIfComplete(
|
|
|
908
908
|
undefined,
|
|
909
909
|
parent.model ?? undefined,
|
|
910
910
|
"skipped",
|
|
911
|
-
"skipped"
|
|
911
|
+
"skipped",
|
|
912
912
|
);
|
|
913
913
|
// Спринт 20: уведомление о завершении матрицы (partial / все упали / успех).
|
|
914
914
|
void notifyMatrixCompletion({
|
|
@@ -923,7 +923,7 @@ export async function finalizeMatrixIfComplete(
|
|
|
923
923
|
console.log(
|
|
924
924
|
`[matrix] ${parent.name}: не удалось записать агрегат: ${
|
|
925
925
|
err instanceof Error ? err.message : String(err)
|
|
926
|
-
}
|
|
926
|
+
}`,
|
|
927
927
|
);
|
|
928
928
|
}
|
|
929
929
|
|
|
@@ -937,7 +937,7 @@ export async function finalizeMatrixIfComplete(
|
|
|
937
937
|
console.log(
|
|
938
938
|
`[matrix] ${parent.name}: не удалось запустить агрегатор: ${
|
|
939
939
|
err instanceof Error ? err.message : String(err)
|
|
940
|
-
}
|
|
940
|
+
}`,
|
|
941
941
|
);
|
|
942
942
|
}
|
|
943
943
|
}
|
|
@@ -52,7 +52,7 @@ $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\power
|
|
|
52
52
|
*/
|
|
53
53
|
export function buildNativeNotificationCommand(
|
|
54
54
|
platform: NodeJS.Platform,
|
|
55
|
-
message: NativeNotificationMessage
|
|
55
|
+
message: NativeNotificationMessage,
|
|
56
56
|
): NativeCommand {
|
|
57
57
|
const title = (message.title ?? "OpenCode Scheduler").trim() || "OpenCode Scheduler";
|
|
58
58
|
const body = String(message.body ?? "");
|
|
@@ -129,7 +129,7 @@ export interface NativeSendResult {
|
|
|
129
129
|
*/
|
|
130
130
|
export async function sendNativeNotification(
|
|
131
131
|
message: NativeNotificationMessage,
|
|
132
|
-
options: SendNativeOptions = {}
|
|
132
|
+
options: SendNativeOptions = {},
|
|
133
133
|
): Promise<NativeSendResult> {
|
|
134
134
|
const platform = options.platform ?? process.platform;
|
|
135
135
|
const command = buildNativeNotificationCommand(platform, message);
|
package/src/core/one-shot.ts
CHANGED
|
@@ -52,7 +52,7 @@ function asDelaySeconds(value: unknown): number | undefined | "invalid" {
|
|
|
52
52
|
*/
|
|
53
53
|
export function normalizeOneShotRunAt(
|
|
54
54
|
input: OneShotInput,
|
|
55
|
-
nowMs: number = Date.now()
|
|
55
|
+
nowMs: number = Date.now(),
|
|
56
56
|
): OneShotNormalization {
|
|
57
57
|
const rawRunAt =
|
|
58
58
|
typeof input.runAt === "string" ? input.runAt.trim() : undefined;
|
|
@@ -73,7 +73,7 @@ export function normalizeOneShotRunAt(
|
|
|
73
73
|
return {
|
|
74
74
|
ok: false,
|
|
75
75
|
error:
|
|
76
|
-
|
|
76
|
+
"runAt должен быть датой в формате ISO-8601, например " +
|
|
77
77
|
`2026-12-01T09:00:00Z (получено «${rawRunAt}»).`,
|
|
78
78
|
};
|
|
79
79
|
}
|
|
@@ -82,7 +82,7 @@ export function normalizeOneShotRunAt(
|
|
|
82
82
|
ok: false,
|
|
83
83
|
error:
|
|
84
84
|
`runAt должен быть в будущем (получено «${rawRunAt}»). ` +
|
|
85
|
-
|
|
85
|
+
"Для запуска сразу используйте run_task_now.",
|
|
86
86
|
};
|
|
87
87
|
}
|
|
88
88
|
return {
|
|
@@ -114,24 +114,48 @@ function pad(value: number): string {
|
|
|
114
114
|
/**
|
|
115
115
|
* Формат даты/времени для schtasks /sd и /st.
|
|
116
116
|
*
|
|
117
|
-
* Windows Task Scheduler ожидает дату в формате текущей локали.
|
|
118
|
-
*
|
|
119
|
-
*
|
|
117
|
+
* Windows Task Scheduler ожидает дату в формате текущей локали. На русской
|
|
118
|
+
* Windows — DD.MM.YYYY, на английской — M/d/yyyy и т.д. Жёсткий DD.MM.YYYY
|
|
119
|
+
* ломает создание one-shot и file/git/mcp-задач на не-RU Windows (P1-8).
|
|
120
|
+
* Вызывающий код (windows.ts) передаёт `dateFormat`, полученный из системной
|
|
121
|
+
* локали через PowerShell `(Get-Culture).DateTimeFormat.ShortDatePattern`.
|
|
122
|
+
*
|
|
123
|
+
* @param runAt — ISO-8601 время запуска.
|
|
124
|
+
* @param dateFormat — шаблон даты локали (например, "dd.MM.yyyy" или "M/d/yyyy").
|
|
125
|
+
* Если не задан — используется DD.MM.YYYY (по умолчанию RU).
|
|
120
126
|
*/
|
|
121
127
|
export function buildWindowsOneShotFlags(
|
|
122
|
-
runAt: string
|
|
128
|
+
runAt: string,
|
|
129
|
+
dateFormat?: string,
|
|
123
130
|
): ["/sc", "ONCE", "/sd", string, "/st", string] {
|
|
124
131
|
const date = new Date(runAt);
|
|
132
|
+
const sd = dateFormat ? formatDateByLocalePattern(date, dateFormat) : `${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`;
|
|
125
133
|
return [
|
|
126
134
|
"/sc",
|
|
127
135
|
"ONCE",
|
|
128
136
|
"/sd",
|
|
129
|
-
|
|
137
|
+
sd,
|
|
130
138
|
"/st",
|
|
131
139
|
`${pad(date.getHours())}:${pad(date.getMinutes())}`,
|
|
132
140
|
];
|
|
133
141
|
}
|
|
134
142
|
|
|
143
|
+
/**
|
|
144
|
+
* Форматирует Date по шаблону локали Windows (.NET-формат, как возвращает
|
|
145
|
+
* (Get-Culture).DateTimeFormat.ShortDatePattern). Поддерживает d/dd, M/MM,
|
|
146
|
+
* y/yy/yyyy. Неизвестные символы копируются как есть.
|
|
147
|
+
*/
|
|
148
|
+
export function formatDateByLocalePattern(date: Date, pattern: string): string {
|
|
149
|
+
const pad2 = (v: number) => String(v).padStart(2, "0");
|
|
150
|
+
return pattern
|
|
151
|
+
.replace(/yyyy/g, String(date.getFullYear()))
|
|
152
|
+
.replace(/yy/g, String(date.getFullYear()).slice(-2))
|
|
153
|
+
.replace(/MM/g, pad2(date.getMonth() + 1))
|
|
154
|
+
.replace(/M/g, String(date.getMonth() + 1))
|
|
155
|
+
.replace(/dd/g, pad2(date.getDate()))
|
|
156
|
+
.replace(/d/g, String(date.getDate()));
|
|
157
|
+
}
|
|
158
|
+
|
|
135
159
|
/** Формат `at -t`: YYYYMMDDHHMM в локальном времени системы. */
|
|
136
160
|
export function buildAtTimestamp(runAt: string): string {
|
|
137
161
|
const date = new Date(runAt);
|
|
@@ -144,9 +168,35 @@ export function buildAtTimestamp(runAt: string): string {
|
|
|
144
168
|
);
|
|
145
169
|
}
|
|
146
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Bash-команда для one-shot в launchd.
|
|
173
|
+
*
|
|
174
|
+
* StartCalendarInterval не поддерживает год: без защиты задача с runAt
|
|
175
|
+
* дальше чем через год сработала бы в ближайшую годовщину, а после
|
|
176
|
+
* выполнения — повторно через год. Гейт сравнивает now с runAt и ставит
|
|
177
|
+
* маркер, привязанный ко времени запуска.
|
|
178
|
+
*/
|
|
179
|
+
export function buildOneShotGuardCommand(
|
|
180
|
+
command: string,
|
|
181
|
+
runAt: string,
|
|
182
|
+
stampPath: string,
|
|
183
|
+
): string {
|
|
184
|
+
const epoch = Math.floor(new Date(runAt).getTime() / 1000);
|
|
185
|
+
const quote = (value: string) => `'${value.replace(/'/g, "'\\''")}'`;
|
|
186
|
+
return [
|
|
187
|
+
`stamp=${quote(stampPath)}`,
|
|
188
|
+
"[ -f \"$stamp\" ] && exit 0",
|
|
189
|
+
`[ "$(date +%s)" -lt ${epoch} ] && exit 0`,
|
|
190
|
+
"mkdir -p \"$(dirname \"$stamp\")\" 2>/dev/null || true",
|
|
191
|
+
": > \"$stamp\" 2>/dev/null || true",
|
|
192
|
+
command,
|
|
193
|
+
].join("; ");
|
|
194
|
+
}
|
|
195
|
+
|
|
147
196
|
/**
|
|
148
197
|
* StartCalendarInterval для launchd. launchd не поддерживает год, поэтому
|
|
149
|
-
*
|
|
198
|
+
* обёртка дополнительно проверяет runAt и ставит маркер выполнения
|
|
199
|
+
* (см. buildOneShotGuardCommand).
|
|
150
200
|
*/
|
|
151
201
|
export function buildLaunchdCalendar(runAt: string): {
|
|
152
202
|
Month: number;
|
|
@@ -166,13 +216,13 @@ export function buildLaunchdCalendar(runAt: string): {
|
|
|
166
216
|
/** Команда самоочистки launchd-агента после единственного запуска. */
|
|
167
217
|
export function buildLaunchdOneShotCleanup(
|
|
168
218
|
sanitizedName: string,
|
|
169
|
-
profile
|
|
219
|
+
profile = "default",
|
|
170
220
|
): string {
|
|
171
221
|
const label = launchdLabel(sanitizedName, profile);
|
|
172
222
|
return (
|
|
173
|
-
|
|
223
|
+
"launchctl bootout \"gui/$(id -u)\" " +
|
|
174
224
|
`"$HOME/Library/LaunchAgents/${label}.plist" ` +
|
|
175
|
-
|
|
225
|
+
">/dev/null 2>&1 || true"
|
|
176
226
|
);
|
|
177
227
|
}
|
|
178
228
|
|
|
@@ -181,7 +231,7 @@ export function buildLaunchdOneShotCleanup(
|
|
|
181
231
|
* `com.opencode.scheduler.<name>`; у не-default профиля свой префикс, чтобы
|
|
182
232
|
* одноимённые задачи разных профилей не затирали plist друг друга.
|
|
183
233
|
*/
|
|
184
|
-
export function launchdLabel(sanitizedName: string, profile
|
|
234
|
+
export function launchdLabel(sanitizedName: string, profile = "default"): string {
|
|
185
235
|
const base = `com.opencode.scheduler.${sanitizedName}`;
|
|
186
236
|
if (profile === "default") return base;
|
|
187
237
|
const scope = profile.replace(/[^A-Za-z0-9_.-]/g, "-");
|