agent-steward 0.0.3 → 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 +154 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +54 -9
- package/ROADMAP-STRATEGY.md +23 -20
- package/ROADMAP.md +140 -143
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +351 -0
- package/dist/core/dlq-api.d.ts +44 -0
- package/dist/core/dlq-api.d.ts.map +1 -0
- package/dist/core/dlq-api.js +68 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +18 -1
- 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 +61 -4
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +213 -26
- 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/one-shot.d.ts +5 -1
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +33 -8
- package/dist/core/opencode-cli.d.ts +28 -0
- package/dist/core/opencode-cli.d.ts.map +1 -0
- package/dist/core/opencode-cli.js +74 -0
- package/dist/core/opencode-models.d.ts +62 -0
- package/dist/core/opencode-models.d.ts.map +1 -0
- package/dist/core/opencode-models.js +277 -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 +261 -63
- package/dist/core/record-history.d.ts +15 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +183 -58
- package/dist/core/router/dispatch.d.ts +36 -0
- package/dist/core/router/dispatch.d.ts.map +1 -0
- package/dist/core/router/dispatch.js +59 -0
- package/dist/core/router/escalation.d.ts +47 -0
- package/dist/core/router/escalation.d.ts.map +1 -0
- package/dist/core/router/escalation.js +87 -0
- package/dist/core/router/planner.d.ts +53 -0
- package/dist/core/router/planner.d.ts.map +1 -0
- package/dist/core/router/planner.js +113 -0
- package/dist/core/router/rules.d.ts +46 -0
- package/dist/core/router/rules.d.ts.map +1 -0
- package/dist/core/router/rules.js +91 -0
- package/dist/core/run-panel-api.d.ts +94 -0
- package/dist/core/run-panel-api.d.ts.map +1 -0
- package/dist/core/run-panel-api.js +169 -0
- package/dist/core/schedule-gate.js +5 -1
- package/dist/core/schedule-v2.d.ts +34 -0
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +91 -5
- package/dist/core/scheduler/at-fallback.d.ts +55 -2
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
- package/dist/core/scheduler/at-fallback.js +135 -5
- package/dist/core/scheduler/linux.d.ts +18 -2
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +63 -20
- 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/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +25 -1
- package/dist/core/scheduler/registry.d.ts +11 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +83 -21
- package/dist/core/scheduler/run-now.d.ts +16 -0
- package/dist/core/scheduler/run-now.d.ts.map +1 -0
- package/dist/core/scheduler/run-now.js +28 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +15 -12
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +125 -28
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +18 -11
- package/dist/core/structured-log.d.ts +7 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/task-name.d.ts +24 -0
- package/dist/core/task-name.d.ts.map +1 -0
- package/dist/core/task-name.js +40 -0
- 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 +224 -28
- package/dist/db/capability-repo.d.ts +124 -0
- package/dist/db/capability-repo.d.ts.map +1 -0
- package/dist/db/capability-repo.js +267 -0
- package/dist/db/history-repo.d.ts +46 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +107 -25
- package/dist/db/index.d.ts +4 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +39 -1
- package/dist/db/metrics-repo.js +2 -2
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +5 -4
- package/dist/db/run-context.d.ts +103 -0
- package/dist/db/run-context.d.ts.map +1 -0
- package/dist/db/run-context.js +224 -0
- package/dist/db/run-dlq.d.ts +100 -0
- package/dist/db/run-dlq.d.ts.map +1 -0
- package/dist/db/run-dlq.js +191 -0
- 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 +10 -2
- package/dist/db/run-resume.d.ts.map +1 -1
- package/dist/db/run-resume.js +39 -13
- package/dist/db/runs-repo.d.ts +32 -7
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +50 -11
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +216 -3
- package/dist/db/settings-repo.d.ts +11 -0
- package/dist/db/settings-repo.d.ts.map +1 -1
- package/dist/db/settings-repo.js +25 -0
- package/dist/db/step-idempotency.d.ts +51 -0
- package/dist/db/step-idempotency.d.ts.map +1 -0
- package/dist/db/step-idempotency.js +136 -0
- 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 +140 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +480 -18
- 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 +924 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +352 -0
- package/dist/server.d.ts +46 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +172 -53
- 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/dist/types.d.ts.map +1 -1
- package/dist/types.js +7 -0
- package/dist/workspaces.d.ts +25 -3
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +43 -8
- package/docs/ARCHITECTURE.md +498 -58
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/CONCEPT.md +185 -91
- package/docs/CROSS_PLATFORM.ru.md +20 -0
- package/docs/CROSS_PLATFORM.zh.md +18 -0
- package/docs/EXECUTION-LOOP.md +211 -0
- 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 +44 -5
- package/docs/README.zh.md +46 -6
- package/docs/SAFETY.md +142 -0
- package/docs/SAVINGS.md +29 -0
- package/docs/SAVINGS.ru.md +29 -0
- package/docs/SAVINGS.zh.md +18 -0
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +84 -1
- package/locales/ru.json +84 -1
- package/locales/zh.json +84 -1
- package/opencode.pipeline.yaml +35 -0
- package/package.json +46 -2
- package/scripts/audit-bundle.mjs +215 -0
- package/scripts/test-home.mjs +83 -0
- package/src/cli.ts +412 -0
- package/src/core/dlq-api.ts +98 -0
- package/src/core/dry-run.ts +27 -3
- 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 +244 -30
- 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/one-shot.ts +36 -8
- package/src/core/opencode-cli.ts +103 -0
- package/src/core/opencode-models.ts +315 -0
- 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 +274 -64
- package/src/core/record-history.ts +229 -104
- package/src/core/router/dispatch.ts +94 -0
- package/src/core/router/escalation.ts +129 -0
- package/src/core/router/planner.ts +166 -0
- package/src/core/router/rules.ts +115 -0
- package/src/core/run-panel-api.ts +262 -0
- package/src/core/schedule-gate.ts +7 -3
- package/src/core/schedule-v2.ts +114 -5
- package/src/core/scheduler/at-fallback.ts +190 -5
- package/src/core/scheduler/linux.ts +72 -21
- package/src/core/scheduler/logs.ts +2 -2
- package/src/core/scheduler/mac.ts +174 -14
- package/src/core/scheduler/posix.ts +20 -1
- package/src/core/scheduler/registry.ts +107 -26
- package/src/core/scheduler/run-now.ts +32 -0
- package/src/core/scheduler/windows.ts +19 -15
- package/src/core/secrets.ts +131 -31
- package/src/core/session.ts +23 -10
- package/src/core/structured-log.ts +22 -5
- package/src/core/task-name.ts +67 -0
- 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 +239 -27
- package/src/db/capability-repo.ts +402 -0
- package/src/db/history-repo.ts +151 -22
- package/src/db/index.ts +37 -1
- package/src/db/metrics-repo.ts +2 -2
- package/src/db/migrate.ts +3 -1
- package/src/db/recovery.ts +5 -4
- package/src/db/run-context.ts +370 -0
- package/src/db/run-dlq.ts +310 -0
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +65 -13
- package/src/db/runs-repo.ts +66 -13
- package/src/db/schema.ts +218 -3
- package/src/db/settings-repo.ts +31 -0
- package/src/db/step-idempotency.ts +185 -0
- package/src/gui.tsx +692 -13
- package/src/history.ts +1 -1
- package/src/i18n.ts +12 -4
- package/src/index.ts +648 -8
- package/src/notifications.ts +38 -8
- package/src/profiles.ts +26 -4
- package/src/rpc.ts +379 -0
- package/src/server.ts +206 -54
- package/src/settings.ts +5 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +31 -0
- package/src/types.ts +9 -0
- package/src/workspaces.ts +58 -9
|
@@ -1,10 +1,12 @@
|
|
|
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";
|
|
5
|
+
import { runTaskNow } from "./scheduler/run-now.js";
|
|
4
6
|
import { createSchedulerBackend } from "./scheduler/index.js";
|
|
5
7
|
import { notifyTaskCompletion } from "../notifications.js";
|
|
6
|
-
import { finishRun,
|
|
7
|
-
import {
|
|
8
|
+
import { finishRun, getLatestHistoryByTask, recordRun, startRun } from "../db/history-repo.js";
|
|
9
|
+
import { deleteSetting, decrementCounterSetting } from "../db/settings-repo.js";
|
|
8
10
|
import { getTask, listTasks } from "../db/tasks-repo.js";
|
|
9
11
|
import { rotateSessionIfNeeded } from "./session.js";
|
|
10
12
|
import type { TaskDefinition } from "../task-transfer.js";
|
|
@@ -13,10 +15,44 @@ import {
|
|
|
13
15
|
advanceMatrixAfterClone,
|
|
14
16
|
finalizeMatrixIfComplete,
|
|
15
17
|
} from "./matrix.js";
|
|
18
|
+
import { appendStructuredLog } from "./structured-log.js";
|
|
16
19
|
|
|
17
|
-
type Status = "success" | "error" | "timeout";
|
|
20
|
+
type Status = "success" | "error" | "timeout" | "skipped";
|
|
18
21
|
|
|
19
|
-
|
|
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
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Префикс ключа настроек со счётчиком повторов конкретной задачи. */
|
|
51
|
+
const RETRY_STATE_PREFIX = "retry_state:";
|
|
52
|
+
|
|
53
|
+
function retryStateKey(taskName: string): string {
|
|
54
|
+
return `${RETRY_STATE_PREFIX}${taskName.toLowerCase()}`;
|
|
55
|
+
}
|
|
20
56
|
|
|
21
57
|
/** Сколько последних строк лога сканировать при поиске токенов/стоимости. */
|
|
22
58
|
const LOG_TAIL_LINES = 500;
|
|
@@ -124,37 +160,23 @@ async function loadRetryConfig(taskName: string): Promise<{ count: number; delay
|
|
|
124
160
|
*/
|
|
125
161
|
async function triggerTask(taskName: string): Promise<boolean> {
|
|
126
162
|
try {
|
|
127
|
-
await
|
|
163
|
+
await runTaskNow(taskName);
|
|
128
164
|
return true;
|
|
129
|
-
} catch (err:
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
);
|
|
165
|
+
} catch (err: unknown) {
|
|
166
|
+
logRecorderEvent("chain.trigger_failed", taskName, {
|
|
167
|
+
nextTask: taskName,
|
|
168
|
+
error: err instanceof Error ? err.message : String(err),
|
|
169
|
+
});
|
|
135
170
|
return false;
|
|
136
171
|
}
|
|
137
172
|
}
|
|
138
173
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
async function writeRetryState(state: RetryState): Promise<void> {
|
|
148
|
-
setSetting(RETRY_STATE_KEY, state);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function clearRetryState(taskName: string): Promise<void> {
|
|
152
|
-
const state = await loadRetryState();
|
|
153
|
-
const key = Object.keys(state).find((k) => k.toLowerCase() === taskName.toLowerCase());
|
|
154
|
-
if (!key) return;
|
|
155
|
-
delete state[key];
|
|
156
|
-
await writeRetryState(state);
|
|
157
|
-
}
|
|
174
|
+
/*
|
|
175
|
+
* P2-30: раньше счётчики повторов лежали одним JSON-объектом в настройках.
|
|
176
|
+
* Каждое завершение задачи — отдельный процесс record-history, поэтому
|
|
177
|
+
* параллельные завершения перезаписывали map и теряли декременты. Теперь
|
|
178
|
+
* на задачу отдельный ключ и атомарный UPDATE ... RETURNING.
|
|
179
|
+
*/
|
|
158
180
|
|
|
159
181
|
/**
|
|
160
182
|
* Планирует повторный запуск упавшей задачи.
|
|
@@ -169,21 +191,15 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
169
191
|
const { count, delay } = await loadRetryConfig(taskName);
|
|
170
192
|
if (count <= 0) return false;
|
|
171
193
|
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
const remaining = Object.prototype.hasOwnProperty.call(state, key)
|
|
175
|
-
? Number(state[key]) || 0
|
|
176
|
-
: count;
|
|
194
|
+
const key = retryStateKey(taskName);
|
|
195
|
+
const remaining = decrementCounterSetting(key, count);
|
|
177
196
|
|
|
178
|
-
if (remaining
|
|
179
|
-
|
|
180
|
-
|
|
197
|
+
if (remaining === null) {
|
|
198
|
+
deleteSetting(key);
|
|
199
|
+
logRecorderEvent("retry.exhausted", taskName, { reason: "retries exhausted" });
|
|
181
200
|
return false;
|
|
182
201
|
}
|
|
183
202
|
|
|
184
|
-
state[key] = remaining - 1;
|
|
185
|
-
await writeRetryState(state);
|
|
186
|
-
|
|
187
203
|
const script = process.argv[1];
|
|
188
204
|
if (!script) return false;
|
|
189
205
|
|
|
@@ -196,17 +212,14 @@ async function scheduleRetry(taskName: string): Promise<boolean> {
|
|
|
196
212
|
});
|
|
197
213
|
child.unref();
|
|
198
214
|
|
|
199
|
-
|
|
200
|
-
`
|
|
201
|
-
|
|
202
|
-
);
|
|
215
|
+
logRecorderEvent("retry.scheduled", taskName, {
|
|
216
|
+
reason: `delay=${delay}s, remaining=${remaining}`,
|
|
217
|
+
});
|
|
203
218
|
return true;
|
|
204
|
-
} catch (err:
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}`,
|
|
209
|
-
);
|
|
219
|
+
} catch (err: unknown) {
|
|
220
|
+
logRecorderEvent("retry.schedule_failed", taskName, {
|
|
221
|
+
error: err instanceof Error ? err.message : String(err),
|
|
222
|
+
});
|
|
210
223
|
return false;
|
|
211
224
|
}
|
|
212
225
|
}
|
|
@@ -221,14 +234,12 @@ async function runRetry(taskName: string, delaySec: number): Promise<void> {
|
|
|
221
234
|
await new Promise<void>((resolve) => setTimeout(resolve, delay * 1000));
|
|
222
235
|
|
|
223
236
|
try {
|
|
224
|
-
await
|
|
225
|
-
|
|
226
|
-
} catch (err:
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
}`,
|
|
231
|
-
);
|
|
237
|
+
await runTaskNow(taskName);
|
|
238
|
+
logRecorderEvent("retry.started", taskName);
|
|
239
|
+
} catch (err: unknown) {
|
|
240
|
+
logRecorderEvent("retry.failed", taskName, {
|
|
241
|
+
error: err instanceof Error ? err.message : String(err),
|
|
242
|
+
});
|
|
232
243
|
}
|
|
233
244
|
}
|
|
234
245
|
|
|
@@ -346,6 +357,50 @@ async function main() {
|
|
|
346
357
|
return;
|
|
347
358
|
}
|
|
348
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
|
+
|
|
349
404
|
const parseOptionalNumber = (value?: string): number | undefined => {
|
|
350
405
|
if (!value || value === "-") return undefined;
|
|
351
406
|
const num = Number(value);
|
|
@@ -370,12 +425,20 @@ async function main() {
|
|
|
370
425
|
if (!taskName) process.exit(1);
|
|
371
426
|
const startedAt = third ?? new Date().toISOString();
|
|
372
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
|
+
};
|
|
373
435
|
const runId = startRun(
|
|
374
436
|
taskName,
|
|
375
437
|
startedAt,
|
|
376
438
|
definition?.workspaceId ?? null,
|
|
377
439
|
definition?.allowedTools ?? null,
|
|
378
440
|
definition?.deniedTools ?? null,
|
|
441
|
+
owner,
|
|
379
442
|
);
|
|
380
443
|
console.log(String(runId));
|
|
381
444
|
return;
|
|
@@ -415,13 +478,15 @@ async function main() {
|
|
|
415
478
|
const preFlightStatus = parseHookStatus(tenth);
|
|
416
479
|
const postFlightStatus = parseHookStatus(eleventh);
|
|
417
480
|
const st: Status =
|
|
418
|
-
status === "success" ? "success" : status === "timeout" ? "timeout" : "error";
|
|
481
|
+
status === "success" ? "success" : status === "timeout" ? "timeout" : status === "skipped" ? "skipped" : "error";
|
|
419
482
|
|
|
420
483
|
const definition = getTask(taskName);
|
|
421
484
|
const chainTarget =
|
|
422
485
|
st === "success"
|
|
423
486
|
? definition?.nextTaskOnSuccess || null
|
|
424
|
-
:
|
|
487
|
+
: st === "skipped"
|
|
488
|
+
? null
|
|
489
|
+
: definition?.nextTaskOnError || null;
|
|
425
490
|
|
|
426
491
|
const completed = finishRun(
|
|
427
492
|
runId,
|
|
@@ -436,9 +501,10 @@ async function main() {
|
|
|
436
501
|
postFlightStatus,
|
|
437
502
|
);
|
|
438
503
|
if (!completed) {
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
504
|
+
logRecorderEvent("run.finish_skipped", taskName, {
|
|
505
|
+
runId,
|
|
506
|
+
reason: "already finished or not found",
|
|
507
|
+
});
|
|
442
508
|
return;
|
|
443
509
|
}
|
|
444
510
|
|
|
@@ -461,6 +527,22 @@ async function main() {
|
|
|
461
527
|
// "-" означает «данных нет» (openCode не печатал usage в лог).
|
|
462
528
|
const tokens = parseOptionalNumber(sixth);
|
|
463
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
|
+
}
|
|
464
546
|
// Восьмой аргумент — модель; "-" означает, что модель не задана.
|
|
465
547
|
const model = eighth && eighth !== "-" ? eighth.trim() || undefined : undefined;
|
|
466
548
|
// Девятый и десятый — итоги pre/post-flight хуков.
|
|
@@ -468,13 +550,15 @@ async function main() {
|
|
|
468
550
|
const postFlightStatus = parseHookStatus(tenth);
|
|
469
551
|
|
|
470
552
|
const st: Status =
|
|
471
|
-
status === "success" ? "success" : status === "timeout" ? "timeout" : "error";
|
|
553
|
+
status === "success" ? "success" : status === "timeout" ? "timeout" : status === "skipped" ? "skipped" : "error";
|
|
472
554
|
|
|
473
555
|
const definition = getTask(taskName);
|
|
474
556
|
const chainTarget =
|
|
475
557
|
st === "success"
|
|
476
558
|
? definition?.nextTaskOnSuccess || null
|
|
477
|
-
:
|
|
559
|
+
: st === "skipped"
|
|
560
|
+
? null
|
|
561
|
+
: definition?.nextTaskOnError || null;
|
|
478
562
|
|
|
479
563
|
recordRun(
|
|
480
564
|
taskName,
|
|
@@ -483,8 +567,8 @@ async function main() {
|
|
|
483
567
|
durationMs,
|
|
484
568
|
error,
|
|
485
569
|
chainTarget,
|
|
486
|
-
|
|
487
|
-
|
|
570
|
+
tokensResolved,
|
|
571
|
+
costResolved,
|
|
488
572
|
model,
|
|
489
573
|
preFlightStatus,
|
|
490
574
|
postFlightStatus,
|
|
@@ -494,7 +578,48 @@ async function main() {
|
|
|
494
578
|
definition?.deniedTools ?? null,
|
|
495
579
|
);
|
|
496
580
|
|
|
497
|
-
await handleCompletion(taskName, st, chainTarget, error, durationMs,
|
|
581
|
+
await handleCompletion(taskName, st, chainTarget, error, durationMs, tokensResolved, costResolved);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Зависимости для тестируемой очистки one-shot (P2-27). */
|
|
585
|
+
export interface OneShotCleanupDeps {
|
|
586
|
+
platform?: NodeJS.Platform;
|
|
587
|
+
getDefinition?: (name: string) => TaskDefinition | undefined;
|
|
588
|
+
deleteTask?: (name: string) => Promise<void>;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Удаляет отработавшую ONCE-задачу из Планировщика Windows.
|
|
593
|
+
*
|
|
594
|
+
* `schtasks /create ... /z` должен был делать это сам, но на Win10/11
|
|
595
|
+
* возвращает «The task XML is missing a required element ... EndBoundary»
|
|
596
|
+
* и задача вообще не создаётся. Поэтому чистим после запуска вручную.
|
|
597
|
+
* На Linux/macOS очистка не нужна: `at` и launchd убирают one-shot сами.
|
|
598
|
+
*/
|
|
599
|
+
export async function cleanupWindowsOneShotTask(
|
|
600
|
+
taskName: string,
|
|
601
|
+
deps: OneShotCleanupDeps = {},
|
|
602
|
+
): Promise<boolean> {
|
|
603
|
+
const platform = deps.platform ?? process.platform;
|
|
604
|
+
if (platform !== "win32") return false;
|
|
605
|
+
|
|
606
|
+
const getDefinition = deps.getDefinition ?? getTask;
|
|
607
|
+
const definition = getDefinition(taskName);
|
|
608
|
+
if (!definition || definition.triggerType !== "once") return false;
|
|
609
|
+
|
|
610
|
+
const deleteTask =
|
|
611
|
+
deps.deleteTask ??
|
|
612
|
+
((name: string) => createSchedulerBackend().deleteTask(name));
|
|
613
|
+
try {
|
|
614
|
+
await deleteTask(taskName);
|
|
615
|
+
logRecorderEvent("oneshot.cleaned", taskName);
|
|
616
|
+
return true;
|
|
617
|
+
} catch (err: unknown) {
|
|
618
|
+
logRecorderEvent("oneshot.cleanup_failed", taskName, {
|
|
619
|
+
error: err instanceof Error ? err.message : String(err),
|
|
620
|
+
});
|
|
621
|
+
return false;
|
|
622
|
+
}
|
|
498
623
|
}
|
|
499
624
|
|
|
500
625
|
/**
|
|
@@ -511,10 +636,18 @@ async function handleCompletion(
|
|
|
511
636
|
costUsd?: number | null,
|
|
512
637
|
): Promise<void> {
|
|
513
638
|
// Уведомление о завершении (webhook). Ошибки отправки логируются внутри
|
|
514
|
-
// и не влияют на историю, цепочки и повторы.
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
639
|
+
// и не влияют на историю, цепочки и повторы. Пропуск guard не уведомляем:
|
|
640
|
+
// для него нет отдельного шаблона, а шум в уведомлениях не нужен.
|
|
641
|
+
if (st !== "skipped") {
|
|
642
|
+
await notifyTaskCompletion(taskName, st, durationMs, error, tokens, costUsd, {
|
|
643
|
+
asyncTriage: true,
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// P2-27: Windows не удаляет ONCE-задачи сам, а флаг schtasks `/z` на
|
|
648
|
+
// практике ломает создание задачи («task XML ... EndBoundary»).
|
|
649
|
+
// Поэтому снимаем отработавшую one-shot задачу из Планировщика здесь.
|
|
650
|
+
await cleanupWindowsOneShotTask(taskName);
|
|
518
651
|
|
|
519
652
|
// Matrix (Спринт 15): клон завершился — двигаем sequential-цепочку или
|
|
520
653
|
// очередь concurrency-лимита (Спринт 17), а когда все клоны готовы —
|
|
@@ -522,21 +655,19 @@ async function handleCompletion(
|
|
|
522
655
|
try {
|
|
523
656
|
await advanceMatrixAfterClone(taskName);
|
|
524
657
|
await finalizeMatrixIfComplete(taskName);
|
|
525
|
-
} catch (err:
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
}`,
|
|
530
|
-
);
|
|
658
|
+
} catch (err: unknown) {
|
|
659
|
+
logRecorderEvent("matrix.error", taskName, {
|
|
660
|
+
error: err instanceof Error ? err.message : String(err),
|
|
661
|
+
});
|
|
531
662
|
}
|
|
532
663
|
|
|
533
664
|
if (st === "success") {
|
|
534
665
|
// Успешный запуск сбрасывает счётчик повторов.
|
|
535
|
-
await
|
|
666
|
+
await deleteSetting(retryStateKey(taskName));
|
|
536
667
|
if (chainTarget) {
|
|
537
668
|
const started = await triggerTask(chainTarget);
|
|
538
669
|
if (started) {
|
|
539
|
-
|
|
670
|
+
logRecorderEvent("chain.triggered", taskName, { nextTask: chainTarget });
|
|
540
671
|
}
|
|
541
672
|
}
|
|
542
673
|
|
|
@@ -544,32 +675,30 @@ async function handleCompletion(
|
|
|
544
675
|
// зависимостей. Запускаем только если ВСЕ зависимости уже успешны и
|
|
545
676
|
// зависимая задача ещё не запускалась после их завершения.
|
|
546
677
|
try {
|
|
547
|
-
|
|
678
|
+
// P2-29: по одной последней записи на задачу, а не «последние 200 строк».
|
|
679
|
+
const history = getLatestHistoryByTask() as HistoryRecord[];
|
|
548
680
|
const definitions = listTasks();
|
|
549
681
|
const dependents = selectDependentsToTrigger(taskName, definitions, history);
|
|
550
682
|
for (const dependent of dependents) {
|
|
551
683
|
const started = await triggerTask(dependent);
|
|
552
684
|
if (started) {
|
|
553
|
-
|
|
554
|
-
`[agent-steward] DAG: все зависимости выполнены, запущена задача "${dependent}".`,
|
|
555
|
-
);
|
|
685
|
+
logRecorderEvent("dag.triggered", taskName, { nextTask: dependent });
|
|
556
686
|
}
|
|
557
687
|
}
|
|
558
|
-
} catch (err:
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
}`,
|
|
563
|
-
);
|
|
688
|
+
} catch (err: unknown) {
|
|
689
|
+
logRecorderEvent("dag.trigger_failed", taskName, {
|
|
690
|
+
error: err instanceof Error ? err.message : String(err),
|
|
691
|
+
});
|
|
564
692
|
}
|
|
565
|
-
} else {
|
|
693
|
+
} else if (st !== "skipped") {
|
|
566
694
|
// Сначала пытаемся повторить саму задачу; компенсирующая задача запускается
|
|
567
695
|
// только когда повторы исчерпаны (или не настроены).
|
|
696
|
+
// Пропуск guard — не ошибка: повторы и компенсации не запускаются.
|
|
568
697
|
const retryScheduled = await scheduleRetry(taskName);
|
|
569
698
|
if (!retryScheduled && chainTarget) {
|
|
570
699
|
const started = await triggerTask(chainTarget);
|
|
571
700
|
if (started) {
|
|
572
|
-
|
|
701
|
+
logRecorderEvent("compensation.triggered", taskName, { nextTask: chainTarget });
|
|
573
702
|
}
|
|
574
703
|
}
|
|
575
704
|
}
|
|
@@ -578,12 +707,10 @@ async function handleCompletion(
|
|
|
578
707
|
// при достижении sessionMaxRuns. Не должна ломать завершение запуска.
|
|
579
708
|
try {
|
|
580
709
|
await rotateSessionIfNeeded(taskName);
|
|
581
|
-
} catch (err:
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
}`,
|
|
586
|
-
);
|
|
710
|
+
} catch (err: unknown) {
|
|
711
|
+
logRecorderEvent("session.rotate_failed", taskName, {
|
|
712
|
+
error: err instanceof Error ? err.message : String(err),
|
|
713
|
+
});
|
|
587
714
|
}
|
|
588
715
|
}
|
|
589
716
|
|
|
@@ -605,11 +732,9 @@ function isDirectInvocation(): boolean {
|
|
|
605
732
|
|
|
606
733
|
if (isDirectInvocation()) {
|
|
607
734
|
main().catch((err) => {
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
}`,
|
|
612
|
-
);
|
|
735
|
+
logRecorderEvent("record_history.fatal", "record-history", {
|
|
736
|
+
error: err instanceof Error ? err.message : String(err),
|
|
737
|
+
});
|
|
613
738
|
process.exit(1);
|
|
614
739
|
});
|
|
615
740
|
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Сборка маршрута шага из слоёв 1–2 (Спринт 36.5.d).
|
|
3
|
+
*
|
|
4
|
+
* Слой 1 отвечает мгновенно по таблице правил, слой 2 — по Capability Map.
|
|
5
|
+
* Модель здесь не участвует: `routeStep` не импортирует planner и ничего не
|
|
6
|
+
* декомпозирует, поэтому известный тип задачи обходится в 0 токенов.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { decideCapabilityRoute } from "../../db/capability-repo.js";
|
|
10
|
+
import type { CapabilityDecision, CapabilityThresholds } from "../../db/capability-repo.js";
|
|
11
|
+
import { normalizeTaskType, routeStaticStep } from "./rules.js";
|
|
12
|
+
import type { RouterExecutor, RouterTransport } from "./rules.js";
|
|
13
|
+
|
|
14
|
+
/** Откуда взято решение о маршруте. */
|
|
15
|
+
export type RouteSource = "static" | "capability";
|
|
16
|
+
|
|
17
|
+
/** Куда направляется шаг: исполнение или ручной разбор. */
|
|
18
|
+
export type RouteTarget = "local" | "cloud" | "review" | "explore";
|
|
19
|
+
|
|
20
|
+
/** Готовый маршрут шага. */
|
|
21
|
+
export interface StepRoute {
|
|
22
|
+
/** Нормализованный тип задачи. */
|
|
23
|
+
taskType: string;
|
|
24
|
+
/** Кто исполняет шаг либо почему шаг уходит человеку. */
|
|
25
|
+
target: RouteTarget;
|
|
26
|
+
/** Транспорт; `null` для `review`/`explore`, где исполнения пока нет. */
|
|
27
|
+
transport: RouterTransport | null;
|
|
28
|
+
/** Исполнитель; `null` для `review`/`explore`. */
|
|
29
|
+
executor: RouterExecutor | null;
|
|
30
|
+
/** Слой, принявший решение. */
|
|
31
|
+
source: RouteSource;
|
|
32
|
+
/** Стабильный код причины: `static-rule` либо решение Capability Map. */
|
|
33
|
+
reason: string;
|
|
34
|
+
/** Решение слоя 2, если он участвовал. */
|
|
35
|
+
decision?: CapabilityDecision;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Строит маршрут для типа задачи: статическое правило, затем Capability Map.
|
|
40
|
+
* Пустой тип — ошибка, а не молчаливый `explore`: маршрутизировать нечего.
|
|
41
|
+
*/
|
|
42
|
+
export function routeStep(
|
|
43
|
+
taskType: string,
|
|
44
|
+
thresholds: CapabilityThresholds = {},
|
|
45
|
+
): StepRoute {
|
|
46
|
+
const key = normalizeTaskType(taskType);
|
|
47
|
+
if (key === "") {
|
|
48
|
+
throw new Error("Пустой тип задачи: маршрутизация невозможна.");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const rule = routeStaticStep(key);
|
|
52
|
+
if (rule !== undefined) {
|
|
53
|
+
return {
|
|
54
|
+
taskType: key,
|
|
55
|
+
target: rule.executor,
|
|
56
|
+
transport: rule.transport,
|
|
57
|
+
executor: rule.executor,
|
|
58
|
+
source: "static",
|
|
59
|
+
reason: "static-rule",
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const decision = decideCapabilityRoute(key, thresholds);
|
|
64
|
+
const target: RouteTarget = decision.target;
|
|
65
|
+
return {
|
|
66
|
+
taskType: key,
|
|
67
|
+
target,
|
|
68
|
+
transport: transportForTarget(target),
|
|
69
|
+
executor: executorForTarget(target),
|
|
70
|
+
source: "capability",
|
|
71
|
+
reason: decision.reason,
|
|
72
|
+
decision,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function transportForTarget(target: RouteTarget): RouterTransport | null {
|
|
77
|
+
if (target === "cloud") {
|
|
78
|
+
return "cloud";
|
|
79
|
+
}
|
|
80
|
+
if (target === "local") {
|
|
81
|
+
return "direct";
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function executorForTarget(target: RouteTarget): RouterExecutor | null {
|
|
87
|
+
if (target === "cloud") {
|
|
88
|
+
return "cloud";
|
|
89
|
+
}
|
|
90
|
+
if (target === "local") {
|
|
91
|
+
return "local";
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|