agent-steward 0.0.4 → 0.0.6
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 +309 -2
- package/CROSS_PLATFORM.md +19 -0
- package/README.md +55 -8
- package/ROADMAP-STRATEGY.md +22 -19
- package/ROADMAP.md +230 -159
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +356 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- 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/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +71 -0
- package/dist/core/gate-integrity.d.ts.map +1 -0
- package/dist/core/gate-integrity.js +275 -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/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- 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 +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +132 -17
- package/dist/core/mission.d.ts +103 -0
- package/dist/core/mission.d.ts.map +1 -0
- package/dist/core/mission.js +374 -0
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -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 +78 -0
- package/dist/core/pipeline-map.d.ts +52 -0
- package/dist/core/pipeline-map.d.ts.map +1 -0
- package/dist/core/pipeline-map.js +208 -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 +27 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +424 -65
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +206 -33
- package/dist/core/router/rules.d.ts.map +1 -1
- package/dist/core/router/rules.js +6 -0
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -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/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- 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/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +37 -1
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -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 +19 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +230 -27
- 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 +70 -5
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +170 -29
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +35 -13
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +11 -5
- 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 +91 -60
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +132 -2
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +7 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- 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 +375 -47
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1344 -192
- package/dist/notifications.d.ts +53 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +168 -21
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +82 -10
- package/dist/rpc.d.ts +354 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +145 -0
- package/dist/server.d.ts +32 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +154 -30
- package/dist/settings.d.ts +44 -2
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +85 -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 +21 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +64 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +319 -66
- 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 +28 -10
- package/docs/FEATURES.md +129 -7
- package/docs/FEATURES.zh.md +97 -6
- package/docs/MIGRATION.md +2 -2
- package/docs/PIPELINE.md +293 -0
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +43 -4
- package/docs/README.zh.md +44 -4
- package/docs/SAFETY.md +23 -3
- package/gui-experimental.cjs +9 -8
- package/locales/en.json +58 -3
- package/locales/ru.json +58 -3
- package/locales/zh.json +58 -3
- package/opencode.pipeline.yaml +35 -0
- package/package.json +36 -4
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +107 -0
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +417 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +235 -12
- package/src/core/execution.ts +538 -0
- package/src/core/feedback.ts +582 -0
- package/src/core/file-watcher.ts +2 -2
- package/src/core/gate-integrity.ts +330 -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/local-ai.ts +7 -3
- package/src/core/lock.ts +178 -37
- package/src/core/matrix.ts +158 -52
- package/src/core/mission.ts +531 -0
- package/src/core/native-notify.ts +1 -1
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-apply.ts +158 -0
- package/src/core/pipeline-io.ts +96 -0
- package/src/core/pipeline-map.ts +283 -0
- package/src/core/pipeline-spec.ts +775 -0
- package/src/core/ps-wrapper.ts +435 -66
- package/src/core/record-history.ts +258 -81
- package/src/core/router/rules.ts +6 -0
- package/src/core/run-mode.ts +19 -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 +34 -3
- 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 +26 -19
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +89 -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/usage-surface.ts +70 -0
- package/src/core/worktree-run.ts +199 -0
- package/src/core/worktree.ts +600 -0
- package/src/core/wrappers/bash.ts +248 -26
- package/src/db/capability-repo.ts +127 -10
- package/src/db/history-repo.ts +281 -40
- package/src/db/metrics-repo.ts +40 -13
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +12 -5
- package/src/db/run-journal.ts +100 -13
- package/src/db/run-resume.ts +17 -1
- package/src/db/runs-repo.ts +147 -65
- package/src/db/schema.ts +134 -2
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +438 -18
- package/src/history.ts +11 -4
- package/src/hook-output.ts +39 -0
- package/src/i18n.ts +12 -4
- package/src/index.ts +1902 -320
- package/src/notifications.ts +227 -47
- package/src/profiles.ts +88 -10
- package/src/rpc.ts +158 -0
- package/src/server.ts +201 -41
- package/src/settings.ts +125 -5
- package/src/shared/jobs-view.ts +3 -1
- package/src/task-transfer.ts +90 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
package/src/db/migrate.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { PLUGIN_DIR } from "../types.js";
|
|
4
|
+
import { PLUGIN_DIR, type MigrationHistoryRow } from "../types.js";
|
|
5
5
|
import { getDb, isDatabaseEmpty, withTransaction } from "./index.js";
|
|
6
6
|
import {
|
|
7
7
|
LEGACY_METRICS_TASK,
|
|
@@ -40,6 +40,34 @@ const EMPTY_RESULT: MigrationResult = {
|
|
|
40
40
|
|
|
41
41
|
const JSON_FILES = ["tasks.json", "history.json", "metrics.json", "templates.json"] as const;
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* JSON читается как unknown: доверяем только форме (объект/массив), а не
|
|
45
|
+
* содержимому. Значения проверяются type guard'ами перед записью в БД (QA-A2.4).
|
|
46
|
+
*/
|
|
47
|
+
type JsonRecord = Record<string, unknown>;
|
|
48
|
+
|
|
49
|
+
function isRecord(value: unknown): value is JsonRecord {
|
|
50
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Встроенный Array.isArray возвращает слабый тип массива; свой guard даёт unknown[] (QA-A2.4). */
|
|
54
|
+
function isUnknownArray(value: unknown): value is unknown[] {
|
|
55
|
+
return Array.isArray(value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Граница внешнего API (node:fs, JSON.parse, node:sqlite): выброшенное значение
|
|
60
|
+
* не гарантированно Error. Извлечение сообщения сохранено как в legacy-коде.
|
|
61
|
+
*/
|
|
62
|
+
function errorText(err: unknown): string {
|
|
63
|
+
return err instanceof Error ? err.message : String(err);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** node:fs сообщает «файл не найден» через свойство code (внешняя граница API). */
|
|
67
|
+
function isErrnoException(err: unknown): err is NodeJS.ErrnoException {
|
|
68
|
+
return err instanceof Error && "code" in err && typeof err.code === "string";
|
|
69
|
+
}
|
|
70
|
+
|
|
43
71
|
interface LoadedFile {
|
|
44
72
|
path: string;
|
|
45
73
|
exists: boolean;
|
|
@@ -51,24 +79,22 @@ async function loadJsonFile(file: string): Promise<LoadedFile> {
|
|
|
51
79
|
const raw = await fs.readFile(file, "utf8");
|
|
52
80
|
try {
|
|
53
81
|
return { path: file, exists: true, value: JSON.parse(raw) };
|
|
54
|
-
} catch (err:
|
|
82
|
+
} catch (err: unknown) {
|
|
55
83
|
throw new Error(
|
|
56
|
-
`Некорректный JSON в ${path.basename(file)}: ${
|
|
57
|
-
err instanceof Error ? err.message : String(err)
|
|
58
|
-
}`,
|
|
84
|
+
`Некорректный JSON в ${path.basename(file)}: ${errorText(err)}`,
|
|
59
85
|
);
|
|
60
86
|
}
|
|
61
|
-
} catch (err:
|
|
62
|
-
if (err
|
|
87
|
+
} catch (err: unknown) {
|
|
88
|
+
if (isErrnoException(err) && err.code === "ENOENT") {
|
|
89
|
+
return { path: file, exists: false, value: null };
|
|
90
|
+
}
|
|
63
91
|
throw err;
|
|
64
92
|
}
|
|
65
93
|
}
|
|
66
94
|
|
|
67
|
-
function asArray(value: unknown):
|
|
68
|
-
if (
|
|
69
|
-
if (value &&
|
|
70
|
-
return (value as any).tasks;
|
|
71
|
-
}
|
|
95
|
+
function asArray(value: unknown): unknown[] {
|
|
96
|
+
if (isUnknownArray(value)) return value;
|
|
97
|
+
if (isRecord(value) && isUnknownArray(value.tasks)) return value.tasks;
|
|
72
98
|
return [];
|
|
73
99
|
}
|
|
74
100
|
|
|
@@ -83,8 +109,8 @@ function toStringOrNull(value: unknown): string | null {
|
|
|
83
109
|
}
|
|
84
110
|
|
|
85
111
|
/** Приводит старую запись истории к колонкам БД. */
|
|
86
|
-
function normalizeHistoryRow(raw:
|
|
87
|
-
if (!raw
|
|
112
|
+
function normalizeHistoryRow(raw: unknown): MigrationHistoryRow | null {
|
|
113
|
+
if (!isRecord(raw)) return null;
|
|
88
114
|
const taskName = typeof raw.taskName === "string" ? raw.taskName.trim() : "";
|
|
89
115
|
const startedAt = typeof raw.startedAt === "string" ? raw.startedAt : "";
|
|
90
116
|
if (!taskName || !startedAt) return null;
|
|
@@ -130,13 +156,10 @@ export async function migrateJsonToDb(
|
|
|
130
156
|
const taskItems = asArray(byName.get("tasks.json")?.value);
|
|
131
157
|
const historyItems = asArray(byName.get("history.json")?.value)
|
|
132
158
|
.map(normalizeHistoryRow)
|
|
133
|
-
.filter((row): row is
|
|
159
|
+
.filter((row): row is MigrationHistoryRow => row !== null);
|
|
134
160
|
const templateItems = asArray(byName.get("templates.json")?.value);
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
typeof byName.get("metrics.json")?.value === "object"
|
|
138
|
-
? (byName.get("metrics.json")!.value as any)
|
|
139
|
-
: null;
|
|
161
|
+
const metricsValue = byName.get("metrics.json")?.value;
|
|
162
|
+
const legacyMetrics: JsonRecord | null = isRecord(metricsValue) ? metricsValue : null;
|
|
140
163
|
|
|
141
164
|
const now = new Date().toISOString();
|
|
142
165
|
let insertedTasks = 0;
|
|
@@ -148,24 +171,27 @@ export async function migrateJsonToDb(
|
|
|
148
171
|
const db = getDb();
|
|
149
172
|
|
|
150
173
|
// --- tasks ---
|
|
174
|
+
// Сырой SQL и node:sqlite — граница внешнего API: в БД попадают только
|
|
175
|
+
// значения, прошедшие проверки выше (name/createdAt — string, остальное — JSON).
|
|
151
176
|
const insertTask = db.prepare(
|
|
152
177
|
"INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)",
|
|
153
178
|
);
|
|
154
179
|
const seenTasks = new Set<string>();
|
|
155
180
|
for (const item of taskItems) {
|
|
156
|
-
if (!item
|
|
181
|
+
if (!isRecord(item)) continue;
|
|
157
182
|
const name = typeof item.name === "string" ? item.name.trim() : "";
|
|
158
183
|
if (!name || seenTasks.has(name.toLowerCase())) continue;
|
|
159
184
|
seenTasks.add(name.toLowerCase());
|
|
160
185
|
|
|
161
186
|
// workdir → workingDirectory, как в старом loadTaskDefinitions().
|
|
162
|
-
const definition:
|
|
187
|
+
const definition: JsonRecord = { ...item, name };
|
|
188
|
+
const legacyWorkdir = definition.workdir;
|
|
163
189
|
if (
|
|
164
190
|
definition.workingDirectory === undefined &&
|
|
165
|
-
typeof
|
|
166
|
-
|
|
191
|
+
typeof legacyWorkdir === "string" &&
|
|
192
|
+
legacyWorkdir.trim()
|
|
167
193
|
) {
|
|
168
|
-
definition.workingDirectory =
|
|
194
|
+
definition.workingDirectory = legacyWorkdir.trim();
|
|
169
195
|
}
|
|
170
196
|
delete definition.workdir;
|
|
171
197
|
|
|
@@ -210,17 +236,18 @@ export async function migrateJsonToDb(
|
|
|
210
236
|
);
|
|
211
237
|
const seenTemplates = new Set<string>();
|
|
212
238
|
for (const item of templateItems) {
|
|
213
|
-
if (!item
|
|
239
|
+
if (!isRecord(item)) continue;
|
|
214
240
|
if (typeof item.prompt !== "string") continue;
|
|
215
241
|
const name = typeof item.name === "string" ? item.name.trim() : "";
|
|
216
242
|
if (!name) continue;
|
|
243
|
+
const legacyId = item.id;
|
|
217
244
|
const id =
|
|
218
|
-
typeof
|
|
245
|
+
typeof legacyId === "string" && legacyId.trim() ? legacyId.trim() : randomUUID();
|
|
219
246
|
const key = id.toLowerCase();
|
|
220
247
|
if (seenTemplates.has(key)) continue;
|
|
221
248
|
seenTemplates.add(key);
|
|
222
249
|
|
|
223
|
-
const template = { ...item, id, name };
|
|
250
|
+
const template: JsonRecord = { ...item, id, name };
|
|
224
251
|
insertTemplate.run(id, name, JSON.stringify(template));
|
|
225
252
|
insertedTemplates += 1;
|
|
226
253
|
}
|
|
@@ -306,11 +333,9 @@ export async function migrateJsonToDb(
|
|
|
306
333
|
await fs.rm(backup, { force: true });
|
|
307
334
|
await fs.rename(file.path, backup);
|
|
308
335
|
backups.push(path.basename(backup));
|
|
309
|
-
} catch (err:
|
|
336
|
+
} catch (err: unknown) {
|
|
310
337
|
console.error(
|
|
311
|
-
`[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${
|
|
312
|
-
err instanceof Error ? err.message : String(err)
|
|
313
|
-
}`,
|
|
338
|
+
`[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${errorText(err)}`,
|
|
314
339
|
);
|
|
315
340
|
}
|
|
316
341
|
}
|
package/src/db/recovery.ts
CHANGED
|
@@ -9,16 +9,23 @@ const JSON_FILES = ["tasks.json", "history.json", "metrics.json", "templates.jso
|
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Crash recovery: помечает незавершённые записи истории как error.
|
|
12
|
-
* Вызывается при setup() до запуска catch-up и файловых
|
|
12
|
+
* Вызывается при setup() до запуска catch-up и файловых триггеров, а также
|
|
13
|
+
* перед выдачей истории (PL-46), чтобы «висящие» запуски не оставались
|
|
14
|
+
* running после schtasks /End.
|
|
13
15
|
*/
|
|
14
16
|
export function recoverInterruptedRuns(): number {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
// Порог можно переопределить: 0 отключает финализацию живого владельца.
|
|
18
|
+
const configured = Number(process.env.AGENT_STEWARD_STALE_RUN_MS);
|
|
19
|
+
const staleAfterMs =
|
|
20
|
+
Number.isFinite(configured) && configured > 0 ? configured : 2 * 60 * 60 * 1000;
|
|
21
|
+
const { recovered, keptAlive } = recoverInterrupted({ staleAfterMs });
|
|
22
|
+
if (recovered > 0) {
|
|
17
23
|
console.log(
|
|
18
|
-
`[recovery] Восстановлено ${
|
|
24
|
+
`[recovery] Восстановлено ${recovered} незавершённых записей истории (error/timeout).` +
|
|
25
|
+
(keptAlive > 0 ? ` Оставлено живым владельцам: ${keptAlive}.` : ""),
|
|
19
26
|
);
|
|
20
27
|
}
|
|
21
|
-
return
|
|
28
|
+
return recovered;
|
|
22
29
|
}
|
|
23
30
|
|
|
24
31
|
/**
|
package/src/db/run-journal.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
+
import os from "node:os";
|
|
1
2
|
import { getDb, withTransaction } from "./index.js";
|
|
2
3
|
import {
|
|
3
4
|
finishStep,
|
|
4
5
|
getRun,
|
|
5
6
|
getStep,
|
|
7
|
+
renewStepLease as renewStepLeaseRow,
|
|
6
8
|
retryStep,
|
|
7
9
|
startRun,
|
|
8
10
|
startStep,
|
|
9
11
|
type FinishOptions,
|
|
10
12
|
type RunRecord,
|
|
11
13
|
type RunStepRecord,
|
|
14
|
+
type StepLease,
|
|
12
15
|
} from "./runs-repo.js";
|
|
13
16
|
|
|
14
17
|
/**
|
|
@@ -23,10 +26,29 @@ import {
|
|
|
23
26
|
/** Текст ошибки, которым помечается шаг, прерванный падением процесса. */
|
|
24
27
|
export const STEP_INTERRUPTED_ERROR = "Прервано падением процесса";
|
|
25
28
|
|
|
29
|
+
/**
|
|
30
|
+
* B12: срок lease шага по умолчанию. Живой процесс продлевает lease
|
|
31
|
+
* (heartbeat в `runStepStatefullyAsync` или явный `renewStepLease`), поэтому
|
|
32
|
+
* recovery финализирует шаг только после истечения этого срока.
|
|
33
|
+
*/
|
|
34
|
+
export const STEP_LEASE_MS = 60_000;
|
|
35
|
+
|
|
36
|
+
let cachedOwnerId: string | null = null;
|
|
37
|
+
|
|
38
|
+
/** B12: идентификатор текущего процесса — `host:pid:startedAt`. */
|
|
39
|
+
export function getStepOwnerId(): string {
|
|
40
|
+
if (!cachedOwnerId) {
|
|
41
|
+
cachedOwnerId = `${os.hostname()}:${process.pid}:${nowIso()}`;
|
|
42
|
+
}
|
|
43
|
+
return cachedOwnerId;
|
|
44
|
+
}
|
|
45
|
+
|
|
26
46
|
/** Опции начала попытки. */
|
|
27
47
|
export interface BeginStepOptions {
|
|
28
48
|
/** Начать запуск, если он ещё в статусе pending (по умолчанию true). */
|
|
29
49
|
startRun?: boolean;
|
|
50
|
+
/** B12: срок lease в миллисекундах (по умолчанию {@link STEP_LEASE_MS}). */
|
|
51
|
+
leaseMs?: number;
|
|
30
52
|
}
|
|
31
53
|
|
|
32
54
|
/** Результат выполнения шага через `runStepStatefully`. */
|
|
@@ -68,15 +90,41 @@ export function beginStepAttempt(
|
|
|
68
90
|
}
|
|
69
91
|
|
|
70
92
|
const step = requireStep(runId, stepName);
|
|
93
|
+
const lease = buildLease(options.leaseMs);
|
|
71
94
|
if (step.status === "failed") {
|
|
72
|
-
retryStep(step.id);
|
|
95
|
+
retryStep(step.id, undefined, lease);
|
|
73
96
|
} else {
|
|
74
|
-
startStep(step.id);
|
|
97
|
+
startStep(step.id, undefined, lease);
|
|
75
98
|
}
|
|
76
99
|
|
|
77
100
|
return requireStep(runId, stepName);
|
|
78
101
|
}
|
|
79
102
|
|
|
103
|
+
/**
|
|
104
|
+
* B12: продлевает lease шага текущего процесса.
|
|
105
|
+
*
|
|
106
|
+
* Нужен долгим синхронным шагам: без продления recovery сочтёт шаг
|
|
107
|
+
* осиротевшим после {@link STEP_LEASE_MS}. Возвращает false, если шаг уже
|
|
108
|
+
* не `running`.
|
|
109
|
+
*/
|
|
110
|
+
export function renewStepLease(
|
|
111
|
+
runId: string,
|
|
112
|
+
stepName: string,
|
|
113
|
+
leaseMs: number = STEP_LEASE_MS,
|
|
114
|
+
): boolean {
|
|
115
|
+
const step = requireStep(runId, stepName);
|
|
116
|
+
if (step.status !== "running") return false;
|
|
117
|
+
return renewStepLeaseRow(step.id, buildLease(leaseMs));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function buildLease(leaseMs: number = STEP_LEASE_MS): StepLease {
|
|
121
|
+
const duration = Number.isFinite(leaseMs) && leaseMs > 0 ? leaseMs : STEP_LEASE_MS;
|
|
122
|
+
return {
|
|
123
|
+
ownerId: getStepOwnerId(),
|
|
124
|
+
leaseUntil: new Date(Date.now() + duration).toISOString(),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
80
128
|
/** Закрывает попытку успехом: running → passed, сохраняет output. */
|
|
81
129
|
export function recordStepSuccess(
|
|
82
130
|
runId: string,
|
|
@@ -127,39 +175,78 @@ export async function runStepStatefullyAsync<T>(
|
|
|
127
175
|
body: () => Promise<T> | T,
|
|
128
176
|
options: BeginStepOptions = {},
|
|
129
177
|
): Promise<StepExecution<T>> {
|
|
178
|
+
const leaseMs = options.leaseMs ?? STEP_LEASE_MS;
|
|
130
179
|
const attempt = beginStepAttempt(runId, stepName, options).attempt;
|
|
180
|
+
// B12: heartbeat продлевает lease, пока тело шага реально выполняется.
|
|
181
|
+
const timer = setInterval(
|
|
182
|
+
() => {
|
|
183
|
+
try {
|
|
184
|
+
renewStepLease(runId, stepName, leaseMs);
|
|
185
|
+
} catch {
|
|
186
|
+
// Шаг уже финализирован — продлевать нечего.
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
Math.max(10, Math.floor(leaseMs / 3)),
|
|
190
|
+
);
|
|
191
|
+
timer.unref?.();
|
|
131
192
|
let result: T;
|
|
132
193
|
try {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
194
|
+
try {
|
|
195
|
+
result = await body();
|
|
196
|
+
} catch (err) {
|
|
197
|
+
recordStepFailure(runId, stepName, err);
|
|
198
|
+
throw err;
|
|
199
|
+
}
|
|
200
|
+
} finally {
|
|
201
|
+
clearInterval(timer);
|
|
137
202
|
}
|
|
138
203
|
const step = recordStepSuccess(runId, stepName, result);
|
|
139
204
|
return { step, result, attempt };
|
|
140
205
|
}
|
|
141
206
|
|
|
207
|
+
export interface RecoverStepsOptions {
|
|
208
|
+
/**
|
|
209
|
+
* B12: текущий момент для проверки lease. По умолчанию now; тесты и
|
|
210
|
+
* отложенный recovery передают «будущее», чтобы lease считался истёкшим.
|
|
211
|
+
*/
|
|
212
|
+
now?: string | Date;
|
|
213
|
+
}
|
|
214
|
+
|
|
142
215
|
/**
|
|
143
|
-
* Помечает
|
|
216
|
+
* Помечает осиротевшие `running`-шаги как failed, сохраняя `attempt`.
|
|
144
217
|
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
147
|
-
*
|
|
218
|
+
* B12: шаг финализируется только при отсутствии lease (legacy-строки) или
|
|
219
|
+
* истёкшем `lease_until`. Шаг с живым lease принадлежит работающему процессу
|
|
220
|
+
* и не трогается. Возвращает обновлённые записи.
|
|
221
|
+
*
|
|
222
|
+
* `attempt` не сбрасывается — следующая попытка получит `attempt + 1` через
|
|
223
|
+
* `retryStep`, поэтому номер попытки переживает падение процесса и восстановление.
|
|
148
224
|
*/
|
|
149
|
-
export function recoverInterruptedSteps(
|
|
225
|
+
export function recoverInterruptedSteps(
|
|
226
|
+
runId?: string,
|
|
227
|
+
options: RecoverStepsOptions = {},
|
|
228
|
+
): RunStepRecord[] {
|
|
150
229
|
const running = listRunningSteps(runId);
|
|
151
230
|
if (running.length === 0) return [];
|
|
152
231
|
|
|
232
|
+
const nowMs = options.now ? new Date(options.now).getTime() : Date.now();
|
|
233
|
+
const expired = running.filter((step) => {
|
|
234
|
+
if (!step.leaseUntil) return true;
|
|
235
|
+
const until = Date.parse(step.leaseUntil);
|
|
236
|
+
return Number.isNaN(until) || until <= nowMs;
|
|
237
|
+
});
|
|
238
|
+
if (expired.length === 0) return [];
|
|
239
|
+
|
|
153
240
|
return withTransaction(() => {
|
|
154
241
|
const timestamp = nowIso();
|
|
155
242
|
const update = getDb().prepare(
|
|
156
243
|
`UPDATE run_steps SET status = 'failed', error = ?, finished_at = ?,
|
|
157
244
|
updated_at = ? WHERE id = ? AND status = 'running'`,
|
|
158
245
|
);
|
|
159
|
-
for (const step of
|
|
246
|
+
for (const step of expired) {
|
|
160
247
|
update.run(STEP_INTERRUPTED_ERROR, timestamp, timestamp, step.id);
|
|
161
248
|
}
|
|
162
|
-
return
|
|
249
|
+
return expired.map((step) => requireStep(step.runId, step.stepName));
|
|
163
250
|
});
|
|
164
251
|
}
|
|
165
252
|
|
package/src/db/run-resume.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
type RunStepRecord,
|
|
9
9
|
} from "./runs-repo.js";
|
|
10
10
|
import {
|
|
11
|
+
listRunningSteps,
|
|
11
12
|
recoverInterruptedSteps,
|
|
12
13
|
requireRun,
|
|
13
14
|
runStepStatefully,
|
|
@@ -38,6 +39,11 @@ export interface ResumeOptions {
|
|
|
38
39
|
handlers: Record<string, StepHandler>;
|
|
39
40
|
/** Восстанавливать зависшие `running`-шаги перед продолжением (по умолчанию true). */
|
|
40
41
|
recover?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* B12: момент для проверки lease при восстановлении. По умолчанию now.
|
|
44
|
+
* Передавайте будущее время, чтобы считать lease зависшего шага истёкшим.
|
|
45
|
+
*/
|
|
46
|
+
recoverNow?: string | Date;
|
|
41
47
|
/** Останавливаться на первой ошибке (по умолчанию true). */
|
|
42
48
|
stopOnError?: boolean;
|
|
43
49
|
}
|
|
@@ -84,7 +90,17 @@ function prepareResume(runId: string, options: ResumeOptions): ResumePlan {
|
|
|
84
90
|
throw new Error(`Запуск отменён, возобновление невозможно: ${runId}`);
|
|
85
91
|
}
|
|
86
92
|
|
|
87
|
-
if (options.recover !== false) recoverInterruptedSteps(runId);
|
|
93
|
+
if (options.recover !== false) recoverInterruptedSteps(runId, { now: options.recoverNow });
|
|
94
|
+
|
|
95
|
+
// B12: шаг с живым lease принадлежит работающему процессу. Возобновлять его
|
|
96
|
+
// здесь нельзя — иначе два исполнителя возьмут один шаг.
|
|
97
|
+
const active = listRunningSteps(runId);
|
|
98
|
+
if (active.length > 0) {
|
|
99
|
+
const step = active[0];
|
|
100
|
+
throw new Error(
|
|
101
|
+
`Шаг ${step.stepName} выполняется другим процессом (lease до ${step.leaseUntil ?? "неизвестно"}); возобновление отложено.`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
88
104
|
|
|
89
105
|
const steps = listRunSteps(runId);
|
|
90
106
|
const startIndex = steps.findIndex((step) => !isStepDone(step.status));
|