agent-steward 0.0.0-stage → 0.0.2
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 +376 -0
- package/CROSS_PLATFORM.md +149 -0
- package/LICENSE +21 -0
- package/README.md +314 -2
- package/ROADMAP-STRATEGY.md +147 -0
- package/ROADMAP.md +1069 -0
- package/dist/core/analytics.d.ts +132 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +290 -0
- package/dist/core/audit.d.ts +96 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +297 -0
- package/dist/core/cron-to-schtasks.d.ts +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +250 -0
- package/dist/core/dry-run.d.ts +102 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +447 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +186 -0
- package/dist/core/git-trigger.d.ts +82 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +312 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +57 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +195 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +724 -0
- package/dist/core/native-notify.d.ts +36 -0
- package/dist/core/native-notify.d.ts.map +1 -0
- package/dist/core/native-notify.js +113 -0
- package/dist/core/one-shot.d.ts +68 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +139 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +73 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +1071 -0
- package/dist/core/record-history.d.ts +25 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +471 -0
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +211 -0
- package/dist/core/schedule-v2.d.ts +116 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +586 -0
- package/dist/core/scheduler/index.d.ts +32 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +63 -0
- package/dist/core/scheduler/linux.d.ts +44 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +225 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +40 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +207 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +89 -0
- package/dist/core/scheduler/registry.d.ts +41 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +57 -0
- package/dist/core/scheduler/types.d.ts +86 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +99 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +596 -0
- package/dist/core/secrets.d.ts +66 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +433 -0
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/self-analysis.test.d.ts +2 -0
- package/dist/core/self-analysis.test.d.ts.map +1 -0
- package/dist/core/self-analysis.test.js +219 -0
- package/dist/core/session.d.ts +42 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +134 -0
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +146 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +55 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +344 -0
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +95 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +413 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/history-repo.d.ts +110 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +300 -0
- package/dist/db/index.d.ts +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -0
- package/dist/db/metrics-repo.d.ts +46 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +103 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +244 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +170 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/gui-experimental.cjs +1 -0
- package/dist/history.d.ts +60 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +70 -0
- package/dist/i18n.d.ts +75 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +357 -0
- package/dist/index.d.ts +858 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5179 -0
- package/dist/integrations.d.ts +72 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +233 -0
- package/dist/notifications.d.ts +199 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +967 -0
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +227 -0
- package/dist/rpc.d.ts +3806 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1507 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +128 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2413 -0
- package/dist/settings.d.ts +389 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +770 -0
- package/dist/shared/jobs-view.d.ts +59 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +146 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +252 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +628 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +96 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +130 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +113 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +393 -0
- package/docs/ARCHITECTURE.md +457 -0
- package/docs/COMPATIBILITY.md +233 -0
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +698 -0
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +355 -0
- package/docs/README.ru.md +268 -0
- package/docs/README.zh.md +305 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/dashboard.png +0 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +9 -0
- package/index.js +1 -0
- package/locales/en.json +780 -0
- package/locales/ru.json +780 -0
- package/locales/zh.json +780 -0
- package/package.json +149 -4
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/demo-dashboard.mjs +209 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +45 -0
- package/skills/scheduled-job-best-practices/SKILL.md +158 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
- package/src/core/analytics.ts +424 -0
- package/src/core/audit.ts +418 -0
- package/src/core/cron-to-schtasks.ts +288 -0
- package/src/core/dry-run.ts +601 -0
- package/src/core/file-watcher.ts +245 -0
- package/src/core/git-trigger.ts +391 -0
- package/src/core/glob.ts +226 -0
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +219 -0
- package/src/core/matrix.ts +947 -0
- package/src/core/native-notify.ts +157 -0
- package/src/core/one-shot.ts +189 -0
- package/src/core/otel.ts +128 -0
- package/src/core/permissions.ts +200 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +1140 -0
- package/src/core/record-history.ts +615 -0
- package/src/core/retention.ts +141 -0
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +253 -0
- package/src/core/schedule-v2.ts +668 -0
- package/src/core/scheduler/index.ts +82 -0
- package/src/core/scheduler/linux.ts +257 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +270 -0
- package/src/core/scheduler/posix.ts +114 -0
- package/src/core/scheduler/registry.ts +99 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +711 -0
- package/src/core/secrets.ts +503 -0
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +150 -0
- package/src/core/shutdown.ts +69 -0
- package/src/core/structured-log.ts +214 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +436 -0
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +532 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/history-repo.ts +492 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +170 -0
- package/src/db/migrate.ts +328 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +188 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +5222 -0
- package/src/history.ts +128 -0
- package/src/i18n.ts +413 -0
- package/src/index.ts +6605 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +254 -0
- package/src/rpc.ts +1609 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2662 -0
- package/src/settings.ts +1369 -0
- package/src/shared/jobs-view.ts +188 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +944 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +191 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { getDb, withTransaction } from "./index.js";
|
|
2
|
+
import { incrementMetricsUnsafe } from "./metrics-repo.js";
|
|
3
|
+
import { appendStructuredLog } from "../core/structured-log.js";
|
|
4
|
+
import type { TaskStatus } from "../history.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* История запусков.
|
|
8
|
+
*
|
|
9
|
+
* completed-запись пишется одной транзакцией вместе с инкрементом метрик.
|
|
10
|
+
* Незавершённые запуски (finished_at IS NULL) при старте помечаются как error
|
|
11
|
+
* в crash recovery.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type HistoryStatus = TaskStatus | "running";
|
|
15
|
+
|
|
16
|
+
export interface StoredHistoryRecord {
|
|
17
|
+
id?: number;
|
|
18
|
+
taskName: string;
|
|
19
|
+
status: HistoryStatus;
|
|
20
|
+
startedAt: string;
|
|
21
|
+
finishedAt?: string | null;
|
|
22
|
+
durationMs?: number | null;
|
|
23
|
+
error?: string | null;
|
|
24
|
+
nextTask?: string | null;
|
|
25
|
+
tokens?: number;
|
|
26
|
+
costUsd?: number;
|
|
27
|
+
model?: string;
|
|
28
|
+
preFlightStatus?: "success" | "error" | "skipped";
|
|
29
|
+
postFlightStatus?: "success" | "error" | "skipped";
|
|
30
|
+
workspaceId?: string | null;
|
|
31
|
+
allowedTools?: string[] | null;
|
|
32
|
+
deniedTools?: string[] | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Поля, которые пишутся в history при завершении запуска. */
|
|
36
|
+
export interface RunResult {
|
|
37
|
+
taskName: string;
|
|
38
|
+
status: TaskStatus;
|
|
39
|
+
startedAt: string;
|
|
40
|
+
durationMs: number;
|
|
41
|
+
error?: string | null;
|
|
42
|
+
nextTask?: string | null;
|
|
43
|
+
tokens?: number;
|
|
44
|
+
costUsd?: number;
|
|
45
|
+
model?: string;
|
|
46
|
+
preFlightStatus?: "success" | "error" | "skipped";
|
|
47
|
+
postFlightStatus?: "success" | "error" | "skipped";
|
|
48
|
+
finishedAt?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function rowToRecord(row: any): StoredHistoryRecord {
|
|
52
|
+
const status = String(row.status) as HistoryStatus;
|
|
53
|
+
return {
|
|
54
|
+
id: Number(row.id),
|
|
55
|
+
taskName: String(row.task_name),
|
|
56
|
+
status,
|
|
57
|
+
startedAt: String(row.started_at),
|
|
58
|
+
finishedAt: row.finished_at == null ? null : String(row.finished_at),
|
|
59
|
+
durationMs: row.duration_ms == null ? null : Number(row.duration_ms),
|
|
60
|
+
error: row.error == null ? null : String(row.error),
|
|
61
|
+
nextTask: row.next_task == null ? null : String(row.next_task),
|
|
62
|
+
tokens: row.tokens == null ? undefined : Number(row.tokens),
|
|
63
|
+
costUsd: row.cost_usd == null ? undefined : Number(row.cost_usd),
|
|
64
|
+
model: row.model == null ? undefined : String(row.model),
|
|
65
|
+
preFlightStatus:
|
|
66
|
+
row.pre_flight_status == null
|
|
67
|
+
? undefined
|
|
68
|
+
: (String(row.pre_flight_status) as "success" | "error" | "skipped"),
|
|
69
|
+
postFlightStatus:
|
|
70
|
+
row.post_flight_status == null
|
|
71
|
+
? undefined
|
|
72
|
+
: (String(row.post_flight_status) as "success" | "error" | "skipped"),
|
|
73
|
+
workspaceId: row.workspace_id == null ? null : String(row.workspace_id),
|
|
74
|
+
allowedTools: row.allowed_tools == null ? null : JSON.parse(String(row.allowed_tools)),
|
|
75
|
+
deniedTools: row.denied_tools == null ? null : JSON.parse(String(row.denied_tools)),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const INSERT_SQL = `INSERT INTO history (
|
|
80
|
+
task_name, status, started_at, finished_at, duration_ms, error,
|
|
81
|
+
tokens, cost_usd, model, pre_flight_status, post_flight_status, next_task,
|
|
82
|
+
workspace_id, allowed_tools, denied_tools
|
|
83
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
|
|
84
|
+
|
|
85
|
+
function lastId(result: { lastInsertRowid: number | bigint }): number {
|
|
86
|
+
return Number(result.lastInsertRowid) || 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Вставляет запись истории без инкремента метрик (совместимость с appendHistory). */
|
|
90
|
+
export function insertHistory(record: StoredHistoryRecord): number {
|
|
91
|
+
const result = getDb()
|
|
92
|
+
.prepare(INSERT_SQL)
|
|
93
|
+
.run(
|
|
94
|
+
record.taskName,
|
|
95
|
+
record.status,
|
|
96
|
+
record.startedAt,
|
|
97
|
+
record.finishedAt ?? null,
|
|
98
|
+
record.durationMs ?? null,
|
|
99
|
+
record.error ?? null,
|
|
100
|
+
record.tokens ?? null,
|
|
101
|
+
record.costUsd ?? null,
|
|
102
|
+
record.model ?? null,
|
|
103
|
+
record.preFlightStatus ?? null,
|
|
104
|
+
record.postFlightStatus ?? null,
|
|
105
|
+
record.nextTask ?? null,
|
|
106
|
+
record.workspaceId ?? null,
|
|
107
|
+
record.allowedTools == null ? null : JSON.stringify(record.allowedTools),
|
|
108
|
+
record.deniedTools == null ? null : JSON.stringify(record.deniedTools)
|
|
109
|
+
);
|
|
110
|
+
return lastId(result);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Начало запуска: строка с finished_at = NULL (переживёт сбой процесса). */
|
|
114
|
+
export function startRun(
|
|
115
|
+
taskName: string,
|
|
116
|
+
startedAt = new Date().toISOString(),
|
|
117
|
+
workspaceId?: string | null,
|
|
118
|
+
allowedTools?: string[] | null,
|
|
119
|
+
deniedTools?: string[] | null
|
|
120
|
+
): number {
|
|
121
|
+
const id = insertHistory({
|
|
122
|
+
taskName,
|
|
123
|
+
status: "running",
|
|
124
|
+
startedAt,
|
|
125
|
+
finishedAt: null,
|
|
126
|
+
workspaceId,
|
|
127
|
+
allowedTools,
|
|
128
|
+
deniedTools,
|
|
129
|
+
});
|
|
130
|
+
appendStructuredLog({
|
|
131
|
+
event: "run.started",
|
|
132
|
+
runId: id,
|
|
133
|
+
task: taskName,
|
|
134
|
+
status: "running",
|
|
135
|
+
startedAt,
|
|
136
|
+
workspaceId: workspaceId ?? null,
|
|
137
|
+
source: "startRun",
|
|
138
|
+
});
|
|
139
|
+
return id;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Завершает ранее начатый запуск и инкрементирует метрики.
|
|
144
|
+
* Возвращает false, если запись уже завершена/не найдена (защита от двойного учёта).
|
|
145
|
+
*/
|
|
146
|
+
export function finishRun(
|
|
147
|
+
id: number,
|
|
148
|
+
status: TaskStatus,
|
|
149
|
+
durationMs: number,
|
|
150
|
+
error?: string | null,
|
|
151
|
+
nextTask?: string | null,
|
|
152
|
+
tokens?: number,
|
|
153
|
+
costUsd?: number,
|
|
154
|
+
model?: string,
|
|
155
|
+
preFlightStatus?: "success" | "error" | "skipped",
|
|
156
|
+
postFlightStatus?: "success" | "error" | "skipped"
|
|
157
|
+
): boolean {
|
|
158
|
+
const safeDuration = Number.isFinite(durationMs) ? Math.max(0, Math.floor(durationMs)) : 0;
|
|
159
|
+
const finishedAt = new Date().toISOString();
|
|
160
|
+
let completed: { taskName: string; startedAt: string } | null = null;
|
|
161
|
+
|
|
162
|
+
const ok = withTransaction(() => {
|
|
163
|
+
const instance = getDb();
|
|
164
|
+
const row = instance
|
|
165
|
+
.prepare("SELECT finished_at FROM history WHERE id = ?")
|
|
166
|
+
.get(id) as any;
|
|
167
|
+
if (!row || row.finished_at != null) return false;
|
|
168
|
+
|
|
169
|
+
instance
|
|
170
|
+
.prepare(
|
|
171
|
+
`UPDATE history SET
|
|
172
|
+
status = ?, finished_at = ?, duration_ms = ?, error = ?, next_task = ?,
|
|
173
|
+
tokens = ?, cost_usd = ?, model = ?,
|
|
174
|
+
pre_flight_status = ?, post_flight_status = ?
|
|
175
|
+
WHERE id = ?`
|
|
176
|
+
)
|
|
177
|
+
.run(
|
|
178
|
+
status,
|
|
179
|
+
finishedAt,
|
|
180
|
+
safeDuration,
|
|
181
|
+
error ?? null,
|
|
182
|
+
nextTask ?? null,
|
|
183
|
+
tokens ?? null,
|
|
184
|
+
costUsd ?? null,
|
|
185
|
+
model ?? null,
|
|
186
|
+
preFlightStatus ?? null,
|
|
187
|
+
postFlightStatus ?? null,
|
|
188
|
+
id
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const taskRow = instance
|
|
192
|
+
.prepare("SELECT task_name, started_at FROM history WHERE id = ?")
|
|
193
|
+
.get(id) as any;
|
|
194
|
+
incrementMetricsUnsafe(String(taskRow.task_name), status, tokens, costUsd);
|
|
195
|
+
completed = {
|
|
196
|
+
taskName: String(taskRow.task_name),
|
|
197
|
+
startedAt: String(taskRow.started_at),
|
|
198
|
+
};
|
|
199
|
+
return true;
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
if (ok && completed) {
|
|
203
|
+
const done = completed as { taskName: string; startedAt: string };
|
|
204
|
+
appendStructuredLog({
|
|
205
|
+
event: "run.finished",
|
|
206
|
+
runId: id,
|
|
207
|
+
task: done.taskName,
|
|
208
|
+
status,
|
|
209
|
+
startedAt: done.startedAt,
|
|
210
|
+
finishedAt,
|
|
211
|
+
durationMs: safeDuration,
|
|
212
|
+
error: error ?? null,
|
|
213
|
+
nextTask: nextTask ?? null,
|
|
214
|
+
tokens,
|
|
215
|
+
costUsd,
|
|
216
|
+
model,
|
|
217
|
+
preFlightStatus,
|
|
218
|
+
postFlightStatus,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return ok;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Записывает завершённый запуск: history + metrics в одной транзакции.
|
|
226
|
+
* Заменяет старый recordTaskRun/recordRun.
|
|
227
|
+
*/
|
|
228
|
+
export function recordRun(
|
|
229
|
+
taskName: string,
|
|
230
|
+
status: TaskStatus,
|
|
231
|
+
startedAt: string,
|
|
232
|
+
durationMs: number,
|
|
233
|
+
error?: string | null,
|
|
234
|
+
nextTask?: string | null,
|
|
235
|
+
tokens?: number,
|
|
236
|
+
costUsd?: number,
|
|
237
|
+
model?: string,
|
|
238
|
+
preFlightStatus?: "success" | "error" | "skipped",
|
|
239
|
+
postFlightStatus?: "success" | "error" | "skipped",
|
|
240
|
+
finishedAt = new Date().toISOString(),
|
|
241
|
+
workspaceId?: string | null,
|
|
242
|
+
allowedTools?: string[] | null,
|
|
243
|
+
deniedTools?: string[] | null
|
|
244
|
+
): number {
|
|
245
|
+
const safeDuration = Math.max(0, Math.floor(Number(durationMs) || 0));
|
|
246
|
+
const id = withTransaction(() => {
|
|
247
|
+
const result = getDb()
|
|
248
|
+
.prepare(INSERT_SQL)
|
|
249
|
+
.run(
|
|
250
|
+
taskName,
|
|
251
|
+
status,
|
|
252
|
+
startedAt,
|
|
253
|
+
finishedAt,
|
|
254
|
+
safeDuration,
|
|
255
|
+
error ?? null,
|
|
256
|
+
tokens ?? null,
|
|
257
|
+
costUsd ?? null,
|
|
258
|
+
model ?? null,
|
|
259
|
+
preFlightStatus ?? null,
|
|
260
|
+
postFlightStatus ?? null,
|
|
261
|
+
nextTask ?? null,
|
|
262
|
+
workspaceId ?? null,
|
|
263
|
+
allowedTools == null ? null : JSON.stringify(allowedTools),
|
|
264
|
+
deniedTools == null ? null : JSON.stringify(deniedTools)
|
|
265
|
+
);
|
|
266
|
+
incrementMetricsUnsafe(taskName, status, tokens, costUsd);
|
|
267
|
+
return lastId(result);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
appendStructuredLog({
|
|
271
|
+
event: "run.finished",
|
|
272
|
+
runId: id,
|
|
273
|
+
task: taskName,
|
|
274
|
+
status,
|
|
275
|
+
startedAt,
|
|
276
|
+
finishedAt,
|
|
277
|
+
durationMs: safeDuration,
|
|
278
|
+
error: error ?? null,
|
|
279
|
+
nextTask: nextTask ?? null,
|
|
280
|
+
tokens,
|
|
281
|
+
costUsd,
|
|
282
|
+
model,
|
|
283
|
+
workspaceId: workspaceId ?? null,
|
|
284
|
+
preFlightStatus,
|
|
285
|
+
postFlightStatus,
|
|
286
|
+
});
|
|
287
|
+
return id;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** История запусков (новые сверху). Без taskName — по всем задачам. */
|
|
291
|
+
export function getHistory(
|
|
292
|
+
taskName?: string | null,
|
|
293
|
+
limit = 200,
|
|
294
|
+
status?: string | null
|
|
295
|
+
): StoredHistoryRecord[] {
|
|
296
|
+
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
297
|
+
const clauses: string[] = [];
|
|
298
|
+
const params: any[] = [];
|
|
299
|
+
if (taskName) {
|
|
300
|
+
clauses.push("lower(task_name) = lower(?)");
|
|
301
|
+
params.push(taskName);
|
|
302
|
+
}
|
|
303
|
+
if (status) {
|
|
304
|
+
const normalizedStatus = status.trim().toLowerCase();
|
|
305
|
+
// loadHistory() отдаёт незавершённые записи (running) как error — сохраняем
|
|
306
|
+
// это поведение и при фильтрации на уровне SQLite.
|
|
307
|
+
if (normalizedStatus === "running") {
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
if (normalizedStatus === "error") {
|
|
311
|
+
clauses.push("lower(status) IN ('error', 'running')");
|
|
312
|
+
} else {
|
|
313
|
+
clauses.push("lower(status) = lower(?)");
|
|
314
|
+
params.push(normalizedStatus);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
|
|
318
|
+
params.push(safeLimit);
|
|
319
|
+
const rows = getDb()
|
|
320
|
+
.prepare(
|
|
321
|
+
`SELECT * FROM history${where}
|
|
322
|
+
ORDER BY started_at DESC, id DESC
|
|
323
|
+
LIMIT ?`
|
|
324
|
+
)
|
|
325
|
+
.all(...params) as any[];
|
|
326
|
+
return rows.map(rowToRecord);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** История запусков, начатых не раньше timestamp (ISO-строка). */
|
|
330
|
+
export function getHistorySince(
|
|
331
|
+
timestamp: string,
|
|
332
|
+
limit = 5000
|
|
333
|
+
): StoredHistoryRecord[] {
|
|
334
|
+
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
335
|
+
const rows = getDb()
|
|
336
|
+
.prepare(
|
|
337
|
+
`SELECT * FROM history
|
|
338
|
+
WHERE started_at >= ?
|
|
339
|
+
ORDER BY started_at DESC, id DESC
|
|
340
|
+
LIMIT ?`
|
|
341
|
+
)
|
|
342
|
+
.all(timestamp, safeLimit) as any[];
|
|
343
|
+
return rows.map(rowToRecord);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Crash recovery: все незавершённые записи (finished_at IS NULL) помечаются
|
|
348
|
+
* как error. Длительность считается от started_at до текущего момента.
|
|
349
|
+
* Возвращает количество восстановленных записей.
|
|
350
|
+
*/
|
|
351
|
+
export function recoverInterrupted(): number {
|
|
352
|
+
const now = new Date().toISOString();
|
|
353
|
+
const result = getDb()
|
|
354
|
+
.prepare(
|
|
355
|
+
`UPDATE history SET
|
|
356
|
+
status = 'error',
|
|
357
|
+
error = CASE
|
|
358
|
+
WHEN error IS NULL OR error = '' THEN 'Прервано (сбой/перезагрузка)'
|
|
359
|
+
ELSE error
|
|
360
|
+
END,
|
|
361
|
+
finished_at = COALESCE(finished_at, ?),
|
|
362
|
+
duration_ms = COALESCE(
|
|
363
|
+
duration_ms,
|
|
364
|
+
CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
|
|
365
|
+
)
|
|
366
|
+
WHERE finished_at IS NULL`
|
|
367
|
+
)
|
|
368
|
+
.run(now, now);
|
|
369
|
+
return Number(result.changes) || 0;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Количество записей истории (для миграции и тестов). */
|
|
373
|
+
export function countHistory(): number {
|
|
374
|
+
const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get() as any;
|
|
375
|
+
return Number(row?.count) || 0;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Число активных (незавершённых) запусков: глубина очереди для /api/health. */
|
|
379
|
+
export function countRunningRecords(): number {
|
|
380
|
+
const row = getDb()
|
|
381
|
+
.prepare("SELECT COUNT(*) AS count FROM history WHERE finished_at IS NULL")
|
|
382
|
+
.get() as any;
|
|
383
|
+
return Number(row?.count) || 0;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Запись о незавершённом запуске — для детектора зависших матриц (Спринт 20). */
|
|
387
|
+
export interface RunningHistoryRecord {
|
|
388
|
+
id: number;
|
|
389
|
+
taskName: string;
|
|
390
|
+
startedAt: string;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** Список активных запусков (finished_at IS NULL), самые старые сверху. */
|
|
394
|
+
export function listRunningRecords(): RunningHistoryRecord[] {
|
|
395
|
+
const rows = getDb()
|
|
396
|
+
.prepare(
|
|
397
|
+
`SELECT id, task_name, started_at FROM history
|
|
398
|
+
WHERE finished_at IS NULL
|
|
399
|
+
ORDER BY started_at ASC, id ASC`
|
|
400
|
+
)
|
|
401
|
+
.all() as any[];
|
|
402
|
+
return rows.map((row) => ({
|
|
403
|
+
id: Number(row.id) || 0,
|
|
404
|
+
taskName: String(row.task_name ?? ""),
|
|
405
|
+
startedAt: String(row.started_at ?? ""),
|
|
406
|
+
}));
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Параметры очистки истории (Спринт 18). 0 — ограничение выключено. */
|
|
410
|
+
export interface PruneHistoryOptions {
|
|
411
|
+
/** Удалять завершённые записи старше N дней. */
|
|
412
|
+
retentionDays?: number;
|
|
413
|
+
/** Оставить не более N последних записей. */
|
|
414
|
+
maxRecords?: number;
|
|
415
|
+
/** Опорный момент времени (для тестов). */
|
|
416
|
+
now?: Date;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export interface PruneHistoryResult {
|
|
420
|
+
deletedByAge: number;
|
|
421
|
+
deletedByCount: number;
|
|
422
|
+
deleted: number;
|
|
423
|
+
kept: number;
|
|
424
|
+
/** Граница по возрасту (ISO) или null, если возраст не ограничивали. */
|
|
425
|
+
cutoff: string | null;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Чистит сырую историю: по возрасту и/или по количеству записей.
|
|
430
|
+
*
|
|
431
|
+
* Незавершённые запуски (`finished_at IS NULL`) не удаляются никогда — их
|
|
432
|
+
* обрабатывает crash recovery. Агрегаты в таблице metrics не трогаются:
|
|
433
|
+
* ретеншн чистит детали, а не статистику.
|
|
434
|
+
*/
|
|
435
|
+
export function pruneHistory(options: PruneHistoryOptions = {}): PruneHistoryResult {
|
|
436
|
+
const instance = getDb();
|
|
437
|
+
const now = options.now ?? new Date();
|
|
438
|
+
let deletedByAge = 0;
|
|
439
|
+
let deletedByCount = 0;
|
|
440
|
+
let cutoff: string | null = null;
|
|
441
|
+
|
|
442
|
+
const days = Number(options.retentionDays ?? 0);
|
|
443
|
+
if (Number.isFinite(days) && days > 0) {
|
|
444
|
+
cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString();
|
|
445
|
+
const result = instance
|
|
446
|
+
.prepare(
|
|
447
|
+
`DELETE FROM history
|
|
448
|
+
WHERE finished_at IS NOT NULL AND finished_at < ?`
|
|
449
|
+
)
|
|
450
|
+
.run(cutoff);
|
|
451
|
+
deletedByAge = Number(result.changes) || 0;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const maxRecords = Number(options.maxRecords ?? 0);
|
|
455
|
+
if (Number.isFinite(maxRecords) && maxRecords > 0) {
|
|
456
|
+
const result = instance
|
|
457
|
+
.prepare(
|
|
458
|
+
`DELETE FROM history
|
|
459
|
+
WHERE finished_at IS NOT NULL
|
|
460
|
+
AND id NOT IN (
|
|
461
|
+
SELECT id FROM history
|
|
462
|
+
WHERE finished_at IS NOT NULL
|
|
463
|
+
ORDER BY started_at DESC, id DESC
|
|
464
|
+
LIMIT ?
|
|
465
|
+
)`
|
|
466
|
+
)
|
|
467
|
+
.run(Math.max(0, Math.floor(maxRecords)));
|
|
468
|
+
deletedByCount = Number(result.changes) || 0;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return {
|
|
472
|
+
deletedByAge,
|
|
473
|
+
deletedByCount,
|
|
474
|
+
deleted: deletedByAge + deletedByCount,
|
|
475
|
+
kept: countHistory(),
|
|
476
|
+
cutoff,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Освобождает место после массового удаления. `PRAGMA incremental_vacuum`
|
|
482
|
+
* работает только при auto_vacuum = INCREMENTAL; иначе это no-op, поэтому
|
|
483
|
+
* вызов безопасен и не требует проверки режима.
|
|
484
|
+
*/
|
|
485
|
+
export function vacuumHistory(): boolean {
|
|
486
|
+
try {
|
|
487
|
+
getDb().exec("PRAGMA incremental_vacuum");
|
|
488
|
+
return true;
|
|
489
|
+
} catch {
|
|
490
|
+
return false;
|
|
491
|
+
}
|
|
492
|
+
}
|
package/src/db/index.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { PLUGIN_DIR } from "../types.js";
|
|
5
|
+
import { applySchema } from "./schema.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Подключение к SQLite через встроенный `node:sqlite` (Node 22.5+).
|
|
9
|
+
*
|
|
10
|
+
* Мы не импортируем модуль статически: в @types/node 20 типов для node:sqlite
|
|
11
|
+
* ещё нет, а `createRequire` позволяет получить модуль без объявления
|
|
12
|
+
* глобального ambient-модуля (и не конфликтовать с будущими версиями типов).
|
|
13
|
+
*/
|
|
14
|
+
export interface SqliteRunResult {
|
|
15
|
+
changes: number | bigint;
|
|
16
|
+
lastInsertRowid: number | bigint;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface SqliteStatement {
|
|
20
|
+
run(...params: any[]): SqliteRunResult;
|
|
21
|
+
get(...params: any[]): any;
|
|
22
|
+
all(...params: any[]): any[];
|
|
23
|
+
iterate(...params: any[]): IterableIterator<any>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SqliteDatabase {
|
|
27
|
+
exec(sql: string): void;
|
|
28
|
+
prepare(sql: string): SqliteStatement;
|
|
29
|
+
close(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type DatabaseSyncCtor = new (
|
|
33
|
+
location: string,
|
|
34
|
+
options?: Record<string, unknown>
|
|
35
|
+
) => SqliteDatabase;
|
|
36
|
+
|
|
37
|
+
const nodeRequire = createRequire(import.meta.url);
|
|
38
|
+
|
|
39
|
+
function loadSqlite(): DatabaseSyncCtor {
|
|
40
|
+
try {
|
|
41
|
+
const mod = nodeRequire("node:sqlite") as { DatabaseSync: DatabaseSyncCtor };
|
|
42
|
+
return mod.DatabaseSync;
|
|
43
|
+
} catch (err: any) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`node:sqlite недоступен (${err instanceof Error ? err.message : String(err)}). ` +
|
|
46
|
+
"Планировщику требуется Node.js 22.5+ (рекомендуется Node 24)."
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Путь к БД. Переменная окружения нужна только тестам. */
|
|
52
|
+
const DEFAULT_DB_FILE = process.env.OPENCODE_SCHEDULER_DB?.trim()
|
|
53
|
+
? path.resolve(process.env.OPENCODE_SCHEDULER_DB.trim())
|
|
54
|
+
: path.join(PLUGIN_DIR, "scheduler.db");
|
|
55
|
+
|
|
56
|
+
let dbFile = DEFAULT_DB_FILE;
|
|
57
|
+
let db: SqliteDatabase | null = null;
|
|
58
|
+
|
|
59
|
+
/** Открывает (или переоткрывает) соединение и применяет схему. */
|
|
60
|
+
export function initDb(file: string = dbFile): SqliteDatabase {
|
|
61
|
+
if (db && file === dbFile) return db;
|
|
62
|
+
if (db) closeDb();
|
|
63
|
+
|
|
64
|
+
dbFile = file;
|
|
65
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
66
|
+
|
|
67
|
+
const DatabaseSync = loadSqlite();
|
|
68
|
+
const instance = new DatabaseSync(file);
|
|
69
|
+
|
|
70
|
+
// WAL — конкурентное чтение во время записи и устойчивость к сбоям.
|
|
71
|
+
instance.exec("PRAGMA journal_mode = WAL;");
|
|
72
|
+
instance.exec("PRAGMA foreign_keys = ON;");
|
|
73
|
+
instance.exec("PRAGMA busy_timeout = 5000;");
|
|
74
|
+
applySchema(instance);
|
|
75
|
+
|
|
76
|
+
db = instance;
|
|
77
|
+
return instance;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Singleton-соединение. Создаётся лениво при первом обращении. */
|
|
81
|
+
export function getDb(): SqliteDatabase {
|
|
82
|
+
return db ?? initDb();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Закрывает соединение (вызывается при выгрузке плагина). */
|
|
86
|
+
export function closeDb(): void {
|
|
87
|
+
if (!db) return;
|
|
88
|
+
try {
|
|
89
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
90
|
+
} catch {
|
|
91
|
+
// Чекпойнт не критичен при закрытии.
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
db.close();
|
|
95
|
+
} catch {
|
|
96
|
+
// Соединение могло быть уже закрыто.
|
|
97
|
+
}
|
|
98
|
+
db = null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Текущий путь к файлу БД. */
|
|
102
|
+
export function getDbFile(): string {
|
|
103
|
+
return dbFile;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Сбрасывает WAL в основной файл — нужно перед отдачей .db наружу. */
|
|
107
|
+
export function checkpointDb(): void {
|
|
108
|
+
getDb().exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Информация о хранилище для /api/health и футера дашборда. */
|
|
112
|
+
export function getDbStatus(): {
|
|
113
|
+
engine: "sqlite";
|
|
114
|
+
file: string;
|
|
115
|
+
journalMode: string;
|
|
116
|
+
wal: boolean;
|
|
117
|
+
} {
|
|
118
|
+
let journalMode = "unknown";
|
|
119
|
+
try {
|
|
120
|
+
const row = getDb().prepare("PRAGMA journal_mode;").get() as any;
|
|
121
|
+
journalMode = String(row?.journal_mode ?? "unknown");
|
|
122
|
+
} catch {
|
|
123
|
+
// Если БД ещё не открыта — не роняем health-check.
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
engine: "sqlite",
|
|
127
|
+
file: dbFile,
|
|
128
|
+
journalMode,
|
|
129
|
+
wal: journalMode.toLowerCase() === "wal",
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Выполняет функцию в транзакции BEGIN IMMEDIATE.
|
|
135
|
+
* При любой ошибке откатывает изменения и пробрасывает исключение дальше.
|
|
136
|
+
*/
|
|
137
|
+
export function withTransaction<T>(fn: () => T): T {
|
|
138
|
+
const instance = getDb();
|
|
139
|
+
instance.exec("BEGIN IMMEDIATE;");
|
|
140
|
+
try {
|
|
141
|
+
const result = fn();
|
|
142
|
+
instance.exec("COMMIT;");
|
|
143
|
+
return result;
|
|
144
|
+
} catch (err) {
|
|
145
|
+
try {
|
|
146
|
+
instance.exec("ROLLBACK;");
|
|
147
|
+
} catch {
|
|
148
|
+
// Откат мог не понадобиться (например, SQLite уже откатил сам).
|
|
149
|
+
}
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Пуста ли БД (не считая служебных настроек вроде retry_state). */
|
|
155
|
+
export function isDatabaseEmpty(): boolean {
|
|
156
|
+
const row = getDb()
|
|
157
|
+
.prepare(
|
|
158
|
+
`SELECT
|
|
159
|
+
(SELECT COUNT(*) FROM tasks) +
|
|
160
|
+
(SELECT COUNT(*) FROM history) +
|
|
161
|
+
(SELECT COUNT(*) FROM metrics) +
|
|
162
|
+
(SELECT COUNT(*) FROM templates) AS count`
|
|
163
|
+
)
|
|
164
|
+
.get() as any;
|
|
165
|
+
return Number(row?.count) === 0;
|
|
166
|
+
}
|