agent-steward 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +9 -8
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +114 -999
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dry-run.js +1 -1
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.js +2 -4
- package/dist/core/one-shot.d.ts +27 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +53 -10
- package/dist/core/otel.js +2 -2
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +55 -35
- package/dist/core/record-history.js +22 -22
- package/dist/core/schedule-v2.d.ts +2 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +7 -7
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/linux.d.ts +3 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +43 -7
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +12 -1
- package/dist/core/scheduler/registry.d.ts +2 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.js +2 -2
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/summary.js +1 -1
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.js +33 -33
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +9 -1
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +190 -35
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -36
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +109 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +89 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +20 -19
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +37 -9
- package/dist/workspaces.js +1 -1
- package/docs/ARCHITECTURE.md +110 -8
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +15 -3
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +26 -7
- package/docs/README.zh.md +9 -8
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +1 -0
- package/locales/ru.json +1 -0
- package/locales/zh.json +1 -0
- package/package.json +31 -10
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dry-run.ts +26 -26
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +9 -9
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +63 -13
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +57 -37
- package/src/core/record-history.ts +40 -40
- package/src/core/retention.ts +3 -3
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +12 -12
- package/src/core/schedule-v2.ts +24 -24
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +64 -13
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +15 -1
- package/src/core/scheduler/registry.ts +6 -4
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +13 -13
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +3 -3
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +41 -41
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +22 -22
- package/src/db/index.ts +16 -6
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +10 -10
- package/src/db/recovery.ts +3 -3
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +205 -44
- package/src/db/settings-repo.ts +2 -2
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +1 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +341 -304
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +96 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +43 -42
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +45 -10
- package/src/workspaces.ts +16 -16
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
package/src/db/git-state-repo.ts
CHANGED
|
@@ -40,7 +40,7 @@ export function setGitState(taskName: string, commitSha: string, branch?: string
|
|
|
40
40
|
ON CONFLICT(task_name) DO UPDATE SET
|
|
41
41
|
commit_sha = excluded.commit_sha,
|
|
42
42
|
branch = excluded.branch,
|
|
43
|
-
updated_at = excluded.updated_at
|
|
43
|
+
updated_at = excluded.updated_at`,
|
|
44
44
|
)
|
|
45
45
|
.run(taskName, commitSha, branch ?? null, new Date().toISOString());
|
|
46
46
|
}
|
package/src/db/history-repo.ts
CHANGED
|
@@ -105,7 +105,7 @@ export function insertHistory(record: StoredHistoryRecord): number {
|
|
|
105
105
|
record.nextTask ?? null,
|
|
106
106
|
record.workspaceId ?? null,
|
|
107
107
|
record.allowedTools == null ? null : JSON.stringify(record.allowedTools),
|
|
108
|
-
record.deniedTools == null ? null : JSON.stringify(record.deniedTools)
|
|
108
|
+
record.deniedTools == null ? null : JSON.stringify(record.deniedTools),
|
|
109
109
|
);
|
|
110
110
|
return lastId(result);
|
|
111
111
|
}
|
|
@@ -116,7 +116,7 @@ export function startRun(
|
|
|
116
116
|
startedAt = new Date().toISOString(),
|
|
117
117
|
workspaceId?: string | null,
|
|
118
118
|
allowedTools?: string[] | null,
|
|
119
|
-
deniedTools?: string[] | null
|
|
119
|
+
deniedTools?: string[] | null,
|
|
120
120
|
): number {
|
|
121
121
|
const id = insertHistory({
|
|
122
122
|
taskName,
|
|
@@ -153,7 +153,7 @@ export function finishRun(
|
|
|
153
153
|
costUsd?: number,
|
|
154
154
|
model?: string,
|
|
155
155
|
preFlightStatus?: "success" | "error" | "skipped",
|
|
156
|
-
postFlightStatus?: "success" | "error" | "skipped"
|
|
156
|
+
postFlightStatus?: "success" | "error" | "skipped",
|
|
157
157
|
): boolean {
|
|
158
158
|
const safeDuration = Number.isFinite(durationMs) ? Math.max(0, Math.floor(durationMs)) : 0;
|
|
159
159
|
const finishedAt = new Date().toISOString();
|
|
@@ -163,7 +163,7 @@ export function finishRun(
|
|
|
163
163
|
const instance = getDb();
|
|
164
164
|
const row = instance
|
|
165
165
|
.prepare("SELECT finished_at FROM history WHERE id = ?")
|
|
166
|
-
.get(id)
|
|
166
|
+
.get(id);
|
|
167
167
|
if (!row || row.finished_at != null) return false;
|
|
168
168
|
|
|
169
169
|
instance
|
|
@@ -172,7 +172,7 @@ export function finishRun(
|
|
|
172
172
|
status = ?, finished_at = ?, duration_ms = ?, error = ?, next_task = ?,
|
|
173
173
|
tokens = ?, cost_usd = ?, model = ?,
|
|
174
174
|
pre_flight_status = ?, post_flight_status = ?
|
|
175
|
-
WHERE id =
|
|
175
|
+
WHERE id = ?`,
|
|
176
176
|
)
|
|
177
177
|
.run(
|
|
178
178
|
status,
|
|
@@ -185,12 +185,12 @@ export function finishRun(
|
|
|
185
185
|
model ?? null,
|
|
186
186
|
preFlightStatus ?? null,
|
|
187
187
|
postFlightStatus ?? null,
|
|
188
|
-
id
|
|
188
|
+
id,
|
|
189
189
|
);
|
|
190
190
|
|
|
191
191
|
const taskRow = instance
|
|
192
192
|
.prepare("SELECT task_name, started_at FROM history WHERE id = ?")
|
|
193
|
-
.get(id)
|
|
193
|
+
.get(id);
|
|
194
194
|
incrementMetricsUnsafe(String(taskRow.task_name), status, tokens, costUsd);
|
|
195
195
|
completed = {
|
|
196
196
|
taskName: String(taskRow.task_name),
|
|
@@ -240,7 +240,7 @@ export function recordRun(
|
|
|
240
240
|
finishedAt = new Date().toISOString(),
|
|
241
241
|
workspaceId?: string | null,
|
|
242
242
|
allowedTools?: string[] | null,
|
|
243
|
-
deniedTools?: string[] | null
|
|
243
|
+
deniedTools?: string[] | null,
|
|
244
244
|
): number {
|
|
245
245
|
const safeDuration = Math.max(0, Math.floor(Number(durationMs) || 0));
|
|
246
246
|
const id = withTransaction(() => {
|
|
@@ -261,7 +261,7 @@ export function recordRun(
|
|
|
261
261
|
nextTask ?? null,
|
|
262
262
|
workspaceId ?? null,
|
|
263
263
|
allowedTools == null ? null : JSON.stringify(allowedTools),
|
|
264
|
-
deniedTools == null ? null : JSON.stringify(deniedTools)
|
|
264
|
+
deniedTools == null ? null : JSON.stringify(deniedTools),
|
|
265
265
|
);
|
|
266
266
|
incrementMetricsUnsafe(taskName, status, tokens, costUsd);
|
|
267
267
|
return lastId(result);
|
|
@@ -291,7 +291,7 @@ export function recordRun(
|
|
|
291
291
|
export function getHistory(
|
|
292
292
|
taskName?: string | null,
|
|
293
293
|
limit = 200,
|
|
294
|
-
status?: string | null
|
|
294
|
+
status?: string | null,
|
|
295
295
|
): StoredHistoryRecord[] {
|
|
296
296
|
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
297
297
|
const clauses: string[] = [];
|
|
@@ -320,16 +320,16 @@ export function getHistory(
|
|
|
320
320
|
.prepare(
|
|
321
321
|
`SELECT * FROM history${where}
|
|
322
322
|
ORDER BY started_at DESC, id DESC
|
|
323
|
-
LIMIT
|
|
323
|
+
LIMIT ?`,
|
|
324
324
|
)
|
|
325
|
-
.all(...params)
|
|
325
|
+
.all(...params);
|
|
326
326
|
return rows.map(rowToRecord);
|
|
327
327
|
}
|
|
328
328
|
|
|
329
329
|
/** История запусков, начатых не раньше timestamp (ISO-строка). */
|
|
330
330
|
export function getHistorySince(
|
|
331
331
|
timestamp: string,
|
|
332
|
-
limit = 5000
|
|
332
|
+
limit = 5000,
|
|
333
333
|
): StoredHistoryRecord[] {
|
|
334
334
|
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
335
335
|
const rows = getDb()
|
|
@@ -337,9 +337,9 @@ export function getHistorySince(
|
|
|
337
337
|
`SELECT * FROM history
|
|
338
338
|
WHERE started_at >= ?
|
|
339
339
|
ORDER BY started_at DESC, id DESC
|
|
340
|
-
LIMIT
|
|
340
|
+
LIMIT ?`,
|
|
341
341
|
)
|
|
342
|
-
.all(timestamp, safeLimit)
|
|
342
|
+
.all(timestamp, safeLimit);
|
|
343
343
|
return rows.map(rowToRecord);
|
|
344
344
|
}
|
|
345
345
|
|
|
@@ -363,7 +363,7 @@ export function recoverInterrupted(): number {
|
|
|
363
363
|
duration_ms,
|
|
364
364
|
CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
|
|
365
365
|
)
|
|
366
|
-
WHERE finished_at IS NULL
|
|
366
|
+
WHERE finished_at IS NULL`,
|
|
367
367
|
)
|
|
368
368
|
.run(now, now);
|
|
369
369
|
return Number(result.changes) || 0;
|
|
@@ -371,7 +371,7 @@ export function recoverInterrupted(): number {
|
|
|
371
371
|
|
|
372
372
|
/** Количество записей истории (для миграции и тестов). */
|
|
373
373
|
export function countHistory(): number {
|
|
374
|
-
const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get()
|
|
374
|
+
const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get();
|
|
375
375
|
return Number(row?.count) || 0;
|
|
376
376
|
}
|
|
377
377
|
|
|
@@ -379,7 +379,7 @@ export function countHistory(): number {
|
|
|
379
379
|
export function countRunningRecords(): number {
|
|
380
380
|
const row = getDb()
|
|
381
381
|
.prepare("SELECT COUNT(*) AS count FROM history WHERE finished_at IS NULL")
|
|
382
|
-
.get()
|
|
382
|
+
.get();
|
|
383
383
|
return Number(row?.count) || 0;
|
|
384
384
|
}
|
|
385
385
|
|
|
@@ -396,9 +396,9 @@ export function listRunningRecords(): RunningHistoryRecord[] {
|
|
|
396
396
|
.prepare(
|
|
397
397
|
`SELECT id, task_name, started_at FROM history
|
|
398
398
|
WHERE finished_at IS NULL
|
|
399
|
-
ORDER BY started_at ASC, id ASC
|
|
399
|
+
ORDER BY started_at ASC, id ASC`,
|
|
400
400
|
)
|
|
401
|
-
.all()
|
|
401
|
+
.all();
|
|
402
402
|
return rows.map((row) => ({
|
|
403
403
|
id: Number(row.id) || 0,
|
|
404
404
|
taskName: String(row.task_name ?? ""),
|
|
@@ -445,7 +445,7 @@ export function pruneHistory(options: PruneHistoryOptions = {}): PruneHistoryRes
|
|
|
445
445
|
const result = instance
|
|
446
446
|
.prepare(
|
|
447
447
|
`DELETE FROM history
|
|
448
|
-
WHERE finished_at IS NOT NULL AND finished_at <
|
|
448
|
+
WHERE finished_at IS NOT NULL AND finished_at < ?`,
|
|
449
449
|
)
|
|
450
450
|
.run(cutoff);
|
|
451
451
|
deletedByAge = Number(result.changes) || 0;
|
|
@@ -462,7 +462,7 @@ export function pruneHistory(options: PruneHistoryOptions = {}): PruneHistoryRes
|
|
|
462
462
|
WHERE finished_at IS NOT NULL
|
|
463
463
|
ORDER BY started_at DESC, id DESC
|
|
464
464
|
LIMIT ?
|
|
465
|
-
)
|
|
465
|
+
)`,
|
|
466
466
|
)
|
|
467
467
|
.run(Math.max(0, Math.floor(maxRecords)));
|
|
468
468
|
deletedByCount = Number(result.changes) || 0;
|
package/src/db/index.ts
CHANGED
|
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { PLUGIN_DIR } from "../types.js";
|
|
5
|
-
import { applySchema } from "./schema.js";
|
|
5
|
+
import { applySchema, getSchemaVersion, SCHEMA_VERSION } from "./schema.js";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Подключение к SQLite через встроенный `node:sqlite` (Node 22.5+).
|
|
@@ -43,7 +43,7 @@ function loadSqlite(): DatabaseSyncCtor {
|
|
|
43
43
|
} catch (err: any) {
|
|
44
44
|
throw new Error(
|
|
45
45
|
`node:sqlite недоступен (${err instanceof Error ? err.message : String(err)}). ` +
|
|
46
|
-
"Планировщику требуется Node.js 22.5+ (рекомендуется Node 24)."
|
|
46
|
+
"Планировщику требуется Node.js 22.5+ (рекомендуется Node 24).",
|
|
47
47
|
);
|
|
48
48
|
}
|
|
49
49
|
}
|
|
@@ -68,7 +68,11 @@ export function initDb(file: string = dbFile): SqliteDatabase {
|
|
|
68
68
|
const instance = new DatabaseSync(file);
|
|
69
69
|
|
|
70
70
|
// WAL — конкурентное чтение во время записи и устойчивость к сбоям.
|
|
71
|
+
// synchronous = NORMAL в WAL гарантирует, что закоммиченная транзакция
|
|
72
|
+
// переживает падение процесса (шаг 36.1.b); при потере питания может
|
|
73
|
+
// потеряться только последний коммит — это осознанный компромисс.
|
|
71
74
|
instance.exec("PRAGMA journal_mode = WAL;");
|
|
75
|
+
instance.exec("PRAGMA synchronous = NORMAL;");
|
|
72
76
|
instance.exec("PRAGMA foreign_keys = ON;");
|
|
73
77
|
instance.exec("PRAGMA busy_timeout = 5000;");
|
|
74
78
|
applySchema(instance);
|
|
@@ -114,11 +118,15 @@ export function getDbStatus(): {
|
|
|
114
118
|
file: string;
|
|
115
119
|
journalMode: string;
|
|
116
120
|
wal: boolean;
|
|
117
|
-
|
|
121
|
+
schemaVersion: number;
|
|
122
|
+
expectedSchemaVersion: number;
|
|
123
|
+
} {
|
|
118
124
|
let journalMode = "unknown";
|
|
125
|
+
let schemaVersion = 0;
|
|
119
126
|
try {
|
|
120
|
-
const row = getDb().prepare("PRAGMA journal_mode;").get()
|
|
127
|
+
const row = getDb().prepare("PRAGMA journal_mode;").get();
|
|
121
128
|
journalMode = String(row?.journal_mode ?? "unknown");
|
|
129
|
+
schemaVersion = getSchemaVersion(getDb());
|
|
122
130
|
} catch {
|
|
123
131
|
// Если БД ещё не открыта — не роняем health-check.
|
|
124
132
|
}
|
|
@@ -127,6 +135,8 @@ export function getDbStatus(): {
|
|
|
127
135
|
file: dbFile,
|
|
128
136
|
journalMode,
|
|
129
137
|
wal: journalMode.toLowerCase() === "wal",
|
|
138
|
+
schemaVersion,
|
|
139
|
+
expectedSchemaVersion: SCHEMA_VERSION,
|
|
130
140
|
};
|
|
131
141
|
}
|
|
132
142
|
|
|
@@ -159,8 +169,8 @@ export function isDatabaseEmpty(): boolean {
|
|
|
159
169
|
(SELECT COUNT(*) FROM tasks) +
|
|
160
170
|
(SELECT COUNT(*) FROM history) +
|
|
161
171
|
(SELECT COUNT(*) FROM metrics) +
|
|
162
|
-
(SELECT COUNT(*) FROM templates) AS count
|
|
172
|
+
(SELECT COUNT(*) FROM templates) AS count`,
|
|
163
173
|
)
|
|
164
|
-
.get()
|
|
174
|
+
.get();
|
|
165
175
|
return Number(row?.count) === 0;
|
|
166
176
|
}
|
package/src/db/metrics-repo.ts
CHANGED
|
@@ -55,7 +55,7 @@ export function incrementMetricsUnsafe(
|
|
|
55
55
|
taskName: string,
|
|
56
56
|
status: TaskStatus,
|
|
57
57
|
tokens = 0,
|
|
58
|
-
costUsd = 0
|
|
58
|
+
costUsd = 0,
|
|
59
59
|
): void {
|
|
60
60
|
// error — только ошибки и таймауты; partial хранится отдельным счётчиком,
|
|
61
61
|
// иначе дашборд показывал частичный запуск как обычную ошибку.
|
|
@@ -75,7 +75,7 @@ export function incrementMetricsUnsafe(
|
|
|
75
75
|
error = error + excluded.error,
|
|
76
76
|
partial = partial + excluded.partial,
|
|
77
77
|
total_tokens = total_tokens + excluded.total_tokens,
|
|
78
|
-
total_cost = total_cost + excluded.total_cost
|
|
78
|
+
total_cost = total_cost + excluded.total_cost`,
|
|
79
79
|
)
|
|
80
80
|
.run(taskName, success, error, partial, safeTokens, safeCost);
|
|
81
81
|
}
|
|
@@ -85,7 +85,7 @@ export function incrementMetrics(
|
|
|
85
85
|
taskName: string,
|
|
86
86
|
status: TaskStatus,
|
|
87
87
|
tokens?: number,
|
|
88
|
-
costUsd?: number
|
|
88
|
+
costUsd?: number,
|
|
89
89
|
): void {
|
|
90
90
|
incrementMetricsUnsafe(taskName, status, tokens, costUsd);
|
|
91
91
|
}
|
|
@@ -94,7 +94,7 @@ export function incrementMetrics(
|
|
|
94
94
|
export function getMetrics(taskName: string): TaskMetricsRow {
|
|
95
95
|
const row = getDb()
|
|
96
96
|
.prepare("SELECT * FROM metrics WHERE lower(task_name) = lower(?) LIMIT 1")
|
|
97
|
-
.get(taskName)
|
|
97
|
+
.get(taskName);
|
|
98
98
|
if (!row) {
|
|
99
99
|
return { taskName, total: 0, success: 0, error: 0, partial: 0, tokens: 0, costUsd: 0 };
|
|
100
100
|
}
|
|
@@ -105,7 +105,7 @@ export function getMetrics(taskName: string): TaskMetricsRow {
|
|
|
105
105
|
export function getAllMetrics(includeInternal = false): TaskMetricsRow[] {
|
|
106
106
|
const rows = getDb()
|
|
107
107
|
.prepare("SELECT * FROM metrics ORDER BY task_name COLLATE NOCASE ASC")
|
|
108
|
-
.all()
|
|
108
|
+
.all();
|
|
109
109
|
return rows.map(rowToMetrics).filter((row) => includeInternal || !isInternal(row.taskName));
|
|
110
110
|
}
|
|
111
111
|
|
|
@@ -120,9 +120,9 @@ export function getTotals(): MetricsTotals {
|
|
|
120
120
|
COALESCE(SUM(partial), 0) AS partial,
|
|
121
121
|
COALESCE(SUM(total_tokens), 0) AS tokens,
|
|
122
122
|
COALESCE(SUM(total_cost), 0) AS cost_usd
|
|
123
|
-
FROM metrics
|
|
123
|
+
FROM metrics`,
|
|
124
124
|
)
|
|
125
|
-
.get()
|
|
125
|
+
.get();
|
|
126
126
|
return {
|
|
127
127
|
total: Number(row?.total) || 0,
|
|
128
128
|
success: Number(row?.success) || 0,
|
|
@@ -150,7 +150,7 @@ export function upsertMetricsRow(row: TaskMetricsRow): void {
|
|
|
150
150
|
error = excluded.error,
|
|
151
151
|
partial = excluded.partial,
|
|
152
152
|
total_tokens = excluded.total_tokens,
|
|
153
|
-
total_cost = excluded.total_cost
|
|
153
|
+
total_cost = excluded.total_cost`,
|
|
154
154
|
)
|
|
155
155
|
.run(
|
|
156
156
|
row.taskName,
|
|
@@ -159,12 +159,12 @@ export function upsertMetricsRow(row: TaskMetricsRow): void {
|
|
|
159
159
|
Math.max(0, Math.floor(row.error)),
|
|
160
160
|
Math.max(0, Math.floor(row.partial)),
|
|
161
161
|
Math.max(0, Math.floor(row.tokens)),
|
|
162
|
-
Math.max(0, row.costUsd)
|
|
162
|
+
Math.max(0, row.costUsd),
|
|
163
163
|
);
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
/** Количество строк метрик. */
|
|
167
167
|
export function countMetrics(): number {
|
|
168
|
-
const row = getDb().prepare("SELECT COUNT(*) AS count FROM metrics").get()
|
|
168
|
+
const row = getDb().prepare("SELECT COUNT(*) AS count FROM metrics").get();
|
|
169
169
|
return Number(row?.count) || 0;
|
|
170
170
|
}
|
package/src/db/migrate.ts
CHANGED
|
@@ -55,7 +55,7 @@ async function loadJsonFile(file: string): Promise<LoadedFile> {
|
|
|
55
55
|
throw new Error(
|
|
56
56
|
`Некорректный JSON в ${path.basename(file)}: ${
|
|
57
57
|
err instanceof Error ? err.message : String(err)
|
|
58
|
-
}
|
|
58
|
+
}`,
|
|
59
59
|
);
|
|
60
60
|
}
|
|
61
61
|
} catch (err: any) {
|
|
@@ -113,12 +113,12 @@ function normalizeHistoryRow(raw: any): any | null {
|
|
|
113
113
|
* migrated: false и нули.
|
|
114
114
|
*/
|
|
115
115
|
export async function migrateJsonToDb(
|
|
116
|
-
pluginDir: string = PLUGIN_DIR
|
|
116
|
+
pluginDir: string = PLUGIN_DIR,
|
|
117
117
|
): Promise<MigrationResult> {
|
|
118
118
|
if (!isDatabaseEmpty()) return { ...EMPTY_RESULT };
|
|
119
119
|
|
|
120
120
|
const files = await Promise.all(
|
|
121
|
-
JSON_FILES.map((name) => loadJsonFile(path.join(pluginDir, name)))
|
|
121
|
+
JSON_FILES.map((name) => loadJsonFile(path.join(pluginDir, name))),
|
|
122
122
|
);
|
|
123
123
|
if (!files.some((file) => file.exists)) return { ...EMPTY_RESULT };
|
|
124
124
|
|
|
@@ -147,7 +147,7 @@ export async function migrateJsonToDb(
|
|
|
147
147
|
|
|
148
148
|
// --- tasks ---
|
|
149
149
|
const insertTask = db.prepare(
|
|
150
|
-
"INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)"
|
|
150
|
+
"INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)",
|
|
151
151
|
);
|
|
152
152
|
const seenTasks = new Set<string>();
|
|
153
153
|
for (const item of taskItems) {
|
|
@@ -182,7 +182,7 @@ export async function migrateJsonToDb(
|
|
|
182
182
|
`INSERT INTO history (
|
|
183
183
|
task_name, status, started_at, finished_at, duration_ms, error,
|
|
184
184
|
tokens, cost_usd, model, pre_flight_status, post_flight_status, next_task
|
|
185
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
185
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
186
186
|
);
|
|
187
187
|
for (const row of historyItems) {
|
|
188
188
|
insertHistory.run(
|
|
@@ -197,14 +197,14 @@ export async function migrateJsonToDb(
|
|
|
197
197
|
row.model,
|
|
198
198
|
row.preFlightStatus,
|
|
199
199
|
row.postFlightStatus,
|
|
200
|
-
row.nextTask
|
|
200
|
+
row.nextTask,
|
|
201
201
|
);
|
|
202
202
|
insertedHistory += 1;
|
|
203
203
|
}
|
|
204
204
|
|
|
205
205
|
// --- templates ---
|
|
206
206
|
const insertTemplate = db.prepare(
|
|
207
|
-
"INSERT INTO templates (id, name, definition_json) VALUES (?, ?, ?)"
|
|
207
|
+
"INSERT INTO templates (id, name, definition_json) VALUES (?, ?, ?)",
|
|
208
208
|
);
|
|
209
209
|
const seenTemplates = new Set<string>();
|
|
210
210
|
for (const item of templateItems) {
|
|
@@ -259,7 +259,7 @@ export async function migrateJsonToDb(
|
|
|
259
259
|
tokens: acc.tokens + row.tokens,
|
|
260
260
|
costUsd: acc.costUsd + row.costUsd,
|
|
261
261
|
}),
|
|
262
|
-
{ total: 0, success: 0, error: 0, partial: 0, tokens: 0, costUsd: 0 }
|
|
262
|
+
{ total: 0, success: 0, error: 0, partial: 0, tokens: 0, costUsd: 0 },
|
|
263
263
|
);
|
|
264
264
|
|
|
265
265
|
const extra = {
|
|
@@ -308,13 +308,13 @@ export async function migrateJsonToDb(
|
|
|
308
308
|
console.error(
|
|
309
309
|
`[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${
|
|
310
310
|
err instanceof Error ? err.message : String(err)
|
|
311
|
-
}
|
|
311
|
+
}`,
|
|
312
312
|
);
|
|
313
313
|
}
|
|
314
314
|
}
|
|
315
315
|
|
|
316
316
|
console.log(
|
|
317
|
-
`[migrate] Перемещено ${insertedTasks} задач, ${insertedHistory} записей истории, ${insertedTemplates}
|
|
317
|
+
`[migrate] Перемещено ${insertedTasks} задач, ${insertedHistory} записей истории, ${insertedTemplates} шаблонов.`,
|
|
318
318
|
);
|
|
319
319
|
|
|
320
320
|
return {
|
package/src/db/recovery.ts
CHANGED
|
@@ -15,7 +15,7 @@ export function recoverInterruptedRuns(): number {
|
|
|
15
15
|
const count = recoverInterrupted();
|
|
16
16
|
if (count > 0) {
|
|
17
17
|
console.log(
|
|
18
|
-
`[recovery] Восстановлено ${count} незавершённых записей истории — помечены как error
|
|
18
|
+
`[recovery] Восстановлено ${count} незавершённых записей истории — помечены как error.`,
|
|
19
19
|
);
|
|
20
20
|
}
|
|
21
21
|
return count;
|
|
@@ -33,14 +33,14 @@ export function checkJsonBackups(): boolean {
|
|
|
33
33
|
} catch {
|
|
34
34
|
return false;
|
|
35
35
|
}
|
|
36
|
-
}
|
|
36
|
+
},
|
|
37
37
|
);
|
|
38
38
|
|
|
39
39
|
if (backups.length === 0) return false;
|
|
40
40
|
if (!isDatabaseEmpty()) return false;
|
|
41
41
|
|
|
42
42
|
console.warn(
|
|
43
|
-
"[recovery] Обнаружены бэкапы JSON, БД пуста. Запустите миграцию заново."
|
|
43
|
+
"[recovery] Обнаружены бэкапы JSON, БД пуста. Запустите миграцию заново.",
|
|
44
44
|
);
|
|
45
45
|
return true;
|
|
46
46
|
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { getDb, withTransaction } from "./index.js";
|
|
2
|
+
import {
|
|
3
|
+
finishStep,
|
|
4
|
+
getRun,
|
|
5
|
+
getStep,
|
|
6
|
+
retryStep,
|
|
7
|
+
startRun,
|
|
8
|
+
startStep,
|
|
9
|
+
type FinishOptions,
|
|
10
|
+
type RunRecord,
|
|
11
|
+
type RunStepRecord,
|
|
12
|
+
} from "./runs-repo.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Журнал выполнения шагов (Sprint 36.1.b).
|
|
16
|
+
*
|
|
17
|
+
* Каждый переход шага пишется отдельной транзакцией и фиксируется в WAL
|
|
18
|
+
* **до** запуска тела шага и **после** него. Если процесс убьют посреди шага,
|
|
19
|
+
* в БД останется строка `running` с номером попытки `attempt`: её помечает
|
|
20
|
+
* `recoverInterruptedSteps()`, а повтор идёт через `retryStep()` с `attempt + 1`.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Текст ошибки, которым помечается шаг, прерванный падением процесса. */
|
|
24
|
+
export const STEP_INTERRUPTED_ERROR = "Прервано падением процесса";
|
|
25
|
+
|
|
26
|
+
/** Опции начала попытки. */
|
|
27
|
+
export interface BeginStepOptions {
|
|
28
|
+
/** Начать запуск, если он ещё в статусе pending (по умолчанию true). */
|
|
29
|
+
startRun?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Результат выполнения шага через `runStepStatefully`. */
|
|
33
|
+
export interface StepExecution<T> {
|
|
34
|
+
/** Состояние шага после завершения. */
|
|
35
|
+
step: RunStepRecord;
|
|
36
|
+
/** Значение, которое вернуло тело шага. */
|
|
37
|
+
result: T;
|
|
38
|
+
/** Номер попытки, с которым выполнялся шаг. */
|
|
39
|
+
attempt: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function nowIso(): string {
|
|
43
|
+
return new Date().toISOString();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function errorMessage(err: unknown): string {
|
|
47
|
+
if (err instanceof Error) return err.message;
|
|
48
|
+
return String(err);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Открывает попытку шага: run pending → running (если нужно), шаг pending → running.
|
|
53
|
+
*
|
|
54
|
+
* Запись коммитится до возврата управления, поэтому вызывающий код может
|
|
55
|
+
* безопасно запускать побочные эффекты: факт старта уже на диске.
|
|
56
|
+
*
|
|
57
|
+
* Если шаг остался `failed` после падения — выполняется `retryStep`, и номер
|
|
58
|
+
* попытки увеличивается, а не начинается заново.
|
|
59
|
+
*/
|
|
60
|
+
export function beginStepAttempt(
|
|
61
|
+
runId: string,
|
|
62
|
+
stepName: string,
|
|
63
|
+
options: BeginStepOptions = {},
|
|
64
|
+
): RunStepRecord {
|
|
65
|
+
if (options.startRun !== false) {
|
|
66
|
+
const run = requireRun(runId);
|
|
67
|
+
if (run.status === "pending") startRun(runId);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const step = requireStep(runId, stepName);
|
|
71
|
+
if (step.status === "failed") {
|
|
72
|
+
retryStep(step.id);
|
|
73
|
+
} else {
|
|
74
|
+
startStep(step.id);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return requireStep(runId, stepName);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Закрывает попытку успехом: running → passed, сохраняет output. */
|
|
81
|
+
export function recordStepSuccess(
|
|
82
|
+
runId: string,
|
|
83
|
+
stepName: string,
|
|
84
|
+
output?: unknown,
|
|
85
|
+
): RunStepRecord {
|
|
86
|
+
completeStep(runId, stepName, "passed", { output });
|
|
87
|
+
return requireStep(runId, stepName);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Закрывает попытку ошибкой: running → failed, сохраняет текст ошибки. */
|
|
91
|
+
export function recordStepFailure(
|
|
92
|
+
runId: string,
|
|
93
|
+
stepName: string,
|
|
94
|
+
error: unknown,
|
|
95
|
+
): RunStepRecord {
|
|
96
|
+
completeStep(runId, stepName, "failed", { error: errorMessage(error) });
|
|
97
|
+
return requireStep(runId, stepName);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Выполняет шаг с журналированием: состояние `running` фиксируется до вызова
|
|
102
|
+
* `body`, результат (`passed`/`failed`) — после. Ошибка тела не теряется:
|
|
103
|
+
* шаг помечается failed, исключение пробрасывается дальше.
|
|
104
|
+
*/
|
|
105
|
+
export function runStepStatefully<T>(
|
|
106
|
+
runId: string,
|
|
107
|
+
stepName: string,
|
|
108
|
+
body: () => T,
|
|
109
|
+
options: BeginStepOptions = {},
|
|
110
|
+
): StepExecution<T> {
|
|
111
|
+
const attempt = beginStepAttempt(runId, stepName, options).attempt;
|
|
112
|
+
let result: T;
|
|
113
|
+
try {
|
|
114
|
+
result = body();
|
|
115
|
+
} catch (err) {
|
|
116
|
+
recordStepFailure(runId, stepName, err);
|
|
117
|
+
throw err;
|
|
118
|
+
}
|
|
119
|
+
const step = recordStepSuccess(runId, stepName, result);
|
|
120
|
+
return { step, result, attempt };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Асинхронный вариант `runStepStatefully` для шагов с I/O. */
|
|
124
|
+
export async function runStepStatefullyAsync<T>(
|
|
125
|
+
runId: string,
|
|
126
|
+
stepName: string,
|
|
127
|
+
body: () => Promise<T> | T,
|
|
128
|
+
options: BeginStepOptions = {},
|
|
129
|
+
): Promise<StepExecution<T>> {
|
|
130
|
+
const attempt = beginStepAttempt(runId, stepName, options).attempt;
|
|
131
|
+
let result: T;
|
|
132
|
+
try {
|
|
133
|
+
result = await body();
|
|
134
|
+
} catch (err) {
|
|
135
|
+
recordStepFailure(runId, stepName, err);
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
const step = recordStepSuccess(runId, stepName, result);
|
|
139
|
+
return { step, result, attempt };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Помечает все зависшие `running`-шаги как failed, сохраняя `attempt`.
|
|
144
|
+
*
|
|
145
|
+
* Возвращает обновлённые записи. `attempt` не сбрасывается — следующая попытка
|
|
146
|
+
* получит `attempt + 1` через `retryStep`, поэтому номер попытки переживает
|
|
147
|
+
* падение процесса и восстановление.
|
|
148
|
+
*/
|
|
149
|
+
export function recoverInterruptedSteps(runId?: string): RunStepRecord[] {
|
|
150
|
+
const running = listRunningSteps(runId);
|
|
151
|
+
if (running.length === 0) return [];
|
|
152
|
+
|
|
153
|
+
return withTransaction(() => {
|
|
154
|
+
const timestamp = nowIso();
|
|
155
|
+
const update = getDb().prepare(
|
|
156
|
+
`UPDATE run_steps SET status = 'failed', error = ?, finished_at = ?,
|
|
157
|
+
updated_at = ? WHERE id = ? AND status = 'running'`,
|
|
158
|
+
);
|
|
159
|
+
for (const step of running) {
|
|
160
|
+
update.run(STEP_INTERRUPTED_ERROR, timestamp, timestamp, step.id);
|
|
161
|
+
}
|
|
162
|
+
return running.map((step) => requireStep(step.runId, step.stepName));
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Список шагов в статусе running (для диагностики и восстановления). */
|
|
167
|
+
export function listRunningSteps(runId?: string): RunStepRecord[] {
|
|
168
|
+
const sql = runId
|
|
169
|
+
? "SELECT run_id, step_name FROM run_steps WHERE status = 'running' AND run_id = ? ORDER BY created_at"
|
|
170
|
+
: "SELECT run_id, step_name FROM run_steps WHERE status = 'running' ORDER BY created_at";
|
|
171
|
+
const statement = getDb().prepare(sql);
|
|
172
|
+
const rows = (runId ? statement.all(runId) : statement.all()) as {
|
|
173
|
+
run_id: string;
|
|
174
|
+
step_name: string;
|
|
175
|
+
}[];
|
|
176
|
+
|
|
177
|
+
const steps: RunStepRecord[] = [];
|
|
178
|
+
for (const row of rows) {
|
|
179
|
+
const step = getStep(String(row.run_id), String(row.step_name));
|
|
180
|
+
if (step && step.status === "running") steps.push(step);
|
|
181
|
+
}
|
|
182
|
+
return steps;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Запуск по id либо ошибка (удобно для журнала и тестов). */
|
|
186
|
+
export function requireRun(runId: string): RunRecord {
|
|
187
|
+
const run = getRun(runId);
|
|
188
|
+
if (!run) throw new Error(`Запуск не найден: ${runId}`);
|
|
189
|
+
return run;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function requireStep(runId: string, stepName: string): RunStepRecord {
|
|
193
|
+
const step = getStep(runId, stepName);
|
|
194
|
+
if (!step) throw new Error(`Шаг не найден: ${runId}/${stepName}`);
|
|
195
|
+
return step;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function completeStep(
|
|
199
|
+
runId: string,
|
|
200
|
+
stepName: string,
|
|
201
|
+
status: "passed" | "failed",
|
|
202
|
+
options: FinishOptions,
|
|
203
|
+
): void {
|
|
204
|
+
const step = requireStep(runId, stepName);
|
|
205
|
+
if (step.status !== "running") {
|
|
206
|
+
// Повторная запись результата — ошибка вызывающего кода, а не «тихий» пропуск.
|
|
207
|
+
throw new Error(
|
|
208
|
+
`Шаг ${runId}/${stepName} не выполняется (статус ${step.status}), запись ${status} невозможна.`,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
finishStep(step.id, status, options);
|
|
212
|
+
}
|