agent-steward 0.0.4 → 0.0.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 +134 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +52 -7
- package/ROADMAP-STRATEGY.md +21 -18
- package/ROADMAP.md +140 -159
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +351 -0
- package/dist/core/execution.d.ts +203 -0
- package/dist/core/execution.d.ts.map +1 -0
- package/dist/core/execution.js +309 -0
- package/dist/core/gate-integrity.d.ts +35 -0
- package/dist/core/gate-integrity.d.ts.map +1 -0
- package/dist/core/gate-integrity.js +132 -0
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +14 -2
- package/dist/core/guard-run.d.ts +4 -0
- package/dist/core/guard-run.d.ts.map +1 -0
- package/dist/core/guard-run.js +101 -0
- package/dist/core/guard.d.ts +52 -0
- package/dist/core/guard.d.ts.map +1 -0
- package/dist/core/guard.js +362 -0
- package/dist/core/lock.d.ts +41 -0
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +141 -29
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +75 -15
- package/dist/core/mission.d.ts +83 -0
- package/dist/core/mission.d.ts.map +1 -0
- package/dist/core/mission.js +334 -0
- package/dist/core/pipeline-apply.d.ts +38 -0
- package/dist/core/pipeline-apply.d.ts.map +1 -0
- package/dist/core/pipeline-apply.js +117 -0
- package/dist/core/pipeline-io.d.ts +13 -0
- package/dist/core/pipeline-io.d.ts.map +1 -0
- package/dist/core/pipeline-io.js +64 -0
- package/dist/core/pipeline-map.d.ts +46 -0
- package/dist/core/pipeline-map.d.ts.map +1 -0
- package/dist/core/pipeline-map.js +196 -0
- package/dist/core/pipeline-spec.d.ts +109 -0
- package/dist/core/pipeline-spec.d.ts.map +1 -0
- package/dist/core/pipeline-spec.js +554 -0
- package/dist/core/ps-wrapper.d.ts +19 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +250 -62
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +130 -29
- package/dist/core/router/rules.d.ts.map +1 -1
- package/dist/core/router/rules.js +6 -0
- package/dist/core/scheduler/linux.d.ts +8 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +34 -9
- package/dist/core/scheduler/mac.d.ts +44 -2
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +126 -15
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +15 -12
- package/dist/core/structured-log.d.ts +7 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/worktree-run.d.ts +4 -0
- package/dist/core/worktree-run.d.ts.map +1 -0
- package/dist/core/worktree-run.js +164 -0
- package/dist/core/worktree.d.ts +115 -0
- package/dist/core/worktree.d.ts.map +1 -0
- package/dist/core/worktree.js +462 -0
- package/dist/core/wrappers/bash.d.ts +17 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +175 -24
- package/dist/db/capability-repo.d.ts +43 -2
- package/dist/db/capability-repo.d.ts.map +1 -1
- package/dist/db/capability-repo.js +96 -11
- package/dist/db/history-repo.d.ts +38 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +88 -25
- package/dist/db/metrics-repo.js +2 -2
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +5 -4
- package/dist/db/run-journal.d.ts +33 -5
- package/dist/db/run-journal.d.ts.map +1 -1
- package/dist/db/run-journal.js +78 -14
- package/dist/db/run-resume.d.ts +5 -0
- package/dist/db/run-resume.d.ts.map +1 -1
- package/dist/db/run-resume.js +9 -2
- package/dist/db/runs-repo.d.ts +19 -2
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +22 -6
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +63 -2
- package/dist/history.d.ts +1 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/i18n.d.ts +5 -0
- package/dist/i18n.d.ts.map +1 -1
- package/dist/i18n.js +11 -4
- package/dist/index.d.ts +136 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +378 -14
- package/dist/notifications.d.ts +22 -0
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +36 -8
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +25 -4
- package/dist/rpc.d.ts +246 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +117 -0
- package/dist/server.d.ts +15 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -18
- package/dist/settings.d.ts +2 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +3 -3
- package/dist/shared/jobs-view.d.ts +1 -1
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/shared/jobs-view.js +2 -0
- package/dist/task-transfer.d.ts +16 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +16 -0
- package/docs/ARCHITECTURE.md +281 -65
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/CONCEPT.md +18 -4
- package/docs/CROSS_PLATFORM.ru.md +20 -0
- package/docs/CROSS_PLATFORM.zh.md +18 -0
- package/docs/EXECUTION-LOOP.md +22 -7
- package/docs/FEATURES.md +65 -4
- package/docs/FEATURES.zh.md +52 -4
- package/docs/MIGRATION.md +2 -2
- package/docs/PIPELINE.md +293 -0
- package/docs/README.ru.md +42 -3
- package/docs/README.zh.md +43 -3
- package/docs/SAFETY.md +23 -3
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +17 -1
- package/locales/ru.json +17 -1
- package/locales/zh.json +17 -1
- package/opencode.pipeline.yaml +35 -0
- package/package.json +23 -4
- package/scripts/test-home.mjs +83 -0
- package/src/cli.ts +412 -0
- package/src/core/dry-run.ts +2 -2
- package/src/core/execution.ts +538 -0
- package/src/core/file-watcher.ts +2 -2
- package/src/core/gate-integrity.ts +160 -0
- package/src/core/git-trigger.ts +18 -5
- package/src/core/guard-run.ts +119 -0
- package/src/core/guard.ts +431 -0
- package/src/core/lock.ts +178 -37
- package/src/core/matrix.ts +95 -50
- package/src/core/mission.ts +485 -0
- package/src/core/native-notify.ts +1 -1
- package/src/core/pipeline-apply.ts +158 -0
- package/src/core/pipeline-io.ts +79 -0
- package/src/core/pipeline-map.ts +264 -0
- package/src/core/pipeline-spec.ts +775 -0
- package/src/core/ps-wrapper.ts +263 -63
- package/src/core/record-history.ts +164 -77
- package/src/core/router/rules.ts +6 -0
- package/src/core/schedule-gate.ts +1 -1
- package/src/core/scheduler/at-fallback.ts +1 -1
- package/src/core/scheduler/linux.ts +40 -11
- package/src/core/scheduler/logs.ts +2 -2
- package/src/core/scheduler/mac.ts +174 -14
- package/src/core/scheduler/registry.ts +2 -2
- package/src/core/scheduler/windows.ts +19 -15
- package/src/core/secrets.ts +8 -8
- package/src/core/structured-log.ts +22 -5
- package/src/core/telegram.ts +2 -2
- package/src/core/triage-worker.ts +7 -7
- package/src/core/triage.ts +2 -2
- package/src/core/worktree-run.ts +199 -0
- package/src/core/worktree.ts +600 -0
- package/src/core/wrappers/bash.ts +190 -23
- package/src/db/capability-repo.ts +127 -10
- package/src/db/history-repo.ts +129 -22
- package/src/db/metrics-repo.ts +2 -2
- package/src/db/recovery.ts +5 -4
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +17 -1
- package/src/db/runs-repo.ts +36 -6
- package/src/db/schema.ts +65 -2
- package/src/gui.tsx +177 -13
- package/src/history.ts +1 -1
- package/src/i18n.ts +12 -4
- package/src/index.ts +524 -4
- package/src/notifications.ts +38 -8
- package/src/profiles.ts +26 -4
- package/src/rpc.ts +128 -0
- package/src/server.ts +94 -18
- package/src/settings.ts +5 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +31 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
3
4
|
import { pathToFileURL } from "node:url";
|
|
4
5
|
import { runTaskNow } from "./scheduler/run-now.js";
|
|
5
6
|
import { createSchedulerBackend } from "./scheduler/index.js";
|
|
@@ -14,8 +15,37 @@ import {
|
|
|
14
15
|
advanceMatrixAfterClone,
|
|
15
16
|
finalizeMatrixIfComplete,
|
|
16
17
|
} from "./matrix.js";
|
|
18
|
+
import { appendStructuredLog } from "./structured-log.js";
|
|
17
19
|
|
|
18
|
-
type Status = "success" | "error" | "timeout";
|
|
20
|
+
type Status = "success" | "error" | "timeout" | "skipped";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Диагностика рекордера пишется в runs.jsonl: цепочки, DAG, повторы и
|
|
24
|
+
* one-shot-очистка иначе не видны в машиночитаемом логе. Human-readable
|
|
25
|
+
* вывод остаётся только в логе задачи; stdout `--start` не трогаем — обёртка
|
|
26
|
+
* читает оттуда runId.
|
|
27
|
+
*/
|
|
28
|
+
function logRecorderEvent(
|
|
29
|
+
event: string,
|
|
30
|
+
task: string,
|
|
31
|
+
details: {
|
|
32
|
+
runId?: number;
|
|
33
|
+
status?: string;
|
|
34
|
+
error?: string;
|
|
35
|
+
reason?: string;
|
|
36
|
+
nextTask?: string;
|
|
37
|
+
} = {},
|
|
38
|
+
): void {
|
|
39
|
+
appendStructuredLog({
|
|
40
|
+
event,
|
|
41
|
+
task,
|
|
42
|
+
runId: details.runId,
|
|
43
|
+
status: details.status,
|
|
44
|
+
error: details.error,
|
|
45
|
+
reason: details.reason,
|
|
46
|
+
nextTask: details.nextTask,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
19
49
|
|
|
20
50
|
/** Префикс ключа настроек со счётчиком повторов конкретной задачи. */
|
|
21
51
|
const RETRY_STATE_PREFIX = "retry_state:";
|
|
@@ -132,12 +162,11 @@ async function triggerTask(taskName: string): Promise<boolean> {
|
|
|
132
162
|
try {
|
|
133
163
|
await runTaskNow(taskName);
|
|
134
164
|
return true;
|
|
135
|
-
} catch (err:
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
);
|
|
165
|
+
} catch (err: unknown) {
|
|
166
|
+
logRecorderEvent("chain.trigger_failed", taskName, {
|
|
167
|
+
nextTask: taskName,
|
|
168
|
+
error: err instanceof Error ? err.message : String(err),
|
|
169
|
+
});
|
|
141
170
|
return false;
|
|
142
171
|
}
|
|
143
172
|
}
|
|
@@ -167,7 +196,7 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
167
196
|
|
|
168
197
|
if (remaining === null) {
|
|
169
198
|
deleteSetting(key);
|
|
170
|
-
|
|
199
|
+
logRecorderEvent("retry.exhausted", taskName, { reason: "retries exhausted" });
|
|
171
200
|
return false;
|
|
172
201
|
}
|
|
173
202
|
|
|
@@ -183,17 +212,14 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
183
212
|
});
|
|
184
213
|
child.unref();
|
|
185
214
|
|
|
186
|
-
|
|
187
|
-
`
|
|
188
|
-
|
|
189
|
-
);
|
|
215
|
+
logRecorderEvent("retry.scheduled", taskName, {
|
|
216
|
+
reason: `delay=${delay}s, remaining=${remaining}`,
|
|
217
|
+
});
|
|
190
218
|
return true;
|
|
191
|
-
} catch (err:
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
}`,
|
|
196
|
-
);
|
|
219
|
+
} catch (err: unknown) {
|
|
220
|
+
logRecorderEvent("retry.schedule_failed", taskName, {
|
|
221
|
+
error: err instanceof Error ? err.message : String(err),
|
|
222
|
+
});
|
|
197
223
|
return false;
|
|
198
224
|
}
|
|
199
225
|
}
|
|
@@ -209,13 +235,11 @@ async function runRetry(taskName: string, delaySec: number): Promise<void> {
|
|
|
209
235
|
|
|
210
236
|
try {
|
|
211
237
|
await runTaskNow(taskName);
|
|
212
|
-
|
|
213
|
-
} catch (err:
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}`,
|
|
218
|
-
);
|
|
238
|
+
logRecorderEvent("retry.started", taskName);
|
|
239
|
+
} catch (err: unknown) {
|
|
240
|
+
logRecorderEvent("retry.failed", taskName, {
|
|
241
|
+
error: err instanceof Error ? err.message : String(err),
|
|
242
|
+
});
|
|
219
243
|
}
|
|
220
244
|
}
|
|
221
245
|
|
|
@@ -333,6 +357,50 @@ async function main() {
|
|
|
333
357
|
return;
|
|
334
358
|
}
|
|
335
359
|
|
|
360
|
+
/**
|
|
361
|
+
* W-4: режим пропуска — node record-history.js --skip "<task>" "<reasonB64>" "<logFile>" [durationMs]
|
|
362
|
+
* Вызывается обёртками при срабатывании guard (код 4). Причина передаётся
|
|
363
|
+
* base64, чтобы не подставлять произвольный текст в командную строку. Пропуск
|
|
364
|
+
* попадает в историю и total-метрику, но не считается ошибкой, не шлёт
|
|
365
|
+
* уведомление, не запускает цепочки/повторы и не запускает DAG.
|
|
366
|
+
*/
|
|
367
|
+
if (first === "--skip") {
|
|
368
|
+
const taskName = second;
|
|
369
|
+
if (!taskName) process.exit(1);
|
|
370
|
+
let reason = "guard conditions not met";
|
|
371
|
+
if (third) {
|
|
372
|
+
try {
|
|
373
|
+
const decoded = Buffer.from(third, "base64").toString("utf8").trim();
|
|
374
|
+
if (decoded) reason = decoded;
|
|
375
|
+
} catch {
|
|
376
|
+
// Битая base64 — оставляем причину по умолчанию.
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
const durationMs = Math.max(0, Number(fifth) || 0);
|
|
380
|
+
const finishedAt = new Date().toISOString();
|
|
381
|
+
const startedAt = new Date(Date.now() - durationMs).toISOString();
|
|
382
|
+
const definition = getTask(taskName);
|
|
383
|
+
recordRun(
|
|
384
|
+
taskName,
|
|
385
|
+
"skipped",
|
|
386
|
+
startedAt,
|
|
387
|
+
durationMs,
|
|
388
|
+
reason,
|
|
389
|
+
null,
|
|
390
|
+
undefined,
|
|
391
|
+
undefined,
|
|
392
|
+
undefined,
|
|
393
|
+
undefined,
|
|
394
|
+
undefined,
|
|
395
|
+
finishedAt,
|
|
396
|
+
definition?.workspaceId ?? null,
|
|
397
|
+
definition?.allowedTools ?? null,
|
|
398
|
+
definition?.deniedTools ?? null,
|
|
399
|
+
);
|
|
400
|
+
await handleCompletion(taskName, "skipped", null, reason, durationMs);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
|
|
336
404
|
const parseOptionalNumber = (value?: string): number | undefined => {
|
|
337
405
|
if (!value || value === "-") return undefined;
|
|
338
406
|
const num = Number(value);
|
|
@@ -357,12 +425,20 @@ async function main() {
|
|
|
357
425
|
if (!taskName) process.exit(1);
|
|
358
426
|
const startedAt = third ?? new Date().toISOString();
|
|
359
427
|
const definition = getTask(taskName);
|
|
428
|
+
// Владелец — процесс-обёртка, запустивший recorder. Он живёт дольше
|
|
429
|
+
// короткоживущего recorder'а, поэтому именно его PID проверяет recovery.
|
|
430
|
+
const owner = {
|
|
431
|
+
pid: process.ppid && process.ppid > 0 ? process.ppid : null,
|
|
432
|
+
host: os.hostname(),
|
|
433
|
+
startedAt: new Date().toISOString(),
|
|
434
|
+
};
|
|
360
435
|
const runId = startRun(
|
|
361
436
|
taskName,
|
|
362
437
|
startedAt,
|
|
363
438
|
definition?.workspaceId ?? null,
|
|
364
439
|
definition?.allowedTools ?? null,
|
|
365
440
|
definition?.deniedTools ?? null,
|
|
441
|
+
owner,
|
|
366
442
|
);
|
|
367
443
|
console.log(String(runId));
|
|
368
444
|
return;
|
|
@@ -402,13 +478,15 @@ async function main() {
|
|
|
402
478
|
const preFlightStatus = parseHookStatus(tenth);
|
|
403
479
|
const postFlightStatus = parseHookStatus(eleventh);
|
|
404
480
|
const st: Status =
|
|
405
|
-
status === "success" ? "success" : status === "timeout" ? "timeout" : "error";
|
|
481
|
+
status === "success" ? "success" : status === "timeout" ? "timeout" : status === "skipped" ? "skipped" : "error";
|
|
406
482
|
|
|
407
483
|
const definition = getTask(taskName);
|
|
408
484
|
const chainTarget =
|
|
409
485
|
st === "success"
|
|
410
486
|
? definition?.nextTaskOnSuccess || null
|
|
411
|
-
:
|
|
487
|
+
: st === "skipped"
|
|
488
|
+
? null
|
|
489
|
+
: definition?.nextTaskOnError || null;
|
|
412
490
|
|
|
413
491
|
const completed = finishRun(
|
|
414
492
|
runId,
|
|
@@ -423,9 +501,10 @@ async function main() {
|
|
|
423
501
|
postFlightStatus,
|
|
424
502
|
);
|
|
425
503
|
if (!completed) {
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
504
|
+
logRecorderEvent("run.finish_skipped", taskName, {
|
|
505
|
+
runId,
|
|
506
|
+
reason: "already finished or not found",
|
|
507
|
+
});
|
|
429
508
|
return;
|
|
430
509
|
}
|
|
431
510
|
|
|
@@ -448,6 +527,22 @@ async function main() {
|
|
|
448
527
|
// "-" означает «данных нет» (openCode не печатал usage в лог).
|
|
449
528
|
const tokens = parseOptionalNumber(sixth);
|
|
450
529
|
const costUsd = parseOptionalNumber(seventh);
|
|
530
|
+
// B10: 11-й аргумент — лог-файл задачи. Раньше legacy-режим его не читал,
|
|
531
|
+
// поэтому при "-" в токенах/стоимости usage терялся. Парсим лог так же,
|
|
532
|
+
// как режим --finish; отсутствие файла — graceful fallback (parseUsageFromLog
|
|
533
|
+
// возвращает пустой объект и не бросает).
|
|
534
|
+
const logFile = eleventh && eleventh !== "-" ? eleventh : undefined;
|
|
535
|
+
let tokensResolved = tokens;
|
|
536
|
+
let costResolved = costUsd;
|
|
537
|
+
if ((tokensResolved === undefined || costResolved === undefined) && logFile) {
|
|
538
|
+
const usage = parseUsageFromLog(logFile);
|
|
539
|
+
if (tokensResolved === undefined && usage.tokens !== undefined) {
|
|
540
|
+
tokensResolved = usage.tokens;
|
|
541
|
+
}
|
|
542
|
+
if (costResolved === undefined && usage.costUsd !== undefined) {
|
|
543
|
+
costResolved = usage.costUsd;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
451
546
|
// Восьмой аргумент — модель; "-" означает, что модель не задана.
|
|
452
547
|
const model = eighth && eighth !== "-" ? eighth.trim() || undefined : undefined;
|
|
453
548
|
// Девятый и десятый — итоги pre/post-flight хуков.
|
|
@@ -455,13 +550,15 @@ async function main() {
|
|
|
455
550
|
const postFlightStatus = parseHookStatus(tenth);
|
|
456
551
|
|
|
457
552
|
const st: Status =
|
|
458
|
-
status === "success" ? "success" : status === "timeout" ? "timeout" : "error";
|
|
553
|
+
status === "success" ? "success" : status === "timeout" ? "timeout" : status === "skipped" ? "skipped" : "error";
|
|
459
554
|
|
|
460
555
|
const definition = getTask(taskName);
|
|
461
556
|
const chainTarget =
|
|
462
557
|
st === "success"
|
|
463
558
|
? definition?.nextTaskOnSuccess || null
|
|
464
|
-
:
|
|
559
|
+
: st === "skipped"
|
|
560
|
+
? null
|
|
561
|
+
: definition?.nextTaskOnError || null;
|
|
465
562
|
|
|
466
563
|
recordRun(
|
|
467
564
|
taskName,
|
|
@@ -470,8 +567,8 @@ async function main() {
|
|
|
470
567
|
durationMs,
|
|
471
568
|
error,
|
|
472
569
|
chainTarget,
|
|
473
|
-
|
|
474
|
-
|
|
570
|
+
tokensResolved,
|
|
571
|
+
costResolved,
|
|
475
572
|
model,
|
|
476
573
|
preFlightStatus,
|
|
477
574
|
postFlightStatus,
|
|
@@ -481,7 +578,7 @@ async function main() {
|
|
|
481
578
|
definition?.deniedTools ?? null,
|
|
482
579
|
);
|
|
483
580
|
|
|
484
|
-
await handleCompletion(taskName, st, chainTarget, error, durationMs,
|
|
581
|
+
await handleCompletion(taskName, st, chainTarget, error, durationMs, tokensResolved, costResolved);
|
|
485
582
|
}
|
|
486
583
|
|
|
487
584
|
/** Зависимости для тестируемой очистки one-shot (P2-27). */
|
|
@@ -515,16 +612,12 @@ export async function cleanupWindowsOneShotTask(
|
|
|
515
612
|
((name: string) => createSchedulerBackend().deleteTask(name));
|
|
516
613
|
try {
|
|
517
614
|
await deleteTask(taskName);
|
|
518
|
-
|
|
519
|
-
`[agent-steward] One-shot "${taskName}": задача удалена из Планировщика Windows.`,
|
|
520
|
-
);
|
|
615
|
+
logRecorderEvent("oneshot.cleaned", taskName);
|
|
521
616
|
return true;
|
|
522
|
-
} catch (err:
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
}`,
|
|
527
|
-
);
|
|
617
|
+
} catch (err: unknown) {
|
|
618
|
+
logRecorderEvent("oneshot.cleanup_failed", taskName, {
|
|
619
|
+
error: err instanceof Error ? err.message : String(err),
|
|
620
|
+
});
|
|
528
621
|
return false;
|
|
529
622
|
}
|
|
530
623
|
}
|
|
@@ -543,10 +636,13 @@ async function handleCompletion(
|
|
|
543
636
|
costUsd?: number | null,
|
|
544
637
|
): Promise<void> {
|
|
545
638
|
// Уведомление о завершении (webhook). Ошибки отправки логируются внутри
|
|
546
|
-
// и не влияют на историю, цепочки и повторы.
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
639
|
+
// и не влияют на историю, цепочки и повторы. Пропуск guard не уведомляем:
|
|
640
|
+
// для него нет отдельного шаблона, а шум в уведомлениях не нужен.
|
|
641
|
+
if (st !== "skipped") {
|
|
642
|
+
await notifyTaskCompletion(taskName, st, durationMs, error, tokens, costUsd, {
|
|
643
|
+
asyncTriage: true,
|
|
644
|
+
});
|
|
645
|
+
}
|
|
550
646
|
|
|
551
647
|
// P2-27: Windows не удаляет ONCE-задачи сам, а флаг schtasks `/z` на
|
|
552
648
|
// практике ломает создание задачи («task XML ... EndBoundary»).
|
|
@@ -559,12 +655,10 @@ async function handleCompletion(
|
|
|
559
655
|
try {
|
|
560
656
|
await advanceMatrixAfterClone(taskName);
|
|
561
657
|
await finalizeMatrixIfComplete(taskName);
|
|
562
|
-
} catch (err:
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
}`,
|
|
567
|
-
);
|
|
658
|
+
} catch (err: unknown) {
|
|
659
|
+
logRecorderEvent("matrix.error", taskName, {
|
|
660
|
+
error: err instanceof Error ? err.message : String(err),
|
|
661
|
+
});
|
|
568
662
|
}
|
|
569
663
|
|
|
570
664
|
if (st === "success") {
|
|
@@ -573,7 +667,7 @@ async function handleCompletion(
|
|
|
573
667
|
if (chainTarget) {
|
|
574
668
|
const started = await triggerTask(chainTarget);
|
|
575
669
|
if (started) {
|
|
576
|
-
|
|
670
|
+
logRecorderEvent("chain.triggered", taskName, { nextTask: chainTarget });
|
|
577
671
|
}
|
|
578
672
|
}
|
|
579
673
|
|
|
@@ -588,26 +682,23 @@ async function handleCompletion(
|
|
|
588
682
|
for (const dependent of dependents) {
|
|
589
683
|
const started = await triggerTask(dependent);
|
|
590
684
|
if (started) {
|
|
591
|
-
|
|
592
|
-
`[agent-steward] DAG: все зависимости выполнены, запущена задача "${dependent}".`,
|
|
593
|
-
);
|
|
685
|
+
logRecorderEvent("dag.triggered", taskName, { nextTask: dependent });
|
|
594
686
|
}
|
|
595
687
|
}
|
|
596
|
-
} catch (err:
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
}`,
|
|
601
|
-
);
|
|
688
|
+
} catch (err: unknown) {
|
|
689
|
+
logRecorderEvent("dag.trigger_failed", taskName, {
|
|
690
|
+
error: err instanceof Error ? err.message : String(err),
|
|
691
|
+
});
|
|
602
692
|
}
|
|
603
|
-
} else {
|
|
693
|
+
} else if (st !== "skipped") {
|
|
604
694
|
// Сначала пытаемся повторить саму задачу; компенсирующая задача запускается
|
|
605
695
|
// только когда повторы исчерпаны (или не настроены).
|
|
696
|
+
// Пропуск guard — не ошибка: повторы и компенсации не запускаются.
|
|
606
697
|
const retryScheduled = await scheduleRetry(taskName);
|
|
607
698
|
if (!retryScheduled && chainTarget) {
|
|
608
699
|
const started = await triggerTask(chainTarget);
|
|
609
700
|
if (started) {
|
|
610
|
-
|
|
701
|
+
logRecorderEvent("compensation.triggered", taskName, { nextTask: chainTarget });
|
|
611
702
|
}
|
|
612
703
|
}
|
|
613
704
|
}
|
|
@@ -616,12 +707,10 @@ async function handleCompletion(
|
|
|
616
707
|
// при достижении sessionMaxRuns. Не должна ломать завершение запуска.
|
|
617
708
|
try {
|
|
618
709
|
await rotateSessionIfNeeded(taskName);
|
|
619
|
-
} catch (err:
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
}`,
|
|
624
|
-
);
|
|
710
|
+
} catch (err: unknown) {
|
|
711
|
+
logRecorderEvent("session.rotate_failed", taskName, {
|
|
712
|
+
error: err instanceof Error ? err.message : String(err),
|
|
713
|
+
});
|
|
625
714
|
}
|
|
626
715
|
}
|
|
627
716
|
|
|
@@ -643,11 +732,9 @@ function isDirectInvocation(): boolean {
|
|
|
643
732
|
|
|
644
733
|
if (isDirectInvocation()) {
|
|
645
734
|
main().catch((err) => {
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
}`,
|
|
650
|
-
);
|
|
735
|
+
logRecorderEvent("record_history.fatal", "record-history", {
|
|
736
|
+
error: err instanceof Error ? err.message : String(err),
|
|
737
|
+
});
|
|
651
738
|
process.exit(1);
|
|
652
739
|
});
|
|
653
740
|
}
|
package/src/core/router/rules.ts
CHANGED
|
@@ -54,6 +54,12 @@ export const STATIC_ROUTE_RULES: readonly StaticRouteRule[] = Object.freeze([
|
|
|
54
54
|
executor: "local",
|
|
55
55
|
description: "Тесты запускаются локальным процессом.",
|
|
56
56
|
},
|
|
57
|
+
{
|
|
58
|
+
taskType: "mission",
|
|
59
|
+
transport: "direct",
|
|
60
|
+
executor: "local",
|
|
61
|
+
description: "Ad-hoc миссия исполняется локально через обёртку без регистрации в ОС.",
|
|
62
|
+
},
|
|
57
63
|
{
|
|
58
64
|
taskType: "apply_diff",
|
|
59
65
|
transport: "direct",
|
|
@@ -160,7 +160,7 @@ async function main(): Promise<number> {
|
|
|
160
160
|
if (cronExpr) {
|
|
161
161
|
try {
|
|
162
162
|
spec = parseCron(cronExpr);
|
|
163
|
-
} catch (err:
|
|
163
|
+
} catch (err: unknown) {
|
|
164
164
|
// Fail-closed: при повреждённом cron проверка расписания невозможна.
|
|
165
165
|
// Если пропустить её (fail-open), задача с окном/днями будет
|
|
166
166
|
// запускаться на каждом минутном тике — включая дорогие LLM-агенты.
|
|
@@ -276,7 +276,7 @@ export async function pruneStaleFallbackEntries(
|
|
|
276
276
|
try {
|
|
277
277
|
entry.atJobId = await schedule(entry, buildFallbackCommand(entry), nowMs);
|
|
278
278
|
report.rescheduled += 1;
|
|
279
|
-
} catch (err:
|
|
279
|
+
} catch (err: unknown) {
|
|
280
280
|
warn(
|
|
281
281
|
`[scheduler] Не удалось пересоздать fallback для "${entry.name}": ${
|
|
282
282
|
err instanceof Error ? err.message : String(err)
|
|
@@ -89,19 +89,27 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
89
89
|
maxBuffer: 10 * 1024 * 1024,
|
|
90
90
|
});
|
|
91
91
|
return stdout;
|
|
92
|
-
} catch (err:
|
|
93
|
-
const
|
|
92
|
+
} catch (err: unknown) {
|
|
93
|
+
const stderrRaw = (err as { stderr?: unknown } | undefined)?.stderr;
|
|
94
|
+
const stderr = typeof stderrRaw === "string" ? stderrRaw : String(stderrRaw ?? "");
|
|
94
95
|
// "no crontab for user" — это нормальное состояние. Любую другую ошибку
|
|
95
96
|
// (нет доступа, сбой crontab) нельзя превращать в пустой crontab: иначе
|
|
96
97
|
// последующая запись затрёт пользовательские задания.
|
|
97
|
-
if (/no crontab/i.test(stderr) || /no crontab/i.test(String(err?.message ?? ""))) {
|
|
98
|
+
if (/no crontab/i.test(stderr) || /no crontab/i.test(String((err as Error | undefined)?.message ?? ""))) {
|
|
98
99
|
return "";
|
|
99
100
|
}
|
|
100
|
-
throw new Error(`Не удалось прочитать crontab: ${stderr.trim() || err?.message || err}`);
|
|
101
|
+
throw new Error(`Не удалось прочитать crontab: ${stderr.trim() || (err as Error | undefined)?.message || String(err)}`);
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
|
|
104
|
-
/**
|
|
105
|
+
/**
|
|
106
|
+
* Убирает управляемый блок плагина из текста crontab.
|
|
107
|
+
*
|
|
108
|
+
* B9: удаляются только строки между парными маркерами. Незакрытый блок
|
|
109
|
+
* (маркер начала без конца) — fail-closed: бросаем ошибку, чтобы вызывающий
|
|
110
|
+
* не записал crontab и пользовательские задания после маркера не пропали.
|
|
111
|
+
* Строки вне маркеров сохраняются байт-в-байт, включая пустые.
|
|
112
|
+
*/
|
|
105
113
|
private stripBlock(content: string): string {
|
|
106
114
|
// Совместимость: до появления профилей блок назывался без суффикса.
|
|
107
115
|
// Он принадлежит профилю default; другие профили его не трогают.
|
|
@@ -119,18 +127,36 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
119
127
|
const lines = content.split(/\r?\n/);
|
|
120
128
|
const result: string[] = [];
|
|
121
129
|
let inside = false;
|
|
122
|
-
|
|
123
|
-
|
|
130
|
+
let openAt = 0;
|
|
131
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
132
|
+
const line = lines[index];
|
|
133
|
+
const trimmed = line.trim();
|
|
134
|
+
if (isBegin(trimmed)) {
|
|
135
|
+
if (inside) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
`crontab: вложенный маркер начала блока на строке ${index + 1} ` +
|
|
138
|
+
`(предыдущий блок открыт на строке ${openAt}). Файл не изменён.`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
124
141
|
inside = true;
|
|
142
|
+
openAt = index + 1;
|
|
125
143
|
continue;
|
|
126
144
|
}
|
|
127
|
-
if (isEnd(
|
|
145
|
+
if (inside && isEnd(trimmed)) {
|
|
128
146
|
inside = false;
|
|
129
147
|
continue;
|
|
130
148
|
}
|
|
149
|
+
// Строки внутри блока удаляются; всё остальное (включая «сиротский»
|
|
150
|
+
// маркер конца) остаётся без изменений.
|
|
131
151
|
if (!inside) result.push(line);
|
|
132
152
|
}
|
|
133
|
-
|
|
153
|
+
if (inside) {
|
|
154
|
+
throw new Error(
|
|
155
|
+
`crontab: незакрытый блок плагина с строки ${openAt} — ` +
|
|
156
|
+
"маркер конца не найден. Файл не изменён.",
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
return result.join("\n");
|
|
134
160
|
}
|
|
135
161
|
|
|
136
162
|
/** Записывает crontab через stdin: `crontab -`. */
|
|
@@ -165,7 +191,10 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
165
191
|
async () => {
|
|
166
192
|
const entries = await this.registry.load();
|
|
167
193
|
const current = await this.readCrontab();
|
|
168
|
-
|
|
194
|
+
// B9: stripBlock сохраняет содержимое вне маркеров. Отрезаем только
|
|
195
|
+
// хвостовые переводы строк, чтобы повторные rebuild не копили пустые
|
|
196
|
+
// строки; одна финальная добавляется ниже.
|
|
197
|
+
const base = this.stripBlock(current).replace(/\n+$/, "");
|
|
169
198
|
const block = this.renderBlock(entries);
|
|
170
199
|
|
|
171
200
|
// Пустой блок (нет задач) не пишем, чтобы не оставлять мусор в crontab.
|
|
@@ -173,7 +202,7 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
173
202
|
.split("\n")
|
|
174
203
|
.some((line) => line.trim().startsWith("# task:"));
|
|
175
204
|
const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
|
|
176
|
-
await this.writeCrontab(next);
|
|
205
|
+
await this.writeCrontab(next ? `${next}\n` : "");
|
|
177
206
|
},
|
|
178
207
|
{ timeoutMs: 15000, staleMs: 60000 },
|
|
179
208
|
);
|
|
@@ -25,8 +25,8 @@ export async function getTaskLogs(
|
|
|
25
25
|
}
|
|
26
26
|
const last = lines.slice(-Math.max(1, Math.min(limit, 1000)));
|
|
27
27
|
return { logs: last.join("\n") };
|
|
28
|
-
} catch (err:
|
|
29
|
-
if (err.code === "ENOENT") {
|
|
28
|
+
} catch (err: unknown) {
|
|
29
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
30
30
|
return {
|
|
31
31
|
logs: "",
|
|
32
32
|
error: `Лог задачи "${name}" не найден по пути ${logPath} (задача ещё не запускалась).`,
|