agent-steward 0.0.2 → 0.0.4
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 +45 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +11 -10
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +148 -1017
- 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/dlq-api.d.ts +44 -0
- package/dist/core/dlq-api.d.ts.map +1 -0
- package/dist/core/dlq-api.js +68 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +19 -2
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.d.ts +20 -4
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +99 -26
- package/dist/core/one-shot.d.ts +31 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +78 -10
- package/dist/core/opencode-cli.d.ts +28 -0
- package/dist/core/opencode-cli.d.ts.map +1 -0
- package/dist/core/opencode-cli.js +74 -0
- package/dist/core/opencode-models.d.ts +62 -0
- package/dist/core/opencode-models.d.ts.map +1 -0
- package/dist/core/opencode-models.js +277 -0
- package/dist/core/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 +66 -36
- package/dist/core/record-history.d.ts +15 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +78 -54
- package/dist/core/router/dispatch.d.ts +36 -0
- package/dist/core/router/dispatch.d.ts.map +1 -0
- package/dist/core/router/dispatch.js +59 -0
- package/dist/core/router/escalation.d.ts +47 -0
- package/dist/core/router/escalation.d.ts.map +1 -0
- package/dist/core/router/escalation.js +87 -0
- package/dist/core/router/planner.d.ts +53 -0
- package/dist/core/router/planner.d.ts.map +1 -0
- package/dist/core/router/planner.js +113 -0
- package/dist/core/router/rules.d.ts +46 -0
- package/dist/core/router/rules.d.ts.map +1 -0
- package/dist/core/router/rules.js +85 -0
- package/dist/core/run-panel-api.d.ts +94 -0
- package/dist/core/run-panel-api.d.ts.map +1 -0
- package/dist/core/run-panel-api.js +169 -0
- package/dist/core/schedule-gate.js +5 -1
- package/dist/core/schedule-v2.d.ts +36 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +98 -12
- package/dist/core/scheduler/at-fallback.d.ts +95 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +200 -0
- package/dist/core/scheduler/linux.d.ts +13 -2
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +67 -13
- 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 +37 -2
- package/dist/core/scheduler/registry.d.ts +13 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +83 -21
- package/dist/core/scheduler/run-now.d.ts +16 -0
- package/dist/core/scheduler/run-now.d.ts.map +1 -0
- package/dist/core/scheduler/run-now.js +28 -0
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +127 -30
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +18 -11
- package/dist/core/summary.js +1 -1
- package/dist/core/task-name.d.ts +24 -0
- package/dist/core/task-name.d.ts.map +1 -0
- package/dist/core/task-name.js +40 -0
- package/dist/core/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.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +82 -37
- package/dist/db/capability-repo.d.ts +83 -0
- package/dist/db/capability-repo.d.ts.map +1 -0
- package/dist/db/capability-repo.js +182 -0
- package/dist/db/history-repo.d.ts +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +19 -0
- package/dist/db/index.d.ts +6 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +48 -2
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +3 -1
- package/dist/db/run-context.d.ts +103 -0
- package/dist/db/run-context.d.ts.map +1 -0
- package/dist/db/run-context.js +224 -0
- package/dist/db/run-dlq.d.ts +100 -0
- package/dist/db/run-dlq.d.ts.map +1 -0
- package/dist/db/run-dlq.js +191 -0
- package/dist/db/run-journal.d.ts +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 +51 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +156 -0
- package/dist/db/runs-repo.d.ts +128 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +342 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +342 -35
- package/dist/db/settings-repo.d.ts +11 -0
- package/dist/db/settings-repo.d.ts.map +1 -1
- package/dist/db/settings-repo.js +25 -0
- package/dist/db/step-idempotency.d.ts +51 -0
- package/dist/db/step-idempotency.d.ts.map +1 -0
- package/dist/db/step-idempotency.js +136 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +168 -40
- 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 +787 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +324 -0
- package/dist/server.d.ts +33 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +115 -54
- 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 +44 -9
- package/dist/workspaces.d.ts +25 -3
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +44 -9
- package/docs/ARCHITECTURE.md +335 -9
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +183 -91
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/EXECUTION-LOOP.md +196 -0
- 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 +27 -8
- package/docs/README.zh.md +11 -10
- package/docs/SAFETY.md +122 -0
- package/docs/SAVINGS.md +29 -0
- package/docs/SAVINGS.ru.md +29 -0
- package/docs/SAVINGS.zh.md +18 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +68 -0
- package/locales/ru.json +68 -0
- package/locales/zh.json +68 -0
- package/package.json +57 -11
- package/scripts/audit-bundle.mjs +215 -0
- 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/dlq-api.ts +98 -0
- package/src/core/dry-run.ts +51 -27
- 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 +104 -31
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +91 -13
- package/src/core/opencode-cli.ts +103 -0
- package/src/core/opencode-models.ts +315 -0
- 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 +68 -38
- package/src/core/record-history.ts +114 -76
- package/src/core/retention.ts +3 -3
- package/src/core/router/dispatch.ts +94 -0
- package/src/core/router/escalation.ts +129 -0
- package/src/core/router/planner.ts +166 -0
- package/src/core/router/rules.ts +109 -0
- package/src/core/run-panel-api.ts +262 -0
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +17 -13
- package/src/core/schedule-v2.ts +138 -29
- package/src/core/scheduler/at-fallback.ts +298 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +92 -19
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +35 -2
- package/src/core/scheduler/registry.ts +109 -26
- package/src/core/scheduler/run-now.ts +32 -0
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +139 -39
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +26 -13
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/task-name.ts +67 -0
- 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 +90 -45
- package/src/db/capability-repo.ts +285 -0
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +44 -22
- package/src/db/index.ts +53 -7
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +13 -11
- package/src/db/recovery.ts +3 -3
- package/src/db/run-context.ts +370 -0
- package/src/db/run-dlq.ts +310 -0
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +256 -0
- package/src/db/runs-repo.ts +504 -0
- package/src/db/schema.ts +357 -44
- package/src/db/settings-repo.ts +33 -2
- package/src/db/step-idempotency.ts +185 -0
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +516 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +465 -308
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +347 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +155 -78
- 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 +54 -10
- package/src/workspaces.ts +73 -24
- 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/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,38 @@ 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
|
+
)
|
|
325
|
+
.all(...params);
|
|
326
|
+
return rows.map(rowToRecord);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Последняя запись по каждой задаче (P2-29).
|
|
331
|
+
*
|
|
332
|
+
* DAG-зависимости нельзя проверять по «последним N записям»: на частой задаче
|
|
333
|
+
* успех зависимости вымывается из окна, и зависимая задача не стартует.
|
|
334
|
+
* Здесь SQL сам выбирает по одной самой свежей записи на задачу.
|
|
335
|
+
*/
|
|
336
|
+
export function getLatestHistoryByTask(limit = 5000): StoredHistoryRecord[] {
|
|
337
|
+
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
338
|
+
const rows = getDb()
|
|
339
|
+
.prepare(
|
|
340
|
+
`SELECT * FROM history
|
|
341
|
+
WHERE id IN (
|
|
342
|
+
SELECT MAX(id) FROM history GROUP BY lower(task_name)
|
|
343
|
+
)
|
|
344
|
+
ORDER BY started_at DESC, id DESC
|
|
345
|
+
LIMIT ?`,
|
|
324
346
|
)
|
|
325
|
-
.all(
|
|
347
|
+
.all(safeLimit);
|
|
326
348
|
return rows.map(rowToRecord);
|
|
327
349
|
}
|
|
328
350
|
|
|
329
351
|
/** История запусков, начатых не раньше timestamp (ISO-строка). */
|
|
330
352
|
export function getHistorySince(
|
|
331
353
|
timestamp: string,
|
|
332
|
-
limit = 5000
|
|
354
|
+
limit = 5000,
|
|
333
355
|
): StoredHistoryRecord[] {
|
|
334
356
|
const safeLimit = Math.max(1, Math.min(100000, Math.floor(limit) || 1));
|
|
335
357
|
const rows = getDb()
|
|
@@ -337,9 +359,9 @@ export function getHistorySince(
|
|
|
337
359
|
`SELECT * FROM history
|
|
338
360
|
WHERE started_at >= ?
|
|
339
361
|
ORDER BY started_at DESC, id DESC
|
|
340
|
-
LIMIT
|
|
362
|
+
LIMIT ?`,
|
|
341
363
|
)
|
|
342
|
-
.all(timestamp, safeLimit)
|
|
364
|
+
.all(timestamp, safeLimit);
|
|
343
365
|
return rows.map(rowToRecord);
|
|
344
366
|
}
|
|
345
367
|
|
|
@@ -363,7 +385,7 @@ export function recoverInterrupted(): number {
|
|
|
363
385
|
duration_ms,
|
|
364
386
|
CAST((julianday(?) - julianday(started_at)) * 86400000 AS INTEGER)
|
|
365
387
|
)
|
|
366
|
-
WHERE finished_at IS NULL
|
|
388
|
+
WHERE finished_at IS NULL`,
|
|
367
389
|
)
|
|
368
390
|
.run(now, now);
|
|
369
391
|
return Number(result.changes) || 0;
|
|
@@ -371,7 +393,7 @@ export function recoverInterrupted(): number {
|
|
|
371
393
|
|
|
372
394
|
/** Количество записей истории (для миграции и тестов). */
|
|
373
395
|
export function countHistory(): number {
|
|
374
|
-
const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get()
|
|
396
|
+
const row = getDb().prepare("SELECT COUNT(*) AS count FROM history").get();
|
|
375
397
|
return Number(row?.count) || 0;
|
|
376
398
|
}
|
|
377
399
|
|
|
@@ -379,7 +401,7 @@ export function countHistory(): number {
|
|
|
379
401
|
export function countRunningRecords(): number {
|
|
380
402
|
const row = getDb()
|
|
381
403
|
.prepare("SELECT COUNT(*) AS count FROM history WHERE finished_at IS NULL")
|
|
382
|
-
.get()
|
|
404
|
+
.get();
|
|
383
405
|
return Number(row?.count) || 0;
|
|
384
406
|
}
|
|
385
407
|
|
|
@@ -396,9 +418,9 @@ export function listRunningRecords(): RunningHistoryRecord[] {
|
|
|
396
418
|
.prepare(
|
|
397
419
|
`SELECT id, task_name, started_at FROM history
|
|
398
420
|
WHERE finished_at IS NULL
|
|
399
|
-
ORDER BY started_at ASC, id ASC
|
|
421
|
+
ORDER BY started_at ASC, id ASC`,
|
|
400
422
|
)
|
|
401
|
-
.all()
|
|
423
|
+
.all();
|
|
402
424
|
return rows.map((row) => ({
|
|
403
425
|
id: Number(row.id) || 0,
|
|
404
426
|
taskName: String(row.task_name ?? ""),
|
|
@@ -445,7 +467,7 @@ export function pruneHistory(options: PruneHistoryOptions = {}): PruneHistoryRes
|
|
|
445
467
|
const result = instance
|
|
446
468
|
.prepare(
|
|
447
469
|
`DELETE FROM history
|
|
448
|
-
WHERE finished_at IS NOT NULL AND finished_at <
|
|
470
|
+
WHERE finished_at IS NOT NULL AND finished_at < ?`,
|
|
449
471
|
)
|
|
450
472
|
.run(cutoff);
|
|
451
473
|
deletedByAge = Number(result.changes) || 0;
|
|
@@ -462,7 +484,7 @@ export function pruneHistory(options: PruneHistoryOptions = {}): PruneHistoryRes
|
|
|
462
484
|
WHERE finished_at IS NOT NULL
|
|
463
485
|
ORDER BY started_at DESC, id DESC
|
|
464
486
|
LIMIT ?
|
|
465
|
-
)
|
|
487
|
+
)`,
|
|
466
488
|
)
|
|
467
489
|
.run(Math.max(0, Math.floor(maxRecords)));
|
|
468
490
|
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
|
}
|
|
@@ -55,6 +55,8 @@ const DEFAULT_DB_FILE = process.env.OPENCODE_SCHEDULER_DB?.trim()
|
|
|
55
55
|
|
|
56
56
|
let dbFile = DEFAULT_DB_FILE;
|
|
57
57
|
let db: SqliteDatabase | null = null;
|
|
58
|
+
/** Глубина вложенности withTransaction: 0 — транзакции нет, >0 — SAVEPOINT. */
|
|
59
|
+
let transactionDepth = 0;
|
|
58
60
|
|
|
59
61
|
/** Открывает (или переоткрывает) соединение и применяет схему. */
|
|
60
62
|
export function initDb(file: string = dbFile): SqliteDatabase {
|
|
@@ -67,10 +69,18 @@ export function initDb(file: string = dbFile): SqliteDatabase {
|
|
|
67
69
|
const DatabaseSync = loadSqlite();
|
|
68
70
|
const instance = new DatabaseSync(file);
|
|
69
71
|
|
|
72
|
+
// busy_timeout ДОЛЖЕН быть установлен до WAL: при одновременном старте
|
|
73
|
+
// нескольких процессов (каждое завершение задачи — отдельный
|
|
74
|
+
// `node record-history`) переключение journal_mode требует эксклюзивной
|
|
75
|
+
// блокировки. Без таймаута SQLite сразу падает с "database is locked".
|
|
76
|
+
instance.exec("PRAGMA busy_timeout = 5000;");
|
|
70
77
|
// WAL — конкурентное чтение во время записи и устойчивость к сбоям.
|
|
78
|
+
// synchronous = NORMAL в WAL гарантирует, что закоммиченная транзакция
|
|
79
|
+
// переживает падение процесса (шаг 36.1.b); при потере питания может
|
|
80
|
+
// потеряться только последний коммит — это осознанный компромисс.
|
|
71
81
|
instance.exec("PRAGMA journal_mode = WAL;");
|
|
82
|
+
instance.exec("PRAGMA synchronous = NORMAL;");
|
|
72
83
|
instance.exec("PRAGMA foreign_keys = ON;");
|
|
73
|
-
instance.exec("PRAGMA busy_timeout = 5000;");
|
|
74
84
|
applySchema(instance);
|
|
75
85
|
|
|
76
86
|
db = instance;
|
|
@@ -84,6 +94,7 @@ export function getDb(): SqliteDatabase {
|
|
|
84
94
|
|
|
85
95
|
/** Закрывает соединение (вызывается при выгрузке плагина). */
|
|
86
96
|
export function closeDb(): void {
|
|
97
|
+
transactionDepth = 0;
|
|
87
98
|
if (!db) return;
|
|
88
99
|
try {
|
|
89
100
|
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
@@ -114,11 +125,15 @@ export function getDbStatus(): {
|
|
|
114
125
|
file: string;
|
|
115
126
|
journalMode: string;
|
|
116
127
|
wal: boolean;
|
|
117
|
-
|
|
128
|
+
schemaVersion: number;
|
|
129
|
+
expectedSchemaVersion: number;
|
|
130
|
+
} {
|
|
118
131
|
let journalMode = "unknown";
|
|
132
|
+
let schemaVersion = 0;
|
|
119
133
|
try {
|
|
120
|
-
const row = getDb().prepare("PRAGMA journal_mode;").get()
|
|
134
|
+
const row = getDb().prepare("PRAGMA journal_mode;").get();
|
|
121
135
|
journalMode = String(row?.journal_mode ?? "unknown");
|
|
136
|
+
schemaVersion = getSchemaVersion(getDb());
|
|
122
137
|
} catch {
|
|
123
138
|
// Если БД ещё не открыта — не роняем health-check.
|
|
124
139
|
}
|
|
@@ -127,16 +142,45 @@ export function getDbStatus(): {
|
|
|
127
142
|
file: dbFile,
|
|
128
143
|
journalMode,
|
|
129
144
|
wal: journalMode.toLowerCase() === "wal",
|
|
145
|
+
schemaVersion,
|
|
146
|
+
expectedSchemaVersion: SCHEMA_VERSION,
|
|
130
147
|
};
|
|
131
148
|
}
|
|
132
149
|
|
|
133
150
|
/**
|
|
134
151
|
* Выполняет функцию в транзакции BEGIN IMMEDIATE.
|
|
135
152
|
* При любой ошибке откатывает изменения и пробрасывает исключение дальше.
|
|
153
|
+
*
|
|
154
|
+
* Вложенный вызов не открывает вторую транзакцию (SQLite это запрещает), а
|
|
155
|
+
* создаёт SAVEPOINT: так композиция вроде «retry из DLQ → reopenRun → retryStep»
|
|
156
|
+
* остаётся атомарной, а внутренний откат не рушит внешнюю транзакцию.
|
|
136
157
|
*/
|
|
137
158
|
export function withTransaction<T>(fn: () => T): T {
|
|
138
159
|
const instance = getDb();
|
|
160
|
+
|
|
161
|
+
if (transactionDepth > 0) {
|
|
162
|
+
const savepoint = `sp_nested_${transactionDepth}`;
|
|
163
|
+
instance.exec(`SAVEPOINT ${savepoint};`);
|
|
164
|
+
transactionDepth += 1;
|
|
165
|
+
try {
|
|
166
|
+
const result = fn();
|
|
167
|
+
instance.exec(`RELEASE ${savepoint};`);
|
|
168
|
+
return result;
|
|
169
|
+
} catch (err) {
|
|
170
|
+
try {
|
|
171
|
+
instance.exec(`ROLLBACK TO ${savepoint};`);
|
|
172
|
+
instance.exec(`RELEASE ${savepoint};`);
|
|
173
|
+
} catch {
|
|
174
|
+
// SAVEPOINT уже снят вместе с внешней транзакцией.
|
|
175
|
+
}
|
|
176
|
+
throw err;
|
|
177
|
+
} finally {
|
|
178
|
+
transactionDepth -= 1;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
139
182
|
instance.exec("BEGIN IMMEDIATE;");
|
|
183
|
+
transactionDepth = 1;
|
|
140
184
|
try {
|
|
141
185
|
const result = fn();
|
|
142
186
|
instance.exec("COMMIT;");
|
|
@@ -148,6 +192,8 @@ export function withTransaction<T>(fn: () => T): T {
|
|
|
148
192
|
// Откат мог не понадобиться (например, SQLite уже откатил сам).
|
|
149
193
|
}
|
|
150
194
|
throw err;
|
|
195
|
+
} finally {
|
|
196
|
+
transactionDepth = 0;
|
|
151
197
|
}
|
|
152
198
|
}
|
|
153
199
|
|
|
@@ -159,8 +205,8 @@ export function isDatabaseEmpty(): boolean {
|
|
|
159
205
|
(SELECT COUNT(*) FROM tasks) +
|
|
160
206
|
(SELECT COUNT(*) FROM history) +
|
|
161
207
|
(SELECT COUNT(*) FROM metrics) +
|
|
162
|
-
(SELECT COUNT(*) FROM templates) AS count
|
|
208
|
+
(SELECT COUNT(*) FROM templates) AS count`,
|
|
163
209
|
)
|
|
164
|
-
.get()
|
|
210
|
+
.get();
|
|
165
211
|
return Number(row?.count) === 0;
|
|
166
212
|
}
|
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) {
|
|
@@ -90,7 +90,9 @@ function normalizeHistoryRow(raw: any): any | null {
|
|
|
90
90
|
if (!taskName || !startedAt) return null;
|
|
91
91
|
|
|
92
92
|
const status =
|
|
93
|
-
raw.status === "success" || raw.status === "
|
|
93
|
+
raw.status === "success" || raw.status === "partial" || raw.status === "timeout"
|
|
94
|
+
? raw.status
|
|
95
|
+
: "error";
|
|
94
96
|
|
|
95
97
|
return {
|
|
96
98
|
taskName,
|
|
@@ -113,12 +115,12 @@ function normalizeHistoryRow(raw: any): any | null {
|
|
|
113
115
|
* migrated: false и нули.
|
|
114
116
|
*/
|
|
115
117
|
export async function migrateJsonToDb(
|
|
116
|
-
pluginDir: string = PLUGIN_DIR
|
|
118
|
+
pluginDir: string = PLUGIN_DIR,
|
|
117
119
|
): Promise<MigrationResult> {
|
|
118
120
|
if (!isDatabaseEmpty()) return { ...EMPTY_RESULT };
|
|
119
121
|
|
|
120
122
|
const files = await Promise.all(
|
|
121
|
-
JSON_FILES.map((name) => loadJsonFile(path.join(pluginDir, name)))
|
|
123
|
+
JSON_FILES.map((name) => loadJsonFile(path.join(pluginDir, name))),
|
|
122
124
|
);
|
|
123
125
|
if (!files.some((file) => file.exists)) return { ...EMPTY_RESULT };
|
|
124
126
|
|
|
@@ -147,7 +149,7 @@ export async function migrateJsonToDb(
|
|
|
147
149
|
|
|
148
150
|
// --- tasks ---
|
|
149
151
|
const insertTask = db.prepare(
|
|
150
|
-
"INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)"
|
|
152
|
+
"INSERT INTO tasks (name, definition_json, created_at, updated_at) VALUES (?, ?, ?, ?)",
|
|
151
153
|
);
|
|
152
154
|
const seenTasks = new Set<string>();
|
|
153
155
|
for (const item of taskItems) {
|
|
@@ -182,7 +184,7 @@ export async function migrateJsonToDb(
|
|
|
182
184
|
`INSERT INTO history (
|
|
183
185
|
task_name, status, started_at, finished_at, duration_ms, error,
|
|
184
186
|
tokens, cost_usd, model, pre_flight_status, post_flight_status, next_task
|
|
185
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
187
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
186
188
|
);
|
|
187
189
|
for (const row of historyItems) {
|
|
188
190
|
insertHistory.run(
|
|
@@ -197,14 +199,14 @@ export async function migrateJsonToDb(
|
|
|
197
199
|
row.model,
|
|
198
200
|
row.preFlightStatus,
|
|
199
201
|
row.postFlightStatus,
|
|
200
|
-
row.nextTask
|
|
202
|
+
row.nextTask,
|
|
201
203
|
);
|
|
202
204
|
insertedHistory += 1;
|
|
203
205
|
}
|
|
204
206
|
|
|
205
207
|
// --- templates ---
|
|
206
208
|
const insertTemplate = db.prepare(
|
|
207
|
-
"INSERT INTO templates (id, name, definition_json) VALUES (?, ?, ?)"
|
|
209
|
+
"INSERT INTO templates (id, name, definition_json) VALUES (?, ?, ?)",
|
|
208
210
|
);
|
|
209
211
|
const seenTemplates = new Set<string>();
|
|
210
212
|
for (const item of templateItems) {
|
|
@@ -259,7 +261,7 @@ export async function migrateJsonToDb(
|
|
|
259
261
|
tokens: acc.tokens + row.tokens,
|
|
260
262
|
costUsd: acc.costUsd + row.costUsd,
|
|
261
263
|
}),
|
|
262
|
-
{ total: 0, success: 0, error: 0, partial: 0, tokens: 0, costUsd: 0 }
|
|
264
|
+
{ total: 0, success: 0, error: 0, partial: 0, tokens: 0, costUsd: 0 },
|
|
263
265
|
);
|
|
264
266
|
|
|
265
267
|
const extra = {
|
|
@@ -308,13 +310,13 @@ export async function migrateJsonToDb(
|
|
|
308
310
|
console.error(
|
|
309
311
|
`[migrate] Не удалось переименовать ${path.basename(file.path)} в .bak: ${
|
|
310
312
|
err instanceof Error ? err.message : String(err)
|
|
311
|
-
}
|
|
313
|
+
}`,
|
|
312
314
|
);
|
|
313
315
|
}
|
|
314
316
|
}
|
|
315
317
|
|
|
316
318
|
console.log(
|
|
317
|
-
`[migrate] Перемещено ${insertedTasks} задач, ${insertedHistory} записей истории, ${insertedTemplates}
|
|
319
|
+
`[migrate] Перемещено ${insertedTasks} задач, ${insertedHistory} записей истории, ${insertedTemplates} шаблонов.`,
|
|
318
320
|
);
|
|
319
321
|
|
|
320
322
|
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
|
}
|